Skip to content

fix(agent-status): stop start-less child stops from minting phantom working - #14375

Merged
brennanb2025 merged 9 commits into
mainfrom
brennanb2025/claude-status-stuck-linear
Aug 14, 2026
Merged

brennanb2025 merged 9 commits into
mainfrom
brennanb2025/claude-status-stuck-linear

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

When Orca restarts, it forgets what each Claude pane was doing. If a subagent then finished, Orca used to guess "the parent must be busy" and show a spinner forever. Now it only says "busy" when something actually proves it, and records when its guess is based on stale, restored data.

What Changed

buildClaudeCachedLeadStatusPayload (src/shared/agent-hook-listener.ts:2775-2812) previously did:

const leadState = lead?.state ?? 'working'   // no cached lead ⇒ always working

It now takes an evidence object and, only in the no-cached-lead case, decides:

evidence result
workingChildEvidence — a roster row is working and was seen this runtime working
endedRuntimeChildWork — the row that just stopped was working and seen this runtime working
endedChildWork — a restored (disk-hydrated) row ended working + restoredUnconfirmed
none of the above null — emit nothing at all

Behavior with a cached lead is unchanged.

Two supporting pieces carry most of the weight:

  • hasCachedLeadEvidence (:2612-2620) — a cached waiting state minted by this child's own permission/question event isn't treated as lead evidence; it's the child's footprint, not a turn boundary.
  • restoredUnconfirmed provenance — new claudeUnconfirmedRestoredStatusPaneKeys set (:139), stamped onto the payload (:4482). Downstream, isFreshNonDoneAgentStatus returns false for these, so the sidebar dot, tab spinner, smart-attention and worktree ps treat the pane as not-live, and server.ts:1279 drops it from runtimeObservedStatusPaneKeys so it stays reap-eligible.

Roster changes (src/shared/claude-subagent-roster.ts): new claudeRosterHasRuntimeWorkingSubagent; stopClaudeSubagent/idleClaudeTeammateByName now clear restoredFromSnapshot and backgroundTasksAuthoritative on the row they park; reapRestoredClaudeSubagentsWithoutLiveAgent renamed to reapUnconfirmedRestoredClaudeSubagents.

Why

claudeLeadStateByPaneKey is in-memory only, so every app restart empties it. A Claude session that outlives the restart (PTYs live on the daemon) reports its next child event into an empty map. On main that unconditionally minted working with an empty roster — no Stop is coming, since the turn ended before the restart. AGENT_STATUS_STALE_AFTER_MS only decays the sidebar dot after 30 minutes; the stored row stays working and re-hydrates on next launch.

Reported as: "stuck in loading even when AI is done working — maybe coming back from sleep or from app restart (installing new update), happens fairly often."

The principle: absence of evidence must not become evidence of activity. A child stopping is the weakest possible ground for claiming the parent is busy.

Linked Issue

Linear STA-4144 (Urgent), with duplicate reports STA-3532 and STA-3522.

Visual Proof

⚠️ These captures are from the first commit on this branch and no longer depict the current implementation. They document the original defect and are kept for that purpose; the mechanism has since been reworked (see the risk section). No capture exists for the current code.

Before — Claude idle at its prompt (- · - tokens, empty input) while the sidebar card spins:

phantom-working-repro.png

After (commit 1 only) — same input, same conditions, completed glyph:

phantom-working-fixed.png

Testing

Automated — 897 passed / 4 skipped across 51 agent-hook, agent-status, roster and server files, run against the current head. tsc --noEmit -p config/tsconfig.node.json exit 0; oxlint clean.

New coverage (agent-hook-listener-startless-child-lifecycle.test.ts, 14 cases; server.test.ts, +297 lines / 7 cases) spans: unknown stop/idle with no roster → null; runtime children draining → working; restored children → working + restoredUnconfirmed; full persist → restart → hydrate → live-event round trips asserting the flag clears only on a real lead Stop; and a truncated background_tasks inventory not confirming a restored row.

Manual — the original defect was reproduced end to end against Claude Code 2.1.229 in an isolated dev instance: launch Claude, kill only the app process group so the daemon and session survive, relaunch (fresh process, empty lead cache), deliver the child event. That reproduction validated commit 1, not the current implementation.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

