Skip to content

fix(terminal): kill agent descendant processes on session teardown (STA-1800) - #8706

Merged
brennanb2025 merged 13 commits into
mainfrom
fix/sta-1800-pty-descendant-kill
Jul 15, 2026
Merged

brennanb2025 merged 13 commits into
mainfrom
fix/sta-1800-pty-descendant-kill

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes STA-1800: agent CLIs can launch tool processes in detached process groups, so killing only the PTY shell leaves those descendants orphaned and consuming CPU.

Agent-session teardown now snapshots the POSIX descendant tree before root teardown, sends SIGTERM to captured descendants, and performs a delayed identity-safe SIGKILL of confirmed survivors. Plain user terminals preserve their existing detached-child semantics.

Review hardening through e948efde3 and current-main integration 6fb775b47:

  • Claims daemon/local teardown ownership synchronously so reattach, same-ID respawn, and duplicate kill cannot race an in-flight snapshot.
  • Duplicate daemon kill callers await the exact same teardown Promise, even if the root exits and the session is reaped while capture is pending.
  • Signals captured descendants before root teardown so parent links do not disappear mid-sweep.
  • Bounds both process-table reads at 1 second and gives the production ps child a hard SIGKILL timeout.
  • Coalesces same-turn teardown bursts onto one fresh scan, but never reuses a completed or already-started table as a later caller's signal source. Callers arriving after scan start immediately share one fresh successor, so their deadline is not spent queued and no unusable ps starts after timeout.
  • Carries the timestamp from before the source ps began through the snapshot. Escalation requires matching PID start time and PGID against a fresh bounded reread.
  • Because ps lstart is second-resolution, a process born in the source scan second receives SIGTERM but is intentionally not escalated to SIGKILL.
  • Awaits daemon immediate-kill completion at the request boundary and documents/tests the lifecycle contract.
  • Requires the exact PTY root session/handle to remain live before signalling captured descendants, preventing a natural-exit race from applying a stale snapshot to a recycled root PID.
  • Traverses descendant rows with a visited set and index cursor so cyclic-looking non-atomic tables terminate and wide trees remain linear instead of blocking the Electron main thread.
  • Indexes only requested descendant PIDs during escalation and treats duplicate PID rows as ambiguous rather than signalling them.
  • Caps worktree provider teardown at 32 concurrent sessions, preserving same-batch ps coalescing without unbounded IPC/RPC fan-out.

Screenshots

No visual change.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test equivalent under the repository-required Node 24 runtime — 2,795 files passed; 29,596 tests passed
  • pnpm build — not run standalone; both focused Electron E2E specs ran from a fresh E2E build
  • Added or updated high-quality regression tests

Additional validation:

  • 221/221 focused unit tests across descendant termination, daemon session/host/server, local provider ownership, bounded worktree teardown, and the shared concurrency primitive.
  • pnpm run check:reliability-gates and pnpm run check:max-lines-ratchet.
  • Fresh Electron E2E: the earlier combined descendant-kill and parked-retirement run passed (2/2, 35.6 s); the current-main integrated run passed (1/1, 37.7 s wall, 5.0 s test body); and the final review head passed from a cold full build (1/1, 78 s wall, 4.8 s test body).
  • Interactive Electron validation on this exact branch lineage: a detached-PGID child was alive before closing the marked agent terminal, gone on the first 100 ms poll afterward, the tab disappeared, and Resource Manager changed from 2 terminal sessions to 1 with no renderer errors.
  • Final safe process-table benchmark: 20 simultaneous captures complete in 66.6 ms with one ps. Twenty deliberately sequential captures take 1.14 s because every later request receives fresh signal targets instead of a cached PID table. On Node 24, a synthetic 100,000-wide descendant tree fell from 861 ms to 16.7 ms after replacing front-removal traversal; worktree teardown coalesces within deterministic 32-session batches.

AI Review Report

A multi-pass review focused on lifecycle races, process/PID safety, failure degradation, completion semantics, and kill-path performance.

