Skip to content

fix(agent-status): stop start-less SubagentStop from minting phantom working - #11961

Closed
brennanb2025 wants to merge 18 commits into
mainfrom
brennanb2025/sta-2915-startless-subagentstop-phantom-working
Closed

brennanb2025 wants to merge 18 commits into
mainfrom
brennanb2025/sta-2915-startless-subagentstop-phantom-working

Conversation

@brennanb2025

Copy link
Copy Markdown
Contributor

Summary

Fixes Linear STA-2915: after Claude /compact on 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 no UserPromptSubmit (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: buildClaudeChildDrivenStatusPayload defaults the lead state to working when the pane has no cached lead record, so compact's start-less SubagentStop on a resumed pane in a fresh Orca process mints a working that no Stop ever 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 → done mapping (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 → sticky working row minted at the exact SubagentStop timestamp) and re-run on this branch's dev build (same sequence → no row minted; real turns still track working → done normally).

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 typecheck
  • pnpm test (664 passed across src/shared + src/relay + src/main/agent-hooks suites)
  • Added regression tests: start-less SubagentStop with no lead record emits nothing (fails on parent commit); lead-present compact re-emits done; spawn with no lead still mints working; unknown stop with a surviving live child keeps working

AI Review Report

Reviewed the guard's interaction with every buildClaudeChildDrivenStatusPayload call 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 minting working with zero evidence). TeammateIdle roster transitions still emit (rosterChanged from idleClaudeTeammateByName), 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 phantom working on an eventless pane). No exec, path, secret, or IPC changes.

Notes

  • Kimi is unaffected (its normalizer ignores subagent lifecycle events entirely).
  • The known-stop-with-no-lead path previously emitted working after 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.

…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.
@coderabbitai

coderabbitai Bot commented Aug 1, 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
📝 Walkthrough

Walkthrough

Claude 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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% 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
Title check ✅ Passed The title clearly identifies the agent-status fix and the prevention of phantom working states from start-less SubagentStop events.
Description check ✅ Passed The description covers all required template sections, testing, regression coverage, AI review, cross-platform checks, security, and notes.
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 💡 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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 16c5526 and 01727af.

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

Comment thread src/shared/agent-hook-listener.ts Resolved
@greptile-apps

greptile-apps Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a sticky working phantom status minted when /compact runs on a freshly resumed Claude session. The live event sequence (PreCompact → SubagentStop (never started) → SessionStart(compact) → PostCompact) produced a start-less SubagentStop that buildClaudeChildDrivenStatusPayload mishandled by defaulting to working whenever no cached lead record existed.

  • Core fix: buildClaudeChildDrivenStatusPayload now requires positive evidence before emitting — a cached lead record, a live working child in the roster, a one-shot row removal, or an identity-correlated wait clearing. Everything else (e.g. compact's start-less stop) returns null.
  • Guard: roster allocation: stop/TeammateIdle events on unknown panes no longer allocate an empty roster per untrusted pane key; only SubagentStart with a valid id may allocate.
  • clearClaudePendingWaitForAgent state machine: the prior fabricated-working fallback when stateBeforeWait was absent is replaced by deleting the lead record and returning a typed result so the caller can emit an identity-correlated clearing transition instead of a sticky phantom.
  • Id canonicalization: lifecycle ids are .trim()ed to match inventory parser output; over-length and whitespace-only ids are rejected early; rawAgentId is read directly before readString to preserve empty-string as the child-origin signal.

Confidence Score: 5/5

Safe 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.

Important Files Changed

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.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review gate complete — CLEAN at 864341ff2d.

Live repro (production build, Claude Code 2.1.220): fresh pane + claude --resume of an idle session + /compact → phantom row state: working, prompt: "", stateStartedAt == updatedAt minted at the exact SubagentStop timestamp, frozen while the TUI sat idle. Event capture across harness 2.1.186/2.1.205/2.1.218/2.1.220 shows compact emits PreCompact → SubagentStop (start-less) → SessionStart(compact) → PostCompact and no UserPromptSubmit — the issue's original theory (and #11353's target) doesn't exist on any harness back to June 22; the real culprit was the ?? 'working' child-driven fallback.

Branch-negative rig at this exact head (isolated dev instance, same recipe): compact completes, no row minted; a control turn still tracks working → done normally. Three screenshots attached to the Linear issue.

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-agent_id lead classification), STA-3167 (relay roster seeding), STA-3174 (permission card outliving a dead owner). Final round independently verified: 473 related tests, full lint + max-lines, full typecheck, cross-platform relay build, non-vacuous coverage across the series.

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 864341ff2d, MERGEABLE. Tests 729 passing across shared/main/relay agent-hooks suites.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Closing as superseded. Three separate reasons, and any one of them is sufficient.

Its central idea already merged, in refined form. #14375 (fix(agent-status): stop start-less child stops from minting phantom working, merged 2026-08-14 as d137bb93e1) landed the same insight this PR was built around: buildClaudeCachedLeadStatusPayload defaulted an uncached lead state to working, and since claudeLeadStateByPaneKey is in-memory only, every restart emptied it so the next child event minted a phantom working with an empty roster that no Stop would ever clear. The base case now returns null and working requires positive evidence.

It has been silently un-tested for over two weeks. The branch is CONFLICTING and has not moved since 2026-08-01, which means CI stopped running on it — so its green history says nothing about its current state against main.

It is on the wrong ticket. STA-2915 is the /compact sticky-working bug. This diff is entirely child-lifecycle and roster work across agent-hook-listener.ts and claude-subagent-roster.ts; /compact appears only in comments and in an agent_id: 'compact-1' fixture, as context for a start-less SubagentStop. Nothing here registers or handles a compact event.

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, /compact emits no UserPromptSubmit at all — so the compact window had no clearing signal whatsoever, rather than a UserPromptSubmit arriving without a Stop. #15202 registers PostCompact only and deliberately never PreCompact, which makes the abort guard structural: an aborted compact emits PreCompact alone, so a design that never registers it cannot be stranded by it. It also deletes the #12332 correlation machinery, which could never execute in production.

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:

  • an isValidClaudeSubagentId pre-check before roster upsert,
  • agent-id trimming,
  • dropping a waiting record that has no stateBeforeWait.

Not deleting the branch, so those remain easy to lift.

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