Skip to content

fix(agent-status): preserve Claude background work - #11838

Merged
nwparker merged 16 commits into
mainfrom
nwparker/Claude-code-running-but-not-indicating
Aug 2, 2026
Merged

nwparker merged 16 commits into
mainfrom
nwparker/Claude-code-running-but-not-indicating

Conversation

@nwparker

@nwparker nwparker commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Keep Claude Code's Orca status working while Claude still reports provider-owned background work, and settle to done only when the lead session reports that work is gone.

This fixes the observed mismatch where Claude's footer says 1 shell still running while Orca's sidebar and orca worktree ps already say done and 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:

  • Orca 1.4.163
  • Claude Code 2.1.220
  • macOS, local worktree
  • a background sleep that outlived the lead turn

Observed simultaneously:

Claude footer: 1 shell still running
Claude title:  ✳ Run background sleep command
Orca agent row: state: "done"

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 subagent and teammate rows from background_tasks. It discarded the shell, stored the lead as done, and let the following child lifecycle event re-emit that cached state. A one-event special case was insufficient because the immediate SubagentStop could overwrite it.

Binary inspection of Claude Code 2.1.220 confirmed 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, and cloud session.

What changed

  • Parse the complete Claude background-task inventory into two independent signals:
    • bounded visible subagent/teammate rows;
    • a pane-level boolean for any running non-agent task.
  • Keep the lead status effectively working while that boolean is set, including across Claude's follow-up child lifecycle hooks.
  • Give only lead-attributed inventories pane-level authority. Any hook carrying agent_id, plus SubagentStart, SubagentStop, and TeammateIdle, is child-owned and cannot assert, clear, interrupt, or fold lead background evidence.
  • Treat unknown task types/statuses and partial/unclassifiable inventories conservatively:
    • future non-agent types and nonterminal statuses fail active;
    • malformed or capped agent inventories are incomplete and cannot reap live child rows;
    • explicit terminal states, including teammate idle, remain non-running.
  • Preserve an authoritative value when background_tasks is absent, but clear it when the lead provides a present empty inventory.
  • Carry the boolean through relay, SSH, and WSL envelopes with boolean validation at trust boundaries.
  • Let reconnect replay seed a cold runtime, then make live observations authoritative so a later stale replay cannot re-arm the gate.
  • Block Escape/Ctrl+C fallback inference while Claude-owned background work is live.
  • Keep the field transport-only: it is excluded from renderer IPC and persisted status files.
  • Move and clear the pane-scoped state with existing cache transfer, pane teardown, inferred interruption, and listener teardown paths.
  • Preserve session-cron evidence across child lifecycle hooks, but let a modern authoritative lead Stop drain it when Claude omits an empty session_crons array.

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.220 order:

UserPromptSubmit                       -> working
Stop + running shell                  -> working
SubagentStop + same running shell     -> working
task completion notification          -> working
Stop + empty background_tasks         -> done

End-to-end transport tests additionally prove:

  • a real local POST /hook/claude with a running shell blocks false Escape inference;
  • live remote true blocks inference and live false restores it;
  • cold-runtime replay can seed evidence, but replay cannot override a later live observation;
  • relay and SSH session forwarding preserve the boolean;
  • the boolean is absent from renderer-facing snapshots and persisted JSON.

Parser/lifecycle tests prove:

  • work after the visible child-row cap is still detected;
  • state follows pane authority transfer and clears on teardown;
  • SubagentStart, SubagentStop, and TeammateIdle inventories cannot assert or retract lead evidence;
  • even an unknown child carrying is_interrupt cannot clear lead evidence;
  • lead empty inventories clear the gate, while absent or partial inventories retain safe state;
  • pending/future statuses remain active, known terminal/idle statuses do not;
  • malformed, untyped, or unparseable rows cannot incorrectly reap live child state;
  • explicit lead interruption remains terminal where that compatibility path applies.

These tests are load-bearing: without the change, the captured post-Stop/SubagentStop state is done, matching the installed-app reproduction.

Proof of no regression

