Repository navigation
fix(native-chat): let the provider reopen a Claude turn it resumed itself - #20518
Conversation
|
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:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (2)
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review. 📝 WalkthroughWalkthroughClaude turn opening now separates send-echo opening from provider-resumed activity. Root assistant output can open a turn around its first message, tool, or reasoning item. Resumed turns can omit Priority: ⬇️ Low Merge Risk: ⚪ Minimal · up to No concrete merge-blocking risk has been established for the current change. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description gives a detailed explanation of the root cause, implementation, testing, and known non-regression failures. However, it omits the required Linked Issue entry, the required Visual Proof section or an explicit N/A justification, and several template sections and checklist confirmations.
✨ 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: Advanced
Run ID: 70644924-a6b8-4e48-a79b-108c049eaf9e
📥 Commits
Reviewing files that changed from the base of the PR and between 22f56f7 and a1b821b3814d8eecab1fbc666ea748571771e3de.
📒 Files selected for processing (5)
src/main/claude/claude-structured-journal-translation.test.tssrc/main/claude/claude-structured-journal-translation.tssrc/main/claude/claude-turn-lifecycle-item.tssrc/main/claude/claude-turn-opening.tssrc/main/claude/claude-turn-resumption.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
| state: end.state, | ||
| startedAt, | ||
| completedAt: end.completedAt, | ||
| userItemId, | ||
| ...(userItemId === undefined ? {} : { userItemId }), | ||
| ...(end.durationMs === undefined ? {} : { durationMs: end.durationMs }) | ||
| } | ||
| : { turnId, state: 'running', startedAt, userItemId } | ||
| : { | ||
| turnId, | ||
| state: 'running', | ||
| startedAt, | ||
| ...(userItemId === undefined ? {} : { userItemId }) | ||
| } | ||
| ), | ||
| // The running row's ts is the turn start itself, so clients read no append lag. | ||
| options: end ? {} : { observedAt: startedAt }, |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Do not apply the older-host fallback to provider-resumed turns.
userItemId is optional in the journal types and schemas, so the journal accepts and reads resumed records without it. However, selectStructuredAgentTurnTimings maps an omitted ID to precedingUserItemId. A resumed Claude lifecycle row can therefore attribute its duration to the previous user message and overwrite that message's timing in the renderer. Separate provider-resumed rows from older-host rows before applying this fallback.
There was a problem hiding this comment.
ℹ️ No critical issues — one minor observation inline.
Reviewed changes
- New turn-boundary module —
claude-turn-opening.tsextractsclaudeTurnOpenedByFrame: subagent frames never open, user roles open only onstartsTurn && claudeHasReplayContent, and any other role opens when!hasOpenTurn && producedContent. - Translator wiring —
claude-structured-journal-translation.tsreplaces the inline user-echo condition with the helper, passingproducedContent: changedandhasOpenTurn: currentTurn !== null. - Optional anchor —
claude-turn-lifecycle-item.tsmakesClaudeCurrentTurn.userItemIdoptional and omits it from the emitted turn body when absent. - Regression coverage —
claude-turn-resumption.test.ts(4 cases, 2 of which fail onmain) plus one retargeted assertion inclaude-structured-journal-translation.test.ts.
The core fix is correct and the asymmetry rationale (any result closes, so the model's own output may open) matches what Codex already does. The subagent and no-reopen guards are both pinned by tests. One downstream consumer of the now-keyless rows is not accounted for — see the inline note.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…self A Claude turn could only be opened by Orca's own send echo, while any `result` frame closed it. The provider resumes work on its own — a background task reports in and wakes the agent after `result` settled the turn — and nothing Orca sent ever arrives to reopen one, so the session projected `idle` for the rest of the work. The model's own output is the evidence a turn is running, the way Codex's `turn/start` is, so it opens one; whichever opened it, the next `result` settles it. Subagent frames still open nothing: children outlive the turn that spawned them, and their work is their parent turn's, never a turn of its own.
…d it A resumed turn was published after the frame's own rows, so its first tool call sat above the turn record. Every reader that scans back to the turn record and stops — the active-tool reader behind the sidebar's tool line, and the turn-window activity selector — looked straight past it, and the row showed working with no tool until a second call landed. The turn now opens before its frame is journaled. A send's turn keeps its existing order: the user echo is that turn's anchor and is written first. Prompt journaling moves to its own module, verbatim, to keep the translator clear of the line cap.
a1b821b to
7901ddb
Compare
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed the delta since the prior Pullfrog review at a1b821b — the second commit brackets a resumed turn around the output that opened it, tightens the opener predicate, and extracts prompt journaling.
- Bracket a resumed turn around its own output —
claude-structured-journal-translation.tsnow opens a provider-resumed turn before appending the frame's items, so the tool call or prose that opened it lives inside its own turn window. Verified this run: reverting the ordering makes the new live-tool test fail (activeStructuredAgentSessionToolCallreturnsundefined), and the change also correctsselectStructuredAgentTurnActivity, which slices forward from the turn record. - Tighten the opener predicate —
claude-turn-opening.tsreplaces the translator-suppliedproducedContentwith an internalproducesModelOutput(envelope): only a modeled body, tool call, or thinking counts as evidence, so unmodeled fallback traffic no longer opens a turn. - Extract prompt journaling —
handlePromptmoved verbatim intoclaude-prompt-journaling.ts; it shares the translator'spromptItemsmap, soprompt-cancelledtombstoning is unchanged.
A prior inline thread on the keyless-row timing selector is not addressed by these commits, so this is a non-approving review; that concern stays with the existing thread.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
The resumed-turn rule was a predicate that re-derived whether a frame had produced anything, duplicating work the frame handler had already done. The content sites know: each one now calls an idempotent ensureTurnOpen before it journals, and the guard against reopening a live turn lives in that one place. Behaviour is unchanged; claude-turn-opening.ts is left owning only the send echo, which is the one opener that anchors its turn to a user row.
There was a problem hiding this comment.
ℹ️ No new issues in this delta — the new commit is a behavior-preserving refactor. This review is non-approving solely because the earlier
selectStructuredAgentTurnTimingsthread is still open; that concern stays with its existing thread.
Reviewed changes
Reviewed the delta since the prior Pullfrog review at 7901ddb — one commit that moves the turn-open decision from a frame-level predicate to the content sites.
- Turn open declared at each content site — the translator gains an idempotent
ensureTurnOpencalled immediately before eachbody/ tool-use / thinking append. It returns early when a turn is already open, the envelope is notassistant, or the frame has a parent tool use. Traced and confirmed equivalent to the priorproducesModelOutputpredicate:ClaudeMessageEnvelope.roleis only'assistant' | 'user', thecurrentTurnguard replaceshasOpenTurn, and the same three content kinds drive opening. openTurnextracted and reused — the settle-interrupted-then-publish block that was inlined in the send-echo path is now a shared helper, and the resumed-turn path uses it too, so both openers end the previous turn identically.- Opener module narrowed to the send echo —
claude-turn-opening.tsnow exports onlyclaudeTurnOpenedBySendEcho; the subagent /startsTurn/claudeHasReplayContent/ explicit-nullconditions are unchanged, and the removed symbol has no other consumers. The ordering guarantee (turn record before the item that opened it) is preserved. - Targeted suites pass —
claude-turn-resumption+claude-structured-journal-translation+claude-structured-journal-translation-turn-timing: 30/30.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
The reopen path already refused nested output; the guard now reads before the already-running check so both edges state root-ness first. The close path had no nesting check at all, so a child's result would have ended the turn that spawned it. The two edges read parent_tool_use_id differently on purpose, and both fail towards not over-claiming: opening needs proof of root-ness, so an absent field opens nothing; closing needs proof of nesting, so an absent field still closes. No real Claude stream has been observed carrying a nested result — the session that prompted this work has none in any subagent stream — so the close-side guard is symmetry, not a demonstrated fix.
There was a problem hiding this comment.
ℹ️ No critical issues — the root-ness gating is correct; two rough edges worth a look.
Reviewed changes
Full review at 6a8b0c8 — the newest commit (6a8b0c84, "gate both turn edges on root-ness") had not been covered by the prior Pullfrog reviews.
- Root-ness gate on both turn edges —
ensureTurnOpennow checks root-ness before the already-running guard (behaviorally identical, both are pure guards), and theresultpath early-returns on a nestedparent_tool_use_idbefore settling the subagent roster or the turn, so a child's result can no longer close the turn that spawned it. The asymmetry is intentional and documented: an absent field opens nothing, but still closes. - Resumed-turn regression tests —
claude-turn-resumption.test.tsgains the nested-result case; the other five cases (working after resume, keyless turn record, subagent-only stays idle, no reopen, first tool call) are unchanged.
The mechanism is sound and the tests exercise the real reducer/projector. One gap in the opener's coverage and the still-open timing thread are noted below.
ℹ️ A resumed turn that opens on streamed prose still reads idle until the final frame
A resumed turn whose first output is streamed assistant text still projects idle until the block's final assistant frame lands, because handleStream returns before handleMessage and so skips every ensureTurnOpen call site. With includePartialMessages always on, that is the common shape of a provider resume, so the session can stay idle through the whole streaming window this fix is meant to cover. It is not a regression against main (which read idle throughout), but the fix is incomplete for prose-first resumptions.
Technical details
# Streamed deltas bypass the turn opener
## Affected sites
- `src/main/claude/claude-structured-journal-translation.ts:265` — `if (event.type === 'message' && handleStream(event.message)) return` returns before `handleMessage`, so `stream_event` delta frames never reach the opener.
- `src/main/claude/claude-structured-journal-translation.ts:126-144` — `ensureTurnOpen` is only called from the body / tool-use / thinking sites (`:190`, `:195`, `:220`).
- `src/main/claude/claude-structured-launch-resolution.ts:53` — `includePartialMessages: true` is unconditional structured-Claude config.
- `src/shared/structured-agent-session-projection.ts:228` — `projectStructuredAgentSessionStatus` reads `working` only from a running turn record or an unanswered dispatch, so a streamed row alone cannot make it working.
## Required outcome
- A provider-resumed turn reads `working` from its first streamed assistant delta, not only once the block's final frame arrives.
- A subagent's streamed text must still open nothing (the root-ness guard must apply on this path too).
## Evidence
- Scratch harness driving the real translator + projector: send opens a turn, `result` settles it, then `message_start`/`content_block_start`/`content_block_delta` for the resumed reply. `projectStructuredAgentSessionStatus` returned `idle` during the stream and `working` only after the final `assistant` frame.
## Suggested approach (optional)
- Thread an open callback through the streamed-text checkpoint/registry so the first accept for a root scope opens a turn (mirroring the content sites), or have `handleStream` call `ensureTurnOpen` for a root `stream_event` before appending.ℹ️ Resumed keyless turns still override the preceding prompt's timing
The prior inline thread on this PR is still open and unaddressed: selectStructuredAgentTurnTimings treats a missing userItemId as an older-host row and falls back to the nearest preceding user message, so a keyless resumed turn overwrites the original turn's settled-timing entry. While it runs the entry is null, which selectNativeChatTurnStatuses deletes, hiding the first turn's worked-for badge on desktop and mobile. No commit since 34a1b0551e touches the selector, so this remains the reason this review is non-approving.
Technical details
# Keyless resumed turn reuses the prior prompt's timing slot
## Affected sites
- `src/shared/structured-agent-session-turn-timing.ts:85-89` — a missing `userItemId` falls back to `precedingUserItemId`, and `Map.set` overwrites the earlier turn's entry.
- `src/main/claude/claude-turn-lifecycle-item.ts:75` and `:82` — the keyless `turn` body is emitted when the provider resumed.
- `src/shared/native-chat-turn-status.ts` — a `null` settled value is deleted, hiding the earlier duration.
## Required outcome
- A keyless resumed turn must not erase timing already attributed to the preceding user prompt; the original completed duration stays visible while the resumed work runs.
## Suggested approach (optional)
- Apply the older-host fallback only while the resolved key has no entry yet, so a keyless row does not take an existing prompt's slot.DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…lose Self-audit found two paths the reopen rule opened where no event could ever settle the turn it created, leaving the row working for the life of the session. Both now suppress reopening until an accepted send lifts it: - a frame arriving after the session ended, when no event will settle anything - a turn the provider failed, or the user stopped, where the next thing the provider says is not a resumption Each has a one-lever ablation: removing the suppression read alone fails exactly those two tests, and both fail as working-instead-of-idle.
There was a problem hiding this comment.
Important
The new is_error latch also suppresses provider-initiated resumption after a user abort — an interrupt arrives as a root result with is_error: true and terminal_reason: aborted_streaming/aborted_tools. A stop does not stop background tasks, so a task-completion wake after an abort still produces undispatched root assistant output that the latch now refuses to bracket in a turn, and the session projects idle while the agent works. That is the same bug this PR fixes, reached through the abort path.
Reviewed changes
Reviewed the delta since the prior Pullfrog review at 6a8b0c8 — one commit that adds a suppression latch so provider output cannot open a turn nothing can close, plus two regression cases.
- Latch provider reopen after the session ended — an
endedevent setsreopenSuppressed, so a late frame cannot open a turn that noresultwill ever settle; the child is gone and no event could close it. - Latch provider reopen after a failed result — a root
resultwithis_error === truesets the same flag, cleared when an accepted send echo opens a turn. The predicate is broader than the stated intent — see the inline note. - Regression coverage — two cases: a frame arriving after
endedstaysidle, and chatter after anis_errorresult staysidleuntil a new send.
ℹ️ Nitpicks
claude-structured-journal-translation.ts:84-86— "Only an accepted send lifts it" is not what the code does: line 298 reassigns the flag on every rootresult, so a later successful result clears it too. The comment could name both reset points.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| // reported as working will never be settled by an event. | ||
| // A turn that failed, or that the user stopped, is not resumed by | ||
| // whatever the provider says next; the next send is what resumes it. | ||
| reopenSuppressed = event.message.is_error === true |
There was a problem hiding this comment.
The is_error latch also catches user aborts, not just failures: an interrupt produces a root result with is_error: true and terminal_reason: 'aborted_streaming'/'aborted_tools' (see the fixture at claude-structured-journal-translation.test.ts:342-348 and claudeTurnEndForResult). A stop does not stop background tasks — cancelClaudeTurn only interrupts and withdraws queued async messages, while stopClaudeBackgroundTasks is a separate action — and backgrounded tasks outlive the turn. So when such a task completes it can still wake the agent and emit root assistant output, which ensureTurnOpen now refuses to bracket, and the session projects idle while the agent works. The ended half of the latch rests on a real invariant (nothing can close a turn once the child is gone); the is_error half does not.
Technical details
# Post-abort provider resumption is suppressed by the error latch
## Affected sites
- `src/main/claude/claude-structured-journal-translation.ts:298` — `reopenSuppressed = event.message.is_error === true`, set before the root result settles the turn.
- `src/main/claude/claude-structured-journal-translation.ts:141` — `ensureTurnOpen` bails on `reopenSuppressed`; reached from the body / tool-use / thinking sites (`:194`, `:199`, `:224`).
- `src/main/claude/claude-turn-lifecycle-item.ts:30,34` — an abort is `is_error: true` with `terminal_reason aborted_streaming|aborted_tools`.
- `src/main/claude/claude-structured-control-actions.ts:16-70` — `cancelClaudeTurn` interrupts and withdraws queued async messages but never stops background tasks; `stopClaudeBackgroundTasks` is separate.
- `src/main/claude/claude-background-task-tracker.ts:97-106` — backgrounded tasks outlive the turn; only their own terminal frame retires them.
## Required outcome
- A provider-resumed turn that begins after a user abort (background-task wake) reads `working`, the same as one that begins after a successful result.
- A frame arriving after the process is gone (`ended`) still opens nothing.
## Suggested approach (optional)
- Key the result latch on a genuine failure rather than on `is_error`, e.g. `reopenSuppressed = claudeResultFailure(event.message) !== null` (already imported at `:31`), or exclude the two abort reasons. State the `ended` latch's rationale separately — process-gone, not result meaning.
- Add a regression case: interrupt (`aborted_streaming`), then a `task-notification` wake plus a root assistant frame, expecting `working`.
## Evidence
- `claude-background-task-tracker.ts:76-106` keeps backgrounded tasks live across a `result` and resettles them only on their terminal frame; `claude-background-task-resume.test.ts:17-27` pins tasks surviving a `result`.
- `cancelClaudeTurn`'s own comment scopes it to queued async user messages, so an aborted turn leaves background tasks running.| reopenSuppressed = event.message.is_error === true | |
| reopenSuppressed = claudeResultFailure(event.message) !== null |
Streamed deltas short-circuit before the frame handler, so a resumed turn whose first output is streamed text — the common case, since partial messages are a pinned launch contract — kept reading idle while its partial text was already journaled and visible. The streamed path now opens the turn too. Also from the same audit: - a nested result no longer swallows its own failure diagnostic; the turn gate now guards only settlement, and the provider-fallback row is written either way - root-ness treats an absent parent_tool_use_id as root, so a build that omits the field cannot silently stop opening turns - the suppression latch only ever sets on a failed result; a later clean result cannot lift it, and only an accepted send does The opener moves into claude-turn-opening.ts so both entry points share one root-then-suppression-then-idempotency order.
There was a problem hiding this comment.
ℹ️ No new issues in this delta — the new commit closes the streamed-prose gap. Still non-approving because two prior inline threads remain open and unaddressed.
Reviewed changes
Reviewed the delta since the prior Pullfrog review at 30d3d90 — one commit that opens a resumed turn from its first streamed delta, extracts the opener into pure helpers, and makes the failure latch sticky.
- Open a resumed turn from its first streamed text delta —
handleStreamnow derives a turn source withclaudeStreamTurnSourceand callsensureTurnOpenbefore appending, so a provider resume whose first output streams readsworkingbefore the block's final assistant frame lands. This closes the earlier prose-first-resume gap, wherehandleStreamreturned before everyensureTurnOpensite. - Extract the opener into pure helpers —
claude-turn-opening.tsgainscreateClaudeTurnOpener,isRootClaudeFrame, andclaudeStreamTurnSource.isRootClaudeFrametreats a missingparent_tool_use_idas root and is now shared by the open path and the root-resultsettle path. - Make the failure latch sticky —
reopenSuppressed ||= event.message.is_error === true, so a later clean root result no longer lifts a failure latch; only an accepted send does. Pinned by a new test. - Regression coverage — three new cases (streamed-delta resume, nested-result failure still journaled, latch survives a later clean result) plus the existing ones; one assertion in
claude-structured-journal-translation.test.tsretargeted offitems.at(-1).
Two reasons this is still non-approving, both already tracked inline and untouched by this commit: the is_error latch still conflates user aborts with failures (claude-structured-journal-translation.ts:300), and a keyless resumed turn still overwrites the preceding prompt's settled timing (claude-turn-opening.ts:47). Separately, I verified that subagent stream_event frames cannot open a turn — Claude Code emits stream events for the main session only — so the streamed path adds no over-claim.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No new issues in this delta. Approval is withheld only because a prior Pullfrog thread remains open and untouched by these commits.
Reviewed changes
Reviewed the delta since the prior Pullfrog review at 947c2a2 — one commit that anchors provider-resumed turn timing to the turn's own lifecycle row and opens the turn earlier on two more paths.
- Anchor provider-resumed turns to their own lifecycle row —
claudeProviderResumedTurnTimingAnchorkeys a provider-opened turn'suserItemIdto its lifecycle row (soClaudeCurrentTurn.userItemIdis required again), andselectStructuredAgentTurnTimingsnow resolves that key to the lifecycle row instead of falling back to the nearest preceding user message. This closes the earlier finding: the resumed turn no longer overwrites the original prompt's settled timing. Regression case added. - Open the turn before unmodeled fallback output —
appendUnmodeledContenttakes abeforeAppendcallback that runs immediately before each unmodeled part is journaled, so the turn record precedes the status row it produced; the empty-assistant placeholder deliberately skips it, since it neither proves work began nor guarantees a closingresult.providerFallback.appendnow reports whether it appended. - Open on
message_start—claudeStreamTurnStartSourceopens a resumed turn at the provider's turn boundary, before its first content delta, keeping the first text delta as a fallback for streams that omit it.
I verified the timing fix against the pure selector, ran the claude/shared/renderer-consumer suites touching these paths (114 tests, all pass), and confirmed pnpm tc is clean. The still-open prior thread concerns the is_error latch conflating user aborts with failures (claude-structured-journal-translation.ts:300); it is unchanged by this commit and remains the reason this review is non-approving.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
Live Electron validation (HEAD
|
Review status: ready to landReviewed, fixed, and re-reviewed through a clean same-model loop at Meaningful fixes added during review:
Architecture and performance are clean: lifecycle remains owned by the host-side provider translator and the existing shared journal/status projection; frame handling is event-driven O(1), with no polling, timers, listeners, subprocess churn, retries, or new unbounded collections. Validation:
Visual proof and the backing lifecycle timeline: #20518 (comment) Scope stayed limited to the Claude resumed-turn lifecycle, its shared optional-field documentation, and regression tests. Branch and remote are synchronized and the worktree is clean. |





Root cause
A Claude turn could only be opened by Orca's own send echo —
startsTurncomes from thedispatch replay waiter — while any
resultframe closed it. That asymmetry is the bug class.The provider resumes work on its own: a background task reports in and wakes the agent after
resulthas already settled the turn. Nothing Orca sent ever arrives to reopen one, tool-resultuserframes do not qualify, and soactiveStructuredAgentSessionTurnIdkeeps reading acompletedrecord for the rest of the work. Once the pending-dispatch signal clears, the sharedprojection returns
idle— in the worktree sidebar, in the chat indicator and inworktree psalike, because all three read the one projection.
The fix makes the lifecycle symmetric, which is what Codex already does
(
codex-structured-journal-translation-turn-boundaries.tsopens on the provider's ownturn/start): the model's own output opens a turn when none is open, and whichever opened it, thenext
resultsettles it. Subagent frames still open nothing — children outlive the turn thatspawned them and their work belongs to the parent turn.
What contradicts the coordinator's hypothesis
The hypothesis was that
activeStructuredAgentSessionTurnIdfails to find the running turn record.It does not. Replaying the user's real journal (945 rows,
962e6f25…/epoch 3d214e6f…) through the real reducer and the real projector:The backward scan finds the correct, newest record,
readAgentJournalTurnparses it fine, and thatrecord genuinely says
completed. The record shape was never the problem.The feed-cache candidate is also ruled out. The projection recomputes on every row (the cursor
sequence changes each time) and the pure projector itself returns
idle. Full transition table fromthe same replay — it matches both of the user's observations exactly:
Between 13:56:06 and 14:05:25 the journal took 230 more rows of assistant messages and Bash
tool calls. Claude's own transcript shows why:
stop_hook_summaryat 13:56:06 (the agent stopped),then a
<task-notification>user frame at 13:58:59 woke it, and it produced continuously from13:59:03. Further stops at 13:59:32 and 14:03:14 journaled nothing at all, because
currentTurnwas already null.
So candidate 4 in the evidence pack is the right one, generalised: the turn ended legitimately, the
provider resumed without an Orca send, and nothing reopened it.
Ablation
Ablation, re-proven at head
947c2a267e. Eleven tests; every gate this PR introduces has itsown lever, and each lever was removed on its own:
mainworkingwhereidleis correctThe five tests that pass with production at
mainare the guard cases — sub-agent output opensnothing, an open turn is never reopened, a nested result settles no turn, a post-
endedframe opensnothing, the latch survives a later clean result. Each is the only ablation lever for a gate this PR
introduces, which is why it passes on
main:mainhas no reopen path for it to guard.One-lever replay of the real provider frames. 125 real frames from the user's session
(13:50:40–14:05:25) fed through the real translator; same harness, only the production code differs:
Arm B reproduces the real journal's own timeline, which is what makes the harness credible.
Live validation
Own isolated dev instance (
ORCA_BACKGROUND_LAUNCH=1, private profile, CDP 9334 / renderer 5174,hidden renderer screenshots, no computer-use, no OS input automation). A real structured Claude
session was given a backgrounded shell command and told to end its turn immediately. Its journal:
The same journal through the shared projector:
working15:30:44,idle15:30:53,working15:31:39,
idle15:32:22. Onmainrow 15 would not exist and the projector would have readidlefor all 89 seconds of that work.At 15:32:14 the chat indicator read "Working for 35s" — counting from the resumed turn's
startedAt(15:31:39 + 35s), not the original send — while the sidebar row for the same worktreeshowed its active agent glyph, with the turn still open and the composer showing its stop control.
Both surfaces, simultaneously, from the one shared projection.
Architecture review against reference implementations
The mechanism was re-derived against two reference agent clients. That review changed the code
twice and is the reason for the second and third commits.
The rule this PR implements is the reference's own rule. One reference runs its Claude provider
through a delta vocabulary into an assembler that keeps an
ensure a turn is openstep: anyprovider output that belongs in a turn opens one when none is open, with idempotency on an
already-open turn. Crucially, the provider adapter does not infer that a frame counts — every
content handler pushes a
turn.openmarker immediately before the content it just extracted(reasoning delta, text delta, assistant message), and the assembler dedupes. Its thread state
machine also has an explicit
idle --run.started--> activecell, so a run beginning with no send inflight is legal there, and deliberately has no such cell from the pre-execution state. The second
reference projects turns server-side with the same four-state vocabulary this repo already uses,
which supports keeping our representation.
Two things the review changed.
own first output. The first revision published the turn record after the frame's rows, which put
the first tool call of a resumed turn above the turn record — and both the active-tool reader and
the turn-window activity selector scan back and stop at that record, so they looked past it. The
row would have shown working with no tool name until a second call landed. Fixed, with a
regression test that fails on the first revision as well as on
main.predicate that re-derived the frame's body, tool uses and thinking — work the handler had already
done. That was invented, not taken from the reference. The content sites now call an idempotent
ensureTurnOpenas they journal, exactly as the reference declares its marker, and thealready-open guard lives in that one function.
A second reference rule this PR does NOT implement, and why. (Tracked as a follow-up.) The same adapter also refuses to
settle a turn at all while a completion-blocking background task is outstanding: a successful result
returns without emitting the turn boundary, and only a failed result settles through. That rule is
narrow — it keys on local agent/subagent task types, not backgrounded shell commands or
workflows. This repo already classifies the same task-type vocabulary and already tracks per-task
terminal state, so it is implementable by reuse rather than invention. It is left out here because
its trigger was not present in the reported session: those
task_notificationframes carry no tasktype at all, so the blocking predicate would not have fired, and the turn would still have settled
exactly as it did. The rule that actually covers the reported bug is the reopen-on-output rule this
PR implements. Worth taking as a follow-up; flagged rather than added on speculation.
Root-ness gates both edges. The reopen path is gated on root-ness before its
already-running check, in that order: a child's output must never open a turn, or the session would
report working because a subagent spoke — the mirror image of this bug, and the worse one because it
over-claims. The close path had no nesting check at all, so a child's result would have ended the
turn that spawned it; it now has one. The two edges read the field differently on purpose, and both
fail towards not over-claiming: opening needs proof of root-ness, so an absent field opens
nothing; closing needs proof of nesting, so an absent field still closes.
To be plain about the close side: no real Claude stream has been observed carrying a nested result.
The session that prompted this work has none in any of its subagent streams, and the result that
closed its turn was provably the root's — its reported duration (322.9s) exceeds the turn's own wall
clock (273.5s), which only a cumulative root-query measure does. The close-side guard has a unit
ablation (removing it alone fails exactly one test) but it is symmetry, not a demonstrated fix,
and it fixes nothing observed.
One shared derivation. The working state is derived once, in a projector the sidebar row, the
in-chat indicator and
worktree psall read, so those surfaces cannot disagree. A follow-up addinga background-liveness term belongs in that same one place.
Material deviations that remain, deliberately.
that normalizes every provider. This repo has no such bridge — each provider translator
normalizes its own stream, and the other provider already receives an explicit turn-start event
from its own protocol — so the rule lives in the Claude translator.
assembler mints its turn-open event with no parent id, so the root filter downstream is inert for
that path and a sub-agent frame there does open a root turn. We filter where the frame is
translated, so sub-agent output opens nothing. This is deliberately stricter than the reference,
in the non-over-claiming direction.
turn completes that never started. Here a terminal frame arriving with no open turn is silently
dropped — not hypothetical: two real stops in the captured journal (13:59:32, 14:03:14) journaled
nothing for exactly this reason.
through an explicit transition table. Here status is derived by scanning the journal tail. That
is this repo's existing architecture across every provider and surface; disclosed, not claimed as
alignment.
Ordering disclosure: the first revision was written before this reference research, not after.
Notes
producer, and this only corrects when it is written (
docs/reference/agent-status-store.md).resultexactly like a send-openedone, and it inherits the same crash/
endedsettlement, so no new staleness class.resumed turn before that row; empty placeholders remain non-opening.
state being missing while nothing is pending.
ClaudeCurrentTurn.userItemIdremains required. Provider-resumed turns self-key their lifecyclerow so legacy and current timing readers do not attribute the synthetic turn to the preceding
prompt; the shared wire field remains optional for older hosts.
items.at(-1)onto the reasoning row it was actually testing —the frame now also opens the turn it produced in.
cap without a disable or a ratchet bump (273 effective lines, cap 300).
Verification
pnpm tc— exit 0.pnpm testonsrc/main/claude src/main/native-chat src/shared— 945 files passed, 9988 testspassed, 6 files / 122 tests skipped, 2 failed. Neither is a regression:
claude-structured-real-cli.test.tsspawns the real installed Claude CLI and asserts on thismachine's command catalog — it fails identically with every change in this PR reverted;
repo-ref-maintenance.test.tsandstructured-agent-session-lease-renewer.test.tseach pass ontheir own (19/19 and 7/7) and are full-suite-load flakes in files this branch does not touch.
claude-turn-resumption+claude-structured-journal-translation(+ turn-timing,subagents, projection, status-feed) — 6 files, 88 tests passed.
pnpm run check:code-quality:changed— 0 new findings across 5 changed files on all five gates.oxlintclean;oxfmt --checkclean. Nomax-linesdisable or ratchet bump: the translator sitsat 286 effective lines against a 300 cap, after prompt journaling moved to its own module with its
code unchanged.
git diff origin/main...HEADbefore push.