From bee4948e1a2a207a817787aa6f9fc35993b68ae8 Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Thu, 19 Nov 2026 15:11:30 +0100 Subject: [PATCH] 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', () => {