Skip to content

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

155 KB
Raw Blame
import { createAsyncThunk, createSlice, type PayloadAction } from '@reduxjs/toolkit';
import debug from 'debug';

import { mapDisplayItems } from '../features/conversations/derived/mapDisplayItems';
import { threadApi } from '../services/api/threadApi';
import type { CostSource } from '../services/chatService';
import type { DerivedTranscriptPage } from '../types/derivedTranscript';
import type { ArtifactKind } from '../types/threadWire.generated';
import type {
  AgentRun,
  PersistedSubagentActivity,
  PersistedSubagentToolCall,
  PersistedSubagentTranscriptItem,
  PersistedToolTimelineEntry,
  PersistedTranscriptItem,
  PersistedTurnState,
} from '../types/turnState';
import { DERIVED_TRANSCRIPT_ENABLED } from '../utils/config';
import {
  formatTimelineEntry,
  isKnownClientTool,
  promptFromArgsBuffer,
} from '../utils/toolTimelineFormatting';
import { resetUserScopedState } from './resetActions';

const turnStateLog = debug('chatRuntime.turnState');

/** A tool call's event args as a row `argsBuffer`; `undefined` when there are none. */
function argsBufferOf(args: Record<string, unknown> | undefined): string | undefined {
  if (!args || typeof args !== 'object' || Object.keys(args).length === 0) return undefined;
  try {
    return JSON.stringify(args);
  } catch {
    return undefined;
  }
}

/** How many turns settled this session keep a frozen trail per thread. */
const SETTLED_TURNS_KEPT = 20;

/**
 * Ordered item in the parent turn's processing transcript (narration /
 * thinking / tool-call pointer). Same shape as the persisted wire type; the
 * "View processing" panel renders these interleaved.
 */
export type ProcessingTranscriptItem = PersistedTranscriptItem;

export type ToolTimelineEntryStatus =
  | 'running'
  | 'success'
  | 'error'
  | 'awaiting_user'
  | 'cancelled';

/**
 * The single answer to "is this row still in flight?".
 *
 * `awaiting_user` is in flight. `subagentAwaitingUser` below sets it on the
 * row's TOP-LEVEL `status` (not only on `subagent.status`) when a delegated
 * child parks on `ask_user_clarification`, and a turn parked on the user has
 * not finished — it is blocked, which is the one moment the UI most needs to
 * keep the row's identity.
 *
 * It lives beside the reducer that produces the status because the alternative
 * was measured: three call sites spelled this out by hand, and the one that
 * omitted `awaiting_user` lost the delegation exactly during the pause. A
 * predicate a caller can retype is a predicate that drifts.
 */
export function isActiveTimelineStatus(status: string | undefined): boolean {
  return status === 'running' || status === 'awaiting_user';
}

/** Live progress of the running turn, as the socket handlers maintain it. */
export interface InferenceStatus {
  /** `compacting`: summarizing earlier conversation before the next model call. */
  phase: 'thinking' | 'compacting' | 'tool_use' | 'subagent';
  iteration: number;
  maxIterations: number;
  activeTool?: string;
  activeSubagent?: string;
}

/**
 * Per-subagent live activity attached to a `subagent:*` timeline row.
 *
 * Carries everything the parent thread's UI needs to render a live
 * subagent block — child iteration counter, mode, dedicated-thread
 * flag, final-run statistics, and a flat list of child tool calls
 * the subagent has executed during its run. Populated incrementally
 * from the new `subagent_*` socket events; absent on plain (legacy)
 * subagent rows so older snapshots stay renderable unchanged.
 */
export interface SubagentActivity {
  /** Spawn task id (`sub-…`). Stable for the lifetime of one delegation. */
  taskId: string;
  /** Sub-agent definition id (e.g. `code_executor`). */
  agentId: string;
  /** High-level status: `"running"`, `"awaiting_user"`, `"completed"`, `"failed"`. */
  status?: string;
  /**
   * The question the sub-agent asked via `ask_user_clarification`, carried on
   * the `subagent_awaiting_user` event's `message`. Present only while
   * `status === 'awaiting_user'`; cleared when the delegation resumes.
   *
   * Without it the pause is unreadable: the UI can say the child is blocked
   * but not what on, and the user has nothing to answer.
   */
  awaitingQuestion?: string;
  /**
   * Identity (`<request_id>:<seq>`) of the `subagent_spawned` event that last
   * started or resumed this delegation.
   *
   * Resuming a paused task republishes `subagent_spawned` for the same
   * task/agent, so "an existing row got spawned again" is the
   * only resume signal the frontend gets — and a Socket.IO redelivery of the
   * ORIGINAL spawn is indistinguishable from it by shape alone. Comparing
   * identities separates them: a redelivery repeats the pair the core stamped
   * (`publish_seq_stamped`), a genuine resume never does. Without this a
   * replay clears a live pause and the child's question disappears while it is
   * still blocked on the user.
   */
  spawnEventId?: string;
  /**
   * Provider-assigned id of the `spawn_subagent`/`spawn_async_subagent`/
   * `delegate_*` tool call that started this delegation
   * (`SubagentProgressDetail.parent_call_id` on the `subagent_spawned`
   * event). When present, `assistantUiMessages.ts` renders this activity's
   * `messages`/nested transcript directly on the ORIGINAL spawn tool-call
   * part (`toolCallId === parentCallId`) instead of a synthetic row, and the
   * spawn row's own part is suppressed so the two never collide. Absent on
   * cores that predate this field — those threads keep rendering via the
   * `findPendingDelegationContext` heuristic below.
   */
  parentCallId?: string;
  /** Human-readable display name from the agent registry (e.g. "Researcher"). */
  displayName?: string;
  /**
   * Persistent worker sub-thread id (`worker-<uuid>`) backing this
   * delegation, when one was created. Lets the drawer reopen the full
   * parent↔subagent conversation from memory (via `threadApi.getThreadMessages`)
   * after the live transcript is gone — navigation, cold boot, etc.
   */
  workerThreadId?: string;
  /** Resolved spawn mode — `"typed"` or `"fork"`. */
  mode?: string;
  /** `true` when the spawn requested a dedicated worker thread. */
  dedicatedThread?: boolean;
  /**
   * The parent's delegation prompt — what the parent agent asked this
   * sub-agent to do. Rendered as the opening (parent) turn in the drawer's
   * parent↔subagent chat. Captured from the originating `spawn_subagent` /
   * `delegate_*` tool call when the row is created.
   */
  prompt?: string;
  /** Sub-agent's current 1-based iteration index (live). */
  childIteration?: number;
  /** Sub-agent's iteration cap. */
  childMaxIterations?: number;
  /** Total iterations once the sub-agent finishes. */
  iterations?: number;
  /** Wall-clock ms once the sub-agent finishes. */
  elapsedMs?: number;
  /** Character length of the final assistant text. */
  outputChars?: number;
  /**
   * The sub-agent's final assistant text (`subagent_completed.subagent.output`,
   * capped by the core). Rendered as the delegation's task-card result once
   * it settles.
   */
  output?: string;
  /** Child tool calls executed inside the sub-agent, in arrival order. */
  toolCalls: SubagentToolCallEntry[];
  /**
   * Ordered, interleaved record of everything the sub-agent did, in the
   * exact sequence it happened: a run of streamed thinking, then streamed
   * visible text, then the tool calls that text triggered, then the next
   * iteration's thinking/text, and so on. This is what the full-processing
   * drawer renders so reasoning, output, and tool calls appear *where they
   * occurred* instead of being split into three flat sections.
   *
   * Built incrementally from the `subagent_text_delta` /
   * `subagent_thinking_delta` / `subagent_tool_call` / `subagent_tool_result`
   * socket events in arrival order (the core flushes a child's text/thinking
   * deltas before its tool-call events within an iteration, so arrival order
   * is chronological order). Text is **not** persisted to the turn-state
   * snapshot — on rehydration the transcript is rebuilt from the persisted
   * `toolCalls` (tool items only), so an interrupted run still shows its
   * tool sequence. Absent on legacy/test rows that predate streaming.
   */
  transcript?: SubagentTranscriptItem[];
}

/**
 * One entry in a sub-agent's ordered {@link SubagentActivity.transcript}.
 * A `thinking`/`text` item accumulates streamed deltas; a `tool` item is a
 * child tool call whose `status` flips on its result event.
 */
export type SubagentTranscriptItem =
  | { kind: 'thinking'; iteration?: number; text: string }
  | { kind: 'text'; iteration?: number; text: string }
  | {
      kind: 'tool';
      iteration?: number;
      callId: string;
      toolName: string;
      status: ToolTimelineEntryStatus;
      elapsedMs?: number;
      outputChars?: number;
      /** Arguments the child invoked the tool with (set on start). */
      args?: unknown;
      /** The tool's actual output text (set on completion). */
      result?: string;
      /** Server-computed human label (from `Tool::display_label`), if any. */
      displayName?: string;
      /** Server-computed contextual detail (path / recipient / query). */
      detail?: string;
      /** Plain-language failure explanation for a FAILED child tool call
       *  (#4459) — kept on the transcript item so the rendered live path (not
       *  just the fallback `toolCalls` list) shows the why/next copy. */
      failure?: ToolFailureExplanation;
    };

/** One child tool call performed by a running sub-agent. */
export interface SubagentToolCallEntry {
  /** Provider-assigned tool call id. */
  callId: string;
  /** Child's tool name. */
  toolName: string;
  status: ToolTimelineEntryStatus;
  /** 1-based child iteration the call belongs to. */
  iteration?: number;
  /** Wall-clock ms the call took (set on completion). */
  elapsedMs?: number;
  /** Character length of the tool result (set on completion). */
  outputChars?: number;
  /** Arguments the child invoked the tool with (set on start). */
  args?: unknown;
  /** The tool's actual output text (set on completion). */
  result?: string;
  /** Server-computed human label (from `Tool::display_label`), if any. */
  displayName?: string;
  /** Server-computed contextual detail (path / recipient / query). */
  detail?: string;
  /** Plain-language explanation for a FAILED child call (#4459). Mirrors the
   *  parent {@link ToolTimelineEntry.failure}; absent on successful rows. */
  failure?: ToolFailureExplanation;
}

/**
 * Human-readable explanation for a FAILED tool call (#4254). Carried on the
 * tool-completion socket event (optional `failure` object, snake_case on the
 * wire) and surfaced in the "View processing" timeline as a "why" + "what to
 * do next" pair. `class`/`category` come from the core's failure taxonomy;
 * `causePlain`/`nextAction` are English fallbacks used when the class is not
 * one the UI has localized copy for.
 */
export interface ToolFailureExplanation {
  /** PascalCase failure class, e.g. `MissingPermission`, `Timeout`, `Unknown`. */
  class: string;
  /** `Recoverable` | `BlockedByPolicy` | `NeedsUserConfirmation` | `UserDeclined` | `Permanent`. */
  category: string;
  /** Whether the core considers the failure automatically recoverable. */
  recoverable: boolean;
  /** English fallback cause copy (used when `class` is unrecognized). */
  causePlain: string;
  /** English fallback next-action copy (used when `class` is unrecognized). */
  nextAction: string;
}

/**
 * Defensively parse an incoming `failure` object from a tool-completion socket
 * payload (snake_case wire) or a persisted entry (camelCase) into a
 * {@link ToolFailureExplanation}. Returns `undefined` for anything that is not
 * a well-formed failure object so a malformed/partial payload never corrupts a
 * timeline entry.
 */
export function parseToolFailure(raw: unknown): ToolFailureExplanation | undefined {
  if (!raw || typeof raw !== 'object') return undefined;
  const obj = raw as Record<string, unknown>;
  const cls = obj.class;
  const category = obj.category;
  // Accept both wire (snake_case) and persisted (camelCase) key spellings.
  const causePlain = obj.cause_plain ?? obj.causePlain;
  const nextAction = obj.next_action ?? obj.nextAction;
  if (
    typeof cls !== 'string' ||
    typeof category !== 'string' ||
    typeof causePlain !== 'string' ||
    typeof nextAction !== 'string'
  ) {
    return undefined;
  }
  return {
    class: cls,
    category,
    recoverable: typeof obj.recoverable === 'boolean' ? obj.recoverable : false,
    causePlain,
    nextAction,
  };
}

/**
 * Fold the optional completion fields of a `tool_result` into its row.
 *
 * The core's start event may carry no arguments (the harness reports them at
 * completion), so `args` backfills an empty `argsBuffer`; without it a row
 * could never show its target. A recomputed server label replaces the one
 * sent at start, which was derived without arguments.
 */
function applyResultExtras(
  entry: ToolTimelineEntry,
  extras: {
    args?: unknown;
    elapsedMs?: number;
    structured?: unknown;
    displayLabel?: string;
    displayDetail?: string;
  }
): void {
  if (!entry.argsBuffer && extras.args && typeof extras.args === 'object') {
    entry.argsBuffer = JSON.stringify(extras.args);
  }
  if (typeof extras.elapsedMs === 'number' && Number.isFinite(extras.elapsedMs)) {
    entry.elapsedMs = extras.elapsedMs;
  }
  if (extras.structured && typeof extras.structured === 'object') {
    entry.structured = extras.structured;
  }
  if (extras.displayLabel?.trim()) entry.displayName = extras.displayLabel.trim();
  if (extras.displayDetail?.trim()) entry.detail = extras.displayDetail.trim();
}

/**
 * Attach a human label/detail to a tool-timeline row. The server supplies a
 * label/detail for dynamic Composio/MCP/integration tools the client can't know
 * — trust it for those; for the fixed set of built-ins the client formatter
 * (args-aware) stays authoritative. Pure — shared by the live reducers and any
 * caller that materialises a row.
 */
function decorateEntry(entry: ToolTimelineEntry): ToolTimelineEntry {
  // `displayName` holds only what the server said. Baking the client title in
  // here froze its tense at call time, so a finished row kept reading
  // "Reading file"; every surface now resolves the title at render time.
  const formatted = formatTimelineEntry(entry);
  if (entry.displayName && !isKnownClientTool(entry.name)) {
    return { ...entry, detail: entry.detail ?? formatted.detail };
  }
  const { displayName: _serverLabel, ...rest } = entry;
  return { ...rest, detail: entry.detail ?? formatted.detail };
}

/**
 * Find the parent `spawn_*`/`delegate_*` tool row a just-spawned subagent should
 * collapse into, so the timeline shows one entry per delegation. Returns the
 * source tool name, the delegation prompt, and the spawn row's id to remove.
 * Pure — searches the round's running rows newest-first.
 */
export function findPendingDelegationContext(
  entries: ToolTimelineEntry[],
  round: number
): { sourceToolName?: string; prompt?: string; spawnEntryId?: string } {
  for (let i = entries.length - 1; i >= 0; i -= 1) {
    const entry = entries[i];
    if (entry.status !== 'running' || entry.round !== round) continue;
    if (
      ['spawn_subagent', 'spawn_async_subagent'].includes(entry.name) ||
      entry.name.startsWith('delegate_')
    ) {
      return {
        sourceToolName: entry.name,
        prompt: entry.detail ?? promptFromArgsBuffer(entry.argsBuffer),
        spawnEntryId: entry.id,
      };
    }
  }
  return {};
}

export interface ToolTimelineEntry {
  id: string;
  name: string;
  round: number;
  /**
   * Monotonic per-thread issue-order index, assigned once when the row is
   * FIRST created (by `toolCallReceived`, `toolArgsDeltaReceived`, or
   * `subagentSpawned`) from {@link ChatRuntimeState.toolTimelineSeqByThread}.
   * Unlike arrival order — which a `tool_args_delta` for a later parallel
   * call can race ahead of — `seq` reflects the order the agent actually
   * issued the calls, so the timeline can be sorted deterministically
   * (see `ToolTimelineBlock`) regardless of socket delivery order.
   */
  seq: number;
  status: ToolTimelineEntryStatus;
  argsBuffer?: string;
  displayName?: string;
  detail?: string;
  sourceToolName?: string;
  /**
   * Live sub-agent activity for `subagent:*` rows. Built up from the
   * `subagent_iteration_start` / `subagent_tool_call` /
   * `subagent_tool_result` socket events. Absent for non-subagent
   * rows and for legacy snapshots emitted by older cores.
   */
  subagent?: SubagentActivity;
  /**
   * Human-readable failure explanation for an `error` row (#4254). Parsed from
   * the tool-completion socket event's optional `failure` object; absent on
   * successful/running rows and on legacy snapshots. Preserved through the
   * persisted round-trip so a reloaded failed turn keeps its explanation.
   */
  failure?: ToolFailureExplanation;
  /**
   * The tool's actual (size-capped) result text, set on completion from the
   * `tool_result` socket event's `output` and carried through the persisted
   * turn-state round-trip. Mirrors {@link SubagentToolCallEntry.result} so the
   * timeline can show what a main-agent tool returned. Absent while running
   * and on rows from cores that predate output forwarding.
   */
  result?: string;
  /**
   * Machine-readable result the core attached to `tool_result` as
   * `structured` (today `{ kind: "web_search", query, provider, results }`).
   * Lets a rich renderer skip re-parsing `result` text. Absent on rows from
   * older cores, which fall back to parsing.
   */
  structured?: unknown;
  /** Wall time the call took, from `tool_result.elapsed_ms`. */
  elapsedMs?: number;
}

