Skip to content

fix(agent-status): mint the Claude turn-complete edge from the turn's own end time - #13295

Closed
ethznn wants to merge 4 commits into
stablyai:mainfrom
ethznn:fix/agent-status-turn-completed-at
Closed

ethznn wants to merge 4 commits into
stablyai:mainfrom
ethznn:fix/agent-status-turn-completed-at

Conversation

@ethznn

@ethznn ethznn commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #13245.

Also reported independently on Windows as #14253 (v1.4.180, long-lived npm run dev background shell) — same SubagentStop / state: working shape, confirmed as the same defect in #13245.

When a Claude lead turn ends while unrelated background work is still registered — a subagent, a
background shell, a session cron — resolveClaudePaneState gates the pane up to working. That is
right for the sidebar (work really is still running), but it also erases the working → done edge
that mints the completion banner. A turn that ends by asking the user a question therefore stays
silent for the whole background lifetime, and for a background shell (which emits no all-clear of
its own) the edge is lost outright.

This teaches the lead turn to carry its own end time.

  • normalizeClaudeEvent stamps turnCompletedAt on a lead Stop/StopFailure that the background
    inventory gates up to working, holds it on the lead-turn record, and repeats it on that turn's
    later all-clear done. The two rows pair by equality.
  • The completion coordinator announces the turn as soon as the stamped row arrives, and recognizes
    the all-clear as that same turn's tail rather than a second completion. The pane's own lifecycle
    keeps following the reported working state, so the sidebar still shows live background work.
  • Completion identity and the OS notification id now come from turnCompletedAt when present. This
    matters because the hook server pins stateStartedAt for as long as the reported state does not
    change, and this bug is precisely "the pane never leaves working" — every turn in one working-run
    would otherwise share a single identity, so turns 2..N would be dropped as replays and their
    banners would close each other in notifications.ts.

Measured end to end through the real normalizeHookPayload → observeAgentHookCompletionForNotification
path (completion banners; time is measured from the start of the sequence, and the turn ends at 1.0 s):

scenario main this branch
subagent, one turn 1 banner at 51.5 s — 50.5 s after the turn ended 1 banner at 1.0 s, carrying that turn's own text
background shell, turn N then N+1 1 banner (turn N+1 only; turn N never notifies) 2 banners, one per turn, distinct notification ids
persistent session cron, 3 turns 0 banners 3 banners, three distinct notification ids

Relationship to #13251: that PR takes the same seam and fixes the subagent case (1 immediate banner
with fresh text). The measured gaps are the other two rows — it produces 1 banner for the
background-shell case and 1 for the three-turn cron case. Its suppression marker is a bare boolean
cleared only by a later done, so where no such done ever arrives for turn N it survives into turn
N+1 and swallows it; and its synthetic identity is derived from stateStartedAt + 1, which is the
pinned value, so every turn in one working-run collapses onto one identity. This branch keys both the
suppression and the identity on the turn's own end time instead, which removes both. It is also
scoped to Claude: the meta-carrying dispatch branch is gated to this one path, so no other agent's
behaviour or existing tests change.

Screenshots

No visual change. The sidebar keeps showing working for the whole background lifetime exactly as
before; only the completion notification timing changes.

Testing

  • pnpm lint — oxlint 0 errors / 9 warnings (all pre-existing, WorktreeJumpPalette.tsx);
    audit:code-quality:native, audit:code-quality:type-aware, check:reliability-gates (73
    gates), check:max-lines-ratchet (352 grandfathered, no new bypasses),
    check:zustand-selector-fanout, and the three verify:localization-* gates all pass.
    check:code-quality:changed and check:react-doctor:changed against the PR base report 0 new
    findings across the changed files. oxfmt --check clean on every touched file.
  • pnpm typecheck (node + cli + web)
  • pnpm test — full vitest run: 4521 files / 48465 tests pass. The only failures are 5 tests in
    config/scripts/check-root-directory-entries.test.mjs and src/relay/agent-exec-handler.test.ts,
    which fail identically on the PR base in this environment (they assert on the sandbox's
    root-directory listing and inherited GIT_CONFIG_* env).
  • pnpm build — not run; this change is pure renderer/shared logic with no packaging surface.
  • Added tests

