Skip to content

fix(claude): judge Stop against the turn the journal published - #20921

Merged
brennanb2025 merged 2 commits into
mainfrom
brennanb2025/claude-stop-turn-source
Sep 16, 2026
Merged

brennanb2025 merged 2 commits into
mainfrom
brennanb2025/claude-stop-turn-source

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​283 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​283
Prod 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​66 $\color{#cf222e}{\Huge{\mathbf{−}}}$​24 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​42

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:

  • The client derives the id it sends from the published journal rows — activeStructuredAgentSessionTurnId(journalItems) in use-structured-agent-session-transport-state.ts:21 feeds controller.turnId, which is what cancel() carries. Mobile does the same in mobile-structured-agent-session-cancel.ts:38.
  • The host judged that request against session.translator?.currentTurnId — the adapter's in-memory turn.

Those are two different notions of "the live turn". ClaudeOpenTurn moves its id synchronously, but the row that publishes it goes through createDeferredStructuredAgentSessionEventSink, 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:

  • cancelClaudeTurn re-checks it immediately before issuing the interrupt, precisely so a delayed request cannot stop a later turn (its own comment says so).
  • The adapter contract is "Cancels one turn, not the session."
  • The interrupt is session-scoped. A stale Stop reaching interrupt({ cancelQueued: true }) settles every queued send as durably rejected — 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 activeStructuredAgentSessionTurnId helper and mirrors the dispatchStatus precedent already in performCancel — a journal-derived fact computed host-side and passed down.

Why a read, not a value

dispatchStatus is 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 to CLAUDE_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 therefore resolveLiveTurnId?: () => string | null, re-read at check time. Callbacks across this adapter input are existing precedent (answerPrompt's commit, rewind's onPrepared, compact's onLateResult). 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 (JournalWriteQueue in journal-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:

const liveTurnId = request.resolveLiveTurnId?.() ?? session.translator?.currentTurnId ?? null

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 === 0 clause 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:

  • a newer published turn still returns non-null, so a Stop the adapter still holds is still refused;
  • an undrained row returns null, so a Stop for the live turn is admitted.

Reading the live turn cheaply

journal.snapshot() is renderJournalState, which allocates and sorts every item and every submission in the session; sessions here reach thousands of rows. AgentSessionJournal already names the cheaper idiom for this (visitItems — "Visits reduced items without allocating and sorting a full snapshot"), so this adds journal.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.ts as activeStructuredAgentSessionTurnIdBySequence, so the two ways of asking "what turn is live" sit in one file and cannot quietly drift. It orders on sequence — the same key renderJournalState sorts 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.cancelTurn supply it:

  1. performCancel (structured-agent-session-turns.ts) — the ordinary Stop, beside the existing dispatchStatus.
  2. acquireNativeStop (structured-agent-session-host-handoff.ts) — the handoff's own Stop, which bypasses performCancel entirely and would otherwise have silently kept the old behaviour. Its inline body moves into an exported stopNativeHandoffTurn, matching how acquireNativeHandoffOwner and importTuiHistory are 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.cancelTurn forwards the request to cancelCodexStructuredTurn, which reads only sessionId, turnId, prompt and fence. It resolves its target through compactions.providerTurnId and targets it by id on the provider wire (turn/interrupt with { threadId, turnId }), keying blocked completions on turnKey(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 full src/main/codex suite 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 for resolveLiveTurnId / activeTurnId / stopNativeHandoffTurn in each reverted production file, non-zero in each test file.

Arm 1 — all six production files reverted to the merge base (a9232e8db6).

Test Ablated Restored
admits a Stop for the published turn while the adapter already holds an undrained one FAIL — {cancelled:false}, the defect PASS
refuses a Stop the adapter still holds once the journal published a newer turn FAIL — {cancelled:true}, wrongly admitted PASS
re-reads the published turn after the delivery fence waits FAIL — {cancelled:true} PASS
performCancel hands the adapter a live-turn read FAIL — resolver undefined PASS
stopNativeHandoffTurn judges its Stop against the published turn FAIL — symbol absent PASS
prompt-cancel adapter call shape FAIL — field absent PASS
journal accessor agrees with the rendered snapshot FAIL — activeTurnId is not a function PASS

Totals: 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 stopNativeHandoffTurn row 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.ts alone, so the journal read stays in place).

Test Ablated Restored
admits a Stop for the live turn while the journal has not drained its row FAIL — {cancelled:false}, the widened refusal PASS
admits a Stop for the published turn while the adapter already holds an undrained one PASS PASS
refuses a Stop the adapter still holds once the journal published a newer turn PASS PASS

1 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.ts and 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-session dispatchSequence === 0 cancel and the delayed-cancellation case), and structured-agent-session-host.test.ts.

One existing test changed: structured-agent-session-prompt-cancel.test.ts asserts the adapter call shape with an exact toHaveBeenCalledWith, which a new field necessarily reddens. It now names resolveLiveTurnId: expect.any(Function) — still exact, so an unexpected extra key would still fail.

Wire compatibility

None. Checked against docs/reference/remote-wire-compatibility.md:

  • Rule 1/2 — no RPC param and no stream opcode changes. resolveLiveTurnId is an input to the in-process StructuredAgentSessionAdapter, which never crosses a process boundary; it is a function, which is itself proof it is not serialized. There is no remote proxy implementing cancelTurn — the only implementations are the Claude and Codex adapters plus the pass-through router.
  • Rule 3 — no change to what the host publishes. No journal row, field, or frame is added, dropped, or re-derived; the journal is read, not written differently. The only client-observable difference is that a Stop the client sent is now honoured in cases where it was previously silently refused.

