Skip to content

fix(pty): signal an agent process group before force-killing a closed terminal - #24314

Closed
innocarpe wants to merge 6 commits into
stablyai:mainfrom
innocarpe:fix-23865-session-end-on-close
Closed

innocarpe wants to merge 6 commits into
stablyai:mainfrom
innocarpe:fix-23865-session-end-on-close

Conversation

@innocarpe

Copy link
Copy Markdown
Contributor

Description

Closing a terminal from Orca sent SIGKILL to the PTY process groups. Claude Code's SessionEnd hooks run on SIGTERM or SIGHUP, so an Orca close skipped them. /exit still ran the hooks. On macOS the PTY root is login, so a signal to that pid does not reach the agent in the foreground group.

Focused fix

  • In scope: an immediate close of an agent session signals the POSIX process groups with SIGTERM, waits up to 2 seconds taken out of the existing physical-exit budget, then SIGKILL if the process is still alive.
  • Out of scope: plain-shell closes, Windows/ConPTY, the in-process local provider, and any increase of the close timeouts.

Preserves

  • A process that exits during the grace is not force-killed.
  • A process that is still alive is still SIGKILLed, and the two waits together stay inside the caller's timeout.
  • Handles without group signals, including Windows, keep the direct force-kill.
  • forceKill itself does not wait, so worktree removal's fail-closed path is unchanged.

Evidence

  • Test: node node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/daemon/session-termination-controller.test.ts src/main/daemon/terminal-session-teardown.test.ts src/main/runtime/terminal-close-slow-agent-exit.test.ts
  • 25 passed.
  • Not run against a live Claude session, and not run on Windows.

User-regression-tradeoffs

  • An agent terminal close can take up to two extra seconds before SIGKILL, inside the budget that close already had. Plain shells are unchanged.

Fixes #23865

@greptile-apps

greptile-apps Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 5/5

[High risk] Changes process termination logic for agent sessions.

The PR appears safe to merge; no new actionable issue or outstanding previous finding remains.

Summary

This PR gives immediate POSIX agent-terminal closes a SIGTERM grace period before force-kill, while retaining direct force-kill for unsupported handles and Windows. The latest change extends the post-exit process-group lookup to match Linux and BusyBox terminal names, addressing the remaining previous finding.

Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Immediate agent close] --> B[SIGTERM to PTY process groups]
  B --> C{PTY root exits during grace?}
  C -->|Yes| D[Recheck groups on the terminal]
  D --> E[SIGKILL remaining remembered groups]
  C -->|No| F[Force-kill within remaining timeout]
Loading

Reviews (6) · Last reviewed commit: "fix(pty): match the tty names ps prints ..."

@coderabbitai

coderabbitai Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

  • Last reviewed commit: bd879f6f5540488b98543e7ea2e16a1dd862ac26
  • Latest commit, not reviewed: e07f4d5

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

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: a787f307-134b-4f04-a942-2aacf3b08ff4

📥 Commits

Reviewing files that changed from the base of the PR and between babdabc20269e16cbdba94ad7900adb2b29d3cc2 and bd879f6f5540488b98543e7ea2e16a1dd862ac26.

📒 Files selected for processing (3)
  • src/main/pty/posix-process-groups-on-terminal.ts
  • src/main/pty/posix-pty-process-groups.test.ts
  • src/main/pty/posix-pty-process-groups.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.

📝 Walkthrough

The change adds process-group discovery and signaling to POSIX PTY subprocess handles. A new termination operation sends SIGTERM, waits within a timeout budget, and then force-kills if the root remains alive. Immediate teardown uses this operation for login-agent sessions. Plain-shell teardown continues to use force-kill. Tests cover process-group discovery, post-exit signaling, termination timing, fallback behavior, platform handling, and teardown paths.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to bd879

The termination changes address the previously identified timeout and cross-platform test issues. No actionable merge-blocking risk remains after normal checks.

Security architecture risk: 🟡 Moderate · up to bd879