export interface StreamingAssistantState {
  requestId: string;
  content: string;
  thinking: string;
  /** Epoch ms of the turn's first thinking delta (drives "Thinking… Ns"). */
  thinkingStartedAt?: number;
  /** Epoch ms of the turn's latest thinking delta (drives "Thought for Ns"). */
  thinkingEndedAt?: number;
}

/**
 * Explicit per-thread agent-turn lifecycle for the composer and Cancel affordance.
 * `started` is set when the user sends; `streaming` after the first inference/socket
 * signal. Rows are removed on completion (not stored as `done`/`error` — those are
 * terminal and handled by deleting the key). This does not rely on `threadSlice`
 * segment appends, which can fire many times per turn.
 */
/**
 * `interrupted` is set only by snapshot rehydration on cold-boot when the
 * core finds a turn-state file left behind by a previous process. The UI
 * surfaces it as a retry affordance — there is no live driver to resume.
 */
export type InferenceTurnLifecycle = 'started' | 'streaming' | 'interrupted';

/**
 * Per-sub-agent token/cost contribution, accumulated across the session and
 * keyed by the sub-agent archetype id (e.g. `code_executor`). Drives the hover
 * breakdown under the composer footer's cost/context cluster.
 */
export interface SubAgentUsage {
  agentId: string;
  inputTokens: number;
  outputTokens: number;
  /** Sum of the known costs; read with `costSource`. */
  costUsd: number;
  /** `unknown` once any run's cost was not known: then show no price. */
  costSource: CostSource;
  /** How many times this archetype was spawned across the session. */
  runs: number;
}

const COST_SOURCE_RANK: Record<CostSource, number> = { charged: 0, estimated: 1, unknown: 2 };

/** The less certain of two cost sources. */
export function worseCostSource(a: CostSource, b: CostSource): CostSource {
  return COST_SOURCE_RANK[b] > COST_SOURCE_RANK[a] ? b : a;
}

/**
 * Folds one reported cost into a running total. A `null` cost (the core did
 * not know it) adds nothing and makes the total unknown; a number keeps its
 * reported source (an older core sends no source: its number is a charge).
 */
function foldCost(
  total: { costUsd: number; costSource: CostSource },
  costUsd: number | null | undefined,
  costSource: CostSource | undefined
): void {
  if (costUsd === null) {
    total.costSource = 'unknown';
    return;
  }
  total.costUsd += nonNeg(costUsd);
  total.costSource = worseCostSource(total.costSource, costSource ?? 'charged');
}

/** Running per-session totals accumulated from `chat:done` events (#703). */
export interface SessionTokenUsage {
  inputTokens: number;
  outputTokens: number;
  turns: number;
  lastUpdated: number;
  lastTurnInputTokens: number;
  lastTurnOutputTokens: number;
  /** Cached-input tokens accumulated across the session. */
  cachedTokens: number;
  /** Known USD cost accumulated across the session (parent + sub-agents). */
  costUsd: number;
  /**
   * How certain `costUsd` is: `charged` (all provider-billed), `estimated`
   * (some list-price estimate), or `unknown` (some turn's cost is not known,
   * so no price is shown at all).
   */
  costSource: CostSource;
  /**
   * Most recent known model context window (tokens). `0` until a turn reports a
   * real value; the UI falls back to a default when unknown.
   */
  contextWindow: number;
  /**
   * Last turn's **orchestrator-only** input+output tokens — the context-window
   * gauge numerator. Sub-agent spend is excluded so the gauge tracks the parent
   * thread's own window (each sub-agent runs in its own context window); summing
   * them in let the gauge exceed 100% in multi-agent sessions (#4271).
   */
  lastTurnContextUsed: number;
  /** Per-sub-agent spend for the session, keyed by archetype id. */
  subAgents: Record<string, SubAgentUsage>;
}

/** A zeroed [SessionTokenUsage] bucket. */
export function emptySessionTokenUsage(): SessionTokenUsage {
  return {
    inputTokens: 0,
    outputTokens: 0,
    turns: 0,
    lastUpdated: 0,
    lastTurnInputTokens: 0,
    lastTurnOutputTokens: 0,
    cachedTokens: 0,
    costUsd: 0,
    costSource: 'charged',
    contextWindow: 0,
    lastTurnContextUsed: 0,
    subAgents: {},
  };
}

/** Payload accepted by `recordChatTurnUsage` (and applied per turn). */
interface ChatTurnUsagePayload {
  inputTokens: number;
  outputTokens: number;
  /**
   * This delta is a detached sub-agent's spend landing on a turn that has
   * already been counted, not a new turn. Set by the `subagent_completed`
   * handler; see the `turns` guard in {@link applyTurnUsage}.
   */
  subAgentSpendOnly?: boolean;
  cachedTokens?: number;
  /** `null` when the core did not know the cost (never a guess). */
  costUsd?: number | null;
  costSource?: CostSource;
  contextWindow?: number;
  /**
   * Tokens the orchestrator's context held after the turn's final model call
   * (`chat_done.usage.context_tokens`). `inputTokens` sums every call of the
   * turn, so it is spend, not occupancy. Absent from an older core; the gauge
   * then falls back to the turn totals.
   */
  contextTokens?: number;
  /** Thread the turn belongs to; routes the delta to that thread's bucket. */
  threadId?: string;
  subAgents?: Array<{
    agentId: string;
    inputTokens: number;
    outputTokens: number;
    costUsd: number | null;
  }>;
}

const nonNeg = (n: number | undefined): number =>
  typeof n === 'number' && Number.isFinite(n) ? Math.max(0, n) : 0;

/** Fold one turn's usage delta into a bucket (mutates in place). */
function applyTurnUsage(usage: SessionTokenUsage, payload: ChatTurnUsagePayload): void {
  const inTok = nonNeg(payload.inputTokens);
  const outTok = nonNeg(payload.outputTokens);
  usage.inputTokens += inTok;
  usage.outputTokens += outTok;
  usage.cachedTokens += nonNeg(payload.cachedTokens);
  foldCost(usage, payload.costUsd, payload.costSource);
  // A detached sub-agent's spend arrives on its own `subagent_completed`, after
  // the parent turn's `chat_done` has already been counted. It is more spend on
  // the SAME turn, not another turn, so counting it would inflate the turn
  // count by one per delegation and skew every per-turn average derived from it.
  if (!payload.subAgentSpendOnly) usage.turns += 1;
  usage.lastUpdated = Date.now();
  if (!payload.subAgentSpendOnly) {
    usage.lastTurnInputTokens = inTok;
    usage.lastTurnOutputTokens = outTok;
  }
  // Only overwrite the known context window when the turn reported a real value
  // (>0); an unknown-window turn leaves the prior value intact.
  const ctxWindow = nonNeg(payload.contextWindow);
  if (ctxWindow > 0) usage.contextWindow = ctxWindow;
  // `inTok`/`outTok` are combined parent+sub-agent turn totals (the core sends
  // one number for cost), but the context window is the orchestrator model's
  // alone. Subtract this turn's sub-agent spend so the gauge numerator is the
  // orchestrator thread's own occupancy and can't overflow its window (#4271).
  let subTurnTokens = 0;
  for (const sub of payload.subAgents ?? []) {
    if (!sub || typeof sub.agentId !== 'string' || sub.agentId.length === 0) continue;
    const subIn = nonNeg(sub.inputTokens);
    const subOut = nonNeg(sub.outputTokens);
    subTurnTokens += subIn + subOut;
    const existing = usage.subAgents[sub.agentId] ?? {
      agentId: sub.agentId,
      inputTokens: 0,
      outputTokens: 0,
      costUsd: 0,
      costSource: 'charged',
      runs: 0,
    };
    existing.inputTokens += subIn;
    existing.outputTokens += subOut;
    foldCost(existing, sub.costUsd, undefined);
    existing.runs += 1;
    usage.subAgents[sub.agentId] = existing;
  }
  // The context gauge belongs to the turn, and a late sub-agent delta is not
  // one: recomputing it here would read `0 + 0 - childTokens` and clamp the
  // gauge to zero, blanking a bar the parent's own turn had just set
  // correctly. The parent's value already excludes children by design (#4271),
  // which is exactly what this delta must not disturb.
  if (!payload.subAgentSpendOnly) {
    const contextTokens = nonNeg(payload.contextTokens);
    usage.lastTurnContextUsed =
      contextTokens > 0 ? contextTokens : Math.max(0, inTok + outTok - subTurnTokens);
  }
}

/**
 * A `Prompt`-class tool call parked on the ApprovalGate, awaiting the user's
 * decision. Surfaced from the `approval_request` socket event; cleared when the
 * user answers (`openhuman.approval_decide`) or the turn ends / is cancelled.
 */
export interface PendingApproval {
  requestId: string;
  toolName: string;
  message: string;
  /**
   * The exact command/target being requested (shell command, file path, URL),
   * extracted from the event's redacted args for display. Empty if unavailable.
   */
  command?: string;
  /**
   * Toolkit slug carried on `composio_connect` requests (#3993). Present only
   * when `toolName === 'composio_connect'`; the inline connect card uses it to
   * run the OAuth handoff and poll for completion. The slug is a public
   * identifier (not PII), so it survives arg redaction unchanged.
   */
  toolkit?: string;
  /**
   * The parked call's own tool-call id, when the core attached one
   * (`ChatApprovalRequestEvent.tool_call_id`, additive wire field). Lets
   * `assistantUiMessages.ts`'s `withApproval` attach the approval to the
   * exact tool-call part it gates instead of the newest-unresolved-by-name
   * heuristic. Absent on a core that has not landed the C2 approvals
   * workstream.
   */
  toolCallId?: string;
  /**
   * RFC3339 timestamp the gate's TTL expires at
   * (`ChatApprovalRequestEvent.expires_at`, additive wire field). Drives the
   * expiry countdown on the approval card. Absent on an older core.
   */
  expiresAt?: string;
  /**
   * Terminal non-decision outcome recorded by the server
   * (`approval_decided` socket event) — the gate's TTL expired, or the
   * request was cancelled, with nobody answering interactively. Distinct
   * from simply clearing the entry: keeping it around with a resolution
   * lets the card show *why* it is gone for one more render before the
   * turn-end handlers remove it. Mirrors assistant-ui's own
   * `ToolCallMessagePart.approval.resolution` union.
   */
  resolution?: 'expired' | 'cancelled';
  /**
   * The park can outlive the turn it is shown on
   * (`ChatApprovalRequestEvent.detached`): an async-delegated sub-agent asking
   * for approval after — or while — its parent turn finishes. Turn-end
   * handlers keep a detached entry (its gate is still parked; clearing it was
   * what left every async `image_agent` approval invisible until it expired)
   * and `approval_decided` clears it instead.
   */
  detached?: boolean;
}

/**
 * Drop the thread's parked approval at a turn boundary, unless it is detached
 * from that turn (see `PendingApproval.detached`) — a detached park is still
 * waiting on the user after the turn that surfaced it ends.
 */
function dropTurnBoundApproval(state: ChatRuntimeState, threadId: string): void {
  if (state.pendingApprovalByThread[threadId]?.detached) return;
  removeShownApproval(state, threadId);
}

/**
 * Remove the thread's shown approval and promote the next queued detached one
 * (see `ChatRuntimeState.queuedApprovalsByThread`), so every parked request on
 * the thread is answerable in turn.
 */
function removeShownApproval(state: ChatRuntimeState, threadId: string): void {
  delete state.pendingApprovalByThread[threadId];
  const queue = state.queuedApprovalsByThread[threadId];
  if (!queue || queue.length === 0) {
    delete state.queuedApprovalsByThread[threadId];
    return;
  }
  const [next, ...rest] = queue;
  state.pendingApprovalByThread[threadId] = next;
  if (rest.length > 0) state.queuedApprovalsByThread[threadId] = rest;
  else delete state.queuedApprovalsByThread[threadId];
}

/** Drop `requestId` from the thread's queue; `true` when it was queued. */
function removeQueuedApproval(
  state: ChatRuntimeState,
  threadId: string,
  requestId: string
): boolean {
  const queue = state.queuedApprovalsByThread[threadId];
  if (!queue) return false;
  const rest = queue.filter(entry => entry.requestId !== requestId);
  if (rest.length === queue.length) return false;
  if (rest.length > 0) state.queuedApprovalsByThread[threadId] = rest;
  else delete state.queuedApprovalsByThread[threadId];
  return true;
}

/**
 * A thread-scoped plan the orchestrator parked for interactive review (Codex/
 * Claude plan mode). Surfaced from the `plan_review_request` socket event and
 * resolved via the `openhuman.plan_review_decide` RPC. The parked agent turn
 * blocks until the user approves / rejects / sends feedback.
 */
export interface PendingPlanReview {
  requestId: string;
  /** One-line summary of the plan. */
  summary: string;
  /** Ordered plan steps to display for review. */
  steps: string[];
  /**
   * The `request_plan_review` tool call this review binds to (wire contract:
   * `DomainEvent::PlanReviewRequested.tool_call_id`, additive, lands with core
   * workstream C2). Absent on a core that has not landed C2 yet.
   */
  toolCallId?: string;
  /** RFC3339 expiry for the parked review (additive, lands with C2). */
  expiresAt?: string;
}

/** One step in a `WorkflowProposal`'s summary — a non-trigger node. */
export interface WorkflowProposalStep {
  /** tinyflows node kind (e.g. `"agent"`, `"tool_call"`, `"http_request"`). */
  kind: string;
  /** Human-readable node name. */
  name: string;
  /** Optional short description of the node's config (e.g. a tool slug, prompt). */
  config_hint?: string;
}

/**
 * A candidate automation workflow the agent proposed via the `propose_workflow`
 * tool (issue B4 — agent-first Workflow authoring). VALIDATED but never
 * created — the agent's tool can only validate and summarize a graph; the
 * user must click "Save & enable" on `WorkflowProposalCard` to actually
 * persist it via `openhuman.flows_create`. Parsed from the `propose_workflow`
 * tool call's completed-result JSON (`tool_result` socket event) in
 * `ChatRuntimeProvider`.
 */
export interface WorkflowProposal {
  /** Proposed flow name. */
  name: string;
  /** The validated tinyflows WorkflowGraph, ready to hand to `flows_create` as-is. */
  graph: unknown;
  /** Whether the flow should require approval on every outbound action once saved. */
  requireApproval: boolean;
  summary: {
    /** One-line description of the trigger (e.g. `"schedule: 0 9 * * *"`). */
    trigger: string;
    /** Ordered non-trigger steps. */
    steps: WorkflowProposalStep[];
  };
  /**
   * Id of the persisted thread message this proposal was rehydrated from
   * (`extraMetadata.scope === 'workflow_proposal'`), when it came from the
   * durable backstop rather than a live socket event. Save/Dismiss mark that
   * message `consumed: true` so the card does not resurrect on reload.
   */
  sourceMessageId?: string;
  /**
   * Id of the flow once `WorkflowProposalCard`'s "Save & enable" has fully
   * persisted AND enabled it (issue B36). Mirrored into Redux (rather than
   * living only in the card's component state) because the card
   * deliberately stays mounted showing a "saved" confirmation after success
   * instead of dispatching `clearWorkflowProposalForThread` right away — so
   * a thread/route change can remount the card before the user clicks
   * "View workflow". Without this, the remount would reset local state to
   * `null`, fall back to the pre-save editable view, and a second "Save &
   * enable" click would call `createFlow` again and duplicate the flow.
   */
  completedFlowId?: string;
  /**
   * The saved flow this proposal revises (`flow_id` on the proposal payload,
   * set when the builder edited an existing flow). "Save & enable" writes onto
   * this flow with `flows_update` instead of creating another one.
   */
  flowId?: string;
  /**
   * `flowId`'s `updated_at` when the builder produced this revision
   * (`flow_version` on the payload). Sent as `flows_update`'s
   * `expected_version`, so a save refuses to overwrite a newer edit.
   */
  flowVersion?: string;
  /**
   * Id of the flow once "Save & enable" persisted it, before the enable step
   * finished (pre-authorization pending, denied, or failed). Mirrored into
   * Redux and onto the source message's `saved_flow_id` so a remount or reload
   * resumes the enable step instead of creating the flow again.
   */
  savedFlowId?: string;
}