It flagged async teardown ownership gaps, duplicate cleanup/early acknowledgement, unbounded or wedged ps children, process-table fan-out, root-before-descendant signaling, false certainty from second-resolution lstart, the unsafe possibility of applying a later consumer timestamp to cached process rows, successor scans that could start only after their caller timed out, stale descendant signals after root ownership was lost, cyclic-looking process tables, quadratic queue shifts, full-table escalation indexing, and unbounded provider shutdown fan-out. The follow-up commits fix each issue and add deterministic regression tests for pending-capture reattach, same-ID respawn, duplicate completion sharing after root exit, RPC acknowledgement timing, synchronous/rejected/wedged readers, same-turn coalescing, post-start successor scans, source-scan timestamps, timeout cleanup, PID/PGID revalidation, same-second ambiguity, cyclic rows, duplicate escalation identities, and the 32-session fan-out cap.

Cross-platform compatibility was explicitly checked:

  • macOS/Linux use the fixed-argument POSIX ps path.
  • Windows remains a deliberate no-op in the descendant snapshot module; ConPTY keeps its prior foreground-tree behavior. Windows native-smoke passed on the prior pushed revision and the follow-up does not enter this path on Windows.
  • SSH-hosted PTYs keep their prior behavior; no local-only path assumptions were added to SSH code.
  • No shortcut, shortcut-label, filesystem-path, or UI behavior changed.
  • Electron daemon request routing awaits asynchronous immediate teardown without changing the wire payload.

Security Audit

  • ps is invoked with execFile and fixed arguments, not a shell; no user input is interpolated into a command.
  • Process-table output remains capped, and the subprocess plus caller-facing wait are both bounded.
  • Completed or already-started process tables are never reused as later signal targets.
  • The identity boundary is recorded before the source scan begins. SIGKILL additionally requires matching PID, start-time token, and PGID from a fresh bounded reread; ambiguous same-second identities are never escalated.
  • Signal errors and snapshot failures degrade to the existing root-only teardown rather than blocking the user action.
  • Teardown ownership is claimed before the first await, preventing stale-handle reattachment or duplicate owners; duplicate callers share completion. Descendant signalling additionally requires the exact root owner to remain live after capture.
  • No auth, secrets, dependencies, path parsing, or new externally supplied IPC fields are introduced.

Residual risk: all PPID snapshots are inherently point-in-time. Processes already orphaned by a crash before teardown cannot be recovered by a kill-time tree walk and remain follow-up work.

Notes

  • Windows ConPTY, SSH-hosted PTYs, app-quit killAll, and daemon dispose retain foreground-tree-only teardown for now.
  • Disconnected SSH relay death still needs reconnect-aware provider ownership; daemon owner leases and durable retry inventory remain follow-up hardening.
  • A process born in the source scan second is SIGTERMed but not SIGKILLed because ps cannot prove that a same-second PID was not recycled.
  • Plain user terminals intentionally retain classic nohup-style detached-child behavior; descendant sweeping is agent-session-only.

Linear: STA-1800

…TA-1800)

Agent CLIs spawn tool children in detached process groups that PTY
SIGHUP can never reach. Killing an agent session (tab close, retire,
sleep) left those children running as orphans — eight orphaned git
processes burned ~8 cores for up to 11.5h under the agents-running
keep-awake and drained a battery to 8%.

New pty-descendant-termination module: snapshot the ppid tree BEFORE
signalling (a dead root's descendants reparent to pid 1 and become
unfindable), SIGTERM the root group and every descendant, then after a
2s grace SIGKILL survivors gated on a pid+start-time identity re-check
so a recycled pid is never signalled. Snapshot is bounded and never
rejects; failures degrade to today's shell-only kill.

Wired for agent sessions only (plain terminals keep nohup semantics) at
all three POSIX kill sites: local provider shutdown, daemon
TerminalHost immediate kill (the pty:kill path — force-kill bypassed
Session.kill entirely), and daemon Session graceful kill.