New suite agent-hook-completion-background-turn-notifications.test.ts replays real Claude hook
sequences through the real listener and the real coordinator, stamping stateStartedAt the way the
hook server does (pinned across same-state events), and pins:

  • a turn taken after a background-shell turn still notifies, and the first banner carries its own
    done snapshot (the pane row still says working, so nothing else can supply the turn's text);
  • three turns under a persistent session cron produce three banners with three distinct
    stateStartedAt values, so their notification ids cannot collide;
  • an all-clear that arrives after a background child paused for a human answer does not re-announce
    the turn;
  • a live coordinator remount between the gated Stop and the all-clear does not double-fire.

Plus unit pins: the listener stamps only on a gated turn boundary and drops the stamp when the next
turn starts; the coordinator pairs an all-clear with the turn it announced even after a working-title
blip resets the pane's identity record; the field is clamped to working/done and survives the
client payload projection; the IPC field whitelist forwards it; and the notification id is built from
the completion snapshot rather than the pinned working row.

Every production change was reverted in turn and the corresponding test confirmed failing (11
mutations, each one caught, on a 413-test baseline).

One existing assertion moved: restores the stashed lead state for an answered child question now
expects the restored lead record to keep turnCompletedAt. That carry is deliberate — a background
child pausing for a human answer displaces the finished lead turn, and without it the drain that
follows reads as a second completion. The test's original intent (the lead restores to done, not
working) is unchanged, and the case is now covered by a behavioural test too.

AI Review Report

Reviewed for: turn-identity correctness across pinned stateStartedAt; suppression lifetime (does a
turn whose all-clear never arrives silence the next turn?); coordinator remount and the module-scoped
identity map's eviction rules; blast radius onto non-Claude agents; and whether the new field can
leak into persisted pane state.

Flagged and addressed:

  • The suppression must be keyed by turn, not by a boolean — it now lives in the existing per-pane
    identity map as lastTurnCompletedAtNotified and only matches an exact turnCompletedAt, so a
    stale mark cannot swallow a later turn. Living in that map is also what makes the remount case
    work, since dispose() already preserves it while the pane is live.
  • A background child's permission pause displaces the finished lead turn through stateBeforeWait;
    the stamp is carried through that stash, otherwise the later drain double-fires. Covered by a test.
  • The review also caught two tests that were too weak to see a regression: the completion counter
    was ignoring banners dispatched without a snapshot (so a duplicate could hide), and the identity
    derivation had no failing case. Both are now pinned, verified by mutation.
  • The synthetic done must not run pane lifecycle effects while the pane is genuinely still working;
    it is dispatched with notifyWithoutLifecycle, and the lifecycle keeps following the reported
    working row.
  • turnCompletedAt is clamped to working/done on parse and is never written into
    AgentStatusEntry (that entry is built field-by-field), so nothing reaches last-status.json.

Cross-platform: the change is platform-agnostic — no shell invocation, no path handling, no
keyboard/shortcut or label surface, no Electron platform branches. The only platform-adjacent
behaviour is OS notification identity, which flows through the existing shared
buildAgentNotificationId and the existing notifications.ts replacement rule on all three
platforms; the change makes those ids more distinct, never less.

Security Audit

  • Input handling: turnCompletedAt arrives from an agent hook payload, so it is treated as
    untrusted. It is accepted only as a finite number and only on working/done; every other type
    or state normalizes to undefined, matching how interrupted/sessionBoundary are clamped. It is
    never parsed, formatted into a path, or interpolated into a command.
  • IPC: the field is added to the same explicit whitelist the other status fields already pass
    through; no widening of the IPC surface, no new channel, no new privilege.
  • The value only affects notification identity and a per-pane in-memory dedupe key. A hostile value
    could at worst change grouping of that pane's own notifications; it cannot cross panes (the map is
    keyed by paneKey) and cannot suppress another agent's notifications.
  • No command execution, path handling, auth, secrets, or dependency changes. No follow-up needed.

