Skip to content

fix(claude): single-own turn identity so Stop reaches a provider-opened turn - #20794

Merged
brennanb2025 merged 10 commits into
mainfrom
brennanb2025/claude-turn-ownership
Sep 15, 2026
Merged

brennanb2025 merged 10 commits into
mainfrom
brennanb2025/claude-turn-ownership

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​466 $\color{#cf222e}{\Huge{\mathbf{−}}}$​13 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​453
Prod 12 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​291 $\color{#cf222e}{\Huge{\mathbf{−}}}$​108 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​183

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. cancelClaudeTurn returned { 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.

  1. The journal translator wrote turnId into the durable turn row. That row's id is what every client's Stop carries, and what status, prompt binding and rewind read.
  2. settleWaiter separately wrote session.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 activeTurnId was 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. activeTurnId and activeTurnSequence are deleted, so the second writer goes away rather than a second guard being added beside the first.

Prompt binding (bindPromptItemId) and permission callbacks' currentTurnId now 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

activeTurnSequence was 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 no lastAdmittedDispatchSequence latch 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):

  • accepted and rejected admit ordinary Stop;
  • unknown admits only when recovered: true;
  • live pending and unrecovered unknown remain 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 dispatchStatus use an in-memory fallback over both dispatchWaiters and retiredDispatchWaiters for 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 as Boolean(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 (dispatchState plus recovered) 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.ts drives 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.ts covers 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:

Assertion Final head Full production ablation
Provider-opened assistant turn (provider-opened-assistant) cancels pass FAIL — the exact Stop assertion received cancelled: false
Other integration assertions pass pass (7 tests)

The 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=1 Electron instance was launched from this worktree and verified by window.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 showed Cancellation requested. rather than The provider had already finished this turn.; the command never wrote FIRSTDONE.

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 turn item'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.cancelTurn now 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

  • Focused cancellation/journal suite — 5 files, 40 tests passed
  • pnpm tc — exit 0
  • pnpm run check:code-quality:changed — 0 new findings across 17 changed files
  • Final-head provider-opened ablation — fails with cancelled: false when production levers are reverted; passes at head
  • No max-lines disable 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 analysis check is unrelated to this PR. It fails at src/shared/agent-status-legacy-adapter.ts:95 on Reflect.get. Main commit 9ab0a18e82 (#20716) introduced that line after anti-slop/no-reflect-get was enabled by f107499e44; 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, durationMs precedence, queued-message affordances, and stranded-turn settlement are separate planned PRs and are not included here.

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

coderabbitai Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The change introduces ClaudeOpenTurn as the owner of open-turn identity and lifecycle publishing. Claude translation, cancellation, permissions, and prompt binding now read the translator’s current turn. Dispatch cancellation also receives the latest journal dispatch observation. Session-level active-turn fields and related assertions are removed. New tests cover provider and echo turns, stale identifiers, unresolved dispatches, cancellation, and resume behavior.

Priority: ➖ Normal

Merge Risk: 🟡 Moderate · up to a2215

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 21 functions across 21 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning 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… Add the required template sections and complete them. Include a valid issue reference under ## Linked Issue using Fixes #<issue-number>. Add the ELI5 summary, Review, Agent skill upstream boundary status, Notes, and Checklist responses.…
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the main change: centralizing Claude turn ownership so Stop can reach provider-opened turns.
Full details: Description check

Explanation

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 ## Linked Issue using Fixes #&lt;issue-number&gt;. Add the ELI5 summary, Review, Agent skill upstream boundary status, Notes, and Checklist responses. Retain the existing technical explanation, test results, and visual proof.

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

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/suppressReopen replace the translator's closure state.
  • Translator delegates (claude-structured-journal-translation.ts): all turn lifecycle calls route to the owner and currentTurnId exposes the id the published row carries.
  • activeTurnId / activeTurnSequence deleted (claude-structured-session-state.ts): prompt binding, the permission callbacks and the cancel guard now read session.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) around ownsRequestedTurn().
  • Tests: new claude-turn-ownership.test.ts drives the real adapter and reads the turn id out of the published journal row; fixture acquired() now acquires with a journal sink.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟠 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 lift

Bind queued prompt cancellation to the pending dispatch. If canUseTool runs before the newly dispatched message opens a translator turn, it records turnId: null, and bindPromptItemId preserves that binding. cancelClaudeStructuredTurn then calls claimBound, which requires the binding turn ID to equal the request turn ID and returns { cancelled: false } before ownsRequestedTurn or 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

📥 Commits

Reviewing files that changed from the base of the PR and between 62d9bb5 and 4f61be5.

📒 Files selected for processing (2)
  • src/main/claude/claude-structured-prompt-ownership.ts
  • src/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.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

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 ORCA_BACKGROUND_LAUNCH=1 Electron instance from this worktree (Orca: brennanb2025/claude-turn-ownership, CDP 127.0.0.1:9335, renderer 127.0.0.1:5175). Identity via window.api.app.getIdentity(): devRepoRoot=/Users/brennanbenson/orca/workspaces/orca/claude-turn-ownership, devBranch=brennanb2025/claude-turn-ownership.

Scenario exercised

  1. Fresh isolated profile + throwaway git folder workspace.
  2. Default New-tab → Claude launched the PTY TUI (structured native chat flags off). Closed that tab.
  3. Enabled experimentalNativeChat, experimentalStructuredNativeChat, and openAgentTabsInChatByDefault in the isolated profile only, then New-tab → Claude opened a structured Claude Chat session (contentType: agent-session, structuredHostOwned: true).
  4. Sent a one-word ping; the turn completed (Done, assistant text ping). This is the “session already dispatched once” precondition.
  5. Sent a longer count prompt so a second echo-opened turn would stay live long enough to Stop.
  6. Clicked the composer Stop affordance (aria-label: Stop the agent) once controller.turnId was set.

Visible evidence

Before (idle structured composer, Send not Stop):

05-structured-claude-chat-idle-send.png

After first dispatch (precondition: prior turn finished, Send restored):

08-structured-claude-after-first-dispatch.png

During second turn (Stop square visible, “Working for 0s”):

09-structured-claude-stop-visible.png

After Stop (status is “Cancellation requested.”, not the stale-finish note; no 1–80 count):

10-structured-claude-after-stop.png

Backing state

  • App identity matched this worktree/branch.
  • Session tab: structured-agent-session-claude_85a7e985_454c_4b51_a14b_e31b0c32955f, agentSessionAgent: claude.
  • agentStatusByPaneKey: state: done, agentType: claude, structuredHostOwned: true, providerSession.id: ca57c373-c2bb-4a22-8682-140ff625dab1.
  • Transcript status after Stop: “Cancellation requested.” That string is written only when adapter.cancelTurn returns { cancelled: true }. The bug’s user-visible failure is “The provider had already finished this turn.” (cancelled: false) while the model keeps working. That note did not appear.
  • Composer Stop is gated on controller.turnId !== null (journal running-turn id), which is the id the client sends.

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 src/main/claude/claude-turn-ownership.test.ts.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

Reviewed the delta since the prior pullfrog review (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): ownsRequestedTurn now treats a null currentTurnId as "no id this request can contradict" only when dispatchSequence === 0, so a foreign Stop is refused while a compaction runs or before a new provider turn's first frame. compactions.ownsTurn still admits the /compact command id.
  • Regression test for a settled turn (claude-turn-ownership.test.ts): a Stop naming an echo turn that already settled is refused with no interrupt, 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}.

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Electron UI validation: provider-opened Claude Stop

Follow-up to the earlier echo-opened evidence. This path was reached in a background ORCA_BACKGROUND_LAUNCH=1 Electron instance of this worktree (Orca: brennanb2025/claude-turn-ownership, CDP 127.0.0.1:9334). Identity via window.api.app.getIdentity() matched devRepoRoot=/Users/brennanbenson/orca/workspaces/orca/claude-turn-ownership. No production code was changed; screenshots are not committed.

Scenario

  1. Structured Claude Chat, after at least one completed dispatch (ping).
  2. Sent Run this exact bash command and nothing else: sleep 25 && echo FIRSTDONE.
  3. Claude backgrounded it (task ID bvo1ckmn1) and ended the echo turn (Worked for 7s, composer back to Send, shell-command strip still running).
  4. When that background command completed, a new Working turn opened with no new user message — Stop square visible, Working for 0s, bash row checkmarked.
  5. Clicked Stop on that turn.

Visible evidence

Precondition — first dispatch complete:

01-after-first-dispatch.png

Echo turn settled, background bash still running, Send not Stop:

09-echo-settled-waiting-bg.png

Provider-opened turn (no new user bubble; Stop visible; bash completed):

10-provider-opened-stop-visible.png

After Stop — “Cancellation requested.” not the stale-finish note; sleep 25 never wrote FIRSTDONE:

11-after-provider-opened-stop.png

Backing state

  • Session: structured Claude Chat, structuredHostOwned: true.
  • After Stop: state: done, Stop hidden, transcript contains “Cancellation requested.” and does not contain “The provider had already finished this turn.”
  • Composer Stop is gated on controller.turnId !== null (the journal running-turn id the client sends). That id appeared after the echo turn had already settled, so this Stop targeted the provider-opened turn.

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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

Reviewed the delta since the prior pullfrog review (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 on lastAdmittedDispatchSequence === dispatchSequence, replacing the live-waiter claudeHasUnsettledDispatch derivation 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 new ClaudeSession.lastAdmittedDispatchSequence on 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 the 4f61be5 form, 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.

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

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.ts returns 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() treats accepted/rejected/recovered-unknown as settled and pending/live-unknown as still outstanding; the queued-interrupt bypass is now gated on Boolean(prompt), restoring main's plain-Stop behavior for CLIs advertising interrupt_cancel_queued_v1.
  • lastAdmittedDispatchSequence deleted — 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.

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

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues 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): performCancel and acquireNativeStop compute latestJournalDispatchObservation(...) once and spread it as ...(dispatchStatus ? { dispatchStatus } : {}), mirroring the adjacent conditional prompt spread.
  • The guard already reads request.dispatchStatus with a truthy test, so an absent key and null are 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-wire 569/569, claude-turn-ownership 7/7, pnpm tc:node exit 0.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (2)

🟠 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 win

Select the latest matching submission by journal sequence. JournalRowBase defines seq, not ts, as the ordering field, but applySubmission discards seq and latestJournalDispatchObservation selects by submittedAt. 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. Preserve seq in 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 win

Clear streamed checkpoint state when the provider ends. The ended event is reachable on child exit. streamedText.flush() persists pending text but does not remove checkpoint state. streamedText.settle() and streamedBlocks.clear() are required to remove pending identities and block state. Without them, pendingStreamedBlocks remains 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

📥 Commits

Reviewing files that changed from the base of the PR and between 892335d and a2215d1.

📒 Files selected for processing (2)
  • 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

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status: clean at a2215d1405

The same-model adversarial review and final readiness checklist both found no in-scope P0/P1/P2 issues. The one CI regression found during review was meaningful: the new optional journal observation was being passed as null into an existing exact-argument adapter caller. I fixed that by omitting the field when absent (preserving the waiter fallback), committed it as a2215d1405, pushed it, and reran the affected tests.

Validation:

  • pnpm test with seven explicit paths: 7 files, 68 tests passed.
  • pnpm tc: pass.
  • pnpm run check:code-quality:changed: 0 new findings across 17 changed files.
  • Full Claude suite: 101 files, 959 passed, 5 skipped; the only failure is the known pre-existing real Claude CLI handshake failure.
  • Final-head ablation at a2215d1405: with every PR production lever reverted to the base and tests kept, the provider-opened integration assertion fails with cancelled: false at the exact Stop call; 7 other integration tests pass. The ablation was restored and the worktree is clean.

Electron proof is attached in the PR body and in the provider-opened follow-up comment: the background-task flow opened a new assistant-only turn after the echo turn settled, Stop produced Cancellation requested., and the command never wrote FIRSTDONE. Screenshots: precondition, echo settled, provider-opened Stop, after Stop.

CI is green for all eight test shards, typecheck, packaging, wire compatibility, and other applicable checks. The remaining red static analysis check is unrelated to this PR: it reports Reflect.get at src/shared/agent-status-legacy-adapter.ts:95, introduced on main by #20716 (9ab0a18e82) after anti-slop/no-reflect-get was already enforcing. Static analysis runs on PRs, not main; this PR does not touch that file and it was intentionally not changed or suppressed. The red verify check follows from that required static-analysis failure.

Out of scope remains unchanged: steered-turn folding, durationMs precedence, queued-message affordances, and stranded-turn settlement.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — the 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 new CLAUDE_DISPATCH_ADMISSION_TIMEOUT_MS (3s) wait sets dispatchAdmissionExpired, 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 takes AgentJournalSubmission instead 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 — || dispatchAdmissionExpired in the prompt branch is always false: the flag is set only when !prompt.

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

}
})