Verified live in the built app: an agent pane with a detached-pgid
child; the child survived on the unwired build (three control runs) and
dies within ~5s with the fix. Windows ConPTY and SSH-hosted PTYs keep
the previous foreground-tree contract (documented follow-ups).
@coderabbitai

coderabbitai Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

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

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
📝 Walkthrough

Walkthrough

Adds timestamped process-table snapshots, descendant traversal, bounded scanning, and identity-checked SIGTERM/SIGKILL escalation. Agent PTY and daemon session teardown now coordinate asynchronous shutdown, prevent reattachment during teardown, coalesce duplicate kills, and support immediate upgrades. Worktree shutdown runs concurrently, while tests, reliability gates, documentation, and an end-to-end scenario cover the updated lifecycle behavior.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 26.32% which is insufficient. The required threshold is 80.00%. 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 summarizes the main change: agent descendant processes are killed during terminal teardown.
Description check ✅ Passed The description follows the template and includes summary, screenshots, testing, AI review, security audit, and notes with cross-platform coverage.

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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/main/providers/local-pty-provider.ts (1)

905-941: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Prevent reattach while async teardown is in flight src/main/providers/local-pty-provider.ts#L905-L941 still waits on the descendant snapshot before marking shutdown in progress, so spawn() can reattach the same PTY during teardown. The immediate launchAgent branch in src/main/daemon/terminal-host.ts#L197-L218 has the same gap before killWithDescendantSweep(). Add a synchronous shutting-down/terminating marker before the await and block reattach/re-entry until teardown finishes.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 1e2e5145-64ac-4611-a0a9-d7da24c11ced

📥 Commits

Reviewing files that changed from the base of the PR and between 59460f7 and 40548e5.

📒 Files selected for processing (9)
  • docs/reference/terminal-session-lifecycle.md
  • src/main/daemon/session.test.ts
  • src/main/daemon/session.ts
  • src/main/daemon/terminal-host.test.ts
  • src/main/daemon/terminal-host.ts
  • src/main/providers/local-pty-provider.ts
  • src/main/pty-descendant-termination.test.ts
  • src/main/pty-descendant-termination.ts
  • tests/e2e/agent-descendant-process-kill.spec.ts

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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: a2a1f998-ad51-4c26-a1a1-bddb04507445

📥 Commits

Reviewing files that changed from the base of the PR and between 40548e5 and d35e215.

📒 Files selected for processing (12)
  • config/reliability-gates.jsonc
  • docs/reference/terminal-session-lifecycle.md
  • src/main/daemon/daemon-server.test.ts
  • src/main/daemon/daemon-server.ts
  • src/main/daemon/session.ts
  • src/main/daemon/terminal-host.test.ts
  • src/main/daemon/terminal-host.ts
  • src/main/daemon/terminal-immediate-kill.ts
  • src/main/providers/local-pty-provider.test.ts
  • src/main/providers/local-pty-provider.ts
  • src/main/pty-descendant-termination.test.ts
  • src/main/pty-descendant-termination.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/daemon/terminal-host.test.ts
  • src/main/providers/local-pty-provider.ts

Comment thread config/reliability-gates.jsonc Resolved
Comment thread src/main/pty-descendant-termination.ts Resolved

@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

🧹 Nitpick comments (1)
src/main/daemon/terminal-agent-teardown.ts (1)

56-82: 🩺 Stability & Availability | 🔵 Trivial

Operation promise can still reject even after teardown succeeds.

killWithDescendantSweep's finally guarantees the callback (the real signalTerminationRoot()/finishImmediate() work) runs before any error from terminateDescendantSnapshot propagates, so the root/descendants are still handled correctly. But operation (== entry.promise, returned all the way up through TerminalHost.kill()) can still reject in that case. Anyone awaiting the returned promise (e.g. a daemon kill RPC handler) would then see a rejection for a teardown that actually completed, and could misreport success as failure.