Notes

  • Claude-only by construction: only normalizeClaudeEvent emits the field, so every other agent
    takes byte-identical paths.
  • Not verified without running the app: the on-screen banner and Dock/tray presentation. The tests
    cover the dispatch decision, the snapshot carried, and the id inputs, but not the OS presentation
    itself.

@coderabbitai

coderabbitai Bot commented Aug 9, 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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 2b52fc54-ad0b-4dd4-a97c-a006eac104c8

📥 Commits

Reviewing files that changed from the base of the PR and between 2b10767 and 3c4b206aed32d557a955937b94e43192defc4f86.

📒 Files selected for processing (12)
  • src/renderer/src/components/terminal-pane/agent-completion-coordinator.test.ts
  • src/renderer/src/components/terminal-pane/agent-completion-coordinator.ts
  • src/renderer/src/components/terminal-pane/use-notification-dispatch.test.ts
  • src/renderer/src/components/terminal-pane/use-notification-dispatch.ts
  • src/renderer/src/hooks/agent-hook-completion-background-turn-notifications.test.ts
  • src/renderer/src/hooks/useIpcEvents.test.ts
  • src/renderer/src/hooks/useIpcEvents.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
🚧 Files skipped from review as they are similar to previous changes (12)
  • src/shared/agent-hook-listener.test.ts
  • src/renderer/src/components/terminal-pane/use-notification-dispatch.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/components/terminal-pane/agent-completion-coordinator.test.ts
  • src/renderer/src/hooks/agent-hook-completion-background-turn-notifications.test.ts
  • src/renderer/src/hooks/useIpcEvents.test.ts
  • src/renderer/src/components/terminal-pane/agent-completion-coordinator.ts
  • src/shared/agent-status-types.test.ts
  • src/shared/agent-status-types.ts
  • src/renderer/src/components/terminal-pane/use-notification-dispatch.test.ts
  • src/shared/agent-status-field-normalization.ts
  • src/shared/agent-hook-listener.ts

📝 Walkthrough

Walkthrough

The change adds optional turnCompletedAt metadata to Claude agent status payloads. Claude lead-turn handling records and preserves the timestamp through background work and child-agent waits. IPC handling forwards the field to the completion coordinator. The coordinator uses it for completion identity, emits announcement-only snapshots, and suppresses duplicate all-clear notifications. Tests cover normalization, propagation, distinct turns, child recovery, remounts, and notification IDs.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% 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
Linked Issues check ✅ Passed The changes satisfy issue #13245 by announcing completed Claude turns independently of unrelated background work while preventing duplicate notifications.
Out of Scope Changes check ✅ Passed The production and test changes remain focused on Claude turn-completion tracking, notification identity, payload propagation, and regression coverage.
Title check ✅ Passed The title clearly identifies the Claude turn-completion edge fix and its use of the turn's own end time.
Description check ✅ Passed The description is detailed, on-topic, and covers the change, rationale, linked issue, testing, and lack of visual change despite using non-template headings.
✨ Finishing Touches 💡 1
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch fix/agent-status-turn-completed-at

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 (2)
src/renderer/src/components/terminal-pane/agent-completion-coordinator.test.ts (1)

1195-1210: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

This test proves suppression through the local lastCompletionIdentity, not the pane-scoped record.

observeTitleWorking calls recordTitleWorking, which deletes the pane entry from lastCompletionIdentityByPaneKey. The test advances 2000 ms first, so the replay guard has expired and the delete runs. turnCompletedAtAlreadyNotified therefore returns false for the done at Line 1201, and the suppression comes from the identity comparison at Lines 931-941 of agent-completion-coordinator.ts instead.

The comment at Lines 1195-1197 states the all-clear is recognized by the repeated turn end time. That is accurate for the identity string, but the pane-scoped all-clear path is not the mechanism here. Add a second assertion that no lifecycle-only drain path was skipped, or add a case without the title blip so the turnCompletedAtAlreadyNotified branch is covered directly.

src/renderer/src/hooks/agent-hook-completion-background-turn-notifications.test.ts (1)

38-38: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Import HOOK_DONE_QUIET_MS from the source instead of redeclaring it.

Line 38 hardcodes 1_500. If the coordinator changes its quiet window, these tests advance the wrong amount and can pass without exercising the quiet-window flush. Import the exported constant if one exists, or export it.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 7267674e-294d-4cd7-b6e7-8d8669ed0157

