Repository navigation
fix(pty): stop detached OMP tools on immediate terminal close - #20642
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review. 📝 WalkthroughWalkthroughImmediate plain-shell and local PTY shutdowns now run descendant sweeps on all platforms before root termination. Tests cover ownership, termination ordering, deferred sweeps, and login preflight timing. Daemon tests load a shared descendant-sweep mock. A new opt-in OMP lifecycle probe exercises local and daemon shutdown paths and records process cleanup results. Priority: ➖ Normal Merge Risk: ⚪ Minimal · up to Immediate terminal closure retains its teardown claim while descendants are swept and the root is terminated. No concrete unresolved release risk remains. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: dd767920-8643-46f6-8a7a-74fbde586810
📒 Files selected for processing (51)
src/main/daemon/daemon-audit-eligibility-event.test.tssrc/main/daemon/daemon-authenticated-client-activity.test.tssrc/main/daemon/daemon-endpoint-ownership.test.tssrc/main/daemon/daemon-health.test.tssrc/main/daemon/daemon-idle-shutdown.test.tssrc/main/daemon/daemon-preflight-client-replacement.test.tssrc/main/daemon/daemon-pty-adapter-cold-restore-reanchor.test.tssrc/main/daemon/daemon-pty-adapter-cold-restore-seed.test.tssrc/main/daemon/daemon-pty-adapter-concurrent-recovery.test.tssrc/main/daemon/daemon-pty-adapter-daemon-recovery.test.tssrc/main/daemon/daemon-pty-adapter-history-checkpoints.test.tssrc/main/daemon/daemon-pty-adapter-history-recovery.test.tssrc/main/daemon/daemon-pty-adapter-inventory-respawn.test.tssrc/main/daemon/daemon-pty-adapter-protocol-compatibility.test.tssrc/main/daemon/daemon-pty-adapter-session-adoption.test.tssrc/main/daemon/daemon-pty-adapter.test.tssrc/main/daemon/daemon-pty-router-history-handoff.test.tssrc/main/daemon/daemon-pty-upgrade-adoption.test.tssrc/main/daemon/daemon-reattach-checkpoint-isolation.test.tssrc/main/daemon/daemon-restore-scrollback-depth.test.tssrc/main/daemon/daemon-self-retirement-respawn.test.tssrc/main/daemon/daemon-server-async-spawn-cancellation.test.tssrc/main/daemon/daemon-server-attach-only.test.tssrc/main/daemon/daemon-server-attachment-lifecycle.test.tssrc/main/daemon/daemon-server-error-handling.test.tssrc/main/daemon/daemon-server-kill-attribution.test.tssrc/main/daemon/daemon-server.test.tssrc/main/daemon/daemon-session-scrollback-window.test.tssrc/main/daemon/daemon-shutdown-final-checkpoint-caller-deadline.test.tssrc/main/daemon/daemon-stream-droppability-lifecycle.test.tssrc/main/daemon/daemon-transport-attachment-release.test.tssrc/main/daemon/issue-6814-daemon-failure-classification.test.tssrc/main/daemon/mock-descendant-sweep.tssrc/main/daemon/reattach-snapshot.test.tssrc/main/daemon/slow-daemon-session-verification.test.tssrc/main/daemon/terminal-host-agent-session.test.tssrc/main/daemon/terminal-host-attach-only.test.tssrc/main/daemon/terminal-host-process-inspection.test.tssrc/main/daemon/terminal-host-readiness-reporting.test.tssrc/main/daemon/terminal-host-session-reaping-leak.test.tssrc/main/daemon/terminal-host-startup.test.tssrc/main/daemon/terminal-host-wsl-context.test.tssrc/main/daemon/terminal-session-teardown.test.tssrc/main/daemon/terminal-session-teardown.tssrc/main/ipc/pty-listener-teardown-and-orphans.test.tssrc/main/providers/local-pty-provider-shutdown.test.tssrc/main/providers/local-pty-termination.tssrc/main/pty-descendant-termination-job-coverage.test.tssrc/main/runtime/remote-agent-session-host-authority.integration.test.tstests/tools/omp-close-lifecycle.mdtests/tools/omp-close-lifecycle.test.mjs
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- POSIX plain-shell immediate close now sweeps descendants (daemon).
forceKillPlainShellSessiondrops itswin32guard: every immediate plain-shell close claims termination, snapshots descendants through the existing sweep, then force-kills the root (src/main/daemon/terminal-session-teardown.ts:83). - POSIX plain-shell immediate close now sweeps descendants (local provider).
shutdownTrackedPtybroadens its condition toptyAgentSessionIds.has(id) || operation.immediate, collapsing the old agent andwin32 && immediatebranches into one guarded call site (src/main/providers/local-pty-termination.ts:178). - Descendant sweep stubbed for tests. New
src/main/daemon/mock-descendant-sweep.tssubstitutes a no-opkillWithDescendantSweepand is imported first by ~40 daemon/IPC tests so fabricated PIDs never reach the host process table; teardown, provider, reaping-leak, and IPC tests now pin snapshot-before-force-kill ordering (src/main/daemon/terminal-session-teardown.test.ts:64). - Opt-in OMP close probe.
tests/tools/omp-close-lifecycle.{md,test.mjs}drives a real installed OMP plus a detached/bin/sleepthrough production local and daemon teardown, skipped unlessORCA_OMP_PROBE_BINARYis set.
ℹ️ Immediate POSIX close now reaps TTY-detached, still-parented jobs
The sweep reaches any process still parented to the shell, including ones that left the controlling TTY (e.g. setsid) and survived before this change. This is deliberate and documented in the PR description and tests/tools/omp-close-lifecycle.md; flagging it so the expansion is a conscious product call on POSIX. Its practical scope is narrow: forceKillPosixPtyProcessGroups already SIGKILLs every process group on the PTY's TTY, so the sweep only adds children that detached from the TTY while staying parented — double-forked or already-reparented processes remain outside, as the docs note.
Technical details
# Intentional scope of the plain-shell descendant sweep
## Affected sites
- `src/main/daemon/terminal-session-teardown.ts:86` — sweep with a no-op `killRoot`; detached-but-parented children are signalled before `forceKillAndWaitForExit`.
- `src/main/providers/local-pty-termination.ts:180` — same sweep on the local-provider immediate path.
- `src/main/pty/posix-pty-process-groups.ts:90` — pre-existing same-TTY process-group sweep; the new sweep is additive only for processes no longer on that TTY.
## Outcome
- Intended: immediate close leaves no still-parented tool process behind, which is what the #9530 reproduction showed (`sleep` in its own PGID reparented to PID 1).
- Cost: each immediate POSIX close now pays a bounded full `ps -axo` capture (1s deadline / 32 MiB) before the root signal, plus the existing unref'd 2s delayed identity-stable SIGKILL when descendants exist.
## Open question for the human (optional)
- Is terminating still-parented, TTY-detached processes (e.g. a `setsid`/`disown`-style background helper) on every immediate close the intended policy, or should that be opt-in so workspace/keep-alive semantics stay untouched?DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
|
Risk-reduction review at 54 tests; actual OMP with external sleep cleaned up in 4 native macOS cases (recognized/typed × local/daemon). Strengthened sequencing and process-query test assertions, independently reviewed. Remaining user-facing consequence: Immediate close kills all still-parented background jobs, not only OMP tools. No fresh Linux/WSL full-app proof. The follow-up is independently reviewed. Focused local checks passed; CI for this new commit must be assessed separately from the previously green head. |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed the delta since the prior pullfrog review (ea5fa7d..71743b9, one commit, test-only):
- IPC teardown test now waits before asserting.
pty-listener-teardown-and-orphans.test.tsmovesexpect(killSpy).not.toHaveBeenCalled()and the disposable-dispose checks afterawait vi.waitFor(() => expect(finishSnapshot).toBeTypeOf('function')), so they only run once the kill handler is provably blocked on the snapshotexecFile— addressing the prior CodeRabbit thread rather than letting them pass vacuously. - Opt-in OMP probe rejects inconclusive
psresults.ownedPidRowsintests/tools/omp-close-lifecycle.test.mjsnow assertstimedOut === false,signal === null, emptystderr, exit code in[0, 1], and empty stdout on code 1, so a failed/truncated capture can no longer be mistaken for a clean "after" reading.
Verified locally: pty-listener-teardown-and-orphans.test.ts 10 passed, probe skipped without ORCA_OMP_PROBE_BINARY. No production code changed in this delta and no prior pullfrog threads were open.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
|
Deeper risk challenge at |
…ing gate (#21362) #20642 and #20645 added src/main/daemon/mock-descendant-sweep.ts and src/relay/mock-descendant-sweep.ts: test-only side-effect modules whose whole body is one vi.mock, imported by 60 suites so mock PTY PIDs never reach the host process table. Their CI ran before the anti-slop gate landed, so main now fails `oxlint --config config/oxlint-anti-slop.json` on every PR's merge ref. File-scoped exemption, like the others in this config, because the root lint scan does not load the plugin and an inline directive would read back as unused. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
…ai#20642) * test(omp): add opt-in owned PTY closure probe * fix(pty): sweep detached tools on immediate unrecognized shell close * test(omp): create close probe evidence root in fresh worktrees * test(pty): account for asynchronous immediate descendant cleanup * test(pty): reject inconclusive descendant cleanup probes
…ing gate (stablyai#21362) stablyai#20642 and stablyai#20645 added src/main/daemon/mock-descendant-sweep.ts and src/relay/mock-descendant-sweep.ts: test-only side-effect modules whose whole body is one vi.mock, imported by 60 suites so mock PTY PIDs never reach the host process table. Their CI ran before the anti-slop gate landed, so main now fails `oxlint --config config/oxlint-anti-slop.json` on every PR's merge ref. File-scoped exemption, like the others in this config, because the root lint scan does not load the plugin and an inline directive would read back as unused. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

Closing a terminal where OMP was typed into the shell could leave its detached tools running. On macOS with Orca 1.4.202-hourly.202609132311 and OMP 18.1.18,
! /bin/sleep 120survived an actual CLI terminal close after both the shell and OMP exited.Immediate local-provider and daemon close now reuse the existing guarded descendant sweep before killing the shell, even when startup did not recognize an agent. ELI5: closing the terminal now also stops the tools its running programs started, including tools that made their own process group.
This applies to every immediate POSIX shell close, so still-parented intentionally detached jobs that previously survived are also terminated. Graceful plain-shell shutdown and disconnect/keep-alive policy are unchanged. The owning host executes the cleanup; folder workspaces and worktrees share the same path. Direct SSH relay termination is separate and is not covered. Windows keeps its existing guarded job/tree cleanup.
Related to #9530. This reproduces and fixes detached-tool leakage; it does not establish that the original foreground-OMP-survives-for-days report is resolved.
Validation:
93c370246388: the typed-launch sleep PID survives reparented to PID 1, while the recognized-launch control exits. Final daemon, provider, descendant and remote authority suite: 170 files passed, 1,951 tests passed (13 skipped)./bin/sleepexit under both production local and daemon teardown (four cases). No model calls. After-proof exercises backend classes/functions, not a rebuilt installed application's CLI route.ea5fa7dc61c: 196 explicit-close backend tests and four native macOS PTY I/O-failure cases (16 real shell cycles) passed. These overlap the parent suite; counts are not additive.The opt-in reproduction, limitations and bounded snapshot/escalation contract are documented in
tests/tools/omp-close-lifecycle.md. Process reports and terminal transcripts remain local; there is no rendered UI change or screenshot claim.Runtime coverage is macOS only. Linux/Windows/WSL, live paired/SSH hosts, busy model/LSP workers, full app quit and rebuilt-app close routing were not validated. Children already reparented before capture remain outside the sweep; existing same-second PID identity ambiguity limits delayed escalation.
Reliability contract (
terminal-session.explicit-close-retirement): retain the exact PTY owner until physical exit; snapshot still-parented descendants before stopping the root. The existing experimental gate's 196-test backend command and native I/O-cleanup gate passed. Cleanup adds the existing bounded one-second/32-MiB process-table capture and one two-second delayed identity recheck when needed; same-turn captures coalesce. No recurring polling is added. The opt-in reports capture exact PID evidence. Rebuilt-app and remote/runtime platform gaps above remain explicit.CI follow-up: updated the manual-kill IPC test to hold snapshot completion before force-kill and listener reaping; adjusted the structural call-site floor from five to four after consolidating the duplicate local branches. All four sites still require job ownership. The 65-file IPC suite passed 641 tests plus five ownership-coverage tests; the two-file correction independently passed 15 tests.
Review findings — read before merging
1. This changes ordinary tab-close semantics, not only the OMP path (needs sign-off)
immediate: trueis the normal renderer tab close —src/main/ipc/pty/ipc/renderer-kill.ts:85andsrc/main/ipc/pty/runtime/kill.ts:286— not a path reserved for agent tooling. This PR deletes thewin32gate interminal-session-teardown.tsand widenslocal-pty-termination.tsfromptyAgentSessionIds.has(id)toptyAgentSessionIds.has(id) || operation.immediate, so on POSIX every tab close now sweeps the shell's still-parented descendant tree.The delta is precise:
forceKillPosixPtyProcessGroupssignalled process groups attached to the pty's tty. A tool that detached from the controlling terminal but stayed a ppid child of the shell was in neither measurement and survived a tab close. It now dies — the intended fix for detached agent tooling, and also a user's own terminal-detached long-running job, with no gate and no setting.A product decision shipped under a bug-fix title. Wants explicit sign-off, not a code review.
2. Added latency, measured
The sweep runs a whole-host
ps -axo pid=,ppid=,pgid=,lstart=before signalling the root — the scansrc/main/pty/posix-pty-process-groups.ts:34-35deliberately avoids. Measured on a host with 1963 process rows: 60.8 / 62.0 / 63.6 / 64.8 / 69.1 ms against a ~20 ms bare-psspawn floor, so roughly 40-50 ms added per immediate close, coalesced across same-turn bursts bycreateProcessTableSnapshotReader.DESCENDANT_SNAPSHOT_TIMEOUT_MS = 1_000is a bound, not a typical cost.3. Open residual: duplicated test mock
src/main/daemon/mock-descendant-sweep.tsand #20645'ssrc/relay/mock-descendant-sweep.tsare 8 lines each and differ only in a comment and the relative import path. Left as-is deliberately — consolidating means churn across two PRs for a test-only mock. Worth folding into one*.test-mock.tsif either grows.Boundary audit — clean
Traced against
docs/reference/ssh-execution-boundary.md:readProcessTableBeforeDeadlinereturnsnullon ps error or timeout → sweep skipped, root-only kill.collectDescendantRowsbails with{ rootPgid: null, descendants: [] }(pty-descendant-termination.ts:192-194).startedAt, matchingpgid, an unambiguous capture second, and non-duplicate rows.ownsRoothere isthis.sessions.get(sessionId) === session && session.isAlive, whereisAliverests on a positive exit event rather than an inferred one.Nothing fires on an absence of evidence; no verdict word outside
live/unverifiable/exitedis introduced. Windows paths are unchanged and still route identity throughsrc/main/windows/windows-process-table.ts, never a forkedpowershell.exe.Verification
47 test files, 501 passed, 1 skipped. Mutation-verified: reverting
terminal-session-teardown.tsandlocal-pty-termination.tsalone fails 8 tests across 4 files — no inert assertions among the new ones. Changed-code quality gate clean on a current-main merge.Merge constraint: this and #20645 land together or neither. Two genuinely distinct sites — different processes on different hosts — implementing one policy, already sharing the algorithm through
killWithDescendantSweep. Landing one alone leaves local and remote terminals behaving differently on close. This one first: it consolidates the local branch and lowersEXPECTED_MINIMUM_SITES5→4, and #20645 adds a site back.