The internal operation.then(clearOperation, clearOperation) at Line 81 does prevent a Node unhandledRejection here (it's attached to the same promise object), so this isn't a crash risk — it's a correctness/reporting risk for callers of kill()/TerminalHost.kill().

♻️ Suggested normalization
     const operation = Promise.resolve(
       killWithDescendantSweep(session.pid, () => {
         // Why: natural exit reaps the PID while ps is running. Never signal that
         // stale numeric PID after the Session no longer represents a live root.
         if (!session.isAlive) {
           return
         }
         if (entry.immediate) {
           this.finishImmediate(sessionId, session)
         } else {
           session.signalTerminationRoot()
         }
       })
-    )
+    ).catch(() => {
+      // killRoot() above already ran via the sweep's `finally`; a rejection here
+      // means descendant signalling failed, not that the root wasn't handled.
+    })

This depends on whether terminateDescendantSnapshot (prior layer, pty-descendant-termination.ts) can actually throw per-descendant signal errors rather than swallowing them — worth confirming against that file.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 85dc4495-1086-4db0-896f-32f61fc5f446

📥 Commits

Reviewing files that changed from the base of the PR and between d35e215 and 5be7ba6.

📒 Files selected for processing (10)
  • config/reliability-gates.jsonc
  • docs/reference/terminal-session-lifecycle.md
  • src/main/daemon/session.ts
  • src/main/daemon/terminal-agent-teardown.ts
  • src/main/daemon/terminal-host.test.ts
  • src/main/daemon/terminal-host.ts
  • src/main/pty-descendant-termination.test.ts
  • src/main/pty-descendant-termination.ts
  • src/main/runtime/worktree-teardown.test.ts
  • src/main/runtime/worktree-teardown.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/main/daemon/session.ts
  • docs/reference/terminal-session-lifecycle.md
  • src/main/pty-descendant-termination.test.ts
  • config/reliability-gates.jsonc

Comment on lines +75 to +88
const ownedSessions = sessions.filter((session) => session.id.startsWith(prefix))
// Why: agent shutdown snapshots coalesce only when requests begin together;
// serial awaits multiply process-table scans and worktree-delete latency.
await Promise.all(
ownedSessions.map(async (session) => {
try {
await provider.shutdown(session.id, { immediate: true })
clearStoppedPtyState(session.id, onPtyStopped)
} catch {
// Already dead, or the backend dropped the session — treat as success.
}
})
)
return ownedSessions.length

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Inconsistent "stopped" counting between the two sweep helpers.

sweepProviderByPrefix counts a failed shutdown() as stopped (per the "treat as success" comment), but sweepRegistryForWorktree counts a failed shutdown() as not stopped (return 0 in the catch). Same operation, same "already dead" rationale, different semantics for providerStopped vs registryStopped in the returned WorktreeTeardownResult.

🐛 Suggested fix: align semantics with sweepProviderByPrefix
   const entries = listRegisteredPtys().filter((r) => r.worktreeId === worktreeId)
-  const stopped = await Promise.all(
-    entries.map(async (entry) => {
-      try {
-        await localProvider.shutdown(entry.ptyId, { immediate: true })
-        clearStoppedPtyState(entry.ptyId, onPtyStopped)
-        return 1
-      } catch {
-        return 0
-      }
-    })
-  )
-  return stopped.reduce<number>((count, value) => count + value, 0)
+  await Promise.all(
+    entries.map(async (entry) => {
+      try {
+        await localProvider.shutdown(entry.ptyId, { immediate: true })
+        clearStoppedPtyState(entry.ptyId, onPtyStopped)
+      } catch {
+        // Already dead, or the backend dropped the session — treat as success,
+        // matching sweepProviderByPrefix's semantics.
+      }
+    })
+  )
+  return entries.length

Also applies to: 97-108

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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 3d88e96c-d79c-470b-a0f0-6ec7f6b9e788

📥 Commits

Reviewing files that changed from the base of the PR and between d50cbeb and 373f8ff.