cross-version-agent-session-wire.unit.test.ts is green.

SSH / remote and folder workspaces

performCancel and stopNativeHandoffTurn both 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 0
  • pnpm run check:code-quality:changed — passed, 0 findings (re-run after the commit hook's oxfmt pass)
  • pnpm format — applied
  • pnpm 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 is claude-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 with origin/main's production code in the tree.

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

coderabbitai Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

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: 6d073480-1cff-4bdc-bafc-e6d5b7ae8f00

📥 Commits

Reviewing files that changed from the base of the PR and between 53130f1 and 99b4146.

📒 Files selected for processing (7)
  • src/main/claude/claude-structured-prompt-ownership.ts
  • src/main/claude/claude-turn-ownership.test.ts
  • src/main/native-chat/agent-session-journal/journal-store.test.ts
  • src/main/native-chat/agent-session-journal/journal-store.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host-handoff.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-turns.ts
  • src/shared/structured-agent-session-live-turn.ts

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


📝 Walkthrough

Walkthrough

The change adds an optional resolveLiveTurnId callback to cancelTurn. Claude cancellation uses this callback for ownership checks and re-reads the published turn after the delivery fence. Normal native cancellation and native handoff cancellation derive the live turn from journal state. Tests cover matching, stale, completed, and changed-turn cases.

Priority: ⬇️ Low

Merge Risk: ⚪ Minimal · up to 99b41

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 10 functions across 11 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: Claude Stop requests now use the journal-published turn for ownership checks.
Description check ✅ Passed The description thoroughly explains the failure, implementation, affected cancellation paths, compatibility, testing, and validation results. It does not use all template headings and does not provide…
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.
  • 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.

@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 open question on the residual Stop window.

Reviewed changes

  • Stop guard now reads the published journal — ownsRequestedTurn() in claude-structured-prompt-ownership.ts prefers a host-supplied resolveLiveTurnId?: () => string | null over session.translator?.currentTurnId, falling back only for direct adapter callers with no journal. Passed as a function (re-read at isCurrent() after the 3s delivery fence), not a captured value.
  • Both production callers wired — performCancel supplies () => activeStructuredAgentSessionTurnId(ctx.journal.snapshot().items); the handoff's acquireNativeStop body is extracted into the exported stopNativeHandoffTurn, which supplies the same read. These are the only two adapter.cancelTurn call sites in src/main.
  • Codex untouched — cancelCodexStructuredTurn never 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 stopNativeHandoffTurn wiring test and a performCancel call-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, and check:code-quality:changed all 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.

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

@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

  • Added an in-memory fallback for a null journal read — ownsRequestedTurn() moved from resolveLiveTurnId ? resolveLiveTurnId() : translator.currentTurnId to resolveLiveTurnId?.() ?? 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() — both performCancel and stopNativeHandoffTurn call it instead of materialising snapshot().items. The new activeStructuredAgentSessionTurnIdBySequence picks 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 a stopNativeHandoffTurn re-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.

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Electron visual proof (PR #20921)

Launched this worktree's Orca under ORCA_BACKGROUND_LAUNCH=1 + CDP (127.0.0.1:9333). Identity from window.api.app.getIdentity(): Orca: brennanb2025/claude-stop-turn-source (isDev, branch brennanb2025/claude-stop-turn-source, repo root this worktree). Launch log: [orca-dev] Instance: claude-stop-turn-source. Bundle name: Orca: brennanb2025-claude-stop-turn-source.app.

Rendered native Claude session UI (isolated disposable project; experimental native chat on):

Idle / Send

02-claude-native-chat-idle-send.png

Working / Stop — composer aria-label="Stop the agent", sidebar and tab show Working.

03-claude-native-chat-working-stop.png

Launch identity (empty profile home)

01-identity-home.png

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 MaxListenersExceededWarning on BrowserWindow at startup.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review complete: land.

  • Functional correctness: clean. The independent review found no in-scope defects, so no code changes were needed. The cancellation ownership and journal-drain lifecycle fix addresses the reported failure mechanism without adding a parallel guard or broadening product scope.
  • Architecture and performance: clean. The mechanism fits the existing ownership/delivery lifecycle, and the review found no regression or performance concerns.
  • Focused validation: 45/45 changed tests passed, including 14/14 Claude ownership tests. tc:node, changed-code quality, and git diff --check passed.
  • Readiness: both the opening and closing readiness audits returned land with no P0/P1/P2 findings.
  • Electron validation: the exact PR worktree rendered the idle Send and active Stop states under background launch via CDP. Screenshots and validation notes are attached here. The rendered flow was validated; the journal-drain race itself was covered by tests rather than a live Claude provider turn.
  • CI: the rerun is fully green, including all eight Node 24 test shards and aggregate verify. The original failure was a late window is not defined timer from an untouched renderer test after 10,378 assertions had passed; that test also passed locally (18/18).

No review commit was necessary, and the PR branch remains clean at 99b41465b518dcf097ad60cd4ffc8cdaf9f8dfca.

@brennanb2025
brennanb2025 merged commit 9ed561c into main Sep 16, 2026
52 of 54 checks passed
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
…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.
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