From bee4948e1a2a207a817787aa6f9fc35993b68ae8 Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Thu, 19 Nov 2026 15:11:30 +0100 Subject: [PATCH 1/7] fix(tmux): see an exited agent on tmux 3.8, which blanks a dead pane's pid tmux 3.8 prints #{pane_pid} blank once a pane's program has exited. parsePaneRows() skipped any row without a numeric pid, so the watcher never saw an exited agent: the session stayed idle with no paneExit and the clean-exit sweep (#446) never closed it. reconcileSessions() read the same rows, so at server start such a session's record was dropped while its tmux session stayed on the socket. Keep a dead row with no pid (a live one is still a bad read), tell one exit from the next by #{pane_dead_time} next to the pid, and keep a tracked session with a dead pane alive with its last known pid. An untracked one is still not rediscovered: a made-up pid would reach killSession()'s process-tree walk. Co-Authored-By: Claude Opus 5.5 --- .changeset/dead-pane-blank-pid.md | 5 ++ docs/architecture-invariants.md | 2 +- src/tmux-manager.ts | 85 ++++++++++++------ test/pane-cwd-tracking.test.ts | 48 +++++----- test/tmux-manager.test.ts | 144 ++++++++++++++++++++++++++---- 5 files changed, 214 insertions(+), 70 deletions(-) create mode 100644 .changeset/dead-pane-blank-pid.md diff --git a/.changeset/dead-pane-blank-pid.md b/.changeset/dead-pane-blank-pid.md new file mode 100644 index 00000000..fdbd974a --- /dev/null +++ b/.changeset/dead-pane-blank-pid.md @@ -0,0 +1,5 @@ +--- +'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}`. diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index e17a089b..6264bf12 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 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 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. 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 5f77b116..6b232a38 100644 --- a/src/tmux-manager.ts +++ b/src/tmux-manager.ts @@ -277,19 +277,24 @@ const PANE_LIST_SEP = '|'; /** * Format string for `tmux list-panes -F`. Keep in sync with {@link parsePaneRows}. * - * The three `pane_dead*` fields carry the agent-exit signal of Ark0N/Codeman#446. + * The four `pane_dead*` fields carry the agent-exit signal of Ark0N/Codeman#446. * Appending them is backward compatible in both directions. A tmux that does not * know a variable substitutes the empty string rather than failing, which is how * tmux 3.2a answers `#{pane_dead_signal}` (added in 3.4), and the parser reads a * short row as "pid known, deadness unknown" rather than discarding it. * + * `#{pane_dead_time}` is what tells one exit from the next. tmux 3.8 prints a + * blank `#{pane_pid}` once a pane's program has exited, so the pid cannot do it + * there, and the time is stamped once per exit, so a respawned pane that exits + * again reads as a new exit even with the same status. + * * `#{pane_current_path}` comes last on purpose: a directory name may contain the * separator, and only the final field can absorb it without ambiguity. */ const PANE_LIST_FORMAT = `#{session_name}${PANE_LIST_SEP}#{pane_pid}` + `${PANE_LIST_SEP}#{pane_dead}${PANE_LIST_SEP}#{pane_dead_status}${PANE_LIST_SEP}#{pane_dead_signal}` + - `${PANE_LIST_SEP}#{pane_current_path}`; + `${PANE_LIST_SEP}#{pane_dead_time}${PANE_LIST_SEP}#{pane_current_path}`; /** * 构建 pane 启动前的 nofile 修复命令。 @@ -308,31 +313,39 @@ export function buildNofileLimitCommand(targetLimit = CLAUDE_CODE_NOFILE_LIMIT): 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. */ - pid: number; + /** + * `#{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. + */ + pid?: number; /** `#{pane_dead}` — true for 1, false for 0, undefined when tmux said nothing. */ dead?: boolean; /** `#{pane_dead_status}` — the exit code, absent when tmux reported none. */ exitStatus?: number; /** `#{pane_dead_signal}` — the killing signal, absent before tmux 3.4 and when unsignalled. */ exitSignal?: number; + /** `#{pane_dead_time}` — when the program exited (epoch seconds), absent while it runs. */ + deadTime?: number; /** `#{pane_current_path}` — the pane's current directory, absent when tmux reported none. */ currentPath?: string; } /** - * One pane-exit reading, with the pane pid that produced it. + * One pane-exit reading, with the pane pid and exit time that identify it. * - * The pid never leaves this module. It is what distinguishes "the same dead - * pane, seen again" from "a second command in the same pane that also exited - * with the same status", so the `at` stamp can hold across the first and must - * not across the second. {@link PaneExit} itself stays free of it: the pid on + * Neither leaves this module. Together they distinguish "the same dead pane, + * seen again" from "a second command in the same pane that also exited with + * the same status", so the `at` stamp can hold across the first and must not + * across the second. Either may be absent: tmux 3.8 blanks the pid of a dead + * pane, and a tmux before 3.4 has no exit time. {@link PaneExit} itself stays free of it: the pid on * the session record is the attach client's, and a second pid there would * invite exactly the confusion Ark0N/Codeman#446 is about. */ export interface PaneExitObservation { - /** `#{pane_pid}` of the pane this reading came from. */ - panePid: number; + /** `#{pane_pid}` of the pane this reading came from, when tmux reported one. */ + panePid?: number; + /** `#{pane_dead_time}` of the exit this reading saw, when tmux reported one. */ + deadTime?: number; /** What to publish on the session record. */ exit: PaneExit; } @@ -363,7 +376,9 @@ 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 a non-numeric pid or empty name. + * - 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. * - Leaves every field after the pid undefined when it is blank or absent, so a * row from an older tmux still yields its pid. */ @@ -374,17 +389,19 @@ export function parsePaneRows(output: string): PaneRow[] { if (!line.includes(PANE_LIST_SEP)) continue; const fields = line.split(PANE_LIST_SEP); const sessionName = fields[0]; - const pid = parseInt(fields[1] ?? '', 10); - if (!sessionName || Number.isNaN(pid)) continue; 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; rows.push({ sessionName, - pid, - dead: deadFlag === '1' ? true : deadFlag === '0' ? false : undefined, + ...(pid !== undefined ? { pid } : {}), + dead, exitStatus: paneField(fields, 3), exitSignal: paneField(fields, 4), - // Everything after the fifth separator, so a path containing `|` stays whole. - currentPath: fields.slice(5).join(PANE_LIST_SEP) || undefined, + deadTime: paneField(fields, 5), + // Everything after the sixth separator, so a path containing `|` stays whole. + currentPath: fields.slice(6).join(PANE_LIST_SEP) || undefined, }); } return rows; @@ -420,7 +437,8 @@ export function derivePaneExits(rows: PaneRow[], now: number): Map; + // 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 + // blanks it): the session exists, so it must not be reported as gone. + let active: Map; const paneDirs = new Map(); try { const output = execSync(`${this.tmux()} list-panes -a -F '${PANE_LIST_FORMAT}' 2>/dev/null || true`, { @@ -3512,7 +3533,10 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { // Not trimmed: the directory is the last field, so trimming would cut a // trailing space off the last row's path. parsePaneRows skips empty lines. const rows = parsePaneRows(output); - active = new Map(rows.map((row) => [row.sessionName, row.pid])); + active = new Map(); + for (const row of rows) { + if (row.pid !== undefined || !active.has(row.sessionName)) active.set(row.sessionName, row.pid); + } // A discovered session's directory, from its first pane with a usable path. // The path is admitted only if it passes the same check createSession and // respawnPane apply, since it was set by whoever owns the pane, not by us. @@ -3547,10 +3571,12 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { // Check tracked sessions against the live pane list. for (const [sessionId, session] of this.sessions) { - const pid = active.get(session.muxName); - if (pid !== undefined) { + if (active.has(session.muxName)) { alive.push(sessionId); - if (pid !== session.pid) session.pid = pid; + // No pid is a dead pane: keep the last one known, which is what tmux + // itself reported for a dead pane before 3.8. + const pid = active.get(session.muxName); + if (pid !== undefined && pid !== session.pid) session.pid = pid; } else { dead.push(sessionId); this.sessions.delete(sessionId); @@ -3570,6 +3596,9 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { for (const [sessionName, pid] of active) { if (!sessionName.startsWith('codeman-') && !sessionName.startsWith('claudeman-')) continue; + // A session with no live pane has no pid to record, and a made-up one would + // reach killSession()'s process-tree walk. Left undiscovered, as before. + if (pid === undefined) continue; // Only admit names that pass the safe-name pattern. A foreign process on the // shared `tmux -L codeman` socket could create a `codeman-…` session whose name // contains shell metacharacters; rejecting it here keeps it out of this.sessions @@ -3890,9 +3919,10 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { * * An entry keeps the `at` of the FIRST read that saw that exit, so the stamp * says when the agent was found gone rather than when the last poll ran. A - * changed status, a changed signal, or a different pane pid all start a new - * observation — the pid is what catches a second command in the same pane - * that happened to exit the same way. + * changed status, a changed signal, a different pane pid or a different exit + * time all start a new observation — the pid and the time are what catch a + * second command in the same pane that happened to exit the same way (the + * time alone on tmux 3.8, which blanks a dead pane's pid). * * The same rule decides the read count: a repeat of the stored exit adds one, * and anything that starts a new observation starts the count again at 1. @@ -3906,6 +3936,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { const sameExit = prev !== undefined && prev.panePid === next.panePid && + prev.deadTime === next.deadTime && prev.exit.status === next.exit.status && prev.exit.signal === next.exit.signal; this.paneExits.set(muxName, sameExit ? { ...prev, reads: prev.reads + 1 } : { ...next, reads: 1 }); diff --git a/test/pane-cwd-tracking.test.ts b/test/pane-cwd-tracking.test.ts index de02eb73..70b24a80 100644 --- a/test/pane-cwd-tracking.test.ts +++ b/test/pane-cwd-tracking.test.ts @@ -48,7 +48,7 @@ const docker: SessionDocker = { hostId: 'd1', label: 'ctr', containerName: 'ctr' describe('derivePaneCurrentPaths', () => { it("maps each single-pane session to its pane's directory", () => { - const rows = parsePaneRows(['codeman-a|100|0|||/work/proj/sub', 'codeman-b|200|0|||/srv/app'].join('\n')); + const rows = parsePaneRows(['codeman-a|100|0||||/work/proj/sub', 'codeman-b|200|0||||/srv/app'].join('\n')); const paths = derivePaneCurrentPaths(rows); expect(paths.get('codeman-a')).toBe('/work/proj/sub'); expect(paths.get('codeman-b')).toBe('/srv/app'); @@ -56,19 +56,19 @@ describe('derivePaneCurrentPaths', () => { }); it('keeps a separator that belongs to the directory name', () => { - const paths = derivePaneCurrentPaths(parsePaneRows('codeman-a|100|0|||/home/u/weird|dir/sub')); + const paths = derivePaneCurrentPaths(parsePaneRows('codeman-a|100|0||||/home/u/weird|dir/sub')); expect(paths.get('codeman-a')).toBe('/home/u/weird|dir/sub'); }); it('answers nothing for a session split into several panes', () => { // Codeman creates one pane per session; which of a hand-split session's // panes "the" directory belongs to is a guess, so none is made. - const rows = parsePaneRows(['codeman-a|100|0|||/one', 'codeman-a|101|0|||/two'].join('\n')); + const rows = parsePaneRows(['codeman-a|100|0||||/one', 'codeman-a|101|0||||/two'].join('\n')); expect(derivePaneCurrentPaths(rows).has('codeman-a')).toBe(false); }); it('drops a missing or relative directory', () => { - const rows = parsePaneRows(['codeman-a|100|0|||', 'codeman-b|200|0|||rel/ative'].join('\n')); + const rows = parsePaneRows(['codeman-a|100|0||||', 'codeman-b|200|0||||rel/ative'].join('\n')); expect(derivePaneCurrentPaths(rows).size).toBe(0); }); @@ -76,7 +76,7 @@ describe('derivePaneCurrentPaths', () => { // A blank `#{pane_current_path}` is a tmux that could not read the process // cwd that tick, not a pane that has no directory. const previous = new Map([['codeman-a', '/work/proj/sub']]); - const paths = derivePaneCurrentPaths(parsePaneRows('codeman-a|100|0|||'), previous); + const paths = derivePaneCurrentPaths(parsePaneRows('codeman-a|100|0||||'), previous); expect(paths.get('codeman-a')).toBe('/work/proj/sub'); }); @@ -89,7 +89,7 @@ describe('derivePaneCurrentPaths', () => { ['codeman-rel', '/three'], ]); const rows = parsePaneRows( - ['codeman-split|100|0|||', 'codeman-split|101|0|||', 'codeman-rel|300|0|||rel/ative'].join('\n') + ['codeman-split|100|0||||', 'codeman-split|101|0||||', 'codeman-rel|300|0||||rel/ative'].join('\n') ); expect(derivePaneCurrentPaths(rows, previous).size).toBe(0); }); @@ -117,7 +117,7 @@ describe('TmuxManager pane directory bookkeeping', () => { it('records the directory from the same read the pane-exit watcher makes', async () => { const manager = new TestManager(); manager.registerSession(localSession('s1')); - manager.rows = parsePaneRows('codeman-s1|100|0|||/work/proj/sub'); + manager.rows = parsePaneRows('codeman-s1|100|0||||/work/proj/sub'); await manager.refreshPaneExits(); expect(manager.getPaneCurrentPath('codeman-s1')).toBe('/work/proj/sub'); }); @@ -125,7 +125,7 @@ describe('TmuxManager pane directory bookkeeping', () => { it('keeps the last known directory when a read comes back empty', async () => { const manager = new TestManager(); manager.registerSession(localSession('s1')); - manager.rows = parsePaneRows('codeman-s1|100|0|||/work/proj/sub'); + manager.rows = parsePaneRows('codeman-s1|100|0||||/work/proj/sub'); await manager.refreshPaneExits(); manager.rows = []; await manager.refreshPaneExits(); @@ -135,9 +135,9 @@ describe('TmuxManager pane directory bookkeeping', () => { it('keeps the last directory across a blank field on a single-pane read', async () => { const manager = new TestManager(); manager.registerSession(localSession('s1')); - manager.rows = parsePaneRows('codeman-s1|100|0|||/work/proj/sub'); + manager.rows = parsePaneRows('codeman-s1|100|0||||/work/proj/sub'); await manager.refreshPaneExits(); - manager.rows = parsePaneRows('codeman-s1|100|0|||'); + manager.rows = parsePaneRows('codeman-s1|100|0||||'); await manager.refreshPaneExits(); expect(manager.getPaneCurrentPath('codeman-s1')).toBe('/work/proj/sub'); }); @@ -145,9 +145,9 @@ describe('TmuxManager pane directory bookkeeping', () => { it('forgets the directory once the session is split into several panes', async () => { const manager = new TestManager(); manager.registerSession(localSession('s1')); - manager.rows = parsePaneRows('codeman-s1|100|0|||/work/proj/sub'); + manager.rows = parsePaneRows('codeman-s1|100|0||||/work/proj/sub'); await manager.refreshPaneExits(); - manager.rows = parsePaneRows(['codeman-s1|100|0|||/work/proj/sub', 'codeman-s1|101|0|||/work/proj'].join('\n')); + manager.rows = parsePaneRows(['codeman-s1|100|0||||/work/proj/sub', 'codeman-s1|101|0||||/work/proj'].join('\n')); await manager.refreshPaneExits(); expect(manager.getPaneCurrentPath('codeman-s1')).toBeUndefined(); }); @@ -163,7 +163,7 @@ describe('TmuxManager pane directory bookkeeping', () => { } const manager = new RacingManager(); manager.registerSession(localSession('s1')); - manager.rows = parsePaneRows('codeman-s1|100|1|0||/work/proj/sub'); + manager.rows = parsePaneRows('codeman-s1|100|1|0|||/work/proj/sub'); await manager.refreshPaneExits(); expect(manager.getPaneCurrentPath('codeman-s1')).toBe('/work/proj/sub'); expect(manager.getPaneExit('codeman-s1')).toBeUndefined(); @@ -174,7 +174,7 @@ describe('TmuxManager pane directory bookkeeping', () => { const read = vi.spyOn(manager as unknown as { readPaneRows: () => Promise }, 'readPaneRows'); manager.registerSession({ ...localSession('s1'), remote } as MuxSession); manager.registerSession({ ...localSession('s2'), docker } as MuxSession); - manager.rows = parsePaneRows('codeman-s1|100|0|||/tmp'); + manager.rows = parsePaneRows('codeman-s1|100|0||||/tmp'); await manager.refreshPaneExits(); expect(read).not.toHaveBeenCalled(); expect(manager.getPaneCurrentPath('codeman-s1')).toBeUndefined(); @@ -183,9 +183,9 @@ describe('TmuxManager pane directory bookkeeping', () => { it('forgets a session that an authoritative read no longer lists', async () => { const manager = new TestManager(); manager.registerSession(localSession('s1')); - manager.rows = parsePaneRows('codeman-s1|100|0|||/work/proj/sub'); + manager.rows = parsePaneRows('codeman-s1|100|0||||/work/proj/sub'); await manager.refreshPaneExits(); - manager.rows = parsePaneRows('codeman-other|300|0|||/elsewhere'); + manager.rows = parsePaneRows('codeman-other|300|0||||/elsewhere'); await manager.refreshPaneExits(); expect(manager.getPaneCurrentPath('codeman-s1')).toBeUndefined(); }); @@ -584,37 +584,37 @@ describe('a pane read reaching the session record', () => { it('clears the directory once the session is split into several panes', async () => { const { session, broadcast, tick } = buildWithRealManager(); - await tick('codeman-aaaa|100|0|||/work/proj/sub'); + await tick('codeman-aaaa|100|0||||/work/proj/sub'); expect(session.toState().paneCwd).toBe('/work/proj/sub'); expect(broadcast).toHaveBeenCalledTimes(1); - await tick(['codeman-aaaa|100|0|||/work/proj/sub', 'codeman-aaaa|101|0|||/work/proj'].join('\n')); + await tick(['codeman-aaaa|100|0||||/work/proj/sub', 'codeman-aaaa|101|0||||/work/proj'].join('\n')); // An absent cwd is what makes the browser fall back to workingDir. expect(session.toState().paneCwd).toBeUndefined(); expect(broadcast).toHaveBeenCalledTimes(2); // The clear is announced once, not on every later tick that agrees. - await tick(['codeman-aaaa|100|0|||/work/proj/sub', 'codeman-aaaa|101|0|||/work/proj'].join('\n')); + await tick(['codeman-aaaa|100|0||||/work/proj/sub', 'codeman-aaaa|101|0||||/work/proj'].join('\n')); expect(broadcast).toHaveBeenCalledTimes(2); }); it('clears the directory once a read no longer lists the session', async () => { const { session, broadcast, tick } = buildWithRealManager(); - await tick('codeman-aaaa|100|0|||/work/proj/sub'); + await tick('codeman-aaaa|100|0||||/work/proj/sub'); expect(session.toState().paneCwd).toBe('/work/proj/sub'); - await tick('codeman-other|300|0|||/elsewhere'); + await tick('codeman-other|300|0||||/elsewhere'); expect(session.toState().paneCwd).toBeUndefined(); expect(broadcast).toHaveBeenCalledTimes(2); - await tick('codeman-other|300|0|||/elsewhere'); + await tick('codeman-other|300|0||||/elsewhere'); expect(broadcast).toHaveBeenCalledTimes(2); }); it('keeps the directory across a blank field and across a failed read', async () => { const { session, broadcast, tick } = buildWithRealManager(); - await tick('codeman-aaaa|100|0|||/work/proj/sub'); + await tick('codeman-aaaa|100|0||||/work/proj/sub'); // tmux could not read the process cwd for one tick. - await tick('codeman-aaaa|100|0|||'); + await tick('codeman-aaaa|100|0||||'); expect(session.toState().paneCwd).toBe('/work/proj/sub'); // A failed read arrives as no rows at all. await tick(''); diff --git a/test/tmux-manager.test.ts b/test/tmux-manager.test.ts index 9bbef05b..8d0face7 100644 --- a/test/tmux-manager.test.ts +++ b/test/tmux-manager.test.ts @@ -1182,21 +1182,21 @@ describe('TmuxManager (unit)', () => { mockedExecSync.mockImplementation((cmd: string) => { if (typeof cmd === 'string' && cmd.includes(' list-panes ')) { return [ - 'codeman-aaaa1111|101|0|||/home/user/project-a', + 'codeman-aaaa1111|101|0||||/home/user/project-a', // A hand-split session answers with the pane tmux lists first. - 'codeman-bbbb2222|102|0|||/home/user/project-b', - 'codeman-bbbb2222|103|0|||/home/user/project-b/sub', + 'codeman-bbbb2222|102|0||||/home/user/project-b', + 'codeman-bbbb2222|103|0||||/home/user/project-b/sub', // Set by whoever owns the pane, so it must pass the same check as any workingDir. - 'codeman-cccc3333|104|0|||/home/user/$(touch pwned)', + 'codeman-cccc3333|104|0||||/home/user/$(touch pwned)', // A tmux that reported no path. - 'codeman-dddd4444|105|0|||', + 'codeman-dddd4444|105|0||||', // The launch directory every pane starts in; a remote or docker pane never leaves it. - 'codeman-eeee5555|106|0|||/tmp', + 'codeman-eeee5555|106|0||||/tmp', // A directory deleted while its pane ran, as tmux 3.4 on Linux reports it. isValidPath() // rejects it for the parentheses; a relaxed path pattern must not adopt a dead directory. - 'codeman-abcd7777|108|0|||/home/user/gone (deleted)', + 'codeman-abcd7777|108|0||||/home/user/gone (deleted)', // Last row, path ending in a space: the output must not be trimmed. - 'codeman-ffff6666|107|0|||/home/user/trailing ', + 'codeman-ffff6666|107|0||||/home/user/trailing ', ].join('\n'); } return ''; @@ -1237,12 +1237,70 @@ describe('TmuxManager (unit)', () => { } }); + // tmux 3.8 prints a blank `#{pane_pid}` for a dead pane. Reading that as "no such + // session" dropped the record of a session whose agent had exited, while its tmux + // session stayed on the socket where nothing would ever find it again. + it('keeps a tracked session whose only pane is dead and has no pid', async () => { + mockedExecSync.mockImplementation((cmd: string) => { + if (typeof cmd === 'string' && cmd.includes(' list-panes ')) { + return ['codeman-dead1111||1|0||1795091616|', 'codeman-abcd2222|202|0||||/srv'].join('\n'); + } + return ''; + }); + const NonTestTmuxManager = await importWithTmuxCommandsEnabled(); + const nonTestManager = new NonTestTmuxManager(); + for (const [sessionId, muxName, pid] of [ + ['dead1111', 'codeman-dead1111', 101], + ['abcd2222', 'codeman-abcd2222', 102], + ] as const) { + nonTestManager.registerSession({ + sessionId, + muxName, + pid, + createdAt: Date.now(), + workingDir: '/tmp', + mode: 'claude', + attached: false, + }); + } + + try { + const { alive, dead } = await nonTestManager.reconcileSessions(); + expect(alive.sort()).toEqual(['abcd2222', 'dead1111']); + expect(dead).toEqual([]); + const pids = Object.fromEntries(nonTestManager.getSessions().map((s) => [s.muxName, s.pid])); + // The last pid known stays, as tmux itself reported it for a dead pane before 3.8. + expect(pids).toEqual({ 'codeman-dead1111': 101, 'codeman-abcd2222': 202 }); + expect(nonTestManager.getPaneExit('codeman-dead1111')).toMatchObject({ status: 0 }); + } 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) => { + if (typeof cmd === 'string' && cmd.includes(' list-panes ')) { + return ['codeman-dead3333||1|0||1795091616|', 'codeman-abcd4444|404|0||||/srv'].join('\n'); + } + return ''; + }); + const NonTestTmuxManager = await importWithTmuxCommandsEnabled(); + const nonTestManager = new NonTestTmuxManager(); + try { + const { discovered } = await nonTestManager.reconcileSessions(); + expect(discovered).toEqual(['restored-abcd4444']); + } finally { + nonTestManager.destroy(); + } + }); + it('treats the resolved spelling of the launch directory as no answer too (macOS /private/tmp)', async () => { // On macOS /tmp is a symlink and a pane reports its process cwd resolved. realpathOverrides.set('/tmp', '/private/tmp'); mockedExecSync.mockImplementation((cmd: string) => { if (typeof cmd === 'string' && cmd.includes(' list-panes ')) { - return ['codeman-aaaa1111|101|0|||/private/tmp', 'codeman-bbbb2222|102|0|||/tmp'].join('\n'); + return ['codeman-aaaa1111|101|0||||/private/tmp', 'codeman-bbbb2222|102|0||||/tmp'].join('\n'); } return ''; }); @@ -1337,7 +1395,7 @@ describe('parsePaneRows', () => { it('reads a live pane as not dead, with no status or signal', () => { // Measured against tmux 3.2a: a live pane leaves both numeric fields blank. - const [row] = parsePaneRows('codeman-aaaa|1234|0|||1'); + const [row] = parsePaneRows('codeman-aaaa|1234|0||||1'); expect(row.dead).toBe(false); expect(row.exitStatus).toBeUndefined(); expect(row.exitSignal).toBeUndefined(); @@ -1374,27 +1432,53 @@ describe('parsePaneRows', () => { }); it('reads the pane directory from the last field', () => { - const [row] = parsePaneRows('codeman-aaaa|1234|0|||/home/user/project'); + const [row] = parsePaneRows('codeman-aaaa|1234|0||||/home/user/project'); expect(row.pid).toBe(1234); expect(row.dead).toBe(false); expect(row.currentPath).toBe('/home/user/project'); }); it('keeps a pane directory that contains the separator whole', () => { - const [row] = parsePaneRows('codeman-aaaa|1234|0|||/home/user/a|b'); + const [row] = parsePaneRows('codeman-aaaa|1234|0||||/home/user/a|b'); expect(row.currentPath).toBe('/home/user/a|b'); }); it('leaves the pane directory undefined when tmux reported none', () => { expect(parsePaneRows('codeman-aaaa|1234')[0].currentPath).toBeUndefined(); - expect(parsePaneRows('codeman-aaaa|1234|0|||')[0].currentPath).toBeUndefined(); + expect(parsePaneRows('codeman-aaaa|1234|0||||')[0].currentPath).toBeUndefined(); }); it('returns one row per pane of a split session, in tmux order', () => { - const rows = parsePaneRows('codeman-aaaa|100|0|||\ncodeman-aaaa|200|1|0|'); + const rows = parsePaneRows('codeman-aaaa|100|0||||\ncodeman-aaaa|200|1|0|'); expect(rows.map((row) => row.pid)).toEqual([100, 200]); expect(rows.map((row) => row.sessionName)).toEqual(['codeman-aaaa', 'codeman-aaaa']); }); + + // Measured on tmux 3.8: once a pane's program exits, `#{pane_pid}` prints + // blank. Skipping that row hid every exited agent from the watcher, so a + // clean `/exit` left the session on the board as idle. + it('keeps a dead pane whose pid tmux left blank', () => { + const [row] = parsePaneRows('codeman-aaaa||1|0||1795091616|'); + expect(row).toBeDefined(); + expect(row.pid).toBeUndefined(); + expect(row.dead).toBe(true); + expect(row.exitStatus).toBe(0); + expect(row.deadTime).toBe(1795091616); + 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([]); + expect(parsePaneRows('codeman-aaaa||')).toEqual([]); + }); + + it('reads the exit time, and leaves it undefined while the pane runs', () => { + expect(parsePaneRows('codeman-aaaa|1234|1|0||1795091616|/srv')[0]).toMatchObject({ + deadTime: 1795091616, + currentPath: '/srv', + }); + expect(parsePaneRows('codeman-aaaa|1234|0||||/srv')[0].deadTime).toBeUndefined(); + }); }); describe('derivePaneExits', () => { @@ -1419,7 +1503,7 @@ describe('derivePaneExits', () => { }); it('says nothing about a live pane', () => { - const exits = derivePaneExits(parsePaneRows('codeman-aaaa|1234|0|||'), NOW); + const exits = derivePaneExits(parsePaneRows('codeman-aaaa|1234|0||||'), NOW); expect(exits.has('codeman-aaaa')).toBe(false); }); @@ -1436,11 +1520,16 @@ describe('derivePaneExits', () => { it("answers per session, so one session's split does not silence another", () => { const exits = derivePaneExits( - parsePaneRows('codeman-aaaa|100|1|0|\ncodeman-bbbb|200|1|0|\ncodeman-bbbb|201|0|||'), + parsePaneRows('codeman-aaaa|100|1|0|\ncodeman-bbbb|200|1|0|\ncodeman-bbbb|201|0||||'), NOW ); expect([...exits.keys()]).toEqual(['codeman-aaaa']); }); + + it('reports a clean exit from a dead pane whose pid tmux left blank', () => { + const exits = derivePaneExits(parsePaneRows('codeman-aaaa||1|0||1795091616|'), NOW); + expect(exits.get('codeman-aaaa')).toEqual({ deadTime: 1795091616, exit: { status: 0, at: NOW } }); + }); }); describe('TmuxManager pane-exit bookkeeping', () => { @@ -1470,7 +1559,7 @@ describe('TmuxManager pane-exit bookkeeping', () => { it('forgets the exit once the same session reports a live pane', () => { const manager = new TmuxManager(); manager.applyPaneExits(derivePaneExits(parsePaneRows('codeman-aaaa|100|1|0|'), NOW)); - manager.applyPaneExits(derivePaneExits(parsePaneRows('codeman-aaaa|101|0|||'), NOW + 2000)); + manager.applyPaneExits(derivePaneExits(parsePaneRows('codeman-aaaa|101|0||||'), NOW + 2000)); expect(manager.getPaneExit('codeman-aaaa')).toBeUndefined(); }); @@ -1530,11 +1619,30 @@ describe('TmuxManager pane-exit bookkeeping', () => { it('drops the count once a read sees the pane alive again', () => { const manager = new TmuxManager(); manager.applyPaneExits(derivePaneExits(parsePaneRows('codeman-aaaa|100|1|0|'), NOW)); - manager.applyPaneExits(derivePaneExits(parsePaneRows('codeman-aaaa|101|0|||'), NOW + 2000)); + manager.applyPaneExits(derivePaneExits(parsePaneRows('codeman-aaaa|101|0||||'), NOW + 2000)); expect(manager.getPaneExitReadCount('codeman-aaaa')).toBe(0); manager.applyPaneExits(derivePaneExits(parsePaneRows('codeman-aaaa|101|1|0|'), NOW + 4000)); expect(manager.getPaneExitReadCount('codeman-aaaa')).toBe(1); }); + + // tmux 3.8 blanks a dead pane's pid, so the exit time is what tells one + // exit from the next there. + it('counts repeated reads of one exit when tmux gave no pid', () => { + const manager = new TmuxManager(); + manager.applyPaneExits(derivePaneExits(parsePaneRows('codeman-aaaa||1|0||1795091616|'), NOW)); + manager.applyPaneExits(derivePaneExits(parsePaneRows('codeman-aaaa||1|0||1795091616|'), NOW + 2000)); + expect(manager.getPaneExitReadCount('codeman-aaaa')).toBe(2); + expect(manager.getPaneExit('codeman-aaaa')).toEqual({ status: 0, at: NOW }); + }); + + it('starts a new observation when the exit time changes and tmux gave no pid', () => { + // A hand-run `tmux respawn-pane` whose command exited 0 again between two reads. + const manager = new TmuxManager(); + manager.applyPaneExits(derivePaneExits(parsePaneRows('codeman-aaaa||1|0||1795091616|'), NOW)); + manager.applyPaneExits(derivePaneExits(parsePaneRows('codeman-aaaa||1|0||1795091620|'), NOW + 2000)); + expect(manager.getPaneExitReadCount('codeman-aaaa')).toBe(1); + expect(manager.getPaneExit('codeman-aaaa')).toEqual({ status: 0, at: NOW + 2000 }); + }); }); describe('the pane-exit watcher tick', () => { From df494b21ce97bcce3ded8411cb03ec249e2cc6a9 Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Tue, 24 Nov 2026 13:22:42 +0100 Subject: [PATCH 2/7] fix(tmux): never signal the recorded pid of a dead pane on close killSession() read `#{pane_pid}` and fell back to the recorded pid when tmux printed none, which tmux 3.8 does for every dead pane. That pid belongs to the program that exited; the OS may have reused it, and the kill path walked its process tree and SIGKILLed it. It now reads `#{pane_dead}` with the pid (parsePaneKillRead) and, for a dead pane, only runs kill-session. Survivors of an exited program were already out of reach (reparented, and the group kill only ran for a live leader), so nothing a live pane gets is lost. Strategies 1 and 2 move into killPaneProcessTree() unchanged. Docs: the architecture-invariants paragraph says a kept dead pane is respawned by the restore at the next server start (measured on tmux 3.8; tmux 3.7 and older always did this), and describes the kill rule. CLAUDE.md's paneExit rule gains the no-pid warning. The PaneExitObservation comment no longer claims tmux before 3.4 lacks `#{pane_dead_time}`, which was never measured. Co-Authored-By: Claude Opus 5.5 --- .changeset/dead-pane-blank-pid.md | 2 +- CLAUDE.md | 2 +- docs/architecture-invariants.md | 2 +- src/tmux-manager.ts | 177 +++++++++++++++++++----------- test/tmux-manager.test.ts | 22 ++++ 5 files changed, 135 insertions(+), 70 deletions(-) diff --git a/.changeset/dead-pane-blank-pid.md b/.changeset/dead-pane-blank-pid.md index fdbd974a..44a3755f 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}`. +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. diff --git a/CLAUDE.md b/CLAUDE.md index 9472b727..597b5bb1 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 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 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) **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 6264bf12..d61fe1d2 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. 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 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`. ⚠️ **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 6b232a38..8188f18d 100644 --- a/src/tmux-manager.ts +++ b/src/tmux-manager.ts @@ -337,9 +337,10 @@ export interface PaneRow { * seen again" from "a second command in the same pane that also exited with * the same status", so the `at` stamp can hold across the first and must not * across the second. Either may be absent: tmux 3.8 blanks the pid of a dead - * pane, and a tmux before 3.4 has no exit time. {@link PaneExit} itself stays free of it: the pid on - * the session record is the attach client's, and a second pid there would - * invite exactly the confusion Ark0N/Codeman#446 is about. + * pane, and a tmux that does not know `#{pane_dead_time}` prints it empty. + * {@link PaneExit} itself stays free of both: the pid on the session record is + * the attach client's, and a second pid there would invite exactly the + * confusion Ark0N/Codeman#446 is about. */ export interface PaneExitObservation { /** `#{pane_pid}` of the pane this reading came from, when tmux reported one. */ @@ -407,6 +408,25 @@ export function parsePaneRows(output: string): PaneRow[] { return rows; } +/** 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. */ + 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 + * 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 }; +} + /** * Decide, from every pane tmux listed, which tmux sessions have an exited agent. * Exported for unit testing. Returns one entry per session with a known answer; @@ -2886,24 +2906,26 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { } /** - * {@link getPanePid} without blocking the event loop, for the kill path: a close - * must not stall every other session's I/O while tmux answers. + * The kill path's pane read: the pane pid and whether the pane is dead, in one + * `display-message`, without blocking the event loop (a close must not stall + * every other session's I/O while tmux answers). A failed read answers + * `{ dead: false, pid: null }`, so the caller falls back to the recorded pid + * exactly as before. */ - private async getPanePidAsync(muxName: string): Promise { - if (IS_TEST_MODE) return 99999; + private async readPaneForKill(muxName: string): Promise { + if (IS_TEST_MODE) return { dead: false, pid: 99999 }; if (!isValidMuxName(muxName)) { - console.error('[TmuxManager] Invalid session name in getPanePidAsync:', muxName); - return null; + console.error('[TmuxManager] Invalid session name in readPaneForKill:', muxName); + return { dead: false, pid: null }; } try { - const { stdout } = await execAsync(`${this.tmux()} display-message -t "${muxName}" -p '#{pane_pid}'`, { - encoding: 'utf-8', - timeout: EXEC_TIMEOUT_MS, - }); - const pid = parseInt(stdout.trim(), 10); - return Number.isNaN(pid) ? null : pid; + const { stdout } = await execAsync( + `${this.tmux()} display-message -t "${muxName}" -p '#{pane_dead}${PANE_LIST_SEP}#{pane_pid}'`, + { encoding: 'utf-8', timeout: EXEC_TIMEOUT_MS } + ); + return parsePaneKillRead(stdout); } catch { - return null; + return { dead: false, pid: null }; } } @@ -3244,6 +3266,62 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { return stillAlive.length === 0; } + /** + * Strategies 1 and 2 of {@link killSession}: SIGTERM then SIGKILL the pane + * process's killable descendants, then its process group. Every pid it + * targets is appended to `allPids` for the final verify. Only ever called + * with the pid of a LIVE pane. + */ + private async killPaneProcessTree(mode: SessionMode, panePid: number, allPids: number[]): Promise { + allPids.push(panePid); + + // Strategy 1: Kill all child processes recursively (but never a shared daemon the + // pane's CLI started for every session of that CLI: see killableDescendants) + let childPids = await this.killableDescendants(mode, panePid, await this.getChildPidsFresh(panePid)); + if (childPids.length > 0) { + console.log(`[TmuxManager] Found ${childPids.length} child processes to kill`); + allPids.push(...childPids); + + for (const childPid of [...childPids].reverse()) { + if (this.isProcessAlive(childPid)) { + try { + process.kill(childPid, 'SIGTERM'); + } catch { + // Process may already be dead + } + } + } + + // Most children are gone within a few ms; the re-scan below still runs, to + // catch anything spawned since the first one. + await waitForProcessesExit(childPids, { timeoutMs: TMUX_KILL_WAIT_MS }); + + childPids = await this.killableDescendants(mode, panePid, await this.getChildPidsFresh(panePid)); + for (const childPid of childPids) { + if (this.isProcessAlive(childPid)) { + try { + process.kill(childPid, 'SIGKILL'); + } catch { + // Process already terminated + } + } + } + } + + // Strategy 2: Kill the entire process group + if (this.isProcessAlive(panePid)) { + try { + process.kill(-panePid, 'SIGTERM'); + await waitForProcessesExit([panePid], { timeoutMs: GRACEFUL_SHUTDOWN_WAIT_MS }); + if (this.isProcessAlive(panePid)) { + process.kill(-panePid, 'SIGKILL'); + } + } catch { + // Process group may not exist or already terminated + } + } + } + /** * Kill a tmux session and all its child processes. * Uses a 4-strategy approach (children → process group → tmux kill → SIGKILL). @@ -3364,58 +3442,23 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { return true; } - // Get current PID (may have changed) - const currentPid = (await this.getPanePidAsync(session.muxName)) || session.pid; + // Get current PID (may have changed). A dead pane has no process left to + // signal, and the pid on the record is the one that exited, which the OS may + // 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. + const pane = await this.readPaneForKill(session.muxName); + const currentPid = pane.dead ? null : (pane.pid ?? session.pid); - console.log(`[TmuxManager] Killing session ${session.muxName} (PID ${currentPid})`); + console.log( + currentPid === null + ? `[TmuxManager] Killing session ${session.muxName} (pane dead, PID ${session.pid} not signalled)` + : `[TmuxManager] Killing session ${session.muxName} (PID ${currentPid})` + ); - const allPids: number[] = [currentPid]; - - // Strategy 1: Kill all child processes recursively (but never a shared daemon the - // pane's CLI started for every session of that CLI: see killableDescendants) - let childPids = await this.killableDescendants(session.mode, currentPid, await this.getChildPidsFresh(currentPid)); - if (childPids.length > 0) { - console.log(`[TmuxManager] Found ${childPids.length} child processes to kill`); - allPids.push(...childPids); - - for (const childPid of [...childPids].reverse()) { - if (this.isProcessAlive(childPid)) { - try { - process.kill(childPid, 'SIGTERM'); - } catch { - // Process may already be dead - } - } - } - - // Most children are gone within a few ms; the re-scan below still runs, to - // catch anything spawned since the first one. - await waitForProcessesExit(childPids, { timeoutMs: TMUX_KILL_WAIT_MS }); - - childPids = await this.killableDescendants(session.mode, currentPid, await this.getChildPidsFresh(currentPid)); - for (const childPid of childPids) { - if (this.isProcessAlive(childPid)) { - try { - process.kill(childPid, 'SIGKILL'); - } catch { - // Process already terminated - } - } - } - } - - // Strategy 2: Kill the entire process group - if (this.isProcessAlive(currentPid)) { - try { - process.kill(-currentPid, 'SIGTERM'); - await waitForProcessesExit([currentPid], { timeoutMs: GRACEFUL_SHUTDOWN_WAIT_MS }); - if (this.isProcessAlive(currentPid)) { - process.kill(-currentPid, 'SIGKILL'); - } - } catch { - // Process group may not exist or already terminated - } - } + const allPids: number[] = []; + if (currentPid !== null) await this.killPaneProcessTree(session.mode, currentPid, allPids); // Strategy 3: Kill tmux session by name (guard the name before it reaches the shell). // Async: tmux takes tens of ms to tear a session down, and execSync held the @@ -3457,7 +3500,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { } // Strategy 4: Direct kill by PID as final fallback - if (this.isProcessAlive(currentPid)) { + if (currentPid !== null && this.isProcessAlive(currentPid)) { try { process.kill(currentPid, 'SIGKILL'); } catch { diff --git a/test/tmux-manager.test.ts b/test/tmux-manager.test.ts index 8d0face7..9832b83e 100644 --- a/test/tmux-manager.test.ts +++ b/test/tmux-manager.test.ts @@ -16,6 +16,7 @@ import { buildRemoteLaunchCommand, formatPaneSnapshot, parsePaneRows, + parsePaneKillRead, derivePaneExits, hasObservablePaneSession, endedAdoptedAttaches, @@ -1481,6 +1482,27 @@ describe('parsePaneRows', () => { }); }); +describe('parsePaneKillRead', () => { + it('reads a live pane as its pid', () => { + 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 }); + }); + + 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('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 }); + }); +}); + describe('derivePaneExits', () => { const NOW = 1_700_000_000_000; From 67aa28ac4f571e9bdd342f198a912e819966cbfa Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Tue, 24 Nov 2026 15:41:39 +0100 Subject: [PATCH 3/7] test(tmux): close a dead-pane session end to end without signalling its pid The kill rule was pinned only through parsePaneKillRead(). Drive killSession() with tmux commands enabled and exec answering like tmux 3.8 (a dead pane, pid blank), and assert nothing signals the recorded pid while kill-session still runs. Against bee4948e it fails: pid 4242 is signalled 201 times. Group the three no-pid tests in their own describe instead of the launch-cwd one. Co-Authored-By: Claude Opus 5.5 --- test/tmux-manager.test.ts | 85 +++++++++++++++++++++++++++++---------- 1 file changed, 64 insertions(+), 21 deletions(-) diff --git a/test/tmux-manager.test.ts b/test/tmux-manager.test.ts index 9832b83e..35dace11 100644 --- a/test/tmux-manager.test.ts +++ b/test/tmux-manager.test.ts @@ -1238,6 +1238,35 @@ describe('TmuxManager (unit)', () => { } }); + it('treats the resolved spelling of the launch directory as no answer too (macOS /private/tmp)', async () => { + // On macOS /tmp is a symlink and a pane reports its process cwd resolved. + realpathOverrides.set('/tmp', '/private/tmp'); + mockedExecSync.mockImplementation((cmd: string) => { + if (typeof cmd === 'string' && cmd.includes(' list-panes ')) { + return ['codeman-aaaa1111|101|0||||/private/tmp', 'codeman-bbbb2222|102|0||||/tmp'].join('\n'); + } + return ''; + }); + try { + const NonTestTmuxManager = await importWithTmuxCommandsEnabled(); + const nonTestManager = new NonTestTmuxManager(); + try { + await nonTestManager.reconcileSessions(); + const dirs = Object.fromEntries(nonTestManager.getSessions().map((s) => [s.muxName, s.workingDir])); + expect(dirs).toEqual({ + 'codeman-aaaa1111': process.cwd(), + 'codeman-bbbb2222': process.cwd(), + }); + } finally { + nonTestManager.destroy(); + } + } finally { + realpathOverrides.clear(); + } + }); + }); + + describe('a dead pane tmux printed no pid for (tmux 3.8)', () => { // tmux 3.8 prints a blank `#{pane_pid}` for a dead pane. Reading that as "no such // session" dropped the record of a session whose agent had exited, while its tmux // session stayed on the socket where nothing would ever find it again. @@ -1296,30 +1325,44 @@ describe('TmuxManager (unit)', () => { } }); - it('treats the resolved spelling of the launch directory as no answer too (macOS /private/tmp)', async () => { - // On macOS /tmp is a symlink and a pane reports its process cwd resolved. - realpathOverrides.set('/tmp', '/private/tmp'); - mockedExecSync.mockImplementation((cmd: string) => { - if (typeof cmd === 'string' && cmd.includes(' list-panes ')) { - return ['codeman-aaaa1111|101|0||||/private/tmp', 'codeman-bbbb2222|102|0||||/tmp'].join('\n'); - } - return ''; + // The recorded pid of a dead pane belongs to the program that exited, and the OS + // may have handed it to an unrelated process since: closing must not signal it. + it('closes a session whose pane is dead without signalling its recorded pid', 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. 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') : ''; + 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: 'dead5555', + muxName: 'codeman-dead5555', + pid: 4242, + createdAt: Date.now(), + workingDir: '/tmp', + mode: 'claude', + attached: false, }); + try { - const NonTestTmuxManager = await importWithTmuxCommandsEnabled(); - const nonTestManager = new NonTestTmuxManager(); - try { - await nonTestManager.reconcileSessions(); - const dirs = Object.fromEntries(nonTestManager.getSessions().map((s) => [s.muxName, s.workingDir])); - expect(dirs).toEqual({ - 'codeman-aaaa1111': process.cwd(), - 'codeman-bbbb2222': process.cwd(), - }); - } finally { - nonTestManager.destroy(); - } + 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); + expect(commands.some((cmd) => cmd.includes('kill-session -t "codeman-dead5555"'))).toBe(true); + expect(nonTestManager.getSession('dead5555')).toBeUndefined(); } finally { - realpathOverrides.clear(); + kill.mockRestore(); + mockedExec.mockImplementation(defaultExec!); + nonTestManager.destroy(); } }); }); From d7c141e25f8eac3e9c12aed2e91af67e42368165 Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Tue, 24 Nov 2026 17:10:37 +0100 Subject: [PATCH 4/7] docs(tmux): note second-granular dead time and orphaned-session cleanup Review follow-ups on #840: `#{pane_dead_time}` is stamped in whole seconds, so two same-status exits in one second read as one; and the changeset tells users how to remove a dead codeman-* session orphaned before this fix. Co-Authored-By: Claude Opus 5.5 --- .changeset/dead-pane-blank-pid.md | 2 +- src/tmux-manager.ts | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/.changeset/dead-pane-blank-pid.md b/.changeset/dead-pane-blank-pid.md index 44a3755f..f38c2d41 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. +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-`. diff --git a/src/tmux-manager.ts b/src/tmux-manager.ts index 8188f18d..1cf2af1b 100644 --- a/src/tmux-manager.ts +++ b/src/tmux-manager.ts @@ -286,7 +286,8 @@ const PANE_LIST_SEP = '|'; * `#{pane_dead_time}` is what tells one exit from the next. tmux 3.8 prints a * blank `#{pane_pid}` once a pane's program has exited, so the pid cannot do it * there, and the time is stamped once per exit, so a respawned pane that exits - * again reads as a new exit even with the same status. + * again reads as a new exit even with the same status. The stamp is in whole + * seconds, so two exits with the same status in the same second read as one. * * `#{pane_current_path}` comes last on purpose: a directory name may contain the * separator, and only the final field can absorb it without ambiguity. @@ -3965,7 +3966,9 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { * changed status, a changed signal, a different pane pid or a different exit * time all start a new observation — the pid and the time are what catch a * second command in the same pane that happened to exit the same way (the - * time alone on tmux 3.8, which blanks a dead pane's pid). + * time alone on tmux 3.8, which blanks a dead pane's pid). `#{pane_dead_time}` + * is stamped to the second, so two exits with the same status in the same + * second read as one there. * * The same rule decides the read count: a repeat of the stored exit adds one, * and anything that starts a new observation starts the count again at 1. From ccf502b7a806744088a2a8bbe09139cc95ac1d56 Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Wed, 25 Nov 2026 12:59:40 +0100 Subject: [PATCH 5/7] fix(tmux): keep a closing pane, and trust a dead flag only with an exit sign Review follow-up on the tmux 3.8 dead-pane fix. - parsePaneRows() skipped a row with a blank pid and pane_dead 0. tmux blanks the pid when the pty closes, and pane_dead turns 1 only once the exit status is collected (seconds for some exits on tmux 3.4), so a restart in that window dropped the session. Only a row with neither a pid nor a dead flag is skipped now. - Before tmux 3.7 pane_dead means only that the pty is closed. The kill read now also reads #{pane_dead_time}, and counts a pane as dead only with a blank pid or a set exit time, so a program that closed its tty and ignores SIGHUP is still killed on tmux 3.3a to 3.6. - Tests pin the last two pane format fields and add a live-pane counterpart to the dead-pane kill test. - Changeset notes that finished sessions piled up on 3.8 are relaunched once at the first start after the update. Co-Authored-By: Claude Opus 5.5 --- .changeset/dead-pane-blank-pid.md | 2 +- CLAUDE.md | 2 +- docs/architecture-invariants.md | 2 +- src/tmux-manager.ts | 54 +++++++++++++------- test/tmux-manager.test.ts | 85 ++++++++++++++++++++++++++++--- 5 files changed, 117 insertions(+), 28 deletions(-) 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', () => { From 891f3a19e9bbf007a259c6eae39e3af9517e59e1 Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Wed, 25 Nov 2026 14:19:18 +0100 Subject: [PATCH 6/7] test(tmux): let the live pane die on its signal, so Linux CI never reads /proc The live-pane close test mocked process.kill to always succeed, so the pane never exited and the kill path's wait polled isProcessRunning(). On Linux that reads /proc//stat, which this file mocks to return undefined, and the test threw "Cannot read properties of undefined (reading 'lastIndexOf')". macOS skips that read, so it passed locally. The mock now models a pane that exits on its first real signal, after which kill(pid, 0) throws ESRCH. Reproduced the CI error locally by forcing the Linux branch; it passes with this change. Co-Authored-By: Claude Opus 5.5 --- test/tmux-manager.test.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/test/tmux-manager.test.ts b/test/tmux-manager.test.ts index 40582f8d..d4c43990 100644 --- a/test/tmux-manager.test.ts +++ b/test/tmux-manager.test.ts @@ -1386,7 +1386,19 @@ describe('TmuxManager (unit)', () => { 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); + // The pane's process exits on its first real signal, as a live CLI does. + // Afterwards the liveness probe (`kill(pid, 0)`) throws, so the kill path + // stops waiting before it reads /proc, which this file mocks (Linux CI). + let paneAlive = true; + const kill = vi.spyOn(process, 'kill').mockImplementation(((pid: number, signal?: string | number) => { + if (Math.abs(pid) !== 4343) return true; + if (signal === 0) { + if (paneAlive) return true; + throw Object.assign(new Error('kill ESRCH'), { code: 'ESRCH' }); + } + paneAlive = false; + return true; + }) as typeof process.kill); const NonTestTmuxManager = await importWithTmuxCommandsEnabled(); const nonTestManager = new NonTestTmuxManager(); nonTestManager.registerSession({ From 9309500d409cb7caa79769f4d6fe7bf9824b7531 Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Thu, 26 Nov 2026 10:20:57 +0100 Subject: [PATCH 7/7] 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 });