Skip to content

fix(native-chat): turn facts come from the turn record, and /compact is a message the chat sends - #23059

Merged
brennanb2025 merged 222 commits into
mainfrom
brennanb2025/chat-turn-facts-from-record
Sep 29, 2026
Merged

brennanb2025 merged 222 commits into
mainfrom
brennanb2025/chat-turn-facts-from-record

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 129 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​6668 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1678 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​4990
Prod 144 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​4030 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1654 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2376

Builds on #22835 and #22944, both now merged; this PR targets main.

ELI5

Typing /compact in a structured chat used to paint its result inside the previous turn: the "Conversation compacted" line folded away under the last answer's "Worked for", the previous turn's timing moved, and the sidebar re-dated the chat as if new work had finished. Messages typed while it ran were refused. Now /compact is a message the chat sends like any other: it gets its own row, its own "Worked for", a visible result, and the turn before it is left alone. Messages typed meanwhile wait and are sent right after it.

Scope: which chat this affects

  • Structured chat (desktop and mobile): /compact behaves as described above; rows are grouped under the turn they belong to instead of the user message above them; error rows and the compaction separator never fold away. It is behind the experimentalStructuredNativeChat setting, off by default.
  • Default chat view: no change. It has no journal, so it keeps today's grouping by position.
  • Terminal agents and plain terminals: no change.

What Changed

Terms used below: the journal is the saved record of every row in a structured chat; the delivery loop is the host step that hands queued messages to the agent one at a time; a provider's translator is the code that turns the agent's output into journal rows; a steer is a message sent while the agent is still working on a turn.

Before

  • /compact ran outside the send path. The host wrote a status row that pretended to be a running turn and later overwrote it with the result, so the result drew inside the previous turn and folded under its "Worked for".
  • A 180 s timer decided when a compaction was "unconfirmed"; after it, a late result could still arrive and rewrite the row.
  • Sends were refused while a compaction ran, on the host and in the desktop composer.
  • After /compact the sidebar showed "/compact" as the latest prompt, raised a completion notification and moved the row's "done" time.
  • Rows were grouped by position: every row belonged to the last user message above it. A message typed into a running turn split it in two, and output from a turn the provider started on its own (a Claude background wake) folded under the previous turn.
  • A child that died mid-turn wrote its "exited unexpectedly" row as an ordinary status row, which folded away. A Claude child that died after echoing a message often wrote no exit row at all.

After

  • /compact is accepted into the chat's queue as the user's message, marked with command: {name: 'compact'}. The existing command RPC is a front door to that path and replies once the command is handed over to the agent: completed now means "started".
  • When the delivery loop reaches it, it opens the command's own turn record and hands /compact to the provider. From then on the provider's translator owns that turn exactly as it owns any turn: it ends it from the provider's own frames and writes the result (the compaction separator, or the provider's error).
  • While a command's turn runs on a live agent, the loop hands nothing else over. Messages typed meanwhile wait, are drawn below the "Compacting the conversation" line, and are delivered after it, even if it fails. Each takes its place in the transcript, and starts its "Worked for", at the moment it is handed over.
  • A compaction counts as done only when the provider reports the compaction itself. Without that, it is "stopped" if Orca interrupted it and "failed" otherwise.
  • Stop interrupts a command like any turn. If the provider cannot take the interrupt (Codex before it opens the compaction's turn), or a second Stop finds the first went unanswered, Stop restarts the agent and the command ends as interrupted.
  • If the agent exits mid-command, the exit row is shown on that command's turn and the next message starts a new agent.
  • There is no completion deadline. The command ends when the provider reports its end, when the agent exits, on Stop, or on a host crash (the next open settles it as for any turn).
  • Every journal row states which turn it belongs to (turnScope). Desktop and mobile group rows by that, anchored on the message that opened the turn, or on the turn itself when the provider opened it unasked. The live turn is the one actually running, so a background wake's tools stay live and the previous turn keeps its "Worked for". Since fix(native-chat): show the "Working for" bar while a turn runs #23537 moved a running turn's clock from the bottom activity line onto the turn's own bar, the wake's running "Working for" bar draws at the wake's first row and settles there to "Worked for"; a turn opened by a message draws it under that message, as fix(native-chat): show the "Working for" bar while a turn runs #23537 does.
  • A message Claude answers in its own turn after the running one draws after every row the running turn wrote after it, so the earlier turn's answer stays under the earlier turn's bar. fix(native-chat): keep a turn's bar on the prompt that opened it #23573 (a turn's bar stays on the prompt that opened it) and fix(native-chat): group chat rows by the turn that produced them #23671 (rows grouped by the turn that produced them) keep their behaviour on this model: hosts that state turnScope group by it, and fix(native-chat): group chat rows by the turn that produced them #23671's journal-order grouping remains for older hosts that state none.
  • Rows that report how a turn ended (an error, the compaction separator) never fold.
  • The sidebar's prompt, preview, verdict and time, the completion feed and restart resume all read past a command to the last real request. A /compact neither notifies nor re-dates the row.
  • Rewind keeps each retained row's turn and producer, so a subagent's row stays the subagent's after a rewind, and each turn keeps the message that opened it.

Why

The bug class came from one fact being derived from position instead of read from its record: which turn a row belongs to. /compact was the loudest case, but messages sent into a running turn, turns the provider started on its own, and the exit row all hit the same rule. Stating the turn on the row, at the write that creates it, removes the rule instead of guarding each case.

/compact joins the send path because the send path already owns ordering, idempotency, withdrawal on Stop, crash recovery and "not sent" with Retry. The separate command runner duplicated a weaker version of each, which is why it needed the 180 s timer, the late-result repair and a record that blocked every send after a crash.

A command ends the way every turn ends: the provider's translator reads it from the provider's frames, and the agent's exit settles anything left running. The delivery loop keeps no state about the command; it only declines to hand over while the journal shows a command running on a live agent. An earlier revision kept a separate compaction tracker beside the journal, and review kept finding defects in it (a stalled queue when Codex exited, a late Stop cancelling the next compaction, a stopped compaction swallowing the next reply); removing the tracker removed that class.

Alternatives considered:

  • Keep the runner, fix the fold with a rule for status rows. Rejected: it adds a second rule beside the positional one and leaves messages sent into a running turn and provider-started turns wrong.
  • Wait for the command to finish before replying to the RPC. Rejected: with no deadline, mobile's 195 s request timeout would report every long compaction as unconfirmed. Replying at handover is what the reply shape can honestly mean.
  • Keep a deadline. Rejected: Stop always ends the command, so a hung compaction reads "Working" until the user stops it, rather than being guessed at.
  • A command tracker in each provider adapter, correlated per input. Rejected after review: it keeps a second record of "a command is running" that can disagree with the journal.

Persisted fields (decided once)

  • turnScope: {kind: 'turn', turnItemId} | {kind: 'thread'} on the journal row base, lifecycle mutations, dispatch{pending} rows and render items. It names the turn record's journal key, not a provider turn id, so it survives rewinds and provider changes, and it answers membership, anchoring and "belongs to no turn" with one field. Rows stored without it get one on replay from the root turn open when they were created, so no migration is needed.
  • command: {name} on a user message body. The text stays what the user typed; the marker says which command it is, so no reader parses text.
  • providerTurnId on a turn record, written only on a command turn once Codex opens a turn for it. Nothing else can re-derive that claim after the command settles, and rewind needs it to place that turn's rows.
  • Optional turnScope and producer fields on a rewind record's retained rows. Records written before them replay through the same derivation.

Differences from the common pattern

  • Matches: a compaction travels the ordinary send path as the user's message, marked as a command rather than recognised by its text; each row carries the turn it belongs to; a turn with no opening message anchors on itself; Stop interrupts a compaction and never settles it by itself; the command reply returns once the work has started.
  • The command's turn is opened by the delivery loop and ended by the provider's translator. The common pattern opens the compaction's turn inside the provider adapter. Claude opens no turn for /compact, so Orca writes the record at handover; on Codex the provider's turn is claimed into it.
  • Held messages are saved when accepted and placed when handed over. The common pattern keeps them in a separate queue and adds them to the conversation only when sent. Saving them at once keeps them across a restart; placing them at handover gives the same order on screen.
  • Messages held behind a failed compaction are delivered. The common pattern cancels them or leaves them waiting. A user's messages are their intent to talk to the agent, and a failed compaction does not withdraw that intent; the context is simply left as it was.
  • No completion deadline. The common pattern times out after minutes and latches "may still be running". Here Stop always ends the command, so nothing needs to be guessed.
  • Readers skip a command more widely. The common pattern skips a compaction only for the chat's title; here the sidebar preview, verdict, completion notification and restart resume skip it too, because none of them describes the user's work.
  • The fold never hides error or compaction rows. The common pattern hides a compaction only alongside other work; this is stricter.
  • Mobile gets the grouping keys and the held-message placement; its fold behaviour is unchanged in this PR.