Review

  • Security — no new input surface; strictly narrows when a working state can be fabricated.
  • Cross-platform — pure state-resolution logic in src/shared. No paths, shells, shortcuts, or platform branches.
  • Remote SSH — no wire schema change. But restoredUnconfirmed is added to AgentHookEventPayload, a local main-process type; it is not on AgentHookRelayEnvelope and is not forwarded by relay/agent-hook-server.ts or accepted by ingestRemote. So for SSH/relay-hosted panes the marker is computed relay-side and dropped in transit — remote panes get the state-value changes but none of the provenance mitigation, and they were already excluded from the liveness reap by connectionId === null. Not a regression (main emitted a bare working too), but the fix does not cover the SSH case.
  • Mobile — locally-hosted panes now set the existing optional RuntimeWorktreeAgentRow.restoredUnconfirmed in new circumstances. Older paired clients that predate the field render those rows as ordinary fresh working: additive-optional, decodes fine, mixed-version rendering divergence rather than a wire break.
  • Backwards compatibility — panes with no subagents (the common case) are unaffected: every new gate is subagent-conditional. The one residual is that a pane with no roster receiving a stray SubagentStop now emits nothing where it previously emitted working.
  • Performance — fewer phantom transitions, so less status churn and IPC fanout.

Open questions for review

Three things a reviewer should decide on deliberately:

  1. The original phantom is still reachable, unmarked. Verified by running the listener directly: SubagentStart → clear the lead cache → SubagentStop yields state=working, restoredUnconfirmed=undefined, rosterSize=0. Because endedRuntimeChildWork is true and no restored child exists, the marker condition at :2669-2675 is false, so server.ts:1281 adds the pane to runtimeObservedStatusPaneKeys, which permanently disqualifies it from the liveness reap. This is asserted as intended behavior by the test "keeps the parent working when a current-runtime child drains with no cached lead". The real-world path is the same missed-lead-event class that emptied the cache in the first place. Is holding working here deliberate?

  2. endedChildWork → 'working' for a restored child has no guaranteed clearer. The marker correctly suppresses freshness everywhere, but the only things that can clear the state are another Claude hook (requires the user to prompt again) or the liveness reap — and the reap can't fire, for two independent reasons: candidate selection requires claudeRosterHasRestoredSnapshotSubagent, which idleClaudeTeammateByName just cleared on that row, and the reap also requires the pane to be dead, whereas the pane just proved it's alive by delivering the hook. Concrete case: restart, surviving session, teammate emits TeammateIdle, lead's turn ended pre-restart so no Stop follows, user leaves the pane at the prompt → stored working indefinitely. The visible symptom isn't a spinner but hibernation lockout, since agent-hibernation-planner.ts:147-152 rejects state !== 'done' and doesn't consult restoredUnconfirmed. Should restoredUnconfirmed make a working row hibernation-eligible, given it already means "never fresh" everywhere else?

  3. Two inference paths are disabled for marked panes — server.ts:794 and :886 skip Ctrl+C interrupt inference and AskUserQuestion answered-inference while restoredUnconfirmed is set, and running-agent-targets.ts:74-75 labels the pane "Agent status is stale" and disables it as a dispatch target. Both were designed for genuinely hydrated rows; they now also apply to a pane that just proved it is live. Intended?

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred) — targeted lint/typecheck/tests run locally as listed; full build and remaining typecheck projects left to CI

Author

  • X / Twitter: @BrennanKB5

…orking

buildClaudeCachedLeadStatusPayload fell back to 'working' whenever the pane had
no cached lead-turn state. That default is right for a spawn or a child tool
call, but the same helper serves SubagentStop and TeammateIdle, which end work
and prove the opposite.

claudeLeadStateByPaneKey is in-memory only, so every app restart empties it. A
Claude session that outlives the restart reports its next child event into an
empty map and the pane latches 'working' with an empty roster -- no Stop ever
clears it, and the 30-minute window only decays the sidebar dot, never the
stored state.

Fall back by the event's evidence: terminating child events resolve to 'done',
which still gates up through resolveClaudePaneState when the roster or
background work proves the pane is busy.
@coderabbitai

coderabbitai Bot commented Aug 13, 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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b13062c4-6c8e-491a-a295-fe401322e13c

📥 Commits

Reviewing files that changed from the base of the PR and between a147b4d and 50b35d2.

📒 Files selected for processing (2)
  • src/shared/agent-hook-listener-startless-child-lifecycle.test.ts
  • src/shared/claude-subagent-roster.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/shared/claude-subagent-roster.ts
  • src/shared/agent-hook-listener-startless-child-lifecycle.test.ts

📝 Walkthrough

Walkthrough

