Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

165 KB
Raw Blame
"use client";

import { supportsSubmissionReplacement } from "@/lib/session-api";

import { activeWorkspaceId } from "@/lib/workspace-scope";
import {
  clearFailedSubmission,
  moveFailedSubmissions,
  readFailedSubmissions,
  serverContainsFailedSubmission,
  storeFailedSubmission,
  type FailedSubmissionRecord,
} from "@/lib/failed-submissions";
import { randomUuid } from "@/lib/random-uuid";
import { newCommandId } from "@/contracts/parse/turn-command";

import React, {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useLayoutEffect,
  useMemo,
  useReducer,
  useRef,
} from "react";
import type { ClientCommand } from "@/contracts/generated/turn-protocol";
import {
  RESPONSE_LANGUAGE_EVENT,
  RESPONSE_LANGUAGE_STORAGE_KEY,
  isResponseLanguage,
  readStoredChatResponseTimeout,
  readStoredResponseLanguage,
  resolveResponseLanguage,
  writeStoredActiveSessionId,
} from "@/context/app-shell-storage";
import type {
  StreamEvent,
  ChatMessage,
  LLMSelection,
} from "@/features/chat/model/protocol";
import { UnifiedTurnClient } from "@/features/chat/transport/UnifiedTurnClient";
import { buildStartTurnInput } from "@/features/chat/controllers/buildStartTurnInput";
import {
  getSession,
  replaceSubmission,
  getMessageTrace,
  deleteMessage,
  updateBranchSelection,
  updateSessionTitle,
  updateSessionReplyLanguage,
  type MessageTracePage,
  type SessionMessage,
  type OrphanedFailedTurn,
} from "@/lib/session-api";
import {
  TraceCache,
  compactTracePreview,
  settleMessageTrace,
  traceSettleAction,
  type MessageTraceMetadata,
} from "@/features/chat/trace/memory";
import {
  appendWithEmphasisRepair,
  normalizeMarkdownForDisplay,
  repairChineseEmphasis,
} from "@/lib/markdown-display";
import { normalizeMessageContent } from "@/lib/message-content";
import {
  buildVisiblePath,
  persistedBranchSelections,
  selectChildBranch,
  tipMessageId,
} from "@/lib/message-branches";
import { nextOptimisticId, resolvePersistedMessage } from "@/lib/optimistic-id";
import { recoveryPrincipal, RECOVERY_PRINCIPAL_CHANGED } from "@/lib/recovery-principal";
import {
  SUBMIT_CONNECT_RETRY_INTERVAL_MS,
  SUBMIT_CONNECT_RETRY_LIMIT,
} from "@/lib/send-retry";
import { reconcileTurnIds } from "@/lib/turn-reconcile";
import { decideFailedTurnReplay, isFailedTurnVisible } from "@/lib/chat-resend";
import { shouldAppendEventContent } from "@/lib/stream";
import { hasPendingAskUserInMessages, pendingAskUserKeyInMessages } from "@/lib/ask-user-state";
import { notify } from "@/lib/notifications";
import { forwardReaderAction } from "@/lib/reading-reader-action";
import {
  normalizeReadingMaterialId,
  normalizeReadingMaterialRevision,
  readingTurnFields,
} from "@/lib/reading-turn-state";
import {
  decideIdleTurnRecovery,
  resolveLoadedRunStatus,
} from "@/lib/chat-idle-recovery";
import i18n from "i18next";
import {
  normalizeBookReferences,
  type BookReferencePayload,
} from "@/lib/book-references";
import {
  normalizeWorkspaceMode,
  type WorkspaceMode,
} from "@/lib/workspace-mode";
import {
  normalizeReadingReferences,
  type ReadingReferencePayload,
} from "@/lib/reading-references";

type SessionRuntimeStatus =
  "idle" | "running" | "completed" | "failed" | "cancelled" | "rejected";

interface OutgoingAttachment {
  type: string;
  url?: string;
  base64?: string;
  filename?: string;
  mime_type?: string;
}

interface NotebookReferencePayload {
  notebook_id: string;
  record_ids: string[];
}

type HistoryReferencePayload = string[];

type QuestionNotebookReferencePayload = number[];

type MemoryReferencePayload = Array<"summary" | "profile">;

export interface SendMessageOptions {
  displayUserMessage?: boolean;
  persistUserMessage?: boolean;
  requestSnapshotOverride?: MessageRequestSnapshot;
  /** Internal resend identity: reuse the original server correlation token. */
  retrySubmissionId?: string;
  replacesSubmissionId?: string;
  replacementRootSubmissionId?: string;
  replacedMessageId?: number;
  bookReferences?: BookReferencePayload[];
  readingReferences?: ReadingReferencePayload[];
  /** Edit-branching: when set, the new user message is inserted as a
   *  sibling under this parent rather than appended to the session tail.
   *  ``null`` means "explicitly attach to the session root". */
  parentMessageId?: number | null;
  /** Which mastery question this message is answering. Set when the message
   *  came from a question card, so the backend can commit the answer to the
   *  engine before the tutor's first token instead of pairing a bare "C"
   *  with a question from scrollback. */
  masteryAnswer?: { question_id: string; text: string } | null;
  /** Which mastery question this message drops. Set when the learner used the
   *  card's skip control, so the engine is clear of it before the tutor's
   *  first ``mastery_status`` — otherwise the next ``mastery_quiz`` simply
   *  re-presents the question they just declined. */
  masterySkip?: { question_id: string } | null;
  /** Run this one turn in another mode (a reading "Quiz me" asks the quiz
   *  engine) without switching the conversation's own mode. Recorded in the
   *  turn's snapshot, so a regenerate runs in it again. */
  capability?: string;
  /** The note page's learning block this turn fills in (note companion). */
  noteGeneration?: { block_id: string; kind?: string } | null;
}

/** Per-conversation narrowing of the workspace's skill and MCP selections.
 *  Both lists are intersected with what the workspace allows, never added to
 *  it, so a conversation can only ever reach less than its workspace. */
export interface ResourceSelection {
  skills: string[];
  mcp: string[];
}

export function emptyResourceSelection(): ResourceSelection {
  return { skills: [], mcp: [] };
}

/**
 * A message sent while a turn was still running.
 *
 * Text-only messages are offered to the running turn (``user_input``), whose
 * agent loop reads them at its next step boundary — after the tool call or
 * model output in flight — and steers by them. Whatever the turn never reads
 * (it ended first, its mode has no steps, or the message carries attachments
 * or references) is sent as the next turn, in order, once the turn ends.
 */
export interface QueuedMessage {
  /** Also the command id it is offered to the running turn under. */
  id: string;
  content: string;
  /** The send it becomes as a turn of its own. */
  send: Parameters<ChatContextValue["sendMessage"]>;
  /** Text only, so the running turn can take it. */
  steerable: boolean;
  /** The turn it was offered to; null until offered. */
  offeredTo: string | null;
}

export interface ChatState {
  /** Local identity, available before the backend assigns a session ID. */
  sessionKey: string;
  /** The draft key this entry had before the server bound it to a session.
   *  Lets per-conversation UI state (the viewer's tabs) follow the draft
   *  across the re-key instead of mistaking it for leaving the draft. */
  boundFromKey?: string | null;
  sessionId: string | null;
  sessionTitle: string;
  enabledTools: string[];
  activeCapability: string | null;
  /** Stable product surface; per-turn capability selection is orthogonal. */
  workspaceMode: WorkspaceMode | null;
  knowledgeBases: string[];
  llmSelection: LLMSelection | null;
  /** Persistent mastery state associated with this conversation. */
  masteryPathId: string | null;
  /** Note page this conversation is held beside (the notebook's companion);
   *  sent with every turn so the notes tools read and propose against it. */
  noteDocumentId: string | null;
  /** What this mastery conversation is for — "outline" | "study" | "review".
   *  Durable like the path id and decided when the conversation is opened: it
   *  picks the tutor's prompt block and narrows its tool surface, so a session
   *  that changed it mid-way would hand itself tools its kind withholds. */
  masterySessionMode: string | null;
  workspaceId: string | null;
  /** Session-level persona preference; "" = Default (no persona). Applies
   *  to every following message until changed (persisted on the session). */
  personaSelection: string;
  /** Who answers this conversation instead of DeepTutor — `partner:<id>` or
   *  `subagent:<name>`; null when DeepTutor does. Sent with every turn and
   *  kept on the session, so it holds until the learner hands it back. */
  answerBy: string | null;
  /** Skills and MCP servers this conversation narrowed itself to. Empty means
   *  inherit — everything the workspace allows — which is what a conversation
   *  that never opened the pickers keeps sending. */
  resourceSelection: ResourceSelection;
  messages: MessageItem[];
  isStreaming: boolean;
  currentStage: string;
  language: string;
  /** Explicit conversation choice; null follows the account reply language. */
  replyLanguageOverride: string | null;
  /** Edit-branching: keyed by stringified parent_message_id (or "null"
   *  for the root). Empty means "default to latest sibling everywhere". */
  selectedBranches: Record<string, number>;
  /** True when the last turn ended in a failure (not a user cancel) and
   *  the session is no longer streaming. Drives the Resend affordance. */
  lastTurnFailed: boolean;
  /** True when the tail of the transcript is a user row the server never
   *  accepted (#1594). Drives the composer-adjacent error banner; the
   *  error must not render as an assistant reply. */
  submissionFailed: boolean;
  /** The text was recovered without its attachments or other request context. */
  submissionNeedsReview: boolean;
  /** No browser storage accepted even the text. Copy before leaving this tab. */
  submissionNotSaved: boolean;
  /** Messages sent while a turn ran, oldest first. */
  queuedMessages: QueuedMessage[];
}

export interface SessionConfiguration {
  capability?: string | null;
  workspaceMode?: WorkspaceMode | null;
  knowledgeBases?: string[];
  masteryPathId?: string | null;
  masterySessionMode?: string | null;
  noteDocumentId?: string | null;
  workspaceId?: string | null;
  enabledTools?: string[];
}

interface SessionStatusSnapshot {
  sessionId: string;
  status: SessionRuntimeStatus;
  activeTurnId: string | null;
  updatedAt: number;
}

export interface MessageAttachment {
  type: string;
  filename?: string;
  base64?: string;
  url?: string;
  mime_type?: string;
  /** Stable per-attachment id; matches the URL segment served by /files/attachments. */
  id?: string;
  /** Plain-text rendering of office docs, populated by the backend extractor.
   *  Used by the preview drawer to show "what the LLM saw" for binary docs. */
  extracted_text?: string;
  /** Set on files the assistant produced this turn (exec
   *  artifacts) rather than files the user uploaded. Rendered as openable
   *  cards under the assistant message. */
  generated?: boolean;
  /** Byte size of the generated file, for the card's subtitle. */
  size_bytes?: number;
  /** Unified content-workspace presentation metadata. Physical paths are
   * deliberately never sent to the browser. */
  origin?: "workspace";
  workspace_id?: string;
  workspace_item_id?: string;
  relative_path?: string;
  sha256?: string;
  title?: string;
  caption?: string;
}

export interface MessageRequestSnapshot {
  /** Durable edit intent; replay the exact reserved wire request after a lost acknowledgement. */
  replacesSubmissionId?: string;
  replacementRootSubmissionId?: string;
  replacementRequest?: Record<string, unknown>;
  resourceSelection?: ResourceSelection;
  content: string;
  capability?: string | null;
  workspaceMode?: WorkspaceMode | null;
  workspaceId?: string | null;
  replyLanguageOverride?: string | null;
  enabledTools: string[];
  knowledgeBases: string[];
  language: string;
  attachments?: MessageAttachment[];
  config?: Record<string, unknown>;
  notebookReferences?: NotebookReferencePayload[];
  historyReferences?: HistoryReferencePayload;
  questionNotebookReferences?: QuestionNotebookReferencePayload;
  bookReferences?: BookReferencePayload[];
  readingReferences?: ReadingReferencePayload[];
  masteryPathId?: string;
  masterySessionMode?: string;
  masteryAnswer?: { question_id: string; text: string };
  masterySkip?: { question_id: string };
  timedMediaId?: string;
  persona?: string;
  memoryReferences?: MemoryReferencePayload;
  llmSelection?: LLMSelection | null;
  /** Stable identity of the material open for this turn. */
  readingMaterialId?: string;
  /** Immutable content revision open when the turn was submitted. */
  readingMaterialRevision?: number;
  /** The passage the question was asked about, and the unit it came from. */
  readingSelection?: ReadingSelectionSnapshot;
  /** Complete wire context captured at first send for deterministic retry. */
  readingTurnFields?: ReturnType<typeof readingTurnFields>;
  watchingTurnFields?: { timed_media_id?: string; timed_media_viewport?: { time_seconds: number } };
  /** `capability` ran for this turn only (see SendMessageOptions.capability). */
  capabilityOnce?: boolean;
  /** The note page's learning block this turn filled in (note companion). */
  noteGeneration?: { block_id: string; kind?: string };
}

export interface ReadingSelectionSnapshot {
  quote: string;
  locator: number;
}

export interface MessageItem {
  id?: number;
  role: "user" | "assistant" | "system";
  content: string;
  /** Original model text accumulated during a live stream. Kept separate from
   * `content`, which may be Markdown-normalized for display. */
  rawContent?: string;
  capability?: string;
  events?: StreamEvent[];
  attachments?: MessageAttachment[];
  requestSnapshot?: MessageRequestSnapshot;
  trace?: MessageTraceMetadata;
  /** Edit-branching: id of the message this row continues. */
  parentMessageId?: number | null;
  /** This submission never reached the server (#1594). Rendered with an
   *  "unsent" marker; its requestSnapshot drives the retry. */
  failedSubmission?: boolean;
  failedSubmissionNeedsReview?: boolean;
  failedSubmissionNotSaved?: boolean;
  failedSubmissionId?: string;
  /** A backend failure with a saved user row and no assistant reply (#1570). */
  orphanedFailedTurn?: OrphanedFailedTurn;
}

interface SessionEntry extends Omit<ChatState, "sessionKey"> {
  key: string;
  status: SessionRuntimeStatus;
  /** Runtime status underneath locally restored unsent messages. */
  submissionBaseStatus: SessionRuntimeStatus;
  activeTurnId: string | null;
  lastSeq: number;
  updatedAt: number;
  /** Edit-branching: maps a parent_message_id (stringified, or "null" for
   *  the session root) to the chosen child id at that branch point. */
  selectedBranches: Record<string, number>;
}

interface ProviderState {
  selectedKey: string | null;
  sessions: Record<string, SessionEntry>;
  sidebarRefreshToken: number;
}

/** A session as the server describes it. ``LOAD_SESSION`` applies it and
 *  selects the session; ``REVALIDATE_SESSION`` applies it in the background
 *  to a session the user is already reading. */
interface SessionSnapshot {
  key: string;
  sessionId: string;
  title?: string;
  messages: MessageItem[];
  activeTurnId?: string | null;
  status?: SessionRuntimeStatus;
  serverStatus?: SessionRuntimeStatus;
  tools?: string[];
  capability?: string | null;
  workspaceMode?: WorkspaceMode | null;
  knowledgeBases?: string[];
  llmSelection?: LLMSelection | null;
  masteryPathId?: string | null;
  masterySessionMode?: string | null;
  noteDocumentId?: string | null;
  workspaceId?: string | null;
  personaSelection?: string;
  answerBy?: string | null;
  resourceSelection?: ResourceSelection;
  language?: string;
  replyLanguageOverride?: string | null;
  selectedBranches?: Record<string, number>;
}

type Action =
  | { type: "RESET_ACCOUNT" }
  | { type: "SET_TOOLS"; tools: string[] }
  | { type: "SET_CAPABILITY"; cap: string | null }
  | { type: "SET_KB"; kbs: string[] }
  | { type: "SET_LLM_SELECTION"; selection: LLMSelection | null }
  // ``key`` targets a specific conversation — a backend push belongs to the
  // session that produced it, which may no longer be the selected one. The
  // composer omits it and means "the one on screen".
  | { type: "SET_MASTERY_PATH_ID"; masteryPathId: string | null; key?: string }
  | { type: "SET_MASTERY_SESSION_MODE"; mode: string | null; key?: string }
  | { type: "SET_PERSONA_SELECTION"; persona: string }
  | { type: "SET_ANSWER_BY"; answerBy: string | null }
  | { type: "SET_RESOURCE_SELECTION"; selection: ResourceSelection }
  | { type: "SET_LANGUAGE"; lang: string }
  | { type: "SET_REPLY_LANGUAGE_OVERRIDE"; key: string; language: string | null }
  | {
      type: "ADD_USER_MSG";
      key: string;
      content: string;
      capability?: string | null;
      attachments?: MessageAttachment[];
      requestSnapshot?: MessageRequestSnapshot;
      parentMessageId?: number | null;
      failedSubmissionId?: string;
    }
  | { type: "SET_SUBMISSION_PERSISTENCE"; key: string; submissionId: string; saved: boolean }
  | { type: "POP_LAST_ASSISTANT"; key: string }
  | { type: "RESTORE_ASSISTANT"; key: string; message: MessageItem }
  | { type: "STREAM_START"; key: string; startedAt: number; capability?: string | null }
  | { type: "QUEUE_MESSAGE"; key: string; message: QueuedMessage }
  | { type: "OFFER_QUEUED"; key: string; ids: string[]; turnId: string }
  | { type: "DROP_QUEUED"; key: string; ids: string[] }
  | { type: "STREAM_TOUCH"; key: string }
  | { type: "STREAM_EVENT"; key: string; event: StreamEvent }
  | {
      type: "STREAM_END";
      key: string;
      status?: SessionRuntimeStatus;
      errorMessage?: string;
      turnId?: string | null;
      /** The turn never left this tab: the WebSocket could not connect, so
       *  the server never saw the user's message (#1594). */
      submissionFailed?: boolean;
    }
  | {
      type: "BIND_SERVER_SESSION";
      key: string;
      sessionId: string;
      turnId?: string | null;
    }
  | ({ type: "LOAD_SESSION" } & SessionSnapshot)
  | ({ type: "REVALIDATE_SESSION" } & SessionSnapshot)
  | { type: "SELECT_SESSION"; key: string }
  | { type: "SET_SESSION_TITLE"; key: string; title: string }
  | {
      type: "RECONCILE_TURN";
      key: string;
      turnId?: string | null;
      userMessageId?: number | null;
      assistantMessageId?: number | null;
    }
  | {
      type: "SET_MESSAGE_TRACE";
      key: string;
      messageId: number;
      events: StreamEvent[];
      trace: MessageTraceMetadata;
    }
  | {
      type: "SETTLE_MESSAGE_TRACE";
      key: string;
      messageId: number;
      turnId: string | null;
    }
  | { type: "DELETE_TURN"; key: string; messageId: number }
  | { type: "DISCARD_FAILED_SUBMISSION"; key: string; messageId: number; submissionId: string }
  | {
      type: "NEW_SESSION";
      key: string;
      configuration?: SessionConfiguration;
    }
  | {
      type: "CONFIGURE_SESSION";
      key?: string;
      configuration: SessionConfiguration;
    }
  | { type: "ENSURE_DRAFT_SESSION"; key: string; failedRecords?: FailedSubmissionRecord[] }
  | {
      type: "SET_SELECTED_BRANCH";
      key: string;
      parentKey: string;
      childId: number;
    }
  | {
      type: "REPLACE_SELECTED_BRANCHES";
      key: string;
      selectedBranches: Record<string, number>;
    }
  | { type: "BUMP_SIDEBAR_REFRESH" };

