Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(agent-fold): speculative fold and one AgentSession per session (#6518)
Wolf Mermelstein3c8cd4edf9da
diff --git a/apps/web/scripts/agent-fold.test.ts b/apps/web/scripts/agent-fold.test.tsindex b887f53ffc..b5631a43bc 100644--- a/apps/web/scripts/agent-fold.test.ts+++ b/apps/web/scripts/agent-fold.test.ts@@ -20,7 +20,7 @@ beforeAll(async () => {Stream = wasm.FoldStream;}, 300_000);-it('decodes durable DTOs, reconciles overlap, and keeps raw frame consumers', () => {+it('decodes durable DTOs, reconciles overlap, and folds a batch like a stream', () => {const session = '00000000-0000-0000-0000-00000000000a';const chunk = (text: string) => ({direction: 'to_server' as const,@@ -43,32 +43,36 @@ it('decodes durable DTOs, reconciles overlap, and keeps raw frame consumers', ()createdAt: '2026-08-13T00:00:00.000002Z',userId: 'macro|[email protected]',};+ const confirmed = (row: typeof boundary) => ({ kind: 'confirmed' as const, row });const stream = new Stream(session);- const raw = new Stream(session);+ const other = new Stream(session);try {- expect(stream.snapshot([boundary])).toEqual(raw.extend([boundary]));- expect(stream.push_rows([boundary, boundary])).toEqual([]);+ // A snapshot and the same row confirmed derive the same view.+ stream.push([{ kind: 'snapshot', rows: [boundary] }]);+ other.push([{ kind: 'snapshot', rows: [] }]);+ other.push([confirmed(boundary)]);+ expect(stream.messages()).toEqual(other.messages());+ // Rows the snapshot already holds, and rows behind its cursor, change nothing.+ expect(stream.push([confirmed(boundary), confirmed(boundary)])).toEqual([]);expect(- stream.push_rows([- {+ stream.push([+ confirmed({...boundary,id: '00000000-0000-0000-0000-000000000009',createdAt: '2026-08-13T00:00:00.000001Z',- },+ }),])).toEqual([]);+ // A new row folds, and both streams still agree.const live = { ...boundary, id: '00000000-0000-0000-0000-000000000003' };- expect(stream.push_rows([live])).toEqual(raw.push(live));- expect(stream.messages()).toEqual(raw.messages());- // Raw protocol APIs still accept frames with no durable metadata.- raw.snapshot([]);- expect(raw.extend([chunk('raw')])).toHaveLength(1);- expect(raw.push(chunk(' tail'))).not.toEqual([]);- expect(stream.snapshot([])).toEqual([]);- expect(stream.push_rows([boundary])).not.toEqual([]);+ expect(stream.push([confirmed(live)])).toEqual(other.push([confirmed(live)]));+ expect(stream.messages()).toEqual(other.messages());+ // A fresh snapshot resets the committed tier: the boundary folds again.+ expect(stream.push([{ kind: 'snapshot', rows: [] }])).not.toEqual([]);+ expect(stream.push([confirmed(boundary)])).not.toEqual([]);} finally {stream.free();- raw.free();+ other.free();}});@@ -82,17 +86,19 @@ it('preserves replacement events and later updates within one durable batch', ()id: `00000000-0000-0000-0000-${index.toString(16).padStart(12, '0')}`,createdAt: '2026-08-13T00:00:00Z',}));+ const confirmed = (row: (typeof rows)[number]) => ({ kind: 'confirmed' as const, row });const stream = new Stream(session);- const raw = new Stream(session);+ const one = new Stream(session);try {- stream.snapshot(rows.slice(0, 10));- raw.extend(rows.slice(0, 10));- const expected = rows.slice(10).flatMap((row) => raw.push(row));+ stream.push([{ kind: 'snapshot', rows: rows.slice(0, 10) }]);+ one.push([{ kind: 'snapshot', rows: rows.slice(0, 10) }]);+ const expected = rows.slice(10).flatMap((row) => one.push([confirmed(row)]));expect(expected.some((event) => event.kind === 'replace')).toBe(true);- expect(stream.push_rows(rows.slice(5))).toEqual(expected);- expect(stream.messages()).toEqual(raw.messages());+ // Overlap with the snapshot is dropped; the rest folds as if one at a time.+ expect(stream.push(rows.slice(5).map(confirmed))).toEqual(expected);+ expect(stream.messages()).toEqual(one.messages());} finally {stream.free();- raw.free();+ one.free();}});diff --git a/apps/web/src/features/block-agent/CHANNEL_BLOCK_NOTES.md b/apps/web/src/features/block-agent/CHANNEL_BLOCK_NOTES.mdindex 5edc234c48..1283da8a54 100644--- a/apps/web/src/features/block-agent/CHANNEL_BLOCK_NOTES.md+++ b/apps/web/src/features/block-agent/CHANNEL_BLOCK_NOTES.md@@ -267,32 +267,26 @@ messages in a `Scroll` (component/Block.tsx), `AgentInput` with an unwired `onSeand exposes a small handle (`goToLatest`, `getStateSnapshot`, maybe `goToTurn`).2. **The factory decomposition.** Build the stateful surface as `create*` factories withaccessor-in/accessor-out interfaces, composed in the root:- - `createAgentSessionFeed` — the analog of `createFoldedMessages` + `createMessageIndex`:- resource that fetches the log, opens the fold machine, follows live frames, and exposes a- reconciled *ordered* store of folded messages (the block needs an ordered list, not the- channel's `(sessionId, turn, author)` lookup — that shape exists in- `agent-session-stream.ts`'s sink; keep `reconcile()` so streaming appends don't remount rows).- Reuse `beginAgentSessionStream`/`followAgentSession` (or `subscribeAgentSessionLog`) —- the buffering seam and one-machine-per-session refcounting are already solved there;- do NOT refetch-per-frame.- - `createSessionStatusController` — session status / turn-in-flight / streaming signals- (derive from the feed's frames; this is our analog of `threadListScrollState` + typing).- - `createPermissionPrompts` — pending permission requests as a store keyed by request id,- with `respond(id, outcome)`; model it on `createDeleteMessageConfirmation` (a factory that- owns pending state *and* returns the UI component) if prompts render as a dialog, or on- `threadManager` if they render inline per-message.- - `createComposerController` — the busy/enabled state machine: analog of- `channelInputSnapshot`/`channelInputHandle` signals + `onSend` in Channel.tsx:623. Own- `isSending`/`isTurnRunning`, gate `onSend`, and implement **restore-on-error** exactly as- Channel does (restore snapshot only if input is still empty).+ - `createAgentSession` (`context/create-agent-session.ts`) — the Solid face of the+ shared `AgentSession` class (`lib/core/agent-session/AgentSession.ts`): the class owns+ the fold machine, the realtime subscription, the REST calls, and *speculation*; the+ wrapper owns a reconciled ordered store and applies fold events to it. One instance per+ session id, refcounted across the block, the agents view, and the magic chip.+ - There is no status or composer controller. "What is the agent doing" is the fold's+ `metadata.turn` discriminant (`idle | starting | running | stopping | blocked |+ disconnected`), and "is this message still on the wire" is `message.pending`. The+ composer reads both and keeps no state.+ - `createElicitationController` — the live question and the one POST that answers it.+ - `createQueueController` — the server-side action queue, baselined once per socket.3. **Late-bound handles as signals** for anything the child publishes upward (input handle,scroll navigation), with `awaitCondition` in the adapter if orchestrator methods need them.-4. **Optimistic send with nonce-style dedup.** When sending a prompt: append an optimistic- user-turn row to the feed store immediately, key it by a client id, and adopt/replace when- the corresponding frame (or server ack) arrives — the exact pattern of- `optimisticInsertChannelMessage` + `adoptAgentSessionPlaceholder`. The channel's prompt-echo- problem (`hide-duplicate-prompts.ts`, flagged as a stopgap in Channel.tsx:241–250) is the- cautionary tale: decide the dedup key (client nonce in the frame?) up front.+4. **Optimistic send (implemented, in the fold).** `AgentSession.issue` speculates the+ action into the machine before the POST: the machine forks its confirmed state, folds the+ frame the harness will log (built by the same `AgentAction::to_runtime`), and marks the+ derived messages `pending`. The confirmed row promotes it in place by action id (by+ content for a stop), a foreign row rebases the suffix behind it, a failed POST retracts+ it. Nothing is predicted about the runtime's answer: a pending stop reads as `stopping`,+ never as a closed turn. See `crates/agent_fold/src/domain/speculation.rs`.5. **Scroll (implemented)**: reuse `ThreadList` directly, as described in section 5.If history restoration is later added, use its `measurements` snapshot contract,not the retired Virtua cache or a second pinning loop.diff --git a/apps/web/src/features/block-agent/component/AgentComposer.tsx b/apps/web/src/features/block-agent/component/AgentComposer.tsxindex d90ca429ed..95f2c6ae85 100644--- a/apps/web/src/features/block-agent/component/AgentComposer.tsx+++ b/apps/web/src/features/block-agent/component/AgentComposer.tsx@@ -1,13 +1,17 @@/**- * The block's composer container: reads the composer controller from the- * session context and drives the dumb `AgentInput` with derived props. All- * block-level state stays on this side of the boundary.+ * The block's composer container: reads the session from context and drives+ * the dumb `AgentInput` with derived props. Every in-flight state it shows+ * is read off the fold — the turn discriminant and the messages' pending+ * marks — so the composer keeps no state of its own.*/+import { toast } from '@core/component/Toast/Toast';import { useUserId } from '@core/context/user';import { idToDisplayName } from '@core/user/util';+import type { AgentAction } from '@service-agent-harness/generated/schemas';import { type Component, Show } from 'solid-js';import { useAgentSession } from '../context/AgentSessionContext';+import { changingModel, hasPendingStop } from '../state/control-message';import {AgentInput,type AgentInputProps,@@ -30,18 +34,49 @@ export function AgentComposer(props: {const Input = props.input ?? AgentInput;const ModelSelector = props.modelSelector ?? AgentModelSelector;const {- blockedOnUser,- composer,elicitation,+ issue,loadFailed,+ messages,metadata,pending,queue,- resuming,+ sendNext,+ turn,registerQuoteInsert,} = useAgentSession();const userId = useUserId();+ // The fold speculates the action the moment it is issued, so success is+ // observed there; only a refusal needs saying here.+ const act = (action: AgentAction, failure: string) => {+ void issue(action)?.then((result) => {+ if (result.isErr()) toast.failure(failure);+ });+ };++ // A turn is open in some form: the send button becomes a stop square and+ // prompts sent now wait in the server queue behind it. A stop the fold has+ // speculated already reads as done - the button goes back to send with the+ // rest of the transcript, and the log confirms the end of the turn later.+ const busy = () => {+ const state = turn();+ return (+ (state !== 'idle' && state !== 'disconnected' && state !== 'stopping') ||+ resuming()+ );+ };+ // The runtime is gone and the user has asked it for something anyway, so+ // the service is bringing its sandbox back before it can deliver. There is+ // no signal for this on the wire; it is the one honest inference from a+ // disconnected runtime and a pending action of ours. The wake is a turn in+ // all but name, so it can be stopped - and a pending stop ends it here as+ // it does everywhere else, before the log says so.+ const resuming = () =>+ turn() === 'disconnected' &&+ messages().some((message) => message.pending) &&+ !hasPendingStop(messages());+// Focus plumbing between the input and the queue list above it: Up at the// start of the input lands on the bottom (next-to-dispatch) queue row, and// Down past that row comes back. Plain variables, read only at call time.@@ -81,7 +116,7 @@ export function AgentComposer(props: {<Show when={resuming()}><ComposerNotice text="Waking the agent's sandbox…" active /></Show>- <Show when={blockedOnUser()}>+ <Show when={turn() === 'blocked'}><ComposerNoticetext={elicitation.canAnswer()@@ -93,15 +128,24 @@ export function AgentComposer(props: {<Inputplaceholder="Message the agent, @mention anything"autofocus={props.autofocus}- busy={composer.busy()}+ busy={busy()}hasQueuedMessages={queuedItems().length > 0}+ // The fold's own answer to "a stop is already working on this turn",+ // which holds from the moment the stop is folded until the turn+ // actually ends. `pending` alone clears as soon as the log confirms+ // the cancel, which is well before the runtime winds the turn down -+ // and every Enter in that gap posted another cancel.+ stopPending={turn() === 'stopping'}// Prompts go straight to the service, so sending needs a session to// post to — a block whose create is still on the wire can be typed// into, but not sent from, until the id lands.disabled={loadFailed() || pending()}commands={() => metadata()?.availableCommands ?? []}- onSend={composer.send}- onStop={composer.stop}+ onSend={(prompt) =>+ act({ type: 'prompt', prompt }, 'The message could not be sent')+ }+ onStop={() => act({ type: 'stop' }, 'The agent could not be stopped')}+ onSendNext={sendNext}// Installed only while a queue row exists to land on: an installed// handler claims the keys (Up, and the shared plugin's other// leave-at-start keys), which must keep their defaults when there is@@ -116,10 +160,12 @@ export function AgentComposer(props: {modelControl={<ModelSelectormodel={metadata()?.model ?? null}- changingTo={composer.changingModel()}+ changingTo={changingModel(messages(), metadata()?.model ?? null)}options={metadata()?.supportedModels ?? []}disabled={loadFailed()}- onSelect={composer.setModel}+ onSelect={(model) =>+ act({ type: 'setModel', model }, 'The model could not be changed')+ }/>}/>diff --git a/apps/web/src/features/block-agent/component/AgentMessage.test.tsx b/apps/web/src/features/block-agent/component/AgentMessage.test.tsxindex 5f8102287c..a07bc98bfa 100644--- a/apps/web/src/features/block-agent/component/AgentMessage.test.tsx+++ b/apps/web/src/features/block-agent/component/AgentMessage.test.tsx@@ -50,7 +50,9 @@ vi.mock('../ui', () => ({{props.text}</div>),- WorkingLine: () => <div data-testid="working" />,+ WorkingLine: (props: { label?: string }) => (+ <div data-testid="working">{props.label}</div>+ ),ActionLine: (props: { label: string }) => <div>{props.label}</div>,ToolGroup: (props: {count: number;@@ -95,6 +97,7 @@ const message = (): FoldedMessage => ({agentSessionId: 'session',requestId: null,+ pending: false,turn: 0,author: { kind: 'agent' },parts,@@ -233,6 +236,18 @@ describe('Message tool grouping', () => {});});+describe('Message working tail', () => {+ it('names the work after the last part of an open turn', () => {+ const view = render(() => (+ <Message+ message={message([text('Looking.'), tool('a')], null)}+ inFlight+ />+ ));+ expect(view.getByTestId('working').textContent).toBe('Running tools');+ });+});+describe('Message thought shimmer', () => {const thought = (value: string): MessagePart => ({kind: 'thought',diff --git a/apps/web/src/features/block-agent/component/AgentMessage.tsx b/apps/web/src/features/block-agent/component/AgentMessage.tsxindex f3a03e7e8b..526494b3e5 100644--- a/apps/web/src/features/block-agent/component/AgentMessage.tsx+++ b/apps/web/src/features/block-agent/component/AgentMessage.tsx@@ -145,6 +145,19 @@ function showsWorkingLine(message: FoldedMessage): boolean {.otherwise(() => true);}+/**+ * What the working row says: the last part names the work — a tool call or+ * a plan — and a bare turn is just working.+ */+function workingLabel(message: FoldedMessage): string {+ const last = message.parts.at(-1);+ if (last === undefined) return 'Working';+ return match(last)+ .with({ kind: 'tool_use' }, () => 'Running tools')+ .with({ kind: 'plan' }, () => 'Planning')+ .otherwise(() => 'Working');+}+/*** A prompt, in the chat block's user-bubble treatment* (`@core/component/AI/component/message/UserMessage.tsx`): right-aligned,@@ -153,7 +166,11 @@ function showsWorkingLine(message: FoldedMessage): boolean {function UserMessage(props: { message: FoldedMessage }) {return (<div- class="flex w-full"+ class="flex w-full transition-opacity"+ // Still on the wire: the fold shows the prompt before the log confirms+ // it, and the confirmation clears this in place.+ classList={{ 'opacity-60': props.message.pending }}+ aria-busy={props.message.pending || undefined}ref={(el) =>messageSendMotion(el, () =>props.message.requestId@@ -225,10 +242,10 @@ export function Message(props: {</Show>)}</Index>- {/* The turn is open with nothing to read yet — a dot and a rotating- verb, so the wait reads as work rather than as a stall. */}+ {/* The turn is open with nothing to read yet — a ripple and a label+ naming the work, so the wait reads as work rather than a stall. */}<Show when={inFlight() && showsWorkingLine(props.message)}>- <WorkingLine />+ <WorkingLine label={workingLabel(props.message)} /></Show>{/* A turn the runtime errored is something that happened to thesession, like a model change or a stop — so it reads as one,diff --git a/apps/web/src/features/block-agent/component/Transcript.test.tsx b/apps/web/src/features/block-agent/component/Transcript.test.tsxindex cffb384a78..243db52805 100644--- a/apps/web/src/features/block-agent/component/Transcript.test.tsx+++ b/apps/web/src/features/block-agent/component/Transcript.test.tsx@@ -1,4 +1,7 @@-import type { FoldedMessage } from '@service-agent-fold/generated/types';+import type {+ FoldedMessage,+ TurnState,+} from '@service-agent-fold/generated/types';import { cleanup, render } from '@solidjs/testing-library';import { createSignal } from 'solid-js';import { createStore, reconcile } from 'solid-js/store';@@ -8,8 +11,8 @@ import { Transcript } from './Transcript';const session = vi.hoisted(() => ({sessionId: () => 'session',+ turn: (): TurnState => 'idle',messages: () => [] as FoldedMessage[],- working: (): boolean => false,quoteSelection: vi.fn(),touch: false,top: () => 40,@@ -97,7 +100,7 @@ beforeEach(() => {viewport = 400;rowHeight = 96;session.touch = false;- session.working = () => false;+ session.turn = () => 'idle';session.bottom = () => 80;vi.stubGlobal('ResizeObserver',@@ -191,8 +194,8 @@ describe('Transcript live turn', () => {it('marks only the newest turn live, however many messages lack a stop', async () => {// Every one of these reads `stop: null`; a superseded turn keeps it.- const [working, setWorking] = createSignal(true);- session.working = working;+ const [turn, setTurn] = createSignal<TurnState>('running');+ session.turn = turn;const view = mount([message(0), message(1), message(2)]);await settle();expect(inFlight(view)).toEqual([@@ -202,7 +205,7 @@ describe('Transcript live turn', () => {]);// The runtime went away: the block stops working, and so does the tail.- setWorking(false);+ setTurn('disconnected');await settle();expect(inFlight(view)).toEqual(['0:agent=false',@@ -212,7 +215,7 @@ describe('Transcript live turn', () => {});it('marks nothing live while the newest turn is a prompt awaiting its reply', async () => {- session.working = () => true;+ session.turn = () => 'running';const view = mount([message(0),{ ...message(1), author: { kind: 'user', userId: 'u' } } as FoldedMessage,diff --git a/apps/web/src/features/block-agent/component/Transcript.tsx b/apps/web/src/features/block-agent/component/Transcript.tsxindex e1ff4dd24e..2d469f0967 100644--- a/apps/web/src/features/block-agent/component/Transcript.tsx+++ b/apps/web/src/features/block-agent/component/Transcript.tsx@@ -16,17 +16,25 @@ import {onCleanup,Show,} from 'solid-js';+import { match } from 'ts-pattern';import { useAgentSession } from '../context/AgentSessionContext';import type { AgentMessageTarget } from '../core/search-location';import { isLiveTurn, liveTurnMessage } from '../state/live-turn';+import { WorkingLine } from '../ui/WorkingLine';import { Message } from './AgentMessage';import { ReplyToSelection } from './ReplyToSelection';export function Transcript(props: { searchTarget?: AgentMessageTarget }) {- const { messages, quoteSelection, sessionId, working } = useAgentSession();- // At most one turn runs, and the block's `working` is the one word on- // whether it does — so which message shimmers is decided here, once, not- // by each message from its own `stop` (see `state/live-turn`).+ const { messages, quoteSelection, sessionId, turn } = useAgentSession();+ // At most one turn runs, and the fold's `turn` is the one word on whether+ // it does - so which message shimmers is decided here, once, not by each+ // message from its own `stop` (see `state/live-turn`). A speculated stop+ // reads as `stopping`, which settles the live message before the log+ // closes it.+ const working = () => {+ const state = turn();+ return state === 'starting' || state === 'running' || state === 'blocked';+ };const liveTurn = () => liveTurnMessage(messages(), working());const initialTarget = props.searchTarget;const initialSessionId = sessionId();@@ -46,7 +54,26 @@ export function Transcript(props: { searchTarget?: AgentMessageTarget }) {])));- const keys = createMemo(() => [...messageById().keys()]);+ // The turn is open and the agent has said nothing yet: the newest message+ // is the user's, so no agent row exists to carry the working line. One+ // extra row at the tail says the wait is work, not a stall - a prompt still+ // on the wire (`starting`) included.+ const workingKey = () => `${sessionId() ?? ''}:working`;+ const showsWorking = createMemo(() => {+ const state = turn();+ if (state !== 'starting' && state !== 'running') return false;+ const last = messages().at(-1);+ return last?.author.kind === 'user';+ });+ // What the wait is: the prompt still on the wire, or the agent at work.+ const workingLabel = () =>+ match(turn())+ .with('starting', () => 'Sending')+ .otherwise(() => 'Working');+ const keys = createMemo(() => [+ ...messageById().keys(),+ ...(showsWorking() ? [workingKey()] : []),+ ]);let positionedTarget: AgentMessageTarget | undefined;// Navigation is an external effect. Wait for both log hydration and the// virtual list's layout; subsequent live folds must not repeat the jump.@@ -112,19 +139,30 @@ export function Transcript(props: { searchTarget?: AgentMessageTarget }) {onScroll={(state) => setScrollState(state)}>{({ id }) => (- <Show when={messageById().get(id)}>- {(message) => (- <div- class="macro-message-width mx-auto px-4 pb-4 min-w-0 rounded-lg"- classList={{ 'bg-accent/10': highlightedId() === id }}- data-search-target={highlightedId() === id ? 'true' : undefined}- >- <Message- message={message()}- inFlight={isLiveTurn(message(), liveTurn())}- />+ <Show+ when={id !== workingKey()}+ fallback={+ <div class="macro-message-width mx-auto px-4 pb-4 min-w-0">+ <WorkingLine label={workingLabel()} /></div>- )}+ }+ >+ <Show when={messageById().get(id)}>+ {(message) => (+ <div+ class="macro-message-width mx-auto px-4 pb-4 min-w-0 rounded-lg"+ classList={{ 'bg-accent/10': highlightedId() === id }}+ data-search-target={+ highlightedId() === id ? 'true' : undefined+ }+ >+ <Message+ message={message()}+ inFlight={isLiveTurn(message(), liveTurn())}+ />+ </div>+ )}+ </Show></Show>)}</ThreadList>diff --git a/apps/web/src/features/block-agent/component/parts/ControlPart.test.tsx b/apps/web/src/features/block-agent/component/parts/ControlPart.test.tsxindex b71aa7a0b8..cc72d4c736 100644--- a/apps/web/src/features/block-agent/component/parts/ControlPart.test.tsx+++ b/apps/web/src/features/block-agent/component/parts/ControlPart.test.tsx@@ -45,9 +45,9 @@ const failedOf = (part: Control) => {};describe('a model change', () => {- it('reads as done only once it is accepted', () => {- expect(lineOf(setModel({ kind: 'pending' }))).toContain(- 'Setting model to openai/gpt-5'+ it('reads as done the moment it is issued', () => {+ expect(lineOf(setModel({ kind: 'pending' }))).toBe(+ 'Model set to openai/gpt-5');expect(lineOf(setModel({ kind: 'accepted' }))).toBe('Model set to openai/gpt-5'diff --git a/apps/web/src/features/block-agent/component/parts/ControlPart.tsx b/apps/web/src/features/block-agent/component/parts/ControlPart.tsxindex cda2497007..2b27eee043 100644--- a/apps/web/src/features/block-agent/component/parts/ControlPart.tsx+++ b/apps/web/src/features/block-agent/component/parts/ControlPart.tsx@@ -1,16 +1,16 @@/*** A control the user issued mid-session: model switch, compaction, stop.*- * The outcome is half the message. A runtime that refuses a control answers+ * A rejection is half the message. A runtime that refuses a control answers* with a JSON-RPC error the fold records as `rejected` — most often a model- * the harness advertised but cannot actually run — and a line that read- * "Model set to X" either way would be reporting a change that never- * happened. So each control names all three states, and a rejection carries- * the runtime's own words.+ * the harness advertised but cannot actually run — and that line has to say+ * so, carrying the runtime's own words. Everything short of a rejection+ * reads as done: the fold speculates the control, so naming a separate+ * in-progress state would only make the switch look slower than it is.*/import type { MessagePart } from '@service-agent-fold/generated/types';-import { match } from 'ts-pattern';+import { match, P } from 'ts-pattern';import { ActionLine } from '../../ui';type ControlPartData = Extract<MessagePart, { kind: 'control' }>;@@ -19,12 +19,10 @@ type ControlPartData = Extract<MessagePart, { kind: 'control' }>;function label(part: ControlPartData): string {return (match([part.control, part.outcome] as const)+ // A model switch reads as done the instant it is issued; only a+ // runtime refusal, after the fact, reads differently..with(- [{ kind: 'set_model' }, { kind: 'pending' }],- ([control]) => `Setting model to ${control.model}…`- )- .with(- [{ kind: 'set_model' }, { kind: 'accepted' }],+ [{ kind: 'set_model' }, { kind: P.union('pending', 'accepted') }],([control]) => `Model set to ${control.model}`).with(diff --git a/apps/web/src/features/block-agent/component/parts/ElicitationPart.test.tsx b/apps/web/src/features/block-agent/component/parts/ElicitationPart.test.tsxindex e14e204955..94c821b4b6 100644--- a/apps/web/src/features/block-agent/component/parts/ElicitationPart.test.tsx+++ b/apps/web/src/features/block-agent/component/parts/ElicitationPart.test.tsx@@ -25,7 +25,6 @@ vi.mock('../../context/AgentSessionContext', () => ({elicitation: {pending: () => pending,canAnswer: () => canAnswer,- answering: () => false,respond,},}),diff --git a/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsx b/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsxindex 1d481185cc..60ac52dc08 100644--- a/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsx+++ b/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsx@@ -61,9 +61,10 @@ export function ElicitationPart(props: { part: ElicitationPartData }) {elicitation.pending()?.requestId === props.part.requestId;const agentName = () => bot()?.name ?? 'The agent';- // Controls are inert while an answer is on the wire and for anyone- // without edit access.- const locked = () => elicitation.answering() || !elicitation.canAnswer();+ // Controls are inert for anyone without edit access. An answer in flight+ // needs no lock of its own: the fold speculates it, so the card has+ // already left its live state by the time the POST lands.+ const locked = () => !elicitation.canAnswer();const waitingFor = () =>elicitation.canAnswer() ? 'Waiting for you' : 'Waiting for an editor';@@ -142,7 +143,6 @@ function LiveUserTool(props: {fallback={fallback}review={{canAnswer: elicitation.canAnswer,- answering: elicitation.answering,respond: props.onRespond,}}/>diff --git a/apps/web/src/features/block-agent/component/parts/LiveElicitation.tsx b/apps/web/src/features/block-agent/component/parts/LiveElicitation.tsxindex cc87ba610f..c89b55a7fd 100644--- a/apps/web/src/features/block-agent/component/parts/LiveElicitation.tsx+++ b/apps/web/src/features/block-agent/component/parts/LiveElicitation.tsx@@ -351,7 +351,7 @@ export function UserToolComposer(props: {fallback?: JSX.Element;}) {const sink = <T,>() => createElicitationReviewSink<T>(props.review);- const locked = () => !props.review.canAnswer() || props.review.answering();+ const locked = () => !props.review.canAnswer();return (<Switch fallback={props.fallback}><Match when={props.tool.name === 'CreateCalendarEvent'}>diff --git a/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx b/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsxindex 88edffee1d..9d121223b9 100644--- a/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx+++ b/apps/web/src/features/block-agent/component/sidepanel/AgentSidePanelSections.tsx@@ -16,6 +16,7 @@ import { openExternalUrl } from '@core/util/url';import GitBranch from '@phosphor/git-branch.svg';import { createMemo, For, Show } from 'solid-js';import { useAgentSession } from '../../context/AgentSessionContext';+import { sessionStatus } from '../../state/session-status';import {activityCounts,changedFiles,@@ -31,7 +32,7 @@ import { AgentPullRequestChip } from '../AgentPullRequestChip';import { harnessTitle } from '../AgentSplitHeader';export function AgentSidePanelSections() {- const { session, bot, metadata, messages, status } = useAgentSession();+ const { session, bot, metadata, messages } = useAgentSession();const plan = createMemo(() => latestPlan(messages()));const files = createMemo(() => changedFiles(messages()));@@ -46,7 +47,7 @@ export function AgentSidePanelSections() {<SidePanel.Section id="details" title="Details" defaultOpen order={10}><SidePanel.Grid><SidePanel.Row label="Status">- <SessionStatusPill status={status()} />+ <SessionStatusPill status={sessionStatus(metadata())} /></SidePanel.Row><Show when={bot()?.name}>{(name) => (diff --git a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx b/apps/web/src/features/block-agent/context/AgentSessionContext.tsxindex 8212715bb1..f97e6404ee 100644--- a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx+++ b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx@@ -1,22 +1,29 @@import { isCodexBotId } from '@core/constant/codexAgent';+/*** Block-level state for the agent block, following the chat block's* `ChatInputProvider`/`useChatInputContext` convention: the provider owns the- * session data and controllers, composer/container components consume them+ * session and its controllers, composer/container components consume them* from context, and the `ui/` leaves stay dumb — they only ever receive* derived props.*- * The value is assembled from `create*` factories (CHANNEL_BLOCK_NOTES.md §3)- * so each stateful concern stays a composable unit as wiring grows.+ * The session itself is `createAgentSession`, the Solid face of the shared+ * `AgentSession` class: one machine per session, speculation inside it, so+ * everything about "what is the agent doing" is read off the fold's+ * `metadata.turn` and the messages' `pending` marks rather than kept here.*/+import type { IssueResult } from '@core/agent-session/AgentSession';import { isCursorBotId } from '@core/constant/cursorAgent';+import { useUserId } from '@core/context/user';import { useAgentSessionExternalUrlQuery } from '@queries/agent-session/session';import type {FoldedMessage,SessionMetadata,+ TurnState,} from '@service-agent-fold/generated/types';import type {+ AgentAction,AgentSessionResponse,SessionBot,} from '@service-agent-harness/generated/schemas';@@ -28,13 +35,8 @@ import {Suspense,useContext,} from 'solid-js';-import { controlOutcome } from '../state/control-message';import type { QuoteInsert } from '../ui';-import { createAgentSessionFeed } from './create-agent-session-feed';-import {- type ComposerController,- createComposerController,-} from './create-composer-controller';+import { createAgentSession } from './create-agent-session';import {createElicitationController,type ElicitationController,@@ -43,11 +45,6 @@ import {createQueueController,type QueueController,} from './create-queue-controller';-import {- createSessionStatusController,- isDisconnected,- type SessionStatus,-} from './create-session-status-controller';import { resolveSessionId } from './resolve-session-id';export type AgentSessionState = {@@ -64,7 +61,7 @@ export type AgentSessionState = {session: Accessor<AgentSessionResponse | undefined>;/** The bot the session runs as, absent until the fold is acquired. */bot: Accessor<SessionBot | undefined>;- /** The fold's session metadata (title, model, …), followed live. */+ /** The fold's session metadata (title, model, turn, …), followed live. */metadata: Accessor<SessionMetadata | undefined>;/** The folded transcript, ordered by turn, live-following the session. */messages: Accessor<FoldedMessage[]>;@@ -77,33 +74,27 @@ export type AgentSessionState = {/** Re-runs a failed load. */retryLoad: () => void;/**- * The block's one answer to "is the agent working": the fold's- * turn-in-flight signal, cut off when the runtime is known to be gone.- * Every consumer — composer, shimmer, header — reads this, never- * `feed.working` or `status` directly, so the block cannot disagree with- * itself about whether a turn is running.+ * Where the newest turn stands, as the fold reports it: the block's one+ * answer to "what is the agent doing". Every consumer — composer, working+ * line, chrome — reads this discriminant, never the transcript's tail or+ * its own record of what it posted, so the block cannot disagree with+ * itself. `idle` until the fold has loaded.*/- working: Accessor<boolean>;- /** The runtime's status: the GET snapshot, followed live over the log. */- status: Accessor<SessionStatus>;+ turn: Accessor<TurnState>;/**- * The runtime is gone and the user has asked it for something anyway, so- * the service is bringing its sandbox back before it can deliver.- *- * There is no signal for this on the wire: the resume happens inside the- * service, and the session log stays silent until the container answers.- * It is inferred instead, from the one thing the block does know — the- * runtime was disconnected, and a request it must wait on is outstanding.+ * Do something to the agent: prompt, stop, change model. The fold shows+ * the action at once and the log settles it. `undefined` while the block+ * has no session to act on.*/- resuming: Accessor<boolean>;+ issue: (action: AgentAction) => Promise<IssueResult> | undefined;/**- * The agent is mid-turn but waiting on the user, not generating: the- * fold's metadata names a question to answer. Presentational only -- * `working` stays true so queued prompts keep waiting behind the question.+ * Send the next queued message now: stop the running turn, and show the+ * queue head as sent under the id the server already holds it by. The+ * server dispatches it when the turn actually ends, and that row promotes+ * the speculation in place. No-op with nothing queued.*/- blockedOnUser: Accessor<boolean>;- composer: ComposerController;- /** The live question, and the one POST that answers it. */+ sendNext: () => void;+ /** The live question, and the action that answers it. */elicitation: ElicitationController;/*** The session's server-side action queue: prompts sent mid-turn wait@@ -139,35 +130,47 @@ export function AgentSessionProvider(if (id && id !== props.blockId) props.onSessionId?.(id);});- const feed = createAgentSessionFeed(sessionId);- const status = createSessionStatusController({+ const userId = useUserId();+ const live = createAgentSession(sessionId, { userId });+ const turn = () => live.metadata()?.turn ?? 'idle';+ const served = createQueueController({sessionId,- seed: () => feed.session()?.status,- });- // A last message with no stop reason reads as an open turn forever; the- // status stream knows when the runtime disconnected without closing it.- // Combining them here is what keeps "working" a single truth.- const working = () => feed.working() && !isDisconnected(status.status());- const queue = createQueueController({- sessionId,- messages: feed.messages,- });- const composer = createComposerController({- sessionId,- working,- model: () => feed.metadata()?.model,- controlOutcome: (requestId) => controlOutcome(feed.messages(), requestId),+ messages: live.messages,});+ // A row the user removes may be one `sendNext` already showed as sent;+ // the fold has to forget it too, or it stays a bubble the log never fills.+ const queue: QueueController = {+ ...served,+ remove: (actionId) => {+ live.retract(actionId);+ return served.remove(actionId);+ },+ };+ const sendNext = () => {+ const head = queue.entries()[0];+ if (!head) return;+ const action: AgentAction | undefined =+ head.kind === 'prompt' && head.prompt != null+ ? { type: 'prompt', prompt: head.prompt }+ : head.kind === 'compact'+ ? { type: 'compact' }+ : undefined;+ void live.issue({ type: 'stop' })?.then((result) => {+ if (result.isErr()) live.retract(head.actionId);+ });+ if (action) live.expect(head.actionId, action);+ };+ // A question the connection that asked is gone cannot be answered; the+ // fold keeps the part but the slot is dead.const pendingElicitation = () =>- isDisconnected(status.status())+ turn() === 'disconnected'? undefined- : (feed.metadata()?.pendingElicitation ?? undefined);+ : (live.metadata()?.pendingElicitation ?? undefined);const elicitation = createElicitationController({- sessionId,pending: pendingElicitation,- canEdit: () => feed.session()?.canEdit,+ canEdit: () => live.session()?.canEdit,+ issue: live.issue,});- const blockedOnUser = () => working() && pendingElicitation() !== undefined;// The transcript's "Reply to this" chip hands selected text to the// composer through here. A plain variable, not a signal: it is only read@@ -178,12 +181,6 @@ export function AgentSessionProvider(};const quoteSelection: QuoteInsert = (text) => quoteInsert?.(text);- // Anything the service can only deliver over a live transport: a prompt on- // the wire, or a model change waiting to be seen in the fold.- const awaitingRuntime = () =>- composer.sending() || composer.changingModel() !== undefined;- const resuming = () => isDisconnected(status.status()) && awaitingRuntime();-return (<>{/* Nested so a pending poll cannot take the block orchestrator's@@ -193,8 +190,8 @@ export function AgentSessionProvider(<Suspense fallback={null}><CloudExternalUrlPollsessionId={sessionId}- session={feed.session}- applySnapshot={feed.applySnapshot}+ session={live.session}+ applySnapshot={live.applySnapshot}/></Suspense><AgentSessionCtx.Provider@@ -202,20 +199,18 @@ export function AgentSessionProvider(sessionId,pending,startupError: error,- session: feed.session,- bot: feed.bot,- metadata: feed.metadata,- messages: feed.messages,+ session: live.session,+ bot: live.bot,+ metadata: live.metadata,+ messages: live.messages,// A create that failed leaves the block with nothing to load, which// is the same dead end for the reader as a load that failed.- loadFailed: () => feed.loadFailed() || failed(),- loadRetryable: feed.loadFailed,- retryLoad: feed.retry,- working,- status: status.status,- resuming,- blockedOnUser,- composer,+ loadFailed: () => live.loadFailed() || failed(),+ loadRetryable: live.loadFailed,+ retryLoad: live.retry,+ turn,+ issue: live.issue,+ sendNext,elicitation,queue,quoteSelection,diff --git a/apps/web/src/features/block-agent/context/create-agent-session-feed.test.ts b/apps/web/src/features/block-agent/context/create-agent-session-feed.test.tsdeleted file mode 100644index 9f4a6854f6..0000000000--- a/apps/web/src/features/block-agent/context/create-agent-session-feed.test.ts+++ /dev/null@@ -1,564 +0,0 @@-/**- * @vitest-environment jsdom- *- * The live path, end to end below the socket: a frame handed to- * `handleAgentSessionLog` (what `SyncProvider` calls) must reach the feed's- * ordered store without a refetch.- */--import type {- FoldedMessage,- FoldedStreamEvent,-} from '@service-agent-fold/generated/types';-import type { AgentSessionResponse } from '@service-agent-harness/generated/schemas';-import {- createComputed,- createMemo,- createRoot,- createSignal,- mapArray,-} from 'solid-js';-import { beforeEach, describe, expect, it, vi } from 'vitest';--const worker = vi.hoisted(() => ({- /** Messages the fold machine reports for the session. */- messages: [] as FoldedMessage[],- /** Events the next `pushSessionEntries` resolves with. */- pushed: [] as FoldedStreamEvent[],- getSession: async (): Promise<{- isErr: () => boolean;- value: Partial<AgentSessionResponse>;- }> => ({- isErr: () => false,- value: {- id: 'session',- name: 'Agent Session',- modifiedAt: '2026-08-24T12:00:00Z',- harness: 'claude-code',- },- }),-}));--const emptyMetadata = {- model: null,- supportedModels: [],- title: null,- availableCommands: [],- status: null,-};--vi.mock('@core/agent-fold/client', () => ({- openSession: vi.fn(async () => ({- messages: [],- metadata: emptyMetadata,- })),- closeSession: vi.fn(),- sessionMessages: vi.fn(async () => ({- messages: worker.messages,- metadata: { ...emptyMetadata, title: 'Fixture session' },- })),- pushSessionEntries: vi.fn(async () => worker.pushed),-}));--vi.mock('@service-agent-harness/client', () => ({- agentHarnessServiceClient: {- get: vi.fn(() => worker.getSession()),- getLog: vi.fn(async () => ({- isErr: () => false,- value: {- bot: { id: 'bot', name: 'Agent', handle: 'agent' },- entries: [],- },- })),- },-}));--function message(- turn: number,- author: 'user' | 'agent',- text: string,- stop: FoldedMessage['stop'] = null-): FoldedMessage {- return {- agentSessionId: 'session',- requestId: null,- turn,- author:- author === 'user' ? { kind: 'user', userId: null } : { kind: 'agent' },- parts: [{ kind: 'text', text }],- stop,- };-}--const flush = () => new Promise((resolve) => setTimeout(resolve, 0));--describe('createAgentSessionFeed live updates', () => {- beforeEach(() => {- worker.messages = [];- worker.pushed = [];- worker.getSession = async () => ({- isErr: () => false,- value: {- id: 'session',- name: 'Agent Session',- modifiedAt: '2026-08-24T12:00:00Z',- harness: 'claude-code',- },- });- vi.resetModules();- });-- it('keeps committed messages during replay, replaces atomically, and accepts continuation', async () => {- const { createAgentSessionFeed } = await import(- './create-agent-session-feed'- );- const { handleAgentSessionLog } = await import(- '@queries/agent-session/session-fold'- );- worker.messages = [- message(0, 'user', 'old'),- message(0, 'agent', 'old answer'),- message(1, 'user', 'obsolete'),- ];- let dispose!: () => void;- const feed = createRoot((cleanup) => {- dispose = cleanup;- return createAgentSessionFeed(() => 'session');- });- await flush();- await flush();- const emit = async () => {- handleAgentSessionLog({- agentSessionId: 'session',- direction: 'to_server',- content: { type: 'acp' },- } as never);- await flush();- };- // Staged and discarded frames produce no visible fold events.- await emit();- expect(feed.messages()).toHaveLength(3);- const replacement = [- message(0, 'user', 'replayed'),- message(0, 'agent', 'replayed answer', { kind: 'end_turn' }),- ];- worker.pushed = [{ kind: 'replace', messages: replacement }];- await emit();- expect([...feed.messages()]).toEqual(replacement);- expect(feed.working()).toBe(false);- const continuation = message(1, 'user', 'next');- worker.pushed = [{ kind: 'new', message: continuation }];- await emit();- expect([...feed.messages()]).toEqual([...replacement, continuation]);- worker.pushed = [{ kind: 'replace', messages: [] }];- await emit();- expect(feed.messages()).toHaveLength(0);- dispose();- });-- it('remounts replay rows when the same message and tool IDs acquire different shapes', async () => {- const { createAgentSessionFeed } = await import(- './create-agent-session-feed'- );- const { handleAgentSessionLog } = await import(- '@queries/agent-session/session-fold'- );- const control: FoldedMessage = {- ...message(0, 'user', ''),- parts: [- {- kind: 'control',- control: { kind: 'stop' },- outcome: { kind: 'accepted' },- },- ],- };- const tool: FoldedMessage = {- ...message(0, 'agent', ''),- parts: [- {- kind: 'tool_use',- id: 'same-tool-id',- name: { kind: 'native', name: 'Bash' },- status: 'completed',- detail: {- kind: 'terminal',- command: 'old command',- output: null,- exitCode: 0,- },- },- ],- };- worker.messages = [control, tool, message(1, 'user', 'obsolete')];- let dispose!: () => void;- const feed = createRoot((cleanup) => {- dispose = cleanup;- return createAgentSessionFeed(() => 'session');- });- await flush();- await flush();- const oldRows = [...feed.messages()];- const observed: string[][] = [];- let disposeReader!: () => void;- createRoot((cleanup) => {- disposeReader = cleanup;- // Like the transcript's For/Virtualizer and AgentMessagePart, select- // the union branch once per mounted object, then read its fields live.- const rows = mapArray(feed.messages, (row) =>- mapArray(- () => row.parts,- (part) => {- if (part.kind === 'control')- return createMemo(() => part.outcome.kind);- if (part.kind === 'text') return createMemo(() => part.text);- if (part.kind === 'tool_use') {- const detail = part.detail;- if (detail.kind === 'terminal')- return createMemo(() => detail.command);- if (detail.kind === 'read')- return createMemo(() => detail.paths.join(','));- }- throw new Error('unexpected fixture part');- }- )- );- createComputed(() => {- observed.push(- rows().map((parts) =>- parts()- .map((read) => read())- .join('|')- )- );- });- });- const errors = vi.spyOn(console, 'error').mockImplementation(() => {});- try {- const replacement: FoldedMessage[] = [- message(0, 'user', 'replayed prompt'),- {- ...tool,- stop: { kind: 'end_turn' },- parts: [- {- kind: 'tool_use',- id: 'same-tool-id',- name: { kind: 'native', name: 'Read' },- status: 'completed',- detail: { kind: 'read', paths: ['replayed.txt'] },- },- ],- },- ];- const emit = async (events: FoldedStreamEvent[]) => {- worker.pushed = events;- handleAgentSessionLog({- agentSessionId: 'session',- direction: 'to_server',- content: { type: 'acp' },- } as never);- await flush();- };- await emit([{ kind: 'replace', messages: replacement }]);- expect(errors).not.toHaveBeenCalled();- expect(observed).toEqual([- ['accepted', 'old command', 'obsolete'],- ['replayed prompt', 'replayed.txt'],- ]);- expect([...feed.messages()]).toEqual(replacement);- expect(feed.messages()[0]).not.toBe(oldRows[0]);- expect(feed.messages()[1]).not.toBe(oldRows[1]);- expect(oldRows).toEqual([control, tool, message(1, 'user', 'obsolete')]);- expect(feed.working()).toBe(false);-- // Subsequent streaming updates still keep the new row and part alive.- const replayedRow = feed.messages()[0];- const replayedPart = replayedRow?.parts[0];- await emit([- { kind: 'update', message: message(0, 'user', 'continued prompt') },- ]);- expect(feed.messages()[0]).toBe(replayedRow);- expect(feed.messages()[0]?.parts[0]).toBe(replayedPart);- expect(observed.at(-1)).toEqual(['continued prompt', 'replayed.txt']);- await emit([{ kind: 'replace', messages: [] }]);- expect(observed.at(-1)).toEqual([]);- expect(feed.working()).toBe(false);- expect(errors).not.toHaveBeenCalled();- } finally {- errors.mockRestore();- disposeReader();- dispose();- }- });-- it('applies a streamed frame without refetching', async () => {- const { createAgentSessionFeed } = await import(- './create-agent-session-feed'- );- const { handleAgentSessionLog } = await import(- '@queries/agent-session/session-fold'- );-- worker.messages = [message(0, 'user', 'hi')];-- const feed = createRoot(() => createAgentSessionFeed(() => 'session'));- await flush();- await flush();- expect(feed.messages().map((m) => m.parts)).toHaveLength(1);-- // A live frame arrives: the fold reports a new agent message.- worker.pushed = [{ kind: 'new', message: message(0, 'agent', 'working') }];- handleAgentSessionLog({- agentSessionId: 'session',- direction: 'to_server',- content: { type: 'acp' },- } as never);- await flush();- await flush();-- expect(feed.messages()).toHaveLength(2);- expect(feed.messages()[1]?.parts[0]).toMatchObject({ text: 'working' });- expect(feed.working()).toBe(true);- // The acquisition's snapshot metadata and bot land on the feed.- expect(feed.metadata()?.title).toBe('Fixture session');- expect(feed.bot()?.name).toBe('Agent');- });-- it('refreshes the persisted name after a rename notification', async () => {- const { createAgentSessionFeed } = await import(- './create-agent-session-feed'- );- const { handleAgentSessionRenamed } = await import(- '@queries/agent-session/session-metadata-sync'- );- const feed = createRoot(() => createAgentSessionFeed(() => 'session'));- await flush();-- expect(feed.session()?.name).toBe('Agent Session');- worker.getSession = async () => ({- isErr: () => false,- value: {- id: 'session',- name: 'Fix Flaky Tests',- modifiedAt: '2026-08-24T12:00:01Z',- harness: 'claude-code',- },- });- handleAgentSessionRenamed({- agentSessionId: 'session',- name: 'Fix Flaky Tests',- });- await flush();- expect(feed.session()?.name).toBe('Fix Flaky Tests');- });-- it('does not let an in-flight stale fetch overwrite a rename', async () => {- let resolveSession!: (- value: Awaited<ReturnType<typeof worker.getSession>>- ) => void;- let calls = 0;- worker.getSession = () => {- if (calls++ === 0) {- return new Promise((resolve) => {- resolveSession = resolve;- });- }- return Promise.resolve({- isErr: () => false,- value: {- id: 'session',- name: 'Fix Flaky Tests',- modifiedAt: '2026-08-24T12:00:01Z',- harness: 'claude-code',- },- });- };- const { createAgentSessionFeed } = await import(- './create-agent-session-feed'- );- const { handleAgentSessionRenamed } = await import(- '@queries/agent-session/session-metadata-sync'- );- const feed = createRoot(() => createAgentSessionFeed(() => 'session'));-- handleAgentSessionRenamed({- agentSessionId: 'session',- name: 'Fix Flaky Tests',- });- await flush();- resolveSession!({- isErr: () => false,- value: {- id: 'session',- name: 'Agent Session',- modifiedAt: '2026-08-24T12:00:00Z',- harness: 'claude-code',- },- });- await flush();-- expect(feed.session()?.name).toBe('Fix Flaky Tests');- });-- it('adopts a linked pull request when the session row updates', async () => {- const { createAgentSessionFeed } = await import(- './create-agent-session-feed'- );- const { handleAgentSessionUpdated } = await import(- '@queries/agent-session/session-metadata-sync'- );- const feed = createRoot(() => createAgentSessionFeed(() => 'session'));- await flush();-- expect(feed.session()?.pullRequestUrl).toBeUndefined();- worker.getSession = async () => ({- isErr: () => false,- value: {- id: 'session',- name: 'Agent Session',- modifiedAt: '2026-08-24T12:00:02Z',- harness: 'claude-code',- pullRequestUrl: 'https://github.com/macro-inc/macro/pull/6303',- },- });- await handleAgentSessionUpdated({ agentSessionId: 'session' });- await flush();-- expect(feed.session()?.pullRequestUrl).toBe(- 'https://github.com/macro-inc/macro/pull/6303'- );- });-- it('uses persisted state instead of a stale event payload', async () => {- const { createAgentSessionFeed } = await import(- './create-agent-session-feed'- );- const { handleAgentSessionRenamed } = await import(- '@queries/agent-session/session-metadata-sync'- );- const feed = createRoot(() => createAgentSessionFeed(() => 'session'));- await flush();-- worker.getSession = async () => ({- isErr: () => false,- value: {- id: 'session',- name: 'New Name',- modifiedAt: '2026-08-24T12:00:02Z',- harness: 'claude-code',- },- });- handleAgentSessionRenamed({- agentSessionId: 'session',- name: 'Stale Name',- });- await flush();-- expect(feed.session()?.name).toBe('New Name');- });-- it('does not re-read the snapshot for a session with no provider', async () => {- let calls = 0;- worker.getSession = async () => {- calls += 1;- return {- isErr: () => false,- value: {- id: 'session',- name: 'Agent Session',- modifiedAt: '2026-08-24T12:00:00Z',- harness: 'claude-code',- },- };- };- const { createAgentSessionFeed } = await import(- './create-agent-session-feed'- );-- worker.messages = [message(0, 'agent', 'done', { kind: 'end_turn' })];- createRoot(() => createAgentSessionFeed(() => 'session'));- await flush();- await flush();- await flush();-- expect(calls).toBe(1);- });-- it('replaces a streaming message in place as it grows', async () => {- const { createAgentSessionFeed } = await import(- './create-agent-session-feed'- );- const { handleAgentSessionLog } = await import(- '@queries/agent-session/session-fold'- );-- worker.messages = [message(0, 'agent', 'partial')];- const feed = createRoot(() => createAgentSessionFeed(() => 'session'));- await flush();- await flush();-- worker.pushed = [- {- kind: 'update',- message: message(0, 'agent', 'partial then more', { kind: 'end_turn' }),- },- ];- handleAgentSessionLog({- agentSessionId: 'session',- direction: 'to_server',- content: { type: 'acp' },- } as never);- await flush();- await flush();-- expect(feed.messages()).toHaveLength(1);- expect(feed.messages()[0]?.parts[0]).toMatchObject({- text: 'partial then more',- });- expect(feed.working()).toBe(false);- });-- it('does not suspend session() while the first fetch runs after a pending open', async () => {- let release!: () => void;- const gate = new Promise<void>((resolve) => {- release = resolve;- });- worker.getSession = async () => {- await gate;- return {- isErr: () => false,- value: {- id: 'session',- name: 'Agent Session',- modifiedAt: '2026-08-24T12:00:00Z',- harness: 'claude-code',- },- };- };-- const { createAgentSessionFeed } = await import(- './create-agent-session-feed'- );-- let dispose!: () => void;- let setSessionId!: (id: string | undefined) => void;- const feed = createRoot((cleanup) => {- dispose = cleanup;- const [sessionId, setId] = createSignal<string | undefined>(undefined);- setSessionId = setId;- return createAgentSessionFeed(sessionId);- });-- expect(feed.session()).toBeUndefined();- setSessionId('session');- // The fetch is in flight. Reading session() must not throw a promise- // (the unguarded `resource.latest` path suspends until first resolve).- expect(feed.session()).toBeUndefined();- release();- await flush();- await flush();- expect(feed.session()?.id).toBe('session');- dispose();- });-});diff --git a/apps/web/src/features/block-agent/context/create-agent-session-feed.ts b/apps/web/src/features/block-agent/context/create-agent-session.tssimilarity index 54%rename from apps/web/src/features/block-agent/context/create-agent-session-feed.tsrename to apps/web/src/features/block-agent/context/create-agent-session.tsindex 33eff9a851..b8203d1c55 100644--- a/apps/web/src/features/block-agent/context/create-agent-session-feed.ts+++ b/apps/web/src/features/block-agent/context/create-agent-session.ts@@ -1,57 +1,71 @@/**- * The block's session feed: session metadata plus the shared live fold,- * exposed as an *ordered* reactive list of folded messages — the shape a- * linear transcript renders from.+ * The Solid face of {@link AgentSession}: the shared session for whatever id+ * the block currently shows, as a reconciled ordered store of folded messages+ * plus the signals a transcript renders from.*- * The heavy lifting lives in `@queries/agent-session/session-fold`'s- * `acquireAgentSessionFold`: it buffers realtime frames before fetching the- * persisted log, folds through one worker machine per session, and- * refcounts across surfaces. This factory just orders what the fold reports- * and keeps rows reconciled so a streaming turn updates in place.+ * Everything stateful about the session lives in the class. This only owns+ * the store, applies fold events to it, and releases the acquisition when+ * the id changes or the owner disposes.*/+import {+ AgentSession,+ type IssueResult,+} from '@core/agent-session/AgentSession';import type { AgentSessionRenamedEvent } from '@queries/agent-session/realtime-protocol';-import { acquireAgentSessionFold } from '@queries/agent-session/session-fold';import {subscribeAgentSessionRenamed,subscribeAgentSessionUpdated,} from '@queries/agent-session/session-metadata-sync';import type {FoldedMessage,+ FoldedStreamEvent,SessionMetadata,} from '@service-agent-fold/generated/types';import { agentHarnessServiceClient } from '@service-agent-harness/client';import type {+ AgentAction,AgentSessionResponse,SessionBot,} from '@service-agent-harness/generated/schemas';import {type Accessor,batch,+ createMemo,createResource,createSignal,onCleanup,+ untrack,} from 'solid-js';import { createStore, produce, reconcile } from 'solid-js/store';-import { lastTurnMessage } from '../state/control-message';-export type AgentSessionFeed = {- /** Session metadata, absent until the load resolves. */+export type AgentSessionHandle = {+ /** Session row, absent until the load resolves. */session: Accessor<AgentSessionResponse | undefined>;- /** The bot the session runs as, absent until the fold is acquired. */+ /** The bot the session runs as, absent until the load resolves. */bot: Accessor<SessionBot | undefined>;- /** The fold's session metadata (title, model, …), followed live. */+ /** The fold's session metadata (title, model, turn, …), followed live. */metadata: Accessor<SessionMetadata | undefined>;/** The folded transcript, ordered by turn (prompt before reply). */messages: Accessor<FoldedMessage[]>;loadFailed: Accessor<boolean>;/** Re-runs a failed load. */retry: () => void;- /** The newest turn has no stop reason yet — the agent is working. */- working: Accessor<boolean>;+ /**+ * Do something to the agent. Folded speculatively at once; settled by the+ * log. `undefined` while the block has no session to act on.+ */+ issue: (action: AgentAction) => Promise<IssueResult> | undefined;+ /**+ * Show a queued action as dispatched under the id the server holds it+ * by. See {@link AgentSession.expect}.+ */+ expect: (actionId: string, action: AgentAction) => void;+ /** Take a speculation back. See {@link AgentSession.retract}. */+ retract: (actionId: string) => void;/*** Adopt a newer snapshot of this session (the bounded external-url poll).- * No-op when the payload is for a different session or the feed has closed.+ * No-op when the payload is for a different session.*/applySnapshot: (session: AgentSessionResponse) => void;};@@ -74,11 +88,15 @@ function sameMessage(a: FoldedMessage, b: FoldedMessage): boolean {* `sessionId` is absent while a just-created session's `POST` is still on the* wire (`pending-session.ts`). `createResource` treats an absent source as* "nothing to fetch", so the block simply renders its empty transcript until- * the id lands and the fetch runs itself.+ * the id lands and the load runs itself.*/-export function createAgentSessionFeed(- sessionId: Accessor<string | undefined>-): AgentSessionFeed {+export function createAgentSession(+ sessionId: Accessor<string | undefined>,+ options: {+ /** The viewer, so a speculated prompt is attributed as the log will. */+ userId: Accessor<string | undefined>;+ }+): AgentSessionHandle {// Whether this block went on screen before it had a session to load.//// `resource.latest` falls back to a *suspending* read until the resource has@@ -121,70 +139,91 @@ export function createAgentSessionFeed(}});- let release: (() => void) | undefined;+ /** A row's identity in the transcript, and the transcript's render key. */+ const keyOf = (message: FoldedMessage) =>+ `${message.turn}:${message.author.kind}`;++ // A whole new view of the conversation: what a load reports, and what every+ // rebase reports while something is speculated.+ //+ // Merged row by row rather than spliced wholesale. A splice hands the store+ // a fresh object for every index, so Solid remounts every row - the+ // transcript re-measures, entrance motions replay, and a streaming turn+ // visibly jumps. A rebase happens on *every* confirmed frame while an+ // action is pending, so that jump was the whole turn flickering. Reconciling+ // each row against the one already there keeps identity for everything that+ // did not actually change.+ const replace = (messages: FoldedMessage[]) =>+ batch(() => {+ const wanted = new Set(messages.map(keyOf));+ // Tail first, so the indices ahead of each removal still hold.+ for (let index = list.length - 1; index >= 0; index--) {+ if (wanted.has(keyOf(list[index]!))) continue;+ setList(+ produce((current: FoldedMessage[]) => {+ current.splice(index, 1);+ })+ );+ }+ upsert(messages);+ });++ const applyEvents = (events: FoldedStreamEvent[]) =>+ batch(() => {+ for (const event of events) {+ if (event.kind === 'replace') replace(event.messages);+ else if (event.kind === 'metadata') setMetadata(event.metadata);+ else upsert([event.message]);+ }+ });++ // The shared session for the current id. A memo rather than an effect so+ // acquisition and release track the id exactly, with nothing to schedule.+ const live = createMemo(() => {+ const id = sessionId();+ if (!id) return undefined;+ const session = AgentSession.acquire(id);+ const unsubscribe = session.subscribe(applyEvents);+ onCleanup(() => {+ unsubscribe();+ session.release();+ });+ return session;+ });- // A superseded run (session switch, unmount mid-fetch) must release its- // acquisition or the shared fold leaks a reference.- let generation = 0;- let closed = false;let latestRename: AgentSessionRenamedEvent | undefined;let renameRefresh = 0;- onCleanup(() => {- closed = true;- release?.();- release = undefined;- });const [resource, { mutate, refetch }] = createResource(- sessionId,- async (id) => {- const run = ++generation;+ live,+ async (session) => {const renameRefreshAtStart = renameRefresh;- const superseded = () => closed || generation !== run;+ const superseded = () => untrack(sessionId) !== session.id;- release?.();- release = undefined;batch(() => {setList(reconcile([]));setBot(undefined);setMetadata(undefined);});- const session = await agentHarnessServiceClient.get(id);- if (session.isErr()) {- throw new Error(`agent session could not be fetched: ${id}`);- }- if (superseded()) return session.value;+ const record = await session.load();+ if (superseded()) return record.session;+ // Read after every input pushed so far, and applied before any event+ // that arrives later: events between subscribe and here upserted into+ // the list, and this replaces the list with a view that includes them.+ const snapshot = await session.snapshot();+ if (superseded()) return record.session;- const fold = await acquireAgentSessionFold({- agentSessionId: id,- onChange: upsert,- onReplace: (messages) =>- setList(- produce((current: FoldedMessage[]) => {- // Replay can reuse turn/author and tool IDs for different part- // kinds. Replace row identities atomically so mounted parts- // cannot keep reading a union variant that reconcile removed.- current.splice(0, current.length, ...messages);- })- ),- onMetadata: setMetadata,- });- if (superseded()) {- fold.release();- return session.value;- }- release = fold.release;batch(() => {- setBot(fold.bot);- setMetadata(fold.metadata);- upsert(fold.messages);+ setBot(record.bot);+ setMetadata(snapshot.metadata);+ replace(snapshot.messages);});return renameRefresh > renameRefreshAtStart &&- latestRename?.agentSessionId === id- ? { ...session.value, name: latestRename.name }- : session.value;+ latestRename?.agentSessionId === session.id+ ? { ...record.session, name: latestRename.name }+ : record.session;});@@ -233,23 +272,6 @@ export function createAgentSessionFeed(}));- const messages = () => list;- // A user-authored tail means a prompt is awaiting its reply — except when- // it is a control, which is user-authored, never gets a stop reason, and- // starts no turn. Counting one would latch this signal true forever, and- // the composer's drain holds every prompt behind it: changing the model- // would silently stop the session from accepting anything again.- const working = () => {- const last = lastTurnMessage(list);- if (!last) return false;- return last.author.kind === 'user' || last.stop == null;- };-- const applySnapshot = (session: AgentSessionResponse) => {- if (closed || sessionId() !== session.id) return;- mutate(session);- };-// A first fetch would suspend; see `openedPending`.const session = () =>openedPending && resource.state === 'pending' ? undefined : resource.latest;@@ -258,10 +280,16 @@ export function createAgentSessionFeed(session,bot,metadata,- messages,+ messages: () => list,loadFailed: () => resource.error !== undefined,retry: () => void refetch(),- working,- applySnapshot,+ issue: (action) => live()?.issue(action, { userId: options.userId() }),+ expect: (actionId, action) =>+ live()?.expect(actionId, action, { userId: options.userId() }),+ retract: (actionId) => live()?.retract(actionId),+ applySnapshot: (snapshot) => {+ if (sessionId() !== snapshot.id) return;+ mutate(snapshot);+ },};}diff --git a/apps/web/src/features/block-agent/context/create-composer-controller.test.ts b/apps/web/src/features/block-agent/context/create-composer-controller.test.tsdeleted file mode 100644index 87bf4aea74..0000000000--- a/apps/web/src/features/block-agent/context/create-composer-controller.test.ts+++ /dev/null@@ -1,325 +0,0 @@-/**- * @vitest-environment jsdom- *- * The controller against a mocked harness client: prompts post immediately- * (the service owns queueing), failures surface as a toast, stop is latched- * per turn, and a pending model change resolves only through the fold.- */--import { createRoot, createSignal } from 'solid-js';-import { beforeEach, describe, expect, it, vi } from 'vitest';-import type { ControlOutcome } from '../state/control-message';-import { createComposerController } from './create-composer-controller';--const control = vi.hoisted(() => ({- calls: [] as { sessionId: string; action: unknown }[],- /** What the next `control` calls resolve to. */- outcome: 'ok' as 'ok' | 'err' | 'reject',-}));--vi.mock('@service-agent-harness/client', () => ({- agentHarnessServiceClient: {- control: vi.fn(async (sessionId: string, action: unknown) => {- control.calls.push({ sessionId, action });- if (control.outcome === 'reject') throw new Error('network');- return {- isErr: () => control.outcome === 'err',- // The control response — the action id is the fold's `requestId`- // for the folded message this action derives. One per call, in- // order; always `sent` here, queueing is the server's business.- value: {- actionId: `action-${control.calls.length - 1}`,- status: 'sent',- },- };- }),- },-}));--const toast = vi.hoisted(() => ({ failure: vi.fn(), success: vi.fn() }));-vi.mock('@core/component/Toast/Toast', () => ({ toast }));--/** Let the awaited POST settle. */-const flush = () => new Promise((resolve) => setTimeout(resolve, 0));--const prompts = () =>- control.calls- .filter((c) => (c.action as { type: string }).type === 'prompt')- .map((c) => (c.action as { prompt: string }).prompt);--function setup(options?: {- working?: boolean;- sessionId?: string;- model?: string | null;-}) {- const [working, setWorking] = createSignal(options?.working ?? false);- const [sessionId, setSessionId] = createSignal<string | undefined>(- 'sessionId' in (options ?? {}) ? options?.sessionId : 'session-1'- );- const [model, setModel] = createSignal<string | null>(options?.model ?? null);- // The fold's per-action outcomes, keyed by the id `control` returned.- const [outcomes, setOutcomes] = createSignal<Record<string, ControlOutcome>>(- {}- );- const resolveControl = (requestId: string, outcome: ControlOutcome) =>- setOutcomes((current) => ({ ...current, [requestId]: outcome }));- const { controller, dispose } = createRoot((dispose) => ({- controller: createComposerController({- sessionId,- working,- model,- controlOutcome: (requestId) => outcomes()[requestId],- }),- dispose,- }));- return {- controller,- setWorking,- setSessionId,- setModel,- resolveControl,- dispose,- };-}--beforeEach(() => {- control.calls = [];- control.outcome = 'ok';- toast.failure.mockClear();-});--describe('sending', () => {- it('posts immediately', async () => {- const { controller, dispose } = setup();- controller.send('hello');- await flush();-- expect(prompts()).toEqual(['hello']);- expect(controller.sending()).toBe(false);- dispose();- });-- it('posts immediately even while a turn is running — the service queues', async () => {- const { controller, dispose } = setup({ working: true });- controller.send('one');- controller.send('two');- await flush();-- expect(prompts()).toEqual(['one', 'two']);- dispose();- });-- it('reports sending while the POST is on the wire', async () => {- const { controller, dispose } = setup();- controller.send('hello');-- expect(controller.sending()).toBe(true);- expect(controller.busy()).toBe(true);- await flush();- expect(controller.sending()).toBe(false);- expect(controller.busy()).toBe(false);- dispose();- });-- it('surfaces a failed POST as a toast', async () => {- const { controller, dispose } = setup();- control.outcome = 'err';- controller.send('doomed');- await flush();-- expect(toast.failure).toHaveBeenCalledWith('Message could not be sent');- expect(controller.sending()).toBe(false);- dispose();- });-- it('a rejected promise (network error) behaves like a failure', async () => {- const { controller, dispose } = setup();- control.outcome = 'reject';- controller.send('offline');- await flush();-- expect(toast.failure).toHaveBeenCalledWith('Message could not be sent');- expect(controller.sending()).toBe(false);- dispose();- });-});--describe('stop', () => {- it('posts a stop while busy and is a no-op while idle', async () => {- const { controller, setWorking, dispose } = setup();- controller.stop();- await flush();- expect(control.calls).toEqual([]);-- setWorking(true);- controller.stop();- await flush();- expect(control.calls.at(-1)?.action).toEqual({ type: 'stop' });- dispose();- });-- // Each cancel the service accepts is its own Stopped line in the- // transcript, so a user clicking through a turn that takes a moment to- // settle would otherwise stack one per click.- it('posts one stop per turn, however many times it is clicked', async () => {- const { controller, setWorking, dispose } = setup({ working: true });- const isStop = (action: unknown) =>- typeof action === 'object' &&- action !== null &&- 'type' in action &&- action.type === 'stop';- const stops = () => control.calls.filter((call) => isStop(call.action));-- controller.stop();- controller.stop();- controller.stop();- await flush();- expect(stops()).toHaveLength(1);-- // The next turn stops on its own click: the latch tracks the turn, not- // the session.- setWorking(false);- await flush();- setWorking(true);- controller.stop();- await flush();- expect(stops()).toHaveLength(2);- dispose();- });-});--describe('a session that does not exist yet', () => {- it('does not post anything before there is a session', async () => {- const { controller, dispose } = setup({ sessionId: undefined });- controller.send('too early');- controller.stop();- controller.setModel('opus');- await flush();-- expect(control.calls).toEqual([]);- dispose();- });-});--describe('a model change in flight', () => {- it('holds until the fold shows the runtime moved, not until the POST returns', async () => {- const { controller, setModel, dispose } = setup({ model: 'old-model' });- controller.setModel('new-model');- await flush();-- // The POST has already come back; the runtime has not moved yet.- expect(control.calls.at(-1)?.action).toEqual({- type: 'setModel',- model: 'new-model',- });- expect(controller.changingModel()).toBe('new-model');-- setModel('new-model');- await flush();-- expect(controller.changingModel()).toBeUndefined();- dispose();- });-- it('clears when the runtime settles on something else entirely', async () => {- const { controller, setModel, dispose } = setup({ model: 'old-model' });- controller.setModel('new-model');- await flush();-- // A later change overtook this one; nothing is still pending.- setModel('third-model');- await flush();- controller.setModel('third-model');- await flush();-- expect(controller.changingModel()).toBeUndefined();- dispose();- });-- it('clears immediately when the POST fails', async () => {- const { controller, dispose } = setup({ model: 'old-model' });- control.outcome = 'err';- controller.setModel('new-model');- await flush();-- expect(controller.changingModel()).toBeUndefined();- dispose();- });-- it('clears when the runtime rejects the change', async () => {- const { controller, resolveControl, dispose } = setup({- model: 'old-model',- });- controller.setModel('new-model');- await flush();- expect(controller.changingModel()).toBe('new-model');-- // The runtime refuses: the fold resolves this action's control outcome,- // the model never moves. The pending state must release on it alone.- resolveControl('action-0', {- kind: 'rejected',- message: 'no provider serves it',- });- await flush();-- expect(controller.changingModel()).toBeUndefined();- dispose();- });-- it("ignores another action's rejection", async () => {- const { controller, resolveControl, dispose } = setup({- model: 'old-model',- });- // An earlier change was refused before this request.- controller.setModel('new-model');- await flush();- controller.setModel('new-model');- await flush();-- // The first action's rejection must not answer the second request…- resolveControl('action-0', { kind: 'rejected', message: 'refused' });- await flush();- expect(controller.changingModel()).toBe('new-model');-- // …but its own does.- resolveControl('action-1', { kind: 'rejected', message: 'refused again' });- await flush();-- expect(controller.changingModel()).toBeUndefined();- dispose();- });-- it('keeps waiting while its own action is pending or accepted', async () => {- const { controller, resolveControl, dispose } = setup({- model: 'old-model',- });- controller.setModel('new-model');- await flush();-- resolveControl('action-0', { kind: 'pending' });- await flush();- expect(controller.changingModel()).toBe('new-model');-- // Accepted alone is not the end of the wait — the fold's `model` moving- // is (the accepted response carries it) — so the pending state holds.- resolveControl('action-0', { kind: 'accepted' });- await flush();- expect(controller.changingModel()).toBe('new-model');- dispose();- });-});--describe('session switch', () => {- it('drops a pending model change — it never leaks into another session', async () => {- const { controller, setSessionId, dispose } = setup({ model: 'old-model' });- controller.setModel('new-model');- await flush();- expect(controller.changingModel()).toBe('new-model');-- setSessionId('session-2');- await flush();-- expect(controller.changingModel()).toBeUndefined();- dispose();- });-});diff --git a/apps/web/src/features/block-agent/context/create-composer-controller.ts b/apps/web/src/features/block-agent/context/create-composer-controller.tsdeleted file mode 100644index f034a8c2d1..0000000000--- a/apps/web/src/features/block-agent/context/create-composer-controller.ts+++ /dev/null@@ -1,228 +0,0 @@-/**- * The composer's send/stop/model controls.- *- * Prompt ordering lives in the service: every control POST joins the- * session's per-command queue there, so a prompt sent mid-turn waits its- * turn on the server, not in the client. `send` therefore posts- * immediately, and the only state kept here is what the UI needs to show —- * a prompt POST on the wire, a stop underway, a model change waiting to be- * seen in the fold.- */--import { toast } from '@core/component/Toast/Toast';-import { markMessageSent } from '@core/util/message-send-motion';-import { agentHarnessServiceClient } from '@service-agent-harness/client';-import { type Accessor, batch, createEffect } from 'solid-js';-import { createStore } from 'solid-js/store';-import type { ControlOutcome } from '../state/control-message';--export type ComposerController = {- /** A prompt POST is on the wire. */- sending: Accessor<boolean>;- /** A turn is running or a prompt is on its way to start one — the stop- * affordance shows. */- busy: Accessor<boolean>;- /**- * A model change is on the wire: the id requested, until the fold shows the- * runtime moved to it (or the POST fails).- *- * Worth its own signal because this is the request that can take longest- * with the least to show for it — a change issued to a reaped sandbox- * blocks in the service for the whole container resume, and nothing is- * written to the log until it lands, so without this the UI has no- * evidence anything is happening at all.- */- changingModel: Accessor<string | undefined>;- /** Post the prompt. No-op without a session — the input disables until- * there is one. */- send: (markdown: string) => void;- stop: () => void;- /** Ask the agent to run on a different model from here on. */- setModel: (model: string) => void;-};--export function createComposerController(options: {- /** The fold's current model, which is how a model change is seen to land. */- model?: Accessor<string | null | undefined>;- /** Absent until a just-created session's `POST` lands- * (`context/pending-session.ts`). */- sessionId: Accessor<string | undefined>;- /** The block's one working signal — see `AgentSessionContext`. */- working: Accessor<boolean>;- /**- * The fold's outcome for the control action `requestId` — the id the- * control POST returned, which the fold stamps on the folded message the- * action derives. A rejection is the other way a pending model change- * resolves — the fold's `model` never moves for one — so without this a- * refused switch would shimmer forever.- */- controlOutcome?: (requestId: string) => ControlOutcome | undefined;-}): ComposerController {- const [state, setState] = createStore<{- /** Prompt POSTs on the wire. A count, not a flag: sends can overlap. */- inflightPrompts: number;- /** The model a `setModel` is currently asking for. */- requestedModel: string | undefined;- /**- * The id the control POST returned for the in-flight change — the exact- * handle for its outcome in the fold, so no other action's rejection- * (nor an older refusal of the same model) can answer this request.- */- requestedActionId: string | undefined;- /**- * A stop has been posted and the fold has not settled the turn yet.- * Further clicks must not stack another `session/cancel`, each of which- * the fold renders as its own accepted Stopped line.- */- stopping: boolean;- }>({- inflightPrompts: 0,- requestedModel: undefined,- requestedActionId: undefined,- stopping: false,- });-- const postPrompt = async (sessionId: string, markdown: string) => {- setState('inflightPrompts', (count) => count + 1);- const result = await agentHarnessServiceClient- .control(sessionId, { type: 'prompt', prompt: markdown })- .catch(() => undefined);- // Floored: a session switch resets the count while this POST is still- // out, and its settle must not drive the new session's count negative.- setState('inflightPrompts', (count) => Math.max(0, count - 1));- if (result === undefined || result.isErr()) {- toast.failure('Message could not be sent');- } else {- markMessageSent(`agent:${sessionId}:${result.value.actionId}`);- }- // A 200 with status `queued` means the prompt waits in the session's- // server-side queue; the gateway publishes the queue, so nothing more- // to do here.- };-- const postSetModel = async (sessionId: string, model: string) => {- setState('requestedModel', model);- const result = await agentHarnessServiceClient- .control(sessionId, { type: 'setModel', model })- .catch(() => undefined);- if (result === undefined || result.isErr()) {- batch(() => {- setState('requestedModel', undefined);- setState('requestedActionId', undefined);- });- toast.failure('The model could not be changed');- return;- }- // The POST returning only means the service accepted it; resolution is- // observed through the fold. The returned action id is the fold's- // `requestId` for this change: an accepted change moves the metadata's- // `model`, a rejected one resolves this id's control outcome, and the- // effects below watch for whichever comes.- if (state.requestedModel === model) {- setState('requestedActionId', result.value.actionId);- }- };-- const postStop = async (sessionId: string) => {- const result = await agentHarnessServiceClient- .control(sessionId, { type: 'stop' })- .catch(() => undefined);- if (result === undefined || result.isErr()) {- setState('stopping', false);- toast.failure('The agent could not be stopped');- }- // Success is observed through the fold: the turn settles and `working`- // flips false, which releases the latch.- };-- const busy = () => options.working() || state.inflightPrompts > 0;-- // A model change is done when the fold says the runtime moved, not when- // the POST returns. Also clears when the runtime settles somewhere else- // entirely — another change overtook this one — so this can never stick.- createEffect(() => {- const requested = state.requestedModel;- if (requested === undefined) return;- const current = options.model?.();- if (current == null) return;- if (current === requested) {- batch(() => {- setState('requestedModel', undefined);- setState('requestedActionId', undefined);- });- }- });-- // The other resolution: the runtime refused the change. The fold resolves- // this exact action's control outcome (`ControlOutcome::Rejected`) on the- // message carrying its id, and the transcript renders the refusal; here it- // just has to release the pending state, and say so — a refused switch- // otherwise looks like one that never registered.- createEffect(() => {- const requested = state.requestedModel;- const actionId = state.requestedActionId;- if (requested === undefined || actionId === undefined) return;- const outcome = options.controlOutcome?.(actionId);- if (outcome?.kind !== 'rejected') return;- batch(() => {- setState('requestedModel', undefined);- setState('requestedActionId', undefined);- });- toast.failure(`Couldn't switch to ${requested}`);- });-- // The stop is done when the fold says the turn is no longer running. The- // release is read off `working` rather than off the POST returning, because- // the POST only means the cancel was accepted, not that the turn is over.- createEffect(() => {- if (!options.working()) setState('stopping', false);- });-- // A session switch resets the composer: a pending model change or stop- // belongs to the session it was issued in, never the next one.- //- // Acquiring an id is not a switch. A block that opened on a placeholder- // goes `undefined -> id` when its create lands. The previous id is tracked- // by hand rather than read from `on`'s `prevInput`, which a deferred `on`- // leaves undefined through the first change and so cannot tell the two- // apart.- let previousSessionId = options.sessionId();- createEffect(() => {- const sessionId = options.sessionId();- if (sessionId === previousSessionId) return;- const acquired = previousSessionId === undefined;- previousSessionId = sessionId;- if (acquired) return;- setState({- // A send still on the wire belongs to the previous session; its- // eventual settle must not keep this one's stop control up.- inflightPrompts: 0,- requestedModel: undefined,- requestedActionId: undefined,- stopping: false,- });- });-- return {- sending: () => state.inflightPrompts > 0,- busy,- changingModel: () => state.requestedModel,- send: (markdown) => {- const sessionId = options.sessionId();- if (!sessionId) return;- void postPrompt(sessionId, markdown);- },- stop: () => {- const sessionId = options.sessionId();- if (!sessionId) return;- if (!busy() || state.stopping) return;- setState('stopping', true);- void postStop(sessionId);- },- setModel: (model) => {- const sessionId = options.sessionId();- if (!sessionId) return;- void postSetModel(sessionId, model);- },- };-}diff --git a/apps/web/src/features/block-agent/context/create-elicitation-controller.test.ts b/apps/web/src/features/block-agent/context/create-elicitation-controller.test.tsindex 344a3e451d..e546cec1fa 100644--- a/apps/web/src/features/block-agent/context/create-elicitation-controller.test.ts+++ b/apps/web/src/features/block-agent/context/create-elicitation-controller.test.ts@@ -1,41 +1,43 @@/*** @vitest-environment jsdom*- * The controller against a mocked harness client: an answer is one POST on- * the agent's request id, only a viewer with edit access may send it, and a- * 409 is said once.+ * The controller against a stub `issue`: an answer is one action on the+ * session's optimistic path, only a viewer with edit access may send it, and+ * a 409 is said once.*/+import type { IssueResult } from '@core/agent-session/AgentSession';import type { PendingElicitation } from '@service-agent-fold/generated/types';+import type { AgentAction } from '@service-agent-harness/generated/schemas';+import { err, ok } from 'neverthrow';import { createRoot, createSignal } from 'solid-js';import { beforeEach, describe, expect, it, vi } from 'vitest';import { createElicitationController } from './create-elicitation-controller';-const control = vi.hoisted(() => ({- calls: [] as { sessionId: string; action: unknown }[],- outcome: 'ok' as 'ok' | 'conflict' | 'err' | 'reject',-}));--vi.mock('@service-agent-harness/client', () => ({- agentHarnessServiceClient: {- control: vi.fn(async (sessionId: string, action: unknown) => {- control.calls.push({ sessionId, action });- if (control.outcome === 'reject') throw new Error('network');- return {- isErr: () => control.outcome !== 'ok',- error:- control.outcome === 'conflict'- ? [{ code: 'CONFLICT' }]- : [{ code: 'INTERNAL' }],- value: { actionId: 'unused', status: 'sent' },- };- }),- },+const issued = vi.hoisted(() => ({+ actions: [] as AgentAction[],+ outcome: 'ok' as 'ok' | 'conflict' | 'err' | 'reject' | 'no-session',}));const toast = vi.hoisted(() => ({ failure: vi.fn(), success: vi.fn() }));vi.mock('@core/component/Toast/Toast', () => ({ toast }));+const issue = (action: AgentAction): Promise<IssueResult> | undefined => {+ issued.actions.push(action);+ if (issued.outcome === 'no-session') return undefined;+ if (issued.outcome === 'reject') return Promise.reject(new Error('network'));+ if (issued.outcome === 'ok') {+ return Promise.resolve(+ ok({ actionId: 'accepted', status: 'sent' }) as IssueResult+ );+ }+ return Promise.resolve(+ err([+ { code: issued.outcome === 'conflict' ? 'CONFLICT' : 'INTERNAL' },+ ]) as unknown as IssueResult+ );+};+const question: PendingElicitation = {requestId: 43,turn: 0,@@ -53,24 +55,20 @@ function setup(options: { canEdit?: boolean } = { canEdit: true }) {);const [canEdit] = createSignal<boolean | undefined>(options.canEdit);const { controller, dispose } = createRoot((dispose) => ({- controller: createElicitationController({- sessionId: () => 'session-1',- pending,- canEdit,- }),+ controller: createElicitationController({ pending, canEdit, issue }),dispose,}));return { controller, setPending, dispose };}beforeEach(() => {- control.calls = [];- control.outcome = 'ok';+ issued.actions = [];+ issued.outcome = 'ok';toast.failure.mockReset();});describe('createElicitationController', () => {- it('answers on the agent request id with the action spread into the body', async () => {+ it('answers through the session with the agent request id and the answer', async () => {const { controller, dispose } = setup();expect(controller.canAnswer()).toBe(true);const accepted = await controller.respond({@@ -78,15 +76,12 @@ describe('createElicitationController', () => {content: { colour: 'teal' },});expect(accepted).toBe(true);- expect(control.calls).toEqual([+ expect(issued.actions).toEqual([{- sessionId: 'session-1',- action: {- type: 'respondElicitation',- requestId: 43,- action: 'accept',- content: { colour: 'teal' },- },+ type: 'respondElicitation',+ requestId: 43,+ action: 'accept',+ content: { colour: 'teal' },},]);dispose();@@ -97,7 +92,7 @@ describe('createElicitationController', () => {expect(controller.canAnswer()).toBe(false);const sent = await controller.respond({ action: 'decline' });expect(sent).toBe(false);- expect(control.calls).toEqual([]);+ expect(issued.actions).toEqual([]);dispose();});@@ -108,7 +103,7 @@ describe('createElicitationController', () => {});it('a 409 means the agent moved on: said once, nothing else', async () => {- control.outcome = 'conflict';+ issued.outcome = 'conflict';const { controller, dispose } = setup();expect(await controller.respond({ action: 'cancel' })).toBe(false);expect(toast.failure).toHaveBeenCalledWith(@@ -118,21 +113,29 @@ describe('createElicitationController', () => {});it('other failures and thrown errors read as a failed send', async () => {- control.outcome = 'err';+ issued.outcome = 'err';const { controller, dispose } = setup();expect(await controller.respond({ action: 'decline' })).toBe(false);- control.outcome = 'reject';+ issued.outcome = 'reject';expect(await controller.respond({ action: 'decline' })).toBe(false);expect(toast.failure).toHaveBeenCalledTimes(2);expect(toast.failure).toHaveBeenCalledWith("Couldn't send your answer");dispose();});+ it('a block with no session to act on reports nothing sent', async () => {+ issued.outcome = 'no-session';+ const { controller, dispose } = setup();+ expect(await controller.respond({ action: 'decline' })).toBe(false);+ expect(toast.failure).not.toHaveBeenCalled();+ dispose();+ });+it('nothing is sent once the question is gone', async () => {const { controller, setPending, dispose } = setup();setPending(undefined);expect(await controller.respond({ action: 'decline' })).toBe(false);- expect(control.calls).toEqual([]);+ expect(issued.actions).toEqual([]);dispose();});});diff --git a/apps/web/src/features/block-agent/context/create-elicitation-controller.ts b/apps/web/src/features/block-agent/context/create-elicitation-controller.tsindex abd7bb5d47..2b8a7df032 100644--- a/apps/web/src/features/block-agent/context/create-elicitation-controller.ts+++ b/apps/web/src/features/block-agent/context/create-elicitation-controller.ts@@ -1,22 +1,31 @@/*** The block's half of answering an elicitation: which question is live (the- * fold's metadata slot), who may answer it, and the one POST that does.+ * fold's metadata slot), who may answer it, and the action that answers it.** Not a queue. An answer is a response to a request the agent is blocked on,* so it goes straight out rather than behind queued prompts - and a second* answer to the same question is refused by the server (409), not merged.*+ * The answer rides the session's one optimistic path: {@link AgentSession}+ * speculates it into the fold before the POST, so the outcome on the part,+ * the turn leaving `blocked`, and the message's pending mark are the only+ * things a surface reads. There is no second "an answer is on the wire"+ * channel; only a refusal is surfaced after the fact.+ ** Anyone with edit access may answer - the same `EditAccessLevel` gate every* other control action has - so a surface shared with viewers (the session* split, a channel thread) reads {@link ElicitationController.canAnswer}* before offering a form, and says it is waiting on an editor otherwise.*/+import type { IssueResult } from '@core/agent-session/AgentSession';import { toast } from '@core/component/Toast/Toast';import type { PendingElicitation } from '@service-agent-fold/generated/types';-import { agentHarnessServiceClient } from '@service-agent-harness/client';-import type { ElicitationAnswer } from '@service-agent-harness/generated/schemas';-import { type Accessor, createSignal } from 'solid-js';+import type {+ AgentAction,+ ElicitationAnswer,+} from '@service-agent-harness/generated/schemas';+import type { Accessor } from 'solid-js';export type ElicitationController = {/** The question awaiting an answer right now, if any. */@@ -26,40 +35,36 @@ export type ElicitationController = {* until the session has loaded.*/canAnswer: Accessor<boolean>;- /** An answer is on the wire. */- answering: Accessor<boolean>;/*** Answer the pending question. Resolves `true` when the service accepted- * the answer; the fold then shows the outcome. A `409` means the agent is- * no longer waiting (someone else answered, a stop cancelled it, or the- * connection that asked is gone) - said once, and the metadata refresh- * removes the form. A viewer without edit access gets `false` without a- * request.+ * the answer; the fold has already shown it. A `409` means the agent is no+ * longer waiting (someone else answered, a stop cancelled it, or the+ * connection that asked is gone) - said once, and the retracted+ * speculation puts the form back where the metadata still has it. A viewer+ * without edit access gets `false` without a request.*/respond: (answer: ElicitationAnswer) => Promise<boolean>;};export function createElicitationController(options: {- sessionId: Accessor<string | undefined>;pending: Accessor<PendingElicitation | undefined>;/** Whether the viewer may drive the session, once it has loaded. */canEdit: Accessor<boolean | undefined>;+ /** The session's one optimistic path; absent while there is no session. */+ issue: (action: AgentAction) => Promise<IssueResult> | undefined;}): ElicitationController {- const [answering, setAnswering] = createSignal(false);-const canAnswer = () => options.canEdit() === true;const respond = async (answer: ElicitationAnswer): Promise<boolean> => {- const sessionId = options.sessionId();const pending = options.pending();- if (!sessionId || !pending || answering() || !canAnswer()) return false;- setAnswering(true);+ if (!pending || !canAnswer()) return false;try {- const result = await agentHarnessServiceClient.control(sessionId, {+ const result = await options.issue({type: 'respondElicitation',requestId: pending.requestId,...answer,});+ if (!result) return false;if (result.isErr()) {const conflict = result.error.some((error) => error.code === 'CONFLICT'@@ -75,15 +80,12 @@ export function createElicitationController(options: {} catch {toast.failure("Couldn't send your answer");return false;- } finally {- setAnswering(false);}};return {pending: options.pending,canAnswer,- answering,respond,};}diff --git a/apps/web/src/features/block-agent/context/create-queue-controller.ts b/apps/web/src/features/block-agent/context/create-queue-controller.tsindex 260302cea3..dfec28c910 100644--- a/apps/web/src/features/block-agent/context/create-queue-controller.ts+++ b/apps/web/src/features/block-agent/context/create-queue-controller.ts@@ -34,7 +34,8 @@ export type QueueController = {/*** The actions still waiting, oldest first, minus any the fold already* shows. An entry whose `actionId` matches a folded message's `requestId`- * has dispatched — the transcript renders it, so the queue must not.+ * has dispatched, or is shown as dispatching — the transcript renders it,+ * so the queue must not.*/entries: Accessor<QueuedActionDto[]>;/** Replace a queued prompt's text. A 404 means it already dispatched —@@ -105,6 +106,10 @@ export function createQueueController(options: {}));+ // A pending message retires a row too. `sendNext` speculates the queue+ // head under the id this list knows it by, and the whole point is that it+ // reads as sent; a prompt the server queued after the client speculated+ // it is retracted by the response, so its row comes back on its own.const dispatchedIds = createMemo(() => {const ids = new Set<string>();for (const message of options.messages()) {diff --git a/apps/web/src/features/block-agent/context/create-session-status-controller.test.ts b/apps/web/src/features/block-agent/context/create-session-status-controller.test.tsdeleted file mode 100644index b84e14a0ce..0000000000--- a/apps/web/src/features/block-agent/context/create-session-status-controller.test.ts+++ /dev/null@@ -1,49 +0,0 @@-import type { AgentSessionLogEntryDto } from '@service-agent-harness/generated/schemas';-import { describe, expect, it } from 'vitest';-import {- isDisconnected,- statusFromEntry,-} from './create-session-status-controller';--function entry(content: unknown): AgentSessionLogEntryDto {- return { direction: 'to_server', content } as AgentSessionLogEntryDto;-}--describe('statusFromEntry', () => {- it('projects a system-event frame into an event status', () => {- expect(entryStatus({ type: 'event', event: 'acp_ready' })).toEqual({- kind: 'event',- event: 'acp_ready',- });- });-- it('ignores ACP frames', () => {- expect(- entryStatus({ type: 'acp', jsonrpc: '2.0', method: 'session/update' })- ).toBeUndefined();- });-- it('ignores malformed event frames', () => {- expect(entryStatus({ type: 'event' })).toBeUndefined();- expect(entryStatus({ type: 'event', event: 7 })).toBeUndefined();- });-- function entryStatus(content: unknown) {- return statusFromEntry(entry(content));- }-});--describe('isDisconnected', () => {- // The bug this closes: a live disconnect arrives as an *event*, never as- // the snapshot's own kind, so checking only the latter missed every- // disconnect that happened while the block was open.- it('recognises the live event, not just the snapshot kind', () => {- expect(isDisconnected({ kind: 'disconnected' })).toBe(true);- expect(isDisconnected({ kind: 'event', event: 'disconnected' })).toBe(true);- });-- it('leaves every other status alone', () => {- expect(isDisconnected({ kind: 'no_messages' })).toBe(false);- expect(isDisconnected({ kind: 'event', event: 'acp_ready' })).toBe(false);- });-});diff --git a/apps/web/src/features/block-agent/context/create-session-status-controller.ts b/apps/web/src/features/block-agent/context/create-session-status-controller.tsdeleted file mode 100644index 1e1d33e3ef..0000000000--- a/apps/web/src/features/block-agent/context/create-session-status-controller.ts+++ /dev/null@@ -1,98 +0,0 @@-/**- * The session's live status: seeded from the GET snapshot, then followed- * through the same realtime stream the transcript folds.- *- * There is no dedicated status feed — status is a projection of the log- * (`crates/agent_session/src/outbound/postgres/mod.rs`, the log-create- * transaction), and every appended frame, including the system-event frames- * that move the status, is published over the one `agent_session_log`- * gateway event. This controller taps those raw frames and keeps the last- * system event, exactly as the backend projection does.- */--import { subscribeAgentSessionLog } from '@queries/agent-session/session-fold';-import type { AgentSessionLogEntryDto } from '@service-agent-harness/generated/schemas';-import { type Accessor, createEffect, createSignal, onCleanup } from 'solid-js';--/** Mirrors `SessionStatusDto`, which mirrors the backend's `SessionStatus`. */-export type SessionStatus =- /** No status updates received. */- | { kind: 'no_messages' }- /** The last system event received from the runtime, e.g. `acp_ready`. */- | { kind: 'event'; event: string }- /** The session disconnected without sending a closed event. */- | { kind: 'disconnected' };--/**- * The status a log frame projects, or undefined for frames that carry none- * (ACP traffic). The backend's projection rule, applied client-side to the- * same bytes.- */-export function statusFromEntry(- entry: AgentSessionLogEntryDto-): SessionStatus | undefined {- const content = entry.content as { type?: string; event?: string };- if (content?.type !== 'event') return undefined;- if (typeof content.event !== 'string') return undefined;- return { kind: 'event', event: content.event };-}--export type SessionStatusController = {- status: Accessor<SessionStatus>;-};--/**- * Whether the runtime is gone, in either shape the status can take.- *- * The GET snapshot reports it as its own kind; a live frame always arrives- * as `{ kind: 'event', event: 'disconnected' }`, because the projection- * keeps the wire name. Reading only the former is how a live disconnect gets- * missed — which left `working` latched on and the composer waiting on a- * runtime that had gone away.- */-export function isDisconnected(status: SessionStatus): boolean {- return (- status.kind === 'disconnected' ||- (status.kind === 'event' && status.event === 'disconnected')- );-}--/**- * `sessionId` is absent until a just-created session's `POST` lands- * (`pending-session.ts`). There is no log to follow before then, so the- * controller holds its initial `no_messages` — which the pill reads as- * "Starting" — and subscribes once there is something to subscribe to.- */-export function createSessionStatusController(options: {- sessionId: Accessor<string | undefined>;- /** The GET snapshot's status, absent until the session loads. */- seed: Accessor<SessionStatus | undefined>;-}): SessionStatusController {- const [status, setStatus] = createSignal<SessionStatus>({- kind: 'no_messages',- });-- // A live frame is always newer than the snapshot; once one lands, the- // (possibly slower) GET must not roll the status back.- let live = false;-- createEffect(() => {- const seeded = options.seed();- if (seeded && !live) setStatus(seeded);- });-- createEffect(() => {- const id = options.sessionId();- if (!id) return;- live = false;- const unsubscribe = subscribeAgentSessionLog(id, (event) => {- const next = statusFromEntry(event);- if (!next) return;- live = true;- setStatus(next);- });- onCleanup(unsubscribe);- });-- return { status };-}diff --git a/apps/web/src/features/block-agent/debug/Gallery.tsx b/apps/web/src/features/block-agent/debug/Gallery.tsxindex c1f8c6d265..63140d7a46 100644--- a/apps/web/src/features/block-agent/debug/Gallery.tsx+++ b/apps/web/src/features/block-agent/debug/Gallery.tsx@@ -195,6 +195,7 @@ const FIXTURE_DIFF = {const FIXTURE_MESSAGE: FoldedMessage = {agentSessionId: 'demo',requestId: null,+ pending: false,turn: 0,author: { kind: 'agent' },stop: { kind: 'end_turn' },@@ -439,6 +440,7 @@ const FIXTURE_MESSAGE: FoldedMessage = {const FIXTURE_IN_FLIGHT: FoldedMessage = {agentSessionId: 'demo',requestId: null,+ pending: false,turn: 1,author: { kind: 'agent' },stop: null,@@ -481,6 +483,7 @@ const FIXTURE_IN_FLIGHT: FoldedMessage = {const FIXTURE_UNCLOSED: FoldedMessage = {agentSessionId: 'demo',requestId: null,+ pending: false,turn: 2,author: { kind: 'agent' },stop: null,@@ -659,7 +662,6 @@ function MagicChipAskingDemo(props: {presentation={presentation}header={GALLERY_CHIP_HEADER}answer={{- answering: false,respond: async (answer) => {console.log('[gallery] elicitation answer', answer);return true;diff --git a/apps/web/src/features/block-agent/debug/replay/Replay.tsx b/apps/web/src/features/block-agent/debug/replay/Replay.tsxindex f158875fc2..f8c27653ab 100644--- a/apps/web/src/features/block-agent/debug/replay/Replay.tsx+++ b/apps/web/src/features/block-agent/debug/replay/Replay.tsx@@ -18,6 +18,7 @@ import {AgentSessionProvider,useAgentSession,} from '../../context/AgentSessionContext';+import { sessionStatus } from '../../state/session-status';import { SessionStatusPill } from '../../ui';import { createReplayDriver, type ReplayDriver } from './driver';import { registerReplaySession } from './interceptor';@@ -42,10 +43,16 @@ function Knob(props: {}function SessionChrome() {- const { status, working } = useAgentSession();+ const { metadata, turn } = useAgentSession();+ // Same reading as the product composer's `busy()`: a speculated stop+ // already reads as done.+ const working = () => {+ const state = turn();+ return state !== 'idle' && state !== 'disconnected' && state !== 'stopping';+ };return (<div class="flex items-center gap-2 border-b border-edge-muted px-4 py-2">- <SessionStatusPill status={status()} />+ <SessionStatusPill status={sessionStatus(metadata())} /><Show when={working()}><span class="text-xs text-ink-extra-muted">working…</span></Show>diff --git a/apps/web/src/features/block-agent/debug/replay/driver.ts b/apps/web/src/features/block-agent/debug/replay/driver.tsindex c77593bd75..70e6070be4 100644--- a/apps/web/src/features/block-agent/debug/replay/driver.ts+++ b/apps/web/src/features/block-agent/debug/replay/driver.ts@@ -3,7 +3,7 @@** The driver owns a recording split in two: entries before `splitIndex` are* served as the persisted log (`getLog`), the rest stream one at a time- * through the real realtime entry point, `handleAgentSessionLog` — so+ * through the real realtime entry point, `AgentSession.ingest` — so* buffering, Rust row ingestion, the worker fold, and the status projection all* run exactly as they do against the gateway.*@@ -13,8 +13,8 @@* split so the first streamed frames duplicate fetched ones (they must drop).*/+import { AgentSession } from '@core/agent-session/AgentSession';import type { ResultError } from '@core/util/result';-import { handleAgentSessionLog } from '@queries/agent-session/session-fold';import type {AgentSessionLogEntryDto,AgentSessionResponse,@@ -119,7 +119,7 @@ export function createReplayDriver(options: ReplayDriverOptions): ReplayDriver {let timer: ReturnType<typeof setTimeout> | undefined;const emit = (entry: AgentSessionLogEntryDto) => {- handleAgentSessionLog({ agentSessionId, ...entry });+ AgentSession.ingest({ agentSessionId, ...entry });};const pause = () => {diff --git a/apps/web/src/features/block-agent/state/control-message.test.ts b/apps/web/src/features/block-agent/state/control-message.test.tsindex 4a6285b904..7f21e0d52f 100644--- a/apps/web/src/features/block-agent/state/control-message.test.ts+++ b/apps/web/src/features/block-agent/state/control-message.test.ts@@ -6,7 +6,12 @@import type { FoldedMessage } from '@service-agent-fold/generated/types';import { describe, expect, it } from 'vitest';-import { isControlMessage, lastTurnMessage } from './control-message';+import {+ changingModel,+ hasPendingStop,+ isControlMessage,+ lastTurnMessage,+} from './control-message';const message = (id: number,@@ -31,14 +36,23 @@ const reply = (id: number, stopped: boolean) =>[{ kind: 'text', text: 'hello' }],stopped ? ({ kind: 'end_turn' } as FoldedMessage['stop']) : null);-const modelChange = (id: number) =>- message(id, 'user', [+const modelChange = (+ id: number,+ outcome: 'pending' | 'accepted' | 'rejected' = 'accepted',+ pending = false+) => ({+ ...message(id, 'user', [{kind: 'control',control: { kind: 'set_model', model: 'github-copilot/gpt-5.6-terra' },- outcome: { kind: 'accepted' },+ outcome:+ outcome === 'rejected'+ ? { kind: 'rejected', message: 'no such model' }+ : { kind: outcome },},- ]);+ ]),+ pending,+});describe('isControlMessage', () => {it('is the whole message or nothing', () => {@@ -73,3 +87,48 @@ describe('lastTurnMessage', () => {expect(lastTurnMessage([modelChange(0)])).toBeUndefined();});});++describe('changingModel', () => {+ it('is the model of a change still on the wire or unanswered', () => {+ expect(changingModel([prompt(0), modelChange(1, 'pending')], 'old')).toBe(+ 'github-copilot/gpt-5.6-terra'+ );+ expect(+ changingModel([prompt(0), modelChange(1, 'accepted', true)], 'old')+ ).toBe('github-copilot/gpt-5.6-terra');+ });++ it('clears once the runtime moved the model or refused the change', () => {+ expect(+ changingModel(+ [modelChange(0, 'accepted')],+ 'github-copilot/gpt-5.6-terra'+ )+ ).toBeUndefined();+ expect(changingModel([modelChange(0, 'rejected')], 'old')).toBeUndefined();+ expect(changingModel([modelChange(0, 'accepted')], 'old')).toBeUndefined();+ });+});++describe('hasPendingStop', () => {+ const stop = (id: number, pending: boolean) => ({+ ...message(id, 'user', [+ {+ kind: 'control',+ control: { kind: 'stop' },+ outcome: { kind: 'accepted' },+ },+ ]),+ pending,+ });++ it('sees a stop the log has not confirmed', () => {+ expect(hasPendingStop([prompt(1), stop(2, true)])).toBe(true);+ });++ it('ignores confirmed stops and other pending actions', () => {+ expect(hasPendingStop([prompt(1), stop(2, false)])).toBe(false);+ expect(hasPendingStop([{ ...prompt(1), pending: true }])).toBe(false);+ expect(hasPendingStop([modelChange(1, 'pending', true)])).toBe(false);+ });+});diff --git a/apps/web/src/features/block-agent/state/control-message.ts b/apps/web/src/features/block-agent/state/control-message.tsindex 3f54cc1eaa..117950e4ec 100644--- a/apps/web/src/features/block-agent/state/control-message.ts+++ b/apps/web/src/features/block-agent/state/control-message.ts@@ -33,32 +33,43 @@ export function lastTurnMessage(return undefined;}-/** How the runtime disposed of one control, read off its folded message. */-export type ControlOutcome = Extract<- FoldedMessage['parts'][number],- { kind: 'control' }->['outcome'];-/**- * The outcome of the control action `requestId`, once the fold has folded it.+ * The model a change still in flight is switching to, if any.*- * The control endpoint returns each accepted action's id, and the fold- * stamps that same id as `requestId` on the folded message the action- * derives — so this is exact correlation, not a newest-wins scan. The- * composer uses it to resolve a pending model switch: the fold's `model`- * only moves for an accepted change, so a rejection is only visible here.- * `undefined` until the fold has seen the action's frame.+ * A model change is in flight from the moment it is issued - the fold shows+ * it as a pending control, then as an accepted one - until the runtime's+ * response moves `metadata.model`. Read off the newest set-model control:+ * one still unconfirmed by the log (`pending`), or one the runtime has not+ * answered (`outcome: pending`). A rejected change renders its own line and+ * moves nothing, so it is not "changing".*/-export function controlOutcome(+export function changingModel(messages: readonly FoldedMessage[],- requestId: string-): ControlOutcome | undefined {+ current: string | null+): string | undefined {for (let index = messages.length - 1; index >= 0; index--) {const message = messages[index]!;- if (message.requestId !== requestId) continue;- for (const part of message.parts) {- if (part.kind === 'control') return part.outcome;- }+ const part = message.parts[0];+ if (message.parts.length !== 1 || part?.kind !== 'control') continue;+ if (part.control.kind !== 'set_model') continue;+ const inFlight = message.pending || part.outcome.kind === 'pending';+ if (!inFlight || part.control.model === current) return undefined;+ return part.control.model;}return undefined;}++/**+ * A stop this client issued that the log has not confirmed. While one is+ * pending the session reads as stopped whatever the runtime is doing - a+ * sandbox still waking included.+ */+export function hasPendingStop(messages: readonly FoldedMessage[]): boolean {+ return messages.some(+ (message) =>+ message.pending &&+ message.parts.length === 1 &&+ message.parts[0]?.kind === 'control' &&+ message.parts[0].control.kind === 'stop'+ );+}diff --git a/apps/web/src/features/block-agent/state/elicitation-review-sink.ts b/apps/web/src/features/block-agent/state/elicitation-review-sink.tsindex ebe1db4b9e..abeeaeddc5 100644--- a/apps/web/src/features/block-agent/state/elicitation-review-sink.ts+++ b/apps/web/src/features/block-agent/state/elicitation-review-sink.ts@@ -17,10 +17,9 @@ export const DRAFT_FIELD = 'draft';export function createElicitationReviewSink<T>(options: {canAnswer: Accessor<boolean>;- answering: Accessor<boolean>;respond: (answer: ElicitationAnswer) => Promise<boolean>;}): UserToolReviewSink<T> {- const canAct = () => options.canAnswer() && !options.answering();+ const canAct = () => options.canAnswer();return {canAct,lockedNotice: () =>diff --git a/apps/web/src/features/block-agent/state/live-turn.test.ts b/apps/web/src/features/block-agent/state/live-turn.test.tsindex 4ff5bf3d8a..20ce8e4220 100644--- a/apps/web/src/features/block-agent/state/live-turn.test.ts+++ b/apps/web/src/features/block-agent/state/live-turn.test.ts@@ -4,6 +4,7 @@ import { isLiveTurn, liveTurnMessage } from './live-turn';const agent = (turn: number, stop: FoldedMessage['stop']): FoldedMessage => ({agentSessionId: 'session',+ pending: false,requestId: null,turn,author: { kind: 'agent' },@@ -12,6 +13,7 @@ const agent = (turn: number, stop: FoldedMessage['stop']): FoldedMessage => ({});const user = (turn: number): FoldedMessage => ({agentSessionId: 'session',+ pending: false,requestId: null,turn,author: { kind: 'user', userId: 'u' },@@ -20,6 +22,7 @@ const user = (turn: number): FoldedMessage => ({});const control = (turn: number): FoldedMessage => ({agentSessionId: 'session',+ pending: false,requestId: 'r',turn,author: { kind: 'user', userId: 'u' },diff --git a/apps/web/src/features/block-agent/state/session-status.ts b/apps/web/src/features/block-agent/state/session-status.tsnew file mode 100644index 0000000000..c62f891340--- /dev/null+++ b/apps/web/src/features/block-agent/state/session-status.ts@@ -0,0 +1,19 @@+/**+ * The status pill's input, read off the fold's metadata.+ *+ * Status is a projection of the log - the last system event's wire name -+ * and the fold carries it on `SessionMetadata.status`, so the pill needs no+ * feed of its own. `null` means the runtime has reported nothing yet, which+ * the pill shows as Starting.+ */++import type { SessionStatusLike } from '@core/component/AgentSessionStatusPill';+import type { SessionMetadata } from '@service-agent-fold/generated/types';++export function sessionStatus(+ metadata: SessionMetadata | undefined+): SessionStatusLike {+ const status = metadata?.status;+ if (!status) return { kind: 'no_messages' };+ return { kind: 'event', event: status };+}diff --git a/apps/web/src/features/block-agent/state/session-summary.test.ts b/apps/web/src/features/block-agent/state/session-summary.test.tsindex 2fd66362f2..086e8d21ab 100644--- a/apps/web/src/features/block-agent/state/session-summary.test.ts+++ b/apps/web/src/features/block-agent/state/session-summary.test.ts@@ -14,6 +14,7 @@ function message(turn: number, parts: MessagePart[]): FoldedMessage {return {agentSessionId: 'session',requestId: null,+ pending: false,turn,author: { kind: 'agent' },parts,diff --git a/apps/web/src/features/block-agent/ui/AgentInput.tsx b/apps/web/src/features/block-agent/ui/AgentInput.tsxindex 475922b40c..b8077f5360 100644--- a/apps/web/src/features/block-agent/ui/AgentInput.tsx+++ b/apps/web/src/features/block-agent/ui/AgentInput.tsx@@ -38,6 +38,17 @@ export interface AgentInputProps {* input is empty, Enter and the matching button do exactly that.*/hasQueuedMessages?: boolean;+ /**+ * A stop is already on its way. The queue advances when the turn it ends+ * actually ends, so a second stop does nothing but post again.+ */+ stopPending?: boolean;+ /**+ * Enter or the send button with an empty input and a queued message. Falls+ * back to `onStop`, which is the mechanism: the queue advances when the+ * turn it waits on ends.+ */+ onSendNext?: () => void;disabled?: boolean;autofocus?: boolean;/**@@ -89,18 +100,26 @@ export function AgentInput(props: AgentInputProps) {props.onSend(content);};+ // Deliberately not gated on `busy`. A speculated stop reads as done+ // everywhere else, so `busy` is already false while the runtime is still+ // winding the turn down - and that is exactly when a waiting message is+ // most worth advancing. What does gate it is a stop already in flight:+ // repeating it just posts another cancel for the same turn.const canSendNext = () =>markdown().trim().length === 0 &&- props.busy &&- props.hasQueuedMessages &&+ props.hasQueuedMessages === true &&+ !props.stopPending &&!props.disabled &&props.onStop !== undefined;const sendNext = () => {if (!canSendNext()) return;- // Stop bypasses the server queue. The cancelled turn ending immediately- // dispatches its oldest waiting action, so the queue remains FIFO.- props.onStop?.();+ // Stop bypasses the server queue: the fold shows it at once as a pending+ // Stopped line, and when the runtime ends the cancelled turn the server+ // dispatches the oldest waiting action, so the queue remains FIFO. How+ // soon that is depends on the runtime - a booting sandbox cannot be+ // interrupted until it is up.+ (props.onSendNext ?? props.onStop)?.();};const editor = buildConfig('chat')@@ -224,19 +243,19 @@ export function AgentInput(props: AgentInputProps) {</Show><div class="ml-auto shrink-0"><Show- when={props.busy && props.onStop}+ when={canSendNext()}fallback={- <SendButton- appearance="composer"- tooltip="Send"- disabled={!canSend()}- onClick={send}- />- }- >- <Show- when={canSendNext()}- fallback={+ <Show+ when={props.busy && props.onStop}+ fallback={+ <SendButton+ appearance="composer"+ tooltip="Send"+ disabled={!canSend()}+ onClick={send}+ />+ }+ ><Buttonvariant={isTouchDevice() ? 'ghost' : 'strong'}size="icon-composer"@@ -250,18 +269,18 @@ export function AgentInput(props: AgentInputProps) {><div class="size-3.5 not-touch:size-[13.125px] rounded-sm bg-current" /></Button>- }+ </Show>+ }+ >+ <SendButton+ appearance="composer"+ aria-label="Send next queued message"+ tooltip="Send next queued message"+ shortcut="Enter"+ onClick={sendNext}>- <SendButton- appearance="composer"- aria-label="Send next queued message"- tooltip="Send next queued message"- shortcut="Enter"- onClick={sendNext}- >- <EnterIcon />- </SendButton>- </Show>+ <EnterIcon />+ </SendButton></Show></div></div>diff --git a/apps/web/src/features/block-agent/ui/AgentModelSelector.tsx b/apps/web/src/features/block-agent/ui/AgentModelSelector.tsxindex eeccda9842..dedc20f04c 100644--- a/apps/web/src/features/block-agent/ui/AgentModelSelector.tsx+++ b/apps/web/src/features/block-agent/ui/AgentModelSelector.tsx@@ -35,7 +35,6 @@ import type { ModelOption } from '@service-agent-fold/generated/types';import { Button, cn, Dropdown } from '@ui';import { createMemo, createSignal, For, Show } from 'solid-js';import { groupOptions, withoutRedundantGroups } from './model-groups';-import { TextShimmer } from './TextShimmer';/** Compact ghost pill — same size as the short-list trigger and chat's selector. */const PILL_TRIGGER_CLASS =@@ -63,9 +62,9 @@ export interface AgentModelSelectorProps {/** Current model id, when the fold has learned it. */model: string | null;/**- * A change to this model is on the wire. The pill shows it, shimmering,- * so the switch is visibly in progress rather than appearing not to have- * registered — the request can block for a whole container resume.+ * A change to this model the fold has shown but `metadata.model` has not+ * caught up to. The pill reads it as the current model at once and stays+ * interactive; a runtime rejection later reverts it through the fold.*/changingTo?: string;/** The models the harness offers, in the order it listed them. */@@ -103,8 +102,6 @@ export function AgentModelSelector(props: AgentModelSelectorProps) {: options();return groupOptions(matching);});- const disabled = () => props.disabled || props.changingTo !== undefined;-const openSheet = (open: boolean) => {setSheetOpen(open);if (!open) setQuery('');@@ -129,14 +126,10 @@ export function AgentModelSelector(props: AgentModelSelectorProps) {variant="ghost"size="sm"aria-label="Agent model"- disabled={disabled()}+ disabled={props.disabled}class="h-8 max-w-[60vw] min-w-0 justify-start gap-1 rounded-lg border-none bg-transparent px-1.5 text-left text-sm text-ink-subtle hover:bg-hover">- <TextShimmer- text={label()}- active={props.changingTo !== undefined}- class="min-w-0 truncate"- />+ <span class="min-w-0 truncate">{label()}</span><CaretDown class="size-3.5 shrink-0" /></MobileDrawer.Trigger><MobileDrawer.Portal>@@ -209,9 +202,9 @@ export function AgentModelSelector(props: AgentModelSelectorProps) {variant="ghost"size="sm"class={PILL_TRIGGER_CLASS}- disabled={disabled()}+ disabled={props.disabled}>- <TextShimmer text={label()} active={props.changingTo !== undefined} />+ {label()}<CaretDown /></Dropdown.Trigger><Dropdown.Content class="w-60 max-w-[calc(100vw-1rem)] overflow-hidden">@@ -254,7 +247,7 @@ export function AgentModelSelector(props: AgentModelSelectorProps) {value={shown()}options={catalogOptions()}onSelect={pick}- disabled={disabled()}+ disabled={props.disabled}ariaLabel="Agent model"searchPlaceholder="Search models"triggerClass={PILL_TRIGGER_CLASS}diff --git a/apps/web/src/features/block-agent/ui/WorkingLine.test.tsx b/apps/web/src/features/block-agent/ui/WorkingLine.test.tsxindex 0655d94654..9b5cac3d42 100644--- a/apps/web/src/features/block-agent/ui/WorkingLine.test.tsx+++ b/apps/web/src/features/block-agent/ui/WorkingLine.test.tsx@@ -3,21 +3,29 @@import { cleanup, render } from '@solidjs/testing-library';import { afterEach, describe, expect, it } from 'vitest';import { WorkingLine } from './WorkingLine';-import { WORKING_LABEL } from './working-verbs';afterEach(cleanup);describe('WorkingLine', () => {- it('opens on the base word, so short turns never show a verb', () => {+ it('reads "Working" when the caller has nothing more specific to say', () => {const { container } = render(() => <WorkingLine />);- expect(container.textContent).toContain(WORKING_LABEL);+ expect(container.textContent).toContain('Working');});- it('offers one stable label rather than a rotating one', () => {- const { getAllByLabelText } = render(() => <WorkingLine />);+ it('shows the label the caller derives from state', () => {+ const { container } = render(() => <WorkingLine label="Running tools" />);- expect(getAllByLabelText(WORKING_LABEL)).toHaveLength(1);+ expect(container.textContent).toContain('Running tools');+ expect(container.textContent).not.toContain('Working');+ });++ it('offers one accessible label, matching the visible one', () => {+ const { getAllByLabelText } = render(() => (+ <WorkingLine label="Stopping" />+ ));++ expect(getAllByLabelText('Stopping')).toHaveLength(1);});it('has nothing to expand, so it is not a control', () => {diff --git a/apps/web/src/features/block-agent/ui/WorkingLine.tsx b/apps/web/src/features/block-agent/ui/WorkingLine.tsxindex 03a6544946..e5144e4170 100644--- a/apps/web/src/features/block-agent/ui/WorkingLine.tsx+++ b/apps/web/src/features/block-agent/ui/WorkingLine.tsx@@ -3,65 +3,38 @@** A sibling of `Thought`, deliberately shaped differently. A thought row leads* with a caret because there is text behind it; this row has nothing to- * expand, so the caret gives way to a dot that breathes on the shimmer's own- * period, and the row is not a control at all. The leading slot keeps the+ * expand, so the caret gives way to three dots that ripple on the shimmer's+ * own period, and the row is not a control at all. The leading slot keeps the* caret's width so the label does not shift sideways once reasoning arrives* and the row becomes a `Thought`.+ *+ * The label is the caller's: it says what the session is doing (`Sending`,+ * `Running tools`, `Stopping`), so it changes only when the state does.*/-import { createSignal, onCleanup } from 'solid-js';import { TextShimmer } from './TextShimmer';-import { createVerbDraw, WORKING_LABEL } from './working-verbs';--/**- * How long a word holds. Faster reads as thrashing rather than work. The first- * word holds for a full interval too, so the short turns that make up most of- * a session never show a verb at all.- */-const HOLD_MS = 4000;-/** How long the crossfade between words runs. */-const SWAP_MS = 180;--export function WorkingLine() {- const [verb, setVerb] = createSignal(WORKING_LABEL);- const [swapping, setSwapping] = createSignal(false);-- const drawVerb = createVerbDraw();- let swapTimer: ReturnType<typeof setTimeout> | undefined;+export interface WorkingLineProps {+ /** What the turn is doing right now. Defaults to `Working`. */+ label?: string;+}- const rotation = setInterval(() => {- setSwapping(true);- swapTimer = setTimeout(() => {- setVerb(drawVerb());- setSwapping(false);- }, SWAP_MS);- }, HOLD_MS);+const DEFAULT_LABEL = 'Working';- onCleanup(() => {- clearInterval(rotation);- if (swapTimer !== undefined) clearTimeout(swapTimer);- });+export function WorkingLine(props: WorkingLineProps) {+ const label = () => props.label ?? DEFAULT_LABEL;return (<div class="flex min-h-7 items-center gap-1 py-1 text-xs leading-5 text-ink-extra-muted"><spanaria-hidden="true"- class="flex size-4 shrink-0 items-center justify-center"+ class="agent-working-wave flex size-4 shrink-0 items-center justify-center gap-[2px]">- <span class="agent-working-dot size-[5px] rounded-full bg-current" />+ <span class="size-[3px] rounded-full bg-current" />+ <span class="size-[3px] rounded-full bg-current" />+ <span class="size-[3px] rounded-full bg-current" /></span>- {/* The visible word rotates; the label a screen reader hears does not.- Narrating a synonym every few seconds is noise, and the one fact- worth announcing is that the turn is still open. */}- <TextShimmer- text={verb()}- label={WORKING_LABEL}- active- class={`transition-opacity duration-200 motion-reduce:transition-none ${- swapping() ? 'opacity-0' : ''- }`}- />+ <TextShimmer text={label()} label={label()} active /></div>);}diff --git a/apps/web/src/features/block-agent/ui/index.ts b/apps/web/src/features/block-agent/ui/index.tsindex 00cbf7aca9..6d69a3fa8c 100644--- a/apps/web/src/features/block-agent/ui/index.ts+++ b/apps/web/src/features/block-agent/ui/index.ts@@ -64,4 +64,3 @@ export {type ToolStatus,} from './types';export { WorkingLine } from './WorkingLine';-export { createVerbDraw, WORKING_LABEL } from './working-verbs';diff --git a/apps/web/src/features/block-agent/ui/working-verbs.test.ts b/apps/web/src/features/block-agent/ui/working-verbs.test.tsdeleted file mode 100644index 0ed1167712..0000000000--- a/apps/web/src/features/block-agent/ui/working-verbs.test.ts+++ /dev/null@@ -1,22 +0,0 @@-import { describe, expect, it } from 'vitest';-import { createVerbDraw, VERBS } from './working-verbs';--describe('createVerbDraw', () => {- it('spends the whole list before repeating a verb', () => {- const draw = createVerbDraw();- const drawn = Array.from({ length: VERBS.length }, draw);-- expect(new Set(drawn).size).toBe(VERBS.length);- });-- it('reshuffles rather than running dry', () => {- const draw = createVerbDraw();- const drawn = Array.from({ length: VERBS.length * 3 }, draw);-- expect(drawn.every((verb) => VERBS.includes(verb))).toBe(true);- });-- it('offers gerunds only, so any two read as the same kind of word', () => {- expect(VERBS.every((verb) => verb.endsWith('ing'))).toBe(true);- });-});diff --git a/apps/web/src/features/block-agent/ui/working-verbs.ts b/apps/web/src/features/block-agent/ui/working-verbs.tsdeleted file mode 100644index 0642017d9c..0000000000--- a/apps/web/src/features/block-agent/ui/working-verbs.ts+++ /dev/null@@ -1,64 +0,0 @@-/**- * The words an open turn shows while the agent has produced nothing to read.- *- * Modelled on Claude Code's spinner corpus, but off paper rather than out of a- * kitchen, because that is the work this agent does.- */--export const VERBS: readonly string[] = [- 'Skimming',- 'Poring',- 'Leafing',- 'Combing',- 'Sifting',- 'Thumbing',- 'Excerpting',- 'Pondering',- 'Puzzling',- 'Mulling',- 'Percolating',- 'Weighing',- 'Reconsidering',- 'Drafting',- 'Wordsmithing',- 'Redlining',- 'Tightening',- 'Annotating',- 'Collating',- 'Threading',- 'Indexing',- 'Cross-referencing',-];--/**- * The word an open turn shows before its first rotation, and the label a- * screen reader hears for the whole turn. Deliberately not "Thinking": a bare- * row has no reasoning behind it and the turn may well be running a tool.- */-export const WORKING_LABEL = 'Working';--/**- * A draw that does not repeat until every verb has been used.- *- * Repetition is the one thing that makes a rotation look cheap, so the list is- * drawn down and reshuffled rather than sampled.- */-export function createVerbDraw(- random: () => number = Math.random-): () => string {- let remaining: string[] = [];-- return () => {- if (remaining.length === 0) remaining = shuffled(VERBS, random);- return remaining.pop() ?? WORKING_LABEL;- };-}--function shuffled(pool: readonly string[], random: () => number): string[] {- const out = [...pool];- for (let index = out.length - 1; index > 0; index--) {- const swap = Math.floor(random() * (index + 1));- [out[index], out[swap]] = [out[swap] as string, out[index] as string];- }- return out;-}diff --git a/apps/web/src/index.css b/apps/web/src/index.cssindex 25a9c458bd..234663ad66 100644--- a/apps/web/src/index.css+++ b/apps/web/src/index.css@@ -1016,26 +1016,36 @@ html[data-touch-device='true'] :is(}}-/* The dot leading an open agent turn that has nothing to expand yet. Shares- the shimmer's period so the row reads as one motion, not two. */-@keyframes agent-working-dot {+/* The three dots leading an open agent turn that has nothing to expand yet.+ A staggered ripple on the shimmer's period, so the row reads as one motion,+ not two. */+@keyframes agent-working-wave {0%,+ 60%,100% {- opacity: 0.3;- transform: scale(0.65);+ opacity: 0.35;+ transform: translateY(0);}- 50% {+ 30% {opacity: 1;- transform: scale(1);+ transform: translateY(-2px);}}-.agent-working-dot {- animation: agent-working-dot 1.8s ease-in-out infinite;+.agent-working-wave > * {+ animation: agent-working-wave 1.8s ease-in-out infinite;+}++.agent-working-wave > :nth-child(2) {+ animation-delay: 0.2s;+}++.agent-working-wave > :nth-child(3) {+ animation-delay: 0.4s;}@media (prefers-reduced-motion: reduce) {- .agent-working-dot {+ .agent-working-wave > * {animation: none;opacity: 0.55;}diff --git a/apps/web/src/lib/core/agent-fold/client.ts b/apps/web/src/lib/core/agent-fold/client.tsindex d74f576b19..686c27f344 100644--- a/apps/web/src/lib/core/agent-fold/client.ts+++ b/apps/web/src/lib/core/agent-fold/client.ts@@ -1,9 +1,9 @@/*** The fold, as the app calls it: async functions, worker behind them.*- * One worker per tab, started on first use and kept — every agent channel+ * One worker per tab, started on first use and kept — every agent surface* folds through it, so the wasm module is instantiated once rather than per- * channel, and the live sessions' machines all live in one place.+ * surface, and the live sessions' machines all live in one place.*/import type {@@ -11,8 +11,9 @@ import type {FoldedStreamEvent,SessionMetadata,} from '@service-agent-fold/generated/types';-import type { AgentSessionLogEntryDto } from '@service-agent-harness/generated/schemas';-import type { FoldRequest, FoldResponse } from './protocol';+import type { FoldInput, FoldRequest, FoldResponse } from './protocol';++export type { FoldInput } from './protocol';/** A machine-backed read: the fold's messages plus its current metadata. */export type SessionFoldSnapshot = {@@ -20,17 +21,6 @@ export type SessionFoldSnapshot = {metadata: SessionMetadata;};-/** What a machine that has folded nothing knows — every field still absent. */-const EMPTY_METADATA: SessionMetadata = {- harness: 'unknown',- model: null,- supportedModels: [],- title: null,- availableCommands: [],- status: null,- pendingElicitation: null,-};-interface Pending {resolve: (response: Extract<FoldResponse, { ok: true }>) => void;reject: (error: Error) => void;@@ -40,6 +30,10 @@ let worker: Worker | undefined;const pending = new Map<number, Pending>();let nextId = 0;+/**+ * Lazily constructed on purpose: on iOS, WKWebView deadlocks when a module+ * Worker is constructed eagerly over `tauri://` (apps/web/AGENTS.md).+ */function ensureWorker(): Worker {if (worker) return worker;@@ -66,7 +60,7 @@ function ensureWorker(): Worker {pending.clear();// Dropped so the next call starts a fresh one rather than waiting on a// worker that is not listening. Every open machine died with it, so a- // follower has to reopen — see `openSession`.+ // follower has to push a fresh snapshot.worker = undefined;});@@ -87,87 +81,40 @@ function request(}/**- * Fold a session's log into the messages a channel renders, keeping nothing.- *- * `entries` are passed through exactly as the raw-log endpoint served them:- * the wasm side reads the same `{userId?, direction, content}` shape the- * server writes, a recording stores, and the realtime event carries.- *- * For a session that is still running, {@link openSession} instead — that- * leaves a machine behind for {@link pushSessionEntries} to continue.- */-export async function foldSession(- sessionId: string,- entries: AgentSessionLogEntryDto[]-): Promise<FoldedMessage[]> {- const response = await request((id) => ({- id,- kind: 'once',- sessionId,- entries,- }));- return response.kind === 'once' ? response.messages : [];-}--/**- * Fold a fetched log and leave the machine open for what comes next.- *- * Discards any machine already open for the session, because `entries` start- * at the top of the log: seeding a machine that has already folded them would- * derive every message a second time. So a caller opens once, when it has a- * fresh snapshot, and pushes from then on.- */-export async function openSession(- sessionId: string,- entries: AgentSessionLogEntryDto[]-): Promise<SessionFoldSnapshot> {- const response = await request((id) => ({- id,- kind: 'open',- sessionId,- entries,- }));- return response.kind === 'open'- ? { messages: response.messages, metadata: response.metadata }- : { messages: [], metadata: EMPTY_METADATA };-}--/**- * Fold more frames into an open session, in log order.+ * Fold inputs into a session's machine, in order, and hear what changed.*- * Rejects when the session has no open machine — the worker will not seed one- * from the middle of a log, since the messages that would derive belong to a- * session that never happened.+ * The first input a session ever sends must be a snapshot; the machine+ * refuses live and speculative inputs before one, since folding from the+ * middle of a log derives a session that never happened.*/-export async function pushSessionEntries(+export async function pushSession(sessionId: string,- entries: AgentSessionLogEntryDto[]+ inputs: FoldInput[]): Promise<FoldedStreamEvent[]> {const response = await request((id) => ({id,kind: 'push',sessionId,- entries,+ inputs,}));return response.kind === 'push' ? response.changes : [];}/**- * Every message an open session has folded so far.- *- * For a reader joining a session someone else is already following: the open- * machine is ahead of any snapshot that reader could fetch, so asking it beats- * reopening it.+ * Everything a session's machine holds right now.*- * Rejects when the session has no open machine.+ * For a surface joining a session someone else is already following: the+ * open machine is ahead of any snapshot that surface could fetch, so asking+ * it beats refetching. Rejects when the session has no open machine.*/-export async function sessionMessages(+export async function readSession(sessionId: string): Promise<SessionFoldSnapshot> {- const response = await request((id) => ({ id, kind: 'messages', sessionId }));- return response.kind === 'messages'- ? { messages: response.messages, metadata: response.metadata }- : { messages: [], metadata: EMPTY_METADATA };+ const response = await request((id) => ({ id, kind: 'read', sessionId }));+ if (response.kind !== 'read') {+ throw new Error(`unexpected fold response for session ${sessionId}`);+ }+ return { messages: response.messages, metadata: response.metadata };}/** Drop a session's machine once nothing is watching it. */diff --git a/apps/web/src/lib/core/agent-fold/fold.worker.ts b/apps/web/src/lib/core/agent-fold/fold.worker.tsindex a8e55b4d16..6f063b4123 100644--- a/apps/web/src/lib/core/agent-fold/fold.worker.ts+++ b/apps/web/src/lib/core/agent-fold/fold.worker.ts@@ -11,8 +11,8 @@** It is also where a live session's fold *lives*: one machine per session id,* held across requests. That is the whole reason requests are served strictly- * one at a time below — a machine is a sequence, and answering an `open` and- * a `push` concurrently would fold frames out of order.+ * one at a time below — a machine is a sequence, and answering two `push`es+ * concurrently would fold inputs out of order.*/import { match } from 'ts-pattern';@@ -28,10 +28,10 @@ const streams = new Map<string, FoldStream>();* The tail of the request chain.** Handling a request awaits the wasm module, so without this each request- * would suspend and resume independently and two frames could reach a machine+ * would suspend and resume independently and two inputs could reach a machine* in the wrong order. Chaining every request onto the previous one makes the- * worker serve them in the order they were posted, which is the order the log- * is in.+ * worker serve them in the order they were posted, which is the order the+ * caller folded them in.*/let queue: Promise<void> = Promise.resolve();@@ -39,39 +39,20 @@ async function serve(request: FoldRequest): Promise<FoldResponse> {const wasm = await loadAgentFoldWasm();return match(request)- .with({ kind: 'once' }, ({ id, kind, sessionId, entries }) => ({- id,- kind,- ok: true as const,- messages: wasm.fold_session(sessionId, entries),- }))- .with({ kind: 'open' }, ({ id, kind, sessionId, entries }) => {- // A fresh machine even when one is already open: the entries are a- // snapshot from the top of the log, so replaying them into a machine- // that has already seen them would duplicate every message.- streams.get(sessionId)?.free();- streams.delete(sessionId);- const stream = new wasm.FoldStream(sessionId);- try {- const messages = stream.snapshot(entries);- const metadata = stream.metadata();+ .with({ kind: 'push' }, ({ id, kind, sessionId, inputs }) => {+ // Created on first use. The machine itself refuses anything before a+ // snapshot, so a caller that lost its machine (a worker restart) hears+ // about it on its next live input rather than folding from the middle+ // of a log.+ let stream = streams.get(sessionId);+ if (!stream) {+ stream = new wasm.FoldStream(sessionId);streams.set(sessionId, stream);- return { id, kind, ok: true as const, messages, metadata };- } catch (error) {- stream.free();- throw error;}- })- .with({ kind: 'push' }, ({ id, kind, sessionId, entries }) => {- const stream = streams.get(sessionId);- // Refusing rather than opening one: a machine seeded from the middle of- // a log folds a session that never happened, and a caller that has lost- // its machine needs to refetch, not to keep pushing.- if (!stream) throw new Error(`no open fold for session ${sessionId}`);- const changes = stream.push_rows(entries);+ const changes = stream.push(inputs);return { id, kind, ok: true as const, changes };})- .with({ kind: 'messages' }, ({ id, kind, sessionId }) => {+ .with({ kind: 'read' }, ({ id, kind, sessionId }) => {const stream = streams.get(sessionId);if (!stream) throw new Error(`no open fold for session ${sessionId}`);return {@@ -99,7 +80,7 @@ scope.addEventListener('message', (event: MessageEvent<FoldRequest>) => {response = await serve(request);} catch (error) {// Includes the wasm module failing to load at all, which is why the- // caller treats a failure as "this channel folds to nothing" rather+ // caller treats a failure as "this session folds to nothing" rather// than retrying: a missing module will not appear on a second try.response = {id: request.id,diff --git a/apps/web/src/lib/core/agent-fold/protocol.ts b/apps/web/src/lib/core/agent-fold/protocol.tsindex 558c0c2dd8..72b50a5956 100644--- a/apps/web/src/lib/core/agent-fold/protocol.ts+++ b/apps/web/src/lib/core/agent-fold/protocol.ts@@ -2,14 +2,14 @@* The messages exchanged with the agent-fold worker.** Request/response pairs correlated by `id`, because one worker serves every- * agent channel a session might have open and replies can interleave.+ * agent surface a session might have open and replies can interleave.*- * The worker keeps one fold machine per `sessionId`, which is what makes- * {@link FoldOpenRequest} and {@link FoldPushRequest} halves of one thing- * rather than two ways to fold: a channel opened mid-session catches up by- * opening the machine with its fetched log and then pushes live frames into- * that same machine. Two machines over two halves of one log would derive the- * same messages twice.+ * The worker keeps one fold machine per `sessionId`, created on the first+ * `push` and fed every input after it in order: the fetched log as a+ * snapshot, confirmed rows as they stream in, and this client's own actions+ * the moment they are issued. One machine over one ordered input stream is+ * what keeps a surface opened mid-session from deriving the same messages+ * twice.*/import type {@@ -17,41 +17,55 @@ import type {FoldedStreamEvent,SessionMetadata,} from '@service-agent-fold/generated/types';-import type { AgentSessionLogEntryDto } from '@service-agent-harness/generated/schemas';+import type {+ AgentAction,+ AgentSessionLogEntryDto,+} from '@service-agent-harness/generated/schemas';/**- * Open (or reopen) a session's machine and seed it with a fetched log.- *- * Always starts a fresh machine: the entries are a snapshot from the top of- * the log, so folding them into a machine that already holds them would- * double-count. A caller that has been following the session and does not- * want to lose that state simply does not send this.+ * One thing that can happen to a client's view of a session log. Mirrors+ * `FoldInput` in `crates/agent_fold/src/domain/speculation.rs`.*/-export interface FoldOpenRequest {- id: number;- kind: 'open';- sessionId: string;- entries: AgentSessionLogEntryDto[];-}+export type FoldInput =+ /**+ * Authoritative history from the top of the log. Resets the machine's+ * confirmed tier and settles any speculation the rows already contain.+ * Must be the first input a session's machine sees.+ */+ | { kind: 'snapshot'; rows: AgentSessionLogEntryDto[] }+ /** One durable row, in delivery order. */+ | { kind: 'confirmed'; row: AgentSessionLogEntryDto }+ /**+ * An action this client issued that the log has not confirmed. `action`+ * is the control endpoint's request body, `actionId` the id it will be+ * accepted under, `userId` the caller so the folded message is attributed+ * exactly as the confirmed row will be.+ */+ | {+ kind: 'speculated';+ actionId: string;+ action: AgentAction;+ userId?: string;+ }+ /** An action the server will never log: failed POST, refused control. */+ | { kind: 'retracted'; actionId: string };-/** Fold more frames into an already-open session, in log order. */+/** Fold inputs into a session's machine, in order. */export interface FoldPushRequest {id: number;kind: 'push';sessionId: string;- entries: AgentSessionLogEntryDto[];+ inputs: FoldInput[];}/**- * Read an open session's messages without folding anything.- *- * What a second reader of an already-followed session asks, instead of- * opening the machine again and throwing away the frames it has folded since- * that reader's snapshot was taken.+ * Read a session's machine without folding anything: what a surface joining+ * an already-followed session asks, instead of refetching a log the machine+ * is ahead of.*/-export interface FoldMessagesRequest {+export interface FoldReadRequest {id: number;- kind: 'messages';+ kind: 'read';sessionId: string;}@@ -62,34 +76,17 @@ export interface FoldCloseRequest {sessionId: string;}-/** Fold a log with no machine kept — the one-shot form. */-export interface FoldOnceRequest {- id: number;- kind: 'once';- sessionId: string;- entries: AgentSessionLogEntryDto[];-}--export type FoldRequest =- | FoldOpenRequest- | FoldPushRequest- | FoldMessagesRequest- | FoldCloseRequest- | FoldOnceRequest;+export type FoldRequest = FoldPushRequest | FoldReadRequest | FoldCloseRequest;/** What the worker sends back, one per request. */export type FoldResponse =- | { id: number; ok: true; kind: 'once'; messages: FoldedMessage[] }- // Machine-backed reads also answer with the machine's current metadata,- // so a caller catching up (or joining late) does not have to wait for the- // next `{kind: 'metadata'}` push event to learn the session's title/model.+ | { id: number; ok: true; kind: 'push'; changes: FoldedStreamEvent[] }| {id: number;ok: true;- kind: 'open' | 'messages';+ kind: 'read';messages: FoldedMessage[];metadata: SessionMetadata;}- | { id: number; ok: true; kind: 'push'; changes: FoldedStreamEvent[] }| { id: number; ok: true; kind: 'close' }| { id: number; ok: false; error: string };diff --git a/apps/web/src/lib/core/agent-fold/wasm-module.ts b/apps/web/src/lib/core/agent-fold/wasm-module.tsindex 052ce7801c..07e0479df8 100644--- a/apps/web/src/lib/core/agent-fold/wasm-module.ts+++ b/apps/web/src/lib/core/agent-fold/wasm-module.ts@@ -13,49 +13,30 @@ import type {FoldedStreamEvent,SessionMetadata,} from '@service-agent-fold/generated/types';-import type { AgentSessionLogEntryDto } from '@service-agent-harness/generated/schemas';+import type { FoldInput } from './protocol';/**- * One live session's fold, held open between frames.+ * One live session's fold, held open between inputs.*- * Mirrors `agent_fold::inbound::wasm::FoldStream`. Frames must be handed over- * in log order, and one machine serves a session for its whole life — the- * fetched log and the streamed frames after it go into the same instance, so- * that a channel opened mid-session continues the fold rather than starting a- * second one beside it.+ * Mirrors `agent_fold::inbound::wasm::FoldStream`. Inputs must be handed over+ * in order, a snapshot first, and one machine serves a session for its whole+ * life: the fetched log, the streamed rows after it, and this client's own+ * speculated actions all go into the same instance.*/export interface FoldStream {- /** Replace with durable history; retain row metadata for live overlap. */- snapshot: (entries: AgentSessionLogEntryDto[]) => FoldedMessage[];- /** Reconcile durable rows against the snapshot, preserving delivery order. */- push_rows: (entries: AgentSessionLogEntryDto[]) => FoldedStreamEvent[];/**- * Fold a run of frames and answer with every message derived so far.- *- * The catch-up path. Not a loop of {@link push}: a push serializes the- * message it changed, and a session's frames change the same agent message- * over and over, so replaying a fetched log one frame at a time would- * serialize thousands of whole messages to produce a handful.+ * Fold inputs in order, reporting the changes they implied. Empty for+ * inputs that change nothing renderable, which is most confirmed rows.+ * Throws a string when an input cannot be read or arrives before any+ * snapshot.*/- extend: (- entries: Pick<AgentSessionLogEntryDto, 'direction' | 'content' | 'userId'>[]- ) => FoldedMessage[];+ push: (inputs: FoldInput[]) => FoldedStreamEvent[];/**- * Fold one more frame, reporting the changes it implied.- *- * Empty for the frames that change nothing renderable — handshakes, token- * accounting — which is most of them.+ * Every message as the reader should see it, oldest first: the confirmed+ * conversation with this client's unconfirmed actions on top.*/- push: (- entry: Pick<AgentSessionLogEntryDto, 'direction' | 'content' | 'userId'>- ) => FoldedStreamEvent[];- /** Every message folded so far, oldest first. */messages: () => FoldedMessage[];- /**- * The session metadata as it now stands — what the latest- * `{kind: "metadata"}` event carried, for a caller that caught up with- * {@link extend} and saw no events.- */+ /** The session metadata as it now stands. */metadata: () => SessionMetadata;/** Releases the machine's wasm memory. */free: () => void;@@ -63,18 +44,6 @@ export interface FoldStream {interface AgentFoldWasmModule {default: (input?: { module_or_path?: unknown }) => Promise<unknown>;- /**- * Fold a session's log into the messages a channel renders.- *- * Throws a string when the input cannot be read — a session id that is not- * a UUID, or entries that are not log frames. The fold itself is total, so- * a half-finished or unrecognized frame yields a partially-known message- * rather than an error.- */- fold_session: (- sessionId: string,- entries: AgentSessionLogEntryDto[]- ) => FoldedMessage[];/** Opens a fold for one session. Throws when the id is not a UUID. */FoldStream: new (sessionId: stringdiff --git a/apps/web/src/lib/core/agent-session/AgentSession.test.ts b/apps/web/src/lib/core/agent-session/AgentSession.test.tsnew file mode 100644index 0000000000..b2e2004f07--- /dev/null+++ b/apps/web/src/lib/core/agent-session/AgentSession.test.ts@@ -0,0 +1,464 @@+/**+ * The class against a mocked worker client and harness client: inputs reach+ * the machine in order with the snapshot first, an issued action is+ * speculated before its POST and settled by the answer, and the last release+ * closes the machine.+ */++import type { FoldInput } from '@core/agent-fold/client';+import type { FoldedStreamEvent } from '@service-agent-fold/generated/types';+import type {+ AgentSessionLogEntryDto,+ AgentSessionLogResponse,+} from '@service-agent-harness/generated/schemas';+import { err, ok, type Result } from 'neverthrow';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const fold = vi.hoisted(() => ({+ pushSession: vi.fn(),+ readSession: vi.fn(),+ closeSession: vi.fn(),+}));+const harness = vi.hoisted(() => ({+ get: vi.fn(),+ getLog: vi.fn(),+ control: vi.fn(),+}));+const socket = vi.hoisted(() => ({+ listeners: new Set<() => void>(),+ subscribeSocketSessionStarted: vi.fn((listener: () => void) => {+ socket.listeners.add(listener);+ return () => socket.listeners.delete(listener);+ }),+}));++vi.mock('@core/agent-fold/client', () => fold);+vi.mock('@service-agent-harness/client', () => ({+ agentHarnessServiceClient: harness,+}));+vi.mock('@queries/agent-session/queue-sync', () => ({+ subscribeSocketSessionStarted: socket.subscribeSocketSessionStarted,+}));++import { AgentSession } from './AgentSession';++const SESSION = '01a0abed-279f-724c-9f49-60dbedc79b6e';++function row(n: number): AgentSessionLogEntryDto {+ return {+ id: `00000000-0000-0000-0000-${n.toString(16).padStart(12, '0')}`,+ createdAt: new Date(Date.UTC(2026, 7, 13, 0, 0, n)).toISOString(),+ direction: 'to_server',+ content: { type: 'acp', jsonrpc: '2.0', id: n },+ } as unknown as AgentSessionLogEntryDto;+}++const bot = { id: 'bot-id', name: 'Agent', handle: 'agent' };+const session = { id: SESSION, name: 'A session', canEdit: true };+type LogResult = Result<AgentSessionLogResponse, unknown>;+const logOf = (entries: AgentSessionLogEntryDto[]): LogResult =>+ ok({ bot, entries } as unknown as AgentSessionLogResponse);++/** Every input the worker saw, flattened across pushes. */+const inputs = (): FoldInput[] =>+ fold.pushSession.mock.calls.flatMap((call) => call[1] as FoldInput[]);++/** Let awaited promises settle. */+const settle = () => new Promise((resolve) => setTimeout(resolve, 0));++/** A deferred the test resolves by hand. */+function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((r) => {+ resolve = r;+ });+ return { promise, resolve };+}++beforeEach(() => {+ vi.clearAllMocks();+ socket.listeners.clear();+ // Instances are shared and refcounted, so a test that fails before its+ // `release()` would hand the next one a session that is already loaded.+ for (+ let leaked = AgentSession.get(SESSION);+ leaked;+ leaked = AgentSession.get(SESSION)+ ) {+ leaked.release();+ }+ fold.pushSession.mockResolvedValue([]);+ fold.readSession.mockResolvedValue({ messages: [], metadata: {} });+ harness.get.mockResolvedValue(ok(session));+ harness.getLog.mockResolvedValue(ok({ bot, entries: [row(1)] }));+ harness.control.mockImplementation(+ async (_id: string, request: { actionId: string }) =>+ ok({ actionId: request.actionId, status: 'sent' })+ );+});++describe('AgentSession', () => {+ it('folds the snapshot first, then rows that arrived during the load', async () => {+ const log = deferred<LogResult>();+ harness.getLog.mockReturnValue(log.promise);++ const live = AgentSession.acquire(SESSION);+ AgentSession.ingest({ agentSessionId: SESSION, ...row(2) });+ AgentSession.ingest({ agentSessionId: SESSION, ...row(3) });+ log.resolve(logOf([row(1), row(2)]));+ const record = await live.load();++ expect(record).toEqual({ session, bot });+ expect(inputs()).toEqual([+ { kind: 'snapshot', rows: [row(1), row(2)] },+ { kind: 'confirmed', row: row(2) },+ { kind: 'confirmed', row: row(3) },+ ]);+ live.release();+ });++ it('ignores rows for sessions nobody has open', () => {+ AgentSession.ingest({ agentSessionId: 'other', ...row(1) });+ expect(fold.pushSession).not.toHaveBeenCalled();+ });++ it('speculates before the POST and keeps the id the harness accepted', async () => {+ const live = AgentSession.acquire(SESSION);+ await live.load();+ const events: FoldedStreamEvent[][] = [];+ live.subscribe((batch) => events.push(batch));+ const speculated = {+ kind: 'new',+ message: { turn: 1 },+ } as unknown as FoldedStreamEvent;+ fold.pushSession.mockResolvedValueOnce([speculated]);++ const result = await live.issue(+ { type: 'prompt', prompt: 'hi' },+ { userId: 'macro|[email protected]' }+ );++ expect(result.isOk()).toBe(true);+ const [speculation] = inputs().filter(+ (input) => input.kind === 'speculated'+ );+ expect(speculation).toMatchObject({+ kind: 'speculated',+ action: { type: 'prompt', prompt: 'hi' },+ userId: 'macro|[email protected]',+ });+ const actionId = (speculation as { actionId: string }).actionId;+ // The POST carries the speculated id so the harness can accept it.+ expect(harness.control).toHaveBeenCalledWith(SESSION, {+ type: 'prompt',+ prompt: 'hi',+ actionId,+ });+ // Same id back: nothing to reconcile.+ expect(inputs().filter((input) => input.kind === 'retracted')).toEqual([]);+ expect(events).toEqual([[speculated]]);+ live.release();+ });++ it('reissues the speculation under the id the harness minted instead', async () => {+ harness.control.mockResolvedValue(+ ok({ actionId: 'server-id', status: 'sent' })+ );+ const live = AgentSession.acquire(SESSION);+ await live.load();++ await live.issue({ type: 'prompt', prompt: 'hi' });+ await settle();++ const tail = inputs().slice(-3);+ expect(tail[0]).toMatchObject({ kind: 'speculated' });+ const clientId = (tail[0] as { actionId: string }).actionId;+ expect(tail[1]).toEqual({ kind: 'retracted', actionId: clientId });+ expect(tail[2]).toMatchObject({+ kind: 'speculated',+ actionId: 'server-id',+ });+ // The swap is one push, so a listener sees one replace, not a flicker.+ expect(fold.pushSession).toHaveBeenLastCalledWith(SESSION, [+ tail[1],+ tail[2],+ ]);+ live.release();+ });++ it('leaves a stop alone whatever id it was accepted under', async () => {+ harness.control.mockResolvedValue(+ ok({ actionId: 'server-id', status: 'sent' })+ );+ const live = AgentSession.acquire(SESSION);+ await live.load();++ await live.issue({ type: 'stop' });+ await settle();++ expect(inputs().filter((input) => input.kind === 'retracted')).toEqual([]);+ expect(+ inputs().filter((input) => input.kind === 'speculated')+ ).toHaveLength(1);+ live.release();+ });++ it('retracts a speculation the harness refused', async () => {+ harness.control.mockResolvedValue(err([{ code: 'FORBIDDEN' }]));+ const live = AgentSession.acquire(SESSION);+ await live.load();++ const result = await live.issue({ type: 'prompt', prompt: 'hi' });+ await settle();++ expect(result.isErr()).toBe(true);+ const [speculation] = inputs().filter(+ (input) => input.kind === 'speculated'+ );+ expect(inputs().at(-1)).toEqual({+ kind: 'retracted',+ actionId: (speculation as { actionId: string }).actionId,+ });+ live.release();+ });++ it('speculates an elicitation answer like any other action', async () => {+ const live = AgentSession.acquire(SESSION);+ await live.load();++ await live.issue({+ type: 'respondElicitation',+ requestId: 3,+ action: 'decline',+ });++ expect(+ inputs().filter((input) => input.kind === 'speculated')+ ).toMatchObject([{ action: { type: 'respondElicitation', requestId: 3 } }]);+ expect(inputs().filter((input) => input.kind === 'retracted')).toEqual([]);+ live.release();+ });++ it('retracts a prompt the server only queued', async () => {+ // The harness logs a queued action's row at dispatch, so holding the+ // speculation would show an open turn for the whole wait.+ harness.control.mockImplementation(+ async (_id: string, request: { actionId: string }) =>+ ok({ actionId: request.actionId, status: 'queued' })+ );+ const live = AgentSession.acquire(SESSION);+ await live.load();++ await live.issue({ type: 'prompt', prompt: 'later' });+ await settle();++ const [speculation] = inputs().filter(+ (input) => input.kind === 'speculated'+ );+ expect(inputs().at(-1)).toEqual({+ kind: 'retracted',+ actionId: (speculation as { actionId: string }).actionId,+ });+ live.release();+ });++ it('buffers an action issued before the snapshot behind it', async () => {+ const log = deferred<LogResult>();+ harness.getLog.mockReturnValue(log.promise);+ const live = AgentSession.acquire(SESSION);++ void live.issue({ type: 'prompt', prompt: 'early' });+ await settle();+ expect(fold.pushSession).not.toHaveBeenCalled();++ log.resolve(logOf([]));+ await live.load();+ expect(inputs().map((input) => input.kind)).toEqual([+ 'snapshot',+ 'speculated',+ ]);+ live.release();+ });++ it('shares one instance across acquisitions and closes on the last release', async () => {+ const first = AgentSession.acquire(SESSION);+ const second = AgentSession.acquire(SESSION);+ expect(second).toBe(first);+ await first.load();+ expect(harness.getLog).toHaveBeenCalledOnce();++ first.release();+ expect(fold.closeSession).not.toHaveBeenCalled();+ expect(AgentSession.get(SESSION)).toBe(first);+ second.release();+ expect(fold.closeSession).toHaveBeenCalledWith(SESSION);+ expect(AgentSession.get(SESSION)).toBeUndefined();+ });++ it('re-snapshots when the socket reopens', async () => {+ const live = AgentSession.acquire(SESSION);+ await live.load();+ harness.getLog.mockResolvedValue(ok({ bot, entries: [row(1), row(2)] }));++ for (const listener of socket.listeners) listener();+ await settle();++ expect(inputs().at(-1)).toEqual({+ kind: 'snapshot',+ rows: [row(1), row(2)],+ });+ live.release();+ });++ /** A fold whose turn state is `state` from the moment it loads. */+ const loadedWith = async (state: string) => {+ fold.readSession.mockResolvedValue({+ messages: [],+ metadata: { turn: state },+ });+ const live = AgentSession.acquire(SESSION);+ await live.load();+ return live;+ };++ const speculations = () =>+ inputs().filter((input) => input.kind === 'speculated');++ it.each(['starting', 'running', 'stopping', 'blocked'])(+ 'does not speculate a prompt while a turn is %s: the server queues it',+ async (state) => {+ const live = await loadedWith(state);++ const result = await live.issue({ type: 'prompt', prompt: 'later' });++ expect(speculations()).toEqual([]);+ // Still posted - the queue row is what shows it, not a bubble.+ expect(harness.control).toHaveBeenCalledOnce();+ expect(result.isOk()).toBe(true);+ live.release();+ }+ );++ it.each(['idle', 'disconnected'])(+ 'speculates a prompt while the session is %s',+ async (state) => {+ const live = await loadedWith(state);++ await live.issue({ type: 'prompt', prompt: 'now' });++ expect(speculations()).toHaveLength(1);+ live.release();+ }+ );++ it('speculates a stop and a model change even mid-turn: both ride alongside', async () => {+ const live = await loadedWith('running');++ await live.issue({ type: 'stop' });+ await live.issue({ type: 'setModel', model: 'sonnet' });+ await settle();++ expect(speculations().map((input) => input.action.type)).toEqual([+ 'stop',+ 'setModel',+ ]);+ live.release();+ });++ it('follows the turn state through fold events, not just the load', async () => {+ const live = await loadedWith('idle');+ // The agent starts working: the next prompt belongs in the queue.+ fold.pushSession.mockResolvedValueOnce([+ { kind: 'metadata', metadata: { turn: 'running' } },+ ]);+ AgentSession.ingest({ agentSessionId: SESSION, ...row(2) });+ await settle();++ await live.issue({ type: 'prompt', prompt: 'later' });++ expect(speculations()).toEqual([]);+ live.release();+ });++ it('retracts a speculation the server queued after all', async () => {+ harness.control.mockResolvedValue(+ ok({ actionId: 'server-id', status: 'queued' })+ );+ const live = await loadedWith('idle');++ await live.issue({ type: 'prompt', prompt: 'raced' });+ await settle();++ const [speculation] = speculations();+ expect(inputs().at(-1)).toEqual({+ kind: 'retracted',+ actionId: (speculation as { actionId: string }).actionId,+ });+ live.release();+ });++ it('sends two prompts back to back without speculating the second', async () => {+ const live = await loadedWith('idle');++ // No await between them: the fold's turn state cannot have moved yet, so+ // only the session's own record of what it just folded can catch this.+ const first = live.issue({ type: 'prompt', prompt: 'one' });+ const second = live.issue({ type: 'prompt', prompt: 'two' });+ await Promise.all([first, second]);+ await settle();++ expect(+ speculations().map((input) =>+ input.action.type === 'prompt' ? input.action.prompt : undefined+ )+ ).toEqual(['one']);+ expect(harness.control).toHaveBeenCalledTimes(2);+ live.release();+ });++ it('shows a queued action as dispatched without posting, and takes it back', async () => {+ const live = AgentSession.acquire(SESSION);+ await live.load();+ fold.pushSession.mockClear();++ live.expect(+ 'head-id',+ { type: 'prompt', prompt: 'next' },+ { userId: 'me' }+ );+ await settle();+ expect(inputs()).toEqual([+ {+ kind: 'speculated',+ actionId: 'head-id',+ action: { type: 'prompt', prompt: 'next' },+ userId: 'me',+ },+ ]);+ expect(harness.control).not.toHaveBeenCalled();++ // The head now occupies the turn, so a prompt sent meanwhile is queued+ // and not speculated.+ fold.pushSession.mockClear();+ await live.issue({ type: 'prompt', prompt: 'later' });+ expect(inputs().filter((input) => input.kind === 'speculated')).toEqual([]);++ live.retract('head-id');+ await settle();+ expect(inputs().at(-1)).toEqual({ kind: 'retracted', actionId: 'head-id' });+ live.release();+ });++ it('re-runs a failed load on the next call only', async () => {+ harness.getLog.mockResolvedValueOnce(err([{ code: 'NOT_FOUND' }]));+ const live = AgentSession.acquire(SESSION);+ await expect(live.load()).rejects.toThrow('log could not be fetched');++ const record = await live.load();+ expect(record.bot).toEqual(bot);+ expect(harness.getLog).toHaveBeenCalledTimes(2);+ await live.load();+ expect(harness.getLog).toHaveBeenCalledTimes(2);+ live.release();+ });+});diff --git a/apps/web/src/lib/core/agent-session/AgentSession.ts b/apps/web/src/lib/core/agent-session/AgentSession.tsnew file mode 100644index 0000000000..c7b71bb790--- /dev/null+++ b/apps/web/src/lib/core/agent-session/AgentSession.ts@@ -0,0 +1,358 @@+/**+ * One live agent session: the fold machine, the realtime rows that feed it,+ * and the REST calls that act on it, behind one object with one event stream.+ *+ * Framework-free. A surface acquires the session for the ids it shows and+ * releases it on unmount; every surface showing the same session shares one+ * instance, so the log is fetched once, folded once, and speculated once.+ *+ * Speculation lives in the machine, not here. `issue` folds an action the+ * moment it is sent and the machine promotes it when the log confirms it,+ * rebases it when a foreign row lands first, and drops it if this class+ * retracts it. Listeners only ever see fold events; whether a message is+ * still on the wire is a field on the message, never a second channel.+ */++import {+ closeSession,+ type FoldInput,+ pushSession,+ readSession,+ type SessionFoldSnapshot,+} from '@core/agent-fold/client';+import { subscribeSocketSessionStarted } from '@queries/agent-session/queue-sync';+import {+ type AgentSessionLogEvent,+ entryOf,+} from '@queries/agent-session/realtime-protocol';+import type {+ FoldedStreamEvent,+ TurnState,+} from '@service-agent-fold/generated/types';+import { agentHarnessServiceClient } from '@service-agent-harness/client';+import type {+ AgentAction,+ AgentSessionResponse,+ ControlRequest,+ SessionBot,+} from '@service-agent-harness/generated/schemas';+import { v7 as uuidv7 } from 'uuid';++export type AgentSessionListener = (events: FoldedStreamEvent[]) => void;++/** The session row and the bot it runs as, once the load resolved. */+export type AgentSessionRecord = {+ session: AgentSessionResponse;+ bot: SessionBot;+};++export type IssueResult = Awaited<+ ReturnType<typeof agentHarnessServiceClient.control>+>;++/**+ * Whether this action takes the turn, rather than riding alongside one. ACP+ * runs a prompt at a time, so these are the ones the harness queues; mirrors+ * `AgentAction::occupies_turn` in `agent_runtime_protocol`.+ */+function occupiesTurn(action: AgentAction): boolean {+ return action.type === 'prompt' || action.type === 'compact';+}++export class AgentSession {+ private static readonly open = new Map<string, AgentSession>();++ /**+ * The shared instance for `id`, created on first acquisition. Every+ * acquisition needs a matching {@link release}; the last one closes the+ * machine and drops the subscriptions.+ */+ static acquire(id: string): AgentSession {+ const session = AgentSession.open.get(id) ?? new AgentSession(id);+ AgentSession.open.set(id, session);+ session.references += 1;+ return session;+ }++ /** The open instance for `id`, for a caller that only wants to act on it. */+ static get(id: string): AgentSession | undefined {+ return AgentSession.open.get(id);+ }++ /**+ * Realtime ingress: one persisted row, addressed by session. The socket+ * dispatch and the replay driver both call this; a session nobody has open+ * ignores it.+ */+ static ingest(event: AgentSessionLogEvent): void {+ AgentSession.open+ .get(event.agentSessionId)+ ?.enqueue({ kind: 'confirmed', row: entryOf(event) });+ }++ readonly id: string;++ private references = 0;+ private closed = false;+ /** The snapshot has been folded; inputs no longer wait for it. */+ private ready = false;+ /** Inputs that arrived before the snapshot, in order. */+ private buffered: FoldInput[] = [];+ private readonly listeners = new Set<AgentSessionListener>();+ private readonly unsubscribeSocket: () => void;+ /**+ * Serializes worker pushes so inputs reach the machine in the order this+ * class saw them, even though each push is its own await.+ */+ private chain: Promise<void> = Promise.resolve();+ private loading: Promise<AgentSessionRecord>;+ private loadFailed = false;+ /**+ * The fold's turn state, tracked off the same events listeners see. What+ * {@link issue} reads to know whether an action will reach the runtime or+ * wait in the server's queue.+ */+ private turn: TurnState = 'idle';++ private constructor(id: string) {+ this.id = id;+ // Subscribed before the fetch so no row between the two is lost: rows+ // that arrive during the load are buffered and folded after the snapshot.+ this.unsubscribeSocket = subscribeSocketSessionStarted(() => {+ void this.resync();+ });+ this.loading = this.startLoad();+ }++ /**+ * The load: the session row and the log, fetched and folded. Resolves to+ * the same record for every caller; a load that failed is re-run by the+ * next call, which is how a surface's Retry works.+ */+ load(): Promise<AgentSessionRecord> {+ if (this.loadFailed) {+ this.loadFailed = false;+ this.loading = this.startLoad();+ }+ return this.loading;+ }++ /**+ * Do something to the agent. The action is folded before the harness+ * answers, so its effect is visible at once: a prompt as a pending bubble,+ * a stop as a pending Stopped line, a model change as a pending control.+ * The harness's answer settles it: accepted under the same id, the+ * confirmed row promotes it in place; accepted under another id, the+ * speculation is reissued under that one; refused, it is retracted.+ *+ * An action the server will queue rather than run is not speculated at all+ * - see {@link reaches} - so a waiting prompt shows in the queue and+ * nowhere else.+ *+ * `userId` is the caller, so the pending bubble is attributed exactly as+ * the confirmed row will be.+ */+ async issue(+ action: AgentAction,+ options: { userId?: string } = {}+ ): Promise<IssueResult> {+ const actionId = uuidv7();+ const speculated = this.reaches(action);+ if (speculated) {+ // A prompt we just folded opens a turn, so the next one belongs in the+ // queue. Recorded here rather than waited for: `turn` otherwise only+ // moves when the worker answers, and two prompts sent inside that+ // window would both speculate - the second one showing a bubble the+ // server's `queued` then takes away again.+ if (occupiesTurn(action)) this.turn = 'starting';+ void this.enqueue({+ kind: 'speculated',+ actionId,+ action,+ userId: options.userId,+ });+ }++ // The harness adopts the id the client speculated under; the response+ // names the id it was accepted under and `issue` reconciles the two.+ const request: ControlRequest = { ...action, actionId };+ const result = await agentHarnessServiceClient.control(this.id, request);++ if (!speculated) return result;+ if (result.isErr()) {+ void this.enqueue({ kind: 'retracted', actionId });+ return result;+ }+ // Queued after all: the turn opened between the check and the POST. The+ // harness logs the row only when the queue dispatches it, so holding the+ // speculation would show an open turn for the whole wait.+ if (result.value.status === 'queued') {+ void this.enqueue({ kind: 'retracted', actionId });+ return result;+ }+ // A stop is a notification and carries no id on the wire, so the log+ // confirms it by content whatever id the harness accepted it under.+ const accepted = result.value.actionId;+ if (accepted !== actionId && action.type !== 'stop') {+ void this.apply([+ { kind: 'retracted', actionId },+ {+ kind: 'speculated',+ actionId: accepted,+ action,+ userId: options.userId,+ },+ ]);+ }+ return result;+ }++ /**+ * Show an action the server already holds as if it had dispatched. Nothing+ * is sent: the server queued this action earlier under `actionId`, and the+ * caller has just done the thing that makes it dispatch next - stopped the+ * running turn. The dispatched row arrives under the same id and promotes+ * the speculation in place; `retract` takes it back if the queue says the+ * action is still waiting after all.+ */+ expect(+ actionId: string,+ action: AgentAction,+ options: { userId?: string } = {}+ ): void {+ if (occupiesTurn(action)) this.turn = 'starting';+ void this.enqueue({+ kind: 'speculated',+ actionId,+ action,+ userId: options.userId,+ });+ }++ /** Take back a speculation the log will not confirm. Unknown ids are a no-op. */+ retract(actionId: string): void {+ void this.enqueue({ kind: 'retracted', actionId });+ }++ /**+ * Whether this action reaches the runtime now, rather than waiting in the+ * server's queue.+ *+ * ACP runs one prompt at a time, so the harness queues a prompt or a+ * compact issued while a turn is open and logs nothing until it dispatches.+ * Speculating one anyway would show it twice - a sent-looking bubble in the+ * transcript *and* the queue row that says it is waiting - and then take+ * the bubble away again. Everything else (a stop, a model change, an+ * answer) rides alongside the running turn and is folded at once.+ *+ * A disconnected runtime is not an open turn: the prompt wakes the sandbox,+ * which is exactly the wait worth showing.+ */+ private reaches(action: AgentAction): boolean {+ if (!occupiesTurn(action)) return true;+ return (+ this.turn !== 'starting' &&+ this.turn !== 'running' &&+ this.turn !== 'stopping' &&+ this.turn !== 'blocked'+ );+ }++ /** Fold events, in order. The only way anything about the fold is observed. */+ subscribe(listener: AgentSessionListener): () => void {+ this.listeners.add(listener);+ return () => {+ this.listeners.delete(listener);+ };+ }++ /**+ * Everything the machine holds right now, for a listener that joined late.+ * Ordered after every input pushed so far, so a caller that subscribes+ * first and reads second misses nothing and double-applies nothing worse+ * than a message it already holds.+ */+ snapshot(): Promise<SessionFoldSnapshot> {+ return this.chain.then(() => readSession(this.id));+ }++ release(): void {+ this.references -= 1;+ if (this.references > 0) return;+ if (AgentSession.open.get(this.id) === this)+ AgentSession.open.delete(this.id);+ this.closed = true;+ this.listeners.clear();+ this.unsubscribeSocket();+ closeSession(this.id);+ }++ private startLoad(): Promise<AgentSessionRecord> {+ return this.fetchAndFold().catch((error: unknown) => {+ this.loadFailed = true;+ throw error;+ });+ }++ private async fetchAndFold(): Promise<AgentSessionRecord> {+ const [session, log] = await Promise.all([+ agentHarnessServiceClient.get(this.id),+ agentHarnessServiceClient.getLog(this.id),+ ]);+ if (session.isErr()) {+ throw new Error(`agent session could not be fetched: ${this.id}`);+ }+ if (log.isErr()) {+ throw new Error(`agent session log could not be fetched: ${this.id}`);+ }+ if (this.closed) throw new Error(`agent session released: ${this.id}`);++ await this.apply([{ kind: 'snapshot', rows: log.value.entries }]);+ // Inputs can keep arriving while each push is in flight; drain until a+ // check finds nothing, then flip ready so the next one goes straight in.+ while (this.buffered.length > 0) {+ const inputs = this.buffered;+ this.buffered = [];+ await this.apply(inputs);+ }+ this.ready = true;+ this.turn = (await readSession(this.id)).metadata.turn;+ return { session: session.value, bot: log.value.bot };+ }++ /**+ * A reopened socket is a new socket session: rows may have been missed+ * while it was down. Refetch, and let the machine reconcile the overlap+ * and settle any speculation the log confirmed meanwhile.+ */+ private async resync(): Promise<void> {+ if (!this.ready || this.closed) return;+ const log = await agentHarnessServiceClient.getLog(this.id);+ if (log.isErr() || this.closed) return;+ await this.apply([{ kind: 'snapshot', rows: log.value.entries }]);+ }++ private enqueue(input: FoldInput): Promise<void> {+ if (!this.ready) {+ this.buffered.push(input);+ return Promise.resolve();+ }+ return this.apply([input]);+ }++ private apply(inputs: FoldInput[]): Promise<void> {+ const run = this.chain.then(async () => {+ if (this.closed) return;+ const events = await pushSession(this.id, inputs);+ if (this.closed || events.length === 0) return;+ const metadata = events.findLast((event) => event.kind === 'metadata');+ if (metadata) this.turn = metadata.metadata.turn;+ for (const listener of this.listeners) listener(events);+ });+ // A failed push must not poison the chain for every input after it.+ this.chain = run.catch((error: unknown) => {+ console.error('[agent-session] fold input could not be applied', error);+ });+ return this.chain;+ }+}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChip.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChip.tsxindex f883906dab..8484ff2841 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChip.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChip.tsx@@ -17,10 +17,7 @@ export const MagicChip: Component<presentation={model.presentation()}header={model.header()}onCollapse={props.onCollapse}- answer={{- answering: model.elicitation.answering(),- respond: model.elicitation.respond,- }}+ answer={{ respond: model.elicitation.respond }}onOpen={() => insertSplit({ type: 'agent', id: props.agentSessionId })}/>);diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsxindex 36922cf668..2b0734c167 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx@@ -349,7 +349,7 @@ describe('MagicChipView reviewing a tool draft', () => {<MagicChipViewagentSessionId="session"presentation={asking(true, 'Setting that up.')}- answer={{ answering: false, respond }}+ answer={{ respond }}onOpen={onOpen}/>));@@ -393,7 +393,7 @@ describe('MagicChipView reviewing a tool draft', () => {<MagicChipViewagentSessionId="session"presentation={asking(true)}- answer={{ answering: false, respond }}+ answer={{ respond }}onOpen={onOpen}/>));@@ -422,7 +422,7 @@ describe('MagicChipView reviewing a tool draft', () => {<MagicChipViewagentSessionId="session"presentation={asking(false)}- answer={{ answering: false, respond }}+ answer={{ respond }}onOpen={onOpen}/>));@@ -438,13 +438,9 @@ describe('MagicChipView reviewing a tool draft', () => {expect(respond).not.toHaveBeenCalled();});- it('holds the buttons while an answer is on the wire', () => {+ it('a chip with no answer handler is read-only', () => {const view = render(() => (- <MagicChipView- agentSessionId="session"- presentation={asking(true)}- answer={{ answering: true, respond }}- />+ <MagicChipView agentSessionId="session" presentation={asking(true)} />));expect(view.getByTestId('calendar-composer').dataset.canAct).toBe('false');fireEvent.click(view.getByTestId('composer-execute'));@@ -467,7 +463,7 @@ describe('MagicChipView reviewing a tool draft', () => {<MagicChipViewagentSessionId="session"presentation={presentation()}- answer={{ answering: false, respond }}+ answer={{ respond }}onOpen={onOpen}/>));@@ -553,7 +549,7 @@ describe('MagicChipView asking a form', () => {<MagicChipViewagentSessionId="session"presentation={askingQuestion(colourForm)}- answer={{ answering: false, respond }}+ answer={{ respond }}onOpen={onOpen}/>));@@ -597,7 +593,7 @@ describe('MagicChipView asking a form', () => {<MagicChipViewagentSessionId="session"presentation={askingQuestion(colourForm)}- answer={{ answering: false, respond }}+ answer={{ respond }}/>));fireEvent.input(view.getByPlaceholderText('Type your own answer'), {@@ -618,7 +614,7 @@ describe('MagicChipView asking a form', () => {<MagicChipViewagentSessionId="session"presentation={presentation()}- answer={{ answering: false, respond }}+ answer={{ respond }}/>));fireEvent.click(view.getByRole('radio', { name: 'Blue' }));@@ -640,7 +636,7 @@ describe('MagicChipView asking a form', () => {<MagicChipViewagentSessionId="session"presentation={askingQuestion(colourForm, { canAnswer: false })}- answer={{ answering: false, respond }}+ answer={{ respond }}onOpen={onOpen}/>));@@ -664,7 +660,7 @@ describe('MagicChipView asking a form', () => {elicitationId: 'gh-1',url: 'https://agent.example.com/connect?e=gh-1',})}- answer={{ answering: false, respond }}+ answer={{ respond }}/>));expect(view.getByText('agent.example.com')).toBeTruthy();@@ -690,7 +686,7 @@ describe('MagicChipView asking a form', () => {mode: 'hologram',raw: {},})}- answer={{ answering: false, respond }}+ answer={{ respond }}/>));expect(view.getByText(/cannot display a "hologram" request/)).toBeTruthy();diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsxindex 268356aa2f..1341aec16a 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsx@@ -61,8 +61,6 @@ function isTextEntry(target: EventTarget | null) {/** What the chip's answer to a question does. */export type MagicChipAnswer = {- /** An answer is on the wire; the buttons wait. */- answering: boolean;respond: (answer: ElicitationAnswer) => Promise<boolean>;};@@ -315,8 +313,7 @@ const Question: Component<ChipAsking> = (props) => (tool={review().tool}toolCall={review().toolCall}review={{- canAnswer: () => props.asking.canAnswer,- answering: () => props.locked && props.asking.canAnswer,+ canAnswer: () => props.asking.canAnswer && !props.locked,respond: props.respond,}}/>@@ -376,8 +373,7 @@ export const MagicChipView: Component<{const current = asking();const state = question();if (!current || !state) return undefined;- const locked =- !current.canAnswer || !props.answer || props.answer.answering;+ const locked = !current.canAnswer || !props.answer;return {asking: current,question: state,diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.tsindex 89eaa07e3c..5ae4bccb5b 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts@@ -6,6 +6,7 @@ import {import { queryClient } from '@queries/client';import type {FoldedMessage,+ FoldedStreamEvent,PendingElicitation,SessionMetadata,} from '@service-agent-fold/generated/types';@@ -13,11 +14,21 @@ import { QueryClientProvider } from '@tanstack/solid-query';import { createComponent, createRoot } from 'solid-js';import { beforeEach, describe, expect, it, vi } from 'vitest';-const sessionFold = vi.hoisted(() => ({- acquireAgentSessionFold: vi.fn(),- subscribeAgentSessionLog: vi.fn(),+/**+ * The shared session, faked: what the machine holds when a chip reads it,+ * and the listeners it would tell about fold events.+ */+const live = vi.hoisted(() => ({+ acquire: vi.fn(),+ release: vi.fn(),+ issue: vi.fn(),+ snapshot: {+ messages: [] as unknown[],+ metadata: {} as unknown,+ },+ listeners: new Set<(events: unknown[]) => void>(),}));-const serviceClient = vi.hoisted(() => ({ get: vi.fn(), control: vi.fn() }));+const serviceClient = vi.hoisted(() => ({ get: vi.fn() }));vi.mock('@queries/client', async () => {const { QueryClient } = await import('@tanstack/solid-query');@@ -27,7 +38,24 @@ vi.mock('@queries/client', async () => {}),};});-vi.mock('@queries/agent-session/session-fold', () => sessionFold);+vi.mock('@core/agent-session/AgentSession', () => ({+ AgentSession: {+ acquire: (id: string) => {+ live.acquire(id);+ return {+ id,+ load: () => Promise.resolve({ session: {}, bot: {} }),+ snapshot: () => Promise.resolve(live.snapshot),+ subscribe: (listener: (events: unknown[]) => void) => {+ live.listeners.add(listener);+ return () => live.listeners.delete(listener);+ },+ release: live.release,+ issue: live.issue,+ };+ },+ },+}));vi.mock('@service-agent-harness/client', () => ({agentHarnessServiceClient: serviceClient,}));@@ -42,6 +70,17 @@ vi.mock('@core/component/Toast/Toast', () => ({import { createMagicChipModel } from './create-magic-chip-model';+/** Fold events, as the session would deliver them. */+const emit = (events: FoldedStreamEvent[]) => {+ for (const listener of live.listeners) listener(events);+};+const onChange = (messages: FoldedMessage[]) =>+ emit(messages.map((message) => ({ kind: 'new' as const, message })));+const onReplace = (messages: FoldedMessage[]) =>+ emit([{ kind: 'replace', messages }]);+const onMetadata = (metadata: SessionMetadata) =>+ emit([{ kind: 'metadata', metadata }]);+function createModel(props: MagicChipDecoratorProps) {let model!: ReturnType<typeof createMagicChipModel>;createComponent(QueryClientProvider, {@@ -61,6 +100,7 @@ const prompt: FoldedMessage = {author: { kind: 'user', userId: 'macro|[email protected]' },parts: [{ kind: 'text', text: 'Say hi' }],stop: null,+ pending: false,};const response: FoldedMessage = {@@ -70,6 +110,7 @@ const response: FoldedMessage = {author: { kind: 'agent' },parts: [{ kind: 'text', text: 'Hi!' }],stop: { kind: 'end_turn' },+ pending: false,};const openResponse: FoldedMessage = {@@ -110,12 +151,8 @@ describe('createMagicChipModel', () => {beforeEach(() => {queryClient.clear();vi.clearAllMocks();- sessionFold.subscribeAgentSessionLog.mockReturnValue(vi.fn());- sessionFold.acquireAgentSessionFold.mockResolvedValue({- messages: [prompt, response],- metadata: metadata(null),- release: vi.fn(),- });+ live.listeners.clear();+ live.snapshot = { messages: [prompt, response], metadata: metadata(null) };serviceClient.get.mockResolvedValue({isOk: () => true,isErr: () => false,@@ -125,7 +162,7 @@ describe('createMagicChipModel', () => {canEdit: true,},});- serviceClient.control.mockResolvedValue({ isErr: () => false });+ live.issue.mockResolvedValue({ isErr: () => false });});it.each(['cursor', 'codex-cloud'])(@@ -179,7 +216,7 @@ describe('createMagicChipModel', () => {await settle();expect(model.header()?.pullRequestUrl).toBe(first);- sessionFold.acquireAgentSessionFold.mock.calls[0]![0].onReplace([]);+ onReplace([]);expect(model.header()?.pullRequestUrl).toBe(first);serviceClient.get.mockResolvedValue(snapshot(second));await invalidateAgentSessionMetadata();@@ -224,22 +261,16 @@ describe('createMagicChipModel', () => {it('follows the latest turn and streaming updates without rewinding for late patches', async () => {let model!: ReturnType<typeof createMagicChipModel>;- const release = vi.fn();- sessionFold.acquireAgentSessionFold.mockResolvedValue({- messages: [prompt, response],- metadata: metadata(null),- release,- });+ live.snapshot = { messages: [prompt, response], metadata: metadata(null) };const dispose = createRoot((dispose) => {model = createModel({ ...props, promptedMessage: null });return dispose;});await settle();expect(model.presentation()).toEqual({ kind: 'settled', markdown: 'Hi!' });- const callbacks = sessionFold.acquireAgentSessionFold.mock.calls[0]![0];- callbacks.onChange([{ ...prompt, turn: 3 }]);+ onChange([{ ...prompt, turn: 3 }]);expect(model.presentation()).not.toMatchObject({ markdown: 'Hi!' });- callbacks.onChange([+ onChange([{...openResponse,turn: 3,@@ -250,7 +281,7 @@ describe('createMagicChipModel', () => {kind: 'answering',markdown: 'Newest stream',});- callbacks.onChange([+ onChange([{...response,turn: 1,@@ -258,7 +289,7 @@ describe('createMagicChipModel', () => {},]);expect(model.presentation()).toMatchObject({ markdown: 'Newest stream' });- callbacks.onChange([+ onChange([{...response,turn: 3,@@ -269,13 +300,13 @@ describe('createMagicChipModel', () => {kind: 'settled',markdown: 'Newest answer',});- callbacks.onMetadata(metadata({ ...question, turn: 4 }));+ onMetadata(metadata({ ...question, turn: 4 }));expect(model.presentation()).toMatchObject({kind: 'asking',asking: { question: { turn: 4 } },});dispose();- expect(release).toHaveBeenCalledOnce();+ expect(live.release).toHaveBeenCalledOnce();});it('keeps an explicit message lock when later turns arrive', async () => {@@ -285,11 +316,10 @@ describe('createMagicChipModel', () => {return dispose;});await settle();- const callbacks = sessionFold.acquireAgentSessionFold.mock.calls[0]![0];- callbacks.onChange([+ onChange([{ ...response, turn: 3, parts: [{ kind: 'text', text: 'New turn' }] },]);- callbacks.onMetadata(metadata({ ...question, turn: 3 }));+ onMetadata(metadata({ ...question, turn: 3 }));expect(model.presentation()).toEqual({ kind: 'settled', markdown: 'Hi!' });dispose();});@@ -304,12 +334,7 @@ describe('createMagicChipModel', () => {await settle();expect(presentation()).toEqual({ kind: 'settled', markdown: 'Hi!' });- expect(sessionFold.acquireAgentSessionFold).toHaveBeenCalledWith({- agentSessionId: 'session',- onChange: expect.any(Function),- onReplace: expect.any(Function),- onMetadata: expect.any(Function),- });+ expect(live.acquire).toHaveBeenCalledWith('session');dispose();});@@ -321,8 +346,7 @@ describe('createMagicChipModel', () => {return rootDispose;});await Promise.resolve();- const callbacks = sessionFold.acquireAgentSessionFold.mock.calls[0]![0];- callbacks.onReplace([+ onReplace([prompt,{ ...response, parts: [{ kind: 'text', text: 'Reconstructed answer' }] },]);@@ -330,7 +354,7 @@ describe('createMagicChipModel', () => {kind: 'settled',markdown: 'Reconstructed answer',});- callbacks.onReplace([]);+ onReplace([]);expect(presentation()).not.toEqual({kind: 'settled',markdown: 'Reconstructed answer',@@ -339,11 +363,7 @@ describe('createMagicChipModel', () => {});it('hydrates a disconnected status from the session', async () => {- sessionFold.acquireAgentSessionFold.mockResolvedValue({- messages: [],- metadata: metadata(null),- release: vi.fn(),- });+ live.snapshot = { messages: [], metadata: metadata(null) };let presentation!: ReturnType<typeof createMagicChipModel>['presentation'];const dispose = createRoot((rootDispose) => {presentation = createModel(props).presentation;@@ -361,11 +381,10 @@ describe('createMagicChipModel', () => {});it('offers a question asked in its turn to an editor, and answers on the request id', async () => {- sessionFold.acquireAgentSessionFold.mockResolvedValue({+ live.snapshot = {messages: [prompt, openResponse],metadata: metadata(question),- release: vi.fn(),- });+ };let model!: ReturnType<typeof createMagicChipModel>;const dispose = createRoot((rootDispose) => {model = createModel(props);@@ -380,7 +399,8 @@ describe('createMagicChipModel', () => {asking: { question, canAnswer: true },});expect(await model.elicitation.respond({ action: 'decline' })).toBe(true);- expect(serviceClient.control).toHaveBeenCalledWith('session', {+ // The answer rides the session's optimistic path, not a bare POST.+ expect(live.issue).toHaveBeenCalledWith({type: 'respondElicitation',requestId: 9,action: 'decline',@@ -390,11 +410,10 @@ describe('createMagicChipModel', () => {});it('shows another viewer who is being waited on, and sends nothing for them', async () => {- sessionFold.acquireAgentSessionFold.mockResolvedValue({+ live.snapshot = {messages: [prompt, openResponse],metadata: metadata(question),- release: vi.fn(),- });+ };serviceClient.get.mockResolvedValue({isOk: () => true,isErr: () => false,@@ -418,23 +437,16 @@ describe('createMagicChipModel', () => {expect(presentation.asking.canAnswer).toBe(false);}expect(await model.elicitation.respond({ action: 'decline' })).toBe(false);- expect(serviceClient.control).not.toHaveBeenCalled();+ expect(live.issue).not.toHaveBeenCalled();dispose();});it("a question from a later turn is not this chip's, and the live metadata moves it", async () => {- let onMetadata: ((metadata: SessionMetadata) => void) | undefined;- sessionFold.acquireAgentSessionFold.mockImplementation(- (args: { onMetadata?: (metadata: SessionMetadata) => void }) => {- onMetadata = args.onMetadata;- return Promise.resolve({- messages: [prompt, openResponse],- metadata: metadata({ ...question, turn: 3 }),- release: vi.fn(),- });- }- );+ live.snapshot = {+ messages: [prompt, openResponse],+ metadata: metadata({ ...question, turn: 3 }),+ };let presentation!: ReturnType<typeof createMagicChipModel>['presentation'];const dispose = createRoot((rootDispose) => {presentation = createModel(props).presentation;@@ -444,10 +456,10 @@ describe('createMagicChipModel', () => {await settle();expect(presentation().kind).toBe('answering');- onMetadata?.(metadata(question));+ onMetadata(metadata(question));expect(presentation().kind).toBe('asking');- onMetadata?.(metadata(null));+ onMetadata(metadata(null));expect(presentation().kind).toBe('answering');dispose();diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.tsindex 706f1f4e2c..7e4528d253 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts@@ -7,25 +7,20 @@ import {createElicitationController,type ElicitationController,} from '@app/features/block-agent/context/create-elicitation-controller';+import { AgentSession } from '@core/agent-session/AgentSession';import {MAGIC_CHIP_STATUSES,type MagicChipData,type MagicChipStatus,} from '@macro-inc/lexical-core';import { useAgentSessionQuery } from '@queries/agent-session/session';-import {- acquireAgentSessionFold,- subscribeAgentSessionLog,-} from '@queries/agent-session/session-fold';import { queryReadyGate } from '@queries/gate';import type {FoldedMessage,+ FoldedStreamEvent,SessionMetadata,} from '@service-agent-fold/generated/types';-import type {- AgentSessionLogEntryDto,- SessionStatusDto,-} from '@service-agent-harness/generated/schemas';+import type { SessionStatusDto } from '@service-agent-harness/generated/schemas';import { type Accessor, createMemo, createSignal, onCleanup } from 'solid-js';import {deriveMagicChipPresentation,@@ -34,13 +29,6 @@ import {type MagicChipQuestion,} from './presentation';-function systemEvent(entry: AgentSessionLogEntryDto): string | undefined {- const content = entry.content;- return content.type === 'event' && typeof content.event === 'string'- ? content.event- : undefined;-}-function magicChipStatus(status: SessionStatusDto): MagicChipStatus | undefined {@@ -79,6 +67,21 @@ function modelName(return modelDisplayName(model, metadata.supportedModels);}+/** Replace the message under the same turn and author, or append it. */+function upsert(+ current: FoldedMessage[],+ message: FoldedMessage+): FoldedMessage[] {+ return [+ ...current.filter(+ (existing) =>+ existing.turn !== message.turn ||+ existing.author.kind !== message.author.kind+ ),+ message,+ ];+}+/*** Observe the session lifecycle and the chip's anchored folded turn.*@@ -86,13 +89,15 @@ function modelName(* that turn: the session's metadata names the live question, the session* row names its owner, and {@link ElicitationController} sends the answer.* The header names the persona and model from the session row and the fold.+ *+ * The fold is the shared {@link AgentSession} for the id, so a chip and a+ * block showing the same session fold it once between them.*/export function createMagicChipModel(props: MagicChipData): {presentation: Accessor<MagicChipPresentation>;header: Accessor<MagicChipHeader | undefined>;elicitation: ElicitationController;} {- const [latestEvent, setLatestEvent] = createSignal<string>();const [messages, setMessages] = createSignal<FoldedMessage[]>([]);const sessionQuery = useAgentSessionQuery(() => props.agentSessionId);// Guard pending data so a cold query cannot suspend the surrounding editor.@@ -105,53 +110,32 @@ export function createMagicChipModel(props: MagicChipData): {};const [metadata, setMetadata] = createSignal<SessionMetadata>();const pendingElicitation = () => metadata()?.pendingElicitation ?? undefined;- let active = true;- let release: (() => void) | undefined;- const unsubscribe = subscribeAgentSessionLog(- props.agentSessionId,- (event) => {- const name = systemEvent(event);- if (name) setLatestEvent(name);- }- );+ // The last system event's wire name, which the fold carries as status.+ const latestEvent = () => metadata()?.status ?? undefined;- void acquireAgentSessionFold({- agentSessionId: props.agentSessionId,- onReplace: setMessages,- onChange: (changed) => {- setMessages((current) =>- changed.reduce(- (next, message) => [- ...next.filter(- (existing) =>- existing.turn !== message.turn ||- existing.author.kind !== message.author.kind- ),- message,- ],- current- )- );- },- onMetadata: setMetadata,- })- .then((acquired) => {- if (!active) {- acquired.release();- return;- }- release = acquired.release;- setMessages(acquired.messages);- setMetadata(acquired.metadata);+ const live = AgentSession.acquire(props.agentSessionId);+ const applyEvents = (events: FoldedStreamEvent[]) => {+ for (const event of events) {+ if (event.kind === 'replace') setMessages(event.messages);+ else if (event.kind === 'metadata') setMetadata(event.metadata);+ else setMessages((current) => upsert(current, event.message));+ }+ };+ const unsubscribe = live.subscribe(applyEvents);+ void live+ .load()+ .then(() => live.snapshot())+ .then((snapshot) => {+ setMessages(snapshot.messages);+ setMetadata(snapshot.metadata);}).catch((error: unknown) => {console.error('[magic-chip] session log could not be folded', error);});onCleanup(() => {- active = false;unsubscribe();- release?.();+ live.release();});// Fold patches can arrive out of order. Follow the highest turn, including@@ -169,9 +153,9 @@ export function createMagicChipModel(props: MagicChipData): {return question?.turn === turn() ? question : undefined;};const elicitation = createElicitationController({- sessionId: () => props.agentSessionId,pending: questionForTurn,canEdit,+ issue: (action) => live.issue(action),});const asking = (): MagicChipQuestion | undefined => {const question = questionForTurn();diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.tsindex ce8d5a0941..8e71a1fd49 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts@@ -12,6 +12,7 @@ const response = (overrides: Partial<FoldedMessage> = {}): FoldedMessage => ({author: { kind: 'agent' },parts: [{ kind: 'thought', text: 'Inspecting the repository' }],stop: null,+ pending: false,...overrides,});diff --git a/apps/web/src/lib/queries/agent-session/session-fold.test.ts b/apps/web/src/lib/queries/agent-session/session-fold.test.tsdeleted file mode 100644index 8ceb798e30..0000000000--- a/apps/web/src/lib/queries/agent-session/session-fold.test.ts+++ /dev/null@@ -1,256 +0,0 @@-import type { FoldedMessage } from '@service-agent-fold/generated/types';-import type {- AgentSessionLogEntryDto,- AgentSessionLogResponse,-} from '@service-agent-harness/generated/schemas';-import type { Result } from 'neverthrow';-import { err, ok } from 'neverthrow';-import { beforeEach, describe, expect, it, vi } from 'vitest';--const fold = vi.hoisted(() => ({- closeSession: vi.fn(),- openSession: vi.fn(),- pushSessionEntries: vi.fn(),- sessionMessages: vi.fn(),-}));-const harness = vi.hoisted(() => ({ getLog: vi.fn() }));--vi.mock('@core/agent-fold/client', () => fold);-vi.mock('@service-agent-harness/client', () => ({- agentHarnessServiceClient: harness,-}));--import {- acquireAgentSessionFold,- handleAgentSessionLog,- subscribeAgentSessionLog,-} from './session-fold';--function frame(n: number): AgentSessionLogEntryDto {- return {- id: `00000000-0000-0000-0000-${n.toString(16).padStart(12, '0')}`,- createdAt: new Date(Date.UTC(2026, 7, 13, 0, 0, n)).toISOString(),- direction: 'to_server',- content: { type: 'acp', jsonrpc: '2.0', id: n },- } as unknown as AgentSessionLogEntryDto;-}--function event(session: string, n: number) {- return { agentSessionId: session, ...frame(n) };-}--const bot = { id: 'bot-id', name: 'Agent', handle: 'agent' };-const message = { agentSessionId: 'session-a' } as FoldedMessage;-const metadata = {- model: null,- supportedModels: [],- title: null,- availableCommands: [],- status: null,-};--beforeEach(() => {- vi.clearAllMocks();- fold.openSession.mockResolvedValue({ messages: [message], metadata });- fold.sessionMessages.mockResolvedValue({ messages: [message], metadata });- fold.pushSessionEntries.mockResolvedValue([]);- harness.getLog.mockResolvedValue(ok({ bot, entries: [] }));-});--describe('shared session folds', () => {- it('passes buffered overlap to the durable fold after fetching', async () => {- // This test verifies that buffered entries are replayed during opening.- // Sinks are registered AFTER getting the snapshot to prevent duplicate- // notifications: replayed entries update the worker but don't notify sinks,- // then the caller receives the full snapshot (including replayed messages).- let resolveFetch!: (- value: Result<AgentSessionLogResponse, unknown>- ) => void;- harness.getLog.mockReturnValue(- new Promise<Result<AgentSessionLogResponse, unknown>>((resolve) => {- resolveFetch = resolve;- })- );- const acquired = acquireAgentSessionFold({ agentSessionId: 'session-a' });- handleAgentSessionLog(event('session-a', 2));- handleAgentSessionLog(event('session-a', 3));- resolveFetch(ok({ bot, entries: [frame(1), frame(2)] }));- await acquired;-- expect(fold.openSession).toHaveBeenCalledWith('session-a', [- frame(1),- frame(2),- ]);- expect(fold.pushSessionEntries).toHaveBeenCalledWith('session-a', [- frame(2),- frame(3),- ]);- (await acquired).release();- });-- it('drains every raced row to Rust in delivery order before becoming ready', async () => {- let resolveFetch!: (- value: Result<AgentSessionLogResponse, unknown>- ) => void;- harness.getLog.mockReturnValue(- new Promise((resolve) => {- resolveFetch = resolve;- })- );- const oldChunk = {- ...frame(1),- content: {- type: 'acp',- jsonrpc: '2.0',- method: 'session/update',- params: {- sessionId: 'runtime',- update: {- sessionUpdate: 'agent_message_chunk',- content: { type: 'text', text: 'obsolete' },- },- },- },- };- const oldLifecycle = {- ...frame(2),- content: { type: 'event', event: 'disconnected' },- };- const snapshot = [frame(3), frame(4), frame(5)];- const acquired = acquireAgentSessionFold({- agentSessionId: 'boundary-race',- });- handleAgentSessionLog({ agentSessionId: 'boundary-race', ...oldChunk });- handleAgentSessionLog({ agentSessionId: 'boundary-race', ...oldLifecycle });- handleAgentSessionLog(event('boundary-race', 4));- handleAgentSessionLog(event('boundary-race', 6));- // The successful load selects row 3 while GET is in flight. More obsolete- // and overlapping delivery arrives during both opening and pushing.- fold.openSession.mockImplementationOnce(async () => {- handleAgentSessionLog({ agentSessionId: 'boundary-race', ...oldChunk });- handleAgentSessionLog(event('boundary-race', 5));- });- fold.pushSessionEntries.mockImplementationOnce(async () => {- handleAgentSessionLog({- agentSessionId: 'boundary-race',- ...oldLifecycle,- });- handleAgentSessionLog(event('boundary-race', 4));- handleAgentSessionLog(event('boundary-race', 7));- return [];- });- resolveFetch(ok({ bot, entries: snapshot }));- const result = await acquired;- expect(fold.openSession).toHaveBeenCalledWith('boundary-race', snapshot);- expect(fold.pushSessionEntries.mock.calls).toEqual([- [- 'boundary-race',- [oldChunk, oldLifecycle, frame(4), frame(6), oldChunk, frame(5)],- ],- ['boundary-race', [oldLifecycle, frame(4), frame(7)]],- ]);- result.release();- });-- it('isolates raw and folded events by session', async () => {- const raw: string[] = [];- const changed: FoldedMessage[][] = [];- const unsubscribe = subscribeAgentSessionLog('session-b', (value) =>- raw.push(value.agentSessionId)- );- const acquired = await acquireAgentSessionFold({- agentSessionId: 'session-a',- onChange: (messages) => changed.push(messages),- });- fold.pushSessionEntries.mockResolvedValue([{ kind: 'insert', message }]);-- handleAgentSessionLog(event('session-b', 1));- await Promise.resolve();-- expect(raw).toEqual(['session-b']);- expect(fold.pushSessionEntries).not.toHaveBeenCalled();- expect(changed).toEqual([]);- unsubscribe();- acquired.release();- });-- it('shares one fetch and machine until the last idempotent release', async () => {- const first = await acquireAgentSessionFold({- agentSessionId: 'session-a',- });- const second = await acquireAgentSessionFold({- agentSessionId: 'session-a',- });-- expect(harness.getLog).toHaveBeenCalledTimes(1);- expect(fold.openSession).toHaveBeenCalledTimes(1);- expect(first.bot).toEqual(bot);- first.release();- first.release();- expect(fold.closeSession).not.toHaveBeenCalled();- second.release();- expect(fold.closeSession).toHaveBeenCalledOnce();- expect(fold.closeSession).toHaveBeenCalledWith('session-a');- });-- it('routes metadata push events to metadata sinks, latest wins', async () => {- const seen: unknown[] = [];- const acquired = await acquireAgentSessionFold({- agentSessionId: 'session-a',- onMetadata: (value) => seen.push(value),- });- expect(acquired.metadata).toEqual(metadata);-- fold.pushSessionEntries.mockResolvedValue([- { kind: 'metadata', metadata: { ...metadata, title: 'First' } },- { kind: 'metadata', metadata: { ...metadata, title: 'Second' } },- ]);- handleAgentSessionLog(event('session-a', 1));- await new Promise((resolve) => setTimeout(resolve, 0));-- expect(seen).toEqual([{ ...metadata, title: 'Second' }]);- acquired.release();- });-- it('delivers replacements in order, including empty replacements, only to the matching session', async () => {- const seen: unknown[] = [];- const other = vi.fn();- const acquired = await acquireAgentSessionFold({- agentSessionId: 'session-a',- onChange: (messages) => seen.push(['change', messages]),- onReplace: (messages) => seen.push(['replace', messages]),- });- const second = await acquireAgentSessionFold({- agentSessionId: 'session-b',- onReplace: other,- });- fold.pushSessionEntries.mockResolvedValue([- { kind: 'new', message },- { kind: 'replace', messages: [] },- { kind: 'replace', messages: [message] },- { kind: 'update', message },- ]);- handleAgentSessionLog(event('session-a', 1));- await new Promise((resolve) => setTimeout(resolve, 0));- expect(seen).toEqual([- ['change', [message]],- ['replace', []],- ['replace', [message]],- ['change', [message]],- ]);- expect(other).not.toHaveBeenCalled();- acquired.release();- second.release();- });-- it('releases a failed acquisition without retaining shared state', async () => {- harness.getLog.mockResolvedValueOnce(- err([{ code: 'HTTP_ERROR', message: 'nope' }])- );- await expect(- acquireAgentSessionFold({ agentSessionId: 'session-a' })- ).rejects.toThrow();- await acquireAgentSessionFold({ agentSessionId: 'session-a' });- expect(harness.getLog).toHaveBeenCalledTimes(2);- });-});diff --git a/apps/web/src/lib/queries/agent-session/session-fold.ts b/apps/web/src/lib/queries/agent-session/session-fold.tsdeleted file mode 100644index 9629ca0134..0000000000--- a/apps/web/src/lib/queries/agent-session/session-fold.ts+++ /dev/null@@ -1,202 +0,0 @@-import {- closeSession,- openSession,- pushSessionEntries,- sessionMessages,-} from '@core/agent-fold/client';-import type {- FoldedMessage,- SessionMetadata,-} from '@service-agent-fold/generated/types';-import { agentHarnessServiceClient } from '@service-agent-harness/client';-import type {- AgentSessionLogEntryDto,- SessionBot,-} from '@service-agent-harness/generated/schemas';-import { type AgentSessionLogEvent, entryOf } from './realtime-protocol';--/** Receives the folded messages changed by appended frames. */-export type FoldedMessageSink = (messages: FoldedMessage[]) => void;--/** Receives the session metadata whenever a frame changes it (latest-wins). */-export type SessionMetadataSink = (metadata: SessionMetadata) => void;--/** Receives raw realtime frames for one session. */-export type AgentSessionLogSink = (event: AgentSessionLogEvent) => void;--type SessionState = {- agentSessionId: string;- bot?: SessionBot;- buffered: AgentSessionLogEntryDto[];- foldedSinks: Set<FoldedMessageSink>;- replacementSinks: Set<FoldedMessageSink>;- metadataSinks: Set<SessionMetadataSink>;- opening?: Promise<void>;- ready: boolean;- references: number;-};--const sessions = new Map<string, SessionState>();-const rawSinks = new Map<string, Set<AgentSessionLogSink>>();--/** Follow raw realtime log frames for one session. */-export function subscribeAgentSessionLog(- agentSessionId: string,- sink: AgentSessionLogSink-): () => void {- const sinks = rawSinks.get(agentSessionId) ?? new Set<AgentSessionLogSink>();- sinks.add(sink);- rawSinks.set(agentSessionId, sinks);-- return () => {- sinks.delete(sink);- if (sinks.size === 0) rawSinks.delete(agentSessionId);- };-}--/**- * Acquire the shared live fold for a session.- *- * The first acquisition starts buffering before fetching the persisted log.- * Concurrent acquisitions share that catch-up and worker machine. Call the- * returned `release` once per successful acquisition.- */-export async function acquireAgentSessionFold(args: {- agentSessionId: string;- onChange?: FoldedMessageSink;- onReplace?: FoldedMessageSink;- onMetadata?: SessionMetadataSink;-}): Promise<{- bot: SessionBot;- messages: FoldedMessage[];- metadata: SessionMetadata;- release: () => void;-}> {- const { agentSessionId, onChange, onReplace, onMetadata } = args;- const state = sessions.get(agentSessionId) ?? {- agentSessionId,- buffered: [],- foldedSinks: new Set<FoldedMessageSink>(),- replacementSinks: new Set<FoldedMessageSink>(),- metadataSinks: new Set<SessionMetadataSink>(),- ready: false,- references: 0,- };- state.references += 1;- sessions.set(agentSessionId, state);-- let released = false;- const release = () => {- if (released) return;- released = true;- if (onChange) state.foldedSinks.delete(onChange);- if (onReplace) state.replacementSinks.delete(onReplace);- if (onMetadata) state.metadataSinks.delete(onMetadata);- state.references -= 1;- releaseState(state);- };-- try {- state.opening ??= open(state);- await state.opening;- const snapshot = await sessionMessages(agentSessionId);- const bot = state.bot;- if (!bot) throw new Error(`agent session ${agentSessionId} has no bot`);-- // Add sinks after getting the initial snapshot to avoid duplicate- // notifications: buffered entries replayed during opening would otherwise- // notify the sinks, and then the caller would also process the snapshot- // (which includes those same messages).- if (onChange) state.foldedSinks.add(onChange);- if (onReplace) state.replacementSinks.add(onReplace);- if (onMetadata) state.metadataSinks.add(onMetadata);-- return {- bot,- messages: snapshot.messages,- metadata: snapshot.metadata,- release,- };- } catch (error) {- release();- throw error;- }-}--async function open(state: SessionState): Promise<void> {- let machineOpen = false;- try {- const result = await agentHarnessServiceClient.getLog(state.agentSessionId);- if (result.isErr()) {- throw new Error(`failed to fetch agent session ${state.agentSessionId}`);- }-- state.bot = result.value.bot;- await openSession(state.agentSessionId, result.value.entries);- machineOpen = true;-- // Frames can continue arriving while each worker request is in flight.- // Drain until an empty check and `ready` assignment can happen together.- while (state.buffered.length > 0) {- const buffered = state.buffered;- state.buffered = [];- await push(state, buffered);- }- state.ready = true;- } catch (error) {- if (machineOpen) closeSession(state.agentSessionId);- if (sessions.get(state.agentSessionId) === state) {- sessions.delete(state.agentSessionId);- }- throw error;- }-}--function releaseState(state: SessionState): void {- if (state.references > 0) return;- if (sessions.get(state.agentSessionId) !== state) return;- if (!state.ready && state.opening) {- void state.opening.finally(() => releaseState(state)).catch(() => {});- return;- }- sessions.delete(state.agentSessionId);- if (state.ready) closeSession(state.agentSessionId);-}--/** Route one realtime frame to its session's raw observers and shared fold. */-export function handleAgentSessionLog(event: AgentSessionLogEvent): void {- for (const sink of rawSinks.get(event.agentSessionId) ?? []) sink(event);-- const state = sessions.get(event.agentSessionId);- if (!state) return;- const entry = entryOf(event);- if (!state.ready) {- state.buffered.push(entry);- return;- }- void push(state, [entry]).catch((error: unknown) => {- console.error('[agent-fold] live frame could not be folded', error);- });-}--async function push(- state: SessionState,- entries: AgentSessionLogEntryDto[]-): Promise<void> {- const events = await pushSessionEntries(state.agentSessionId, entries);- if (sessions.get(state.agentSessionId) !== state) return;- // Apply in order: a replacement invalidates every earlier message event,- // and later live updates must land on the newly committed conversation.- for (const event of events) {- if (event.kind === 'metadata') continue;- if (event.kind === 'replace') {- for (const sink of state.replacementSinks) sink(event.messages);- } else {- for (const sink of state.foldedSinks) sink([event.message]);- }- }- const metadata = events.findLast((event) => event.kind === 'metadata');- if (metadata) {- for (const sink of state.metadataSinks) sink(metadata.metadata);- }-}diff --git a/apps/web/src/lib/queries/sync/SyncProvider.tsx b/apps/web/src/lib/queries/sync/SyncProvider.tsxindex f6925f2e09..be6947ebe0 100644--- a/apps/web/src/lib/queries/sync/SyncProvider.tsx+++ b/apps/web/src/lib/queries/sync/SyncProvider.tsx@@ -1,3 +1,4 @@+import { AgentSession } from '@core/agent-session/AgentSession';import {enableGraphqlSoup,isFeatureEnabled,@@ -14,7 +15,6 @@ import {type AgentSessionRenamedEvent,type AgentSessionUpdatedEvent,} from '@queries/agent-session/realtime-protocol';-import { handleAgentSessionLog } from '@queries/agent-session/session-fold';import {handleAgentSessionRenamed,handleAgentSessionUpdated,@@ -114,7 +114,7 @@ export function QuerySyncProvider(props: SyncProviderProps) {withParsedWebsocketPayload<AgentSessionLogEvent>(data.type,data.data,- handleAgentSessionLog+ (event) => AgentSession.ingest(event));}).with({ type: AGENT_SESSION_UPDATED_EVENT }, () => {diff --git a/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts b/apps/web/src/lib/service-clients/service-agent-fold/generated/types.tsindex 2a31afa299..a5db47fb5c 100644--- a/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts+++ b/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts@@ -426,6 +426,12 @@ export type FoldedMessage = {parts: MessagePart[];/** How the turn ended, absent while it remains in flight. */stop: StopReason | null;+ /**+ * Derived from an action this client issued that the log has not yet+ * confirmed. A reader shows it as sending; it flips off in place when+ * the confirmed frame arrives.+ */+ pending: boolean;};/**@@ -753,6 +759,12 @@ export type SessionMetadata = {* connection that asked is gone - the request id dies with it.*/pendingElicitation: PendingElicitation | null;+ /**+ * Where the newest turn stands, as one value. Readers used to derive it+ * from the transcript's tail, the status, and their own record of what+ * they had posted; this is that derivation done once, in the fold.+ */+ turn: TurnState;};/**@@ -1101,6 +1113,24 @@ export type ToolStatus =/** A tool call within a turn, identified by its ACP `toolCallId`. */export type ToolUseId = string;+/** Where the newest turn stands. */+export type TurnState =+ /** No turn is open. */+ | 'idle'+ /**+ * A prompt this client issued is on the wire, unconfirmed, and the agent+ * has produced nothing. Only a speculative fold reports this.+ */+ | 'starting'+ /** A turn is open and the agent is working. */+ | 'running'+ /** A stop was issued against the open turn and no stop reason has arrived. */+ | 'stopping'+ /** The open turn is waiting on the user to answer an elicitation. */+ | 'blocked'+ /** The runtime reported `disconnected`; whatever was open is not moving. */+ | 'disconnected';+/*** How far a user tool has got - the fold's reading of the backend's* `UserToolResponse`, restated each time the call is patched.diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.tsindex 79d3ab2e5e..c16b9a49c4 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts@@ -503,6 +503,10 @@ export const deleteAgentSession = async (/*** Edit access suffices: whoever can prompt the bot through its thread canprompt it here.++A caller may name the action with `actionId`; the response echoes it.+Re-posting an id the session still holds queued or in flight reports that+action's status rather than accepting a duplicate.* @summary Perform a control operation on a live agent session.*/export type controlAgentSessionResponse200 = {diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionId.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionId.tsindex b14e2d1e62..368fac88b0 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionId.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionId.ts@@ -11,10 +11,11 @@ control endpoint, written as the JSON-RPC request id on the action's wireframe, and read back off that frame as `request_id` on the folded messageit derives.-Minted only by the server at accept time, as a v7 uuid so ids sort by mint-time. On the wire and in JSON it is the bare uuid, and a uuid-shaped-request id is the whole ownership test: the server is the only writer of-runtime-bound frames. The machine's own handshake request ids-(`agent_session:{session}:{n}`) are not uuids and stay `None`.+A v7 uuid, so ids sort by mint time. Minted by the server at accept time,+or by a client that speculated the action and named it in the control+request - either way the server is the only writer of runtime-bound+frames, so a uuid-shaped request id remains the whole ownership test. The+machine's own handshake request ids (`agent_session:{session}:{n}`) are+not uuids and stay `None`.*/export type AgentActionId = string;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlRequest.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlRequest.tsindex 9aa8f464b5..eba91feeac 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlRequest.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlRequest.ts@@ -5,6 +5,7 @@* OpenAPI spec version: 0.1.0*/import type { AgentAction } from './agentAction';+import type { ControlRequestAllOf } from './controlRequestAllOf';/*** Request body for a control operation on a live session.@@ -16,4 +17,4 @@ credentials, so that a caller cannot attribute an operation to someone else.Clients serialize this, so both derives are used.*/-export type ControlRequest = AgentAction;+export type ControlRequest = AgentAction & ControlRequestAllOf;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlRequestAllOf.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlRequestAllOf.tsnew file mode 100644index 0000000000..1543ba9463--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlRequestAllOf.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { ControlRequestAllOfActionId } from './controlRequestAllOfActionId';++export type ControlRequestAllOf = {+ actionId?: ControlRequestAllOfActionId;+};diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlRequestAllOfActionId.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlRequestAllOfActionId.tsnew file mode 100644index 0000000000..21e7502eda--- /dev/null+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlRequestAllOfActionId.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * agent_harness_service+ * OpenAPI spec version: 0.1.0+ */+import type { AgentActionId } from './agentActionId';++export type ControlRequestAllOfActionId = null | AgentActionId;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlResponse.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlResponse.tsindex bf24936e68..039ac05581 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlResponse.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlResponse.ts@@ -14,7 +14,8 @@ Clients deserialize this, so both derives are used.*/export interface ControlResponse {/** Matches `requestId` on the folded message this action derives once it-dispatches, and names the queue entry until then. */+dispatches, and names the queue entry until then. The caller's own+`actionId` when it supplied one; a freshly minted id otherwise. */actionId: AgentActionId;/** Whether the action went out or waits in the queue. */status: ControlStatusDto;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.tsindex ae14bba680..19ddf08200 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts@@ -58,6 +58,8 @@ export * from './agentSetModelAction';export * from './botId';export * from './completeRequest';export * from './controlRequest';+export * from './controlRequestAllOf';+export * from './controlRequestAllOfActionId';export * from './controlResponse';export * from './controlStatusDto';export * from './createAgentSessionRequest';diff --git a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json b/apps/web/src/lib/service-clients/service-agent-harness/openapi.jsonindex 8d16a0e071..7ca3f4554b 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json+++ b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json@@ -405,7 +405,7 @@"post": {"tags": ["agent-sessions"],"summary": "Perform a control operation on a live agent session.",- "description": "Edit access suffices: whoever can prompt the bot through its thread can\nprompt it here.",+ "description": "Edit access suffices: whoever can prompt the bot through its thread can\nprompt it here.\n\nA caller may name the action with `actionId`; the response echoes it.\nRe-posting an id the session still holds queued or in flight reports that\naction's status rather than accepting a duplicate.","operationId": "control_agent_session","parameters": [{@@ -1138,7 +1138,7 @@"AgentActionId": {"type": "string","format": "uuid",- "description": "Identifies one accepted [`AgentAction`] end to end: returned by the\ncontrol endpoint, written as the JSON-RPC request id on the action's wire\nframe, and read back off that frame as `request_id` on the folded message\nit derives.\n\nMinted only by the server at accept time, as a v7 uuid so ids sort by mint\ntime. On the wire and in JSON it is the bare uuid, and a uuid-shaped\nrequest id is the whole ownership test: the server is the only writer of\nruntime-bound frames. The machine's own handshake request ids\n(`agent_session:{session}:{n}`) are not uuids and stay `None`."+ "description": "Identifies one accepted [`AgentAction`] end to end: returned by the\ncontrol endpoint, written as the JSON-RPC request id on the action's wire\nframe, and read back off that frame as `request_id` on the folded message\nit derives.\n\nA v7 uuid, so ids sort by mint time. Minted by the server at accept time,\nor by a client that speculated the action and named it in the control\nrequest - either way the server is the only writer of runtime-bound\nframes, so a uuid-shaped request id remains the whole ownership test. The\nmachine's own handshake request ids (`agent_session:{session}:{n}`) are\nnot uuids and stay `None`."},"AgentModelDto": {"type": "object",@@ -1539,6 +1539,22 @@{"$ref": "#/components/schemas/AgentAction","description": "The operation to perform."+ },+ {+ "type": "object",+ "properties": {+ "actionId": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/AgentActionId",+ "description": "The id the caller already speculated this action under, when it has\none. Adopted as the accepted id, so a client that renders the action\noptimistically promotes that entry in place instead of retracting it\nand re-speculating under a server id. Re-sending the same id is not a\nsecond action: see [`ControlResponse`].\n\nNamed rather than flattened so it cannot collide with the action's own\nfields, which are tagged under `type`."+ }+ ]+ }+ }}],"description": "Request body for a control operation on a live session.\n\nA wrapper around the operation rather than the bare enum so that fields\nwhich are about the request rather than the operation have somewhere to go.\nThe acting user is deliberately not one of them: it comes from the caller's\ncredentials, so that a caller cannot attribute an operation to someone else.\n\nClients serialize this, so both derives are used."@@ -1550,7 +1566,7 @@"properties": {"actionId": {"$ref": "#/components/schemas/AgentActionId",- "description": "Matches `requestId` on the folded message this action derives once it\ndispatches, and names the queue entry until then."+ "description": "Matches `requestId` on the folded message this action derives once it\ndispatches, and names the queue entry until then. The caller's own\n`actionId` when it supplied one; a freshly minted id otherwise."},"status": {"$ref": "#/components/schemas/ControlStatusDto",diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentActionId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentActionId.tsindex 1144d789b0..9951d16849 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentActionId.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/agentActionId.ts@@ -11,10 +11,11 @@ control endpoint, written as the JSON-RPC request id on the action's wireframe, and read back off that frame as `request_id` on the folded messageit derives.-Minted only by the server at accept time, as a v7 uuid so ids sort by mint-time. On the wire and in JSON it is the bare uuid, and a uuid-shaped-request id is the whole ownership test: the server is the only writer of-runtime-bound frames. The machine's own handshake request ids-(`agent_session:{session}:{n}`) are not uuids and stay `None`.+A v7 uuid, so ids sort by mint time. Minted by the server at accept time,+or by a client that speculated the action and named it in the control+request - either way the server is the only writer of runtime-bound+frames, so a uuid-shaped request id remains the whole ownership test. The+machine's own handshake request ids (`agent_session:{session}:{n}`) are+not uuids and stay `None`.*/export type AgentActionId = string;diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex 489ecc05ae..240858172b 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -14335,7 +14335,7 @@"AgentActionId": {"type": "string","format": "uuid",- "description": "Identifies one accepted [`AgentAction`] end to end: returned by the\ncontrol endpoint, written as the JSON-RPC request id on the action's wire\nframe, and read back off that frame as `request_id` on the folded message\nit derives.\n\nMinted only by the server at accept time, as a v7 uuid so ids sort by mint\ntime. On the wire and in JSON it is the bare uuid, and a uuid-shaped\nrequest id is the whole ownership test: the server is the only writer of\nruntime-bound frames. The machine's own handshake request ids\n(`agent_session:{session}:{n}`) are not uuids and stay `None`."+ "description": "Identifies one accepted [`AgentAction`] end to end: returned by the\ncontrol endpoint, written as the JSON-RPC request id on the action's wire\nframe, and read back off that frame as `request_id` on the folded message\nit derives.\n\nA v7 uuid, so ids sort by mint time. Minted by the server at accept time,\nor by a client that speculated the action and named it in the control\nrequest - either way the server is the only writer of runtime-bound\nframes, so a uuid-shaped request id remains the whole ownership test. The\nmachine's own handshake request ids (`agent_session:{session}:{n}`) are\nnot uuids and stay `None`."},"AgentChannelScope": {"type": "string",diff --git a/crates/agent_fold/src/domain/fold.rs b/crates/agent_fold/src/domain/fold.rsindex aa32e2019c..7c5d27cd02 100644--- a/crates/agent_fold/src/domain/fold.rs+++ b/crates/agent_fold/src/domain/fold.rs@@ -53,8 +53,12 @@use std::borrow::Cow;+use agent_client_protocol::schema::v1::SessionId;+use crate::domain::log::{AgentSessionId, AgentSessionLog};-use crate::domain::model::{FoldEvent, FoldedMessage, SessionMetadata, TurnId};+use crate::domain::model::{+ ElicitationRequestId, FoldEvent, FoldedMessage, SessionMetadata, TurnId,+};use crate::domain::ports::{FoldMachine, FoldSession, LogRepo};/// Config-option and session-info bookkeeping.@@ -117,7 +121,11 @@ fn fold_machine(log: impl IntoIterator<Item = AgentSessionLog>) -> FoldMachineIm/// Frames must be pushed in log order. A machine only ever grows, so a caller/// tracking a live session keeps one per session and pushes for as long as/// the session lasts.-#[derive(Debug, Default)]+///+/// `Clone` is what makes speculation possible: a+/// [`SpeculativeFold`](crate::domain::speculation::SpeculativeFold) forks the+/// confirmed machine and folds unconfirmed frames onto the copy.+#[derive(Debug, Clone, Default)]pub struct FoldMachineImpl {state: FoldState,replay: replay::Replay,@@ -130,6 +138,91 @@ impl FoldMachineImpl {Self::default()}+ /// Fold a frame this client caused but the log has not confirmed. Every+ /// message it touches is marked [`FoldedMessage::pending`] until the+ /// confirmed frame is folded in its place - the ones it mints, and the+ /// ones it only resolves: an elicitation answer lands on the part the+ /// question already occupies in a message the log confirmed long ago.+ ///+ /// Bypasses the replay gate on purpose. That gate stages runtime-bound+ /// frames while the connection is down or a load is in flight, because a+ /// *logged* frame in that window may belong to a session that will never+ /// answer. A speculated frame is not logged traffic: it is what this+ /// client just asked for, and the whole point is to show it while the+ /// runtime is still booting - exactly when the gate would swallow it.+ pub fn push_speculative(&mut self, log: AgentSessionLog) -> Vec<FoldEvent<'_>> {+ self.state.speculative = true;+ let changes = self.state.step(log);+ self.state.speculative = false;+ for change in &changes {+ if let StepChange::Message(changed) = change+ && let Some(message) = self.state.messages.get_mut(changed.message)+ {+ message.pending = true;+ }+ }+ self.report(changes)+ }++ /// Turn a step's changes into events, refreshing the turn state first.+ fn report(&mut self, mut changes: Vec<StepChange>) -> Vec<FoldEvent<'_>> {+ // The turn state is a projection of everything the step touched, so+ // it is refreshed once per push rather than by every handler.+ if self.state.refresh_turn_state()+ && !changes+ .iter()+ .any(|change| matches!(change, StepChange::Metadata))+ {+ changes.push(StepChange::Metadata);+ }+ changes+ .into_iter()+ .filter_map(|change| match change {+ StepChange::Message(changed) => {+ self.state+ .messages+ .get(changed.message)+ .map(|message| match changed.kind {+ Change::New => FoldEvent::NewMessage(Cow::Borrowed(message)),+ Change::Updated => FoldEvent::MessageUpdate(Cow::Borrowed(message)),+ })+ }+ StepChange::Metadata => Some(FoldEvent::MetadataUpdated(Cow::Borrowed(+ &self.state.metadata,+ ))),+ })+ .collect()+ }++ /// The ACP session id the runtime answers to, once the log has shown it:+ /// the `session/new` or `session/load` that opened it, or any prompt+ /// addressed to it. What a synthesized frame has to name so the replay+ /// gate does not treat it as another session's traffic.+ #[must_use]+ pub fn acp_session_id(&self) -> Option<&SessionId> {+ self.state.acp_session.as_ref()+ }++ /// Whether the open turn has already been asked to stop. A cancel is a+ /// notification carrying no action id, so this is the only way to ask+ /// whether a stop is already reflected here.+ #[must_use]+ pub fn stop_requested(&self) -> bool {+ self.state+ .turn+ .as_ref()+ .is_some_and(|turn| turn.stop_requested)+ }++ /// Whether the question the agent asked under `request_id` has resolved.+ /// An answer rides on the agent's own request id, so a folded answer+ /// leaves no message under the answerer's action id - the question's+ /// outcome is what records that it landed.+ #[must_use]+ pub fn elicitation_answered(&self, request_id: &ElicitationRequestId) -> bool {+ self.state.elicitation_answered(request_id)+ }+/// Every committed message, oldest first. A pending load is invisible here./// The candidate remains in the machine so snapshot catch-up can continue/// through its eventual success or failure on the live stream.@@ -168,29 +261,14 @@ impl FoldMachine for FoldMachineImpl {replay::Outcome::Changes(changes) => changes,replay::Outcome::Staged => return Vec::new(),replay::Outcome::Replaced => {+ self.state.refresh_turn_state();return vec![FoldEvent::MessagesReplaced(Cow::Borrowed(&self.state.messages)),FoldEvent::MetadataUpdated(Cow::Borrowed(&self.state.metadata)),];}};- changes- .into_iter()- .filter_map(|change| match change {- StepChange::Message(changed) => {- self.state- .messages- .get(changed.message)- .map(|message| match changed.kind {- Change::New => FoldEvent::NewMessage(Cow::Borrowed(message)),- Change::Updated => FoldEvent::MessageUpdate(Cow::Borrowed(message)),- })- }- StepChange::Metadata => Some(FoldEvent::MetadataUpdated(Cow::Borrowed(- &self.state.metadata,- ))),- })- .collect()+ self.report(changes)}}diff --git a/crates/agent_fold/src/domain/fold/content.rs b/crates/agent_fold/src/domain/fold/content.rsindex ddb12a9cf5..8204503626 100644--- a/crates/agent_fold/src/domain/fold/content.rs+++ b/crates/agent_fold/src/domain/fold/content.rs@@ -77,6 +77,7 @@ impl FoldState {request_id: None,parts: NonEmpty::one(part),stop: None,+ pending: self.speculative,});self.open_turn().agent = Some(message);return Some((Changed::new(message), 0));diff --git a/crates/agent_fold/src/domain/fold/control.rs b/crates/agent_fold/src/domain/fold/control.rsindex 0f0cd73e26..79343aca05 100644--- a/crates/agent_fold/src/domain/fold/control.rs+++ b/crates/agent_fold/src/domain/fold/control.rs@@ -33,9 +33,12 @@ impl FoldState {outcome: ControlOutcome::Accepted,}),stop: None,+ pending: self.speculative,});self.turn = Some(Turn {id,+ prompt_pending: self.speculative,+ stop_requested: false,prompt_id: Some(prompt_id.clone()),agent: None,permission_positions: HashMap::new(),@@ -71,6 +74,7 @@ impl FoldState {request_id: request_id.and_then(AgentActionId::from_request_id),parts: NonEmpty::one(MessagePart::Control { control, outcome }),stop: None,+ pending: self.speculative,});Some(Changed::new(message))}diff --git a/crates/agent_fold/src/domain/fold/elicitation.rs b/crates/agent_fold/src/domain/fold/elicitation.rsindex a602882321..06ee208b03 100644--- a/crates/agent_fold/src/domain/fold/elicitation.rs+++ b/crates/agent_fold/src/domain/fold/elicitation.rs@@ -336,6 +336,15 @@ impl FoldState {self.clear_pending_elicitation_if(|_| true)}+ /// Whether the question asked under `request_id` has an outcome. See+ /// [`FoldMachineImpl::elicitation_answered`](super::FoldMachineImpl::elicitation_answered).+ pub(super) fn elicitation_answered(&self, request_id: &ElicitationRequestId) -> bool {+ self.messages+ .iter()+ .flat_map(|message| message.parts.iter())+ .any(|part| answered(part, request_id))+ }+/// Forget everything about outstanding elicitations: the connection that/// asked is gone and its request ids with it.pub(super) fn forget_elicitations(&mut self) -> bool {@@ -345,6 +354,22 @@ impl FoldState {}}+/// Whether `part`, or anything nested under it, is the question asked under+/// `request_id` and has stopped being pending.+fn answered(part: &MessagePart, request_id: &ElicitationRequestId) -> bool {+ if let MessagePart::Elicitation {+ request_id: asked,+ outcome,+ ..+ } = part+ {+ return asked == request_id && !matches!(outcome, ElicitationOutcome::Pending);+ }+ part.children()+ .iter()+ .any(|child| answered(child, request_id))+}+/// The tool call (if any) and the renderable request, decoded from ACP's/// typed request plus the raw params for what the typed form loses.fn decode_request(diff --git a/crates/agent_fold/src/domain/fold/replay.rs b/crates/agent_fold/src/domain/fold/replay.rsindex a966975c76..4892707072 100644--- a/crates/agent_fold/src/domain/fold/replay.rs+++ b/crates/agent_fold/src/domain/fold/replay.rs@@ -3,7 +3,7 @@use agent_client_protocol::schema::v1::{AGENT_METHOD_NAMES, InitializeRequest, LoadSessionRequest, LoadSessionResponse,NewSessionRequest, NewSessionResponse, PromptRequest, RequestId, Response,- ResumeSessionRequest, ResumeSessionResponse,+ ResumeSessionRequest, ResumeSessionResponse, SessionId,};use agent_client_protocol::{JsonRpcMessage, JsonRpcResponse, RawJsonRpcMessage, RawJsonRpcParams};use agent_runtime_protocol::domain::schema::v0::{SystemEvent, ToRuntimeMessage, ToServerMessage};@@ -12,7 +12,7 @@ use super::convert::param;use super::state::{FoldState, StepChange};use crate::domain::log::{AgentSessionId, AgentSessionLog, Message};-#[derive(Debug, Default)]+#[derive(Debug, Clone, Default)]pub(super) struct Replay {session: Option<AgentSessionId>,initialization: FoldState,@@ -21,38 +21,46 @@ pub(super) struct Replay {// A failed/abandoned load may still have queued notifications. Handshake// markers invalidate correlations, but do not prove those frames are live.quarantined: bool,- replay_session: Option<String>,+ replay_session: Option<SessionId>,pending_open: Option<(RequestId, Opening)>,}-#[derive(Debug)]+#[derive(Debug, Clone)]enum Opening {New,- Resume,+ /// A resume names the session in its request; the response only confirms.+ Resume {+ session: Option<SessionId>,+ },}impl Opening {- fn accepts(&self, response: &Response<serde_json::Value>) -> bool {+ /// The ACP session id the response opened, or `None` for a response that+ /// does not decode as this opening's success. A resume whose request+ /// named no session reads as `Some(None)`: accepted, id unknown.+ fn accepts(&self, response: &Response<serde_json::Value>) -> Option<Option<SessionId>> {let Response::Result { result, .. } = response else {- return false;+ return None;};match self {Self::New => {NewSessionResponse::from_value(AGENT_METHOD_NAMES.session_new, result.clone())- .is_ok()+ .ok()+ .map(|response| Some(response.session_id.clone()))}- Self::Resume => {+ Self::Resume { session } => {ResumeSessionResponse::from_value(AGENT_METHOD_NAMES.session_resume, result.clone())- .is_ok()+ .ok()+ .map(|_| session.clone())}}}}-#[derive(Debug)]+#[derive(Debug, Clone)]struct Transaction {request: RequestId,- session: String,+ session: SessionId,metadata: crate::domain::model::SessionMetadata,pending_initialize: Option<RequestId>,entries: Vec<AgentSessionLog>,@@ -76,6 +84,7 @@ impl Replay {metadata: transaction.metadata,pending_initialize: transaction.pending_initialize,replaying: true,+ acp_session: Some(transaction.session),..FoldState::default()};for entry in transaction.entries {@@ -133,10 +142,11 @@ impl Replay {return Outcome::Staged;};self.pending_open = None;- self.replay_session = Some(session.to_owned());+ let session = SessionId::new(session);+ self.replay_session = Some(session.clone());self.transaction = Some(Transaction {request: request.id.clone(),- session: session.to_owned(),+ session,metadata: self.initialization.metadata.clone(),pending_initialize: self.initialization.pending_initialize.clone(),entries: vec![entry],@@ -171,7 +181,10 @@ impl Replay {&& ResumeSessionRequest::parse_message(method, params).is_ok()&& self.matches_replay_session(request.params.as_ref()) =>{- self.pending_open = Some((request.id.clone(), Opening::Resume));+ let session = param(request.params.as_ref(), "sessionId")+ .and_then(|value| value.as_str())+ .map(SessionId::new);+ self.pending_open = Some((request.id.clone(), Opening::Resume { session }));return Outcome::Changes(committed.step(entry));}_ => {}@@ -218,8 +231,11 @@ impl Replay {.is_some_and(|(pending, _)| pending == id){let (_, opening) = self.pending_open.take().expect("matched opening request");- if opening.accepts(response) {+ if let Some(session) = opening.accepts(response) {self.quarantined = false;+ if let Some(session) = session {+ committed.acp_session = Some(session);+ }} else {committed.pending_config_requests.remove(id);return Outcome::Staged;@@ -238,7 +254,7 @@ impl Replay {};if param(params, "sessionId").and_then(|v| v.as_str())- .is_some_and(|session| session != candidate.session)+ .is_some_and(|session| session != candidate.session.0.as_ref()){return Outcome::Staged;}@@ -259,8 +275,8 @@ impl Replay {.and_then(|value| value.as_str()).is_some_and(|session| {self.replay_session- .as_deref()- .is_none_or(|expected| session == expected)+ .as_ref()+ .is_none_or(|expected| session == expected.0.as_ref())})}}diff --git a/crates/agent_fold/src/domain/fold/state.rs b/crates/agent_fold/src/domain/fold/state.rsindex 260030d386..ea3fc5eb26 100644--- a/crates/agent_fold/src/domain/fold/state.rs+++ b/crates/agent_fold/src/domain/fold/state.rs@@ -4,8 +4,10 @@ use std::collections::{HashMap, HashSet};use crate::domain::error::FoldError;use crate::domain::harness::{HarnessReader, ToolFrame};+use agent_client_protocol::schema::v1::SessionId;+use crate::domain::log::{AgentSessionId, AgentSessionLog, Message};-use crate::domain::model::{Control, FoldedMessage, SessionMetadata, ToolUseId, TurnId};+use crate::domain::model::{Control, FoldedMessage, SessionMetadata, ToolUseId, TurnId, TurnState};use agent_client_protocol::schema::v1::{CompleteElicitationNotification, CreateElicitationRequest, PromptRequest, RequestId,RequestPermissionRequest, Response, SessionNotification, SessionUpdate,@@ -83,13 +85,21 @@ impl FoldState {/// The fold's state, advanced one log entry at a time by [`State::step`] and/// owned by [`FoldMachineImpl`].-#[derive(Debug, Default)]+#[derive(Debug, Clone, Default)]pub(super) struct FoldState {/// Every message derived so far, oldest first - including the open turn's/// agent message, which is appended to in place as the agent talks.pub(super) messages: Vec<FoldedMessage>,/// User notifications are authoritative only inside a staged load.pub(super) replaying: bool,+ /// The frame being stepped is one this client caused but the log has not+ /// confirmed. Every message it derives is marked pending. Set for one+ /// step by [`FoldMachineImpl::push_speculative`].+ pub(super) speculative: bool,+ /// The ACP session id the runtime answers to, from the request that+ /// opened it or any prompt addressed to it. See+ /// [`FoldMachineImpl::acp_session_id`].+ pub(super) acp_session: Option<SessionId>,/// The session the entry currently being folded belongs to, for/// [`State::warn`]. Set fresh from each log entry, so it is always/// current even though it rarely changes within one fold.@@ -145,9 +155,15 @@ pub(super) struct ToolPath {/// Holds no content of its own. The turn's agent message lives in/// [`State::messages`] as soon as there is one, and everything here is a way/// back into it.-#[derive(Debug)]+#[derive(Debug, Clone)]pub(super) struct Turn {pub(super) id: TurnId,+ /// The prompt that opened this turn is speculative: on the wire, not yet+ /// in the log. Reads as [`TurnState::Starting`] until the agent answers.+ pub(super) prompt_pending: bool,+ /// A stop was issued against this turn and no stop reason has arrived.+ /// Reads as [`TurnState::Stopping`].+ pub(super) stop_requested: bool,/// The `session/prompt` request whose response will close this turn.////// `None` for a turn opened without one - see@@ -224,8 +240,12 @@ impl FoldState {_ => None,},// A stop is a notification: nothing can answer it, so- // it is accepted the moment it is sent.+ // it is accepted the moment it is sent. The turn it+ // interrupts ends through the agent's own stop event.AgentAction::Stop => {+ if let Some(turn) = &mut self.turn {+ turn.stop_requested = true;+ }self.record_control(Control::Stop, None, entry.user_id.clone())}// `control_from_runtime` never yields these: a prompt@@ -234,13 +254,18 @@ impl FoldState {AgentAction::Prompt(_) | AgentAction::RespondElicitation(_) => None,});}+ // A user's prompt opens a turn - and may close the one+ // before it, so it reports on its own.+ if let RawJsonRpcMessage::Request(request) = &acp.0+ && PromptRequest::matches_method(&request.method)+ {+ return self+ .begin_turn(&request.id, request.params.as_ref(), entry.user_id.clone())+ .into_iter()+ .map(StepChange::Message)+ .collect();+ }StepChange::message(match &acp.0 {- // A user's prompt opens a turn.- RawJsonRpcMessage::Request(request)- if PromptRequest::matches_method(&request.method) =>- {- self.begin_turn(&request.id, request.params.as_ref(), entry.user_id.clone())- }// The user's answer to a question or a permission// request. Each map holds only the ids of its own// requests, so trying the elicitations first is order,@@ -479,6 +504,31 @@ impl FoldState {}}+ /// Recompute [`SessionMetadata::turn`] from the state, reporting whether+ /// it moved. Called once per push, after the step, because it is a+ /// projection of several things a step may touch at once.+ pub(super) fn refresh_turn_state(&mut self) -> bool {+ let turn = if self.metadata.status.as_deref() == Some(SystemEvent::Disconnected.as_str()) {+ TurnState::Disconnected+ } else {+ match &self.turn {+ None => TurnState::Idle,+ // Before `Blocked`: a user who pressed stop while the agent+ // was waiting on their answer is owed the stop, not the+ // question they just walked away from.+ Some(turn) if turn.stop_requested => TurnState::Stopping,+ Some(_) if self.metadata.pending_elicitation.is_some() => TurnState::Blocked,+ Some(turn) if turn.prompt_pending && turn.agent.is_none() => TurnState::Starting,+ Some(_) => TurnState::Running,+ }+ };+ if self.metadata.turn == turn {+ return false;+ }+ self.metadata.turn = turn;+ true+ }+/// How to read the frames of whichever harness produced this log.pub(super) fn reader(&self) -> &'static dyn HarnessReader {self.metadata.harness.reader()diff --git a/crates/agent_fold/src/domain/fold/turn.rs b/crates/agent_fold/src/domain/fold/turn.rsindex 446c431d7b..bf4da2c953 100644--- a/crates/agent_fold/src/domain/fold/turn.rs+++ b/crates/agent_fold/src/domain/fold/turn.rs@@ -37,6 +37,7 @@ impl FoldState {request_id: None,parts: NonEmpty::one(MessagePart::Text { text }),stop: None,+ pending: self.speculative,});Some(Changed::new(message))}@@ -47,16 +48,27 @@ impl FoldState {prompt_id: &RequestId,params: Option<&RawJsonRpcParams>,user_id: Option<MacroUserIdStr<'static>>,- ) -> Option<Changed> {- // A second prompt without an intervening response means the previous- // turn never got one. Its agent message is already in `messages` and- // already reads `stop: None`, so there is nothing left to report -- // which is what keeps a push to one changed message.- let closed = self.close_turn(None);- debug_assert!(- closed.is_none(),- "closing a turn without a stop reason changes nothing"- );+ ) -> Vec<Changed> {+ // A speculative prompt behind a stop is the queue head, dispatching+ // once the cancel lands. The turn it follows can only end one way,+ // so that end is predicted here rather than leaving the turn open+ // under the prompt that replaces it. A confirmed prompt never does+ // this: the runtime's own response closes its turn, in log order.+ let closed =+ if self.speculative && self.turn.as_ref().is_some_and(|turn| turn.stop_requested) {+ self.close_turn(Some(StopReason::Cancelled))+ } else {+ // A second prompt without an intervening response means the+ // previous turn never got one. Its agent message is already in+ // `messages` and already reads `stop: None`, so there is nothing+ // left to report.+ let closed = self.close_turn(None);+ debug_assert!(+ closed.is_none(),+ "closing a turn without a stop reason changes nothing"+ );+ None+ };let id = TurnId(self.turns_opened);self.turns_opened += 1;@@ -69,6 +81,12 @@ impl FoldState {// message already says.let text = deserialize_params::<PromptRequest>(params).map(|request| {+ // A confirmed prompt names the session the runtime answers+ // to; a speculative one only echoes what this fold already+ // knew, so it must not become the source of that fact.+ if !self.speculative {+ self.acp_session = Some(request.session_id.clone());+ }request.prompt.into_iter()@@ -88,12 +106,15 @@ impl FoldState {request_id: AgentActionId::from_request_id(prompt_id),parts: NonEmpty::one(MessagePart::Text { text }),stop: None,+ pending: self.speculative,});Changed::new(message)});self.turn = Some(Turn {id,+ prompt_pending: self.speculative,+ stop_requested: false,prompt_id: Some(prompt_id.clone()),agent: None,permission_positions: HashMap::new(),@@ -101,7 +122,7 @@ impl FoldState {expects_reply: true,});- changed+ closed.into_iter().chain(changed).collect()}/// Handle the response to `session/prompt`: close the turn.@@ -212,6 +233,7 @@ impl FoldState {text: String::new(),}),stop: None,+ pending: self.speculative,});(message, Changed::new(message))}@@ -234,6 +256,8 @@ impl FoldState {self.turn = Some(Turn {id,+ prompt_pending: false,+ stop_requested: false,prompt_id: None,agent: None,permission_positions: HashMap::new(),diff --git a/crates/agent_fold/src/domain/mod.rs b/crates/agent_fold/src/domain/mod.rsindex cb7b9de1da..ccae009df2 100644--- a/crates/agent_fold/src/domain/mod.rs+++ b/crates/agent_fold/src/domain/mod.rs@@ -21,6 +21,8 @@ pub mod model_selection;pub mod ports;/// The domain service answering queries by folding on read.pub mod service;+/// Unconfirmed client actions folded on a fork of the confirmed history.+pub mod speculation;#[cfg(test)]mod test;diff --git a/crates/agent_fold/src/domain/model.rs b/crates/agent_fold/src/domain/model.rsindex 8d07e22b43..060c70ba76 100644--- a/crates/agent_fold/src/domain/model.rs+++ b/crates/agent_fold/src/domain/model.rs@@ -47,7 +47,7 @@ pub use elicitation::{ElicitationSchema, PendingElicitation,};pub use event::{FoldEvent, OwnedFoldEvent};-pub use metadata::{AvailableCommand, Harness, ModelOption, SessionMetadata};+pub use metadata::{AvailableCommand, Harness, ModelOption, SessionMetadata, TurnState};pub use part::{Control, ControlOutcome, MessagePart, StopReason};pub use permission::{PermissionOption, PermissionOptionKind, PermissionOutcome};pub use plan::{PlanEntry, PlanEntryPriority, PlanEntryStatus};@@ -188,6 +188,10 @@ pub struct FoldedMessage {/// `None` while a turn is still in flight, or when the session died/// without a response to the prompt.pub stop: Option<StopReason>,+ /// Derived from a frame this client issued that the log has not yet+ /// confirmed: a prompt on the wire, a stop just pressed. Cleared when the+ /// confirmed frame folds in its place. Always false on the server's fold.+ pub pending: bool,}impl FoldedMessage {diff --git a/crates/agent_fold/src/domain/model/metadata.rs b/crates/agent_fold/src/domain/model/metadata.rsindex a6af4dcf32..ed83c2b3b4 100644--- a/crates/agent_fold/src/domain/model/metadata.rs+++ b/crates/agent_fold/src/domain/model/metadata.rs@@ -67,6 +67,30 @@ pub struct SessionMetadata {/// nothing is pending, when the turn that asked has ended, or when the/// connection that asked is gone - the request id dies with it.pub pending_elicitation: Option<PendingElicitation>,+ /// Where the newest turn stands, as one value. Readers used to derive it+ /// from the transcript's tail, the status, and their own record of what+ /// they had posted; this is that derivation done once, in the fold.+ pub turn: TurnState,+}++/// Where the newest turn stands.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Type)]+#[serde(rename_all = "snake_case")]+pub enum TurnState {+ /// No turn is open.+ #[default]+ Idle,+ /// A prompt this client issued is on the wire, unconfirmed, and the agent+ /// has produced nothing. Only a speculative fold reports this.+ Starting,+ /// A turn is open and the agent is working.+ Running,+ /// A stop was issued against the open turn and no stop reason has arrived.+ Stopping,+ /// The open turn is waiting on the user to answer an elicitation.+ Blocked,+ /// The runtime reported `disconnected`; whatever was open is not moving.+ Disconnected,}/// One slash command the harness advertises.diff --git a/crates/agent_fold/src/domain/model/search/test.rs b/crates/agent_fold/src/domain/model/search/test.rsindex fa192624d4..4ff1dd38d0 100644--- a/crates/agent_fold/src/domain/model/search/test.rs+++ b/crates/agent_fold/src/domain/model/search/test.rs@@ -16,6 +16,7 @@ fn message(parts: Vec<MessagePart>) -> FoldedMessage {request_id: None,parts: NonEmpty::new(parts).expect("test message has parts"),stop: None,+ pending: false,}}diff --git a/crates/agent_fold/src/domain/speculation.rs b/crates/agent_fold/src/domain/speculation.rsnew file mode 100644index 0000000000..04c4dd0a7c--- /dev/null+++ b/crates/agent_fold/src/domain/speculation.rs@@ -0,0 +1,403 @@+//! Unconfirmed client actions folded on a fork of the confirmed history.+//!+//! A client that issues an action knows exactly which frame the harness will+//! log for it, because the harness builds that frame with+//! [`AgentAction::to_runtime`] and this module builds its copy the same way.+//! So the fold can show the action's effect before the log confirms it:+//! the confirmed machine stays authoritative, and the unconfirmed frames form+//! a *suffix* replayed on a clone of it. Three things can then happen to a+//! suffix entry:+//!+//! - **Promote.** A confirmed row matches it - same request id, or for a+//! frame that carries none the same method or content - and the entry is+//! dropped. The committed machine now derives what the fork already+//! showed, minus the pending mark.+//! - **Rebase.** A confirmed row matches nothing while the suffix is+//! non-empty. It belongs *before* the suffix, so the fork is rebuilt:+//! clone the committed machine, replay the suffix.+//! - **Retract.** The caller learns the server will never log it (the POST+//! failed, the control was rejected) and the suffix loses it. Rebase.+//!+//! Only frames this client causes are ever synthesized. What the runtime+//! answers is never predicted: a speculated stop renders as stopping and a+//! speculated prompt as starting, and the turn closes when the log says so.+//!+//! Think of a git rebase: the confirmed log is upstream, the suffix is the+//! local commits replayed on top, and each one disappears the moment upstream+//! contains it.++use std::borrow::Cow;++use agent_client_protocol::RawJsonRpcMessage;+use agent_client_protocol::schema::v1::SessionId;+use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};+use agent_runtime_protocol::domain::schema::v0::ToRuntimeMessage;+use macro_user_id::user_id::MacroUserIdStr;++use super::fold::FoldMachineImpl;+use super::ingestion::{LogCursor, LogIngestion};+use super::log::{AgentSessionId, AgentSessionLog, Message};+use super::model::{FoldEvent, FoldedMessage, SessionMetadata};++#[cfg(test)]+mod test;++/// The ACP session id a synthesized frame names before the log has shown the+/// real one - a first prompt into a session whose runtime is still booting.+/// The fold's handlers ignore it; only the replay gate reads it, and that gate+/// is closed while nothing has been opened yet. The confirmed frame carries+/// the real id and promotes by request id - or, for a stop, by method - so+/// the placeholder never sticks.+const PLACEHOLDER_ACP_SESSION: &str = "pending";++/// One thing that can happen to a client's view of a session log.+#[derive(Debug)]+pub enum FoldInput {+ /// Authoritative history from the top of the log. Resets the committed+ /// tier, drops every suffix entry the rows already confirm, and rebuilds+ /// the fork. Must come first; a fresh fold refuses everything else.+ Snapshot(Vec<(LogCursor, AgentSessionLog)>),+ /// One durable row, in delivery order.+ Confirmed(LogCursor, AgentSessionLog),+ /// An action this client issued that the log has not confirmed.+ Speculated(Speculation),+ /// An action the server will never log: the request that carried it+ /// failed, or the control was refused.+ Retracted(AgentActionId),+}++/// An action to fold before the log confirms it.+#[derive(Debug, Clone)]+pub struct Speculation {+ action_id: AgentActionId,+ action: AgentAction,+ user_id: Option<MacroUserIdStr<'static>>,+}++impl Speculation {+ /// An action under the id the client will send it with. The id is what a+ /// confirmed row is matched on where the wire carries one; a stop and an+ /// elicitation answer carry no id, and are matched as described on+ /// [`Pending::is_confirmed_by`].+ #[must_use]+ pub fn new(+ action_id: AgentActionId,+ action: AgentAction,+ user_id: Option<MacroUserIdStr<'static>>,+ ) -> Self {+ Self {+ action_id,+ action,+ user_id,+ }+ }+}++/// Why an input could not be folded.+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]+pub enum SpeculationError {+ /// A live or speculative frame arrived before any snapshot. Folding from+ /// the middle of a log derives a session that never happened, so the+ /// caller has to fetch first.+ #[error("the fold has no snapshot yet; a snapshot must be the first input")]+ NoSnapshot,+ /// The action could not be encoded as the frame the harness would log.+ #[error("the action could not be encoded as an ACP frame: {0}")]+ Encode(String),+}++/// A confirmed fold with this client's unconfirmed actions replayed on top.+///+/// [`Self::messages`] and [`Self::metadata`] read the fork while anything is+/// pending and the committed machine otherwise, so a reader never sees two+/// machines - only one conversation that occasionally gets ahead of the log.+pub struct SpeculativeFold {+ session: AgentSessionId,+ /// Everything the durable log has confirmed.+ committed: LogIngestion,+ /// Whether a snapshot has been folded. Nothing else is accepted before.+ snapshotted: bool,+ /// Frames this client caused that the log has not confirmed, in order.+ suffix: Vec<Pending>,+ /// `committed` plus `suffix`. `None` whenever the suffix is empty.+ fork: Option<FoldMachineImpl>,+}++/// One suffix entry: the frame as it was folded, and what a confirmed row+/// has to look like to be it.+#[derive(Debug, Clone)]+struct Pending {+ action_id: AgentActionId,+ frame: AgentSessionLog,+}++impl Pending {+ /// Whether `row` is the log's confirmation of this entry.+ ///+ /// A request carries the action id on the wire, so it matches on that+ /// alone: the harness composes prompts (mentions, context) after+ /// accepting them, so the confirmed text may legitimately differ from+ /// what was speculated, and the confirmed content wins.+ ///+ /// A notification - a stop - carries no id, and its content is no help+ /// either: `session/cancel` is byte-identical for every stop in a+ /// session, and one speculated before the log showed the ACP session+ /// names [`PLACEHOLDER_ACP_SESSION`] where the confirmed frame names the+ /// real id, so full content never matches. It matches on the method+ /// instead, and on the user where both rows name one.+ ///+ /// Everything else - an elicitation answer, which is a response on the+ /// agent's own request id - matches on content, which is deterministic:+ /// the agent's id plus the answer, encoded the one way+ /// [`AgentAction::to_runtime`] encodes it.+ fn is_confirmed_by(&self, row: &AgentSessionLog) -> bool {+ if let Some(id) = request_action_id(row) {+ return id == self.action_id;+ }+ if request_action_id(&self.frame).is_some() {+ return false;+ }+ match (notification_method(&self.frame), notification_method(row)) {+ (Some(mine), Some(theirs)) => mine == theirs && self.same_user_as(row),+ _ => {+ serde_json::to_value(&self.frame.content).ok()+ == serde_json::to_value(&row.content).ok()+ }+ }+ }++ /// Whether `row` was issued by whoever issued this entry. A row that+ /// names no user cannot contradict one that does, so it is accepted.+ fn same_user_as(&self, row: &AgentSessionLog) -> bool {+ match (&self.frame.user_id, &row.user_id) {+ (Some(mine), Some(theirs)) => mine == theirs,+ _ => true,+ }+ }+}++/// The method of a notification frame, if the row is one.+fn notification_method(row: &AgentSessionLog) -> Option<&str> {+ match &row.content {+ Message::ToRuntime(ToRuntimeMessage::Acp(acp)) => match &acp.0 {+ RawJsonRpcMessage::Notification(notification) => Some(notification.method.as_ref()),+ _ => None,+ },+ _ => None,+ }+}++/// The action id a runtime-bound request carries, if the row is one.+fn request_action_id(row: &AgentSessionLog) -> Option<AgentActionId> {+ match &row.content {+ Message::ToRuntime(ToRuntimeMessage::Acp(acp)) => match &acp.0 {+ RawJsonRpcMessage::Request(request) => AgentActionId::from_request_id(&request.id),+ _ => None,+ },+ _ => None,+ }+}++impl SpeculativeFold {+ /// A fold for `session` that has seen nothing. The first input must be a+ /// [`FoldInput::Snapshot`].+ #[must_use]+ pub fn new(session: AgentSessionId) -> Self {+ Self {+ session,+ committed: LogIngestion::default(),+ snapshotted: false,+ suffix: Vec::new(),+ fork: None,+ }+ }++ /// Every message as the reader should see it: the fork's while anything+ /// is pending, the committed machine's otherwise.+ #[must_use]+ pub fn messages(&self) -> &[FoldedMessage] {+ self.tier().messages()+ }++ /// Session metadata, from the same tier as [`Self::messages`].+ #[must_use]+ pub fn metadata(&self) -> &SessionMetadata {+ self.tier().metadata()+ }++ /// The action ids still waiting on the log.+ pub fn pending(&self) -> impl Iterator<Item = AgentActionId> + '_ {+ self.suffix.iter().map(|pending| pending.action_id)+ }++ fn tier(&self) -> &FoldMachineImpl {+ self.fork.as_ref().unwrap_or(&self.committed.machine)+ }++ /// Fold one input, reporting what it changed in the same vocabulary a+ /// plain machine push does. A rebase or snapshot reports+ /// [`FoldEvent::MessagesReplaced`]; everything else reports only what+ /// moved, which for a promotion is the confirmed message losing its+ /// pending mark.+ ///+ /// # Errors+ ///+ /// See [`SpeculationError`].+ pub fn push(&mut self, input: FoldInput) -> Result<Vec<FoldEvent<'_>>, SpeculationError> {+ match input {+ FoldInput::Snapshot(rows) => {+ self.snapshotted = true;+ for (_, row) in &rows {+ self.settle(row);+ }+ self.committed.replace_snapshot(rows);+ Ok(self.rebase())+ }+ FoldInput::Confirmed(cursor, row) => {+ if !self.snapshotted {+ return Err(SpeculationError::NoSnapshot);+ }+ let promoted = self.settle(&row);+ if self.suffix.is_empty() {+ // Nothing pending after this row: the fork, if any, is+ // now redundant and the committed machine's own report+ // describes the change - for a promotion, the message+ // the reader already has, minus its pending mark.+ self.fork = None;+ let events: Vec<FoldEvent<'static>> = self+ .committed+ .push(cursor, row)+ .into_iter()+ .map(FoldEvent::into_owned)+ .collect();+ // A promoted row the snapshot already held reports+ // nothing from the machine, yet the reader still shows+ // the fork's pending message: restate the committed view.+ if promoted && events.is_empty() {+ return Ok(self.replaced());+ }+ return Ok(events);+ }+ let _ = self.committed.push(cursor, row);+ Ok(self.rebase())+ }+ FoldInput::Speculated(speculation) => {+ if !self.snapshotted {+ return Err(SpeculationError::NoSnapshot);+ }+ // The log got there first: the confirmed row can land over+ // the socket before the control response names its id, and+ // a client re-speculating under that id must not double it.+ if self.already_reflected(&speculation) {+ return Ok(Vec::new());+ }+ let frame = self.synthesize(&speculation)?;+ let fork = self+ .fork+ .get_or_insert_with(|| self.committed.machine.clone());+ let events: Vec<FoldEvent<'static>> = fork+ .push_speculative(frame.clone())+ .into_iter()+ .map(FoldEvent::into_owned)+ .collect();+ self.suffix.push(Pending {+ action_id: speculation.action_id,+ frame,+ });+ Ok(events)+ }+ FoldInput::Retracted(action_id) => {+ let before = self.suffix.len();+ self.suffix.retain(|pending| pending.action_id != action_id);+ if self.suffix.len() == before {+ return Ok(Vec::new());+ }+ Ok(self.rebase())+ }+ }+ }++ /// The frame the harness will log for `speculation`, built the way the+ /// harness builds it.+ fn synthesize(&self, speculation: &Speculation) -> Result<AgentSessionLog, SpeculationError> {+ let acp_session = self+ .committed+ .machine+ .acp_session_id()+ .cloned()+ .unwrap_or_else(|| SessionId::from(PLACEHOLDER_ACP_SESSION));+ let message = speculation+ .action+ .to_runtime(&acp_session, speculation.action_id.to_request_id())+ .map_err(|error| SpeculationError::Encode(error.to_string()))?;+ Ok(AgentSessionLog {+ agent_session_id: self.session,+ user_id: speculation.user_id.clone(),+ content: Message::ToRuntime(message),+ })+ }++ /// Whether the fold already shows what this speculation would add, so+ /// folding it again would only double it.+ ///+ /// A prompt, a compact and a model change carry their action id on the+ /// wire, so the committed fold answers for them directly - and only the+ /// committed fold, because a second prompt while one is still pending is+ /// an ordinary queued prompt, not a duplicate.+ ///+ /// A stop and an elicitation answer carry no action id, so each is+ /// recognized by the effect it has already had, on the fork as much as on+ /// the committed machine: two of either add nothing the first did not,+ /// and a second suffix entry that nothing distinguishes would outlive the+ /// one confirmed row that could settle it.+ fn already_reflected(&self, speculation: &Speculation) -> bool {+ match &speculation.action {+ AgentAction::Stop => self.tier().stop_requested(),+ AgentAction::RespondElicitation(answer) => {+ self.tier().elicitation_answered(&answer.request_id)+ }+ AgentAction::Prompt(_) | AgentAction::Compact | AgentAction::SetModel(_) => self+ .committed+ .machine+ .messages()+ .iter()+ .any(|message| message.request_id == Some(speculation.action_id)),+ }+ }++ /// Drop the suffix entry `row` confirms, if any. `true` when one was.+ fn settle(&mut self, row: &AgentSessionLog) -> bool {+ let Some(index) = self+ .suffix+ .iter()+ .position(|pending| pending.is_confirmed_by(row))+ else {+ return false;+ };+ self.suffix.remove(index);+ true+ }++ /// Rebuild the fork from the committed machine and the suffix, and report+ /// the whole view - the only honest report when what changed is "where+ /// the suffix sits".+ fn rebase(&mut self) -> Vec<FoldEvent<'_>> {+ if self.suffix.is_empty() {+ self.fork = None;+ } else {+ let mut fork = self.committed.machine.clone();+ for pending in &self.suffix {+ let _ = fork.push_speculative(pending.frame.clone());+ }+ self.fork = Some(fork);+ }+ self.replaced()+ }++ fn replaced(&self) -> Vec<FoldEvent<'_>> {+ vec![+ FoldEvent::MessagesReplaced(Cow::Borrowed(self.messages())),+ FoldEvent::MetadataUpdated(Cow::Borrowed(self.metadata())),+ ]+ }+}diff --git a/crates/agent_fold/src/domain/speculation/test.rs b/crates/agent_fold/src/domain/speculation/test.rsnew file mode 100644index 0000000000..cc15a4221f--- /dev/null+++ b/crates/agent_fold/src/domain/speculation/test.rs@@ -0,0 +1,807 @@+//! The two-tier fold's contract: speculate, promote, rebase, retract.++use std::collections::BTreeMap;++use super::*;+use crate::domain::model::{+ AnsweredField, AnsweredValue, Author, Control, ControlOutcome, ElicitationOutcome,+ ElicitationRequestId, MessagePart, StopReason, TurnId, TurnState,+};+use crate::testing::{TURN, parse_log, test_session};+use agent_client_protocol::schema::v1::SessionId;+use agent_runtime_protocol::domain::action::{ElicitationAnswer, ElicitationContentValue};+use chrono::{Duration, TimeZone, Utc};+use macro_uuid::Uuid;++/// The ACP session the `TURN` fixture runs in.+const ACP_SESSION: &str = "s1";++/// The id the agent asks its question under in [`blocked`].+const QUESTION_ID: ElicitationRequestId = ElicitationRequestId::Number(7);++fn cursor(index: usize) -> LogCursor {+ let index = u128::try_from(index).expect("small index");+ LogCursor {+ id: Uuid::from_u128(index + 1),+ created_at: Utc.with_ymd_and_hms(2026, 8, 13, 0, 0, 0).unwrap()+ + Duration::microseconds(i64::try_from(index).expect("small index")),+ }+}++fn rows(log: Vec<AgentSessionLog>) -> Vec<(LogCursor, AgentSessionLog)> {+ log.into_iter()+ .enumerate()+ .map(|(index, row)| (cursor(index), row))+ .collect()+}++fn user() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from_email("[email protected]").expect("test email parses")+}++/// The row the harness logs for `action` under `action_id` - built the way+/// the harness builds it, which is also how the fold speculates it.+fn logged(action: &AgentAction, action_id: AgentActionId) -> AgentSessionLog {+ AgentSessionLog {+ agent_session_id: test_session(),+ user_id: Some(user()),+ content: Message::ToRuntime(+ action+ .to_runtime(&SessionId::from(ACP_SESSION), action_id.to_request_id())+ .expect("action encodes"),+ ),+ }+}++fn speculation(action: AgentAction, action_id: AgentActionId) -> FoldInput {+ FoldInput::Speculated(Speculation::new(action_id, action, Some(user())))+}++/// A fold that has folded the whole `TURN` fixture: one closed turn.+fn settled() -> SpeculativeFold {+ let mut fold = SpeculativeFold::new(test_session());+ fold.push(FoldInput::Snapshot(rows(parse_log(TURN))))+ .expect("snapshot");+ assert_eq!(fold.metadata().turn, TurnState::Idle);+ fold+}++/// A fold whose turn is still open: the fixture up to the agent's first chunk.+fn mid_turn() -> SpeculativeFold {+ let open: String = TURN.lines().take(5).collect::<Vec<_>>().join("\n");+ let mut fold = SpeculativeFold::new(test_session());+ fold.push(FoldInput::Snapshot(rows(parse_log(&open))))+ .expect("snapshot");+ assert_eq!(fold.metadata().turn, TurnState::Running);+ fold+}++/// A fold whose open turn is blocked on a question the agent asked.+fn blocked() -> SpeculativeFold {+ let mut log: Vec<&str> = TURN.lines().take(5).collect();+ log.push(+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":7,"method":"elicitation/create","params":{"mode":"form","sessionId":"s1","message":"Which colour?","requestedSchema":{"type":"object","properties":{"colour":{"type":"string","title":"Colour"}}}}}}"#,+ );+ let mut fold = SpeculativeFold::new(test_session());+ fold.push(FoldInput::Snapshot(rows(parse_log(&log.join("\n")))))+ .expect("snapshot");+ assert_eq!(fold.metadata().turn, TurnState::Blocked);+ fold+}++/// Submitting `colour` to the question [`blocked`] holds open.+fn accept(colour: &str) -> AgentAction {+ AgentAction::respond_elicitation(+ QUESTION_ID,+ ElicitationAnswer::Accept {+ content: Some(BTreeMap::from([(+ "colour".to_owned(),+ ElicitationContentValue::Text(colour.to_owned()),+ )])),+ },+ )+}++/// The question's outcome, and whether the message holding it is pending.+fn question(fold: &SpeculativeFold) -> (ElicitationOutcome, bool) {+ fold.messages()+ .iter()+ .find_map(|message| {+ message.parts.iter().find_map(|part| match part {+ MessagePart::Elicitation { outcome, .. } => {+ Some((outcome.clone(), message.pending))+ }+ _ => None,+ })+ })+ .expect("the question is in the transcript")+}++/// Whether each stop line in the transcript is still pending, in order.+fn stops(fold: &SpeculativeFold) -> Vec<bool> {+ fold.messages()+ .iter()+ .filter(|message| {+ matches!(+ message.parts.first(),+ Some(MessagePart::Control {+ control: Control::Stop,+ ..+ })+ )+ })+ .map(|message| message.pending)+ .collect()+}++fn user_texts(messages: &[FoldedMessage]) -> Vec<(String, bool)> {+ messages+ .iter()+ .filter(|message| matches!(message.author, Author::User { .. }))+ .filter_map(|message| match message.parts.first() {+ Some(MessagePart::Text { text }) => Some((text.clone(), message.pending)),+ _ => None,+ })+ .collect()+}++fn is_replace(events: &[FoldEvent<'_>]) -> bool {+ matches!(+ events,+ [+ FoldEvent::MessagesReplaced(_),+ FoldEvent::MetadataUpdated(_)+ ]+ )+}++#[test]+fn nothing_is_accepted_before_a_snapshot() {+ let mut fold = SpeculativeFold::new(test_session());+ let id = AgentActionId::mint();+ assert_eq!(+ fold.push(FoldInput::Confirmed(+ cursor(0),+ logged(&AgentAction::prompt("hi"), id)+ ))+ .unwrap_err(),+ SpeculationError::NoSnapshot+ );+ assert_eq!(+ fold.push(speculation(AgentAction::prompt("hi"), id))+ .unwrap_err(),+ SpeculationError::NoSnapshot+ );+}++#[test]+fn a_speculated_answer_resolves_the_question_and_unblocks_the_turn() {+ let mut fold = blocked();+ let before = fold.messages().len();+ let id = AgentActionId::mint();++ fold.push(speculation(accept("red"), id)).unwrap();++ let (outcome, pending) = question(&fold);+ assert_eq!(+ outcome,+ ElicitationOutcome::Accepted {+ answers: vec![AnsweredField {+ name: "colour".to_owned(),+ label: "Colour".to_owned(),+ value: AnsweredValue::Text {+ text: "red".to_owned()+ },+ }],+ }+ );+ assert!(pending, "the message holding the question is unconfirmed");+ assert!(fold.metadata().pending_elicitation.is_none());+ assert_eq!(fold.metadata().turn, TurnState::Running);+ // The answer resolves a part; it mints no message of its own.+ assert_eq!(fold.messages().len(), before);+ assert_eq!(fold.pending().collect::<Vec<_>>(), vec![id]);+}++#[test]+fn the_confirmed_answer_promotes_by_content() {+ let mut fold = blocked();+ let id = AgentActionId::mint();+ fold.push(speculation(accept("red"), id)).unwrap();+ let speculated = fold.messages().len();++ // The harness logs the answer under the agent's request id, so the row+ // carries no action id at all and matches on content.+ fold.push(FoldInput::Confirmed(+ cursor(99),+ logged(&accept("red"), AgentActionId::mint()),+ ))+ .unwrap();++ assert_eq!(fold.pending().count(), 0);+ assert!(fold.fork.is_none());+ let (outcome, pending) = question(&fold);+ assert!(matches!(outcome, ElicitationOutcome::Accepted { .. }));+ assert!(!pending);+ assert_eq!(fold.messages().len(), speculated, "nothing was duplicated");+ assert_eq!(fold.metadata().turn, TurnState::Running);+}++#[test]+fn retracting_an_answer_restores_the_question() {+ let mut fold = blocked();+ let id = AgentActionId::mint();+ fold.push(speculation(accept("red"), id)).unwrap();++ let events = fold.push(FoldInput::Retracted(id)).unwrap();++ assert!(is_replace(&events));+ assert_eq!(question(&fold), (ElicitationOutcome::Pending, false));+ assert!(fold.metadata().pending_elicitation.is_some());+ assert_eq!(fold.metadata().turn, TurnState::Blocked);+}++#[test]+fn a_speculated_decline_reads_as_declined() {+ let mut fold = blocked();+ fold.push(speculation(+ AgentAction::respond_elicitation(QUESTION_ID, ElicitationAnswer::Decline),+ AgentActionId::mint(),+ ))+ .unwrap();++ assert_eq!(question(&fold).0, ElicitationOutcome::Declined);+ assert_eq!(fold.metadata().turn, TurnState::Running);+}++#[test]+fn answering_a_question_already_answered_changes_nothing() {+ let mut fold = blocked();+ fold.push(speculation(accept("red"), AgentActionId::mint()))+ .unwrap();+ let answered: Vec<FoldedMessage> = fold.messages().to_vec();++ let events = fold+ .push(speculation(accept("blue"), AgentActionId::mint()))+ .unwrap();++ assert!(events.is_empty());+ assert_eq!(fold.pending().count(), 1);+ assert_eq!(fold.messages(), answered.as_slice());+}++#[test]+fn a_stop_beats_a_question_the_user_walked_away_from() {+ let mut fold = blocked();++ fold.push(speculation(AgentAction::Stop, AgentActionId::mint()))+ .unwrap();++ assert_eq!(fold.metadata().turn, TurnState::Stopping);+}++#[test]+fn a_stop_speculated_before_the_session_id_is_known_still_promotes() {+ let mut fold = SpeculativeFold::new(test_session());+ fold.push(FoldInput::Snapshot(rows(parse_log(+ r#"{"direction":"to_server","content":{"type":"event","event":"acp_ready"}}"#,+ ))))+ .unwrap();+ assert_eq!(fold.committed.machine.acp_session_id(), None);++ let id = AgentActionId::mint();+ fold.push(speculation(AgentAction::Stop, id)).unwrap();+ let Message::ToRuntime(ToRuntimeMessage::Acp(acp)) = &fold.suffix[0].frame.content else {+ panic!("a runtime-bound frame");+ };+ let RawJsonRpcMessage::Notification(notification) = &acp.0 else {+ panic!("a notification");+ };+ let params = serde_json::to_value(notification.params.as_ref()).unwrap();+ assert_eq!(params["sessionId"], PLACEHOLDER_ACP_SESSION);++ // The harness sent the cancel into the session the runtime had by then.+ fold.push(FoldInput::Confirmed(+ cursor(99),+ logged(&AgentAction::Stop, AgentActionId::mint()),+ ))+ .unwrap();++ assert_eq!(fold.pending().count(), 0);+ assert!(fold.fork.is_none());+ assert_eq!(stops(&fold), vec![false], "one stop line, confirmed");+}++#[test]+fn stopping_twice_leaves_one_stop_line() {+ let mut fold = mid_turn();+ fold.push(speculation(AgentAction::Stop, AgentActionId::mint()))+ .unwrap();++ let events = fold+ .push(speculation(AgentAction::Stop, AgentActionId::mint()))+ .unwrap();++ assert!(events.is_empty());+ assert_eq!(stops(&fold), vec![true]);+ assert_eq!(fold.pending().count(), 1);+}++#[test]+fn a_speculated_prompt_is_pending_and_the_turn_is_starting() {+ let mut fold = settled();+ let before = fold.messages().len();+ let id = AgentActionId::mint();++ let events = fold+ .push(speculation(AgentAction::prompt("hi"), id))+ .unwrap();++ let message = events+ .iter()+ .find_map(|event| match event {+ FoldEvent::NewMessage(message) => Some(message.clone().into_owned()),+ _ => None,+ })+ .expect("the prompt is reported new");+ assert_eq!(message.request_id, Some(id));+ assert!(message.pending);+ assert_eq!(+ message.author,+ Author::User {+ user_id: Some(user())+ }+ );+ assert!(+ events+ .iter()+ .any(|event| matches!(event, FoldEvent::MetadataUpdated(_))),+ "the turn state moved"+ );+ assert_eq!(fold.messages().len(), before + 1);+ assert_eq!(fold.metadata().turn, TurnState::Starting);+ assert_eq!(fold.pending().collect::<Vec<_>>(), vec![id]);+}++#[test]+fn the_confirmed_row_promotes_the_speculation_in_place() {+ let mut fold = settled();+ let id = AgentActionId::mint();+ let action = AgentAction::prompt("hi");+ fold.push(speculation(action.clone(), id)).unwrap();+ let speculated: Vec<FoldedMessage> = fold.messages().to_vec();++ let events = fold+ .push(FoldInput::Confirmed(cursor(99), logged(&action, id)))+ .unwrap();++ // Not a replace: the reader already has this message and only its+ // pending mark changes.+ assert!(!is_replace(&events));+ let reported = events+ .iter()+ .filter_map(FoldEvent::message)+ .find(|message| message.request_id == Some(id))+ .expect("the confirmed prompt is reported");+ assert!(!reported.pending);+ assert_eq!(fold.pending().count(), 0);+ assert!(fold.fork.is_none());++ let mut expected = speculated;+ for message in &mut expected {+ message.pending = false;+ }+ assert_eq!(fold.messages(), expected.as_slice());+ assert_eq!(fold.metadata().turn, TurnState::Running);+}++#[test]+fn a_prompt_the_harness_composed_differently_still_promotes_by_id() {+ let mut fold = settled();+ let id = AgentActionId::mint();+ fold.push(speculation(AgentAction::prompt("hi"), id))+ .unwrap();++ fold.push(FoldInput::Confirmed(+ cursor(99),+ logged(&AgentAction::prompt("hi\n\n<context>doc</context>"), id),+ ))+ .unwrap();++ assert_eq!(fold.pending().count(), 0);+ let (text, pending) = user_texts(fold.messages()).pop().unwrap();+ assert_eq!(text, "hi\n\n<context>doc</context>");+ assert!(!pending);+}++#[test]+fn a_foreign_row_while_pending_rebases_the_suffix_after_it() {+ let mut fold = settled();+ let mine = AgentActionId::mint();+ fold.push(speculation(AgentAction::prompt("mine"), mine))+ .unwrap();++ let theirs = AgentActionId::mint();+ let events = fold+ .push(FoldInput::Confirmed(+ cursor(99),+ logged(&AgentAction::prompt("theirs"), theirs),+ ))+ .unwrap();++ assert!(is_replace(&events));+ let texts = user_texts(fold.messages());+ let tail = &texts[texts.len() - 2..];+ assert_eq!(+ tail,+ [("theirs".to_owned(), false), ("mine".to_owned(), true)],+ "the confirmed prompt sits before the still-pending one"+ );+ assert_eq!(fold.pending().collect::<Vec<_>>(), vec![mine]);+ // Turn ids are assigned in fold order, so the speculated prompt moved up.+ let mine_message = fold+ .messages()+ .iter()+ .find(|message| message.request_id == Some(mine))+ .unwrap();+ let theirs_message = fold+ .messages()+ .iter()+ .find(|message| message.request_id == Some(theirs))+ .unwrap();+ assert!(mine_message.id > theirs_message.id);+}++#[test]+fn a_retraction_removes_the_speculation_and_restores_the_committed_view() {+ let mut fold = settled();+ let committed: Vec<FoldedMessage> = fold.messages().to_vec();+ let id = AgentActionId::mint();+ fold.push(speculation(AgentAction::prompt("hi"), id))+ .unwrap();++ let events = fold.push(FoldInput::Retracted(id)).unwrap();++ assert!(is_replace(&events));+ assert_eq!(fold.messages(), committed.as_slice());+ assert_eq!(fold.metadata().turn, TurnState::Idle);+ assert!(fold.fork.is_none());++ // Retracting something never speculated changes nothing.+ assert!(+ fold.push(FoldInput::Retracted(AgentActionId::mint()))+ .unwrap()+ .is_empty()+ );+}++#[test]+fn a_snapshot_settles_what_it_already_contains() {+ let mut fold = settled();+ let id = AgentActionId::mint();+ let action = AgentAction::prompt("hi");+ fold.push(speculation(action.clone(), id)).unwrap();++ let mut log = parse_log(TURN);+ log.push(logged(&action, id));+ let events = fold.push(FoldInput::Snapshot(rows(log))).unwrap();++ assert!(is_replace(&events));+ assert_eq!(fold.pending().count(), 0);+ assert!(fold.fork.is_none());+ let (text, pending) = user_texts(fold.messages()).pop().unwrap();+ assert_eq!(text, "hi");+ assert!(!pending);+}++#[test]+fn a_speculated_stop_reads_as_stopping_and_promotes_by_method() {+ let mut fold = mid_turn();+ let id = AgentActionId::mint();++ let events = fold.push(speculation(AgentAction::Stop, id)).unwrap();++ let control = events+ .iter()+ .filter_map(FoldEvent::message)+ .find(|message| {+ matches!(+ message.parts.first(),+ Some(MessagePart::Control {+ control: Control::Stop,+ ..+ })+ )+ })+ .expect("the stop renders as a control line");+ assert!(control.pending);+ assert!(matches!(+ control.parts.first(),+ Some(MessagePart::Control {+ outcome: ControlOutcome::Accepted,+ ..+ })+ ));+ // The turn is not closed: only the runtime's own stop event does that.+ assert_eq!(fold.metadata().turn, TurnState::Stopping);+ assert!(fold.messages().last().unwrap().stop.is_none() || fold.messages().len() > 1);++ // A cancel is a notification with no request id, and its content is the+ // same bytes for every stop in the session, so the confirmed row matches+ // on its method and promotes the same way.+ let events = fold+ .push(FoldInput::Confirmed(+ cursor(99),+ logged(&AgentAction::Stop, AgentActionId::mint()),+ ))+ .unwrap();+ assert!(!is_replace(&events));+ assert_eq!(fold.pending().count(), 0);+ let control = fold+ .messages()+ .iter()+ .find(|message| {+ matches!(+ message.parts.first(),+ Some(MessagePart::Control {+ control: Control::Stop,+ ..+ })+ )+ })+ .unwrap();+ assert!(!control.pending);+ assert_eq!(fold.metadata().turn, TurnState::Stopping);+}++#[test]+fn a_speculated_frame_names_the_session_the_log_showed() {+ let mut fold = settled();+ assert_eq!(+ fold.committed.machine.acp_session_id(),+ Some(&SessionId::from(ACP_SESSION))+ );+ let id = AgentActionId::mint();+ fold.push(speculation(AgentAction::prompt("hi"), id))+ .unwrap();+ let frame = &fold.suffix[0].frame;+ let Message::ToRuntime(ToRuntimeMessage::Acp(acp)) = &frame.content else {+ panic!("a runtime-bound frame");+ };+ let RawJsonRpcMessage::Request(request) = &acp.0 else {+ panic!("a request");+ };+ let params = serde_json::to_value(request.params.as_ref()).unwrap();+ assert_eq!(params["sessionId"], ACP_SESSION);+ assert_eq!(request.id, id.to_request_id());+}++#[test]+fn a_session_with_no_runtime_yet_still_speculates() {+ let mut fold = SpeculativeFold::new(test_session());+ fold.push(FoldInput::Snapshot(rows(parse_log(+ r#"{"direction":"to_server","content":{"type":"event","event":"acp_ready"}}"#,+ ))))+ .unwrap();+ assert_eq!(fold.committed.machine.acp_session_id(), None);++ let id = AgentActionId::mint();+ fold.push(speculation(AgentAction::prompt("hi"), id))+ .unwrap();++ assert_eq!(user_texts(fold.messages()), vec![("hi".to_owned(), true)]);+ assert_eq!(fold.metadata().turn, TurnState::Starting);+}++/// The frontend's job, written out: a reader holding only what the events+/// told it must end up with exactly what `messages()` says.+#[test]+fn events_alone_reconstruct_the_view() {+ #[derive(Default)]+ struct Reader {+ messages: Vec<FoldedMessage>,+ }+ impl Reader {+ fn apply(&mut self, events: Vec<FoldEvent<'_>>) {+ for event in events {+ match event {+ FoldEvent::NewMessage(message) | FoldEvent::MessageUpdate(message) => {+ let message = message.into_owned();+ match self+ .messages+ .iter_mut()+ .find(|held| held.id() == message.id())+ {+ Some(held) => *held = message,+ None => self.messages.push(message),+ }+ }+ FoldEvent::MessagesReplaced(messages) => {+ self.messages = messages.into_owned();+ }+ FoldEvent::MetadataUpdated(_) => {}+ }+ }+ }+ }++ let mut fold = SpeculativeFold::new(test_session());+ let mut reader = Reader::default();+ let open: String = TURN.lines().take(4).collect::<Vec<_>>().join("\n");+ reader.apply(+ fold.push(FoldInput::Snapshot(rows(parse_log(&open))))+ .unwrap(),+ );++ let stop = AgentActionId::mint();+ reader.apply(fold.push(speculation(AgentAction::Stop, stop)).unwrap());+ let next = AgentActionId::mint();+ reader.apply(+ fold.push(speculation(AgentAction::prompt("next"), next))+ .unwrap(),+ );+ assert_eq!(reader.messages, fold.messages());++ // The rest of the fixture confirms the running turn's answer and end,+ // each one a foreign row that rebases the suffix.+ for (index, row) in parse_log(TURN).into_iter().enumerate().skip(4) {+ reader.apply(fold.push(FoldInput::Confirmed(cursor(index), row)).unwrap());+ assert_eq!(reader.messages, fold.messages());+ }+ reader.apply(+ fold.push(FoldInput::Confirmed(+ cursor(50),+ logged(&AgentAction::Stop, AgentActionId::mint()),+ ))+ .unwrap(),+ );+ assert_eq!(reader.messages, fold.messages());+ reader.apply(+ fold.push(FoldInput::Confirmed(+ cursor(51),+ logged(&AgentAction::prompt("next"), next),+ ))+ .unwrap(),+ );+ assert_eq!(reader.messages, fold.messages());+ assert_eq!(fold.pending().count(), 0);+ assert!(fold.messages().iter().all(|message| !message.pending));+}++#[test]+fn speculating_an_action_the_log_already_confirmed_changes_nothing() {+ let mut fold = settled();+ let id = AgentActionId::mint();+ let action = AgentAction::prompt("hi");+ fold.push(FoldInput::Confirmed(cursor(99), logged(&action, id)))+ .unwrap();+ let confirmed: Vec<FoldedMessage> = fold.messages().to_vec();++ let events = fold.push(speculation(action, id)).unwrap();++ assert!(events.is_empty());+ assert_eq!(fold.pending().count(), 0);+ assert_eq!(fold.messages(), confirmed.as_slice());+}++/// The bug this pins: a prompt sent into a booting session showed, vanished+/// on the first live row, and came back once the runtime answered. The+/// runtime's `disconnected` event makes the replay gate stage every+/// runtime-bound frame until the next `initialize`, and a rebase re-folded+/// the speculated prompt through that gate.+#[test]+fn a_speculation_survives_the_replay_gate_across_a_disconnect() {+ let mut fold = settled();+ let id = AgentActionId::mint();+ fold.push(speculation(AgentAction::prompt("hi"), id))+ .unwrap();++ // The runtime drops while the prompt is still on the wire.+ let disconnected =+ parse_log(r#"{"direction":"to_server","content":{"type":"event","event":"disconnected"}}"#)+ .remove(0);+ let events = fold+ .push(FoldInput::Confirmed(cursor(99), disconnected))+ .unwrap();++ assert!(is_replace(&events), "a foreign row rebases the suffix");+ assert_eq!(+ user_texts(fold.messages()).pop(),+ Some(("hi".to_owned(), true)),+ "the pending prompt is still shown after the rebase"+ );+ assert_eq!(fold.metadata().turn, TurnState::Disconnected);++ // Speculating straight into a disconnected session shows just the same.+ let second = AgentActionId::mint();+ fold.push(speculation(AgentAction::prompt("again"), second))+ .unwrap();+ assert_eq!(+ user_texts(fold.messages()).pop(),+ Some(("again".to_owned(), true))+ );+}++/// Enter with a queued message: the client stops the turn and speculates the+/// queue head under the id the server already gave it, so the head reads as+/// sent while the runtime winds the old turn down.+#[test]+fn a_speculated_prompt_behind_a_stop_closes_the_stopped_turn_as_cancelled() {+ let mut fold = mid_turn();+ let stop_id = AgentActionId::mint();+ fold.push(speculation(AgentAction::Stop, stop_id)).unwrap();+ assert_eq!(fold.metadata().turn, TurnState::Stopping);++ let head_id = AgentActionId::mint();+ fold.push(speculation(AgentAction::prompt("next"), head_id))+ .unwrap();+ let stopped = |fold: &SpeculativeFold| {+ fold.messages()+ .iter()+ .find(|message| message.id == TurnId(0) && matches!(message.author, Author::Agent))+ .map(|message| (message.stop.clone(), message.pending))+ .expect("the stopped turn's agent message")+ };+ assert_eq!(+ stopped(&fold),+ (Some(StopReason::Cancelled), true),+ "the only way a stopped turn can end is predicted, and marked pending"+ );+ assert_eq!(+ user_texts(fold.messages()).pop(),+ Some(("next".to_owned(), true))+ );+ assert_eq!(fold.metadata().turn, TurnState::Starting);++ // The log then confirms in its own order: the cancel, the cancelled+ // response, and the head the server dispatched under the same id.+ fold.push(FoldInput::Confirmed(+ cursor(50),+ logged(&AgentAction::Stop, stop_id),+ ))+ .unwrap();+ assert_eq!(fold.metadata().turn, TurnState::Starting);+ let cancelled = parse_log(+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"prompt-1","result":{"stopReason":"cancelled"}}}"#,+ )+ .remove(0);+ fold.push(FoldInput::Confirmed(cursor(51), cancelled))+ .unwrap();+ assert_eq!(stopped(&fold), (Some(StopReason::Cancelled), false));+ assert_eq!(fold.metadata().turn, TurnState::Starting);+ fold.push(FoldInput::Confirmed(+ cursor(52),+ logged(&AgentAction::prompt("next"), head_id),+ ))+ .unwrap();+ assert_eq!(+ user_texts(fold.messages()).pop(),+ Some(("next".to_owned(), false))+ );+ assert_eq!(fold.metadata().turn, TurnState::Running);+ assert_eq!(fold.pending().count(), 0);+}++/// A confirmed prompt that follows an unanswered one still leaves the old+/// turn open-ended: only the speculative path predicts the runtime.+#[test]+fn a_confirmed_prompt_behind_a_stop_predicts_nothing() {+ let mut fold = mid_turn();+ let stop_id = AgentActionId::mint();+ fold.push(FoldInput::Confirmed(+ cursor(50),+ logged(&AgentAction::Stop, stop_id),+ ))+ .unwrap();+ fold.push(FoldInput::Confirmed(+ cursor(51),+ logged(&AgentAction::prompt("next"), AgentActionId::mint()),+ ))+ .unwrap();+ let first_agent = fold+ .messages()+ .iter()+ .find(|message| message.id == TurnId(0) && matches!(message.author, Author::Agent))+ .expect("agent message");+ assert_eq!(first_agent.stop, None);+}diff --git a/crates/agent_fold/src/domain/test/elicitation.rs b/crates/agent_fold/src/domain/test/elicitation.rsindex 3ecf953345..a6a8a06268 100644--- a/crates/agent_fold/src/domain/test/elicitation.rs+++ b/crates/agent_fold/src/domain/test/elicitation.rs@@ -94,7 +94,10 @@ fn elicitations(machine: &FoldMachineImpl) -> Vec<&MessagePart> {fn a_form_request_becomes_a_pending_part_and_the_live_slot() {let (machine, metadata_events) = drive(&lines(&[PROMPT, FORM]));- assert_eq!(metadata_events, 1, "the slot filling is a metadata change");+ assert_eq!(+ metadata_events, 2,+ "the turn opening, then the slot filling, are metadata changes"+ );let parts = elicitations(&machine);assert_eq!(parts.len(), 1);let MessagePart::Elicitation {@@ -250,7 +253,7 @@ fn accept_resolves_the_part_with_its_content_and_frees_the_slot() {&accept(7, r#"{"zeta":"svc","port":8080}"#),]));- assert_eq!(metadata_events, 2, "filled, then cleared");+ assert_eq!(metadata_events, 3, "turn opened, slot filled, then cleared");let parts = elicitations(&machine);let MessagePart::Elicitation { outcome, .. } = parts[0] else {unreachable!()@@ -388,7 +391,9 @@ fn a_second_request_gets_a_part_but_never_the_slot() {fn the_turn_ending_clears_the_slot_but_leaves_the_part_pending() {let (machine, metadata_events) = drive(&lines(&[PROMPT, FORM, END_TURN]));- assert_eq!(metadata_events, 2);+ // Turn opened, slot filled, then the turn ending clears the slot and+ // closes the turn in one step.+ assert_eq!(metadata_events, 3);assert_eq!(machine.metadata().pending_elicitation, None);let parts = elicitations(&machine);let MessagePart::Elicitation { outcome, .. } = parts[0] else {diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@command_invocation.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@command_invocation.jsonl.snapindex 98f7a351f1..912f7e5d25 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@command_invocation.jsonl.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@command_invocation.jsonl.snap@@ -396,4 +396,5 @@ SessionMetadata {"acp_ready",),pending_elicitation: None,+ turn: Idle,}diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@elicitation_claude_single_select.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@elicitation_claude_single_select.jsonl.snapindex 33bb439dfc..189d00bdb7 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@elicitation_claude_single_select.jsonl.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@elicitation_claude_single_select.jsonl.snap@@ -74,4 +74,5 @@ SessionMetadata {"acp_ready",),pending_elicitation: None,+ turn: Idle,}diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@long_multi_resume.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@long_multi_resume.jsonl.snapindex de9a448c4d..a1b012ab62 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@long_multi_resume.jsonl.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@long_multi_resume.jsonl.snap@@ -391,4 +391,5 @@ SessionMetadata {"acp_ready",),pending_elicitation: None,+ turn: Idle,}diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@plan_todo.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@plan_todo.jsonl.snapindex dee87985f1..15cddab387 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@plan_todo.jsonl.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@plan_todo.jsonl.snap@@ -396,4 +396,5 @@ SessionMetadata {"acp_ready",),pending_elicitation: None,+ turn: Idle,}diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@real_multi_turn.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@real_multi_turn.jsonl.snapindex a8468de61f..c22569c7d6 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@real_multi_turn.jsonl.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@real_multi_turn.jsonl.snap@@ -431,4 +431,5 @@ SessionMetadata {"acp_ready",),pending_elicitation: None,+ turn: Running,}diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@real_single_turn.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@real_single_turn.jsonl.snapindex c5e5cc513b..34989ad533 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@real_single_turn.jsonl.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@real_single_turn.jsonl.snap@@ -431,4 +431,5 @@ SessionMetadata {"acp_ready",),pending_elicitation: None,+ turn: Idle,}diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@resumed_and_continued.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@resumed_and_continued.jsonl.snapindex 376ade08c3..1d9723e03b 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@resumed_and_continued.jsonl.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@resumed_and_continued.jsonl.snap@@ -431,4 +431,5 @@ SessionMetadata {"acp_ready",),pending_elicitation: None,+ turn: Idle,}diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@resumed_no_prompt.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@resumed_no_prompt.jsonl.snapindex b3d5b413dc..7adca192f3 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@resumed_no_prompt.jsonl.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@resumed_no_prompt.jsonl.snap@@ -429,4 +429,5 @@ SessionMetadata {"acp_ready",),pending_elicitation: None,+ turn: Running,}diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_claude_code.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_claude_code.jsonl.snapindex fa90f9c836..86a7d36780 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_claude_code.jsonl.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_claude_code.jsonl.snap@@ -58,4 +58,5 @@ SessionMetadata {"acp_ready",),pending_elicitation: None,+ turn: Idle,}diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_cursor.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_cursor.jsonl.snapindex d4e10b8a16..ed66a374d5 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_cursor.jsonl.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_cursor.jsonl.snap@@ -244,4 +244,5 @@ SessionMetadata {"acp_ready",),pending_elicitation: None,+ turn: Idle,}diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_macro_inmem.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_macro_inmem.jsonl.snapindex 85bfede3c9..40e2921754 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_macro_inmem.jsonl.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_macro_inmem.jsonl.snap@@ -13,4 +13,5 @@ SessionMetadata {"acp_ready",),pending_elicitation: None,+ turn: Idle,}diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_opencode.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_opencode.jsonl.snapindex f9d46d3b9c..ea74c69692 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_opencode.jsonl.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_opencode.jsonl.snap@@ -61,4 +61,5 @@ SessionMetadata {"acp_ready",),pending_elicitation: None,+ turn: Idle,}diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@command_invocation.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@command_invocation.jsonl.snapindex 1f9745128f..b14283b39b 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@command_invocation.jsonl.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@command_invocation.jsonl.snap@@ -27,6 +27,7 @@ input_file: crates/agent_fold/fixtures/real/command_invocation.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -50,6 +51,7 @@ input_file: crates/agent_fold/fixtures/real/command_invocation.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -67,5 +69,6 @@ input_file: crates/agent_fold/fixtures/real/command_invocation.jsonlstop: Some(EndTurn,),+ pending: false,},]diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@elicitation_claude_single_select.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@elicitation_claude_single_select.jsonl.snapindex 8223ab6026..3a708c28bc 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@elicitation_claude_single_select.jsonl.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@elicitation_claude_single_select.jsonl.snap@@ -26,6 +26,7 @@ input_file: crates/agent_fold/fixtures/real/elicitation_claude_single_select.jso],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -137,5 +138,6 @@ input_file: crates/agent_fold/fixtures/real/elicitation_claude_single_select.jsostop: Some(EndTurn,),+ pending: false,},]diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@plan_todo.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@plan_todo.jsonl.snapindex a026ca0dde..9cef450448 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@plan_todo.jsonl.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@plan_todo.jsonl.snap@@ -27,6 +27,7 @@ input_file: crates/agent_fold/fixtures/real/plan_todo.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -50,6 +51,7 @@ input_file: crates/agent_fold/fixtures/real/plan_todo.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -166,5 +168,6 @@ input_file: crates/agent_fold/fixtures/real/plan_todo.jsonlstop: Some(EndTurn,),+ pending: false,},]diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_multi_turn.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_multi_turn.jsonl.snapindex 0a374116a7..42006bd5f0 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_multi_turn.jsonl.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_multi_turn.jsonl.snap@@ -26,6 +26,7 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -118,6 +119,7 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonlstop: Some(EndTurn,),+ pending: false,},FoldedMessage {id: TurnId(@@ -141,6 +143,7 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -734,6 +737,7 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonlstop: Some(EndTurn,),+ pending: false,},FoldedMessage {id: TurnId(@@ -758,6 +762,7 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -781,6 +786,7 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -826,5 +832,6 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl],},stop: None,+ pending: false,},]diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_single_turn.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_single_turn.jsonl.snapindex 47ef4b7efb..3df4571748 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_single_turn.jsonl.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_single_turn.jsonl.snap@@ -26,6 +26,7 @@ input_file: crates/agent_fold/fixtures/real/real_single_turn.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -43,5 +44,6 @@ input_file: crates/agent_fold/fixtures/real/real_single_turn.jsonlstop: Some(EndTurn,),+ pending: false,},]diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_and_continued.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_and_continued.jsonl.snapindex 0733100ef7..9bf950467a 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_and_continued.jsonl.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_and_continued.jsonl.snap@@ -20,6 +20,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -266,6 +267,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonlstop: Some(EndTurn,),+ pending: false,},FoldedMessage {id: TurnId(@@ -283,6 +285,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -298,6 +301,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -321,6 +325,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -338,6 +343,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonlstop: Some(EndTurn,),+ pending: false,},FoldedMessage {id: TurnId(@@ -361,6 +367,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -428,6 +435,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonlstop: Some(EndTurn,),+ pending: false,},FoldedMessage {id: TurnId(@@ -451,6 +459,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -662,5 +671,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonlstop: Some(EndTurn,),+ pending: false,},]diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snapindex d0f51db892..0c03af3091 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snap@@ -20,6 +20,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -480,6 +481,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonlstop: Some(EndTurn,),+ pending: false,},FoldedMessage {id: TurnId(@@ -497,6 +499,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -627,6 +630,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonlstop: Some(EndTurn,),+ pending: false,},FoldedMessage {id: TurnId(@@ -644,6 +648,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -827,6 +832,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonlstop: Some(EndTurn,),+ pending: false,},FoldedMessage {id: TurnId(@@ -844,6 +850,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -1910,6 +1917,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonlstop: Some(EndTurn,),+ pending: false,},FoldedMessage {id: TurnId(@@ -1927,6 +1935,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -2733,6 +2742,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonlstop: Some(EndTurn,),+ pending: false,},FoldedMessage {id: TurnId(@@ -2750,6 +2760,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -3641,6 +3652,7 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -3665,5 +3677,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl],},stop: None,+ pending: false,},]diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_claude_code.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_claude_code.jsonl.snapindex 4edf0ed574..b072f40511 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_claude_code.jsonl.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_claude_code.jsonl.snap@@ -27,6 +27,7 @@ input_file: crates/agent_fold/fixtures/real/subagent_claude_code.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -50,6 +51,7 @@ input_file: crates/agent_fold/fixtures/real/subagent_claude_code.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -147,5 +149,6 @@ input_file: crates/agent_fold/fixtures/real/subagent_claude_code.jsonlstop: Some(EndTurn,),+ pending: false,},]diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_cursor.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_cursor.jsonl.snapindex b2abb0c7ec..274aa8c7b2 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_cursor.jsonl.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_cursor.jsonl.snap@@ -22,6 +22,7 @@ input_file: crates/agent_fold/fixtures/real/subagent_cursor.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -143,5 +144,6 @@ input_file: crates/agent_fold/fixtures/real/subagent_cursor.jsonlstop: Some(EndTurn,),+ pending: false,},]diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_macro_inmem.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_macro_inmem.jsonl.snapindex 48f880080d..36ec808f65 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_macro_inmem.jsonl.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_macro_inmem.jsonl.snap@@ -22,6 +22,7 @@ input_file: crates/agent_fold/fixtures/real/subagent_macro_inmem.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -78,5 +79,6 @@ input_file: crates/agent_fold/fixtures/real/subagent_macro_inmem.jsonlstop: Some(EndTurn,),+ pending: false,},]diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_opencode.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_opencode.jsonl.snapindex 2edbb060d1..d15387777f 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_opencode.jsonl.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_opencode.jsonl.snap@@ -26,6 +26,7 @@ input_file: crates/agent_fold/fixtures/real/subagent_opencode.jsonl],},stop: None,+ pending: false,},FoldedMessage {id: TurnId(@@ -84,5 +85,6 @@ input_file: crates/agent_fold/fixtures/real/subagent_opencode.jsonlstop: Some(EndTurn,),+ pending: false,},]diff --git a/crates/agent_fold/src/inbound/wasm.rs b/crates/agent_fold/src/inbound/wasm.rsindex f7bd50413a..4b9955b3d7 100644--- a/crates/agent_fold/src/inbound/wasm.rs+++ b/crates/agent_fold/src/inbound/wasm.rs@@ -1,196 +1,119 @@//! The fold, as the browser calls it.//!-//! Two entry points over one fold. [`fold_session`] takes a session id and-//! that session's whole log and gives back the messages it derives.-//! [`FoldStream`] is the same fold kept open: construct one per live session,-//! push frames as they arrive, and each push reports the single message it-//! changed. The log arrives in exactly the shape the raw-log endpoint serves,-//! a recording stores, and the realtime event carries - `{userId?, direction,-//! content}` per frame - so a caller passes bytes through rather than-//! translating them, and catching up and following are the same code.+//! One entry point: [`FoldStream`], a session's fold kept open. Construct one+//! per live session and push [`FoldInput`]s into it in order - a snapshot of+//! the fetched log first, then confirmed rows as they arrive over the socket,+//! and the client's own actions the moment it issues them. Each push reports+//! what it changed.+//!+//! The confirmed rows arrive in exactly the shape the raw-log endpoint serves+//! and the realtime event carries - `{createdAt, id, userId?, direction,+//! content}` per row - so a caller passes bytes through rather than+//! translating them. A speculated action arrives as the same JSON the control+//! endpoint accepts, so the client never learns a second shape for it.//!//! The shape JavaScript actually sees lives in [`crate::inbound::wire`], not//! here - this module is only the wasm-bindgen glue that carries values of//! those types across the boundary. See that module's docs for why they are//! kept apart.-//!-//! # Why catching up is not a loop of pushes-//!-//! [`FoldStream::extend`] exists rather than leaving a caller to push a-//! fetched log frame by frame. A push serializes the message it changed-//! across the boundary, and a session's frames overwhelmingly change the same-//! agent message over and over - so replaying 6500 frames one at a time would-//! serialize 6500 whole messages to produce one. `extend` folds them all and-//! serializes the answer once.-use crate::domain::fold::fold;-use crate::domain::ingestion::{LogCursor, LogIngestion};+use crate::domain::ingestion::LogCursor;use crate::domain::log::{AgentSessionId, AgentSessionLog, Message};-use crate::domain::model::{FoldedMessage as ModelFoldedMessage, SessionMetadata};-use crate::domain::ports::FoldMachine;+use crate::domain::model::SessionMetadata;+use crate::domain::speculation::{FoldInput, Speculation, SpeculativeFold};use crate::inbound::wire::{FoldedMessage, FoldedStreamEvent};+use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};use macro_user_id::user_id::MacroUserIdStr;use serde::Deserialize;use wasm_bindgen::prelude::*;-/// Fold one session's log into the messages a channel renders.-///-/// `session_id` is the session the entries belong to; it is not repeated per-/// entry, and it is what the returned `agentSessionMessageId`s are built from.-///-/// Errors only on input this cannot read - a session id that is not a UUID, or-/// entries that are not log frames. The fold itself is total: an unrecognized-/// or half-finished frame yields a partially-known message rather than a-/// failure, because rendering some of a session always beats rendering none.-///-/// # Errors-///-/// Returns a JS string describing what could not be read.-#[wasm_bindgen]-pub fn fold_session(session_id: &str, entries: JsValue) -> Result<JsValue, JsValue> {- let session = parse_session(session_id)?;- let messages = fold(parse_log(session, entries)?);- encode_messages(session, messages)-}--/// One live session's fold, held open between frames.-///-/// The streaming counterpart to [`fold_session`], wrapping the same-/// [`crate::domain::fold::FoldMachineImpl`] the server folds with. A caller following a session-/// keeps one of these per session for as long as the session lasts: frames-/// must arrive in log order. Successful loads replace its committed history.+/// One live session's fold, held open between inputs.///-/// A durable-log client catches up with [`Self::snapshot`] and follows with-/// [`Self::push_rows`]. Raw recording consumers use [`Self::extend`] and-/// [`Self::push`] without requiring row metadata. Refolding the-/// fetched log into a throwaway and then pushing live frames into a second-/// machine would derive the same messages twice from different halves of the-/// log; there is one machine per session precisely so that cannot happen.+/// Wraps [`SpeculativeFold`], which wraps the same+/// [`crate::domain::fold::FoldMachineImpl`] the server folds with. A caller+/// following a session keeps one of these per session for as long as the+/// session lasts and pushes every input through [`Self::push`]: the fetched+/// log and the streamed frames after it go into one machine, so a channel+/// opened mid-session continues the fold rather than starting a second one+/// beside it.#[wasm_bindgen]pub struct FoldStream {/// Half of the composite id every message this machine derives is keyed- /// by, and the reason the session id is taken once rather than per frame.+ /// by, and the reason the session id is taken once rather than per input.session: AgentSessionId,- ingestion: LogIngestion,+ fold: SpeculativeFold,}#[wasm_bindgen]impl FoldStream {- /// Replace this fold with a durable effective-history snapshot.- ///- /// # Errors- /// Returns a JS string if any durable row cannot be read.- pub fn snapshot(&mut self, entries: JsValue) -> Result<JsValue, JsValue> {- let entries: Vec<DurableEntry> = serde_wasm_bindgen::from_value(entries)- .map_err(|error| JsValue::from_str(&format!("log rows are not readable: {error}")))?;- self.ingestion.replace_snapshot(- entries- .into_iter()- .map(|entry| (entry.cursor, entry.frame.into_log(self.session)))- .collect(),- );- self.messages()- }-- /// Ingest durable live rows in delivery order, including snapshot overlap.- ///- /// # Errors- /// Returns a JS string if any row cannot be read or events cannot be encoded.- pub fn push_rows(&mut self, entries: JsValue) -> Result<JsValue, JsValue> {- let entries: Vec<DurableEntry> = serde_wasm_bindgen::from_value(entries)- .map_err(|error| JsValue::from_str(&format!("log rows are not readable: {error}")))?;- let mut events = Vec::new();- for entry in entries {- events.extend(- self.ingestion- .push(entry.cursor, entry.frame.into_log(self.session))- .into_iter()- .map(|event| FoldedStreamEvent::new(self.session, event)),- );- }- encode(&events)- .map_err(|error| JsValue::from_str(&format!("fold events are not encodable: {error}")))- }-- /// A machine for `session_id` that has folded nothing.+ /// A fold for `session_id` that has seen nothing. The first input pushed+ /// must be a snapshot.////// # Errors////// Returns a JS string when the session id is not a UUID.#[wasm_bindgen(constructor)]pub fn new(session_id: &str) -> Result<FoldStream, JsValue> {+ let session = parse_session(session_id)?;Ok(Self {- session: parse_session(session_id)?,- ingestion: LogIngestion::default(),+ session,+ fold: SpeculativeFold::new(session),})}- /// Fold a run of frames in one go, answering with every message derived- /// so far - the catch-up path. See the module docs for why this is not a- /// loop of [`Self::push`].+ /// Fold inputs in order, reporting the changes they implied as an array+ /// of `{kind: "new" | "update", message}`, `{kind: "replace", messages}`+ /// and `{kind: "metadata", metadata}` events. Empty for inputs that+ /// change nothing renderable, which is most confirmed rows.////// # Errors///- /// Returns a JS string when the entries are not log frames.- pub fn extend(&mut self, entries: JsValue) -> Result<JsValue, JsValue> {- for entry in parse_log(self.session, entries)? {- let _ = self.ingestion.machine.push(entry);+ /// Returns a JS string when an input cannot be read, when a live or+ /// speculative input arrives before any snapshot, or when an action+ /// cannot be encoded as the frame the harness would log.+ pub fn push(&mut self, inputs: JsValue) -> Result<JsValue, JsValue> {+ let inputs: Vec<WireInput> = serde_wasm_bindgen::from_value(inputs).map_err(|error| {+ JsValue::from_str(&format!("fold inputs are not readable: {error}"))+ })?;+ let mut events = Vec::new();+ for input in inputs {+ let input = input.into_input(self.session)?;+ let changes = self+ .fold+ .push(input)+ .map_err(|error| JsValue::from_str(&error.to_string()))?;+ events.extend(+ changes+ .into_iter()+ .map(|event| FoldedStreamEvent::new(self.session, event)),+ );}- self.messages()- }-- /// Fold one more frame, reporting the changes it implied as an array of- /// `{kind: "new" | "update", message}`, `{kind: "replace", messages}`,- /// and `{kind: "metadata", metadata}`- /// events - empty for a frame that changes nothing, which is most of- /// them.- ///- /// # Errors- ///- /// Returns a JS string when the entry is not a log frame.- pub fn push(&mut self, entry: JsValue) -> Result<JsValue, JsValue> {- let entry: LogEntry = serde_wasm_bindgen::from_value(entry)- .map_err(|error| JsValue::from_str(&format!("log entry is not readable: {error}")))?;-- let events: Vec<FoldedStreamEvent> = self- .ingestion- .machine- .push(entry.into_log(self.session))- .into_iter()- .map(|event| FoldedStreamEvent::new(self.session, event))- .collect();-encode(&events).map_err(|error| JsValue::from_str(&format!("fold events are not encodable: {error}")))}/// The session metadata as it now stands - what the latest- /// `{kind: "metadata"}` event carried, for a caller that caught up with- /// [`Self::extend`] and saw no events.+ /// `{kind: "metadata"}` event carried.////// # Errors////// Returns a JS string describing what could not be encoded.pub fn metadata(&self) -> Result<JsValue, JsValue> {- let metadata: SessionMetadata = self.ingestion.machine.metadata().clone().into();- encode(&metadata).map_err(|error| {+ let metadata: &SessionMetadata = self.fold.metadata();+ encode(metadata).map_err(|error| {JsValue::from_str(&format!("session metadata is not encodable: {error}"))})}- /// Every message folded so far, oldest first.- ///- /// The same answer [`fold_session`] gives for the frames pushed so far -- /// they are one fold - which is what a reader relies on when a channel- /// that has been following a session is reopened.+ /// Every message as the reader should see it, oldest first - the+ /// confirmed conversation with this client's unconfirmed actions on top.////// # Errors////// Returns a JS string describing what could not be encoded.pub fn messages(&self) -> Result<JsValue, JsValue> {let messages: Vec<FoldedMessage> = self- .ingestion- .machine+ .fold.messages().iter().cloned()@@ -211,31 +134,6 @@ fn parse_session(session_id: &str) -> Result<AgentSessionId, JsValue> {.map_err(|error| JsValue::from_str(&format!("session id is not a uuid: {error}")))}-/// Read an array of served log entries as this session's log frames.-fn parse_log(session: AgentSessionId, entries: JsValue) -> Result<Vec<AgentSessionLog>, JsValue> {- let entries: Vec<LogEntry> = serde_wasm_bindgen::from_value(entries)- .map_err(|error| JsValue::from_str(&format!("log entries are not readable: {error}")))?;-- Ok(entries- .into_iter()- .map(|entry| entry.into_log(session))- .collect())-}--/// Encode folded messages for the browser.-fn encode_messages(- session: AgentSessionId,- messages: Vec<ModelFoldedMessage>,-) -> Result<JsValue, JsValue> {- let messages: Vec<FoldedMessage> = messages- .into_iter()- .map(|message| FoldedMessage::new(session, message))- .collect();-- encode(&messages)- .map_err(|error| JsValue::from_str(&format!("folded messages are not encodable: {error}")))-}-/// Encode a value for the browser as plain JSON-shaped data.////// `serde_wasm_bindgen`'s default turns a `serde_json::Value` object into an@@ -246,6 +144,51 @@ fn encode<T: serde::Serialize>(value: &T) -> Result<JsValue, serde_wasm_bindgen:serde::Serialize::serialize(value, &serde_wasm_bindgen::Serializer::json_compatible())}+/// One input, as JavaScript sends it. Mirrors the `FoldInput` union in the+/// worker protocol.+#[derive(Deserialize)]+#[serde(tag = "kind", rename_all = "snake_case")]+enum WireInput {+ /// `{kind: "snapshot", rows: DurableEntry[]}`+ Snapshot { rows: Vec<DurableEntry> },+ /// `{kind: "confirmed", row: DurableEntry}`+ Confirmed { row: DurableEntry },+ /// `{kind: "speculated", actionId, action, userId?}` - `action` is the+ /// control endpoint's request body. The user id is the caller's own, so+ /// it is read strictly: a client that cannot name itself has a bug.+ #[serde(rename_all = "camelCase")]+ Speculated {+ action_id: AgentActionId,+ action: AgentAction,+ #[serde(default)]+ user_id: Option<MacroUserIdStr<'static>>,+ },+ /// `{kind: "retracted", actionId}`+ #[serde(rename_all = "camelCase")]+ Retracted { action_id: AgentActionId },+}++impl WireInput {+ fn into_input(self, session: AgentSessionId) -> Result<FoldInput, JsValue> {+ Ok(match self {+ Self::Snapshot { rows } => FoldInput::Snapshot(+ rows.into_iter()+ .map(|row| (row.cursor, row.frame.into_log(session)))+ .collect(),+ ),+ Self::Confirmed { row } => {+ FoldInput::Confirmed(row.cursor, row.frame.into_log(session))+ }+ Self::Speculated {+ action_id,+ action,+ user_id,+ } => FoldInput::Speculated(Speculation::new(action_id, action, user_id)),+ Self::Retracted { action_id } => FoldInput::Retracted(action_id),+ })+ }+}+/// One entry of a session's protocol log, as the endpoint serves it.#[derive(Deserialize)]struct LogEntry {@@ -258,6 +201,8 @@ struct LogEntry {message: Message,}+/// A log entry with its durable cursor, as the endpoint and the realtime+/// event both carry it.#[derive(Deserialize)]struct DurableEntry {#[serde(flatten)]diff --git a/crates/agent_fold/src/inbound/wire.rs b/crates/agent_fold/src/inbound/wire.rsindex c8beb9cbe3..098d5f5d16 100644--- a/crates/agent_fold/src/inbound/wire.rs+++ b/crates/agent_fold/src/inbound/wire.rs@@ -38,6 +38,10 @@ pub struct FoldedMessage {parts: Vec<MessagePart>,/// How the turn ended, absent while it remains in flight.stop: Option<StopReason>,+ /// Derived from an action this client issued that the log has not yet+ /// confirmed. A reader shows it as sending; it flips off in place when+ /// the confirmed frame arrives.+ pending: bool,}impl FoldedMessage {@@ -51,6 +55,7 @@ impl FoldedMessage {request_id: message.request_id.map(|id| id.to_string()),parts: message.parts.into_inner(),stop: message.stop,+ pending: message.pending,}}}diff --git a/crates/agent_fold/src/inbound/wire/test.rs b/crates/agent_fold/src/inbound/wire/test.rsindex 0e1f862732..e8ff6c9d85 100644--- a/crates/agent_fold/src/inbound/wire/test.rs+++ b/crates/agent_fold/src/inbound/wire/test.rs@@ -22,6 +22,7 @@ fn domain_parts_serialize_directly_into_the_browser_contract() {},}),stop: None,+ pending: false,};let session = AgentSessionId::new_from_uuid(macro_uuid::Uuid::from_u128(7));@@ -44,7 +45,8 @@ fn domain_parts_serialize_directly_into_the_browser_contract() {"exitCode": null}}],- "stop": null+ "stop": null,+ "pending": false}));diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rsindex 63e223e039..896cce401d 100644--- a/crates/agent_harness/src/domain/model.rs+++ b/crates/agent_harness/src/domain/model.rs@@ -264,13 +264,15 @@ impl DeliverAction {}}- /// A control request under a caller-visible id. Names no origin: control- /// is "deliver this to the session", and announcing a prompt into its- /// channel is the trigger pipeline's job, keyed on what it observed- /// rather than anything a caller claims.- pub fn control(id: AgentActionId, event: ControlEvent) -> Self {+ /// A control request under a caller-visible id: the caller's own id when+ /// it named one, so its optimistic entry is confirmed in place, and a+ /// freshly minted id otherwise. Names no origin: control is "deliver this+ /// to the session", and announcing a prompt into its channel is the+ /// trigger pipeline's job, keyed on what it observed rather than anything+ /// a caller claims.+ pub fn control(event: ControlEvent) -> Self {Self {- id,+ id: event.action_id.unwrap_or_else(AgentActionId::mint),action: event.action,actor: event.actor,announce: None,diff --git a/crates/agent_harness/src/domain/service/lifecycle.rs b/crates/agent_harness/src/domain/service/lifecycle.rsindex 7a534dcee5..f82d0429c1 100644--- a/crates/agent_harness/src/domain/service/lifecycle.rs+++ b/crates/agent_harness/src/domain/service/lifecycle.rs@@ -61,12 +61,10 @@ whereid: AgentSessionId,event: ControlEvent,) -> agent_session::domain::error::Result<AcceptedControl> {- let action_id = AgentActionId::mint();+ let action = DeliverAction::control(event);+ let action_id = action.id;let outcome = self- .execute(- id,- HarnessCommand::Deliver(DeliverAction::control(action_id, event)),- )+ .execute(id, HarnessCommand::Deliver(action)).await.map_err(into_session_error)?;Ok(AcceptedControl {diff --git a/crates/agent_harness/src/domain/service/queue.rs b/crates/agent_harness/src/domain/service/queue.rsindex 3538c41e6e..93e671229e 100644--- a/crates/agent_harness/src/domain/service/queue.rs+++ b/crates/agent_harness/src/domain/service/queue.rs@@ -496,6 +496,14 @@ where/// order holds regardless. The outcome reports what happened to *this*/// action - still waiting, or on the wire.///+ /// An action whose id this session already holds is the same action+ /// arriving twice - a caller retrying a control request under the id it+ /// named. It reports what became of the first copy instead of queueing a+ /// second, so a retry cannot double-prompt. Only what this replica still+ /// holds is checked: an id whose action has already finished its turn is+ /// no longer anywhere to be seen, and accepting it again is indistinguishable+ /// from asking for the same thing twice on purpose.+ ////// A channel follow-up (`announce` set) that lands on a running turn/// steers: it goes to the front of the queue, a stop cancels the current/// turn, and the chip is posted on that follow-up immediately - so it@@ -506,6 +514,16 @@ wherecommand: DeliverAction,) -> Result<CommandOutcome> {let action_id = command.id;+ if self.queues.contains(session_id, action_id) {+ return Ok(CommandOutcome::Queued);+ }+ if self+ .busy+ .turn(session_id)+ .is_some_and(|turn| turn.action_id == action_id)+ {+ return Ok(CommandOutcome::Completed);+ }let prompt = match &command.action {AgentAction::Prompt(prompt) => Some(prompt.prompt.clone()),_ => None,diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rsindex bfbdf7f430..53cb5dbf60 100644--- a/crates/agent_harness/src/domain/service/test.rs+++ b/crates/agent_harness/src/domain/service/test.rs@@ -15,7 +15,7 @@ use agent_fold::domain::model::TurnSignal;use agent_fold::domain::model::{AuthorKind, MessageId};use agent_fold::domain::service::FoldedMessageService;use agent_runtime_protocol::domain::{- action::AgentAction,+ action::{AgentAction, AgentActionId},schema::v0::{AcpMessage, SystemEvent, ToRuntimeMessage, ToServerMessage},};use agent_session::PROTOCOL_VERSION;@@ -603,6 +603,7 @@ async fn claude_cloud_only_accepts_control_from_the_subscription_owner() {id,ControlEvent {action: AgentAction::prompt("spend another user's subscription"),+ action_id: None,actor,},)@@ -615,6 +616,7 @@ async fn claude_cloud_only_accepts_control_from_the_subscription_owner() {id,ControlEvent {action: AgentAction::prompt("owner follow-up"),+ action_id: None,actor: Some(owner),},);@@ -1295,6 +1297,7 @@ async fn changing_the_model_persists_it_and_tells_the_running_agent() {id,ControlEvent {action: AgentAction::set_model("opus"),+ action_id: None,actor: Some(sender()),},)@@ -1348,6 +1351,7 @@ async fn a_prompt_through_control_reaches_the_agent_without_announcing() {id,ControlEvent {action: AgentAction::prompt("and now the docs <user-content>unchanged</user-content>"),+ action_id: None,actor: Some(sender()),},);@@ -1392,6 +1396,7 @@ async fn a_non_staff_control_event_cannot_drive_a_sandboxed_coder_session() {id,ControlEvent {action: AgentAction::prompt("spend daytona credits"),+ action_id: None,actor: Some(sender()),},)@@ -1415,6 +1420,7 @@ async fn a_staff_control_event_can_drive_a_sandboxed_coder_session() {id,ControlEvent {action: AgentAction::prompt("continue"),+ action_id: None,actor: Some(staff_sender()),},)@@ -1465,6 +1471,7 @@ async fn a_prompt_during_a_running_turn_queues_and_dispatches_when_it_ends() {id,ControlEvent {action: AgentAction::prompt("and then this"),+ action_id: None,actor: Some(sender()),},)@@ -1513,6 +1520,7 @@ async fn a_stop_cancels_the_turn_and_the_queue_keeps_draining() {id,ControlEvent {action: AgentAction::prompt("still wanted after the stop"),+ action_id: None,actor: Some(sender()),},)@@ -1529,6 +1537,7 @@ async fn a_stop_cancels_the_turn_and_the_queue_keeps_draining() {id,ControlEvent {action: AgentAction::Stop,+ action_id: None,actor: Some(sender()),},)@@ -1583,6 +1592,7 @@ async fn a_channel_follow_up_stops_the_running_turn_announces_and_flushes() {id,ControlEvent {action: AgentAction::prompt("queued earlier from the session page"),+ action_id: None,actor: Some(staff_sender()),},)@@ -1705,6 +1715,7 @@ async fn queued_prompts_are_editable_and_removable_until_dispatch() {let prompt = |text: &str| ControlEvent {action: AgentAction::prompt(text),+ action_id: None,actor: Some(sender()),};let second = service.control_event(id, prompt("second")).await.unwrap();@@ -1768,6 +1779,7 @@ async fn a_model_change_bypasses_the_running_turn() {id,ControlEvent {action: AgentAction::set_model("opus"),+ action_id: None,actor: Some(sender()),},)@@ -1789,6 +1801,107 @@ async fn a_model_change_bypasses_the_running_turn() {agent.wait_for_requests(4).await;}+#[tokio::test]+async fn a_control_event_is_accepted_under_the_callers_own_action_id() {+ let ((service, _repo, containers, _announcer, _runtimes), _turns) =+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());+ let id = AgentSessionId::new();+ let _container = session_with_a_running_turn(&service, &containers, id).await;++ let action_id = AgentActionId::mint();+ let accepted = service+ .control_event(+ id,+ ControlEvent {+ action: AgentAction::prompt("speculated by the caller"),+ action_id: Some(action_id),+ actor: Some(sender()),+ },+ )+ .await+ .expect("a prompt is accepted behind the running turn");++ assert_eq!(+ accepted.action_id, action_id,+ "the caller's id names the action it already speculated"+ );+ assert_eq!(+ accepted.disposition,+ agent_session::domain::ports::ControlDisposition::Queued+ );+ let queued = service.queued_controls(id).await.expect("queue lists");+ assert_eq!(+ queued+ .iter()+ .map(|entry| entry.action_id)+ .collect::<Vec<_>>(),+ vec![action_id],+ "the queue entry keeps the caller's id, so the log row will too"+ );+}++#[tokio::test]+async fn a_control_event_without_an_action_id_is_given_a_fresh_one() {+ let ((service, _repo, containers, _announcer, _runtimes), _turns) =+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());+ let id = AgentSessionId::new();+ let _container = session_with_a_running_turn(&service, &containers, id).await;++ let unnamed = |text: &str| ControlEvent {+ action: AgentAction::prompt(text),+ action_id: None,+ actor: Some(sender()),+ };+ let first = service.control_event(id, unnamed("first")).await.unwrap();+ let second = service.control_event(id, unnamed("second")).await.unwrap();++ assert_ne!(+ first.action_id, second.action_id,+ "each unnamed action is minted its own id"+ );+ assert_eq!(+ service+ .queued_controls(id)+ .await+ .expect("queue lists")+ .iter()+ .map(|entry| entry.action_id)+ .collect::<Vec<_>>(),+ vec![first.action_id, second.action_id]+ );+}++/// A retried POST arrives under the id the caller already used. It reports+/// what became of the first copy; it does not prompt the agent twice.+#[tokio::test]+async fn re_sending_a_waiting_action_id_does_not_queue_it_twice() {+ let ((service, _repo, containers, _announcer, _runtimes), _turns) =+ harness_with_signals(PromptContextMock::default(), PromptComposerMock::default());+ let id = AgentSessionId::new();+ let _container = session_with_a_running_turn(&service, &containers, id).await;++ let action_id = AgentActionId::mint();+ let retried = || ControlEvent {+ action: AgentAction::prompt("said once"),+ action_id: Some(action_id),+ actor: Some(sender()),+ };+ let first = service.control_event(id, retried()).await.unwrap();+ let again = service.control_event(id, retried()).await.unwrap();++ assert_eq!(again.action_id, first.action_id);+ assert_eq!(again.disposition, first.disposition);+ assert_eq!(+ service+ .queued_controls(id)+ .await+ .expect("queue lists")+ .len(),+ 1,+ "the retry is the same action, not a second one"+ );+}+#[tokio::test]async fn compact_through_control_reaches_opencode_as_a_slash_command() {let (service, _repo, containers, _announcer, _runtimes) = harness();@@ -1799,6 +1912,7 @@ async fn compact_through_control_reaches_opencode_as_a_slash_command() {id,ControlEvent {action: AgentAction::Compact,+ action_id: None,actor: Some(sender()),},);@@ -1828,6 +1942,7 @@ async fn a_prompt_through_control_resumes_a_disconnected_session() {id,ControlEvent {action: AgentAction::prompt("wake up"),+ action_id: None,actor: Some(staff_sender()),},);@@ -1983,6 +2098,7 @@ async fn an_external_open_provisions_nothing_and_prompts_nobody() {session.id,ControlEvent {action: AgentAction::prompt("@claude fix the failing test"),+ action_id: None,actor: Some(sender()),},);@@ -2164,6 +2280,7 @@ async fn a_managed_session_resumes_its_sandbox_rather_than_a_dialed_in_runtime()id,ControlEvent {action: AgentAction::prompt("wake up"),+ action_id: None,actor: Some(staff_sender()),},);@@ -2670,9 +2787,7 @@ mod lifecycle_events {RequestId,};use agent_fold::domain::model::TurnId;- use agent_runtime_protocol::domain::action::{- AgentActionId, ElicitationAnswer, ElicitationRequestId,- };+ use agent_runtime_protocol::domain::action::{ElicitationAnswer, ElicitationRequestId};use agent_session::domain::events::AgentSessionLifecycleEvent as Lifecycle;/// Open a session from a mention and let its first turn settle: `Opened`,@@ -2881,6 +2996,7 @@ mod lifecycle_events {// `a_channel_follow_up_stops_the_running_turn_announces_and_flushes`.let prompt = |text: &str| ControlEvent {action: AgentAction::prompt(text),+ action_id: None,actor: Some(staff_sender()),};service@@ -2962,16 +3078,14 @@ mod lifecycle_events {service.execute(id,- HarnessCommand::Deliver(DeliverAction::control(- AgentActionId::mint(),- ControlEvent {- action: AgentAction::respond_elicitation(- ElicitationRequestId::Number(7),- ElicitationAnswer::Decline,- ),- actor: Some(staff_sender()),- },- )),+ HarnessCommand::Deliver(DeliverAction::control(ControlEvent {+ action: AgentAction::respond_elicitation(+ ElicitationRequestId::Number(7),+ ElicitationAnswer::Decline,+ ),+ action_id: None,+ actor: Some(staff_sender()),+ })),).await.expect("the answer is delivered");diff --git a/crates/agent_runtime_protocol/src/domain/action.rs b/crates/agent_runtime_protocol/src/domain/action.rsindex d7e75a9b54..5c36c1dc78 100644--- a/crates/agent_runtime_protocol/src/domain/action.rs+++ b/crates/agent_runtime_protocol/src/domain/action.rs@@ -27,11 +27,12 @@ pub const MODEL_CONFIG_ID: &str = "model";/// frame, and read back off that frame as `request_id` on the folded message/// it derives.///-/// Minted only by the server at accept time, as a v7 uuid so ids sort by mint-/// time. On the wire and in JSON it is the bare uuid, and a uuid-shaped-/// request id is the whole ownership test: the server is the only writer of-/// runtime-bound frames. The machine's own handshake request ids-/// (`agent_session:{session}:{n}`) are not uuids and stay `None`.+/// A v7 uuid, so ids sort by mint time. Minted by the server at accept time,+/// or by a client that speculated the action and named it in the control+/// request - either way the server is the only writer of runtime-bound+/// frames, so a uuid-shaped request id remains the whole ownership test. The+/// machine's own handshake request ids (`agent_session:{session}:{n}`) are+/// not uuids and stay `None`.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(transparent)]#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rsindex 0a2427e3b4..3682155a8f 100644--- a/crates/agent_session/src/domain/ports.rs+++ b/crates/agent_session/src/domain/ports.rs@@ -863,6 +863,11 @@ impl AgentSessionRealtime for NoOpRealtime {pub struct ControlEvent {/// What the agent was asked to do.pub action: AgentAction,+ /// The id the caller already speculated this action under, when it minted+ /// one. Adopted as the accepted id so the caller's optimistic entry is+ /// promoted in place rather than retracted and reissued; `None` leaves+ /// the recipient to mint one.+ pub action_id: Option<AgentActionId>,/// The user responsible, absent when a bot acted on nobody's behalf.////// `None` means "no user is responsible", not "unknown" - a bot's own@@ -921,6 +926,11 @@ pub trait AgentSessionNotificationRecipient: Send + Sync + 'static {/// A control operation the live connection has to be told about. Returns/// the action id the caller correlates against the fold stream, and/// whether the action went out or waits in the session's queue.+ ///+ /// A caller-supplied [`ControlEvent::action_id`] is adopted as that id.+ /// Re-sending an action under an id the session still has queued or in+ /// flight reports what became of the first one instead of accepting a+ /// second, so a retried request cannot double-prompt.fn control_event(&self,id: AgentSessionId,diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rsindex 974869c4b0..5c09bc4138 100644--- a/crates/agent_session/src/inbound/axum_router.rs+++ b/crates/agent_session/src/inbound/axum_router.rs@@ -374,6 +374,16 @@ pub struct RenameAgentSessionRequest {#[derive(Debug, Serialize, Deserialize, ToSchema)]#[serde(rename_all = "camelCase")]pub struct ControlRequest {+ /// The id the caller already speculated this action under, when it has+ /// one. Adopted as the accepted id, so a client that renders the action+ /// optimistically promotes that entry in place instead of retracting it+ /// and re-speculating under a server id. Re-sending the same id is not a+ /// second action: see [`ControlResponse`].+ ///+ /// Named rather than flattened so it cannot collide with the action's own+ /// fields, which are tagged under `type`.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub action_id: Option<AgentActionId>,/// The operation to perform.#[serde(flatten)]pub action: AgentAction,@@ -407,7 +417,8 @@ impl From<ControlDisposition> for ControlStatusDto {#[serde(rename_all = "camelCase")]pub struct ControlResponse {/// Matches `requestId` on the folded message this action derives once it- /// dispatches, and names the queue entry until then.+ /// dispatches, and names the queue entry until then. The caller's own+ /// `actionId` when it supplied one; a freshly minted id otherwise.pub action_id: AgentActionId,/// Whether the action went out or waits in the queue.pub status: ControlStatusDto,@@ -818,6 +829,10 @@ async fn ensure_harness_serves_session<R: AgentSessionNotificationRecipient>(////// Edit access suffices: whoever can prompt the bot through its thread can/// prompt it here.+///+/// A caller may name the action with `actionId`; the response echoes it.+/// Re-posting an id the session still holds queued or in flight reports that+/// action's status rather than accepting a duplicate.#[tracing::instrument(skip_all,fields(@@ -856,6 +871,7 @@ pub async fn control_agent_session_handler<AgentSessionId::new_from_uuid(session_id),ControlEvent {action: req.action,+ action_id: req.action_id,actor,},)diff --git a/crates/agent_session/src/inbound/axum_router/test.rs b/crates/agent_session/src/inbound/axum_router/test.rsindex 5a0491cf14..79a1e5ad2e 100644--- a/crates/agent_session/src/inbound/axum_router/test.rs+++ b/crates/agent_session/src/inbound/axum_router/test.rs@@ -794,6 +794,60 @@ async fn an_external_open_carries_its_instructions() {mod read;+/// The client speculates under an id it mints and sends it alongside the+/// action's own flattened fields, which are tagged under `type`.+#[test]+fn a_control_request_carries_the_callers_action_id() {+ let action_id = AgentActionId::mint();+ let request: ControlRequest = serde_json::from_value(serde_json::json!({+ "type": "prompt",+ "prompt": "hello",+ "actionId": action_id,+ }))+ .expect("a control request with an action id parses");++ assert_eq!(request.action_id, Some(action_id));+ assert_eq!(request.action, AgentAction::prompt("hello"));+}++#[test]+fn a_control_request_without_an_action_id_names_none() {+ let request: ControlRequest = serde_json::from_value(serde_json::json!({+ "type": "compact",+ }))+ .expect("a control request without an action id parses");++ assert_eq!(request.action_id, None);+ assert_eq!(request.action, AgentAction::Compact);+}++/// A caller that names no id must not put `actionId: null` on the wire: the+/// field is absent, so an older reader sees exactly what it saw before.+#[test]+fn an_unnamed_control_request_omits_the_field() {+ let body = serde_json::to_value(ControlRequest {+ action_id: None,+ action: AgentAction::Stop,+ })+ .expect("a control request serializes");++ assert_eq!(body, serde_json::json!({ "type": "stop" }));+}++/// A client that speculates an action sends the id it speculated under. The+/// action's own fields are flattened in beside it, so this pins that the+/// named id survives that flatten rather than being swallowed by the enum.+#[test]+fn a_control_request_keeps_the_client_minted_action_id() {+ let body =+ r#"{"type":"prompt","prompt":"hi","actionId":"01a0acab-5eff-72d6-91ca-16997a26d13a"}"#;+ let request: ControlRequest = serde_json::from_str(body).expect("the body parses");+ assert_eq!(+ request.action_id.map(|id| id.to_string()).as_deref(),+ Some("01a0acab-5eff-72d6-91ca-16997a26d13a")+ );+}+#[tokio::test]async fn managed_repository_and_branch_reach_the_domain() {let opener = Arc::new(RecordingOpener::default());diff --git a/crates/codex_cloud_agents/tests/snapshots/fold__recorded_missing_deltas_replay.snap b/crates/codex_cloud_agents/tests/snapshots/fold__recorded_missing_deltas_replay.snapindex 5bbd808313..014103c379 100644--- a/crates/codex_cloud_agents/tests/snapshots/fold__recorded_missing_deltas_replay.snap+++ b/crates/codex_cloud_agents/tests/snapshots/fold__recorded_missing_deltas_replay.snap@@ -16,7 +16,8 @@ expression: messages"text": "wh atis this repo how is ti going man"}],- "stop": null+ "stop": null,+ "pending": false},{"turn": 0,@@ -66,7 +67,8 @@ expression: messages],"stop": {"kind": "end_turn"- }+ },+ "pending": false},{"turn": 1,@@ -81,7 +83,8 @@ expression: messages"text": "what is your name"}],- "stop": null+ "stop": null,+ "pending": false},{"turn": 1,@@ -97,6 +100,7 @@ expression: messages],"stop": {"kind": "end_turn"- }+ },+ "pending": false}]diff --git a/crates/codex_cloud_agents/tests/snapshots/fold__verified_pr_tool.snap b/crates/codex_cloud_agents/tests/snapshots/fold__verified_pr_tool.snapindex 68d016f7be..9c814b308e 100644--- a/crates/codex_cloud_agents/tests/snapshots/fold__verified_pr_tool.snap+++ b/crates/codex_cloud_agents/tests/snapshots/fold__verified_pr_tool.snap@@ -16,7 +16,8 @@ expression: messages"text": "Inspect repository"}],- "stop": null+ "stop": null,+ "pending": false},{"turn": 0,@@ -55,6 +56,7 @@ expression: messages],"stop": {"kind": "end_turn"- }+ },+ "pending": false}]diff --git a/crates/coding_agent_worker/src/outbound/agent_session.rs b/crates/coding_agent_worker/src/outbound/agent_session.rsindex a518a64164..2838558094 100644--- a/crates/coding_agent_worker/src/outbound/agent_session.rs+++ b/crates/coding_agent_worker/src/outbound/agent_session.rs@@ -106,7 +106,10 @@ impl HarnessApi {.post(format!("{}/agent-sessions/{session}/control", self.base)).header(HARNESS_TOKEN_HEADER, &self.token).header(HARNESS_ACTING_USER_HEADER, actor.as_ref())- .json(&ControlRequest { action })+ .json(&ControlRequest {+ action_id: None,+ action,+ }).send().await?;refuse_errors(response).await?;diff --git a/packages/sdk/generated/agent-harness/sdk.gen.ts b/packages/sdk/generated/agent-harness/sdk.gen.tsindex 637ee47cbf..f52bfcfa83 100644--- a/packages/sdk/generated/agent-harness/sdk.gen.ts+++ b/packages/sdk/generated/agent-harness/sdk.gen.ts@@ -151,6 +151,10 @@ export class Sdk extends HeyApiClient {** Edit access suffices: whoever can prompt the bot through its thread can* prompt it here.+ *+ * A caller may name the action with `actionId`; the response echoes it.+ * Re-posting an id the session still holds queued or in flight reports that+ * action's status rather than accepting a duplicate.*/public controlAgentSession<ThrowOnError extends boolean = false>(options: Options<ControlAgentSessionData, ThrowOnError>): RequestResult<ControlAgentSessionResponses, ControlAgentSessionErrors, ThrowOnError> {return (options.client ?? this.client).post<ControlAgentSessionResponses, ControlAgentSessionErrors, ThrowOnError>({diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.tsindex 5e9d75d813..064a3c96f1 100644--- a/packages/sdk/generated/agent-harness/types.gen.ts+++ b/packages/sdk/generated/agent-harness/types.gen.ts@@ -25,11 +25,12 @@ export type AgentAction = (AgentPromptAction & {* frame, and read back off that frame as `request_id` on the folded message* it derives.*- * Minted only by the server at accept time, as a v7 uuid so ids sort by mint- * time. On the wire and in JSON it is the bare uuid, and a uuid-shaped- * request id is the whole ownership test: the server is the only writer of- * runtime-bound frames. The machine's own handshake request ids- * (`agent_session:{session}:{n}`) are not uuids and stay `None`.+ * A v7 uuid, so ids sort by mint time. Minted by the server at accept time,+ * or by a client that speculated the action and named it in the control+ * request - either way the server is the only writer of runtime-bound+ * frames, so a uuid-shaped request id remains the whole ownership test. The+ * machine's own handshake request ids (`agent_session:{session}:{n}`) are+ * not uuids and stay `None`.*/export type AgentActionId = string;@@ -329,9 +330,18 @@ export type CompleteRequest = {};/**- * The operation to perform.+ * Request body for a control operation on a live session.+ *+ * A wrapper around the operation rather than the bare enum so that fields+ * which are about the request rather than the operation have somewhere to go.+ * The acting user is deliberately not one of them: it comes from the caller's+ * credentials, so that a caller cannot attribute an operation to someone else.+ *+ * Clients serialize this, so both derives are used.*/-export type ControlRequest = AgentAction;+export type ControlRequest = AgentAction & {+ actionId?: null | AgentActionId;+};/*** Response body for a control operation.@@ -341,7 +351,8 @@ export type ControlRequest = AgentAction;export type ControlResponse = {/*** Matches `requestId` on the folded message this action derives once it- * dispatches, and names the queue entry until then.+ * dispatches, and names the queue entry until then. The caller's own+ * `actionId` when it supplied one; a freshly minted id otherwise.*/actionId: AgentActionId;/**diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex 2a178e660f..b219646856 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -127,11 +127,12 @@ export type Agent = {* frame, and read back off that frame as `request_id` on the folded message* it derives.*- * Minted only by the server at accept time, as a v7 uuid so ids sort by mint- * time. On the wire and in JSON it is the bare uuid, and a uuid-shaped- * request id is the whole ownership test: the server is the only writer of- * runtime-bound frames. The machine's own handshake request ids- * (`agent_session:{session}:{n}`) are not uuids and stay `None`.+ * A v7 uuid, so ids sort by mint time. Minted by the server at accept time,+ * or by a client that speculated the action and named it in the control+ * request - either way the server is the only writer of runtime-bound+ * frames, so a uuid-shaped request id remains the whole ownership test. The+ * machine's own handshake request ids (`agent_session:{session}:{n}`) are+ * not uuids and stay `None`.*/export type AgentActionId = string;diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.jsonindex 8d16a0e071..7ca3f4554b 100644--- a/packages/sdk/specs/agent-harness.json+++ b/packages/sdk/specs/agent-harness.json@@ -405,7 +405,7 @@"post": {"tags": ["agent-sessions"],"summary": "Perform a control operation on a live agent session.",- "description": "Edit access suffices: whoever can prompt the bot through its thread can\nprompt it here.",+ "description": "Edit access suffices: whoever can prompt the bot through its thread can\nprompt it here.\n\nA caller may name the action with `actionId`; the response echoes it.\nRe-posting an id the session still holds queued or in flight reports that\naction's status rather than accepting a duplicate.","operationId": "control_agent_session","parameters": [{@@ -1138,7 +1138,7 @@"AgentActionId": {"type": "string","format": "uuid",- "description": "Identifies one accepted [`AgentAction`] end to end: returned by the\ncontrol endpoint, written as the JSON-RPC request id on the action's wire\nframe, and read back off that frame as `request_id` on the folded message\nit derives.\n\nMinted only by the server at accept time, as a v7 uuid so ids sort by mint\ntime. On the wire and in JSON it is the bare uuid, and a uuid-shaped\nrequest id is the whole ownership test: the server is the only writer of\nruntime-bound frames. The machine's own handshake request ids\n(`agent_session:{session}:{n}`) are not uuids and stay `None`."+ "description": "Identifies one accepted [`AgentAction`] end to end: returned by the\ncontrol endpoint, written as the JSON-RPC request id on the action's wire\nframe, and read back off that frame as `request_id` on the folded message\nit derives.\n\nA v7 uuid, so ids sort by mint time. Minted by the server at accept time,\nor by a client that speculated the action and named it in the control\nrequest - either way the server is the only writer of runtime-bound\nframes, so a uuid-shaped request id remains the whole ownership test. The\nmachine's own handshake request ids (`agent_session:{session}:{n}`) are\nnot uuids and stay `None`."},"AgentModelDto": {"type": "object",@@ -1539,6 +1539,22 @@{"$ref": "#/components/schemas/AgentAction","description": "The operation to perform."+ },+ {+ "type": "object",+ "properties": {+ "actionId": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/AgentActionId",+ "description": "The id the caller already speculated this action under, when it has\none. Adopted as the accepted id, so a client that renders the action\noptimistically promotes that entry in place instead of retracting it\nand re-speculating under a server id. Re-sending the same id is not a\nsecond action: see [`ControlResponse`].\n\nNamed rather than flattened so it cannot collide with the action's own\nfields, which are tagged under `type`."+ }+ ]+ }+ }}],"description": "Request body for a control operation on a live session.\n\nA wrapper around the operation rather than the bare enum so that fields\nwhich are about the request rather than the operation have somewhere to go.\nThe acting user is deliberately not one of them: it comes from the caller's\ncredentials, so that a caller cannot attribute an operation to someone else.\n\nClients serialize this, so both derives are used."@@ -1550,7 +1566,7 @@"properties": {"actionId": {"$ref": "#/components/schemas/AgentActionId",- "description": "Matches `requestId` on the folded message this action derives once it\ndispatches, and names the queue entry until then."+ "description": "Matches `requestId` on the folded message this action derives once it\ndispatches, and names the queue entry until then. The caller's own\n`actionId` when it supplied one; a freshly minted id otherwise."},"status": {"$ref": "#/components/schemas/ControlStatusDto",diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex 489ecc05ae..240858172b 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -14335,7 +14335,7 @@"AgentActionId": {"type": "string","format": "uuid",- "description": "Identifies one accepted [`AgentAction`] end to end: returned by the\ncontrol endpoint, written as the JSON-RPC request id on the action's wire\nframe, and read back off that frame as `request_id` on the folded message\nit derives.\n\nMinted only by the server at accept time, as a v7 uuid so ids sort by mint\ntime. On the wire and in JSON it is the bare uuid, and a uuid-shaped\nrequest id is the whole ownership test: the server is the only writer of\nruntime-bound frames. The machine's own handshake request ids\n(`agent_session:{session}:{n}`) are not uuids and stay `None`."+ "description": "Identifies one accepted [`AgentAction`] end to end: returned by the\ncontrol endpoint, written as the JSON-RPC request id on the action's wire\nframe, and read back off that frame as `request_id` on the folded message\nit derives.\n\nA v7 uuid, so ids sort by mint time. Minted by the server at accept time,\nor by a client that speculated the action and named it in the control\nrequest - either way the server is the only writer of runtime-bound\nframes, so a uuid-shaped request id remains the whole ownership test. The\nmachine's own handshake request ids (`agent_session:{session}:{n}`) are\nnot uuids and stay `None`."},"AgentChannelScope": {"type": "string",