diff --git a/.changeset/dead-pane-blank-pid.md b/.changeset/dead-pane-blank-pid.md index f38c2d41..20719d51 100644 --- a/.changeset/dead-pane-blank-pid.md +++ b/.changeset/dead-pane-blank-pid.md @@ -2,4 +2,4 @@ 'aicodeman': patch --- -On tmux 3.8, a session whose agent exited (`/exit`) is now seen as exited and closed like on older tmux, instead of staying on the board as idle. tmux 3.8 prints a blank pane pid for a dead pane, and the pane watcher threw that row away, so the clean-exit sweep never ran and a restart of Codeman dropped the session's record while its tmux session stayed on the socket. A dead pane's exit is now told apart from the next one by `#{pane_dead_time}`. Closing a session whose pane is dead no longer signals the pid recorded for it, which belonged to the program that exited and may have been reused by another process; only the tmux session is killed. A dead `codeman-*` tmux session that was orphaned before this fix is still not rediscovered; remove it with `tmux -L codeman kill-session -t codeman-`. +On tmux 3.8, a session whose agent exited (`/exit`) is now seen as exited and closed like on older tmux, instead of staying on the board as idle. tmux 3.8 prints a blank pane pid for a dead pane, and the pane watcher threw that row away, so the clean-exit sweep never ran and a restart of Codeman dropped the session's record while its tmux session stayed on the socket. A dead pane's exit is now told apart from the next one by `#{pane_dead_time}`. Closing a session whose pane is dead no longer signals the pid recorded for it, which belonged to the program that exited and may have been reused by another process; only the tmux session is killed. Finished sessions that piled up on the board on tmux 3.8 are relaunched once, at the first start after this update. A dead `codeman-*` tmux session that was orphaned before this fix is still not rediscovered; remove it with `tmux -L codeman kill-session -t codeman-`. diff --git a/CLAUDE.md b/CLAUDE.md index 597b5bb1..58bf9315 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -152,7 +152,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph ⚠️ **A quiet pane is not always a pane that wants you.** A CLI can declare an optional `capabilities.workDetect.watchingLine` (a monitor, background shell or cloud hand-off it is still running); the idle probe reads it into `Session.watching` and `notePrompt()` opens that idle item ALREADY acknowledged, so no surface alerts. Only `idle` is eligible, and the label is pane-derived and prompt-injectable, so a pattern must anchor on chrome only that CLI draws. → [architecture-invariants#the-watching-signal-a-quiet-pane-that-is-not-waiting-for-you](docs/architecture-invariants.md#the-watching-signal-a-quiet-pane-that-is-not-waiting-for-you). Tests: `test/session-watching.test.ts`, `test/watching-no-alert.test.ts`. -**An exited agent in a live pane** (`paneExit`, #446): panes use `remain-on-exit on`, so `/exit` leaves a pane, session and pid that look alive; `TmuxManager.startPaneExitWatcher()` publishes `SessionState.paneExit` via `session:updated`. ⚠️ Never set `status: 'error'` or null the `pid` for it; the field is TRI-STATE (absent = UNKNOWN, never alive, scoped by `Session.paneExitApplies`); an absent `#{pane_dead_status}` is not 0; a dead pane may have NO pid (tmux 3.8 prints `#{pane_pid}` blank), so never skip a dead row for it, and never signal the recorded pid of a dead pane in `killSession()`; a path that starts a command in a pane must clear the record AND persist. A clean exit is CLOSED via `cleanupSession()` (`pane-exit-sweep.ts`): only an explicit numeric status 0 with no signal, confirmed by 2 reads, with no start/attach in flight (`paneLifecycleInFlight`) and not within 10 s of one (a startup error keeps its row); a crashed agent keeps its row. → [architecture-invariants#an-exited-agent-in-a-live-pane-paneexit](docs/architecture-invariants.md#an-exited-agent-in-a-live-pane-paneexit) +**An exited agent in a live pane** (`paneExit`, #446): panes use `remain-on-exit on`, so `/exit` leaves a pane, session and pid that look alive; `TmuxManager.startPaneExitWatcher()` publishes `SessionState.paneExit` via `session:updated`. ⚠️ Never set `status: 'error'` or null the `pid` for it; the field is TRI-STATE (absent = UNKNOWN, never alive, scoped by `Session.paneExitApplies`); an absent `#{pane_dead_status}` is not 0; a dead pane may have NO pid (tmux 3.8 prints `#{pane_pid}` blank), so never skip a no-pid row whose `#{pane_dead}` tmux answered, and never signal the recorded pid of a dead pane in `killSession()` (dead = flag 1 plus a blank pid or a `#{pane_dead_time}`); a path that starts a command in a pane must clear the record AND persist. A clean exit is CLOSED via `cleanupSession()` (`pane-exit-sweep.ts`): only an explicit numeric status 0 with no signal, confirmed by 2 reads, with no start/attach in flight (`paneLifecycleInFlight`) and not within 10 s of one (a startup error keeps its row); a crashed agent keeps its row. → [architecture-invariants#an-exited-agent-in-a-live-pane-paneexit](docs/architecture-invariants.md#an-exited-agent-in-a-live-pane-paneexit) **Dead-pane respawn resume pin** (`_buildRespawnPaneOptionsWithResumePin()`, session.ts): recovering a dead pane, like a custom-model `restartCli()`, must pin the conversation or claude refuses the reused `--session-id`. The pin takes the first transcript-backed candidate (chain tail, launch seed, own id), never `_claudeSessionId`, adds nothing when none is backed, and is never applied to remote or docker sessions. → [architecture-invariants#dead-pane-respawn-the-resume-pin](docs/architecture-invariants.md#dead-pane-respawn-the-resume-pin) diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index d61fe1d2..cb661430 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -297,7 +297,7 @@ Further detail, closing: ⚠️ **Closing has the mirror-image race and one owne ### An exited agent in a live pane (`paneExit`) -**Codeman creates every pane with `remain-on-exit on`, so a session whose agent exited still looks alive.** `/exit` ends the CLI, tmux keeps the pane and the tmux session, and the `tmux attach-session` process Codeman records as `Session.pid` runs on, so no PTY exit handler fires and the record keeps its pid and `status: 'idle'` (Ark0N/Codeman#446). `SessionState.paneExit` (`{status?, signal?, at}`) is the fact tmux already knows, published through `toState()` so it rides `session:updated` and lands in `state.json` on the same persist — there is no SSE event for it. One batched `tmux list-panes -a` per tick fills it, from `TmuxManager.startPaneExitWatcher()`, which has its OWN always-on interval: the stats collector cannot carry it, because the browser arms and disarms that one with the Monitor panel (`panels-ui.js`) and boot skips it entirely when no session was recovered. ⚠️ **The field is TRI-STATE and its third state is absence**, meaning UNKNOWN, which renders as nothing and must NEVER read as alive; it covers a running pane, a session the read did not list, a failed probe, and every session shape a dead local pane does not describe. `Session.paneExitApplies` is the single place that scoping lives, and it fails closed for four shapes: a direct-PTY session (no pane), a remote SSH session (the local pane is the ssh client, whose death is a transport drop OR an exit — the whole of #355), a docker case (the local pane is a `docker exec` into the container's own tmux), and a session rebuilt from the socket (`MuxSession.discovered`: its synthetic `restored-` id matches no `state.json` entry, so a remote session rediscovered after `mux-sessions.json` was lost would arrive looking local). ⚠️ **Never set `status: 'error'`** for an exited pane — that value is the PTY-exit breaker's and the browser answers it with a "restart it?" confirm — and **never null the `pid`**, which is what makes `selectSession()` re-attach and launch a fresh CLI. Local panes keep `remain-on-exit on`; flipping them to `failed` ends the tmux session, nulls the pid and reintroduces the auto-revive #355 removed. ⚠️ **An absent `#{pane_dead_status}` is not 0**: measured on tmux 3.2a a SIGKILLed pane reports neither a status nor a signal (`#{pane_dead_signal}` did not exist before tmux 3.4), so folding it into 0 would turn an unexplained death into a clean exit. ⚠️ **A dead pane may have no pid**: measured on tmux 3.8, `#{pane_pid}` prints blank once the pane's program exits, so `parsePaneRows()` keeps a row with no pid when `#{pane_dead}` is 1 (a LIVE row with no pid is still a bad read and is skipped). `#{pane_dead_time}` then tells one exit from the next, next to the pid, so two reads of one exit still count as two and a hand-run `respawn-pane` that exits 0 again starts a new observation. `reconcileSessions()` keeps such a tracked session alive with its last known pid, and does not rediscover an untracked one, since a made-up pid would reach `killSession()`'s process-tree walk. ⚠️ Kept alive means restored: at the next server start the restore goes through the dead-pane branch of `Session._setupOrAttachMuxSession()`, which respawns the pane and clears `paneExit` (measured on tmux 3.8, and what tmux 3.7 and older always did, since they still printed the pid). So a row kept as evidence of a crash or a startup error survives a restart only until the CLI is relaunched in it. `killSession()` reads `#{pane_dead}` with the pid and, for a dead pane, signals nothing and walks no tree: the recorded pid belongs to the program that exited and may since have been reused by an unrelated process, so only `kill-session` runs (`parsePaneKillRead()`). A session answers only when the read listed EXACTLY ONE pane for it, since Codeman never splits a pane and a session the user split by hand has none that speaks for the agent. The three synchronous `isPaneDead()` callers (the `/wait` route, the TUI, the attach path) keep their own probes — this watcher is never fresh enough for them. ⚠️ **A path that starts a command in a pane must clear the record AND persist**, since the watcher's next tick sees the field already cleared and writes nothing. ⚠️ **The always-on timer gates the READ, never the tick.** `hasObservablePaneSession()` (`tmux-manager.ts`) skips the tmux exec while every session on the manager is one of the shapes `paneExitApplies` forces to UNKNOWN, so an instance running only remote or Docker work keeps ticking and costs nothing; the two predicates are two copies of one rule, and `test/session-pane-exit.test.ts` pins them against each other for the four session shapes that exist today — a FIFTH condition added to one and not the other still fails nothing, so change them together. Skipping retracts nothing, for the same reason a failed read does not. ⚠️ **The muted status dot is a specificity fight, and it is fought on three surfaces.** The tab renders `status` as before, and `tab-agent-exited` only quiets the dot, so the rule excludes three states BY HAND: `.tab-alert-action` and `.tab-alert-idle` on the tab, and `.tab-status.error` on the dot itself. Each of those colours means "this needs you" — the two alerts because a human is blocked, `error` because the browser answers it with a "restart it?" confirm — and each must survive the exit. The rich tab rail needs a SECOND copy of the rule, because its own `tab-state-*` dot rules are (0,9,1) against the strip's (0,5,0) — measured, an exited session on a detailed rail kept a full green dot and the working halo beside a badge reading "exited". Its twin matches that specificity exactly and therefore must stay BELOW those rules in source order. mobile.css needs a THIRD copy, with `!important`, because the phone block enlarges a `busy` dot and gives it a green glow that way, and `status` stays `busy` for a pane whose agent died mid-turn — without it a phone renders a grey dot still wearing the green halo. `test/session-pane-exit-ui.test.ts` resolves the real stylesheets in jsdom rather than matching selector text — styles.css for the desktop cases and both files for the phone ones — so the ordering, the hand-written exclusions and a missing phone rule all fail there. Tests: `test/session-pane-exit.test.ts`, `test/tmux-manager.test.ts`, `test/session-pane-exit-ui.test.ts`. +**Codeman creates every pane with `remain-on-exit on`, so a session whose agent exited still looks alive.** `/exit` ends the CLI, tmux keeps the pane and the tmux session, and the `tmux attach-session` process Codeman records as `Session.pid` runs on, so no PTY exit handler fires and the record keeps its pid and `status: 'idle'` (Ark0N/Codeman#446). `SessionState.paneExit` (`{status?, signal?, at}`) is the fact tmux already knows, published through `toState()` so it rides `session:updated` and lands in `state.json` on the same persist — there is no SSE event for it. One batched `tmux list-panes -a` per tick fills it, from `TmuxManager.startPaneExitWatcher()`, which has its OWN always-on interval: the stats collector cannot carry it, because the browser arms and disarms that one with the Monitor panel (`panels-ui.js`) and boot skips it entirely when no session was recovered. ⚠️ **The field is TRI-STATE and its third state is absence**, meaning UNKNOWN, which renders as nothing and must NEVER read as alive; it covers a running pane, a session the read did not list, a failed probe, and every session shape a dead local pane does not describe. `Session.paneExitApplies` is the single place that scoping lives, and it fails closed for four shapes: a direct-PTY session (no pane), a remote SSH session (the local pane is the ssh client, whose death is a transport drop OR an exit — the whole of #355), a docker case (the local pane is a `docker exec` into the container's own tmux), and a session rebuilt from the socket (`MuxSession.discovered`: its synthetic `restored-` id matches no `state.json` entry, so a remote session rediscovered after `mux-sessions.json` was lost would arrive looking local). ⚠️ **Never set `status: 'error'`** for an exited pane — that value is the PTY-exit breaker's and the browser answers it with a "restart it?" confirm — and **never null the `pid`**, which is what makes `selectSession()` re-attach and launch a fresh CLI. Local panes keep `remain-on-exit on`; flipping them to `failed` ends the tmux session, nulls the pid and reintroduces the auto-revive #355 removed. ⚠️ **An absent `#{pane_dead_status}` is not 0**: measured on tmux 3.2a a SIGKILLed pane reports neither a status nor a signal (`#{pane_dead_signal}` did not exist before tmux 3.4), so folding it into 0 would turn an unexplained death into a clean exit. ⚠️ **A dead pane may have no pid**: measured on tmux 3.8, `#{pane_pid}` prints blank once the pane's program exits, so `parsePaneRows()` keeps a row with no pid whenever tmux answered `#{pane_dead}`, and skips only a row with neither. The pid goes blank when the pty closes, and `#{pane_dead}` turns 1 only once tmux has collected the exit status, which took several seconds for some exits on tmux 3.4: a row with no pid and `pane_dead` 0 is that window, and a restart in it must not drop the session. `#{pane_dead_time}` then tells one exit from the next, next to the pid, so two reads of one exit still count as two and a hand-run `respawn-pane` that exits 0 again starts a new observation. `reconcileSessions()` keeps such a tracked session alive with its last known pid, and does not rediscover an untracked one, since a made-up pid would reach `killSession()`'s process-tree walk. ⚠️ Kept alive means restored: at the next server start the restore goes through the dead-pane branch of `Session._setupOrAttachMuxSession()`, which respawns the pane and clears `paneExit` (measured on tmux 3.8, and what tmux 3.7 and older always did, since they still printed the pid). So a row kept as evidence of a crash or a startup error survives a restart only until the CLI is relaunched in it. `killSession()` reads `#{pane_dead}` with the pid and, for a dead pane, signals nothing and walks no tree: the recorded pid belongs to the program that exited and may since have been reused by an unrelated process, so only `kill-session` runs (`parsePaneKillRead()`). ⚠️ The flag alone is not trusted: before tmux 3.7 `#{pane_dead}` means only that the pty is closed, so a program that closed its tty and ignores SIGHUP reads dead while it runs. A dead reading counts only with a blank pid or a set `#{pane_dead_time}`, which keeps the old close on tmux 3.3a to 3.6. A session answers only when the read listed EXACTLY ONE pane for it, since Codeman never splits a pane and a session the user split by hand has none that speaks for the agent. The three synchronous `isPaneDead()` callers (the `/wait` route, the TUI, the attach path) keep their own probes — this watcher is never fresh enough for them. ⚠️ **A path that starts a command in a pane must clear the record AND persist**, since the watcher's next tick sees the field already cleared and writes nothing. ⚠️ **The always-on timer gates the READ, never the tick.** `hasObservablePaneSession()` (`tmux-manager.ts`) skips the tmux exec while every session on the manager is one of the shapes `paneExitApplies` forces to UNKNOWN, so an instance running only remote or Docker work keeps ticking and costs nothing; the two predicates are two copies of one rule, and `test/session-pane-exit.test.ts` pins them against each other for the four session shapes that exist today — a FIFTH condition added to one and not the other still fails nothing, so change them together. Skipping retracts nothing, for the same reason a failed read does not. ⚠️ **The muted status dot is a specificity fight, and it is fought on three surfaces.** The tab renders `status` as before, and `tab-agent-exited` only quiets the dot, so the rule excludes three states BY HAND: `.tab-alert-action` and `.tab-alert-idle` on the tab, and `.tab-status.error` on the dot itself. Each of those colours means "this needs you" — the two alerts because a human is blocked, `error` because the browser answers it with a "restart it?" confirm — and each must survive the exit. The rich tab rail needs a SECOND copy of the rule, because its own `tab-state-*` dot rules are (0,9,1) against the strip's (0,5,0) — measured, an exited session on a detailed rail kept a full green dot and the working halo beside a badge reading "exited". Its twin matches that specificity exactly and therefore must stay BELOW those rules in source order. mobile.css needs a THIRD copy, with `!important`, because the phone block enlarges a `busy` dot and gives it a green glow that way, and `status` stays `busy` for a pane whose agent died mid-turn — without it a phone renders a grey dot still wearing the green halo. `test/session-pane-exit-ui.test.ts` resolves the real stylesheets in jsdom rather than matching selector text — styles.css for the desktop cases and both files for the phone ones — so the ordering, the hand-written exclusions and a missing phone rule all fail there. Tests: `test/session-pane-exit.test.ts`, `test/tmux-manager.test.ts`, `test/session-pane-exit-ui.test.ts`. ⚠️ **The tab's badge is translated (zh-CN), so its updates compare with English, never the DOM.** `applyPaneExitBadge()` remembers the last English badge text (`data-label`) and the tab's accessible name (`data-aria-source`), both also seeded by the full render, and writes only when those change: the translator rewrites both in zh-CN, and a DOM compare (or an unconditional set) would write the English back on every incremental pass for it to translate again. i18n.js has `exited` and patterns for `exited (N)`, `exited (signal N)` and ` session, agent exited ...` (the name passed through); `test/i18n-exit-run-help.test.ts` covers every `paneExitLabel()` form. diff --git a/src/tmux-manager.ts b/src/tmux-manager.ts index 1cf2af1b..4b211318 100644 --- a/src/tmux-manager.ts +++ b/src/tmux-manager.ts @@ -315,8 +315,9 @@ export interface PaneRow { /** tmux session this pane belongs to. Repeats once per pane of a split session. */ sessionName: string; /** - * `#{pane_pid}` — the process tmux started in the pane. Absent only for a dead - * pane: tmux 3.8 prints it blank once the program has exited. + * `#{pane_pid}` — the process tmux started in the pane. Absent only when tmux + * printed it blank: tmux 3.8 does that once the pane's pty has closed, which + * can be seconds before `#{pane_dead}` turns 1. */ pid?: number; /** `#{pane_dead}` — true for 1, false for 0, undefined when tmux said nothing. */ @@ -378,9 +379,12 @@ function paneField(fields: string[], index: number): number | undefined { * into one row per pane, in tmux's own order. Exported for unit testing. * * - Skips empty lines and lines without the separator. - * - Skips entries with an empty name, and entries with a non-numeric pid unless - * the pane is dead: tmux 3.8 blanks `#{pane_pid}` for a pane whose program - * exited, and dropping that row would hide exactly the exit this read is for. + * - Skips entries with an empty name, and entries where tmux answered neither a + * pid nor `#{pane_dead}`, which is a bad read. tmux 3.8 blanks `#{pane_pid}` + * as soon as the pane's pty closes, while `#{pane_dead}` turns 1 only once + * tmux has collected the exit status (several seconds for some exits, + * measured on tmux 3.4). A row with no pid and `pane_dead` 0 is that window, + * and dropping it would report a live session as gone. * - Leaves every field after the pid undefined when it is blank or absent, so a * row from an older tmux still yields its pid. */ @@ -394,7 +398,7 @@ export function parsePaneRows(output: string): PaneRow[] { const deadFlag = fields[2]; const dead = deadFlag === '1' ? true : deadFlag === '0' ? false : undefined; const pid = paneField(fields, 1); - if (!sessionName || (pid === undefined && dead !== true)) continue; + if (!sessionName || (pid === undefined && dead === undefined)) continue; rows.push({ sessionName, ...(pid !== undefined ? { pid } : {}), @@ -411,21 +415,34 @@ export function parsePaneRows(output: string): PaneRow[] { /** What {@link TmuxManager.killSession} reads about a pane before it signals anything. */ export interface PaneKillRead { - /** `#{pane_dead}` was 1: the pane's program exited, so no process is left to signal. */ + /** + * The pane's program exited, so no process is left to signal: `#{pane_dead}` + * was 1 AND either the pid was blank or `#{pane_dead_time}` was set. + */ dead: boolean; /** `#{pane_pid}`, or null when tmux printed none (tmux 3.8 for a dead pane) or the read failed. */ pid: number | null; } /** - * Parse the kill path's `#{pane_dead}|#{pane_pid}` read. Exported for unit testing. - * Only an explicit `1` is dead; anything else keeps the old behaviour of + * Parse the kill path's `#{pane_dead}|#{pane_pid}|#{pane_dead_time}` read. + * Exported for unit testing. + * + * Only an explicit `1` can be dead, and only with a second sign of an exit. + * Before tmux 3.7 `#{pane_dead}` means only that the pane's pty is closed, so + * a program that closed its tty and ignores SIGHUP reads as dead while it + * still runs, with its pid printed and no exit time. Trusting the flag alone + * would leave that program running after a close that used to kill it. tmux + * 3.8 blanks the pid of an exited program and stamps `#{pane_dead_time}`, so + * either one confirms the exit. Anything else keeps the old behaviour of * signalling the pid (or the recorded one when tmux printed none). */ export function parsePaneKillRead(output: string): PaneKillRead { - const [deadFlag = '', pidField = ''] = output.trim().split(PANE_LIST_SEP); - const pid = parseInt(pidField, 10); - return { dead: deadFlag === '1', pid: Number.isNaN(pid) ? null : pid }; + const [deadFlag = '', pidField = '', deadTimeField = ''] = output.trim().split(PANE_LIST_SEP); + const parsedPid = parseInt(pidField, 10); + const pid = Number.isNaN(parsedPid) ? null : parsedPid; + const exited = pid === null || !Number.isNaN(parseInt(deadTimeField, 10)); + return { dead: deadFlag === '1' && exited, pid }; } /** @@ -2921,7 +2938,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { } try { const { stdout } = await execAsync( - `${this.tmux()} display-message -t "${muxName}" -p '#{pane_dead}${PANE_LIST_SEP}#{pane_pid}'`, + `${this.tmux()} display-message -t "${muxName}" -p '#{pane_dead}${PANE_LIST_SEP}#{pane_pid}${PANE_LIST_SEP}#{pane_dead_time}'`, { encoding: 'utf-8', timeout: EXEC_TIMEOUT_MS } ); return parsePaneKillRead(stdout); @@ -3448,7 +3465,9 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { // since have handed to an unrelated process: walking its tree or signalling // it could kill that. tmux 3.8 prints no pid for a dead pane, so without this // check the fallback below would pick that stale pid every time. Only the - // kill-session below runs for it. + // kill-session below runs for it. A blank pid with `#{pane_dead}` still 0 + // (tmux 3.8, pty closed, exit not collected yet) keeps the fallback: tmux + // has not reaped that process, so its pid cannot have been reused. const pane = await this.readPaneForKill(session.muxName); const currentPid = pane.dead ? null : (pane.pid ?? session.pid); @@ -3565,7 +3584,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { // socket tag to reconcile and no cross-socket ambiguity that could mark a // live session dead (the root cause of vanished/duplicate tabs). // Every tmux session on the socket, with its pane pid when tmux printed one. - // A session whose only pane is dead is still listed, with no pid (tmux 3.8 + // A session whose only pane is dead or closing is still listed, with no pid (tmux 3.8 // blanks it): the session exists, so it must not be reported as gone. let active: Map; const paneDirs = new Map(); @@ -3617,8 +3636,9 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { for (const [sessionId, session] of this.sessions) { if (active.has(session.muxName)) { alive.push(sessionId); - // No pid is a dead pane: keep the last one known, which is what tmux - // itself reported for a dead pane before 3.8. + // No pid is a dead or closing pane (tmux 3.8 blanks it once the pty + // closes): keep the last one known, which is what tmux itself reported + // for such a pane before 3.8. const pid = active.get(session.muxName); if (pid !== undefined && pid !== session.pid) session.pid = pid; } else { diff --git a/test/tmux-manager.test.ts b/test/tmux-manager.test.ts index 35dace11..40582f8d 100644 --- a/test/tmux-manager.test.ts +++ b/test/tmux-manager.test.ts @@ -1232,7 +1232,9 @@ describe('TmuxManager (unit)', () => { .map(([cmd]) => cmd) .filter((cmd): cmd is string => typeof cmd === 'string' && cmd.includes(' list-panes ')); expect(listCalls).toHaveLength(1); - expect(listCalls[0]).toContain("|#{pane_current_path}'"); + // The last two fields: the exit time that tells one exit from the next + // on tmux 3.8, then the directory, which must stay last. + expect(listCalls[0]).toContain("|#{pane_dead_time}|#{pane_current_path}'"); } finally { nonTestManager.destroy(); } @@ -1335,7 +1337,11 @@ describe('TmuxManager (unit)', () => { | undefined; // promisify(exec) on this mock resolves with the second argument. tmux 3.8 // prints a dead pane's pid blank, so a pid-only read answers an empty line. - const stdout = cmd.includes(' display-message ') ? (cmd.includes('#{pane_dead}') ? '1|\n' : '\n') : ''; + const stdout = cmd.includes(' display-message ') + ? cmd.includes('#{pane_dead}') + ? '1||1795091616\n' + : '\n' + : ''; if (callback) setImmediate(() => callback(null, { stdout, stderr: '' }, '')); return { on: vi.fn(), kill: vi.fn(), pid: 12345 }; }) as unknown as typeof exec); @@ -1365,6 +1371,49 @@ describe('TmuxManager (unit)', () => { nonTestManager.destroy(); } }); + + // The counterpart: the dead-pane rule must not stop a close from killing a + // pane whose program still runs. + it('still signals the process tree of a live pane on close', async () => { + const defaultExec = mockedExec.getMockImplementation(); + mockedExec.mockImplementation(((cmd: string, optionsOrCallback?: unknown, maybeCallback?: unknown) => { + const callback = (typeof optionsOrCallback === 'function' ? optionsOrCallback : maybeCallback) as + | ((err: Error | null, out: unknown, stderr: string) => void) + | undefined; + // promisify(exec) on this mock resolves with the second argument. A live + // pane: not dead, its own pid, no exit time. + const stdout = cmd.includes(' display-message ') ? (cmd.includes('#{pane_dead}') ? '0|4343|\n' : '4343\n') : ''; + if (callback) setImmediate(() => callback(null, { stdout, stderr: '' }, '')); + return { on: vi.fn(), kill: vi.fn(), pid: 12345 }; + }) as unknown as typeof exec); + const kill = vi.spyOn(process, 'kill').mockImplementation(() => true); + const NonTestTmuxManager = await importWithTmuxCommandsEnabled(); + const nonTestManager = new NonTestTmuxManager(); + nonTestManager.registerSession({ + sessionId: 'beef5555', + muxName: 'codeman-beef5555', + pid: 4242, + createdAt: Date.now(), + workingDir: '/tmp', + mode: 'claude', + attached: false, + }); + + try { + expect(await nonTestManager.killSession('beef5555')).toBe(true); + // The pid tmux printed is signalled, not the recorded one. + expect(kill.mock.calls.some(([pid]) => Math.abs(Number(pid)) === 4343)).toBe(true); + expect(kill.mock.calls.filter(([pid]) => Math.abs(Number(pid)) === 4242)).toEqual([]); + const commands = mockedExec.mock.calls.map(([cmd]) => String(cmd)); + expect(commands.some((cmd) => cmd.includes('display-message') && cmd.includes('#{pane_dead}'))).toBe(true); + expect(commands.some((cmd) => cmd.includes('kill-session -t "codeman-beef5555"'))).toBe(true); + expect(nonTestManager.getSession('beef5555')).toBeUndefined(); + } finally { + kill.mockRestore(); + mockedExec.mockImplementation(defaultExec!); + nonTestManager.destroy(); + } + }); }); }); @@ -1511,9 +1560,20 @@ describe('parsePaneRows', () => { expect(row.currentPath).toBeUndefined(); }); - it('still skips a live pane with a blank pid, which is a bad read', () => { - expect(parsePaneRows('codeman-aaaa||0||||/home/user/project')).toEqual([]); + // Measured on tmux 3.4: the pid goes blank when the pty closes, and + // `#{pane_dead}` turns 1 only once tmux has collected the exit status, which + // took seconds for some exits. A restart in that window must keep the session. + it('keeps a pane whose pid went blank before tmux marked it dead', () => { + const [row] = parsePaneRows('codeman-aaaa||0||||/home/user/project'); + expect(row).toBeDefined(); + expect(row.pid).toBeUndefined(); + expect(row.dead).toBe(false); + expect(row.currentPath).toBe('/home/user/project'); + }); + + it('still skips a row with neither a pid nor a dead flag, which is a bad read', () => { expect(parsePaneRows('codeman-aaaa||')).toEqual([]); + expect(parsePaneRows('codeman-aaaa||||||/home/user/project')).toEqual([]); }); it('reads the exit time, and leaves it undefined while the pane runs', () => { @@ -1527,17 +1587,26 @@ describe('parsePaneRows', () => { describe('parsePaneKillRead', () => { it('reads a live pane as its pid', () => { - expect(parsePaneKillRead('0|4242\n')).toEqual({ dead: false, pid: 4242 }); + expect(parsePaneKillRead('0|4242|\n')).toEqual({ dead: false, pid: 4242 }); }); it('reads a dead pane as dead, with the pid tmux 3.8 leaves blank', () => { // killSession must not walk or signal the recorded pid of an exited program: // the OS may have reused it for an unrelated process. - expect(parsePaneKillRead('1|\n')).toEqual({ dead: true, pid: null }); + expect(parsePaneKillRead('1||1795091616\n')).toEqual({ dead: true, pid: null }); + expect(parsePaneKillRead('1||\n')).toEqual({ dead: true, pid: null }); }); - it('reads a dead pane as dead on a tmux that still prints its pid', () => { - expect(parsePaneKillRead('1|4242')).toEqual({ dead: true, pid: 4242 }); + it('reads a dead pane as dead on a tmux that still prints its pid, once it has an exit time', () => { + expect(parsePaneKillRead('1|4242|1795091616')).toEqual({ dead: true, pid: 4242 }); + }); + + // Before tmux 3.7 `#{pane_dead}` means only that the pty is closed. A program + // that closed its tty and ignores SIGHUP still runs there, with its pid + // printed and no exit time, and the close must still signal it. + it('does not trust a dead flag with a pid and no exit time (tmux 3.3a to 3.6)', () => { + expect(parsePaneKillRead('1|4242|')).toEqual({ dead: false, pid: 4242 }); + expect(parsePaneKillRead('1|4242')).toEqual({ dead: false, pid: 4242 }); }); it('treats an unreadable answer as not dead, so the recorded pid is still used', () => {