function createSessionEntry(
  key: string,
  sessionId: string | null = null,
): SessionEntry {
  return {
    key,
    sessionId,
    sessionTitle: "",
    enabledTools: [],
    activeCapability: null,
    workspaceMode: null,
    knowledgeBases: [],
    llmSelection: null,
    masteryPathId: null,
    masterySessionMode: null,
    noteDocumentId: null,
    workspaceId: activeWorkspaceId() || null,
    personaSelection: "",
    answerBy: null,
    resourceSelection: emptyResourceSelection(),
    messages: [],
    isStreaming: false,
    currentStage: "",
    language:
      typeof window === "undefined" ? "en" : readStoredResponseLanguage(),
    replyLanguageOverride: null,
    status: "idle",
    submissionBaseStatus: "idle",
    activeTurnId: null,
    lastSeq: 0,
    updatedAt: Date.now(),
    selectedBranches: {},
    lastTurnFailed: false,
    submissionFailed: false,
    submissionNeedsReview: false,
    submissionNotSaved: false,
    queuedMessages: [],
  };
}

function draftFailedSubmissionKey(): string {
  return `draft:${activeWorkspaceId() || "general"}`;
}

function restoredFailedMessage(
  record: FailedSubmissionRecord,
  parentMessageId: number | null,
): MessageItem {
  const stored = record.requestSnapshot;
  const base: Record<string, unknown> =
    typeof stored === "object" && stored !== null
      ? (stored as Record<string, unknown>)
      : {};
  const snapshot = {
    ...base,
    content: record.content,
    enabledTools: Array.isArray(base.enabledTools) ? base.enabledTools : [],
    knowledgeBases: Array.isArray(base.knowledgeBases) ? base.knowledgeBases : [],
    language: typeof base.language === "string" ? base.language : "en",
  } as MessageRequestSnapshot;
  return {
    id: nextOptimisticId(),
    role: "user",
    content: record.content,
    capability: record.capability,
    parentMessageId,
    ...(snapshot.attachments?.length ? { attachments: snapshot.attachments } : {}),
    requestSnapshot: snapshot,
    failedSubmission: true,
    failedSubmissionNeedsReview: record.retryRequiresReview,
    failedSubmissionId: record.submissionId,
  };
}

function ensureSelectedSession(state: ProviderState): SessionEntry {
  if (state.selectedKey && state.sessions[state.selectedKey]) {
    return state.sessions[state.selectedKey];
  }
  return createSessionEntry("draft");
}

function updateSessionQueue(
  state: ProviderState,
  key: string,
  update: (queue: QueuedMessage[]) => QueuedMessage[],
): ProviderState {
  const session = state.sessions[key];
  if (!session) return state;
  return {
    ...state,
    sessions: {
      ...state.sessions,
      [key]: { ...session, queuedMessages: update(session.queuedMessages ?? []) },
    },
  };
}

/** The queued messages a turn's loop just read (its ``user_input`` row). */
export function readUserInputIds(event: StreamEvent): string[] {
  const metadata = event.metadata as { trace_kind?: string; user_inputs?: unknown } | undefined;
  if (metadata?.trace_kind !== "user_input" || !Array.isArray(metadata.user_inputs)) return [];
  return metadata.user_inputs
    .map((item) => String((item as { command_id?: unknown })?.command_id ?? ""))
    .filter(Boolean);
}

function updateSelectedSession(
  state: ProviderState,
  updater: (session: SessionEntry) => SessionEntry,
): ProviderState {
  const current = ensureSelectedSession(state);
  const key = state.selectedKey || current.key;
  const nextSession = updater(current);
  return {
    ...state,
    selectedKey: key,
    sessions: {
      ...state.sessions,
      [key]: nextSession,
    },
  };
}

function applySessionConfiguration(
  session: SessionEntry,
  configuration?: SessionConfiguration,
): SessionEntry {
  if (!configuration) return session;
  return {
    ...session,
    activeCapability:
      configuration.capability !== undefined
        ? configuration.capability
        : session.activeCapability,
    workspaceMode:
      configuration.workspaceMode !== undefined
        ? configuration.workspaceMode
        : session.workspaceMode,
    knowledgeBases:
      configuration.knowledgeBases !== undefined
        ? [...configuration.knowledgeBases]
        : session.knowledgeBases,
    masteryPathId:
      configuration.masteryPathId !== undefined
        ? configuration.masteryPathId
        : session.masteryPathId,
    masterySessionMode:
      configuration.masterySessionMode !== undefined
        ? configuration.masterySessionMode
        : session.masterySessionMode,
    noteDocumentId:
      configuration.noteDocumentId !== undefined
        ? configuration.noteDocumentId
        : session.noteDocumentId,
    workspaceId: configuration.workspaceId !== undefined ? configuration.workspaceId : session.workspaceId,
    enabledTools:
      configuration.enabledTools !== undefined
        ? [...configuration.enabledTools]
        : session.enabledTools,
    updatedAt: Date.now(),
  };
}

const MAX_CACHED_SESSIONS = 20;

/**
 * Keep at most ``MAX_CACHED_SESSIONS`` conversations in memory, dropping the
 * least recently touched first. Every way a conversation enters the map goes
 * through here — a new draft, one opened from history, a draft becoming a
 * session — so browsing a long history does not hold each one opened, with
 * its messages and traces, for the life of the tab. The one on screen and any
 * still streaming are never dropped; a dropped one is fetched again on open.
 */
function trimSessions(
  sessions: Record<string, SessionEntry>,
  keep: string | null,
): Record<string, SessionEntry> {
  const keys = Object.keys(sessions);
  if (keys.length <= MAX_CACHED_SESSIONS) return sessions;
  const evictable = keys
    .filter(
      (k) => k !== keep && sessions[k].status !== "running" && !sessions[k].isStreaming,
    )
    .sort((a, b) => sessions[a].updatedAt - sessions[b].updatedAt);
  const next = { ...sessions };
  for (const k of evictable.slice(0, keys.length - MAX_CACHED_SESSIONS)) delete next[k];
  return next;
}

/** Add an empty session under ``key`` and make it the selected one. */
function selectFreshDraft(
  state: ProviderState,
  key: string,
  configuration?: SessionConfiguration,
): ProviderState {
  const nextSessions = trimSessions(
    {
      ...state.sessions,
      [key]: applySessionConfiguration(createSessionEntry(key), configuration),
    },
    key,
  );
  return { ...state, selectedKey: key, sessions: nextSessions };
}

function isSameTurnEvent(a: StreamEvent, b: StreamEvent): boolean {
  const aSeq = Number(a.seq || 0);
  const bSeq = Number(b.seq || 0);
  if (aSeq <= 0 || bSeq <= 0 || aSeq !== bSeq) return false;
  const aTurn = a.turn_id || "";
  const bTurn = b.turn_id || "";
  return Boolean(aTurn && bTurn && aTurn === bTurn);
}

/**
 * Whether ``event`` is already in ``events``. A turn's events arrive in seq
 * order, so the latest one of the same turn usually settles it at once; only
 * a replay of something older needs the full look. Scanning every event for
 * every new one made a long turn quadratic.
 */
function hasTurnEvent(events: StreamEvent[], event: StreamEvent): boolean {
  const seq = Number(event.seq || 0);
  const turn = event.turn_id || "";
  if (seq <= 0 || !turn) return false;
  for (let index = events.length - 1; index >= 0; index -= 1) {
    const other = events[index];
    const otherSeq = Number(other.seq || 0);
    if ((other.turn_id || "") !== turn || otherSeq <= 0) continue;
    if (otherSeq < seq) return false;
    break;
  }
  return events.some((other) => isSameTurnEvent(other, event));
}

function reducer(state: ProviderState, action: Action): ProviderState {
  const next = reduce(state, action);
  // Opening a conversation from history is how most of them enter memory.
  return action.type === "LOAD_SESSION" && next !== state
    ? { ...next, sessions: trimSessions(next.sessions, next.selectedKey) }
    : next;
}