📥 Commits

Reviewing files that changed from the base of the PR and between e172a51 and 940e5bc7f1c9d2ba46a0e59069b65cb0865b97c6.

📒 Files selected for processing (12)
  • src/renderer/src/components/terminal-pane/agent-completion-coordinator.test.ts
  • src/renderer/src/components/terminal-pane/agent-completion-coordinator.ts
  • src/renderer/src/components/terminal-pane/use-notification-dispatch.test.ts
  • src/renderer/src/components/terminal-pane/use-notification-dispatch.ts
  • src/renderer/src/hooks/agent-hook-completion-background-turn-notifications.test.ts
  • src/renderer/src/hooks/useIpcEvents.test.ts
  • src/renderer/src/hooks/useIpcEvents.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

@ethznn
ethznn force-pushed the fix/agent-status-turn-completed-at branch from 940e5bc to 6e32897 Compare August 9, 2026 05:56
@ethznn

ethznn commented Aug 9, 2026

Copy link
Copy Markdown
Contributor Author

Checked all three against running code.

F1 is real. Of the vetoes listed, only completionIdentityAlreadyNotified is reachable at this site — it matches cross-source on agent identity, so a prior title completion for the same agent vetoes the gated Stop. Added the failing sequence as a test (title completion → gated Stop → working-title blip → all-clear): zero banners for that turn. dispatchCompletion now reports whether it committed, and the identity is mirrored only then.

Fixing it surfaced a second issue in the same code: recognizing the all-clear through the local mirror skipped dispatchHookLifecycle, which the pane-scoped path does run. turnCompletedAtAlreadyNotified now reads both records, so either route drains.

F2 is correct. Mutating that check to return false left the test green, so it was pinning the identity comparison. Comment fixed, remount case added, and lifecycle assertions added so both halves are killable.

F3 declined. The sibling test file already redeclares the same constant; exporting it purely for tests isn't worth the widened surface.

@ethznn ethznn closed this Aug 11, 2026
@ethznn
ethznn force-pushed the fix/agent-status-turn-completed-at branch from d0f9960 to 23c803a Compare August 11, 2026 06:08
@ethznn ethznn reopened this Aug 11, 2026
@coderabbitai

coderabbitai Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@coderabbitai

coderabbitai Bot commented Aug 15, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

ethznn added 2 commits August 15, 2026 17:27
… own end time

A Claude lead turn that ends while unrelated background work is still
registered — a subagent, a background shell, a session cron — has its pane
gated up to `working` by resolveClaudePaneState. That gate is right for the
sidebar, but it also erases the `working -> done` edge that mints the
completion notification: a turn that ends by asking the user a question stays
silent for the whole background lifetime, and a background shell emits no
all-clear of its own, so the edge is lost outright.

Stamp `turnCompletedAt` on the gated lead Stop/StopFailure, hold it on the
lead-turn record, and repeat it on that turn's later all-clear `done`. The
completion coordinator announces the turn as soon as the stamped row arrives
and recognizes the all-clear as that same turn's tail rather than a second
completion; pane lifecycle keeps following the reported `working` state, so
the sidebar still shows the background work.

The identity has to come from the turn's own end time and not from
`stateStartedAt`. The hook server pins `stateStartedAt` for as long as the
reported state does not change, and this bug is precisely "the pane never
leaves `working`", so every turn in one working-run would share a single
identity: turns 2..N would be dropped as replays, and their banners would
close each other because the OS notification id is built from the same value.
Keying the suppression on that end time rather than on a one-shot marker also
means a turn whose all-clear never arrives cannot silence the next turn.

Fixes stablyai#13245
…it announces

Review caught the gated Stop mirroring its completion identity into the
coordinator-local record before `dispatchCompletion` ran. That dispatch can be
vetoed — the pane is not live, or the pane-scoped record already names this
agent from an earlier title or process-exit completion — and a vetoed dispatch
announces nothing and writes no pane-scoped record. The turn's later all-clear
`done` then built the same identity string, matched the mirrored value, and was
dropped as that turn's tail, so the turn produced no banner at all.

