Repository navigation
fix(agent-status): stop start-less SubagentStop from minting phantom working - #11961
brennanb2025 wants to merge 18 commits into
Conversation
…working Claude compact emits PreCompact -> SubagentStop (never started) -> SessionStart(compact) -> PostCompact. On a freshly resumed pane with no cached lead state, the child-driven default minted a sticky empty-prompt 'working' that no Stop ever clears (STA-2915). Emit child-driven status only on positive evidence: a lead record, a live working child, or an actual roster change.
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughClaude subagent lifecycle handling now validates subagent IDs and tracks roster changes for teammate-idle, start, and tracked stop events. Unknown agent stops are treated as no-ops. Child-driven status construction suppresses stale payloads when no lead state, roster change, or working child exists. Tests cover invalid IDs, start-less stops, completed lead state, valid starts, and active-child state retention. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 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.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 144db959-f0ae-41fe-b3bf-3db835b14601
📒 Files selected for processing (2)
src/shared/agent-hook-listener.test.tssrc/shared/agent-hook-listener.ts
Greptile SummaryThis PR fixes a sticky
Confidence Score: 5/5Safe to merge — the change is strictly a tightening of which events may emit a status payload, with no new mutable state, no new IPC or platform surfaces. The guard is fail-closed by construction: every path that previously emitted by default now requires explicit positive evidence. The 490-line regression block covers start-less stops, truncated inventories, id-canonicalization round-trips, the stale-stop race, and wait-owner-still-tracked suppression. No behavioral change occurs for normal turns. Files Needing Attention: No files require special attention. All three changed files are in the shared normalization layer with no platform-specific paths.
|
| Filename | Overview |
|---|---|
| src/shared/agent-hook-listener.ts | Core fix: buildClaudeChildDrivenStatusPayload now requires positive evidence to emit; normalizeClaudeSubagentLifecycleEvent guards roster allocation to spawns only; clearClaudePendingWaitForAgent returns a typed discriminant instead of fabricating a working fallback; id canonicalization and validity checks added consistently throughout. |
| src/shared/claude-subagent-roster.ts | Adds isValidClaudeSubagentId export used by callers to pre-check before allocating a roster for an id that upsertWorkingClaudeSubagent would silently reject; fixes readClaudeBackgroundAgentTasks to trim and validate inventory ids before capping-slot consumption. |
| src/shared/agent-hook-listener.test.ts | 490 lines of new regression tests covering every new guard: start-less stop, no-lead inventory paths, truncated-inventory claims, id canonicalization, wait-owner-still-tracked suppression, and delayed-stale-stop ordering. Existing tests updated where a lead record is now required. |
Reviews (18): Last reviewed commit: "fix(agent-status): read agent_id raw and..." | Re-trigger Greptile
…cycle events Review finding: the early null return left getOrCreateClaudeSubagentRoster's empty allocation behind, one per untrusted pane key with no lifecycle bound. Only SubagentStart may allocate; stop/idle now read the existing roster.
Review finding round 2: upsert silently rejects over-length agent ids after the caller already allocated, stranding one empty roster per invented pane key with zero emitted payloads. Export the id validity check and gate both wire-reachable allocation sites.
…out a lead record Review finding round 3: rosterChanged let a known-child drain bypass the no-evidence guard into the unconditional 'working' default — sticky until the stale sweeper when no lead hook ever arrives. With no lead record the pane state now follows tracked children: live child -> working, identity- matched drain/park -> done. Duplicate stale stops stay suppressed.
…d record exists Review finding round 4: teammate ids persist across turns, so a delayed stale SubagentStop parks a live teammate's row and the drain->done inference retired newer work — PR #11353's uncorrelated-completion race. With no lead record, only a live working child (working) or a one-shot row removal (done; duplicate-proof since the row is gone) may speak; teammate parks and idle-only refreshes stay silent.
Review finding round 5: after a restart the listener can miss a child's start; another child's stop still lists it running in background_tasks. A running non-teammate task or live shell/cron now vetoes the no-lead removal->done into working. Veto only — folding the inventory at stop time would reap a just-parked teammate row before its TeammateIdle confirmation arrives.
…d on truncated inventories Review findings round 6: (1) veto-only left the vetoing child untracked, so its own later drain was start-less-suppressed and the pane stuck on working — fold running non-teammate inventory entries additively (inventoryComplete: false; no reap, so a just-parked unconfirmed teammate row survives). (2) The agent-task parser caps at 32 entries; a running child past the cap is invisible, so a truncated inventory now claims neither done nor working. The raw-array shell/cron veto stays uncapped.
Review findings round 7: (1) a child permission wait that is a fresh pane's first lead record fabricated 'working' from the no-stash clear fallback when the child died — drop the record instead and let evidence rules decide. (2) A complete empty stop inventory now clears restored phantom rows (it is complete by construction; the non-empty additive fold is unchanged). (3) An uncapped raw scan sees running subagents hidden past the 32-entry parser cap, so a capped inventory with live work emits truthful working instead of retaining stale state.
…its explicitly Review findings round 8: (1) over-length running inventory ids could allocate rosters or claim liveness despite being untrackable — the fold guard and raw liveness scan now require an id the upsert would accept. (2) Deleting a fresh pane's no-stash wait record left the stale amber waiting card fresh for the stale sweeper; the wait's own agent id parking/stopping is an identity-correlated resolution and now emits a clearing done.
…untrackable ids everywhere Review findings round 9: (1) a delayed prior-turn stop for a reused teammate id could park the newer start's working row and ride the wait- clear into done — the clearing done now fires only when the owner has no roster row left; a parked owner stays silent (sweeper-bounded card). (2) Over-length ids no longer consume inventory parser cap slots, so junk cannot fake truncation and veto a legitimate drain. (3) A waiting- inducing child event with an untrackable id mints no card at all.
…tory Review finding round 11: the complete-empty fold cleared live-tracked rows, so a delayed stale stop's empty list could retire a newer live start — the uncorrelated-retirement race again. The empty inventory now reaps only restored/inventory-derived claims not backed by live lifecycle events.
Review finding round 12: reaping the last inventory-derived rows emitted nothing, stranding the previously published working until the sweeper. The reap is same-source-correlated removal evidence — the authority that minted those rows now reports empty — so it rides the existing done veto chain.
Review findings round 13 share one root: stop-time inventories are mutually unordered, so any deletion they drive can be a stale claim against newer live state. Fold only running valid entries (no deletions; listed-non-running cleanup stays with turn-serialized lead Stops), reap only pre-restart restoredFromSnapshot rows on an empty inventory, and drop the untrackable raw-scan working mint (truncated stays silent).
Review findings round 14: (1) the clearing emission after a wait owner's death carried the cached tool/interactive card, leaving it actionable on a resolved pane — the cache resets like the answered-question clear. (2) Whitespace-padded inventory ids were stored raw yet published trimmed, so their own stops could never drain them — canonicalize at parse time.
…entory ids Review finding round 15: inventory ids trim at parse but lifecycle/tool agent_id stayed raw, so a padded stop missed the trimmed roster key and the row could never drain. All id reads now canonicalize identically.
…erant Review finding round 16: the padded-id tests used identical padding on both events, passing even without trimming. Mixed-form cases now cover lifecycle stop vs inventory mint, padded start vs clean stop, and padded child tool routing.
Review findings round 17: a whitespace-only agent_id canonicalized to undefined and reclassified the child event as the LEAD's, minting a lead waiting no lead Stop ever clears; agent_id-present events with an unattributable id are now ignored. The padded-child-tool regression now drains via a clean-id stop so it fails if canonicalization reverts.
…stale snapshots Review findings round 18: (1) readString swallows empty strings, erasing the child-origin marker — an empty agent_id PermissionRequest minted an unclearable lead wait; the raw field now decides child origin. (2) A stop whose payload carried a pre-stop inventory snapshot re-created the id it had just removed, flipping a done lead back to sticky working — the stop is authoritative for its own id and excludes it from the fold.
|
Review gate complete — CLEAN at Live repro (production build, Claude Code 2.1.220): fresh pane + Branch-negative rig at this exact head (isolated dev instance, same recipe): compact completes, no row minted; a control turn still tracks Same-model Codex review loop (xhigh): 19 fresh-reviewer rounds until CLEAN. Each round's findings were fixed in-scope (empty-roster retention, inventory-id validation, drain/park completion authority, temporal-ordering races, id canonicalization, dead-wait card cleanup, test vacuity) or verified pre-existing on the merge base and filed: STA-3166 (unknown- Perf: guard short-circuits on cached lead (zero added cost for lead-present panes); 600 invented-pane stops = 0 payloads, 0 retained rosters, 0.47ms; lead hot path ~10.6M events/s; independent round-11 measurement 1.58µs/event nominal, 362µs with 8,000 invalid inventory rows. CI: all 30 checks green at |
|
Closing as superseded. Three separate reasons, and any one of them is sufficient. Its central idea already merged, in refined form. #14375 ( It has been silently un-tested for over two weeks. The branch is It is on the wrong ticket. STA-2915 is the What actually fixes STA-2915: #15202. The mechanism turned out not to be the one in this ticket's title. Measured under a PTY on Claude Code 2.1.227, Worth keeping from this PR. Three small residuals here are real and are not carried by #14375 or #15202, and deserve their own follow-up rather than dying with this branch:
Not deleting the branch, so those remain easy to lift. |
Summary
Fixes Linear STA-2915: after Claude
/compacton a freshly resumed session, the worktree card/sidebar agent row could stick on Working… forever (empty prompt, no tool,stateStartedAt == updatedAt) while the TUI sat idle.Live event capture across Claude Code 2.1.186 / 2.1.205 / 2.1.218 / 2.1.220 shows compact emits
PreCompact → SubagentStop (never started) → SessionStart(compact) → PostCompact— and noUserPromptSubmit(the issue's original theory, and the mechanism PR #11353 targeted, no longer exists on any harness back to June 22). The real culprit is receiver-side:buildClaudeChildDrivenStatusPayloaddefaults the lead state toworkingwhen the pane has no cached lead record, so compact's start-lessSubagentStopon a resumed pane in a fresh Orca process mints aworkingthat noStopever clears (until the 30-minute stale window).The fix emits child-driven status only on positive evidence: a cached lead record, a live working child in the roster, or an actual roster change from the event. Unlike #11353's
PostCompact → donemapping (rejected for stale-completion races), this claims no completion authority, needs no correlation ID, and adds no per-pane state.Reproduced live on the current production build (fresh pane +
claude --resume+/compact→ stickyworkingrow minted at the exact SubagentStop timestamp) and re-run on this branch's dev build (same sequence → no row minted; real turns still trackworking → donenormally).Screenshots
No visual change (status correctness fix). Post-fix rig screenshot of the idle sidebar after compact is attached to the Linear issue evidence.
Testing
pnpm lint(oxlint + react-doctor config on changed files: clean; oxfmt clean)pnpm typecheckpnpm test(664 passed across src/shared + src/relay + src/main/agent-hooks suites)SubagentStopwith no lead record emits nothing (fails on parent commit); lead-present compact re-emitsdone; spawn with no lead still mintsworking; unknown stop with a surviving live child keepsworkingAI Review Report
Reviewed the guard's interaction with every
buildClaudeChildDrivenStatusPayloadcall site: subagent lifecycle (start/stop/teammate-idle), child tool activity (upserts a working row before emitting, so unaffected), and known-child turn-boundary re-emits (now fail closed to no claim instead of mintingworkingwith zero evidence). TeammateIdle roster transitions still emit (rosterChanged fromidleClaudeTeammateByName), preserving idle-row UI refreshes. Cross-platform: pure shared normalization logic consumed identically by the local hook server and the SSH relay; no shortcuts, paths, shell, or Electron platform surface touched. A same-model Codex review loop runs on this exact head via Orca orchestration; findings will be pushed before merge.Security Audit
No new input surface: the change only tightens which authenticated hook events may emit a status payload. Untrusted payload fields (
agent_id) already flowed through these paths; the guard strictly reduces what an unauthenticated-content payload can cause (it can no longer mint a phantomworkingon an eventless pane). No exec, path, secret, or IPC changes.Notes
workingafter a restart-seeded roster drained; it now emits nothing, leaving the restored persisted status in place until real lead evidence arrives — fail-closed by design.