function reduce(state: ProviderState, action: Action): ProviderState {
  if (action.type === "RESET_ACCOUNT") return initialState;
  switch (action.type) {
    case "SET_TOOLS":
      return updateSelectedSession(state, (session) => ({
        ...session,
        enabledTools: action.tools,
      }));
    case "SET_CAPABILITY":
      return updateSelectedSession(state, (session) => ({
        ...session,
        activeCapability: action.cap,
      }));
    case "SET_KB":
      return updateSelectedSession(state, (session) => ({
        ...session,
        knowledgeBases: action.kbs,
      }));
    case "SET_LLM_SELECTION":
      return updateSelectedSession(state, (session) => ({
        ...session,
        llmSelection: action.selection,
      }));
    case "SET_MASTERY_SESSION_MODE": {
      // ``key`` targets the conversation that produced the change: a backend
      // push belongs to the session it came from, which may no longer be the
      // one on screen. The mode buttons omit it and mean "the one I am in".
      if (!action.key) {
        return updateSelectedSession(state, (session) => ({
          ...session,
          masterySessionMode: action.mode,
        }));
      }
      const target = state.sessions[action.key];
      if (!target) return state;
      return {
        ...state,
        sessions: {
          ...state.sessions,
          [action.key]: { ...target, masterySessionMode: action.mode },
        },
      };
    }
    case "SET_MASTERY_PATH_ID": {
      if (!action.key) {
        return updateSelectedSession(state, (session) => ({
          ...session,
          masteryPathId: action.masteryPathId,
        }));
      }
      const target = state.sessions[action.key];
      if (!target) return state;
      return {
        ...state,
        sessions: {
          ...state.sessions,
          [action.key]: { ...target, masteryPathId: action.masteryPathId },
        },
      };
    }
    case "SET_PERSONA_SELECTION":
      return updateSelectedSession(state, (session) => ({
        ...session,
        personaSelection: action.persona,
      }));
    case "SET_ANSWER_BY":
      return updateSelectedSession(state, (session) => ({
        ...session,
        answerBy: action.answerBy,
      }));
    case "SET_RESOURCE_SELECTION":
      return updateSelectedSession(state, (session) => ({
        ...session,
        resourceSelection: action.selection,
      }));
    case "SET_LANGUAGE":
      return updateSelectedSession(state, (session) => ({
        ...session,
        language: session.replyLanguageOverride ?? action.lang,
      }));
    case "SET_REPLY_LANGUAGE_OVERRIDE": {
      const session = state.sessions[action.key];
      if (!session) return state;
      return {
        ...state,
        sessions: {
          ...state.sessions,
          [action.key]: {
            ...session,
            replyLanguageOverride: action.language,
            language: action.language ?? readStoredResponseLanguage(),
          },
        },
      };
    }
    case "ADD_USER_MSG": {
      const session =
        state.sessions[action.key] ?? createSessionEntry(action.key);
      const userId = nextOptimisticId();
      const parentId =
        action.parentMessageId === undefined ? null : action.parentMessageId;
      return {
        ...state,
        sessions: {
          ...state.sessions,
          [action.key]: {
            ...session,
            submissionBaseStatus: session.messages.some(message => message.failedSubmission)
              ? session.submissionBaseStatus
              : session.status,
            messages: [
              ...session.messages,
              {
                id: userId,
                role: "user",
                content: action.content,
                capability: action.capability || "",
                parentMessageId: parentId,
                ...(action.attachments?.length
                  ? { attachments: action.attachments }
                  : {}),
                ...(action.requestSnapshot
                  ? { requestSnapshot: action.requestSnapshot }
                  : {}),
                ...(action.failedSubmissionId
                  ? { failedSubmissionId: action.failedSubmissionId }
                  : {}),
              },
            ],
            selectedBranches: selectChildBranch(
              session.selectedBranches,
              parentId,
              userId,
            ),
            updatedAt: Date.now(),
          },
        },
      };
    }
    case "SET_SUBMISSION_PERSISTENCE": {
      const session = state.sessions[action.key];
      if (!session) return state;
      return {
        ...state,
        sessions: {
          ...state.sessions,
          [action.key]: {
            ...session,
            messages: session.messages.map((message) =>
              message.failedSubmissionId === action.submissionId
                ? { ...message, failedSubmissionNotSaved: !action.saved }
                : message),
          },
        },
      };
    }
    case "DISCARD_FAILED_SUBMISSION": {
      const session = state.sessions[action.key];
      if (!session || session.isStreaming) return state;
      const target = session.messages.find(message =>
        message.id === action.messageId && message.role === "user" &&
        message.failedSubmission && message.failedSubmissionId === action.submissionId && action.messageId < 0);
      if (!target) return state;
      // Pending rows form a chain after server history. Removing an earlier
      // one must leave later recoverable submissions on the visible branch.
      const messages = session.messages
        .filter(message => message !== target)
        .map(message => message.parentMessageId === target.id
          ? { ...message, parentMessageId: target.parentMessageId ?? null }
          : message);
      const selectedBranches = { ...session.selectedBranches };
      const parentKey = String(target.parentMessageId ?? "null");
      if (selectedBranches[parentKey] === target.id) {
        const child = selectedBranches[String(target.id)];
        if (child !== undefined) selectedBranches[parentKey] = child;
        else delete selectedBranches[parentKey];
      }
      delete selectedBranches[String(target.id)];
      for (const [key, id] of Object.entries(selectedBranches)) {
        if (id === target.id) delete selectedBranches[key];
      }
      return {
        ...state,
        sessions: {
          ...state.sessions,
          [action.key]: {
            ...session, messages, selectedBranches,
            status: messages.some(message => message.failedSubmission)
              ? session.status : session.submissionBaseStatus,
            updatedAt: Date.now(),
          },
        },
      };
    }
    case "POP_LAST_ASSISTANT": {
      const session = state.sessions[action.key];
      if (!session || session.messages.length === 0) return state;
      const last = session.messages[session.messages.length - 1];
      if (last.role !== "assistant") return state;
      return {
        ...state,
        sessions: {
          ...state.sessions,
          [action.key]: {
            ...session,
            messages: session.messages.slice(0, -1),
            updatedAt: Date.now(),
          },
        },
      };
    }
    case "RESTORE_ASSISTANT": {
      // Revert an optimistic POP_LAST_ASSISTANT when the server rejects a
      // regenerate request (e.g. ``regenerate_busy``), so the user doesn't
      // silently lose their last reply.
      const session = state.sessions[action.key];
      if (!session) return state;
      const messages = [...session.messages];
      // Admission and transport failures can attach an error to the
      // optimistic placeholder before rollback. It is still the retry's
      // bubble, so discard it rather than leaving two assistant rows.
      const placeholder = messages[messages.length - 1];
      if (
        placeholder?.role === "assistant" &&
        typeof placeholder.id === "number" &&
        placeholder.id < 0
      ) {
        messages.pop();
      }
      messages.push(action.message);
      return {
        ...state,
        sessions: {
          ...state.sessions,
          [action.key]: {
            ...session,
            messages,
            updatedAt: Date.now(),
          },
        },
      };
    }
    case "QUEUE_MESSAGE":
      return updateSessionQueue(state, action.key, (queue) => [...queue, action.message]);
    case "OFFER_QUEUED":
      return updateSessionQueue(state, action.key, (queue) =>
        queue.map((queued) =>
          action.ids.includes(queued.id) ? { ...queued, offeredTo: action.turnId } : queued,
        ),
      );
    case "DROP_QUEUED":
      return updateSessionQueue(state, action.key, (queue) =>
        queue.filter((queued) => !action.ids.includes(queued.id)),
      );
    case "STREAM_START": {
      const session =
        state.sessions[action.key] ?? createSessionEntry(action.key);
      const existing = session.messages ?? [];
      // A retry (or the next message) is underway, so the trailing user row
      // is being submitted again — drop the unsent marker for the attempt
      // in flight; a failing attempt re-flags it on STREAM_END (#1594).
      const flaggedTail = existing[existing.length - 1];
      const unflagged =
        flaggedTail?.role === "user" && flaggedTail.failedSubmission
          ? [
              ...existing.slice(0, -1),
              { ...flaggedTail, failedSubmission: false },
            ]
          : existing;
      // Chain the placeholder assistant onto whatever message currently
      // sits at the tip — this is normally the user row just added by
      // ADD_USER_MSG (possibly an optimistic negative id during an edit).
      const tip = unflagged.length > 0 ? unflagged[unflagged.length - 1] : null;
      return {
        ...state,
        sessions: {
          ...state.sessions,
          [action.key]: {
            ...session,
            isStreaming: true,
            status: "running",
            // Sequence numbers belong to one turn, not the conversation.
            // Reusing the previous turn's cursor when answering ask_user
            // makes the transport drop the new turn's reply and done frames.
            activeTurnId: null,
            lastSeq: 0,
            messages: [
              ...unflagged,
              {
                id: nextOptimisticId(),
                role: "assistant",
                content: "",
                rawContent: "",
                events: [],
                // Include connection and provider latency before the first frame (#1435).
                trace: { started_at: action.startedAt },
                capability: action.capability !== undefined
                  ? action.capability || ""
                  : session.activeCapability || "",
                parentMessageId: tip?.id ?? null,
              },
            ],
            updatedAt: Date.now(),
          },
        },
      };
    }
    case "STREAM_TOUCH": {
      const session = state.sessions[action.key];
      if (!session) return state;
      return {
        ...state,
        sessions: {
          ...state.sessions,
          [action.key]: { ...session, updatedAt: Date.now() },
        },
      };
    }
    case "STREAM_EVENT": {
      // If the session entry has been removed (e.g., BIND_SERVER_SESSION
      // just renamed ``draft_X`` to a real id but a stray event still
      // targets the old key), drop the event rather than synthesise an
      // orphan session with no user message — that would scrub the
      // user's just-sent bubble from view.
      if (!state.sessions[action.key]) return state;
      const session = state.sessions[action.key];
      const msgs = [...session.messages];
      let last = msgs[msgs.length - 1];
      if (last?.role !== "assistant") {
        msgs.push({
          id: nextOptimisticId(),
          role: "assistant",
          content: "",
          rawContent: "",
          events: [],
          capability: session.activeCapability || "",
          parentMessageId: last?.id ?? null,
        });
        last = msgs[msgs.length - 1];
      }
      if (hasTurnEvent(last?.events || [], action.event)) {
        return state;
      }
      const events = [...(last?.events || []), action.event];
      const language = session.language;
      let rawContent = last?.rawContent ?? last?.content ?? "";
      let content = last?.content ?? "";
      if (shouldAppendEventContent(action.event)) {
        const delta = action.event.content;
        rawContent += delta;
        content = appendWithEmphasisRepair(content, delta, rawContent, language);
      }
      // Any other event (progress, tool rows, stage markers) leaves the text
      // alone, so it reuses the display string as-is. Re-deriving it here was
      // running the Chinese emphasis repair over the whole reply for events
      // that could not have changed a character of it.
      const capability = last?.capability || session.activeCapability || "";
      const read = readUserInputIds(action.event);
      msgs[msgs.length - 1] = {
        ...(last || { role: "assistant", content: "" }),
        content,
        rawContent,
        events,
        capability,
      };
      return {
        ...state,
        sessions: {
          ...state.sessions,
          [action.key]: {
            ...session,
            messages: msgs,
            queuedMessages: read.length
              ? (session.queuedMessages ?? []).filter((queued) => !read.includes(queued.id))
              : session.queuedMessages,
            currentStage:
              action.event.type === "stage_start"
                ? action.event.stage
                : action.event.type === "stage_end"
                  ? ""
                  : session.currentStage,
            activeTurnId: action.event.turn_id || session.activeTurnId,
            lastSeq:
              action.event.turn_id &&
              action.event.turn_id !== session.activeTurnId
                ? action.event.seq || 0
                : Math.max(session.lastSeq, action.event.seq || 0),
            updatedAt: Date.now(),
          },
        },
      };
    }
    case "STREAM_END": {
      const ending = state.sessions[action.key];
      // A submission the server never received (#1594): drop the empty
      // STREAM_START placeholder so the failure cannot read as an assistant
      // reply that errored, and flag the optimistic user row as unsent
      // instead. The connection error surfaces next to the composer, retry
      // rides on the flagged row's request snapshot. Only this submission's
      // own optimistic row qualifies — a regenerate or ask_user reply that
      // cannot connect falls through to the standard failed handling below,
      // where its user row is a row the server already holds.
      if (action.submissionFailed && ending) {
        const messages = [...ending.messages];
        const placeholder = messages[messages.length - 1];
        const candidate =
          placeholder?.role === "assistant" &&
          !placeholder.content &&
          !(placeholder.events ?? []).length
            ? messages[messages.length - 2]
            : undefined;
        if (
          candidate?.role === "user" &&
          typeof candidate.id === "number" &&
          candidate.id < 0
        ) {
          messages.pop();
          messages[messages.length - 1] = {
            ...candidate,
            failedSubmission: true,
          };
          return {
            ...state,
            sessions: {
              ...state.sessions,
              [action.key]: {
                ...ending,
                messages,
                isStreaming: false,
                currentStage: "",
                status: action.status ?? "failed",
                activeTurnId: null,
                updatedAt: Date.now(),
              },
            },
            sidebarRefreshToken: state.sidebarRefreshToken + 1,
          };
        }
      }
      // Settle the trailing line: during streaming the emphasis repair runs
      // only when a newline completes a line, so the last one is still raw.
      const settled = (() => {
        if (!ending?.messages?.length) return ending?.messages ?? [];
        const messages = [...ending.messages];
        const last = messages[messages.length - 1];
        if (last?.role !== "assistant") return messages;
        const raw = last.rawContent ?? last.content ?? "";
        const repaired = repairChineseEmphasis(raw, ending.language);
        const trace =
          ending.isStreaming && last.trace?.started_at != null
            ? { ...last.trace, ended_at: Date.now() / 1000 }
            : last.trace;
        let events = last.events ?? [];
        if (
          ["cancelled", "failed", "rejected"].includes(action.status ?? "") &&
          !events.some((event) => event.type === "error" && event.metadata?.turn_terminal)
        ) {
          events = [...events, {
            type: "error",
            source: "transport",
            stage: "",
            content: action.errorMessage ?? [...events].reverse().find((event) => event.type === "error")?.content ?? "",
            timestamp: Date.now() / 1000,
            metadata: { turn_terminal: true, status: action.status, retryable: action.status !== "cancelled" },
          }];
        }
        if (repaired === last.content && trace === last.trace && events === last.events) return messages;
        messages[messages.length - 1] = { ...last, content: repaired, trace, events };
        return messages;
      })();
      const endedTurnId = action.turnId || ending?.activeTurnId || null;
      // A completed turn can still own an unanswered card (for example, a
      // replay/sentinel race). Keep its address so submit_user_reply can
      // reach the backend waiter instead of failing the visible card.
      const pendingAskUser =
        action.status === "completed" &&
        hasPendingAskUserInMessages(settled, endedTurnId);
      return {
        ...state,
        sessions: {
          ...state.sessions,
          [action.key]: {
            ...(state.sessions[action.key] ?? createSessionEntry(action.key)),
            messages: settled,
            isStreaming: false,
            currentStage: "",
            // What the ended turn never read waits for the next one.
            queuedMessages: (ending?.queuedMessages ?? []).map((queued) =>
              queued.offeredTo ? { ...queued, offeredTo: null } : queued,
            ),
            status: action.status ?? "completed",
            submissionBaseStatus: action.status ?? "completed",
            activeTurnId:
              action.status === "running" || pendingAskUser
                ? action.turnId ||
                  state.sessions[action.key]?.activeTurnId ||
                  null
                : null,
            updatedAt: Date.now(),
          },
        },
        sidebarRefreshToken: state.sidebarRefreshToken + 1,
      };
    }
    case "BIND_SERVER_SESSION": {
      const current =
        state.sessions[action.key] ?? createSessionEntry(action.key);
      const targetKey = action.sessionId;
      const existing = state.sessions[targetKey];
      const merged: SessionEntry = {
        ...(existing ?? current),
        ...current,
        key: targetKey,
        boundFromKey: action.key === targetKey ? current.boundFromKey : action.key,
        sessionId: action.sessionId,
        sessionTitle: current.sessionTitle || existing?.sessionTitle || "",
        activeTurnId: action.turnId || current.activeTurnId,
        lastSeq:
          action.turnId && action.turnId !== current.activeTurnId
            ? 0
            : current.lastSeq,
        status: current.isStreaming ? "running" : current.status,
        updatedAt: Date.now(),
      };
      const nextSessions = { ...state.sessions };
      delete nextSessions[action.key];
      nextSessions[targetKey] = merged;
      const selectedKey =
        state.selectedKey === action.key ? targetKey : state.selectedKey;
      return {
        ...state,
        selectedKey,
        sessions: trimSessions(nextSessions, selectedKey),
        sidebarRefreshToken: state.sidebarRefreshToken + 1,
      };
    }
    case "SELECT_SESSION": {
      // Show a session we already hold in memory. No fetch, no spinner —
      // the pair to ``REVALIDATE_SESSION``, which refreshes it afterwards.
      if (!state.sessions[action.key]) return state;
      if (state.selectedKey === action.key) return state;
      return { ...state, selectedKey: action.key };
    }
    case "LOAD_SESSION":
    case "REVALIDATE_SESSION": {
      if (action.type === "REVALIDATE_SESSION") {
        // Second line of defence: ``loadSession`` already drops a revalidate
        // whose session went live, but the check belongs here too so no
        // background snapshot can ever clobber a streaming turn.
        const local = state.sessions[action.key];
        if (!local || local.isStreaming || local.status === "running") {
          return state;
        }
      }
      const existing =
        state.sessions[action.key] ??
        createSessionEntry(action.key, action.sessionId);
      return {
        ...state,
        selectedKey:
          action.type === "LOAD_SESSION" ? action.key : state.selectedKey,
        sessions: {
          ...state.sessions,
          [action.key]: {
            ...existing,
            key: action.key,
            sessionId: action.sessionId,
            sessionTitle:
              action.title !== undefined ? action.title : existing.sessionTitle,
            enabledTools: action.tools ?? existing.enabledTools,
            activeCapability:
              action.capability !== undefined
                ? action.capability
                : existing.activeCapability,
            workspaceMode:
              action.workspaceMode !== undefined
                ? action.workspaceMode
                : existing.workspaceMode,
            knowledgeBases: action.knowledgeBases ?? existing.knowledgeBases,
            llmSelection:
              action.llmSelection !== undefined
                ? action.llmSelection
                : existing.llmSelection,
            masteryPathId:
              action.masteryPathId !== undefined
                ? action.masteryPathId
                : existing.masteryPathId,
            masterySessionMode:
              action.masterySessionMode !== undefined
                ? action.masterySessionMode
                : existing.masterySessionMode,
            noteDocumentId:
              action.noteDocumentId !== undefined
                ? action.noteDocumentId
                : existing.noteDocumentId,
            workspaceId: action.workspaceId !== undefined ? action.workspaceId : existing.workspaceId,
            personaSelection:
              action.personaSelection !== undefined
                ? action.personaSelection
                : existing.personaSelection,
            answerBy:
              action.answerBy !== undefined ? action.answerBy : existing.answerBy,
            resourceSelection:
              action.resourceSelection !== undefined
                ? action.resourceSelection
                : existing.resourceSelection,
            messages: action.messages,
            isStreaming: (action.status || "idle") === "running",
            currentStage: "",
            activeTurnId: action.activeTurnId || null,
            // Loaded messages contain only a trace preview. Replay the live
            // turn from the start rather than trusting a cached cursor.
            lastSeq: 0,
            status: action.status || "idle",
            submissionBaseStatus: action.serverStatus ?? action.status ?? "idle",
            language: action.language ?? existing.language,
            replyLanguageOverride:
              action.replyLanguageOverride !== undefined
                ? action.replyLanguageOverride
                : existing.replyLanguageOverride,
            selectedBranches:
              action.selectedBranches ?? existing.selectedBranches,
            updatedAt: Date.now(),
          },
        },
      };
    }
    case "SET_SESSION_TITLE": {
      const session = state.sessions[action.key];
      if (!session) return state;
      return {
        ...state,
        sessions: {
          ...state.sessions,
          [action.key]: {
            ...session,
            sessionTitle: action.title,
            updatedAt: Date.now(),
          },
        },
        sidebarRefreshToken: state.sidebarRefreshToken + 1,
      };
    }
    case "RECONCILE_TURN": {
      // Swap the finished turn's optimistic (negative) message ids for the
      // persisted ids carried on the ``done`` event. This replaces the old
      // "refetch the whole session after every turn" reconcile, whose
      // hydrate + normalize + full re-render froze the tab for seconds on
      // long conversations.
      const session = state.sessions[action.key];
      if (!session) return state;
      const result = reconcileTurnIds(
        session.messages,
        session.selectedBranches,
        {
          turnId: action.turnId,
          userMessageId: action.userMessageId,
          assistantMessageId: action.assistantMessageId,
        },
      );
      if (!result.changed) return state;
      return {
        ...state,
        sessions: {
          ...state.sessions,
          [action.key]: {
            ...session,
            messages: result.messages,
            selectedBranches: result.selectedBranches,
            updatedAt: Date.now(),
          },
        },
      };
    }
    case "SET_MESSAGE_TRACE": {
      const session = state.sessions[action.key];
      if (!session) return state;
      const messages = session.messages.map((message) =>
        message.id === action.messageId && message.role === "assistant"
          ? { ...message, events: action.events, trace: action.trace }
          : message,
      );
      return {
        ...state,
        sessions: {
          ...state.sessions,
          [action.key]: { ...session, messages, updatedAt: Date.now() },
        },
      };
    }
    case "SETTLE_MESSAGE_TRACE": {
      // The finished message trades its full event list for the compact
      // preview it keeps in memory. Done here, from the events the reducer
      // holds, rather than from a snapshot taken in the ``done`` handler: that
      // snapshot lags React's commit, and the last round's content, tool call
      // and card arrive in the same burst as ``done`` — a stale snapshot
      // settled the message on a trace without its card.
      const session = state.sessions[action.key];
      if (!session) return state;
      //
      // The compaction is deferred by one turn. The turn that just finished is
      // the one the reader is most likely to open, and trading its events for
      // a preview means the rows they were watching a second ago have to come
      // back from the server: the reasoning vanishes from the trace, the fetch
      // lands, and the whole block jumps. Keeping the newest turn whole costs
      // one turn's events and makes opening it instant; the turn before it is
      // compacted now instead, which is what bounds the memory.
      let changed = false;
      const messages = session.messages.map((message) => {
        const settleAction = traceSettleAction(message, action.messageId);
        if (settleAction === "skip") return message;
        changed = true;
        if (settleAction === "keep") {
          const settled = settleMessageTrace(
            message.events ?? [],
            action.turnId,
            message.trace,
          );
          return {
            ...message,
            // Measured now, over the full stream, exactly as before — only the
            // events are kept. ``truncated`` describes the preview that was
            // not taken, so leaving it set would send the reader on a fetch
            // for rows already in hand.
            trace: { ...settled.trace, truncated: false },
          };
        }
        return {
          ...message,
          ...settleMessageTrace(
            message.events ?? [],
            message.trace?.turn_id ?? "",
            message.trace,
          ),
        };
      });
      if (!changed) return state;
      return {
        ...state,
        sessions: {
          ...state.sessions,
          [action.key]: { ...session, messages, updatedAt: Date.now() },
        },
      };
    }
    case "SET_SELECTED_BRANCH": {
      const session = state.sessions[action.key];
      if (!session) return state;
      return {
        ...state,
        sessions: {
          ...state.sessions,
          [action.key]: {
            ...session,
            selectedBranches: {
              ...session.selectedBranches,
              [action.parentKey]: action.childId,
            },
            updatedAt: Date.now(),
          },
        },
      };
    }
    case "REPLACE_SELECTED_BRANCHES": {
      const session = state.sessions[action.key];
      if (!session) return state;
      return {
        ...state,
        sessions: {
          ...state.sessions,
          [action.key]: {
            ...session,
            selectedBranches: { ...action.selectedBranches },
            updatedAt: Date.now(),
          },
        },
      };
    }
    case "DELETE_TURN": {
      const session = state.sessions[action.key];
      if (!session) return state;
      const idx = session.messages.findIndex((m) => m.id === action.messageId);
      if (idx === -1) return state;
      const msg = session.messages[idx];
      const toRemove = new Set<number>();
      toRemove.add(idx);
      if (msg.role === "user") {
        if (
          idx + 1 < session.messages.length &&
          session.messages[idx + 1].role === "assistant"
        ) {
          toRemove.add(idx + 1);
        }
      } else if (msg.role === "assistant") {
        if (idx - 1 >= 0 && session.messages[idx - 1].role === "user") {
          toRemove.add(idx - 1);
        }
      }
      const nextMessages = session.messages.filter((_, i) => !toRemove.has(i));
      return {
        ...state,
        sessions: {
          ...state.sessions,
          [action.key]: {
            ...session,
            messages: nextMessages,
            isStreaming: false,
            status: "idle",
            updatedAt: Date.now(),
          },
        },
        sidebarRefreshToken: state.sidebarRefreshToken + 1,
      };
    }
    case "BUMP_SIDEBAR_REFRESH":
      return {
        ...state,
        sidebarRefreshToken: state.sidebarRefreshToken + 1,
      };
    case "NEW_SESSION":
      return selectFreshDraft(state, action.key, action.configuration);
    case "CONFIGURE_SESSION": {
      const key = action.key || state.selectedKey;
      if (!key) return state;
      const session = state.sessions[key];
      if (!session) return state;
      return {
        ...state,
        sessions: {
          ...state.sessions,
          [key]: applySessionConfiguration(session, action.configuration),
        },
      };
    }
    // A chat page's child effect can create and configure a draft before this
    // provider's mount effect runs. Hydrate that empty draft in place; never
    // replace its configuration or a URL-selected server session. Repeated
    // mount effects are harmless once the failed rows have been attached.
    case "ENSURE_DRAFT_SESSION": {
      const fresh = state.selectedKey && state.sessions[state.selectedKey]
        ? state
        : selectFreshDraft(state, action.key);
      const selectedKey = fresh.selectedKey;
      if (!selectedKey || !action.failedRecords?.length) return fresh;
      const selected = fresh.sessions[selectedKey];
      if (selected.sessionId || selected.messages.length) return fresh;
      const messages: MessageItem[] = [];
      for (const record of action.failedRecords) {
        messages.push(restoredFailedMessage(record, messages.at(-1)?.id ?? null));
      }
      return {
        ...fresh,
        sessions: {
          ...fresh.sessions,
          [selectedKey]: {
            ...selected,
            messages,
            status: "failed",
          },
        },
      };
    }
    default:
      return state;
  }
}

const initialState: ProviderState = {
  selectedKey: null,
  sessions: {},
  sidebarRefreshToken: 0,
};

// Grace window between the orchestrator's ``done`` event and the actual
// WS disconnect. Keeps the connection alive long enough for post-turn
// pushes like the LLM-generated ``session_meta`` title update to land.
const POST_DONE_DISCONNECT_DELAY_MS = 15_000;

/**
 * How long after DONE to refetch the sidebar so a post-turn title shows up.
 *
 * The title is written *after* the turn finishes (see `title_service`), so the
 * sidebar refresh that `STREAM_END` already triggers necessarily runs before
 * the title exists — it re-reads the list and gets the placeholder that was
 * there all along, which is why a finished conversation could sit on "New
 * conversation" forever.
 *
 * The backend publishes the title as a post-DONE `session_meta` frame and the
 * client holds the socket open for it (above), so that is the primary path —
 * it was broken until the subscription stopped closing itself on DONE
 * (`TurnApplication.subscribe_turn`). This refetch stays as the belt to that
 * brace: a socket dropped between DONE and the title would otherwise lose it
 * with no second chance, and the cost is one list fetch per turn.
 */
const POST_DONE_TITLE_REFRESH_MS = 5_000;

