Repository navigation
fix(claude): judge Stop against the turn the journal published - #20921
Conversation
A Stop could be refused for the turn the user was actually looking at. The client derives the id it sends from the published journal rows, but the host compared it against the adapter's own in-memory turn. The journal sink drains asynchronously, so that in-memory value can already name a turn whose row has not landed — an id no client has been shown, and one the client's Stop can therefore never match. The user pressed Stop and nothing stopped. Fix the guard's source rather than the guard. ownsRequestedTurn stays: it is what stops a delayed request from interrupting a later turn, and without it a stale Stop would reach a session-scoped interrupt that settles every queued send as durably rejected. The host now resolves the live turn from the journal projection and hands it to the adapter, which prefers it and falls back to its in-memory read for direct callers that have no journal. It is passed as a read rather than a value because the guard re-checks after the delivery fence may have waited seconds; a value captured at request time would interrupt whatever turn ran next. Both callers supply it. The handoff's own Stop bypasses performCancel, so its body moves into stopNativeHandoffTurn beside the file's other extracted flows, which is also what lets it be tested on its own.
|
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 (7)
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review. 📝 WalkthroughWalkthroughThe change adds an optional Priority: ⬇️ Low Merge Risk: ⚪ Minimal · up to The cancellation change preserves live-turn ownership across journal drain timing and completed turns; no actionable merge risk remains. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ 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 critical issues — one open question on the residual Stop window.
Reviewed changes
- Stop guard now reads the published journal —
ownsRequestedTurn()inclaude-structured-prompt-ownership.tsprefers a host-suppliedresolveLiveTurnId?: () => string | nulloversession.translator?.currentTurnId, falling back only for direct adapter callers with no journal. Passed as a function (re-read atisCurrent()after the 3s delivery fence), not a captured value. - Both production callers wired —
performCancelsupplies() => activeStructuredAgentSessionTurnId(ctx.journal.snapshot().items); the handoff'sacquireNativeStopbody is extracted into the exportedstopNativeHandoffTurn, which supplies the same read. These are the only twoadapter.cancelTurncall sites insrc/main. - Codex untouched —
cancelCodexStructuredTurnnever reads the new field, so the optional input cannot change its behavior. - Tests — three new adapter-level tests (admit for the published turn while the adapter holds an undrained one; refuse once the journal published a newer turn; re-read after the fence waits) plus a
stopNativeHandoffTurnwiring test and aperformCancelcall-shape assertion. I verified each new assertion fails under the ablation the PR describes, and that the changed suites (24), sensitive suites (51),pnpm tc, andcheck:code-quality:changedall pass.
ℹ️ The guard now admits a Stop in the journal-lag window, where the interrupt can reject a queued send
The fix moves the guard from the adapter's in-memory turn to the journal, which is the right source for the reported bug. It also means that while the in-memory turn has already advanced or settled but its lifecycle rows are still queued in the deferred sink, the guard admits a Stop that the pre-PR in-memory guard refused. That Stop reaches interrupt({ cancelQueued: true }), and a still-queued user send is then durably settled rejected. The window is narrow (it needs at least the 3s admission timeout of journal lag at the post-wait re-read, or a row dropped under backpressure) and the user did press Stop while their UI showed a running turn — so this may be exactly the intent. Flagging it only as an open question, since no clean fix exists without reintroducing the bug this PR fixes.
Technical details
# Journal-lag Stop can cancel a queued send
## Affected sites
- `src/main/claude/claude-structured-prompt-ownership.ts:117-122` — `ownsRequestedTurn()` now
returns true whenever `resolveLiveTurnId()` names the requested turn, even if neither the
in-memory turn nor a live provider turn is that turn.
- `src/main/native-chat/agent-session-wire/structured-agent-session-adapter.ts:210-213` — the
new input's JSDoc calls the journal value "the only turn a client could have named"; the client
can lag the host journal by one publish, so the host value can be ahead.
- `src/main/claude/claude-structured-control-actions.ts:35-42` — on the
`interrupt_cancel_queued_v1` path the admitted Stop calls
`settleCancelledClaudeDispatchWaiters`, which resolves queued waiters as `rejected`.
## Reachable interleaving
1. Turn T running and published; user sends P1, which the CLI parks behind T
(`dispatchClaudeTurn` keeps P1's submission `pending`, no dispatch row for `admitted`).
2. Root `result` for T → `turn.settle()` clears the in-memory turn and queues T's completion row
(`claude-open-turn.ts:78-84, 101-106`).
3. P1's echo → `turn.open(T+1)` queues T+1's running row behind it
(`claude-structured-journal-translation.ts:213-216`). The host journal snapshot still reports
**T running** until the sink drains.
4. User sends P2 (parks behind T+1) and presses Stop; the client's projection also reads the
lagging journal, so its `turnId` is T and its Stop control is enabled.
5. `performCancel` reads `dispatchStatus = pending` for P2 and passes `turnId: 'T'` +
`resolveLiveTurnId()` (`structured-agent-session-turns.ts:206, 216-225`).
6. `dispatchAdmissionIsCurrent()` is false → the 3s `waitForClaudeDispatchAdmission` runs; P2
stays queued, the wait times out, `dispatchAdmissionExpired = true`
(`claude-structured-prompt-ownership.ts:144-154`).
7. `isCurrent()` re-reads the still-lagging journal → T → admits; `cancelClaudeTurn` interrupts
with `cancelQueued: true`, and P2 is durably `rejected`.
## Required outcome
Decide whether "the turn the client was shown is running" is sufficient authority to issue the
session-scoped interrupt, or whether an in-memory turn that has settled/advanced should still
veto (which is the pre-PR behavior for exactly this window).
## Open questions for the human
- Is a Stop that reaches the interrupt only because the journal is ≥3s behind (or because a
completion row was dropped under sink backpressure) acceptable, given it can reject a queued
send the user typed?
- If the settled case matters more than the new-turn case, a partial guard
(`translator.currentTurnId === null && dispatchSequence !== 0` → refuse) closes only the
between-`settle`-and-echo sub-window and leaves the T+1 sub-window open.DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
The journal drains through a serialized async queue, so a live turn routinely has no published row yet. Judging a Stop only against the journal refused in that window, which gates a user action on bookkeeping. The journal stays authoritative while it HAS an answer; a null read falls through to the in-memory turn, and the nothing-dispatched clause is unchanged. Both call sites now read the live turn through `journal.activeTurnId()`, which folds reduced items instead of rendering and sorting a whole snapshot.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Added an in-memory fallback for a null journal read —
ownsRequestedTurn()moved fromresolveLiveTurnId ? resolveLiveTurnId() : translator.currentTurnIdtoresolveLiveTurnId?.() ?? session.translator?.currentTurnId ?? null, so a Stop is no longer gated on the journal having drained a running row. Direct callers with no journal keep the previous in-memory read. - Promoted the journal live-turn read to
AgentSessionJournal.activeTurnId()— bothperformCancelandstopNativeHandoffTurncall it instead of materialisingsnapshot().items. The newactiveStructuredAgentSessionTurnIdBySequencepicks the max-sequence turn, the same verdict the render-sorted snapshot and the client's sequence-sorted projection give. - Added tests — an
activeTurnId()/rendered-snapshot equivalence test, a drain-lag admit test, and astopNativeHandoffTurnre-read test. I confirmed the drain-lag test fails under the prior commit's implementation ({cancelled:false}), and the five changed suites (45 tests) pass at head.
One note outside the diff: the PR description still names 53130f14c7 as the final head and its ablation table predates this commit, so it does not cover the new fallback test — worth a refresh so the recorded evidence matches the branch.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
Electron visual proof (PR #20921)Launched this worktree's Orca under Rendered native Claude session UI (isolated disposable project; experimental native chat on): Idle / Send Working / Stop — composer Launch identity (empty profile home) Gap: the journal-drain Stop ownership race is host-side and was not exercised live. A real in-flight Claude provider turn during journal drain is not a safe disposable UI state. Closest proof is the native Claude composer Stop vs Send (seeded working/idle status; no real Claude prompt dispatched). Console: 0 renderer errors. Warnings: tooltip controlled/uncontrolled, React Grab outdated, xterm.js task-queue deadline, and a main-process |
|
Review complete: land.
No review commit was necessary, and the PR branch remains clean at |
…yai#20921) * fix(claude): judge Stop against the turn the journal published A Stop could be refused for the turn the user was actually looking at. The client derives the id it sends from the published journal rows, but the host compared it against the adapter's own in-memory turn. The journal sink drains asynchronously, so that in-memory value can already name a turn whose row has not landed — an id no client has been shown, and one the client's Stop can therefore never match. The user pressed Stop and nothing stopped. Fix the guard's source rather than the guard. ownsRequestedTurn stays: it is what stops a delayed request from interrupting a later turn, and without it a stale Stop would reach a session-scoped interrupt that settles every queued send as durably rejected. The host now resolves the live turn from the journal projection and hands it to the adapter, which prefers it and falls back to its in-memory read for direct callers that have no journal. It is passed as a read rather than a value because the guard re-checks after the delivery fence may have waited seconds; a value captured at request time would interrupt whatever turn ran next. Both callers supply it. The handoff's own Stop bypasses performCancel, so its body moves into stopNativeHandoffTurn beside the file's other extracted flows, which is also what lets it be tested on its own. * fix(claude): fall back to the in-memory turn while the journal drains The journal drains through a serialized async queue, so a live turn routinely has no published row yet. Judging a Stop only against the journal refused in that window, which gates a user action on bookkeeping. The journal stays authoritative while it HAS an answer; a null read falls through to the in-memory turn, and the nothing-dispatched clause is unchanged. Both call sites now read the live turn through `journal.activeTurnId()`, which folds reduced items instead of rendering and sorting a whole snapshot.




The failure
A Stop could be refused for the turn the user was actually looking at, and the transcript would say the turn had already finished while the model kept working.
The two sides named different things:
activeStructuredAgentSessionTurnId(journalItems)inuse-structured-agent-session-transport-state.ts:21feedscontroller.turnId, which is whatcancel()carries. Mobile does the same inmobile-structured-agent-session-cancel.ts:38.session.translator?.currentTurnId— the adapter's in-memory turn.Those are two different notions of "the live turn".
ClaudeOpenTurnmoves its id synchronously, but the row that publishes it goes throughcreateDeferredStructuredAgentSessionEventSink, which queues the append and drains it later. So the in-memory value can already name a turn whose row has not landed — an id no client has been shown, and therefore one no client's Stop can match. The client Stops the turn it was shown; the host compares it to a newer id and refuses.This is the residual disagreement left after #20794 (
a9232e8db6) removed the older two-writer hazard. #20794 made turn identity single-owned; the remaining defect is that the guard reads that owner through the in-memory copy rather than through the rows the copy publishes.Why fix the source and not remove the guard
ownsRequestedTurn()is load-bearing and stays:cancelClaudeTurnre-checks it immediately before issuing the interrupt, precisely so a delayed request cannot stop a later turn (its own comment says so).interrupt({ cancelQueued: true })settles every queued send as durablyrejected— user data loss.So the guard keeps its job and changes what it reads. The host resolves the live turn from the journal projection and hands it to the adapter; the adapter prefers the supplied read and falls back to its in-memory value for direct callers that have no journal. This reuses the existing
activeStructuredAgentSessionTurnIdhelper and mirrors thedispatchStatusprecedent already inperformCancel— a journal-derived fact computed host-side and passed down.Why a read, not a value
dispatchStatusis passed as a value because a settled delivery does not un-settle. Turn identity does change. The guard re-checks after the bounded delivery fence may have waited up toCLAUDE_DISPATCH_ADMISSION_TIMEOUT_MS, so a value captured at request time would go stale across exactly the window the guard exists to cover — and would interrupt whatever turn ran next. It is thereforeresolveLiveTurnId?: () => string | null, re-read at check time. Callbacks across this adapter input are existing precedent (answerPrompt'scommit,rewind'sonPrepared,compact'sonLateResult). A test pins the re-read.The journal is authoritative only while it HAS an answer
Reading the journal instead of the in-memory turn widens an existing refusal window unless the null case is handled, so it is handled here.
ownsRequestedTurn()treats a null live-turn id as "nothing has published an identity this request can contradict", and on a session that has already dispatched (dispatchSequence !== 0) that resolves to a refusal. That clause predates this PR. But the two reads fail differently: the translator sets its current turn synchronously, whereas the journal is drained through a serialized async write queue (JournalWriteQueueinjournal-store.ts).ClaudeOpenTurn.publish()already names this ordering in its own comment — "Preserve first-work evidence when completion arrives before the journal drains." So judging only against the journal creates a real window in which a turn is live, its row has not drained, the read is null, and the user's Stop is refused.That would gate a user action on bookkeeping, which is the wrong trade. The fix keeps the journal authoritative wherever it has an answer and lets the in-memory read cover the drain lag:
This preserves the whole thesis of the PR — when the journal knows, it wins, so the client's id and the host's verdict project the same published event — while not refusing in the one window where the in-memory turn is more current than the journal rather than less. The genuinely-nothing-running case is untouched: when neither read names a turn, the
dispatchSequence === 0clause still decides, and a cancel on a fresh session with nothing running still resolves{ cancelled: true }.Both directions are pinned by tests that fail in opposite directions:
Reading the live turn cheaply
journal.snapshot()isrenderJournalState, which allocates and sorts every item and every submission in the session; sessions here reach thousands of rows.AgentSessionJournalalready names the cheaper idiom for this (visitItems— "Visits reduced items without allocating and sorting a full snapshot"), so this addsjournal.activeTurnId()beside it, folding the reduced items to the newest turn record without materialising a snapshot. Both call sites use it.The fold lives next to the existing reader in
structured-agent-session-live-turn.tsasactiveStructuredAgentSessionTurnIdBySequence, so the two ways of asking "what turn is live" sit in one file and cannot quietly drift. It orders onsequence— the same keyrenderJournalStatesorts on — and resolves ties to the later-reduced item exactly as that stable sort does. A test asserts the accessor and the rendered snapshot agree across turn start, revision-carried completion, and a second turn. This is once per Stop, so it is cleanliness rather than a hot-path fix.The two callers
Both paths that reach
adapter.cancelTurnsupply it:performCancel(structured-agent-session-turns.ts) — the ordinary Stop, beside the existingdispatchStatus.acquireNativeStop(structured-agent-session-host-handoff.ts) — the handoff's own Stop, which bypassesperformCancelentirely and would otherwise have silently kept the old behaviour. Its inline body moves into an exportedstopNativeHandoffTurn, matching howacquireNativeHandoffOwnerandimportTuiHistoryare already factored in that same file; that also makes it testable on its own, with no mocks and no type assertions.Codex is unaffected
Verified, not assumed.
CodexStructuredSessionAdapter.cancelTurnforwards the request tocancelCodexStructuredTurn, which reads onlysessionId,turnId,promptandfence. It resolves its target throughcompactions.providerTurnIdand targets it by id on the provider wire (turn/interruptwith{ threadId, turnId }), keying blocked completions onturnKey(threadId, turnId). It has no single live-turn owner to resolve from and never reads the new field —rg resolveLiveTurnId src/main/codex/returns nothing. An optional input it does not read cannot change its behaviour. The fullsrc/main/codexsuite is green.Ablation
Re-run at this PR's final commit head,
99b41465b5. Every arm reverts production files only and keeps every test file. Each revert was asserted to have landed before any failure was trusted: zero hits forresolveLiveTurnId/activeTurnId/stopNativeHandoffTurnin each reverted production file, non-zero in each test file.Arm 1 — all six production files reverted to the merge base (
a9232e8db6).{cancelled:false}, the defect{cancelled:true}, wrongly admitted{cancelled:true}performCancelhands the adapter a live-turn readundefinedstopNativeHandoffTurnjudges its Stop against the published turnactiveTurnId is not a functionTotals: 7 failed / 45 ablated, 45 passed / 45 restored.
The two middle-direction failures are the point: the journal is authoritative in both directions — it admits a Stop the in-memory copy would have refused, and refuses one the in-memory copy would have wrongly admitted. The
stopNativeHandoffTurnrow fails at the symbol rather than behaviourally, since the ablation removes the extracted function; it proves the caller is wired, not that the old inline body misbehaved.Arm 2 — only the null-fallback lever reverted (
claude-structured-prompt-ownership.tsalone, so the journal read stays in place).{cancelled:false}, the widened refusal1 failed / 14. Arm 2 is the arm that pins the null-fallback, and Arm 1 deliberately cannot: reverting everything also removes the journal read that opens the drain-lag window, so the guard falls back to the in-memory turn for a different reason and the test passes vacuously. Both directional tests stay green under Arm 2, which is what "the journal still wins when it has an answer" has to mean.
Arm 3 — only the accessor reverted (
journal-store.ts,structured-agent-session-live-turn.tsand the two call sites). 1 failed / 20:journal.activeTurnId is not a function. The accessor is a like-for-like read, so this pins that the callers go through it rather than a behavioural difference.Existing tests
All four flagged as sensitive stay green unchanged:
claude-turn-ownership.test.ts(including the #20794 mirror-defect guard),claude-structured-session-adapter-turns.test.ts(both the fresh-sessiondispatchSequence === 0cancel and the delayed-cancellation case), andstructured-agent-session-host.test.ts.One existing test changed:
structured-agent-session-prompt-cancel.test.tsasserts the adapter call shape with an exacttoHaveBeenCalledWith, which a new field necessarily reddens. It now namesresolveLiveTurnId: expect.any(Function)— still exact, so an unexpected extra key would still fail.Wire compatibility
None. Checked against
docs/reference/remote-wire-compatibility.md:resolveLiveTurnIdis an input to the in-processStructuredAgentSessionAdapter, which never crosses a process boundary; it is a function, which is itself proof it is not serialized. There is no remote proxy implementingcancelTurn— the only implementations are the Claude and Codex adapters plus the pass-through router.cross-version-agent-session-wire.unit.test.tsis green.SSH / remote and folder workspaces
performCancelandstopNativeHandoffTurnboth run on the execution host, which owns the journal — so the read is local to whichever host is executing, native, WSL or SSH, and no extra round trip is introduced. Nothing here touches workspace shape, so folder workspaces and git worktrees behave identically.Gates
pnpm tc— exit 0pnpm run check:code-quality:changed— passed, 0 findings (re-run after the commit hook'soxfmtpass)pnpm format— appliedpnpm test src/main/claude src/main/native-chat/agent-session-wire src/main/native-chat/agent-session-journal src/shared/structured-agent-session-projection.test.ts— 1493 passed, 5 skipped across 168 files; the single failure isclaude-structured-real-cli.test.ts, which spawns the real Claude CLI and times out on init without a signed-in account. Confirmed pre-existing: it fails identically withorigin/main's production code in the tree.