Skip to content

fix(pty): stop detached OMP tools on immediate terminal close - #20642

Merged
nwparker merged 5 commits into
mainfrom
nwparker/omp-close-lifecycle
Sep 18, 2026
Merged

nwparker merged 5 commits into
mainfrom
nwparker/omp-close-lifecycle

Conversation

@nwparker

@nwparker nwparker commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 48 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​448 $\color{#cf222e}{\Huge{\mathbf{−}}}$​46 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​402
Prod 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​16 $\color{#cf222e}{\Huge{\mathbf{−}}}$​33 $\color{#cf222e}{\Huge{\mathbf{−}}}$​17

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 120 survived 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:

  • Two new local/daemon regressions failed before the fix. The actual external-tool probe also fails on source base 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).
  • Real installed OMP, isolated disposable homes and real PTYs: recognized and typed launches with detached /bin/sleep exit 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.
  • Node typecheck, changed-code quality, formatting and lint checked locally.
  • Mock subprocess tests explicitly isolate descendant cleanup so fabricated PIDs never reach the host process table or signals. Session-reaping coverage verifies sweep completion precedes force-kill and the session persists until physical exit.
  • Independent review approved the production fix and the test-only follow-up at 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: true is the normal renderer tab close — src/main/ipc/pty/ipc/renderer-kill.ts:85 and src/main/ipc/pty/runtime/kill.ts:286 — not a path reserved for agent tooling. This PR deletes the win32 gate in terminal-session-teardown.ts and widens local-pty-termination.ts from ptyAgentSessionIds.has(id) to ptyAgentSessionIds.has(id) || operation.immediate, so on POSIX every tab close now sweeps the shell's still-parented descendant tree.

The delta is precise: forceKillPosixPtyProcessGroups signalled 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 scan src/main/pty/posix-pty-process-groups.ts:34-35 deliberately 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-ps spawn floor, so roughly 40-50 ms added per immediate close, coalesced across same-turn bursts by createProcessTableSnapshotReader. DESCENDANT_SNAPSHOT_TIMEOUT_MS = 1_000 is a bound, not a typical cost.

3. Open residual: duplicated test mock

src/main/daemon/mock-descendant-sweep.ts and #20645's src/relay/mock-descendant-sweep.ts are 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.ts if either grows.

Boundary audit — clean

Traced against docs/reference/ssh-execution-boundary.md:

  • readProcessTableBeforeDeadline returns null on ps error or timeout → sweep skipped, root-only kill.
  • Absent or duplicate root → collectDescendantRows bails with { rootPgid: null, descendants: [] } (pty-descendant-termination.ts:192-194).
  • The delayed SIGKILL requires a fresh table, matching startedAt, matching pgid, an unambiguous capture second, and non-duplicate rows.
  • ownsRoot here is this.sessions.get(sessionId) === session && session.isAlive, where isAlive rests on a positive exit event rather than an inferred one.
  • An empty enumeration means "no descendants" → leak, never kill.

Nothing fires on an absence of evidence; no verdict word outside live / unverifiable / exited is introduced. Windows paths are unchanged and still route identity through src/main/windows/windows-process-table.ts, never a forked powershell.exe.

Verification

47 test files, 501 passed, 1 skipped. Mutation-verified: reverting terminal-session-teardown.ts and local-pty-termination.ts alone 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 lowers EXPECTED_MINIMUM_SITES 5→4, and #20645 adds a site back.

@nwparker
nwparker marked this pull request as ready for review September 14, 2026 15:42
@coderabbitai

coderabbitai Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 316994e5-8537-447d-a7f2-d975fa5bc22e

📥 Commits

Reviewing files that changed from the base of the PR and between ea5fa7d and 71743b9.

📒 Files selected for processing (2)
  • src/main/ipc/pty-listener-teardown-and-orphans.test.ts
  • tests/tools/omp-close-lifecycle.test.mjs
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/tools/omp-close-lifecycle.test.mjs
  • src/main/ipc/pty-listener-teardown-and-orphans.test.ts

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


📝 Walkthrough

Walkthrough

Immediate 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 71743

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 50 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly describes the main change: preventing detached OMP tools from surviving immediate terminal closure.
Description check ✅ Passed The description provides a clear user-facing explanation, implementation details, rationale, linked issue reference, testing evidence, platform limitations, review findings, and visual-change clarific…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: dd767920-8643-46f6-8a7a-74fbde586810

📥 Commits

Reviewing files that changed from the base of the PR and between 93c3702 and ea5fa7d.

📒 Files selected for processing (51)
  • src/main/daemon/daemon-audit-eligibility-event.test.ts
  • src/main/daemon/daemon-authenticated-client-activity.test.ts
  • src/main/daemon/daemon-endpoint-ownership.test.ts
  • src/main/daemon/daemon-health.test.ts
  • src/main/daemon/daemon-idle-shutdown.test.ts
  • src/main/daemon/daemon-preflight-client-replacement.test.ts
  • src/main/daemon/daemon-pty-adapter-cold-restore-reanchor.test.ts
  • src/main/daemon/daemon-pty-adapter-cold-restore-seed.test.ts
  • src/main/daemon/daemon-pty-adapter-concurrent-recovery.test.ts
  • src/main/daemon/daemon-pty-adapter-daemon-recovery.test.ts
  • src/main/daemon/daemon-pty-adapter-history-checkpoints.test.ts
  • src/main/daemon/daemon-pty-adapter-history-recovery.test.ts
  • src/main/daemon/daemon-pty-adapter-inventory-respawn.test.ts
  • src/main/daemon/daemon-pty-adapter-protocol-compatibility.test.ts
  • src/main/daemon/daemon-pty-adapter-session-adoption.test.ts
  • src/main/daemon/daemon-pty-adapter.test.ts
  • src/main/daemon/daemon-pty-router-history-handoff.test.ts
  • src/main/daemon/daemon-pty-upgrade-adoption.test.ts
  • src/main/daemon/daemon-reattach-checkpoint-isolation.test.ts
  • src/main/daemon/daemon-restore-scrollback-depth.test.ts
  • src/main/daemon/daemon-self-retirement-respawn.test.ts
  • src/main/daemon/daemon-server-async-spawn-cancellation.test.ts
  • src/main/daemon/daemon-server-attach-only.test.ts
  • src/main/daemon/daemon-server-attachment-lifecycle.test.ts
  • src/main/daemon/daemon-server-error-handling.test.ts
  • src/main/daemon/daemon-server-kill-attribution.test.ts
  • src/main/daemon/daemon-server.test.ts
  • src/main/daemon/daemon-session-scrollback-window.test.ts
  • src/main/daemon/daemon-shutdown-final-checkpoint-caller-deadline.test.ts
  • src/main/daemon/daemon-stream-droppability-lifecycle.test.ts
  • src/main/daemon/daemon-transport-attachment-release.test.ts
  • src/main/daemon/issue-6814-daemon-failure-classification.test.ts
  • src/main/daemon/mock-descendant-sweep.ts
  • src/main/daemon/reattach-snapshot.test.ts
  • src/main/daemon/slow-daemon-session-verification.test.ts
  • src/main/daemon/terminal-host-agent-session.test.ts
  • src/main/daemon/terminal-host-attach-only.test.ts
  • src/main/daemon/terminal-host-process-inspection.test.ts
  • src/main/daemon/terminal-host-readiness-reporting.test.ts
  • src/main/daemon/terminal-host-session-reaping-leak.test.ts
  • src/main/daemon/terminal-host-startup.test.ts
  • src/main/daemon/terminal-host-wsl-context.test.ts
  • src/main/daemon/terminal-session-teardown.test.ts
  • src/main/daemon/terminal-session-teardown.ts
  • src/main/ipc/pty-listener-teardown-and-orphans.test.ts
  • src/main/providers/local-pty-provider-shutdown.test.ts
  • src/main/providers/local-pty-termination.ts
  • src/main/pty-descendant-termination-job-coverage.test.ts
  • src/main/runtime/remote-agent-session-host-authority.integration.test.ts
  • tests/tools/omp-close-lifecycle.md
  • tests/tools/omp-close-lifecycle.test.mjs

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

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

  • POSIX plain-shell immediate close now sweeps descendants (daemon). forceKillPlainShellSession drops its win32 guard: 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). shutdownTrackedPty broadens its condition to ptyAgentSessionIds.has(id) || operation.immediate, collapsing the old agent and win32 && immediate branches 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.ts substitutes a no-op killWithDescendantSweep and 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/sleep through production local and daemon teardown, skipped unless ORCA_OMP_PROBE_BINARY is 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?

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@nwparker

