Skip to content

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

fix(ui): restore chat runtime slice

Steven Enamakel1c739616d056
diff --git a/app/src/store/chatRuntimeSlice.ts b/app/src/store/chatRuntimeSlice.ts
index c901fdd02a..b0dc2a6335 100644
--- a/app/src/store/chatRuntimeSlice.ts
+++ b/app/src/store/chatRuntimeSlice.ts
@@ -1,6 +1,3 @@
-Warning: truncated output (original token count: 33517)
-Total output lines: 3112
-
import { createAsyncThunk, createSlice, type PayloadAction } from '@reduxjs/toolkit';
import debug from 'debug';
@@ -1412,7 +1409,320 @@ const chatRuntimeSlice = createSlice({
/** Reset the live processing transcript at the start of a fresh turn so a
* new turn's narration/steps don't append onto the previous turn's. */
clearProcessingForThread: (state, action: PayloadAction<{ threadId: string }>) => {
- delete state.processingByThread[action.payl…3517 tokens truncated…nning',
+ delete state.processingByThread[action.payload.threadId];
+ },
+ /**
+ * Append a streamed narration/thinking delta to the live processing
+ * transcript, coalescing into the trailing same-kind, same-round block so
+ * a paragraph stays one item. Mirrors the Rust mirror's accumulation so
+ * the live "View processing" panel matches the persisted one.
+ */
+ appendProcessingProse: (
+ state,
+ action: PayloadAction<{
+ threadId: string;
+ kind: 'narration' | 'thinking';
+ round: number;
+ delta: string;
+ }>
+ ) => {
+ const { threadId, kind, round, delta } = action.payload;
+ if (!delta) return;
+ const list = (state.processingByThread[threadId] ??= []);
+ const last = list[list.length - 1];
+ if (last && last.kind === kind && last.round === round) {
+ last.text += delta;
+ return;
+ }
+ list.push({ kind, round, seq: list.length, text: delta });
+ },
+ /**
+ * Reducer-side merge for a `tool_call` socket event (Phase 3 — replaces the
+ * provider's `getState()` + find-row + full-array-rebuild). Upserts the row
+ * by `toolCallId` (falling back to a generated stable id), decorates its
+ * label/detail, and records the processing-transcript pointer in one pass.
+ */
+ toolCallReceived: (
+ state,
+ action: PayloadAction<{
+ threadId: string;
+ round: number;
+ toolName: string;
+ toolCallId?: string;
+ displayLabel?: string;
+ displayDetail?: string;
+ /**
+ * The call's arguments as the `tool_call` event carries them. Kept as
+ * the row's `argsBuffer` unless `tool_args_delta` already streamed
+ * them, so a call whose args were not streamed still shows its input —
+ * as the same call does on reload, where the core transcript always
+ * has them.
+ */
+ args?: Record<string, unknown>;
+ }>
+ ) => {
+ const { threadId, round, toolName, displayLabel, displayDetail } = action.payload;
+ const argsBuffer = argsBufferOf(action.payload.args);
+ // Normalise an absent id to `undefined` *before* anything reads it. A
+ // provider that sends `tool_call_id: ""` is saying "no id", but `??` only
+ // falls back on null/undefined — so the empty string used to survive as
+ // the row id, and every such call in a turn got the same one. Downstream
+ // that is fatal, not cosmetic: assistant-ui keys message parts as
+ // `toolCallId-${id}`, so two id-less calls collide on the literal key
+ // `toolCallId-` and `useResources` throws "Duplicate key toolCallId-",
+ // taking the whole thread render down. The two guards below already
+ // treated `""` as absent (both are truthiness checks); only the id
+ // fallback disagreed.
+ const toolCallId = action.payload.toolCallId || undefined;
+ const entries = (state.toolTimelineByThread[threadId] ??= []);
+ 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 =
+ 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: settled ? prev.status : 'running',
+ argsBuffer: prev.argsBuffer ?? argsBuffer,
+ displayName: displayLabel ?? prev.displayName,
+ detail: displayDetail ?? prev.detail,
+ });
+ } else {
+ const seq = state.toolTimelineSeqByThread[threadId] ?? 0;
+ state.toolTimelineSeqByThread[threadId] = seq + 1;
+ entries.push(
+ decorateEntry({
+ id: rowId,
+ name: toolName,
+ round,
+ seq,
+ status: 'running',
+ argsBuffer,
+ displayName: displayLabel,
+ detail: displayDetail,
+ })
+ );
+ }
+ // Fold the processing-transcript pointer (was a second dispatch).
+ if (!list.some(i => i.kind === 'toolCall' && i.callId === rowId)) {
+ list.push({ kind: 'toolCall', round, seq: list.length, callId: rowId });
+ }
+ },
+ /**
+ * Reducer-side merge for a `tool_result` socket event (Phase 3). Settles the
+ * matching row by `toolCallId`, else the newest still-running row with the
+ * same name+round. A no-op when no row matches (mirrors the provider's
+ * `changed` guard). `failure` is the raw socket payload, parsed here.
+ */
+ toolResultReceived: (
+ state,
+ action: PayloadAction<{
+ threadId: string;
+ round: number;
+ toolName: string;
+ toolCallId?: string;
+ success: boolean;
+ output?: string;
+ failure?: unknown;
+ args?: unknown;
+ elapsedMs?: number;
+ structured?: unknown;
+ displayLabel?: string;
+ displayDetail?: string;
+ }>
+ ) => {
+ const { threadId, round, toolName, success, output, failure } = action.payload;
+ // Same normalisation as `toolCallReceived` — an empty id must not match a
+ // row whose id is the generated fallback, and must fall through to the
+ // name+round scan below.
+ const toolCallId = action.payload.toolCallId || undefined;
+ const entries = state.toolTimelineByThread[threadId];
+ if (!entries || entries.length === 0) return;
+ const status: ToolTimelineEntryStatus = success ? 'success' : 'error';
+ // On failure, parse the optional structured explanation (#4254); a
+ // successful result clears any stale failure carried on the row.
+ const parsedFailure = success ? undefined : parseToolFailure(failure);
+ // The core forwards the (size-capped) tool result text on `output`; accept
+ // only non-empty payloads so a stub-less row stays `undefined`.
+ const result = output && output.length > 0 ? output : undefined;
+ const settle = (entry: ToolTimelineEntry) => {
+ entry.status = status;
+ entry.failure = parsedFailure;
+ entry.result = result;
+ applyResultExtras(entry, action.payload);
+ };
+ if (toolCallId) {
+ const entry = entries.find(e => e.id === toolCallId);
+ if (entry) {
+ settle(entry);
+ return;
+ }
+ }
+ // FIFO, not LIFO: entries are appended in `seq` (issue) order and never
+ // reordered in place, so scanning forward from index 0 finds the OLDEST
+ // still-running row of this name+round — settling the call that was
+ // actually issued first. A backward (newest-first) scan mis-pairs a
+ // result with the wrong row when 2+ calls with the same name are
+ // in-flight in parallel (e.g. `get_tool_contract` ×2) and results land
+ // out of order.
+ for (let i = 0; i < entries.length; i += 1) {
+ const entry = entries[i];
+ if (entry.status === 'running' && entry.name === toolName && entry.round === round) {
+ settle(entry);
+ return;
+ }
+ }
+ },
+ /**
+ * Reducer-side merge for a `text_delta` / `thinking_delta` socket event
+ * (Phase 3 — replaces the provider's `getState()` + parallel-vs-primary
+ * routing). Forked (parallel) turns append into their own lane and skip the
+ * processing transcript; the primary turn appends to the streaming preview
+ * and coalesces a narration/thinking block into the live processing panel.
+ * A `requestId` change starts a fresh preview (drops the prior turn's tail).
+ */
+ streamDeltaReceived: (
+ state,
+ action: PayloadAction<{
+ threadId: string;
+ requestId: string;
+ round: number;
+ delta: string;
+ channel: 'content' | 'thinking';
+ /**
+ * Epoch ms the delta arrived, stamped by the dispatcher so the
+ * reducer stays pure. Timestamps the thinking block for the
+ * reasoning panel's "Thought for Ns"; omitted deltas carry no timing.
+ */
+ at?: number;
+ }>
+ ) => {
+ const { threadId, requestId, round, delta, channel, at } = action.payload;
+ // A parallel (forked) turn streams into its own lane so it doesn't clobber
+ // the primary turn's stream on the same thread.
+ if (state.parallelRequestThreads[requestId] !== undefined) {
+ const lane = (state.parallelStreamsByThread[threadId] ??= {});
+ const prev = lane[requestId];
+ lane[requestId] = {
+ requestId,
+ content: channel === 'content' ? `${prev?.content ?? ''}${delta}` : (prev?.content ?? ''),
+ thinking:
+ channel === 'thinking' ? `${prev?.thinking ?? ''}${delta}` : (prev?.thinking ?? ''),
+ };
+ return;
+ }
+ state.liveRequestIdByThread[threadId] = requestId;
+ const existing = state.streamingAssistantByThread[threadId];
+ const sameTurn = existing != null && existing.requestId === requestId;
+ const carryContent = sameTurn ? existing.content : '';
+ const carryThinking = sameTurn ? existing.thinking : '';
+ const next: StreamingAssistantState = {
+ requestId,
+ content: channel === 'content' ? `${carryContent}${delta}` : carryContent,
+ thinking: channel === 'thinking' ? `${carryThinking}${delta}` : carryThinking,
+ };
+ const carryStartedAt = sameTurn ? existing.thinkingStartedAt : undefined;
+ const carryEndedAt = sameTurn ? existing.thinkingEndedAt : undefined;
+ const stampThinking = channel === 'thinking' && delta.length > 0 && at !== undefined;
+ const startedAt = carryStartedAt ?? (stampThinking ? at : undefined);
+ const endedAt = stampThinking ? at : carryEndedAt;
+ if (startedAt !== undefined) next.thinkingStartedAt = startedAt;
+ if (endedAt !== undefined) next.thinkingEndedAt = endedAt;
+ state.streamingAssistantByThread[threadId] = next;
+ // Live interleaved processing transcript so a mid-turn "View processing"
+ // isn't empty — coalesce into the trailing same-kind, same-round block.
+ if (!delta) return;
+ const kind = channel === 'content' ? 'narration' : 'thinking';
+ const list = (state.processingByThread[threadId] ??= []);
+ const last = list[list.length - 1];
+ if (last && last.kind === kind && last.round === round) {
+ last.text += delta;
+ if (last.kind === 'thinking' && at !== undefined) {
+ last.startedAt ??= at;
+ last.endedAt = at;
+ }
+ } else if (kind === 'thinking' && at !== undefined) {
+ list.push({ kind, round, seq: list.length, text: delta, startedAt: at, endedAt: at });
+ } else {
+ list.push({ kind, round, seq: list.length, text: delta });
+ }
+ },
+ /**
+ * Reducer-side merge for a `tool_args_delta` socket event (Phase 3).
+ * Appends the streamed args to the matching row (by `toolCallId`, else the
+ * newest running row of the same name+round), or creates a running row when
+ * the args arrive before the tool-call event. Re-decorates each time.
+ */
+ toolArgsDeltaReceived: (
+ state,
+ action: PayloadAction<{
+ threadId: string;
+ round: number;
+ delta: string;
+ toolName?: string;
+ toolCallId?: string;
+ }>
+ ) => {
+ const { threadId, round, delta, toolName } = action.payload;
+ // `""` means "no id" — see `toolCallReceived` for why the empty string
+ // must never reach a row id.
+ const toolCallId = action.payload.toolCallId || undefined;
+ const entries = (state.toolTimelineByThread[threadId] ??= []);
+ let matchIdx = -1;
+ if (toolCallId) matchIdx = entries.findIndex(e => e.id === toolCallId);
+ if (matchIdx < 0 && toolName) {
+ matchIdx = entries.findIndex(
+ e => e.status === 'running' && e.name === toolName && e.round === round
+ );
+ }
+ if (matchIdx >= 0) {
+ const prev = entries[matchIdx];
+ entries[matchIdx] = decorateEntry({
+ ...prev,
+ argsBuffer: `${prev.argsBuffer ?? ''}${delta}`,
+ name: prev.name.length === 0 && toolName ? toolName : prev.name,
+ });
+ } else {
+ const seq = state.toolTimelineSeqByThread[threadId] ?? 0;
+ state.toolTimelineSeqByThread[threadId] = seq + 1;
+ entries.push(
+ decorateEntry({
+ // Same stable fallback `toolCallReceived` generates. This branch
+ // used to write `''`, so an args-delta that arrived before its
+ // `tool_call` event with no id produced an id-less row — and a
+ // second one collided with it.
+ id: toolCallId ?? `${threadId}:${round}:${entries.length}:${toolName ?? ''}`,
+ name: toolName ?? '',
+ round,
+ seq,
+ status: 'running',
argsBuffer: delta,
})
);