Repository navigation
fix(agent-status): preserve Claude background work - #11838
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughClaude background-task parsing now detects active shell and monitor tasks, including entries beyond the agent-task cap. The listener stores this activity per pane and uses it in lifecycle state resolution. Relay envelopes and remote ingestion carry the activity indicator without persisting runtime-only state. Interrupted stops clear cached activity and remain terminal. Tests cover parsing, transitions, migration, interruption handling, relay propagation, and cache cleanup. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 2📝 Generate docstrings 💡
⚔️ Resolve merge conflicts 💡
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 |
Greptile SummaryThis PR fixes a status mismatch where Orca would report an agent session as
Confidence Score: 5/5Safe to merge; all new state is O(1) per live pane, transport-only, and cleared through existing lifecycle paths. The change is purely in-memory TypeScript with no new I/O, filesystem access, IPC endpoints, or cross-platform native behavior. The conservative fail-active inventory parser, the rollback wrapper that guards Set mutations until a status is accepted, the child-authority isolation, and the replay-vs-live precedence rule are all directly verified by a purpose-built regression test that reproduces the exact Claude 2.1.220 event sequence. The full suite of 1,800+ related tests plus typecheck, lint, and format gates all pass at head. Files Needing Attention: No files require special attention. The most complex new pattern—the normalizeLocalHookPayload rollback mechanism in server.ts—is load-bearing for the rejected-status tests and is exercised from both the local HTTP path and the remote ingestRemote path.
|
| Filename | Overview |
|---|---|
| src/shared/claude-background-task-inventory.ts | New module splitting background-task parsing from the roster; conservative fail-active design handles malformed/future entries by treating them as running |
| src/shared/agent-hook-listener.ts | Adds two pane-keyed Sets for non-agent task and cron evidence, refactors lead/child ownership, adds resolveClaudePaneState and updateClaudeRunningNonAgentTask helpers; all edge cases covered by the new test suite |
| src/main/agent-hooks/server.ts | Introduces normalizeLocalHookPayload rollback pattern to defer background-evidence mutation until status is accepted; adds inferInterrupt guard; clears Sets on connection teardown; excludes the field from persistence |
| src/shared/claude-background-task-status.test.ts | New comprehensive test file covering the full regression scenario, child-authority isolation, cron draining, interrupted-stop terminal semantics, and teardown paths |
| src/main/agent-hooks/server.test.ts | Adds end-to-end tests for interrupt inference gating, local HTTP path rejection, remote replay ordering, and persistence exclusion of the new transport field |
| src/shared/claude-subagent-roster.ts | Removes hasActiveClaudeNonAgentBackgroundWork and old readClaudeBackgroundAgentTasks (superseded by the new inventory module); imports ClaudeBackgroundAgentTask type from the new location |
| src/relay/agent-hook-server.ts | One-line addition forwarding claudeRunningNonAgentTask into the relay envelope; tested by the new relay test |
| src/main/ssh/ssh-relay-session.ts | Passes claudeRunningNonAgentTask through the SSH relay envelope with typeof-boolean validation at the trust boundary |
| src/shared/agent-hook-relay.ts | Type-only addition of the optional claudeRunningNonAgentTask boolean to AgentHookRelayEnvelope |
Sequence Diagram
sequenceDiagram
participant C as Claude CLI
participant L as agent-hook-listener
participant S as AgentHookServer
participant UI as Orca UI
C->>S: "Stop {background_tasks:[shell]}"
S->>L: normalizeHookPayload() [saves prev Sets]
L->>L: updateClaudeRunningNonAgentTask(pane, true)
L-->>S: "event{state:'working'}"
S->>L: rollback Sets to prev
S->>S: applyNormalizedStatus accepted
S->>L: "onAccepted() apply next Sets (task=true)"
S-->>UI: "state='working'"
C->>S: "SubagentStop {agent_id:'child', background_tasks:[shell]}"
S->>L: normalizeHookPayload()
Note over L: agent_id present -> child path, lead Sets NOT touched
L-->>S: "event{state:'working'} re-emits lead+roster"
S-->>UI: "state='working' background gate holds"
C->>S: "Stop {background_tasks:[]}"
S->>L: normalizeHookPayload()
L->>L: updateClaudeRunningNonAgentTask(pane, false)
L-->>S: "event{state:'done'}"
S->>L: rollback Sets
S->>S: applyNormalizedStatus accepted
S->>L: "onAccepted() apply next Sets (task=false)"
S-->>UI: "state='done'"
Reviews (20): Last reviewed commit: "fix(agent-hooks): gate local Claude back..." | Re-trigger Greptile
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: c5f80a5f-21b0-4ef7-bc80-c4ef9fbab3d8
📒 Files selected for processing (10)
src/main/agent-hooks/server.test.tssrc/main/agent-hooks/server.tssrc/main/ssh/ssh-relay-session-agent-hooks.integration.test.tssrc/main/ssh/ssh-relay-session.tssrc/relay/agent-hook-server.test.tssrc/relay/agent-hook-server.tssrc/shared/agent-hook-listener.tssrc/shared/agent-hook-relay.tssrc/shared/claude-background-task-status.test.tssrc/shared/claude-subagent-roster.ts
There was a problem hiding this comment.
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)
2627-2635: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winRestrict shell and monitor tracking to lead inventories.
Line 2627 processes child-attributed inventories before child-event handling.
inventoryCanClearprevents a child inventory from clearing state, but Line 2437 still adds the pane when that inventory reports active shell or monitor work.Only call
updateClaudeRunningShellOrMonitorwheneventAgentIdis undefined. Add a regression case where a child inventory contains a running shell and does not change lead-pane background activity.Proposed fix
- if (backgroundTasks.present) { + if (backgroundTasks.present && eventAgentId === undefined) { updateClaudeRunningShellOrMonitor( state, paneKey, backgroundTasks.hasRunningShellOrMonitor, interrupted === true, eventAgentId === undefined ) }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 71a57d9f-c9b6-4427-80d6-5802323fe519
📒 Files selected for processing (5)
src/main/agent-hooks/server.test.tssrc/main/agent-hooks/server.tssrc/shared/agent-hook-listener.tssrc/shared/claude-background-task-status.test.tssrc/shared/claude-subagent-roster.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- src/shared/claude-subagent-roster.ts
- src/main/agent-hooks/server.ts
- src/main/agent-hooks/server.test.ts
1682700 to
6a55cd6
Compare
|
Trade-offs I confirmed but left alone Two are worth your explicit sign-off, since they're policy rather than bugs:
Gates at this head: 1,822 related tests pass (3 skipped), pnpm typecheck lint + oxfmt clean on all changed files, max-lines ratchet reports no newbypasses. Full CI hasn't spun up yet beyond Greptile. |
9d5ef08 to
cd9363a
Compare
Collapse the five inline copies of the Stop/StopFailure test into a single isTurnBoundary constant and drop the reportedStateName/stateName alias, so a future edit can't move one copy and leave the others behind. Pin the two behaviors that unification now depends on: a non-interrupted StopFailure keeps gating on live background work, and interrupted state does not survive a mid-turn lead event that has no prompt submit. Co-authored-by: Orca <[email protected]>
cd9363a to
27062e7
Compare
Conflict resolution: main gave `applyNormalizedStatus` an `onAccepted` callback (stablyai#11838, Claude background work), and this branch inserted `updateClaudeAnnouncedToolUses` just above it. Both are kept — the new method stays and the method now takes main's signature. Checked the ordering the ledger depends on rather than only the text: the announcement update still runs before `shouldKeepClaudePermissionVisible` and before every sticky `return previous`, and main's new early return (`providerSessionOnly`) is Pi-gated, so no Claude payload can reach it and skip the ledger.
#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
#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
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
* fix(agent-status): preserve Claude background work * fix(agent-status): harden background task lifecycle * fix(agent-status): narrow interruption retention * fix(agent-status): scope background task authority * fix(agent-status): isolate lifecycle inventories * fix(agent-status): harden background evidence recovery * fix(agent-status): reject ambiguous child authority * perf(agent-status): skip lifecycle inventory scans * refactor(agent-status): isolate task inventory parsing * fix(agent-status): clear stale background evidence * fix(agent-status): gate accepted remote evidence * test(agent-status): pin session cron interrupts * fix: harden Claude inventory tracking * test: pin Claude cron drain authority * refactor(agent-status): unify Claude turn-boundary predicate Collapse the five inline copies of the Stop/StopFailure test into a single isTurnBoundary constant and drop the reportedStateName/stateName alias, so a future edit can't move one copy and leave the others behind. Pin the two behaviors that unification now depends on: a non-interrupted StopFailure keeps gating on live background work, and interrupted state does not survive a mid-turn lead event that has no prompt submit. Co-authored-by: Orca <[email protected]> * fix(agent-hooks): gate local Claude background evidence --------- Co-authored-by: Orca <[email protected]>
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
Summary
Keep Claude Code's Orca status
workingwhile Claude still reports provider-owned background work, and settle todoneonly when the lead session reports that work is gone.This fixes the observed mismatch where Claude's footer says
1 shell still runningwhile Orca's sidebar andorca worktree psalready saydoneand remove the spinner.Addresses the background-task portion of #10997. Related prior attempts: #8853 and #10998.
Reproduction and root cause
Reproduced before the change with:
1.4.1632.1.220sleepthat outlived the lead turnObserved simultaneously:
The installed Claude binary emitted this exact sequence:
{"event":"Stop","background_tasks":[{"id":"b8rs2wmxg","type":"shell","status":"running","description":"Sleep for 15 seconds","command":"sleep 15"}]} {"event":"SubagentStop","agent_id":"a70fdf2986e38302b","background_tasks":[{"id":"b8rs2wmxg","type":"shell","status":"running","description":"Sleep for 15 seconds","command":"sleep 15"}]}When the shell finished, Claude emitted its completion notification and then:
{"event":"Stop","background_tasks":[]} {"event":"SubagentStop","agent_id":"a8ab60ba5d4410c47","background_tasks":[]}Orca previously extracted only
subagentandteammaterows frombackground_tasks. It discarded the shell, stored the lead asdone, and let the following child lifecycle event re-emit that cached state. A one-event special case was insufficient because the immediateSubagentStopcould overwrite it.Binary inspection of Claude Code
2.1.220confirmed that the wire inventory includes running/pending work and currently maps these provider task families:subagent,teammate,workflow,shell,monitor,MCP task,dream,auto-mode scan, andcloud session.What changed
subagent/teammaterows;workingwhile that boolean is set, including across Claude's follow-up child lifecycle hooks.agent_id, plusSubagentStart,SubagentStop, andTeammateIdle, is child-owned and cannot assert, clear, interrupt, or fold lead background evidence.idle, remain non-running.background_tasksis absent, but clear it when the lead provides a present empty inventory.session_cronsarray.ELI5
Claude can say, “I’m done talking,” while a job it started is still running in the background. Orca used to hear only “I’m done” and turn off the working light.
Now Orca also checks Claude's attached job list. If a background job is still alive, the working light stays on. Only Claude's main session may update that shared job-list signal, so a child agent's bookkeeping message cannot accidentally turn the light off—or turn it on. When the main session later sends an empty list, Orca marks the work finished.
Proof of fix
The production normalizer regression test replays the captured Claude
2.1.220order:End-to-end transport tests additionally prove:
POST /hook/claudewith a running shell blocks false Escape inference;trueblocks inference and livefalserestores it;Parser/lifecycle tests prove:
SubagentStart,SubagentStop, andTeammateIdleinventories cannot assert or retract lead evidence;is_interruptcannot clear lead evidence;These tests are load-bearing: without the change, the captured post-
Stop/SubagentStopstate isdone, matching the installed-app reproduction.Proof of no regression
Final coordinator verification at
8a922e3997, rebased ontoorigin/mainat8ab85c9bfc:pnpm typecheck: passed for node, CLI, and web TypeScript projects on the latest head.pnpm exec oxfmt --checkon all 12 changed files: passed.pnpm run check:max-lines-ratchet: passed, no new bypasses.git diff --check: passed.pnpm run build:electron-vite: passed for main, preload, and renderer production bundles during the hardening cycle.git range-diffmarks 12/15 commits as exact equivalents. The other three intentionally integrate newly merged relay frame-shedding metadata/tests alongside this PR’s Claude background-work transport field; no PR behavior was dropped.The only textual conflicts were in
server.ts,ssh-relay-session.ts, and adjacentserver.test.tscoverage. Resolution preserves both upstreamshedFieldsrestoration and this PR’s validatedclaudeRunningNonAgentTaskforwarding, plus both upstream roster-shedding tests and the PR’s connection-cleanup test. No conflict markers or uncommitted changes remain.Performance evidence
Synthetic worst-case benchmark: 200 hook events, each carrying a 10,000-row
background_tasksinventory. Timings are local wall-clock measurements and are intended to expose relative hot-path work, not claim production latency.SubagentStoplifecycle path before early return: 51.01 ms.SubagentStoplifecycle path after early return: 0.29 ms median across seven samples (~176x faster; ~99.4% less time).The optimized lifecycle path is correct because
SubagentStart,SubagentStop, andTeammateIdledo not own pane-wide inventory authority; they update only the bounded roster and reuse pane-cached lead evidence. The retained lead path still performs one complete scan so capped or future task kinds cannot be missed.Adversarial AI review report
Review was coordinated through Orca orchestration Run
run_04348f604e05. Each round used a freshclaude --model opussession, reviewed the completeorigin/main...HEADdiff, was review-only, and was required to provide concrete reproductions or an explicitCLEANverdict.TeammateIdlebypassing the child check viateammate_name, insufficient remote-ingest coverage, and missing/non-string task types failing inactive. Moved lifecycle handling ahead of inventory authority, hardened parsing, and tested the public remote path in both directions.agent_idevent child-owned and marked every unclassifiable inventory incomplete.CLEAN: no actionable defects. Opus revalidated all previous areas, inspected the shipped Claude2.1.220binary for wire-schema ground truth, reran tests/typecheck/lint, and confirmed the worktree was unchanged.Final Opus verdict:
Non-blocking suggestions were limited to cleanup/documentation and future product-policy choices (dead condition members, long-lived background-task presentation, and possible SessionEnd handling); none changes the correctness or merge readiness of this fix.
Fresh post-rebase Opus review
Orca orchestration Run
run_5b6490fd4e9acoordinated eight fresh review-only rounds withclaude --model opus. Every round re-read the complete relevant diff and had to return concrete actionable findings or an explicit clean verdict.CLEAN: verified all 14 commits as exact equivalents, proved the dropped lint patch is byte-identical upstream, checked the three new upstream commits for interaction, reran 337 focused tests and all static gates, and found no actionable issue.Final Opus verdict at
6a55cd6fba:The reviewer explicitly found no correctness, security, performance, lifecycle/memory, transport, or Windows/Linux/macOS/WSL/SSH/relay/mobile/folder-workspace/git-worktree regression.
Independent review round at
0d9f04e4beA fresh adversarial pass over the full
origin/main...HEADdiff found no correctness, lifecycle, transport, or security defect. Areas re-derived from source rather than from the log above: pane-key identity acrossingestRemote's alias resolution andinferInterrupt's lookup; the accepted-evidence gate against every early return inapplyNormalizedStatus; replay seeding against the relay's one-entry-per-pane cache;movePaneScopedSetEntrieson plain (non-composite) pane keys; and the absence of any renderer-side optimistic interrupt path that could bypass the main-process gate.Two maintainability findings were fixed:
stateNamewas a bare alias ofreportedStateName, with both names used interchangeably in one function. Collapsed to a singleisTurnBoundaryconstant and one state name — behavior-preserving, confirmed by the full related suite.StopFailurepath was pinned. Added two tests: a non-interruptedStopFailurekeeps gating on live background work, and interrupted state does not survive a mid-turn lead event with no prompt submit. Both were mutation-checked — narrowingisTurnBoundarytoStopkills the first, and lettinginterruptedescape the turn boundary kills the second.Gates at this head: 1,822 related tests passed (3 skipped),
pnpm typecheckpassed for node/CLI/web, oxlint and oxfmt clean on all changed files, andcheck:max-lines-ratchetreported no new bypasses.Cross-platform and workspace assessment
AgentStatusIpcPayloadfromgetStatusSnapshot(). The transport-only boolean is stripped before IPC, snapshots, and persistence, so no protocol or mobile schema change is required.Sets, bounded by live panes and cleared through existing lifecycle cleanup. Visible child rows remain capped byAGENT_STATUS_MAX_SUBAGENTS.No platform-specific fallback is required.
Security audit
typeof value === 'boolean'.No security follow-up is required.
Notes and trade-offs
Final exact-head merge gate
27062e709968c822cf5bd26a9884d6ef2c663b12onorigin/main4f963fd279ceeed031b7c0495f62ba920b774588.git range-diffmarks all 16/16 commits as exact equivalents; the three latest upstream commits touch zero PR files.27062e7099defers both Claude background-task and session-cron evidence until the normalized status is accepted.run_5b6490fd4e9a: CLEAN with no actionable findings. It independently confirmed 16/16 range-diff equivalence, zero upstream overlap, 342/342 focused tests, node/CLI/web typecheck, oxlint, max-lines, and 61/61 reliability gates.git diff --checkpassed.30731878819: every Node 24/26 shard, Git compatibility, Windows packaging, static analysis, typecheck, shell contracts, root guard, and aggregateverifypassed; E2E was intentionally skipped because no changed E2E specs were detected. The latest Greptile review on the exact-equivalent pre-rebase head also passed.fix(browser): remove unsafe window close bypass (#12040), changes only browser/window/session code and has zero overlap with the PR's agent-hook files; the last rebase remains 16/16 exact-equivalent.