Skip to content

fix(daemon): sweep descendants on graceful close of shells without launch metadata - #33317

Merged
nwparker merged 4 commits into
mainfrom
nwparker/agint-agent-process-tree-leak
Oct 25, 2026
Merged

nwparker merged 4 commits into
mainfrom
nwparker/agint-agent-process-tree-leak

Conversation

@nwparker

@nwparker nwparker commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​98 $\color{#cf222e}{\Huge{\mathbf{−}}}$​69 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​29
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​30 $\color{#cf222e}{\Huge{\mathbf{−}}}$​53 $\color{#cf222e}{\Huge{\mathbf{−}}}$​23

ELI5

If you open a plain Orca terminal, type claude or codex, 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 with nohup or disown are 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.

  • Since fix(pty): stop detached OMP tools on immediate terminal close #20642, immediate closes sweep descendants for every shell (desktop tab close and orca terminal close via stopAndWait). That path was not leaking.
  • Graceful closes (killPtyFromRuntimeController → shutdown({ immediate: false })) still went through Session.kill(). For a shell without launchAgent, 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.
  • When the shell exits, the 5s force-kill fallback is cancelled. Children that put themselves in their own process group never get the hangup and are reparented. MCP servers do this, for example Node spawn(..., { detached: true }), which is how browser-launching MCP servers start Chrome.

Upstream behaviour I checked:

  • Claude Code 2.1.310 (installed binary): it installs process.on("SIGHUP"/"SIGTERM", exit) handlers. On macOS its process title is its version (2.1.310), so recognizeAgentProcess(getForegroundProcess()) returns null unless the async foreground cache happens to be warm. My probe logged fg=2.1.310 before close on every macOS run. A gate based on foreground name would miss a real hand-typed claude.
  • Codex 0.164 starts its MCP servers in their own process groups (pgid == pid in the probe rows below).

Other observation: the launchAgent branch inside SessionTerminationController.kill() was already unreachable in production. TerminalSessionTeardown.killSession sends launchAgent sessions to killAgentSession and never calls Session.kill() for them.

What changed

  • TerminalSessionTeardown.killSession: graceful closes now go through the existing tracked, snapshot-first teardown that launched agents use (renamed killAgentSession → 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.
  • I deleted the now-dead Session.kill() / SessionTerminationController.kill() and the controller's launchAgent dependency.
  • Tests: one regression test (graceful close of a shell without launchAgent snapshots before it signals the root). Callers of session.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, so nohup/disown jobs survive. This check lives in excludeShellBackgroundJobs (src/main/pty-shell-job-preservation.ts) and is applied only in TerminalSessionTeardown's graceful plain-shell path. collectDescendantRows stays unfiltered, so host shutdown, the local provider, exit verification and Orca-launched agents are unchanged.

process graceful close before graceful close after immediate close / Orca-launched agent
tmux new -d … server + its children survives survives survives
(cmd &) double-fork / setsid / self-daemonizing tools survives survives survives*
nohup cmd &, cmd & disown typed in the shell survives survives terminated
a tool's own process group that keeps the tty (Codex MCP stdio servers, process_group(0) helpers) leaks terminated terminated
agent tools that setsid() / detached: true leaks terminated terminated

*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-rs rmcp-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 -flpq TCC 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 or taskkill /T, because the job deliberately leaves start /b and 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.killSession path, with a plain login shell, and types:

  • nohup sleep 611 & and sleep 612 & disown
  • a Codex-like foreground child, sh -c '…'. It starts a python child that calls setpgid(0,0) and keeps the tty (620), a setsid() child (621), and its own sleep 622.

It then closes and checks the captured PIDs 7s later.

run survivors at head 5d3b97e survivors with this commit
macOS graceful, plain shell 611, 612, 620 611, 612
macOS immediate, plain shell none none
macOS graceful, launchAgent: codex 611, 612, 620 none
Linux (omarchy) graceful, plain shell 611, 612, 620 611, 612
Linux immediate, plain shell none none
Linux graceful, launchAgent: codex 611, 612, 620 none

The 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 shows login -flpq nwparker /bin/bash … as root → /opt/homebrew/bin/bash --rcfile … (own pgid) → jobs:

macOS, login wrapper active survivors at c89e4c5 survivors at e36046b
graceful, plain shell none (nohup/disown swept) 611, 612
immediate, plain shell none none
graceful, launchAgent: codex none none

Linux (omarchy) at e36046b, root /usr/bin/bash -l with no wrapper: graceful plain shell leaves 611, 612; immediate and launchAgent: codex leave 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 calls createPtySubprocess (including the macOS /usr/bin/login TCC 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 a detached: true helper (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:

claude graceful  fg=2.1.310  survivors: [sleep 618 (pgid self)]   <- leak
claude immediate              survivors: []
codex  graceful  fg=codex    survivors: [sleep 618 (pgid self)]   <- leak
codex  immediate              survivors: []

With this PR: claude graceful ×3 and codex graceful give survivors: [], and immediate stays []. In separate runs without MCP, a graceful close also left the hand-typed claude itself 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:

base:  claude graceful survivors: [sleep 618]   codex graceful survivors: [sleep 618]   immediate: [] / []
fix:   claude graceful survivors: []            codex graceful survivors: []

The changed test files also pass on Linux (127 tests).

Automated checks:

  • pnpm tc
  • pnpm 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:changed

Windows (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-verified taskkill /T, then the ConPTY kill).

Risk / compatibility

  • POSIX only: graceful plain-shell close keeps a group only if its leader is a direct child of the shell, still holds the tty, and is not the foreground group. A tool that calls setpgid from 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.
  • Windows graceful plain-shell close is unchanged from main (root signal only), so detached tools of a hand-typed agent can still leak there. That is a known gap, traded for not killing start /b/GUI children.
  • POSIX graceful close now runs one bounded process-table scan (≤1s) before it signals the root. If descendants exist, it runs one more scan 2s later to SIGKILL survivors with the same identity. This is the cost immediate close already pays. No polling.
  • A rejected root signal now reaches the RPC caller as an async rejection instead of a synchronous throw, the same as launched-agent sessions today. The session drops back to running and can still be attached. The informational daemon tombstone (only tests read isKilled) is recorded first.
  • Daemon-only change with no wire or protocol fields, so it is safe across mixed client and daemon versions. Remote hosts get the fix when their daemon updates. Folder workspaces are unaffected (no git assumptions).
  • Not covered: the in-process local provider's graceful path (local-pty-termination.ts sweeps on ptyAgentSessionIds || immediate, where agent ids come only from launch or startup-command recognition), and the SSH relay pty-handler.ts.

Related PRs

Fixes #16714
Refs #21953. That report also covers session-kill-failed / “Session not found” bookkeeping and UI surfacing, which this PR does not change.

…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]>
@coderabbitai

coderabbitai Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent 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: 36529f48-1ceb-4bcf-951a-0ab301a0ccf0
Commits

Reviewing files that changed from the base of the PR and between 1c95313 and c89e4c5.

Files selected for processing: 6
  • src/main/daemon/terminal-session-teardown.test.ts
  • src/main/daemon/terminal-session-teardown.ts
  • src/main/pty-descendant-termination.test.ts
  • src/main/pty-descendant-termination.ts
  • src/main/pty-process-table-parser.ts
  • src/main/pty-shell-job-preservation.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.

Walkthrough

Graceful teardown now uses descendant snapshots for sessions without launch-agent metadata. The process-table scan includes terminal process-group IDs, which the teardown path uses to exclude shell background jobs from graceful termination snapshots. Immediate plain-shell teardown retains its tracked force-kill path. SessionTerminationController and Session no longer expose the previous kill method or launch-agent dependency. Shutdown tests use the updated teardown flow, and host tests await kill completion.

Priority: Normal

Severity of issue fixed: Medium

Merge Risk: Low · up to c89e4

Graceful close of a plain shell now sweeps descendants. The root shell can be signaled slightly before helper processes are, but helpers are still targeted by identity afterward, so leftover helpers are unlikely. The preservation filter has some narrow edge cases. The merge risk is bounded.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 6 functions across 11 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title names the daemon fix, graceful close, and shells without launch metadata, which matches the main change. It is specific and concise, and it fits the changeset. The title uses the conventiona…
Linked Issues check Passed For direct issue [#16714], graceful TerminalSessionTeardown.killSession now uses killAfterDescendantSnapshot when immediate is false, including sessions without launchAgent. The code captures …
Out of Scope Changes check Passed The changes remain connected to [#16714]. The tpgid parser and excludeShellBackgroundJobs helper support safe graceful teardown. Removal of the obsolete Session.kill() path and dependency update…
Description check Passed The description is detailed and directly addresses the change, root cause, rationale, linked issue, testing, platform behavior, compatibility, and known limitations. It does not reproduce every templa…
Full details: Title check

Explanation

The title names the daemon fix, graceful close, and shells without launch metadata, which matches the main change. It is specific and concise, and it fits the changeset. The title uses the conventional fix(scope) prefix.

Full details: Linked Issues check

Explanation

For direct issue [#16714], graceful TerminalSessionTeardown.killSession now uses killAfterDescendantSnapshot when immediate is false, including sessions without launchAgent. The code captures descendants before signalTerminationRoot, then performs descendant termination and verification. Plain-shell graceful teardown excludes only qualifying shell-led background groups; agent-created descendant groups remain covered. Immediate plain-shell teardown retains the existing sweep path. Tests verify snapshot-before-root-signal behavior and plain-shell versus launched-agent filtering.

Full details: Out of Scope Changes check

Explanation

The changes remain connected to [#16714]. The tpgid parser and excludeShellBackgroundJobs helper support safe graceful teardown. Removal of the obsolete Session.kill() path and dependency updates align all callers with the shared teardown entry point. The modified tests cover the teardown routing, ordering, escalation, process filtering, and Windows job ownership. No unrelated production feature is shown.

Full details: Description check

Explanation

The description is detailed and directly addresses the change, root cause, rationale, linked issue, testing, platform behavior, compatibility, and known limitations. It does not reproduce every template heading, such as Visual Proof, Review, Agent skill upstream boundary, and Checklist, but the required substantive information is mostly present.

Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
Commits

Reviewing files that changed from the base of the PR and between 4995568 and 1c95313.

Files selected for processing: 9
  • src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.ts
  • src/main/daemon/session-terminal-control.test.ts
  • src/main/daemon/session-termination-controller.ts
  • src/main/daemon/session.test.ts
  • src/main/daemon/session.ts
  • src/main/daemon/terminal-host-closing-session-listing.test.ts
  • src/main/daemon/terminal-host.test.ts
  • src/main/daemon/terminal-session-teardown.test.ts
  • src/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.

Comment on lines +72 to +73
if (session.launchAgent || !immediate) {
return this.killAfterDescendantSnapshot(sessionId, session, immediate)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Stability & Availability · Heavy lift

🔎 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Hand-typed agent sessions (claude/codex in a plain shell) leak their process tree on tab close

1 participant