Skip to content

fix(agent-status): reap finished Claude named agents/teammates from the sidebar roster - #8825

Merged
brennanb2025 merged 5 commits into
mainfrom
brennanb2025/fix-subagent-visibility-regression
Jul 15, 2026
Merged

brennanb2025 merged 5 commits into
mainfrom
brennanb2025/fix-subagent-visibility-regression

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Finished Claude named background agents pile up as permanent Idle - <type> child rows under a pane's sidebar row for the rest of the session. Reported live: a --- Orchestration Messages --- pane showing 11 Idle - codebase-machinery / pr-history / web-research / … rows, every one idle for 3–6h after the agent finished, while the pane already read done ✅.

This is the tail of #8522 / #8211: those PRs stopped anonymous one-shot subagents from squatting, but named agents (Workflow / orchestration / ultracode lanes, and agent-teams teammates) still never left.

Root cause (confirmed against live hook captures, claude 2.1.210)

Named agents get teammate-shaped ids (a<name>-<hex>) and now appear in Stop's background_tasks as type: "teammate" entries whose status stays "running" forever — even after the agent finished and its SubagentStop fired.

The old roster treated that shape as a "resumable teammate": SubagentStop only marked the row idle (never removed), and the background-tasks fold only reaped teammate-shaped rows when no teammate-typed task was present — but a session with any named agent always lists at least one permanently-running teammate task. So hasTeammateTypedTask stayed true and the idle rows were never reaped.

Fix

The roster now tracks only working children (src/shared/claude-subagent-roster.ts):

  • SubagentStop removes the child outright — teammate-shaped or not. It is the reliable finish signal; the teammate task's "running" status is not. A resumed teammate re-earns its row via SubagentStart.
  • TeammateIdle removes by name (removeClaudeTeammateByName) as the fallback when a SubagentStop is lost.
  • A lead Stop's background_tasks still reaps unlisted children: hyphen-free one-shots always, and teammate-shaped rows once a complete inventory lists no teammate-typed task at all. A live named agent whose id never appears is kept only while a teammate-typed task is still present — that preserves the feat(agent-status): show Claude subagent child rows and gate premature done #8211 done-gate (pane stays working while a background child runs).
  • Hydration drops persisted idle snapshots, so a restart can't re-pile the exact rows this fixes.

claudeRosterHasWorkingSubagent / claudeRosterToSnapshots now emit working only.

Verification — live A/B in a dev Electron instance driving a real Claude TUI

A real claude v2.1.210 TUI launched inside an Orca terminal spawns four named background agents (alpha/beta/gamma/delta-probe, each sleep 4 then finish). Snapshots read from agentStatusByPaneKey[paneKey].subagents via CDP:

Before (main): pane resolves to done but four rows persist as idle indefinitely

23:06:45  state=done  subs=[alpha:idle, beta:idle, gamma:idle, delta:idle]
23:07:11  state=done  subs=[alpha:idle, beta:idle, gamma:idle, delta:idle]   ← still there 30s later

After (this branch): each row disappears the instant its agent finishes; roster drains to empty

23:11:40  state=working  subs=[alpha:working, beta:working, gamma:working, delta:working]
23:11:49  state=working  subs=[beta:working, gamma:working, delta:working]   ← alpha removed on finish
23:11:57  state=working  subs=[gamma:working]
23:12:06  state=done     subs=[]                                            ← clean, zero squatters

The Orca sidebar Claude Code row shows zero child rows after all four finish (terminal shows Teammate @…-probe finished / ALL-DONE).

Tests

Roster, row-lifecycle, and hook-listener suites rewritten to the working-only semantics and grounded in the captured 2.1.210 hook stream (teammate-typed background_tasks, name-embedding ids). 126 passing. Typecheck + oxlint clean.

Scope

Only src/shared/claude-subagent-roster.ts + agent-hook-listener.ts (+ their tests). No renderer/UI changes — the sidebar renders entry.subagents 1:1.

Known residual (unchanged, out of scope)

A pane whose PTY teardown skips clearPaneState, or a persisted last-status snapshot with a stale working child, can still render its last snapshot until a new event or eviction — the same residual noted in #8522.

Review follow-up