📒 Files selected for processing (11)
  • config/reliability-gates.jsonc
  • docs/reference/terminal-session-lifecycle.md
  • src/main/daemon/session.test.ts
  • src/main/daemon/session.ts
  • src/main/daemon/terminal-host.test.ts
  • src/main/daemon/terminal-host.ts
  • src/main/daemon/terminal-session-teardown.ts
  • src/main/providers/local-pty-provider.test.ts
  • src/main/providers/local-pty-provider.ts
  • src/main/pty-descendant-termination.test.ts
  • src/main/pty-descendant-termination.ts
🚧 Files skipped from review as they are similar to previous changes (9)
  • src/main/providers/local-pty-provider.test.ts
  • docs/reference/terminal-session-lifecycle.md
  • src/main/daemon/session.test.ts
  • config/reliability-gates.jsonc
  • src/main/pty-descendant-termination.test.ts
  • src/main/daemon/session.ts
  • src/main/daemon/terminal-session-teardown.ts
  • src/main/daemon/terminal-host.ts
  • src/main/daemon/terminal-host.test.ts

Comment on lines +943 to +945
const descendants = ptyAgentSessionIds.has(id)
? await captureDescendantSnapshot(proc.pid)
: null

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Wrap snapshot capture in a try/catch to guarantee root teardown.

If captureDescendantSnapshot throws (e.g., due to an unexpected system error or resource exhaustion during process table reading), the exception will abort shutdownTrackedPty immediately. This prevents proc.kill() and clearPtyState(id) from running, leaving the agent session orphaned but still tracked in ptyProcesses (which causes subsequent spawns to reattach to the zombie process).

To ensure "snapshot failures degrade to existing root-only teardown" as intended, wrap the capture in a try/catch block so teardown continues regardless.

