Repository navigation
fix(claude): single-own turn identity so Stop reaches a provider-opened turn - #20794
Conversation
…ed turn Stop silently failed on any Claude turn the provider opened on its own — a background task reporting in wakes the agent — once the session had dispatched at least once. The transcript read "The provider had already finished this turn." while the model kept working. Turn identity was minted twice from the same stream by two components that never talked. The journal translator writes turnId into the durable turn row, which is the id every client's Stop carries. settleWaiter separately wrote session.activeTurnId, only ever on the dispatch-echo path, and nothing cleared it. Cancel read the adapter's copy; prompt binding, status and both clients read the journal's. They agreed only when a send echo opened the turn. Turn identity is now single-owned. The open turn moves out of the translator's closure into ClaudeOpenTurn, which holds the turn and publishes its lifecycle row, so the id readers ask for is the id the row carries. activeTurnId and activeTurnSequence are deleted rather than widened, so the second writer goes with them instead of a second guard being added beside the first. activeTurnSequence was never turn identity: it asked whether a send was still awaiting its echo, which an interrupt would release as an unexpected turn. That is now derived from the live dispatch waiters. Deriving it also retires a latch — a retired waiter left the stored sequence permanently behind the dispatch sequence, refusing every later Stop for the life of the session. Also fixes the mirror defect the same hazard caused: a stale turn id was accepted against a newer provider-opened turn, because activeTurnId was never cleared when a turn ended. The Claude adapter fixture now acquires with a journal sink, as production does; without one it modelled a session that never ships.
|
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:
📝 WalkthroughWalkthroughThe change introduces Priority: ➖ Normal Merge Risk: 🟡 Moderate · up to Under timestamp regressions, Stop may admit or reject cancellation incorrectly, and ended sessions can retain streamed state for their lifetime. These issues should be fixed before merge. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description gives detailed coverage of the failure, design, behavior, testing, visual validation, compatibility, and known CI issue. However, it omits the required Linked Issue section and several required template sections, including ELI5, Review, Agent skill upstream boundary, Notes, and Checklist. Resolution Add the required template sections and complete them. Include a valid issue reference under
✨ 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.
Important
The provider-opened-turn fix is sound and well tested, but the rewritten guard has a hole: ownsRequestedTurn treats "the translator has no open turn" the same as "the session has no journal". While a compaction runs the translator deliberately observes no turn, so a stale or foreign Stop is accepted and interrupts it. Reproduced at head — details inline.
Reviewed changes
- Open turn extracted into
ClaudeOpenTurn(claude-open-turn.ts): sole owner of the open turn and its lifecycle row;open/ensureOpen/settle/allowReopen/suppressReopenreplace the translator's closure state. - Translator delegates (
claude-structured-journal-translation.ts): all turn lifecycle calls route to the owner andcurrentTurnIdexposes the id the published row carries. activeTurnId/activeTurnSequencedeleted (claude-structured-session-state.ts): prompt binding, the permission callbacks and the cancel guard now readsession.translator?.currentTurnId.claudeHasUnsettledDispatch(claude-structured-dispatch.ts) derives the queued-send gate from live waiters, retiring the dispatch-sequence latch that refused Stop for the life of a session after one doubtful dispatch.- Cancel guard rewritten (
claude-structured-prompt-ownership.ts) aroundownsRequestedTurn(). - Tests: new
claude-turn-ownership.test.tsdrives the real adapter and reads the turn id out of the published journal row; fixtureacquired()now acquires with a journal sink.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
🟠 Major · Bind queued prompt cancellation to the pending dispatch. · src/main/claude/claude-structured-prompt-ownership.ts:77-98
77-98: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy liftBind queued prompt cancellation to the pending dispatch. If
canUseToolruns before the newly dispatched message opens a translator turn, it recordsturnId: null, andbindPromptItemIdpreserves that binding.cancelClaudeStructuredTurnthen callsclaimBound, which requires the binding turn ID to equal the request turn ID and returns{ cancelled: false }beforeownsRequestedTurnor queued-interrupt support runs. The prompt remains pending. Bind the prompt to the pending dispatch identity before applying the stale-turn fallback.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 5305a5da-204a-49d6-9832-6e1cf2e8d689
📒 Files selected for processing (2)
src/main/claude/claude-structured-prompt-ownership.tssrc/main/claude/claude-turn-ownership.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
Electron UI validation (Claude Stop / turn identity)Validation-only. No production code was changed. Screenshots are attached here and were not committed. Launched a background Scenario exercised
Visible evidenceBefore (idle structured composer, Send not Stop): After first dispatch (precondition: prior turn finished, Send restored): During second turn (Stop square visible, “Working for 0s”): After Stop (status is “Cancellation requested.”, not the stale-finish note; no 1–80 count): Backing state
Gap (not fabricated as success)A provider-opened turn after a prior dispatch — the failure the PR fixes — was not reproduced. That turn is opened when the provider emits an assistant frame on its own (a background task reporting in), not from Orca’s send echo. Forcing a background-task wake is outside a safe, bounded UI flow here, and this run stayed on echo-opened Stop after one completed dispatch (the regression arm that already passed when production levers were ablated). So this UI run proves: structured Claude Chat Stop is reachable, it carries the journal turn, and an echo-opened turn after a prior dispatch cancels with “Cancellation requested.” It does not prove the provider-opened cancel path in the live app; that remains unit-test / ablation coverage in |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed the delta since the prior pullfrog review (62d9bb5): the cancel guard's null-turn wildcard plus one new regression test.
- Null-turn wildcard gated on the dispatch sequence (
claude-structured-prompt-ownership.ts):ownsRequestedTurnnow treats a nullcurrentTurnIdas "no id this request can contradict" only whendispatchSequence === 0, so a foreign Stop is refused while a compaction runs or before a new provider turn's first frame.compactions.ownsTurnstill admits the/compactcommand id. - Regression test for a settled turn (
claude-turn-ownership.test.ts): a Stop naming an echo turn that already settled is refused with nointerrupt, pinning the stale-id-accepted half of the mirrored defect.
The prior review's guard-hole finding is resolved: reverting ownsRequestedTurn to the 62d9bb5 form reproduces {cancelled:true} for a foreign id during a compaction, while the head returns {cancelled:false}.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
Electron UI validation: provider-opened Claude StopFollow-up to the earlier echo-opened evidence. This path was reached in a background Scenario
Visible evidencePrecondition — first dispatch complete: Echo turn settled, background bash still running, Send not Stop: Provider-opened turn (no new user bubble; Stop visible; bash completed): After Stop — “Cancellation requested.” not the stale-finish note; sleep 25 never wrote FIRSTDONE: Backing state
A 10s sleep earlier in the same session was absorbed into the still-open echo turn (FIRSTDONE arrived before the echo turn ended). The 25s sleep left a real gap: echo settled with a live background command, then the provider woke a new turn when that command completed. |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed the delta since the prior pullfrog review (4f61be5): restoring the dispatch-admission fence in the cancel guard, plus the unit and integration tests that pin it.
- Restored the dispatch-admission fence (
claude-structured-prompt-ownership.ts):dispatchAdmissionIsCurrent()now gates Stop onlastAdmittedDispatchSequence === dispatchSequence, replacing the live-waiterclaudeHasUnsettledDispatchderivation so a Stop is refused after a send whose outcome is unknown until a later send is admitted. - Removed
claudeHasUnsettledDispatch(claude-structured-dispatch.ts) and advanced the newClaudeSession.lastAdmittedDispatchSequenceon each replay-admission path (settleWaiter,recoverLateIdentity, the dispatch error-after-replay branch). - Added a regression test (
claude-turn-ownership.test.ts):keeps the prior dispatch fence after an unknown later send. I confirmed it fails ({cancelled:true}) when the guard is reverted to the4f61be5form, so it is load-bearing rather than theatre. - Extended the runtime integration test (
claude-structured-session-integration.test.ts): opens a provider-owned turn after the dispatch settles and Stops it end to end, retargeting the resume-leaf assertions to that frame. Without this commit the test fails against the new guard; at head all 54 relevant tests pass.
ℹ️ PR description's latch-retirement claim no longer matches the guard
The description's "activeTurnSequence was never turn identity" section says the queued-send question "is now derived from the live dispatch waiters (claudeHasUnsettledDispatch) instead of stored" and that this "retires a latch." The final guard does the opposite: it stores lastAdmittedDispatchSequence and refuses Stop after a doubtful dispatch, and the new test asserts exactly that refusal. This matches pre-PR main, so nothing ships differently than before the PR, but the description (and the 62d9bb5 commit narrative) should be updated before merge so the record reflects the intentionally restored fence.
Technical details
# Stale latch narrative in the PR description
## Affected sites
- PR body, "### `activeTurnSequence` was never turn identity" — claims the admission gate is derived from live waiters and that the doubtful-dispatch latch is retired.
- `src/main/claude/claude-structured-prompt-ownership.ts:86-89` — the gate is `dispatchSequence === 0 || lastAdmittedDispatchSequence === dispatchSequence || supportsClaudeQueuedInterruptCancellation(session)`; `lastAdmittedDispatchSequence` only advances on replay admission, so a doubtful dispatch leaves it behind until a later send is admitted.
- `src/main/claude/claude-turn-ownership.test.ts:132-164` — pins the refusal after an unknown later send.
## Required outcome
- Documentation-only: update the PR description (and the `62d9bb5` commit message) to describe the restored fence and its consequence on CLIs without `interrupt_cancel_queued_v1`, where a Stop is refused until a later dispatch is admitted.
## Open questions for the human
- Is refusing Stop after a doubtful dispatch the intended long-term behavior, or should the guard re-sync once the doubtful waiter is provably retired (child exit / provably-unwritten)? The new test locks the stricter behavior.DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Important
The new dispatchStatus plumbing leaves one existing performCancel test failing.
Reviewed changes
Reviewed the two commits since the prior pullfrog review (f761bf5c): the dispatch cancellation fence moved off the in-memory lastAdmittedDispatchSequence and onto the durable journal.
- Journal-derived admission — new
journal-dispatch-observation.tsreturns the newest submission for the execution fence as{state, recovered}, and both host cancel paths feed it to the adapter (performCancel,acquireNativeStop). - Guard consults the journal —
dispatchAdmissionIsCurrent()treatsaccepted/rejected/recovered-unknownas settled andpending/live-unknownas still outstanding; the queued-interrupt bypass is now gated onBoolean(prompt), restoring main's plain-Stop behavior for CLIs advertisinginterrupt_cancel_queued_v1. lastAdmittedDispatchSequencedeleted — the stored latch and its three writers (settleWaiter,recoverLateIdentity, the dispatch error-after-replay branch) are gone; direct adapter callers fall back to live plus retired waiters.- Tests — two guard tests pinning the journal-driven refusal and the plain-Stop gate, plus the helper's unit test.
Rechecked against main: head is at least as permissive on the prompt branch (provider-opened turns now reachable) and matches main's refusal on the plain-Stop branch. No behavioral regression found in the fence rewrite itself.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed the delta since the prior pullfrog review (892335d3f1): the host cancel paths no longer send dispatchStatus: null when the journal holds no submission for the fence.
- Omit absent dispatch observation (
structured-agent-session-turns.ts:205,219,structured-agent-session-host-handoff.ts:107,113):performCancelandacquireNativeStopcomputelatestJournalDispatchObservation(...)once and spread it as...(dispatchStatus ? { dispatchStatus } : {}), mirroring the adjacent conditionalpromptspread. - The guard already reads
request.dispatchStatuswith a truthy test, so an absent key andnullare behaviorally identical — the change is confined to the call shape. - This clears the prior review's failing-assertion finding at
structured-agent-session-prompt-cancel.test.ts:133. Verified locally:agent-session-wire569/569,claude-turn-ownership7/7,pnpm tc:nodeexit 0.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
🟠 Major · Select the latest matching submission by journal sequence. · src/main/native-chat/agent-session-journal/journal-dispatch-observation.ts:20-26
20-26: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winSelect the latest matching submission by journal sequence.
JournalRowBasedefinesseq, notts, as the ordering field, butapplySubmissiondiscardsseqandlatestJournalDispatchObservationselects bysubmittedAt. With a timestamp regression, native Stop can admit a stale accepted or rejected state, or reject a valid cancellation because it selected an older unresolved state. Preserveseqin the projection or expose submissions in sequence order, then select the greatest sequence. Equal timestamps currently follow replay insertion order; the failure is the timestamp regression.
🟡 Minor · Clear streamed checkpoint state when the provider ends. · src/main/claude/claude-structured-journal-translation.ts:225-234
225-234: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winClear streamed checkpoint state when the provider ends. The
endedevent is reachable on child exit.streamedText.flush()persists pending text but does not remove checkpoint state.streamedText.settle()andstreamedBlocks.clear()are required to remove pending identities and block state. Without them,pendingStreamedBlocksremains nonzero and retained text state can grow for the translator's lifetime.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: b64cbe1d-604a-4652-a887-03e10c6b57e2
📒 Files selected for processing (2)
src/main/native-chat/agent-session-wire/structured-agent-session-host-handoff.tssrc/main/native-chat/agent-session-wire/structured-agent-session-turns.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.
Review status: clean at
|
There was a problem hiding this comment.
ℹ️ No critical issues — the deadline closes the "unresolved fence never releases" gap; minor suggestions inline.
Reviewed changes
Reviewed the single commit since the prior pullfrog review (a2215d1): a bounded escape for the durable dispatch fence.
- Added a bounded Stop fence (
claude-structured-prompt-ownership.ts): a newCLAUDE_DISPATCH_ADMISSION_TIMEOUT_MS(3s) wait setsdispatchAdmissionExpired, so an ordinary Stop interrupts after an unresolved delivery fence instead of waiting for a later admitted dispatch. - Converted the guard tests to fake timers (
claude-turn-ownership.test.ts): three tests now advance the deadline and assert the interrupt is withheld until expiry then issued; the former refusal test now expects{ cancelled: true }. - Widened the journal observation helper's type (
journal-dispatch-observation.ts): the helper takesAgentJournalSubmissioninstead of an ad-hoc shape, and its unit test builds full submissions.
ℹ️ PR description still describes the fence as never releasing
The description's "Dispatch admission is derived from the journal" section says a current-fence pending or unrecovered-unknown submission leaves ordinary Stop fenced "until provider evidence resolves it or a later current-fence submission is safely admitted." This commit adds a 3s deadline that admits Stop after expiry regardless of the journal's durable state, and flips the previously-refusal test to cancelled: true. Please update the description to describe the bounded escape and its delivery-safety tradeoff before merge.
Technical details
# Stale fence narrative after the deadline
## Affected sites
- PR body, "### Dispatch admission is derived from the journal" — claims ordinary Stop stays fenced until durable resolution; no longer true.
- `src/main/claude/claude-structured-prompt-ownership.ts:115-119` — `dispatchAdmissionExpired` is set unconditionally once the 3s timer fires; the journal is not re-read at expiry.
- `src/main/claude/claude-turn-ownership.test.ts:133-176` — the "keeps the prior dispatch fence after an unknown later send" test now asserts `{ cancelled: true }` after the deadline rather than the refusal.
## Required outcome
- The PR body describes the 3s bounded release and confirms it is the intended long-term behavior (vs. waiting for durable settlement).
## Open questions for the human
- Is a fixed 3s deadline the intended bound, or should the escape be tied to an observable settlement signal? Under load the input pump may not have settled in 3s, at which point the interrupt can still release an uncertain queued send.ℹ️ Nitpicks
src/main/claude/claude-structured-prompt-ownership.ts:127—|| dispatchAdmissionExpiredin the prompt branch is always false: the flag is set only when!prompt.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| } | ||
| }) | ||
|
|
||
| it('lets a queued-cancel provider release an unresolved ordinary Stop', async () => { |
There was a problem hiding this comment.
This name says the interrupt_cancel_queued_v1 capability releases an unresolved ordinary Stop, but dispatchAdmissionAllowsCancellation only consults supportsClaudeQueuedInterruptCancellation under Boolean(prompt) — with no prompt the capability has no effect, and the pass actually comes from the 3s deadline. It also omits vi.useFakeTimers, so it sleeps ~3 real seconds and duplicates the next test. Either drop the unused capability and rename, or drive it through a prompt cancel if the capability path is what it should pin.
There was a problem hiding this comment.
ℹ️ No critical issues — the polled bounded wait is sound, but the poll cannot observe host-side settlement; details inline.
Reviewed changes
Reviewed the single commit since the prior pullfrog review (611bd80): the dispatch-admission wait is now polled and gated.
- Polled bounded wait (
claude-structured-prompt-ownership.ts):waitForClaudeDispatchAdmissionnow takes anadmittedpredicate, polls it every 50ms, and resolvestrueearly orfalseat the 3s deadline;dispatchAdmissionExpiredderives from that result instead of a fixed-sleep that always expired. - Gated the bounded escape (
claude-structured-prompt-ownership.ts): the wait now runs only whenrequest.dispatchStatus !== undefinedor a retired waiter exists for the current dispatch sequence, so a direct caller with only a live in-memory waiter no longer gets the release.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| !dispatchAdmissionAllowsCancellation() && | ||
| (request.dispatchStatus !== undefined || currentDispatchHasRetiredWaiter()) | ||
| ) { | ||
| dispatchAdmissionExpired = !(await waitForClaudeDispatchAdmission( |
There was a problem hiding this comment.
The poll re-reads dispatchAdmissionAllowsCancellation, but for a host cancel request.dispatchStatus is a one-shot value captured before the call, so the predicate is constant during the wait and the early release can never fire for the durable pending/unrecovered-unknown case — every such ordinary Stop still waits the full 3s even if the journal settles at 50ms. The poll only ever helps the in-memory waiter fallback. If early release was intended for host cancels, the host has to hand the adapter a live reader rather than a value.
Technical details
# Poll cannot observe host-side settlement
## Affected sites
- `src/main/claude/claude-structured-prompt-ownership.ts:152-154` — `waitForClaudeDispatchAdmission(dispatchAdmissionAllowsCancellation)`; for a host request the predicate reads the immutable `request.dispatchStatus`.
- `src/main/native-chat/agent-session-wire/structured-agent-session-turns.ts:205,219` and `structured-agent-session-host-handoff.ts:107,113` — derive `latestJournalDispatchObservation(...)` once and pass the value.
- `src/main/native-chat/agent-session-journal/journal-dispatch-observation.ts:28` — returns a fresh `{ state, recovered }` object, not a live view.
## Required outcome
- Either the wait observes durable state changes (the host re-derives admission during the wait), or the poll is documented as fallback-only with the full deadline always applying to host cancels.
## Open questions for the human
- Should an ordinary Stop release as soon as the journal settles, or is a flat 3s ceiling acceptable for the durable `pending`/unrecovered-`unknown` case?| !prompt && | ||
| !compactionOwnsTurn() && | ||
| !dispatchAdmissionAllowsCancellation() && | ||
| (request.dispatchStatus !== undefined || currentDispatchHasRetiredWaiter()) |
There was a problem hiding this comment.
request.dispatchStatus !== undefined disagrees with the guard's truthy check: the type allows null (structured-agent-session-adapter.ts:207), which dispatchAdmissionIsCurrent treats as absent but this gate treats as present. The gate also omits live dispatchWaiters, so a direct caller with a live waiter and no observation skips both the wait and the expiry and refuses indefinitely — where 611bd80 released it after the deadline. Consider one shared predicate (request.dispatchStatus != null || …) and decide whether the live-waiter case should escape.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed the delta since the prior pullfrog review (114df332af): a test-only commit that closes the previously-noted gap where no test exercised the bounded dispatch-admission wait's early-release path.
- Early-release regression test (
claude-turn-ownership.test.ts): drivescancelClaudeStructuredTurnwith a retired waiter at the currentdispatchSequence, clears it mid-wait, and asserts the interrupt fires before the 3s deadline under fake timers — pinning the polled release for the in-memory fallback. - Fast-path test (
claude-turn-ownership.test.ts): with fake timers that are never advanced, asserts an already-current admission cancels without waiting, so a regression that re-introduces an unnecessary wait hangs rather than silently passing. - Documented the bounded window (
claude-structured-prompt-ownership.ts): theCLAUDE_DISPATCH_ADMISSION_TIMEOUT_MSJSDoc now states the conservative tradeoff.
Verified locally: claude-turn-ownership.test.ts 10/10 pass. The two new tests are load-bearing — the early-release test fails if the poll is removed, and the fast-path test blocks on the un-advanced timer if a wait is added.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
Review status — ready for mergeFinal head:
|
…ed turn (stablyai#20794) * fix(claude): single-own turn identity so Stop reaches a provider-opened turn Stop silently failed on any Claude turn the provider opened on its own — a background task reporting in wakes the agent — once the session had dispatched at least once. The transcript read "The provider had already finished this turn." while the model kept working. Turn identity was minted twice from the same stream by two components that never talked. The journal translator writes turnId into the durable turn row, which is the id every client's Stop carries. settleWaiter separately wrote session.activeTurnId, only ever on the dispatch-echo path, and nothing cleared it. Cancel read the adapter's copy; prompt binding, status and both clients read the journal's. They agreed only when a send echo opened the turn. Turn identity is now single-owned. The open turn moves out of the translator's closure into ClaudeOpenTurn, which holds the turn and publishes its lifecycle row, so the id readers ask for is the id the row carries. activeTurnId and activeTurnSequence are deleted rather than widened, so the second writer goes with them instead of a second guard being added beside the first. activeTurnSequence was never turn identity: it asked whether a send was still awaiting its echo, which an interrupt would release as an unexpected turn. That is now derived from the live dispatch waiters. Deriving it also retires a latch — a retired waiter left the stored sequence permanently behind the dispatch sequence, refusing every later Stop for the life of the session. Also fixes the mirror defect the same hazard caused: a stale turn id was accepted against a newer provider-opened turn, because activeTurnId was never cleared when a turn ended. The Claude adapter fixture now acquires with a journal sink, as production does; without one it modelled a session that never ships. * fix(claude): reject stale stop after turn settles * fix(claude): preserve dispatch cancellation fence * test(claude): cover provider-opened stop integration * fix(claude): derive dispatch cancellation fence from journal * fix(claude): honor journal dispatch status before local sends * fix(native-chat): omit absent dispatch observation * fix(claude): release unresolved stop fence after deadline * fix(claude): bound and poll dispatch admission wait * test(claude): cover dispatch admission fast path









What broke
Stop silently failed on any Claude turn the provider opened on its own, once the session had dispatched at least once. The user saw "The provider had already finished this turn." in the transcript while the model kept working.
The provider opens turns without Orca sending anything — a background task reporting in wakes the agent, and the turn Orca journals is opened from an assistant frame rather than from a send echo.
cancelClaudeTurnreturned{ cancelled: false }for those turns.The failure mechanism: turn identity had two writers
Turn identity was minted twice from the same frame stream, by two components that never talked.
turnIdinto the durable turn row. That row's id is what every client's Stop carries, and what status, prompt binding and rewind read.settleWaiterseparately wrotesession.activeTurnId, and only ever on the dispatch-echo path. Nothing on the provider-output path wrote it, and nothing ever cleared it.The cancel guard read the adapter's copy (
activeTurnId), while everyone else read the journal's. The two agreed only when a send echo had opened the turn — by accident, because both happened to name the same frame's uuid.The same stale copy caused the mirror defect: because
activeTurnIdwas never cleared when a turn ended, a Stop carrying the old, finished turn's id could interrupt a newer provider-opened turn.Why single ownership rather than a wider guard
Widening the cancel guard to accept provider-output ids would have left two writers racing over one fact. Turn identity is now single-owned by
ClaudeOpenTurn(src/main/claude/claude-open-turn.ts), which holds the turn and publishes its lifecycle row. The id readers ask for is therefore, by construction, the id the row carries.activeTurnIdandactiveTurnSequenceare deleted, so the second writer goes away rather than a second guard being added beside the first.Prompt binding (
bindPromptItemId) and permission callbacks'currentTurnIdnow ask the same owner. Compaction keeps its own turn ownership (compactions.ownsTurn), which cancel already consulted and which is unchanged.Dispatch admission is derived from the journal
activeTurnSequencewas never turn identity. It asked whether a send was still awaiting its echo, because interrupting then could release a queued message as an unexpected turn. There is nolastAdmittedDispatchSequencelatch at this head and nothing needs to re-sync it.For host-owned cancellation, the host reads
latestJournalDispatchObservation(session.journal, fence)on every request. It derives the latest write-ahead submission for the current execution fence from durable journal state (request.dispatchStatus):acceptedandrejectedadmit ordinary Stop;unknownadmits only whenrecovered: true;pendingand unrecoveredunknownremain fenced.Journal state changes through the normal submission, settlement and recovery writes, so the next cancellation observes current durable truth. This is why the design does not store a second session-local sequence that can strand.
Direct adapter callers that do not supply
dispatchStatususe an in-memory fallback over bothdispatchWaitersandretiredDispatchWaitersfor the current dispatch sequence. Retired waiters are included deliberately: retirement means delivery became unknown, not settled, so it must continue to fence Stop until durable evidence resolves it.An unresolved current-fence submission fences ordinary Stop, but the fence is bounded: it polls admission every 50ms and releases Stop when the 3,000ms deadline expires, so a user-initiated abort is never blocked indefinitely by delivery bookkeeping. If the durable host observation is still unresolved at expiry, Stop proceeds to the provider interrupt; the timer writes no delivery verdict and is unref'd, so journal recovery can still reconcile an unknown send.
The 3,000ms value is a conservative user-facing default, not a measurement derived from replay-echo lag. It is deliberately below Claude's 10,000ms structured-session initialization deadline and 30,000ms provider-control deadline: that trades the residual risk of an exceptionally slow input pump settling after the window for ensuring Stop never requires a second user action. A direct caller with an active waiter and no durable observation remains fenced; only a retired, delivery-unknown fallback waiter gets the same expiry path. This keeps the fallback from allowing a later unresolved send to release an earlier acknowledged turn.
Behavior change: queued interrupt cancellation remains prompt-gated
Before the journal-derived fix,
supportsClaudeQueuedInterruptCancellation(session)was an unconditional cancellation disjunct. It is still used only asBoolean(prompt) && supportsClaudeQueuedInterruptCancellation(session).That narrowing remains intentional after the bounded ordinary-Stop wait. Prompt cancellation has a separate callback-settlement contract: without the provider's queued-cancel capability, interrupting after a timeout could release a queued prompt while its callback observation is still unresolved. Ordinary Stop has no prompt callback to settle and therefore gets the bounded escape above. The provider capability remains a prompt-scoped escape hatch, while ordinary Stop relies on the delivery window and its expiry. Bookkeeping still does not permanently gate a user action.
Why the journal, not another session latch
Deriving doubt from the journal submission (
dispatchStateplusrecovered) was considered and implemented. It is durable, survives session restart, and is recoverable from state Orca already holds, so it avoids a second copy that can disagree. The waiter fallback is limited to direct adapter/control callers that have no journal observation; it includes retired waiters for the unknown-delivery reason above.Tests and ablation
src/main/claude/claude-turn-ownership.test.tsdrives the real adapter with a journal sink and cancels using the turn id from the published journal row, not a fabricated id. It includes the bounded admission regression: no interrupt at timeout-1, then{ cancelled: true }and an interrupt at expiry. It also covers early polling resolution when a retired waiter settles before the deadline, plus the already-current admission path with no timer advance. The same suite covers the stale-earlier-turn guard, compaction bypass, provider-opened turns, and the retired-waiter fallback.src/main/native-chat/agent-session-journal/journal-dispatch-observation.test.tscovers latest-fence selection and recovery state.At final head
674a30d2bced48b5091c5ecf43ac541f06141b6f, the provider-opened integration test was ablated by reverting every PR production lever to the PR base while keeping the final test. The explicit revert was verified before the run, and the primary worktree was restored and verified clean afterward:provider-opened-assistant) cancelscancelled: falseThe regression is therefore tied to the production ownership change, not a permissive test guard.
Electron UI validation
Validation-only; no production code was changed for the screenshots. A background
ORCA_BACKGROUND_LAUNCH=1Electron instance was launched from this worktree and verified bywindow.api.app.getIdentity().The bounded flow used a structured Claude Chat session with one completed dispatch, then sent
Run this exact bash command and nothing else: sleep 25 && echo FIRSTDONE. Claude moved it to a background task and ended the echo turn. When the task completed, an assistant frame opened a new turn without a new user message. Stop was clicked on that provider-opened turn and the transcript showedCancellation requested.rather thanThe provider had already finished this turn.; the command never wroteFIRSTDONE.Screenshots (not committed):
Remote wire compatibility
Nothing published changes. No RPC param, stream opcode or journal field is added, removed or re-typed, and the
turnitem's content is byte-identical. Only which host-side reader is consulted for that id moves. The client-visible difference is the intended one:agentSession.cancelTurnnow returns{ cancelled: true }for a genuinely running provider-opened turn.SSH and remote hosts are unaffected because the execution host owns the turn and the adapter, and this change stays entirely inside it. Nothing here assumes a git worktree, so folder workspaces are unaffected.
Gates
pnpm tc— exit 0pnpm run check:code-quality:changed— 0 new findings across 17 changed filescancelled: falsewhen production levers are reverted; passes at headmax-linesdisable was added; the translator's open-turn state machine remains in its own module.The broader Claude suite's only known failure remains the pre-existing real Claude CLI handshake test; the lease-renewer is known to flake only under full-suite load and passes in isolation.
CI note
The red
static analysischeck is unrelated to this PR. It fails atsrc/shared/agent-status-legacy-adapter.ts:95onReflect.get. Main commit9ab0a18e82(#20716) introduced that line afteranti-slop/no-reflect-getwas enabled byf107499e44; static analysis runs on PR merge refs, not on main, so the current main head exposes the failure on this PR's merge ref. This PR does not touch that file, and it is intentionally not changed or suppressed here. The fix belongs in a separate owner-directed change.Out of scope
Folding steered turns,
durationMsprecedence, queued-message affordances, and stranded-turn settlement are separate planned PRs and are not included here.