Final coordinator verification at 8a922e3997, rebased onto origin/main at 8ab85c9bfc:

  • Complete shared suite from the adversarial hardening cycle: 390 files passed, 3 skipped; 3,627 tests passed, 15 skipped.
  • Main server/relay/SSH integration suite from that cycle: 3 files passed; 280 tests passed.
  • Latest merge-conflict integration suite: 10 files passed; 505 tests passed, covering listener state, inventories, main ingest, relay frame shedding/publication, SSH forwarding, WSL forwarding, and cleanup.
  • Final Opus confirmation recorded 5,247 passing tests and killed 8/8 targeted mutants before the latest rebase; the rebased implementation preserves every reviewed behavior.
  • pnpm typecheck: passed for node, CLI, and web TypeScript projects on the latest head.
  • Repository oxlint, native focused audit, type-aware audit, and changed-code quality gate: passed with zero findings.
  • pnpm exec oxfmt --check on all 12 changed files: passed.
  • pnpm run check:max-lines-ratchet: passed, no new bypasses.
  • Reliability gates, React Doctor changed-line review, localization checks, feature-wall asset budget, macOS entitlements, the root-directory guard, and git diff --check: passed.
  • pnpm run build:electron-vite: passed for main, preload, and renderer production bundles during the hardening cycle.
  • Final git range-diff marks 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 adjacent server.test.ts coverage. Resolution preserves both upstream shedFields restoration and this PR’s validated claudeRunningNonAgentTask forwarding, 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_tasks inventory. Timings are local wall-clock measurements and are intended to expose relative hot-path work, not claim production latency.

  • Rebase merge before cleanup, with duplicate full scan: 58.55 ms.
  • Parser-only baseline: 41.99 ms.
  • After duplicate-scan removal: 45.68 ms.
  • SubagentStop lifecycle path before early return: 51.01 ms.
  • SubagentStop lifecycle 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, and TeammateIdle do 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 fresh claude --model opus session, reviewed the complete origin/main...HEAD diff, was review-only, and was required to provide concrete reproductions or an explicit CLEAN verdict.

  1. Round 1 — not clean: found interruption state reopening, missing Escape/Ctrl+C protection, ambiguous child inventory ownership, and StopFailure asymmetry. Fixed lifecycle ordering, interruption handling, server inference, and cache representation.
  2. Round 2 — not clean: found child permission waits hidden after interruption, resumed turns remaining interrupted, child inventories clearing lead state, and replay overriding live authority. Fixed precedence, bounded resume behavior, lead ownership, and replay suppression.
  3. Round 3 — not clean: found child inventories able to assert pane work, case/whitespace-sensitive statuses, and a fail-inactive task-type allowlist. Switched to lead-only authority, normalized statuses/types, and made future non-agent kinds fail active.
  4. Round 4 — not clean: found TeammateIdle bypassing the child check via teammate_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.
  5. Round 5 — not clean: found agent rows with future/omitted statuses being reaped, unknown-child roster folding, no cold-runtime replay recovery, and missing local HTTP/persistence/IPC coverage. Made agent inventories fail active/incomplete, aligned lead scoping, added replay-before-live precedence, and added end-to-end proof.
  6. Round 6 — not clean: found unknown-child interrupted Stops clearing lead evidence and fully unclassifiable rows still permitting authoritative reap. Made every agent_id event child-owned and marked every unclassifiable inventory incomplete.
  7. Round 7 — CLEAN: no actionable defects. Opus revalidated all previous areas, inspected the shipped Claude 2.1.220 binary for wire-schema ground truth, reran tests/typecheck/lint, and confirmed the worktree was unchanged.

Final Opus verdict:

CLEAN. No actionable defects.

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_5b6490fd4e9a coordinated eight fresh review-only rounds with claude --model opus. Every round re-read the complete relevant diff and had to return concrete actionable findings or an explicit clean verdict.

  1. Round 1: eight findings; fixed the substantive lifecycle, ownership, and transport issues.
  2. Round 2: three findings; fixed remote-evidence acceptance ordering, independent cron state, and ambiguous status handling.
  3. Round 3: one low policy/test gap; pinned interruption semantics and hardened intake.
  4. Round 4: no implementation defect at the reviewed head.
  5. Post-CI cleanup round: found three low hardening/coverage gaps. Malformed entries now fail active, child inventory authority is non-vacuously tested, and omitted empty cron inventories drain safely.
  6. Hardening re-review: all three fixes passed mutation checks; one remaining test-only guard gap was found and pinned.
  7. Clean confirmation: 8/8 targeted mutants killed, 5,247 tests passed, all static gates passed, and no actionable finding remained.
  8. Final post-rebase confirmation — 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:

CLEAN with no actionable findings.

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 0d9f04e4be

A fresh adversarial pass over the full origin/main...HEAD diff found no correctness, lifecycle, transport, or security defect. Areas re-derived from source rather than from the log above: pane-key identity across ingestRemote's alias resolution and inferInterrupt's lookup; the accepted-evidence gate against every early return in applyNormalizedStatus; replay seeding against the relay's one-entry-per-pane cache; movePaneScopedSetEntries on 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:

  • The Stop/StopFailure predicate was written inline five times and stateName was a bare alias of reportedStateName, with both names used interchangeably in one function. Collapsed to a single isTurnBoundary constant and one state name — behavior-preserving, confirmed by the full related suite.
  • Only the interrupted StopFailure path was pinned. Added two tests: a non-interrupted StopFailure keeps gating on live background work, and interrupted state does not survive a mid-turn lead event with no prompt submit. Both were mutation-checked — narrowing isTurnBoundary to Stop kills the first, and letting interrupted escape the turn boundary kills the second.