Signal targets remain constrained to the session’s terminal, and unsupported platforms retain their existing behavior. However, successful root exit does not establish that shutdown-created process groups have stopped. This creates a failure-containment risk during the new graceful shutdown window.

Retained concerns

  • Medium · reliability · inferred: The new SIGTERM window can create process groups outside both cleanup captures. Immediate teardown captures and verifies descendants before signaling the root’s terminal groups; the handle then remembers only groups successfully signaled at that moment. If shutdown handling creates another group and the root exits, post-root cleanup excludes that new group and completion follows root exit without verifying its termination. Cleanup failures are also logged rather than propagated. Previously captured descendant verification is important counterevidence, but it does not cover processes created afterward. This can leave session-associated execution running after close, weakening failure containment.
Security review details

Security Blast Radius

  • inferred — The identified exposure is continued execution associated with a closing POSIX agent session, rather than a demonstrated cross-tenant or cross-service privilege expansion. Surviving processes could retain their existing access; credential contents and deployment-wide exposure were not established.

Security Findings and Attack Paths

  • inferred — A process handling the newly delivered SIGTERM can create another process group after descendant capture. If the root then exits, the remembered-group intersection excludes that new group. This is a source-supported cleanup escape condition, not a demonstrated exploit or evidence of additional privileges.

Trust Boundaries and Controls

  • observed — The saved terminal path originates from the internal PTY handle. Terminal queries reject unsafe names, use explicit process arguments, and return unavailable on query failure. Fresh terminal membership limits reuse of remembered group IDs; unreadable membership suppresses signaling rather than broadening its authority.

Resilience and Maintainability Implications

  • observed — Termination is synchronously claimed, paused producers are resumed, teardown operations are tracked by session ID, and direct force-kill is guarded against repetition. Existing descendant shutdown requires identity before signaling. These controls reduce stale-target and repeated-close hazards, but do not extend the captured set to shutdown-created processes.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 8.70% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 23 functions across 12 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 identifies the main change: signaling an agent process group before force-killing a closed terminal.
