From 9309500d409cb7caa79769f4d6fe7bf9824b7531 Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Thu, 26 Nov 2026 10:20:57 +0100 Subject: [PATCH] fix(tmux): a pane pid of 0 falls back to the recorded pid on close Review follow-up (owner's merge-time items, applied here). - killSession() used `pane.pid ?? session.pid`, which kept tmux's 0 for an empty active pane (`split-window ''`: `1|0|` up to tmux 3.6, `0|0|` on 3.7) beside a running agent, so the close signalled nothing where master signals the agent's tree. `||` restores that; isSignalablePid() still refuses 0 or 1. - kill-pid-guard.test.ts answered the old pid-only read, which the three-field parser read as no pid, so no case gave killSession() tmux's own 0. Its mock now answers the kill read, with cases for `1|0|`, `0|0|` and `0||` against a recorded agent pid and a recorded 0. - Tests pin the whole kill read format, and the reconcile rule that a pane without a pid never overwrites a live pane's pid. Dropping `#{pane_dead_time}`, using `??` or `pane.pid` alone, or a plain `active.set(...)` each fail now. - parsePaneKillRead() cases for `1|0|`, `0|0|` and `1|-1|`. - Comments and docs: the blank pid with a late dead flag is tmux 3.8; on 3.4 only the seconds to collect the status were measured. A pid below 2 is no pid. The recorded pid is unreaped in the closing window only when it is the pane's start pid (`respawn-pane` breaks that). Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- docs/architecture-invariants.md | 2 +- src/tmux-manager.ts | 22 +++++++----- test/kill-pid-guard.test.ts | 44 +++++++++++++++++++++++- test/tmux-manager.test.ts | 60 ++++++++++++++++++++++++++++++--- 5 files changed, 113 insertions(+), 17 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 76c71a9a..2b0724ba 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 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) +**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 pid below 2 is no pid, since an empty pane prints 0 before tmux 3.8); 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 2ada4b92..969f5792 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 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`. +**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. On tmux 3.8 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 (measured on tmux 3.4, where the pid itself stays): 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 pid below 2 is no pid: an empty active pane (`split-window ''`) prints 0 before tmux 3.8, so the close falls back to the recorded pid (`pane.pid || session.pid`), and `isSignalablePid()` refuses 0 or 1 wherever it comes from. 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 c2fbec55..6556fec3 100644 --- a/src/tmux-manager.ts +++ b/src/tmux-manager.ts @@ -382,9 +382,10 @@ function paneField(fields: string[], index: number): number | undefined { * - 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. + * tmux has collected the exit status. Collecting it took several seconds for + * some exits (measured on tmux 3.4, where the pid itself stays). 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. */ @@ -3482,12 +3483,15 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { // check the fallback below would pick that stale pid every time. Only the // 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. - // An empty pane has no process either: tmux says 0, and so does the record - // once a server start has read it. Nothing is signalled for pid 0 or 1 - // (isSignalablePid), and only tmux is asked to close the session. + // has not reaped the pane's process yet. That holds when the recorded pid is + // the one the pane was started with; a hand-run `respawn-pane` breaks it. + // A pid of 0 is no pid either: tmux prints it for an empty active pane + // (`split-window ''`) before 3.8, beside a session's running agent, so + // `||` falls back to the recorded pid as master always did. Nothing is + // ever signalled for 0 or 1 (isSignalablePid): then only tmux is asked to + // close the session. const pane = await this.readPaneForKill(session.muxName); - const candidatePid = pane.dead ? null : (pane.pid ?? session.pid); + const candidatePid = pane.dead ? null : pane.pid || session.pid; const currentPid = candidatePid !== null && isSignalablePid(candidatePid) ? candidatePid : null; console.log( @@ -3495,7 +3499,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { ? `[TmuxManager] Killing session ${session.muxName} (PID ${currentPid})` : pane.dead ? `[TmuxManager] Killing session ${session.muxName} (pane dead, PID ${session.pid} not signalled)` - : `[TmuxManager] Killing session ${session.muxName} (no process, pane pid ${candidatePid})` + : `[TmuxManager] Killing session ${session.muxName} (no usable pid, recorded ${session.pid}, nothing signalled)` ); const allPids: number[] = []; diff --git a/test/kill-pid-guard.test.ts b/test/kill-pid-guard.test.ts index 2a820b19..b2a3ec64 100644 --- a/test/kill-pid-guard.test.ts +++ b/test/kill-pid-guard.test.ts @@ -22,6 +22,9 @@ vi.mock('node:child_process', async () => { return { ...actual, exec: vi.fn(), execFile: vi.fn(), execSync: vi.fn(), spawn: vi.fn() }; }); +/** The kill path's pane read, as killSession() sends it. */ +const KILL_READ = "'#{pane_dead}|#{pane_pid}|#{pane_dead_time}'"; + /** A machine: init, kthreadd, the user's own programs, and one agent (4242) with a child. */ const PS = ['1 0', '2 0', '900 1', '901 900', '902 900', '4242 901', '4243 4242'].join('\n') + '\n'; @@ -36,12 +39,18 @@ describe('isSignalablePid', () => { describe('killSession and a pane without a process', () => { let panePid: string; + /** + * The kill path's own read, `#{pane_dead}|#{pane_pid}|#{pane_dead_time}`. Unset, it + * answers a live pane with `panePid`, which is what tmux prints for one. + */ + let paneRead: string | undefined; let commands: string[]; let kill: MockInstance; let signals: [number, string | number | undefined][]; beforeEach(() => { panePid = '4242\n'; + paneRead = undefined; commands = []; signals = []; vi.mocked(execSync).mockImplementation(((cmd: string) => { @@ -51,7 +60,11 @@ describe('killSession and a pane without a process', () => { vi.mocked(exec).mockImplementation(((cmd: string, options: unknown, maybeCallback?: unknown) => { commands.push(cmd); const callback = (typeof options === 'function' ? options : maybeCallback) as (e: null, out: object) => void; - const stdout = cmd.includes('display-message') ? panePid : ''; + const stdout = !cmd.includes('display-message') + ? '' + : cmd.includes(KILL_READ) + ? (paneRead ?? `0|${panePid.trim()}|\n`) + : panePid; setImmediate(() => callback(null, { stdout, stderr: '' })); return { on: vi.fn(), kill: vi.fn(), pid: 12345 }; }) as unknown as typeof exec); @@ -97,6 +110,8 @@ describe('killSession and a pane without a process', () => { return m; } const closedByTmux = () => commands.some((c) => c.includes('kill-session -t "codeman-feed1234"')); + /** The close read the pane through the three-field kill read, and not the old pid-only one. */ + const readTheKillFormat = () => commands.some((c) => c.includes(KILL_READ)); // The control: without it, a guard that refused every kill would pass the rest. it('still signals the process tree of a real pane', async () => { @@ -106,9 +121,36 @@ describe('killSession and a pane without a process', () => { expect(signals).toContainEqual([-4242, 'SIGTERM']); expect(signals.every(([pid]) => [4242, 4243].includes(Math.abs(pid)))).toBe(true); expect(closedByTmux()).toBe(true); + expect(readTheKillFormat()).toBe(true); m.destroy(); }); + // tmux's own 0, for an empty active pane beside the agent: `1|0|` up to tmux 3.6, + // `0|0|` on 3.7, and `0||` is tmux 3.8's closing window (pty closed, exit not + // collected). Each falls back to the recorded agent pid, as master does, and + // nothing outside that pid's tree is signalled. + for (const answer of ['1|0|', '0|0|', '0||']) { + it(`falls back to the recorded pid when the kill read answers ${answer}`, async () => { + paneRead = `${answer}\n`; + const m = await manager(4242); + expect(await m.killSession('feed1234')).toBe(true); + expect(readTheKillFormat()).toBe(true); + expect(signals).toContainEqual([-4242, 'SIGTERM']); + expect(signals.every(([pid]) => [4242, 4243].includes(Math.abs(pid)))).toBe(true); + expect(closedByTmux()).toBe(true); + m.destroy(); + }); + + it(`signals nothing for ${answer} when the record holds 0 too`, async () => { + paneRead = `${answer}\n`; + const m = await manager(0); + expect(await m.killSession('feed1234')).toBe(true); + expect(signals).toEqual([]); + expect(closedByTmux()).toBe(true); + m.destroy(); + }); + } + for (const pid of [0, 1]) { it(`signals nothing for pid ${pid}, and tmux still closes the session`, async () => { panePid = `${pid}\n`; diff --git a/test/tmux-manager.test.ts b/test/tmux-manager.test.ts index d4c43990..17a8565c 100644 --- a/test/tmux-manager.test.ts +++ b/test/tmux-manager.test.ts @@ -1309,6 +1309,36 @@ describe('TmuxManager (unit)', () => { } }); + // A split session: the live pane's pid is what the record follows, whichever + // order tmux lists the panes in. A pane without a pid never overwrites it. + it('keeps the pid of the live pane when another pane of the session has none', async () => { + mockedExecSync.mockImplementation((cmd: string) => { + if (typeof cmd === 'string' && cmd.includes(' list-panes ')) { + return ['codeman-abcd5555|505|0||||/srv', 'codeman-abcd5555||1|0||1795091616|'].join('\n'); + } + return ''; + }); + const NonTestTmuxManager = await importWithTmuxCommandsEnabled(); + const nonTestManager = new NonTestTmuxManager(); + nonTestManager.registerSession({ + sessionId: 'abcd5555', + muxName: 'codeman-abcd5555', + pid: 50, + createdAt: Date.now(), + workingDir: '/tmp', + mode: 'claude', + attached: false, + }); + + try { + const { alive } = await nonTestManager.reconcileSessions(); + expect(alive).toEqual(['abcd5555']); + expect(nonTestManager.getSession('abcd5555')?.pid).toBe(505); + } finally { + nonTestManager.destroy(); + } + }); + it('does not rediscover an untracked session whose only pane is dead and has no pid', async () => { // A made-up pid would reach killSession()'s process-tree walk. mockedExecSync.mockImplementation((cmd: string) => { @@ -1362,7 +1392,12 @@ describe('TmuxManager (unit)', () => { expect(await nonTestManager.killSession('dead5555')).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); + // The whole kill read: dropping `#{pane_dead_time}` would trust a pre-3.7 dead flag again. + expect( + commands.some( + (cmd) => cmd.includes('display-message') && cmd.includes("'#{pane_dead}|#{pane_pid}|#{pane_dead_time}'") + ) + ).toBe(true); expect(commands.some((cmd) => cmd.includes('kill-session -t "codeman-dead5555"'))).toBe(true); expect(nonTestManager.getSession('dead5555')).toBeUndefined(); } finally { @@ -1417,7 +1452,12 @@ describe('TmuxManager (unit)', () => { 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); + // The whole kill read: dropping `#{pane_dead_time}` would trust a pre-3.7 dead flag again. + expect( + commands.some( + (cmd) => cmd.includes('display-message') && cmd.includes("'#{pane_dead}|#{pane_pid}|#{pane_dead_time}'") + ) + ).toBe(true); expect(commands.some((cmd) => cmd.includes('kill-session -t "codeman-beef5555"'))).toBe(true); expect(nonTestManager.getSession('beef5555')).toBeUndefined(); } finally { @@ -1572,9 +1612,10 @@ describe('parsePaneRows', () => { expect(row.currentPath).toBeUndefined(); }); - // 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. + // tmux 3.8 blanks the pid when the pty closes, and `#{pane_dead}` turns 1 only + // once tmux has collected the exit status. Collecting it took seconds for some + // exits (measured on tmux 3.4, where the pid stays and only that delay was + // seen). 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(); @@ -1621,6 +1662,15 @@ describe('parsePaneKillRead', () => { expect(parsePaneKillRead('1|4242')).toEqual({ dead: false, pid: 4242 }); }); + // A pid below 2 is no pid. An empty active pane prints 0 before tmux 3.8, and + // killSession() falls back to the recorded pid for it; it is never dead here, + // because 0 is not a blank pid and there is no exit time. + it('reads a pid of 0 or below as no exit, whatever the flag says', () => { + expect(parsePaneKillRead('1|0|')).toEqual({ dead: false, pid: 0 }); + expect(parsePaneKillRead('0|0|')).toEqual({ dead: false, pid: 0 }); + expect(parsePaneKillRead('1|-1|')).toEqual({ dead: false, pid: -1 }); + }); + it('treats an unreadable answer as not dead, so the recorded pid is still used', () => { expect(parsePaneKillRead('')).toEqual({ dead: false, pid: null }); expect(parsePaneKillRead('|')).toEqual({ dead: false, pid: null });