`dispatchCompletion` now reports whether it committed, and the identity is
mirrored only on a committed announcement. The reproduction is a title-driven
completion for the same agent followed by a gated Stop: the cross-source dedupe
vetoes the Stop, and before this change the all-clear was swallowed too.

The all-clear check now reads both records that can carry the turn end time.
The pane-scoped one outlives a remount; the coordinator-local one outlives a
working title, which drops the pane-scoped one. Recognizing the all-clear
through either of them keeps it on the drain path that still runs pane
lifecycle, instead of falling into the replay dedupe that returns silently.

Also closes coverage the mutation matrix surfaced: an interrupted Stop is not
stamped even while a child still gates the pane to `working`, a non-finite
stamp names no turn at either layer, a stamped `working` row alone does not
mint a banner for a turn this coordinator never saw start, and the two-turn
background-shell ledger now pins two distinct notification ids rather than
two distinct bodies.
@ethznn
ethznn force-pushed the fix/agent-status-turn-completed-at branch from 3c4b206 to ea1fcd8 Compare August 15, 2026 09:13
@ethznn

ethznn commented Aug 15, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto 2b10767d9. #14728 split the three test files this PR touched, so each case moved to the split file that now owns its behavior: the four listener cases and the clearClaudeAnsweredQuestionWait edit to agent-hook-listener-claude-subagents.test.ts, the IPC whitelist case to useIpcEvents-agent-status-pane-teardown.test.ts, and the five coordinator cases to a new agent-completion-coordinator-background-turn-identity.test.ts sibling on the shared harness — their old neighbours straddled two split files.

Production code is unchanged by the rebase; the ledger and the mutation matrix (23/27, same four survivors) reproduce exactly, and the #13245 sequences still misbehave on current main (cron case 0 of 3, background-shell case 1 of 2).

ethznn added 2 commits August 17, 2026 12:13
Three seams the notes pass flagged as weak were assertions that no production
mutation could break.

The next-turn case only read the following Stop's emitted payload, whose stamp
is computed fresh and is absent either way; merging the previous lead record so
a stale stamp survived passed the whole suite. It now reads the lead record
itself after the new prompt lands.

The two-turn background-shell ledger ended its second turn with the shell
already finished, so its two notification ids came from an ordinary
`working -> done` transition — the weaker seam the session-cron case already
pins for real. Both turns are now gated by a running shell, so both ids come
from the turns' own end times.

The rest closes coverage the mutation matrix still listed as missing: the
turn-boundary conjunct of the stamp (a manual PostCompact reports `done`
without ending a turn, and a running shell supplies the gate), the turn end
time on the row that restores a lead displaced by a child's permission pause,
the `done` scoping that decides whether a completion snapshot outranks the
stored row for the notification id, and the completion identity built from the
turn end time, which is what lets a replayed gated row pair with the banner its
own all-clear raised.

Two conjuncts of the stamp cannot be covered without changing production:
`eventAgentId === undefined` and `reportedStateName === 'done'` are both implied
by the conjuncts beside them, so dropping either is behaviour-preserving.
@ethznn

ethznn commented Aug 17, 2026

Copy link
Copy Markdown
Contributor Author

Went over the turn-identity tests twice: first trimming four comments that claimed more than their assertions reached, then fixing the assertions themselves.

Three were unfalsifiable — the next-turn case only read a payload whose stamp is recomputed anyway, and the two-turn shell ledger got its second id from a plain working→done edge — so they now read the lead record directly and gate both turns on running background work. New cases cover the turn-boundary conjunct of the stamp, the restored-lead row's stamp, the done scoping on the notification id, and the completion identity built from the turn end time.

A 27-mutation matrix over the production diff goes from 20 to 25 killed. The two remaining survivors are equivalent mutants — eventAgentId === undefined and reportedStateName === 'done' are each implied by the conjuncts beside them — which I left alone rather than reshape production to suit a test. Production code is unchanged in both passes.

@ethznn

ethznn commented Aug 19, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by #14580, which landed the same turnCompletedAt keying on main and closed #13245. Closing this branch.

@ethznn ethznn closed this Aug 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants