Repository navigation
fix(daemon): sweep descendants on graceful close of shells without launch metadata - #33317
Conversation
…unch metadata A claude/codex typed into a plain shell has no launchAgent, so graceful daemon teardown only SIGHUPed the PTY root. Detached MCP/tool process groups reparented to init and survived. Route graceful closes through the same snapshot-first descendant sweep immediate closes already use for every shell (#20642), and drop the now-unreachable Session.kill path. Fixes #16714 Co-authored-by: PeaceTis <[email protected]>
|
No actionable comments were generated in the recent review.
|
There was a problem hiding this comment.
Actionable comments posted: 1

Review info
-
Run configuration-
- Source mode: Auto
- Repository: Unavailable
- Branch: Unavailable
- File: No configuration file from this repository applied
- Commit: Unavailable
- Layers: Repository UI
- Review profile: CHILL
- Plan: Advanced
- Run ID:
598e18e0-512b-44a5-8275-dd00932b44e2
Files selected for processing: 9-
src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.tssrc/main/daemon/session-terminal-control.test.tssrc/main/daemon/session-termination-controller.tssrc/main/daemon/session.test.tssrc/main/daemon/session.tssrc/main/daemon/terminal-host-closing-session-listing.test.tssrc/main/daemon/terminal-host.test.tssrc/main/daemon/terminal-session-teardown.test.tssrc/main/daemon/terminal-session-teardown.ts
Files with no reviewable changes: 2-
- src/main/daemon/session.ts
- src/main/daemon/session-termination-controller.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.
-
| if (session.launchAgent || !immediate) { | ||
| return this.killAfterDescendantSnapshot(sessionId, session, immediate) |
There was a problem hiding this comment.
🔎 Supported by static analysis
-
Script executed:
#!/bin/bash set -euo pipefail # Locate the implementation and its call sites. Inspect the first await and # whether SIGTERM is sent before terminateShutdownDescendants returns a promise. rg -n -C 12 --type ts \ 'function terminateShutdownDescendants\b|const terminateShutdownDescendants\b|terminateShutdownDescendants\(' \ src/main
Repository: stablyai/orca
Length of output: 8495
Script executed:
set -euo pipefail printf '%s\n' '--- terminal-descendant-shutdown.ts ---' nl -ba src/main/daemon/terminal-descendant-shutdown.ts printf '%s\n' '--- bound implementation and call sites ---' rg -n -C 18 --type ts \ 'function terminateDescendantSnapshotWithVerdict|const terminateDescendantSnapshotWithVerdict|terminateDescendantSnapshotWithVerdict\(' \ src/main printf '%s\n' '--- signal operations in descendant shutdown area ---' rg -n -C 10 --type ts \ 'process\.kill|kill\(|SIGTERM|SIGKILL|terminateDescendantSnapshotWithVerdict' \ src/main/daemon/terminal-descendant-shutdown.ts src/main/daemon/terminal-descendant-*.ts
Repository: stablyai/orca
Length of output: 42140
Script executed:
set -euo pipefail nl -ba src/main/pty-descendant-exit-verification.ts printf '%s\n' '--- implementation references and signal-order tests ---' rg -n -C 16 --type ts \ 'terminateDescendantSnapshotWithVerdict|sendSignal|SIGTERM|graceMs|requireIdentityBeforeSignal' \ src/main/pty-descendant-exit-verification.ts src/main/pty-descendant-exit-verification.test.ts
Repository: stablyai/orca
Length of output: 42459
Script executed:
set -euo pipefail printf '%s\n' '--- terminal-session-teardown.ts relevant block ---' nl -ba src/main/daemon/terminal-session-teardown.ts | sed -n '110,180p' printf '%s\n' '--- killWithDescendantSweep declaration and references ---' rg -n -C 24 --type ts \ 'function killWithDescendantSweep|const killWithDescendantSweep|killWithDescendantSweep\(' \ src/main
Repository: stablyai/orca
Length of output: 41676
Script executed:
set -euo pipefail nl -ba src/main/pty-descendant-termination.ts | sed -n '215,330p'
Repository: stablyai/orca
Length of output: 5099
Wait for descendant termination before signaling the root.
For graceful teardown, awaitEscalation is false. killWithDescendantSweep starts terminateDescendants(snapshot) and then calls killRoot() without awaiting it. terminateShutdownDescendants must await a process-table read before it sends SIGTERM, so the root can be signaled first.
Suggested fix
-
- awaitEscalation: () => entry.immediate + awaitEscalation: true
…dant sweep The graceful-close sweep killed every descendant, including background jobs a user deliberately detached. Read tpgid with the existing ps snapshot and skip rows in a background process group on the shell's terminal: the shell's own SIGHUP still ends plain '&' jobs, nohup/disown jobs survive as in any terminal, and agent tools that setsid() away (no terminal) are still swept.
The tpgid filter sat inside the shared collectDescendantRows, so it also skipped any process group that kept the tty, e.g. Codex MCP stdio servers (rmcp-client ProcessMode::NewGroup), on every caller: host shutdown, local provider, exit verification and Orca-launched agents. Keep collection unfiltered and drop only background groups whose leader is a direct child of the shell, and only on graceful close of a shell without launchAgent.
…ful close root-only The macOS TCC wrapper makes login(1) the PTY root and the shell its child, so the shell-job check spared the shell's own group and swept nohup jobs. Resolve the job-control shell as the root's single child only when the session runs under the login wrapper. On win32 a graceful plain-shell close went through the PTY job and ended `start /b` and GUI children the job deliberately leaves to the user; signal only the root there, as before.
ELI5
If you open a plain Orca terminal, type
claudeorcodex, and later close that pane from mobile, a headless tab, or a worktree stop, Orca only told the shell to hang up. The agent's MCP servers and tools could keep running forever, reparented to PID 1. Now, on macOS and Linux, every close first takes a snapshot of the shell's process tree and cleans that tree up. Jobs you deliberately backgrounded withnohupordisownare left alone, as in any terminal. Agents Orca launched itself already got this cleanup. Windows graceful close is unchanged.Root cause
The daemon chose its teardown based on
session.launchAgent. Only Orca's own agent-launch path sets that field.orca terminal closeviastopAndWait). That path was not leaking.killPtyFromRuntimeController→shutdown({ immediate: false })) still went throughSession.kill(). For a shell withoutlaunchAgent, that sent SIGHUP to the PTY root only. The graceful callers are: mobile pane close (closeMobileSessionTerminalPane), headless tab close, worktree terminal-stop fallback, and failed-start and split cleanup.spawn(..., { detached: true }), which is how browser-launching MCP servers start Chrome.Upstream behaviour I checked:
process.on("SIGHUP"/"SIGTERM", exit)handlers. On macOS its process title is its version (2.1.310), sorecognizeAgentProcess(getForegroundProcess())returnsnullunless the async foreground cache happens to be warm. My probe loggedfg=2.1.310before close on every macOS run. A gate based on foreground name would miss a real hand-typedclaude.Other observation: the
launchAgentbranch insideSessionTerminationController.kill()was already unreachable in production.TerminalSessionTeardown.killSessionsendslaunchAgentsessions tokillAgentSessionand never callsSession.kill()for them.What changed
TerminalSessionTeardown.killSession: graceful closes now go through the existing tracked, snapshot-first teardown that launched agents use (renamedkillAgentSession→killAfterDescendantSnapshot, since it is no longer agent-only). Immediate plain-shell closes keep the fix(pty): stop detached OMP tools on immediate terminal close #20642 path unchanged.Session.kill()/SessionTerminationController.kill()and the controller'slaunchAgentdependency.launchAgentsnapshots before it signals the root). Callers ofsession.kill()in existing tests were moved to the teardown entry point.Net production change: +8 / −48 lines.
What survives a close
The sweep only reaches processes that are still descendants of the PTY root when the snapshot is taken. On a POSIX graceful close of a plain shell (no
launchAgent), Orca also skips the shell's own background jobs: a process group whose leader (pid == pgid) is a direct child of the shell, still holds the tty, and is not the foreground group. Those are left to the shell's SIGHUP, as in any terminal, sonohup/disownjobs survive. This check lives inexcludeShellBackgroundJobs(src/main/pty-shell-job-preservation.ts) and is applied only inTerminalSessionTeardown's graceful plain-shell path.collectDescendantRowsstays unfiltered, so host shutdown, the local provider, exit verification and Orca-launched agents are unchanged.tmux new -d …server + its children(cmd &)double-fork /setsid/ self-daemonizing toolsnohup cmd &,cmd & disowntyped in the shellprocess_group(0)helpers)setsid()/detached: true*Immediate close also
killpgs process groups that still hold the tty, so whether a double-forked job survives depends on the shell/root wrapper.Codex starts each MCP stdio server with
ProcessMode::NewGroup(codex-rsrmcp-client/src/stdio_server_launcher.rs:284). That gives it a new process group but keeps the controlling tty, so a tpgid-only test cannot tell it apart from a shell job. Its group leader's parent is Codex, not the shell, which is why the check uses the leader's ppid.On macOS the daemon spawns the shell under the
/usr/bin/login -flpqTCC wrapper (native-pty-spawn.ts), so the PTY root is login and the job-control shell is its only child. In that case, and only that case (Session.shellIsRootChild, set from!hostReportsChildExitStatus(file)), the check uses that single child as the shell. If login has more or fewer than one child, nothing is preserved. I did not use a looser "root or root's child" rule, because it would also spare an agent's NewGroup MCP servers on Linux.Windows: a graceful plain-shell close keeps main's behaviour: it signals only the root (
beginTermination→signalTerminationRoot→ force-dispose fallback). It does not use the PTY job ortaskkill /T, because the job deliberately leavesstart /band GUI children alone on a graceful close (windows-pty-job.ts). This means hand-typed agents' detached tools can still leak on a Windows graceful close. Immediate close and Orca-launched agents keep their existing win32 job/tree kill.Verification
Shell-job preservation (commits c89e4c5, e36046b)
This used an opt-in probe that was not checked in. It runs the same
createPtySubprocess→Session→TerminalSessionTeardown.killSessionpath, with a plain login shell, and types:nohup sleep 611 &andsleep 612 & disownsh -c '…'. It starts a python child that callssetpgid(0,0)and keeps the tty (620), asetsid()child (621), and its ownsleep 622.It then closes and checks the captured PIDs 7s later.
launchAgent: codexlaunchAgent: codexThe macOS runs above did not go through the login wrapper (no TCC preflight). Re-run at e36046b with the preflight (
prepareMacosTccLoginShell→accepted), so the wrapper was actually active. The ps tree showslogin -flpq nwparker /bin/bash …as root →/opt/homebrew/bin/bash --rcfile …(own pgid) → jobs:launchAgent: codexLinux (omarchy) at e36046b, root
/usr/bin/bash -lwith no wrapper: graceful plain shell leaves 611, 612; immediate andlaunchAgent: codexleave none. The targeted tests also pass on Linux (119).I ran the real daemon code path with real CLIs: an opt-in probe, not checked in, modelled on
tests/tools/omp-close-lifecycle.test.mjs. It callscreatePtySubprocess(including the macOS/usr/bin/loginTCC wrapper) →Session→TerminalSessionTeardown.killSession, types the agent into a plain login shell, waits, closes, then checks the captured PIDs (matched by start time) 9s later. The MCP server is a minimal stdio server that, like browser-launching MCP servers, spawns adetached: truehelper (sleep 618). No model requests are made. Everything ran in the background (ORCA_BACKGROUND_LAUNCH=1); no windows.macOS arm64 (claude 2.1.310, codex 0.164.0), base
e18752acea62:With this PR:
claude graceful×3 andcodex gracefulgivesurvivors: [], andimmediatestays[]. In separate runs without MCP, a graceful close also left the hand-typedclaudeitself alive once (still starting up), and left a Claude!bash-mode tool child alive once.Linux x86_64 (omarchy) (claude 2.1.309, codex 0.160.0), same probe:
The changed test files also pass on Linux (127 tests).
Automated checks:
pnpm tcpnpm test src/main/daemon src/main/providers src/main/pty src/main/ipc/pty: 5334 passed. Two unrelated tests failed only under full-suite load and pass in isolation:daemon-init-provider-installation,pty-pane-materialization-race.pnpm run check:code-quality:changedWindows (unit-tested, not run on Windows): a graceful plain-shell close signals only the root, as on main. The teardown test asserts that it does not call
killWithDescendantSweep/terminateOwnedTree. Launched-agent and immediate closes keep their existing win32 branch (PTY job, else identity-verifiedtaskkill /T, then the ConPTY kill).Risk / compatibility
setpgidfrom a shell-launched background job, rather than from the foreground agent, is still swept. A hand-typed agent the user started with&is a shell job, so the shell's SIGHUP decides its fate (the default kills it). Process groups the agent creates are still swept. Under the macOS login wrapper the shell is the root's single child; with any other child count, nothing is preserved.start /b/GUI children.runningand can still be attached. The informational daemon tombstone (only tests readisKilled) is recorded first.local-pty-termination.tssweeps onptyAgentSessionIds || immediate, where agent ids come only from launch or startup-command recognition), and the SSH relaypty-handler.ts.Related PRs
recognizeAgentProcess(getForegroundProcess()). On macOS a realclaudereports its foreground name as its version (2.1.310), so that gate misses it unless the async cache is warm (see probe output). This PR replaces both; credit to PeaceTis viaCo-authored-byfor the diagnosis in Hand-typed agent sessions (claude/codex in a plain shell) leak their process tree on tab close #16714.Fixes #16714
Refs #21953. That report also covers
session-kill-failed/ “Session not found” bookkeeping and UI surfacing, which this PR does not change.