A deep correctness/performance review found and fixed one additional restart regression in a211b8c78: the roster seeder discarded persisted idle children, but the original last-status.json payload was still replayed directly to the renderer before any new hook event. Hydration now prunes legacy idle Claude children from the replay payload itself, so an old pile cannot reappear after relaunch. A main-process persistence test measures the reported shape deterministically: two persisted idle named-agent rows become zero in both listener replay and the renderer snapshot. The hook-registration comment was also aligned with the working-only roster semantics.

Review coverage: focused roster/lifecycle/listener/server suites (357 passing), full typecheck, full lint/reliability/max-lines/localization gates, formatting, and git diff --check. The broad unit run reached 29,904 passing tests; its 30 unrelated failures were environment-only under Node 26 (the repo requires Node 24): 28 tests lacked Node 26 experimental window.localStorage, and 2 relay tests inherited duplicated GIT_CONFIG_* variables. None touched this PR.

The performance shape remains bounded and improves over main: roster/inventory operations are O(32), finished rows are deleted instead of retained/serialized/fanned out, hydration scans at most 32 child snapshots per cached pane once at startup, and no polling, timers, subprocesses, or renderer subscriptions were added.

…he sidebar roster

#8522 stopped one-shot subagents from squatting as idle rows, but named
background agents (Workflow/orchestration/ultracode lanes and agent-teams
teammates) still piled up permanent "Idle - <type>" child rows for the rest
of the session — the reported regression (11 idle rows under an
"Orchestration Messages" pane, all idle 3-6h after finishing).

Root cause, confirmed against live hook captures (claude 2.1.210): named
agents get teammate-shaped ids (a<name>-<hex>) AND now appear in Stop's
`background_tasks` as `type: "teammate"` entries whose status stays "running"
forever — even after the agent finished. The old code read that shape as a
"resumable teammate", so SubagentStop only marked it idle and the fold never
reaped it (a present teammate task kept hasTeammateTypedTask true). The rows
never left.

Fix: the roster now tracks only WORKING children.
- SubagentStop removes the child outright (teammate-shaped or not) — it is
  the reliable finish signal; the teammate task's "running" status is not.
- TeammateIdle removes by name as the fallback when a SubagentStop is lost.
- A lead Stop's background_tasks still reaps unlisted children: hyphen-free
  one-shots always, and teammate-shaped rows once a complete inventory shows
  no teammate-typed task at all. A live named agent whose id never appears is
  kept only while a teammate-typed task is still present (the done-gate).
- Hydration drops persisted idle snapshots so a restart can't re-pile them.

Verified live in a dev Electron instance driving a real Claude TUI that spawns
four named background agents: pre-fix the pane resolves to done with four
persistent "Idle - <probe>" rows; post-fix each row disappears the instant its
agent finishes and the roster drains to empty (done, zero child rows).

Tests: roster + row-lifecycle + hook-listener suites rewritten to the
working-only semantics, grounded in the captured 2.1.210 hook stream
(126 passing). Typecheck + oxlint clean.
@coderabbitai

coderabbitai Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: c1c3749f-db09-409e-83fa-c60a163be2c1

📥 Commits

Reviewing files that changed from the base of the PR and between aa4edcb and 701818c.

📒 Files selected for processing (2)
  • src/shared/claude-subagent-roster.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.test.ts
  • src/shared/claude-subagent-roster.ts

📝 Walkthrough

Walkthrough

Claude subagent tracking now maintains working entries only. Finished subagents and idle teammates are removed instead of transitioned to idle, roster capacity no longer evicts active entries, and background task folding uses updated teammate and subagent authority rules. Snapshot hydration skips non-working children and persists cleanup of legacy idle rows. Lifecycle and regression tests cover teammate removal, stopped or killed named agents, incomplete inventories, roster limits, and restart behavior.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the fix well, but it misses required template sections like Screenshots, Testing checklist, AI Review Report, Security Audit, and Notes. Reformat the PR body to match the template, add the missing headings, include the testing checklist, and state either screenshots or 'No visual change'.
Docstring Coverage ⚠️ Warning Docstring coverage is 62.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: removing finished Claude named agents/teammates from the sidebar roster.
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.
✨ 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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/shared/claude-subagent-roster.ts (1)

159-221: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Fold logic verified correct — consider extracting the cleanup predicate.

Traced this against every case in claude-subagent-roster.test.ts (id-exact match/removal, killed one-shot reaping, teammate-shape protection with/without teammate tasks present, override via listedAsSubagentTask, seeded-phantom vs re-tracked retention) — all consistent with the documented rules. The 4-term boolean at Lines 211-216 is the densest part of this change (flagged complexity_high) and is easy to get subtly wrong on a future edit. Extracting it into a named predicate would make the "why kept vs deleted" intent self-documenting.

