Merge #840: fix(tmux): see an exited agent on tmux 3.8, which blanks a dead pane's pid

This commit is contained in:
Codeman maintainer committed 2026-11-27 06:08:26 +01:00
commit a4201b34a8
7 files changed
+595 -142

No files matched your search

+5
View File
@@ -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}`. 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-<id>`.
+1 -1
View File
@@ -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 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)
+1 -1
View File
@@ -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-<fragment>` 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-manLine truncated
**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-<fragment>` 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 seLine truncated
⚠️ **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 `<name> session, agent exited ...` (the name passed through); `test/i18n-exit-run-help.test.ts` covers every `paneExitLabel()` form.
+198 -96
View File
@@ -277,19 +277,25 @@ 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. 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.
*/
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 +314,41 @@ 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 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. */
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
* the session record is the attach client's, and a second pid there would
* invite exactly the confusion Ark0N/Codeman#446 is about.
* 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 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. */
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 +379,13 @@ 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 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. 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.
*/
@@ -374,22 +396,56 @@ 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 === undefined)) 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;
}
/** What {@link TmuxManager.killSession} reads about a pane before it signals anything. */
export interface PaneKillRead {
/**
* 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}|#{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 = '', 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 };
}
/**
* 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;
@@ -420,7 +476,8 @@ export function derivePaneExits(rows: PaneRow[], now: number): Map<string, PaneE
if (panesPerSession.get(row.sessionName) !== 1) continue;
if (row.dead !== true) continue;
exits.set(row.sessionName, {
panePid: row.pid,
...(row.pid !== undefined ? { panePid: row.pid } : {}),
...(row.deadTime !== undefined ? { deadTime: row.deadTime } : {}),
exit: {
...(row.exitStatus !== undefined ? { status: row.exitStatus } : {}),
...(row.exitSignal !== undefined ? { signal: row.exitSignal } : {}),
@@ -2868,24 +2925,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<number | null> {
if (IS_TEST_MODE) return 99999;
private async readPaneForKill(muxName: string): Promise<PaneKillRead> {
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}${PANE_LIST_SEP}#{pane_dead_time}'`,
{ encoding: 'utf-8', timeout: EXEC_TIMEOUT_MS }
);
return parsePaneKillRead(stdout);
} catch {
return null;
return { dead: false, pid: null };
}
}
@@ -3241,6 +3300,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<void> {
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 {
this.signalProcess(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 {
this.signalProcess(childPid, 'SIGKILL');
} catch {
// Process already terminated
}
}
}
}
// Strategy 2: Kill the entire process group
if (this.isProcessAlive(panePid)) {
try {
this.signalProcess(-panePid, 'SIGTERM');
await waitForProcessesExit([panePid], { timeoutMs: GRACEFUL_SHUTDOWN_WAIT_MS });
if (this.isProcessAlive(panePid)) {
this.signalProcess(-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).
@@ -3361,63 +3476,34 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
return true;
}
// Get current PID (may have changed)
const currentPid = (await this.getPanePidAsync(session.muxName)) || session.pid;
// An empty pane has no process: tmux says 0, and so does the record once a server
// start has read it. Nothing is signalled then, and only tmux is asked to close it.
const hasProcess = isSignalablePid(currentPid);
// 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. A blank pid with `#{pane_dead}` still 0
// (tmux 3.8, pty closed, exit not collected yet) keeps the fallback: tmux
// 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 currentPid = candidatePid !== null && isSignalablePid(candidatePid) ? candidatePid : null;
console.log(
`[TmuxManager] Killing session ${session.muxName} (${hasProcess ? `PID ${currentPid}` : `no process, pane pid ${currentPid}`})`
currentPid !== null
? `[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 usable pid, recorded ${session.pid}, nothing signalled)`
);
const allPids: number[] = hasProcess ? [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 {
this.signalProcess(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 {
this.signalProcess(childPid, 'SIGKILL');
} catch {
// Process already terminated
}
}
}
}
// Strategy 2: Kill the entire process group
if (hasProcess && this.isProcessAlive(currentPid)) {
try {
this.signalProcess(-currentPid, 'SIGTERM');
await waitForProcessesExit([currentPid], { timeoutMs: GRACEFUL_SHUTDOWN_WAIT_MS });
if (this.isProcessAlive(currentPid)) {
this.signalProcess(-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
@@ -3459,7 +3545,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
}
// Strategy 4: Direct kill by PID as final fallback
if (hasProcess && this.isProcessAlive(currentPid)) {
if (currentPid !== null && this.isProcessAlive(currentPid)) {
try {
this.signalProcess(currentPid, 'SIGKILL');
} catch {
@@ -3522,7 +3608,10 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
// socket a session's location is a constant, so there is no per-session
// socket tag to reconcile and no cross-socket ambiguity that could mark a
// live session dead (the root cause of vanished/duplicate tabs).
let active: Map<string, number>;
// Every tmux session on the socket, with its pane pid when tmux printed one.
// 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<string, number | undefined>;
const paneDirs = new Map<string, string>();
try {
const output = execSync(`${this.tmux()} list-panes -a -F '${PANE_LIST_FORMAT}' 2>/dev/null || true`, {
@@ -3532,7 +3621,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.
@@ -3567,10 +3659,13 @@ 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 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 {
dead.push(sessionId);
this.sessions.delete(sessionId);
@@ -3590,6 +3685,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
@@ -3910,9 +4008,12 @@ 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). `#{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.
@@ -3926,6 +4027,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 });
+43 -1
View File
@@ -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<typeof process.kill>;
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`;
+24 -24
View File
@@ -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<PaneRow[]> }, '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('');
+323 -19
View File
@@ -16,6 +16,7 @@ import {
buildRemoteLaunchCommand,
formatPaneSnapshot,
parsePaneRows,
parsePaneKillRead,
derivePaneExits,
hasObservablePaneSession,
endedAdoptedAttaches,
@@ -1182,21 +1183,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 '';
@@ -1231,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();
}
@@ -1242,7 +1245,7 @@ describe('TmuxManager (unit)', () => {
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 '';
});
@@ -1264,6 +1267,206 @@ describe('TmuxManager (unit)', () => {
}
});
});
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.
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();
}
});
// 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) => {
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();
}
});
// 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||1795091616\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 {
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));
// 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 {
kill.mockRestore();
mockedExec.mockImplementation(defaultExec!);
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);
// 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({
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));
// 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 {
kill.mockRestore();
mockedExec.mockImplementation(defaultExec!);
nonTestManager.destroy();
}
});
});
});
// ============================================================================
@@ -1337,7 +1540,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 +1577,104 @@ 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();
});
// 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();
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', () => {
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('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||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, 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 });
});
// 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 });
});
});
describe('derivePaneExits', () => {
@@ -1419,7 +1699,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 +1716,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 +1755,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 +1815,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', () => {