Copy link
Copy Markdown
Contributor Author

Risk-reduction review at 71743b958fb3428868af231b2a150882f8707990: Medium.

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.

@pullfrog pullfrog 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.

✅ 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.ts moves expect(killSpy).not.toHaveBeenCalled() and the disposable-dispose checks after await vi.waitFor(() => expect(finishSnapshot).toBeTypeOf('function')), so they only run once the kill handler is provably blocked on the snapshot execFile — addressing the prior CodeRabbit thread rather than letting them pass vacuously.
  • Opt-in OMP probe rejects inconclusive ps results. ownedPidRows in tests/tools/omp-close-lifecycle.test.mjs now asserts timedOut === false, signal === null, empty stderr, 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.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@nwparker

Copy link
Copy Markdown
Contributor Author

Deeper risk challenge at 71743b958fb3428868af231b2a150882f8707990: hold for exit-ordering correction. Production TerminalSessionTeardown plus real killWithDescendantSweep, with only process-table capture and signaling controlled, passes the live-root case but leaves the captured child unsignaled when the root exits/is reaped during capture (1 pass / 1 fail). This is the same underlying limitation found on the relay path, now demonstrated through the newly expanded POSIX plain-shell teardown path. Prior actual OMP happy-path passes remain valid. Dropping the ownership guard would introduce PID-reuse risk; no speculative production change made.

@nwparker
nwparker merged commit 691d969 into main Sep 18, 2026
33 checks passed
Jinwoo-H added a commit that referenced this pull request Sep 18, 2026
…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
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
…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
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
…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
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.

1 participant