♻️ Suggested extraction
+/** True when an unlisted roster entry must survive this fold: it's
+ *  teammate-shaped, never proven by an id-exact subagent listing, and the
+ *  current inventory still shows teammate-typed tasks (session has live
+ *  named-agent machinery). */
+function isProtectedUnlistedTeammateShapedEntry(
+  id: string,
+  tracked: TrackedClaudeSubagent,
+  hasTeammateTypedTask: boolean
+): boolean {
+  return (
+    hasTeammateTypedTask &&
+    !tracked.backgroundTasksAuthoritative &&
+    tracked.listedAsSubagentTask !== true &&
+    isClaudeTeammateLifecycleId(id)
+  )
+}
+
 export function foldClaudeBackgroundTasksIntoRoster(
   ...
   for (const [id, tracked] of roster) {
     if (listedIds.has(id)) {
       continue
     }
-    if (
-      hasTeammateTypedTask &&
-      !tracked.backgroundTasksAuthoritative &&
-      tracked.listedAsSubagentTask !== true &&
-      isClaudeTeammateLifecycleId(id)
-    ) {
+    if (isProtectedUnlistedTeammateShapedEntry(id, tracked, hasTeammateTypedTask)) {
       continue
     }
     roster.delete(id)
   }
 }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 09bd0537-58b9-4474-832f-4387a848a5f1

📥 Commits

Reviewing files that changed from the base of the PR and between bf0b65a and 80f7511.

📒 Files selected for processing (5)
  • src/shared/agent-hook-listener.test.ts
  • src/shared/agent-hook-listener.ts
  • src/shared/claude-subagent-roster.test.ts
  • src/shared/claude-subagent-roster.ts
  • src/shared/claude-subagent-row-lifecycle.test.ts

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Additional correctness/performance review follow-up (701818c): found and fixed a cap-edge reconciliation regression. With 32 tracked children, a complete 32-task inventory that replaced one stale child tried to add the replacement while full, dropped it, then removed the stale row—leaving 31 tracked children and losing the replacement's done-gate. Reconciliation now retries only blocked running tasks after authoritative cleanup, remains bounded to AGENT_STATUS_MAX_SUBAGENTS, and stops retrying once full. The deterministic regression test measured 31/missing replacement before and 32/replacement retained after. Verification: 364 affected tests passed (2 skipped); typecheck, full lint/reliability/max-lines/localization gates, formatting, and diff checks passed. The repository-configured full unit run reached 29,907 passing tests; its 28 failures are the known Node 26 window.localStorage incompatibility (the repo requires Node 24), with none in agent-status code.

@brennanb2025
brennanb2025 merged commit c8986ca into main Jul 15, 2026
1 check passed
brennanb2025 added a commit that referenced this pull request Jul 22, 2026
…idebar rows (#9850)

* fix(agent-status): keep Claude in-process teammates visible as idle sidebar rows

Claude Code 2.1.21x runs named Agent-tool agents as turn-based in-process
teammates: SubagentStop and TeammateIdle fire at every TURN end while the
teammate stays alive awaiting mail (verified live on 2.1.217). Treating
those events as finish signals deleted the child row seconds after each
burst, so the sidebar showed no subagents for most of a teammate's life.

Root-cause fix: the roster now tracks a working/idle state per child.

- One-shot children (hyphen-free ids) keep remove-on-stop: their
  SubagentStop is a true finish.
- Teammate-shaped rows park as idle on SubagentStop/TeammateIdle and
  revive to working via the next SubagentStart (same lifecycle id,
  first-observed startedAt preserved).
- Idle rows never gate the pane 'working' (#8825's done-gate rule).
- Only TeammateIdle-confirmed idle rows survive a complete lead-Stop
  fold; a stopped workflow lane wearing a teammate-shaped id is reaped
  there (or immediately, once a fold tagged it listedAsSubagentTask), so
  the pre-#8825 idle pile cannot rebuild.
- At the wire cap, the oldest idle row is evicted to admit a working
  spawn; working children are never displaced.
- Hydrate keeps pruning idle snapshots: idle-teammate liveness cannot be
  proven across a restart, and a live teammate re-earns its row.

* fix(agent-status): restore inventory-confirmed workflow lanes
brennanb2025 added a commit that referenced this pull request Sep 22, 2026
…orrect two stale claims

The hook inventory now classifies through the shared kind table, which also maps the
SDK stream's `local_agent` / `local_subagent`. Nothing pinned that widening, so add
cases for all four agent names — including `teammate`, whose pane state stays `done`
under the #8825 idle-squat rule.

Two comments the fold made false:
- the teardown marker rule's comment claimed it could not disagree with what the UI
  calls working; it is deliberately lead-only, so now it says that and why;
- the agent-status store reference still described the structured row's `state` as the
  deleted `structuredAgentSessionStatusState`, and omitted the `workingMode` the ingest
  now writes.
brennanb2025 added a commit that referenced this pull request Sep 22, 2026
… working (#22295)

* fix(agent-status): a structured session with live child work reads as working

An idle native-chat session whose subagent was still running showed a green
check in the sidebar, the collapsed worktree pill, and worktree ps, while a
terminal Claude session in the same situation showed working. The two lanes
folded child work into the parent's status with different code: the hook
listener did, the structured lane did not.

Both lanes now share one child-work liveness vocabulary and one lead-status
fold. Live agent work makes a settled lead working; shells and monitors alone
make it monitoring. The structured lane derives liveness from the background
task list already on the wire, in both its readers, so the sidebar, the CLI,
the dashboard and mobile agree. The Claude task-kind table is one shared file
covering both the hook inventory and SDK stream names, and the renderer bridge
reuses the shared child-work projection instead of carrying its own copy.

* fix(agent-status): a blocked or out-of-contact subagent still holds its session working

Child-work liveness retired an agent-kind child on any state but working/monitoring,
while the shell beside it stayed live on everything except done/idle. A subagent
waiting on a permission prompt, or one whose host lost contact, therefore counted
for less than a backgrounded sleep and let the session read done. Both kinds now
share the settlement rule `resolveAgentChildWorkFreshness` already reads rows by:
only an explicit done/idle retires child work.

Also keep empty task labels out of the shared background-task projection candidate,
so a host that publishes `name: ''` cannot beat the child-row fallbacks.

* test(agent-status): pin the widened hook-inventory agent names, and correct two stale claims

The hook inventory now classifies through the shared kind table, which also maps the
SDK stream's `local_agent` / `local_subagent`. Nothing pinned that widening, so add
cases for all four agent names — including `teammate`, whose pane state stays `done`
under the #8825 idle-squat rule.

Two comments the fold made false:
- the teardown marker rule's comment claimed it could not disagree with what the UI
  calls working; it is deliberately lead-only, so now it says that and why;
- the agent-status store reference still described the structured row's `state` as the
  deleted `structuredAgentSessionStatusState`, and omitted the `workingMode` the ingest
  now writes.

* fix(agent-status): the state clock restarts when monitoring becomes a real turn

`stateStartedAt` carried forward whenever the prior `state` matched, which was sound
while `state` meant "a turn is running". Now that it folds in child work, an idle lead
watching a `sleep 3600` publishes `working`/`monitoring`; the user's prompt 45 minutes
later keeps `state: 'working'`, so the row inherited the watch loop's clock and read
"Working for 45m" the instant the turn began. Monitoring is its own displayed label
(`worktree-card-compact-agent-row.tsx:40`), so the continuity key is now the whole
published work identity — state AND workingMode — in both writers.

Also record two facts the code stated wrongly: the structured lane's `interrupted: false`
is inert (a projected session status has no interrupted member) rather than a decision,
and the child-work liveness rule's escape hatch is the roster's session lifetime, not a
settled state.

* fix(agent-status): a workflow is watch work, and child work dates itself

Two defects the fold introduced.

`isAgentChildWorkKind` counted `workflow` as agent work, so a structured session
whose only live task was a backgrounded `local_workflow` published a full working
spinner while the children projection — which admits `kind === 'agent'` only —
rendered nothing to expand, and the same workflow in a terminal pane showed the
monitoring badge instead. The repo already decides this: `isClaudeSubagentTask`
excludes workflows by name, and MATERIALIZED_TASK_KINDS leaves "the backgrounded
shell command and the workflow" to the non-agent owner. The predicate is now
`kind === 'agent'`, and the three sites that restated the same test route through
it, so a new kind is decided in one place instead of three that merely agree.

`evidenceObservedAt` dated every row by `summary.updatedAt`, the journal's last
activity. The journal cannot date child work: its clock stopped when the lead's
turn did, so a genuinely live roster aged past the 30-minute staleness window and
mobile's dot decayed a running session to idle. The fold now reports whether child
work alone holds the row open, and only then does the host's observation clock
stand in — keeping "a restart's republish is not new evidence" for lead turns.

* fix(agent-status): the sidebar dates child work the same way the host does

`fromChildWork` reached the host ingest but not the renderer bridge, so after ~30
minutes of live child work with no journal activity the sidebar's row aged into
staleness while `worktree ps` and mobile stayed fresh — two writers for one session
answering differently, which is the defect this PR exists to remove. For a remote
host the client's own receipt time is also the more honest clock, since the journal
stamp is the host's and is never comparable against this machine's now.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…he sidebar roster (stablyai#8825)

* fix(agent-status): reap finished Claude named agents/teammates from the sidebar roster

stablyai#8522 stopped one-shot subagents from squatting as idle rows, but named
background agents (Workflow/orchestration/ultracode lanes and agent-teams
teammates) still piled up permanent "Idle - <type>" child rows for the rest
of the session — the reported regression (11 idle rows under an
"Orchestration Messages" pane, all idle 3-6h after finishing).

Root cause, confirmed against live hook captures (claude 2.1.210): named
agents get teammate-shaped ids (a<name>-<hex>) AND now appear in Stop's
`background_tasks` as `type: "teammate"` entries whose status stays "running"
forever — even after the agent finished. The old code read that shape as a
"resumable teammate", so SubagentStop only marked it idle and the fold never
reaped it (a present teammate task kept hasTeammateTypedTask true). The rows
never left.

Fix: the roster now tracks only WORKING children.
- SubagentStop removes the child outright (teammate-shaped or not) — it is
  the reliable finish signal; the teammate task's "running" status is not.
- TeammateIdle removes by name as the fallback when a SubagentStop is lost.
- A lead Stop's background_tasks still reaps unlisted children: hyphen-free
  one-shots always, and teammate-shaped rows once a complete inventory shows
  no teammate-typed task at all. A live named agent whose id never appears is
  kept only while a teammate-typed task is still present (the done-gate).
- Hydration drops persisted idle snapshots so a restart can't re-pile them.

Verified live in a dev Electron instance driving a real Claude TUI that spawns
four named background agents: pre-fix the pane resolves to done with four
persistent "Idle - <probe>" rows; post-fix each row disappears the instant its
agent finishes and the roster drains to empty (done, zero child rows).

Tests: roster + row-lifecycle + hook-listener suites rewritten to the
working-only semantics, grounded in the captured 2.1.210 hook stream
(126 passing). Typecheck + oxlint clean.

* fix(agent-status): prune persisted idle Claude children

* fix(agent-status): persist Claude idle-row hydration cleanup

* fix(agent-status): avoid ambiguous teammate idle cleanup

* fix(agent-status): reconcile replacement children at roster cap
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…idebar rows (stablyai#9850)

* fix(agent-status): keep Claude in-process teammates visible as idle sidebar rows

Claude Code 2.1.21x runs named Agent-tool agents as turn-based in-process
teammates: SubagentStop and TeammateIdle fire at every TURN end while the
teammate stays alive awaiting mail (verified live on 2.1.217). Treating
those events as finish signals deleted the child row seconds after each
burst, so the sidebar showed no subagents for most of a teammate's life.

Root-cause fix: the roster now tracks a working/idle state per child.

- One-shot children (hyphen-free ids) keep remove-on-stop: their
  SubagentStop is a true finish.
- Teammate-shaped rows park as idle on SubagentStop/TeammateIdle and
  revive to working via the next SubagentStart (same lifecycle id,
  first-observed startedAt preserved).
- Idle rows never gate the pane 'working' (stablyai#8825's done-gate rule).
- Only TeammateIdle-confirmed idle rows survive a complete lead-Stop
  fold; a stopped workflow lane wearing a teammate-shaped id is reaped
  there (or immediately, once a fold tagged it listedAsSubagentTask), so
  the pre-stablyai#8825 idle pile cannot rebuild.
- At the wire cap, the oldest idle row is evicted to admit a working
  spawn; working children are never displaced.
- Hydrate keeps pruning idle snapshots: idle-teammate liveness cannot be
  proven across a restart, and a live teammate re-earns its row.

* fix(agent-status): restore inventory-confirmed workflow lanes
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