The listener now handles missing Claude child rosters, creates rosters on child starts, updates restored-row markers, removes matching children, and deletes empty rosters. Confirmed child removal can resolve cached lead state to done, while runtime child activity preserves working. Tests cover start-less events, sibling activity, waiting children, live leads, roster retention, teammate idle events, runtime liveness, and restored state after restart.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% 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.
Description check ✅ Passed The description includes all required sections and gives clear scope, rationale, testing details, limitations, and review considerations.
Title check ✅ Passed The title clearly and concisely describes the main fix: preventing phantom working states from start-less child stops.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/shared/agent-hook-listener.ts (1)

2590-2594: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Shorten the added lifecycle comments.

Keep the rationale, but use one concise line at each location. The current comments restate control flow and make the state transition harder to scan.

Proposed change
-/** Child lifecycle events that end work. They say nothing about the lead being busy, so they must never be the reason a pane reads 'working'. */
+/** Stop and idle child events do not prove lead activity. */
...
-// Why: with no cached lead (Orca restarted mid-session) the fallback must follow the event's
-// evidence. A spawn or child tool call proves activity; a stop/idle proves the opposite, so
-// defaulting those to 'working' mints a phantom no Stop will ever clear. 'done' still gates up
-// through resolveClaudePaneState when the roster or background work proves the pane is busy.
+// When the lead cache is missing, terminating child events default to done.

As per coding guidelines, comments must be concise, non-obvious, and brief—prefer one line.

Also applies to: 2731-2735

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3943e57f-3690-4c7c-b126-90c101c8223d

📥 Commits

Reviewing files that changed from the base of the PR and between ff8dda8 and d0fab8d.

📒 Files selected for processing (2)
  • src/shared/agent-hook-listener-startless-child-lifecycle.test.ts
  • src/shared/agent-hook-listener.ts

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Visual QA @ e8de2d46563964e9e50c65384610af4848781a9a

Validated this exact worktree HEAD in an isolated Electron instance (ORCA_DEV_USER_DATA_PATH + CDP 9334). window.api.app.getIdentity() resolved sta-4144-phantom-working @ brennanb2025/claude-status-stuck-linear before any UI interaction. No source edits.

Actions

  1. Added this worktree as a disposable project in the isolated profile and launched a real idle Claude Code TUI (v2.1.231) in the visible pane.
  2. Posted UserPromptSubmit on /hook/claude while Claude stayed at an empty prompt → phantom working.
  3. Posted an unknown start-less SubagentStop (no new status claim), then identity-matched SubagentStart / SubagentStop plus lead Stop with an empty background_tasks inventory.

Results

  • Before: idle Claude prompt + worktree card / Claude row / tab all Working.
  • After: same idle Claude prompt + card / row / tab settled to Done (last-status.json persisted state: "done").
  • Renderer console: one 404 from a failed dynamic import of launch-agent-in-new-tab.ts (unused after launching Claude in the existing terminal). App log: isolated-profile terminal_liveness_unavailable on orchestration recovery, Claude usage refresh 401. No secrets or tokens in screenshots or logs.

Visual QA: passed for the user-visible idle-Claude + phantom-working → settled-done path.

Evidence

Before — idle Claude with phantom working

01-before-phantom-working.png

After — identity-safe lifecycle + lead completion

02-after-settled-done.png

Limitation

This live pass did not restart the app to replay last-status hydration with an empty in-memory lead cache. The start-less unknown SubagentStop ran after UserPromptSubmit had already cached a live lead, so the no-cached-lead restart matrix remains covered by the existing automated tests rather than this screenshot pair.

@brennanb2025
brennanb2025 merged commit d137bb9 into main Aug 14, 2026
44 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…orking (stablyai#14375)

* fix(agent-status): stop start-less child stops from minting phantom working

buildClaudeCachedLeadStatusPayload fell back to 'working' whenever the pane had
no cached lead-turn state. That default is right for a spawn or a child tool
call, but the same helper serves SubagentStop and TeammateIdle, which end work
and prove the opposite.

claudeLeadStateByPaneKey is in-memory only, so every app restart empties it. A
Claude session that outlives the restart reports its next child event into an
empty map and the pane latches 'working' with an empty roster -- no Stop ever
clears it, and the 30-minute window only decays the sidebar dot, never the
stored state.

Fall back by the event's evidence: terminating child events resolve to 'done',
which still gates up through resolveClaudePaneState when the roster or
background work proves the pane is busy.

* fix(agent-status): require evidence for child completion

* fix(agent-status): publish matched teammate idle

* fix(agent-status): preserve confirmed child work

* fix(agent-status): retain live restored teammates

* fix(agent-status): reap unconfirmed siblings after child drain

* fix(agent-status): preserve unmatched restored children

* fix(agent-status): wait for lead completion after child stop

* fix(agent-status): persist restored child transitions

---------

Co-authored-by: Brennan Benson <[email protected]>
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