Repository navigation
fix(native-chat): name a chat write by its target, not the owner generation - #22812
Conversation
No client ever called agentSession.requestHandoff or mounted the handoff chrome. Delete the handoff coordinator, the terminal-owner runtime, the proof write path and the unmounted UI. Keep agentSession.handoffStatus, which released desktop clients read for worktree activation, and let records an older build left mid handoff reconcile through the ordinary restart and recovery paths.
Eviction now drains delivered events before quit's resume-offer snapshot. An unbounded wait there sits ahead of the provider stop, so a sink whose journal write stalls kept the child running until the step deadline aborted the eviction. The offer is advisory: bound the drain and stop the child regardless. Co-Authored-By: Claude <[email protected]>
`claudeAuthEnvCarriedForward`, `isPathWithinDirectory` and
`queryWindowsProcessRowsFresh` lost their last caller with the handoff. The
fresh-scan tests now go through `queryWindowsProcessDescendants({ fresh: true })`,
the teardown path that still depends on that contract.
Co-Authored-By: Claude <[email protected]>
Six comments still named the handoff coordinator, a handoff suspend, or a terminal-owned session as live participants in the flows they describe. Co-Authored-By: Claude <[email protected]>
Co-Authored-By: Claude <[email protected]>
…ement The removed restart handoff test pinned this branch; nothing else did. Co-Authored-By: Claude <[email protected]>
The handoff removal dropped the per-session queue from `handoffStatus`, so a read landing mid-start reported the reservation (no owner) instead of the settled chat owner, and shipped desktop clients blocked worktree activation on it. The read is queued again, as it was before the removal. Co-Authored-By: Claude <[email protected]>
The gate only refused a write when a PTY had been bound to a chat session, and the only code that ever bound one was the terminal handoff this branch removes. With it gone, every admit/readmit returned "admitted" unconditionally, so the checks on the renderer write path, the runtime controller backstop, terminal.send, agent prompts, preview input and orchestration pointers, the refusal fields on terminal.send and worker-start receipts, the plugin and CLI refusal copy, and the adopted-pane orchestration routing could no longer run. Ordinary writes take the same path in the same order as before. Co-Authored-By: Claude <[email protected]>
…alled appendLegacyTranscriptMessages fed the terminal transcript catch-up and proveClaudeTranscriptBranch backed the terminal owner's exit proof. Both lost their last caller with the handoff. Their tests now go through the live entry points instead: the roster bounds through the legacy import, the pinned-read and growth tests through the ancestry replay the history window uses, and the marker rules through the string proof in their own file rather than the session-file resolver's. Co-Authored-By: Claude <[email protected]>
A send refused because the chat's owner is not settled showed "The session is mid-handoff (<stage>)." in the composer. With the handoff gone, the stages that reach it are a chat that is still starting, or one whose previous agent process has not yet been confirmed stopped. The message now says which of the two it is. The refusal code is unchanged. Co-Authored-By: Claude <[email protected]>
Co-Authored-By: Claude <[email protected]>
With the terminal handoff gone, the module named codex-tui-rollout-proof holds only the pinned rollout lookup that structured Codex launches use to resume a thread, so the name described code that no longer exists. Rename the module and its options type. Also drop a mobile allowlist assertion that pinned the removed agentSession.requestHandoff method, which no longer exists to allow.
The handoffStatus reply type still listed the terminal handoff's fields and states (terminal placement, host label, proof retry, queued and waiting phases, the to-terminal direction). No host writes them any more and the only client reader parses the reply as unknown, so they described nothing. The reply on the wire is unchanged.
…t decode Nothing in this build writes a terminal owner (`runtimeKind: 'tui'`) or the handoff's `preparing` / `old-owner-stopped` stages, but the in-memory types still admitted them, so readers across the host kept branches for values no path produces and the compiler could not point at them. The store now validates the on-disk shape, which still accepts those values so an older record is not quarantined, and maps them once while parsing: - `preparing` and `old-owner-stopped` become `recovering` - a `tui` lease becomes `native`; when it records a process it also becomes `conflicted`, the claim every build probes but never stops. A plain native owner would be stopped by restart recovery, here and in older builds. Revisions are taken over the normalized state on both sides of every compare, and the mapped record reaches disk with the store's first transaction, the same way the tab-id backfill does. The in-memory types narrow to what this build writes, and the branches that existed only for the removed values go. Structured-worker identity keeps its verdict for a former terminal owner by refusing a conflicted claim rather than a non-native kind.
…ation A reservation only ever names a native owner now, so the request no longer carries a kind and the reserved lease records `native` directly. The attach params keep `runtimeKind`: agentSession.ensure and create accept it, and the operation fingerprint stored in the ledger covers it.
…at changes nothing else Hiding a tab also committed the visibility index, so the no-op transaction wrote the file even when its open-time revision was wrong. Committing the index first leaves the pending rewrite as the only reason to write.
…ration A write carried the fence of the last frame the pane read, and the host refused it unless that fence was still current. An idle release and the restart after it each move the fence, and the release publishes nothing, so a send after a release was refused "Expected runtime fence 1; the session is at 3", and a Stop queued behind a cold start was refused as stale. Every write already names what it acts on: a send its conversation, a cancel its turn, a prompt answer its item revision, a rewind its epoch; an option is last-writer-wins. So admission stops comparing the client's fence, and the rebase that papered over one restart (admitAtResumedFence, resumedFromFence) goes with it. The writer-lease check stays, and so does the attach's compare-and-swap. Frames now stamp the fence read when each frame is sent instead of a copy each subscriber kept, which went stale on the same release.
There was a problem hiding this comment.
Important
This PR leaves an existing test in the suite broken. tests/e2e/structured-agent-session-read-owner.unit.test.ts was not updated for the required readFence hook on AgentSessionSubscribers, and 2 of its 3 tests fail on this branch (they pass on the base). Details and evidence below.
Reviewed changes
- Drop the write-time fence check.
admitAgentSessionMutationno longer comparesexpectedRuntimeFencewith the lease; writes are admitted by their own target and still require a live writer lease.isAgentSessionFenceCurrentsurvives only in the attach acquisition compare-and-swap. - Delete the one-restart rebase.
admitAtResumedFenceandresumedFromFence(host session + attach computation) are removed; send preparation now answers refused-or-not and no longer rewrites the envelope. - Frames carry the live fence.
AgentSessionSubscribersdrops the per-subscriber fence and takes a requiredreadFence(sessionId)hook, read at send time and stamped on every frame;open/snapshot/reset/backgroundTaskslose their fence argument. - Tests and docs rewritten to pin the new behavior rather than the removed refusal, plus the cross-version wire test and
remote-wire-compatibility.md.
⚠️ A missed AgentSessionSubscribers call site breaks an existing test
AgentSessionSubscribers now requires a readFence hook, and open() no longer accepts a fence. Every call site was updated except tests/e2e/structured-agent-session-read-owner.unit.test.ts: it constructs the class at line 144 with only onJournalPublished, and still passes fence: 1 to open() at line 173. Because readFence is invoked on every emitted frame, the subscribe edge throws and the read owner never catches up.
On the committed head, structured-agent-session-read-owner.unit.test.ts fails 2/3 (cursor stalls at 100 instead of 140/501). I checked out the base and the same file passes 3/3, then added readFence: () => 1 locally on the head and the suite went green again — so the regression is caused by this PR. This file matches the vitest include glob tests/e2e/**/*.unit.test.ts, so pnpm test (and CI) will fail; config/tsconfig.e2e.json is explicitly not enforced, so typecheck did not surface it. Worth grepping once more for new AgentSessionSubscribers before merging, in case any other out-of-tree spec has the same shape.
Technical details
# AgentSessionSubscribers call site missing the required readFence hook
## Affected sites
- `tests/e2e/structured-agent-session-read-owner.unit.test.ts:144` — constructs
`new AgentSessionSubscribers({ onJournalPublished })` without the required
`readFence` hook.
- `tests/e2e/structured-agent-session-read-owner.unit.test.ts:173` — `subscribers.open({...})`
still passes `fence: 1`, which the method no longer accepts.
- `src/main/native-chat/agent-session-wire/structured-agent-session-subscribers.ts:47`
— `readFence` is a required member, read at
`structured-agent-session-subscribers.ts:87` and `:212`.
## Required outcome
- The spec constructs the subscribers with a `readFence` hook and stops passing `fence`
to `open`, so the two currently-failing tests pass on the head.
## Suggested approach (optional)
- Add `readFence: () => 1` to the hooks object at line 144 (the journal rows in this
fixture are all fenced at 1) and delete `fence: 1` from the `open()` call at line 173.
- Re-run `pnpm vitest run --config config/vitest.config.ts tests/e2e/structured-agent-session-read-owner.unit.test.ts`
and confirm 3/3.DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…start is not resent
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
The delta since the prior pullfrog review is two docs/wording commits and one behavioral fix that settles the frames-versus-fence question.
- Restored the per-subscriber fence on frames.
AgentSessionSubscribersdrops the livereadFencehook and returns to the base shape:opentakes afence,reset/snapshot/backgroundTaskstake one, and every frame carries the pane's own fence, advanced only by a replay or a background-task publication. Call sites passsession.fence(host.publishFence, background-taskpublish) or the store lease fence onsubscribe. - Added a regression test for the resend loop.
structured-agent-session-send-preparation.test.tsnow pins that a failed restart's published frames keep the pane's original fence, even though the lease moved — the trigger that made a refused send resend forever. - Removed the obsolete live-fence test (
stamps a fence that moved without a replay) and the matchingreadFencewiring in the affected specs. - Cleared the prior blocking finding. With
open({ fence })restored and the constructor hooks optional,tests/e2e/structured-agent-session-read-owner.unit.test.tspasses again (3/3; 40/40 withsubscribersandsend-preparation). Verified locally.
The write-time fence removal itself is unchanged from the previously reviewed revision; this commit only realigns frame publication with it.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…box comments Three places still gave the removed fence check as a reason: the launch replay said admission puts the ledger ahead of the fence, the launch surface said a send must name the lease it was admitted against, and the direct-mailbox path said the lease fence decides whether delivery is safe. Admission now checks only the writer lease.
Review status: ready for review at
|
…tes-by-target # Conflicts: # src/main/native-chat/agent-session-wire/structured-agent-session-host-types.ts # src/main/runtime/agent-session-record-store-legacy-handoff-lease.test.ts # src/renderer/src/lib/worktree-agent-activation-gate.test.ts
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (23)
💤 Files with no reviewable changes (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review. 📝 WalkthroughWalkthroughMutation admission no longer rejects writes based on Priority: ➖ Normal Merge Risk: ⚪ Minimal · up to The changed structured-chat write behavior has no identified merge-blocking issue; normal checks can proceed. Security Architecture ReviewSecurity architecture risk: 🔵 Low · up to Older chat writes can now proceed after an agent restart, but the reviewed path still requires a valid writer and preserves operation identity. No introduced security finding was established. Some mutation-specific behavior remains unverified. Retained concerns Security review detailsSecurity Blast Radius
Trust Boundaries and Controls
Hardening Proposals
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Docstring CoverageExplanation Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 10 functions across 21 files. (1 skipped: 1 unsupported.)
✨ Finishing Touches 💡 2📝 Generate docstrings 💡
🛠️ Fix failing CI checks 💡
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 |
|
Ready to merge. This is my view as coordinator of the native-chat redesign PRs.
|

Scope: which chat this affects
experimentalStructuredNativeChatsetting, which is off by default (src/shared/default-global-settings.ts:137).Follows #22783 (merged); this PR targets
main.ELI5
Every chat request carries a note saying which copy of the agent the app last saw. The host refused the request if that copy had since been replaced, even when the request didn't depend on which copy was running. After the agent went idle and came back, a send or a Stop could fail with "Expected runtime fence 1; the session is at 3." The host now ignores that note, because every request already says exactly what it acts on.
What Changed
Before
agent_session_checkpoint_stalewith "Expected runtime fence 1; the session is at 3."After
The mechanism
admitAgentSessionMutation(src/shared/agent-session-mutation-envelope.ts) no longer comparesexpectedRuntimeFencewith the lease. It still checks the fingerprint, then the ledger, then the writer lease.The rebase that covered one restart is deleted:
admitAtResumedFencein send preparation;resumedFromFenceon the host session and its computation in the attach.Session preparation now answers only "refused or not", and no longer returns a rewritten envelope.
Kept, deliberately:
evaluateAgentSessionAcquisition). It is host-internal, and it is what makes two concurrent attaches safe.agentSession.ensureat an old fence is still refusedagent_session_checkpoint_stalewith the live fence attached.Why
The fence has no remaining job as a write check. It came with the terminal handoff, to stop a native write landing on a session a terminal had taken over. #22783 removed that handoff. Every write now names its own target, which is what actually protects it:
validatePendingPromptexpectedEpochWhy not rebase more cases instead?
admitAtResumedFencewas a guard beside the check. It covered a send after exactly one clean restart, and it never covered Stop. Extending it to more hops and more methods would add rules to a check that no longer protects anything, so the check goes instead.Why frames keep each pane's own fence. This is on purpose. A pane that learned every fence move would treat a failed restart as a reason to resend. A restart refused before it spawns anything still moves the fence and leaves no recorded answer, so each resend tries again and moves the fence again, forever. A start that fails after spawning does not loop, because the ledger replays its answer. The lasting fix belongs with the later accept-then-deliver change: record a failed restart as a rejected message, and stop the client retrying on a fence change.
Differences from the common pattern
Linked Issue
Part of the native-chat "a chat never gets stuck" series. Follows #22783 (merged); no separate issue.
Visual Proof
Live desktop app, structured Claude chat, idle release forced with a shortened release window. Before = base
713b126feb, after =31444bf876(later commits change comments only).Testing
New tests, in
structured-agent-session-send-preparation.test.tsagainst the real host and store:Ablations. Each was run on the committed head and then restored from it.
Expected runtime fence 1; the session is at 3.(the idle-release send),Expected runtime fence 2; the session is at 3.(the first send and the Stop),Expected runtime fence 1; the session is at 3.(the send typed during the start). The existing restart tests go red too, which shows the rebase existed only to cover the check.fence: 4, expected1agent_session_checkpoint_staleRewritten on purpose (each pinned the removed refusal):
null;checkpoint_staleis now unreachable for send and setOption, and a stale fence is admitted;refuses a write still fenced to the host generation that died, nowdelivers a write still fenced to the host generation that died. Itsreattachhelper still pins the attach refusal.docs/reference/remote-wire-compatibility.md: the line describing that cross-version case is updated to match.Runs
src/main/native-chat/agent-session-wire,src/shared/agent-session*,src/shared/structured-agent-session*,src/main/runtime/agent-session*,src/main/runtime/rpc/methods/structured-agent-session*,src/main/runtime/orchestration/structured*,src/renderer/src/components/native-chatandtests/e2e/cross-version-wire/cross-version-agent-session-wire.unit.test.ts: 374 files, 3663 of 3663 pass.tsc -p config/tsconfig.node.jsonandpnpm tc:webare clean.oxlinton the changed files andpnpm run check:code-quality:changedpass.Manual (live desktop app, structured Claude chat, forced idle release, before
713b126febvs after31444bf876):Send after an idle release, chat open: before, "Message was not sent." with "Expected runtime fence 1; the session is at 3."; after, the agent restarts and the message is answered once, with no error.
Stop after an idle release: before, the message is refused, so there is nothing to stop; after, Stop clears the turn in about 260 ms and the next message is answered.
Restart that fails after an idle release: both builds make one attempt, then show "Message was not sent." with Retry, and the fence stops moving. An earlier revision of this PR that sent the live fence on every frame turned this into an endless resend; that half was removed and this lane re-run.
Ordinary chat (send, send, Stop mid-turn, send): identical on both builds.
Not run: mobile, paired web and SSH by hand. The host change is the same code on every host, and no client code changed.
I manually tested these changes locally
Automated tests added/updated, or explained why not below
AI Disclosure
Built with Claude (Opus 5.5).
Review
Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
Mixed versions. Clients and hosts update independently, so each pairing was checked:
checkpoint_staleis no longer returned for a write, so the client's retry-on-stale path never runs. Frames are unchanged: each pane still gets its own fence, so a client's retry-on-fence-change logic sees nothing new.checkpoint_stale, so an old host behaves exactly as today.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)Author X handle: @BrennanKB5