Gates at this head: 1,822 related tests passed (3 skipped), pnpm typecheck passed for node/CLI/web, oxlint and oxfmt clean on all changed files, and check:max-lines-ratchet reported no new bypasses.

Cross-platform and workspace assessment

  • Windows / Linux / macOS / WSL: the change is transport-agnostic TypeScript and adds no OS-specific path, shortcut, shell, native module, or Git behavior. Named-pipe and socket transports continue to carry ordinary JSON; the new field is an optional boolean.
  • SSH / relay: ingress accepts the field only when its runtime type is boolean; cold replay may seed a restarted runtime, while any live observation wins over later stale replay. The focused SSH integration suite passes.
  • Mobile / renderer: mobile and desktop both consume the same normalized AgentStatusIpcPayload from getStatusSnapshot(). The transport-only boolean is stripped before IPC, snapshots, and persistence, so no protocol or mobile schema change is required.
  • Folder workspaces / git worktrees: evidence is keyed only by stable pane identity, not repository metadata. Move, pane-clear, listener-clear, and teardown paths are covered.
  • Memory / lifecycle: storage uses two O(1) pane-key Sets, bounded by live panes and cleared through existing lifecycle cleanup. Visible child rows remain capped by AGENT_STATUS_MAX_SUBAGENTS.

No platform-specific fallback is required.

Security audit

  • No new command execution, process launch, filesystem access, IPC endpoint, authentication flow, secret, dependency, or external network behavior.
  • Existing request-size and structural normalization limits still bound hook payload work.
  • Relay/SSH ingress accepts the new field only when typeof value === 'boolean'.
  • The derived boolean contains no user content and is stripped before renderer IPC and disk persistence.
  • Memory remains bounded to one Set entry per live pane and existing child-row caps; move/clear/teardown paths are covered.
  • A compromised relay already controls the pane status payload; this boolean does not expand that trust boundary.

No security follow-up is required.

Notes and trade-offs

  • Long-lived Claude-owned tasks such as monitors or dev servers intentionally keep the working indicator active. That is preferable to reporting completion while Claude itself reports live work.
  • A missing inventory retains the last authoritative value for compatibility with older or partial hooks; a present empty lead inventory clears it.
  • Existing 30-minute status freshness still bounds stale presentation.
  • This PR intentionally does not broaden into the separate permission/plan-mode cases in [Bug]: Claude Stop marks pending monitors, shells, approvals, and plans as completed #10997, which have different precedence and clearing semantics.
  • No screenshot is included because there is no component or layout change; the exact before-state, raw provider payloads, and production-path after-state are recorded above.

Final exact-head merge gate

  • Merge candidate: 27062e709968c822cf5bd26a9884d6ef2c663b12 on origin/main 4f963fd279ceeed031b7c0495f62ba920b774588.
  • Final rebase was conflict-free. git range-diff marks all 16/16 commits as exact equivalents; the three latest upstream commits touch zero PR files.
  • Final Opus feedback loop found one local-HTTP acceptance-ordering gap. Commit 27062e7099 defers both Claude background-task and session-cron evidence until the normalized status is accepted.
  • The new regression test is non-vacuous: copied onto the pre-fix parent it fails while the rejected status itself remains unchanged; on the fixed head it passes.
  • Final exact-head Opus review via Orca orchestration Run 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.
  • Coordinator post-rebase proof: 305/305 focused listener/server/relay/SSH tests, full typecheck, lint, formatting, max-lines, and git diff --check passed.
  • Final GitHub Actions run 30731878819: every Node 24/26 shard, Git compatibility, Windows packaging, static analysis, typecheck, shell contracts, root guard, and aggregate verify passed; E2E was intentionally skipped because no changed E2E specs were detected. The latest Greptile review on the exact-equivalent pre-rebase head also passed.
  • Cross-platform review remains clean for Windows, Linux, macOS, WSL, SSH/relay, mobile, folder workspaces, and git worktrees. The final fix is synchronous in-memory Set gating and adds no platform-specific path, shell, Git, native-module, renderer, or mobile behavior.
  • The final additional upstream commit, 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.

@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Claude 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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes preserving Claude background work in agent status.
Description check ✅ Passed The description covers the change, testing, AI review, security audit, cross-platform impact, screenshots, and follow-up notes.
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch nwparker/Claude-code-running-but-not-indicating

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps

greptile-apps Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a status mismatch where Orca would report an agent session as done while Claude's own UI still showed background work (shells, crons, monitors) running. The root cause was that Orca only examined subagent/teammate entries from background_tasks, discarded all other task types, and allowed a child lifecycle event (SubagentStop) to re-emit the cached done state before the shell finished.

  • Extracts claude-background-task-inventory.ts to parse the full task array: agent entries become roster rows (as before) and any non-agent entry with a non-terminal status sets a hasRunningNonAgentTask boolean, using a conservative fail-active policy for unknown/malformed entries.
  • Adds two pane-scoped Sets (claudeRunningNonAgentTaskPaneKeys, claudeActiveSessionCronPaneKeys) in HookListenerState, gated exclusively to lead events (no agent_id), and feeds them into resolveClaudePaneState to keep the effective display state working until an authoritative empty inventory arrives.
  • Introduces a normalizeLocalHookPayload rollback wrapper in the server so that Set mutations from normalizeHookPayload are deferred via an onAccepted callback, preventing rejected statuses from clearing live background-work evidence; propagates the combined boolean over the relay/SSH/WSL transport and strips it from renderer IPC and persisted files.

Confidence Score: 5/5

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

Important Files Changed

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'"
Loading

Reviews (20): Last reviewed commit: "fix(agent-hooks): gate local Claude back..." | Re-trigger Greptile

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c5f80a5f-21b0-4ef7-bc80-c4ef9fbab3d8

📥 Commits

Reviewing files that changed from the base of the PR and between 77c63d3 and 375a35a.

📒 Files selected for processing (10)
  • src/main/agent-hooks/server.test.ts
  • src/main/agent-hooks/server.ts
  • src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/relay/agent-hook-server.test.ts
  • src/relay/agent-hook-server.ts
  • src/shared/agent-hook-listener.ts
  • src/shared/agent-hook-relay.ts
  • src/shared/claude-background-task-status.test.ts
  • src/shared/claude-subagent-roster.ts

Comment thread src/main/agent-hooks/server.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 win

Restrict shell and monitor tracking to lead inventories.

Line 2627 processes child-attributed inventories before child-event handling. inventoryCanClear prevents a child inventory from clearing state, but Line 2437 still adds the pane when that inventory reports active shell or monitor work.

Only call updateClaudeRunningShellOrMonitor when eventAgentId is 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

📥 Commits

Reviewing files that changed from the base of the PR and between 375a35a and 58f0183.

📒 Files selected for processing (5)
  • src/main/agent-hooks/server.test.ts
  • src/main/agent-hooks/server.ts
  • src/shared/agent-hook-listener.ts
  • src/shared/claude-background-task-status.test.ts
  • src/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

@nwparker
nwparker force-pushed the nwparker/Claude-code-running-but-not-indicating branch 3 times, most recently from 1682700 to 6a55cd6 Compare August 1, 2026 09:15
@nwparker

nwparker commented Aug 2, 2026

Copy link
Copy Markdown
Contributor Author

Trade-offs I confirmed but left alone

Two are worth your explicit sign-off, since they're policy rather than bugs:

  1. Escape/Ctrl+C is now permanently blocked while evidence is live. If Claude exits without a draining Stop (orphaned background task), the user loses the manual escape hatch and the pane spins until the 30-minute staleness bound. The working pre-PR; losing the override is new.
  2. An explicit interrupt stays terminal even when Claude still reports a running shell — so the exact symptom in your repro can still occur via the Ctrl+C path. Deliberate and pinned by tests, but it is the one hole left in the fix.

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.

@nwparker
nwparker force-pushed the nwparker/Claude-code-running-but-not-indicating branch 2 times, most recently from 9d5ef08 to cd9363a Compare August 2, 2026 03:58
@nwparker
nwparker force-pushed the nwparker/Claude-code-running-but-not-indicating branch from cd9363a to 27062e7 Compare August 2, 2026 04:09
@nwparker
nwparker merged commit a20d822 into main Aug 2, 2026
42 checks passed
@nwparker
nwparker deleted the nwparker/Claude-code-running-but-not-indicating branch August 2, 2026 04:10
giirrr added a commit to giirrr/orca that referenced this pull request Aug 3, 2026
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.
brennanb2025 added a commit that referenced this pull request Aug 24, 2026
#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
brennanb2025 added a commit that referenced this pull request Aug 25, 2026
#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
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 25, 2026
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)
dallascrilley pushed a commit to dallascrilley/orca that referenced this pull request Aug 27, 2026
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
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* 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]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant