Skip to content

fix(terminal): sweep descendants when tearing down hand-typed agent sessions - #16713

Closed
PeaceTis wants to merge 1 commit into
stablyai:mainfrom
PeaceTis:fix/daemon-plain-shell-agent-teardown
Closed

PeaceTis wants to merge 1 commit into
stablyai:mainfrom
PeaceTis:fix/daemon-plain-shell-agent-teardown

Conversation

@PeaceTis

@PeaceTis PeaceTis commented Aug 27, 2026 •

Copy link
Copy Markdown

ELI5

If you open a plain terminal in Orca, type claude yourself, and later close the tab, the claude process and its MCP servers keep running forever. Orca only knew how to fully clean up agents it launched itself. Now closing the tab cleans up hand-typed agents the same way.

What Changed

  • New src/main/daemon/agent-teardown-evidence.ts: teardown treats a session as an agent session when launchAgent is set or a recognized agent is live in the foreground (recognizeAgentProcess over the daemon's existing foreground tracker, which already resolves agents running under wrappers).
  • terminal-session-teardown.ts routes evidence-bearing sessions through killAgentSession (descendant snapshot → SIGTERM → SIGKILL survivors) for both graceful and immediate kills, instead of the root-only / tty-killpg plain-shell paths.
  • session-termination-controller.ts applies the same gate to the graceful kill() primitive.
  • Regression tests in terminal-session-teardown.test.ts and session.test.ts (hand-typed agent foreground → sweep; shell foreground → plain path unchanged).

Why

The daemon gated the descendant sweep on session.launchAgent, which only Orca's explicit agent-launch path sets. A hand-typed claude/codex got root-only teardown on tab close:

  • graceful: SIGHUP to the PTY root only, and the SIGKILL fallback is cancelled the moment the shell exits — the whole agent tree reparents to PID 1 and survives;
  • immediate (POSIX): killpg over the controlling tty misses MCP servers that setsid()'d away.

The leaked sessions still carry agent-ownership evidence, so the Resource Manager's "Kill N orphan terminals" deliberately skips them (#8459 guard) — they're unreclaimable from the UI. The in-process fallback provider already unions launchAgent || startupAgentRecognition before sweeping (local-pty-provider.ts); this brings the daemon path — where real tab closes land — to the same rule, reusing the existing foreground tracker rather than adding a new probe.

Observed on a real workstation: 45 connected daemon sessions vs ~12 visible tabs; ~4GB RSS of leaked claude CLIs plus ~1.2GB of orphaned MCP servers, some alive 5+ days.

Linked Issue

Fixes #16714

Visual Proof

N/A — daemon process-teardown change with no UI or interaction change. Verifiable via ps/orca terminal list before/after closing a tab running a hand-typed claude (steps below).

Testing

  • Automated: pnpm test src/main/daemon — 141 files / 1655 tests pass, including new regression tests for the hand-typed-agent sweep (graceful + immediate) and the unchanged plain-shell path. pnpm tc:node and oxlint clean.

  • Manual repro for reviewers (macOS): open a plain terminal tab, run claude (with MCP servers configured), close the tab, then check ps aux | grep -E 'claude|mcp' — before this change the tree survives; after, it is swept.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

AI Disclosure

Implemented with Claude Code (Fable 5); diagnosis, fix, and tests reviewed by the submitter.

Review

Ready for review — no open findings; CodeRabbit reported no actionable comments (merge risk: minimal). The remaining docstring-coverage warning is the generic threshold check, consistent with prior PRs.

Agent skill upstream boundary

N/A — daemon teardown change only; no agent skill files touched.

@coderabbitai

coderabbitai Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b387fc73-9dff-4c37-b21d-a86ab0222eb4

📥 Commits

Reviewing files that changed from the base of the PR and between d607a63 and b5b6655.

📒 Files selected for processing (5)
  • src/main/daemon/agent-teardown-evidence.ts
  • src/main/daemon/session-termination-controller.ts
  • src/main/daemon/session.test.ts
  • src/main/daemon/terminal-session-teardown.test.ts
  • src/main/daemon/terminal-session-teardown.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • src/main/daemon/agent-teardown-evidence.ts
  • src/main/daemon/session.test.ts
  • src/main/daemon/terminal-session-teardown.ts
  • src/main/daemon/terminal-session-teardown.test.ts
  • src/main/daemon/session-termination-controller.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.


📝 Walkthrough

Walkthrough

The change adds hasAgentTeardownEvidence, which detects launched agents and recognized foreground agent processes. Session termination now uses this helper to choose direct killing or descendant sweeping. Terminal session teardown applies the agent path to hand-typed claude processes without launch-agent metadata. Tests cover zsh, claude, graceful termination, immediate termination, and default foreground-process behavior.

Merge Risk: ⚪ Minimal · up to b5b66

This change extends terminal cleanup to hand-typed agent sessions while preserving the existing shell teardown path; no actionable merge-blocking risk remains beyond normal checks and review.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 5 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary change: descendant sweeping for hand-typed agent sessions during terminal teardown.
Description check ✅ Passed The description covers the required core sections, including ELI5, changes, rationale, linked issue, visual proof, testing, AI disclosure, and review context. The omitted Notes and Checklist sections …
Linked Issues check ✅ Passed The implementation satisfies issue #16714 by detecting hand-typed foreground agents, routing both graceful and immediate teardown through descendant sweeping, and preserving the plain-shell path. Regr…
Out of Scope Changes check ✅ Passed All changes are limited to agent teardown evidence, daemon termination routing, and regression tests for the linked issue. No unrelated code changes are described.
Full details: Description check

Explanation

The description covers the required core sections, including ELI5, changes, rationale, linked issue, visual proof, testing, AI disclosure, and review context. The omitted Notes and Checklist sections are non-critical because their relevant concerns are addressed elsewhere.

Full details: Linked Issues check

Explanation

The implementation satisfies issue #16714 by detecting hand-typed foreground agents, routing both graceful and immediate teardown through descendant sweeping, and preserving the plain-shell path. Regression tests cover the required agent and shell behaviors.

  • Fix all pre-merge checks with AI

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.

@nwparker

Copy link
Copy Markdown
Contributor

I independently reproduced the related #17276 failure on macOS before changing code: non-interactive zsh returned an empty jobs -p, printed cleanup success, and left a background child alive with PPID 1. I then implemented and tested the bounded hand-typed-agent descendant teardown locally; the behavior matches this PR across the same five daemon paths.

I linked #17276 to this PR instead of opening a duplicate. The branch is substantially behind current main, so a rebase is advisable before merge; the descendant-sweep behavior itself remains the needed fix.

…essions

Daemon teardown gated the descendant sweep on launchAgent, which is only set
by Orca's explicit agent-launch path. A claude/codex the user typed into a
plain shell got root-only teardown on tab close, so its detached MCP children
(and on the graceful path the whole agent tree) survived as orphans invisible
to the orphan reaper.

Gate the sweep on teardown evidence instead: launchAgent OR a recognized
agent in the live foreground, reusing the foreground tracker that already
resolves agents under wrappers. Mirrors the in-process provider's
launchAgent-or-recognition union.
@PeaceTis
PeaceTis force-pushed the fix/daemon-plain-shell-agent-teardown branch from 06027cb to b5b6655 Compare August 30, 2026 12:43
@PeaceTis

Copy link
Copy Markdown
Author

Thanks for reproducing this independently — good to have the macOS behavior confirmed on a second machine.

Rebase: agreed, and done. The branch was 264 commits behind; it rebases onto current main with zero conflicts — none of the five files has any churn on main since the fork point. On the rebased head: typecheck:node clean, vitest run src/main/daemon → 147 files / 1699 tests pass.

On #17276 — I'd keep it separate from this PR. I don't think this change reaches that population, and I'd rather the issue not read as covered here.

Every path this PR touches routes into killWithDescendantSweep(session.pid, …), whose target set comes from captureDescendantSnapshot — a ppid walk rooted at the live PTY root. Its own docstring states the limit:

once the root dies, surviving descendants reparent to pid 1 and can no longer be found by a ppid walk

#17276 reports its 37 yes processes already at PPID 1 while the tab was still open — orphaned at each completed tool call, not at teardown. A row whose ppid is 1 never enters childrenByPpid under the root, so it is never in descendants and never signalled: not on graceful teardown, not on immediate teardown, not on a tab close hours later. (rootPgid is captured, but only as an identity guard before the delayed SIGKILL — it never widens the target set.)

Where this PR does help a #17276-shaped leak is the case where the escaped child is still transitively parented to the PTY root: that now gets swept on tab close for a hand-typed agent, which it didn't before. But the failure #17276 actually reports sits outside the ppid walk by construction, and its ask — provenance for descendants that escape mid-session, visibility on high-resource survivors, and termination on stop/cancel/timeout rather than only on close — needs containment this doesn't provide (a per-session pgid or job object the children can't leave, or a recorded ownership tag). That's a materially bigger change than this teardown gate, so I'd rather land #16714's fix here and take #17276 as a follow-up.

For triage: this PR still declares only Fixes #16714; the #17276 link is a cross-reference, so merging won't auto-close it. Flagging so it doesn't get swept up.

@coderabbitai

coderabbitai Bot commented Aug 30, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@greptile-apps

greptile-apps Bot commented Aug 30, 2026

Copy link
Copy Markdown

Greptile Summary

The PR broadens daemon terminal teardown so sessions with either launch metadata or a recognized foreground agent receive the existing descendant sweep.

  • Adds a shared agent-teardown evidence predicate.
  • Applies the predicate to tab-close teardown and the session termination controller.
  • Adds regression coverage for hand-typed agents and unchanged plain-shell behavior.

Confidence Score: 5/5

The PR appears safe to merge, with no concrete changed-code failure identified.

The new classification gate reuses guarded descendant termination, preserves the plain-shell path when no agent is recognized, and is covered across both termination entry points.

Important Files Changed

Filename Overview
src/main/daemon/agent-teardown-evidence.ts Adds the shared predicate that combines explicit launch metadata with foreground-process recognition.
src/main/daemon/session-termination-controller.ts Routes graceful termination through the existing descendant sweep when agent evidence is present.
src/main/daemon/terminal-session-teardown.ts Applies the same evidence gate to graceful and immediate daemon session teardown.
src/main/daemon/session.test.ts Covers recognized foreground agents and verifies ordinary shell termination remains on the plain path.
src/main/daemon/terminal-session-teardown.test.ts Covers graceful and immediate teardown of hand-typed foreground agents without launch metadata.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Terminal teardown requested] --> B{Launch metadata or recognized foreground agent?}
  B -->|Yes| C[Snapshot and terminate descendants]
  C --> D[Signal or force-kill PTY root]
  B -->|No| E[Use plain-shell teardown path]
Loading

Reviews (1): Last reviewed commit: "fix(terminal): sweep descendants when te..." | Re-trigger Greptile

@nwparker

Copy link
Copy Markdown
Contributor

Thanks @PeaceTis for the detailed write-up and the leak measurements! This is now fixed on main by #33317 (9b23bd6), which closed #16714. The daemon no longer decides on session.launchAgent: on macOS and Linux every close, graceful or immediate, snapshots the shell's descendant tree and sweeps it (leaving only deliberate nohup/disown jobs), so a hand-typed claude/codex and its detached MCP servers are cleaned up when the tab closes. It also avoids gating on the foreground process name, because Claude Code's macOS process title is its version string and isn't reliably recognized. If you still see leaked agent trees after closing a tab on the latest build, please comment or reopen and we'll dig in.

@nwparker nwparker closed this Oct 26, 2026
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

2 participants