Skip to content

fix(native-chat): let the provider reopen a Claude turn it resumed itself - #20518

Merged
brennanb2025 merged 7 commits into
mainfrom
brennanb2025/native-chat-working-status
Sep 14, 2026
Merged

brennanb2025 merged 7 commits into
mainfrom
brennanb2025/native-chat-working-status

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​439 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​437
Prod 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​282 $\color{#cf222e}{\Huge{\mathbf{−}}}$​87 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​195

Root cause

A Claude turn could only be opened by Orca's own send echo — startsTurn comes from the
dispatch replay waiter — while any result frame 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
result has already settled the turn. Nothing Orca sent ever arrives to reopen one, tool-result
user frames do not qualify, and so activeStructuredAgentSessionTurnId keeps reading a
completed record for the rest of the work. Once the pending-dispatch signal clears, the shared
projection returns idle — in the worktree sidebar, in the chat indicator and in worktree ps
alike, 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.ts opens on the provider's own
turn/start): the model's own output opens a turn when none is open, and whichever opened it, the
next result settles it. Subagent frames still open nothing — children outlive the turn that
spawned them and their work belongs to the parent turn.

What contradicts the coordinator's hypothesis

The hypothesis was that activeStructuredAgentSessionTurnId fails 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:

=== AT seq=653 (14:05:18, 7s before "this agent does not currently show as working") ===
activeStructuredAgentSessionTurnId = null
projected status = idle
newest turn record at renderIndex 54 of 267   createdAtSeq=137 revision=2
  turn = {"turnId":"b4ec3f01…","state":"completed","completedAt":1789332966180,"durationMs":322937}
items AFTER newest turn record: 213
  tool-calls still `running` after it: 1   (seq 653, 14:05:18, Bash)

The backward scan finds the correct, newest record, readAgentJournalTurn parses it fine, and that
record 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 from
the same replay — it matches both of the user's observations exactly:

seq= 137 13:51:32  idle -> working      (the send opens the turn)
seq= 423 13:56:06  working -> idle      (a result settles it; the agent really did stop)
seq= 654 14:05:25  idle -> working      (only the user's own next send brings it back)

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_summary at 13:56:06 (the agent stopped),
then a <task-notification> user frame at 13:58:59 woke it, and it produced continuously from
13:59:03. Further stops at 13:59:32 and 14:03:14 journaled nothing at all, because currentTurn
was 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 its
own lever, and each lever was removed on its own:

Lever removed Tests that fail
all production files at main 6 of 11
turn-open on the streamed path 1 — resumed turn reads idle while its partial text is journaled
the settles-turn gate on a nested result 2 — child's result ends the turn, and its diagnostic is written
the suppression latch 3 — all three report working where idle is correct

The five tests that pass with production at main are the guard cases — sub-agent output opens
nothing, an open turn is never reopened, a nested result settles no turn, a post-ended frame opens
nothing, 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: main has 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:

A) with the fix                    B) unmodified main
13:50:43  <start> -> working       13:50:43  <start> -> working
13:56:06  working -> idle          13:56:06  working -> idle
13:59:04  idle -> working
13:59:32  working -> idle
14:02:13  idle -> working
14:03:14  working -> idle
14:03:29  idle -> working
FINAL (14:05:18): working          FINAL (14:05:18): idle

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:

seq= 4  15:30:47 state=running    turnId=aa16fdeb  userItemId=PRESENT  (send-opened)
seq=13  15:30:53 state=completed  turnId=aa16fdeb
seq=15  15:31:39 state=running    turnId=fa3b700d  userItemId=SELF     <-- provider-resumed timing anchor
seq=24  15:32:22 state=completed  turnId=fa3b700d

The same journal through the shared projector: working 15:30:44, idle 15:30:53, working
15:31:39
, idle 15:32:22. On main row 15 would not exist and the projector would have read
idle for 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 worktree
showed 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 open step: any
provider 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.open marker 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--> active cell, so a run beginning with no send in
flight 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.

  1. Ordering. The reference emits its turn marker before the content delta, so a turn brackets its
    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.
  2. No inferred predicate. The first revision decided "did this frame produce anything" in a
    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
    ensureTurnOpen as they journal, exactly as the reference declares its marker, and the
    already-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_notification frames carry no task
type 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 ps all read, so those surfaces cannot disagree. A follow-up adding
a background-liveness term belongs in that same one place.