/**
 * A proposal's identity across Redux updates and card remounts: its source
 * message when it has one, and its name. Also the card's React key, so a
 * replacement remounts the card and a late save/enable result from the
 * replaced proposal is ignored instead of landing on the new one.
 */
export function workflowProposalKey(
  proposal: Pick<WorkflowProposal, 'name' | 'sourceMessageId'>
): string {
  return `${proposal.sourceMessageId ?? ''}|${proposal.name}`;
}

/** Payload of the save/completion updates, naming the proposal they belong to. */
interface WorkflowProposalSaveUpdate {
  threadId: string;
  flowId: string;
  name: string;
  sourceMessageId?: string;
}

const isSameProposal = (proposal: WorkflowProposal, update: WorkflowProposalSaveUpdate) =>
  workflowProposalKey(proposal) === workflowProposalKey(update);

/**
 * Lifecycle status of a single agent-generated artifact, as projected
 * onto the chat runtime per thread.
 *
 * - `in_progress` — derived: the producing tool call is in flight; we
 *   have not yet seen a ready/failed event. UI shows a spinner.
 * - `ready` — `artifact_ready` socket event received. UI shows a
 *   download button.
 * - `failed` — `artifact_failed` socket event received. UI shows the
 *   reason + a retry hint.
 */
export type ArtifactStatus = 'in_progress' | 'ready' | 'failed';

/**
 * Per-thread snapshot of a single artifact's state. Upserted from
 * artifact lifecycle socket events; consumed by `ArtifactCard` for
 * inline message rendering (#2779).
 */
export interface ArtifactSnapshot {
  artifactId: string;
  /** Kind slug from the Rust `ArtifactKind` enum. */
  kind: ArtifactKind;
  /** Human-readable title; also the on-disk filename stem. */
  title: string;
  status: ArtifactStatus;
  /** Final on-disk size. Only set when `status === 'ready'`. */
  sizeBytes?: number;
  /** File name relative to its root folder. Only set when `status === 'ready'`. */
  path?: string;
  /** Producer-supplied reason. Only set when `status === 'failed'`. */
  error?: string;
  /** When the snapshot was last updated, milliseconds since epoch. */
  updatedAt: number;
  /**
   * The `tool_call_id` of the producing tool call, when the core sends one on
   * the `Artifact*` socket event (additive wire field). Present for an
   * artifact produced by a toolkit-rendered call (e.g. `media_generate_image`,
   * `generate_document`) — those render their own in-place state via
   * `MediaAndDocumentCalls.tsx` instead of the header's live-artifact deck, so
   * `Conversations.tsx` filters them out of that deck by this field. Absent
   * on older cores / snapshots that predate the field, and on any artifact
   * with no owning tool call — those keep rendering in the header deck.
   */
  toolCallId?: string;
  /**
   * The turn that made the artifact, from its pending/ready event. Places the
   * card in that turn's message while the turn runs; saved replies place
   * their cards from the core's artifact rows instead
   * (`services/api/artifactRows.ts`).
   */
  ownerRequestId?: string;
}

/**
 * Per-thread UI state for an in-flight agent turn (socket events while the user
 * may navigate away from Conversations). The thread slice keeps `activeThreadId`
 * in sync for cross-thread guards; it is cleared from `ChatRuntimeProvider` on
 * `chat_done` / `chat_error`, not on each persisted segment.
 */
interface ChatRuntimeState {
  inferenceStatusByThread: Record<string, InferenceStatus>;
  streamingAssistantByThread: Record<string, StreamingAssistantState>;
  /**
   * Monotonically-bumped liveness counter per thread, advanced on every
   * `inference_heartbeat` socket event the core emits while a turn is in flight
   * (issue #4270). The Conversations silence timer watches this alongside the
   * status/stream/tool/board slices, so a long prefill or buffered-reasoning
   * phase that emits no other progress still rearms the timer and avoids a
   * false "no response after 2 minutes" timeout. Cleared on turn end.
   */
  inferenceHeartbeatByThread: Record<string, number>;
  /**
   * Threads with an optimistic user send in flight, set the instant the user
   * sends (before `addMessageLocal` resolves and before any streaming state
   * exists). Lets global surfaces — e.g. the New Chat shortcut — tell a
   * mid-send conversation apart from a genuinely-blank one.
   */
  pendingSendThreadIds: Record<string, true>;
  /**
   * Live streams for concurrent PARALLEL (forked) turns on a thread, nested
   * `threadId -> requestId -> stream`. A separate lane from
   * `streamingAssistantByThread` (the single primary stream) so two same-thread
   * turns don't clobber each other — each renders as its own interleaved
   * branch bubble. Populated only for turns sent with `queueMode: 'parallel'`.
   */
  parallelStreamsByThread: Record<string, Record<string, StreamingAssistantState>>;
  /**
   * Maps a parallel turn's `requestId -> threadId`. Lets socket event handlers
   * recognise a forked turn's events (and find its thread) so they route to the
   * parallel lane instead of the primary stream. Entries are added on send and
   * removed on that turn's `chat_done` / `chat_error`.
   */
  parallelRequestThreads: Record<string, string>;
  toolTimelineByThread: Record<string, ToolTimelineEntry[]>;
  /**
   * Per-thread monotonic counter backing {@link ToolTimelineEntry.seq}. Bumped
   * once per NEW row created in {@link toolTimelineByThread} (never on an
   * update to an existing row), so `seq` always reflects issue order even
   * when socket events for parallel tool calls arrive out of order. Reset
   * alongside the timeline itself so a new turn/thread starts counting from
   * zero.
   */
  toolTimelineSeqByThread: Record<string, number>;
  /**
   * Per-turn tool timelines for *past* (settled) turns of a thread, keyed
   * `threadId -> requestId -> entries`. Hydrated from `turn_state_history` on
   * thread open so each past answer keeps its own process trail (Phase 4/5),
   * instead of only the latest turn's live timeline in
   * {@link toolTimelineByThread}. The live turn is intentionally excluded (its
   * rows live in `toolTimelineByThread` and are driven by the socket stream).
   */
  turnTimelinesByThread: Record<string, Record<string, ToolTimelineEntry[]>>;
  /**
   * Per-turn processing transcripts (narration / thinking / tool pointers) for
   * *past* (settled) turns of a thread, keyed `threadId -> requestId -> items`.
   * Sibling of {@link turnTimelinesByThread}: that map holds the past turn's
   * tool rows, this one its interleaved reasoning/narration trail so a reopened
   * thread replays each past answer's thoughts — not just its tool cards
   * (restore-fidelity fix 1). Hydrated from `turn_state_history`; the live turn
   * is excluded (its transcript lives in {@link processingByThread}). Absent for
   * legacy snapshots written before the transcript field existed.
   */
  turnTranscriptsByThread: Record<string, Record<string, ProcessingTranscriptItem[]>>;
  /**
   * The process trail of a turn that settled IN THIS SESSION, frozen at the
   * moment its reply landed, keyed `threadId -> requestId`.
   *
   * The live turn renders from {@link toolTimelineByThread} /
   * {@link processingByThread}. When it settles, those arrays are what the user
   * was just looking at, and the thread's settled message must keep rendering
   * exactly them. Every other source is a different shape of the same turn:
   * the completed turn-state snapshot and the core's transcript projection
   * mint different row ids (a sub-agent row is `subagent:<agent>` there, not the
   * socket's `rowId`) and can differ in what they recorded. Swapping to either
   * mid-session remounts every tool card, resets its disclosure state and jumps
   * the scroll. So the frozen copy wins for this session and the core
   * projection only takes over on the next load, when nothing is on screen to
   * move. Written by {@link chatRuntimeSlice.actions.turnSettled}; ephemeral,
   * like the rest of this slice (never persisted).
   */
  settledTurnsByThread: Record<
    string,
    Record<string, { timeline: ToolTimelineEntry[]; transcript: ProcessingTranscriptItem[] }>
  >;
  /**
   * `request_id` of the primary turn currently live on a thread, set when its
   * first event lands and cleared when it settles. The streaming buffer carries
   * a request id too, but only once text arrives; a turn that opens with tool
   * calls has none, and the projection needs the id from the first event to
   * tell the live turn's own persisted rows apart from earlier ones.
   */
  liveRequestIdByThread: Record<string, string>;
  /**
   * The `request_id` whose rows {@link toolTimelineByThread} currently holds,
   * when known: set by the turn's `inference_start` and by a snapshot hydrate,
   * cleared whenever the timeline is reset. Unlike {@link liveRequestIdByThread}
   * it survives the turn settling, because the rows do. A reply that settles
   * with no `inference_start` of its own (a background delivery, a proactive
   * message) must not adopt another turn's rows as its trail; unknown means
   * no claim either way.
   */
  toolTimelineRequestByThread: Record<string, string>;
  /**
   * The partial assistant answer left behind by an INTERRUPTED turn (the core
   * process that was streaming it is gone), keyed by thread. Surfaced on restore
   * so a turn that crashed mid-answer keeps its visible partial reply + hidden
   * reasoning instead of dropping them (restore-fidelity fix 2). Unlike
   * {@link streamingAssistantByThread} this is a SETTLED, non-live buffer: it is
   * rendered statically (no pulsing cursor) and marked interrupted. Populated
   * only when an interrupted snapshot carries `streamingText`/`thinking`;
   * cleared on any live turn, a completed snapshot, or a thread reset.
   */
  interruptedAssistantByThread: Record<
    string,
    { requestId: string; content: string; thinking: string }
  >;
  /**
   * Ordered narration/thinking/tool transcript per thread for the
   * "View processing" panel — the interleaved Hermes-style record. Hydrated
   * from the persisted turn-state snapshot (which is now KEPT on completion),
   * so a settled / reloaded turn replays its full reasoning. Tool items point
   * into `toolTimelineByThread` by `callId`. Empty/absent → panel falls back
   * to the tool-only view.
   */
  processingByThread: Record<string, ProcessingTranscriptItem[]>;
  inferenceTurnLifecycleByThread: Record<string, InferenceTurnLifecycle>;
  pendingApprovalByThread: Record<string, PendingApproval>;
  /**
   * Detached approvals waiting behind the thread's shown card, oldest first.
   * Several async sub-agents can park on one parent thread at once; the card
   * surface shows one approval per thread, so the rest wait here and are
   * promoted as the shown one is answered, instead of replacing it while its
   * gate still waits.
   */
  queuedApprovalsByThread: Record<string, PendingApproval[]>;
  pendingPlanReviewByThread: Record<string, PendingPlanReview>;
  /**
   * Thread-scoped candidate workflow proposed by the `propose_workflow` agent
   * tool (issue B4), awaiting the user's "Save & enable" / "Dismiss" decision
   * on `WorkflowProposalCard`. Unlike `pendingApprovalByThread` /
   * `pendingPlanReviewByThread`, this is NOT parked on a server-side gate —
   * the underlying tool call already completed; this is purely a
   * client-side "should the card render" flag, cleared on Save, Dismiss, or
   * thread reset.
   */
  pendingWorkflowProposalsByThread: Record<string, WorkflowProposal>;
  /**
   * Per-thread artifact ledger. Snapshots are upserted on
   * `artifact_ready` / `artifact_failed` socket events keyed on
   * `artifactId`. `ArtifactCard` reads this slice to render inline
   * download / retry affordances (#2779).
   */
  artifactsByThread: Record<string, ArtifactSnapshot[]>;
  /** Global, app-session-wide token usage (legacy aggregate). */
  sessionTokenUsage: SessionTokenUsage;
  /**
   * Per-thread token usage, keyed by thread id. Seeded from persisted
   * transcripts via `hydrateThreadUsage` when a thread is opened, then kept live
   * by `recordChatTurnUsage`. The composer footer reads the active thread's
   * bucket so its totals reflect the selected thread, not the whole app session.
   */
  usageByThread: Record<string, SessionTokenUsage>;
  queueStatusByThread: Record<string, QueueStatus>;
  /** Artifacts the user has opened in the right-side preview panel (tab list). */
  openArtifactIds: string[];
  /** Which of the open artifacts is the active tab. */
  activeArtifactId: string | null;
}

/** Snapshot of the active-run queue depth per lane. */
export interface QueueStatus {
  active: boolean;
  steers: number;
  followups: number;
  collects: number;
  total: number;
}

const initialState: ChatRuntimeState = {
  inferenceStatusByThread: {},
  streamingAssistantByThread: {},
  inferenceHeartbeatByThread: {},
  pendingSendThreadIds: {},
  parallelStreamsByThread: {},
  parallelRequestThreads: {},
  toolTimelineByThread: {},
  toolTimelineSeqByThread: {},
  turnTimelinesByThread: {},
  turnTranscriptsByThread: {},
  settledTurnsByThread: {},
  liveRequestIdByThread: {},
  toolTimelineRequestByThread: {},
  interruptedAssistantByThread: {},
  processingByThread: {},
  inferenceTurnLifecycleByThread: {},
  pendingApprovalByThread: {},
  queuedApprovalsByThread: {},
  pendingPlanReviewByThread: {},
  pendingWorkflowProposalsByThread: {},
  artifactsByThread: {},
  sessionTokenUsage: emptySessionTokenUsage(),
  usageByThread: {},
  queueStatusByThread: {},
  openArtifactIds: [],
  activeArtifactId: null,
};

/**
 * A detached child can outlive its parent's reply. Keep its late progress in
 * the frozen turn as well as the live timeline so the settled message remains
 * current without changing its row identity.
 */
/**
 * A row just minted by the stream belongs to the request its event names
 * (`request_id`), else to the live turn. With neither known the owner becomes
 * unknown rather than staying the turn that settled before: a turn whose
 * `inference_start` was missed (a reconnect mid-turn) must still freeze its
 * own rows. A late row of an already-settled turn names that turn, so it
 * keeps the claim instead of erasing it. A parallel (forked) request never
 * owns the primary timeline, as in `liveTurnStarted`.
 */
function claimTimelineForLiveTurn(
  state: ChatRuntimeState,
  threadId: string,
  requestId: string | undefined
): void {
  if (requestId && state.parallelRequestThreads[requestId] !== undefined) return;
  // A row `rowTarget` kept off the live timeline never claims it.
  if (foreignTrail(state, threadId, requestId) !== undefined) return;
  const claim = requestId ?? state.liveRequestIdByThread[threadId];
  if (claim) state.toolTimelineRequestByThread[threadId] = claim;
  else delete state.toolTimelineRequestByThread[threadId];
}

/**
 * Where a newly streamed row belongs. A row naming a request other than the
 * live one (a settled turn's detached child spawning again, a late
 * `tool_call` from an undrained bridge) is that turn's, not the live turn's:
 * it goes into that turn's frozen trail when this session has one, and is
 * otherwise left to the core projection (`null`). Joining the live timeline
 * would either hand it to the live turn's trail or, by claiming, make the
 * live turn's own rows look foreign. With no live turn known, or for the live
 * turn's own rows and parallel requests, the live timeline as before.
 */
function rowTarget(
  state: ChatRuntimeState,
  threadId: string,
  requestId: string | undefined
): { entries: ToolTimelineEntry[]; transcript?: ProcessingTranscriptItem[] } | null {
  const frozen = foreignTrail(state, threadId, requestId);
  if (frozen !== undefined) {
    return frozen ? { entries: frozen.timeline, transcript: frozen.transcript } : null;
  }
  return { entries: (state.toolTimelineByThread[threadId] ??= []) };
}

/**
 * `undefined` when a row naming `requestId` belongs on the live timeline;
 * otherwise that request's frozen trail, or `null` when this session has none.
 */