it('lets a queued-cancel provider release an unresolved ordinary Stop', async () => {

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.

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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — the 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): waitForClaudeDispatchAdmission now takes an admitted predicate, polls it every 50ms, and resolves true early or false at the 3s deadline; dispatchAdmissionExpired derives 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 when request.dispatchStatus !== undefined or 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.

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

!dispatchAdmissionAllowsCancellation() &&
(request.dispatchStatus !== undefined || currentDispatchHasRetiredWaiter())
) {
dispatchAdmissionExpired = !(await waitForClaudeDispatchAdmission(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The 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())

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.

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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

Reviewed the delta since the prior pullfrog review (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): drives cancelClaudeStructuredTurn with a retired waiter at the current dispatchSequence, 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): the CLAUDE_DISPATCH_ADMISSION_TIMEOUT_MS JSDoc 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.

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status — ready for merge

Final head: 674a30d2bced48b5091c5ecf43ac541f06141b6f

  • Same-model adversarial review is clean; the later production head is unchanged, and the final push adds the bounded-wait fast-path tests and calibration comment.
  • Final readiness checklist at this exact head: PASS, with no P0/P1/P2 findings.
  • Validation: focused five-file suite 58 passed; final targeted readiness wave 75 passed; pnpm tc passed; changed-code quality 0 new findings across 17 files. The broader Claude suite has the documented pre-existing real-Claude CLI handshake mismatch (962 passed, 5 skipped); no new failure was introduced.
  • Final production ablation, run last at this exact head: reverting all 11 PR production modules to origin/main while retaining the provider-opened integration test produced 1 failure / 7 passes; the exact Stop assertion received cancelled: false. At the full head the same assertion passes. The worktree was restored clean afterward.
  • Electron validation covered the provider-opened turn flow and Stop action; screenshots are attached in the PR body.
  • The red static analysis check is unrelated to this PR: main commit 9ab0a18e82 (refactor(agent-status): isolate legacy status ingress behind one admission point #20716) introduced Reflect.get at src/shared/agent-status-legacy-adapter.ts:95 after anti-slop/no-reflect-get was enabled; static analysis runs on PR merge refs, not main. This PR does not touch or suppress that file.
  • Folding steered turns, durationMs precedence, queued-message affordances, and stranded-turn settlement remain out of scope.

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