Repository navigation
fix(agent-status): retire panes whose agent process is gone (STA-4612) - #15212
Conversation
Agent status can hold `working` on a pane where no work is outstanding, and nothing closes the gap. A pane's Claude state is a join of a lead turn and three latches — the subagent roster, the background-task gate and the session-cron gate — and each is set by a hook and cleared only by another hook. Claude Code emits no terminating hook on `/exit`, `/clear`, Ctrl+C, crash, SIGKILL or terminal close, so every one of those latches is a claim with no owner and no expiry. The join is also materialised at ingest time and persisted, so a stale `working` survives restart and blocks hibernation, which requires `done`. Registering `SessionEnd` is not the fix: it covers roughly a third of exit paths (measured on 2.1.231/2.1.233; upstream anthropics/claude-code#17885 and #6428 are both closed as not planned). Nor is a TTL — `AGENT_STATUS_STALE_AFTER_MS` only decays the sidebar dot at read time while the stored row stays non-terminal. So the backstop is built from evidence Orca already owns. A session id that changes means the conversation was replaced. On the first hook of the new session — whatever that hook is — the previous session's own claims are void: its session crons and its one-shot subagents. Deliberately not voided: the background-task gate (a background shell is an OS process that survives `/clear`, and the previous inventory is positive evidence it was running), and `confirmedTeammate` rows (persistent in-process teammates a lead swap cannot end). The lead record is left to the incoming event's own fold. A certified process exit retires the pane. Orca already does this on every attributable PTY exit — `clearProviderPtyState` resolves the pane key and calls `clearPaneState` — but that resolution depends on the spawn-time `ptyPaneKey` mapping, which a restored or reattached PTY may never rebuild. Those panes keep their row and latches for good. `onPtyExit` knows the keys teardown could not resolve, so it reconciles them from its own records. The certificate is `exitCode >= 0 || hostExitConfirmed || providerExitObserved`: a synthetic `-1` from a failed stop is not a death (the PTY can have survived it), while a real exit can also report `-1`, so neither the code nor the SSH surface predicate is sufficient alone. `providerExitObserved` is additive and separate from `hostExitConfirmed`, which also drives the liveness verdict and the SSH surface decision. A confirmed shell foreground is the `/exit` case: the agent died, the shell lived. That already dropped the row, but through `agentStatus:drop`, which by its own contract preserves a live pane's caches — so every latch survived and the next event resolved the pane back to `working`. It now routes through the reconciler instead, gated on a per-pane accepted-status generation rather than row identity: the confirming process read can take seconds, and `updatedAt` cannot order two writes inside one millisecond (the store deliberately admits equal timestamps). Cold start generalises the same way. The startup sweep required a restored subagent roster, so a stranded lead row, background-task gate or cron gate — the shapes with no child event left to reap them — were never candidates. Hibernation needs no change: with the above, those rows become genuinely `done` and the lockout resolves through the front door. A `restoredUnconfirmed` bypass in the planner would let it reclaim the heap of an agent that may be working. Not included: folding `background_tasks` from a child-attributed `SubagentStop`. Writing its test surfaced #11838's deliberate assertion that child inventories are not authoritative for lead-owned background work, and the listener says the same — "background_tasks is trusted only where unambiguous". An empty list on a `SubagentStop` does not prove the lead's shell ended, so the fold would have cleared a gate on evidence that establishes nothing. STA-4119's live-side question — whether a genuinely live background shell should hold the lead row after the lead turn ends — is untouched. This change extends gate-clearing to zero new triggers.
📝 WalkthroughWalkthroughThe change adds certified PTY-exit handling that reconciles ended agent processes across pane keys. It tracks Claude session ownership and clears stale claims during session replacement and restored-pane cleanup. New IPC and preload APIs expose ended-process reconciliation. Renderer cleanup uses accepted status sequences to guard deferred reconciliation. PTY provider callbacks now identify physically observed exits. Tests cover reconciliation, liveness, session replacement, exit certification, and renderer cleanup. Merge Risk: 🟡 Moderate · up to The change improves cleanup of panes whose agent process has ended, but an asynchronous cleanup ordering issue can lose resume identity for confirmed shell exits, while session-replacement invalidation and retained resume authority still need owner follow-up. Merge should wait for these bounded correctness risks to be fixed or explicitly accepted. 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 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
🧹 Nitpick comments (3)
src/main/agent-hooks/server.ts (1)
2861-2869: 🚀 Performance & Scalability | 🔵 TrivialConsider capping the liveness-probe fan-out.
The candidate predicate now admits any non-terminal Claude row and any pane holding a background-task or cron latch, not only panes with a restored roster. The probe loop at Line 2875 still calls
isLocalPaneAgentLivefor every candidate inside onePromise.all, so the concurrent process-probe count grows with the number of hydrated Claude panes.The sweep runs once per cold start and the candidate count is bounded by the persisted last-status file, so this is not a correctness problem. If a user restores many Claude panes, the startup probe burst becomes noticeable. A small concurrency limit, or a metric on candidate count and sweep duration, would make the cost observable and bounded.
src/main/agent-hooks/ended-process-reconciliation.test.ts (1)
44-112: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd coverage for the pane-alias resolution branch.
reconcileEndedProcessForPaneKeysresolves each key throughresolvePaneKeyAliasbefore it checks claims, and the method doc names an unresolvable or remapped pane key as the reason the method exists. Every test here passes the stablePANEkey directly, so the alias branch never runs.Add one test that registers a legacy numeric alias with
registerPaneKeyAlias, seeds a row on the stable pane key, then callsreconcileEndedProcessForPaneKeyswith the legacy key. Assert the stable pane's row is retired. That test would fail if alias resolution regressed, which the current suite would not catch.src/main/runtime/pty-exit-agent-status-reconciliation.test.ts (1)
19-35: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a test that exercises the
connectionIdoption, or drop it.
runtimeWithBoundPaneacceptsoptions: { connectionId?: string }, but no test in this file passes aconnectionId. This leaves the connection-scoped (SSH-owned pane) reconciliation path unverified in this suite.
Add a test that binds a pane withconnectionIdset and asserts reconciliation still applies, or remove the unused parameter if SSH-owned panes are covered elsewhere.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: c057503d-36bc-4588-b282-2989e3da2769
📒 Files selected for processing (21)
src/main/agent-hooks/ended-process-reconciliation.test.tssrc/main/agent-hooks/restored-subagent-liveness-sweep.test.tssrc/main/agent-hooks/server.tssrc/main/index.tssrc/main/ipc/agent-hooks.tssrc/main/ipc/agent-status-row-teardown-ipc.tssrc/main/ipc/pty-daemon-ssh-lease-lifecycle.test.tssrc/main/ipc/pty-listener-teardown-and-orphans.test.tssrc/main/ipc/pty-runtime-kill-and-exit.test.tssrc/main/ipc/pty.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/pty-exit-agent-status-reconciliation.test.tssrc/preload/api/agent-status-api.tssrc/preload/index.tssrc/renderer/src/components/terminal-pane/pty-connection-command-finished-cleanup.test.tssrc/renderer/src/components/terminal-pane/pty-connection-test-environment.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/store/slices/agent-status.tssrc/renderer/src/web/web-preload-api.tssrc/shared/agent-hook-listener-session-replacement.test.tssrc/shared/agent-hook-listener.ts
Included review availability: Your plan includes up to 10 reviews per rolling hour; 6 remain after this review.
… drop The /exit leg never fired. `settleDeferredCommandFinishedStatusDrop` runs the paired drop before the reconcile, and `dropAgentStatus` cleared the per-pane accepted-status counter the reconcile's guard then read — so the guard compared a live anchor against a zeroed counter and skipped itself on every pane that had a status row, which is every pane worth reconciling. The existing test passed only because it used a pane with no row, where the drop early-returns and both sides read 0. Stop keying the guard on a counter a sibling teardown path can reset: the ordinal is now stamped on the row itself, derived from the row it replaces, so there is no side table to clear and a batched burst lands the same ordinals as the equivalent sequential writes. A removed row means "nothing reported", which is exactly what the paired drop leaves behind. Also: - Keep the `providerSessionOnly` resume identity that the paired dismissal mints when the shell outlived the agent; a certified PTY exit still takes it, since there is no pane left to resume into. - De-vacuum two guard tests. The confirmed-teammate pin never anchored a session owner, so the void it claimed to survive never ran; the unavailable-inspection pin asserted before the confirm ladder settled. Both now fail when their guard is removed. - Derive `hasLiveClaimsForPaneKey` from a predicate that lives beside `clearPaneCacheState`, so a new latch cannot be added to the teardown and silently missed by the claim check. - Drop the unreachable compact-`trigger` clauses; SessionStart is the whole guard. - Cover the connectionId arm of the exit certificate, where a provider-observed death and a preserved SSH surface are deliberately independent.
Revision evidence (independent review returned REVISE; all findings dispositioned)B1 — blocking: the
|
| Mutation | Before | After |
|---|---|---|
delete the confirmedTeammate !== true roster guard |
8 passed — the pin never anchored a session owner, so the void never ran | × keeps a confirmed teammate across the replacement |
make onCommandFinishedUnavailable tear the pane down |
13 passed — the pin asserted at 350 ms, before the ladder settles | × does NOT reconcile when the process check could not confirm a shell |
Full mutation battery, all six caught:
| # | Mutation | Test that fails |
|---|---|---|
| M1 | void the background-shell gate on session replacement | KEEPS a running background-shell gate across the replacement |
| M2 | drop the child agent_id attribution guard |
voids nothing when a CHILD event carries a foreign session id |
| M3 | certify every exit as a process death | does NOT reconcile a synthetic -1 … (+ the transport-bound arm) |
| M4 | delete the confirmedTeammate guard |
keeps a confirmed teammate across the replacement |
| M5 | reconcile on unproven inspection | does NOT reconcile when the process check could not confirm a shell |
| M6 | treat a removed row as a mismatch (re-introduces B1) | reconciles a pane that HAS a status row … |
B3 — resume identity, now disclosed and fixed
reconcileEndedProcess destroyed the providerSessionOnly remnant that the paired agentStatus:drop deliberately mints. The confirmed-shell route now keeps it (the shell is still there to resume into); a certified PTY exit still takes it, matching what clearProviderPtyState already does for every attributable exit. Both directions are pinned, and the keep-arm is red without the fix.
B4 — the four low findings
| Finding | Disposition |
|---|---|
| Unbounded per-pane generation map | Gone. The B1 fix removes the map entirely; there is nothing left to bound. |
hasLiveClaimsForPaneKey hand-enumerates latches, drifts from clearPaneCacheState |
Fixed. Derived from paneHasStateClaims, which now sits three lines under clearPaneCacheState so the two are edited together. It also picked up the Codex lead/roster claims the old list missed. |
Cold sweep deletes where the sibling branch downgrades to done |
Kept, reasoning written into the code. The reap branch has a real turn to describe; these panes' only claim is the stale non-terminal row, and rewriting a waiting/blocked row to done would invent a completion. The sweep stands in for the exit Orca never observed, so it does what that exit does. |
Dead connectionId scaffolding; unreachable compact-trigger clauses |
Both fixed. Two arms added for a transport-bound pane; the dead clauses removed, since SessionStart is the whole guard. |
Suites
| Suite | main f8e728bb8b |
before revision | after revision |
|---|---|---|---|
agent-hooks + shared/agent-hook + shared/agent-status + claude-subagent-roster + main/claude |
116 files / 1186 + 7 skipped | 118 / 1201 + 7 | 118 / 1203 + 7 |
| store slice + hibernation + running-agent-targets + hook projection + tab index + pty-exit reconciliation + pty-connection | 78 / 832 | 79 / 837 | 79 / 840 |
pnpm typecheck 0, pnpm lint 0.
One regression was caught and fixed during the revision itself: a globally-monotonic ordinal broke setAgentStatuses > matches sequential updates across repeated panes, which pins batch/sequential equivalence. Deriving the ordinal per-pane restores that invariant rather than weakening the test.
Combined tree — main + #15189 + #15202 + #15212
Merged locally on main@13b10e0b54. #15212 conflicts textually in three files now: src/shared/agent-hook-listener.ts, src/shared/agent-status-types.ts, src/renderer/src/store/slices/agent-status.ts. All additive; resolved by taking both sides, plus one judgement call — #15189's claudeUnclassifiedBackgroundTaskPaneKeys must be added to paneHasStateClaims.
pnpm typecheck -> 0
suite A -> 119 files / 1221 passed, 7 skipped
suite B -> 79 files / 842 passed
Live validation — CDP only, isolated instance
Temp HOME + ORCA_DEV_USER_DATA_PATH, throwaway git repo, no computer-use or OS-level input automation. Two panes: A holds working via a background-shell latch after its lead turn ended (the STA-4612 shape); B is a genuinely live agent.
Pane A returned to its shell prompt with the process table confirming the foreground (confirmForegroundProcess → zsh) — the exact signal /exit produces.
| pane A (agent exited) | pane B (live agent) | |
|---|---|---|
| after the shell foreground is confirmed | MISSING — retired |
working |
| its next hook event | done — the latch went with the row |
working — its live latch intact |
The contrast arm, in the same instance: the old route (agentStatus:drop alone) leaves the latch alive, and the pane's next event resolves straight back to working. That is the behaviour B1 showed was shipping.
B3 verified live too: drop mints providerSessionOnly: true with the session id, and reconcileEndedProcess now keeps it (it previously returned an empty snapshot).
Rig note: a second Orca dev instance was running on the neighbouring CDP port with the same devLabel, and playwright-cli's attach drifted onto it between calls. The dev label is not a sufficient discriminator — the worktree path is. Every subsequent call ran under a named -s= session plus a guard that throws unless the target's only worktree is the throwaway repo; the guard caught the drift before any mutation.
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/shared/agent-hook-listener.ts (1)
2985-2995: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winPreserve the previous owner when
SessionStartskips invalidation.Line 2986 records
SESSION_Bbefore lines 2994-2995 return. A later lead event fromSESSION_Bthen sees no owner change. Old-session roster and cron claims remain active.
src/shared/agent-hook-listener.ts#L2985-L2995: move the owner update after the compact-session exception, or invalidate claims for a non-compactSessionStart.src/shared/agent-hook-listener-session-replacement.test.ts#L108-L111: addSessionStartforSESSION_Bbefore a later lead event and assert thatSESSION_Aclaims are removed.
🧹 Nitpick comments (1)
src/shared/agent-hook-listener.ts (1)
213-219: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueShorten the added TypeScript comments.
The changed comments contain implementation narratives. Keep one concise non-obvious rationale near each condition.
src/shared/agent-hook-listener.ts#L213-L219: reduce the cache-claim explanation to one short rationale.src/shared/agent-hook-listener.ts#L2990-L2993: state the compact-session exception briefly.src/shared/agent-status-types.ts#L154-L159: reduce the field invariant to a concise contract.src/main/agent-hooks/server.ts#L2588-L2590: shorten the resume-row purpose.src/main/agent-hooks/server.ts#L2620-L2625: shorten the reconciliation-path history.src/main/agent-hooks/server.ts#L2922-L2931: shorten the delete-versus-donerationale.src/main/runtime/pty-exit-agent-status-reconciliation.test.ts#L65-L69: reduce the test setup explanation.src/main/ipc/agent-status-row-teardown-ipc.ts#L46-L50: reduce the resume-identity explanation.As per coding guidelines: “Comments must be concise, non-obvious, and brief—prefer one line.”
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: b3830771-8027-41e6-8e9f-2d38e2e32a0c
📒 Files selected for processing (10)
src/main/agent-hooks/ended-process-reconciliation.test.tssrc/main/agent-hooks/server.tssrc/main/ipc/agent-status-row-teardown-ipc.tssrc/main/runtime/pty-exit-agent-status-reconciliation.test.tssrc/renderer/src/components/terminal-pane/pty-connection-command-finished-cleanup.test.tssrc/renderer/src/components/terminal-pane/pty-connection.tssrc/renderer/src/store/slices/agent-status.tssrc/shared/agent-hook-listener-session-replacement.test.tssrc/shared/agent-hook-listener.tssrc/shared/agent-status-types.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- src/renderer/src/components/terminal-pane/pty-connection-command-finished-cleanup.test.ts
- src/renderer/src/store/slices/agent-status.ts
- src/renderer/src/components/terminal-pane/pty-connection.ts
Included review availability: Your plan includes up to 10 reviews per rolling hour; 7 remain after this review.
Both conflicts are main's per-write `observation` landing on the same lines as this branch's `acceptedStatusSeq`. They are independent additions, so taking either side whole would silently drop the other's work — main's observation stamping in one direction, the liveness ordinal in the other. Kept both: the type keeps the field and the `WithAgentStatusObservation` intersection, and the store's accept branch stamps the ordinal and spreads the observation.
main already sits exactly at the 300-line max-lines cap for this file, so the single `acceptedStatusSeq` field this branch adds pushed it to 301 once main's observation facet merged in. Declared the field as a mixin beside the observation facet instead. Both are per-write facets mixed into `AgentStatusEntry` rather than fields a reporter supplies, so they belong together — and the capped file loses a line rather than gaining one, since it already imports from that module. No lint suppression.
The previous attempt still tripped max-lines: two mixins on one intersection wrap across two lines under oxfmt, so removing the field line bought nothing. Expose a single AgentStatusRowFacets that already includes the observation facet, so the entry intersects one short name on one line. The payload keeps intersecting the observation facet alone — it must not carry the renderer-local ordinal. Verified by formatting first and then linting, which is the order that catches this.
…on split
main dissolved src/renderer/src/components/terminal-pane/pty-connection.ts into
pty-connection/* and left a two-line re-export, so this branch's edits inside that
file were not a conflict but a port.
Moved into pty-connection/pane-agent-identity.ts, where the split put the anchors:
reconcileEndedProcessIfPaneQuiet, the deferredConfirmedShellReconcile arming, and the
confirmedShell option on settleDeferredCommandFinishedStatusDrop. Kept the ordering the
review established — the paired drop runs FIRST, and an absent row still reconciles,
because a removed row means nothing reported. onCommandFinishedUnavailable is now
wrapped: main passed it bare, where a caller-supplied argument would be read as options
and could reconcile on the path that has no proof.
The other five conflicts were unions, not choices: pty.ts and orca-runtime.ts now carry
BOTH this branch's providerExitObserved certificate and main's exit cause, and the three
pty tests assert both.
Verified: typecheck clean on both projects, 46/46 on the pty and cleanup suites, and the
port proven load-bearing by mutation — disabling the confirmed-shell reconcile turns the
B1 test ('reconciles a pane that HAS a status row, whose own drop removes it first') red.
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/shared/agent-status-observation.ts (1)
65-73: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReduce the new implementation comments to brief rationale.
src/shared/agent-status-observation.ts#L65-L73: keep only the ownership and ordering rationale foracceptedStatusSeq.src/main/agent-hooks/ended-process-reconciliation.test.ts#L58-L60: reduce the restored-PTY setup explanation to one sentence.src/main/agent-hooks/ended-process-reconciliation.test.ts#L116-L120: reduce the resume-identity setup explanation to one sentence.src/renderer/src/components/terminal-pane/pty-connection/pane-agent-identity.ts#L92-L115: keep the quiet-pane guard rationale and remove implementation walkthrough details.src/renderer/src/components/terminal-pane/pty-connection/pane-agent-identity.ts#L181-L182: replace the wrapper explanation with one short reason.src/renderer/src/components/terminal-pane/pty-connection/pane-agent-identity.ts#L233-L234: shorten the deferred-sequence explanation.As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.”
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 8813cd5e-45b2-4392-b9a0-3697d1ebe25b
📒 Files selected for processing (23)
src/main/agent-hooks/ended-process-reconciliation.test.tssrc/main/agent-hooks/restored-subagent-liveness-sweep.test.tssrc/main/agent-hooks/server.tssrc/main/index.tssrc/main/ipc/agent-hooks.tssrc/main/ipc/agent-status-row-teardown-ipc.tssrc/main/ipc/pty-daemon-ssh-lease-lifecycle.test.tssrc/main/ipc/pty-listener-teardown-and-orphans.test.tssrc/main/ipc/pty-runtime-kill-and-exit.test.tssrc/main/ipc/pty.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/pty-exit-agent-status-reconciliation.test.tssrc/preload/api/agent-status-api.tssrc/preload/index.tssrc/renderer/src/components/terminal-pane/pty-connection-command-finished-cleanup.test.tssrc/renderer/src/components/terminal-pane/pty-connection-test-environment.tssrc/renderer/src/components/terminal-pane/pty-connection/pane-agent-identity.tssrc/renderer/src/store/slices/agent-status.tssrc/renderer/src/web/web-preload-api.tssrc/shared/agent-hook-listener-session-replacement.test.tssrc/shared/agent-hook-listener.tssrc/shared/agent-status-observation.tssrc/shared/agent-status-types.ts
🚧 Files skipped from review as they are similar to previous changes (19)
- src/main/ipc/pty-listener-teardown-and-orphans.test.ts
- src/main/ipc/pty-runtime-kill-and-exit.test.ts
- src/preload/index.ts
- src/main/index.ts
- src/renderer/src/components/terminal-pane/pty-connection-test-environment.ts
- src/preload/api/agent-status-api.ts
- src/main/ipc/agent-status-row-teardown-ipc.ts
- src/main/ipc/agent-hooks.ts
- src/renderer/src/store/slices/agent-status.ts
- src/renderer/src/web/web-preload-api.ts
- src/main/runtime/pty-exit-agent-status-reconciliation.test.ts
- src/main/agent-hooks/restored-subagent-liveness-sweep.test.ts
- src/main/agent-hooks/server.ts
- src/renderer/src/components/terminal-pane/pty-connection-command-finished-cleanup.test.ts
- src/main/ipc/pty.ts
- src/main/runtime/orca-runtime.ts
- src/main/ipc/pty-daemon-ssh-lease-lifecycle.test.ts
- src/shared/agent-hook-listener-session-replacement.test.ts
- src/shared/agent-hook-listener.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.
| dropStatus?.() | ||
| if (options.confirmedShell) { | ||
| reconcile?.() | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Run reconciliation after the deferred status drop completes.
If flushPendingInterruptInference() returns a Promise, the closure at Line 221 schedules dropCommandFinishedStatusIfSameTurn and returns. Lines 126-129 then reconcile the main process first. The server can remove the live row before agentStatus:drop creates its providerSessionOnly remnant, so a confirmed-shell exit can lose resume identity.
Chain the reconciliation callback after the asynchronous drop path completes. Add a regression test where interrupt inference resolves asynchronously.
Electron UI proof — local confirmed-shell
|
Review status: PASS — land after fixesReviewed the PR description and all existing comments before review. The same-model senior review/fix loop completed clean on the final adversarial pass. Commit
Validation completed:
No production scope-expanding changes were made. Remaining CodeRabbit suggestions are low-value coverage/perf observability ideas without a measured regression and were intentionally left out of this focused fix. |
Both conflicts are independent map fields added to the same listener state — this branch's `claudeConsumedCompactPromptIdByPaneKey` and #15212's `claudeSessionOwnerByPaneKey`. Taking either side whole would drop the other's work, so both are kept in the type and the initializer.
Two conflicts, both from siblings that have since merged: - agent-hook-listener.ts: #15202 added the manual-compact restored-roster reap immediately before the resolver call this branch replaced. Kept both — main's block runs, then resolveClaudePaneStatus — and bridged `effectiveState` off `resolvedStatus.stateName` so #15202's downstream guard reads the same value instead of resolving twice. - agent-status-types.ts: a SEMANTIC conflict, not a textual one. #15212 replaced the entry's `WithAgentStatusObservation` intersection with `AgentStatusRowFacets`, and the payload type that used the old name moved into the extracted ipc-payload module — so the import went dead and CI failed TS6196. Dropped it.
#15212) * fix(agent-status): retire panes whose agent process is gone (STA-4612) Agent status can hold `working` on a pane where no work is outstanding, and nothing closes the gap. A pane's Claude state is a join of a lead turn and three latches — the subagent roster, the background-task gate and the session-cron gate — and each is set by a hook and cleared only by another hook. Claude Code emits no terminating hook on `/exit`, `/clear`, Ctrl+C, crash, SIGKILL or terminal close, so every one of those latches is a claim with no owner and no expiry. The join is also materialised at ingest time and persisted, so a stale `working` survives restart and blocks hibernation, which requires `done`. Registering `SessionEnd` is not the fix: it covers roughly a third of exit paths (measured on 2.1.231/2.1.233; upstream anthropics/claude-code#17885 and #6428 are both closed as not planned). Nor is a TTL — `AGENT_STATUS_STALE_AFTER_MS` only decays the sidebar dot at read time while the stored row stays non-terminal. So the backstop is built from evidence Orca already owns. A session id that changes means the conversation was replaced. On the first hook of the new session — whatever that hook is — the previous session's own claims are void: its session crons and its one-shot subagents. Deliberately not voided: the background-task gate (a background shell is an OS process that survives `/clear`, and the previous inventory is positive evidence it was running), and `confirmedTeammate` rows (persistent in-process teammates a lead swap cannot end). The lead record is left to the incoming event's own fold. A certified process exit retires the pane. Orca already does this on every attributable PTY exit — `clearProviderPtyState` resolves the pane key and calls `clearPaneState` — but that resolution depends on the spawn-time `ptyPaneKey` mapping, which a restored or reattached PTY may never rebuild. Those panes keep their row and latches for good. `onPtyExit` knows the keys teardown could not resolve, so it reconciles them from its own records. The certificate is `exitCode >= 0 || hostExitConfirmed || providerExitObserved`: a synthetic `-1` from a failed stop is not a death (the PTY can have survived it), while a real exit can also report `-1`, so neither the code nor the SSH surface predicate is sufficient alone. `providerExitObserved` is additive and separate from `hostExitConfirmed`, which also drives the liveness verdict and the SSH surface decision. A confirmed shell foreground is the `/exit` case: the agent died, the shell lived. That already dropped the row, but through `agentStatus:drop`, which by its own contract preserves a live pane's caches — so every latch survived and the next event resolved the pane back to `working`. It now routes through the reconciler instead, gated on a per-pane accepted-status generation rather than row identity: the confirming process read can take seconds, and `updatedAt` cannot order two writes inside one millisecond (the store deliberately admits equal timestamps). Cold start generalises the same way. The startup sweep required a restored subagent roster, so a stranded lead row, background-task gate or cron gate — the shapes with no child event left to reap them — were never candidates. Hibernation needs no change: with the above, those rows become genuinely `done` and the lockout resolves through the front door. A `restoredUnconfirmed` bypass in the planner would let it reclaim the heap of an agent that may be working. Not included: folding `background_tasks` from a child-attributed `SubagentStop`. Writing its test surfaced #11838's deliberate assertion that child inventories are not authoritative for lead-owned background work, and the listener says the same — "background_tasks is trusted only where unambiguous". An empty list on a `SubagentStop` does not prove the lead's shell ended, so the fold would have cleared a gate on evidence that establishes nothing. STA-4119's live-side question — whether a genuinely live background shell should hold the lead row after the lead turn ends — is untouched. This change extends gate-clearing to zero new triggers. * fix(agent-status): make the confirmed-shell reconcile survive its own drop The /exit leg never fired. `settleDeferredCommandFinishedStatusDrop` runs the paired drop before the reconcile, and `dropAgentStatus` cleared the per-pane accepted-status counter the reconcile's guard then read — so the guard compared a live anchor against a zeroed counter and skipped itself on every pane that had a status row, which is every pane worth reconciling. The existing test passed only because it used a pane with no row, where the drop early-returns and both sides read 0. Stop keying the guard on a counter a sibling teardown path can reset: the ordinal is now stamped on the row itself, derived from the row it replaces, so there is no side table to clear and a batched burst lands the same ordinals as the equivalent sequential writes. A removed row means "nothing reported", which is exactly what the paired drop leaves behind. Also: - Keep the `providerSessionOnly` resume identity that the paired dismissal mints when the shell outlived the agent; a certified PTY exit still takes it, since there is no pane left to resume into. - De-vacuum two guard tests. The confirmed-teammate pin never anchored a session owner, so the void it claimed to survive never ran; the unavailable-inspection pin asserted before the confirm ladder settled. Both now fail when their guard is removed. - Derive `hasLiveClaimsForPaneKey` from a predicate that lives beside `clearPaneCacheState`, so a new latch cannot be added to the teardown and silently missed by the claim check. - Drop the unreachable compact-`trigger` clauses; SessionStart is the whole guard. - Cover the connectionId arm of the exit certificate, where a provider-observed death and a preserved SSH surface are deliberately independent. * fix(agent-status): keep agent-status-types under its line cap main already sits exactly at the 300-line max-lines cap for this file, so the single `acceptedStatusSeq` field this branch adds pushed it to 301 once main's observation facet merged in. Declared the field as a mixin beside the observation facet instead. Both are per-write facets mixed into `AgentStatusEntry` rather than fields a reporter supplies, so they belong together — and the capped file loses a line rather than gaining one, since it already imports from that module. No lint suppression. * fix(agent-status): collapse the entry facets into one intersection The previous attempt still tripped max-lines: two mixins on one intersection wrap across two lines under oxfmt, so removing the field line bought nothing. Expose a single AgentStatusRowFacets that already includes the observation facet, so the entry intersects one short name on one line. The payload keeps intersecting the observation facet alone — it must not carry the renderer-local ordinal. Verified by formatting first and then linting, which is the order that catches this. * fix(agent-status): retire resume authority with dead panes
…iation #15172's split modules pass providerExitObserved to onPtyExit, but the option was declared by #15212, which this release deliberately does not carry — it is only reachable via #15166, whose split silently drops the SSH reconnect model-paint gate from #14844 (STA-5395). Widen the option type so the split typechecks, and take #15212's assertion updates for the three test files that observe the call shape. The behaviour #15212 adds — reconciling agent status on a certified process death — is NOT included; the option is accepted and unused.
stablyai#15212) * fix(agent-status): retire panes whose agent process is gone (STA-4612) Agent status can hold `working` on a pane where no work is outstanding, and nothing closes the gap. A pane's Claude state is a join of a lead turn and three latches — the subagent roster, the background-task gate and the session-cron gate — and each is set by a hook and cleared only by another hook. Claude Code emits no terminating hook on `/exit`, `/clear`, Ctrl+C, crash, SIGKILL or terminal close, so every one of those latches is a claim with no owner and no expiry. The join is also materialised at ingest time and persisted, so a stale `working` survives restart and blocks hibernation, which requires `done`. Registering `SessionEnd` is not the fix: it covers roughly a third of exit paths (measured on 2.1.231/2.1.233; upstream anthropics/claude-code#17885 and stablyai#6428 are both closed as not planned). Nor is a TTL — `AGENT_STATUS_STALE_AFTER_MS` only decays the sidebar dot at read time while the stored row stays non-terminal. So the backstop is built from evidence Orca already owns. A session id that changes means the conversation was replaced. On the first hook of the new session — whatever that hook is — the previous session's own claims are void: its session crons and its one-shot subagents. Deliberately not voided: the background-task gate (a background shell is an OS process that survives `/clear`, and the previous inventory is positive evidence it was running), and `confirmedTeammate` rows (persistent in-process teammates a lead swap cannot end). The lead record is left to the incoming event's own fold. A certified process exit retires the pane. Orca already does this on every attributable PTY exit — `clearProviderPtyState` resolves the pane key and calls `clearPaneState` — but that resolution depends on the spawn-time `ptyPaneKey` mapping, which a restored or reattached PTY may never rebuild. Those panes keep their row and latches for good. `onPtyExit` knows the keys teardown could not resolve, so it reconciles them from its own records. The certificate is `exitCode >= 0 || hostExitConfirmed || providerExitObserved`: a synthetic `-1` from a failed stop is not a death (the PTY can have survived it), while a real exit can also report `-1`, so neither the code nor the SSH surface predicate is sufficient alone. `providerExitObserved` is additive and separate from `hostExitConfirmed`, which also drives the liveness verdict and the SSH surface decision. A confirmed shell foreground is the `/exit` case: the agent died, the shell lived. That already dropped the row, but through `agentStatus:drop`, which by its own contract preserves a live pane's caches — so every latch survived and the next event resolved the pane back to `working`. It now routes through the reconciler instead, gated on a per-pane accepted-status generation rather than row identity: the confirming process read can take seconds, and `updatedAt` cannot order two writes inside one millisecond (the store deliberately admits equal timestamps). Cold start generalises the same way. The startup sweep required a restored subagent roster, so a stranded lead row, background-task gate or cron gate — the shapes with no child event left to reap them — were never candidates. Hibernation needs no change: with the above, those rows become genuinely `done` and the lockout resolves through the front door. A `restoredUnconfirmed` bypass in the planner would let it reclaim the heap of an agent that may be working. Not included: folding `background_tasks` from a child-attributed `SubagentStop`. Writing its test surfaced stablyai#11838's deliberate assertion that child inventories are not authoritative for lead-owned background work, and the listener says the same — "background_tasks is trusted only where unambiguous". An empty list on a `SubagentStop` does not prove the lead's shell ended, so the fold would have cleared a gate on evidence that establishes nothing. STA-4119's live-side question — whether a genuinely live background shell should hold the lead row after the lead turn ends — is untouched. This change extends gate-clearing to zero new triggers. * fix(agent-status): make the confirmed-shell reconcile survive its own drop The /exit leg never fired. `settleDeferredCommandFinishedStatusDrop` runs the paired drop before the reconcile, and `dropAgentStatus` cleared the per-pane accepted-status counter the reconcile's guard then read — so the guard compared a live anchor against a zeroed counter and skipped itself on every pane that had a status row, which is every pane worth reconciling. The existing test passed only because it used a pane with no row, where the drop early-returns and both sides read 0. Stop keying the guard on a counter a sibling teardown path can reset: the ordinal is now stamped on the row itself, derived from the row it replaces, so there is no side table to clear and a batched burst lands the same ordinals as the equivalent sequential writes. A removed row means "nothing reported", which is exactly what the paired drop leaves behind. Also: - Keep the `providerSessionOnly` resume identity that the paired dismissal mints when the shell outlived the agent; a certified PTY exit still takes it, since there is no pane left to resume into. - De-vacuum two guard tests. The confirmed-teammate pin never anchored a session owner, so the void it claimed to survive never ran; the unavailable-inspection pin asserted before the confirm ladder settled. Both now fail when their guard is removed. - Derive `hasLiveClaimsForPaneKey` from a predicate that lives beside `clearPaneCacheState`, so a new latch cannot be added to the teardown and silently missed by the claim check. - Drop the unreachable compact-`trigger` clauses; SessionStart is the whole guard. - Cover the connectionId arm of the exit certificate, where a provider-observed death and a preserved SSH surface are deliberately independent. * fix(agent-status): keep agent-status-types under its line cap main already sits exactly at the 300-line max-lines cap for this file, so the single `acceptedStatusSeq` field this branch adds pushed it to 301 once main's observation facet merged in. Declared the field as a mixin beside the observation facet instead. Both are per-write facets mixed into `AgentStatusEntry` rather than fields a reporter supplies, so they belong together — and the capped file loses a line rather than gaining one, since it already imports from that module. No lint suppression. * fix(agent-status): collapse the entry facets into one intersection The previous attempt still tripped max-lines: two mixins on one intersection wrap across two lines under oxfmt, so removing the field line bought nothing. Expose a single AgentStatusRowFacets that already includes the observation facet, so the entry intersects one short name on one line. The payload keeps intersecting the observation facet alone — it must not carry the renderer-local ordinal. Verified by formatting first and then linting, which is the order that catches this. * fix(agent-status): retire resume authority with dead panes (cherry picked from commit 94f2317)
stablyai#15212) * fix(agent-status): retire panes whose agent process is gone (STA-4612) Agent status can hold `working` on a pane where no work is outstanding, and nothing closes the gap. A pane's Claude state is a join of a lead turn and three latches — the subagent roster, the background-task gate and the session-cron gate — and each is set by a hook and cleared only by another hook. Claude Code emits no terminating hook on `/exit`, `/clear`, Ctrl+C, crash, SIGKILL or terminal close, so every one of those latches is a claim with no owner and no expiry. The join is also materialised at ingest time and persisted, so a stale `working` survives restart and blocks hibernation, which requires `done`. Registering `SessionEnd` is not the fix: it covers roughly a third of exit paths (measured on 2.1.231/2.1.233; upstream anthropics/claude-code#17885 and stablyai#6428 are both closed as not planned). Nor is a TTL — `AGENT_STATUS_STALE_AFTER_MS` only decays the sidebar dot at read time while the stored row stays non-terminal. So the backstop is built from evidence Orca already owns. A session id that changes means the conversation was replaced. On the first hook of the new session — whatever that hook is — the previous session's own claims are void: its session crons and its one-shot subagents. Deliberately not voided: the background-task gate (a background shell is an OS process that survives `/clear`, and the previous inventory is positive evidence it was running), and `confirmedTeammate` rows (persistent in-process teammates a lead swap cannot end). The lead record is left to the incoming event's own fold. A certified process exit retires the pane. Orca already does this on every attributable PTY exit — `clearProviderPtyState` resolves the pane key and calls `clearPaneState` — but that resolution depends on the spawn-time `ptyPaneKey` mapping, which a restored or reattached PTY may never rebuild. Those panes keep their row and latches for good. `onPtyExit` knows the keys teardown could not resolve, so it reconciles them from its own records. The certificate is `exitCode >= 0 || hostExitConfirmed || providerExitObserved`: a synthetic `-1` from a failed stop is not a death (the PTY can have survived it), while a real exit can also report `-1`, so neither the code nor the SSH surface predicate is sufficient alone. `providerExitObserved` is additive and separate from `hostExitConfirmed`, which also drives the liveness verdict and the SSH surface decision. A confirmed shell foreground is the `/exit` case: the agent died, the shell lived. That already dropped the row, but through `agentStatus:drop`, which by its own contract preserves a live pane's caches — so every latch survived and the next event resolved the pane back to `working`. It now routes through the reconciler instead, gated on a per-pane accepted-status generation rather than row identity: the confirming process read can take seconds, and `updatedAt` cannot order two writes inside one millisecond (the store deliberately admits equal timestamps). Cold start generalises the same way. The startup sweep required a restored subagent roster, so a stranded lead row, background-task gate or cron gate — the shapes with no child event left to reap them — were never candidates. Hibernation needs no change: with the above, those rows become genuinely `done` and the lockout resolves through the front door. A `restoredUnconfirmed` bypass in the planner would let it reclaim the heap of an agent that may be working. Not included: folding `background_tasks` from a child-attributed `SubagentStop`. Writing its test surfaced stablyai#11838's deliberate assertion that child inventories are not authoritative for lead-owned background work, and the listener says the same — "background_tasks is trusted only where unambiguous". An empty list on a `SubagentStop` does not prove the lead's shell ended, so the fold would have cleared a gate on evidence that establishes nothing. STA-4119's live-side question — whether a genuinely live background shell should hold the lead row after the lead turn ends — is untouched. This change extends gate-clearing to zero new triggers. * fix(agent-status): make the confirmed-shell reconcile survive its own drop The /exit leg never fired. `settleDeferredCommandFinishedStatusDrop` runs the paired drop before the reconcile, and `dropAgentStatus` cleared the per-pane accepted-status counter the reconcile's guard then read — so the guard compared a live anchor against a zeroed counter and skipped itself on every pane that had a status row, which is every pane worth reconciling. The existing test passed only because it used a pane with no row, where the drop early-returns and both sides read 0. Stop keying the guard on a counter a sibling teardown path can reset: the ordinal is now stamped on the row itself, derived from the row it replaces, so there is no side table to clear and a batched burst lands the same ordinals as the equivalent sequential writes. A removed row means "nothing reported", which is exactly what the paired drop leaves behind. Also: - Keep the `providerSessionOnly` resume identity that the paired dismissal mints when the shell outlived the agent; a certified PTY exit still takes it, since there is no pane left to resume into. - De-vacuum two guard tests. The confirmed-teammate pin never anchored a session owner, so the void it claimed to survive never ran; the unavailable-inspection pin asserted before the confirm ladder settled. Both now fail when their guard is removed. - Derive `hasLiveClaimsForPaneKey` from a predicate that lives beside `clearPaneCacheState`, so a new latch cannot be added to the teardown and silently missed by the claim check. - Drop the unreachable compact-`trigger` clauses; SessionStart is the whole guard. - Cover the connectionId arm of the exit certificate, where a provider-observed death and a preserved SSH surface are deliberately independent. * fix(agent-status): keep agent-status-types under its line cap main already sits exactly at the 300-line max-lines cap for this file, so the single `acceptedStatusSeq` field this branch adds pushed it to 301 once main's observation facet merged in. Declared the field as a mixin beside the observation facet instead. Both are per-write facets mixed into `AgentStatusEntry` rather than fields a reporter supplies, so they belong together — and the capped file loses a line rather than gaining one, since it already imports from that module. No lint suppression. * fix(agent-status): collapse the entry facets into one intersection The previous attempt still tripped max-lines: two mixins on one intersection wrap across two lines under oxfmt, so removing the field line bought nothing. Expose a single AgentStatusRowFacets that already includes the observation facet, so the entry intersects one short name on one line. The payload keeps intersecting the observation facet alone — it must not carry the renderer-local ordinal. Verified by formatting first and then linting, which is the order that catches this. * fix(agent-status): retire resume authority with dead panes
stablyai#15212) * fix(agent-status): retire panes whose agent process is gone (STA-4612) Agent status can hold `working` on a pane where no work is outstanding, and nothing closes the gap. A pane's Claude state is a join of a lead turn and three latches — the subagent roster, the background-task gate and the session-cron gate — and each is set by a hook and cleared only by another hook. Claude Code emits no terminating hook on `/exit`, `/clear`, Ctrl+C, crash, SIGKILL or terminal close, so every one of those latches is a claim with no owner and no expiry. The join is also materialised at ingest time and persisted, so a stale `working` survives restart and blocks hibernation, which requires `done`. Registering `SessionEnd` is not the fix: it covers roughly a third of exit paths (measured on 2.1.231/2.1.233; upstream anthropics/claude-code#17885 and stablyai#6428 are both closed as not planned). Nor is a TTL — `AGENT_STATUS_STALE_AFTER_MS` only decays the sidebar dot at read time while the stored row stays non-terminal. So the backstop is built from evidence Orca already owns. A session id that changes means the conversation was replaced. On the first hook of the new session — whatever that hook is — the previous session's own claims are void: its session crons and its one-shot subagents. Deliberately not voided: the background-task gate (a background shell is an OS process that survives `/clear`, and the previous inventory is positive evidence it was running), and `confirmedTeammate` rows (persistent in-process teammates a lead swap cannot end). The lead record is left to the incoming event's own fold. A certified process exit retires the pane. Orca already does this on every attributable PTY exit — `clearProviderPtyState` resolves the pane key and calls `clearPaneState` — but that resolution depends on the spawn-time `ptyPaneKey` mapping, which a restored or reattached PTY may never rebuild. Those panes keep their row and latches for good. `onPtyExit` knows the keys teardown could not resolve, so it reconciles them from its own records. The certificate is `exitCode >= 0 || hostExitConfirmed || providerExitObserved`: a synthetic `-1` from a failed stop is not a death (the PTY can have survived it), while a real exit can also report `-1`, so neither the code nor the SSH surface predicate is sufficient alone. `providerExitObserved` is additive and separate from `hostExitConfirmed`, which also drives the liveness verdict and the SSH surface decision. A confirmed shell foreground is the `/exit` case: the agent died, the shell lived. That already dropped the row, but through `agentStatus:drop`, which by its own contract preserves a live pane's caches — so every latch survived and the next event resolved the pane back to `working`. It now routes through the reconciler instead, gated on a per-pane accepted-status generation rather than row identity: the confirming process read can take seconds, and `updatedAt` cannot order two writes inside one millisecond (the store deliberately admits equal timestamps). Cold start generalises the same way. The startup sweep required a restored subagent roster, so a stranded lead row, background-task gate or cron gate — the shapes with no child event left to reap them — were never candidates. Hibernation needs no change: with the above, those rows become genuinely `done` and the lockout resolves through the front door. A `restoredUnconfirmed` bypass in the planner would let it reclaim the heap of an agent that may be working. Not included: folding `background_tasks` from a child-attributed `SubagentStop`. Writing its test surfaced stablyai#11838's deliberate assertion that child inventories are not authoritative for lead-owned background work, and the listener says the same — "background_tasks is trusted only where unambiguous". An empty list on a `SubagentStop` does not prove the lead's shell ended, so the fold would have cleared a gate on evidence that establishes nothing. STA-4119's live-side question — whether a genuinely live background shell should hold the lead row after the lead turn ends — is untouched. This change extends gate-clearing to zero new triggers. * fix(agent-status): make the confirmed-shell reconcile survive its own drop The /exit leg never fired. `settleDeferredCommandFinishedStatusDrop` runs the paired drop before the reconcile, and `dropAgentStatus` cleared the per-pane accepted-status counter the reconcile's guard then read — so the guard compared a live anchor against a zeroed counter and skipped itself on every pane that had a status row, which is every pane worth reconciling. The existing test passed only because it used a pane with no row, where the drop early-returns and both sides read 0. Stop keying the guard on a counter a sibling teardown path can reset: the ordinal is now stamped on the row itself, derived from the row it replaces, so there is no side table to clear and a batched burst lands the same ordinals as the equivalent sequential writes. A removed row means "nothing reported", which is exactly what the paired drop leaves behind. Also: - Keep the `providerSessionOnly` resume identity that the paired dismissal mints when the shell outlived the agent; a certified PTY exit still takes it, since there is no pane left to resume into. - De-vacuum two guard tests. The confirmed-teammate pin never anchored a session owner, so the void it claimed to survive never ran; the unavailable-inspection pin asserted before the confirm ladder settled. Both now fail when their guard is removed. - Derive `hasLiveClaimsForPaneKey` from a predicate that lives beside `clearPaneCacheState`, so a new latch cannot be added to the teardown and silently missed by the claim check. - Drop the unreachable compact-`trigger` clauses; SessionStart is the whole guard. - Cover the connectionId arm of the exit certificate, where a provider-observed death and a preserved SSH surface are deliberately independent. * fix(agent-status): keep agent-status-types under its line cap main already sits exactly at the 300-line max-lines cap for this file, so the single `acceptedStatusSeq` field this branch adds pushed it to 301 once main's observation facet merged in. Declared the field as a mixin beside the observation facet instead. Both are per-write facets mixed into `AgentStatusEntry` rather than fields a reporter supplies, so they belong together — and the capped file loses a line rather than gaining one, since it already imports from that module. No lint suppression. * fix(agent-status): collapse the entry facets into one intersection The previous attempt still tripped max-lines: two mixins on one intersection wrap across two lines under oxfmt, so removing the field line bought nothing. Expose a single AgentStatusRowFacets that already includes the observation facet, so the entry intersects one short name on one line. The payload keeps intersecting the observation facet alone — it must not carry the renderer-local ordinal. Verified by formatting first and then linting, which is the order that catches this. * fix(agent-status): retire resume authority with dead panes




Fixes STA-4612.
The defect
A Claude pane's state is a join of a lead turn and three latches — the subagent roster, the background-task gate, the session-cron gate (
resolveClaudePaneState,agent-hook-listener.ts). Each is set by a hook and cleared only by another hook, so each is a claim with no owner and no expiry. The join is computed once at ingest, stored, and persisted — so a staleworkingsurvives restart and blocks hibernation, which requiresdone.Two non-fixes, ruled out first:
SessionEndcovers about a third of exit paths. Measured on Claude Code 2.1.231/2.1.233: it does not fire on/exit(upstreamanthropics/claude-code#17885, closed not planned),/clear(#6428, same), Ctrl+C, crash, SIGKILL or terminal close. That approach was implemented and closed unmerged in fix(agent-status): register and handle Claude SessionEnd #14376.AGENT_STATUS_STALE_AFTER_MSdecays only the sidebar dot at read time; the stored row stays non-terminal forever and re-hydrates on next launch. Anti-staleness that works is a liveness join or a process-exit signal.So this is built from evidence Orca already receives.
What changed
A replaced session voids the claims the old one owned. A different Claude
session_idon a lead event means a different conversation, and it arrives on the first hook of the new session whatever that hook is — which is what makes it a backstop for the exits that emit nothing. It voids the previous session's crons and one-shot subagents.Deliberately not voided, and this is the load-bearing part:
/clear(which keeps the Claude process), and the previous inventory is positive evidence it was running;confirmedTeammaterows — persistent in-process teammates a lead swap cannot end;The trigger is an allow-list of lead events requiring no
agent_id, so a child or teammate payload carrying its own session id voids nothing. Claude has no equivalent of the Codex child-session guard, so this matters.A certified process exit retires the pane. Orca already does this on every attributable PTY exit:
clearProviderPtyStateresolves the pane key and callsclearPaneState. But that resolution depends on the spawn-timeptyPaneKeymapping, which a restored or reattached PTY may never rebuild (pty.ts:2148-2149, and the codebase's own note two lines below). Those panes keep their row and every latch for good.onPtyExitknows the keys teardown could not resolve, so it reconciles them from its own records.The certificate is
exitCode >= 0 || hostExitConfirmed || providerExitObserved. Neither half is sufficient alone: a synthetic-1from a failed stop is not a death — its own comment says "a retry can still target a PTY that survived the failed shutdown" — while a real exit can also report-1(local-pty-provider.tsforwards node-pty's code verbatim;local-pty-provider-shutdown.test.ts:174-180pins it).providerExitObservedis additive and deliberately separate fromhostExitConfirmed, which also drives the SSH surface decision and the liveness verdict.A confirmed shell foreground routes through the reconciler. This is the
/exitcase — the agent died, the shell lived — and it is proven by a process-table read. It already dropped the row, but throughagentStatus:drop→dropStatusEntry, which by its own docstring preserves the pane's caches "since the pane's agent may still be alive". Every latch survived, so the next event resolved the pane straight back toworking. A process-confirmed exit is exactly the case that docstring excludes, so it now gets its own IPC.Gated on the row's own
acceptedStatusSeq, not on row identity. The confirming read can ladder out to ~7s, and any unrelated write in that window silently skipped the drop; a timestamp cannot replace it either, since the store deliberately admits equalupdatedAtvalues and a genuinely newer event can share the anchor's millisecond.The first version of that gate kept the ordinal in a per-pane side table — and
dropAgentStatuscleared it. Settling runs the paired drop before the reconcile, so the guard compared a live anchor against a zeroed counter and skipped itself on every pane that had a status row, which is every pane worth reconciling. Review caught it; its own test had passed only because it used a pane with no row, where the drop early-returns and both sides read 0. The ordinal now lives on the row and is derived from the row it replaces, so there is no side table for a sibling teardown to reset, and a removed row reads as "nothing reported" — which is exactly what the paired drop leaves behind. A batched burst lands the same ordinals as the equivalent sequential writes, sosetAgentStatusesstays observationally identical to repeatedsetAgentStatus.The pane's resume identity survives that teardown.
agentStatus:dropdeliberately mints aproviderSessionOnlyremnant when the row carries a resumable session, and clearing the pane's caches used to take it straight back out. That remnant asserts no state — it cannot gate a paneworking— and the shell is still sitting there to resume into, so the confirmed-shell route now keeps it. A certified PTY exit still takes it: there is no pane left to resume into, andclearProviderPtyStatealready does exactly that for every attributable exit.The cold-start sweep generalises. It required a restored subagent roster, so a stranded lead row, background-task gate or cron gate — precisely the shapes with no child event left to reap them — were never candidates. Host scoping, the indeterminate-probe fail-open and the two-phase rebind re-check are unchanged.
Hibernation is unchanged, deliberately. With the above those rows become genuinely
done. ArestoredUnconfirmedbypass in the planner would let it reclaim the heap of an agent that may still be working.What is not here
Folding
background_tasksfrom a child-attributedSubagentStopwas planned and withdrawn during implementation. Writing its test surfaced #11838's deliberate assertion that child inventories are not authoritative for lead-owned background work, and the listener states the rule directly: "background_tasks is trusted only where unambiguous". An empty list on aSubagentStopdoes not prove the lead's shell ended, so the fold would have cleared a gate on evidence that establishes nothing.Scope boundary
STA-4119's live-side question — whether a genuinely live background shell should hold the lead row after the lead turn ends — is a product question owned elsewhere, and this PR takes no position on it. Gate-clearing is extended to zero new triggers. Two pre-existing paths already clear that gate while a shell may be alive (
SessionStart(source='clear'), and the lead interrupt bit inupdateClaudeRunningNonAgentTask); neither is touched here, in either direction.This does not subsume STA-4119, and is not meant to. Only dead-side variants are covered here —
/exit,/clear, Ctrl+C, crash, SIGKILL, terminal close. STA-4119's pane keeps a live PTY, so no liveness join or process-exit signal can ever reach it; that side is settled separately in #15189.Reviewed independently and confirmed three ways, so it doesn't need re-litigating:
voidClaimsOfReplacedClaudeSessiondeletes the cron gate and non-confirmedTeammateroster rows only. It never touchesclaudeRunningNonAgentTaskPaneKeys, never deletes the lead record, and returns before voiding onSessionStart, so the existingsource='clear'reset is untouched in either direction.claudeRunningNonAgentTaskPaneKeys.delete(paneKey)to the void turnsKEEPS a running background-shell gate across the replacementred.working → doneacross a replacement, while a background-shell-only latch staysworking.No process-identity keying is introduced.
git diffover the branch has zero hits forpid,processIdorstartTime. Liveness comes from PTY exit events (already fenced by incarnation inonPtyExit), the pre-existingprobeLiveLocalPty, and the pre-existing foreground process-table read — so there is no pid-without-start-time reuse hazard to reason about.Remote reach
Stated precisely, because it is easy to read four legs as four times the coverage:
finalizeExitpasseshostExitConfirmed: true, which certifies the death and clears the abnormal-SSH surface predicate.isForegroundTrackingAllowedreturns false for remote-runtime andapp-sshPTY ids — the OSC-133 exit fallback is disabled for SSH/WSL./exiton a remote pane, where the shell survives, is not covered.connectionId === null && isLocalExecutionHost(...).Tests
Every RED test below was run against the unmodified tree first and observed to fail.
agent-hook-listener-session-replacement.test.ts— 4 RED: a cron gate and a one-shot subagent are voided by a replacement; a child event with a foreign session id voids nothing; an event with no session id voids nothing. 4 pins that pass before and after: same session id voids nothing, aconfirmedTeammatesurvives, the background gate survives, the lead record is left alone.ended-process-reconciliation.test.ts— 5 RED:workingandwaitingrows retire; latches clear even when the row already readsdone(an interrupted lead suppresses the gate while leaving the latch set); the session owner is dropped; a pane with nothing to retire is a no-op.pty-exit-agent-status-reconciliation.test.ts— 3 RED (zero exit, physical-1via the provider callback, host-confirmed-1) plus the pin that matters most: a synthetic-1from a failed stop does not reconcile. Two further arms cover a pane bound to a transport, where a provider-observed death and a preserved SSH surface are deliberately independent decisions.restored-subagent-liveness-sweep.test.ts— a non-terminal row with no roster is now reaped, with companions asserting it is kept when the PTY is live and when the probe cannot prove either state. This replaces a test that pinned the old narrow scope.pty-connection-command-finished-cleanup.test.ts— a pane that has a status row reconciles even though its own drop removed that row first. Red against the previous commit of this branch, not merely againstmain: the pre-existing test passed there vacuously.Two guard tests were rewritten because they certified safety they never checked. Both now fail when their guard is deleted, which is the only thing that makes a "must not" test worth having:
keeps a confirmed teammate across the replacementconfirmedTeammateguard left all 8 tests green.does NOT reconcile when the process check could not confirm a shellFull typecheck, oxlint and the affected suites are green (
src/main,src/shared,src/preload, terminal-pane, store: 34,465 passing). Ten failures inpty-spawn-env-*and two siblings are pre-existing — verified by restoringpty.tstoHEADand reproducing them unchanged.Wire and persistence
No new field on
AgentHookRelayEnvelope, no new opcode, no terminal-stream change. The session anchor is in-memory and derived from asession_idthe payloads already carry.Rule 3 does apply:
src/shared/agent-hook-listener.tsruns on the relay too, so a newer relay can publishdonewhere an older one publishedworking. That is a corrected value on an existing required field — an existing legal value every shipped client already renders — so it needs no capability negotiation. A newer client paired with an older relay keeps today's behaviour for remote latches and still gains the client-side reconciliation.Merge order — read before merging any of the three
#15189,#15202and this PR all editsrc/shared/agent-hook-listener.ts, and this one also collides with #15189 insrc/shared/agent-status-types.tsandsrc/renderer/src/store/slices/agent-status.ts. GitHub reports all three MERGEABLE/CLEAN, because each is clean againstmain— that is not evidence about each other. Merging them locally in one tree produces real textual conflicts, so whichever lands last needs a manual resolution; a green mergeability badge will not warn you.All of them are additive and resolve by taking both sides. The resolved tree was built and checked:
pnpm typecheckclean, agent-status suites green. One resolution is not purely mechanical and is easy to miss: #15189 adds a fourth Claude latch (claudeUnclassifiedBackgroundTaskPaneKeys), and the merger must add it topaneHasStateClaims— which is why that predicate now lives three lines underclearPaneCacheStateinstead of inserver.ts, so the omission is visible at the conflict site rather than a file away.Process
/brennan-plan-change: plan written first, grounded in precedent, then reviewed by Claude Fable and verified by nine successive fresh Codex reviewers until one returned clean. 27 blocking defects were found and fixed before any code was written; each was re-verified against source before acceptance, and two reviewer premises were corrected rather than accepted. The most valuable finding was that the PTY-exit leg was largely redundant as first designed — which is what narrowed it to the attribution gap above.After implementation this branch went through an independent adversarial review, which returned REVISE and found the ordering bug above plus two vacuous guard tests and the resume-identity regression. All are fixed here, each with a test that fails without its fix.
Does not regress #14375 (start-less child stops mint no phantom
working; nothing here mintsworking— every path only clears) or #15082 (restored child provenance). Neither has shipped; neither is cherry-picked.