function foreignTrail(
  state: ChatRuntimeState,
  threadId: string,
  requestId: string | undefined
): { timeline: ToolTimelineEntry[]; transcript: ProcessingTranscriptItem[] } | null | undefined {
  if (requestId === undefined || state.parallelRequestThreads[requestId] !== undefined) {
    return undefined;
  }
  const live = state.liveRequestIdByThread[threadId];
  const frozen = state.settledTurnsByThread[threadId]?.[requestId];
  if (live !== undefined) return requestId === live ? undefined : (frozen ?? null);
  // No turn is live. The live timeline still holds the last settled turn's
  // rows: a late row of THAT turn keeps joining them (they are its rows, and
  // the background-process panel reads them), but a late row of an earlier
  // turn that has its own frozen trail goes there — appending it would hand
  // it, and by claiming, the whole timeline, to the wrong turn. Without a
  // trail (a missed `inference_start`) it joins the live timeline as before.
  const owner = state.toolTimelineRequestByThread[threadId];
  return frozen && owner !== requestId ? frozen : undefined;
}

function subagentRows(
  state: ChatRuntimeState,
  threadId: string,
  predicate: (entry: ToolTimelineEntry) => boolean
): ToolTimelineEntry[] {
  const rows = [
    ...(state.toolTimelineByThread[threadId] ?? []),
    ...Object.values(state.settledTurnsByThread[threadId] ?? {}).flatMap(turn => turn.timeline),
  ].filter(predicate);
  return rows.filter((row, index) => rows.indexOf(row) === index);
}

/**
 * The turn an artifact belongs to. The event names it; older cores that do not
 * fall back to the thread's live turn. An artifact keeps the owner it already
 * has, so a re-hydration or a late event never moves it.
 */
function ownerFor(
  state: { liveRequestIdByThread: Record<string, string | undefined> },
  threadId: string,
  existing: ArtifactSnapshot | undefined,
  requestId: string | undefined
): string | undefined {
  return existing?.ownerRequestId ?? requestId ?? state.liveRequestIdByThread[threadId];
}

/**
 * Upsert a single artifact snapshot for a thread. New entries append
 * in insertion order (matches the timeline ordering the UI expects);
 * existing entries are replaced in place so the inline card flips
 * status without remounting.
 */
function upsertArtifact(
  bucket: ArtifactSnapshot[] | undefined,
  snapshot: ArtifactSnapshot
): ArtifactSnapshot[] {
  const list = bucket ?? [];
  const idx = list.findIndex(entry => entry.artifactId === snapshot.artifactId);
  if (idx === -1) {
    return [...list, snapshot];
  }
  const next = list.slice();
  next[idx] = snapshot;
  return next;
}

function subagentToolCallFromPersisted(call: PersistedSubagentToolCall): SubagentToolCallEntry {
  return {
    callId: call.callId,
    toolName: call.toolName,
    status: call.status,
    iteration: call.iteration ?? undefined,
    elapsedMs: call.elapsedMs ?? undefined,
    outputChars: call.outputChars ?? undefined,
    displayName: call.displayName ?? undefined,
    detail: call.detail ?? undefined,
    // Carry the persisted arguments so a rehydrated child row keeps its input
    // block, and a degraded generic `tool` name can still derive its search
    // label from `query` (#5987).
    args: call.args ?? undefined,
    // Carry the persisted failure explanation across the round-trip (#4459).
    failure: parseToolFailure(call.failure ?? undefined),
    // Carry the persisted (capped) result text so a rehydrated child row can
    // still show what the tool returned.
    result: call.output ?? undefined,
  };
}

/**
 * Carry the live sub-agent prose (reasoning/narration) across a snapshot
 * rehydration. Sub-agent streamed text/thinking is live-only — the persisted
 * snapshot rebuilds a sub-agent transcript from its tool calls *without* the
 * prose. So when a thread re-hydrates mid-turn (e.g. the user switches tabs
 * and comes back), the snapshot rows would otherwise lose the inline thoughts.
 * Match by sub-agent `taskId` (live and persisted rows use different entry
 * ids) and graft the richer in-memory prose transcript onto the new rows.
 */
function preserveLiveSubagentProse(
  existing: ToolTimelineEntry[] | undefined,
  next: ToolTimelineEntry[]
): ToolTimelineEntry[] {
  if (!existing || existing.length === 0) return next;
  const liveProse = new Map<string, SubagentTranscriptItem[]>();
  for (const entry of existing) {
    const tx = entry.subagent?.transcript;
    if (entry.subagent && tx && tx.some(i => i.kind === 'text' || i.kind === 'thinking')) {
      liveProse.set(entry.subagent.taskId, tx);
    }
  }
  if (liveProse.size === 0) return next;
  return next.map(entry => {
    if (!entry.subagent) return entry;
    const saved = liveProse.get(entry.subagent.taskId);
    if (!saved) return entry;
    // Clone the items so we don't reuse Immer drafts from the prior state.
    return { ...entry, subagent: { ...entry.subagent, transcript: saved.map(i => ({ ...i })) } };
  });
}

function subagentTranscriptItemFromPersisted(
  item: PersistedSubagentTranscriptItem
): SubagentTranscriptItem {
  if (item.kind === 'tool') {
    return {
      kind: 'tool',
      iteration: item.iteration ?? undefined,
      callId: item.callId,
      toolName: item.toolName,
      status: item.status,
      elapsedMs: item.elapsedMs ?? undefined,
      outputChars: item.outputChars ?? undefined,
      displayName: item.displayName ?? undefined,
      detail: item.detail ?? undefined,
    };
  }
  return { kind: item.kind, iteration: item.iteration ?? undefined, text: item.text };
}

function subagentActivityFromPersisted(activity: PersistedSubagentActivity): SubagentActivity {
  const toolCalls = activity.toolCalls.map(subagentToolCallFromPersisted);
  const transcript =
    activity.transcript && activity.transcript.length > 0
      ? activity.transcript.map(item => {
          const mapped = subagentTranscriptItemFromPersisted(item);
          if (mapped.kind !== 'tool') return mapped;
          const call = toolCalls.find(candidate => candidate.callId === mapped.callId);
          return call
            ? { ...mapped, args: call.args, result: call.result, failure: call.failure }
            : mapped;
        })
      : toolCalls.map(call => ({
          kind: 'tool' as const,
          iteration: call.iteration,
          callId: call.callId,
          toolName: call.toolName,
          status: call.status,
          elapsedMs: call.elapsedMs,
          outputChars: call.outputChars,
          args: call.args,
          result: call.result,
          failure: call.failure,
        }));
  return {
    taskId: activity.taskId,
    agentId: activity.agentId,
    status: activity.status ?? undefined,
    workerThreadId: activity.workerThreadId ?? undefined,
    mode: activity.mode ?? undefined,
    dedicatedThread: activity.dedicatedThread ?? undefined,
    childIteration: activity.childIteration ?? undefined,
    childMaxIterations: activity.childMaxIterations ?? undefined,
    iterations: activity.iterations ?? undefined,
    elapsedMs: activity.elapsedMs ?? undefined,
    outputChars: activity.outputChars ?? undefined,
    toolCalls,
    // Prefer the persisted prose transcript (reasoning/narration interleaved
    // with tools) so a settled / reloaded run replays its thoughts. Fall back
    // to a tool-only rebuild for snapshots written before sub-agent prose was
    // persisted (the `transcript` field is absent there).
    transcript,
  };
}

/**
 * Order a persisted processing transcript by its per-item `seq` when every item
 * carries one, falling back to the array (arrival) order otherwise
 * (restore-fidelity fix 5: prefer `seq` for replay ordering when present). The
 * core already writes items in `seq` order, so this is a defensive stable sort
 * that also tolerates a snapshot whose items were reordered in transit. A stable
 * sort preserves arrival order for any items that happen to share a `seq`.
 */
function orderTranscriptBySeq(items: ProcessingTranscriptItem[]): ProcessingTranscriptItem[] {
  if (items.length < 2) return items;
  const allHaveSeq = items.every(item => typeof item.seq === 'number');
  if (!allHaveSeq) return items;
  // `.sort` is stable in modern engines; map to (item, index) to make the
  // tie-break on equal `seq` explicit rather than engine-dependent.
  return items
    .map((item, index) => ({ item, index }))
    .sort((a, b) => a.item.seq - b.item.seq || a.index - b.index)
    .map(({ item }) => item);
}

/**
 * `seq` defaults to the array index the caller maps over — persisted
 * `toolTimeline` order IS issue order (the core appends rows as it issues
 * calls), so the index is a faithful stand-in for the live monotonic
 * counter. Callers that hydrate the *live* timeline (as opposed to a past,
 * settled turn) additionally seed {@link ChatRuntimeState.toolTimelineSeqByThread}
 * with the row count so subsequent live events keep counting up from there.
 */
export function toolTimelineFromPersisted(
  entry: PersistedToolTimelineEntry,
  seq: number
): ToolTimelineEntry {
  return {
    id: entry.id,
    name: entry.name,
    round: entry.round,
    seq,
    status: entry.status,
    argsBuffer: entry.argsBuffer ?? undefined,
    displayName: entry.displayName ?? undefined,
    detail: entry.detail ?? undefined,
    sourceToolName: entry.sourceToolName ?? undefined,
    subagent: entry.subagent ? subagentActivityFromPersisted(entry.subagent) : undefined,
    // Carry a persisted failure explanation across the round-trip (#4254). The
    // shared parser tolerates both camelCase (persisted) and snake_case (wire).
    failure: parseToolFailure(entry.failure),
    // Persisted (capped) tool result text, when the core recorded one.
    result: entry.output ?? undefined,
  };
}

/**
 * Settle a rehydrated tool/subagent row that has no live event driver.
 *
 * A turn-state snapshot is a point-in-time mirror: a row left at the
 * non-terminal `running` status was still in-flight when the snapshot was
 * written. When the owning turn was *interrupted* (the core process that was
 * driving it is gone — see `mark_all_interrupted`), no `subagent_done` /
 * `chat_done` event will ever arrive to flip it terminal, so the row would
 * pulse forever — the agent-name blink is driven by the row `status`
 * (`agentNameTone(entry.status)`; `running` pulses, `cancelled` is muted &
 * static). Settle the row to `cancelled` — terminal, muted, not pulsing —
 * mirroring `markSubagentCancelled`.
 *
 * `running` is the only non-terminal value the persisted *row* status can carry
 * (`PersistedToolStatus` is `running | success | error`), so that single guard
 * catches every orphan.
 *
 * The nested `subagent.status` is a richer enum: a subagent that emitted
 * `SubagentAwaitingUser` is persisted with the row `running` but
 * `subagent.status = 'awaiting_user'`. Only settle a child that is *itself*
 * still `running`; leaving `awaiting_user` (and any other non-running child)
 * intact preserves the truthful "was waiting for the user" history — and the
 * pulse is already stopped by the row-level `cancelled` above.
 *
 * A detached sub-agent (`spawn_subagent`, `mode === 'async'`) is the
 * exception, and the parent's snapshot is never allowed to settle it. It is a
 * fire-and-forget task that deliberately outlives the turn that spawned it, so
 * the parent's lifecycle says nothing about whether the child is alive — and
 * `interrupted` is ambiguous on exactly that point: it is stamped both when the
 * core died (child dead too) and when the parent's agent loop merely errored
 * with the core still running (`TurnStateMirror::finish`, child very possibly
 * still working). Settling on the snapshot made the Background tasks panel
 * read "none running" / "Cancelled" while the sub-agent was visibly still
 * making tool calls. Its liveness is owned by sources that actually track it:
 * its own `subagent_completed` event while the core lives, and the run ledger
 * after a restart (startup stamps orphaned runs `interrupted`, which
 * `hydrateRuntimeFromRunLedger` then applies to the row).
 */
function settleOrphanedTimelineEntry(entry: ToolTimelineEntry): ToolTimelineEntry {
  if (entry.status !== 'running') return entry;
  if (entry.subagent?.mode === 'async') return entry;
  return {
    ...entry,
    status: 'cancelled',
    subagent:
      entry.subagent && entry.subagent.status === 'running'
        ? { ...entry.subagent, status: 'cancelled' }
        : entry.subagent,
  };
}

function timelineStatusFromRun(status: AgentRun['status']): ToolTimelineEntryStatus {
  switch (status) {
    case 'completed':
      return 'success';
    case 'cancelled':
      return 'cancelled';
    case 'failed':
      return 'error';
    case 'interrupted':
      // Orphaned by a process exit (e.g. a detached subagent the core lost track
      // of and settled on next boot) — terminal, but not a user-facing error.
      // Render muted/static like `cancelled`, not alarming red.
      return 'cancelled';
    case 'awaiting_user':
    case 'paused':
      return 'awaiting_user';
    default:
      return 'running';
  }
}

function timelineEntryFromRun(run: AgentRun, seq: number): ToolTimelineEntry | null {
  if (!['subagent', 'worker_thread', 'workflow_child', 'team_member'].includes(run.kind)) {
    return null;
  }
  const agentId = run.agentId ?? 'agent';
  const displayName =
    typeof run.metadata?.displayName === 'string' ? run.metadata.displayName : agentId;
  const elapsedMs = run.telemetry?.elapsedMs ?? undefined;
  const outputChars =
    typeof run.metadata?.outputChars === 'number' ? run.metadata.outputChars : undefined;
  return {
    id: `subagent:${run.id}`,
    name: `subagent:${agentId}`,
    round: 0,
    seq,
    status: timelineStatusFromRun(run.status),
    displayName,
    detail: run.summary ?? run.error ?? undefined,
    sourceToolName: 'run_ledger',
    subagent: {
      taskId: run.id,
      agentId,
      status: run.status,
      displayName,
      workerThreadId: run.workerThreadId ?? undefined,
      mode: typeof run.metadata?.mode === 'string' ? run.metadata.mode : undefined,
      dedicatedThread:
        typeof run.metadata?.dedicatedThread === 'boolean'
          ? run.metadata.dedicatedThread
          : undefined,
      elapsedMs,
      outputChars,
      toolCalls: [],
      transcript: [],
    },
  };
}