Material deviations that remain, deliberately.

  1. Where the rule lives. The reference puts its turn-open step in one provider-agnostic assembler
    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.
  2. Root filtering happens at the producer, and is stricter than the reference. The reference's
    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.
  3. No sequence grammar. The reference validates event order and reports a typed violation when a
    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.
  4. Derived vs stored status. The reference stores an execution status and gates every change
    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

  • No new producer and no reader-side precedence rule: the turn record is the existing single
    producer, and this only corrects when it is written (docs/reference/agent-status-store.md).
  • No over-claiming: the resumed turn is settled by the next result exactly like a send-opened
    one, and it inherits the same crash/ended settlement, so no new staleness class.
  • Substantive unknown assistant content uses the existing provider fallback row and opens the
    resumed turn before that row; empty placeholders remain non-opening.
  • Unrelated to fix(native-chat): hide activity while awaiting input #20496 (which deliberately hides the row while awaiting input) — this is about the
    state being missing while nothing is pending.
  • ClaudeCurrentTurn.userItemId remains required. Provider-resumed turns self-key their lifecycle
    row 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.
  • One existing assertion moved off items.at(-1) onto the reasoning row it was actually testing —
    the frame now also opens the turn it produced in.
  • Prompt journaling moved to its own module, code unchanged, to keep the translator under the line
    cap without a disable or a ratchet bump (273 effective lines, cap 300).

Verification

  • pnpm tc — exit 0.
  • pnpm test on src/main/claude src/main/native-chat src/shared — 945 files passed, 9988 tests
    passed, 6 files / 122 tests skipped, 2 failed
    . Neither is a regression:
    claude-structured-real-cli.test.ts spawns the real installed Claude CLI and asserts on this
    machine's command catalog — it fails identically with every change in this PR reverted;
    repo-ref-maintenance.test.ts and structured-agent-session-lease-renewer.test.ts each pass on
    their own (19/19 and 7/7) and are full-suite-load flakes in files this branch does not touch.
  • Targeted: 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.
  • oxlint clean; oxfmt --check clean. No max-lines disable or ratchet bump: the translator sits
    at 286 effective lines against a 300 cap, after prompt journaling moved to its own module with its
    code unchanged.
  • Both lockfiles verified absent from git diff origin/main...HEAD before push.

@coderabbitai

coderabbitai Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview 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: Advanced

Run ID: dc0a0a0f-2c35-4153-a718-2f1b924cd800

📥 Commits

Reviewing files that changed from the base of the PR and between 6a8b0c8 and 30d3d90.

📒 Files selected for processing (2)
  • src/main/claude/claude-structured-journal-translation.ts
  • src/main/claude/claude-turn-resumption.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.


📝 Walkthrough

Walkthrough

Claude 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 userItemId. Nested results no longer settle the parent turn. Prompt journaling uses journalClaudePrompt. Tests cover lifecycle transitions, resumed records, nested results, tool projection, and reasoning-row lookup.

Priority: ⬇️ Low

Merge Risk: ⚪ Minimal · up to 30d3d

No concrete merge-blocking risk has been established for the current change.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 6 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning 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… Add a valid issue reference under Linked Issue, add Visual Proof with before/after evidence or exactly N/A with a reason, and complete the required template sections and checklist items.
✅ Passed checks (3 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly identifies the primary change: allowing the provider to reopen a Claude turn that it resumed itself.
Full details: Description check

Explanation

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.

  • Fix all pre-merge checks with AI
✨ 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: 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.ts
  • src/main/claude/claude-structured-journal-translation.ts
  • src/main/claude/claude-turn-lifecycle-item.ts
  • src/main/claude/claude-turn-opening.ts
  • src/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.

Comment on lines 72 to 86
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 },

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.

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

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

ℹ️ No critical issues — one minor observation inline.

Reviewed changes

  • New turn-boundary module — claude-turn-opening.ts extracts claudeTurnOpenedByFrame: subagent frames never open, user roles open only on startsTurn && claudeHasReplayContent, and any other role opens when !hasOpenTurn && producedContent.
  • Translator wiring — claude-structured-journal-translation.ts replaces the inline user-echo condition with the helper, passing producedContent: changed and hasOpenTurn: currentTurn !== null.
  • Optional anchor — claude-turn-lifecycle-item.ts makes ClaudeCurrentTurn.userItemId optional and omits it from the emitted turn body when absent.
  • Regression coverage — claude-turn-resumption.test.ts (4 cases, 2 of which fail on main) plus one retargeted assertion in claude-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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment thread src/main/claude/claude-turn-opening.ts Resolved
…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.
@brennanb2025
brennanb2025 force-pushed the brennanb2025/native-chat-working-status branch from a1b821b to 7901ddb Compare September 14, 2026 00:32

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

✅ 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.ts now 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 (activeStructuredAgentSessionToolCall returns undefined), and the change also corrects selectStructuredAgentTurnActivity, which slices forward from the turn record.
  • Tighten the opener predicate — claude-turn-opening.ts replaces the translator-supplied producedContent with an internal producesModelOutput(envelope): only a modeled body, tool call, or thinking counts as evidence, so unmodeled fallback traffic no longer opens a turn.
  • Extract prompt journaling — handlePrompt moved verbatim into claude-prompt-journaling.ts; it shares the translator's promptItems map, so prompt-cancelled tombstoning 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.

Pullfrog  | Fix it ➔ | View workflow run | Using 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.

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