🛡️ Proposed fix to ensure fallback teardown
-    const descendants = ptyAgentSessionIds.has(id)
-      ? await captureDescendantSnapshot(proc.pid)
-      : null
+    let descendants = null
+    if (ptyAgentSessionIds.has(id)) {
+      try {
+        descendants = await captureDescendantSnapshot(proc.pid)
+      } catch {
+        /* Fallback to root-only teardown on capture failure */
+      }
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const descendants = ptyAgentSessionIds.has(id)
? await captureDescendantSnapshot(proc.pid)
: null
let descendants = null
if (ptyAgentSessionIds.has(id)) {
try {
descendants = await captureDescendantSnapshot(proc.pid)
} catch {
/* Fallback to root-only teardown on capture failure */
}
}

Comment on lines +165 to +173
const descendants: ProcessTableRow[] = []
const queue = [rootPid]
while (queue.length > 0) {
const pid = queue.shift()!
for (const child of childrenByPpid.get(pid) ?? []) {
descendants.push(child)
queue.push(child.pid)
}
}

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.

🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

Prevent infinite loops from cyclic process tables.

A ps snapshot on Linux reads /proc sequentially, meaning the capture is not fully atomic. A rapid PID recycle during the scan can theoretically produce a cyclic process tree (e.g., A -> B -> C -> A's reused PID). Because the BFS queue currently lacks cycle detection, traversing a cyclic graph will infinitely loop and permanently hang the Node.js event loop.

Track visited PIDs to guarantee termination regardless of OS-level process table races.

🔒️ Proposed fix to add cycle detection
   const descendants: ProcessTableRow[] = []
   const queue = [rootPid]
+  const visited = new Set<number>([rootPid])
   while (queue.length > 0) {
     const pid = queue.shift()!
     for (const child of childrenByPpid.get(pid) ?? []) {
-      descendants.push(child)
-      queue.push(child.pid)
+      if (!visited.has(child.pid)) {
+        visited.add(child.pid)
+        descendants.push(child)
+        queue.push(child.pid)
+      }
     }
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const descendants: ProcessTableRow[] = []
const queue = [rootPid]
while (queue.length > 0) {
const pid = queue.shift()!
for (const child of childrenByPpid.get(pid) ?? []) {
descendants.push(child)
queue.push(child.pid)
}
}
const descendants: ProcessTableRow[] = []
const queue = [rootPid]
const visited = new Set<number>([rootPid])
while (queue.length > 0) {
const pid = queue.shift()!
for (const child of childrenByPpid.get(pid) ?? []) {
if (!visited.has(child.pid)) {
visited.add(child.pid)
descendants.push(child)
queue.push(child.pid)
}
}
}
🧰 Tools
🪛 ast-grep (0.44.1)

[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { execFile } from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process-typescript)

@brennanb2025
brennanb2025 merged commit 40d0159 into main Jul 15, 2026
9 of 11 checks passed
brennanb2025 added a commit to bbingz/orca that referenced this pull request Jul 15, 2026
…adopt main's stablyai#8706 for POSIX descendants

Reconciles the fail-closed worktree-teardown fix with main's newly-merged
teardown work so the two compose instead of collide.

Kept (the actual stablyai#8275 fix — Windows batch `worktree rm` killing the shared
daemon and unrelated ConPTY panes):
- fail-closed verified worktree teardown + legacy-daemon verification gate
- worktree PTY admission fence (no spawn races an in-progress deletion)
- Windows ConPTY verified teardown / daemon preservation (retain owner until
  native exit; never double-close ConPTY)
- support glue (owner cache, bounded stop concurrency, teardown timeouts)

Dropped the PR's parallel POSIX relay kill-path rewrite (pty-session-kill /
-membership / -exit-verification): main's stablyai#8706 (pty-descendant-termination)
already reaps detached agent descendants on POSIX, so a second freeze-sweep
engine that ran on every immediate shutdown was redundant, riskier scope.

Integrated instead:
- POSIX agent-descendant reaping comes from stablyai#8706, including inside our verified
  daemon force path (Session.forceKillAndDisposeSubprocessAndWait snapshots +
  terminates descendants before the verified root kill)
- daemon POSIX force-kill is a leader SIGKILL + await-native-exit shim
  (zombie-safe via existing exit waiters); relay POSIX teardown is a plain
  SIGKILL (SSH fail-closed enforced at the runtime liveness layer)

Follow-up: descendant-level POSIX verification for non-agent / pre-reparented
survivors on the delete path (leader-level fail-closed holds today).
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…TA-1800) (stablyai#8706)

* fix(terminal): kill agent descendant processes on session teardown (STA-1800)

Agent CLIs spawn tool children in detached process groups that PTY
SIGHUP can never reach. Killing an agent session (tab close, retire,
sleep) left those children running as orphans — eight orphaned git
processes burned ~8 cores for up to 11.5h under the agents-running
keep-awake and drained a battery to 8%.

New pty-descendant-termination module: snapshot the ppid tree BEFORE
signalling (a dead root's descendants reparent to pid 1 and become
unfindable), SIGTERM the root group and every descendant, then after a
2s grace SIGKILL survivors gated on a pid+start-time identity re-check
so a recycled pid is never signalled. Snapshot is bounded and never
rejects; failures degrade to today's shell-only kill.

Wired for agent sessions only (plain terminals keep nohup semantics) at
all three POSIX kill sites: local provider shutdown, daemon
TerminalHost immediate kill (the pty:kill path — force-kill bypassed
Session.kill entirely), and daemon Session graceful kill.

Verified live in the built app: an agent pane with a detached-pgid
child; the child survived on the unwired build (three control runs) and
dies within ~5s with the fix. Windows ConPTY and SSH-hosted PTYs keep
the previous foreground-tree contract (documented follow-ups).

* fix(terminal): harden descendant teardown

* fix(terminal): require fresh process snapshots

* fix(terminal): close descendant teardown races

* refactor(terminal): preserve teardown line budget

* fix(terminal): keep descendant teardown fresh and identity-safe

* docs(reliability): record integrated descendant E2E

* fix(terminal): bound descendant teardown work

* fix(terminal): share descendant snapshot indexes

* docs(reliability): record descendant review evidence

* revert: remove speculative descendant hardening
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