Skip to content

feat(agent-status): show Claude subagent child rows and gate premature done - #8211

Merged
brennanb2025 merged 3 commits into
mainfrom
brennanb2025/fix-agent-status-indicator
Jul 11, 2026
Merged

brennanb2025 merged 3 commits into
mainfrom
brennanb2025/fix-agent-status-indicator

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Problem

A Claude pane that spawned background subagents/teammates showed the green done ✅ the moment the lead's turn ended — even while a background review loop was still running (report: "Says ✅ but should not be"). Orca had no visibility into the pane's children: the Stop hook mapped unconditionally to done, and teammate turn-ends emit SubagentStop, which Orca didn't register.

What this does

  • Tracks the pane's live subagents/teammates in a per-pane roster inside the shared hook listener, fed by newly registered SubagentStart / SubagentStop / TeammateIdle hooks plus child-origin tool events (which carry agent_id; lead events don't).
  • Gates Stop → done: the pane stays working while at least one child is working. Claude wakes the lead when a child finishes, so the pane resolves to ✅ on the follow-up Stop with an empty roster.
  • Renders children as indented rows under the pane's sidebar row (name/type + working/idle dot), reusing the existing lineage UI (rowSource: 'subagent', activation focuses the parent pane, no dismiss X, alive-idle teammates don't read "done").

Design notes (verified live on Claude Code 2.1.207)

Empirical payload captures drove the design; the naive approach (trust background_tasks on Stop) is wrong in interactive/teams mode:

  • Teammates report status: "running" in background_tasks even while idle-alive, so that list cannot decide teammate working-ness (TeammateIdle, keyed by teammate_name, is the idle signal).
  • Teammate lifecycle agent_ids (a<name>-<hex>) never match background_tasks task ids — a reconcile-replace creates duplicate child rows.
  • One-shot -p-mode subagents DO reuse agent_id as the task id, so id-exact folds and restart self-heal are safe there.

Hence: lifecycle events own the roster; background_tasks is folded only where unambiguous (empty list clears; id-exact matches update; unmatched running non-teammate entries are recreated after a restart).

Guard-rails kept intact: child-origin tool events no longer overwrite the lead's tool/prompt caches (a live AskUserQuestion card survives child churn); a child's own PermissionRequest records waitingAgentId so only that child's progress — or death — clears the wait; the interrupted flag survives the gated window; inferInterrupt refuses while a child works and syncs the lead record; hydration reseeds the roster after a restart.

Review

Two independent review rounds (a Fable reviewer agent + a codex exec gpt-5.6-sol high reviewer per round) targeting regressions and performance. All confirmed findings fixed (child-permission clearing, interrupt-badge persistence, restart self-heal, inferInterrupt desync, stuck-wait on killed child, hydration reseed, dead dismiss control, idle-row "done" mislabel). Round 2 verdict: MINOR-ONLY with fixes cross-validated.

Round 3: adversarial re-review + hardening (07a85765f)