Mixed versions

  • New optional fields only: turnScope (row, render item, dispatch row), command (message body), providerTurnId (turn body), rewind-record fields. No new item kind, stream opcode, status value, RPC parameter or capability.
  • Old client, new host: turnScope and command are ignored, so the client groups by position; /compact shows as an ordinary "/compact" bubble with its own rows after it. The command RPC reply now means "started" (an intentional meaning change); an old desktop re-enables its own sends at that point.
  • Clients without accepted-send replies (every mobile build today): a message sent while a command runs is answered "sent" once it is saved and queued behind the command, instead of waiting for the handover (which would outlast mobile's 15 s send timeout). This path is moot once mobile adopts accepted-send.
  • New client, old host: no scope on the wire, so today's positional grouping. The desktop keeps refusing to send while a command is pending when the host states no turn scopes (a legacy branch, removable once those hosts age out); otherwise an old host would refuse each such message as "not sent".
  • An older host opening a newer journal ignores the new fields; an epoch it rebuilds drops them and the newer host derives them again. A newer host opening an older journal derives every row's scope, and an older build's leftover compaction record no longer blocks sends or commands; a replay of that operation id is answered from the ledger without running it again.
  • Codex chats rewound by an older build lost the link from each turn to the message that opened it, and it cannot be recovered. In those chats each turn's work is drawn apart from its message.

Risks

  • Codex could start a turn of its own between the compaction request and the compaction's turn (for example a goal continuation), and it would be claimed as the compaction's. thread/compact/start returns an empty response and turn/started carries no marker that tells a compaction turn apart. The window has never been observed, so no guard is added.
  • A compaction the provider never reports reads "Working" until Stop. Stop always ends it: a second Stop restarts the agent.
  • "Worked for" now counts from the handover for every message, so a message sent while the agent was starting no longer counts the start.
  • Known: on Claude, a message sent mid-turn draws inside the running turn until Claude decides what it is. Claude either folds such a message into the running turn or answers it in a turn of its own afterwards, and Orca only learns which when Claude does one or the other. Until then the message draws inside the running turn, as a folded message would, and the running turn's remaining rows, including its answer while it streams, draw below it under that turn's single bar. The moment the message's own turn opens, it moves below everything the earlier turn wrote, so the earlier answer never ends up under the new message's bar. On main (with fix(native-chat): group chat rows by the turn that produced them #23671), that answer stays under the new message's bar for good.
  • Codex reports a failed turn twice (an error, then a failed turn/completed). This PR makes a failed /compact settle once; the same pattern on ordinary Codex turns is on main today and is fixed separately in fix(native-chat): a failed Codex turn keeps its failure and "Worked for" #23514.
  • A stopped /compact collapses to its "Worked for"; "Cancellation requested." shows when expanded, as for any stopped turn.

Linked Issue

Follow-up to #22944 (turn facts, part B of the plan); no separate issue.

Visual Proof

Live Electron QA ran on a separate Mac with a background-launched development build and a fresh profile per run. Real Claude and Codex where marked; a scripted Claude that reproduces the captured /compact frames for the failure, Stop and exit cases.

Real Claude: /compact has its own row, "Worked for" and separator; the turn before it is untouched, and the sidebar keeps the last real prompt and time.

claude compact

Real Claude, Stop during /compact: it ends stopped, with no error; the next message was then answered in its own turn.

claude stop

Real Claude, a failed /compact ("Not enough messages to compact."): the error sits on that /compact, and the message typed behind it was still delivered and answered.

claude failed compact

Real Codex: one separator and its own "Worked for".

codex compact

A message typed during /compact waits below the live "Compacting the conversation" line...

held while compacting

...and lands after the separator once it is sent, with its own "Worked for".

held message settled

The agent exits mid-/compact: one exit row inside that turn, and the waiting message is delivered to the restarted agent.

exit mid compact

Scripted Claude, Stop during /compact: ends stopped, no error row.

stop scripted

Scripted Claude (the captured frame order), a message sent while a turn runs and answered after it: the first turn's answer stays under the first turn's "Worked for", then the new message, its own bar and its reply.

Q1 settled: A Worked for 37s, FIRST DONE, B, Worked for 12s, B's reply

The same case before Claude opens the new message's turn: the message draws inside the running turn, with the running turn's answer streaming below it under one bar (see Risks).

Q1 before B's turn opens: A's streamed FIRST DONE drawn under B's bubble, A still Working for 30s

Testing

  • I manually tested these changes locally (on the review machine; see Visual Proof)
  • Automated tests added/updated, or explained why not below

Every test below was proven red by removing the code it pins, then restored:

  • Real frames: a captured Claude /compact (a success, then a Stop) is pinned as a fixture. Success needs the compaction boundary; the stopped capture reads as a cancellation with no error row. Ablation: reading the result's own verdict makes the Stop read as a success.
  • The Claude command turn at each place a turn's end is handled: reopen suppression, subagent settle, context settle, the provider fallback, and dropping the command's own frames.
  • Codex: one turn record per command, the claim persisted, the claimed turn's rows scoped to it, one separator, and a Stop before the claim restarting the agent.
  • Stop: a second Stop on a command the provider never answered restarts the agent; a Stop naming an older command ends nothing; after an interrupted Claude /compact the next message gets its own answer; a late result for the first /compact does not end a second.
  • The queue: messages typed during a command wait and are delivered after it, in order, even when it fails; the queue is held only while an agent runs the command, so a crashed agent's leftover command is settled by the next start; every journal commit re-wakes the queue, so none is lost.
  • Exits: a Claude or Codex agent exiting mid-command writes exactly one exit row, scoped to that command's turn.
  • Placement: a held message draws below the live activity while it waits and after the separator once handed over; an ordinary mid-turn message stays put.
  • Mixed versions: a phone send during /compact answers once queued; an older host keeps the desktop's local send block; an older build's compaction record blocks nothing.
  • Grouping and readers: stated scopes, steers, provider-started turns, the live turn, old hosts and no journal; rewind keeping openers and producers; completion feed, sidebar, restart marker and legacy label reading past /compact.

Checks run on the final head: node, web and CLI typechecks; mobile typecheck, tests-typecheck and the touched mobile tests (in a copy with mobile dependencies installed); oxlint; the changed-lines quality gate including React Doctor and the anti-slop audit on this PR's files; the native-chat, Claude, Codex, runtime and renderer suites for the touched areas.

Not run locally: the cross-version wire suite (CI runs it).

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Author X: @BrennanKB5

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

brennanb2025 and others added 30 commits September 24, 2026 23:36
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 <noreply@anthropic.com>
`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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
Co-Authored-By: Claude <noreply@anthropic.com>
…ement

The removed restart handoff test pinned this branch; nothing else did.

Co-Authored-By: Claude <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
…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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
Co-Authored-By: Claude <noreply@anthropic.com>
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.
A journal write and its delivery to open readers were two calls, and some
writers made only the first. A failed start whose lease could not be handed
back, a provider revision with no frame behind it, and eviction's settlement
were all journaled without reaching an open chat.

A journal handle now reports every durable change, and the host's session map
binds that report to the session's readers when the handle is set. Writers no
longer publish what they append; the per-writer publish calls are deleted.
…ackfill cannot supply its rewrite

The seeded record had no surface tab id, so the next open backfilled one and
that rewrite alone made the no-op transaction write. The test passed with the
legacy-lease rewrite signal removed.
The handoff removal deleted it alongside the terminal-owner tests, but it
covers the surfaced-PTY block that still guards resume, including an agent
whose ownership is unknown.
Each commit now delivers itself, so the publish a provider frame still sends
afterwards found every reader caught up but still read rows and rebuilt the
timeline for each one. A caught-up reader now skips the read.
# Conflicts:
#	src/main/native-chat/agent-session-wire/structured-agent-session-subscribers.ts
A send to a chat with no running agent restarted the agent inside the send
call, before the message was recorded, so the client waited for the whole
start and a failed restart refused the message. Claude held prompts sent
during startup, and those could settle as "unconfirmed".

A send is now accepted inside the session's serialized queue: one ledger row
and one submission row marked handoverRecorded, published, answered pending.
A per-session delivery loop exists while a message is queued. It starts the
agent through the same serialized attach a hold uses, waits outside the queue
for a Claude child to prove its start, and hands the oldest queued message
over as its own serialized step, writing dispatch{pending} before the adapter
call. A start it needed and did not get writes one error-tone row and rejects
every queued message with the same words; a start Stop cancelled writes none.

Settlement follows from the rows. A queued message is provably unwritten, so a
close, an eviction or an exit rejects it. A handed-over message stays in doubt.
A queued row at or below the sequence a handle found when it opened was left
by an earlier process and is rejected at open, with no latch. Stop withdraws
queued messages with no writer lease and no fence. An attach failure keeps the
conversation open, and the attach adopts its journal. Owed work counts the
loop and queued rows.

A compaction or rewind found prepared when a conversation opens was started
under a child this process no longer has, so the open settles it rather than
leaving it to refuse every send until a view attaches. The open cursor is
scoped to its epoch, because sequences restart when an epoch is replaced.

Deleted: restart-before-admission, recordFailedRestart, the fence rebase,
Claude's startup gate, the attach's forget on failure and its own crash
boundary. Clients without agent-session.accepted-send.v1 get their reply held
until the handover; the desktop and paired desktop lists advertise it.
A child that proved its start and then exited before its message was handed
over left the message queued: the exit settlement returned early when nothing
else was in flight. Delivery then started another child for it, and a child
that died the same way started another, without end and without a row.

A retried settlement for an earlier generation, run by the attach that
delivery started, did the opposite: with that generation's turn unfinished it
rejected the message queued for the child being attached.

The settlement now takes the rejection for queued messages from its caller.
The unexpected exit and the eviction pass one, and it applies even with no
other work in flight; the retry for an earlier generation passes none.
The crash-turn, stale-turn and sink-queue tests main added wrote rows without a
turn scope, which every item write now states. Rows written inside a running
turn name that turn; the sink-queue batch and a send handed over with no live
turn name the thread.
@greptile-apps

greptile-apps Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 4/5

[High risk] Refactors turn membership and journaling across chat and agent systems.

The PR does not appear safe to merge while existing pre-backfill Codex homes are excluded from account-history bridging.

Findings

  1. P2 Unrelated Claude output can disappear ▶

Summary

The PR records turn ownership on structured-chat journal rows and sends /compact through the ordinary message queue, giving it its own turn and keeping later messages in order. Subsequent changes also adjust transcript grouping, Codex account-history bridging, and related UI and CI behavior.

  • Structured-chat rows and timing now follow turn records on desktop and mobile.
  • A pre-backfill Codex state DB prevents the new history bridge from running.
Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A["User sends /compact"] --> B["Message queue"]
  B --> C["Command turn record"]
  C --> D["Provider frames settle turn"]
  D --> E["Journal rows with turnScope"]
  E --> F["Desktop and mobile transcript"]
  B --> G["Later messages wait"]
  D --> G
  G --> H["Delivery resumes"]
Loading

Reviews (3) · Last reviewed commit: "fix(native-chat): typecheck main's Stop ..."

Comment on lines +63 to +66
message: Record<string, unknown>
): boolean {
if (!command) {
return false

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Unrelated Claude output can disappear

While /compact is open, this check suppresses every root assistant or stream frame without checking which input produced it. The translator then returns before recording the frame. If Claude emits output from an independent background wake during that window, it will be missing from the transcript. Please correlate frames with the command input before suppressing them.

…3700, #22943, #23720, #23793, #23776, #23796) into #23059

#23573 (keep a turn's bar on the prompt that opened it) is ported onto the
turn-record membership instead of kept as a second owner lookup:
- The running turn's bar comes from nativeChatTurnMembership, which now
  returns barTurnKey beside liveTurnKey. Where the host states each row's
  turn they are the same key: the running root turn's anchor, and a
  message handed over mid-turn is already scoped to that turn. Where the
  host states no scope, rows still group by position, so barTurnKey is the
  user entry the running record names (through the same anchors) while
  liveTurnKey keeps the positional live group, as #23573 kept row liveness
  on the newest prompt.
- activeTurnOpenedBy, selectStructuredAgentTurnBars' openedBy and
  selectNativeChatActiveTurnKey are removed; the desktop list, the slot
  builder and both turn-status hooks read barTurnKey.
- The queued-send clock (queuedUntil: a turn counts from the previous
  turn's end when its send waited behind it) is kept, read in the same
  one-pass walk over root turn records that keys timing by anchor.
- Its tests are adapted to pass a journal: each runs on a host that
  states no scope (the original expectations), and the desktop and mobile
  bar tests also run on a scoped host.

#23621 (a message Claude folds into its running turn no longer splits the
turn) is host-only and merged as is: the translator contract carries both
openTurnInLiveProviderCycle and #23059's command-turn members.

Both sides grew the Claude translator past its line budget, so its result
branch moves unchanged into claude-result-journaling.ts, beside
claude-message-journaling.ts (the pre-commit lint refuses the merge
without it).

#23801's Codex child path (no error-driven end) and #23059's Codex /compact
guard (a command turn ends only on turn/completed) both stand.
Brings #23808, which restores the Codex child-turn end on an error Codex
will not retry (the child path has no guaranteed turn/completed), plus a
README badge update. No overlap with #23059's files.

@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 edge case inline.

Reviewed changes (delta since the prior pullfrog review at 436d1771dd)

  • Reconciled onto main's typed failure facts. Two merges (066b4eea78 bringing #23116, acdd559fd9 bringing #23608, #23682, #23456, #23605, #23618, #23702, #23614) move the branch's command/compaction code from string error verdicts to agentSessionFailureFact / agentSessionFailureWords, and the mobile footer's waiting-rows split is extracted into mobile-native-chat-list-footer.tsx. The writer/reader mapping was checked file by file and no verdict, row or rejection was dropped or doubled.
  • A failed start that was carrying /compact now says to run it again. structuredAgentSessionFailureWordsContext can carry any conversation command, derived from the oldest awaited submission, and the /compact RPC reply names it directly (90b68d30d9).
  • A Codex /compact ends only on its turn/completed. The command turn notes when Codex's turn-ending error row has already been written and its end adds no second row; retried stream errors are not counted (7b9fb3f699).
  • Test adaptations. Two commits state turnScope on main's new journal test rows and settle a dead /compact on its recorded exit.

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

/** Codex's `error` frame, already a row in the turn it names. A turn-ending one says why the
* command failed, so the failed completion that follows it adds no second row. */
errorShown(params: unknown): void {
const providerTurnId = readCodexTurnId(params)

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.

A turnId-less error frame leaves failureShown false. The row-writing path resolves the turn as readCodexTurnId(payload) ?? activeTurn(threadId), so during a claimed command turn Codex's own row still lands inside the command's turn — but errorShown reads only readCodexTurnId(params), so end() then adds the command's own Compaction failed… row beside it, exactly the duplicate this commit removes. Mirror the fallback where errorShown is called (readCodexTurnId(event.params) ?? activeTurns.current(event.threadId)), or give it a fallback turn-id parameter.

Technical details
# `errorShown` misses a turnId-less error the row path still journals

## Affected sites
- `src/main/codex/codex-journal-command-turn.ts:149` — `readCodexTurnId(params)` with no active-turn fallback.
- `src/main/codex/codex-structured-journal-generic-frames.ts:82` — the row path resolves `readCodexTurnId(payload) ?? this.activeTurn(threadId)`, so the error row is still journaled and scoped to the command turn.
- `src/main/codex/codex-structured-journal-translation.ts:268-270` — the call site; `activeTurns` is in scope here.
- `src/main/codex/codex-structured-journal-translation-turn-boundaries.ts:74-107` — a claimed command turn is remembered as the active turn, so the fallback resolves to it.

## Required outcome
- A `willRetry:false` error frame that carries no `turnId` but is journaled inside a claimed command turn must set `failureShown`, so `end()` adds no second failure row.

## Suggested approach
- Resolve the turn where the row path does: call `commands.errorShown(readCodexTurnId(event.params) ?? activeTurns.current(event.threadId))`, or give `errorShown` a fallback turn-id parameter.

## Open questions for the human
- Is a `turnId`-less `error` during a command turn reachable in the Codex versions you support? `codex-structured-journal-translation.test.ts:381` pins that exact frame shape for an ordinary turn.

@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 (delta since the prior pullfrog review at 1e6c37ddd4)

  • Reconciled a base sync of two overlapping base PRs. The head advanced through two merges of origin/main (#23573, #23621, #23801 and others, then #23808). #23573's turn-bar fix is ported onto the PR's nativeChatTurnMembership instead of kept as a second owner lookup: the membership now returns barTurnKey beside liveTurnKey, and activeTurnOpenedBy, selectNativeChatActiveTurnKey and selectStructuredAgentTurnBars' openedBy are removed. Where a host states each row's turn the two keys agree; where it states none, the bar follows the running record's named opener while liveness follows position.
  • Kept main's queued-send clock in the PR's timing read. StructuredAgentTurnTiming gains queuedUntil, and the selector is refactored into one pass keyed by anchor and turn id; structuredAgentTurnOrigin and completedStructuredAgentTurnSeconds now count a queued send from the previous turn's end. selectStructuredAgentTurnBars returns {settledTurns, runningTiming}, and both the desktop and mobile timing hooks read it.
  • Desktop and mobile read barTurnKey. The two turn-status hooks, the slot builder's activeTurnKey, and NativeChatMessageList consume it; liveness still follows liveTurnKey, and mobile's private unanchored key folds into the shared constant.
  • The Claude translator contract carries both features. #23621's openTurnInLiveProviderCycle sits beside the PR's command-turn members, and the result branch — which had grown past the file's line budget — moved unchanged into claude-result-journaling.ts. #23801's Codex child path and the PR's Codex /compact guard both stand.

The prior review's one open inline thread (codex-journal-command-turn.ts:149) and the earlier commandBlocked, anchorOf, completion-feed owesWork, and stop-note scoping threads are unchanged by these merges, so they are not re-raised.

Verified locally: the shared turn-bars/timing/membership suites, the desktop transcript-slot and turn-indicator/turn-membership suites, the Claude journal-translation and fold-steer suites, codex-command-turn-claim, and structured-conversation-compaction (the previously-red exit-row case is now green) all pass; tc:web and tc:node are clean.

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

brennanb2025 added a commit that referenced this pull request Sep 29, 2026
# Conflicts:
#	src/renderer/src/components/native-chat/native-chat-transcript-slots.ts
#	src/shared/native-chat-turn-fold.ts
…3745, #23783, #22971, #22565, #22846, #23724, #23721, #23693, #23810) into #23059

#23671 (group chat rows by the turn that produced them) is ported onto
#23059's turn-scope model, so there is one grouping mechanism, not two:

- A host that states each row's turn scope groups by that scope, as
  before. #23671's journal-order derivation (rows between one turn record
  and the next belong to it) moves from the timing selector into
  src/shared/native-chat-turn-grouping.ts and runs only for a host that
  states no scope, replacing the positional fallback there.
- #23671's anchor rules live in structuredAgentTurnAnchors, which
  membership, settled timing and the live clock all read: a turn whose
  opener key nothing resolves yet takes the send still in flight ahead of
  its record (Codex before its echo), else its own record.
- The live turn is one key again. #23671 made row liveness follow the
  owning turn, so the bar key and the liveness key are always the same;
  nativeChatTurnMembership now returns only liveTurnKey (barTurnKey,
  activeTurnOpenedBy and turnKeysByItemId are gone).
- A turn with no user bubble draws its bar above its first row
  (nativeChatTurnBarRows, desktop and mobile), and a turn's diff rollup
  goes under its last row.
- The Codex full-history restore writes each record ahead of its items;
  that also fixes the derived turn scope on #23059's journal.

#23026 (Stop from the moment a message is sent) is ported onto #23059's
command turns: the cancel paths ask the translator for a command's
provider turn instead of the removed compaction tracker, and a Stop that
names no turn still ends a running /compact through its child.
performCancel moved to structured-agent-session-turns-cancel.ts to keep
the turns module under the line limit.

#22090's awaitingInput replaces showTurnStatus/showLiveTurnActivity; the
waiting-behind-/compact rows are kept.
…'s rows

A message sent while A runs is written to the journal when it is sent.
When the provider queues it (Claude answers it after A), A's remaining
rows - its last tool run and its answer - are written after that
message, and the message's own turn opens only after them. Grouping put
those rows in A's turn, but the transcript still drew them in journal
order, below B's bubble and bar, where A's answer read as B's reply. This
is the residual #23671 left open.

A message that opened a turn now draws after the earlier turns' rows the
journal wrote after it, just before its own turn's rows
(nativeChatTurnDrawOrder, returned by nativeChatTurnMembership as
drawOrder). Desktop and mobile both draw in that order. A steer, and a
message that has opened no turn yet, stay where they were written. It
applies on hosts that state turn scopes and, through journal order, on
older ones.
…urns

Two of #23026's tests call APIs #23059 changed, and failed after the
merge:

- codex-structured-conversation-stop: a compaction now goes through
  adapter.compact with the command run the host wrote (#23059), not a
  bare turn id, and answers with the provider's receipt. With the command
  claimed, a Stop that names no turn while the compaction's provider turn
  has not opened still interrupts nothing.
- main-agent-working-agreement: a provider row states its turn scope
  (#23059's appendItem contract); the retry and subagent rows are
  conversation-scoped.
…inst #23059

A Stop's compaction interrupt reads the narrowed requested turn, and the
restore-grouping test states whether each row reports its turn's outcome.

@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

nativeChatTurnDrawOrder, the new reordering this delta adds, leaves a queued opener in place when the earlier turn was provider-opened — the same misattribution it removes for user-opened turns. One reachable shape is affected.

Reviewed changes (delta since the prior pullfrog review at bda9ff153e)

  • Merged origin/main and reconciled it onto the persisted-turn-scope design. The merge brings row grouping by the producing turn, Stop from the moment a message is sent, terminal-backed chat through the structured turn status [#22090], and others; the PR's reconciliation makes main's nativeChatRowTurnKeys/nativeChatTurnBarRows/journal-order grouping the base of nativeChatTurnMembership, drops barTurnKey (the live turn is now also the bar owner), and routes the Codex/Claude cancels through the narrowed requestedTurnId with performCancel split into structured-agent-session-turns-cancel.ts.
  • A message that opened a later turn now draws after the earlier turn's remaining rows, just before its own turn's rows. nativeChatTurnMembership returns a drawOrder from the new nativeChatTurnDrawOrder, computed on both the scoped and no-scope paths; desktop and mobile reorder messages/turnKeys through nativeChatRowsInDrawOrder, and each turn's bar is re-read from the reordered rows.
  • Merged tests and typechecks adapted. #23026's Stop tests call the changed compact/appendItem APIs, and the Claude compaction interrupt reads the narrowed turn id.

Everything else touched by the merge is base-branch content, out of this PR's diff scope. Verified locally at 898daaef: tc:web and tc:node clean, and the grouping/membership, transcript-slot, queued-turn-order, turn-fold, Stop/conversation-stop, compaction, Codex restore-grouping and main-agent-working suites all pass (202 tests).

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

continue
}
// Its own turn's rows, or a later turn's, end the earlier turns' rows it waited behind.
if (turnKey === message.id || (firstRow.get(turnKey) ?? row) > index) {

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.

nativeChatTurnDrawOrder does not move a queued opener when the earlier turn was provider-opened. That turn's anchor is not a message row, so firstRow.get(turnKey) is its first surviving row, which sits after the opener, and firstRow.get(turnKey) > index then misreads the earlier turn as a later one; the opener stays put and the earlier turn's row renders under the opener's bubble — the same misattribution this commit removed for user-opened turns.

Technical details
# Provider-opened earlier turn leaves a queued opener in place

## Affected sites
- `src/shared/native-chat-turn-grouping.ts:111-116,130` — `firstRow` is the first row *in `messages`*, used as a proxy for where the turn opened; for a turn whose anchor has no message row it is the turn's first surviving row.
- `src/shared/native-chat-turn-membership.ts:151,169` — both membership paths pass `anchoring`/`anchoringUserItems`, which contain provider-opened (record-anchored) turn keys with no matching message.
- Consumers inherit the wrong order identically: `src/renderer/src/components/native-chat/native-chat-transcript-slots.ts:155,168-175` and `mobile/src/session/use-mobile-native-chat-turn-disclosure.ts:79-80,130`.

## Reachable shape (a send during a provider-opened wake)
- messages: `B(user)`, `p1(assistant)`, `b1(assistant)`
- journal: `wake` record (`userItemId` = its own item id) → user `B` → `p1` scoped to `wake` → `tB` record (`userItemId: B`) → `b1` scoped to `tB`
- `turnKeys = ['B','wake','B']`, `openers = {'wake','B'}`; `nativeChatTurnDrawOrder` returns `null` (verified with a throwaway test against the pure function).
- Draw order stays `B, p1, b1`: `wake`'s bar (drawn `above`) renders over `p1` immediately below `B`'s bubble, so `p1` reads as `B`'s reply.

## Required outcome
- A queued opener must draw after an earlier turn's rows that the journal wrote after it, whether that earlier turn was opened by a message or by the provider (or its opener is outside the loaded transcript).
- A regression test should pin a provider-opened (or missing-opener) earlier turn; the current `nativeChatTurnDrawOrder` cases only use user-opened earlier turns.

## Suggested approach
- Give the function the earlier turns' journal open order (the membership already holds `journal.items`): order turn keys by their record's position and treat a turn as "earlier" when its record precedes the opener, rather than inferring it from `firstRow`.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Status: ready for review

Head: 898daaef37c. CI is green (23 passed, 12 skipped), and the PR is mergeable. Typecheck is clean for node, web, CLI and mobile, and the mobile test typecheck ratchet passes.

Since the last status

Live QA

Separate Mac, background-launched build of this head, fresh profile with hooks off, scripted Claude replaying the captured frame order. Desktop only.

Queued message. A message sent while a turn runs, and answered after it.

While the second message waits, the only bar is the running turn's:
Q1 while B waits: one running bar under A, B inline after A's first tool row

Before Claude opens the second message's turn, the first turn's answer streams below the message, under one bar. This is disclosed under Risks.
Q1 before B's turn opens: A's streamed FIRST DONE drawn under B's bubble, A still Working for 30s

Once it opens, the first turn's answer moves under the first turn's bar:
Q1 right after B's turn opens: A Worked for 37s with FIRST DONE, then B, then B Working for 2s
Q1 B working: B Working for 10s under B, FIRST DONE stays under A's bar
Q1 settled: A Worked for 37s, FIRST DONE, B, Worked for 12s, B's reply

Fold-in. A message Claude folds into its running turn: one turn, with one bar.
Q2 settled: one Worked for 25s under A, folded B, FIRST DONE banana

Single send.
Q3 settled: one Worked for 0s bar under Say HELLO., then the reply

Not covered

  • Mobile: blocked. The emulator's text input could not enter the pairing code reliably. The mobile rendering tests pass on both host kinds.
  • Real Claude was not used for the queued and fold-in cases. The scripted Claude replays the order of frames captured from the real CLI.

brennanb2025 added a commit that referenced this pull request Sep 29, 2026
Conflicts:
- send preparation: keep #23524's rule (only a committed /clear refuses a send), worded with #23059's typed refusal (reason conversationCleared). The prepared-/clear branch that sent clearUnconfirmed goes, as #23524 already removed it.
- command admission: drop #23059's typed conversationCommandUnconfirmed block for a prepared /clear, which #23524 removed.
- conversation-command test: keep both imports (AgentSessionAcquisitionRefusal from #23059, the idle-sweep constant from #23524).

Outside the conflicts: the admission test now reads the typed refusal, and #23059's send-block test for a prepared /clear becomes the case #23524 lets through.
@brennanb2025
brennanb2025 merged commit d60f999 into main Sep 29, 2026
35 checks passed
brennanb2025 added a commit that referenced this pull request Sep 29, 2026
#23059 landed as a squash identical in content to the branch this PR was built
on (273 files). Merged with #23059's branch tip as the base, so only main's other
changes since then come in.
brennanb2025 added a commit that referenced this pull request Sep 29, 2026
Brings in #23059 (turn facts from the turn record, /compact as a sent
message) and #23026 (Stop from the moment a message is sent), among 23
commits. Conflicts keep main's behaviour on the one shared journal
database: per-chat handle and close tests stay deleted, main's new host
tests open the shared database, and appended rows name their turn scope.
brennanb2025 added a commit that referenced this pull request Sep 29, 2026
#23059 makes /compact a message the chat sends and reads turn facts from the
turn record. The queue follows it:

- /compact is now a queued message and then a turn, not a command holding the
  session's lane for its whole provider call. A capable send during it becomes
  a card held by the ordinary `working` hold, and the drain waits behind the
  compaction's turn like any turn. So the compact side lane
  (structured-conversation-command-lane.ts), draft-only admission, Send-now's
  up-front refusal and the queue gate's `command` hold are gone. Delete, Resume
  and Send-now run on the session's lane, which a compaction no longer holds,
  so they answer at once; Send-now's card is accepted and handed over after the
  compaction, the order every send keeps. A /compact from the command RPC is
  the person's own turn (origin 'client').
- The queue gate's `blocked` hold is now main's send block itself, so a clear in
  doubt, a superseded source and an uncertain rewind hold the queue by one rule.
- Submission folding moved to journal-submission-fold.ts on main; the draft
  link, origin, the latest person's turn and the shared settlement guard are
  carried there. The /clear carry is re-applied to main's clear flow.
- To stay within max-lines, the row writer's cursor-returning append replaces
  the store's appendRow, the open-time draft repair rides the restore, and the
  queue wiring reads the host's mutation context.
brennanb2025 added a commit that referenced this pull request Sep 29, 2026
Main (#23059) gave every roster group the turn it is written beside. This
branch moved group creation into ClaudeSubagentRosterGroups, so a group this
run creates takes the open turn's scope there, and a group inherited from an
earlier run keeps the scope its journaled row was created with, which the
journal reading now carries.
brennanb2025 added a commit that referenced this pull request Oct 1, 2026
…23916 on main) (#24301)

* refactor(native-chat): a stopped child ends on the one reading of its stop

The eviction step reads a stop's result through `stopAgentSessionProviderRoot` and hands that
verdict to the child's ending, so the host never forms a second view of whether the root is gone.
Every ending carries it: a stop's comes from that reading, an exit's root is gone by definition,
and a failed re-attach passes what its release saw. The end-of-child record can therefore also
carry a stop whose root was not seen to go, which nothing ends on yet.

* feat(native-chat): the host says it accepts a send before any agent has it

The host now lists agent-session.accepted-send.v1 among its own runtime capabilities, the same
string capable clients already send. A client can then tell a host that answers a send at
acceptance, and admits a Stop with no writer before a turn starts, from an older one that still
restarts the agent inside the send. Additive: an older client ignores a capability it does not
know.

* refactor(native-chat): an attach never opens a journal of its own

The attach adopts the conversation's open journal, which outlives it, so it no longer opens one
for a direct caller either. That leaves nothing for a failed adopted import to close, and the flag
that told the two cases apart is gone. Tests that attach without a host open the conversation the
way a host does.

* fix(native-chat): a moved fence resends nothing on a host that accepts first

The outbox treated any fence change as a new owner: it dropped the answer of a send in flight,
queued that send to go out again under the same id, and unblocked a refused head. On an older
host that is how a send the restart refused, unrecorded, gets another try. On a host that records
every send before it starts an agent, a fence moves because that start ran, so the same rule
resent into every failed start. With a fence stamped on every frame, that became a loop.

The outbox now reacts to a fence change only when the host has not advertised that it accepts a
send before any agent has it. On such a host, only a Retry or a new send goes out, and a failed
start reaches the client as a rejected message it keeps with its Retry. Against an older host, or
before one has answered, the outbox behaves as it did. Desktop and paired web share this hook.

* refactor(native-chat): a child's end says whether the user or the host stopped it

The end-of-child record's cause now tells a user's Stop from the host stopping the child for a
cause of its own: `user-stop` and `host-stop` replace `stop`. The delivery loop goes on after a
user's Stop, as before, and fails the start it was waiting on after a host stop, with the one
error row and every queued message rejected, in the stop's reason when it gave one. The reason
stays description only. Stop passes `user-stop`; nothing passes `host-stop` yet.

* fix(native-chat): a chat whose only work is a queued message is not offered for resume

A message accepted while the agent was starting counts as working in the chat, and quit rejects it
as never sent. The teardown snapshot read the same working rule, so a relaunch offered to resume a
chat whose agent never had the message. The snapshot now reads only what was handed over.

* fix(native-chat): the conversation outlives its agent

Opening a chat no longer starts its agent. A conversation is reached through one host
accessor that opens its journal at rest, and a send is what starts the agent, through
the delivery loop. One idle sweep, every five minutes, stops an agent that has been
quiet for thirty minutes and owes no work, then drops an open journal handle that is
only a cache. Its record, tab, status row and readers stay.

- hold and release are no-ops; hold still builds the host for shipped mobile builds.
- The holders, the holds, the release clock and the exit respawn are deleted.
- Options, the model list, the goal and the context meter answer at rest; a model pick
  at rest is recorded as intent for the next start.
- Compact, rewind, clear and goal changes start the agent first. A send does too when
  a rewind is still in doubt after the conversation opens.
- Orchestration routes mail and group addresses on ownership (the record plus the chat
  tab), not on whether the process runs. An open dispatch keeps its worker running.
- The restart continuation is a send; Resume all holds each slot until the message is
  handed over or rejected.
- A read error never replaces a loaded transcript, and shows the host's own words.

* test(native-chat): type the queued-message fixtures in the resume-offer tests

* fix(native-chat): a start that dies while a message waits on it is that message's failed start

Opening a chat's tab starts an agent for the view, and a send accepted meanwhile waits on it. When
that start died, its exit wrote the start's error row and left the message queued, so the delivery
loop started a second agent into the same failure and wrote a second row. A child's end now records
where the conversation's journal stood, and the loop settles a message accepted before a failed
start ended with that start: one row, under its key, and no second start. A message sent after the
failure still gets a fresh start.

* fix(native-chat): a request that failed reads as failed

A structured chat whose only message the agent's start refused read as a
green finish, and a cancelled structured turn did too: the host published a
verdict only for turn records, and structured rows carried no `interrupted`.

The host projection now reads the session's latest request: its turn's
outcome, or `failure` for a send the agent or its start refused. A send
that was withdrawn, or left undelivered by a restart or a close, fails
nobody and makes nothing listable. The ingest publishes `interrupted` as the
hook lanes do, and every reader decodes the verdict through one accessor, so
a failure reads Failed on the dot, the rollups, history and `worktree ps`,
behaves like a cancellation in every clean-finish policy, and notifies as
"failed".

* docs(native-chat): say what an attach's open conversation and unconfirmed ids are now

* test(native-chat): a verdict change republishes the mobile status projection

* refactor(native-chat): the store's retention trigger keeps its flag compare

A verdict change always moves the completion clock the same check already
reads, so a second verdict compare there caught nothing new.

* test(native-chat): a user message the provider journaled keeps its session listed

* test(native-chat): pin what a failed start settles, and what a resume offer names

A view's child that dies while a sent message waits settles that message only when it died starting
and no child has taken its place: a proven child's crash, or a second start since, gets the message
delivered. The resume offer names the handed-over message, never a newer one still queued.

* test(native-chat): the failed-start pins fail on what the message became, not on a timeout

* fix(native-chat): a restart offer ends when the chat's agent starts again

The offer used to end only when the chat's newest user message changed,
because opening a chat started its agent and that start could not be told
apart from real activity. Opening a chat starts nothing now, so the host
reads the fact it already publishes: a chat's status row goes from not
host-owned to host-owned exactly when its agent is started. At that edge the
offer and any failure record for the chat are withdrawn, unless the start is
a resume action's own (its continuation is the oldest undelivered message).

A continuation and a message racing to be first are decided at acceptance:
the continuation is refused, quietly and with nothing filed, when any other
message was accepted since the restart. A failed continuation start leaves
the offer retryable, and each resume action sends its own message id.

Deleted: the newest-user-message comparison, its journal reader, the
continuation filter, and the failure ledger's own "answered by the chat"
check. The marker still carries its message id for one release, so the
previous build can read it.

* fix(runtime): end a transcript stream when its client unsubscribes

Desktop: the IPC subscription controller was dropped as soon as the streaming
handler returned, which for most streams is right after it binds. A later
runtime:unsubscribe then found nothing to abort, so the host kept the subscriber
and derived and sent every publish to a channel no one listened to. The controller
now lives until the renderer unsubscribes, resubscribes the same id, or goes away.

Mobile: disposing an agentSession.subscribe stream now sends agentSession.unsubscribe
with the stream's frame id, so the host ends that subscriber and leaves a sibling
stream on the same socket running. The direct path now passes the frame id the relay
path already passed.

* fix(native-chat): a late provider-session update keeps a failed recovery record failed

A provider-session heartbeat that rewrites a completed recovery record kept
its interrupted flag but dropped the outcome it was copied with, so a live
failed checkpoint read as a clean finish until the next status write.

* test(orchestration): the preamble's host stub is typed, not cast

The preamble send now takes only what it reads of the host, the send, the settlement wait and the
record's fence, so its test builds that host with real types instead of `as never`.

* test(native-chat): the terminal-bell check asserts the renamed verdict field

The bell notification test still checked for agentInterrupted, which no
longer exists, so it could not catch a verdict leaking into a bell dispatch.

* fix(native-chat): a failed turn ranks like a completion for attention

Attention readers (completion time, Smart Sort, sticky retention, Cmd+J
Recent) now demote only a turn the user stopped. A failure is news the
user has not seen, so it keeps its completion time, ranks in the Done
class, stays retained after its pane goes away, and a retained failure
reads failed in the worktree rollup instead of done. Clean-finish
policy (hibernation, pane ownership, the value moment) still treats a
failure like a stop.

The retention trigger compares verdicts again: success -> failure no
longer moves the completion clock.

* fix(native-chat): one fact ends a restart offer: the chat moved on since the restart

The offer is live while no other message has been accepted in the chat since the
restart and its agent has not proved a start since. The offer list, the resume's
reservation check and the continuation's acceptance check all read that one fact,
so a message whose start then failed withdraws the offer too, and a stale click
finds nothing to act on.

The fact is read off the conversation's open handle, which the restart closed, so
it is retired durably whenever it may have changed: a message accepted, a start
proven. A close and reopen within the same run therefore cannot bring the offer
back. A continuation rejected before it reached the agent does not count, so a
retry after a failed start still runs.

Deleted: the quit-time gate on withdrawal, which changed nothing because the
withdrawal and the quit's own offer write share one queue; the per-action
"withdrawn" flag and the separate acceptance check it paired with.

* test(native-chat): an older build reads the restart offer this build records

The offer lives in a file the previous release reads after a downgrade. Pin that
against the pinned release's own capsule, and run the lane when the marker or the
capsule changes.

* fix(native-chat): read a restart offer against where the journal stood when it was taken

"Since the restart" was read off the conversation's open handle, which the idle
sweep closes: after a reopen, a message the user had already sent looked older
than the handle and the withdrawn offer came back.

The offer now records the journal position (epoch and sequence) at the moment
it is taken, and a message accepted after that position, or a journal on another
epoch, means the chat moved on. That is derived from the journal, so it holds
across any number of closes and reopens. An older build's offer has no position;
only a start withdraws it. Because the message half is now durable, the offer is
no longer rewritten in the recovery file on every accepted message; a proven
start still writes it, since only the host that saw the start knows of it.

* test(native-chat): wait for the listing's retire write before reading the recovery file

* refactor(native-chat): every journal row states which turn it belongs to

Rows gain a turn scope stated by the write that creates them: the open root
turn, or the conversation. A queued message takes its scope from its handover.
Rows stored before scopes existed are placed on replay by the root turn open
when they were created, so no persisted state is needed for them. Rewind keeps
each retained row's scope and producer, so a subagent's row stays its own.

* fix(native-chat): keep the terminal-backed chat's read error over its local echoes

Messages winning over a read error is right for the structured chat, whose read retries and whose
messages came from the transcript. The terminal-backed view assembles its list from local echoes
too (a launch prompt, a pending send), so a failed read there showed only those bubbles and no
error. Only the structured pane now keeps messages over an error.

* fix(native-chat): a start retries the exit settlement a failed journal write left owed

An agent exit whose journal settlement write failed releases the lease latched until a retry lands.
Reopening the chat used to be that retry; with reveal now only opening the journal, nothing retried
it before the next app launch, and every send was refused. The start the send needs now runs the
retry first, where the attach would.

* fix(native-chat): a failed main agent reads failed while its subagents still work

The verdict is now read from the main agent's own state, not the folded
row: a main agent that is done and failed has a verdict even while its
subagents keep the row working. Without mainAgent (history, worktree ps,
older hosts) the old combined-done rule stands.

Display marks the verdict through agentVerdictDisplayMark: a failure
outranks every combined state on the agent's dot, label, tab badge,
dashboard and activity rows; a stop marks only a done row, so a
successful or stopped main agent with live subagents still reads
working. Subagent rows keep their own state. The worktree card, terminal
tab and Cmd+J rollups share one pane fold and rank a pending question,
then failed, then working, monitoring, interrupted and done.

worktree ps publishes the main agent's outcome on a working row, and the
mobile mirror reads it. The store's change check, the paired-client
mirror's equality and its epoch now see a verdict change on a working
row, which otherwise moves no state or clock and left the worktree card
reading working. Clean-finish policy is unchanged: a working row is never
hibernated and has no completion time.

* perf(native-chat): answer the owner check without opening the chat

Worktree activation calls agentSession.handoffStatus for every chat tab in the worktree, and the
answer comes from the session record alone. Reaching it through the accessor opened each resting
chat's journal (a full read, the crash-boundary write and a restored status publish), then kept it
open for the idle window. It now checks the record and the adapter's support, as before this series,
and opens nothing.

* fix(native-chat): a read waiting on the session lock opens nothing once quit began

The accessor checked for quit before queueing the open, so a read queued behind a session task ran
its open after teardown had begun and indexed a journal no teardown step would close. The check now
runs at the open itself.

* test(native-chat): pin stated turn scopes, the upcast of unscoped rows, and rewind attribution

* fix(native-chat): /compact is a message the chat sends, run as a turn of its own

The conversation command RPC now accepts /compact into the queue like any
send and answers once it is handed over. The delivery loop opens the command's
own turn, starts the provider on it, and waits for the provider's end off the
session's queue, so messages typed meanwhile are held and delivered after it,
even when it fails. It settles by re-reading the journal: a child that died
meanwhile already wrote the verdict. Stop ends the command at once. The 180 s
completion window, the unconfirmed row and the recovery of an older build's
compaction record are gone; that record no longer gates anything. On Codex the
provider turn the command opens is claimed into the command's turn.

* fix(native-chat): read a failed resume's chat before calling it retryable

Whether a failed resume is retryable is the offer's own rule: the chat has not moved on since the
restart, read from its journal. The failure list read it only for a chat already open, so once the
idle sweep closed a chat the user had moved on in, its failure showed Retry again, and the click did
nothing. The list now opens the failed chats first, as the offer list does.

* test(native-chat): type the provider event sink the settlement test reaches for

* docs(native-chat): the worktree ps outcome comment no longer claims old hosts send it

The field is new: an old host sends no outcome at all, so a reader falls
back to interrupted. The removed clause said old hosts send it on done
rows, which never shipped.

* fix(native-chat): say the structured read keeps trying only where it does

The structured pane's "Orca keeps trying to load it" line never showed: the view state filled in an
untranslated fallback whenever the read error had no text, and the empty state prefers any message.
The view state now leaves the message out, so the structured pane shows that line and the
terminal-backed pane its own translated one. Mobile's structured lane does not resubscribe after an
error frame, so it no longer makes the claim.

* fix(native-chat): rows group under the turn their record names, not the one above them

Each row's turn is the turn its stated scope names, anchored on the entry
that opened it, or on the turn itself when the provider opened it unasked.
So /compact groups its own rows and the previous turn is untouched, a message
typed into a running turn joins it, and a provider-resumed turn folds under
its own Worked-for. A row reporting how a turn ended, an error or the
compaction separator, never folds. Desktop and mobile read the same keys; a
host that states no scope keeps today's positional grouping.

* test(native-chat): await the send's settlement instead of polling for the start

The at-rest send tests polled for the provider start with vi.waitFor's one-second default, which a
loaded machine outran. They now await the host's own settlement of the message.

* docs(native-chat): the status-store listing rule names provider-journaled user messages

* fix(native-chat): a restart offer resumes any time after the quit, and knows its own continuations

The continuation's message id was dated by the quit, and the ledger refuses a new id dated more than
a day back, so Resume or Retry a day after quitting was always refused (on main too). It is now
dated by the resume action.

Telling a rejected continuation from the user's own message read the operation ledger, whose rows
expire after about a day; after that a failed resume stopped being retryable. The offer now
records the continuation each action sends on its own capsule entry, bounded to the newest 16, so
the ids end with the offer. The ledger read is deleted.

* fix(native-chat): a /compact is not a request the sidebar, notifications or restart resume report

The sidebar's prompt, preview, verdict and instant, the turn-completion feed,
and the restart-resume marker read past a conversation command and its turn to
the last real request, so a /compact neither notifies nor re-dates the row,
and a command in flight is never offered as work to resume. An older client
shown a command's turn in the legacy form names the session's own agent.

* fix(orchestration): route no mail to a structured worker its orchestration released

A structured worker is routed on ownership, and a resting worker's lease is released, so ownership
held while its chat tab stayed listed. A worker the coordinator abandoned and then released, found
at rest by the release, therefore still took peer mail and @worktree: broadcasts, and each one
restarted its agent. Routing now also reads the orchestration's own resource row: once it is
released, direct mail, group addressing and worker-show's addressable answer drop the worker, as
they would a terminal worker whose terminal closed. The chat tab stays, and nothing new is stored.

* fix(native-chat): a failed retry names the user's prompt, not Orca's continuation

A resume's continuation is written to the chat before its start, so after a failed attempt the chat's
newest user message is that rejected continuation. A second failure then showed Orca's own restart
text as the chat's prompt. A retry now keeps the prompt its first failure named.

* test(native-chat): pin what a conversation command's admission refuses at rest and at handover

* test(native-chat): tests merged from the base state which turn their rows belong to

* fix(native-chat): a refused send notifies failed through the completion feed

The host's completion feed followed only the newest turn, so a send the
agent or its start refused, which creates no turn, read Failed on its row
but sent no notification. The feed now follows the session's latest
request, read from the projection the status feed already makes for the
commit: a turn keeps its id, a refused send is named by its journal item
key. It announces only while the session is idle, as the row reports a
verdict, so queued sends refused one commit at a time notify once, and a
withdrawn send falls back to a request already announced.

* fix(orchestration): read the released row optionally, as the authority does

worker-show's observation called the row lookup directly, which a runtime double without it threw on
and failed the structured tab-retirement release.

* chore(native-chat): one import per module and no unexplained casts in the turn-scope changes

* test(claude): pin which turn a Claude row joins, including a subagent's after the turn ends

* fix(native-chat): the status bar drops a restart offer the chat moved on from

The renderer re-read the host's restart offer only when a failed chat showed activity, so after a
message withdrew a pending offer the host answered no chats while the status bar kept counting one,
and clicking it opened nothing. The same watch now covers pending offers: a status change in an
offered chat asks the host again, once.

* fix(native-chat): a refused steer is read from the turn its handover named

The latest-request reader decided whether a refused send had joined a running turn by comparing
host clocks: its handover time against the previous turn's end. The handover row now states the
turn it delivered into, so the reader reads that instead and the clock comparison goes. A journal
written before handover rows stated a turn is scoped on replay from the turn open when each row
was written, which can differ from the clock reading only when a send and a turn's end share a
millisecond.

* fix(mobile): the native-chat controller contract carries the turn journal

The controller and overlay already pass nativeChatTurnJournal, but the
contract type never declared it, so mobile failed to typecheck.

* fix(native-chat): the live turn is the running turn, not the newest user row

A turn the provider opened on its own (a background wake, a resumed turn)
anchors on its own record, but the list still treated the newest user row
as the live turn. While such a turn ran, the settled user turn before it
lost its duration and the running turn's own rows were drawn as settled,
so its tool calls lost their live state.

nativeChatTurnMembership now answers both questions from the turn record:
each row's turn, and the live turn (the running root turn's anchor, else
the newest user row, which is also all an unscoped host has). Desktop and
mobile key liveness, the timing clock and the live status's row on it.

* test(native-chat): a turn the provider opened keeps its own clock

Pins that the local turn clock follows the live turn, so a wake after a
settled turn does not restart that turn's clock when no host durations
are recorded.

* fix(native-chat): a running turn no message opened draws its status on no row

Its live status belongs to the transcript-tail indicator alone. Once it
settles, its duration draws at its first row as before; a running turn a
message opened still draws on that message.

* fix(native-chat): every copy of a row carries the main agent's own status

History entries, sleep records and `worktree ps` rows carried a flattened
top-level `outcome`, copied under different gates and without the main agent's
clock. They now carry `mainAgent` (state, outcome, stateStartedAt), the type
the live row already persists and sends, and every copy site takes it with
`interrupted` through one function, `agentVerdictFields`.

- The accessor reads `mainAgent` then the legacy flag; the mobile mirror
  matches it line for line.
- Sleep records admit `mainAgent` with `normalizeMainAgentStatusField`, so a
  malformed value drops the field, never the record.
- Mobile dates a main agent that failed under live subagents by its own clock,
  as desktop does, and its row equality compares `mainAgent`.
- The activity feed reads a history entry's own `mainAgent` instead of
  rebuilding one; the sync key and history equality compare it.

* test(native-chat): pin the worktree ps verdict across host and phone versions

Pairs the real v1.4.212 host and phone row reader with this build: an old phone
reads a new host's rows by `interrupted`, a new phone reads an old host's rows
(no `mainAgent`) the same way, and a new phone reads a failure under live
subagents as Failed, dated by `mainAgent.stateStartedAt`. The release checkout
now carries the phone's self-contained row reader, and the lane runs when the
`worktree ps` row producers change.

* test(mobile): name the parity table's row for its role

* test(native-chat): a roster of idle or finished children does not keep an agent awake

The sweep reads owed background work through the shared child-work liveness that upstream's
release clock adopted; a child that went idle or finished is not work the agent still owes.

* fix(native-chat): a request that settles while the user is asked something notifies once

The completion edge waited for an idle session, and a pending prompt (including a
subagent's approval) is not idle. Structured chat has no other attention producer,
so a main turn that finished while a subagent waited on the user sent nothing
until the prompt was answered.

The edge now waits only on owed work (a running turn or an unanswered send), which
the projection reports even beneath a pending prompt. A request that settles with
a prompt pending announces once; the renderer words it "needs input" from the
host status mirror's `attention`, and answering the prompt keeps the same request
identity, so it does not announce again. The wire shape is unchanged.

* fix(orchestration): a task dispatched into a resting structured worker keeps it running

The sweep's open-dispatch check read only the worker-start dispatch that owns the worker's terminal
resource, so a task later dispatched to the same worker (orchestration dispatch --to, which writes a
dispatch with no worker row) did not count: after thirty quiet minutes the worker was stopped while
that task was open, and its coordinator read exited. Any unsettled dispatch addressed to the worker's
process incarnation now counts, derived from the existing rows.

* fix(native-chat): a command's wait ends when its child does

The delivery loop waited for a /compact only on the adapter's compaction
tracker, which learns of the child's end only on some exit paths: a Codex
exit or close, and a Claude close, never reach it. The wait then never
ended, so nothing queued behind the command was delivered again, Stop had
no child to answer through, and the tracker's leftover entry refused the
next /compact.

Every way a child ends passes endProviderChild, so the host now offers a
per-child end signal there. The loop races the tracker against it (the
dead-generation settlement has already written the command's verdict),
and on that end asks every adapter to release the command, so a later
command runs and no later provider turn is claimed into the dead one.
The adapters' own exit-time releases were unreachable (Codex) or covered
one path of several (Claude), and are removed.

The Codex RPC test harness moves to its own module so the exit can be
driven through the real adapter's connection callback.

* fix(native-chat): keep refusing sends during a command on an older host

An older host's controller still refuses a send while a conversation
command runs, so dropping the client's block turned every message typed
during /compact into a 'not sent' row with Retry there. The block stays
for hosts that do not run the command as a send-path turn, and goes only
for those that do.

The signal is one the client already holds: a host that runs /compact on
the send path states a turn scope on every journal row it writes, the
same fact turn membership uses to tell it from an older host. Both now
read it from one predicate. On an empty conversation, or one whose rows
all predate the upgrade, the signal is absent until the command's own
entry streams in, so that brief window keeps the old local refusal; no
capability or wire field is added.

* docs(native-chat): comments stop describing the hold this PR removed

Eight comments still justified orderings and teardown choices by a viewer or dispatch hold that
pinned the provider child. Nothing holds any more; the orderings stand for the binding's redrive
subscription and parked mail, and a chat's agent runs from a send until the idle sweep rests it.
Comment-only.

* fix(native-chat): the completion says when the user is being asked

A request that settles while a prompt waits on the user was worded "needs input"
from the renderer's status-feed mirror. Remote clients receive the status and
completion streams over separate sockets, so they can arrive in either order and
the wording could be wrong both ways.

The host already knows at emit time, so the completion now carries an optional
`awaitingUser: true` in that case and omits it otherwise. The renderer words the
notification from that field alone and no longer reads the status mirror. Old
clients ignore the field and word by outcome; old hosts never send it.

* fix(native-chat): a restart offer keeps the start its own continuation made

Whose start ended an offer was decided at read time, from whether the offer's continuation was
still the queued message. Once the provider refused that continuation, the child it had started
read as someone else's start, so the offer ended and its failure showed no Retry. The delivery
loop now records which queued message a start is for on the in-memory child, and the child's end
carries it; the offer counts a start as its own when that message is one of its continuations.

* fix(native-chat): a rewound turn still names the message that opened it

A Codex rewind rebuilds the epoch without submissions, so each sent message survives only under
its provider key. The kept turn records still named the submission key, so each turn anchored on
itself and its rows grouped apart from the message that opened it. The rewind now renames the
turn's opener along with the message.

* fix(native-chat): Stop ends only the command it names

Stop on a command turn abandoned whatever compaction the session had pending, so a late Stop for
an earlier /compact cancelled the one running now. The tracker now ends a command only when the
Stop names its turn, and the cancel reply reports whether it did.

* fix(native-chat): an agent gets a full idle window after its owed work ends

The sweep measured quiet only from the last journal row, so once a subagent, command, monitor or
dispatch that had outlived the window ended, the agent was stopped at the next tick. A child can
read done before the lead's wake-up turn writes anything, and stopping in that gap loses the
wake-up. The sweep now counts owed work it observes as activity, which gives the agent the full
window afterwards, as the release clock it replaced did.

* test(claude): the options-read fixture runs a live child

The fixture marked its conversation running with a hasProviderChild field the
session type does not have, so the read took the at-rest path and refused a
session with no record. It now carries a child, which is what the read checks.

* test(native-chat): host tests reach its collaborators through a typed seam

The rest-test rig and three test files read the host's private members with
Reflect.get and cast the result. The host now exposes one test-only accessor,
collaboratorsForTests(), and the subscribers class a subscriberCountForTests()
beside its existing retainedActivityCountForTests(), so the tests are checked
against the real types and the casts are gone.

* fix(worktree-status): a departed agent's failure yields to live work on the worktree card

A retained failed agent has no expiry, so ranking it with a live failure pinned the card to Failed over other panes' live work. It now ranks below working, monitoring and permission, and above every finished outcome.

* refactor(orchestration): one owner answers a structured worker's custody

Routing, group addressing, worker-show and the idle sweep each composed their own reading of
whether orchestration still holds a structured worker, so each new obligation or retirement state
had to be added to every reader. structured-worker-custody now derives both answers from the
worker-terminal list state coordinators see in worker-list: addressable is owned and not released,
and owed work is an active custody or an unsettled task dispatched to the same incarnation. The
owner's state is read through the remote dispatch attachment too, as the terminal transfer lookup
already does. Behaviour is unchanged; a settled worker awaiting its coordinator still rests.

* refactor(orchestration): owed work is an open dispatch on the worker's incarnation

A supervised worker's own dispatch context stays open exactly while the worker is active, so the
separate active-custody branch only repeated it. Owed work is now one fact, which also states the
policy that a worker awaiting its coordinator's decision may rest, and both custody decisions are
written once at the top of the module.

* docs(agent-status): a departed agent's failure ranks below live work on the worktree card

* fix(native-chat): a restart offer knows its continuations by a tag in their id

The offer recorded each continuation id in a list on its capsule entry, capped at 16, and a running
action's id in memory. Both could disagree with the journal: past the cap an old rejected
continuation read as the chat moving on, and a crash during a retry restored the failure's older
entry, which lacked the retry's id. Each continuation id now carries a tag derived from the offer
(its teardown and chat), then the action's own part, so any continuation of this offer, queued or
rejected, is recognised from the journal row and the marker alone. The persisted list, its cap and
the in-memory action map are deleted; the agent-start withdrawal keeps an offer whose own
continuation the start was for, read against the stored marker.

* test(runtime): the legacy-worker reveal test judges its stale snapshot inside the wait

The tui-idle probe reads through readTerminal, which now awaits the structured
worker check before the PTY read, so the probe's snapshot request starts a
microtask later. vi.waitFor missed it on its first check and polled again at
50 ms, the same moment the wait's own 50 ms timeout fired. The stale snapshot
then resolved after the wait had already timed out, so the test passed without
judging it, and the rejection landed before any handler was attached. Vitest
reported that as an unhandled error and failed the shard.

Polling every 1 ms sees the request within a few ms, so the snapshot is judged
while the wait is still pending.

* fix(native-chat): a message held behind /compact is drawn where it was handed over

A message typed while /compact runs was drawn above the compaction's result, between
itself and its own answer. The reducer kept every item at the sequence and timestamp of
the row that created it, and a queued message is created at acceptance, long before the
command it waits behind writes its result. The phone orders by that sequence and the
desktop by that timestamp, so both put the message first.

A queued message now takes its position from its handover row, the same row that already
states its turn scope. Everything the agent did before the handover, a command it waited
behind included, draws above it. This holds for every held message, not only /compact's,
and needs no client change: every client, older builds included, reads the position the
host publishes. A live batch already carries the item when its dispatch row lands, and
history pages cut the reduced timeline by sequence, so paging stays contiguous.

* fix(native-chat): a phone's send during /compact answers without waiting out the compaction

A client that predates accepted-send replies, which is every phone build, has its send
reply held until the host hands the message over. A message sent during /compact is not
handed over until the compaction ends, so the phone's 15 s request timeout fired first
and showed the message as unconfirmed.

That wait now also ends once the message is queued behind a running command. This is
read from the journal's running turn and needs no new state. Every other wait still
ends at the handover: behind a starting child or an ordinary turn, and for restart
resume, the command front door and orchestration, which keep the plain handover point.

* perf(native-chat): a rewind places provider items with one pass over the merged rows

A Codex rewind gives each provider item the old epoch never held the turn record for its
provider turn. It found that record by scanning every merged row, restoring each row's
body, once per provider item. That is quadratic, and it runs on the host's main thread
up to the journal's 10,000-row cap, twice per rewind. A rewind record written before
rows carried their scope holds no scope for any provider item, so it paid the full cost.

The merge now indexes turn records by provider turn id once, keeping the first match as
the scan did, and each provider item looks its record up.

* fix(native-chat): a view never restarts a chat whose last start failed

A Claude chat whose CLI exits during startup left one red row per start, and
every time a view bound to it (the chat opening right after its create died,
or the user switching back to it) the hold started the CLI again, so the same
launch-failure row repeated. Only a send retries a failed start now, the same
rule provider-exit recovery already applied; the rule lives in one predicate
the hold, exit recovery and the delivery loop share.

* fix(native-chat): a message waiting behind /compact is drawn after it until it is sent

A message sent while /compact runs is placed where it was handed over. It was still
drawn where it was accepted until then. /compact writes its result one step before the
handover, so for that step the waiting message sat above the compaction's separator.

A message the host accepted but has not handed over is not part of the conversation
yet, so both clients now draw it after everything the agent has done. The shared
projection moves it to the end, which is the order the phone draws. The desktop ranks
it with the other not-yet-sent rows, after the streaming preview. At handover it takes
its place from its handover row, which is also after the separator, so it never
appears above the compaction it waited for.

* fix(native-chat): the idle sweep reads owed work every tick

Owed work counted as activity, but the sweep read it only once the idle window had elapsed, so it
refreshed the clock at most once a window. Work that ended just before the next read left the
agent to be stopped at that read, moments after the work ended, which is the gap the refresh was
meant to cover. The sweep now reads owed work on every tick for a started agent, so the window
always runs from the last tick that saw work owed.

* fix(native-chat): a continuation handed to the agent stays sent

The offer read its own continuation as not reaching the agent while its dispatch was pending, which
also covered one already handed over and still unanswered. When the wait for that answer ended first,
the failure it filed read as retryable, and a retry sent a second continuation to an agent that may
have acted on the first. Only a continuation still queued, or rejected, is now read as unsent.

* test(native-chat): start the child the loop waits on with an attach, not a second view

A view no longer starts a child whose last start failed, so the R2 case that
waits on a child started since the failure now gets that child from a client
attach, the one non-send starter left.

* fix(native-chat): settle a gone generation's turn wherever a conversation opens

A send that opens a chat this process had not read yet (after a crash, from a
phone or the CLI) went through the delivery open, which never settled what the
dead generation left running; only the read restore and a successful acquire
did. When the send's start then failed, the turn stayed running for every
reader. The settlement now runs in the one journal open, at the crash boundary,
for every opener except an acquisition, which settles from the evidence it read
before its reserve; the read restore's separate step is gone.

* test(native-chat): prove the next child's start settles the turn an earlier child left

The R1 case lost its only settlement assertion when the latch it checked was
deleted. It now seeds the running turn the earlier child left and asserts it
ends at the exit's receipt, with the exit's row, before the message is handed
to the new child.

* test(native-chat): count a failed start's rows by row, not by text

Comparing the set of texts passed when two different rows carried the same
words, which is the duplicate the test exists to catch.

* test(cross-version): load the phone row readers without mobile's toolchain

Vite transforms a file against its nearest tsconfig, and mobile/tsconfig.json
extends expo/tsconfig.base.json, which the root-only cross-version lane never
installs. The worktree ps verdict suite imported the current phone row reader
from mobile/ directly, so CI failed with TSConfckParseError before any test ran.

The harness now imports a copy of the working-tree reader placed under the
checkout cache, where the root tsconfig applies, as it already does for the
release checkout's copy. Both readers are still the real files.

* test(cross-version): keep the checkout path-guard message and justify the copy import's cast

* fix(native-chat): a command ends only by its own provider answer or its child's end

Stop no longer settles a conversation command. It interrupts it like any turn,
and when the provider cannot take that (Codex has not opened the command's turn
yet, or Claude refuses the interrupt) it stops the child, whose dead-generation
settlement writes the verdict.

The pending command now lives on the provider child's own session instead of an
adapter-wide map keyed by session, so it dies with the child and nothing has to
release it. Claude's /compact is sent under a uuid the slot records, and only a
root result naming that input (or naming none) ends it; its outcome is read with
the ordinary result reading, so a stopped /compact is a cancellation.

* fix(native-chat): a command's settle answers its message before ending its turn

The two writes are not one batch. Writing the message's answer first means a
crash between them leaves a running command turn, which the stale-turn sweep
already settles, instead of an ended turn whose message reads as in flight
forever. The settle now writes only while the command turn is still running.

* fix(native-chat): "Worked for" counts from the handover, not the send

A message held behind /compact, or behind a cold start, used to count the wait
as the agent's work, although its row is drawn at the handover. Every handed-over
submission's turn, the command's own included, now starts at the handover row's
instant, falling back to the send time for a host that recorded none.

* test(native-chat): give the failed-start and stale-turn waits a loaded runner's budget

* test(native-chat): the interrupted create's own retry continues again

The merge of main's lease-latch fix replaced that test's retry of the interrupted create, under its
own operation id, with a fresh start whose result nothing read. That fresh start passes with the
released-reservation continuation deleted, so the case the fix exists for went untested. The retry
and its assertion are main's again.

* docs(native-chat): three comments that still had views starting agents

A start with nothing queued now comes from a command, goal change or rewind; an interrupted compaction
left alone would refuse every send, so no agent would ever start to finish it; and a current host
raises the unattached read refusal only once quit began, with the attach window belonging to an older
host.

* test(native-chat): pin the open's and the send's start and row counts, however the view binds

Opening a fresh chat whose starts fail makes one start and one row, with two
views bound before or after the create's child died; one send makes one more
of each.

* fix(native-chat): a second Stop on a command ends its child; one compaction verdict for every provider

A Stop's note now names itself in its key, so a later Stop on a command still
running reads, from the journal, that the provider was already asked and never
answered, and stops the child instead of interrupting again. Nothing is held in
memory for it.

Adds the rule both translators will read a compaction's end by: only a
compaction the provider reported is a success; none after Orca's interrupt is a
cancellation; anything else is a failure. A real Claude capture, pinned as a
fixture, is why: a stopped /compact ends in the same success result as a
finished one.

* test(native-chat): a reader's open settles the turn a failed exit settlement left running

An exit whose settlement write failed leaves its turn running in the open journal. PR 1's open now
settles it, and this pins the two reads that reach it here: a reader reopening a chat the idle
sweep closed, and a read that opens the chat before the restart restore reaches it.

* test(native-chat): the view-start test's starting window outlasts two subscriptions on a loaded runner

A subscription reads the conversation before it returns, so under load the two views took longer
than the create child's 300 ms start, which then exited before the test checked that it had not.
The child now takes a second to fail.

* fix(native-chat): settle a gone generation's turn at every open but an acquisition's

The journal open skipped the settlement whenever the lease read reserved or
live, to leave an acquisition's own open to the acquisition. But a lease a
crashed process left in recovery also reads live, until the next acquire
resolves it. A send that opened such a chat, from a phone or the CLI after a
crash on a host that could not prove the old owner gone, skipped the
settlement; when its start then failed, the dead turn stayed running for every
reader. The acquisition now says it is the opener, and every other open
settles, whatever the lease still claims.

* test(native-chat): hold the create's start open until the views bind

The "view binds while the create is still starting" case gave the create a
300 ms head start and asserted the views bound before it died. On a loaded
runner the holds took longer, the create's exit landed first, and the case
failed its own precondition. The create's initialize now waits on a gate the
test releases once the views are bound.

* refactor(native-chat): the provider's translator ends a command's turn; the loop holds no command state

A conversation command is now a turn of the provider child's own journal
pipeline. The adapter-wide tracker, its promise and the loop's settle step are
gone.

- Codex: the translator claims the provider turn that carries the command, scopes
  its rows to the command's turn, and writes the command's end in the same batch
  that settles that turn. Codex's own compaction marker is the success row.
- Claude: the command's turn is the translator's open turn until the result that
  answers the /compact input ends it. The command's own frames, such as the
  continuation summary, its echo and "Compaction canceled.", draw nothing.
- Both read the end with the one compaction rule: success needs the provider's
  report of the compaction; none after Orca's interrupt is a cancellation.
- The message resolves at the provider's receipt, as any send does: the Codex
  ack, or the Claude slash-command waiter on its result. The host writes a
  command's end only when the provider never took it.
- The delivery loop stops while a command's turn runs, and every journal commit
  re-wakes it through the session's serialize, so an end that lands while a step
  decides to stop is never lost. A child that ends first is settled with it.

* test(native-chat): pin a command's end to real /compact frames and to each path it threads

The captured /compact frames drive the Claude translator's command turn: a
finished compaction ends as a success with only the separator drawn; a stopped
one ends as a cancellation with no failure row, and the next send answers in its
own turn; a result naming another input ends nothing. The command's end is
checked at each point the ordinary result path threads through: the reopen latch
after a failure, the settling of a child still working, the context facts the
result reports, and the provider's own error row.

On the host: a message held behind a command is handed over when the command
ends just as the loop stops for it, a refused command settles as a failure and
the loop moves on, and a Claude child that exits mid-command settles the command
and hands what waited to a fresh child.

* test(native-chat): tests merged from the base state which turn their rows belong to

* refactor(native-chat): drop the child-end waiter nothing waits on

A command no longer waits for its child here: its turn ends from the provider's frames or from
that child's settlement, and the delivery loop is woken by the commit. The waiter and its test
were left from the earlier shape.

* fix(native-chat): a command holds the queue only while its child runs it

The delivery loop stopped whenever the journal showed a command's turn running. When the
command's child ended and its settlement could not be written, that turn stayed running with
no child to end it, and the loop's gate kept it from ever starting the next child, which is
what settles a gone generation's leftovers. Every later send was held for good, and Stop had
no child to end.

The gate now holds only while the conversation has a child: with none, the command belongs to
a gone generation, and the loop's start settles it like any turn a dead child left running.

* fix(native-chat): a Claude /compact succeeds only on its compaction boundary

The command's evidence counted Claude's `compact_result: 'success'` status as the compaction
done. That status comes before the boundary that replaces the history, so a Stop landing
between the two read as a finished compaction even though no boundary was ever written. Only
the boundary now counts, as the rule for both providers states; the capture's finished
compaction carries one, so it still reads as a success.

* fix(native-chat): a Claude child's exit says why the turn it ended stopped

When a Claude child exited mid-/compact, the command showed "Worked for 0s" and no reason. The
child's translator ends its open turn the moment the exit is reported, stamped with the exit's
instant, so by the time the exit settlement ran nothing was running. The settlement recognises a
turn the exit already ended by that same instant, but the Claude lifecycle event dropped it on the
way to the host, which then used its own clock, matched nothing, and wrote no row. When the clocks
did agree, the row was scoped to the running turn, of which there was none, so it landed outside
the turn it explained.

The exit's instant now reaches the host, and the exit row belongs to the turn the exit ended:
still running, or ended by the translator at that instant.

* fix(native-chat): a message waiting behind /compact draws below its live activity

A message sent while /compact runs waits on the host until the command ends. Both clients moved
it to the end of the transcript rows, but the running turn's live activity line ("Compacting the
conversation") draws after every row, so the waiting message sat between the command and its own
live status.

A row that is queued, and not what the live turn is for, now draws after that live activity: on
desktop outside the transcript window, below the activity line; on the phone in the list footer,
below the live status. A message whose own start is pending still draws above the activity that
start reports.

* fix(native-chat): only a running command holds a message below its live activity

A message is accepted, then handed over a moment later, and in between it reads as waiting. Every
message waiting behind a live turn drew below that turn's activity line, so an ordinary message
sent while the agent was working crossed below "Thinking" and jumped back up once it was handed
over, on desktop and phone. Only a conversation command's turn holds the queue on the host.

A message now waits below the live activity only while the running turn is one a command opened,
read from the entry that opened it. The phone test also typechecks, which the mobile test ratchet
requires.

* test(codex): the claim test names its notification params as a record

* test(native-chat): a read that reaches a crashed chat before the startup reconcile settles its turn

On desktop the chat on screen at relaunch reads before startup reconciles the leases, while the
dead process's lease still reads live. The open settles the turn it left running anyway, and the
restore that follows finds it settled.

* refactor(native-chat): drop the composer's second error formatter

After the merge with main, every chat write in the composer path reports its
failure as a typed outcome worded by the refusal-notice table, so the send's
catch sees only a local throw. The {code, message} formatter this branch added
for it has no payload left to format, and its claim to be the one way a chat
words a failure is no longer true. The composer send is main's again.

* test(native-chat): pin the reason on a message rejected while its chat was closed

The reopen test checked only that the message reads as not sent; it now also
checks the Retry row carries the host's reason.

* docs(native-chat): drop the removed dispatch hold from six comments

A worker's session no longer takes a dispatch hold, and no release clock
rests a chat by visibility; the agent-launch comments, the abandon test,
the teardown test and the refusal census still said so.

* test(native-chat): rest the owner-status chat through the idle sweep, not a hold

The activation-gate test from #22808 put its chat at rest by holding and
releasing it, and passed the release-clock grace. This branch deleted both,
so the case threw before it reached its assertions. It now moves the host's
clock past the idle window and lets the sweep stop the agent and close the
conversation, then asserts the same owner answer and activation gate.

* fix(native-chat): show the structured pane's retrying line when a read fails

The read transport always hands the pane the host's words, so the error
state's "Orca keeps trying to load it" line, which showed only when there
were none, was never seen: the pane showed the host's text twice, as its
subtitle and on the status line under it. The structured pane now always
says its read keeps retrying, and the host's text stays on the status line.
The terminal-backed chat is unchanged.

* fix(native-chat): a send the provider never received after a restart has no verdict

Restart reconciliation rejects a crash-stranded send that is absent from a
trustworthy provider history with reason 'not_delivered'. Nobody failed that
send, but the verdict allowlist did not name it, so after a crash the chat
read Failed, was listed, and could notify "failed". Give the reason a shared
constant (persisted value unchanged), add it to the no-verdict set, and treat
it as an internal marker so the Retry row no longer shows the raw string.

* fix(native-chat): a failed Codex compaction's late completion writes no turn of its own

Codex ends a failed turn with an error and then still completes it as failed.
The error settled the compaction and released its claim on the provider turn,
so the completion read that turn as an ordinary one and wrote a stray record.
The claim now lasts until the completion, which adds nothing to a command the
error already ended.

* test(native-chat): the mid-command exit case resumes its next child as a real one does

The case's fake started every child as a newly created thread with the same generation. The
store refuses a created link once the conversation has a thread, so the next child's start
failed and wrote its own error row, which landed before or after the case read the journal.
The next child now resumes the thread under its own generation, and the case reads the
journal once the waiting message is delivered, which also proves the loop moved on.

* fix(native-chat): a /clear that never committed no longer locks the chat

A /clear wrote a durable "prepared, outcome unknown" record before starting
the replacement conversation. When that start was refused without a definite
answer (or Orca died), the record stayed forever, and while it did the chat
refused every send, /compact, a new /clear and rewind. Its only exit was a
rerun under the same operation id, which only the renderer held.

The record guarded nothing the process does not already know: a clear in
flight holds the session's serialize for its whole run and the command
controller refuses sends meanwhile, and the replacement's id and start
operation are pure functions of the clear's operation id. So the clear now
writes nothing durable before its commit, the gates refuse only a committed
clear (an older build's prepared record is inert), and a clear with no
committed answer reruns: a same-op retry re-attaches the same replacement,
a new op id runs a fresh clear.

A crash between the replacement's start and the commit leaves a replacement
record nothing points at. Verified: it has no tab, is not in the
replacement list, and a restart opens and starts nothing for it (restore
reads only the visible tab index); restart reconciliation releases its lease
like any dead owner's. In a live process its agent is stopped by the idle
sweep like any quiet agent. Session History lists provider transcripts and
only annotates them with an owner, so it can list this only if the provider
wrote a transcript for a thread that never got a message. Its record stays
on disk, as every closed chat's does; the store deletes none.

* fix(native-chat): a Codex rewind the provider did not keep no longer fails every attach

When Codex acknowledged a revert and Orca stopped before proving it, the
rewind stayed prepared with providerApplied set. On the next attach,
recovery read the provider's history, found the target turn still there
(provider-refused), and threw, because that settlement was limited to
reverts never sent. The throw ran inside the attach, so every attach, and
every send that needs one, failed for good.

The journal is replaced only once the provider proves the revert, so both
the provider and the journal still hold the target turn: settling the
rewind refused is consistent whether or not the provider acknowledged it.

* test(native-chat): a clear retried after a crash starts no second replacement

The replacement's id is the only thing that keeps a retried clear from leaving a second one, and no test held it across a restart.

* chore(native-chat): the clear rerun comment claims only the stable replacement id

* test(native-chat): wait for a send's background start before the refusal oracle removes its store

An accepted send wakes the delivery loop, which starts the agent in the background. The oracle's teardown disposed the loop but did not wait for that start, so its lease write could create a temp file in the store directory while the directory was being removed, failing the test with ENOTEMPTY about one run in four. The teardown now drains tracked starts before it closes the journals.

* fix(native-chat): a start a message waited on gets one failure row, the delivery loop's

When a queued message's start failed, two writers could report it under the same row: the delivery loop, when the adapter settled the start without proving it, and the exit settlement, when the child's exit landed. The last one won, so the chat's row could name a different cause than the one the message was rejected with, or be written twice.

The exit settlement now writes the start's row only when no message is queued and the loop has not already recorded that start. A start for a command, goal change or rewind, with nothing queued, still gets its row from the exit.

* fix(native-chat): a /compact whose start failed says to run /compact again

The failure-words context named only /clear as a command to retry, so a
/compact whose agent failed to start read "Send your message to try again."
on its row, its rejected message and the command reply. The context now
carries any conversation command; the host derives it from the oldest
message still waiting on the provider, which is the one a failed start
fails first, and the /compact reply names it directly.

* fix(native-chat): a Codex /compact ends only on its turn's completion, below Codex's own error row

Since only turn/completed ends a Codex turn, Codex's turn-ending `error` is a row
inside the still-open command turn, and the failed completion that follows it is
the command's end: completed, outcome failure, at the completion's receipt time.
The command's own "Compaction failed" row was written on that completion too, so a
failed /compact read its reason twice.

The command turn now notes when Codex's turn-ending error for the turn it carries
was written as a row, and its end then adds no second row. A retried stream error
ends nothing and is not counted. The flag that let the error end the command and
kept the claim until the completion is gone with the error-driven end.

A test replays the captured failed compaction from the real app-server through a
claimed command turn.

* test(native-chat): main's crash-turn test states its row's turn, and a dead /compact settles on its recorded exit

Two tests the main merge brought together:
- The crash-turn test from #23456 writes a turn record through the event sink
  without options; every row here states its turn scope, and a turn record's is
  the thread.
- The /compact whose exit settlement could not be written no longer stays running
  until the next start: main now settles an open chat from the exit it recorded, so
  the command reads interrupted before the next message, which is then delivered.

* test(native-chat): main's new journal tests state each row's turn

The crash-turn, stale-turn and sink-queue tests main added wrote rows without a
turn scope, which every item write now states. Rows written inside a running
turn name that turn; the sink-queue batch and a send handed over with no live
turn name the thread.

* fix(native-chat): draw a queued turn's message after the earlier turn's rows

A message sent while A runs is written to the journal when it is sent.
When the provider queues it (Claude answers it after A), A's remaining
rows - its last tool run and its answer - are written after that
message, and the message's own turn opens only after them. Grouping put
those rows in A's turn, but the transcript still drew them in journal
order, below B's bubble and bar, where A's answer read as B's reply. This
is the residual #23671 left open.

A message that opened a turn now draws after the earlier turns' rows the
journal wrote after it, just before its own turn's rows
(nativeChatTurnDrawOrder, returned by nativeChatTurnMembership as
drawOrder). Desktop and mobile both draw in that order. A steer, and a
message that has opened no turn yet, stay where they were written. It
applies on hosts that state turn scopes and, through journal order, on
older ones.

* test(native-chat): run #23026's Stop tests against #23059's command turns

Two of #23026's tests call APIs #23059 changed, and failed af…
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