Repository navigation
feat(agent-status): show Claude subagent child rows and gate premature done - #8211
Conversation
…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.
📝 WalkthroughWalkthroughAdds 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)
✅ Passed checks (3 passed)
✨ Finishing Touches📝 Generate docstrings
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (3)
src/renderer/src/components/sidebar/worktree-card-compact-agent-row.tsx (1)
30-34: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider extracting
lastEnteredDoneAtto a shared utility.This function is duplicated in
DashboardAgentRow.tsx(lines 52-69) andworktree-card-compact-agent-row.tsx(lines 29-45) with a minor inconsistency: this copy usesentry.stateHistory?.length ?? 0(defensive optional chaining) while the dashboard copy usesentry.stateHistory.length(direct access). SincestateHistoryis typed as a requiredAgentStateHistoryEntry[], both work, but the divergence suggests the copies were authored independently. Extracting to a sharedgetLastEnteredDoneAt(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 winDedupe subagents by id before capping.
normalizeSubagentsFieldpushes every structurally-valid snapshot without checking for duplicateids. Downstream,buildSubagentChildRows(src/renderer/src/components/sidebar/worktree-subagent-child-rows.ts:20-63) derives each child row'spaneKeyfromsubagent.id, so duplicate ids in the normalized array produce duplicatepaneKeys/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 overunknown(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 | 🔵 TrivialVerify
CLAUDE_SUBAGENT_ID_MAX_LENGTHstays in sync withagent-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.tsrisks 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.tsand 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
📒 Files selected for processing (20)
src/main/agent-hooks/server.test.tssrc/main/agent-hooks/server.tssrc/main/claude/hook-service.test.tssrc/main/claude/hook-settings.tssrc/renderer/src/components/dashboard/DashboardAgentRow.tsxsrc/renderer/src/components/dashboard/DashboardAgentRowTrailingControls.tsxsrc/renderer/src/components/dashboard/useDashboardData.tssrc/renderer/src/components/sidebar/useWorktreeAgentRows.test.tssrc/renderer/src/components/sidebar/worktree-agent-rows.tssrc/renderer/src/components/sidebar/worktree-card-compact-agent-row.tsxsrc/renderer/src/components/sidebar/worktree-subagent-child-rows.tssrc/renderer/src/hooks/useIpcEvents.tssrc/renderer/src/store/slices/agent-status.tssrc/shared/agent-hook-listener.test.tssrc/shared/agent-hook-listener.tssrc/shared/agent-status-field-normalization.tssrc/shared/agent-status-types.test.tssrc/shared/agent-status-types.tssrc/shared/claude-subagent-roster.test.tssrc/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.
…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]>
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
Stophook mapped unconditionally todone, and teammate turn-ends emitSubagentStop, which Orca didn't register.What this does
SubagentStart/SubagentStop/TeammateIdlehooks plus child-origin tool events (which carryagent_id; lead events don't).Stop→done: the pane staysworkingwhile at least one child is working. Claude wakes the lead when a child finishes, so the pane resolves to ✅ on the follow-upStopwith an empty roster.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_taskson Stop) is wrong in interactive/teams mode:status: "running"inbackground_taskseven while idle-alive, so that list cannot decide teammate working-ness (TeammateIdle, keyed byteammate_name, is the idle signal).agent_ids (a<name>-<hex>) never matchbackground_taskstask ids — a reconcile-replace creates duplicate child rows.-p-mode subagents DO reuseagent_idas the task id, so id-exact folds and restart self-heal are safe there.Hence: lifecycle events own the roster;
background_tasksis 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
PermissionRequestrecordswaitingAgentIdso only that child's progress — or death — clears the wait; theinterruptedflag survives the gated window;inferInterruptrefuses 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 execgpt-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:
subagentsverified through IPC, persistence, and relay re-normalization; web/mobile clients deliberately never receive it (zero cross-version schema risk). Four confirmed findings fixed:PermissionRequestoverwrote the lead'sdone, and clearing the wait inventedworking— 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 inClaudeLeadTurnState.stateBeforeWaitand restored on both clear paths; a second concurrent wait carries the original stash forward.workingchild after restart never reconciled. Thebackground_tasksfold was additive-only, so a snapshot-seeded child whoseSubagentStopwas lost during downtime gated the paneworkingindefinitely in teams sessions (their task list is never empty). Seeded and fold-recreated entries are now taggedbackgroundTasksAuthoritativeand 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.TeammateIdlehyphen-prefix collision. Thea<name>-prefix match let teammate "lane" idle "lane-hooks"'s rows and clear its pending wait.claudeTeammateIdMatchesNamenow requires a hyphen-free suffix (the<hex>tail) and is shared by the roster and the wait-clear predicate.Stop/StopFailure/UserPromptSubmitcarrying a known child'sagent_id(a CLI that stops converting child Stops toSubagentStop) 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)
interruptedis lost if Orca restarts during the gated child-working window (narrow; drain then reads as normal completion).Tests
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/subagentson the pane entry).waiting+ working child row), approve in the TUI, child drains → pane resolvesdoneatSubagentStop(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.pnpm typecheck,pnpm lint(incl. max-lines ratchet — normalizers split intoagent-status-field-normalization.ts, no suppressions),git diff --check— clean.verifyflaked once on the untouchedpty-connectionWSL foreground-sampling perf test — passes 5/5 locally on the exact merge ref; rerun green.)