From df494b21ce97bcce3ded8411cb03ec249e2cc6a9 Mon Sep 17 00:00:00 2001 From: Kamil Kalisz Date: Tue, 24 Nov 2026 13:22:42 +0100 Subject: [PATCH] fix(tmux): never signal the recorded pid of a dead pane on close killSession() read `#{pane_pid}` and fell back to the recorded pid when tmux printed none, which tmux 3.8 does for every dead pane. That pid belongs to the program that exited; the OS may have reused it, and the kill path walked its process tree and SIGKILLed it. It now reads `#{pane_dead}` with the pid (parsePaneKillRead) and, for a dead pane, only runs kill-session. Survivors of an exited program were already out of reach (reparented, and the group kill only ran for a live leader), so nothing a live pane gets is lost. Strategies 1 and 2 move into killPaneProcessTree() unchanged. Docs: the architecture-invariants paragraph says a kept dead pane is respawned by the restore at the next server start (measured on tmux 3.8; tmux 3.7 and older always did this), and describes the kill rule. CLAUDE.md's paneExit rule gains the no-pid warning. The PaneExitObservation comment no longer claims tmux before 3.4 lacks `#{pane_dead_time}`, which was never measured. Co-Authored-By: Claude Opus 5.5 --- .changeset/dead-pane-blank-pid.md | 2 +- CLAUDE.md | 2 +- docs/architecture-invariants.md | 2 +- src/tmux-manager.ts | 177 +++++++++++++++++++----------- test/tmux-manager.test.ts | 22 ++++ 5 files changed, 135 insertions(+), 70 deletions(-) diff --git a/.changeset/dead-pane-blank-pid.md b/.changeset/dead-pane-blank-pid.md index fdbd974a..44a3755f 100644 --- a/.changeset/dead-pane-blank-pid.md +++ b/.changeset/dead-pane-blank-pid.md @@ -2,4 +2,4 @@ 'aicodeman': patch --- -On tmux 3.8, a session whose agent exited (`/exit`) is now seen as exited and closed like on older tmux, instead of staying on the board as idle. tmux 3.8 prints a blank pane pid for a dead pane, and the pane watcher threw that row away, so the clean-exit sweep never ran and a restart of Codeman dropped the session's record while its tmux session stayed on the socket. A dead pane's exit is now told apart from the next one by `#{pane_dead_time}`. +On tmux 3.8, a session whose agent exited (`/exit`) is now seen as exited and closed like on older tmux, instead of staying on the board as idle. tmux 3.8 prints a blank pane pid for a dead pane, and the pane watcher threw that row away, so the clean-exit sweep never ran and a restart of Codeman dropped the session's record while its tmux session stayed on the socket. A dead pane's exit is now told apart from the next one by `#{pane_dead_time}`. Closing a session whose pane is dead no longer signals the pid recorded for it, which belonged to the program that exited and may have been reused by another process; only the tmux session is killed. diff --git a/CLAUDE.md b/CLAUDE.md index 9472b727..597b5bb1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -152,7 +152,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph ⚠️ **A quiet pane is not always a pane that wants you.** A CLI can declare an optional `capabilities.workDetect.watchingLine` (a monitor, background shell or cloud hand-off it is still running); the idle probe reads it into `Session.watching` and `notePrompt()` opens that idle item ALREADY acknowledged, so no surface alerts. Only `idle` is eligible, and the label is pane-derived and prompt-injectable, so a pattern must anchor on chrome only that CLI draws. → [architecture-invariants#the-watching-signal-a-quiet-pane-that-is-not-waiting-for-you](docs/architecture-invariants.md#the-watching-signal-a-quiet-pane-that-is-not-waiting-for-you). Tests: `test/session-watching.test.ts`, `test/watching-no-alert.test.ts`. -**An exited agent in a live pane** (`paneExit`, #446): panes use `remain-on-exit on`, so `/exit` leaves a pane, session and pid that look alive; `TmuxManager.startPaneExitWatcher()` publishes `SessionState.paneExit` via `session:updated`. ⚠️ Never set `status: 'error'` or null the `pid` for it; the field is TRI-STATE (absent = UNKNOWN, never alive, scoped by `Session.paneExitApplies`); an absent `#{pane_dead_status}` is not 0; a path that starts a command in a pane must clear the record AND persist. A clean exit is CLOSED via `cleanupSession()` (`pane-exit-sweep.ts`): only an explicit numeric status 0 with no signal, confirmed by 2 reads, with no start/attach in flight (`paneLifecycleInFlight`) and not within 10 s of one (a startup error keeps its row); a crashed agent keeps its row. → [architecture-invariants#an-exited-agent-in-a-live-pane-paneexit](docs/architecture-invariants.md#an-exited-agent-in-a-live-pane-paneexit) +**An exited agent in a live pane** (`paneExit`, #446): panes use `remain-on-exit on`, so `/exit` leaves a pane, session and pid that look alive; `TmuxManager.startPaneExitWatcher()` publishes `SessionState.paneExit` via `session:updated`. ⚠️ Never set `status: 'error'` or null the `pid` for it; the field is TRI-STATE (absent = UNKNOWN, never alive, scoped by `Session.paneExitApplies`); an absent `#{pane_dead_status}` is not 0; a dead pane may have NO pid (tmux 3.8 prints `#{pane_pid}` blank), so never skip a dead row for it, and never signal the recorded pid of a dead pane in `killSession()`; a path that starts a command in a pane must clear the record AND persist. A clean exit is CLOSED via `cleanupSession()` (`pane-exit-sweep.ts`): only an explicit numeric status 0 with no signal, confirmed by 2 reads, with no start/attach in flight (`paneLifecycleInFlight`) and not within 10 s of one (a startup error keeps its row); a crashed agent keeps its row. → [architecture-invariants#an-exited-agent-in-a-live-pane-paneexit](docs/architecture-invariants.md#an-exited-agent-in-a-live-pane-paneexit) **Dead-pane respawn resume pin** (`_buildRespawnPaneOptionsWithResumePin()`, session.ts): recovering a dead pane, like a custom-model `restartCli()`, must pin the conversation or claude refuses the reused `--session-id`. The pin takes the first transcript-backed candidate (chain tail, launch seed, own id), never `_claudeSessionId`, adds nothing when none is backed, and is never applied to remote or docker sessions. → [architecture-invariants#dead-pane-respawn-the-resume-pin](docs/architecture-invariants.md#dead-pane-respawn-the-resume-pin) diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 6264bf12..d61fe1d2 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -297,7 +297,7 @@ Further detail, closing: ⚠️ **Closing has the mirror-image race and one owne ### An exited agent in a live pane (`paneExit`) -**Codeman creates every pane with `remain-on-exit on`, so a session whose agent exited still looks alive.** `/exit` ends the CLI, tmux keeps the pane and the tmux session, and the `tmux attach-session` process Codeman records as `Session.pid` runs on, so no PTY exit handler fires and the record keeps its pid and `status: 'idle'` (Ark0N/Codeman#446). `SessionState.paneExit` (`{status?, signal?, at}`) is the fact tmux already knows, published through `toState()` so it rides `session:updated` and lands in `state.json` on the same persist — there is no SSE event for it. One batched `tmux list-panes -a` per tick fills it, from `TmuxManager.startPaneExitWatcher()`, which has its OWN always-on interval: the stats collector cannot carry it, because the browser arms and disarms that one with the Monitor panel (`panels-ui.js`) and boot skips it entirely when no session was recovered. ⚠️ **The field is TRI-STATE and its third state is absence**, meaning UNKNOWN, which renders as nothing and must NEVER read as alive; it covers a running pane, a session the read did not list, a failed probe, and every session shape a dead local pane does not describe. `Session.paneExitApplies` is the single place that scoping lives, and it fails closed for four shapes: a direct-PTY session (no pane), a remote SSH session (the local pane is the ssh client, whose death is a transport drop OR an exit — the whole of #355), a docker case (the local pane is a `docker exec` into the container's own tmux), and a session rebuilt from the socket (`MuxSession.discovered`: its synthetic `restored-` id matches no `state.json` entry, so a remote session rediscovered after `mux-sessions.json` was lost would arrive looking local). ⚠️ **Never set `status: 'error'`** for an exited pane — that value is the PTY-exit breaker's and the browser answers it with a "restart it?" confirm — and **never null the `pid`**, which is what makes `selectSession()` re-attach and launch a fresh CLI. Local panes keep `remain-on-exit on`; flipping them to `failed` ends the tmux session, nulls the pid and reintroduces the auto-revive #355 removed. ⚠️ **An absent `#{pane_dead_status}` is not 0**: measured on tmux 3.2a a SIGKILLed pane reports neither a status nor a signal (`#{pane_dead_signal}` did not exist before tmux 3.4), so folding it into 0 would turn an unexplained death into a clean exit. ⚠️ **A dead pane may have no pid**: measured on tmux 3.8, `#{pane_pid}` prints blank once the pane's program exits, so `parsePaneRows()` keeps a row with no pid when `#{pane_dead}` is 1 (a LIVE row with no pid is still a bad read and is skipped). `#{pane_dead_time}` then tells one exit from the next, next to the pid, so two reads of one exit still count as two and a hand-run `respawn-pane` that exits 0 again starts a new observation. `reconcileSessions()` keeps such a tracked session alive with its last known pid, and does not rediscover an untracked one, since a made-up pid would reach `killSession()`'s process-tree walk. A session answers only when the read listed EXACTLY ONE pane for it, since Codeman never splits a pane and a session the user split by hand has none that speaks for the agent. The three synchronous `isPaneDead()` callers (the `/wait` route, the TUI, the attach path) keep their own probes — this watcher is never fresh enough for them. ⚠️ **A path that starts a command in a pane must clear the record AND persist**, since the watcher's next tick sees the field already cleared and writes nothing. ⚠️ **The always-on timer gates the READ, never the tick.** `hasObservablePaneSession()` (`tmux-manager.ts`) skips the tmux exec while every session on the manager is one of the shapes `paneExitApplies` forces to UNKNOWN, so an instance running only remote or Docker work keeps ticking and costs nothing; the two predicates are two copies of one rule, and `test/session-pane-exit.test.ts` pins them against each other for the four session shapes that exist today — a FIFTH condition added to one and not the other still fails nothing, so change them together. Skipping retracts nothing, for the same reason a failed read does not. ⚠️ **The muted status dot is a specificity fight, and it is fought on three surfaces.** The tab renders `status` as before, and `tab-agent-exited` only quiets the dot, so the rule excludes three states BY HAND: `.tab-alert-action` and `.tab-alert-idle` on the tab, and `.tab-status.error` on the dot itself. Each of those colours means "this needs you" — the two alerts because a human is blocked, `error` because the browser answers it with a "restart it?" confirm — and each must survive the exit. The rich tab rail needs a SECOND copy of the rule, because its own `tab-state-*` dot rules are (0,9,1) against the strip's (0,5,0) — measured, an exited session on a detailed rail kept a full green dot and the working halo beside a badge reading "exited". Its twin matches that specificity exactly and therefore must stay BELOW those rules in source order. mobile.css needs a THIRD copy, with `!important`, because the phone block enlarges a `busy` dot and gives it a green glow that way, and `status` stays `busy` for a pane whose agent died mid-turn — without it a phone renders a grey dot still wearing the green halo. `test/session-pane-exit-ui.test.ts` resolves the real stylesheets in jsdom rather than matching selector text — styles.css for the desktop cases and both files for the phone ones — so the ordering, the hand-written exclusions and a missing phone rule all fail there. Tests: `test/session-pane-exit.test.ts`, `test/tmux-manager.test.ts`, `test/session-pane-exit-ui.test.ts`. +**Codeman creates every pane with `remain-on-exit on`, so a session whose agent exited still looks alive.** `/exit` ends the CLI, tmux keeps the pane and the tmux session, and the `tmux attach-session` process Codeman records as `Session.pid` runs on, so no PTY exit handler fires and the record keeps its pid and `status: 'idle'` (Ark0N/Codeman#446). `SessionState.paneExit` (`{status?, signal?, at}`) is the fact tmux already knows, published through `toState()` so it rides `session:updated` and lands in `state.json` on the same persist — there is no SSE event for it. One batched `tmux list-panes -a` per tick fills it, from `TmuxManager.startPaneExitWatcher()`, which has its OWN always-on interval: the stats collector cannot carry it, because the browser arms and disarms that one with the Monitor panel (`panels-ui.js`) and boot skips it entirely when no session was recovered. ⚠️ **The field is TRI-STATE and its third state is absence**, meaning UNKNOWN, which renders as nothing and must NEVER read as alive; it covers a running pane, a session the read did not list, a failed probe, and every session shape a dead local pane does not describe. `Session.paneExitApplies` is the single place that scoping lives, and it fails closed for four shapes: a direct-PTY session (no pane), a remote SSH session (the local pane is the ssh client, whose death is a transport drop OR an exit — the whole of #355), a docker case (the local pane is a `docker exec` into the container's own tmux), and a session rebuilt from the socket (`MuxSession.discovered`: its synthetic `restored-` id matches no `state.json` entry, so a remote session rediscovered after `mux-sessions.json` was lost would arrive looking local). ⚠️ **Never set `status: 'error'`** for an exited pane — that value is the PTY-exit breaker's and the browser answers it with a "restart it?" confirm — and **never null the `pid`**, which is what makes `selectSession()` re-attach and launch a fresh CLI. Local panes keep `remain-on-exit on`; flipping them to `failed` ends the tmux session, nulls the pid and reintroduces the auto-revive #355 removed. ⚠️ **An absent `#{pane_dead_status}` is not 0**: measured on tmux 3.2a a SIGKILLed pane reports neither a status nor a signal (`#{pane_dead_signal}` did not exist before tmux 3.4), so folding it into 0 would turn an unexplained death into a clean exit. ⚠️ **A dead pane may have no pid**: measured on tmux 3.8, `#{pane_pid}` prints blank once the pane's program exits, so `parsePaneRows()` keeps a row with no pid when `#{pane_dead}` is 1 (a LIVE row with no pid is still a bad read and is skipped). `#{pane_dead_time}` then tells one exit from the next, next to the pid, so two reads of one exit still count as two and a hand-run `respawn-pane` that exits 0 again starts a new observation. `reconcileSessions()` keeps such a tracked session alive with its last known pid, and does not rediscover an untracked one, since a made-up pid would reach `killSession()`'s process-tree walk. ⚠️ Kept alive means restored: at the next server start the restore goes through the dead-pane branch of `Session._setupOrAttachMuxSession()`, which respawns the pane and clears `paneExit` (measured on tmux 3.8, and what tmux 3.7 and older always did, since they still printed the pid). So a row kept as evidence of a crash or a startup error survives a restart only until the CLI is relaunched in it. `killSession()` reads `#{pane_dead}` with the pid and, for a dead pane, signals nothing and walks no tree: the recorded pid belongs to the program that exited and may since have been reused by an unrelated process, so only `kill-session` runs (`parsePaneKillRead()`). A session answers only when the read listed EXACTLY ONE pane for it, since Codeman never splits a pane and a session the user split by hand has none that speaks for the agent. The three synchronous `isPaneDead()` callers (the `/wait` route, the TUI, the attach path) keep their own probes — this watcher is never fresh enough for them. ⚠️ **A path that starts a command in a pane must clear the record AND persist**, since the watcher's next tick sees the field already cleared and writes nothing. ⚠️ **The always-on timer gates the READ, never the tick.** `hasObservablePaneSession()` (`tmux-manager.ts`) skips the tmux exec while every session on the manager is one of the shapes `paneExitApplies` forces to UNKNOWN, so an instance running only remote or Docker work keeps ticking and costs nothing; the two predicates are two copies of one rule, and `test/session-pane-exit.test.ts` pins them against each other for the four session shapes that exist today — a FIFTH condition added to one and not the other still fails nothing, so change them together. Skipping retracts nothing, for the same reason a failed read does not. ⚠️ **The muted status dot is a specificity fight, and it is fought on three surfaces.** The tab renders `status` as before, and `tab-agent-exited` only quiets the dot, so the rule excludes three states BY HAND: `.tab-alert-action` and `.tab-alert-idle` on the tab, and `.tab-status.error` on the dot itself. Each of those colours means "this needs you" — the two alerts because a human is blocked, `error` because the browser answers it with a "restart it?" confirm — and each must survive the exit. The rich tab rail needs a SECOND copy of the rule, because its own `tab-state-*` dot rules are (0,9,1) against the strip's (0,5,0) — measured, an exited session on a detailed rail kept a full green dot and the working halo beside a badge reading "exited". Its twin matches that specificity exactly and therefore must stay BELOW those rules in source order. mobile.css needs a THIRD copy, with `!important`, because the phone block enlarges a `busy` dot and gives it a green glow that way, and `status` stays `busy` for a pane whose agent died mid-turn — without it a phone renders a grey dot still wearing the green halo. `test/session-pane-exit-ui.test.ts` resolves the real stylesheets in jsdom rather than matching selector text — styles.css for the desktop cases and both files for the phone ones — so the ordering, the hand-written exclusions and a missing phone rule all fail there. Tests: `test/session-pane-exit.test.ts`, `test/tmux-manager.test.ts`, `test/session-pane-exit-ui.test.ts`. ⚠️ **The tab's badge is translated (zh-CN), so its updates compare with English, never the DOM.** `applyPaneExitBadge()` remembers the last English badge text (`data-label`) and the tab's accessible name (`data-aria-source`), both also seeded by the full render, and writes only when those change: the translator rewrites both in zh-CN, and a DOM compare (or an unconditional set) would write the English back on every incremental pass for it to translate again. i18n.js has `exited` and patterns for `exited (N)`, `exited (signal N)` and ` session, agent exited ...` (the name passed through); `test/i18n-exit-run-help.test.ts` covers every `paneExitLabel()` form. diff --git a/src/tmux-manager.ts b/src/tmux-manager.ts index 6b232a38..8188f18d 100644 --- a/src/tmux-manager.ts +++ b/src/tmux-manager.ts @@ -337,9 +337,10 @@ export interface PaneRow { * seen again" from "a second command in the same pane that also exited with * the same status", so the `at` stamp can hold across the first and must not * across the second. Either may be absent: tmux 3.8 blanks the pid of a dead - * pane, and a tmux before 3.4 has no exit time. {@link PaneExit} itself stays free of it: the pid on - * the session record is the attach client's, and a second pid there would - * invite exactly the confusion Ark0N/Codeman#446 is about. + * pane, and a tmux that does not know `#{pane_dead_time}` prints it empty. + * {@link PaneExit} itself stays free of both: the pid on the session record is + * the attach client's, and a second pid there would invite exactly the + * confusion Ark0N/Codeman#446 is about. */ export interface PaneExitObservation { /** `#{pane_pid}` of the pane this reading came from, when tmux reported one. */ @@ -407,6 +408,25 @@ export function parsePaneRows(output: string): PaneRow[] { return rows; } +/** What {@link TmuxManager.killSession} reads about a pane before it signals anything. */ +export interface PaneKillRead { + /** `#{pane_dead}` was 1: the pane's program exited, so no process is left to signal. */ + dead: boolean; + /** `#{pane_pid}`, or null when tmux printed none (tmux 3.8 for a dead pane) or the read failed. */ + pid: number | null; +} + +/** + * Parse the kill path's `#{pane_dead}|#{pane_pid}` read. Exported for unit testing. + * Only an explicit `1` is dead; anything else keeps the old behaviour of + * signalling the pid (or the recorded one when tmux printed none). + */ +export function parsePaneKillRead(output: string): PaneKillRead { + const [deadFlag = '', pidField = ''] = output.trim().split(PANE_LIST_SEP); + const pid = parseInt(pidField, 10); + return { dead: deadFlag === '1', pid: Number.isNaN(pid) ? null : pid }; +} + /** * Decide, from every pane tmux listed, which tmux sessions have an exited agent. * Exported for unit testing. Returns one entry per session with a known answer; @@ -2886,24 +2906,26 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { } /** - * {@link getPanePid} without blocking the event loop, for the kill path: a close - * must not stall every other session's I/O while tmux answers. + * The kill path's pane read: the pane pid and whether the pane is dead, in one + * `display-message`, without blocking the event loop (a close must not stall + * every other session's I/O while tmux answers). A failed read answers + * `{ dead: false, pid: null }`, so the caller falls back to the recorded pid + * exactly as before. */ - private async getPanePidAsync(muxName: string): Promise { - if (IS_TEST_MODE) return 99999; + private async readPaneForKill(muxName: string): Promise { + if (IS_TEST_MODE) return { dead: false, pid: 99999 }; if (!isValidMuxName(muxName)) { - console.error('[TmuxManager] Invalid session name in getPanePidAsync:', muxName); - return null; + console.error('[TmuxManager] Invalid session name in readPaneForKill:', muxName); + return { dead: false, pid: null }; } try { - const { stdout } = await execAsync(`${this.tmux()} display-message -t "${muxName}" -p '#{pane_pid}'`, { - encoding: 'utf-8', - timeout: EXEC_TIMEOUT_MS, - }); - const pid = parseInt(stdout.trim(), 10); - return Number.isNaN(pid) ? null : pid; + const { stdout } = await execAsync( + `${this.tmux()} display-message -t "${muxName}" -p '#{pane_dead}${PANE_LIST_SEP}#{pane_pid}'`, + { encoding: 'utf-8', timeout: EXEC_TIMEOUT_MS } + ); + return parsePaneKillRead(stdout); } catch { - return null; + return { dead: false, pid: null }; } } @@ -3244,6 +3266,62 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { return stillAlive.length === 0; } + /** + * Strategies 1 and 2 of {@link killSession}: SIGTERM then SIGKILL the pane + * process's killable descendants, then its process group. Every pid it + * targets is appended to `allPids` for the final verify. Only ever called + * with the pid of a LIVE pane. + */ + private async killPaneProcessTree(mode: SessionMode, panePid: number, allPids: number[]): Promise { + allPids.push(panePid); + + // Strategy 1: Kill all child processes recursively (but never a shared daemon the + // pane's CLI started for every session of that CLI: see killableDescendants) + let childPids = await this.killableDescendants(mode, panePid, await this.getChildPidsFresh(panePid)); + if (childPids.length > 0) { + console.log(`[TmuxManager] Found ${childPids.length} child processes to kill`); + allPids.push(...childPids); + + for (const childPid of [...childPids].reverse()) { + if (this.isProcessAlive(childPid)) { + try { + process.kill(childPid, 'SIGTERM'); + } catch { + // Process may already be dead + } + } + } + + // Most children are gone within a few ms; the re-scan below still runs, to + // catch anything spawned since the first one. + await waitForProcessesExit(childPids, { timeoutMs: TMUX_KILL_WAIT_MS }); + + childPids = await this.killableDescendants(mode, panePid, await this.getChildPidsFresh(panePid)); + for (const childPid of childPids) { + if (this.isProcessAlive(childPid)) { + try { + process.kill(childPid, 'SIGKILL'); + } catch { + // Process already terminated + } + } + } + } + + // Strategy 2: Kill the entire process group + if (this.isProcessAlive(panePid)) { + try { + process.kill(-panePid, 'SIGTERM'); + await waitForProcessesExit([panePid], { timeoutMs: GRACEFUL_SHUTDOWN_WAIT_MS }); + if (this.isProcessAlive(panePid)) { + process.kill(-panePid, 'SIGKILL'); + } + } catch { + // Process group may not exist or already terminated + } + } + } + /** * Kill a tmux session and all its child processes. * Uses a 4-strategy approach (children → process group → tmux kill → SIGKILL). @@ -3364,58 +3442,23 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { return true; } - // Get current PID (may have changed) - const currentPid = (await this.getPanePidAsync(session.muxName)) || session.pid; + // Get current PID (may have changed). A dead pane has no process left to + // signal, and the pid on the record is the one that exited, which the OS may + // since have handed to an unrelated process: walking its tree or signalling + // it could kill that. tmux 3.8 prints no pid for a dead pane, so without this + // check the fallback below would pick that stale pid every time. Only the + // kill-session below runs for it. + const pane = await this.readPaneForKill(session.muxName); + const currentPid = pane.dead ? null : (pane.pid ?? session.pid); - console.log(`[TmuxManager] Killing session ${session.muxName} (PID ${currentPid})`); + console.log( + currentPid === null + ? `[TmuxManager] Killing session ${session.muxName} (pane dead, PID ${session.pid} not signalled)` + : `[TmuxManager] Killing session ${session.muxName} (PID ${currentPid})` + ); - const allPids: number[] = [currentPid]; - - // Strategy 1: Kill all child processes recursively (but never a shared daemon the - // pane's CLI started for every session of that CLI: see killableDescendants) - let childPids = await this.killableDescendants(session.mode, currentPid, await this.getChildPidsFresh(currentPid)); - if (childPids.length > 0) { - console.log(`[TmuxManager] Found ${childPids.length} child processes to kill`); - allPids.push(...childPids); - - for (const childPid of [...childPids].reverse()) { - if (this.isProcessAlive(childPid)) { - try { - process.kill(childPid, 'SIGTERM'); - } catch { - // Process may already be dead - } - } - } - - // Most children are gone within a few ms; the re-scan below still runs, to - // catch anything spawned since the first one. - await waitForProcessesExit(childPids, { timeoutMs: TMUX_KILL_WAIT_MS }); - - childPids = await this.killableDescendants(session.mode, currentPid, await this.getChildPidsFresh(currentPid)); - for (const childPid of childPids) { - if (this.isProcessAlive(childPid)) { - try { - process.kill(childPid, 'SIGKILL'); - } catch { - // Process already terminated - } - } - } - } - - // Strategy 2: Kill the entire process group - if (this.isProcessAlive(currentPid)) { - try { - process.kill(-currentPid, 'SIGTERM'); - await waitForProcessesExit([currentPid], { timeoutMs: GRACEFUL_SHUTDOWN_WAIT_MS }); - if (this.isProcessAlive(currentPid)) { - process.kill(-currentPid, 'SIGKILL'); - } - } catch { - // Process group may not exist or already terminated - } - } + const allPids: number[] = []; + if (currentPid !== null) await this.killPaneProcessTree(session.mode, currentPid, allPids); // Strategy 3: Kill tmux session by name (guard the name before it reaches the shell). // Async: tmux takes tens of ms to tear a session down, and execSync held the @@ -3457,7 +3500,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer { } // Strategy 4: Direct kill by PID as final fallback - if (this.isProcessAlive(currentPid)) { + if (currentPid !== null && this.isProcessAlive(currentPid)) { try { process.kill(currentPid, 'SIGKILL'); } catch { diff --git a/test/tmux-manager.test.ts b/test/tmux-manager.test.ts index 8d0face7..9832b83e 100644 --- a/test/tmux-manager.test.ts +++ b/test/tmux-manager.test.ts @@ -16,6 +16,7 @@ import { buildRemoteLaunchCommand, formatPaneSnapshot, parsePaneRows, + parsePaneKillRead, derivePaneExits, hasObservablePaneSession, endedAdoptedAttaches, @@ -1481,6 +1482,27 @@ describe('parsePaneRows', () => { }); }); +describe('parsePaneKillRead', () => { + it('reads a live pane as its pid', () => { + expect(parsePaneKillRead('0|4242\n')).toEqual({ dead: false, pid: 4242 }); + }); + + it('reads a dead pane as dead, with the pid tmux 3.8 leaves blank', () => { + // killSession must not walk or signal the recorded pid of an exited program: + // the OS may have reused it for an unrelated process. + expect(parsePaneKillRead('1|\n')).toEqual({ dead: true, pid: null }); + }); + + it('reads a dead pane as dead on a tmux that still prints its pid', () => { + expect(parsePaneKillRead('1|4242')).toEqual({ dead: true, pid: 4242 }); + }); + + it('treats an unreadable answer as not dead, so the recorded pid is still used', () => { + expect(parsePaneKillRead('')).toEqual({ dead: false, pid: null }); + expect(parsePaneKillRead('|')).toEqual({ dead: false, pid: null }); + }); +}); + describe('derivePaneExits', () => { const NOW = 1_700_000_000_000;