Description check ✅ Passed The description explains the problem, scope, behavior change, compatibility decisions, testing evidence, and linked issue. It does not use the required template headings and omits explicit entries for…
Linked Issues check ✅ Passed The changes meet the coding requirements in [#23865]. Agent-session teardown sends SIGTERM to POSIX process groups, waits within the existing close budget for up to 2 seconds, and escalates to `SIGK…
Out of Scope Changes check ✅ Passed The changes remain within [#23865]. The subprocess API, POSIX process-group discovery, bounded termination controller, teardown integration, and tests directly support explicit agent-session closes an…
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.

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.

@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

  • SessionTerminationController.signalGroupsThenForceKillWithinBudget — SIGTERMs the PTY's POSIX process groups, waits a 2s grace clipped to timeoutMs, then SIGKILLs and waits the remaining budget; cancels the 5s graceful fallback first. Windows / handles without signalProcessGroups keep the direct force-kill.
  • SubprocessHandle.signalProcessGroups? — new optional handle method; createDaemonPtySubprocessHandle no-ops when dead/win32 and otherwise delegates to signalPosixPtyProcessGroups with a root-pid fallback.
  • TerminalSessionTeardown — the three immediate agent paths (initial root kill, late requestImmediate escalation, already-terminating escalation) route through the new method; plain shells keep forceKillAndWaitForExit.
  • Tests — new session-termination-controller.test.ts suite, updated teardown assertions, and a signalProcessGroups stub added to the shared adapter harness.

The reported trigger is the immediate path (closeTerminal → stopExplicitlyClosedTabPtys → stopAndWait → daemon kill { immediate: true }), so the fix lands where the hooks were being skipped. I confirmed the total close ceiling is unchanged — grace and the post-SIGKILL wait together stay within timeoutMs (default 8s), which keeps IMMEDIATE_KILL_REPLY_BUDGET_MS and the runtime stop deadline valid. I also ran the changed controller/teardown tests, terminal-host.test.ts, the session-adoption suite, and the existing slow-exit budget test: all pass.

ℹ️ Verification and residual scope

The unit tests pin signal ordering, but the fix was not exercised against a live Claude session (so the actual SessionEnd firing is unverified) nor on Windows — the author called both out in the PR body. Separately, only the immediate path is changed: the graceful fallback used when an immediate stop fails to confirm (killPtyFromRuntimeController with immediate: false, reached via stopExplicitlyClosedTabPtys line 52) still sends the root-only signal, so a hook would be skipped on that narrow path. Neither blocks this PR; noting them so the scope is explicit.

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

@innocarpe
innocarpe force-pushed the fix-23865-session-end-on-close branch from 790650b to 6f16c92 Compare October 1, 2026 09:14
@innocarpe

Copy link
Copy Markdown
Contributor Author

Sync update (6f16c9268b)

Address review: a root that exits during the SIGTERM grace still gets a process-group SIGKILL, so children that ignored SIGTERM do not survive the close.

@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: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: f0f4993e-4c7c-42ab-b780-8fd72a597d51

📥 Commits

Reviewing files that changed from the base of the PR and between 790650b486ca68dbc9776b87be0bc219f977e060 and 6f16c9268b83e1e4a223463c70e7ec0d11f321e1.

📒 Files selected for processing (2)
  • src/main/daemon/session-termination-controller.test.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; 5 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.

Important

The new commit's post-root-exit SIGKILL escalation never reaches the OS — it is dropped by the daemon handle's dead guard before any signal is sent.

Reviewed changes (delta since the prior pullfrog review at 790650b)

  • Added killRemainingProcessGroups to SessionTerminationController, escalating to a group SIGKILL on every branch where the root has already exited (right after SIGTERM, after a successful grace wait, and after the grace catch).
  • Reworked the controller tests to assert the post-exit SIGKILL ordering, replacing the earlier "does not force-kill when the process exits during the grace" case.

The idea is sound — a shell that dies on SIGTERM while a child group ignores it should still get a group SIGKILL — but as written the escalation is inert on POSIX. Detailed below.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@innocarpe
innocarpe force-pushed the fix-23865-session-end-on-close branch from 6f16c92 to 95efbd0 Compare October 1, 2026 11:02
@innocarpe

Copy link
Copy Markdown
Contributor Author

Sync update (95efbd0bbb)

The post-exit SIGKILL now signals the process groups captured while the root still owned the PTY. Root exit marks the handle dead before listeners run, so looking that pid up again never reached the OS. A rejected force-kill retry also stays inside the caller's remaining close budget. POSIX tests pin linux, so the SIGTERM sequence does not depend on the host platform.

@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

The delta since the prior pullfrog review at 6f16c92 is commit 95efbd0, which closes the one open finding from that review.

  • Post-exit group SIGKILL now reaches the OS — createDaemonPtySubprocessHandle.signalProcessGroups captures the pgids it signals during the pre-exit SIGTERM and, once the root has exited (dead), replays process.kill(-pgid, signal) against those captured ids instead of returning early or re-resolving the reaped root. session-termination-controller.test.ts is pinned to a POSIX platform so the group-signal cases run on Windows CI too.
  • Force-kill retry bounded by the caller's budget — requestForceKillWithRetry now takes an optional remaining-budget and clips (or skips) its retry wait to it, so a failing forceKill() cannot overrun timeoutMs after the grace has already consumed it. The no-arg path used by forceKillAndWaitForExit is unchanged.
  • New coverage — subprocess-handle-group-signal.test.ts asserts the captured groups receive SIGKILL after exit (and that no root lookup happens when nothing was captured); a retry-budget case was added to the controller suite.

I confirmed the new capture wiring against the real signalPosixPtyProcessGroups (its deps.signalProcessGroup seam is genuinely invoked), re-ran the changed suites (controller 9, teardown 14, group-signal 2 — 25 passed) plus the slow-exit/pty-subprocess regression suites (39 passed), and linted the changed files clean.

ℹ️ Notes on residual scope

Two carry-forward items that do not block this PR: no live-Claude or Windows verification (author-disclosed — the unit tests pin signal ordering only), and the graceful (non-immediate) agent teardown path still root-signals only, so a hook could be skipped there. Both were noted in the prior review and remain out of scope here.

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

@innocarpe
innocarpe force-pushed the fix-23865-session-end-on-close branch from 95efbd0 to babdabc Compare October 1, 2026 11:17
@innocarpe

Copy link
Copy Markdown
Contributor Author

Sync update (babdabc202)

The close-time SIGKILL now signals a remembered process group only when a fresh process table still lists that group on this PTY. A group id reused after the root exits is left alone. If the table cannot be read, nothing is signaled.

@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

The delta since the prior pullfrog review at 95efbd0 is commit babdabc, which closes the one open concern Greptile raised.

  • Post-root-exit group SIGKILL now checks tty ownership — signalRememberedProcessGroups re-reads the groups still on the PTY through the new readPosixProcessGroupsOnTerminal and only killpgs a remembered id that still appears, so a pgid recycled after the root exited can no longer be signaled.
  • New helper — readPosixProcessGroupsOnTerminal runs ps -t <slave path> -o pgid= behind an isSafeTerminalName guard; it returns null when the name is unsafe or the table is unreadable so the caller fails closed.
  • Coverage — new subprocess-handle cases assert that a group that left the PTY and an unreadable table both skip the SIGKILL, plus three readPosixProcessGroupsOnTerminal cases.

I verified that the full path form node-pty reports (/dev/ttysNNN) is accepted by macOS ps -t (addelem_tty in Apple adv_cmds/ps/ps.c; FreeBSD ps(1) man page), so the guard does not silently no-op on this PR's primary platform, and re-ran the changed suites (57 passed).

ℹ️ Residual scope

The guard replaces the previous unconditional replay with a tty-ownership check, so the post-exit group SIGKILL is now best-effort: if ps -t fails or the group has left the tty, the leftover group is not swept and killRemainingProcessGroups returns without another enforcement step. This is the correct direction — it removes the recycled-pgid hazard — and the case is rare, so it does not block. Flagging only so the behavior is explicit.

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

@innocarpe

Copy link
Copy Markdown
Contributor Author

Sync update (cd34afe858)

When ps rejects -t, the terminal group lookup now reads the full process table and keeps the groups whose tty matches that terminal. A child that ignored SIGTERM is still SIGKILLed after the root exits, instead of the failed lookup skipping every remembered group.

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

Important

The full-process-table fallback added by cd34afe cannot match the PTY on any host that triggers it, so on those hosts it returns an empty list and sweeps nothing, while the new test asserts a scenario no real host produces. The primary macOS fix (the direct ps -t path) is unaffected.

Reviewed changes

The delta since the prior pullfrog review at babdabc is commit cd34afe.

  • Extracted the terminal-group reader — readPosixProcessGroupsOnTerminal (plus isSafeTerminalName and parseProcessGroupIds) moved out of posix-pty-process-groups.ts into the new posix-process-groups-on-terminal.ts and re-exported for existing callers.
  • Added a full-process-table fallback — when ps -t <tty> -o pgid= is rejected, readGroupsOnTerminal latches terminalSelectionUnsupported and reads ps -e -o pid,pgid,tty,stat instead, matching rows by terminal name.
  • New coverage — a case asserting the fallback returns the group from a ttys001-form table, plus tests for the unsafe-name and unreadable-table null paths.

I re-ran the changed suites (posix-pty-process-groups 45, subprocess-handle-group-signal 4, session-termination-controller 9, terminal-session-teardown 14 — all pass) and confirmed the extraction preserves the non-fallback behavior.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@innocarpe
innocarpe force-pushed the fix-23865-session-end-on-close branch from cd34afe to bd879f6 Compare October 1, 2026 12:22
@innocarpe

Copy link
Copy Markdown
Contributor Author

Sync update (bd879f6f55)

The full-table fallback now matches the tty text those hosts actually print: pts/N from Linux ps, and major,minor from BusyBox. The shared ps reader lives with that fallback.

@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

The delta since the prior pullfrog review at cd34afe (commits 79d0386 and bd879f6, replayed by the rebase) closes the one open finding — the -t-rejected full-table fallback could not match the tty form any real host emits.

  • Made the full-table fallback match real ps output — terminalNames now also emits the /dev/-relative form (pts/100 for Linux procps) and the BusyBox major,minor form derived from statSync(ptsName).rdev through posixBusyboxTtyName, so the fallback matches both procps and BusyBox instead of returning an empty list.
  • Deduplicated the shared ps helpers — POSIX_PS_ALL_PROCESS_ARGS, posixProcessTableSpec, readPosixProcessTableOutput, and rejectedPosixPsSelector now live once in posix-process-groups-on-terminal.ts and are imported by posix-pty-process-groups.ts; rejectedPosixPsSelector returns the rejected flag ('p' | 't') rather than a boolean.
  • Added fallback coverage — cases for the pts/N and BusyBox major,minor forms, each of which fails without the fix.

I verified the BusyBox column format against upstream source (procps/ps.c func_tty prints %u,%u; libbb/procps.c applies the glibc major/minor split), so the fallback now models a real -t-rejecting host. Re-ran the four changed suites: 74 passed. The primary macOS ps -t path is unchanged.

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

innocarpe and others added 6 commits October 22, 2026 10:37
… terminal

An Orca close sent SIGKILL to the PTY process groups, so Claude SessionEnd
never ran. SIGTERM those groups first and keep the grace inside the existing
physical-exit budget. A process that is still alive is still SIGKILLed.
Plain shells and Windows stay on the direct force-kill.
A shell can die on SIGTERM while a child group ignores it. Treating that root exit as a finished close skipped the group SIGKILL.

Co-authored-by: Cursor <[email protected]>
The root exit marks the handle dead before listeners run, so the
close-time group SIGKILL returned without reaching the OS. Remember
the groups captured with SIGTERM and signal those ids after exit.
A rejected force-kill retry also stays inside the caller's close budget.
A group id captured at SIGTERM can be reused after the root exits.
The close-time SIGKILL now reads the terminal process table and
signals only ids that are still attached. An unreadable table
signals nothing.
Linux ps prints pts/N and BusyBox prints the device major,minor. The full-table fallback compared only the path and its last segment, so those rows never matched and a child that ignored SIGTERM was left running. The shared ps reader now lives with that fallback.
@innocarpe
innocarpe force-pushed the fix-23865-session-end-on-close branch from bd879f6 to e07f4d5 Compare October 22, 2026 01:38
@nwparker

Copy link
Copy Markdown
Contributor

Thanks @innocarpe! On the default daemon backend this was already fixed by #22232 (v1.4.210, SIGTERM + grace before SIGKILL — we confirmed SessionEnd fires on macOS and Linux). The one remaining SIGKILL-first path was the in-process local provider, fixed via #33367 (credited with Co-authored-by). This branch also made agent closes ~2s slower on Linux and conflicts with current main, so closing as superseded.

nwparker added a commit that referenced this pull request Oct 25, 2026
…r close SIGKILLs them (#33367)

Local (in-process) PTY provider: an immediate close now SIGTERMs descendants and waits up to the shutdown grace before SIGKILL (same as the daemon path since #22232), so Claude's SessionEnd hooks run. Refs #23865, #22039. Supersedes #24314.

Co-authored-by: innocarpe <[email protected]>
@nwparker nwparker closed this Oct 25, 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.

[Bug]: Closing a terminal from Orca skips Claude Code's SessionEnd hooks

2 participants