interface ChatContextValue {
  state: ChatState;
  setTools: (tools: string[]) => void;
  setCapability: (cap: string | null) => void;
  setKBs: (kbs: string[]) => void;
  setLLMSelection: (selection: LLMSelection | null) => void;
  setMasteryPathId: (masteryPathId: string | null) => void;
  /** What this mastery conversation is doing — see lib/mastery-mode. */
  setMasterySessionMode: (mode: string | null) => void;
  setPersonaSelection: (persona: string) => void;
  setAnswerBy: (answerBy: string | null) => void;
  setResourceSelection: (selection: ResourceSelection) => void;
  setLanguage: (lang: string) => void;
  setReplyLanguageOverride: (language: string | null) => Promise<void>;
  sendMessage: (
    content: string,
    attachments?: OutgoingAttachment[],
    config?: Record<string, unknown>,
    notebookReferences?: NotebookReferencePayload[],
    historyReferences?: HistoryReferencePayload,
    options?: SendMessageOptions,
    questionNotebookReferences?: QuestionNotebookReferencePayload,
    persona?: string,
    memoryReferences?: MemoryReferencePayload,
  ) => void;
  /** Hold a message sent while a turn runs; ``send`` is the turn it becomes
   *  if the running turn never reads it (see ``QueuedMessage``). */
  queueMessage: (
    content: string,
    send: QueuedMessage["send"],
    steerable: boolean,
  ) => void;
  /** Take a queued message back, from the running turn too if not yet read. */
  withdrawQueuedMessage: (id: string) => void;
  cancelStreamingTurn: () => void;
  /**
   * Deliver the user's reply for a turn that is paused on an
   * ``ask_user`` tool call. Sends the reply via the unified WS so the
   * backend can substitute it into the matching ``role=tool`` message
   * and resume the agentic loop on the **same** turn.
   *
   * Resolves with whether the reply actually reached a turn that was
   * waiting for it. A question card outlives the turn that asked it — a
   * backend restart drops the waiter while the card stays on screen, fully
   * interactive — so "did this land?" has to be answerable by whoever is
   * showing the card, or the learner is left watching a spinner that will
   * never resolve.
   *
   * Accepts a plain string (legacy single-question reply) or a
   * structured object with ``answers`` (v2 multi-question reply).
   */
  submitUserReply: (
    reply:
      | string
      | {
          text?: string;
          answers?: Array<{ questionId: string; text: string }>;
        },
  ) => Promise<boolean>;
  regenerateLastMessage: () => void;
  /** Re-send the last user message after a failed turn, preserving the
   *  original request snapshot (attachments, capability, tools, KB, etc.)
   *  so the new turn runs with the same context as the failed one. */
  resendLastMessage: () => void;
  deleteTurn: (messageId: number) => Promise<void>;
  /** Forget only this browser's unsent recovery copy; never mutate a server turn. */
  discardFailedSubmission: (messageId: number) => boolean;
  /** Re-send a user message under a new branch (sibling of the original).
   *  Uses the composer's current capability / refs — only the text is
   *  taken from ``newContent``. Re-runs the turn from the original's
   *  parent context. */
  editMessage: (messageId: number, newContent: string) => Promise<boolean>;
  retryFailedSubmission: (messageId: number) => Promise<boolean>;
  /** Switch which sibling is currently visible at a branch point. */
  switchBranch: (parentMessageId: number | null, childId: number) => void;
  renameSessionTitle: (title: string) => Promise<void>;
  newSession: (configuration?: SessionConfiguration) => string;
  /** Apply route-owned preferences to an explicit loaded session (or the
   * selected draft). Dispatching by key keeps this safe immediately after
   * LOAD_SESSION, before React has committed a new context render. */
  configureSession: (
    configuration: SessionConfiguration,
    sessionKey?: string,
  ) => void;
  /** Fetch a session and apply it. Pass ``revalidate`` when the session is
   *  already on screen (see ``showCachedSession``): the snapshot is then
   *  dropped rather than applied if a turn started meanwhile. */
  loadSession: (
    sessionId: string,
    options?: { signal?: AbortSignal; revalidate?: boolean },
  ) => Promise<MessageItem[] | undefined>;
  /** Select an already-loaded session without fetching. Returns false when
   *  it isn't in memory, i.e. the caller must load it. */
  showCachedSession: (sessionId: string) => boolean;
  /** Lazily fetch one persisted turn trace and retain its compact preview. */
  loadMessageTrace: (sessionId: string, messageId: number) => Promise<void>;
  /** Restore the compact preview when a full trace is collapsed. */
  releaseMessageTrace: (sessionId: string, messageId: number) => void;
  selectedSessionId: string | null;
  sessionStatuses: Record<string, SessionStatusSnapshot>;
  sidebarRefreshToken: number;
}

const ChatCtx = createContext<ChatContextValue | null>(null);

export function hydrateMessageAttachments(
  attachments: SessionMessage["attachments"],
): MessageAttachment[] {
  return Array.isArray(attachments)
    ? attachments.map((item) => ({
        type: item.type,
        filename: item.filename,
        base64: item.base64,
        url: item.url,
        mime_type: item.mime_type,
        id: item.id,
        extracted_text: item.extracted_text,
        generated: item.generated,
        size_bytes: item.size_bytes,
        origin: item.origin,
        workspace_id: item.workspace_id,
        workspace_item_id: item.workspace_item_id,
        relative_path: item.relative_path,
        sha256: item.sha256,
        title: item.title,
        caption: item.caption,
      }))
    : [];
}

function asRecord(value: unknown): Record<string, unknown> | null {
  return value && typeof value === "object" && !Array.isArray(value)
    ? (value as Record<string, unknown>)
    : null;
}

function asStringArray(value: unknown): string[] {
  return Array.isArray(value)
    ? value.filter(
        (item): item is string => typeof item === "string" && item.length > 0,
      )
    : [];
}

function asLLMSelection(value: unknown): LLMSelection | null {
  const record = asRecord(value);
  const profileId =
    typeof record?.profile_id === "string" ? record.profile_id.trim() : "";
  const modelId =
    typeof record?.model_id === "string" ? record.model_id.trim() : "";
  return profileId && modelId
    ? { profile_id: profileId, model_id: modelId }
    : null;
}

function normalizeSelectedBranches(value: unknown): Record<string, number> {
  if (!value || typeof value !== "object" || Array.isArray(value)) return {};
  const result: Record<string, number> = {};
  for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
    const n = typeof v === "number" ? v : Number(v);
    if (Number.isInteger(n) && n > 0) result[k] = n;
  }
  return result;
}

function asMemoryReferences(value: unknown): MemoryReferencePayload {
  return asStringArray(value).filter(
    (item): item is "summary" | "profile" =>
      item === "summary" || item === "profile",
  );
}

function asNotebookReferences(value: unknown): NotebookReferencePayload[] {
  if (!Array.isArray(value)) return [];
  return value.flatMap((item) => {
    const ref = asRecord(item);
    const notebookId =
      typeof ref?.notebook_id === "string" ? ref.notebook_id : "";
    const recordIds = asStringArray(ref?.record_ids);
    return notebookId && recordIds.length
      ? [{ notebook_id: notebookId, record_ids: recordIds }]
      : [];
  });
}

function asQuestionReferences(
  value: unknown,
): QuestionNotebookReferencePayload {
  return Array.isArray(value)
    ? value
        .map((item) => (typeof item === "number" ? item : Number(item)))
        .filter((item) => Number.isInteger(item))
    : [];
}

function hydrateRequestSnapshot(
  message: SessionMessage,
  content: string,
  attachments: MessageAttachment[],
): MessageRequestSnapshot | undefined {
  const metadata = asRecord(message.metadata);
  const stored = asRecord(
    metadata?.request_snapshot ?? metadata?.requestSnapshot,
  );
  if (!stored) return undefined;

  const snapshot: MessageRequestSnapshot = {
    content: typeof stored.content === "string" ? stored.content : content,
    capability:
      typeof stored.capability === "string"
        ? stored.capability
        : message.capability || "",
    workspaceMode: normalizeWorkspaceMode(
      stored.workspaceMode ?? stored.workspace_mode,
      stored.capability ?? message.capability,
    ),
    enabledTools: asStringArray(stored.enabledTools),
    knowledgeBases: asStringArray(stored.knowledgeBases),
    language: typeof stored.language === "string" ? stored.language : "en",
    ...(attachments.length ? { attachments } : {}),
  };

  const config = {
    ...(asRecord(stored.config) ?? {}),
    ...(typeof stored.consultPartnerId === "string" ? { consult_partner_id: stored.consultPartnerId } : {}),
    ...(typeof stored.partnerDiscussionGroupId === "string" ? { partner_discussion_group_id: stored.partnerDiscussionGroupId } : {}),
    ...(typeof stored.answerBy === "string" ? { answer_by: stored.answerBy } : {}),
  };
  const notebookReferences = asNotebookReferences(stored.notebookReferences);
  const historyReferences = asStringArray(stored.historyReferences);
  const questionNotebookReferences = asQuestionReferences(
    stored.questionNotebookReferences,
  );
  const persona =
    typeof stored.persona === "string" && stored.persona.length > 0
      ? stored.persona
      : "";
  const memoryReferences = asMemoryReferences(stored.memoryReferences);
  const bookReferences = normalizeBookReferences(stored.bookReferences);
  const readingReferences = normalizeReadingReferences(
    stored.readingReferences,
  );
  const llmSelection = asLLMSelection(stored.llmSelection);
  const masteryPathId =
    typeof (stored.masteryPathId ?? stored.mastery_path_id) === "string"
      ? String(stored.masteryPathId ?? stored.mastery_path_id).trim()
      : "";
  const readingMaterialId = normalizeReadingMaterialId(
    stored.readingMaterialId ?? stored.reading_material_id,
  );
  const readingMaterialRevision = normalizeReadingMaterialRevision(
    stored.readingMaterialRevision ?? stored.reading_material_revision,
  );
  const timedMediaId =
    typeof (stored.timedMediaId ?? stored.timed_media_id) === "string"
      ? String(stored.timedMediaId ?? stored.timed_media_id).trim()
      : "";
  const readingSelection = asReadingSelection(stored.readingSelection);

  if (config && Object.keys(config).length) snapshot.config = config;
  if (notebookReferences.length)
    snapshot.notebookReferences = notebookReferences;
  if (historyReferences.length) snapshot.historyReferences = historyReferences;
  if (questionNotebookReferences.length) {
    snapshot.questionNotebookReferences = questionNotebookReferences;
  }
  if (bookReferences.length) snapshot.bookReferences = bookReferences;
  if (readingReferences.length) {
    snapshot.readingReferences = readingReferences;
  }
  if (persona) snapshot.persona = persona;
  if (memoryReferences.length) snapshot.memoryReferences = memoryReferences;
  if (llmSelection) snapshot.llmSelection = llmSelection;
  if (masteryPathId) snapshot.masteryPathId = masteryPathId;
  const noteGeneration = asRecord(stored.noteGeneration ?? stored.note_generation);
  if (typeof noteGeneration?.block_id === "string" && noteGeneration.block_id) {
    snapshot.noteGeneration = {
      block_id: noteGeneration.block_id,
      kind: typeof noteGeneration.kind === "string" ? noteGeneration.kind : "",
    };
  }
  const masteryAnswer = asRecord(stored.masteryAnswer);
  if (typeof masteryAnswer?.question_id === "string" &&
      typeof masteryAnswer.text === "string") {
    snapshot.masteryAnswer = {
      question_id: masteryAnswer.question_id,
      text: masteryAnswer.text,
    };
  }
  const masterySkip = asRecord(stored.masterySkip);
  if (typeof masterySkip?.question_id === "string") {
    snapshot.masterySkip = { question_id: masterySkip.question_id };
  }
  if (readingMaterialId) {
    snapshot.readingMaterialId = readingMaterialId;
    if (readingMaterialRevision) {
      snapshot.readingMaterialRevision = readingMaterialRevision;
    }
  }
  if (timedMediaId) snapshot.timedMediaId = timedMediaId;
  if (readingSelection) snapshot.readingSelection = readingSelection;
  if (stored.capabilityOnce === true) snapshot.capabilityOnce = true;
  return snapshot;
}

function asReadingSelection(
  value: unknown,
): ReadingSelectionSnapshot | undefined {
  const record = asRecord(value);
  const quote = typeof record?.quote === "string" ? record.quote.trim() : "";
  if (!quote) return undefined;
  const locator = Number(record?.locator);
  return {
    quote,
    locator: Number.isSafeInteger(locator) && locator > 0 ? locator : 0,
  };
}

export function ChatStateAdapterProvider({
  children,
}: {
  children: React.ReactNode;
}) {
  const [state, dispatch] = useReducer(reducer, initialState);
  const stateRef = useRef(initialState);
  const runtimeGeneration = useRef(0);
  const runnersRef = useRef<
    Map<
      string,
      {
        key: string;
        client: UnifiedTurnClient;
        replyCommand?: { fingerprint: string; commandId: string };
      }
    >
  >(new Map());
  const draftCounterRef = useRef(0);
  const retryTimersRef = useRef<Set<ReturnType<typeof setTimeout>>>(new Set());
  // Tracks in-flight regenerate requests so we can restore the popped
  // assistant message if the server rejects the request (e.g. ``regenerate_busy``
  // or ``nothing_to_regenerate``). Keyed by session entry key.
  const pendingRegenerateRef = useRef<Map<string, MessageItem>>(new Map());
  const pendingResendRef = useRef<Map<string, MessageItem>>(new Map());
  const pendingSubmissionIdsRef = useRef<
    Map<string, { storageKey: string; sourceStorageKey?: string; submissionId: string; visibleSubmissionIds: string[] }>
  >(new Map());
  const resolvingResendRef = useRef<Set<string>>(new Set());
  // Parked (``waiting_input``) turns already resubscribed to on load, keyed
  // ``<sessionKey>:<turnId>``. A parked turn keeps the conversation's lease
  // while it waits, and its ask_user card exists only in the live event
  // stream (no assistant row is persisted until the turn settles), so opening
  // the conversation must replay that stream or the card is unreachable.
  const resumedParkedTurnsRef = useRef<Set<string>>(new Set());
  const traceCacheRef = useRef<TraceCache>(new TraceCache());
  const traceRequestsRef = useRef<Map<string, AbortController>>(new Map());
  // Forward-declared so ``handleRunnerEvent`` (created above
  // ``loadSession`` in source order) can trigger a server refresh after
  // a turn finishes without taking a stale closure of ``loadSession``.
  const loadSessionRef = useRef<
    ((sessionId: string) => Promise<MessageItem[] | undefined>) | null
  >(null);
  const principalRef = useRef(recoveryPrincipal());
  const principalResolvedRef = useRef(principalRef.current !== null);

  useEffect(() => {
    const onPrincipalChanged = () => {
      const principal = recoveryPrincipal();
      if (principal === principalRef.current) return;
      const firstResolution = !principalResolvedRef.current && principalRef.current === null;
      principalRef.current = principal;
      if (principal !== null) principalResolvedRef.current = true;
      if (!firstResolution) {
        runtimeGeneration.current += 1;
        runnersRef.current.forEach(({ client }) => client.disconnect());
        runnersRef.current.clear();
        retryTimersRef.current.forEach(clearTimeout);
        retryTimersRef.current.clear();
        traceRequestsRef.current.forEach((controller) => controller.abort());
        traceRequestsRef.current.clear();
        traceCacheRef.current.clear();
        pendingSubmissionIdsRef.current.clear();
        pendingRegenerateRef.current.clear();
        pendingResendRef.current.clear();
        resolvingResendRef.current.clear();
        resumedParkedTurnsRef.current.clear();
        stateRef.current = initialState;
        dispatch({ type: "RESET_ACCOUNT" });
        writeStoredActiveSessionId(null);
      }
      dispatch({ type: "ENSURE_DRAFT_SESSION", key: `draft_${Date.now()}_${++draftCounterRef.current}`,
        failedRecords: readFailedSubmissions(draftFailedSubmissionKey()) });
    };
    window.addEventListener(RECOVERY_PRINCIPAL_CHANGED, onPrincipalChanged);
    onPrincipalChanged();
    return () => window.removeEventListener(RECOVERY_PRINCIPAL_CHANGED, onPrincipalChanged);
  }, []);

  useLayoutEffect(() => {
    stateRef.current = state;
  }, [state]);

  useEffect(() => {
    if (!state.selectedKey) return;
    for (const [key, controller] of traceRequestsRef.current) {
      if (key.startsWith(`${state.selectedKey}:`)) continue;
      controller.abort();
      traceRequestsRef.current.delete(key);
    }
    const released = traceCacheRef.current.releaseExcept(state.selectedKey);
    for (const [key, snapshot] of released) {
      const [sessionId, messageId] = key.split(":");
      dispatch({
        type: "SET_MESSAGE_TRACE",
        key: sessionId,
        messageId: Number(messageId),
        events: snapshot.events,
        trace: snapshot.metadata ?? {},
      });
    }
  }, [state.selectedKey]);

  useEffect(
    () => () => {
      runtimeGeneration.current += 1;
      runnersRef.current.forEach(({ client }) => client.disconnect());
      runnersRef.current.clear();
      retryTimersRef.current.forEach((id) => clearTimeout(id));
      retryTimersRef.current.clear();
      traceRequestsRef.current.forEach((controller) => controller.abort());
      traceRequestsRef.current.clear();
    },
    [],
  );

  const makeDraftKey = useCallback(() => {
    draftCounterRef.current += 1;
    return `draft_${Date.now()}_${draftCounterRef.current}`;
  }, []);

  const hydrateMessages = useCallback(
    (messages: SessionMessage[]): MessageItem[] => {
      return messages
        .filter((message) => message.role !== "system")
        // A row with no text, no attachments and no events has nothing to
        // render — it comes out as an empty bubble. Worse, it still counts as
        // a message, so a conversation holding only such a row shows neither
        // a transcript nor the surface's own empty state: the reading
        // companion went blank, the chat page lost its opening suggestions.
        // A turn interrupted before its first token leaves exactly this
        // behind. A streaming assistant message is not affected: it is built
        // locally as events arrive, never hydrated from the server.
        .filter(
          (message) =>
            normalizeMessageContent(message.content as unknown).trim() !== "" ||
            (message.attachments?.length ?? 0) > 0 ||
            (Array.isArray(message.events) && message.events.length > 0),
        )
        .map((message) => {
          const raw = normalizeMessageContent(message.content as unknown);
          const attachments = hydrateMessageAttachments(message.attachments);
          const requestSnapshot = hydrateRequestSnapshot(
            message,
            raw,
            attachments,
          );
          return {
            id: message.id,
            role: message.role,
            content:
              message.role === "assistant"
                ? normalizeMarkdownForDisplay(raw)
                : raw,
            capability: message.capability || "",
            events: Array.isArray(message.events) ? message.events : [],
            attachments,
            trace: message.trace,
            parentMessageId:
              message.parent_message_id === undefined
                ? null
                : message.parent_message_id,
            ...(requestSnapshot ? { requestSnapshot } : {}),
            ...(typeof message.metadata?.client_submission_id === "string"
              ? { failedSubmissionId: message.metadata.client_submission_id } : {}),
            ...(message.role === "user" && message.metadata?.orphaned_failed_turn
              ? { orphanedFailedTurn: message.metadata.orphaned_failed_turn }
              : {}),
          };
        });
    },
    [],
  );

  const moveRunner = useCallback((oldKey: string, newKey: string) => {
    if (oldKey === newKey) return;
    const runner = runnersRef.current.get(oldKey);
    if (!runner) return;
    runnersRef.current.delete(oldKey);
    runner.key = newKey;
    runnersRef.current.set(newKey, runner);
  }, []);

  const handleRunnerEvent = useCallback(
    (runnerKey: string, event: StreamEvent) => {
      const runner = runnersRef.current.get(runnerKey);
      const effectiveKey = runner?.key || runnerKey;
      // Reading tools ask the reader to act (scroll to a locator, show a mark
      // they just made) by tagging their result metadata. Re-broadcast it as a
      // DOM event so the reader pane can listen without the chat knowing it
      // exists — the same pattern the visualize prompt bridge uses.
      forwardReaderAction(event);
      if (event.type === "session") {
        const sessionId =
          (event.metadata as { session_id?: string } | undefined)?.session_id ||
          event.session_id ||
          "";
        const turnId =
          (event.metadata as { turn_id?: string } | undefined)?.turn_id ||
          event.turn_id ||
          null;
        if (sessionId) {
          const pendingSubmission = pendingSubmissionIdsRef.current.get(effectiveKey);
          const draftSession = stateRef.current.sessions[effectiveKey];
          const movedIds = pendingSubmission && !draftSession?.sessionId
            ? moveFailedSubmissions(
                pendingSubmission.storageKey,
                sessionId,
                pendingSubmission.visibleSubmissionIds,
              )
            : [];
          if (pendingSubmission && !draftSession?.sessionId &&
              movedIds.length < new Set(pendingSubmission.visibleSubmissionIds).size) {
            notify(i18n.t(
              "Some unsent messages could not be moved into this conversation. Open a new chat to recover them.",
            ), { tone: "error", durationMs: 10_000 });
          }
          if (pendingSubmission) {
            pendingSubmissionIdsRef.current.delete(effectiveKey);
            pendingSubmissionIdsRef.current.set(sessionId, movedIds.includes(pendingSubmission.submissionId)
              ? {
                  ...pendingSubmission,
                  sourceStorageKey: pendingSubmission.storageKey,
                  storageKey: sessionId,
                }
              : pendingSubmission);
          }
          dispatch({
            type: "BIND_SERVER_SESSION",
            key: effectiveKey,
            sessionId,
            turnId,
          });
          moveRunner(effectiveKey, sessionId);
        }
        return;
      }
      if (event.type === "session_meta") {
        // Post-turn metadata push: session state the backend settled during
        // the turn. It writes each value to its store *before* sending this,
        // so applying it here only catches the open client up to what a
        // reload would already show.
        const meta = event.metadata as
          | {
              title?: string;
              mastery_path_id?: string;
              mastery_session_mode?: string;
            }
          | undefined;
        // The tutor can move a conversation between mastery paths mid-turn;
        // without this the composer would keep naming the path it started on.
        if (typeof meta?.mastery_path_id === "string") {
          dispatch({
            type: "SET_MASTERY_PATH_ID",
            key: effectiveKey,
            masteryPathId: meta.mastery_path_id.trim() || null,
          });
        }
        // …and it can change what the conversation is doing. The three mode
        // buttons above the transcript are the learner's only sign of which
        // tools the tutor may reach for, so a switch the tutor made itself has
        // to move them: "I've switched to outline mode" over a header still
        // reading "Study" is the product contradicting itself out loud.
        if (typeof meta?.mastery_session_mode === "string") {
          dispatch({
            type: "SET_MASTERY_SESSION_MODE",
            key: effectiveKey,
            mode: meta.mastery_session_mode.trim() || null,
          });
        }
        const title = String(meta?.title || "").trim();
        if (title) {
          dispatch({
            type: "SET_SESSION_TITLE",
            key: effectiveKey,
            title,
          });
        } else if (!meta?.mastery_path_id) {
          dispatch({ type: "BUMP_SIDEBAR_REFRESH" });
        }
        return;
      }
      if (event.type === "done") {
        const status = String(
          (event.metadata as { status?: string } | undefined)?.status ||
            "completed",
        );
        // DONE identifies a persisted user row. Clear only this submission;
        // earlier failed sends in the same conversation remain recoverable.
        const pendingSubmission = pendingSubmissionIdsRef.current.get(effectiveKey);
        const doneUserMessageId = (event.metadata as {
          user_message_id?: number | string | null;
        } | undefined)?.user_message_id;
        if (pendingSubmission && doneUserMessageId != null) {
          clearFailedSubmission(pendingSubmission.storageKey, pendingSubmission.submissionId);
          if (pendingSubmission.sourceStorageKey) {
            clearFailedSubmission(pendingSubmission.sourceStorageKey, pendingSubmission.submissionId);
          }
        }
        pendingSubmissionIdsRef.current.delete(effectiveKey);
        dispatch({
          type: "STREAM_END",
          key: effectiveKey,
          status: (status as SessionRuntimeStatus) || "completed",
          turnId: event.turn_id || null,
        });
        pendingRegenerateRef.current.delete(effectiveKey);
        pendingResendRef.current.delete(effectiveKey);
        const runner = runnersRef.current.get(effectiveKey);
        // Hold the WS open briefly so post-turn ``session_meta`` events
        // (e.g. the LLM-generated title for the first user/assistant
        // pair) can still reach us. The backend generates the title
        // before its finally block sends the subscriber sentinel, but
        // the title model can take a couple of seconds — disconnecting
        // synchronously on ``done`` would race that publish.
        if (runner) {
          runnersRef.current.delete(effectiveKey);
          window.setTimeout(() => {
            runner.client.disconnect();
          }, POST_DONE_DISCONNECT_DELAY_MS);
        }
        // Pick up a title written after this point — see
        // POST_DONE_TITLE_REFRESH_MS.
        window.setTimeout(() => {
          dispatch({ type: "BUMP_SIDEBAR_REFRESH" });
        }, POST_DONE_TITLE_REFRESH_MS);
        // Reconcile optimistic client-side message ids with the
        // server's real ids after the turn finishes. Without this the
        // Edit button (which needs a real id to attach the new branch
        // under) and branch navigation (which keys off real ids) would
        // stay disabled until the user navigates away and back. The
        // backend attaches the persisted ids to the ``done`` event, so
        // this is an in-place swap — refetching the whole session here
        // (the previous approach) re-downloaded, re-normalized, and
        // re-rendered the entire transcript after every turn, freezing
        // the tab for seconds on long conversations.
        const doneMeta = event.metadata as {
          user_message_id?: number;
          assistant_message_id?: number;
        } | null;
        const userMessageId = doneMeta?.user_message_id ?? null;
        const assistantMessageId = doneMeta?.assistant_message_id ?? null;
        // A failed turn can still have persisted its user row. Reconcile its
        // id too, or Resend would treat it as an unsaved optimistic row and
        // submit a duplicate user message on the next attempt.
        if (assistantMessageId != null || userMessageId != null) {
          dispatch({
            type: "RECONCILE_TURN",
            key: effectiveKey,
            turnId: event.turn_id || null,
            userMessageId,
            assistantMessageId,
          });
          if (assistantMessageId != null) {
            // Compact the trace from the reducer, which sees the just-arrived
            // events that stateRef has not observed yet.
            dispatch({
              type: "SETTLE_MESSAGE_TRACE",
              key: effectiveKey,
              messageId: assistantMessageId,
              turnId: event.turn_id || null,
            });
          }
        } else if (status === "completed") {
          // Older backend without ids on ``done`` — fall back to a refetch.
          const finishedSession = stateRef.current.sessions[effectiveKey];
          const sessionId = finishedSession?.sessionId;
          if (sessionId) {
            loadSessionRef.current?.(sessionId).catch(() => {
              /* non-fatal — local state remains usable */
            });
          }
        }
        return;
      }
      const terminalError = event.type === "error" &&
        Boolean((event.metadata as { turn_terminal?: boolean } | undefined)?.turn_terminal);
      const reason = terminalError
        ? String((event.metadata as { reason?: string } | undefined)?.reason || "")
        : "";
      const submissionRejected = new Set([
        "start_turn_rejected", "invalid_command", "invalid_json",
        "unsupported_protocol_version", "unknown_message_type",
      ]).has(reason);
      // An admission rejection is not an assistant reply. Keep the
      // placeholder empty so STREAM_END can flag the optimistic user row.
      if (!submissionRejected) {
        dispatch({ type: "STREAM_EVENT", key: effectiveKey, event });
      }
      if (terminalError) {
        // Pre-flight regenerate rejections never mutate server state, so we
        // roll back the optimistic POP_LAST_ASSISTANT/STREAM_START placeholder
        // to keep the transcript in sync with the server.
        if (
          reason === "regenerate_busy" ||
          reason === "regenerate_rejected" ||
          reason === "nothing_to_regenerate" ||
          reason === "start_turn_rejected"
        ) {
          const stash =
            pendingRegenerateRef.current.get(effectiveKey) ??
            pendingResendRef.current.get(effectiveKey);
          if (stash) {
            dispatch({
              type: "RESTORE_ASSISTANT",
              key: effectiveKey,
              message: stash,
            });
          }
        }
        pendingRegenerateRef.current.delete(effectiveKey);
        pendingResendRef.current.delete(effectiveKey);
        // start_turn_rejected happens before the server creates a turn or
        // user row. Other terminal errors are not causal proof that the user
        // row was persisted either; transcript reconciliation uses the
        // client_submission_id stored on that row.
        pendingSubmissionIdsRef.current.delete(effectiveKey);
        const status = String(
          (event.metadata as { status?: string } | undefined)?.status ||
            "failed",
        );
        dispatch({
          type: "STREAM_END",
          key: effectiveKey,
          status: status as SessionRuntimeStatus,
          turnId: event.turn_id || null,
          submissionFailed: submissionRejected,
        });
      }
    },
    [moveRunner],
  );

  const ensureRunner = useCallback(
    (key: string) => {
      const existing = runnersRef.current.get(key);
      if (existing) {
        const session = stateRef.current.sessions[key];
        if (session) {
          existing.client.setResumeState(session.activeTurnId, session.lastSeq);
        }
        if (!existing.client.connected) existing.client.connect();
        return existing;
      }
      const generation = runtimeGeneration.current;
      const record: {
        key: string;
        client: UnifiedTurnClient;
        replyCommand?: { fingerprint: string; commandId: string };
      } = {
        key,
        client: new UnifiedTurnClient(
          (event) => {
            if (generation === runtimeGeneration.current) handleRunnerEvent(record.key, event);
          },
          () => {
            if (generation !== runtimeGeneration.current) return;
            const session = stateRef.current.sessions[record.key];
            if (session?.isStreaming) {
              if (
                hasPendingAskUserInMessages(
                  session.messages,
                  session.activeTurnId,
                )
              ) {
                return;
              }
              dispatch({
                type: "STREAM_END",
                key: record.key,
                status: "failed",
                errorMessage: i18n.t("Connection lost while generating. Please retry your message."),
              });
              // Surface the disconnect to the user. The WS client already
              // logs to console — we add a toast so non-debugging users
              // don't see streaming silently flatline.
              notify(
                i18n.t(
                  "Connection lost while generating. Please retry your message.",
                ),
                {
                  tone: "error",
                  durationMs: 6000,
                },
              );
            }
          },
        ),
      };
      runnersRef.current.set(key, record);
      const session = stateRef.current.sessions[key];
      if (session?.activeTurnId) {
        record.client.setResumeState(session.activeTurnId, session.lastSeq);
      }
      record.client.connect();
      return record;
    },
    [handleRunnerEvent],
  );

  const sendThroughRunner = useCallback(
    function dispatchToRunner(
      key: string,
      msg: ChatMessage | ClientCommand,
      options: { awaitAck?: boolean; attempt?: number } = {},
    ): Promise<boolean> {
      const attempt = options.attempt ?? 0;
      if (attempt > 0 && !stateRef.current.sessions[key]?.isStreaming) {
        return Promise.resolve(false);
      }
      const runner = ensureRunner(key);
      // The transport owns reconnection and queues durable replies. Local
      // connection retries must not end this already-running turn (#1648).
      if (options.awaitAck) {
        return runner.client.sendAwaitingAck(msg as ClientCommand);
      }
      if (!runner.client.connected) {
        if (attempt >= SUBMIT_CONNECT_RETRY_LIMIT) {
          console.error("WebSocket failed to connect after retries");
          dispatch({
            type: "STREAM_END",
            key,
            status: "failed",
            errorMessage: i18n.t(
              "Couldn't reach the server. Please check your connection and retry.",
            ),
            // The start_turn command never left this tab — mark the turn
            // as an unsent submission rather than a failed assistant
            // reply (#1594).
            submissionFailed: true,
          });
          // Surfaces the dead-after-N-retries case (different code path
          // from the close-while-streaming handler above). Same user
          // mental model, so same toast copy.
          notify(
            i18n.t(
              "Couldn't reach the server. Please check your connection and retry.",
            ),
            {
              tone: "error",
              durationMs: 6000,
            },
          );
          return Promise.resolve(false);
        }
        return new Promise<boolean>((resolve) => {
          const timerId = setTimeout(() => {
            retryTimersRef.current.delete(timerId);
            resolve(
              dispatchToRunner(key, msg, { ...options, attempt: attempt + 1 }),
            );
          }, SUBMIT_CONNECT_RETRY_INTERVAL_MS);
          retryTimersRef.current.add(timerId);
        });
      }
      runner.client.send(msg);
      return Promise.resolve(true);
    },
    [ensureRunner],
  );

  /** Select a session we already hold in memory, if we do.
   *
   *  Lets a caller paint a previously-opened conversation immediately and
   *  refresh it in the background (``loadSession`` with ``revalidate``),
   *  rather than blanking the view behind a spinner for a round-trip whose
   *  result it usually already has. */
  const showCachedSession = useCallback((sessionId: string) => {
    const cached = stateRef.current.sessions[sessionId];
    if (!cached?.messages.length) return false;
    dispatch({ type: "SELECT_SESSION", key: sessionId });
    return true;
  }, []);

  const releaseMessageTrace = useCallback((sessionId: string, messageId: number) => {
    const key = `${sessionId}:${messageId}`;
    traceRequestsRef.current.get(key)?.abort();
    traceRequestsRef.current.delete(key);
    const preview = traceCacheRef.current.release(key);
    if (!preview) return;
    dispatch({
      type: "SET_MESSAGE_TRACE",
      key: sessionId,
      messageId,
      events: preview.events,
      trace: preview.metadata ?? {},
    });
  }, []);

  const loadMessageTrace = useCallback(
    async (sessionId: string, messageId: number) => {
      const key = `${sessionId}:${messageId}`;
      if (traceCacheRef.current.has(key) || traceRequestsRef.current.has(key)) return;
      const session = stateRef.current.sessions[sessionId];
      if (!session || session.isStreaming || session.status === "running") return;
      const message = session.messages.find(
        (item) => item.id === messageId && item.role === "assistant",
      );
      if (!message?.trace?.turn_id) return;
      // Already holding the whole thing — the turn that just finished keeps
      // its events. Fetching would replace them with an identical list and
      // repaint the trace for nothing.
      if (
        !message.trace.truncated &&
        (message.events?.length ?? 0) >= (message.trace.total ?? 0)
      ) {
        return;
      }

      const controller = new AbortController();
      traceRequestsRef.current.set(key, controller);
      try {
        const events: StreamEvent[] = [];
        let afterSeq = 0;
        let page: MessageTracePage | null = null;
        for (let pageCount = 0; pageCount < 1000; pageCount += 1) {
          page = await getMessageTrace(
            sessionId,
            messageId,
            afterSeq,
            controller.signal,
          );
          if (controller.signal.aborted) return;
          events.push(...page.events);
          if (page.complete || page.next_seq == null) break;
          if (page.next_seq <= afterSeq) return;
          afterSeq = page.next_seq;
        }
        if (!page || controller.signal.aborted) return;
        const metadata: MessageTraceMetadata = {
          turn_id: page.turn_id,
          total: page.total,
          last_seq: page.last_seq,
          truncated: false,
          // The turn's span is measured over the whole stream and the trace
          // pages do not carry it, so dropping it here left the duration to be
          // re-derived from whatever events came back — and a turn that read
          // "11s" while collapsed read "12s" the moment it was opened.
          ...(typeof message.trace.started_at === "number"
            ? { started_at: message.trace.started_at }
            : {}),
          ...(typeof message.trace.ended_at === "number"
            ? { ended_at: message.trace.ended_at }
            : {}),
        };
        const preview = compactTracePreview(message.events ?? []);
        const evicted = traceCacheRef.current.retain(key, {
          events: preview.events,
          metadata: message.trace,
        });
        for (const [evictedKey, snapshot] of evicted) {
          const [evictedSession, evictedMessage] = evictedKey.split(":");
          dispatch({
            type: "SET_MESSAGE_TRACE",
            key: evictedSession,
            messageId: Number(evictedMessage),
            events: snapshot.events,
            trace: snapshot.metadata ?? {},
          });
        }
        dispatch({
          type: "SET_MESSAGE_TRACE",
          key: sessionId,
          messageId,
          events,
          trace: metadata,
        });
      } catch (reason) {
        if (!(reason instanceof DOMException && reason.name === "AbortError")) {
          console.warn("Failed to load message trace", reason);
        }
      } finally {
        if (traceRequestsRef.current.get(key) === controller) {
          traceRequestsRef.current.delete(key);
        }
      }
    },
    [],
  );

  const loadSession = useCallback(
    async (
      sessionId: string,
      options?: { signal?: AbortSignal; revalidate?: boolean },
    ) => {
      const generation = runtimeGeneration.current;
      const session = await getSession(sessionId, options?.signal);
      if (options?.signal?.aborted || generation !== runtimeGeneration.current) return;
      const key = session.session_id || session.id;
      const activeTurn = Array.isArray(session.active_turns)
        ? session.active_turns[0]
        : undefined;
      if (options?.revalidate) {
        // Background refresh of a session already on screen. Drop the whole
        // snapshot — data *and* the re-subscribe below — once a turn is live
        // locally: this tab is already receiving that turn's events, so
        // re-subscribing from ``after_seq: 0`` would replay them on top of
        // what we have, and the snapshot predates the turn anyway.
        const local = stateRef.current.sessions[key];
        if (!local || local.isStreaming || local.status === "running") return;
      }
      // Other conversations' opened traces go back to their previews, as on
      // any switch; this one's are moot, its messages are read afresh below.
      // Clearing outright left those traces whole in memory for good.
      for (const [cacheKey, snapshot] of traceCacheRef.current.releaseExcept(key)) {
        const [sessionId, messageId] = cacheKey.split(":");
        dispatch({
          type: "SET_MESSAGE_TRACE",
          key: sessionId,
          messageId: Number(messageId),
          events: snapshot.events,
          trace: snapshot.metadata ?? {},
        });
      }
      traceCacheRef.current.clear();
      const messages = hydrateMessages(session.messages ?? []);
      const loadedWorkspaceMode = normalizeWorkspaceMode(
        session.preferences?.workspace_mode,
        session.preferences?.capability,
      );
      const replyLanguageOverride = isResponseLanguage(
        session.preferences?.reply_language_override,
      )
        ? session.preferences.reply_language_override
        : null;
      // A stored `running` is only believable while it is recent — see
      // `resolveLoadedRunStatus`. A turn the backend never got to close out
      // (crash, restart) would otherwise open the conversation into a
      // permanent "answering" state: Stop instead of Send, with no stream to
      // stop and no way back except starting a new conversation.
      const loadedStatus = resolveLoadedRunStatus(
        (session.status as SessionRuntimeStatus | undefined) ||
          (activeTurn ? "running" : "idle"),
        Number(session.updated_at) > 0 ? Number(session.updated_at) * 1000 : 0,
        Date.now(),
        readStoredChatResponseTimeout() * 1000,
      );
      // Restore every pending submission. A matching client_submission_id on
      // a persisted user row is the only evidence that this particular send
      // was accepted; equal text from another tab is not enough.
      let restoredMessages = messages;
      let restoredStatus = loadedStatus;
      const pendingRecords = readFailedSubmissions(key).filter(record => {
        if (!serverContainsFailedSubmission(session.messages ?? [], record)) return true;
        clearFailedSubmission(key, record.submissionId);
        return false;
      });
      // A background refresh must reconcile pending records exactly like a
      // foreground load; otherwise they vanish until the next full reload.
      if (loadedStatus !== "running") {
        for (const failedRecord of pendingRecords) {
          restoredMessages = [
            ...restoredMessages,
            restoredFailedMessage(
              failedRecord,
              tipMessageId(buildVisiblePath(
                restoredMessages,
                normalizeSelectedBranches(session.preferences?.selected_branches),
              ).messages),
            ),
          ];
          restoredStatus = "failed";
        }
      }
      if (loadedStatus !== "running") {
        for (const local of stateRef.current.sessions[key]?.messages ?? []) {
          if (!local.failedSubmission || !local.failedSubmissionNotSaved ||
              !local.failedSubmissionId ||
              serverContainsFailedSubmission(session.messages ?? [], { submissionId: local.failedSubmissionId }) ||
              restoredMessages.some(message => message.failedSubmissionId === local.failedSubmissionId)) continue;
          restoredMessages = [...restoredMessages, {
            ...local,
            parentMessageId: tipMessageId(buildVisiblePath(
              restoredMessages,
              normalizeSelectedBranches(session.preferences?.selected_branches),
            ).messages),
          }];
          restoredStatus = "failed";
        }
      }
      dispatch({
        type: options?.revalidate ? "REVALIDATE_SESSION" : "LOAD_SESSION",
        key,
        sessionId: key,
        title: session.title || "",
        messages: restoredMessages,
        activeTurnId: activeTurn?.turn_id || activeTurn?.id || null,
        status: restoredStatus,
        serverStatus: loadedStatus,
        tools: Array.isArray(session.preferences?.tools)
          ? session.preferences.tools
          : [],
        // Old sessions stored Reading/Mastery as the capability itself. Once
        // promoted to a workspace mode, that value means the default Chat
        // action rather than a hidden legacy entry in the action picker.
        capability:
          session.preferences?.capability === loadedWorkspaceMode
            ? null
            : session.preferences?.capability || null,
        workspaceMode: loadedWorkspaceMode,
        knowledgeBases: Array.isArray(session.preferences?.knowledge_bases)
          ? session.preferences.knowledge_bases
          : [],
        llmSelection: asLLMSelection(session.preferences?.llm_selection),
        masteryPathId:
          typeof session.preferences?.mastery_path_id === "string"
            ? session.preferences.mastery_path_id
            : null,
        masterySessionMode:
          typeof session.preferences?.mastery_session_mode === "string"
            ? session.preferences.mastery_session_mode
            : null,
        noteDocumentId:
          typeof session.preferences?.note_document_id === "string"
            ? session.preferences.note_document_id || null
            : null,
        workspaceId: session.preferences?.workspace_id || null,
        personaSelection:
          typeof session.preferences?.persona === "string"
            ? session.preferences.persona
            : "",
        answerBy:
          typeof session.preferences?.answer_by === "string" && session.preferences.answer_by
            ? session.preferences.answer_by
            : null,
        resourceSelection: {
          skills: asStringArray(session.preferences?.skills),
          mcp: asStringArray(session.preferences?.mcp),
        },
        // Historical `preferences.language` is only the last turn's account
        // default. The dedicated selector is the durable conversation choice.
        language: replyLanguageOverride ?? readStoredResponseLanguage(),
        replyLanguageOverride,
        selectedBranches: normalizeSelectedBranches(
          session.preferences?.selected_branches,
        ),
      });
      const activeTurnId = activeTurn?.turn_id || activeTurn?.id || "";
      if (activeTurnId && loadedStatus === "running") {
        // Reached on a revalidate too, when the turn is live on the server but
        // not in this tab (started in another tab, or our socket dropped) —
        // that is exactly the case that still needs a subscribe. A turn we
        // just judged stale is not one of them: subscribing would open a
        // socket for a turn that will never speak again.
        sendThroughRunner(key, {
          type: "subscribe_turn",
          turn_id: activeTurnId,
          after_seq: 0,
        });
      } else if (activeTurnId && String(session.status || "") === "waiting_input") {
        // A parked turn still owns the conversation's lease, and its ask_user
        // card only lives in the live event stream: nothing about the pause is
        // persisted as a message until the turn settles. Without a
        // resubscribe, a reload loses the card while the turn keeps waiting —
        // the user can neither answer nor send, and only a backend restart
        // recovers the conversation. Send through the client's durable queue
        // rather than ``sendThroughRunner``: its retry gate drops a command
        // for a session that is not streaming, and a parked turn is exactly
        // that. Once per turn per tab is enough; the reducer de-duplicates a
        // replayed stream anyway.
        const resumeKey = `${key}:${activeTurnId}`;
        if (!resumedParkedTurnsRef.current.has(resumeKey)) {
          resumedParkedTurnsRef.current.add(resumeKey);
          ensureRunner(key).client.send({
            type: "subscribe_turn",
            turn_id: activeTurnId,
            after_seq: 0,
          });
        }
      }
      return messages;
    },
    [ensureRunner, hydrateMessages, sendThroughRunner],
  );

  useLayoutEffect(() => {
    loadSessionRef.current = loadSession;
  }, [loadSession]);

  useEffect(() => {
    if (typeof window === "undefined") return;
    const current = state.selectedKey
      ? state.sessions[state.selectedKey]
      : null;
    writeStoredActiveSessionId(current?.sessionId ?? null);
  }, [state.selectedKey, state.sessions]);

  useEffect(() => {
    if (typeof window === "undefined") return;

    const syncLanguage = (language: string | null | undefined) => {
      dispatch({
        type: "SET_LANGUAGE",
        lang: resolveResponseLanguage(language, readStoredResponseLanguage()),
      });
    };
    const onResponseLanguage = (event: Event) => {
      const detail = (event as CustomEvent<{ language?: string }>).detail;
      syncLanguage(detail?.language);
    };
    const onStorage = (event: StorageEvent) => {
      if (event.key === RESPONSE_LANGUAGE_STORAGE_KEY)
        syncLanguage(event.newValue);
    };

    window.addEventListener(RESPONSE_LANGUAGE_EVENT, onResponseLanguage);
    window.addEventListener("storage", onStorage);
    return () => {
      window.removeEventListener(RESPONSE_LANGUAGE_EVENT, onResponseLanguage);
      window.removeEventListener("storage", onStorage);
    };
  }, []);

  // URL is now the source of truth for session loading.
  // Initialize a draft session, restoring first-message failures before a
  // server session ID exists. A page with a URL-selected session still wins.
  //
  // React flushes a child's effects before its parent's, so any page under
  // this provider has already picked and configured its session by the time
  // this runs — a plain NEW_SESSION here would throw that away (it is what
  // used to silently drop ``/chat?capability=…&mastery_path_id=…``). The
  // reducer decides on live state; this only supplies the key it may need.
  useEffect(() => {
    if (typeof window === "undefined") return;
    dispatch({
      type: "ENSURE_DRAFT_SESSION",
      key: makeDraftKey(),
      failedRecords: readFailedSubmissions(draftFailedSubmissionKey()),
    });
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  // Idle recovery: if a streaming session receives no events for the
  // configured window (default 180s, set in Settings > Network), re-subscribe
  // from the last sequence. A quiet stream is not terminal: long research
  // calls can emit nothing for minutes, while a dropped browser connection
  // leaves the backend turn alive with replayable events.
  useEffect(() => {
    const CHECK_INTERVAL_MS = 10_000;

    const timer = setInterval(() => {
      const timeoutSeconds = readStoredChatResponseTimeout();
      const idleTimeoutMs = timeoutSeconds * 1000;
      const current = stateRef.current;
      for (const [key, session] of Object.entries(current.sessions)) {
        const decision = decideIdleTurnRecovery({
          isStreaming: session.isStreaming,
          hasPendingUserInput: hasPendingAskUserInMessages(
            session.messages,
            session.activeTurnId,
          ),
          activeTurnId: session.activeTurnId,
          lastSeq: session.lastSeq,
          updatedAt: session.updatedAt,
          now: Date.now(),
          idleTimeoutMs,
        });
        if (decision.kind === "none") continue;

        if (decision.kind === "resubscribe") {
          // Avoid retrying on every watchdog tick while the re-subscription is
          // opening. The next event will replace this timestamp naturally.
          dispatch({ type: "STREAM_TOUCH", key });
          sendThroughRunner(key, decision.message);
          continue;
        }

        // A local timeout cannot invent a terminal state. Mark the session as
        // observed so the runtime/session reconciliation path can query the
        // authoritative turn once the server supplies its id.
        dispatch({ type: "STREAM_TOUCH", key });
      }
    }, CHECK_INTERVAL_MS);

    return () => clearInterval(timer);
  }, [sendThroughRunner]);

  const sendMessage = useCallback(
    async (
      content: string,
      attachments?: OutgoingAttachment[],
      config?: Record<string, unknown>,
      notebookReferences?: NotebookReferencePayload[],
      historyReferences?: HistoryReferencePayload,
      options?: SendMessageOptions,
      questionNotebookReferences?: QuestionNotebookReferencePayload,
      persona?: string,
      memoryReferences?: MemoryReferencePayload,
    ) => {
      const generation = runtimeGeneration.current;
      const msgAttachments = attachments?.map((a) => ({
        type: a.type,
        filename: a.filename,
        base64: a.base64,
        url: a.url,
        mime_type: a.mime_type,
      }));
      const currentState = stateRef.current;
      let key = currentState.selectedKey;
      if (!key) {
        key = makeDraftKey();
        dispatch({ type: "NEW_SESSION", key });
      }
      const session = currentState.sessions[key] ?? createSessionEntry(key);
      const replaySnapshot = options?.requestSnapshotOverride;
      const exactReplay = Boolean(replaySnapshot);
      const effectiveCapability =
        exactReplay ? (replaySnapshot?.capability ?? null) :
        replaySnapshot?.capability ??
        options?.capability ??
        session.activeCapability;
      const capabilityOnce = replaySnapshot
        ? replaySnapshot.capabilityOnce === true
        : Boolean(options?.capability);
      const effectiveWorkspaceMode =
        exactReplay ? (replaySnapshot?.workspaceMode ?? null) :
        replaySnapshot?.workspaceMode ?? session.workspaceMode;
      const effectiveTools =
        replaySnapshot?.enabledTools ?? session.enabledTools;
      const effectiveKnowledgeBases =
        replaySnapshot?.knowledgeBases ?? session.knowledgeBases;
      const effectiveLLMSelection =
        exactReplay ? (replaySnapshot?.llmSelection ?? null) :
        replaySnapshot && "llmSelection" in replaySnapshot
          ? (replaySnapshot.llmSelection ?? null)
          : session.llmSelection;
      const effectiveMasteryPathId =
        exactReplay ? (replaySnapshot?.masteryPathId ?? null) :
        replaySnapshot?.masteryPathId ?? session.masteryPathId;
      const effectiveMasterySessionMode =
        exactReplay ? (replaySnapshot?.masterySessionMode ?? null) :
        replaySnapshot?.masterySessionMode ?? session.masterySessionMode;
      const effectiveLanguage =
        replaySnapshot?.language ??
        session.replyLanguageOverride ??
        readStoredResponseLanguage();
      // Persona resolution: replay snapshot wins; then an explicit per-call
      // persona (quiz follow-up surface); then the session-level preference.
      // Always a string — "" means Default / no persona.
      const effectivePersona =
        exactReplay ? (replaySnapshot?.persona ?? "") :
        replaySnapshot?.persona ?? persona ?? session.personaSelection ?? "";
      // Replays retain the original resource selection, including one-turn choices.
      const effectiveResources =
        exactReplay ? (replaySnapshot?.resourceSelection ?? emptyResourceSelection()) :
        replaySnapshot?.resourceSelection ?? session.resourceSelection ?? emptyResourceSelection();
      const effectiveMemoryReferences =
        exactReplay ? replaySnapshot?.memoryReferences :
        replaySnapshot?.memoryReferences ?? memoryReferences;
      const effectiveBookReferences =
        exactReplay ? replaySnapshot?.bookReferences :
        replaySnapshot?.bookReferences ?? options?.bookReferences;
      const effectiveReadingReferences =
        exactReplay ? replaySnapshot?.readingReferences :
        replaySnapshot?.readingReferences ?? options?.readingReferences;
      const effectiveAttachments =
        replaySnapshot?.attachments?.map((a) => ({
          type: a.type,
          filename: a.filename,
          base64: a.base64,
          url: a.url,
          mime_type: a.mime_type,
        })) ?? (exactReplay ? undefined : msgAttachments);
      const effectiveConfig = exactReplay ? replaySnapshot?.config : config ?? replaySnapshot?.config;
      const effectiveNotebookReferences =
        exactReplay ? replaySnapshot?.notebookReferences :
        replaySnapshot?.notebookReferences ?? notebookReferences;
      const effectiveHistoryReferences =
        exactReplay ? replaySnapshot?.historyReferences :
        replaySnapshot?.historyReferences ?? historyReferences;
      const effectiveQuestionNotebookReferences =
        exactReplay ? replaySnapshot?.questionNotebookReferences :
        replaySnapshot?.questionNotebookReferences ??
        questionNotebookReferences;
      const liveReadingFields = exactReplay ? {} : readingTurnFields(effectiveWorkspaceMode);
      const replaySelection = replaySnapshot?.readingSelection;
      const effectiveReadingTurnFields = exactReplay
        ? (replaySnapshot?.readingTurnFields ?? (replaySnapshot?.readingMaterialId
          ? {
              reading_material_id: replaySnapshot.readingMaterialId,
              ...(replaySnapshot.readingMaterialRevision
                ? { reading_material_revision: replaySnapshot.readingMaterialRevision }
                : {}),
              ...(replaySelection
                ? { reading_viewport: { selection: replaySelection.quote,
                    locator: replaySelection.locator } }
                : {}),
            }
          : {}))
        : replaySnapshot?.readingMaterialId
        ? {
            reading_material_id: replaySnapshot.readingMaterialId,
            ...(replaySnapshot.readingMaterialRevision
              ? {
                  reading_material_revision:
                    replaySnapshot.readingMaterialRevision,
                }
              : {}),
            // A regenerate answers the same passage, not whatever the reader
            // happens to have selected now.
            ...(replaySelection
              ? {
                  reading_viewport: {
                    selection: replaySelection.quote,
                    ...(replaySelection.locator
                      ? { locator: replaySelection.locator }
                      : {}),
                  },
                }
              : {}),
          }
        : liveReadingFields;
      const liveViewport = liveReadingFields.reading_viewport;
      const effectiveReadingSelection: ReadingSelectionSnapshot | undefined =
        replaySelection ??
        (liveReadingFields.reading_material_id && liveViewport?.selection
          ? {
              quote: liveViewport.selection,
              locator: liveViewport.locator ?? 0,
            }
          : undefined);
      const effectiveReadingMaterialId =
        effectiveReadingTurnFields.reading_material_id;
      const effectiveReadingMaterialRevision =
        effectiveReadingTurnFields.reading_material_revision;
      const effectiveTimedMediaId = replaySnapshot?.timedMediaId;
      const effectiveWatchingTurnFields = replaySnapshot?.watchingTurnFields ??
        (effectiveTimedMediaId ? { timed_media_id: effectiveTimedMediaId } : {});
      // The bubble names who it was handed to, as the stored snapshot will.
      const snapshotConfig =
        session.answerBy && effectiveConfig?.answer_by === undefined
          ? { ...(effectiveConfig ?? {}), answer_by: session.answerBy }
          : effectiveConfig;
      const requestSnapshot: MessageRequestSnapshot = replaySnapshot ? { ...replaySnapshot } : {
        resourceSelection: {skills:[...effectiveResources.skills],mcp:[...effectiveResources.mcp]},
        content,
        capability: effectiveCapability,
        workspaceMode: effectiveWorkspaceMode,
        workspaceId: session.workspaceId ?? null,
        replyLanguageOverride: session.replyLanguageOverride ?? null,
        enabledTools: [...effectiveTools],
        knowledgeBases: [...effectiveKnowledgeBases],
        language: effectiveLanguage,
        ...(effectiveAttachments?.length
          ? { attachments: effectiveAttachments }
          : {}),
        ...(snapshotConfig && Object.keys(snapshotConfig).length > 0
          ? { config: snapshotConfig }
          : {}),
        ...(effectiveNotebookReferences?.length
          ? { notebookReferences: effectiveNotebookReferences }
          : {}),
        ...(effectiveHistoryReferences?.length
          ? { historyReferences: [...effectiveHistoryReferences] }
          : {}),
        ...(effectiveQuestionNotebookReferences?.length
          ? {
              questionNotebookReferences: [
                ...effectiveQuestionNotebookReferences,
              ],
            }
          : {}),
        ...(effectiveBookReferences?.length
          ? { bookReferences: effectiveBookReferences }
          : {}),
        ...(effectiveReadingReferences?.length
          ? { readingReferences: effectiveReadingReferences }
          : {}),
        ...(effectiveMasteryPathId
          ? { masteryPathId: effectiveMasteryPathId }
          : {}),
        ...(effectiveMasterySessionMode
          ? { masterySessionMode: effectiveMasterySessionMode }
          : {}),
        ...(options?.masteryAnswer ? { masteryAnswer: options.masteryAnswer } : {}),
        ...(options?.noteGeneration ? { noteGeneration: options.noteGeneration } : {}),
        ...(options?.masterySkip ? { masterySkip: options.masterySkip } : {}),
        ...(effectivePersona ? { persona: effectivePersona } : {}),
        ...(effectiveMemoryReferences?.length
          ? { memoryReferences: [...effectiveMemoryReferences] }
          : {}),
        ...(effectiveLLMSelection
          ? { llmSelection: effectiveLLMSelection }
          : {}),
        ...(effectiveReadingMaterialId
          ? { readingMaterialId: effectiveReadingMaterialId }
          : {}),
        ...(effectiveReadingMaterialId && effectiveReadingMaterialRevision
          ? { readingMaterialRevision: effectiveReadingMaterialRevision }
          : {}),
        ...(effectiveReadingSelection
          ? { readingSelection: effectiveReadingSelection }
          : {}),
        ...(Object.keys(effectiveReadingTurnFields).length
          ? { readingTurnFields: effectiveReadingTurnFields }
          : {}),
        ...(capabilityOnce ? { capabilityOnce: true } : {}),
        ...(effectiveTimedMediaId
          ? { timedMediaId: effectiveTimedMediaId }
          : {}),
        ...(Object.keys(effectiveWatchingTurnFields).length
          ? { watchingTurnFields: effectiveWatchingTurnFields }
          : {}),
      };
      // Default the new message's parent to the tip of the currently-
      // visible path so the local chat tree stays connected during
      // streaming. The wire-level ``parent_message_id`` is computed
      // separately further down: only persisted (positive) ids or an
      // explicit ``null`` (root edit) are sent — optimistic negative ids
      // would be meaningless to the server.
      const visible = buildVisiblePath(
        session.messages,
        session.selectedBranches,
      ).messages;
      const tipId = tipMessageId(visible);
      const localParentId =
        options?.parentMessageId !== undefined
          ? options.parentMessageId
          : tipId;
      const wireParentId: number | null | undefined =
        options?.parentMessageId !== undefined
          ? options.parentMessageId
          : tipId !== null && tipId > 0
            ? tipId
            : undefined;
      const trackNewSubmission =
        options?.displayUserMessage !== false &&
        !options?.masteryAnswer &&
        !options?.masterySkip &&
        (content.trim() !== "" || Boolean(effectiveAttachments?.length));
      const submissionId = options?.retrySubmissionId ??
        (trackNewSubmission ? randomUuid() : undefined);
      const persistSubmission = Boolean(submissionId) &&
        (trackNewSubmission || Boolean(options?.retrySubmissionId));
      const replacesSubmissionId = options?.replacesSubmissionId ?? replaySnapshot?.replacesSubmissionId;
      if (replacesSubmissionId && !(await supportsSubmissionReplacement())) return false;
      if (generation !== runtimeGeneration.current) return false;
      const showSubmission = () => {
        if (options?.displayUserMessage !== false) {
        dispatch({
          type: "ADD_USER_MSG",
          key,
          content,
          capability: effectiveCapability,
          attachments: effectiveAttachments,
          requestSnapshot,
          parentMessageId: localParentId,
          failedSubmissionId: submissionId,
        });
        }
        dispatch({
          type: "STREAM_START", key, startedAt: Date.now() / 1000,
          capability: effectiveCapability,
        });
      };
      if (!replacesSubmissionId) showSubmission();
      const {
        _persist_user_message: legacyPersistUserMessage,
        followup_question_context: followupQuestionContext,
        selection_tutor_context: selectionTutorContext,
        subagent_consult_budget: subagentConsultBudget,
        consult_partner_id: consultPartnerId,
        partner_discussion_group_id: partnerDiscussionGroupId,
        answer_by: answerBy,
        auto_route: autoRoute,
        ...finalTurnConfig
      } = effectiveConfig ?? {};
      const persistUserMessage =
        options?.persistUserMessage === false ||
        legacyPersistUserMessage === false
          ? false
          : undefined;
      // Persist before attempting the socket, including a first turn that
      // has no server session yet. Replays reuse their original identity.
      const submissionStorageKey = session.sessionId ?? draftFailedSubmissionKey();
      if (persistSubmission && submissionId && !replacesSubmissionId) {
        const saved = storeFailedSubmission(submissionStorageKey, {
          content,
          capability: effectiveCapability,
          requestSnapshot,
          submissionId,
        });
        dispatch({
          type: "SET_SUBMISSION_PERSISTENCE", key, submissionId,
          saved: saved !== null,
        });
        if (!saved) {
          notify(i18n.t(
            "This unsent message could not be saved in your browser. Copy it before leaving this page.",
          ), { tone: "error", durationMs: 10_000 });
        }
      }
      if (submissionId) {
        pendingSubmissionIdsRef.current.set(key, {
          storageKey: submissionStorageKey,
          submissionId,
          visibleSubmissionIds: [
            ...session.messages
              .map((message) => message.failedSubmissionId)
              .filter((id): id is string => Boolean(id)),
            submissionId,
          ],
        });
      }
      let command = buildStartTurnInput({
        content,
        clientSubmissionId: submissionId,
        tools: effectiveTools,
        capability: effectiveCapability,
        workspaceMode: effectiveWorkspaceMode ?? "",
        knowledgeBases: effectiveKnowledgeBases,
        skills: effectiveResources.skills,
        mcp: effectiveResources.mcp,
        sessionId: session.sessionId,
        // Existing sessions inherit server ownership; new drafts declare it once.
        ...(!session.sessionId ? {
          workspaceId: exactReplay
            ? (replaySnapshot?.workspaceId ?? null)
            : (session.workspaceId ?? null),
        } : {}),
        persistUserMessage,
        followupQuestionContext:
          followupQuestionContext && typeof followupQuestionContext === "object"
            ? (followupQuestionContext as Record<string, unknown>)
            : null,
        selectionTutorContext:
          selectionTutorContext && typeof selectionTutorContext === "object"
            ? (selectionTutorContext as Record<string, unknown>)
            : null,
        consultPartnerId: typeof consultPartnerId === "string" ? consultPartnerId : null,
        partnerDiscussionGroupId: typeof partnerDiscussionGroupId === "string" ? partnerDiscussionGroupId : null,
        // A replay restates the answerer it ran with; a new turn goes to
        // whoever this conversation is handed to now.
        answerBy: typeof answerBy === "string"
          ? answerBy
          : exactReplay ? null : session.answerBy,
        subagentConsultBudget:
          typeof subagentConsultBudget === "number"
            ? subagentConsultBudget
            : null,
        autoRoute: typeof autoRoute === "boolean" ? autoRoute : null,
        capabilityOnce,
        attachments: effectiveAttachments,
        language: effectiveLanguage,
        // A draft has no session to PATCH yet. Persist its selector with the
        // first turn; existing sessions use their server-side preference.
        ...(!session.sessionId && (exactReplay
          ? replaySnapshot?.replyLanguageOverride
          : session.replyLanguageOverride)
          ? { replyLanguageOverride: exactReplay
              ? replaySnapshot?.replyLanguageOverride
              : session.replyLanguageOverride }
          : {}),
        notebookReferences: effectiveNotebookReferences,
        historyReferences: effectiveHistoryReferences,
        questionNotebookReferences: effectiveQuestionNotebookReferences,
        bookReferences: effectiveBookReferences,
        readingReferences: effectiveReadingReferences,
        masteryPathId: effectiveMasteryPathId || null,
        masterySessionMode: effectiveMasterySessionMode || null,
        // A note companion's conversation stays bound to its page for every
        // turn, regenerations included: the binding is the session's, not the
        // request's.
        noteDocumentId: session.noteDocumentId || null,
        noteGeneration: options?.noteGeneration ?? replaySnapshot?.noteGeneration ?? null,
        masteryAnswer: options?.masteryAnswer ?? replaySnapshot?.masteryAnswer ?? null,
        masterySkip: options?.masterySkip ?? replaySnapshot?.masterySkip ?? null,
        // Immersive reading. Gated on the stable workspace mode as well as on
        // an open document: the reader outlives action switches and new
        // sessions, so Home must never inherit its source context.
        // Read from a module cell rather than context state so scrolling the
        // reader never re-renders the chat.
        readingWorkspaceId:
          effectiveReadingTurnFields.reading_workspace_id ?? null,
        readingMaterialId:
          effectiveReadingTurnFields.reading_material_id ?? null,
        readingMaterialRevision:
          effectiveReadingTurnFields.reading_material_revision ?? null,
        readingViewport: effectiveReadingTurnFields.reading_viewport ?? null,
        timedMediaId: effectiveTimedMediaId ?? null,
        timedMediaViewport: null,
        // Always sent (possibly ""): an explicit key is the backend's signal
        // to persist the value into session.preferences — "" clears back to
        // Default. Omitting the key would make the backend fall back to the
        // stored preference, so a clear could never propagate.
        persona: effectivePersona,
        memoryReferences: effectiveMemoryReferences,
        llmSelection: effectiveLLMSelection,
        capabilityConfig: finalTurnConfig,
        // Send ``parent_message_id`` only when we have a real (positive)
        // server id to chain under, or when the caller explicitly pinned
        // a parent (incl. ``null`` for editing the session's first
        // message). When the visible tip is still an optimistic
        // negative id, omit the key and let the backend auto-append to
        // the latest persisted row.
        parentMessageId: wireParentId,
        });
      if (replacesSubmissionId && submissionId) {
        command = (replaySnapshot?.replacementRequest ?? command) as typeof command;
        requestSnapshot.replacesSubmissionId = replacesSubmissionId;
        requestSnapshot.replacementRootSubmissionId = options?.replacementRootSubmissionId ??
          replaySnapshot?.replacementRootSubmissionId ?? replacesSubmissionId;
        requestSnapshot.replacementRequest = { ...command };
        // Save the edit and its identity before fencing the original. A lost
        // HTTP receipt then retries the same native reservation after reload.
        if (!storeFailedSubmission(submissionStorageKey, {
          content, capability: effectiveCapability, requestSnapshot, submissionId,
        })) return false;
        const durable = readFailedSubmissions(submissionStorageKey).find((record) => record.submissionId === submissionId);
        if (!durable || durable.retryRequiresReview || JSON.stringify(durable.requestSnapshot) !== JSON.stringify(requestSnapshot)) {
          notify(i18n.t("This unsent message could not be saved in your browser. Copy it before leaving this page."), { tone: "error" });
          return false;
        }
        try {
          const receipt = await replaceSubmission(replacesSubmissionId, { ...command });
          if (generation !== runtimeGeneration.current) return true;
          command.session_id = receipt.session_id;
          // The server receipt, not transcript absence, authorizes retirement
          // of the superseded local copy. The new durable record already exists.
          clearFailedSubmission(submissionStorageKey, replacesSubmissionId);
          if (options?.replacedMessageId != null) {
            const replaced = session.messages.find((message) => message.id === options.replacedMessageId);
            if (replaced?.failedSubmissionId) dispatch({ type: "DISCARD_FAILED_SUBMISSION", key,
              messageId: options.replacedMessageId, submissionId: replaced.failedSubmissionId });
          }
          showSubmission();
          // HTTP acknowledged native admission. Subscribe/replay the same
          // turn; never send another start command for this edit.
          ensureRunner(key).client.send({ type: "subscribe_turn", turn_id: receipt.turn.id, after_seq: 0 });
          return true;
        } catch {
          pendingSubmissionIdsRef.current.delete(key);
          return false;
        }
      }
      return sendThroughRunner(key, command);
    },
    [makeDraftKey, sendThroughRunner, ensureRunner],
  );

  const cancelStreamingTurn = useCallback(async () => {
    const generation = runtimeGeneration.current;
    const currentState = stateRef.current;
    const key = currentState.selectedKey;
    if (!key) return;
    const session = currentState.sessions[key];
    if (!session) return;
    const turnId = session.activeTurnId;
    const runner = runnersRef.current.get(key);
    if (runner) {
      if (turnId) {
        try {
          if (!await runner.client.sendAwaitingAck({ type: "cancel_turn", turn_id: turnId })) {
            notify(i18n.t("Couldn't reach the server. Please check your connection and retry."), { tone: "error" });
            return;
          }
          if (generation !== runtimeGeneration.current) return;
        } catch {
          notify(i18n.t("Couldn't reach the server. Please check your connection and retry."), { tone: "error" });
          return;
        }
      }
      runner.client.disconnect();
      runnersRef.current.delete(key);
    }
    if (session.isStreaming) {
      // Stop is not proof that the server accepted the user row. In
      // particular, before a turn ID exists another tab may have stored a
      // newer attempt with this same logical submission ID. Keep the record
      // until a server transcript or DONE proves acceptance.
      const pendingSubmission = pendingSubmissionIdsRef.current.get(key);
      if (pendingSubmission) pendingSubmissionIdsRef.current.delete(key);
      dispatch({
        type: "STREAM_END", key,
        status: pendingSubmission && !turnId ? "failed" : "cancelled",
        submissionFailed: Boolean(pendingSubmission && !turnId),
      });
    }
  }, []);

  const submitUserReply = useCallback(
    async (
      reply:
        | string
        | {
            text?: string;
            answers?: Array<{ questionId: string; text: string }>;
          },
    ): Promise<boolean> => {
      const currentState = stateRef.current;
      const key = currentState.selectedKey;
      if (!key) return false;
      const session = currentState.sessions[key];
      const turnId = session?.activeTurnId;
      const pendingAskUser = session
        ? hasPendingAskUserInMessages(session.messages, turnId)
        : false;
      // Only meaningful while a turn is live. A paused ask_user turn can be
      // silent long enough for the socket to reconnect, so allow submission
      // whenever the unresolved card and active turn id are still present.
      if (!session || !turnId || (!session.isStreaming && !pendingAskUser)) {
        return false;
      }
      const message: import("@/features/chat/model/protocol").SubmitUserReplyMessage =
        {
          type: "submit_user_reply",
          turn_id: turnId,
        };
      if (typeof reply === "string") {
        message.text = reply;
      } else {
        if (typeof reply.text === "string") message.text = reply.text;
        if (Array.isArray(reply.answers)) message.answers = reply.answers;
      }
      const runner = ensureRunner(key);
      const fingerprint = JSON.stringify([
        message, pendingAskUserKeyInMessages(session.messages, turnId),
      ]);
      // Retrying an unconfirmed answer reuses its idempotency key. The server
      // may already have accepted it even if its ACK was lost (#1648).
      const commandId = runner.replyCommand?.fingerprint === fingerprint
        ? runner.replyCommand.commandId
        : newCommandId();
      runner.replyCommand = { fingerprint, commandId };
      message.command_id = commandId;
      return sendThroughRunner(key, message, { awaitAck: true });
    },
    [ensureRunner, sendThroughRunner],
  );

  const regenerateLastMessage = useCallback((replaySnapshot = false) => {
    const currentState = stateRef.current;
    const key = currentState.selectedKey;
    if (!key) return;
    const session = currentState.sessions[key];
    if (!session || !session.sessionId) return;
    if (session.isStreaming) return;
    const lastUser = [...session.messages]
      .reverse()
      .find((m) => m.role === "user");
    if (!lastUser) return;
    // Snapshot the trailing assistant (if any) so we can put it back when the
    // server rejects the request. We intentionally keep events/attachments so
    // the restored bubble round-trips identically.
    const lastMessage = session.messages[session.messages.length - 1];
    if (lastMessage && lastMessage.role === "assistant") {
      pendingRegenerateRef.current.set(key, { ...lastMessage });
    } else {
      pendingRegenerateRef.current.delete(key);
    }
    dispatch({ type: "POP_LAST_ASSISTANT", key });
    dispatch({
      type: "STREAM_START", key, startedAt: Date.now() / 1000,
      capability: lastUser.requestSnapshot?.capability ?? lastUser.capability ?? null,
    });
    sendThroughRunner(key, {
      type: "regenerate",
      session_id: session.sessionId,
      overrides: replaySnapshot
        ? { replay_snapshot: true }
        : { language: readStoredResponseLanguage() },
    });
  }, [sendThroughRunner]);

  const resendLastMessage = useCallback(async () => {
    const currentState = stateRef.current;
    const key = currentState.selectedKey;
    if (!key) return;
    const session = currentState.sessions[key];
    if (!session) return;
    if (!isFailedTurnVisible(
      session.messages,
      session.selectedBranches,
      session.status,
      session.isStreaming,
    )) return;
    const lastUser = [...session.messages]
      .reverse()
      .find((m) => m.role === "user" && m.requestSnapshot);
    if (!lastUser?.requestSnapshot) return;
    // Retry the failed tail as a new turn, keeping the existing optimistic
    // user row visible (its snapshot is replayed verbatim).
    const retryUnsavedTail = () => {
      const live = stateRef.current;
      const liveSession = live.sessions[key];
      if (
        live.selectedKey !== key ||
        !liveSession ||
        !isFailedTurnVisible(
          liveSession.messages,
          liveSession.selectedBranches,
          liveSession.status,
          liveSession.isStreaming,
        )
      ) return;
      const liveLastUser = [...liveSession.messages]
        .reverse()
        .find((message) => message.role === "user" && message.requestSnapshot);
      if (!liveLastUser?.requestSnapshot) return;
      const lastMessage =
        liveSession.messages[liveSession.messages.length - 1];
      if (lastMessage?.role === "assistant") {
        pendingResendRef.current.set(key, { ...lastMessage });
      }
      // Remove the trailing failed assistant bubble so the new turn's
      // STREAM_START placeholder replaces it rather than stacking below.
      dispatch({ type: "POP_LAST_ASSISTANT", key });
      const snapshot = liveLastUser.requestSnapshot;
      void sendMessage(
        snapshot.content,
        undefined,
        undefined,
        undefined,
        undefined,
        {
          displayUserMessage: false,
          requestSnapshotOverride: snapshot,
          retrySubmissionId: liveLastUser.failedSubmissionId,
          parentMessageId:
            typeof liveLastUser.parentMessageId === "number" &&
            liveLastUser.parentMessageId <= 0
              ? undefined
              : liveLastUser.parentMessageId,
        },
      ).then((sent) => {
        if (sent) return;
        const stash = pendingResendRef.current.get(key);
        pendingResendRef.current.delete(key);
        // A submission failure settles the tail itself (pops the
        // placeholder, flags the user row) — restoring the stash then
        // would resurrect an empty assistant bubble (#1594).
        const tail = stateRef.current.sessions[key]?.messages.at(-1);
        if (!stash || tail?.role === "user") return;
        dispatch({ type: "RESTORE_ASSISTANT", key, message: stash });
      });
    };
    // A draft has no server session to reconcile against — nothing was
    // persisted, so retry directly (#1594).
    if (!session.sessionId) {
      retryUnsavedTail();
      return;
    }
    // A dropped socket can hide a successfully persisted user row before its
    // DONE ids reach this tab. Query the server before deciding whether this
    // is a regenerate or a genuinely unsaved first attempt.
    if (resolvingResendRef.current.has(key)) return;
    resolvingResendRef.current.add(key);
    let remote: Awaited<ReturnType<typeof getSession>>;
    try {
      remote = await getSession(session.sessionId);
    } catch {
      notify(i18n.t("Couldn't reach the server. Please check your connection and retry."), {
        tone: "error",
      });
      return;
    } finally {
      resolvingResendRef.current.delete(key);
    }
    const live = stateRef.current;
    const liveSession = live.sessions[key];
    if (
      live.selectedKey !== key ||
      !liveSession ||
      !isFailedTurnVisible(
        liveSession.messages,
        liveSession.selectedBranches,
        liveSession.status,
        liveSession.isStreaming,
      )
    ) return;
    const liveLastUser = [...liveSession.messages]
      .reverse()
      .find((message) => message.role === "user" && message.requestSnapshot);
    if (!liveLastUser?.requestSnapshot) return;
    const decision = decideFailedTurnReplay(
      liveSession.messages,
      { ...liveLastUser, requestSnapshot: liveLastUser.requestSnapshot },
      remote,
    );
    if (decision.kind === "refresh") {
      void loadSessionRef.current?.(session.sessionId);
      return;
    }
    if (decision.kind === "reconcile_regenerate") {
      dispatch({
        type: "RECONCILE_TURN",
        key,
        turnId: null,
        // Runtime storage can return PocketBase string IDs; the existing
        // reconciliation path preserves them despite its numeric legacy type.
        userMessageId: decision.userId as number,
        assistantMessageId: null,
      });
    }
    if (decision.kind === "regenerate" || decision.kind === "reconcile_regenerate") {
      regenerateLastMessage(true);
      return;
    }
    // The first attempt failed before the user row reached storage.
    retryUnsavedTail();
  }, [regenerateLastMessage, sendMessage]);

  const derivedState = useMemo<ChatState>(() => {
    const current = ensureSelectedSession(state);
    return {
      sessionKey: current.key,
      boundFromKey: current.boundFromKey ?? null,
      sessionId: current.sessionId,
      sessionTitle: current.sessionTitle,
      enabledTools: current.enabledTools,
      activeCapability: current.activeCapability,
      workspaceMode: current.workspaceMode,
      knowledgeBases: current.knowledgeBases,
      llmSelection: current.llmSelection,
      masteryPathId: current.masteryPathId,
      masterySessionMode: current.masterySessionMode,
      noteDocumentId: current.noteDocumentId,
      workspaceId: current.workspaceId,
      personaSelection: current.personaSelection,
      answerBy: current.answerBy,
      resourceSelection: current.resourceSelection,
      messages: current.messages,
      isStreaming: current.isStreaming,
      currentStage: current.currentStage,
      language: current.language,
      replyLanguageOverride: current.replyLanguageOverride,
      selectedBranches: current.selectedBranches,
      queuedMessages: current.queuedMessages ?? [],
      lastTurnFailed: isFailedTurnVisible(
        current.messages,
        current.selectedBranches,
        current.status,
        current.isStreaming,
      ),
      submissionFailed: (() => {
        if (current.isStreaming) return false;
        const tail = current.messages[current.messages.length - 1];
        return (
          (current.status === "failed" || current.status === "rejected") &&
          tail?.role === "user" &&
          tail.failedSubmission === true
        );
      })(),
      submissionNeedsReview: (() => {
        const tail = current.messages[current.messages.length - 1];
        return tail?.role === "user" && tail.failedSubmissionNeedsReview === true;
      })(),
      submissionNotSaved: (() => {
        const tail = current.messages[current.messages.length - 1];
        return tail?.role === "user" && tail.failedSubmissionNotSaved === true;
      })(),
    };
  }, [state]);

  const sessionStatuses = useMemo<Record<string, SessionStatusSnapshot>>(() => {
    const entries: Record<string, SessionStatusSnapshot> = {};
    for (const session of Object.values(state.sessions)) {
      if (!session.sessionId || session.status !== "running") continue;
      entries[session.sessionId] = {
        sessionId: session.sessionId,
        status: session.status,
        activeTurnId: session.activeTurnId,
        updatedAt: session.updatedAt,
      };
    }
    return entries;
  }, [state.sessions]);

  const setTools = useCallback((tools: string[]) => {
    dispatch({ type: "SET_TOOLS", tools });
  }, []);

  const setCapability = useCallback((cap: string | null) => {
    dispatch({ type: "SET_CAPABILITY", cap });
  }, []);

  const setKBs = useCallback((kbs: string[]) => {
    dispatch({ type: "SET_KB", kbs });
  }, []);

  const setLLMSelection = useCallback((selection: LLMSelection | null) => {
    dispatch({ type: "SET_LLM_SELECTION", selection });
  }, []);

  const setMasteryPathId = useCallback((masteryPathId: string | null) => {
    const normalized = masteryPathId?.trim() || null;
    dispatch({ type: "SET_MASTERY_PATH_ID", masteryPathId: normalized });
  }, []);

  const setMasterySessionMode = useCallback((mode: string | null) => {
    dispatch({
      type: "SET_MASTERY_SESSION_MODE",
      mode: mode?.trim() || null,
    });
  }, []);

  const setPersonaSelection = useCallback((persona: string) => {
    dispatch({ type: "SET_PERSONA_SELECTION", persona });
  }, []);

  const setAnswerBy = useCallback((answerBy: string | null) => {
    dispatch({ type: "SET_ANSWER_BY", answerBy });
  }, []);

  const setResourceSelection = useCallback((selection: ResourceSelection) => {
    dispatch({ type: "SET_RESOURCE_SELECTION", selection });
  }, []);

  const setLanguage = useCallback((lang: string) => {
    dispatch({ type: "SET_LANGUAGE", lang });
  }, []);

  const setReplyLanguageOverride = useCallback(async (language: string | null) => {
    if (language !== null && !isResponseLanguage(language)) {
      throw new Error("Unsupported reply language");
    }
    const currentState = stateRef.current;
    const key = currentState.selectedKey;
    if (!key) return;
    const session = currentState.sessions[key];
    if (!session) return;
    if (!session.sessionId) {
      dispatch({ type: "SET_REPLY_LANGUAGE_OVERRIDE", key, language });
      return;
    }
    const updated = await updateSessionReplyLanguage(
      session.sessionId,
      language,
      session.workspaceId ?? undefined,
    );
    const saved = updated.preferences?.reply_language_override;
    dispatch({
      type: "SET_REPLY_LANGUAGE_OVERRIDE",
      key,
      language: isResponseLanguage(saved) ? saved : null,
    });
  }, []);

  const renameSessionTitle = useCallback(async (title: string) => {
    const trimmed = title.trim();
    if (!trimmed) return;
    const currentState = stateRef.current;
    const key = currentState.selectedKey;
    if (!key) return;
    const session = currentState.sessions[key];
    const sessionId = session?.sessionId;
    if (!sessionId) return;
    const updated = await updateSessionTitle(sessionId, trimmed);
    dispatch({
      type: "SET_SESSION_TITLE",
      key,
      title: updated.title || trimmed,
    });
  }, []);

  const newSession = useCallback(
    (configuration?: SessionConfiguration) => {
      const key = makeDraftKey();
      dispatch({ type: "NEW_SESSION", key, configuration });
      // The provider stays mounted while /chat pages come and go. Restore
      // unsent first turns every time a page creates a fresh draft, too.
      dispatch({
        type: "ENSURE_DRAFT_SESSION",
        key,
        failedRecords: readFailedSubmissions(draftFailedSubmissionKey()),
      });
      return key;
    },
    [makeDraftKey],
  );

  const configureSession = useCallback(
    (configuration: SessionConfiguration, sessionKey?: string) => {
      dispatch({
        type: "CONFIGURE_SESSION",
        key: sessionKey,
        configuration,
      });
    },
    [],
  );

  const discardFailedSubmission = useCallback((messageId: number): boolean => {
    const currentState = stateRef.current;
    const key = currentState.selectedKey;
    const session = key ? currentState.sessions[key] : undefined;
    if (!key || !session || session.isStreaming) return false;
    const message = session.messages.find((item) => item.id === messageId);
    if (message?.role !== "user" || !message.failedSubmission || messageId >= 0 || !message.failedSubmissionId) return false;
    const storageKey = session.sessionId ?? draftFailedSubmissionKey();
    const rootId = message.requestSnapshot?.replacementRootSubmissionId ?? message.failedSubmissionId;
    const pendingEdits = readFailedSubmissions(storageKey, true).filter((record) => {
      const snapshot = record.requestSnapshot as MessageRequestSnapshot;
      return (snapshot?.replacementRootSubmissionId ?? snapshot?.replacesSubmissionId) === rootId;
    });
    for (const pendingEdit of pendingEdits) {
      if (pendingEdit.submissionId && !clearFailedSubmission(storageKey, pendingEdit.submissionId)) return false;
    }
    if (rootId !== message.failedSubmissionId && !clearFailedSubmission(storageKey, rootId)) return false;
    if (!clearFailedSubmission(storageKey, message.failedSubmissionId) && !message.failedSubmissionNotSaved) return false;
    dispatch({ type: "DISCARD_FAILED_SUBMISSION", key, messageId, submissionId: message.failedSubmissionId });
    return true;
  }, []);

  const editMessage = useCallback(
    async (messageId: number, newContent: string): Promise<boolean> => {
      const generation = runtimeGeneration.current;
      const trimmed = newContent.trim();
      if (!trimmed) return false;
      const currentState = stateRef.current;
      const key = currentState.selectedKey;
      if (!key) return false;
      const session = currentState.sessions[key];
      if (!session) return false;
      // Edits create a new branch via a fresh turn — block while one is
      // already running so we don't queue against an in-flight stream
      // (matches the delete-turn guard).
      if (session.isStreaming) return false;
      const local = session.messages.find((message) => message.id === messageId && message.role === "user");
      if (local?.failedSubmission && local.failedSubmissionId && local.requestSnapshot && !local.failedSubmissionNeedsReview) {
        if (!(await supportsSubmissionReplacement()) || generation !== runtimeGeneration.current) return false;
        const rootId = local.requestSnapshot.replacementRootSubmissionId ?? local.failedSubmissionId;
        const pending = readFailedSubmissions(session.sessionId ?? draftFailedSubmissionKey()).find((record) => {
          const snapshot = record.requestSnapshot as MessageRequestSnapshot;
          return (snapshot?.replacementRootSubmissionId ?? snapshot?.replacesSubmissionId) === rootId;
        });
        const sameEdit = pending?.content === trimmed;
        if (pending && !sameEdit) {
          const priorEdit = pending.requestSnapshot as MessageRequestSnapshot;
          if (!priorEdit.replacesSubmissionId || !priorEdit.replacementRequest) return false;
          try {
            // Before chaining another edit, resolve the uncertain predecessor.
            // It might never have reached the server, so replacing its ID alone
            // would leave the original delayed request free to be admitted.
            await replaceSubmission(priorEdit.replacesSubmissionId, priorEdit.replacementRequest);
            if (generation !== runtimeGeneration.current) return false;
          } catch { return false; }
        }
        const snapshot = { ...(sameEdit ? pending.requestSnapshot as MessageRequestSnapshot : local.requestSnapshot), content: trimmed };
        if (!sameEdit) {
          delete snapshot.replacementRequest;
          delete snapshot.replacesSubmissionId;
        }
        return sendMessage(trimmed, undefined, undefined, undefined, undefined, {
          requestSnapshotOverride: snapshot,
          retrySubmissionId: sameEdit ? pending.submissionId : undefined,
          replacesSubmissionId: sameEdit ? (pending.requestSnapshot as MessageRequestSnapshot).replacesSubmissionId : pending?.submissionId ?? local.failedSubmissionId,
          replacementRootSubmissionId: rootId,
          replacedMessageId: messageId,
          parentMessageId: local.parentMessageId != null && local.parentMessageId > 0 ? local.parentMessageId : null,
        });
      }
      let original: MessageItem | undefined;
      try {
        original = await resolvePersistedMessage(
          session.messages,
          messageId,
          "user",
          async () =>
            session.sessionId
              ? await loadSession(session.sessionId)
              : undefined,
        );
      } catch {
        return false;
      }
      if (!original || generation !== runtimeGeneration.current) return false;
      const parentId = original.parentMessageId ?? null;
      return sendMessage(
        trimmed,
        original.attachments,
        undefined,
        undefined,
        undefined,
        { parentMessageId: parentId,
          requestSnapshotOverride: (local?.requestSnapshot ?? original.requestSnapshot)
            ? { ...(local?.requestSnapshot ?? original.requestSnapshot)!, content: trimmed,
                replacesSubmissionId: undefined, replacementRequest: undefined } : undefined },
        undefined,
        undefined,
        undefined,
      );
    },
    [loadSession, sendMessage],
  );

  const retryFailedSubmission = useCallback(async (messageId: number): Promise<boolean> => {
    const current = stateRef.current;
    const key = current.selectedKey;
    const session = key ? current.sessions[key] : undefined;
    const message = session?.messages.find((item) => item.id === messageId);
    if (!key || !session || session.isStreaming || !message?.failedSubmission ||
      !message.failedSubmissionId || !message.requestSnapshot || message.failedSubmissionNeedsReview) return false;
    if (message.requestSnapshot.replacesSubmissionId && !(await supportsSubmissionReplacement())) return false;
    const rootId = message.requestSnapshot.replacementRootSubmissionId ?? message.failedSubmissionId;
    const pending = readFailedSubmissions(session.sessionId ?? draftFailedSubmissionKey()).find((record) => {
      const snapshot = record.requestSnapshot as MessageRequestSnapshot;
      return (snapshot?.replacementRootSubmissionId ?? snapshot?.replacesSubmissionId) === rootId;
    });
    if (pending && pending.submissionId !== message.failedSubmissionId) return editMessage(messageId, pending.content);
    // Move this exact local row to the active tail while retaining its causal
    // ID; retrying an older draft must never resend the newest row instead.
    dispatch({ type: "DISCARD_FAILED_SUBMISSION", key, messageId, submissionId: message.failedSubmissionId });
    return sendMessage(message.content, undefined, undefined, undefined, undefined, {
      requestSnapshotOverride: message.requestSnapshot, retrySubmissionId: message.failedSubmissionId,
      parentMessageId: message.parentMessageId != null && message.parentMessageId > 0 ? message.parentMessageId : null,
    });
  }, [sendMessage, editMessage]);

  const switchBranch = useCallback(
    (parentMessageId: number | null, childId: number) => {
      const currentState = stateRef.current;
      const key = currentState.selectedKey;
      if (!key) return;
      const session = currentState.sessions[key];
      if (!session) return;
      const parentKey =
        parentMessageId == null ? "null" : String(parentMessageId);
      dispatch({
        type: "SET_SELECTED_BRANCH",
        key,
        parentKey,
        childId,
      });
      const sessionId = session.sessionId;
      if (!sessionId || childId < 0) return;
      const nextSelections = persistedBranchSelections({
        ...session.selectedBranches,
        [parentKey]: childId,
      });
      if (Object.keys(nextSelections).length === 0) return;
      // Fire-and-forget — local state is the source of truth for the UI;
      // the server copy only matters for reload-time hydration.
      updateBranchSelection(sessionId, nextSelections).catch((err) => {
        console.warn("Failed to persist branch selection:", err);
      });
    },
    [],
  );

  const deleteTurn = useCallback(
    async (messageId: number) => {
      const generation = runtimeGeneration.current;
      const currentState = stateRef.current;
      const key = currentState.selectedKey;
      if (!key) return;
      const session = currentState.sessions[key];
      if (!session || !session.sessionId) return;
      if (session.isStreaming) return;
      // Same optimistic-id race as editMessage (#739): after loadSession
      // dispatches, stateRef can still hold the negative sentinel until
      // React commits. Resolve from the returned snapshot instead.
      let target: MessageItem | undefined;
      try {
        target = await resolvePersistedMessage(
          session.messages,
          messageId,
          "user",
          async () =>
            session.sessionId
              ? await loadSession(session.sessionId)
              : undefined,
        );
      } catch {
        return;
      }
      if (!target || typeof target.id !== "number" || target.id < 0 || generation !== runtimeGeneration.current) return;
      const effectiveId = target.id;
      try {
        await deleteMessage(session.sessionId, effectiveId);
        dispatch({ type: "DELETE_TURN", key, messageId: effectiveId });
      } catch (err) {
        console.error("Failed to delete turn:", err);
      }
    },
    [loadSession],
  );

  // ── Messages sent while a turn runs ───────────────────────────
  const queueMessage = useCallback(
    (content: string, send: QueuedMessage["send"], steerable: boolean) => {
      const key = stateRef.current.selectedKey;
      if (!key) return;
      dispatch({
        type: "QUEUE_MESSAGE",
        key,
        message: { id: newCommandId(), content, send, steerable, offeredTo: null },
      });
    },
    [],
  );

  const withdrawQueuedMessage = useCallback(
    (id: string) => {
      const key = stateRef.current.selectedKey;
      const session = key ? stateRef.current.sessions[key] : undefined;
      const queued = session?.queuedMessages?.find((item) => item.id === id);
      if (!key || !session || !queued) return;
      dispatch({ type: "DROP_QUEUED", key, ids: [id] });
      // Already offered: take it back before the turn's next step reads it.
      if (queued.offeredTo && queued.offeredTo === session.activeTurnId) {
        void sendThroughRunner(key, {
          type: "user_input",
          turn_id: queued.offeredTo,
          content: "",
          withdraw: id,
          command_id: newCommandId(),
          protocol_version: "2.0",
        });
      }
    },
    [sendThroughRunner],
  );

  // Offer what can steer to the turn running now; it reads them between steps.
  const selectedSession = state.selectedKey ? state.sessions[state.selectedKey] : undefined;
  useEffect(() => {
    const key = state.selectedKey;
    const turnId = selectedSession?.activeTurnId;
    if (!key || !selectedSession?.isStreaming || !turnId) return;
    const offers = (selectedSession.queuedMessages ?? []).filter(
      (queued) => queued.steerable && queued.offeredTo !== turnId,
    );
    if (!offers.length) return;
    dispatch({ type: "OFFER_QUEUED", key, ids: offers.map((queued) => queued.id), turnId });
    for (const queued of offers) {
      void sendThroughRunner(
        key,
        {
          type: "user_input",
          turn_id: turnId,
          content: queued.content,
          command_id: queued.id,
          protocol_version: "2.0",
        },
        { awaitAck: true },
      );
    }
  }, [selectedSession, sendThroughRunner, state.selectedKey]);

  // Once the turn has ended, what it never read goes as the next turn — one
  // at a time, so later messages can steer that one in turn.
  useEffect(() => {
    const key = state.selectedKey;
    const next = selectedSession?.queuedMessages?.[0];
    if (
      !key ||
      !next ||
      selectedSession.isStreaming ||
      selectedSession.status === "running" ||
      // A send the server never received is retried by hand, not queued past.
      derivedState.submissionFailed
    ) {
      return;
    }
    dispatch({ type: "DROP_QUEUED", key, ids: [next.id] });
    sendMessage(...next.send);
  }, [derivedState.submissionFailed, selectedSession, sendMessage, state.selectedKey]);

  // Memoize the context value so consumers don't re-render on every render of
  // this provider. Without this wrap, every stream-event-driven reducer
  // dispatch produced a fresh object identity, cascading a re-render through
  // every adapter consumer (chat page, composer, sidebar) on each
  // token. The callbacks below are already stable via useCallback; the only
  // things that should change identity are derivedState, sessionStatuses,
  // and sidebarRefreshToken.
  const value = useMemo<ChatContextValue>(
    () => ({
      state: derivedState,
      setTools,
      setCapability,
      setKBs,
      setLLMSelection,
      setMasteryPathId,
      setMasterySessionMode,
      setPersonaSelection,
      setAnswerBy,
      setResourceSelection,
      setLanguage,
      setReplyLanguageOverride,
      sendMessage,
      queueMessage,
      withdrawQueuedMessage,
      cancelStreamingTurn,
      submitUserReply,
      regenerateLastMessage,
      resendLastMessage,
      deleteTurn,
      discardFailedSubmission,
      retryFailedSubmission,
      editMessage,
      switchBranch,
      renameSessionTitle,
      newSession,
      configureSession,
      loadSession,
      showCachedSession,
      loadMessageTrace,
      releaseMessageTrace,
      selectedSessionId: derivedState.sessionId,
      sessionStatuses,
      sidebarRefreshToken: state.sidebarRefreshToken,
    }),
    [
      derivedState,
      setTools,
      setCapability,
      setKBs,
      setLLMSelection,
      setMasteryPathId,
      setMasterySessionMode,
      setPersonaSelection,
      setAnswerBy,
      setResourceSelection,
      setLanguage,
      setReplyLanguageOverride,
      sendMessage,
      queueMessage,
      withdrawQueuedMessage,
      cancelStreamingTurn,
      submitUserReply,
      regenerateLastMessage,
      resendLastMessage,
      deleteTurn,
      discardFailedSubmission,
      retryFailedSubmission,
      editMessage,
      switchBranch,
      renameSessionTitle,
      newSession,
      configureSession,
      loadSession,
      showCachedSession,
      loadMessageTrace,
      releaseMessageTrace,
      sessionStatuses,
      state.sidebarRefreshToken,
    ],
  );

  return <ChatCtx.Provider value={value}>{children}</ChatCtx.Provider>;
}

/** Transitional state adapter for surfaces that have not moved to store selectors yet. */
export function useChatStateAdapter() {
  const ctx = useContext(ChatCtx);
  if (!ctx)
    throw new Error(
      "useChatStateAdapter must be inside ChatStateAdapterProvider",
    );
  return ctx;
}