const chatRuntimeSlice = createSlice({
  name: 'chatRuntime',
  initialState,
  reducers: {
    setInferenceStatusForThread: (
      state,
      action: PayloadAction<{ threadId: string; status: InferenceStatus }>
    ) => {
      state.inferenceStatusByThread[action.payload.threadId] = action.payload.status;
    },
    clearInferenceStatusForThread: (state, action: PayloadAction<{ threadId: string }>) => {
      delete state.inferenceStatusByThread[action.payload.threadId];
    },
    /**
     * Bump a thread's liveness counter on each `inference_heartbeat` (issue
     * #4270). The value is opaque — only the *change* matters to the silence
     * timer's signature comparison. Wraps via modulo to stay a small integer.
     */
    bumpInferenceHeartbeatForThread: (state, action: PayloadAction<{ threadId: string }>) => {
      const prev = state.inferenceHeartbeatByThread[action.payload.threadId] ?? 0;
      state.inferenceHeartbeatByThread[action.payload.threadId] = (prev + 1) % 1_000_000;
    },
    setStreamingAssistantForThread: (
      state,
      action: PayloadAction<{ threadId: string; streaming: StreamingAssistantState }>
    ) => {
      state.streamingAssistantByThread[action.payload.threadId] = action.payload.streaming;
    },
    clearStreamingAssistantForThread: (state, action: PayloadAction<{ threadId: string }>) => {
      delete state.streamingAssistantByThread[action.payload.threadId];
    },
    /** Mark a thread as having an optimistic user send in flight. */
    markThreadSendPending: (state, action: PayloadAction<{ threadId: string }>) => {
      state.pendingSendThreadIds[action.payload.threadId] = true;
    },
    /** Clear the in-flight-send marker once the send settles (or fails). */
    clearThreadSendPending: (state, action: PayloadAction<{ threadId: string }>) => {
      delete state.pendingSendThreadIds[action.payload.threadId];
    },
    /**
     * Register a parallel (forked) turn so its socket events route to the
     * parallel lane. Called when a `queueMode: 'parallel'` send is accepted.
     */
    registerParallelRequest: (
      state,
      action: PayloadAction<{ threadId: string; requestId: string }>
    ) => {
      state.parallelRequestThreads[action.payload.requestId] = action.payload.threadId;
    },
    /** Upsert the live stream for a parallel (forked) turn, keyed by requestId. */
    setParallelStream: (
      state,
      action: PayloadAction<{ threadId: string; streaming: StreamingAssistantState }>
    ) => {
      const { threadId, streaming } = action.payload;
      (state.parallelStreamsByThread[threadId] ??= {})[streaming.requestId] = streaming;
    },
    /**
     * Tear down a parallel turn's lane state on its terminal event
     * (chat_done / chat_error). Removes the stream and the request→thread entry.
     */
    clearParallelRequest: (state, action: PayloadAction<{ requestId: string }>) => {
      const { requestId } = action.payload;
      const threadId = state.parallelRequestThreads[requestId];
      delete state.parallelRequestThreads[requestId];
      if (threadId === undefined) return;
      const streams = state.parallelStreamsByThread[threadId];
      if (!streams) return;
      delete streams[requestId];
      if (Object.keys(streams).length === 0) {
        delete state.parallelStreamsByThread[threadId];
      }
    },
    setToolTimelineForThread: (
      state,
      action: PayloadAction<{ threadId: string; entries: ToolTimelineEntry[] }>
    ) => {
      state.toolTimelineByThread[action.payload.threadId] = action.payload.entries;
      // A reset starts a timeline nobody owns yet; the next `inference_start`
      // claims it.
      if (action.payload.entries.length === 0) {
        delete state.toolTimelineRequestByThread[action.payload.threadId];
      }
    },
    clearToolTimelineForThread: (state, action: PayloadAction<{ threadId: string }>) => {
      delete state.toolTimelineByThread[action.payload.threadId];
      delete state.toolTimelineRequestByThread[action.payload.threadId];
      delete state.toolTimelineSeqByThread[action.payload.threadId];
      delete state.processingByThread[action.payload.threadId];
    },
    /**
     * Replace the hydrated past-turn timelines for a thread (Phase 5). The live
     * turn's rows stay in {@link toolTimelineByThread}; this holds only the
     * settled turns, keyed by their producing `requestId`.
     */
    setTurnTimelinesForThread: (
      state,
      action: PayloadAction<{
        threadId: string;
        timelines: Record<string, ToolTimelineEntry[]>;
        transcripts?: Record<string, ProcessingTranscriptItem[]>;
      }>
    ) => {
      const { threadId, timelines, transcripts } = action.payload;
      state.turnTimelinesByThread[threadId] = timelines;
      if (transcripts) {
        state.turnTranscriptsByThread[threadId] = transcripts;
        turnStateLog(
          'past-turn transcripts set thread=%s turns=%d',
          threadId,
          Object.keys(transcripts).length
        );
      }
    },
    /** 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.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<{
        /** The emitting event's `request_id`; see `claimTimelineForLiveTurn`. */
        requestId?: string;
        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 target = rowTarget(state, threadId, action.payload.requestId);
      if (!target) return;
      const entries = target.entries;
      const list = target.transcript ?? (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;
        claimTimelineForLiveTurn(state, threadId, action.payload.requestId);
        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<{
        /** The emitting event's `request_id`; a late result settles its own turn's row. */
        requestId?: string;
        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, requestId } = 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;
      // A late result settles its own turn's row, wherever `rowTarget` put it.
      const trail = foreignTrail(state, threadId, requestId);
      const entries = trail === undefined ? state.toolTimelineByThread[threadId] : trail?.timeline;
      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<{
        /** The emitting event's `request_id`; see `claimTimelineForLiveTurn`. */
        requestId?: string;
        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 target = rowTarget(state, threadId, action.payload.requestId);
      if (!target) return;
      const entries = target.entries;
      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;
        claimTimelineForLiveTurn(state, threadId, action.payload.requestId);
        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,
          })
        );
      }
    },
    /**
     * Reducer-side merges for the sub-agent event family (Phase 3). Each locates
     * the delegation's timeline row by its precomputed `rowId` and updates the
     * nested `subagent` activity in place — no `getState()` / full-array rebuild
     * in the provider.
     */
    subagentSpawned: (
      state,
      action: PayloadAction<{
        /** The emitting event's `request_id`; see `claimTimelineForLiveTurn`. */
        requestId?: string;
        threadId: string;
        round: number;
        rowId: string;
        taskId: string;
        agentId: string;
        displayName?: string;
        workerThreadId?: string;
        mode?: string;
        dedicatedThread?: boolean;
        /** `<request_id>:<seq>` of the emitting event; see {@link SubagentActivity.spawnEventId}. */
        spawnEventId?: string;
        /** `SubagentProgressDetail.parent_call_id`; see {@link SubagentActivity.parentCallId}. */
        parentCallId?: string;
      }>
    ) => {
      const {
        threadId,
        round,
        rowId,
        taskId,
        agentId,
        displayName,
        workerThreadId,
        mode,
        dedicatedThread,
        spawnEventId,
        parentCallId,
      } = action.payload;
      const target = rowTarget(state, threadId, action.payload.requestId);
      if (!target) return;
      const entries = target.entries;
      // Idempotent: a socket redelivery must not append a second row with the
      // same id (later updates find only the first). Not gated by the provider's
      // event-seen map, so guard here.
      const existing = entries.find(e => e.id === rowId);
      if (existing) {
        // ...with one exception. Resuming a paused task republishes
        // `subagent_spawned` for the SAME task/agent, and that is the only signal the
        // frontend gets that the pause is over. Swallowing it left the row
        // stuck on `awaiting_user` for the rest of the run: the card kept
        // asking a question the user had already answered.
        //
        // But "the row already exists and got spawned again" is ALSO what a
        // redelivered original spawn looks like, and this socket redelivers
        // often. So the unpark is gated on event identity: only a spawn the
        // row has not already been started by can be a resume. A replay
        // repeats the identity the core stamped and is ignored, which is the
        // safe direction to fail — a stale question is visible and recoverable
        // (`subagent_done` still settles the row), a silently cleared one
        // leaves the user staring at a spinner with nothing to answer.
        //
        // Unidentifiable events (an older core with no `seq`, replaying inside
        // one request) collapse to the same string and are therefore treated
        // as replays, deliberately: the cross-turn resume that matters carries
        // a different `request_id` regardless.
        const isResume =
          existing.status === 'awaiting_user' &&
          spawnEventId !== undefined &&
          spawnEventId !== existing.subagent?.spawnEventId;
        if (isResume) {
          existing.status = 'running';
          if (existing.subagent) {
            existing.subagent.status = 'running';
            existing.subagent.awaitingQuestion = undefined;
            existing.subagent.spawnEventId = spawnEventId;
            // Reattach the resumed task card to the newest parent call so the
            // completed spawn from its earlier turn does not claim this work.
            if (parentCallId) existing.subagent.parentCallId = parentCallId;
          }
        }
        return;
      }
      // `parent_call_id` names the exact spawn/delegate tool-call row that
      // started this delegation — no need to guess it from "the newest
      // running spawn-shaped row in this round" (the heuristic below).
      // `assistantUiMessages.ts` renders this activity directly on that row
      // (keyed by `parentCallId`) and suppresses that row's own tool-call
      // part, so this reducer does not need to collapse it away either; the
      // spawn row is simply left in the timeline for `resolveSubagentTimeline`
      // to substitute at render time.
      //
      // Fallback for cores/history that predate `parent_call_id`: locate the
      // running spawn/delegate row heuristically and collapse the two IN
      // PLACE — the row takes the spawn row's slot, its `seq` and its
      // transcript pointer, so the delegation renders exactly where the agent
      // issued it. Splicing the spawn row out and appending a fresh one left
      // the pointer dangling and the sub-agent card sorted to the end of the
      // turn, below text that came after it, with every part after the old
      // slot shifting index (and remounting).
      let prompt: string | undefined;
      let sourceToolName: string | undefined;
      let seq: number;
      if (parentCallId) {
        const spawnEntry = entries.find(e => e.id === parentCallId);
        prompt = spawnEntry?.detail ?? promptFromArgsBuffer(spawnEntry?.argsBuffer);
        sourceToolName = spawnEntry?.name;
        seq = state.toolTimelineSeqByThread[threadId] ?? 0;
        state.toolTimelineSeqByThread[threadId] = seq + 1;
        claimTimelineForLiveTurn(state, threadId, action.payload.requestId);
        entries.push(
          decorateEntry({
            id: rowId,
            name: `subagent:${agentId}`,
            round,
            seq,
            status: 'running',
            detail: prompt,
            sourceToolName,
            subagent: {
              taskId,
              agentId,
              displayName,
              workerThreadId,
              spawnEventId,
              parentCallId,
              mode,
              dedicatedThread,
              prompt,
              toolCalls: [],
              transcript: [],
            },
          })
        );
      } else {
        const pending = findPendingDelegationContext(entries, round);
        prompt = pending.prompt;
        sourceToolName = pending.sourceToolName;
        const spawnIdx = pending.spawnEntryId
          ? entries.findIndex(e => e.id === pending.spawnEntryId)
          : -1;
        const spawnSeq = spawnIdx >= 0 ? entries[spawnIdx].seq : undefined;
        seq = spawnSeq ?? state.toolTimelineSeqByThread[threadId] ?? 0;
        if (spawnSeq === undefined) state.toolTimelineSeqByThread[threadId] = seq + 1;
        claimTimelineForLiveTurn(state, threadId, action.payload.requestId);
        const row = decorateEntry({
          id: rowId,
          name: `subagent:${agentId}`,
          round,
          seq,
          status: 'running',
          detail: pending.prompt,
          sourceToolName: pending.sourceToolName,
          subagent: {
            taskId,
            agentId,
            displayName,
            workerThreadId,
            spawnEventId,
            mode,
            dedicatedThread,
            prompt: pending.prompt,
            toolCalls: [],
            transcript: [],
          },
        });
        if (spawnIdx >= 0) {
          entries[spawnIdx] = row;
          const pointer = (target.transcript ?? state.processingByThread[threadId])?.find(
            item => item.kind === 'toolCall' && item.callId === pending.spawnEntryId
          );
          if (pointer && pointer.kind === 'toolCall') pointer.callId = rowId;
        } else {
          entries.push(row);
        }
      }
    },
    subagentAwaitingUser: (
      state,
      action: PayloadAction<{ threadId: string; rowId: string; question?: string }>
    ) => {
      const entries = subagentRows(
        state,
        action.payload.threadId,
        e => e.id === action.payload.rowId && e.status === 'running'
      );
      for (const entry of entries) {
        entry.status = 'awaiting_user';
        if (!entry.subagent) continue;
        entry.subagent.status = 'awaiting_user';
        // The question is the whole point of the pause. Keep the previous one
        // if this event carried none rather than blanking a readable prompt.
        const question = action.payload.question?.trim();
        if (question) entry.subagent.awaitingQuestion = question;
      }
    },
    subagentDone: (
      state,
      action: PayloadAction<{
        threadId: string;
        rowId: string;
        /** The delegation's task id (`skill_id`); see the match below. */
        taskId?: string;
        success: boolean;
        iterations?: number;
        elapsedMs?: number;
        outputChars?: number;
        /** The sub-agent's final assistant text; see {@link SubagentActivity.output}. */
        output?: string;
      }>
    ) => {
      const { threadId, rowId, taskId, success, iterations, elapsedMs, outputChars, output } =
        action.payload;
      // Settle a still-in-flight row: `running`, or `awaiting_user` (a subagent
      // paused for input that then completes must not stay stuck at
      // awaiting_user). Already-terminal rows are left as-is.
      //
      // Also the same delegation under the core's row id: a detached (`async`)
      // child outlives its turn, and that turn's `chat_done` replaces the live
      // timeline with the completed snapshot, whose row is `subagent:<task>`,
      // not this socket `rowId`. Matching the socket id alone left that row
      // running, and a background delivery (a `chat_done` with no
      // `inference_start`) then froze it as its own trail: a card that spun
      // forever under the reply announcing the child's result. Both ids are
      // turn-independent, so a run resumed with the same task id also settles
      // the earlier turn's card for it. That is how a paused
      // `awaiting_user` card clears: the resumed run's completion carries the
      // newest `spawn_subagent` call as its parent, never the original spawn.
      // Restored past-turn timelines too, like `subagentCancelResolved`: they
      // hold persisted (core-id) rows the process-source panel shows.
      const coreRowId = taskId !== undefined ? `subagent:${taskId}` : undefined;
      const matches = (e: ToolTimelineEntry) =>
        (e.id === rowId || e.id === coreRowId) &&
        (e.status === 'running' || e.status === 'awaiting_user');
      const entries = [
        ...subagentRows(state, threadId, matches),
        ...Object.values(state.turnTimelinesByThread[threadId] ?? {})
          .flat()
          .filter(matches),
      ];
      for (const entry of entries) {
        entry.status = success ? 'success' : 'error';
        if (!entry.subagent) continue;
        const s = entry.subagent;
        // The nested activity settles with the row: it drives the card's own
        // transcript status and the live tail's `requires-action` state, and a
        // hydrated row carries the snapshot's `running` / `awaiting_user`.
        s.status = success ? 'completed' : 'failed';
        if (iterations !== undefined) s.iterations = iterations;
        if (elapsedMs !== undefined) s.elapsedMs = elapsedMs;
        if (outputChars !== undefined) s.outputChars = outputChars;
        if (output !== undefined) s.output = output;
      }
    },
    /**
     * Settle a delegation card from the core's answer to "Cancel task".
     *
     * `cancelled: true` — the run was aborted. `cancelled: false` — nothing is
     * running under that id any more, and `outcome` says how it had ended:
     * `completed` / `failed` as the core recorded it, or `unknown` when the
     * core no longer knows the task. Unknown settles as `cancelled` — the user
     * asked to stop it and nothing is running — never as a success it cannot
     * vouch for. Without this a card whose terminal event was missed kept a
     * live spinner and a Cancel button that answered "not running" forever.
     * Matched by task id across every thread — live, settled, and restored
     * past-turn timelines — because the card knows no row id.
     */
    subagentCancelResolved: (
      state,
      action: PayloadAction<{
        taskId: string;
        cancelled: boolean;
        outcome?: 'completed' | 'failed' | 'unknown';
      }>
    ) => {
      const { taskId, cancelled, outcome } = action.payload;
      const status: ToolTimelineEntryStatus = cancelled
        ? 'cancelled'
        : outcome === 'completed'
          ? 'success'
          : outcome === 'failed'
            ? 'error'
            : 'cancelled';
      // The nested activity drives the card's own transcript status, so it
      // settles with the row (its vocabulary: completed / failed / cancelled).
      const activityStatus =
        status === 'success' ? 'completed' : status === 'error' ? 'failed' : 'cancelled';
      const matches = (e: ToolTimelineEntry) =>
        e.subagent?.taskId === taskId && isActiveTimelineStatus(e.status);
      const settle = (entry: ToolTimelineEntry) => {
        entry.status = status;
        if (entry.subagent) entry.subagent.status = activityStatus;
      };
      for (const threadId of Object.keys(state.toolTimelineByThread).concat(
        Object.keys(state.settledTurnsByThread)
      )) {
        subagentRows(state, threadId, matches).forEach(settle);
      }
      for (const timelines of Object.values(state.turnTimelinesByThread)) {
        Object.values(timelines).flat().filter(matches).forEach(settle);
      }
    },
    subagentIterationStarted: (
      state,
      action: PayloadAction<{
        threadId: string;
        rowId: string;
        childIteration?: number;
        childMaxIterations?: number;
      }>
    ) => {
      const { threadId, rowId, childIteration, childMaxIterations } = action.payload;
      // Live and frozen rows alike, as `subagentToolCallReceived`: a detached
      // child keeps reporting after its turn settled (or its row was routed
      // to that turn's frozen trail by `rowTarget`).
      for (const entry of subagentRows(state, threadId, e => e.id === rowId)) {
        if (!entry.subagent) continue;
        if (childIteration !== undefined) entry.subagent.childIteration = childIteration;
        if (childMaxIterations !== undefined)
          entry.subagent.childMaxIterations = childMaxIterations;
      }
    },
    subagentToolCallReceived: (
      state,
      action: PayloadAction<{
        threadId: string;
        rowId: string;
        callId: string;
        toolName: string;
        iteration?: number;
        args?: unknown;
        displayName?: string;
        detail?: string;
      }>
    ) => {
      const { threadId, rowId, callId, toolName, iteration, args, displayName, detail } =
        action.payload;
      for (const entry of subagentRows(state, threadId, e => e.id === rowId)) {
        if (!entry.subagent || entry.subagent.toolCalls.some(c => c.callId === callId)) continue;
        entry.subagent.toolCalls.push({
          callId,
          toolName,
          status: 'running',
          iteration,
          args,
          displayName,
          detail,
        });
      }
    },
    subagentToolResultReceived: (
      state,
      action: PayloadAction<{
        threadId: string;
        rowId: string;
        callId: string;
        success: boolean;
        elapsedMs?: number;
        outputChars?: number;
        result?: string;
        failure?: unknown;
      }>
    ) => {
      const { threadId, rowId, callId, success, elapsedMs, outputChars, result, failure } =
        action.payload;
      for (const entry of subagentRows(state, threadId, e => e.id === rowId)) {
        const call = entry.subagent?.toolCalls.find(c => c.callId === callId);
        if (!call) continue;
        call.status = success ? 'success' : 'error';
        if (elapsedMs !== undefined) call.elapsedMs = elapsedMs;
        if (outputChars !== undefined) call.outputChars = outputChars;
        if (result !== undefined) call.result = result;
        // A successful result clears any stale failure on the row.
        call.failure = success ? undefined : parseToolFailure(failure);
      }
    },
    /**
     * Optimistically mark a detached background sub-agent as cancelled after the
     * user confirms a cancel via `openhuman.subagent_cancel`. The aborted run
     * emits no terminal socket event, so without this the row would keep showing
     * "running" forever. Located by the subagent's stable `taskId`.
     */
    markSubagentCancelled: (state, action: PayloadAction<{ threadId: string; taskId: string }>) => {
      const { threadId, taskId } = action.payload;
      for (const entry of subagentRows(state, threadId, e => e.subagent?.taskId === taskId)) {
        entry.status = 'cancelled';
        if (entry.subagent) entry.subagent.status = 'cancelled';
      }
    },
    /**
     * Settle rows whose terminal turn snapshot could not be fetched.
     *
     * `chat_done` means their event driver has stopped. A non-async row still
     * marked `running` therefore has no remaining source that can truthfully
     * complete it, while detached sub-agents intentionally outlive the parent
     * turn and must remain owned by their run ledger.
     */
    cancelUnresolvedTurnTimeline: (
      state,
      action: PayloadAction<{ threadId: string; rowIds?: string[] }>
    ) => {
      const { threadId, rowIds } = action.payload;
      const entries = state.toolTimelineByThread[threadId];
      if (!entries) return;
      const eligible = rowIds && new Set(rowIds);
      state.toolTimelineByThread[threadId] = entries.map(entry =>
        !eligible || eligible.has(entry.id) ? settleOrphanedTimelineEntry(entry) : entry
      );
    },
    /**
     * Append a streamed `subagent_text_delta` / `subagent_thinking_delta`
     * chunk to the ordered transcript of the matching subagent row. The row
     * is located by its synthetic id (`<thread>:subagent:<taskId>:<agentId>`)
     * built from the event's subagent detail — the same id the
     * `subagent_spawned` handler created.
     *
     * Consecutive deltas of the same kind extend the trailing transcript
     * item; a kind switch (or an intervening tool call) starts a new item.
     * That keeps reasoning, output, and tool calls in the exact order they
     * occurred. No-ops if the row isn't present yet (a delta racing ahead of
     * its spawn event is dropped rather than resurrecting a context-less row).
     */
    appendSubagentStreamDelta: (
      state,
      action: PayloadAction<{
        threadId: string;
        rowId: string;
        kind: 'text' | 'thinking';
        delta: string;
        iteration?: number;
      }>
    ) => {
      const { threadId, rowId, kind, delta, iteration } = action.payload;
      for (const entry of subagentRows(state, threadId, e => e.id === rowId)) {
        if (!entry.subagent) continue;
        const transcript = (entry.subagent.transcript ??= []);
        const last = transcript[transcript.length - 1];
        // Extend the trailing item only when it's the same kind AND the same
        // iteration — otherwise two same-kind chunks from different turns (with
        // no tool call between them) would fuse into one transcript entry.
        if (
          last &&
          (last.kind === 'text' || last.kind === 'thinking') &&
          last.kind === kind &&
          last.iteration === iteration
        ) {
          last.text += delta;
        } else {
          transcript.push({ kind, iteration, text: delta });
        }
      }
    },
    /**
     * Record the start of a child tool call as a `tool` item at the current
     * tail of the subagent transcript — i.e. right after the text that
     * triggered it. De-duped by `callId` so a socket redelivery doesn't
     * append twice. Complements the flat `toolCalls` list (kept for the
     * compact card + persistence).
     */
    recordSubagentTranscriptTool: (
      state,
      action: PayloadAction<{
        threadId: string;
        rowId: string;
        callId: string;
        toolName: string;
        iteration?: number;
        args?: unknown;
        displayName?: string;
        detail?: string;
      }>
    ) => {
      const { threadId, rowId, callId, toolName, iteration, args, displayName, detail } =
        action.payload;
      // Live and frozen rows alike; see `subagentIterationStarted`.
      for (const entry of subagentRows(state, threadId, e => e.id === rowId)) {
        if (!entry.subagent) continue;
        const transcript = (entry.subagent.transcript ??= []);
        if (transcript.some(i => i.kind === 'tool' && i.callId === callId)) continue;
        transcript.push({
          kind: 'tool',
          iteration,
          callId,
          toolName,
          status: 'running',
          args,
          displayName,
          detail,
        });
      }
    },
    /**
     * Flip a transcript `tool` item to its terminal status when the child
     * tool result arrives, recording timing/size. No-op if the matching
     * item isn't present.
     */
    resolveSubagentTranscriptTool: (
      state,
      action: PayloadAction<{
        threadId: string;
        rowId: string;
        callId: string;
        success: boolean;
        elapsedMs?: number;
        outputChars?: number;
        result?: string;
        failure?: ToolFailureExplanation;
      }>
    ) => {
      const { threadId, rowId, callId, success, elapsedMs, outputChars, result, failure } =
        action.payload;
      // Live and frozen rows alike; see `subagentIterationStarted`.
      for (const entry of subagentRows(state, threadId, e => e.id === rowId)) {
        const item = entry.subagent?.transcript?.find(
          i => i.kind === 'tool' && i.callId === callId
        );
        if (!item || item.kind !== 'tool') continue;
        item.status = success ? 'success' : 'error';
        if (elapsedMs != null) item.elapsedMs = elapsedMs;
        if (outputChars != null) item.outputChars = outputChars;
        if (result != null) item.result = result;
        // Carry the structured why/next onto the rendered transcript item; a
        // successful result clears any stale failure (#4459).
        item.failure = success ? undefined : failure;
      }
    },
    setPendingApprovalForThread: (
      state,
      action: PayloadAction<{ threadId: string; approval: PendingApproval }>
    ) => {
      const { threadId, approval } = action.payload;
      const current = state.pendingApprovalByThread[threadId];
      const queue = state.queuedApprovalsByThread[threadId];
      // A replay of a request already waiting in the queue updates it there.
      const queuedAt = queue?.findIndex(entry => entry.requestId === approval.requestId) ?? -1;
      if (queue && queuedAt >= 0) {
        queue[queuedAt] = approval;
        return;
      }
      if (current && current.requestId !== approval.requestId && !current.resolution) {
        // A detached request never displaces a card that is still waiting:
        // both gates stay parked until answered or expired, so it queues.
        if (approval.detached) {
          state.queuedApprovalsByThread[threadId] = [...(queue ?? []), approval];
          return;
        }
        // The parent turn's own approval goes first (it blocks that turn); a
        // detached card it covers waits at the head of the queue.
        if (current.detached) {
          state.queuedApprovalsByThread[threadId] = [current, ...(queue ?? [])];
        }
      }
      state.pendingApprovalByThread[threadId] = approval;
    },
    clearPendingApprovalForThread: (state, action: PayloadAction<{ threadId: string }>) => {
      removeShownApproval(state, action.payload.threadId);
    },
    /**
     * Drop every detached approval on the thread, shown or queued, for
     * reconciliation: after a socket drop (which a core restart always
     * causes) the client cannot tell which parks the core still holds, so it
     * forgets them and the thread rejoin replays exactly the live ones.
     */
    dropDetachedApprovalsForThread: (state, action: PayloadAction<{ threadId: string }>) => {
      const { threadId } = action.payload;
      delete state.queuedApprovalsByThread[threadId];
      if (state.pendingApprovalByThread[threadId]?.detached) {
        delete state.pendingApprovalByThread[threadId];
      }
    },
    /**
     * Turn-end clear (`chat_done` / `chat_error`): a park bound to the turn
     * cannot outlive it, but a detached one (an async sub-agent's) is still
     * waiting on the user and stays until `approval_decided` clears it.
     */
    clearTurnApprovalForThread: (state, action: PayloadAction<{ threadId: string }>) => {
      dropTurnBoundApproval(state, action.payload.threadId);
    },
    /**
     * Clear the thread's parked approval when it is `requestId` — for an
     * `approval_decided` that resolves a detached card on a client that did
     * not answer it (no turn end follows to clear it). A no-op when the store
     * holds a different request.
     */
    clearPendingApprovalIfRequest: (
      state,
      action: PayloadAction<{ threadId: string; requestId: string }>
    ) => {
      const { threadId, requestId } = action.payload;
      const current = state.pendingApprovalByThread[threadId];
      if (current?.requestId === requestId) {
        removeShownApproval(state, threadId);
        return;
      }
      removeQueuedApproval(state, threadId, requestId);
    },
    /**
     * Record a server-decided terminal resolution (`approval_decided` socket
     * event carrying `resolution: 'expired' | 'cancelled'`) on the thread's
     * still-parked entry, rather than deleting it outright. Only applies when
     * the event names the SAME request the store is holding — a decided
     * event for a request the client already cleared (the common,
     * interactive-decision case) is a no-op here. A caller that wants the
     * card gone immediately still dispatches `clearPendingApprovalForThread`
     * itself once it has shown the resolution.
     */
    resolvePendingApprovalForThread: (
      state,
      action: PayloadAction<{
        threadId: string;
        requestId: string;
        resolution: 'expired' | 'cancelled';
      }>
    ) => {
      const current = state.pendingApprovalByThread[action.payload.threadId];
      if (!current || current.requestId !== action.payload.requestId) {
        // A queued request that expired or was cancelled was never shown;
        // there is nothing to explain, so it simply leaves the queue.
        removeQueuedApproval(state, action.payload.threadId, action.payload.requestId);
        return;
      }
      current.resolution = action.payload.resolution;
    },
    setPendingPlanReviewForThread: (
      state,
      action: PayloadAction<{ threadId: string; review: PendingPlanReview }>
    ) => {
      state.pendingPlanReviewByThread[action.payload.threadId] = action.payload.review;
    },
    clearPendingPlanReviewForThread: (state, action: PayloadAction<{ threadId: string }>) => {
      delete state.pendingPlanReviewByThread[action.payload.threadId];
    },
    clearPendingPlanReviewIfRequest: (
      state,
      action: PayloadAction<{ threadId: string; requestId: string }>
    ) => {
      if (
        state.pendingPlanReviewByThread[action.payload.threadId]?.requestId ===
        action.payload.requestId
      ) {
        delete state.pendingPlanReviewByThread[action.payload.threadId];
      }
    },
    setWorkflowProposalForThread: (
      state,
      action: PayloadAction<{ threadId: string; proposal: WorkflowProposal }>
    ) => {
      state.pendingWorkflowProposalsByThread[action.payload.threadId] = action.payload.proposal;
    },
    clearWorkflowProposalForThread: (state, action: PayloadAction<{ threadId: string }>) => {
      delete state.pendingWorkflowProposalsByThread[action.payload.threadId];
    },
    /**
     * Record that a pending workflow proposal's flow finished saving AND
     * enabling (issue B36), so `WorkflowProposalCard`'s terminal "saved"
     * state survives a remount (thread switch, route change) while the
     * proposal is still sitting in `pendingWorkflowProposalsByThread` — see
     * `WorkflowProposal.completedFlowId`. No-op if the proposal was already
     * cleared (e.g. a race with `clearWorkflowProposalForThread`) or replaced
     * by another proposal (see `isSameProposal`).
     */
    markWorkflowProposalCompleted: (state, action: PayloadAction<WorkflowProposalSaveUpdate>) => {
      const proposal = state.pendingWorkflowProposalsByThread[action.payload.threadId];
      if (proposal && isSameProposal(proposal, action.payload)) {
        proposal.completedFlowId = action.payload.flowId;
      }
    },
    /**
     * Record that a pending proposal's flow is persisted but not yet enabled
     * (see `WorkflowProposal.savedFlowId`). Applied only to the proposal that
     * was saved (same name and source message): a newer proposal that replaced
     * it while the save was in flight must not inherit its flow id. No-op if
     * the proposal was cleared or replaced.
     */
    markWorkflowProposalSaved: (state, action: PayloadAction<WorkflowProposalSaveUpdate>) => {
      const proposal = state.pendingWorkflowProposalsByThread[action.payload.threadId];
      if (proposal && isSameProposal(proposal, action.payload)) {
        proposal.savedFlowId = action.payload.flowId;
      }
    },
    /**
     * Mark a producer-tool call as in-flight so the `ArtifactCard` can
     * render a spinner before any ready/failed event arrives. Caller
     * usually fires this off the corresponding `ChatToolCallEvent`
     * when the tool is in the known artifact-producing allowlist
     * (e.g. `generate_presentation`). Re-firing for the same
     * `artifactId` is a no-op (idempotent upsert).
     */
    upsertArtifactInProgressForThread: (
      state,
      action: PayloadAction<{
        threadId: string;
        artifactId: string;
        kind: ArtifactSnapshot['kind'];
        title: string;
        toolCallId?: string;
        requestId?: string;
      }>
    ) => {
      const { threadId, artifactId, kind, title, toolCallId, requestId } = action.payload;
      // No-downgrade guard: a late `artifact_pending` (re-delivery, or a
      // socket race) must never regress an artifact that already reached
      // `ready` / `failed` back to a spinner. Only the regenerate flow
      // (#3162) legitimately re-enters `in_progress`, and that reuses the
      // id via a fresh pending event AFTER the failed state — which is
      // allowed because the previous terminal state was `failed`, and a
      // retry SHOULD show the spinner again. So: block downgrade only from
      // `ready`; allow `failed -> in_progress` (an explicit retry).
      const existing = (state.artifactsByThread[threadId] ?? []).find(
        entry => entry.artifactId === artifactId
      );
      if (existing && existing.status === 'ready') {
        return;
      }
      const snapshot: ArtifactSnapshot = {
        artifactId,
        kind,
        title,
        status: 'in_progress',
        updatedAt: Date.now(),
        toolCallId: toolCallId ?? existing?.toolCallId,
        ownerRequestId: ownerFor(state, threadId, existing, requestId),
      };
      state.artifactsByThread[threadId] = upsertArtifact(
        state.artifactsByThread[threadId],
        snapshot
      );
    },
    /**
     * Mark an artifact as ready (download-able). Triggered by the
     * `artifact_ready` socket event. Promotes status off `in_progress`
     * and fills in `path` / `sizeBytes` for the download flow.
     */
    upsertArtifactReadyForThread: (
      state,
      action: PayloadAction<{
        threadId: string;
        artifactId: string;
        kind: ArtifactSnapshot['kind'];
        title: string;
        path: string;
        sizeBytes: number;
        toolCallId?: string;
        requestId?: string;
        /**
         * Loaded from the core (`ai_list_artifacts`), not announced by a turn:
         * it takes no owner from the thread's live turn. Its placement comes
         * from the thread's artifact rows.
         */
        loaded?: boolean;
      }>
    ) => {
      const { threadId, artifactId, kind, title, path, sizeBytes, toolCallId, requestId, loaded } =
        action.payload;
      const existing = (state.artifactsByThread[threadId] ?? []).find(
        entry => entry.artifactId === artifactId
      );
      const snapshot: ArtifactSnapshot = {
        artifactId,
        kind,
        title,
        status: 'ready',
        path,
        sizeBytes,
        updatedAt: Date.now(),
        toolCallId: toolCallId ?? existing?.toolCallId,
        ownerRequestId: loaded
          ? existing?.ownerRequestId
          : ownerFor(state, threadId, existing, requestId),
      };
      state.artifactsByThread[threadId] = upsertArtifact(
        state.artifactsByThread[threadId],
        snapshot
      );
    },
    /**
     * Mark an artifact as failed. Triggered by the `artifact_failed`
     * socket event. Promotes status off `in_progress` and persists the
     * producer-supplied `error` so the card can show a retry hint.
     */
    upsertArtifactFailedForThread: (
      state,
      action: PayloadAction<{
        threadId: string;
        artifactId: string;
        kind: ArtifactSnapshot['kind'];
        title: string;
        error: string;
        toolCallId?: string;
        requestId?: string;
      }>
    ) => {
      const { threadId, artifactId, kind, title, error, toolCallId, requestId } = action.payload;
      const existing = (state.artifactsByThread[threadId] ?? []).find(
        entry => entry.artifactId === artifactId
      );
      const snapshot: ArtifactSnapshot = {
        artifactId,
        kind,
        title,
        status: 'failed',
        error,
        updatedAt: Date.now(),
        toolCallId: toolCallId ?? existing?.toolCallId,
        ownerRequestId: ownerFor(state, threadId, existing, requestId),
      };
      state.artifactsByThread[threadId] = upsertArtifact(
        state.artifactsByThread[threadId],
        snapshot
      );
    },
    /**
     * Open an artifact in the right-side preview panel: append its id to the
     * tab list (idempotent) and make it the active tab. Clicking a card calls
     * this — if the artifact is already open it just re-activates it.
     */
    openArtifact: (state, action: PayloadAction<string>) => {
      const id = action.payload;
      if (!state.openArtifactIds.includes(id)) {
        state.openArtifactIds.push(id);
      }
      state.activeArtifactId = id;
    },
    /**
     * Close one artifact tab. Removes it from the tab list; if it was active,
     * the next remaining tab becomes active, and closing the last tab clears
     * `activeArtifactId` so the panel unmounts.
     */
    closeArtifactTab: (state, action: PayloadAction<string>) => {
      const id = action.payload;
      const idx = state.openArtifactIds.indexOf(id);
      if (idx !== -1) {
        state.openArtifactIds.splice(idx, 1);
      }
      if (state.activeArtifactId === id) {
        state.activeArtifactId = state.openArtifactIds[0] ?? null;
      }
    },
    /** Set the active tab explicitly (clicking a tab). */
    activateArtifactTab: (state, action: PayloadAction<string>) => {
      state.activeArtifactId = action.payload;
    },
    /** Close the preview panel and every tab in it (the header X). */
    closeArtifactPanel: state => {
      state.openArtifactIds = [];
      state.activeArtifactId = null;
    },
    clearArtifactsForThread: (state, action: PayloadAction<{ threadId: string }>) => {
      delete state.artifactsByThread[action.payload.threadId];
    },
    /**
     * Remove a single artifact entry from a thread's ledger (#3024). Used
     * by the Files panel's per-row Delete affordance: caller dispatches
     * this optimistically, then fires `openhuman.ai_delete_artifact` and
     * re-upserts the snapshot on RPC failure. No-op if either the thread
     * or the artifactId is unknown.
     */
    removeArtifactForThread: (
      state,
      action: PayloadAction<{ threadId: string; artifactId: string }>
    ) => {
      const bucket = state.artifactsByThread[action.payload.threadId];
      if (!bucket) return;
      const next = bucket.filter(entry => entry.artifactId !== action.payload.artifactId);
      if (next.length === 0) {
        delete state.artifactsByThread[action.payload.threadId];
      } else {
        state.artifactsByThread[action.payload.threadId] = next;
      }
    },
    setQueueStatusForThread: (
      state,
      action: PayloadAction<{ threadId: string; status: QueueStatus }>
    ) => {
      state.queueStatusByThread[action.payload.threadId] = action.payload.status;
    },
    clearQueueStatusForThread: (state, action: PayloadAction<{ threadId: string }>) => {
      delete state.queueStatusByThread[action.payload.threadId];
    },
    beginInferenceTurn: (state, action: PayloadAction<{ threadId: string }>) => {
      state.inferenceTurnLifecycleByThread[action.payload.threadId] = 'started';
      // The live transcript belongs to the previous turn until this one's
      // `inference_start` resets it — and the tail is minted from the moment
      // the lifecycle is `started`, so it would draw the last turn's narration
      // and reasoning again under the new question. That turn is settled (its
      // trail frozen, or served by the core projection); start this one clean.
      delete state.processingByThread[action.payload.threadId];
      delete state.liveRequestIdByThread[action.payload.threadId];
    },
    markInferenceTurnStreaming: (state, action: PayloadAction<{ threadId: string }>) => {
      if (state.inferenceTurnLifecycleByThread[action.payload.threadId]) {
        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;
      state.toolTimelineRequestByThread[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,
     *   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;
      // The live rows are provably another turn's (it settled already and its
      // rows stayed on screen): this reply arrived without an
      // `inference_start` of its own. Freezing them here gave the reply a
      // copy of that turn's trail — a second, stale delegation card.
      const owner = state.toolTimelineRequestByThread[threadId];
      const foreignRows = requestId !== undefined && owner !== undefined && owner !== requestId;
      if (requestId && !foreignRows) {
        // 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];
      dropTurnBoundApproval(state, 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. Any follow-ups queued behind it are now being
      // dispatched by the backend — `queueSlice`'s own `endInferenceTurn`
      // listener drops its optimistic pills there; the queued texts reappear
      // as real messages on their dispatched turns.
    },
    clearRuntimeForThread: (state, action: PayloadAction<{ threadId: string }>) => {
      delete state.inferenceStatusByThread[action.payload.threadId];
      delete state.streamingAssistantByThread[action.payload.threadId];
      delete state.interruptedAssistantByThread[action.payload.threadId];
      delete state.inferenceHeartbeatByThread[action.payload.threadId];
      // Drop any parallel (forked) streams for this thread and their
      // request→thread mappings — a hard per-thread reset covers every branch.
      const parallelStreams = state.parallelStreamsByThread[action.payload.threadId];
      if (parallelStreams) {
        for (const requestId of Object.keys(parallelStreams)) {
          delete state.parallelRequestThreads[requestId];
        }
        delete state.parallelStreamsByThread[action.payload.threadId];
      }
      delete state.toolTimelineByThread[action.payload.threadId];
      delete state.toolTimelineRequestByThread[action.payload.threadId];
      delete state.toolTimelineSeqByThread[action.payload.threadId];
      delete state.processingByThread[action.payload.threadId];
      // `settledTurnsByThread` is kept: those turns are finished, and their
      // frozen trails are what their messages render — dropping them here (a
      // failed send, the silence timeout) would remount every settled turn.
      delete state.liveRequestIdByThread[action.payload.threadId];
      delete state.inferenceTurnLifecycleByThread[action.payload.threadId];
      dropTurnBoundApproval(state, action.payload.threadId);
      delete state.pendingPlanReviewByThread[action.payload.threadId];
      delete state.pendingWorkflowProposalsByThread[action.payload.threadId];
      delete state.queueStatusByThread[action.payload.threadId];
      delete state.pendingSendThreadIds[action.payload.threadId];
      // Note: artifactsByThread intentionally NOT cleared here. The
      // ArtifactCard renders inline in the message timeline, so the
      // snapshot needs to survive turn boundaries — historic artifacts
      // stay visible alongside the messages that produced them. Use
      // `clearArtifactsForThread` if a hard reset is desired.
    },
    clearAllChatRuntime: state => {
      state.inferenceStatusByThread = {};
      state.streamingAssistantByThread = {};
      state.inferenceHeartbeatByThread = {};
      state.parallelStreamsByThread = {};
      state.parallelRequestThreads = {};
      state.toolTimelineByThread = {};
      state.toolTimelineSeqByThread = {};
      state.turnTimelinesByThread = {};
      state.turnTranscriptsByThread = {};
      state.settledTurnsByThread = {};
      state.liveRequestIdByThread = {};
      state.toolTimelineRequestByThread = {};
      state.interruptedAssistantByThread = {};
      state.processingByThread = {};
      state.inferenceTurnLifecycleByThread = {};
      state.pendingApprovalByThread = {};
      state.queuedApprovalsByThread = {};
      state.pendingPlanReviewByThread = {};
      state.pendingWorkflowProposalsByThread = {};
      state.artifactsByThread = {};
      // The preview tabs name artifacts that are gone now.
      state.openArtifactIds = [];
      state.activeArtifactId = null;
      state.queueStatusByThread = {};
      state.pendingSendThreadIds = {};
    },
    recordChatTurnUsage: (state, action: PayloadAction<ChatTurnUsagePayload>) => {
      // Fold into the global aggregate and, when the turn names a thread, into
      // that thread's bucket (what the composer footer reads).
      applyTurnUsage(state.sessionTokenUsage, action.payload);
      const threadId = action.payload.threadId;
      if (threadId) {
        const bucket = state.usageByThread[threadId] ?? emptySessionTokenUsage();
        applyTurnUsage(bucket, action.payload);
        state.usageByThread[threadId] = bucket;
      }
    },
    /**
     * Seed a thread's usage bucket from persisted transcript totals (the
     * `openhuman.threads_token_usage` RPC). Replaces the bucket so re-opening a
     * thread reflects its on-disk history rather than starting at zero. Live
     * turns then accumulate on top via `recordChatTurnUsage`.
     */
    hydrateThreadUsage: (
      state,
      action: PayloadAction<{
        threadId: string;
        inputTokens: number;
        outputTokens: number;
        cachedTokens: number;
        /** `null` when some turn's cost is not known. */
        costUsd: number | null;
        costSource?: CostSource;
        turns: number;
        contextWindow: number;
        lastTurnInputTokens: number;
        lastTurnOutputTokens: number;
        /**
         * Context the last turn ended with (one request, not the turn's summed
         * spend). `0`/absent from an older core: fall back to the turn totals.
         */
        lastTurnContextTokens?: number;
        subAgents?: Array<{
          agentId: string;
          inputTokens: number;
          outputTokens: number;
          costUsd: number | null;
          runs: number;
        }>;
      }>
    ) => {
      const p = action.payload;
      if (!p.threadId) return;
      // Reconstruct the per-archetype sub-agent map from the persisted breakdown
      // (read back from the thread's `__` sub-agent transcripts).
      const subAgents: Record<string, SubAgentUsage> = {};
      for (const s of p.subAgents ?? []) {
        if (!s || typeof s.agentId !== 'string' || s.agentId.length === 0) continue;
        subAgents[s.agentId] = {
          agentId: s.agentId,
          inputTokens: nonNeg(s.inputTokens),
          outputTokens: nonNeg(s.outputTokens),
          costUsd: nonNeg(s.costUsd ?? 0),
          costSource: s.costUsd === null ? 'unknown' : 'charged',
          runs: nonNeg(s.runs),
        };
      }
      state.usageByThread[p.threadId] = {
        inputTokens: nonNeg(p.inputTokens),
        outputTokens: nonNeg(p.outputTokens),
        cachedTokens: nonNeg(p.cachedTokens),
        costUsd: nonNeg(p.costUsd ?? 0),
        costSource: p.costUsd === null ? 'unknown' : (p.costSource ?? 'charged'),
        turns: nonNeg(p.turns),
        lastUpdated: Date.now(),
        lastTurnInputTokens: nonNeg(p.lastTurnInputTokens),
        lastTurnOutputTokens: nonNeg(p.lastTurnOutputTokens),
        contextWindow: nonNeg(p.contextWindow),
        lastTurnContextUsed:
          nonNeg(p.lastTurnContextTokens) > 0
            ? nonNeg(p.lastTurnContextTokens)
            : nonNeg(p.lastTurnInputTokens) + nonNeg(p.lastTurnOutputTokens),
        subAgents,
      };
    },
    resetSessionTokenUsage: state => {
      state.sessionTokenUsage = emptySessionTokenUsage();
      state.usageByThread = {};
    },
    /**
     * Apply a persisted [TurnState] snapshot from the Rust core to the
     * per-thread runtime state. Used on thread switch / cold boot so the
     * UI can resume rendering an in-flight turn (or an interrupted turn
     * left behind by a previous core process).
     */
    hydrateRuntimeFromSnapshot: (
      state,
      action: PayloadAction<{ snapshot: PersistedTurnState }>
    ) => {
      const { snapshot } = action.payload;
      const threadId = snapshot.threadId;

      // A live socket driver is feeding this thread right now (the provider is
      // mounted globally, so events keep dispatching even while the user is on
      // another tab/route). The snapshot was written at the last flush boundary
      // and is at best equal to — usually behind — the in-memory state, so
      // applying it would wipe streamed prose, tool results, and any pending
      // approval card mid-turn. Leave the volatile state to the live event
      // stream. Rehydration is a
      // fallback for when there is no live driver (cold boot, new window,
      // interrupted turn), not an overwrite of one.
      const liveLifecycle = state.inferenceTurnLifecycleByThread[threadId];
      if (liveLifecycle === 'started' || liveLifecycle === 'streaming') {
        // A live turn is driving the thread — any interrupted partial from a
        // prior crashed turn is superseded and must not linger under it.
        delete state.interruptedAssistantByThread[threadId];
        return;
      }

      // `completed` is a settled turn, not an in-flight lifecycle — drop any
      // stale in-flight marker rather than store it (the in-flight enum only
      // covers started/streaming/interrupted).
      if (snapshot.lifecycle === 'completed') {
        delete state.inferenceTurnLifecycleByThread[threadId];
      } else {
        state.inferenceTurnLifecycleByThread[threadId] = snapshot.lifecycle;
      }
      // Snapshots don't carry pending-approval payloads; drop any stale in-memory
      // approval so the card reflects the rehydrated core truth, not pre-drift state.
      dropTurnBoundApproval(state, threadId);
      // Likewise drop any stale parked plan review — its gate future cannot
      // survive a rehydrate, so the card must not linger.
      delete state.pendingPlanReviewByThread[threadId];
      // Same for a workflow proposal (B4) — it's a client-only "should the
      // card render" flag with no server-side record, so a rehydrate must
      // not resurrect one left over from a previous session. But only clear
      // it on a genuinely stale snapshot (`interrupted` = crashed mid-flight
      // in a prior process): a `completed` snapshot can be this session's own
      // just-settled turn, racing against the streaming/blocking path that
      // set the proposal moments ago — clearing unconditionally here would
      // wipe a proposal that's still pending the user's Accept/Reject.
      if (snapshot.lifecycle === 'interrupted') {
        delete state.pendingWorkflowProposalsByThread[threadId];
      }

      // Terminal turns (interrupted = crashed mid-flight; completed = finished
      // normally, snapshot kept for replay) have no live driver — surface only
      // the lifecycle so the UI renders settled, not a fake "live" status /
      // streaming buffer from stale snapshot fields. The processing transcript
      // is still carried so "View processing" replays the full reasoning.
      if (snapshot.lifecycle === 'interrupted' || snapshot.lifecycle === 'completed') {
        delete state.inferenceStatusByThread[threadId];

        // A `completed` snapshot can still lag behind live state this session
        // already has for the thread: the socket-disconnect reconciliation
        // path (`ChatRuntimeProvider`) deliberately *keeps*
        // `streamingAssistantByThread` set across `endInferenceTurn` so a
        // partial reply stays visible while the socket reconnects, and a
        // `fetchAndHydrateTurnState` rehydration can land moments later. The
        // same applies to `toolTimelineByThread`, which the live event
        // stream keeps richer/fresher than a flush-boundary persisted copy.
        // Only let the snapshot clobber those lanes when it is unambiguously
        // the authority: an `interrupted` snapshot (the process that was
        // streaming is gone — nothing fresher can exist) or there is no live
        // streaming state for this thread to lose (cold boot / new window).
        const hasFresherLiveStream = Boolean(state.streamingAssistantByThread[threadId]);
        if (snapshot.lifecycle === 'interrupted' || !hasFresherLiveStream) {
          delete state.streamingAssistantByThread[threadId];
          // Settle any in-flight rows so their agent names stop pulsing
          // (no-op for an already-completed snapshot whose rows are terminal).
          state.toolTimelineByThread[threadId] = preserveLiveSubagentProse(
            state.toolTimelineByThread[threadId],
            snapshot.toolTimeline
              .map((e, seq) => toolTimelineFromPersisted(e, seq))
              .map(settleOrphanedTimelineEntry)
          );
          // Persisted order is issue order — seed the live counter with the
          // row count so events arriving after this hydration keep counting
          // up rather than restarting at 0 and colliding with existing seqs.
          state.toolTimelineSeqByThread[threadId] = snapshot.toolTimeline.length;
          state.toolTimelineRequestByThread[threadId] = snapshot.requestId;
        }
        // An interrupted turn was killed mid-answer (its core process is gone,
        // so no `chat_done` will ever complete it). The partial reply +
        // reasoning it had already streamed are persisted — surface them as a
        // SETTLED buffer (rendered static + marked interrupted, not as a live
        // pulsing stream) instead of dropping them (restore-fidelity fix 2). A
        // `completed` turn's answer is the durable message, so it has no partial
        // to keep — clear any stale interrupted buffer for the thread instead.
        if (
          snapshot.lifecycle === 'interrupted' &&
          (snapshot.streamingText.length > 0 || snapshot.thinking.length > 0)
        ) {
          state.interruptedAssistantByThread[threadId] = {
            requestId: snapshot.requestId,
            content: snapshot.streamingText,
            thinking: snapshot.thinking,
          };
          turnStateLog(
            'interrupted partial kept thread=%s chars=%d thinkingChars=%d',
            threadId,
            snapshot.streamingText.length,
            snapshot.thinking.length
          );
        } else {
          delete state.interruptedAssistantByThread[threadId];
        }
        state.processingByThread[threadId] = orderTranscriptBySeq(snapshot.transcript ?? []);
        return;
      }

      if (snapshot.iteration > 0 && snapshot.maxIterations > 0) {
        state.inferenceStatusByThread[threadId] = {
          phase: snapshot.phase ?? 'thinking',
          iteration: snapshot.iteration,
          maxIterations: snapshot.maxIterations,
          activeTool: snapshot.activeTool ?? undefined,
          activeSubagent: snapshot.activeSubagent ?? undefined,
        };
      } else {
        delete state.inferenceStatusByThread[threadId];
      }

      if (snapshot.streamingText.length > 0 || snapshot.thinking.length > 0) {
        state.streamingAssistantByThread[threadId] = {
          requestId: snapshot.requestId,
          content: snapshot.streamingText,
          thinking: snapshot.thinking,
        };
      } else {
        delete state.streamingAssistantByThread[threadId];
      }
      // This snapshot is in-flight (a live driver may be resuming it), not a
      // settled interruption — drop any stale interrupted partial for the thread.
      delete state.interruptedAssistantByThread[threadId];

      state.toolTimelineByThread[threadId] = preserveLiveSubagentProse(
        state.toolTimelineByThread[threadId],
        snapshot.toolTimeline.map((e, seq) => toolTimelineFromPersisted(e, seq))
      );
      // Persisted order is issue order — seed the live counter with the row
      // count so events arriving after this hydration keep counting up.
      state.toolTimelineSeqByThread[threadId] = snapshot.toolTimeline.length;
      state.toolTimelineRequestByThread[threadId] = snapshot.requestId;
      state.processingByThread[threadId] = orderTranscriptBySeq(snapshot.transcript ?? []);
    },
    /**
     * Rebuild durable historical subagent rows from the run ledger. This is
     * intentionally compact: streamed child prose is not replayed from the
     * ledger, but the row remains inspectable and links to its worker thread /
     * checkpoint metadata when present.
     */
    hydrateRuntimeFromRunLedger: (
      state,
      action: PayloadAction<{ threadId: string; runs: AgentRun[] }>
    ) => {
      const { threadId, runs } = action.payload;
      const existing = state.toolTimelineByThread[threadId] ?? [];
      const byId = new Map(existing.map(entry => [entry.id, entry]));
      // Live rows key their id differently from ledger rows
      // (`<thread>:subagent:<task>:<tool>` vs `subagent:<runId>`), so also
      // dedupe on the sub-agent taskId — otherwise a ledger hydrate during a
      // live turn would add a second row for a delegation already on screen.
      const liveTaskIds = new Set(
        existing.map(entry => entry.subagent?.taskId).filter(Boolean) as string[]
      );
      for (const run of runs) {
        // Ledger rows are historical/durable, not live-issued — assign the
        // next counter value like any other newly-created row so they still
        // get a stable, monotonically increasing `seq` for sorting.
        const seq = state.toolTimelineSeqByThread[threadId] ?? 0;
        const entry = timelineEntryFromRun(run, seq);
        if (liveTaskIds.has(run.id)) {
          // The parent's snapshot never settles a detached `async` row (see
          // `settleOrphanedTimelineEntry`): its lifecycle cannot say whether
          // the child is alive. That is only truthful while the child is. If
          // the core died, no `subagent_completed` is ever coming, so without
          // this the row would read "Running" forever. The ledger is the
          // independent authority on the child: startup stamps orphaned runs
          // `interrupted` (`interrupt_orphaned_agent_runs`). Let a terminal
          // ledger status settle a row that is still shown running.
          const live = existing.find(e => e.subagent?.taskId === run.id);
          const settled = timelineStatusFromRun(run.status);
          if (
            live?.status === 'running' &&
            live.subagent?.mode === 'async' &&
            settled !== 'running'
          ) {
            byId.set(live.id, {
              ...live,
              status: settled,
              subagent: live.subagent && { ...live.subagent, status: run.status },
            });
          }
          continue;
        }
        if (!entry || byId.has(entry.id)) continue;
        state.toolTimelineSeqByThread[threadId] = seq + 1;
        byId.set(entry.id, entry);
      }
      state.toolTimelineByThread[threadId] = Array.from(byId.values());
    },
  },
  extraReducers: builder => {
    builder.addCase(resetUserScopedState, () => initialState);
  },
});

export const {
  setInferenceStatusForThread,
  clearInferenceStatusForThread,
  bumpInferenceHeartbeatForThread,
  setStreamingAssistantForThread,
  clearStreamingAssistantForThread,
  markThreadSendPending,
  clearThreadSendPending,
  registerParallelRequest,
  setParallelStream,
  clearParallelRequest,
  setToolTimelineForThread,
  clearToolTimelineForThread,
  setTurnTimelinesForThread,
  streamDeltaReceived,
  subagentAwaitingUser,
  subagentDone,
  subagentCancelResolved,
  subagentIterationStarted,
  subagentSpawned,
  subagentToolCallReceived,
  subagentToolResultReceived,
  toolArgsDeltaReceived,
  toolCallReceived,
  toolResultReceived,
  clearProcessingForThread,
  appendProcessingProse,
  markSubagentCancelled,
  cancelUnresolvedTurnTimeline,
  appendSubagentStreamDelta,
  recordSubagentTranscriptTool,
  resolveSubagentTranscriptTool,
  setPendingApprovalForThread,
  clearPendingApprovalForThread,
  dropDetachedApprovalsForThread,
  clearPendingApprovalIfRequest,
  clearTurnApprovalForThread,
  resolvePendingApprovalForThread,
  setPendingPlanReviewForThread,
  clearPendingPlanReviewForThread,
  clearPendingPlanReviewIfRequest,
  setWorkflowProposalForThread,
  clearWorkflowProposalForThread,
  markWorkflowProposalCompleted,
  markWorkflowProposalSaved,
  upsertArtifactInProgressForThread,
  upsertArtifactReadyForThread,
  upsertArtifactFailedForThread,
  clearArtifactsForThread,
  removeArtifactForThread,
  openArtifact,
  closeArtifactTab,
  activateArtifactTab,
  closeArtifactPanel,
  setQueueStatusForThread,
  clearQueueStatusForThread,
  beginInferenceTurn,
  markInferenceTurnStreaming,
  endInferenceTurn,
  liveTurnStarted,
  turnSettled,
  clearRuntimeForThread,
  clearAllChatRuntime,
  recordChatTurnUsage,
  hydrateThreadUsage,
  resetSessionTokenUsage,
  hydrateRuntimeFromSnapshot,
  hydrateRuntimeFromRunLedger,
} = chatRuntimeSlice.actions;

/**
 * Fetch the persisted turn snapshot for a thread from the Rust core and,
 * if present, dispatch `hydrateRuntimeFromSnapshot`. Used on thread
 * switch so a turn that was mid-flight when the user navigated away (or
 * when the previous app session ended) re-renders rather than appearing
 * as an empty composer.
 *
 * Failures are swallowed — a missing snapshot or transport error must
 * not block thread navigation. Errors land in the `chatRuntime.turnState`
 * debug namespace for diagnosis.
 */
export const fetchAndHydrateTurnState = createAsyncThunk(
  'chatRuntime/fetchAndHydrateTurnState',
  async (threadId: string, { dispatch }) => {
    try {
      const snapshot = await threadApi.getTurnState(threadId);
      if (snapshot) {
        turnStateLog(
          'hydrated thread=%s lifecycle=%s iter=%d/%d',
          threadId,
          snapshot.lifecycle,
          snapshot.iteration,
          snapshot.maxIterations
        );
        dispatch(hydrateRuntimeFromSnapshot({ snapshot }));
      } else {
        turnStateLog('no snapshot thread=%s', threadId);
      }
      const runs = await threadApi.listRuns({ parentThreadId: threadId, limit: 50 });
      if (runs.length > 0) {
        turnStateLog('hydrated run ledger thread=%s runs=%d', threadId, runs.length);
        dispatch(hydrateRuntimeFromRunLedger({ threadId, runs }));
      }
      return snapshot;
    } catch (error) {
      turnStateLog('fetch failed thread=%s err=%O', threadId, error);
      return null;
    }
  }
);

/**
 * Wait briefly for the progress bridge to flush its terminal snapshot, then
 * hydrate it. `chat_done` is delivered by the response presenter while the
 * bridge may still be consuming the final `TurnCompleted` event; reading once
 * at that boundary can otherwise install an intermediate, last-round-only
 * transcript over the just-settled UI.
 */
export const fetchAndHydrateCompletedTurnState = createAsyncThunk(
  'chatRuntime/fetchAndHydrateCompletedTurnState',
  async (threadId: string, { dispatch, signal }) => {
    for (let attempt = 0; attempt < 20; attempt += 1) {
      if (signal.aborted) return null;
      try {
        const snapshot = await threadApi.getTurnState(threadId);
        if (signal.aborted) return null;
        if (snapshot?.lifecycle === 'completed') {
          dispatch(hydrateRuntimeFromSnapshot({ snapshot }));
          return snapshot;
        }
      } catch (error) {
        turnStateLog('completed snapshot fetch failed thread=%s err=%O', threadId, error);
        return null;
      }
      await new Promise<void>(resolve => {
        const finish = () => {
          clearTimeout(timer);
          signal.removeEventListener('abort', finish);
          resolve();
        };
        const timer = setTimeout(finish, 50);
        signal.addEventListener('abort', finish, { once: true });
        if (signal.aborted) finish();
      });
    }
    turnStateLog('completed snapshot did not arrive thread=%s', threadId);
    return null;
  }
);

/**
 * Fetch the per-turn history for a thread and populate
 * {@link ChatRuntimeState.turnTimelinesByThread} so each *past* answer renders
 * its own process trail (Phase 5). Only settled turns (completed / interrupted)
 * are stored — the live turn's rows are driven by the socket stream into
 * `toolTimelineByThread`. Failures are swallowed: missing history must never
 * block thread navigation.
 */
export const fetchAndHydrateTurnHistory = createAsyncThunk(
  'chatRuntime/fetchAndHydrateTurnHistory',
  async (threadId: string, { dispatch }) => {
    try {
      const history = await threadApi.getTurnStateHistory(threadId);
      const timelines: Record<string, ToolTimelineEntry[]> = {};
      const transcripts: Record<string, ProcessingTranscriptItem[]> = {};
      // History is newest-first; the newest turn is the one `getTurnState`
      // hydrates into `toolTimelineByThread` (rendered as the live/anchored
      // "agent insights"), so skip it here to avoid rendering it twice — this
      // field holds only the *older* settled turns.
      for (const turn of history.slice(1)) {
        if (turn.lifecycle !== 'completed' && turn.lifecycle !== 'interrupted') continue;
        if (!turn.requestId) continue;
        // A past turn can have a reasoning/narration trail with NO tool calls
        // (the agent only thought/narrated). Keep the turn whenever it has
        // either a tool timeline OR a transcript so a tool-less answer still
        // replays its thoughts (restore-fidelity fix 1) — the old
        // `toolTimeline.length === 0` skip dropped those turns entirely.
        const hasTools = turn.toolTimeline.length > 0;
        const persistedTranscript = turn.transcript ?? [];
        const hasTranscript = persistedTranscript.length > 0;
        if (!hasTools && !hasTranscript) continue;
        if (hasTools) {
          timelines[turn.requestId] = turn.toolTimeline.map((e, seq) =>
            toolTimelineFromPersisted(e, seq)
          );
        }
        if (hasTranscript) {
          // Prefer persisted `seq` for replay order, falling back to array
          // order (restore-fidelity fix 5).
          transcripts[turn.requestId] = orderTranscriptBySeq(persistedTranscript);
        }
      }
      turnStateLog(
        'hydrated turn history thread=%s timelines=%d transcripts=%d',
        threadId,
        Object.keys(timelines).length,
        Object.keys(transcripts).length
      );
      dispatch(setTurnTimelinesForThread({ threadId, timelines, transcripts }));
      return timelines;
    } catch (error) {
      turnStateLog('history fetch failed thread=%s err=%O', threadId, error);
      return null;
    }
  }
);

/**
 * Initial derived-transcript page size. Sized generously (the core clamps to
 * 500) so a reopened thread's visible turns all carry their process trail
 * without a second round-trip.
 */
const DERIVED_TRANSCRIPT_INITIAL_LIMIT = 500;

const derivedLog = debug('chatRuntime.derivedTranscript');

/**
 * Read the {@link ChatRuntimeState} out of an arbitrary redux root, tolerating
 * both the app store (`state.chatRuntime`) and a bare test store whose root IS
 * the slice state. Used only to read live-turn request ids for the skip set.
 */
function readChatRuntimeState(state: unknown): ChatRuntimeState | undefined {
  if (!state || typeof state !== 'object') return undefined;
  const root = state as Record<string, unknown>;
  if ('chatRuntime' in root && root.chatRuntime && typeof root.chatRuntime === 'object') {
    return root.chatRuntime as ChatRuntimeState;
  }
  if ('streamingAssistantByThread' in root) {
    return root as unknown as ChatRuntimeState;
  }
  return undefined;
}

/**
 * The request ids whose derived trail must NOT be hydrated: only turns that
 * are provably active in this renderer. Do not infer "live" from whichever
 * request happens to be newest in one transcript file: detached/background
 * delivery runs in a separate session, so the root file's newest request can
 * already be historical and must remain visible.
 */
function liveRequestIdsToSkip(state: unknown, threadId: string): Set<string> {
  const skip = new Set<string>();
  const runtime = readChatRuntimeState(state);
  const streamingRid = runtime?.streamingAssistantByThread[threadId]?.requestId;
  if (streamingRid) skip.add(streamingRid);
  for (const [rid, mappedThread] of Object.entries(runtime?.parallelRequestThreads ?? {})) {
    if (mappedThread === threadId) skip.add(rid);
  }
  return skip;
}

/**
 * Phase C settled-turn restore: hydrate past-turn process trails from the
 * transcript-derived projection (`openhuman.threads_transcript_get`) instead of
 * the legacy `turn_state_history` snapshot ring. Populates the SAME
 * {@link ChatRuntimeState.turnTimelinesByThread} /
 * {@link ChatRuntimeState.turnTranscriptsByThread} the legacy path did, so the
 * renderers are reused unchanged. The live/most-recent turn is skipped so
 * derived data never fights socket-fed live state.
 *
 * Automatic fallback to {@link fetchAndHydrateTurnHistory} when the flag is
 * off, the RPC errors, or the thread has no persisted transcript (legacy
 * thread). Failures never block navigation.
 */
export const fetchAndHydrateDerivedTranscript = createAsyncThunk(
  'chatRuntime/fetchAndHydrateDerivedTranscript',
  async (threadId: string, { dispatch, getState }) => {
    if (!DERIVED_TRANSCRIPT_ENABLED) {
      derivedLog('disabled thread=%s -> turn_state history', threadId);
      await dispatch(fetchAndHydrateTurnHistory(threadId));
      return null;
    }
    let page: DerivedTranscriptPage;
    try {
      page = await threadApi.getDerivedTranscript(threadId, {
        limit: DERIVED_TRANSCRIPT_INITIAL_LIMIT,
      });
    } catch (error) {
      derivedLog('rpc failed thread=%s err=%O -> turn_state history fallback', threadId, error);
      await dispatch(fetchAndHydrateTurnHistory(threadId));
      return null;
    }
    if (!page.hasTranscript) {
      derivedLog('no transcript thread=%s -> turn_state history fallback (legacy)', threadId);
      await dispatch(fetchAndHydrateTurnHistory(threadId));
      return null;
    }
    const skipRequestIds = liveRequestIdsToSkip(getState(), threadId);
    const { timelines, transcripts } = mapDisplayItems(page.items, { skipRequestIds });
    derivedLog(
      'hydrated thread=%s items=%d timelines=%d transcripts=%d skip=%d hasMore=%s',
      threadId,
      page.items.length,
      Object.keys(timelines).length,
      Object.keys(transcripts).length,
      skipRequestIds.size,
      page.hasMore
    );
    dispatch(setTurnTimelinesForThread({ threadId, timelines, transcripts }));
    return { timelines, transcripts, nextCursor: page.nextCursor ?? null, hasMore: page.hasMore };
  }
);

export default chatRuntimeSlice.reducer;