Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

Merge upstream/main (incl. #6590 transcript ordering) into chat-stream-parity

Steven Enamakel45cc062434f4
diff --cc app/src/features/conversations/derived/mapDisplayItems.test.ts
index 16a53fc70a,28c4a3eded..47a8acad25
--- a/app/src/features/conversations/derived/mapDisplayItems.test.ts
+++ b/app/src/features/conversations/derived/mapDisplayItems.test.ts
@@@ -351,66 -351,85 +351,168 @@@ describe('mapDisplayItems', () =>
expect(timelines['req-1'][0].round).toBe(2);
});
+ /**
+ * The core projects a step's reasoning *before* its message. The round used
+ * to be taken only from the following assistantMessage, so each step's
+ * reasoning was filed under the previous step.
+ */
+ it('files reasoning under the step it precedes, from its own iteration', () => {
+ const chronological: DerivedDisplayItem[] = [
+ { kind: 'turnBoundary', requestId: 'req-1' },
+ { kind: 'reasoning', text: 'think one', iteration: 1 },
+ {
+ kind: 'assistantMessage',
+ content: 'Let me check.',
+ interim: true,
+ iteration: 1,
+ requestId: 'req-1',
+ },
+ { kind: 'toolCall', callId: 'c1', name: 'shell', status: 'success', iteration: 1 },
+ { kind: 'reasoning', text: 'think two', iteration: 2 },
+ // Step 2 has no narration: only its tool call says which step it is.
+ { kind: 'toolCall', callId: 'c2', name: 'shell', status: 'success', iteration: 2 },
+ { kind: 'reasoning', text: 'think three', iteration: 3 },
+ { kind: 'assistantMessage', content: 'Done.', iteration: 3, requestId: 'req-1' },
+ ];
+
+ const { transcripts, timelines } = mapDisplayItems(newestFirst(chronological));
+
+ const thinking = transcripts['req-1']
+ .filter(item => item.kind === 'thinking')
+ .map(item => ('text' in item ? [item.text, item.round] : []));
+ expect(thinking).toEqual([
+ ['think one', 1],
+ ['think two', 2],
+ ['think three', 3],
+ ]);
+ expect(timelines['req-1'].map(entry => [entry.id, entry.round])).toEqual([
+ ['c1', 1],
+ ['c2', 2],
+ ]);
+ });
+
+ it('keys sub-agent rows by their unique run id and maps their terminal status', () => {
+ const chronological: DerivedDisplayItem[] = [
+ { kind: 'turnBoundary', requestId: 'req-1' },
+ { kind: 'toolCall', callId: 'c1', name: 'research', status: 'success', iteration: 1 },
+ {
+ kind: 'subagent',
+ id: 'sub-aaa',
+ agentId: 'researcher',
+ taskId: 'sub-aaa',
+ callId: 'c1',
+ status: 'completed',
+ requestId: 'req-1',
+ items: [],
+ },
+ { kind: 'toolCall', callId: 'c2', name: 'research', status: 'error', iteration: 2 },
+ {
+ kind: 'subagent',
+ id: 'sub-bbb',
+ agentId: 'researcher',
+ taskId: 'sub-bbb',
+ callId: 'c2',
+ status: 'failed',
+ requestId: 'req-1',
+ items: [],
+ },
+ ];
+
+ const rows = mapDisplayItems(newestFirst(chronological)).timelines['req-1'];
+
+ // Each run follows its spawning call, and two runs of one agent no longer
+ // share `subagent:researcher` as their id.
+ expect(rows.map(row => row.id)).toEqual(['c1', 'subagent:sub-aaa', 'c2', 'subagent:sub-bbb']);
+ const [, first, , second] = rows;
+ expect(first.name).toBe('subagent:researcher');
+ expect(first.status).toBe('success');
+ expect(first.subagent).toEqual(
+ expect.objectContaining({ taskId: 'sub-aaa', agentId: 'researcher', status: 'completed' })
+ );
+ expect(second.status).toBe('error');
+ expect(second.subagent?.status).toBe('failed');
+ });
++
+ describe('sub-agent placement (live parity)', () => {
+ /**
+ * Live, `subagentSpawned` turns the `spawn_subagent` row into the
+ * delegation card IN ITS SLOT. The projection nests sub-agents after every
+ * root item, so a reopened turn used to show the spawn call as a plain
+ * tool card and the delegation card at the bottom — a different turn from
+ * the one the user watched stream.
+ */
+ it('puts the sub-agent in the slot of the call that spawned it', () => {
+ const { timelines, transcripts } = mapDisplayItems(
+ newestFirst([
+ { kind: 'turnBoundary', requestId: 'req-1' },
+ { kind: 'toolCall', callId: 'call-a', name: 'shell', status: 'success' },
+ {
+ kind: 'toolCall',
+ callId: 'call-spawn',
+ name: 'spawn_subagent',
+ args: { prompt: 'dig in' },
+ status: 'success',
+ },
+ { kind: 'toolCall', callId: 'call-b', name: 'shell', status: 'success' },
+ { kind: 'subagent', id: 'researcher', requestId: 'req-1', items: [] },
+ ])
+ );
+ const rows = timelines['req-1'] ?? [];
+ expect(rows.map(row => row.id)).toEqual(['call-a', 'subagent:researcher', 'call-b']);
+ expect(rows[1]?.seq).toBeLessThan(rows[2]?.seq ?? -1);
+ expect(rows[1]?.sourceToolName).toBe('spawn_subagent');
+ // The transcript pointer follows the row, so the card renders in place.
+ const pointers = (transcripts['req-1'] ?? []).flatMap(item =>
+ item.kind === 'toolCall' ? [item.callId] : []
+ );
+ expect(pointers).toEqual(['call-a', 'subagent:researcher', 'call-b']);
+ });
+
+ it('pairs several sub-agents with their spawn calls in order', () => {
+ const { timelines } = mapDisplayItems(
+ newestFirst([
+ { kind: 'turnBoundary', requestId: 'req-1' },
+ { kind: 'toolCall', callId: 's1', name: 'spawn_subagent', status: 'success' },
+ { kind: 'toolCall', callId: 's2', name: 'delegate_coder', status: 'success' },
+ { kind: 'subagent', id: 'researcher', requestId: 'req-1', items: [] },
+ { kind: 'subagent', id: 'researcher', requestId: 'req-1', items: [] },
+ ])
+ );
+ expect((timelines['req-1'] ?? []).map(row => row.id)).toEqual([
+ 'subagent:researcher',
+ 'subagent:researcher#2',
+ ]);
+ });
+
+ it('appends a sub-agent with no spawn call to pair with, as before', () => {
+ const { timelines } = mapDisplayItems(
+ newestFirst([
+ { kind: 'turnBoundary', requestId: 'req-1' },
+ { kind: 'toolCall', callId: 'call-a', name: 'shell', status: 'success' },
+ { kind: 'subagent', id: 'coder', requestId: 'req-1', items: [] },
+ ])
+ );
+ expect((timelines['req-1'] ?? []).map(row => row.id)).toEqual(['call-a', 'subagent:coder']);
+ });
++
++ it('folds a delegation the core names by callId into that call’s slot', () => {
++ const { timelines } = mapDisplayItems(
++ newestFirst([
++ { kind: 'turnBoundary', requestId: 'req-1' },
++ { kind: 'toolCall', callId: 'call-spawn', name: 'spawn_subagent', status: 'success' },
++ {
++ kind: 'subagent',
++ id: 'sub-1',
++ agentId: 'researcher',
++ callId: 'call-spawn',
++ status: 'completed',
++ requestId: 'req-1',
++ items: [],
++ },
++ { kind: 'toolCall', callId: 'call-b', name: 'shell', status: 'success' },
++ ])
++ );
++ expect((timelines['req-1'] ?? []).map(row => row.id)).toEqual(['subagent:sub-1', 'call-b']);
++ });
+ });
});
diff --cc app/src/features/conversations/derived/mapDisplayItems.ts
index efea80d1d0,5290eed84e..c658c4c594
--- a/app/src/features/conversations/derived/mapDisplayItems.ts
+++ b/app/src/features/conversations/derived/mapDisplayItems.ts
@@@ -297,15 -344,18 +344,22 @@@ export function mapDisplayItems
break;
}
const turn = ensureTurn(turns, anchorRequestId);
- const activity = buildSubagentActivity(item.id, item.items);
- placeSubagentRow(turn, {
- id: uniqueSubagentRowId(turn, item.id),
- name: `subagent:${item.id}`,
- round: turn.round,
- seq: 0,
- status: 'success',
- subagent: activity,
- });
+ const activity = buildSubagentActivity(item);
+ const agentId = activity.agentId;
- turn.entries.push({
- // `item.id` is unique per run (task id), so two runs of one agent
- // in a turn no longer collide on `subagent:<agent>`.
- id: `subagent:${item.id}`,
- name: `subagent:${agentId}`,
- round: turn.round,
- seq: turn.seq++,
- status: subagentEntryStatus(item.status),
- subagent: activity,
- });
++ placeSubagentRow(
++ turn,
++ {
++ // `item.id` is unique per run (task id) on a current core; an older
++ // core sends the agent name, so it is still disambiguated per turn.
++ id: uniqueSubagentRowId(turn, item.id),
++ name: `subagent:${agentId}`,
++ round: turn.round,
++ seq: 0,
++ status: subagentEntryStatus(item.status),
++ subagent: activity,
++ },
++ item.callId
++ );
break;
}
@@@ -345,58 -395,6 +399,71 @@@
return { timelines, transcripts, interrupted };
}
+/** Tool names that open a delegation — mirrors `findPendingDelegationContext`. */
+function isDelegationToolName(name: string): boolean {
+ return (
+ name === 'spawn_subagent' || name === 'spawn_async_subagent' || name.startsWith('delegate_')
+ );
+}
+
+/** `subagent:<id>`, disambiguated when one turn delegates to the same agent twice. */
+function uniqueSubagentRowId(turn: TurnAccumulator, agentId: string): string {
+ const base = `subagent:${agentId}`;
+ let id = base;
+ for (let n = 2; turn.callIds.has(id); n += 1) id = `${base}#${n}`;
+ turn.callIds.add(id);
+ return id;
+}
+
+/**
+ * Put a sub-agent row where the live stream puts it: in the slot of the call
+ * that spawned it.
+ *
+ * The projection nests sub-agents as sibling items after every root item (the
+ * transcript records no link from a delegation call to the child's file), so
+ * appending them gave every reopened turn a different shape from the one the
+ * user watched stream: the spawn call rendered as a plain tool card and the
+ * delegation card sat at the bottom of the turn. Children are ordered by spawn
+ * time, and so are the turn's delegation calls, so the Nth child takes the Nth
+ * not-yet-claimed delegation row — its `seq` and its transcript pointer —
+ * exactly as `subagentSpawned` does live. With no such row (an older
+ * transcript, or a spawn outside this turn's page) it is appended as before.
+ */
- function placeSubagentRow(turn: TurnAccumulator, row: ToolTimelineEntry): void {
- const spawnIdx = turn.entries.findIndex(
- entry => entry.subagent === undefined && isDelegationToolName(entry.name)
- );
- if (spawnIdx < 0) {
++function placeSubagentRow(
++ turn: TurnAccumulator,
++ row: ToolTimelineEntry,
++ spawnCallId: string | undefined
++): void {
++ // A current core names the spawning call and has already placed the child
++ // right after it in the stream. An older core names none and appends every
++ // child after all root items, so the Nth child pairs with the Nth unclaimed
++ // delegation row.
++ const spawnIdx = spawnCallId
++ ? turn.entries.findIndex(entry => entry.subagent === undefined && entry.id === spawnCallId)
++ : turn.entries.findIndex(
++ entry => entry.subagent === undefined && isDelegationToolName(entry.name)
++ );
++ const spawn = spawnIdx >= 0 ? turn.entries[spawnIdx] : undefined;
++ // Only a delegation-shaped call is folded into its card, exactly the calls
++ // `findPendingDelegationContext` folds live; any other spawning call (an
++ // agent exposed as a tool) stays a card of its own with the child after it.
++ if (!spawn || !isDelegationToolName(spawn.name)) {
+ turn.entries.push({ ...row, seq: turn.seq++ });
+ return;
+ }
- const spawn = turn.entries[spawnIdx];
+ turn.entries[spawnIdx] = {
+ ...row,
+ seq: spawn.seq,
+ detail: spawn.detail,
+ sourceToolName: spawn.name,
+ subagent: row.subagent ? { ...row.subagent, prompt: spawn.detail } : row.subagent,
+ };
+ const pointer = turn.transcript.find(
+ item => item.kind === 'toolCall' && item.callId === spawn.id
+ );
+ if (pointer && pointer.kind === 'toolCall') pointer.callId = row.id;
+}
+
/**
* A row id that is unique within the turn.
*
diff --cc app/src/providers/ChatRuntimeProvider.tsx
index 0a5cf0ff8f,dbde30ee9b..322a2206ba
--- a/app/src/providers/ChatRuntimeProvider.tsx
+++ b/app/src/providers/ChatRuntimeProvider.tsx
@@@ -595,727 -640,734 +649,804 @@@ const ChatRuntimeProvider = ({ childre
await flushQueuedFollowups(event.thread_id);
dispatch(endInferenceTurn({ threadId: event.thread_id }));
dispatch(clearThreadInferenceActive(event.thread_id));
+ // Snapshot polling can outlive this completed turn. Capture the rows it
+ // owns before awaiting it so a newer turn on the same thread is never
+ // cancelled by this recovery path.
- const unresolvedRowIds = (store.getState().chatRuntime.toolTimelineByThread[event.thread_id] ?? [])
++ const unresolvedRowIds = (
++ store.getState().chatRuntime.toolTimelineByThread[event.thread_id] ?? []
++ )
+ .filter(entry => entry.status === 'running' && entry.subagent?.mode !== 'async')
+ .map(entry => entry.id);
// Socket reducers keep only the current iteration's prose in the live
// buffer. Once the turn settles, replace that partial projection with
// the core's completed snapshot, whose ordered transcript contains every
// parent and sub-agent event from the whole turn. Doing this here (after
// ending the live lifecycle) matters: `hydrateRuntimeFromSnapshot`
// intentionally refuses to overwrite an actively streaming turn.
- await dispatch(fetchAndHydrateCompletedTurnState(event.thread_id));
+ const completedSnapshot = await dispatch(
+ fetchAndHydrateCompletedTurnState(event.thread_id)
+ ).unwrap();
+ if (!completedSnapshot) {
- dispatch(cancelUnresolvedTurnTimeline({ threadId: event.thread_id, rowIds: unresolvedRowIds }));
++ dispatch(
++ cancelUnresolvedTurnTimeline({ threadId: event.thread_id, rowIds: unresolvedRowIds })
++ );
+ }
};
rtLog('subscribe_chat_events', { socket: socketStatus });
- const cleanup = subscribeChatEvents({
- onInferenceStart: (event: ChatInferenceStartEvent) => {
- rtLog('inference_start', { thread: event.thread_id, request: event.request_id });
- // Fresh turn: drop the previous turn's live processing transcript so a
- // new turn's narration/steps don't append onto the old one.
- dispatch(clearProcessingForThread({ threadId: event.thread_id }));
- dispatch(markInferenceTurnStreaming({ threadId: event.thread_id }));
- dispatch(
- setInferenceStatusForThread({
- threadId: event.thread_id,
- status: { phase: 'thinking', iteration: 0, maxIterations: 0 },
- })
- );
- },
- onInferenceHeartbeat: (event: ChatInferenceHeartbeatEvent) => {
- // #4270: liveness beat — bump the per-thread counter so the
- // Conversations silence timer rearms even when the turn is in a long
- // prefill / buffered-reasoning phase that emits no other progress.
- rtLog('inference_heartbeat', { thread: event.thread_id, request: event.request_id });
- // A parallel (forked) turn streams into its own lane and must NOT keep
- // the thread's primary silence timer alive — otherwise a sibling branch
- // would mask a stalled primary turn. Mirror the text/thinking-delta
- // routing: ignore heartbeats owned by a parallel request.
- if (store.getState().chatRuntime.parallelRequestThreads[event.request_id] !== undefined) {
- return;
- }
- dispatch(bumpInferenceHeartbeatForThread({ threadId: event.thread_id }));
- },
- onIterationStart: (event: ChatIterationStartEvent) => {
- const prev = inferenceStatusRef.current[event.thread_id];
- rtLog('iteration_start', {
- thread: event.thread_id,
- request: event.request_id,
- iteration: event.round,
- });
- dispatch(
- setInferenceStatusForThread({
- threadId: event.thread_id,
- status: {
- phase: 'thinking',
- iteration: event.round,
- maxIterations: prev?.maxIterations ?? 0,
- },
- })
- );
- },
- onToolCall: (event: ChatToolCallEvent) => {
- const prev = store.getState().chatRuntime.inferenceStatusByThread[event.thread_id];
- dispatch(
- setInferenceStatusForThread({
- threadId: event.thread_id,
- status: {
- ...(prev ?? { iteration: event.round, maxIterations: 0 }),
- phase: 'tool_use',
- activeTool: event.tool_name,
- },
- })
- );
+ // Deltas are coalesced per frame; every other event flushes them first so
+ // ordering holds. See `chatDeltaCoalescer`.
- const coalesced = withCoalescedDeltas<ChatTextDeltaEvent, ChatEventListeners>({
- onInferenceStart: (event: ChatInferenceStartEvent) => {
- rtLog('inference_start', { thread: event.thread_id, request: event.request_id });
- // Fresh turn: drop the previous turn's live processing transcript so a
- // new turn's narration/steps don't append onto the old one.
- dispatch(clearProcessingForThread({ threadId: event.thread_id }));
- dispatch(markInferenceTurnStreaming({ threadId: event.thread_id }));
- if (event.request_id) {
- dispatch(liveTurnStarted({ threadId: event.thread_id, requestId: event.request_id }));
- }
- dispatch(
- setInferenceStatusForThread({
- threadId: event.thread_id,
- status: { phase: 'thinking', iteration: 0, maxIterations: 0 },
- })
- );
- },
- onInferenceHeartbeat: (event: ChatInferenceHeartbeatEvent) => {
- // #4270: liveness beat — bump the per-thread counter so the
- // Conversations silence timer rearms even when the turn is in a long
- // prefill / buffered-reasoning phase that emits no other progress.
- rtLog('inference_heartbeat', { thread: event.thread_id, request: event.request_id });
- // A parallel (forked) turn streams into its own lane and must NOT keep
- // the thread's primary silence timer alive — otherwise a sibling branch
- // would mask a stalled primary turn. Mirror the text/thinking-delta
- // routing: ignore heartbeats owned by a parallel request.
- if (store.getState().chatRuntime.parallelRequestThreads[event.request_id] !== undefined) {
- return;
- }
- dispatch(bumpInferenceHeartbeatForThread({ threadId: event.thread_id }));
- },
- onIterationStart: (event: ChatIterationStartEvent) => {
- const prev = inferenceStatusRef.current[event.thread_id];
- rtLog('iteration_start', {
- thread: event.thread_id,
- request: event.request_id,
- iteration: event.round,
- });
- dispatch(
- setInferenceStatusForThread({
- threadId: event.thread_id,
- status: {
- phase: 'thinking',
- iteration: event.round,
- maxIterations: prev?.maxIterations ?? 0,
- },
- })
- );
- },
- onToolCall: (event: ChatToolCallEvent) => {
- const prev = store.getState().chatRuntime.inferenceStatusByThread[event.thread_id];
- dispatch(
- setInferenceStatusForThread({
- threadId: event.thread_id,
- status: {
- ...(prev ?? { iteration: event.round, maxIterations: 0 }),
- phase: 'tool_use',
- activeTool: event.tool_name,
- },
- })
- );
++ const coalesced = withCoalescedDeltas<ChatTextDeltaEvent, ChatEventListeners>(
++ {
++ onInferenceStart: (event: ChatInferenceStartEvent) => {
++ rtLog('inference_start', { thread: event.thread_id, request: event.request_id });
++ // Fresh turn: drop the previous turn's live processing transcript so a
++ // new turn's narration/steps don't append onto the old one.
++ dispatch(clearProcessingForThread({ threadId: event.thread_id }));
++ dispatch(markInferenceTurnStreaming({ threadId: event.thread_id }));
++ if (event.request_id) {
++ dispatch(liveTurnStarted({ threadId: event.thread_id, requestId: event.request_id }));
++ }
++ dispatch(
++ setInferenceStatusForThread({
++ threadId: event.thread_id,
++ status: { phase: 'thinking', iteration: 0, maxIterations: 0 },
++ })
++ );
++ },
++ onInferenceHeartbeat: (event: ChatInferenceHeartbeatEvent) => {
++ // #4270: liveness beat — bump the per-thread counter so the
++ // Conversations silence timer rearms even when the turn is in a long
++ // prefill / buffered-reasoning phase that emits no other progress.
++ rtLog('inference_heartbeat', { thread: event.thread_id, request: event.request_id });
++ // A parallel (forked) turn streams into its own lane and must NOT keep
++ // the thread's primary silence timer alive — otherwise a sibling branch
++ // would mask a stalled primary turn. Mirror the text/thinking-delta
++ // routing: ignore heartbeats owned by a parallel request.
++ if (store.getState().chatRuntime.parallelRequestThreads[event.request_id] !== undefined) {
++ return;
++ }
++ dispatch(bumpInferenceHeartbeatForThread({ threadId: event.thread_id }));
++ },
++ onIterationStart: (event: ChatIterationStartEvent) => {
++ const prev = inferenceStatusRef.current[event.thread_id];
++ rtLog('iteration_start', {
++ thread: event.thread_id,
++ request: event.request_id,
++ iteration: event.round,
++ });
++ dispatch(
++ setInferenceStatusForThread({
++ threadId: event.thread_id,
++ status: {
++ phase: 'thinking',
++ iteration: event.round,
++ maxIterations: prev?.maxIterations ?? 0,
++ },
++ })
++ );
++ },
++ onToolCall: (event: ChatToolCallEvent) => {
++ const prev = store.getState().chatRuntime.inferenceStatusByThread[event.thread_id];
++ dispatch(
++ setInferenceStatusForThread({
++ threadId: event.thread_id,
++ status: {
++ ...(prev ?? { iteration: event.round, maxIterations: 0 }),
++ phase: 'tool_use',
++ activeTool: event.tool_name,
++ },
++ })
++ );
- const eventKey = `tool_call:${event.thread_id}:${event.request_id ?? 'none'}:${event.round}:${event.tool_name}:${event.tool_call_id ?? ''}`;
- const eventKey = `tool_call:${event.thread_id}:${event.request_id ?? 'none'}:${event.round}:${event.tool_name}:${toolEventIdentity(event)}`;
-- if (
-- !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
-- )
-- return;
++ const eventKey = `tool_call:${event.thread_id}:${event.request_id ?? 'none'}:${event.round}:${event.tool_name}:${toolEventIdentity(event)}`;
++ if (
++ !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
++ )
++ return;
-- // Start (or extend) the tool-chain latency window for this turn (#4273).
-- // Key by thread+request (same scheme as segment delivery) so parallel /
-- // forked turns that share a thread_id keep independent chains (#4288).
-- skillLatencyRef.current.noteToolCall(segmentDeliveryKey(event.thread_id, event.request_id));
++ // Start (or extend) the tool-chain latency window for this turn (#4273).
++ // Key by thread+request (same scheme as segment delivery) so parallel /
++ // forked turns that share a thread_id keep independent chains (#4288).
++ skillLatencyRef.current.noteToolCall(
++ segmentDeliveryKey(event.thread_id, event.request_id)
++ );
-- // Merge + processing-pointer are now a single reducer (Phase 3) — no
-- // getState()/full-array rebuild in the provider.
-- dispatch(
-- toolCallReceived({
-- threadId: event.thread_id,
-- round: event.round,
-- toolName: event.tool_name,
-- toolCallId: event.tool_call_id,
-- displayLabel: event.tool_display_label,
-- displayDetail: event.tool_display_detail,
- args: event.args,
-- })
-- );
-- },
-- onToolResult: (event: ChatToolResultEvent) => {
- const eventKey = `tool_result:${event.thread_id}:${event.request_id ?? 'none'}:${event.round}:${event.tool_name}:${event.success}:${event.tool_call_id ?? ''}`;
- const eventKey = `tool_result:${event.thread_id}:${event.request_id ?? 'none'}:${event.round}:${event.tool_name}:${event.success}:${toolEventIdentity(event)}`;
-- if (
-- !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
-- )
-- return;
--
-- // Settle the matching row in the reducer (Phase 3) — no getState() /
-- // full-array rebuild. A no-op when no row matches.
-- dispatch(
-- toolResultReceived({
-- threadId: event.thread_id,
-- round: event.round,
-- toolName: event.tool_name,
-- toolCallId: event.tool_call_id,
-- success: event.success,
-- output: event.output,
-- failure: event.failure,
-- })
-- );
++ // Merge + processing-pointer are now a single reducer (Phase 3) — no
++ // getState()/full-array rebuild in the provider.
++ dispatch(
++ toolCallReceived({
++ threadId: event.thread_id,
++ round: event.round,
++ toolName: event.tool_name,
++ toolCallId: event.tool_call_id,
++ displayLabel: event.tool_display_label,
++ displayDetail: event.tool_display_detail,
++ args: event.args,
++ })
++ );
++ },
++ onToolResult: (event: ChatToolResultEvent) => {
++ const eventKey = `tool_result:${event.thread_id}:${event.request_id ?? 'none'}:${event.round}:${event.tool_name}:${event.success}:${toolEventIdentity(event)}`;
++ if (
++ !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
++ )
++ return;
-- // Agent-first Workflow authoring (issue B4): a completed
-- // `propose_workflow` call carries a `workflow_proposal` JSON payload
-- // in `output` — surface it as a `WorkflowProposalCard` above the
-- // composer. The tool only validates; only the card's "Save & enable"
-- // action ever calls `flows_create`, so this dispatch alone can never
-- // create a flow.
-- const mainProposal = maybeParseWorkflowProposalTool(
-- event.tool_name,
-- event.success,
-- event.output
-- );
-- if (mainProposal) {
-- rtLog('workflow proposal parsed (main agent)', {
-- thread: event.thread_id,
-- tool: event.tool_name,
-- name: mainProposal.name,
-- });
++ // Settle the matching row in the reducer (Phase 3) — no getState() /
++ // full-array rebuild. A no-op when no row matches.
dispatch(
-- setWorkflowProposalForThread({ threadId: event.thread_id, proposal: mainProposal })
++ toolResultReceived({
++ threadId: event.thread_id,
++ round: event.round,
++ toolName: event.tool_name,
++ toolCallId: event.tool_call_id,
++ success: event.success,
++ output: event.output,
++ failure: event.failure,
++ })
);
-- }
-- const current = store.getState().chatRuntime.inferenceStatusByThread[event.thread_id];
-- if (!current) return;
-- dispatch(
-- setInferenceStatusForThread({
-- threadId: event.thread_id,
-- status: { ...current, phase: 'thinking', activeTool: undefined },
-- })
-- );
-- },
-- onSubagentSpawned: event => {
-- // Event-seen guard, matching `onToolCall`/`onToolResult`. This socket
-- // reconnects and redelivers freely (13+ times in one measured
-- // session), and a replayed `subagent_spawned` that lands AFTER
-- // `subagent_awaiting_user` looks exactly like `continue_subagent`
-- // resuming the child — the reducer would clear the pause and the
-- // question would vanish while the child was still blocked. `seq` is
-- // the core's own answer to this: `(request_id, seq)` is stamped per
-- // emission (`publish_seq_stamped`), so a redelivery repeats the pair
-- // and a real resume never does. The reducer keeps its own durable
-- // check for the case this bounded cache has already evicted.
-- const eventKey = `subagent_spawned:${event.thread_id}:${event.request_id ?? 'none'}:${event.seq ?? `${event.round}:${event.skill_id}:${event.tool_name}`}`;
-- if (
-- !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
-- ) {
-- return;
-- }
-- const prev = store.getState().chatRuntime.inferenceStatusByThread[event.thread_id];
-- dispatch(
-- setInferenceStatusForThread({
-- threadId: event.thread_id,
-- status: {
-- ...(prev ?? { iteration: event.round, maxIterations: 0 }),
-- phase: 'subagent',
-- activeSubagent: event.tool_name,
-- },
-- })
-- );
++ // Agent-first Workflow authoring (issue B4): a completed
++ // `propose_workflow` call carries a `workflow_proposal` JSON payload
++ // in `output` — surface it as a `WorkflowProposalCard` above the
++ // composer. The tool only validates; only the card's "Save & enable"
++ // action ever calls `flows_create`, so this dispatch alone can never
++ // create a flow.
++ const mainProposal = maybeParseWorkflowProposalTool(
++ event.tool_name,
++ event.success,
++ event.output
++ );
++ if (mainProposal) {
++ rtLog('workflow proposal parsed (main agent)', {
++ thread: event.thread_id,
++ tool: event.tool_name,
++ name: mainProposal.name,
++ });
++ dispatch(
++ setWorkflowProposalForThread({ threadId: event.thread_id, proposal: mainProposal })
++ );
++ }
-- // Collapse the parent spawn/delegate row into the subagent row (one
-- // entry per delegation) — merge now lives in the reducer (Phase 3).
-- dispatch(
-- subagentSpawned({
-- threadId: event.thread_id,
-- round: event.round,
-- rowId: `${event.thread_id}:subagent:${event.skill_id}:${event.tool_name}`,
-- taskId: event.skill_id,
-- agentId: event.tool_name,
-- displayName: event.subagent?.display_name,
-- workerThreadId: event.subagent?.worker_thread_id,
-- mode: event.subagent?.mode,
-- dedicatedThread: event.subagent?.dedicated_thread,
-- // Identity of THIS emission, carried into the reducer so it can
-- // tell a resume from a replay without depending on the cache above.
-- spawnEventId: `${event.request_id ?? 'none'}:${event.seq ?? 'noseq'}`,
-- })
-- );
-- },
-- onSubagentAwaitingUser: (event: ChatSubagentDoneEvent) => {
-- // Same guard, mirrored: a replayed `subagent_awaiting_user` arriving
-- // after the child has resumed would re-park a running row.
-- const eventKey = `subagent_awaiting_user:${event.thread_id}:${event.request_id ?? 'none'}:${event.seq ?? `${event.round}:${event.skill_id}:${event.tool_name}`}`;
-- if (
-- !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
-- ) {
-- return;
-- }
-- dispatch(
-- subagentAwaitingUser({
-- threadId: event.thread_id,
-- rowId: `${event.thread_id}:subagent:${event.skill_id}:${event.tool_name}`,
-- // The core puts the child's `ask_user_clarification` question in
-- // `message` (progress_bridge.rs:1055). It is the only copy of the
-- // question the frontend ever receives.
-- question: event.message,
-- })
-- );
-- },
-- onSubagentDone: (event: ChatSubagentDoneEvent) => {
-- // Worktree isolation metadata (#3376) — present only for workers that ran
-- // with `isolation = "worktree"`; drives the inline worktree row's
-- // open/diff/remove affordances. Undefined fields leave the row untouched.
-- dispatch(
-- subagentDone({
-- threadId: event.thread_id,
-- rowId: `${event.thread_id}:subagent:${event.skill_id}:${event.tool_name}`,
-- success: event.success,
-- iterations: event.subagent?.iterations,
-- elapsedMs: event.subagent?.elapsed_ms,
-- outputChars: event.subagent?.output_chars,
-- worktreePath: event.subagent?.worktree_path,
-- changedFiles: event.subagent?.changed_files,
-- isDirty: event.subagent?.dirty_status,
-- })
-- );
++ const current = store.getState().chatRuntime.inferenceStatusByThread[event.thread_id];
++ if (!current) return;
++ dispatch(
++ setInferenceStatusForThread({
++ threadId: event.thread_id,
++ status: { ...current, phase: 'thinking', activeTool: undefined },
++ })
++ );
++ },
++ onSubagentSpawned: event => {
++ // Event-seen guard, matching `onToolCall`/`onToolResult`. This socket
++ // reconnects and redelivers freely (13+ times in one measured
++ // session), and a replayed `subagent_spawned` that lands AFTER
++ // `subagent_awaiting_user` looks exactly like `continue_subagent`
++ // resuming the child — the reducer would clear the pause and the
++ // question would vanish while the child was still blocked. `seq` is
++ // the core's own answer to this: `(request_id, seq)` is stamped per
++ // emission (`publish_seq_stamped`), so a redelivery repeats the pair
++ // and a real resume never does. The reducer keeps its own durable
++ // check for the case this bounded cache has already evicted.
++ const eventKey = `subagent_spawned:${event.thread_id}:${event.request_id ?? 'none'}:${event.seq ?? `${event.round}:${event.skill_id}:${event.tool_name}`}`;
++ if (
++ !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
++ ) {
++ return;
++ }
++ const prev = store.getState().chatRuntime.inferenceStatusByThread[event.thread_id];
++ dispatch(
++ setInferenceStatusForThread({
++ threadId: event.thread_id,
++ status: {
++ ...(prev ?? { iteration: event.round, maxIterations: 0 }),
++ phase: 'subagent',
++ activeSubagent: event.tool_name,
++ },
++ })
++ );
-- // A detached sub-agent's spend reaches the composer here or nowhere.
-- //
-- // The parent turn's `chat_done` fired before this child finished, and
-- // for a detached spawn the child's usage never entered the parent's
-- // ledger — `detached_child()` sets `parent_subagent_usage` to `None` —
-- // so `holistic_last_turn_usage` folded nothing and the reported totals
-- // are parent-only. The core populates these fields ONLY when that is
-- // the case, so adding them unconditionally is correct: for a blocking
-- // spawn they are absent, because its spend is already inside the
-- // `chat_done` figures (tokens AND cost). See #6459.
-- const childInput = event.subagent?.input_tokens;
-- const childOutput = event.subagent?.output_tokens;
-- if (childInput !== undefined || childOutput !== undefined) {
++ // Collapse the parent spawn/delegate row into the subagent row (one
++ // entry per delegation) — merge now lives in the reducer (Phase 3).
dispatch(
-- recordChatTurnUsage({
++ subagentSpawned({
threadId: event.thread_id,
-- // The child's tokens go at the TOP level because that is what
-- // `applyTurnUsage` folds into the thread totals the composer
-- // shows — mirroring `chat_done`, whose top-level figures are
-- // already parent+child. The `subAgents` entry below is the
-- // per-agent breakdown, not the total.
-- inputTokens: childInput ?? 0,
-- outputTokens: childOutput ?? 0,
-- cachedTokens: event.subagent?.cached_input_tokens ?? 0,
-- costUsd: event.subagent?.cost_usd ?? 0,
-- subAgentSpendOnly: true,
-- subAgents: [
-- {
-- agentId: event.tool_name ?? 'subagent',
-- inputTokens: childInput ?? 0,
-- outputTokens: childOutput ?? 0,
-- costUsd: event.subagent?.cost_usd ?? 0,
-- },
-- ],
++ round: event.round,
++ rowId: `${event.thread_id}:subagent:${event.skill_id}:${event.tool_name}`,
++ taskId: event.skill_id,
++ agentId: event.tool_name,
++ displayName: event.subagent?.display_name,
++ workerThreadId: event.subagent?.worker_thread_id,
++ mode: event.subagent?.mode,
++ dedicatedThread: event.subagent?.dedicated_thread,
++ // Identity of THIS emission, carried into the reducer so it can
++ // tell a resume from a replay without depending on the cache above.
++ spawnEventId: `${event.request_id ?? 'none'}:${event.seq ?? 'noseq'}`,
++ })
++ );
++ },
++ onSubagentAwaitingUser: (event: ChatSubagentDoneEvent) => {
++ // Same guard, mirrored: a replayed `subagent_awaiting_user` arriving
++ // after the child has resumed would re-park a running row.
++ const eventKey = `subagent_awaiting_user:${event.thread_id}:${event.request_id ?? 'none'}:${event.seq ?? `${event.round}:${event.skill_id}:${event.tool_name}`}`;
++ if (
++ !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
++ ) {
++ return;
++ }
++ dispatch(
++ subagentAwaitingUser({
++ threadId: event.thread_id,
++ rowId: `${event.thread_id}:subagent:${event.skill_id}:${event.tool_name}`,
++ // The core puts the child's `ask_user_clarification` question in
++ // `message` (progress_bridge.rs:1055). It is the only copy of the
++ // question the frontend ever receives.
++ question: event.message,
++ })
++ );
++ },
++ onSubagentDone: (event: ChatSubagentDoneEvent) => {
++ // Worktree isolation metadata (#3376) — present only for workers that ran
++ // with `isolation = "worktree"`; drives the inline worktree row's
++ // open/diff/remove affordances. Undefined fields leave the row untouched.
++ dispatch(
++ subagentDone({
++ threadId: event.thread_id,
++ rowId: `${event.thread_id}:subagent:${event.skill_id}:${event.tool_name}`,
++ success: event.success,
++ iterations: event.subagent?.iterations,
++ elapsedMs: event.subagent?.elapsed_ms,
++ outputChars: event.subagent?.output_chars,
++ worktreePath: event.subagent?.worktree_path,
++ changedFiles: event.subagent?.changed_files,
++ isDirty: event.subagent?.dirty_status,
})
);
-- }
-- const current = store.getState().chatRuntime.inferenceStatusByThread[event.thread_id];
-- if (!current) return;
-- dispatch(
-- setInferenceStatusForThread({
-- threadId: event.thread_id,
-- status: { ...current, phase: 'thinking', activeSubagent: undefined },
-- })
-- );
-- },
-- onSubagentIterationStart: event => {
-- const taskId = event.subagent?.task_id ?? event.skill_id;
-- const agentId = event.subagent?.agent_id ?? event.tool_name;
-- dispatch(
-- subagentIterationStarted({
-- threadId: event.thread_id,
-- rowId: `${event.thread_id}:subagent:${taskId}:${agentId}`,
-- childIteration: event.subagent?.child_iteration,
-- childMaxIterations: event.subagent?.child_max_iterations,
-- })
-- );
-- },
-- onSubagentToolCall: event => {
-- const taskId = event.subagent?.task_id ?? event.skill_id;
-- const agentId = event.subagent?.agent_id;
-- if (!agentId) return;
-- const rowId = `${event.thread_id}:subagent:${taskId}:${agentId}`;
-- // Reducer owns the toolCalls upsert (dedup on call_id) — no getState().
-- dispatch(
-- subagentToolCallReceived({
-- threadId: event.thread_id,
-- rowId,
-- callId: event.tool_call_id,
-- toolName: event.tool_name,
-- iteration: event.subagent?.child_iteration,
-- args: event.args,
-- displayName: event.tool_display_label,
-- detail: event.tool_display_detail,
-- })
-- );
-- // Mirror the call into the ordered transcript so the drawer renders it
-- // right after the text that triggered it (self-guarded / self-deduped).
-- dispatch(
-- recordSubagentTranscriptTool({
-- threadId: event.thread_id,
-- rowId,
-- callId: event.tool_call_id,
-- toolName: event.tool_name,
-- iteration: event.subagent?.child_iteration,
-- args: event.args,
-- displayName: event.tool_display_label,
-- detail: event.tool_display_detail,
-- })
-- );
-- },
-- onSubagentToolResult: event => {
-- // Phase 5c: the Flows prompt bar / canvas copilot route to the
-- // `workflow_builder` specialist via delegation (`build_workflow`), so a
-- // `propose_workflow`/`revise_workflow` proposal is produced INSIDE the
-- // delegated worker and arrives here (not on `onToolResult`). This
-- // extraction must run BEFORE the timeline-entry guards below: under
-- // the workflow_builder subagent's heavy event volume, the progress
-- // channel (bounded, `try_send`) can drop earlier events, so the
-- // timeline row for this call may never have been created — gating
-- // proposal extraction on finding that row silently drops the
-- // proposal and the Accept/Reject card never renders (bug). The
-- // extraction only needs `tool_name`/`success`/`output`, all present
-- // directly on the event, with no timeline dependency. Surface it on
-- // the PARENT thread (`event.thread_id`, which the progress bridge
-- // always stamps with the parent request's thread, not the child's)
-- // so the same `WorkflowProposalCard` the direct-tool path uses
-- // renders it. Still validate-only — the card's explicit Save is the
-- // sole persistence gate.
-- const subagentProposal = maybeParseWorkflowProposalTool(
-- event.tool_name,
-- event.success,
-- event.output
-- );
-- if (subagentProposal) {
-- rtLog('workflow proposal parsed (delegated worker)', {
-- thread: event.thread_id,
-- tool: event.tool_name,
-- name: subagentProposal.name,
-- });
++ // A detached sub-agent's spend reaches the composer here or nowhere.
++ //
++ // The parent turn's `chat_done` fired before this child finished, and
++ // for a detached spawn the child's usage never entered the parent's
++ // ledger — `detached_child()` sets `parent_subagent_usage` to `None` —
++ // so `holistic_last_turn_usage` folded nothing and the reported totals
++ // are parent-only. The core populates these fields ONLY when that is
++ // the case, so adding them unconditionally is correct: for a blocking
++ // spawn they are absent, because its spend is already inside the
++ // `chat_done` figures (tokens AND cost). See #6459.
++ const childInput = event.subagent?.input_tokens;
++ const childOutput = event.subagent?.output_tokens;
++ if (childInput !== undefined || childOutput !== undefined) {
++ dispatch(
++ recordChatTurnUsage({
++ threadId: event.thread_id,
++ // The child's tokens go at the TOP level because that is what
++ // `applyTurnUsage` folds into the thread totals the composer
++ // shows — mirroring `chat_done`, whose top-level figures are
++ // already parent+child. The `subAgents` entry below is the
++ // per-agent breakdown, not the total.
++ inputTokens: childInput ?? 0,
++ outputTokens: childOutput ?? 0,
++ cachedTokens: event.subagent?.cached_input_tokens ?? 0,
++ costUsd: event.subagent?.cost_usd ?? 0,
++ subAgentSpendOnly: true,
++ subAgents: [
++ {
++ agentId: event.tool_name ?? 'subagent',
++ inputTokens: childInput ?? 0,
++ outputTokens: childOutput ?? 0,
++ costUsd: event.subagent?.cost_usd ?? 0,
++ },
++ ],
++ })
++ );
++ }
++
++ const current = store.getState().chatRuntime.inferenceStatusByThread[event.thread_id];
++ if (!current) return;
+ dispatch(
- setWorkflowProposalForThread({ threadId: event.thread_id, proposal: subagentProposal })
++ setInferenceStatusForThread({
++ threadId: event.thread_id,
++ status: { ...current, phase: 'thinking', activeSubagent: undefined },
++ })
+ );
- }
++ },
++ onSubagentIterationStart: event => {
++ const taskId = event.subagent?.task_id ?? event.skill_id;
++ const agentId = event.subagent?.agent_id ?? event.tool_name;
+ dispatch(
- setWorkflowProposalForThread({ threadId: event.thread_id, proposal: subagentProposal })
++ subagentIterationStarted({
++ threadId: event.thread_id,
++ rowId: `${event.thread_id}:subagent:${taskId}:${agentId}`,
++ childIteration: event.subagent?.child_iteration,
++ childMaxIterations: event.subagent?.child_max_iterations,
++ })
+ );
- }
++ },
++ onSubagentToolCall: event => {
++ const taskId = event.subagent?.task_id ?? event.skill_id;
++ const agentId = event.subagent?.agent_id;
++ if (!agentId) return;
++ const rowId = `${event.thread_id}:subagent:${taskId}:${agentId}`;
++ // Reducer owns the toolCalls upsert (dedup on call_id) — no getState().
++ dispatch(
++ subagentToolCallReceived({
++ threadId: event.thread_id,
++ rowId,
++ callId: event.tool_call_id,
++ toolName: event.tool_name,
++ iteration: event.subagent?.child_iteration,
++ args: event.args,
++ displayName: event.tool_display_label,
++ detail: event.tool_display_detail,
++ })
++ );
++ // Mirror the call into the ordered transcript so the drawer renders it
++ // right after the text that triggered it (self-guarded / self-deduped).
++ dispatch(
++ recordSubagentTranscriptTool({
++ threadId: event.thread_id,
++ rowId,
++ callId: event.tool_call_id,
++ toolName: event.tool_name,
++ iteration: event.subagent?.child_iteration,
++ args: event.args,
++ displayName: event.tool_display_label,
++ detail: event.tool_display_detail,
++ })
++ );
++ },
++ onSubagentToolResult: event => {
++ // Phase 5c: the Flows prompt bar / canvas copilot route to the
++ // `workflow_builder` specialist via delegation (`build_workflow`), so a
++ // `propose_workflow`/`revise_workflow` proposal is produced INSIDE the
++ // delegated worker and arrives here (not on `onToolResult`). This
++ // extraction must run BEFORE the timeline-entry guards below: under
++ // the workflow_builder subagent's heavy event volume, the progress
++ // channel (bounded, `try_send`) can drop earlier events, so the
++ // timeline row for this call may never have been created — gating
++ // proposal extraction on finding that row silently drops the
++ // proposal and the Accept/Reject card never renders (bug). The
++ // extraction only needs `tool_name`/`success`/`output`, all present
++ // directly on the event, with no timeline dependency. Surface it on
++ // the PARENT thread (`event.thread_id`, which the progress bridge
++ // always stamps with the parent request's thread, not the child's)
++ // so the same `WorkflowProposalCard` the direct-tool path uses
++ // renders it. Still validate-only — the card's explicit Save is the
++ // sole persistence gate.
++ const subagentProposal = maybeParseWorkflowProposalTool(
++ event.tool_name,
++ event.success,
++ event.output
++ );
++ if (subagentProposal) {
++ rtLog('workflow proposal parsed (delegated worker)', {
++ thread: event.thread_id,
++ tool: event.tool_name,
++ name: subagentProposal.name,
++ });
++ dispatch(
++ setWorkflowProposalForThread({
++ threadId: event.thread_id,
++ proposal: subagentProposal,
++ })
++ );
++ }
-- const taskId = event.subagent?.task_id ?? event.skill_id;
-- const agentId = event.subagent?.agent_id;
-- if (!agentId) return;
-- const rowId = `${event.thread_id}:subagent:${taskId}:${agentId}`;
-- // Reducer owns the nested toolCall settle (no-op if the call is absent).
-- dispatch(
-- subagentToolResultReceived({
-- threadId: event.thread_id,
-- rowId,
-- callId: event.tool_call_id,
-- success: event.success,
-- elapsedMs: event.subagent?.elapsed_ms,
-- outputChars: event.subagent?.output_chars,
-- result: event.output,
-- failure: event.failure,
-- })
-- );
-- dispatch(
-- resolveSubagentTranscriptTool({
-- threadId: event.thread_id,
-- rowId,
-- callId: event.tool_call_id,
-- success: event.success,
-- elapsedMs: event.subagent?.elapsed_ms,
-- outputChars: event.subagent?.output_chars,
-- result: event.output,
-- failure: event.success ? undefined : parseToolFailure(event.failure),
-- })
-- );
-- },
-- onSubagentTextDelta: (event: ChatSubagentTextDeltaEvent) => {
-- const taskId = event.subagent?.task_id;
-- const agentId = event.subagent?.agent_id;
-- if (!taskId || !agentId || !event.delta) return;
-- dispatch(
-- appendSubagentStreamDelta({
-- threadId: event.thread_id,
-- rowId: `${event.thread_id}:subagent:${taskId}:${agentId}`,
-- kind: 'text',
-- delta: event.delta,
-- iteration: event.subagent?.child_iteration,
-- })
-- );
-- },
-- onSubagentThinkingDelta: (event: ChatSubagentThinkingDeltaEvent) => {
-- const taskId = event.subagent?.task_id;
-- const agentId = event.subagent?.agent_id;
-- if (!taskId || !agentId || !event.delta) return;
-- dispatch(
-- appendSubagentStreamDelta({
-- threadId: event.thread_id,
-- rowId: `${event.thread_id}:subagent:${taskId}:${agentId}`,
-- kind: 'thinking',
-- delta: event.delta,
-- iteration: event.subagent?.child_iteration,
-- })
-- );
-- },
-- onSegment: (event: ChatSegmentEvent) => {
-- const eventKey = `segment:${event.thread_id}:${event.request_id}:${event.segment_index}`;
-- if (
-- !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
-- )
-- return;
-- const content = segmentText(event);
-- const deliveryKey = segmentDeliveryKey(event.thread_id, event.request_id);
-- const delivery = getOrCreateSegmentDelivery(segmentDeliveriesRef.current, deliveryKey);
-- delivery.segments.set(event.segment_index, content);
-- void dispatch(
-- addInferenceResponse({
-- content,
-- threadId: event.thread_id,
-- // Stamp the producing turn's request id so the timeline projection
-- // can group this answer with its per-turn process trail (Phase 4
-- // anchoring, Option B — see the companion plan). `citations` is
-- // merged in when present.
-- extraMetadata: {
-- ...(event.citations?.length ? { citations: event.citations } : {}),
-- ...(event.request_id ? { requestId: event.request_id } : {}),
-- },
-- })
-- );
-- },
-- onInterim: (event: ChatInterimEvent) => {
-- // One interim per round — `round` is a stable per-turn dedup key that
-- // survives socket reconnect/replay (a re-delivered frame must not
-- // append the narration bubble twice).
-- const eventKey = `interim:${event.thread_id}:${event.request_id}:${event.round}`;
-- if (
-- !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
-- )
-- return;
-- const content = event.full_response?.trim() ?? '';
-- if (!content) return;
-- // Narration is NOT promoted to a chat message any more.
-- //
-- // It used to be persisted here via `addInferenceResponse({ isInterim })`,
-- // which gave it a lifetime no other progress signal has: thinking is
-- // wiped at `chat_done`, tool rows collapse, but narration bubbles
-- // ("Let me get the data for both.", "The HTML is hard to parse…")
-- // stayed in the thread forever, wedged between the question and the
-- // answer they were superseded by.
-- //
-- // It is already captured twice over without this: `streamDeltaReceived`
-- // coalesces every `content` delta into `processingByThread` as a
-- // `narration` transcript item (chatRuntimeSlice), and the core persists
-- // the same thing server-side as `TranscriptItem::Narration`, kept after
-- // completion so a reload replays it. The inline rail and the Agent
-- // Process Source panel both render that transcript — so narration is
-- // still fully visible while the turn runs, and still inspectable after,
-- // just not as a permanent chat bubble.
-- //
-- // The event is still consumed (not dropped upstream) for its dedup key
-- // and the preview reset below, both of which are round-scoped.
-- rtLog('interim_narration_observed', {
-- thread: event.thread_id,
-- request: event.request_id,
-- round: event.round,
-- });
-- // Drop the round's narration from the live streaming preview, which
-- // accumulates across the whole turn under one request_id. This matters
-- // MORE now: without it the same text renders both in the rail (as a
-- // transcript item) and in the preview tail. Reset synchronously so the
-- // next round's deltas start from an empty buffer.
-- const cr = store.getState().chatRuntime;
-- const existing = cr.streamingAssistantByThread[event.thread_id];
-- if (existing && existing.requestId === event.request_id) {
++ const taskId = event.subagent?.task_id ?? event.skill_id;
++ const agentId = event.subagent?.agent_id;
++ if (!agentId) return;
++ const rowId = `${event.thread_id}:subagent:${taskId}:${agentId}`;
++ // Reducer owns the nested toolCall settle (no-op if the call is absent).
++ dispatch(
++ subagentToolResultReceived({
++ threadId: event.thread_id,
++ rowId,
++ callId: event.tool_call_id,
++ success: event.success,
++ elapsedMs: event.subagent?.elapsed_ms,
++ outputChars: event.subagent?.output_chars,
++ result: event.output,
++ failure: event.failure,
++ })
++ );
++ dispatch(
++ resolveSubagentTranscriptTool({
++ threadId: event.thread_id,
++ rowId,
++ callId: event.tool_call_id,
++ success: event.success,
++ elapsedMs: event.subagent?.elapsed_ms,
++ outputChars: event.subagent?.output_chars,
++ result: event.output,
++ failure: event.success ? undefined : parseToolFailure(event.failure),
++ })
++ );
++ },
++ onSubagentTextDelta: (event: ChatSubagentTextDeltaEvent) => {
++ const taskId = event.subagent?.task_id;
++ const agentId = event.subagent?.agent_id;
++ if (!taskId || !agentId || !event.delta) return;
+ dispatch(
- setStreamingAssistantForThread({
++ appendSubagentStreamDelta({
++ threadId: event.thread_id,
++ rowId: `${event.thread_id}:subagent:${taskId}:${agentId}`,
++ kind: 'text',
++ delta: event.delta,
++ iteration: event.subagent?.child_iteration,
++ })
++ );
++ },
++ onSubagentThinkingDelta: (event: ChatSubagentThinkingDeltaEvent) => {
++ const taskId = event.subagent?.task_id;
++ const agentId = event.subagent?.agent_id;
++ if (!taskId || !agentId || !event.delta) return;
+ dispatch(
- setStreamingAssistantForThread({
++ appendSubagentStreamDelta({
+ threadId: event.thread_id,
- streaming: {
- requestId: existing.requestId,
- content: '',
- thinking: existing.thinking,
++ rowId: `${event.thread_id}:subagent:${taskId}:${agentId}`,
++ kind: 'thinking',
++ delta: event.delta,
++ iteration: event.subagent?.child_iteration,
++ })
++ );
++ },
++ onSegment: (event: ChatSegmentEvent) => {
++ const eventKey = `segment:${event.thread_id}:${event.request_id}:${event.segment_index}`;
++ if (
++ !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
++ )
++ return;
++ const content = segmentText(event);
++ const deliveryKey = segmentDeliveryKey(event.thread_id, event.request_id);
++ const delivery = getOrCreateSegmentDelivery(segmentDeliveriesRef.current, deliveryKey);
++ delivery.segments.set(event.segment_index, content);
++ void dispatch(
++ addInferenceResponse({
++ content,
+ threadId: event.thread_id,
- streaming: {
- requestId: existing.requestId,
- content: '',
- thinking: existing.thinking,
++ // Stamp the producing turn's request id so the timeline projection
++ // can group this answer with its per-turn process trail (Phase 4
++ // anchoring, Option B — see the companion plan). `citations` is
++ // merged in when present.
++ extraMetadata: {
++ ...(event.citations?.length ? { citations: event.citations } : {}),
++ ...(event.request_id ? { requestId: event.request_id } : {}),
},
})
);
-- }
-- },
-- onTextDelta: event => {
- if (isReplayedDelta(event)) return;
-- // Parallel-vs-primary routing + processing transcript now live in the
-- // reducer (Phase 3) — no getState() in the provider.
-- dispatch(
-- streamDeltaReceived({
-- threadId: event.thread_id,
-- requestId: event.request_id,
-- round: event.round,
-- delta: event.delta,
-- channel: 'content',
-- })
-- );
-- },
-- onThinkingDelta: event => {
- if (isReplayedDelta(event)) return;
-- dispatch(
-- streamDeltaReceived({
-- threadId: event.thread_id,
-- requestId: event.request_id,
-- round: event.round,
-- delta: event.delta,
-- channel: 'thinking',
-- at: Date.now(),
-- })
-- );
-- },
-- onToolArgsDelta: event => {
-- // Match + append + decorate now live in the reducer (Phase 3).
-- dispatch(
-- toolArgsDeltaReceived({
-- threadId: event.thread_id,
++ },
++ onInterim: (event: ChatInterimEvent) => {
++ // One interim per round — `round` is a stable per-turn dedup key that
++ // survives socket reconnect/replay (a re-delivered frame must not
++ // append the narration bubble twice).
++ const eventKey = `interim:${event.thread_id}:${event.request_id}:${event.round}`;
++ if (
++ !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
++ )
++ return;
++ const content = event.full_response?.trim() ?? '';
++ if (!content) return;
++ // Narration is NOT promoted to a chat message any more.
++ //
++ // It used to be persisted here via `addInferenceResponse({ isInterim })`,
++ // which gave it a lifetime no other progress signal has: thinking is
++ // wiped at `chat_done`, tool rows collapse, but narration bubbles
++ // ("Let me get the data for both.", "The HTML is hard to parse…")
++ // stayed in the thread forever, wedged between the question and the
++ // answer they were superseded by.
++ //
++ // It is already captured twice over without this: `streamDeltaReceived`
++ // coalesces every `content` delta into `processingByThread` as a
++ // `narration` transcript item (chatRuntimeSlice), and the core persists
++ // the same thing server-side as `TranscriptItem::Narration`, kept after
++ // completion so a reload replays it. The inline rail and the Agent
++ // Process Source panel both render that transcript — so narration is
++ // still fully visible while the turn runs, and still inspectable after,
++ // just not as a permanent chat bubble.
++ //
++ // The event is still consumed (not dropped upstream) for its dedup key
++ // and the preview reset below, both of which are round-scoped.
++ rtLog('interim_narration_observed', {
++ thread: event.thread_id,
++ request: event.request_id,
round: event.round,
-- delta: event.delta,
-- toolName: event.tool_name,
-- toolCallId: event.tool_call_id,
-- })
-- );
-- },
-- onProactiveMessage: (event: ProactiveMessageEvent) => {
-- const messageDigest = proactiveMessageDigest(event.full_response ?? '');
-- const eventKey = `proactive:${event.thread_id}:${event.request_id ?? 'none'}:${messageDigest}`;
-- if (
-- !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
-- )
-- return;
--
-- proactiveDispatchQueueRef.current = proactiveDispatchQueueRef.current.then(async () => {
-- try {
-- const targetThreadId = await resolveVisibleThreadForProactive(event.thread_id);
-- if (!targetThreadId) return;
-- rtLog('proactive_message', {
-- from: event.thread_id,
-- to: targetThreadId,
-- request: event.request_id,
-- });
-- await dispatch(
-- addInferenceResponse({
-- content: event.full_response,
-- threadId: targetThreadId,
-- // Stamp the producing turn's request id when present (Phase 4
-- // anchoring); proactive events may omit it, in which case the
-- // message falls back to the legacy single-anchor turn.
-- extraMetadata: event.request_id ? { requestId: event.request_id } : undefined,
++ });
++ // Drop the round's narration from the live streaming preview, which
++ // accumulates across the whole turn under one request_id. This matters
++ // MORE now: without it the same text renders both in the rail (as a
++ // transcript item) and in the preview tail. Reset synchronously so the
++ // next round's deltas start from an empty buffer.
++ const cr = store.getState().chatRuntime;
++ const existing = cr.streamingAssistantByThread[event.thread_id];
++ if (existing && existing.requestId === event.request_id) {
++ dispatch(
++ setStreamingAssistantForThread({
++ threadId: event.thread_id,
++ streaming: {
++ requestId: existing.requestId,
++ content: '',
++ thinking: existing.thinking,
++ },
})
);
-- } catch (error) {
-- rtLog('proactive_dispatch_failed', {
-- from: event.thread_id,
-- request: event.request_id,
-- error: error instanceof Error ? error.message : String(error),
-- });
}
-- });
-- },
-- onArtifactPending: event => {
-- rtLog('artifact_pending', {
-- thread: event.thread_id,
-- artifact_id: event.artifact_id,
-- kind: event.kind,
-- });
-- dispatch(
-- upsertArtifactInProgressForThread({
-- threadId: event.thread_id,
-- artifactId: event.artifact_id,
++ },
++ onTextDelta: event => {
++ // Redelivered frames are dropped before coalescing (`accept` below).
++ // Parallel-vs-primary routing + processing transcript now live in the
++ // reducer (Phase 3) — no getState() in the provider.
++ dispatch(
++ streamDeltaReceived({
++ threadId: event.thread_id,
++ requestId: event.request_id,
++ round: event.round,
++ delta: event.delta,
++ channel: 'content',
++ })
++ );
++ },
++ onThinkingDelta: event => {
++ dispatch(
++ streamDeltaReceived({
++ threadId: event.thread_id,
++ requestId: event.request_id,
++ round: event.round,
++ delta: event.delta,
++ channel: 'thinking',
++ at: Date.now(),
++ })
++ );
++ },
++ onToolArgsDelta: event => {
++ // Match + append + decorate now live in the reducer (Phase 3).
++ dispatch(
++ toolArgsDeltaReceived({
++ threadId: event.thread_id,
++ round: event.round,
++ delta: event.delta,
++ toolName: event.tool_name,
++ toolCallId: event.tool_call_id,
++ })
++ );
++ },
++ onProactiveMessage: (event: ProactiveMessageEvent) => {
++ const messageDigest = proactiveMessageDigest(event.full_response ?? '');
++ const eventKey = `proactive:${event.thread_id}:${event.request_id ?? 'none'}:${messageDigest}`;
++ if (
++ !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
++ )
++ return;
++
++ proactiveDispatchQueueRef.current = proactiveDispatchQueueRef.current.then(async () => {
++ try {
++ const targetThreadId = await resolveVisibleThreadForProactive(event.thread_id);
++ if (!targetThreadId) return;
++ rtLog('proactive_message', {
++ from: event.thread_id,
++ to: targetThreadId,
++ request: event.request_id,
++ });
++ await dispatch(
++ addInferenceResponse({
++ content: event.full_response,
++ threadId: targetThreadId,
++ // Stamp the producing turn's request id when present (Phase 4
++ // anchoring); proactive events may omit it, in which case the
++ // message falls back to the legacy single-anchor turn.
++ extraMetadata: event.request_id ? { requestId: event.request_id } : undefined,
++ })
++ );
++ } catch (error) {
++ rtLog('proactive_dispatch_failed', {
++ from: event.thread_id,
++ request: event.request_id,
++ error: error instanceof Error ? error.message : String(error),
++ });
++ }
++ });
++ },
++ onArtifactPending: event => {
++ rtLog('artifact_pending', {
++ thread: event.thread_id,
++ artifact_id: event.artifact_id,
kind: event.kind,
-- title: event.title,
-- })
-- );
-- },
-- onArtifactReady: event => {
-- rtLog('artifact_ready', {
-- thread: event.thread_id,
-- artifact_id: event.artifact_id,
-- kind: event.kind,
-- size_bytes: event.size_bytes,
-- });
-- dispatch(
-- upsertArtifactReadyForThread({
-- threadId: event.thread_id,
-- artifactId: event.artifact_id,
++ });
++ dispatch(
++ upsertArtifactInProgressForThread({
++ threadId: event.thread_id,
++ artifactId: event.artifact_id,
++ kind: event.kind,
++ title: event.title,
++ })
++ );
++ },
++ onArtifactReady: event => {
++ rtLog('artifact_ready', {
++ thread: event.thread_id,
++ artifact_id: event.artifact_id,
kind: event.kind,
-- title: event.title,
-- path: event.path,
-- sizeBytes: event.size_bytes,
-- })
-- );
-- },
-- onArtifactFailed: event => {
-- // Defence-in-depth: producer is expected to pre-truncate the
-- // reason, but cap again here so a leaky producer cannot dump
-- // unbounded provider stderr into client telemetry.
-- rtLog('artifact_failed', {
-- thread: event.thread_id,
-- artifact_id: event.artifact_id,
-- kind: event.kind,
-- error: event.error.slice(0, 80),
-- });
-- dispatch(
-- upsertArtifactFailedForThread({
-- threadId: event.thread_id,
-- artifactId: event.artifact_id,
++ size_bytes: event.size_bytes,
++ });
++ dispatch(
++ upsertArtifactReadyForThread({
++ threadId: event.thread_id,
++ artifactId: event.artifact_id,
++ kind: event.kind,
++ title: event.title,
++ path: event.path,
++ sizeBytes: event.size_bytes,
++ })
++ );
++ },
++ onArtifactFailed: event => {
++ // Defence-in-depth: producer is expected to pre-truncate the
++ // reason, but cap again here so a leaky producer cannot dump
++ // unbounded provider stderr into client telemetry.
++ rtLog('artifact_failed', {
++ thread: event.thread_id,
++ artifact_id: event.artifact_id,
kind: event.kind,
-- title: event.title,
-- error: event.error,
-- })
-- );
-- },
-- onApprovalRequest: (event: ChatApprovalRequestEvent) => {
-- rtLog('approval_request', {
-- thread: event.thread_id,
-- request: event.request_id,
-- tool: event.tool_name,
-- });
-- // Pull the exact command/target out of the redacted args for display:
-- // shell → command, file write/edit → path, network → url.
-- const a = event.args ?? {};
-- const firstString = (v: unknown): string | undefined =>
-- typeof v === 'string' && v.length > 0 ? v : undefined;
-- const command =
-- firstString(a.command) ??
-- firstString(a.path) ??
-- firstString(a.url) ??
-- firstString(a.target);
-- // `composio_connect` carries the toolkit slug so the inline connect
-- // card (#3993) knows which integration to authorize.
-- const toolkit = firstString(a.toolkit);
-- dispatch(
-- setPendingApprovalForThread({
-- threadId: event.thread_id,
-- approval: {
-- requestId: event.request_id,
-- toolName: event.tool_name,
-- message: event.message,
-- command,
-- toolkit,
-- },
-- })
-- );
-- },
-- onPlanReviewRequest: (event: ChatPlanReviewRequestEvent) => {
-- rtLog('plan_review_request', { thread: event.thread_id, request: event.request_id });
-- const steps = Array.isArray(event.args?.steps)
-- ? event.args.steps.filter((s): s is string => typeof s === 'string')
-- : [];
-- dispatch(
-- setPendingPlanReviewForThread({
-- threadId: event.thread_id,
-- review: { requestId: event.request_id, summary: event.message, steps },
-- })
-- );
-- },
-- onDone: event => {
-- const eventKey = `done:${event.thread_id}:${event.request_id ?? 'none'}`;
-- if (
-- !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
-- )
-- return;
--
-- rtLog('chat_done', {
-- thread: event.thread_id,
-- request: event.request_id,
-- segments: event.segment_total,
-- input_tokens: event.total_input_tokens,
-- output_tokens: event.total_output_tokens,
-- });
++ error: event.error.slice(0, 80),
++ });
++ dispatch(
++ upsertArtifactFailedForThread({
++ threadId: event.thread_id,
++ artifactId: event.artifact_id,
++ kind: event.kind,
++ title: event.title,
++ error: event.error,
++ })
++ );
++ },
++ onApprovalRequest: (event: ChatApprovalRequestEvent) => {
++ rtLog('approval_request', {
++ thread: event.thread_id,
++ request: event.request_id,
++ tool: event.tool_name,
++ });
++ // Pull the exact command/target out of the redacted args for display:
++ // shell → command, file write/edit → path, network → url.
++ const a = event.args ?? {};
++ const firstString = (v: unknown): string | undefined =>
++ typeof v === 'string' && v.length > 0 ? v : undefined;
++ const command =
++ firstString(a.command) ??
++ firstString(a.path) ??
++ firstString(a.url) ??
++ firstString(a.target);
++ // `composio_connect` carries the toolkit slug so the inline connect
++ // card (#3993) knows which integration to authorize.
++ const toolkit = firstString(a.toolkit);
++ dispatch(
++ setPendingApprovalForThread({
++ threadId: event.thread_id,
++ approval: {
++ requestId: event.request_id,
++ toolName: event.tool_name,
++ message: event.message,
++ command,
++ toolkit,
++ },
++ })
++ );
++ },
++ onPlanReviewRequest: (event: ChatPlanReviewRequestEvent) => {
++ rtLog('plan_review_request', { thread: event.thread_id, request: event.request_id });
++ const steps = Array.isArray(event.args?.steps)
++ ? event.args.steps.filter((s): s is string => typeof s === 'string')
++ : [];
++ dispatch(
++ setPendingPlanReviewForThread({
++ threadId: event.thread_id,
++ review: { requestId: event.request_id, summary: event.message, steps },
++ })
++ );
++ },
++ onDone: event => {
++ const eventKey = `done:${event.thread_id}:${event.request_id ?? 'none'}`;
++ if (
++ !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
++ )
++ return;
-- // Close the tool-chain latency window and surface overruns of the 60s
-- // target (#4273, AC3). Observability only — never blocks the turn.
-- const latency = skillLatencyRef.current.finishChain(
-- segmentDeliveryKey(event.thread_id, event.request_id),
-- { ok: true }
-- );
-- if (latency) {
-- rtLog('skill_tool_chain_latency', {
++ rtLog('chat_done', {
thread: event.thread_id,
request: event.request_id,
-- elapsed_ms: latency.elapsedMs,
-- tools: latency.toolCount,
-- within_target: latency.withinTarget ? 'true' : 'false',
++ segments: event.segment_total,
++ input_tokens: event.total_input_tokens,
++ output_tokens: event.total_output_tokens,
});
-- if (!latency.withinTarget) {
-- console.warn(
-- `[skill-latency] tool chain on thread ${event.thread_id} took ${latency.elapsedMs}ms ` +
-- `across ${latency.toolCount} tool(s) — exceeds the ${SKILL_TOOL_CHAIN_TARGET_MS}ms target`
-- );
++
++ // Close the tool-chain latency window and surface overruns of the 60s
++ // target (#4273, AC3). Observability only — never blocks the turn.
++ const latency = skillLatencyRef.current.finishChain(
++ segmentDeliveryKey(event.thread_id, event.request_id),
++ { ok: true }
++ );
++ if (latency) {
++ rtLog('skill_tool_chain_latency', {
++ thread: event.thread_id,
++ request: event.request_id,
++ elapsed_ms: latency.elapsedMs,
++ tools: latency.toolCount,
++ within_target: latency.withinTarget ? 'true' : 'false',
++ });
++ if (!latency.withinTarget) {
++ console.warn(
++ `[skill-latency] tool chain on thread ${event.thread_id} took ${latency.elapsedMs}ms ` +
++ `across ${latency.toolCount} tool(s) — exceeds the ${SKILL_TOOL_CHAIN_TARGET_MS}ms target`
++ );
++ }
+ }
- }
+
- // Parallel (forked) turn: resolve only its own lane. The primary turn's
- // stream / status / lifecycle / active marker may still be running, so
- // we must NOT clear them here. Segmented parallel turns already
- // persisted via `onSegment` (keyed by thread+request); a single-bubble
- // parallel turn persists its full response now.
- if (
- event.request_id !== undefined &&
- store.getState().chatRuntime.parallelRequestThreads[event.request_id] !== undefined
- ) {
- const parallelRequestId = event.request_id;
++ // Parallel (forked) turn: resolve only its own lane. The primary turn's
++ // stream / status / lifecycle / active marker may still be running, so
++ // we must NOT clear them here. Segmented parallel turns already
++ // persisted via `onSegment` (keyed by thread+request); a single-bubble
++ // parallel turn persists its full response now.
++ if (
++ event.request_id !== undefined &&
++ store.getState().chatRuntime.parallelRequestThreads[event.request_id] !== undefined
++ ) {
++ const parallelRequestId = event.request_id;
++ dispatch(recordChatTurnUsage(chatTurnUsagePayload(event)));
++ if (!event.segment_total && event.full_response.length > 0) {
++ void (async () => {
++ try {
++ await dispatch(
++ addInferenceResponse({
++ content: event.full_response,
++ threadId: event.thread_id,
++ messageId: deliveredReplyMessageId(event),
++ extraMetadata: chatDoneExtraMetadata(event),
++ })
++ ).unwrap();
++ void dispatch(
++ generateThreadTitleIfNeeded({
++ threadId: event.thread_id,
++ assistantMessage: event.full_response,
++ })
++ );
++ } catch (error) {
++ rtLog('parallel_chat_done_append_failed', {
++ thread: event.thread_id,
++ request: event.request_id,
++ error: error instanceof Error ? error.message : String(error),
++ });
++ await recoverDeliveredReply(event, error);
++ }
++ })();
++ }
++ dispatch(clearParallelRequest({ requestId: parallelRequestId }));
++ requestUsageRefresh();
++ return;
+ }
- }
+
- // Parallel (forked) turn: resolve only its own lane. The primary turn's
- // stream / status / lifecycle / active marker may still be running, so
- // we must NOT clear them here. Segmented parallel turns already
- // persisted via `onSegment` (keyed by thread+request); a single-bubble
- // parallel turn persists its full response now.
- if (
- event.request_id !== undefined &&
- store.getState().chatRuntime.parallelRequestThreads[event.request_id] !== undefined
- ) {
- const parallelRequestId = event.request_id;
++ const deliveryKey = segmentDeliveryKey(event.thread_id, event.request_id);
++ const segmentDelivery = takeSegmentDelivery(segmentDeliveriesRef.current, deliveryKey);
++ const completeSegmentDelivery = hasCompleteSegmentDelivery(event, segmentDelivery);
++
dispatch(recordChatTurnUsage(chatTurnUsagePayload(event)));
-- if (!event.segment_total && event.full_response.length > 0) {
++ // A parked gate cannot outlive its turn, so those go now.
++ dispatch(clearPendingApprovalForThread({ threadId: event.thread_id }));
++ dispatch(clearPendingPlanReviewForThread({ threadId: event.thread_id }));
++ // Nothing the turn RENDERED is cleared here. The streaming buffer, the
++ // status line and the running rows used to be torn down first, before
++ // the reply was even persisted, and every one of those was a render:
++ // the answer vanished, then reappeared above its own tools, then the
++ // tools moved back and remounted collapsed. The live tail now stays as
++ // it is until `finishChatDoneTurn` swaps it for the persisted reply in
++ // one `turnSettled` update (the reply row is hidden behind the tail
++ // until then — see `buildRuntimeMessages`).
++ //
++ // Rows still `running` are NOT forced to `success` here. The core now
++ // forwards every queued progress event before `chat_done`, so a row
++ // still running at this point genuinely has no result — marking it
++ // successful invented an outcome. The settled turn_state snapshot /
++ // transcript projection settles it (to its real status, or
++ // `cancelled`).
++ if (!event.segment_total) {
void (async () => {
try {
await dispatch(
@@@ -1333,268 -1385,267 +1464,223 @@@
})
);
} catch (error) {
-- rtLog('parallel_chat_done_append_failed', {
++ rtLog('chat_done_append_failed', {
thread: event.thread_id,
request: event.request_id,
error: error instanceof Error ? error.message : String(error),
});
await recoverDeliveredReply(event, error);
}
++ await finishChatDoneTurn(event, 'proactive');
})();
++ return;
}
-- dispatch(clearParallelRequest({ requestId: parallelRequestId }));
-- requestUsageRefresh();
-- return;
-- }
-- const deliveryKey = segmentDeliveryKey(event.thread_id, event.request_id);
-- const segmentDelivery = takeSegmentDelivery(segmentDeliveriesRef.current, deliveryKey);
-- const completeSegmentDelivery = hasCompleteSegmentDelivery(event, segmentDelivery);
--
-- dispatch(recordChatTurnUsage(chatTurnUsagePayload(event)));
- // A parked gate cannot outlive its turn, so those go now.
- dispatch(clearInferenceStatusForThread({ threadId: event.thread_id }));
- dispatch(clearStreamingAssistantForThread({ threadId: event.thread_id }));
-- dispatch(clearPendingApprovalForThread({ threadId: event.thread_id }));
-- dispatch(clearPendingPlanReviewForThread({ threadId: event.thread_id }));
- // Nothing the turn RENDERED is cleared here. The streaming buffer, the
- // status line and the running rows used to be torn down first, before
- // the reply was even persisted, and every one of those was a render:
- // the answer vanished, then reappeared above its own tools, then the
- // tools moved back and remounted collapsed. The live tail now stays as
- // it is until `finishChatDoneTurn` swaps it for the persisted reply in
- // one `turnSettled` update (the reply row is hidden behind the tail
- // until then — see `buildRuntimeMessages`).
-
- // Rows still `running` are NOT forced to `success` here. The core now
- // forwards every queued progress event before `chat_done`, so a row
- // still running at this point genuinely has no result — marking it
- // successful invented an outcome. The settled turn_state snapshot /
- // transcript projection settles it (to its real status, or
- // `cancelled`).
-- if (!event.segment_total) {
-- void (async () => {
-- try {
-- await dispatch(
-- addInferenceResponse({
-- content: event.full_response,
-- threadId: event.thread_id,
-- messageId: deliveredReplyMessageId(event),
-- extraMetadata: chatDoneExtraMetadata(event),
-- })
-- ).unwrap();
-- void dispatch(
-- generateThreadTitleIfNeeded({
-- threadId: event.thread_id,
-- assistantMessage: event.full_response,
-- })
-- );
-- } catch (error) {
-- rtLog('chat_done_append_failed', {
-- thread: event.thread_id,
-- request: event.request_id,
-- error: error instanceof Error ? error.message : String(error),
-- });
-- await recoverDeliveredReply(event, error);
-- }
-- await finishChatDoneTurn(event, 'proactive');
-- })();
-- return;
-- }
++ if (!completeSegmentDelivery && event.full_response.length > 0) {
++ rtLog('chat_done_segment_reconcile', {
++ thread: event.thread_id,
++ request: event.request_id,
++ expected: event.segment_total,
++ received: segmentDelivery?.segments.size ?? 0,
++ full_len: event.full_response.length,
++ });
++ void (async () => {
++ try {
++ await dispatch(
++ addInferenceResponse({
++ content: event.full_response,
++ threadId: event.thread_id,
++ messageId: corePersistedMessageId(event),
++ extraMetadata: chatDoneExtraMetadata(event),
++ })
++ ).unwrap();
++ void dispatch(
++ generateThreadTitleIfNeeded({
++ threadId: event.thread_id,
++ assistantMessage: event.full_response,
++ })
++ );
++ } catch (error) {
++ rtLog('chat_done_reconcile_append_failed', {
++ thread: event.thread_id,
++ request: event.request_id,
++ error: error instanceof Error ? error.message : String(error),
++ });
++ }
++ await finishChatDoneTurn(event, 'segment_reconcile');
++ })();
++ return;
++ }
+
- if (!completeSegmentDelivery && event.full_response.length > 0) {
- rtLog('chat_done_segment_reconcile', {
++ void dispatch(
++ generateThreadTitleIfNeeded({
++ threadId: event.thread_id,
++ assistantMessage: event.full_response,
++ })
++ );
++ void finishChatDoneTurn(event, 'ordinary');
++ },
++ onError: event => {
++ const eventKey = `error:${event.thread_id}:${event.request_id ?? 'none'}:${event.error_type}`;
++ if (
++ !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
++ )
++ return;
+
- if (!completeSegmentDelivery && event.full_response.length > 0) {
- rtLog('chat_done_segment_reconcile', {
++ rtLog('chat_error', {
thread: event.thread_id,
request: event.request_id,
-- expected: event.segment_total,
-- received: segmentDelivery?.segments.size ?? 0,
-- full_len: event.full_response.length,
++ err: event.error_type,
});
-- void (async () => {
-- try {
-- await dispatch(
-- addInferenceResponse({
-- content: event.full_response,
-- threadId: event.thread_id,
-- messageId: corePersistedMessageId(event),
-- extraMetadata: chatDoneExtraMetadata(event),
-- })
-- ).unwrap();
-- void dispatch(
-- generateThreadTitleIfNeeded({
-- threadId: event.thread_id,
-- assistantMessage: event.full_response,
++
++ // A failed turn still closes its latency window so the chain timer never
++ // leaks into a later turn on the same thread (#4273, AC3).
++ const errLatency = skillLatencyRef.current.finishChain(
++ segmentDeliveryKey(event.thread_id, event.request_id),
++ { ok: false }
++ );
++ if (errLatency) {
++ rtLog('skill_tool_chain_latency', {
++ thread: event.thread_id,
++ request: event.request_id,
++ elapsed_ms: errLatency.elapsedMs,
++ tools: errLatency.toolCount,
++ within_target: errLatency.withinTarget ? 'true' : 'false',
++ ok: 'false',
++ });
++ }
++
++ // #3931: surface expected, user-actionable provider/billing states
++ // (insufficient BYO credits, managed-budget exhaustion) in the shell's
++ // dedicated error panel — in ADDITION to the inline chat message below.
++ // Additive + defensive: no-op for non-actionable errors, never throws.
++ if (event.error_type !== 'cancelled') {
++ ingestRuntimeErrorSignal(dispatch, {
++ message: event.message,
++ errorType: event.error_type,
++ scope: 'chat',
++ sourceDomain: 'chat',
++ });
++ // #5868: a session_expired chat error means the Rust core already
++ // published DomainEvent::SessionExpired and set signed_out=true, but
++ // the auth:session_expired socket event may have been suppressed
++ // (isBootstrapping guard) or missed. Dispatch the same window event
++ // socketService emits so CoreStateProvider's runReauth() fires the
++ // clearSession() → login redirect path from this side too. The 10s
++ // debounce in runReauth() ensures a concurrent socket event does not
++ // cause a double-clear.
++ if (event.error_type === 'session_expired') {
++ // `reason: 'unconfirmed'` is load-bearing, not defensive. The core
++ // classifies this error with `is_session_expired_message`, which
++ // matches the LOCAL guards "no backend session token" and
++ // "session jwt required" as well as a real backend expiry
++ // (`core/observability.rs`). Those two fire transiently before the
++ // on-disk auth profile has been read — #2758 is the bug where
++ // treating them as definitive forced a re-login even though the
++ // token had survived the restart. `unconfirmed` routes through
++ // `confirmSessionTokenGone()` in `runReauth`, so a signal raised
++ // while the token is still on disk stops short of the destructive
++ // `clearSession()`. A genuine expiry still corroborates and signs
++ // out; only the false positive is filtered.
++ window.dispatchEvent(
++ new CustomEvent('openhuman:session-expired', {
++ detail: { source: 'chat-error', reason: 'unconfirmed' },
})
);
-- } catch (error) {
-- rtLog('chat_done_reconcile_append_failed', {
-- thread: event.thread_id,
-- request: event.request_id,
-- error: error instanceof Error ? error.message : String(error),
-- });
}
-- await finishChatDoneTurn(event, 'segment_reconcile');
-- })();
-- return;
-- }
--
-- void dispatch(
-- generateThreadTitleIfNeeded({
-- threadId: event.thread_id,
-- assistantMessage: event.full_response,
-- })
-- );
-- void finishChatDoneTurn(event, 'ordinary');
-- },
-- onError: event => {
-- const eventKey = `error:${event.thread_id}:${event.request_id ?? 'none'}:${event.error_type}`;
-- if (
-- !markChatEventSeen(eventKey, { threadId: event.thread_id, requestId: event.request_id })
-- )
-- return;
--
-- rtLog('chat_error', {
-- thread: event.thread_id,
-- request: event.request_id,
-- err: event.error_type,
-- });
--
-- // A failed turn still closes its latency window so the chain timer never
-- // leaks into a later turn on the same thread (#4273, AC3).
-- const errLatency = skillLatencyRef.current.finishChain(
-- segmentDeliveryKey(event.thread_id, event.request_id),
-- { ok: false }
-- );
-- if (errLatency) {
-- rtLog('skill_tool_chain_latency', {
-- thread: event.thread_id,
-- request: event.request_id,
-- elapsed_ms: errLatency.elapsedMs,
-- tools: errLatency.toolCount,
-- within_target: errLatency.withinTarget ? 'true' : 'false',
-- ok: 'false',
-- });
-- }
++ }
-- // #3931: surface expected, user-actionable provider/billing states
-- // (insufficient BYO credits, managed-budget exhaustion) in the shell's
-- // dedicated error panel — in ADDITION to the inline chat message below.
-- // Additive + defensive: no-op for non-actionable errors, never throws.
-- if (event.error_type !== 'cancelled') {
-- ingestRuntimeErrorSignal(dispatch, {
-- message: event.message,
-- errorType: event.error_type,
-- scope: 'chat',
-- sourceDomain: 'chat',
-- });
-- // #5868: a session_expired chat error means the Rust core already
-- // published DomainEvent::SessionExpired and set signed_out=true, but
-- // the auth:session_expired socket event may have been suppressed
-- // (isBootstrapping guard) or missed. Dispatch the same window event
-- // socketService emits so CoreStateProvider's runReauth() fires the
-- // clearSession() → login redirect path from this side too. The 10s
-- // debounce in runReauth() ensures a concurrent socket event does not
-- // cause a double-clear.
-- if (event.error_type === 'session_expired') {
-- // `reason: 'unconfirmed'` is load-bearing, not defensive. The core
-- // classifies this error with `is_session_expired_message`, which
-- // matches the LOCAL guards "no backend session token" and
-- // "session jwt required" as well as a real backend expiry
-- // (`core/observability.rs`). Those two fire transiently before the
-- // on-disk auth profile has been read — #2758 is the bug where
-- // treating them as definitive forced a re-login even though the
-- // token had survived the restart. `unconfirmed` routes through
-- // `confirmSessionTokenGone()` in `runReauth`, so a signal raised
-- // while the token is still on disk stops short of the destructive
-- // `clearSession()`. A genuine expiry still corroborates and signs
-- // out; only the false positive is filtered.
-- window.dispatchEvent(
-- new CustomEvent('openhuman:session-expired', {
-- detail: { source: 'chat-error', reason: 'unconfirmed' },
-- })
++ // Parallel (forked) turn error: resolve only its lane, leaving the
++ // primary turn untouched. Surface a non-cancellation error as a message
++ // so the failed branch is visible.
++ if (
++ event.request_id !== undefined &&
++ store.getState().chatRuntime.parallelRequestThreads[event.request_id] !== undefined
++ ) {
++ deleteSegmentDelivery(
++ segmentDeliveriesRef.current,
++ segmentDeliveryKey(event.thread_id, event.request_id)
);
++ if (event.error_type !== 'cancelled') {
++ const errorContent = event.message || USER_FACING_AGENT_ERROR_MESSAGE;
++ void dispatch(
++ addInferenceResponse({ content: errorContent, threadId: event.thread_id })
++ );
++ requestUsageRefresh();
++ }
++ dispatch(clearParallelRequest({ requestId: event.request_id }));
++ return;
}
-- }
-- // Parallel (forked) turn error: resolve only its lane, leaving the
-- // primary turn untouched. Surface a non-cancellation error as a message
-- // so the failed branch is visible.
-- if (
-- event.request_id !== undefined &&
-- store.getState().chatRuntime.parallelRequestThreads[event.request_id] !== undefined
-- ) {
deleteSegmentDelivery(
segmentDeliveriesRef.current,
segmentDeliveryKey(event.thread_id, event.request_id)
);
-- if (event.error_type !== 'cancelled') {
-- const errorContent = event.message || USER_FACING_AGENT_ERROR_MESSAGE;
-- void dispatch(
-- addInferenceResponse({ content: errorContent, threadId: event.thread_id })
++ dispatch(clearInferenceStatusForThread({ threadId: event.thread_id }));
++ dispatch(clearStreamingAssistantForThread({ threadId: event.thread_id }));
++ dispatch(clearPendingApprovalForThread({ threadId: event.thread_id }));
++ dispatch(clearPendingPlanReviewForThread({ threadId: event.thread_id }));
++
++ const existing = store.getState().chatRuntime.toolTimelineByThread[event.thread_id] ?? [];
++ if (existing.length > 0) {
++ const entries = existing.map(entry =>
++ entry.status === 'running' ? { ...entry, status: 'error' as const } : entry
);
-- requestUsageRefresh();
++ dispatch(setToolTimelineForThread({ threadId: event.thread_id, entries }));
}
-- dispatch(clearParallelRequest({ requestId: event.request_id }));
-- return;
-- }
-- deleteSegmentDelivery(
-- segmentDeliveriesRef.current,
-- segmentDeliveryKey(event.thread_id, event.request_id)
-- );
-- dispatch(clearInferenceStatusForThread({ threadId: event.thread_id }));
-- dispatch(clearStreamingAssistantForThread({ threadId: event.thread_id }));
-- dispatch(clearPendingApprovalForThread({ threadId: event.thread_id }));
-- dispatch(clearPendingPlanReviewForThread({ threadId: event.thread_id }));
--
-- const existing = store.getState().chatRuntime.toolTimelineByThread[event.thread_id] ?? [];
-- if (existing.length > 0) {
-- const entries = existing.map(entry =>
-- entry.status === 'running' ? { ...entry, status: 'error' as const } : entry
-- );
-- dispatch(setToolTimelineForThread({ threadId: event.thread_id, entries }));
-- }
++ if (event.error_type !== 'cancelled') {
++ const currentState = store.getState();
++ const threadMessages = currentState.thread.messagesByThreadId[event.thread_id] ?? [];
++ const lastMsg = threadMessages[threadMessages.length - 1];
++ // Every error_type — including the generic 'inference' fallback — carries a
++ // user-facing `message` produced by classify_inference_error() in web_errors.rs.
++ // For 'inference' that message is the friendly summary PLUS the real, sanitized
++ // upstream provider error appended as a `> quote` block (secret-scrubbed and
++ // length-capped server-side via with_provider_detail()/sanitize_api_error()), so
++ // surfacing it tells the user *why* the turn failed instead of a blanket apology.
++ // The hardcoded constant is only a last-resort fallback for an empty/missing message.
++ const errorContent = event.message || USER_FACING_AGENT_ERROR_MESSAGE;
++ // A core-owned failure carries a deterministic id, so dedupe on that
++ // rather than on the text. Two runs can fail with byte-identical
++ // content — the same upstream provider message, or the generic
++ // fallback above — and a text check would then read the previous
++ // run's row as this one and drop the current failure from the cache.
++ // Interactive turns have no pre-persisted id and keep the text check.
++ const errorMessageId = corePersistedMessageId(event);
++ const alreadyPresent = errorMessageId
++ ? threadMessages.some(message => message.id === errorMessageId)
++ : lastMsg?.sender === 'agent' && lastMsg?.content === errorContent;
++ if (!alreadyPresent) {
++ void dispatch(
++ addInferenceResponse({
++ content: errorContent,
++ threadId: event.thread_id,
++ messageId: errorMessageId,
++ })
++ );
++ }
-- if (event.error_type !== 'cancelled') {
-- const currentState = store.getState();
-- const threadMessages = currentState.thread.messagesByThreadId[event.thread_id] ?? [];
-- const lastMsg = threadMessages[threadMessages.length - 1];
-- // Every error_type — including the generic 'inference' fallback — carries a
-- // user-facing `message` produced by classify_inference_error() in web_errors.rs.
-- // For 'inference' that message is the friendly summary PLUS the real, sanitized
-- // upstream provider error appended as a `> quote` block (secret-scrubbed and
-- // length-capped server-side via with_provider_detail()/sanitize_api_error()), so
-- // surfacing it tells the user *why* the turn failed instead of a blanket apology.
-- // The hardcoded constant is only a last-resort fallback for an empty/missing message.
-- const errorContent = event.message || USER_FACING_AGENT_ERROR_MESSAGE;
-- // A core-owned failure carries a deterministic id, so dedupe on that
-- // rather than on the text. Two runs can fail with byte-identical
-- // content — the same upstream provider message, or the generic
-- // fallback above — and a text check would then read the previous
-- // run's row as this one and drop the current failure from the cache.
-- // Interactive turns have no pre-persisted id and keep the text check.
-- const errorMessageId = corePersistedMessageId(event);
-- const alreadyPresent = errorMessageId
-- ? threadMessages.some(message => message.id === errorMessageId)
-- : lastMsg?.sender === 'agent' && lastMsg?.content === errorContent;
-- if (!alreadyPresent) {
-- void dispatch(
-- addInferenceResponse({
-- content: errorContent,
-- threadId: event.thread_id,
-- messageId: errorMessageId,
-- })
-- );
++ rtLog('refresh_usage_counter', {
++ thread: event.thread_id,
++ request: event.request_id,
++ reason: 'chat_error',
++ });
++ requestUsageRefresh();
}
-- rtLog('refresh_usage_counter', {
-- thread: event.thread_id,
-- request: event.request_id,
-- reason: 'chat_error',
-- });
-- requestUsageRefresh();
-- }
--
-- // The backend drains + dispatches queued follow-ups even when the turn
-- // errored, so flush them to the transcript here too (otherwise their
-- // prompts are lost). Mirrors the done path (sequential internally).
-- void flushQueuedFollowups(event.thread_id);
-- dispatch(endInferenceTurn({ threadId: event.thread_id }));
-- dispatch(clearThreadInferenceActive(event.thread_id));
++ // The backend drains + dispatches queued follow-ups even when the turn
++ // errored, so flush them to the transcript here too (otherwise their
++ // prompts are lost). Mirrors the done path (sequential internally).
++ void flushQueuedFollowups(event.thread_id);
++ dispatch(endInferenceTurn({ threadId: event.thread_id }));
++ dispatch(clearThreadInferenceActive(event.thread_id));
++ },
},
-- });
++ // A redelivered frame must be dropped before it can be merged into text.
++ { accept: event => !isReplayedDelta(event) }
++ );
+ const cleanup = subscribeChatEvents(coalesced.listeners);
return () => {
rtLog('unsubscribe_chat_events');
diff --cc app/src/providers/__tests__/ChatRuntimeProvider.test.tsx
index 9d36e701d7,634afad982..cd4b0ad09d
--- a/app/src/providers/__tests__/ChatRuntimeProvider.test.tsx
+++ b/app/src/providers/__tests__/ChatRuntimeProvider.test.tsx
@@@ -1668,17 -1649,60 +1668,63 @@@ describe('ChatRuntimeProvider — dedup
});
});
+ // The core drains every queued progress event before `chat_done`, so a
+ // row with no result by now has none. If the completed snapshot cannot
+ // be loaded, it has no remaining event driver and must not pulse as
+ // `running`; this still does not invent a successful tool outcome.
+ await waitFor(() => {
+ const timeline = store.getState().chatRuntime.toolTimelineByThread['t-inv'] ?? [];
+ expect(timeline).toHaveLength(1);
+ expect(timeline[0]?.status).toBe('cancelled');
+ });
+ });
+
+ it('keeps two id-less calls of one tool in a round apart by seq, still deduping a redelivery', () => {
+ const listeners = renderProvider();
+ const call = (seq: number) => ({
+ thread_id: 't-seq',
+ request_id: 'r1',
+ seq,
+ round: 1,
+ tool_name: 'shell',
+ skill_id: 'web_channel',
+ args: {},
+ });
+
+ act(() => {
+ listeners.onToolCall?.(call(3));
+ listeners.onToolCall?.(call(5));
+ // Socket redelivery of the first frame.
+ listeners.onToolCall?.(call(3));
+ });
+
+ expect(store.getState().chatRuntime.toolTimelineByThread['t-seq']).toHaveLength(2);
+ });
+
- it('drops a redelivered text delta by seq instead of appending it twice', () => {
++ it('drops a redelivered text delta by seq instead of appending it twice', async () => {
+ const listeners = renderProvider();
+ const delta = (seq: number, text: string) => ({
+ thread_id: 't-delta',
+ request_id: 'r1',
+ seq,
+ round: 1,
+ delta: text,
+ });
+
+ act(() => {
+ listeners.onTextDelta?.(delta(1, 'Hel'));
+ listeners.onTextDelta?.(delta(2, 'lo'));
+ listeners.onTextDelta?.(delta(1, 'Hel'));
+ listeners.onThinkingDelta?.(delta(2, 'lo'));
+ listeners.onTextDelta?.(delta(3, '!'));
+ });
+
- expect(store.getState().chatRuntime.streamingAssistantByThread['t-delta']?.content).toBe(
- 'Hello!'
++ // Deltas are coalesced per frame (`chatDeltaCoalescer`); wait for the flush.
+ await waitFor(() =>
- expect(store.getState().chatRuntime.toolTimelineByThread['t-inv']?.[0]?.status).toBe(
- 'success'
++ expect(store.getState().chatRuntime.streamingAssistantByThread['t-delta']?.content).toBe(
++ 'Hello!'
+ )
);
- const timeline = store.getState().chatRuntime.toolTimelineByThread['t-inv'] ?? [];
- expect(timeline).toHaveLength(1);
- // Frozen for the settled message too, so it keeps rendering these rows.
- expect(
- store.getState().chatRuntime.settledTurnsByThread['t-inv']?.['r1']?.timeline[0]?.status
- ).toBe('success');
});
it('transitions running tool-timeline rows to error on chat_error', () => {
diff --cc app/src/providers/__tests__/assistantUiMessages.test.ts
index 7a557d522d,6f00fbb725..598d08a65c
--- a/app/src/providers/__tests__/assistantUiMessages.test.ts
+++ b/app/src/providers/__tests__/assistantUiMessages.test.ts
@@@ -220,30 -219,6 +220,59 @@@ describe('buildRuntimeMessages', () =>
]);
});
++ it('settles a frozen trail’s running row from the core projection, keeping its id', () => {
++ const answer = msg({
++ id: 'answer',
++ sender: 'agent',
++ content: 'Done.',
++ extraMetadata: { requestId: 'req-f' },
++ });
++ const frozenTimeline = [tool({ id: 'call-1', status: 'running' })];
++ const frozenTranscript = [{ kind: 'toolCall' as const, round: 1, seq: 0, callId: 'call-1' }];
++ const build = (settledRows?: ReturnType<typeof tool>[]) =>
++ buildRuntimeMessages([answer], null, {
++ isRunning: false,
++ settledTurns: { 'req-f': { timeline: frozenTimeline, transcript: frozenTranscript } },
++ ...(settledRows ? { turnTimelines: { 'req-f': settledRows } } : {}),
++ })[0]?.content;
++
++ const before = build();
++ const toolBefore = Array.isArray(before) ? before[0] : undefined;
++ expect(toolBefore).toMatchObject({ toolCallId: 'call-1' });
++ expect(toolBefore && 'result' in toolBefore ? toolBefore.result : undefined).toBeUndefined();
++
++ const after = build([tool({ id: 'call-1', status: 'cancelled' })]);
++ const toolAfter = Array.isArray(after) ? after[0] : undefined;
++ expect(toolAfter).toMatchObject({
++ toolCallId: 'call-1',
++ result: expect.objectContaining({ status: 'cancelled' }),
++ });
++ });
++
+ it('never renders the answer twice when a transcript records it as narration', () => {
+ // An older core projects a prompt-guided turn's answer as an interim step
+ // with every call after it. The answer must still render once, last.
+ const answer = msg({
+ id: 'answer',
+ sender: 'agent',
+ content: 'The setting is on.',
+ extraMetadata: { requestId: 'req-p' },
+ });
+ const content = buildRuntimeMessages([answer], null, {
+ turnTimelines: { 'req-p': [tool({ id: 'call-1', status: 'success', result: 'ok' })] },
+ turnTranscripts: {
+ 'req-p': [
+ { kind: 'narration', round: 3, seq: 0, text: 'The setting is on.' },
+ { kind: 'toolCall', round: 3, seq: 1, callId: 'call-1' },
+ ],
+ },
+ })[0]?.content;
+ expect(Array.isArray(content) ? content.map(part => part.type) : content).toEqual([
+ 'tool-call',
+ 'text',
+ ]);
+ });
+
it('chronologically anchors persisted trails to async agent messages without request ids', () => {
const acknowledgement = msg({
id: 'ack',
diff --cc app/src/providers/assistantUiMessages.ts
index 24d473e7cb,bb26a5aeca..2c9d275446
--- a/app/src/providers/assistantUiMessages.ts
+++ b/app/src/providers/assistantUiMessages.ts
@@@ -701,6 -656,6 +701,49 @@@ export function streamingTailMessage
};
}
++const settledStatusCache = new WeakMap<
++ readonly ToolTimelineEntry[],
++ { settled: readonly ToolTimelineEntry[]; merged: readonly ToolTimelineEntry[] }
++>();
++
++/**
++ * A frozen live trail, with each still-running row settled from the core
++ * projection's row of the same id.
++ *
++ * `chat_done` does not invent a status for a row that has no result yet; the
++ * core projection settles it (to its real status, or `cancelled`). The frozen
++ * trail keeps the live row ids — which is what keeps every card mounted — so
++ * only status, result and failure are taken over, never the row. Sub-agent
++ * rows carry different ids on the two sides and are left to their own events.
++ * Returns the frozen array itself when nothing changes, so the conversion
++ * cache keeps hitting.
++ */
++function withSettledStatuses(
++ frozen: readonly ToolTimelineEntry[],
++ settled: readonly ToolTimelineEntry[] | undefined
++): readonly ToolTimelineEntry[] {
++ if (!settled || !frozen.some(entry => isActiveTimelineStatus(entry.status))) return frozen;
++ const cached = settledStatusCache.get(frozen);
++ if (cached?.settled === settled) return cached.merged;
++ const byId = new Map(settled.map(entry => [entry.id, entry]));
++ let changed = false;
++ const merged = frozen.map(entry => {
++ if (!isActiveTimelineStatus(entry.status)) return entry;
++ const final = byId.get(entry.id);
++ if (!final || isActiveTimelineStatus(final.status)) return entry;
++ changed = true;
++ return {
++ ...entry,
++ status: final.status,
++ result: final.result ?? entry.result,
++ failure: final.failure ?? entry.failure,
++ };
++ });
++ const result = changed ? merged : frozen;
++ settledStatusCache.set(frozen, { settled, merged: result });
++ return result;
++}
++
export type AssistantUiProjection = {
/** Whether the synthetic live tail has an active core turn driving it. */
isRunning?: boolean;
@@@ -803,12 -728,6 +846,19 @@@ export function buildRuntimeMessages
msg.sender === 'agent' && typeof msg.extraMetadata?.requestId === 'string'
? msg.extraMetadata.requestId
: undefined;
+ if (hiddenLiveRequestId !== undefined && requestId === hiddenLiveRequestId) continue;
+ const frozen = requestId ? projection.settledTurns?.[requestId] : undefined;
+ if (frozen) {
- out.push(toThreadMessageLike(msg, frozen.timeline, frozen.transcript));
++ const settledRows = requestId ? projection.turnTimelines?.[requestId] : undefined;
++ out.push(
++ toThreadMessageLike(
++ msg,
++ withSettledStatuses(frozen.timeline, settledRows),
++ frozen.transcript
++ )
++ );
+ continue;
+ }
const effectiveRequestId =
requestId ??
(msg.sender === 'agent' && pairOrphanTrails
diff --cc app/src/services/chatDeltaCoalescer.test.ts
index a3219fd45c,0000000000..b3100267e8
mode 100644,000000..100644
--- a/app/src/services/chatDeltaCoalescer.test.ts
+++ b/app/src/services/chatDeltaCoalescer.test.ts
@@@ -1,122 -1,0 +1,153 @@@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ type CoalescibleDelta,
+ createChatDeltaCoalescer,
+ type DeltaChannel,
+ type FlushScheduler,
+ withCoalescedDeltas,
+} from './chatDeltaCoalescer';
+
+/** A scheduler the test fires by hand: one pending flush at a time. */
+function manualScheduler() {
+ let pending: (() => void) | null = null;
+ const schedule: FlushScheduler = flush => {
+ pending = flush;
+ return () => {
+ pending = null;
+ };
+ };
+ return {
+ schedule,
+ frame: () => {
+ const run = pending;
+ pending = null;
+ run?.();
+ },
+ get scheduled() {
+ return pending !== null;
+ },
+ };
+}
+
+const delta = (over: Partial<CoalescibleDelta>): CoalescibleDelta => ({
+ thread_id: 't',
+ request_id: 'r',
+ round: 1,
+ delta: '',
+ ...over,
+});
+
+describe('createChatDeltaCoalescer', () => {
+ it('delivers a frame of same-key deltas as ONE merged delta', () => {
+ const frames = manualScheduler();
+ const deliver = vi.fn();
+ const coalescer = createChatDeltaCoalescer(deliver, frames.schedule);
+
+ for (const piece of ['He', 'll', 'o']) coalescer.push('content', delta({ delta: piece }));
+ expect(deliver).not.toHaveBeenCalled();
+
+ frames.frame();
+ expect(deliver).toHaveBeenCalledTimes(1);
+ expect(deliver).toHaveBeenCalledWith('content', delta({ delta: 'Hello' }));
+ });
+
+ it('keeps interleaved channels, rounds and threads in arrival order', () => {
+ const frames = manualScheduler();
+ const delivered: [DeltaChannel, string][] = [];
+ const coalescer = createChatDeltaCoalescer<CoalescibleDelta>(
+ (channel, event) =>
+ delivered.push([channel, `${event.thread_id}/${event.round}:${event.delta}`]),
+ frames.schedule
+ );
+
+ coalescer.push('thinking', delta({ delta: 'a' }));
+ coalescer.push('thinking', delta({ delta: 'b' }));
+ coalescer.push('content', delta({ delta: 'c' }));
+ coalescer.push('content', delta({ round: 2, delta: 'd' }));
+ coalescer.push('content', delta({ thread_id: 'u', round: 2, delta: 'e' }));
+ coalescer.push('content', delta({ round: 2, delta: 'f' }));
+ frames.frame();
+
+ expect(delivered).toEqual([
+ ['thinking', 't/1:ab'],
+ ['content', 't/1:c'],
+ ['content', 't/2:d'],
+ ['content', 'u/2:e'],
+ ['content', 't/2:f'],
+ ]);
+ });
+
+ it('flushes synchronously on demand and cancels the scheduled frame', () => {
+ const frames = manualScheduler();
+ const deliver = vi.fn();
+ const coalescer = createChatDeltaCoalescer(deliver, frames.schedule);
+
+ coalescer.push('content', delta({ delta: 'x' }));
+ expect(frames.scheduled).toBe(true);
+ coalescer.flush();
+ expect(deliver).toHaveBeenCalledTimes(1);
+ expect(frames.scheduled).toBe(false);
+ });
+});
+
+describe('withCoalescedDeltas', () => {
+ it('flushes pending text before any other event, so a tool call lands after its text', () => {
+ const frames = manualScheduler();
+ const order: string[] = [];
+ const { listeners } = withCoalescedDeltas(
+ {
+ onTextDelta: (event: CoalescibleDelta) => order.push(`text:${event.delta}`),
+ onToolCall: () => order.push('tool_call'),
+ },
- frames.schedule
++ { schedule: frames.schedule }
+ );
+
+ listeners.onTextDelta?.(delta({ delta: 'Let me ' }));
+ listeners.onTextDelta?.(delta({ delta: 'check.' }));
+ (listeners.onToolCall as () => void)();
+
+ expect(order).toEqual(['text:Let me check.', 'tool_call']);
+ });
+
+ it('dispose delivers whatever is still queued', () => {
+ const frames = manualScheduler();
+ const onThinkingDelta = vi.fn();
- const { listeners, dispose } = withCoalescedDeltas({ onThinkingDelta }, frames.schedule);
++ const { listeners, dispose } = withCoalescedDeltas(
++ { onThinkingDelta },
++ { schedule: frames.schedule }
++ );
+
+ listeners.onThinkingDelta?.(delta({ delta: 'hmm' }));
+ dispose();
+ expect(onThinkingDelta).toHaveBeenCalledWith(delta({ delta: 'hmm' }));
+ });
++
++ it('filters redelivered frames before merging, and the merge carries the last seq', () => {
++ const frames = manualScheduler();
++ const onTextDelta = vi.fn();
++ let lastSeq = 0;
++ const { listeners } = withCoalescedDeltas<
++ CoalescibleDelta & { seq: number },
++ { onTextDelta: typeof onTextDelta }
++ >(
++ { onTextDelta },
++ {
++ schedule: frames.schedule,
++ accept: event => {
++ if (event.seq <= lastSeq) return false;
++ lastSeq = event.seq;
++ return true;
++ },
++ }
++ );
++
++ listeners.onTextDelta({ ...delta({ delta: 'Hel' }), seq: 1 });
++ listeners.onTextDelta({ ...delta({ delta: 'lo' }), seq: 2 });
++ listeners.onTextDelta({ ...delta({ delta: 'Hel' }), seq: 1 }); // redelivery, same frame
++ frames.frame();
++
++ expect(onTextDelta).toHaveBeenCalledTimes(1);
++ expect(onTextDelta).toHaveBeenCalledWith(expect.objectContaining({ delta: 'Hello', seq: 2 }));
++ });
+});
diff --cc app/src/services/chatDeltaCoalescer.ts
index 25680d69ab,0000000000..6257c34319
mode 100644,000000..100644
--- a/app/src/services/chatDeltaCoalescer.ts
+++ b/app/src/services/chatDeltaCoalescer.ts
@@@ -1,142 -1,0 +1,162 @@@
+/**
+ * Coalesce streamed text/thinking deltas into at most one store update per
+ * animation frame.
+ *
+ * Every socket delta used to be its own Redux dispatch, and every dispatch
+ * re-projected and re-rendered the live assistant tail — a token rate well
+ * above the display's frame rate spent most of that work on frames nobody saw,
+ * and that backlog is what the stream stuttered on. A frame is the natural
+ * unit: nothing is painted between two of them anyway.
+ *
+ * ## Ordering is preserved, not traded away
+ *
+ * - Only ADJACENT deltas for the same `(thread, request, round, channel)` are
+ * merged. A delta for a different key closes the current run, so interleaved
+ * thinking and content — or two threads streaming at once — replay in the
+ * exact order they arrived.
+ * - Every other chat event must call {@link ChatDeltaCoalescer.flush} before it
+ * is handled. A `tool_call` therefore always lands after the text that
+ * preceded it, which is the order the transcript records (and the order the
+ * parts render in).
++ *
++ * ## Redelivery is filtered before merging, not after
++ *
++ * The socket redelivers frames, and the provider drops a delta whose `seq` it
++ * has already applied. That check has to see every frame on its own: once two
++ * deltas are merged, a redelivered one inside the same frame is already part
++ * of the text. So the filter ({@link CoalesceOptions.accept}) runs at push
++ * time, and a merged delta carries its LAST frame's fields (its `seq`), which
++ * is the one a later redelivery must compare against.
+ */
+
+export type DeltaChannel = 'content' | 'thinking';
+
+export interface CoalescibleDelta {
+ thread_id: string;
+ request_id: string;
+ round: number;
+ delta: string;
+}
+
+type Pending<E extends CoalescibleDelta> = { channel: DeltaChannel; event: E };
+
+/** Schedules one flush; returns a canceller. */
+export type FlushScheduler = (flush: () => void) => () => void;
+
+/**
+ * The next animation frame, or a short timer when there is no frame to wait
+ * for (a hidden window throttles rAF to nothing, and the stream must not stall
+ * there — it would all land at once on refocus).
+ */
+export const frameScheduler: FlushScheduler = flush => {
+ let done = false;
+ const run = () => {
+ if (done) return;
+ done = true;
+ flush();
+ };
+ const frames = typeof window === 'undefined' ? undefined : window;
+ const raf =
+ typeof frames?.requestAnimationFrame === 'function'
+ ? frames.requestAnimationFrame(run)
+ : undefined;
+ const timer = setTimeout(run, 50);
+ return () => {
+ done = true;
+ if (raf !== undefined) frames?.cancelAnimationFrame(raf);
+ clearTimeout(timer);
+ };
+};
+
+export interface ChatDeltaCoalescer<E extends CoalescibleDelta> {
+ /** Queue a delta; merged into the previous one when the key matches. */
+ push: (channel: DeltaChannel, event: E) => void;
+ /** Deliver everything queued, in arrival order, now. */
+ flush: () => void;
+ /** Drop the scheduled flush (queued deltas are delivered first). */
+ dispose: () => void;
+}
+
+export function createChatDeltaCoalescer<E extends CoalescibleDelta>(
+ deliver: (channel: DeltaChannel, event: E) => void,
+ schedule: FlushScheduler = frameScheduler
+): ChatDeltaCoalescer<E> {
+ let queue: Pending<E>[] = [];
+ let cancel: (() => void) | null = null;
+
+ const flush = () => {
+ cancel?.();
+ cancel = null;
+ if (queue.length === 0) return;
+ const drained = queue;
+ queue = [];
+ for (const item of drained) deliver(item.channel, item.event);
+ };
+
+ const push = (channel: DeltaChannel, event: E) => {
+ const last = queue[queue.length - 1];
+ if (
+ last &&
+ last.channel === channel &&
+ last.event.thread_id === event.thread_id &&
+ last.event.request_id === event.request_id &&
+ last.event.round === event.round
+ ) {
- last.event = { ...last.event, delta: `${last.event.delta}${event.delta}` };
++ last.event = { ...event, delta: `${last.event.delta}${event.delta}` };
+ } else {
+ queue.push({ channel, event });
+ }
+ cancel ??= schedule(flush);
+ };
+
+ return { push, flush, dispose: flush };
+}
+
+type DeltaListeners<E extends CoalescibleDelta> = {
+ onTextDelta?: (event: E) => void;
+ onThinkingDelta?: (event: E) => void;
+};
+
++export interface CoalesceOptions<E extends CoalescibleDelta> {
++ /** When to flush; one animation frame by default. */
++ schedule?: FlushScheduler;
++ /** Drop a delta before it is merged (e.g. a redelivered `seq`). */
++ accept?: (event: E) => boolean;
++}
++
+/**
+ * Wrap a chat listener set so text/thinking deltas are coalesced per frame and
+ * every other listener flushes them first (see the ordering note above).
+ * `dispose` delivers anything still queued and stops the scheduled flush.
+ */
+export function withCoalescedDeltas<E extends CoalescibleDelta, L extends DeltaListeners<E>>(
+ listeners: L,
- schedule: FlushScheduler = frameScheduler
++ { schedule = frameScheduler, accept }: CoalesceOptions<E> = {}
+): { listeners: L; dispose: () => void } {
+ const coalescer = createChatDeltaCoalescer<E>((channel, event) => {
+ if (channel === 'content') listeners.onTextDelta?.(event);
+ else listeners.onThinkingDelta?.(event);
+ }, schedule);
+ const wrapped: Record<string, unknown> = {};
+ for (const [name, listener] of Object.entries(listeners as Record<string, unknown>)) {
+ if (typeof listener !== 'function') {
+ wrapped[name] = listener;
+ continue;
+ }
+ if (name === 'onTextDelta') {
- wrapped[name] = (event: E) => coalescer.push('content', event);
++ wrapped[name] = (event: E) => {
++ if (!accept || accept(event)) coalescer.push('content', event);
++ };
+ } else if (name === 'onThinkingDelta') {
- wrapped[name] = (event: E) => coalescer.push('thinking', event);
++ wrapped[name] = (event: E) => {
++ if (!accept || accept(event)) coalescer.push('thinking', event);
++ };
+ } else {
+ wrapped[name] = (...args: unknown[]) => {
+ coalescer.flush();
+ return (listener as (...a: unknown[]) => unknown)(...args);
+ };
+ }
+ }
+ return { listeners: wrapped as L, dispose: coalescer.dispose };
+}
diff --cc app/src/store/__tests__/chatRuntimeSlice.liveParity.test.ts
index 8ebc41e5ca,0000000000..3e994c0d46
mode 100644,000000..100644
--- a/app/src/store/__tests__/chatRuntimeSlice.liveParity.test.ts
+++ b/app/src/store/__tests__/chatRuntimeSlice.liveParity.test.ts
@@@ -1,232 -1,0 +1,234 @@@
+/**
+ * Reducer-level guards for the live half of live/history parity: the rows and
+ * transcript pointers the socket stream builds must have the shape — and keep
+ * the slots — that a reopened thread shows, and settling a turn must be one
+ * transition. The end-to-end version is `providers/__tests__/liveHistoryParity`.
+ */
+import type { UnknownAction } from '@reduxjs/toolkit';
+import { describe, expect, it } from 'vitest';
+
+import reducer, {
+ beginInferenceTurn,
+ liveTurnStarted,
+ markInferenceTurnStreaming,
+ registerParallelRequest,
+ setInferenceStatusForThread,
+ streamDeltaReceived,
+ subagentSpawned,
+ toolArgsDeltaReceived,
+ toolCallReceived,
+ turnSettled,
+} from '../chatRuntimeSlice';
+
+type ChatRuntimeState = ReturnType<typeof reducer>;
+
+const T = 'thread-1';
+
+function run(actions: UnknownAction[], from?: ChatRuntimeState): ChatRuntimeState {
+ return actions.reduce<ChatRuntimeState>(
+ (state, action) => reducer(state, action),
+ from ?? reducer(undefined, { type: '@@init' })
+ );
+}
+
+function pointers(state: ChatRuntimeState): string[] {
+ return (state.processingByThread[T] ?? []).flatMap(item =>
+ item.kind === 'toolCall' ? [item.callId] : []
+ );
+}
+
+describe('toolCallReceived adopts the row a tool_args_delta minted', () => {
+ it('takes over the args-delta row under the real id instead of pushing a duplicate', () => {
+ const state = run([
+ toolArgsDeltaReceived({ threadId: T, round: 1, delta: '{"q":1}', toolName: 'search' }),
+ toolCallReceived({ threadId: T, round: 1, toolName: 'search', toolCallId: 'call-1' }),
+ ]);
+ const rows = state.toolTimelineByThread[T] ?? [];
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toMatchObject({ id: 'call-1', argsBuffer: '{"q":1}', seq: 0 });
+ expect(pointers(state)).toEqual(['call-1']);
+ });
+
+ it('adopts it for an id-less call too', () => {
+ const state = run([
+ toolArgsDeltaReceived({ threadId: T, round: 1, delta: '{}', toolName: 'search' }),
+ toolCallReceived({ threadId: T, round: 1, toolName: 'search' }),
+ ]);
+ expect(state.toolTimelineByThread[T]).toHaveLength(1);
+ expect(pointers(state)).toHaveLength(1);
+ });
+
+ it('does not adopt a row an earlier call already owns', () => {
+ const state = run([
+ toolCallReceived({ threadId: T, round: 1, toolName: 'search', toolCallId: 'call-1' }),
+ toolCallReceived({ threadId: T, round: 1, toolName: 'search', toolCallId: 'call-2' }),
+ ]);
+ expect((state.toolTimelineByThread[T] ?? []).map(row => row.id)).toEqual(['call-1', 'call-2']);
+ });
+
+ it('keeps the args the tool_call event carries, as a reload shows them', () => {
+ const state = run([
+ toolCallReceived({
+ threadId: T,
+ round: 1,
+ toolName: 'search',
+ toolCallId: 'call-1',
+ args: { q: 'agenda' },
+ }),
+ ]);
+ expect(state.toolTimelineByThread[T]?.[0]?.argsBuffer).toBe('{"q":"agenda"}');
+ });
+
+ it('never overwrites args that streamed', () => {
+ const state = run([
+ toolArgsDeltaReceived({
+ threadId: T,
+ round: 1,
+ delta: '{"q":"streamed"}',
+ toolName: 'search',
+ toolCallId: 'call-1',
+ }),
+ toolCallReceived({
+ threadId: T,
+ round: 1,
+ toolName: 'search',
+ toolCallId: 'call-1',
+ args: { q: 'event' },
+ }),
+ ]);
+ expect(state.toolTimelineByThread[T]?.[0]?.argsBuffer).toBe('{"q":"streamed"}');
+ });
+});
+
+describe('subagentSpawned promotes the spawn row in place', () => {
+ const spawned = () =>
+ run([
+ toolCallReceived({ threadId: T, round: 1, toolName: 'shell', toolCallId: 'call-a' }),
+ toolCallReceived({
+ threadId: T,
+ round: 1,
+ toolName: 'spawn_subagent',
+ toolCallId: 'call-spawn',
+ }),
+ toolCallReceived({ threadId: T, round: 1, toolName: 'shell', toolCallId: 'call-b' }),
+ subagentSpawned({
+ threadId: T,
+ round: 1,
+ rowId: `${T}:subagent:sub-1:researcher`,
+ taskId: 'sub-1',
+ agentId: 'researcher',
+ }),
+ ]);
+
+ it('takes the spawn row’s slot and seq rather than moving to the end', () => {
+ const rows = spawned().toolTimelineByThread[T] ?? [];
+ expect(rows.map(row => row.id)).toEqual(['call-a', `${T}:subagent:sub-1:researcher`, 'call-b']);
+ expect(rows.map(row => row.seq)).toEqual([0, 1, 2]);
+ });
+
+ it('re-points the transcript at the delegation row, so it is not dangling', () => {
+ expect(pointers(spawned())).toEqual(['call-a', `${T}:subagent:sub-1:researcher`, 'call-b']);
+ });
+});
+
+describe('turnSettled', () => {
+ const live = () =>
+ run([
+ beginInferenceTurn({ threadId: T }),
+ markInferenceTurnStreaming({ threadId: T }),
+ liveTurnStarted({ threadId: T, requestId: 'req-1' }),
+ setInferenceStatusForThread({
+ threadId: T,
+ status: { phase: 'tool_use', iteration: 1, maxIterations: 5 },
+ }),
+ toolCallReceived({ threadId: T, round: 1, toolName: 'shell', toolCallId: 'call-a' }),
+ streamDeltaReceived({
+ threadId: T,
+ requestId: 'req-1',
+ round: 2,
+ delta: 'Done.',
+ channel: 'content',
+ }),
+ ]);
+
- it('freezes the live trail under the request id, running rows settled', () => {
++ it('freezes the live trail under the request id, without inventing an outcome', () => {
+ const settled = reducer(live(), turnSettled({ threadId: T, requestId: 'req-1' }));
+ const frozen = settled.settledTurnsByThread[T]?.['req-1'];
- expect(frozen?.timeline.map(row => [row.id, row.status])).toEqual([['call-a', 'success']]);
++ // A row with no result at `chat_done` stays running; the core projection's
++ // terminal status is overlaid at render (`buildRuntimeMessages`).
++ expect(frozen?.timeline.map(row => [row.id, row.status])).toEqual([['call-a', 'running']]);
+ expect(frozen?.transcript.map(item => item.kind)).toEqual(['toolCall', 'narration']);
+ });
+
+ it('ends the tail and everything it drew in the same transition', () => {
+ const settled = reducer(live(), turnSettled({ threadId: T, requestId: 'req-1' }));
+ expect(settled.inferenceTurnLifecycleByThread[T]).toBeUndefined();
+ expect(settled.streamingAssistantByThread[T]).toBeUndefined();
+ expect(settled.inferenceStatusByThread[T]).toBeUndefined();
+ expect(settled.liveRequestIdByThread[T]).toBeUndefined();
+ });
+
+ it('falls back to the live-turn id when the event carries none', () => {
+ const settled = reducer(live(), turnSettled({ threadId: T }));
+ expect(settled.settledTurnsByThread[T]?.['req-1']).toBeDefined();
+ });
+
+ it('keeps a bounded number of frozen turns per thread', () => {
+ let state = live();
+ for (let n = 0; n < 30; n += 1) {
+ state = run(
+ [
+ toolCallReceived({ threadId: T, round: 1, toolName: 'shell', toolCallId: `c-${n}` }),
+ turnSettled({ threadId: T, requestId: `req-${n}` }),
+ ],
+ state
+ );
+ }
+ const kept = Object.keys(state.settledTurnsByThread[T] ?? {});
+ expect(kept).toHaveLength(20);
+ expect(kept.at(-1)).toBe('req-29');
+ });
+});
+
+describe('turn boundaries', () => {
+ it('a newer live turn is not torn down by the previous turn settling late', () => {
+ const state = run([
+ beginInferenceTurn({ threadId: T }),
+ markInferenceTurnStreaming({ threadId: T }),
+ liveTurnStarted({ threadId: T, requestId: 'req-2' }),
+ toolCallReceived({ threadId: T, round: 1, toolName: 'shell', toolCallId: 'call-2' }),
+ turnSettled({ threadId: T, requestId: 'req-1' }),
+ ]);
+ expect(state.inferenceTurnLifecycleByThread[T]).toBe('streaming');
+ expect(state.liveRequestIdByThread[T]).toBe('req-2');
+ expect(state.toolTimelineByThread[T]?.[0]?.status).toBe('running');
+ expect(state.settledTurnsByThread[T]?.['req-1']).toBeUndefined();
+ });
+
+ it('a new send starts from an empty transcript, not the last turn’s', () => {
+ const state = run([
+ streamDeltaReceived({
+ threadId: T,
+ requestId: 'req-1',
+ round: 1,
+ delta: 'Last turn said this.',
+ channel: 'content',
+ }),
+ turnSettled({ threadId: T, requestId: 'req-1' }),
+ beginInferenceTurn({ threadId: T }),
+ ]);
+ expect(state.processingByThread[T]).toBeUndefined();
+ // …while the settled turn keeps the trail it rendered with.
+ expect(state.settledTurnsByThread[T]?.['req-1']?.transcript).toHaveLength(1);
+ });
+});
+
+describe('liveTurnStarted', () => {
+ it('ignores a parallel (forked) request, which never owns the tail', () => {
+ const state = run([
+ registerParallelRequest({ threadId: T, requestId: 'fork' }),
+ liveTurnStarted({ threadId: T, requestId: 'fork' }),
+ ]);
+ expect(state.liveRequestIdByThread[T]).toBeUndefined();
+ });
+});
diff --cc app/src/store/chatRuntimeSlice.ts
index 0fdb5d4fe9,551474a966..11df2a7dab
--- a/app/src/store/chatRuntimeSlice.ts
+++ b/app/src/store/chatRuntimeSlice.ts
@@@ -1362,37 -1309,22 +1362,42 @@@ const chatRuntimeSlice = createSlice(
// fallback disagreed.
const toolCallId = action.payload.toolCallId || undefined;
const entries = (state.toolTimelineByThread[threadId] ??= []);
- const existingIdx = toolCallId ? entries.findIndex(e => e.id === toolCallId) : -1;
+ const list = (state.processingByThread[threadId] ??= []);
+ let existingIdx = toolCallId ? entries.findIndex(e => e.id === toolCallId) : -1;
+ // A `tool_args_delta` can land before its `tool_call` and mint the row
+ // under a fallback id. Adopt that row rather than pushing a second one
+ // for the same call: the duplicate rendered as two cards live (one stuck
+ // running) and as one on reload.
+ if (existingIdx < 0) {
+ existingIdx = entries.findIndex(
+ e =>
+ e.id.startsWith(`${threadId}:${round}:`) &&
+ e.round === round &&
+ e.status === 'running' &&
+ (e.name === toolName || e.name === '') &&
+ !list.some(item => item.kind === 'toolCall' && item.callId === e.id)
+ );
+ if (existingIdx >= 0 && toolCallId) entries[existingIdx].id = toolCallId;
+ }
// Stable row id, shared with the processing-transcript tool pointer so the
// panel can resolve the row by `callId`.
- const rowId = toolCallId ?? `${threadId}:${round}:${entries.length}:${toolName}`;
+ const rowId =
+ existingIdx >= 0
+ ? entries[existingIdx].id
+ : (toolCallId ?? `${threadId}:${round}:${entries.length}:${toolName}`);
if (existingIdx >= 0) {
const prev = entries[existingIdx];
+ // A settled row stays settled. A replayed/late `tool_call` for a call
+ // whose result already landed used to flip it back to `running`, and
+ // nothing would ever settle it again.
+ const settled =
+ prev.status === 'success' || prev.status === 'error' || prev.status === 'cancelled';
entries[existingIdx] = decorateEntry({
...prev,
name: toolName,
round,
- status: 'running',
+ status: settled ? prev.status : 'running',
+ argsBuffer: prev.argsBuffer ?? argsBuffer,
displayName: displayLabel ?? prev.displayName,
detail: displayDetail ?? prev.detail,
});
@@@ -2198,83 -2127,8 +2223,84 @@@
state.inferenceTurnLifecycleByThread[action.payload.threadId] = 'streaming';
}
},
+ /** Record the primary turn now live on a thread; see {@link ChatRuntimeState.liveRequestIdByThread}. */
+ liveTurnStarted: (state, action: PayloadAction<{ threadId: string; requestId: string }>) => {
+ const { threadId, requestId } = action.payload;
+ if (!requestId || state.parallelRequestThreads[requestId] !== undefined) return;
+ state.liveRequestIdByThread[threadId] = requestId;
+ },
+ /**
+ * Settle the live turn in ONE store transition.
+ *
+ * Before this existed `chat_done` settled a turn in four separate steps
+ * (clear the streaming buffer, settle the rows, append the reply after an
+ * RPC, then end the lifecycle after another), and each step was a render
+ * of an intermediate state nobody designed: the answer vanished, then
+ * appeared ABOVE its own tools while the tail was pushed one slot down and
+ * remounted, then the tools moved back and remounted again collapsed.
+ *
+ * Here the reply is already in the thread cache (appended while the tail
+ * still stood in for it — `buildRuntimeMessages` hides the live turn's own
+ * rows while its tail is minted), so ending the tail and revealing the row
+ * happen in the same render, at the same index, with the same parts:
+ *
- * - the live rows and transcript are frozen under the turn's request id
- * (running rows settled to `success`: `chat_done` means the turn
- * finished), which is what the settled message renders from;
++ * - the live rows and transcript are frozen under the turn's request id,
++ * which is what the settled message renders from;
+ * - the streaming buffer, status line, parked gates and live-turn id are
+ * cleared;
+ * - the lifecycle ends, so the tail is no longer minted.
+ *
+ * Queued follow-ups are deliberately left alone: they are flushed after the
+ * reply and dropped by {@link endInferenceTurn}, as before.
+ */
+ turnSettled: (state, action: PayloadAction<{ threadId: string; requestId?: string }>) => {
+ const { threadId } = action.payload;
+ const live = state.liveRequestIdByThread[threadId];
+ // A newer turn is already live on the thread (a queued follow-up the
+ // core started while this turn's reply was still being persisted). The
+ // live state is that turn's now: freezing or clearing it would erase the
+ // turn that is streaming. This turn's reply is already in the cache and
+ // its trail comes from the core projection.
+ if (action.payload.requestId && live && live !== action.payload.requestId) {
+ turnStateLog(
+ 'turn settle superseded thread=%s request=%s live=%s',
+ threadId,
+ action.payload.requestId,
+ live
+ );
+ return;
+ }
+ const requestId = action.payload.requestId ?? live;
+ if (requestId) {
- const timeline = (state.toolTimelineByThread[threadId] ?? []).map(entry =>
- entry.status === 'running' ? { ...entry, status: 'success' as const } : entry
- );
++ // Rows are frozen as they are: one still running at `chat_done` has no
++ // result, and inventing `success` for it is the wrong answer. The core
++ // projection's terminal status for the same row id is overlaid at
++ // render (`buildRuntimeMessages`), which keeps the row's identity.
++ const timeline = [...(state.toolTimelineByThread[threadId] ?? [])];
+ const transcript = state.processingByThread[threadId] ?? [];
+ if (timeline.length > 0 || transcript.length > 0) {
+ const turns = (state.settledTurnsByThread[threadId] ??= {});
+ turns[requestId] = { timeline, transcript: [...transcript] };
+ // Bounded: only turns settled while this view was open need a frozen
+ // copy; older ones render from the core projection like any reload.
+ const keys = Object.keys(turns);
+ for (const stale of keys.slice(0, Math.max(0, keys.length - SETTLED_TURNS_KEPT))) {
+ delete turns[stale];
+ }
+ }
+ state.toolTimelineByThread[threadId] = timeline;
+ }
+ turnStateLog('turn settled thread=%s request=%s', threadId, requestId ?? 'none');
+ delete state.streamingAssistantByThread[threadId];
+ delete state.inferenceStatusByThread[threadId];
+ delete state.pendingApprovalByThread[threadId];
+ delete state.pendingPlanReviewByThread[threadId];
+ delete state.liveRequestIdByThread[threadId];
+ delete state.inferenceTurnLifecycleByThread[threadId];
+ },
endInferenceTurn: (state, action: PayloadAction<{ threadId: string }>) => {
delete state.inferenceTurnLifecycleByThread[action.payload.threadId];
+ delete state.liveRequestIdByThread[action.payload.threadId];
// The turn finished, so any follow-ups queued behind it are now being
// dispatched by the backend — drop the optimistic pills; the queued
// texts reappear as real messages on their dispatched turns.
diff --cc crates/openhuman-core/src/threads/transcript_view/mod.rs
index 7362f25b98,d94ae0ad7e..d825b320e7
--- a/crates/openhuman-core/src/threads/transcript_view/mod.rs
+++ b/crates/openhuman-core/src/threads/transcript_view/mod.rs
@@@ -6,7 -6,8 +6,9 @@@
mod cache;
mod project;
+mod prompt_tools;
+ mod resolve;
+ mod subagents;
pub mod types;
use std::path::Path;
diff --cc crates/openhuman-core/src/threads/transcript_view/project.rs
index 0caacde005,3aa9924a3d..aa936fc137
--- a/crates/openhuman-core/src/threads/transcript_view/project.rs
+++ b/crates/openhuman-core/src/threads/transcript_view/project.rs
@@@ -11,7 -11,8 +11,9 @@@ use std::path::{Path, PathBuf}
use tinyagents_session::transcript::{self, CompactionMarker, DisplayMessage, DisplayRecord};
+use super::prompt_tools::{self, CallRegistry, PromptToolResult};
+ use super::resolve;
+ use super::subagents;
use super::types::{DisplayItem, ProjectedTranscript, ToolCallFailure, ToolCallStatus};
const LOG_PREFIX: &str = "[threads][transcript]";
@@@ -301,221 -135,246 +136,297 @@@ pub fn project_from_files
/// - System lines are dropped (they carry the tool-policy preamble and other
/// scaffolding that must never render as a chat item).
/// - `reasoning_content` on an assistant line becomes a [`DisplayItem::Reasoning`]
- /// preceding its message.
- /// - Assistant `tool_calls` register pending [`DisplayItem::ToolCall`]s; a later
+ /// preceding its message, carrying the same `iteration`.
+ /// - An assistant line's tool calls come from its native provider envelope.
+ /// Only a line that is *not* an envelope falls back to the calls recorded on
+ /// its usage (legacy text-dialect rows) — and never to a call id already
+ /// projected, which is how an aggregate list copied onto a final answer
+ /// would otherwise duplicate every call of the turn.
+ /// - Each call registers a pending [`DisplayItem::ToolCall`]; a later
/// `role:"tool"` line pairs to one by id, falling back to FIFO order.
- /// - Prompt-guided tool rounds (no per-line `tool_calls`, results folded into a
- /// `[Tool results]` user line) project to the same shape: see
++/// - A prompt-guided round (calls in the visible text, results folded into one
++/// `[Tool results]` user line) projects to the same shape: see
+/// [`prompt_tools`].
/// - Interrupted partials and compaction markers pass through as their items.
/// - A [`DisplayItem::TurnBoundary`] is emitted whenever `request_id` changes.
pub fn project_records(records: &[DisplayRecord]) -> Vec<DisplayItem> {
- let mut items: Vec<DisplayItem> = Vec::new();
- // Pending tool calls awaiting a result line: (call_id, index into `items`).
- let mut pending: VecDeque<(String, usize)> = VecDeque::new();
- let mut last_request_id: Option<String> = None;
- let mut calls = ProjectedCalls {
- registry: CallRegistry::from_records(records),
- emitted: HashSet::new(),
- let mut projector = Projector::default();
- for record in records {
++ let mut projector = Projector {
++ calls: CallRegistry::from_records(records),
++ ..Projector::default()
+ };
-
+ for (index, record) in records.iter().enumerate() {
match record {
DisplayRecord::Message(msg) => {
- maybe_emit_turn_boundary(msg, &mut last_request_id, &mut items);
+ projector.turn_boundary(msg);
+ // A prompt-guided round's results are on the NEXT line; they are
+ // the only record of which calls this assistant line issued.
- let next_results = match records.get(index + 1) {
++ projector.next_results = match records.get(index + 1) {
+ Some(DisplayRecord::Message(next)) => prompt_tools::parse_tool_results(next),
+ _ => None,
+ };
- project_message(msg, next_results, &mut items, &mut pending, &mut calls);
+ projector.message(msg);
}
DisplayRecord::Compaction(marker) => {
- project_compaction(marker, &mut items);
+ project_compaction(marker, &mut projector.items);
// A compaction supersedes prior context; drop stale pending
// pairings so a post-compaction result never binds to them.
- pending.clear();
+ projector.pending.clear();
}
}
}
- items
- }
-
- fn maybe_emit_turn_boundary(
- msg: &DisplayMessage,
- last_request_id: &mut Option<String>,
- items: &mut Vec<DisplayItem>,
- ) {
- let Some(rid) = msg.request_id.as_deref() else {
- return;
- };
- if last_request_id.as_deref() != Some(rid) {
- items.push(DisplayItem::TurnBoundary {
- request_id: rid.to_string(),
- });
- *last_request_id = Some(rid.to_string());
- }
+ projector.items
}
- /// Which calls the projection has already placed, and where to look them up.
- struct ProjectedCalls {
- registry: CallRegistry,
- /// Call ids already emitted as a [`DisplayItem::ToolCall`]. A prompt-guided
- /// turn records its calls again on the answer line; those are not new.
- emitted: HashSet<String>,
+ #[derive(Default)]
+ struct Projector {
+ items: Vec<DisplayItem>,
+ /// Pending tool calls awaiting a result line: (call_id, index into `items`).
+ pending: VecDeque<(String, usize)>,
+ last_request_id: Option<String>,
+ /// Every tool-call id already projected, so a row repeating calls issued
+ /// earlier (the aggregate usage list) does not render them twice.
+ seen_call_ids: HashSet<String>,
+ /// The model-call ordinal of the last assistant row in the current turn —
+ /// the fallback `iteration` for rows written without one.
+ step: u32,
++ /// Every call the file records, for resolving a prompt-guided round.
++ calls: CallRegistry,
++ /// Result blocks of the line after the one being projected, when that line
++ /// is a prompt-guided `[Tool results]` turn.
++ next_results: Option<Vec<PromptToolResult>>,
}
- fn project_message(
- msg: &DisplayMessage,
- next_results: Option<Vec<PromptToolResult>>,
- items: &mut Vec<DisplayItem>,
- pending: &mut VecDeque<(String, usize)>,
- calls: &mut ProjectedCalls,
- ) {
- // Interrupted partial: display-only, carries its own thinking.
- if msg.interrupted {
- items.push(DisplayItem::InterruptedPartial {
- text: msg.message.content.clone(),
- thinking: msg.reasoning_content.clone(),
- });
- return;
+ impl Projector {
+ fn turn_boundary(&mut self, msg: &DisplayMessage) {
+ let Some(rid) = msg.request_id.as_deref() else {
+ return;
+ };
+ if self.last_request_id.as_deref() != Some(rid) {
+ self.items.push(DisplayItem::TurnBoundary {
+ request_id: rid.to_string(),
+ });
+ self.last_request_id = Some(rid.to_string());
+ self.step = 0;
+ self.seen_call_ids.clear();
+ }
}
- match msg.message.role.as_str() {
- "system" => {
- // Scaffolding (tool-policy preamble, etc.) — never a display item.
- log::debug!("{LOG_PREFIX} sanitize: dropped system line from projection");
+ fn message(&mut self, msg: &DisplayMessage) {
+ // Interrupted partial: display-only, carries its own thinking.
+ if msg.interrupted {
+ self.items.push(DisplayItem::InterruptedPartial {
+ text: msg.message.content.clone(),
+ thinking: msg.reasoning_content.clone(),
+ });
+ return;
}
- "user" => {
- if let Some(blocks) = prompt_tools::parse_tool_results(msg) {
- // Tool plumbing, not something the user said.
- for block in blocks {
- pair_tool_result(block.id.as_deref(), block.body, false, None, items, pending);
+
+ match msg.message.role.as_str() {
+ "system" => {
+ // Scaffolding (tool-policy preamble, etc.) — never a display item.
+ log::debug!("{LOG_PREFIX} sanitize: dropped system line from projection");
+ }
+ "user" => {
++ if let Some(blocks) = prompt_tools::parse_tool_results(msg) {
++ // Tool plumbing, not something the user said.
++ for block in blocks {
++ self.pair_result(block.id, block.body, ToolCallStatus::Success, None);
++ }
++ return;
+ }
- return;
+ // A legacy turn without request ids still restarts the step
+ // count at its prompt.
+ self.step = 0;
+ self.seen_call_ids.clear();
+ let raw = msg.message.content.clone();
+ let sanitized = sanitize_user_content(&raw);
+ if sanitized.is_some() {
+ log::debug!(
+ "{LOG_PREFIX} sanitize: stripped injected prefix from user message"
+ );
+ }
+ self.items.push(DisplayItem::UserMessage {
+ content: raw,
+ display_content: sanitized,
+ request_id: msg.request_id.clone(),
+ });
}
- let raw = msg.message.content.clone();
- let sanitized = sanitize_user_content(&raw);
- if sanitized.is_some() {
- log::debug!("{LOG_PREFIX} sanitize: stripped injected prefix from user message");
+ "assistant" => self.assistant(msg),
+ "tool" => self.tool_result(msg),
+ other => {
+ log::debug!("{LOG_PREFIX} projecting unknown role {other:?} as assistant message");
+ self.items.push(DisplayItem::AssistantMessage {
+ content: msg.message.content.clone(),
+ interim: false,
+ request_id: msg.request_id.clone(),
+ model: msg.turn_usage.as_ref().map(|tu| tu.model.clone()),
+ iteration: msg.iteration,
+ });
}
- items.push(DisplayItem::UserMessage {
- content: raw,
- display_content: sanitized,
- request_id: msg.request_id.clone(),
- });
}
- "assistant" => project_assistant(msg, next_results, items, pending, calls),
- "tool" => project_tool_result(msg, items, pending),
- other => {
- log::debug!("{LOG_PREFIX} projecting unknown role {other:?} as assistant message");
- items.push(DisplayItem::AssistantMessage {
- content: msg.message.content.clone(),
- interim: false,
+ }
+
+ fn assistant(&mut self, msg: &DisplayMessage) {
+ // Rows the writer stamped keep their own number; earlier writers only
+ // stamped the final row, so unstamped rows count up within the turn.
+ let iteration = msg.iteration.unwrap_or(self.step + 1);
+ self.step = iteration;
+
+ // Reasoning precedes the message it belongs to.
+ if let Some(reasoning) = msg.reasoning_content.as_deref() {
+ if !reasoning.trim().is_empty() {
+ self.items.push(DisplayItem::Reasoning {
+ text: reasoning.to_string(),
+ iteration: Some(iteration),
+ });
+ }
+ }
+
+ let native_envelope = parse_native_tool_envelope(&msg.message.content);
+ let tool_calls: Vec<NativeToolCall> = match &native_envelope {
+ Some((_, calls)) => calls.clone(),
+ None => {
+ let recorded: Vec<NativeToolCall> = msg
+ .turn_usage
+ .as_ref()
+ .map(|tu| {
+ tu.tool_calls
+ .iter()
+ .map(|call| {
+ (call.id.clone(), call.name.clone(), call.arguments.clone())
+ })
+ .collect()
+ })
+ .unwrap_or_default();
+ let total = recorded.len();
+ let fresh: Vec<NativeToolCall> = recorded
+ .into_iter()
+ .filter(|(id, _, _)| id.is_empty() || !self.seen_call_ids.contains(id))
+ .collect();
+ if fresh.len() < total {
+ log::debug!(
+ "{LOG_PREFIX} dropped {} already-projected tool call(s) repeated on an assistant row iteration={iteration}",
+ total - fresh.len()
+ );
+ }
+ fresh
+ }
+ };
++ // A prompt-guided line records no calls of its own; the `[Tool results]`
++ // line after it names the calls it made.
++ let tool_calls = match self.next_results.take() {
++ Some(blocks) if tool_calls.is_empty() => {
++ let inferred = self
++ .calls
++ .calls_for(&msg.request_id, &blocks, &self.seen_call_ids);
++ log::debug!(
++ "{LOG_PREFIX} prompt-guided round: {} call(s) inferred from the next [Tool results] line iteration={iteration}",
++ inferred.len()
++ );
++ inferred
++ }
++ _ => tool_calls,
++ };
+ let interim = !tool_calls.is_empty();
+
+ // Native tool-call turns are persisted as their provider envelope so they
+ // can be replayed byte-faithfully. The display projection needs only the
+ // envelope's visible `content`; rendering/sanitizing the whole JSON object
+ // makes the narration disappear (and risks showing raw tool JSON).
+ let visible_content = native_envelope
+ .map(|(content, _)| content)
+ .unwrap_or_else(|| msg.message.content.clone());
+
+ // The assistant's prose (if any) shows before its tool calls.
+ if !visible_content.trim().is_empty() {
+ self.items.push(DisplayItem::AssistantMessage {
+ content: visible_content,
+ interim,
request_id: msg.request_id.clone(),
model: msg.turn_usage.as_ref().map(|tu| tu.model.clone()),
- iteration: msg.iteration,
+ iteration: Some(iteration),
});
}
- }
- }
- fn project_assistant(
- msg: &DisplayMessage,
- next_results: Option<Vec<PromptToolResult>>,
- items: &mut Vec<DisplayItem>,
- pending: &mut VecDeque<(String, usize)>,
- calls: &mut ProjectedCalls,
- ) {
- // Reasoning precedes the message it belongs to.
- if let Some(reasoning) = msg.reasoning_content.as_deref() {
- if !reasoning.trim().is_empty() {
- items.push(DisplayItem::Reasoning {
- text: reasoning.to_string(),
+ for (call_id, name, arguments) in tool_calls {
+ let args = parse_tool_args(&arguments);
+ if !call_id.is_empty() {
+ self.seen_call_ids.insert(call_id.clone());
+ }
+ self.items.push(DisplayItem::ToolCall {
+ call_id: call_id.clone(),
+ name,
+ iteration: Some(iteration),
+ args,
+ result: None,
+ status: ToolCallStatus::Running,
+ failure: None,
});
+ self.pending.push_back((call_id, self.items.len() - 1));
}
}
- let persisted_tool_calls: Vec<(String, String, String)> = msg
- .turn_usage
- .as_ref()
- .map(|tu| {
- tu.tool_calls
- .iter()
- .map(|call| (call.id.clone(), call.name.clone(), call.arguments.clone()))
- .collect()
- })
- .unwrap_or_default();
- let native_envelope = parse_native_tool_envelope(&msg.message.content);
- // Some native/tinyagents histories predate top-level `turn_usage` lifting
- // and carry the invocation only inside the provider replay envelope. Use
- // that canonical call shape rather than degrading the paired result to an
- // orphan named "tool".
- let recorded_calls: Vec<NativeToolCall> = if persisted_tool_calls.is_empty() {
- native_envelope
- .as_ref()
- .map(|(_, calls)| calls.clone())
- .unwrap_or_default()
- } else {
- persisted_tool_calls
- };
- // Calls already placed after an earlier narration are the prompt-guided
- // turn-level list repeated on its answer line — not calls this line made.
- let mut tool_calls: Vec<NativeToolCall> = recorded_calls
- .into_iter()
- .filter(|(id, _, _)| id.is_empty() || !calls.emitted.contains(id))
- .collect();
- // A prompt-guided line records no calls of its own; the `[Tool results]`
- // line after it names the calls it made.
- if tool_calls.is_empty() {
- if let Some(blocks) = next_results.as_deref() {
- tool_calls = calls
- .registry
- .calls_for(&msg.request_id, blocks, &calls.emitted);
- log::debug!(
- "{LOG_PREFIX} prompt-guided round: {} call(s) inferred from the next [Tool results] line",
- tool_calls.len()
- );
- }
+ fn tool_result(&mut self, msg: &DisplayMessage) {
+ let (result, wrapped_id) = unwrap_tool_result(&msg.message.content);
+ // A failed tool line (`ToolResult::is_error`, stamped at persistence)
+ // pairs to an error row with a failure payload instead of a false
+ // success.
+ let (status, failure) = if msg.failure {
+ (
+ ToolCallStatus::Error,
+ Some(ToolCallFailure {
+ detail: msg.failure_detail.clone(),
+ }),
+ )
+ } else {
+ (ToolCallStatus::Success, None)
+ };
+ let call_id = msg.message.id.clone().or(wrapped_id);
++ self.pair_result(call_id, result, status, failure);
+ }
- for (id, _, _) in &tool_calls {
- if !id.is_empty() {
- calls.emitted.insert(id.clone());
++
++ /// Settle the pending call a result belongs to — by id first, else FIFO — or
++ /// emit an orphan row so the output is not lost.
++ fn pair_result(
++ &mut self,
++ call_id: Option<String>,
++ result: String,
++ status: ToolCallStatus,
++ failure: Option<ToolCallFailure>,
++ ) {
+ // Pair by explicit call id first, else FIFO.
+ let idx = call_id
+ .as_deref()
+ .and_then(|id| take_pending_by_id(&mut self.pending, id))
+ .or_else(|| self.pending.pop_front().map(|(_, idx)| idx));
+
+ if let Some(idx) = idx {
+ if let Some(DisplayItem::ToolCall {
+ result: slot,
+ status: status_slot,
+ failure: failure_slot,
+ ..
+ }) = self.items.get_mut(idx)
+ {
+ *slot = Some(result);
+ *status_slot = status;
+ *failure_slot = failure;
+ return;
+ }
}
- }
- let interim = !tool_calls.is_empty();
-
- // Native tool-call turns are persisted as their provider envelope so they
- // can be replayed byte-faithfully. The display projection needs only the
- // envelope's visible `content`; rendering/sanitizing the whole JSON object
- // makes the narration disappear (and risks showing raw tool JSON).
- let visible_content = native_envelope
- .map(|(content, _)| content)
- .unwrap_or_else(|| msg.message.content.clone());
-
- // The assistant's prose (if any) shows before its tool calls.
- if !visible_content.trim().is_empty() {
- items.push(DisplayItem::AssistantMessage {
- content: visible_content,
- interim,
- request_id: msg.request_id.clone(),
- model: msg.turn_usage.as_ref().map(|tu| tu.model.clone()),
- iteration: msg.iteration,
- });
- }
- for (call_id, name, arguments) in tool_calls {
- let args = parse_tool_args(&arguments);
- items.push(DisplayItem::ToolCall {
- call_id: call_id.clone(),
- name,
- args,
- result: None,
- status: ToolCallStatus::Running,
- failure: None,
+ // Orphan result (no matching assistant tool_call recorded) — surface it
+ // as a best-effort completed tool row so the output is not lost.
+ log::debug!("{LOG_PREFIX} tool result with no pending call — emitting orphan tool row");
+ self.items.push(DisplayItem::ToolCall {
+ call_id: call_id.unwrap_or_default(),
+ name: "tool".to_string(),
+ iteration: None,
+ args: None,
+ result: Some(result),
+ status,
+ failure,
});
- pending.push_back((call_id, items.len() - 1));
}
}
diff --cc crates/openhuman-core/src/threads/transcript_view/transcript_view_tests.rs
index e1577c229e,2c5de789f2..29a9a78adf
--- a/crates/openhuman-core/src/threads/transcript_view/transcript_view_tests.rs
+++ b/crates/openhuman-core/src/threads/transcript_view/transcript_view_tests.rs
@@@ -735,125 -778,3 +778,119 @@@ fn subagent_anchors_to_parent_turn_by_s
"each sub-agent anchors to the turn active at its spawn time"
);
}
+
- #[test]
- fn get_page_missing_thread_is_empty_not_error() {
- let dir = TempDir::new().unwrap();
- let page = get_page(dir.path(), "no_such_thread", None, Some(DEFAULT_LIMIT));
- assert!(!page.has_transcript);
- assert_eq!(page.total, 0);
- assert!(page.items.is_empty());
- }
-
+/// A prompt-guided (text-mode) turn, as `session_raw` actually records it: the
+/// calling lines carry no `tool_calls`, each round's results are ONE
+/// `[Tool results]` user line, and the turn's calls are stamped once on the
+/// final answer line.
+fn prompt_guided_turn_body(result_ids: bool) -> Vec<String> {
+ let block = |id: &str, body: &str| {
+ if result_ids {
+ format!("<tool_result id=\\\"{id}\\\">\\n{body}\\n</tool_result>")
+ } else {
+ format!("<tool_result>\\n{body}\\n</tool_result>")
+ }
+ };
+ vec![
+ r#"{"role":"user","content":"Check the config, then search.","request_id":"req-p"}"#.to_string(),
+ r#"{"role":"assistant","content":"Let me read the config first.","request_id":"req-p"}"#.to_string(),
+ format!(
+ r#"{{"role":"user","content":"[Tool results]\n{}","request_id":"req-p"}}"#,
+ block("call-read", "port = 8080")
+ ),
+ r#"{"role":"assistant","content":"Now I will search for the setting.","request_id":"req-p"}"#.to_string(),
+ format!(
+ r#"{{"role":"user","content":"[Tool results]\n{}","request_id":"req-p"}}"#,
+ block("call-grep", "config.toml:3: setting = on")
+ ),
+ r#"{"role":"assistant","content":"The setting is on.","provider":"openhuman","model":"m","usage":{"input":1,"output":1,"cached_input":0,"cost_usd":0.0},"tool_calls":[{"id":"call-read","name":"file_read","arguments":"{\"path\":\"/etc/config.toml\"}"},{"id":"call-grep","name":"grep","arguments":"{\"pattern\":\"setting\"}"}],"iteration":3,"ts":"2026-09-24T05:20:52Z","request_id":"req-p"}"#.to_string(),
+ ]
+}
+
+/// What a reader sees of a projected turn, in order.
+fn outline(items: &[DisplayItem]) -> Vec<String> {
+ items
+ .iter()
+ .filter_map(|item| match item {
+ DisplayItem::UserMessage { content, .. } => Some(format!("user:{content}")),
+ DisplayItem::AssistantMessage {
+ content, interim, ..
+ } => Some(format!(
+ "{}:{content}",
+ if *interim { "narration" } else { "answer" }
+ )),
+ DisplayItem::ToolCall {
+ call_id,
+ name,
+ status,
+ result,
+ ..
+ } => Some(format!(
+ "tool:{call_id}:{name}:{status:?}:{}",
+ result.as_deref().unwrap_or("-")
+ )),
+ _ => None,
+ })
+ .collect()
+}
+
+/// The prompt-guided turn used to project inverted: both narrations as final
+/// answers, the answer as an interim step with every call after it, and each
+/// `[Tool results]` line as something the user said. A reopened thread showed
+/// the answer twice with its tools below it.
+#[test]
+fn prompt_guided_turn_projects_like_a_native_one() {
+ let dir = TempDir::new().unwrap();
+ let body = prompt_guided_turn_body(true);
+ let body: Vec<&str> = body.iter().map(String::as_str).collect();
+ let path = write_raw(dir.path(), "300_orchestrator", "thr_p", &body);
+ let display = read_transcript_display(&path).unwrap();
+
+ assert_eq!(
+ outline(&project_records(&display.records)),
+ vec![
+ "user:Check the config, then search.".to_string(),
+ "narration:Let me read the config first.".to_string(),
+ "tool:call-read:file_read:Success:port = 8080".to_string(),
+ "narration:Now I will search for the setting.".to_string(),
+ "tool:call-grep:grep:Success:config.toml:3: setting = on".to_string(),
+ "answer:The setting is on.".to_string(),
+ ]
+ );
+}
+
+#[test]
+fn prompt_guided_results_without_ids_pair_in_issue_order() {
+ let dir = TempDir::new().unwrap();
+ let body = prompt_guided_turn_body(false);
+ let body: Vec<&str> = body.iter().map(String::as_str).collect();
+ let path = write_raw(dir.path(), "301_orchestrator", "thr_q", &body);
+ let display = read_transcript_display(&path).unwrap();
+
+ let outline = outline(&project_records(&display.records));
+ assert_eq!(outline[2], "tool:call-read:file_read:Success:port = 8080");
- assert_eq!(outline[4], "tool:call-grep:grep:Success:config.toml:3: setting = on");
++ assert_eq!(
++ outline[4],
++ "tool:call-grep:grep:Success:config.toml:3: setting = on"
++ );
+ assert_eq!(outline[5], "answer:The setting is on.");
+}
+
+/// A native turn records its calls on the line that made them; the answer
+/// line's calls are only skipped when they were already placed.
+#[test]
+fn native_turn_projection_is_unchanged() {
+ let dir = TempDir::new().unwrap();
+ let path = write_raw(dir.path(), "302_orchestrator", "thr_n", &full_turn_body());
+ let display = read_transcript_display(&path).unwrap();
+ assert_eq!(
+ outline(&project_records(&display.records)),
+ vec![
+ "user:Current Date & Time: 2026-07-21 09:00:00 UTC\n\nWhat's the weather in NYC?"
+ .to_string(),
+ "narration:Let me check.".to_string(),
+ "tool:call-1:get_weather:Success:72F and sunny".to_string(),
+ "answer:It's 72F and sunny in NYC.".to_string(),
+ ]
+ );
+}