Repository navigation
fix(native-chat): a message Claude folds into its running turn no longer splits the turn - #23621
Conversation
… not a turn boundary A message sent while a Claude turn runs is folded into the running turn by the CLI and replayed mid-turn with the client uuid. The replay-driven opener treated that replay as a new turn: the running turn was marked interrupted and the 'Worked for' bar split. The dispatch waiter now captures the open turn at write time (sentDuringTurnId, volatile); a replay that adopts the client uuid while that exact turn is still open settles delivery and opens no boundary. Plural result user_message_uuids settle each waiter under its own uuid; every other relation (miss, replaced turn, provider-resumed root, idle write, fresh replay uuid) keeps the opener path. Replay/turn resolution split out of the dispatch module to hold the line budget.
…easured The receipt admits only a replay that adopts the client uuid. The comment and test named a fresh replay uuid as "the CLI starting the queued send's own turn", but the measured miss case adopts the client uuid too, so adoption does not tell a fold from a later turn. Say what the rule actually is: the measured fold shape qualifies, and an unmeasured fresh-uuid replay keeps the opener path it always had. No behavior change.
… request cycle Measured (p3 captures, CLI 2.1.280): the CLI folds any send that arrives while its request cycle runs — including one written before the first replay — and it announces every new cycle (sequential turn, queued turn, background wake, /compact) with a root system/init; each result names the sends its cycle ran in user_message_uuids. So the fold decision now reads provider state: an adopted replay while the open turn's cycle is still live (no root init since it opened) is a delivery receipt. The send-time bookkeeping (sentDuringTurnId) is removed; it missed the measured early-steer fold and guessed at what the provider states outright. A lost result is covered by the init staleness mark, and CLIs below the per-turn-init version floor (or with no reported version) keep today's opener path via an explicit gate on the init frame's claude_code_version.
A finished background task revises its row before the wake cycle's init, so the wake turn opened ahead of that init and was marked stale by it: a send folded into the wake still split the bar and interrupted the wake turn (captured p3-background-wake order). A send replayed after the current cycle's first root work (send echo or model output) is the fold; the cycle's first send is its opener. Init and every settle start a cycle with no work.
… the startup proof Live sessions prove the session from a SessionStart hook frame that arrives BEFORE system/init, so startup facts read a frame with no claude_code_version and the fold receipt's version gate never passed: the real app still split the bar and marked the running turn interrupted while every fixture test — whose harness proves startup with the init frame itself — stayed green. The version is now adopted from whichever init frame carries it, at the same site that already adopts the per-turn model report, and the startup proof never clobbers a version a real init already reported. Pinned twice: a fixture run whose startup proof is the SessionStart hook frame, and a real-CLI fold test (skipped without a signed-in CLI) that fails on the unfixed branch at the interrupted assertion and passes with the fix.
…obed The connection strips an inherited CLAUDE_CONFIG_DIR and inherited auth vars, and with no launch env the pin compared against that same inherited value and emitted nothing, so the fold test always ran against ~/.claude whatever CLAUDE_CONFIG_DIR the availability probe checked. It also relied on the user's own SessionStart hooks for the live proof order and on their permission rules for the Bash steps; an isolated home hung at startup. The test now launches with the probed home and env auth, and pins a SessionStart hook and the sleep permission itself.
…t full adapter captures The fold rule stands on frame-derived facts alone: an adopted client uuid (the capability check, read off the replay itself) while the open turn's cycle has done root work. The claude_code_version floor guarded only an unobserved triple fault — an adopting CLI without per-turn init AND a lost result — and its cost was a silent latch that already fired once live; all cliVersion plumbing is removed. Mid-turn auto-compaction was measured (forced via CLAUDE_CODE_AUTO_COMPACT_WINDOW): it emits status/compact_boundary and a synthetic continuation but NO root init, so the init cycle reset stays and the capture is pinned. The fake connection now defaults to the live startup shape (SessionStart hook proof; one init when the first command starts a cycle; capabilities on the initialize result), with init-at-startup an explicit unmeasured opt-in. Full frame streams recorded through Orca's own adapter against the real CLI are committed and replayed verbatim, asserting the provider's membership fact (each result's user_message_uuids) rather than design internals.
…omments Also reattaches the fake harness's initProof doc to initProof (it had landed on contextUsage, replacing that field's own doc) and renames a plural-result test whose title described a retired waiter it never creates.
…eipt # Conflicts: # src/main/claude/claude-structured-session-acquisition.ts
…give the slow-init test a live startup report The shared real-CLI availability probe moved out of a test file, so the child_process and CLI-runtime-pairing ratchets now scan it. It spawns through runProcessSync with the CLI paired to its own node, as the structured launch does. The provider-started test's CLI default now reaches startup the live way: get_settings reports it, since system/init only arrives with the first command.
|
Status: ready for review (head
|
|
| async () => { | ||
| const providerSessionId = randomUUID() | ||
| const { claudeConfigDir, env } = realClaudeLaunchHome() | ||
| const cwd = await mkdtemp(join(tmpdir(), 'orca-real-fold-')) |
There was a problem hiding this comment.
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. 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 (37)
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review. 📝 WalkthroughWalkthroughThe Claude adapter now tracks root work within provider cycles and resolves replay and result frames against dispatch waiters. Folded replays can settle delivery without opening another turn. New captured fixtures and tests cover folded, early, late, missed, cancelled, and background-wake scenarios. Test support also separates startup proof from cycle initialization and centralizes the real-CLI availability probe. Priority: ➖ Normal Merge Risk: ⚪ Minimal · up to The Claude turn-handling change is mergeable after normal checks; no actionable issue is established by the supplied evidence. Security Architecture ReviewSecurity architecture risk: 🟡 Moderate · up to The fix keeps messages folded into ongoing work in one turn. Session checks limit its reach, but an unusual out-of-order replay could attribute the active turn incorrectly and affect a stop request. That ordering case is not resolved by the evidence reviewed. Retained concerns
Security review detailsSecurity Blast Radius
Security Findings and Attack Paths
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Docstring CoverageExplanation Docstring coverage is 20.93% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 43 functions across 34 files. (3 skipped: 3 unsupported.) Full details: Description checkExplanation The description is detailed and covers the required explanation, user-facing change, rationale, testing, visual proof, scope, and checklist. However, the required Linked Issue section contains “None,” which does not satisfy the template unless the author is a repository maintainer covered by the stated exception.
✨ 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.
✅ No new issues found.
Reviewed changes
- Fold receipt rule — an adopted send replay (
frame.uuid === waiter.sentUuid) is treated as a delivery receipt, not a turn boundary, when the translator reportsopenTurnInLiveProviderCycle. Wired through the newresolveClaudeReplayTurninclaude-replay-turn-resolution.ts:26and the extractedClaudeLateDispatchSettlement. - Provider-cycle state —
ClaudeOpenTurnnow derivesopenedInLiveProviderCyclefromcycleWorkObserved: a rootsystem/initresets it, root send-echo /assistant/stream_eventset it, everysettleclears it. Task frames are deliberately not work (claude-open-turn.ts:74,claude-structured-journal-translation.ts:191). - Plural result correlation — a
result'suser_message_uuidssettles each named unsettled waiter under its own uuid, and a result naming only settled sends no longer claims an unnamed live waiter by queue order (claude-replay-turn-resolution.ts:56). - Captured evidence — full adapter captures (
__fixtures__/claude-adapter-capture-{fold,early-steer,miss}.jsonl) replayed frame-for-frame with the provider's own membership fact as the oracle, plus 15 synthetic/captured cases inclaude-fold-steer-receipt.test.ts. - Test harness fidelity —
fakeClaudedefault startup proof is now the livesession-startshape (hook frames first,initon the first command); the real-CLI probe routes through therunProcessSyncspawn chokepoint.
I confirmed the new tests actually pin the fix: disabling claudeReplayIsFoldReceipt fails every fold case and the capture-replay membership assertion. The changed suites pass locally; the only src/main/claude failures are pre-existing environment cases (claude-agent-sdk-exit-proof, -background-task-retention without --expose-gc, -stream-json-connection descendant proof), none of which this PR touches.
ℹ️ The per-cycle init reset is now load-bearing
The receipt rule depends on cycleWorkObserved being cleared by a root init, so that a lost result followed by a new cycle still yields a turn boundary. If a future CLI ever omits that init (the auto-compaction variant is already documented), the flag stays set and a genuinely new send's adopted replay is swallowed as a receipt — a missing boundary rather than a spurious one. Nothing to change now; the captured corpus is what keeps this honest, so it is worth keeping the replay fixtures current when the CLI moves.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…3700, #22943, #23720, #23793, #23776, #23796) into #23059 #23573 (keep a turn's bar on the prompt that opened it) is ported onto the turn-record membership instead of kept as a second owner lookup: - The running turn's bar comes from nativeChatTurnMembership, which now returns barTurnKey beside liveTurnKey. Where the host states each row's turn they are the same key: the running root turn's anchor, and a message handed over mid-turn is already scoped to that turn. Where the host states no scope, rows still group by position, so barTurnKey is the user entry the running record names (through the same anchors) while liveTurnKey keeps the positional live group, as #23573 kept row liveness on the newest prompt. - activeTurnOpenedBy, selectStructuredAgentTurnBars' openedBy and selectNativeChatActiveTurnKey are removed; the desktop list, the slot builder and both turn-status hooks read barTurnKey. - The queued-send clock (queuedUntil: a turn counts from the previous turn's end when its send waited behind it) is kept, read in the same one-pass walk over root turn records that keys timing by anchor. - Its tests are adapted to pass a journal: each runs on a host that states no scope (the original expectations), and the desktop and mobile bar tests also run on a scoped host. #23621 (a message Claude folds into its running turn no longer splits the turn) is host-only and merged as is: the translator contract carries both openTurnInLiveProviderCycle and #23059's command-turn members. Both sides grew the Claude translator past its line budget, so its result branch moves unchanged into claude-result-journaling.ts, beside claude-message-journaling.ts (the pre-commit lint refuses the merge without it). #23801's Codex child path (no error-driven end) and #23059's Codex /compact guard (a command turn ends only on turn/completed) both stand.
main's #23621 moved the real-Claude probe into a shared support module that both real-CLI suites import, probing on import with no opt-in. That module now takes its availability from this PR's opt-in gate, so neither suite probes or runs the CLI unless ORCA_REAL_CLAUDE_CLI_TEST=1, and AGENTS.md names both suites.

Where this fits: the plan for messages sent while the agent is working
The problem. In a structured (native) chat, a message you sent while the agent was still working went straight to the agent. What happened next depended on the agent:
Orca then drew the conversation wrong:
The plan. A message sent mid-turn waits as a card above the message box, with three actions:
Otherwise it sends by itself when the turn ends. Only Steer puts a message into a running turn. With queueing turned off in Settings, mid-turn messages still go straight in, as they do today.
The work is split into six PRs:
Steer on Codex also needs Codex's turn-steer support from #21062, which is still open.
The queue stays switched off, meaning the host does not advertise it and every client behaves as today, until PRs 1–6 and #21062 have landed. Turning it on is then a one-line change.
This PR is step 3, and the Claude half of Steer. When you press Steer, the queued message is written to Claude while it works, and Claude folds it into the running turn at its next step. Today Orca reads Claude's echo of that message as a brand-new turn, so the running turn is marked interrupted and the time splits across two bars. This PR reads Claude's own cycle boundaries instead, so a folded message joins the turn. It also fixes today's immediate mid-turn sends and sends made with queueing turned off.
ELI5
When you send Claude a second message while it is still working, Claude folds it into the work it is already doing. Orca used to show that as the first task being "interrupted" and a brand-new task starting, which split the "Worked for" time in two. Now Orca shows it as one piece of work that your extra message joined.
What Changed
Before: in a Claude chat, you send a message, and while Claude is working you send another one. Claude reads it at its next step and keeps going. It never stops, and at the end it reports one finished result that covers both messages. Orca, though, saw Claude echo your second message back and treated that echo as the start of a new turn. It marked the running turn as interrupted and opened a new one. The chat showed two "Worked for" bars (for example 17s and 52s) and an interrupted turn that never really happened.
After: the echo of a message Claude folded into its running turn is treated as a delivery receipt. The running turn stays open and is not marked interrupted, and the chat shows one "Worked for" for the whole piece of work. Your second message still appears in the transcript where you sent it. If your message arrives just too late, after Claude has already finished, Claude really does start a new turn for it, and Orca still shows that as its own turn.
Mechanism: the Claude CLI already states where its work cycles begin and end. Each cycle starts with a
system/initframe and ends with aresultthat lists every message that ran in it (user_message_uuids). A message Claude folds in produces no newinit. Orca now uses those provider facts. An echo of our own message is a receipt when a turn is open and the current cycle has already produced output. A newinitor the end of a turn resets that. Each message named in a result is settled under its own id. Nothing new is stored: "this cycle has already done work" is derived from the frames as they arrive, and every new cycle recomputes it. Older CLIs that give the echo a fresh id instead of reusing ours never match, so they keep today's behaviour. There is no version check: the rule reads only what the frames say.Why
The bug came from treating "Claude confirmed it received my message" and "Claude started a new turn" as the same signal. The CLI reports both separately, so the fix reads the CLI's own boundaries instead of inferring them from Orca's send-time bookkeeping. An earlier version of this change keyed off which turn was open when the message was written. A live capture showed that misses messages written before Claude has echoed the first one, so the design moved to the provider's own cycle state.
Alternatives considered: marking a steered message as "inside the turn" on Orca's side regardless of what Claude does. That would hide real new turns when a message arrives after Claude finished, so it was rejected. Opening turns directly from
initalso doesn't work, because the CLI emits aninitwhen an idle session starts, with nothing to run.This pairs with #23573, which keeps a running turn's bar under the message that opened it. Without #23573, the renderer still moves the live bar to the newest message, so both are needed for the single bar users should see.
Known limits (unchanged behaviour, none seen in captures): if auto-compaction ever emitted an
initin the middle of a turn, a message landing in that gap would fall back to today's split.Linked Issue
None; found during QA of #23537 and #23573.
Visual Proof
Live structured Claude chat on a dev build (real Claude CLI 2.1.283). Prompt A asks for four
sleep 15tool calls, and message B ("Also say the word banana at the end.") is sent about 5 s in, while A is still running. Claude folds B into the running turn.Before: A reads "Worked for 17s", and B has its own "Worked for 52s"; the host journal records A's turn as interrupted plus a second turn. After: there is one "Worked for 1m 10s" under A (≈ wall time), with no bar on B and nothing interrupted. Sampled every second, one bar counted without a break for the whole run. The host journal shows a single turn owned by A that ends completed. The first live QA of this branch failed. An earlier version gated the fix on the CLI version, and a live session proves its startup with a hook frame that carries no version, so the fix silently switched itself off. The gate is gone, and the run above is after that change.
Testing
Three full captures, recorded through Orca's own adapter against the real CLI (a folded message, a message sent before the first echo, and a message that misses the turn end), are replayed frame for frame. The check is the CLI's own statement of which messages ran in each turn (
user_message_uuids), not Orca's internals. Scrubbed synthetic sequences cover a resumed session, two folded messages, Stop with a queued message, a background-task wake, mid-turn auto-compaction (measured to emit no newinit), a lost result, a turn the provider opened, a fresh echo id, and results naming several messages. The fake CLI used by the tests now starts the way a live session does: a hook frame first, and noinituntil the first message. A real-CLI fold test runs when a signed-in CLI is present and is skipped in CI. Removing the fold rule fails the capture replays and the fold tests. Removing the reset on a new cycle fails the lost-result test. Claude and orchestration suites, typecheck, oxlint, the changed-code quality gate and the anti-slop audit pass.AI Disclosure
Review
Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
Host-only change in the Claude structured-session adapter. No wire, storage or client change, so desktop, mobile, paired clients and SSH hosts all read the corrected journal with no update. Stop/cancel behaviour and turn-timing rules are unchanged.
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)