A four-lane adversarial pass (correctness/state-machine, contract/consumer trace, adversarial scenarios, perf audit) over the finished branch. Perf verdict: no regression — the Claude normalizer now validates the payload object directly instead of a JSON stringify/parse round trip (net faster hot path), roster work is bounded by the 32-cap, and both new listener maps are cleared on every pane-teardown path. Contract trace: subagents verified through IPC, persistence, and relay re-normalization; web/mobile clients deliberately never receive it (zero cross-version schema risk). Four confirmed findings fixed:

  • Lead state displaced by a child wait was never restored. A child's PermissionRequest overwrote the lead's done, and clearing the wait invented working — the done-gate never upgrades back, so the pane spun forever after the roster drained (until the lead's next wake turn). The pre-wait lead state (incl. interrupted) is now stashed in ClaudeLeadTurnState.stateBeforeWait and restored on both clear paths; a second concurrent wait carries the original stash forward.
  • Phantom working child after restart never reconciled. The background_tasks fold was additive-only, so a snapshot-seeded child whose SubagentStop was lost during downtime gated the pane working indefinitely in teams sessions (their task list is never empty). Seeded and fold-recreated entries are now tagged backgroundTasksAuthoritative and demoted when a present list omits their id; live lifecycle activity clears the tag, so real teammates (whose ids legitimately never appear in the list) keep their state.
  • TeammateIdle hyphen-prefix collision. The a<name>- prefix match let teammate "lane" idle "lane-hooks"'s rows and clear its pending wait. claudeTeammateIdMatchesName now requires a hyphen-free suffix (the <hex> tail) and is shared by the roster and the wait-clear predicate.
  • Defensive guard for raw child turn-boundary events. A Stop/StopFailure/UserPromptSubmit carrying a known child's agent_id (a CLI that stops converting child Stops to SubagentStop) is re-emitted as child activity instead of being adopted as the lead's state; the prompt-cache new-turn reset is now tied to lead-origin events so child-driven refreshes can't blank the prompt label.

Accepted limitations (called out by reviewers, deliberate)

  • One waiting slot per pane (matches pre-existing behavior; concurrent lead+child waits show the latest).
  • interrupted is lost if Orca restarts during the gated child-working window (narrow; drain then reads as normal completion).
  • 32-child roster cap: a 33rd concurrent working child is not tracked (far above Claude's real concurrency).
  • Child rows are sidebar-only for now; the full-screen Agents dashboard is a follow-up.

Tests

  • Live end-to-end in a dev instance (demo-project, real Claude 2.1.207 TUI): spawned background teammates; pane stayed amber-working with indented child rows ("Working - probe3" / "Idle - probe2") after the lead's turn ended — the exact moment that previously showed ✅ — then settled to ✅ with idle children when the last child finished. Store-level evidence captured at each phase (state/subagents on the pane entry).
  • Hook payloads ground-truthed against scratch Claude sessions (foreground, background, teams mode) before implementation.
  • Round-3 fixes verified live (dev instance of this branch): real-CLI run — lead spawns a background subagent, ends its turn, child hits a Bash permission gate (waiting + working child row), approve in the TUI, child drains → pane resolves done at SubagentStop (recorded store timeline; impossible pre-fix). Restart-phantom demotion, hyphen-teammate scoping, and the raw-child-Stop guard exercised against the real local hook HTTP endpoint with recorded state timelines; sidebar UI (child rows, needs-permission state, hydrated idle rows) verified visually at each step.
  • Unit: 463 tests across listener, roster, status-types normalization, hook-service/remote installers, server (HTTP hook path, inferInterrupt, permission stickiness), sidebar row builders, and the store slice — all green (round 3 adds 12: wait-restore, phantom demotion, authoritative-tag lifecycle, hyphen matching, turn-boundary guard).
  • pnpm typecheck, pnpm lint (incl. max-lines ratchet — normalizers split into agent-status-field-normalization.ts, no suppressions), git diff --check — clean.
  • Full unit suite: 5 failing files are pre-existing on the base commit (verified identical failures on a clean HEAD worktree); nothing touched by this diff fails. (CI verify flaked once on the untouched pty-connection WSL foreground-sampling perf test — passes 5/5 locally on the exact merge ref; rerun green.)
  • SSH relay path exercised live (shared listener is covered by relay unit suite — 729 tests — but no live SSH session was run).

Brennan Benson added 2 commits July 10, 2026 21:34
…e done

A Claude pane that spawned background subagents/teammates showed a green
done check the moment the lead's turn ended, even while a background
review loop was still running. Orca now tracks the pane's live children
from Claude hook events and:

- keeps the pane 'working' while at least one child is working (Stop is
  gated; Claude wakes the lead when a child finishes, so the pane
  resolves to done on the follow-up Stop with an empty roster)
- renders the children as indented child rows under the pane's sidebar
  row (name/type + working/idle dot), reusing the existing lineage UI

Tracking is lifecycle-primary: SubagentStart/SubagentStop/TeammateIdle
(newly registered hooks) plus child-origin tool events (they carry
agent_id) own the roster. Stop's background_tasks is folded only where
unambiguous — verified live on Claude Code 2.1.207 that teammates report
status "running" while idle-alive and their task ids never match
lifecycle agent_ids, so the list cannot decide teammate working-ness.

Child-origin events no longer overwrite the lead's tool/prompt caches
(a live AskUserQuestion card survives child churn); a child's own
PermissionRequest records waitingAgentId so only that child's progress
or death clears the wait. The interrupted flag survives the gated
window, inferred interrupts sync the lead record and refuse while a
child works, and hydration reseeds the roster after a restart.
The child's agentType carries its NAME (e.g. "pr-reviewer"), which is not
an iconable agent and rendered the unknown "?" glyph. Nesting under the
parent row already conveys identity.
@coderabbitai

coderabbitai Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds normalized subagent snapshots to agent status payloads and implements a capped Claude roster with lifecycle and background-task reconciliation. Claude listener state now tracks per-pane subagents, preserves lead interruption and waiting state, and restores rosters from persisted snapshots. IPC and status storage retain subagent data. Dashboard and sidebar views render derived child rows that activate the parent pane, suppress inappropriate dismissal controls, and handle idle timestamps. Tests cover normalization, lifecycle transitions, interruption inference, persistence, and row derivation.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.78% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description is detailed, but it does not follow the required template and omits explicit Screenshots and Security Audit sections. Add the template sections with clear headings, include screenshots or 'No visual change', a security audit, and the testing checklist items.
✅ Passed checks (3 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 is concise and accurately summarizes the main change: Claude subagent child rows and delaying done status.
✨ Finishing Touches
📝 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 (3)
src/renderer/src/components/sidebar/worktree-card-compact-agent-row.tsx (1)

30-34: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider extracting lastEnteredDoneAt to a shared utility.

This function is duplicated in DashboardAgentRow.tsx (lines 52-69) and worktree-card-compact-agent-row.tsx (lines 29-45) with a minor inconsistency: this copy uses entry.stateHistory?.length ?? 0 (defensive optional chaining) while the dashboard copy uses entry.stateHistory.length (direct access). Since stateHistory is typed as a required AgentStateHistoryEntry[], both work, but the divergence suggests the copies were authored independently. Extracting to a shared getLastEnteredDoneAt(agent) utility would eliminate the drift risk as the subagent idle-guard logic evolves.

Also applies to: 133-137

src/shared/agent-status-types.ts (1)

299-314: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Dedupe subagents by id before capping.

normalizeSubagentsField pushes every structurally-valid snapshot without checking for duplicate ids. Downstream, buildSubagentChildRows (src/renderer/src/components/sidebar/worktree-subagent-child-rows.ts:20-63) derives each child row's paneKey from subagent.id, so duplicate ids in the normalized array produce duplicate paneKeys/React keys and broken/duplicated sidebar rows. The normal pipeline (Claude roster → claudeRosterToSnapshots, which is Map-keyed and therefore always unique) never triggers this, but this function is a generic boundary parser over unknown (also used for hydration from an on-disk file and for re-normalizing IPC payloads), so a corrupted/hand-crafted payload can reach it with duplicate ids.

🛡️ Proposed fix to dedupe by id
 function normalizeSubagentsField(value: unknown): AgentSubagentSnapshot[] | undefined {
   if (!Array.isArray(value) || value.length === 0) {
     return undefined
   }
   const normalized: AgentSubagentSnapshot[] = []
+  const seenIds = new Set<string>()
   for (const item of value) {
     const snapshot = normalizeSubagentSnapshot(item)
-    if (snapshot) {
+    if (snapshot && !seenIds.has(snapshot.id)) {
+      seenIds.add(snapshot.id)
       normalized.push(snapshot)
       if (normalized.length >= AGENT_STATUS_MAX_SUBAGENTS) {
         break
       }
     }
   }
   return normalized.length > 0 ? normalized : undefined
 }
src/shared/claude-subagent-roster.ts (1)

3-6: 📐 Maintainability & Code Quality | 🔵 Trivial

Verify CLAUDE_SUBAGENT_ID_MAX_LENGTH stays in sync with agent-status-types.ts.

The comment states this constant Mirrors the wire-normalization id cap in agent-status-types. Enforced at upsert so an over-long id can't gate the pane 'working' while being invisible in the emitted snapshots. Duplicating the numeric literal instead of importing a shared constant from agent-status-types.ts risks silent drift if that cap changes there.

♻️ Suggested direction
-const CLAUDE_SUBAGENT_ID_MAX_LENGTH = 64
+import { AGENT_STATUS_SUBAGENT_ID_MAX_LENGTH } from './agent-status-types'

(exporting the cap from agent-status-types.ts and reusing it here, rather than a second literal.)

Also applies to: 38-38


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: b29e87e8-6181-4fc5-b011-d5fdc7964838

📥 Commits

Reviewing files that changed from the base of the PR and between 4df9457 and c84fc40.

📒 Files selected for processing (20)
  • src/main/agent-hooks/server.test.ts
  • src/main/agent-hooks/server.ts
  • src/main/claude/hook-service.test.ts
  • src/main/claude/hook-settings.ts
  • src/renderer/src/components/dashboard/DashboardAgentRow.tsx
  • src/renderer/src/components/dashboard/DashboardAgentRowTrailingControls.tsx
  • src/renderer/src/components/dashboard/useDashboardData.ts
  • src/renderer/src/components/sidebar/useWorktreeAgentRows.test.ts
  • src/renderer/src/components/sidebar/worktree-agent-rows.ts
  • src/renderer/src/components/sidebar/worktree-card-compact-agent-row.tsx
  • src/renderer/src/components/sidebar/worktree-subagent-child-rows.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/store/slices/agent-status.ts
  • src/shared/agent-hook-listener.test.ts
  • src/shared/agent-hook-listener.ts
  • src/shared/agent-status-field-normalization.ts
  • src/shared/agent-status-types.test.ts
  • src/shared/agent-status-types.ts
  • src/shared/claude-subagent-roster.test.ts
  • src/shared/claude-subagent-roster.ts

… subagents

Four review findings from the adversarial pass on the subagent child-row
feature:

- Stash the lead state a child-induced wait displaces
  (ClaudeLeadTurnState.stateBeforeWait) and restore it when the wait
  clears, instead of inventing 'working' — a lead that had already
  stopped left the pane spinning forever after the roster drained,
  since the done-gate only ever downgrades done → working.
- Tag snapshot-seeded and background_tasks-recreated roster entries
  (backgroundTasksAuthoritative) and demote them when a PRESENT
  background_tasks list omits their id. A phantom child seeded before a
  restart could otherwise gate the pane 'working' indefinitely in teams
  sessions, whose task list is never empty. Live activity clears the
  tag so lifecycle-tracked teammates keep their state.
- Match teammate ids with a hyphen-free suffix after `a<name>-` so
  TeammateIdle for "lane" cannot idle "lane-hooks"'s rows or clear its
  pending permission wait.
- Route turn-boundary events (Stop/StopFailure/UserPromptSubmit) that
  carry a KNOWN child agent_id through the child-driven re-emit instead
  of adopting them as lead state, and tie the prompt-cache new-turn
  reset to lead-origin events so child refreshes can't blank the
  prompt label.
@brennanb2025
brennanb2025 merged commit 31cff75 into main Jul 11, 2026
2 of 3 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…e done (stablyai#8211)

* feat(agent-status): show Claude subagent child rows and gate premature done

A Claude pane that spawned background subagents/teammates showed a green
done check the moment the lead's turn ended, even while a background
review loop was still running. Orca now tracks the pane's live children
from Claude hook events and:

- keeps the pane 'working' while at least one child is working (Stop is
  gated; Claude wakes the lead when a child finishes, so the pane
  resolves to done on the follow-up Stop with an empty roster)
- renders the children as indented child rows under the pane's sidebar
  row (name/type + working/idle dot), reusing the existing lineage UI

Tracking is lifecycle-primary: SubagentStart/SubagentStop/TeammateIdle
(newly registered hooks) plus child-origin tool events (they carry
agent_id) own the roster. Stop's background_tasks is folded only where
unambiguous — verified live on Claude Code 2.1.207 that teammates report
status "running" while idle-alive and their task ids never match
lifecycle agent_ids, so the list cannot decide teammate working-ness.

Child-origin events no longer overwrite the lead's tool/prompt caches
(a live AskUserQuestion card survives child churn); a child's own
PermissionRequest records waitingAgentId so only that child's progress
or death clears the wait. The interrupted flag survives the gated
window, inferred interrupts sync the lead record and refuse while a
child works, and hydration reseeds the roster after a restart.

* fix(agent-status): drop identity icon on subagent child rows

The child's agentType carries its NAME (e.g. "pr-reviewer"), which is not
an iconable agent and rendered the unknown "?" glyph. Nesting under the
parent row already conveys identity.

* fix(agent-status): restore displaced lead state and reconcile phantom subagents

Four review findings from the adversarial pass on the subagent child-row
feature:

- Stash the lead state a child-induced wait displaces
  (ClaudeLeadTurnState.stateBeforeWait) and restore it when the wait
  clears, instead of inventing 'working' — a lead that had already
  stopped left the pane spinning forever after the roster drained,
  since the done-gate only ever downgrades done → working.
- Tag snapshot-seeded and background_tasks-recreated roster entries
  (backgroundTasksAuthoritative) and demote them when a PRESENT
  background_tasks list omits their id. A phantom child seeded before a
  restart could otherwise gate the pane 'working' indefinitely in teams
  sessions, whose task list is never empty. Live activity clears the
  tag so lifecycle-tracked teammates keep their state.
- Match teammate ids with a hyphen-free suffix after `a<name>-` so
  TeammateIdle for "lane" cannot idle "lane-hooks"'s rows or clear its
  pending permission wait.
- Route turn-boundary events (Stop/StopFailure/UserPromptSubmit) that
  carry a KNOWN child agent_id through the child-driven re-emit instead
  of adopting them as lead state, and tie the prompt-cache new-turn
  reset to lead-origin events so child refreshes can't blank the
  prompt label.

---------

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