ℹ️ No new issues in this delta — the new commit is a behavior-preserving refactor. This review is non-approving solely because the earlier selectStructuredAgentTurnTimings thread 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 ensureTurnOpen called immediately before each body / tool-use / thinking append. It returns early when a turn is already open, the envelope is not assistant, or the frame has a parent tool use. Traced and confirmed equivalent to the prior producesModelOutput predicate: ClaudeMessageEnvelope.role is only 'assistant' | 'user', the currentTurn guard replaces hasOpenTurn, and the same three content kinds drive opening.
  • openTurn extracted 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.ts now exports only claudeTurnOpenedBySendEcho; the subagent / startsTurn / claudeHasReplayContent / explicit-null conditions 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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@brennanb2025
brennanb2025 marked this pull request as draft September 14, 2026 01:50
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.
@brennanb2025
brennanb2025 marked this pull request as ready for review September 14, 2026 02:41

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

ℹ️ 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 — ensureTurnOpen now checks root-ness before the already-running guard (behaviorally identical, both are pure guards), and the result path early-returns on a nested parent_tool_use_id before 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.ts gains 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.

Pullfrog  | Fix it ➔ | View workflow run | Using 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.

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

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 ended event sets reopenSuppressed, so a late frame cannot open a turn that no result will ever settle; the child is gone and no event could close it.
  • Latch provider reopen after a failed result — a root result with is_error === true sets 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 ended stays idle, and chatter after an is_error result stays idle until 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 root result, so a later successful result clears it too. The comment could name both reset points.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using 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

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.

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.
Suggested change
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.

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

ℹ️ 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 — handleStream now derives a turn source with claudeStreamTurnSource and calls ensureTurnOpen before appending, so a provider resume whose first output streams reads working before the block's final assistant frame lands. This closes the earlier prose-first-resume gap, where handleStream returned before every ensureTurnOpen site.
  • Extract the opener into pure helpers — claude-turn-opening.ts gains createClaudeTurnOpener, isRootClaudeFrame, and claudeStreamTurnSource. isRootClaudeFrame treats a missing parent_tool_use_id as root and is now shared by the open path and the root-result settle 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.ts retargeted off items.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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

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

ℹ️ 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 — claudeProviderResumedTurnTimingAnchor keys a provider-opened turn's userItemId to its lifecycle row (so ClaudeCurrentTurn.userItemId is required again), and selectStructuredAgentTurnTimings now 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 — appendUnmodeledContent takes a beforeAppend callback 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 closing result. providerFallback.append now reports whether it appended.
  • Open on message_start — claudeStreamTurnStartSource opens 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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Live Electron validation (HEAD fe2f2b806863f90827fcd34e34ee55f8a1c7e315)

Hidden-renderer CDP run (ORCA_BACKGROUND_LAUNCH=1). App identity: Orca: brennanb2025/native-chat-working-status. A real structured Claude session was given a backgrounded shell command and told to end its turn immediately, then reply when the task-notification arrived.

Provider-resumed turn is Working before its first new output (chat shows Working for 0s, composer Stop, sidebar glyph live; last journaled assistant text is still the previous turn):

08-provider-resumed-working.png

Idle after the send-opened turn settled (Worked for 5s, composer Send, background shell still running):

02-idle-after-send-opened-turn.png

Idle after the first provider-resumed root result (RESUMED, original Worked for 5s timing unchanged):

04-idle-after-provider-resume.png

Idle after a later resumed root result (RESUMED3, composer Send):

12-final-idle.png

Cycle-1 backing feed (same session claude_9620a359_3d77_4a7d_bb03_1430cd85b4c6):

  • send-opened turn bb7f3b01… completed
  • status idle
  • provider-resumed turn d6541496… opened running with userItemId legacy:claude:…:turn-lifecycle%3Ad6541496… (no Orca send)
  • status working while last assistant text was still the previous turn
  • first resumed token "R" 25ms later
  • status idle on the closing root result (RESUMED)

Public attachment URLs:

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status: ready to land

Reviewed, fixed, and re-reviewed through a clean same-model loop at fe2f2b806863f90827fcd34e34ee55f8a1c7e315.

Meaningful fixes added during review:

  • corrected the stale streamed-journal assertion that was failing CI
  • opens resumed turns at the provider message_start boundary, retaining the first text delta as a compatibility fallback
  • opens before substantive unknown root-assistant fallback output
  • keeps empty assistant placeholders from creating a permanently Working turn
  • self-anchors provider-resumed lifecycle timing so current and legacy clients do not overwrite the preceding prompt timing
  • preserves the root/subagent, result, failure, suppression, and end-of-session gates

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:

  • closing readiness audit: PASS, no proven P0/P1/P2 findings
  • focused lifecycle/projection/capability coverage: 137/137 passed
  • pnpm tc:node: passed
  • changed-code quality: 0 findings across all 8 changed files
  • all GitHub checks green: static analysis, typecheck, all 8 test shards, cross-version wire compatibility, macOS/Linux package, Windows package, verify, guards, and Pullfrog
  • live hidden Electron validation with a real structured Claude session: provider-resumed status became Working 25 ms before its first new token, rendered Working for 0s with Stop/live sidebar state, and returned idle on the closing root result

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.

@brennanb2025
brennanb2025 merged commit 4634d2c into main Sep 14, 2026
52 of 54 checks passed
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