Repository navigation
fix(terminal): kill agent descendant processes on session teardown (STA-1800) - #8706
Conversation
…TA-1800) Agent CLIs spawn tool children in detached process groups that PTY SIGHUP can never reach. Killing an agent session (tab close, retire, sleep) left those children running as orphans — eight orphaned git processes burned ~8 cores for up to 11.5h under the agents-running keep-awake and drained a battery to 8%. New pty-descendant-termination module: snapshot the ppid tree BEFORE signalling (a dead root's descendants reparent to pid 1 and become unfindable), SIGTERM the root group and every descendant, then after a 2s grace SIGKILL survivors gated on a pid+start-time identity re-check so a recycled pid is never signalled. Snapshot is bounded and never rejects; failures degrade to today's shell-only kill. Wired for agent sessions only (plain terminals keep nohup semantics) at all three POSIX kill sites: local provider shutdown, daemon TerminalHost immediate kill (the pty:kill path — force-kill bypassed Session.kill entirely), and daemon Session graceful kill. Verified live in the built app: an agent pane with a detached-pgid child; the child survived on the unwired build (three control runs) and dies within ~5s with the fix. Windows ConPTY and SSH-hosted PTYs keep the previous foreground-tree contract (documented follow-ups).
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds timestamped process-table snapshots, descendant traversal, bounded scanning, and identity-checked SIGTERM/SIGKILL escalation. Agent PTY and daemon session teardown now coordinate asynchronous shutdown, prevent reattachment during teardown, coalesce duplicate kills, and support immediate upgrades. Worktree shutdown runs concurrently, while tests, reliability gates, documentation, and an end-to-end scenario cover the updated lifecycle behavior. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/providers/local-pty-provider.ts (1)
905-941: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy liftPrevent reattach while async teardown is in flight
src/main/providers/local-pty-provider.ts#L905-L941still waits on the descendant snapshot before marking shutdown in progress, sospawn()can reattach the same PTY during teardown. The immediatelaunchAgentbranch insrc/main/daemon/terminal-host.ts#L197-L218has the same gap beforekillWithDescendantSweep(). Add a synchronous shutting-down/terminating marker before the await and block reattach/re-entry until teardown finishes.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 1e2e5145-64ac-4611-a0a9-d7da24c11ced
📒 Files selected for processing (9)
docs/reference/terminal-session-lifecycle.mdsrc/main/daemon/session.test.tssrc/main/daemon/session.tssrc/main/daemon/terminal-host.test.tssrc/main/daemon/terminal-host.tssrc/main/providers/local-pty-provider.tssrc/main/pty-descendant-termination.test.tssrc/main/pty-descendant-termination.tstests/e2e/agent-descendant-process-kill.spec.ts
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: a2a1f998-ad51-4c26-a1a1-bddb04507445
📒 Files selected for processing (12)
config/reliability-gates.jsoncdocs/reference/terminal-session-lifecycle.mdsrc/main/daemon/daemon-server.test.tssrc/main/daemon/daemon-server.tssrc/main/daemon/session.tssrc/main/daemon/terminal-host.test.tssrc/main/daemon/terminal-host.tssrc/main/daemon/terminal-immediate-kill.tssrc/main/providers/local-pty-provider.test.tssrc/main/providers/local-pty-provider.tssrc/main/pty-descendant-termination.test.tssrc/main/pty-descendant-termination.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/main/daemon/terminal-host.test.ts
- src/main/providers/local-pty-provider.ts
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/main/daemon/terminal-agent-teardown.ts (1)
56-82: 🩺 Stability & Availability | 🔵 TrivialOperation promise can still reject even after teardown succeeds.
killWithDescendantSweep'sfinallyguarantees the callback (the realsignalTerminationRoot()/finishImmediate()work) runs before any error fromterminateDescendantSnapshotpropagates, so the root/descendants are still handled correctly. Butoperation(==entry.promise, returned all the way up throughTerminalHost.kill()) can still reject in that case. Anyone awaiting the returned promise (e.g. a daemon kill RPC handler) would then see a rejection for a teardown that actually completed, and could misreport success as failure.The internal
operation.then(clearOperation, clearOperation)at Line 81 does prevent a NodeunhandledRejectionhere (it's attached to the same promise object), so this isn't a crash risk — it's a correctness/reporting risk for callers ofkill()/TerminalHost.kill().♻️ Suggested normalization
const operation = Promise.resolve( killWithDescendantSweep(session.pid, () => { // Why: natural exit reaps the PID while ps is running. Never signal that // stale numeric PID after the Session no longer represents a live root. if (!session.isAlive) { return } if (entry.immediate) { this.finishImmediate(sessionId, session) } else { session.signalTerminationRoot() } }) - ) + ).catch(() => { + // killRoot() above already ran via the sweep's `finally`; a rejection here + // means descendant signalling failed, not that the root wasn't handled. + })This depends on whether
terminateDescendantSnapshot(prior layer,pty-descendant-termination.ts) can actually throw per-descendant signal errors rather than swallowing them — worth confirming against that file.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 85dc4495-1086-4db0-896f-32f61fc5f446
📒 Files selected for processing (10)
config/reliability-gates.jsoncdocs/reference/terminal-session-lifecycle.mdsrc/main/daemon/session.tssrc/main/daemon/terminal-agent-teardown.tssrc/main/daemon/terminal-host.test.tssrc/main/daemon/terminal-host.tssrc/main/pty-descendant-termination.test.tssrc/main/pty-descendant-termination.tssrc/main/runtime/worktree-teardown.test.tssrc/main/runtime/worktree-teardown.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- src/main/daemon/session.ts
- docs/reference/terminal-session-lifecycle.md
- src/main/pty-descendant-termination.test.ts
- config/reliability-gates.jsonc
| const ownedSessions = sessions.filter((session) => session.id.startsWith(prefix)) | ||
| // Why: agent shutdown snapshots coalesce only when requests begin together; | ||
| // serial awaits multiply process-table scans and worktree-delete latency. | ||
| await Promise.all( | ||
| ownedSessions.map(async (session) => { | ||
| try { | ||
| await provider.shutdown(session.id, { immediate: true }) | ||
| clearStoppedPtyState(session.id, onPtyStopped) | ||
| } catch { | ||
| // Already dead, or the backend dropped the session — treat as success. | ||
| } | ||
| }) | ||
| ) | ||
| return ownedSessions.length |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Inconsistent "stopped" counting between the two sweep helpers.
sweepProviderByPrefix counts a failed shutdown() as stopped (per the "treat as success" comment), but sweepRegistryForWorktree counts a failed shutdown() as not stopped (return 0 in the catch). Same operation, same "already dead" rationale, different semantics for providerStopped vs registryStopped in the returned WorktreeTeardownResult.
🐛 Suggested fix: align semantics with sweepProviderByPrefix
const entries = listRegisteredPtys().filter((r) => r.worktreeId === worktreeId)
- const stopped = await Promise.all(
- entries.map(async (entry) => {
- try {
- await localProvider.shutdown(entry.ptyId, { immediate: true })
- clearStoppedPtyState(entry.ptyId, onPtyStopped)
- return 1
- } catch {
- return 0
- }
- })
- )
- return stopped.reduce<number>((count, value) => count + value, 0)
+ await Promise.all(
+ entries.map(async (entry) => {
+ try {
+ await localProvider.shutdown(entry.ptyId, { immediate: true })
+ clearStoppedPtyState(entry.ptyId, onPtyStopped)
+ } catch {
+ // Already dead, or the backend dropped the session — treat as success,
+ // matching sweepProviderByPrefix's semantics.
+ }
+ })
+ )
+ return entries.lengthAlso applies to: 97-108
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 3d88e96c-d79c-470b-a0f0-6ec7f6b9e788
📒 Files selected for processing (11)
config/reliability-gates.jsoncdocs/reference/terminal-session-lifecycle.mdsrc/main/daemon/session.test.tssrc/main/daemon/session.tssrc/main/daemon/terminal-host.test.tssrc/main/daemon/terminal-host.tssrc/main/daemon/terminal-session-teardown.tssrc/main/providers/local-pty-provider.test.tssrc/main/providers/local-pty-provider.tssrc/main/pty-descendant-termination.test.tssrc/main/pty-descendant-termination.ts
🚧 Files skipped from review as they are similar to previous changes (9)
- src/main/providers/local-pty-provider.test.ts
- docs/reference/terminal-session-lifecycle.md
- src/main/daemon/session.test.ts
- config/reliability-gates.jsonc
- src/main/pty-descendant-termination.test.ts
- src/main/daemon/session.ts
- src/main/daemon/terminal-session-teardown.ts
- src/main/daemon/terminal-host.ts
- src/main/daemon/terminal-host.test.ts
| const descendants = ptyAgentSessionIds.has(id) | ||
| ? await captureDescendantSnapshot(proc.pid) | ||
| : null |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Wrap snapshot capture in a try/catch to guarantee root teardown.
If captureDescendantSnapshot throws (e.g., due to an unexpected system error or resource exhaustion during process table reading), the exception will abort shutdownTrackedPty immediately. This prevents proc.kill() and clearPtyState(id) from running, leaving the agent session orphaned but still tracked in ptyProcesses (which causes subsequent spawns to reattach to the zombie process).
To ensure "snapshot failures degrade to existing root-only teardown" as intended, wrap the capture in a try/catch block so teardown continues regardless.
🛡️ Proposed fix to ensure fallback teardown
- const descendants = ptyAgentSessionIds.has(id)
- ? await captureDescendantSnapshot(proc.pid)
- : null
+ let descendants = null
+ if (ptyAgentSessionIds.has(id)) {
+ try {
+ descendants = await captureDescendantSnapshot(proc.pid)
+ } catch {
+ /* Fallback to root-only teardown on capture failure */
+ }
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const descendants = ptyAgentSessionIds.has(id) | |
| ? await captureDescendantSnapshot(proc.pid) | |
| : null | |
| let descendants = null | |
| if (ptyAgentSessionIds.has(id)) { | |
| try { | |
| descendants = await captureDescendantSnapshot(proc.pid) | |
| } catch { | |
| /* Fallback to root-only teardown on capture failure */ | |
| } | |
| } |
| const descendants: ProcessTableRow[] = [] | ||
| const queue = [rootPid] | ||
| while (queue.length > 0) { | ||
| const pid = queue.shift()! | ||
| for (const child of childrenByPpid.get(pid) ?? []) { | ||
| descendants.push(child) | ||
| queue.push(child.pid) | ||
| } | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win
Prevent infinite loops from cyclic process tables.
A ps snapshot on Linux reads /proc sequentially, meaning the capture is not fully atomic. A rapid PID recycle during the scan can theoretically produce a cyclic process tree (e.g., A -> B -> C -> A's reused PID). Because the BFS queue currently lacks cycle detection, traversing a cyclic graph will infinitely loop and permanently hang the Node.js event loop.
Track visited PIDs to guarantee termination regardless of OS-level process table races.
🔒️ Proposed fix to add cycle detection
const descendants: ProcessTableRow[] = []
const queue = [rootPid]
+ const visited = new Set<number>([rootPid])
while (queue.length > 0) {
const pid = queue.shift()!
for (const child of childrenByPpid.get(pid) ?? []) {
- descendants.push(child)
- queue.push(child.pid)
+ if (!visited.has(child.pid)) {
+ visited.add(child.pid)
+ descendants.push(child)
+ queue.push(child.pid)
+ }
}
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const descendants: ProcessTableRow[] = [] | |
| const queue = [rootPid] | |
| while (queue.length > 0) { | |
| const pid = queue.shift()! | |
| for (const child of childrenByPpid.get(pid) ?? []) { | |
| descendants.push(child) | |
| queue.push(child.pid) | |
| } | |
| } | |
| const descendants: ProcessTableRow[] = [] | |
| const queue = [rootPid] | |
| const visited = new Set<number>([rootPid]) | |
| while (queue.length > 0) { | |
| const pid = queue.shift()! | |
| for (const child of childrenByPpid.get(pid) ?? []) { | |
| if (!visited.has(child.pid)) { | |
| visited.add(child.pid) | |
| descendants.push(child) | |
| queue.push(child.pid) | |
| } | |
| } | |
| } |
🧰 Tools
🪛 ast-grep (0.44.1)
[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { execFile } from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').
(detect-child-process-typescript)
…adopt main's stablyai#8706 for POSIX descendants Reconciles the fail-closed worktree-teardown fix with main's newly-merged teardown work so the two compose instead of collide. Kept (the actual stablyai#8275 fix — Windows batch `worktree rm` killing the shared daemon and unrelated ConPTY panes): - fail-closed verified worktree teardown + legacy-daemon verification gate - worktree PTY admission fence (no spawn races an in-progress deletion) - Windows ConPTY verified teardown / daemon preservation (retain owner until native exit; never double-close ConPTY) - support glue (owner cache, bounded stop concurrency, teardown timeouts) Dropped the PR's parallel POSIX relay kill-path rewrite (pty-session-kill / -membership / -exit-verification): main's stablyai#8706 (pty-descendant-termination) already reaps detached agent descendants on POSIX, so a second freeze-sweep engine that ran on every immediate shutdown was redundant, riskier scope. Integrated instead: - POSIX agent-descendant reaping comes from stablyai#8706, including inside our verified daemon force path (Session.forceKillAndDisposeSubprocessAndWait snapshots + terminates descendants before the verified root kill) - daemon POSIX force-kill is a leader SIGKILL + await-native-exit shim (zombie-safe via existing exit waiters); relay POSIX teardown is a plain SIGKILL (SSH fail-closed enforced at the runtime liveness layer) Follow-up: descendant-level POSIX verification for non-agent / pre-reparented survivors on the delete path (leader-level fail-closed holds today).
…TA-1800) (stablyai#8706) * fix(terminal): kill agent descendant processes on session teardown (STA-1800) Agent CLIs spawn tool children in detached process groups that PTY SIGHUP can never reach. Killing an agent session (tab close, retire, sleep) left those children running as orphans — eight orphaned git processes burned ~8 cores for up to 11.5h under the agents-running keep-awake and drained a battery to 8%. New pty-descendant-termination module: snapshot the ppid tree BEFORE signalling (a dead root's descendants reparent to pid 1 and become unfindable), SIGTERM the root group and every descendant, then after a 2s grace SIGKILL survivors gated on a pid+start-time identity re-check so a recycled pid is never signalled. Snapshot is bounded and never rejects; failures degrade to today's shell-only kill. Wired for agent sessions only (plain terminals keep nohup semantics) at all three POSIX kill sites: local provider shutdown, daemon TerminalHost immediate kill (the pty:kill path — force-kill bypassed Session.kill entirely), and daemon Session graceful kill. Verified live in the built app: an agent pane with a detached-pgid child; the child survived on the unwired build (three control runs) and dies within ~5s with the fix. Windows ConPTY and SSH-hosted PTYs keep the previous foreground-tree contract (documented follow-ups). * fix(terminal): harden descendant teardown * fix(terminal): require fresh process snapshots * fix(terminal): close descendant teardown races * refactor(terminal): preserve teardown line budget * fix(terminal): keep descendant teardown fresh and identity-safe * docs(reliability): record integrated descendant E2E * fix(terminal): bound descendant teardown work * fix(terminal): share descendant snapshot indexes * docs(reliability): record descendant review evidence * revert: remove speculative descendant hardening
Summary
Fixes STA-1800: agent CLIs can launch tool processes in detached process groups, so killing only the PTY shell leaves those descendants orphaned and consuming CPU.
Agent-session teardown now snapshots the POSIX descendant tree before root teardown, sends SIGTERM to captured descendants, and performs a delayed identity-safe SIGKILL of confirmed survivors. Plain user terminals preserve their existing detached-child semantics.
Review hardening through
e948efde3and current-main integration6fb775b47:pschild a hard SIGKILL timeout.psstarts after timeout.psbegan through the snapshot. Escalation requires matching PID start time and PGID against a fresh bounded reread.ps lstartis second-resolution, a process born in the source scan second receives SIGTERM but is intentionally not escalated to SIGKILL.pscoalescing without unbounded IPC/RPC fan-out.Screenshots
No visual change.
Testing
pnpm lintpnpm typecheckpnpm testequivalent under the repository-required Node 24 runtime — 2,795 files passed; 29,596 tests passedpnpm build— not run standalone; both focused Electron E2E specs ran from a fresh E2E buildAdditional validation:
pnpm run check:reliability-gatesandpnpm run check:max-lines-ratchet.ps. Twenty deliberately sequential captures take 1.14 s because every later request receives fresh signal targets instead of a cached PID table. On Node 24, a synthetic 100,000-wide descendant tree fell from 861 ms to 16.7 ms after replacing front-removal traversal; worktree teardown coalesces within deterministic 32-session batches.AI Review Report
A multi-pass review focused on lifecycle races, process/PID safety, failure degradation, completion semantics, and kill-path performance.
It flagged async teardown ownership gaps, duplicate cleanup/early acknowledgement, unbounded or wedged
pschildren, process-table fan-out, root-before-descendant signaling, false certainty from second-resolutionlstart, the unsafe possibility of applying a later consumer timestamp to cached process rows, successor scans that could start only after their caller timed out, stale descendant signals after root ownership was lost, cyclic-looking process tables, quadratic queue shifts, full-table escalation indexing, and unbounded provider shutdown fan-out. The follow-up commits fix each issue and add deterministic regression tests for pending-capture reattach, same-ID respawn, duplicate completion sharing after root exit, RPC acknowledgement timing, synchronous/rejected/wedged readers, same-turn coalescing, post-start successor scans, source-scan timestamps, timeout cleanup, PID/PGID revalidation, same-second ambiguity, cyclic rows, duplicate escalation identities, and the 32-session fan-out cap.Cross-platform compatibility was explicitly checked:
pspath.Security Audit
psis invoked withexecFileand fixed arguments, not a shell; no user input is interpolated into a command.Residual risk: all PPID snapshots are inherently point-in-time. Processes already orphaned by a crash before teardown cannot be recovered by a kill-time tree walk and remain follow-up work.
Notes
killAll, and daemon dispose retain foreground-tree-only teardown for now.pscannot prove that a same-second PID was not recycled.nohup-style detached-child behavior; descendant sweeping is agent-session-only.Linear: STA-1800