Skip to content

Enterprise agent platform for building, deploying, and operating AI teammates.

366 KB
Raw Blame
"use client"

import React, { createContext, useContext, useReducer, useCallback, useEffect, useLayoutEffect, useState, useRef, useMemo } from "react"
import { useRouter } from "next/navigation"
import { FileText, Target, Zap, CheckCircle, XCircle, Wrench, Activity, Search, Lightbulb, AlertTriangle, Info, Brain, Bot } from "lucide-react"
import { JsonRenderer, MarkdownRenderer } from "../components/ui/markdown-renderer"
import { UserMessageContent } from "@/components/chat/user-message-content"
import { ReplayScheduler } from '@/lib/replay-scheduler'
import { CollapsibleSection } from "@/components/collapsible-section"
import { Badge } from "@/components/ui/badge"
import { ClarificationForm } from "@/components/chat/clarification-form"
import { ConnectorRuntimeDialog } from "@/components/chat/connector-runtime-dialog"
import {
  AgentCardPresentationCapability,
  LinksOpenInNewTabCapability,
  resolveAgentCardPresentationCapability,
} from "@/contexts/presentation-capabilities"
import {
  FileAccessProvider,
  type FileAccessPolicy,
} from "@/contexts/file-access-context"
import { useConnectorRuntimeDialogActionsIfMounted } from "@/contexts/connector-runtime-dialog-context"
import { FIRST_GATE_CLEARED_MESSAGE_KEY, isConnectorRuntimeDialogTriggerCode, shouldHoldFirstMessage } from "@/lib/connector-runtime-api"
import { getAgentTaskHref } from "@/lib/agent-ui-access"
import type { AutoResumeCancelSnapshot } from "@/lib/task-auto-resume-api"

interface WebSocketMessage {
  type: string
  data?: unknown
  timestamp: string
  task_id?: number
  step_id?: string
  event_type?: string
  event_id?: string
  message_id?: string
  execution_sequence?: number
  run_id?: string | null
  stream_run_id?: string | null
  stream_attempt_id?: string | null
  state_version?: number
  control_state?: TaskControlState
  status?: unknown
  task?: Record<string, unknown>
}

type TaskControlState =
  | "idle"
  | "running"
  | "pause_requested"
  | "paused"
  | "resume_requested"
  | "waiting_for_user"
  | "completed"
  | "failed"

// The structured half of a terminal task_error frame: the stable error code
// the client renders and localizes. The frame carries nothing else
// connector-specific -- its audience includes anonymous widget and
// share-link visitors.
type TaskErrorProjection = {
  code: string
}

type TaskControlEnvelope = {
  isStateEvent: boolean
  taskId?: number
  runId?: string | null
  stateVersion?: number
  controlState?: TaskControlState
  status?: TaskStatus
}

export const VERSIONED_TASK_EVENT_TYPES = new Set([
  "task_stream_snapshot",
  "agent_error",
  "error",
  "task_completed",
  "task_error",
  "task_pause_requested",
  "task_paused",
  "task_resumed",
  "task_started",
  "task_waiting_for_user",
])
// Action types that describe state scoped to one specific task's
// conversation (chat/trace/DAG/status). Used by handleMessage's dispatch
// wrapper to drop these when a message's task_id doesn't match the task
// actually being viewed - see the wrapper's own comment for why. Kept at
// module scope (built once) rather than inside handleMessage, matching
// VERSIONED_TASK_EVENT_TYPES above.
// TRIGGER_TASK_UPDATE is deliberately NOT in this set: it only bumps
// lastTaskUpdate to tell the sidebar's task list to refetch (sidebar.tsx),
// which should happen for ANY task's status change regardless of which task
// is currently being viewed - unlike every action below, it isn't part of
// the viewed task's own displayed state.
const TASK_SCOPED_ACTION_TYPES = new Set<AppAction["type"]>([
  "SET_DAG_EXECUTION",
  "SET_STEPS",
  // Not currently dispatched from inside handleMessage (its only two call
  // sites use the raw, unwrapped dispatch), so this has no effect today -
  // included so a future call site inside handleMessage inherits the same
  // scoping SET_DAG_EXECUTION/SET_STEPS already get individually, instead of
  // silently bypassing it.
  "RESET_DAG_STATE",
  "ADD_STEP",
  "UPDATE_STEP",
  "UPDATE_TASK_STATUS",
  "APPLY_AUTO_RESUME_NOTICE",
  "RECONCILE_AUTO_RESUME_CANCEL",
  "SET_CURRENT_TASK",
  "SET_PROCESSING",
  "SET_HISTORY_LOADING",
  "ADD_MESSAGE",
  "UPSERT_STREAMING_FINAL_ANSWER",
  "SET_STREAM_RECOVERY",
  "RECONCILE_STREAM_OUTPUT",
  "ADD_TRACE_EVENT",
  "SET_CONTEXT_USAGE",
  "SET_PLAN_MEMORY_INFO",
  "OPEN_FILE_PREVIEW",
])
const MAX_TRACKED_TASK_STATE_VERSIONS = 500
// A Session may reset repeatedly during its absolute lifetime. Retired ids are
// retained only to reject late frames, so bound this lineage guard separately
// from the unrelated task-state ordering cache.
const MAX_RETIRED_SESSION_TASK_IDS = 500
const SESSION_RESET_ACK_TIMEOUT_MS = 30_000
const SESSION_TASK_ADOPTION_TIMEOUT_MS = 30_000
const SESSION_STOP_TIMEOUT_MS = 30_000
const MAX_SESSION_PRE_ADOPTION_FRAMES = 64
const MAX_SESSION_PRE_ADOPTION_BYTES = 256 * 1024

type SessionConversationState =
  | { phase: "unbound"; connectionIdentity: string | null; taskId: null }
  | { phase: "bound"; connectionIdentity: string; taskId: number }
  | { phase: "reset_requested"; connectionIdentity: string; taskId: number }
  | { phase: "replacement_ready"; connectionIdentity: string; taskId: null }
  | { phase: "replacement_sending"; connectionIdentity: string; taskId: null }
  | { phase: "replacement_awaiting_task"; connectionIdentity: string; taskId: null }
  | { phase: "reload_required"; connectionIdentity: string | null; taskId: null }

// The stop control's own state. The server sends no acknowledgement frame for
// a stop, so "stopping" ends in one of six ways: this task's terminal frame,
// the local timeout above, an agent_error for this task that carries no code
// or carries external_stop_not_applied, a reconnect (the button's own state is
// per-connection and cannot outlive the connection it was set on), the
// control ceasing to be available while the run pauses without ending or
// while the socket is down (see the effect keyed on canStopTask), or a later
// stop attempt that the socket refuses, which moves the state straight to
// "not_sent" (see stopTask). The last one is defensive: the stop button ignores
// presses while a stop is pending, so only a caller other than the button can
// reach it. That agent_error only returns the control to pressable and does
// not end the stop intent: it is broadcast to every connection on the task
// without naming which stop press it answers. "not_sent" itself is usually
// short-lived: a socket that refuses a frame is normally closing or already
// replaced, and once the drop or the new connection is observed the control
// returns to "idle" (the effect keyed on canStopTask, or the one keyed on the
// connection identity).
export type SessionStopState = "idle" | "stopping" | "timed_out" | "not_sent"

export type SessionStop = {
  control: SessionStopState
  // Per task, not per connection: "the visitor asked to stop task N" stays
  // true across a token-refresh reconnect and across an isProcessing dip. It
  // is cleared by that task's own terminal frame -- failure or completion --
  // and by this connection binding a different task. Nothing else clears it:
  // an agent_error, coded external_stop_not_applied or codeless, is broadcast
  // to every connection on the task without naming which stop press it
  // answers, so it releases the control and leaves the intent standing.
  intentTaskId: number | null
  // The last task this connection was bound to, so a change of bound task can
  // be told apart from the first binding.
  boundTaskId: number | null
}

export type SessionStopEvent =
  | { type: "STOP_SENT"; taskId: number }
  | { type: "STOP_NOT_SENT" }
  | { type: "STOP_TIMED_OUT" }
  // Sent only for a task_error whose projectErrorFrameForDisplay result has
  // endsStopIntent, so the reducer does not match the task again.
  | { type: "STOPPED_TASK_FAILED" }
  | { type: "TASK_COMPLETED"; taskId: number | undefined }
  // An agent_error that carries no code or carries external_stop_not_applied.
  | { type: "STOP_NOT_APPLIED"; taskId: number | undefined }
  | { type: "CONNECTION_CHANGED" }
  | { type: "STOP_UNAVAILABLE" }
  | { type: "TASK_BOUND"; taskId: number }

// The one side effect a stop transition can ask for: the 30-second window
// that ends "stopping" in "timed_out". "arm_timeout" replaces any window
// already running.
export type SessionStopEffect = "arm_timeout" | "clear_timeout" | null

export type SessionStopTransition = {
  next: SessionStop
  effect: SessionStopEffect
}

export const initialSessionStop: SessionStop = {
  control: "idle",
  intentTaskId: null,
  boundTaskId: null,
}

// A frame answers the stop intent when it names the task the visitor asked to
// stop. A frame's task id is never null, so no frame matches when there is no
// intent.
export const isFrameForStopIntent = (
  intentTaskId: number | null,
  frameTaskId: number | undefined,
): boolean => frameTaskId === intentTaskId

// Pure on purpose, like reduceSessionConversation: the provider keeps the
// result in a ref, mirrors `control` into React state and runs `effect`, so
// every transition is unit-testable without rendering the provider.
export const reduceSessionStop = (
  state: SessionStop,
  event: SessionStopEvent,
): SessionStopTransition => {
  switch (event.type) {
    case "STOP_SENT":
      // A fresh window replaces any earlier one. Only a stop that left the
      // socket does that; one that did not leaves the earlier window running
      // (see STOP_NOT_SENT). Defensive: the stop button ignores presses while
      // a stop is pending, so only a caller other than the button can send a
      // stop with a window still armed.
      return {
        next: { ...state, control: "stopping", intentTaskId: event.taskId },
        effect: "arm_timeout",
      }
    case "STOP_NOT_SENT":
      // The frame never left the socket, so nobody received the request, so
      // the hint says so rather than reusing the unconfirmed-timeout wording.
      // An earlier attempt's window keeps running, so the request that did
      // leave the socket can still reach its unconfirmed timeout instead of
      // ending in a state nothing ever advances.
      return { next: { ...state, control: "not_sent" }, effect: null }
    case "STOP_TIMED_OUT":
      return { next: { ...state, control: "timed_out" }, effect: null }
    case "STOPPED_TASK_FAILED":
      return {
        next: { ...state, control: "idle", intentTaskId: null },
        effect: "clear_timeout",
      }
    case "TASK_COMPLETED":
      // A stop intent lives until this task's next terminal frame, and a
      // normal completion is the other terminal frame. Without this, an
      // intent recorded for a turn that finished on its own would still be
      // standing when a later turn of the same task is interrupted by a stop
      // this visitor did not ask for, and that turn would render as this
      // visitor's stopped turn. The control is left alone: the completion
      // also ends processing, which releases it through STOP_UNAVAILABLE.
      return isFrameForStopIntent(state.intentTaskId, event.taskId)
        ? { next: { ...state, intentTaskId: null }, effect: null }
        : { next: state, effect: null }
    case "STOP_NOT_APPLIED":
      // The frame does not name which stop press it answers, so it cannot end
      // the stop intent: a second press on this page, or a press on another
      // page bound to the same task, may still take effect. What it does
      // answer is the button: the visitor has just been shown a sentence
      // about a failure on this task, and a control still stuck on
      // "Stopping..." would contradict it.
      return isFrameForStopIntent(state.intentTaskId, event.taskId)
        ? { next: { ...state, control: "idle" }, effect: "clear_timeout" }
        : { next: state, effect: null }
    case "CONNECTION_CHANGED":
    case "STOP_UNAVAILABLE":
      // The button's own state is per connection and lasts only while the
      // control is available. The intent is per task and survives both.
      return { next: { ...state, control: "idle" }, effect: "clear_timeout" }
    case "TASK_BOUND":
      // The task this connection is bound to changed. It had to pass through
      // an unbound or replacement phase to get here -- SESSION_TASK_INFO
      // leaves the bound id alone when a task_info names a different task --
      // so whatever the visitor asked to stop, this connection no longer
      // follows it. Only the intent is cleared: the control was already
      // released on the way through that phase, because canStopTask is false
      // there.
      return state.boundTaskId === null || state.boundTaskId === event.taskId
        ? { next: { ...state, boundTaskId: event.taskId }, effect: null }
        : {
            next: { ...state, boundTaskId: event.taskId, intentTaskId: null },
            effect: null,
          }
  }
}

type SessionConversationAction =
  | { type: "SESSION_TASK_INFO"; connectionIdentity: string; taskId: number }
  | { type: "SESSION_RESET_REQUESTED"; connectionIdentity: string; taskId: number }
  | { type: "SESSION_RESET_NOT_SENT"; connectionIdentity: string }
  | { type: "SESSION_RESET_ACKNOWLEDGED"; connectionIdentity: string }
  | { type: "SESSION_REPLACEMENT_SENDING"; connectionIdentity: string }
  | { type: "SESSION_REPLACEMENT_ACCEPTED"; connectionIdentity: string }
  | { type: "SESSION_REPLACEMENT_REJECTED"; connectionIdentity: string }
  | { type: "SESSION_BOUND_CONNECTION_REBOUND"; connectionIdentity: string }
  | { type: "SESSION_RELOAD_REQUIRED"; connectionIdentity: string | null }

const initialSessionConversationState: SessionConversationState = {
  phase: "unbound",
  connectionIdentity: null,
  taskId: null,
}

const reduceSessionConversation = (
  state: SessionConversationState,
  action: SessionConversationAction,
): SessionConversationState => {
  if (state.phase === "reload_required") return state
  switch (action.type) {
    case "SESSION_TASK_INFO":
      if (state.phase === "unbound") {
        return { phase: "bound", connectionIdentity: action.connectionIdentity, taskId: action.taskId }
      }
      if (
        state.phase === "replacement_awaiting_task"
        && state.connectionIdentity === action.connectionIdentity
      ) {
        return { phase: "bound", connectionIdentity: action.connectionIdentity, taskId: action.taskId }
      }
      return state
    case "SESSION_RESET_REQUESTED":
      return state.phase === "bound" && state.connectionIdentity === action.connectionIdentity
        ? { phase: "reset_requested", connectionIdentity: action.connectionIdentity, taskId: action.taskId }
        : state
    case "SESSION_RESET_NOT_SENT":
      return state.phase === "reset_requested" && state.connectionIdentity === action.connectionIdentity
        ? { phase: "bound", connectionIdentity: state.connectionIdentity, taskId: state.taskId }
        : state
    case "SESSION_RESET_ACKNOWLEDGED":
      return state.phase === "reset_requested" && state.connectionIdentity === action.connectionIdentity
        ? { phase: "replacement_ready", connectionIdentity: action.connectionIdentity, taskId: null }
        : state
    case "SESSION_REPLACEMENT_SENDING":
      return state.phase === "replacement_ready" && state.connectionIdentity === action.connectionIdentity
        ? { phase: "replacement_sending", connectionIdentity: action.connectionIdentity, taskId: null }
        : state
    case "SESSION_REPLACEMENT_ACCEPTED":
      return state.phase === "replacement_sending" && state.connectionIdentity === action.connectionIdentity
        ? { phase: "replacement_awaiting_task", connectionIdentity: action.connectionIdentity, taskId: null }
        : state
    case "SESSION_REPLACEMENT_REJECTED":
      return state.phase === "replacement_sending" && state.connectionIdentity === action.connectionIdentity
        ? { phase: "replacement_ready", connectionIdentity: action.connectionIdentity, taskId: null }
        : state
    case "SESSION_BOUND_CONNECTION_REBOUND":
      return state.phase === "bound"
        ? { ...state, connectionIdentity: action.connectionIdentity }
        : state
    case "SESSION_RELOAD_REQUIRED":
      return { phase: "reload_required", connectionIdentity: action.connectionIdentity, taskId: null }
  }
}

type SessionConversationTransition = {
  accepted: boolean
  changed: boolean
  next: SessionConversationState
}

const transitionSessionConversation = (
  current: SessionConversationState,
  action: SessionConversationAction,
): SessionConversationTransition => {
  const next = reduceSessionConversation(current, action)
  const changed = next !== current
  const accepted = changed || (
    action.type === "SESSION_TASK_INFO"
    && current.phase === "bound"
    && current.connectionIdentity === action.connectionIdentity
    && current.taskId === action.taskId
  )
  return { accepted, changed, next }
}

const asMessageRecord = (value: unknown): Record<string, unknown> =>
  value && typeof value === "object" ? value as Record<string, unknown> : {}

const parseInteger = (value: unknown): number | undefined => {
  if (typeof value === "number") return Number.isInteger(value) ? value : undefined
  if (typeof value !== "string" || value.trim() === "") return undefined
  const parsed = Number(value)
  return Number.isInteger(parsed) ? parsed : undefined
}

export const extractTaskControlEnvelope = (message: WebSocketMessage): TaskControlEnvelope => {
  const root = message as unknown as Record<string, unknown>
  const data = asMessageRecord(root.data)
  const nestedData = asMessageRecord(data.data)
  const task = asMessageRecord(root.task)
  const eventType = String(root.event_type || data.event_type || "")
  const isStateEvent = VERSIONED_TASK_EVENT_TYPES.has(message.type)
    || (message.type === "trace_event" && eventType === "task_info")
  if (!isStateEvent) return { isStateEvent: false }

  const rawTaskId = root.task_id ?? task.id ?? data.id ?? nestedData.id
  const parsedTaskId = parseInteger(rawTaskId)
  const rawVersion =
    root.state_version
    ?? task.state_version
    ?? data.state_version
    ?? nestedData.state_version
  const parsedVersion = parseInteger(rawVersion)
  const rawRunId =
    root.run_id ?? task.run_id ?? data.run_id ?? nestedData.run_id
  const rawControlState =
    root.control_state
    ?? task.control_state
    ?? data.control_state
    ?? nestedData.control_state
  const rawStatus =
    root.status ?? task.status ?? data.status ?? nestedData.status

  return {
    isStateEvent: true,
    taskId: parsedTaskId !== undefined && parsedTaskId > 0 ? parsedTaskId : undefined,
    runId: typeof rawRunId === "string" || rawRunId === null ? rawRunId : undefined,
    stateVersion: parsedVersion !== undefined && parsedVersion >= 0 ? parsedVersion : undefined,
    controlState: typeof rawControlState === "string" ? rawControlState as TaskControlState : undefined,
    status: normalizeTaskStatus(rawStatus) || undefined,
  }
}

const taskEventMatchesControlState = (
  message: WebSocketMessage,
  envelope: TaskControlEnvelope,
): boolean => {
  const expected: Partial<Record<string, TaskControlState[]>> = {
    task_completed: ["completed", "failed"],
    task_pause_requested: ["pause_requested"],
    task_paused: ["paused"],
    task_resumed: ["running"],
    task_started: ["running"],
    task_waiting_for_user: ["waiting_for_user"],
  }
  const allowed = expected[message.type]
  return !allowed || !envelope.controlState || allowed.includes(envelope.controlState)
}

type TaskStateVersionEntry = {
  version: number
  runId?: string | null
}

const canAcceptTaskControlVersion = (
  message: WebSocketMessage,
  envelope: TaskControlEnvelope,
  versions: Map<number, TaskStateVersionEntry>,
): boolean => {
  if (!envelope.isStateEvent || envelope.taskId === undefined) return true

  const knownState = versions.get(envelope.taskId)
  if (envelope.stateVersion === undefined) {
    // Once the server establishes versioned state for a Task, an unversioned
    // replay cannot roll it back. Error frames remain informational.
    const isErrorEvent =
      message.type === "error" || message.type === "agent_error"
    return !knownState || isErrorEvent
  }

  const isOlderVersion =
    knownState && envelope.stateVersion < knownState.version
  const isDifferentRunAtSameVersion =
    knownState
    && envelope.stateVersion === knownState.version
    && knownState.runId !== undefined
    && envelope.runId !== undefined
    && knownState.runId !== envelope.runId
  if (isOlderVersion || isDifferentRunAtSameVersion) return false

  return true
}

const acceptTaskControlVersion = (
  message: WebSocketMessage,
  envelope: TaskControlEnvelope,
  versions: Map<number, TaskStateVersionEntry>,
): boolean => {
  if (!canAcceptTaskControlVersion(message, envelope, versions)) return false
  if (!envelope.isStateEvent || envelope.taskId === undefined) return true
  if (envelope.stateVersion === undefined) return true

  versions.delete(envelope.taskId)
  versions.set(envelope.taskId, {
    version: envelope.stateVersion,
    runId: envelope.runId,
  })
  if (versions.size > MAX_TRACKED_TASK_STATE_VERSIONS) {
    const oldestTaskId = versions.keys().next().value
    if (oldestTaskId !== undefined) versions.delete(oldestTaskId)
  }
  return true
}

export interface Interaction {
  type: "select_one" | "select_multiple" | "text_input" | "file_upload" | "confirm" | "number_input" | "action_cards" | "connect_apps" | "teammate_summary";
  field: string;
  label: string;
  /** Read-only first-run overview seeded from the hired template. */
  description?: string;
  options?: Array<{ label: string; value: string; description?: string; action_type?: string }>;
  placeholder?: string;
  multiline?: boolean;
  min?: number;
  max?: number;
  default?: any;
  default_value?: string | number | boolean | null;
  accept?: string[] | string;
  multiple?: boolean;
  /** For "connect_apps": connector app display names (matched against
   * useMcpApps()'s McpApp.name) to group by OAuth provider and render as
   * connect cards - e.g. ["Gmail", "Google Calendar", "HubSpot"]. */
  apps?: string[];
  /** First-run cards group builtin OAuth apps under their shared provider. */
  group_by_provider?: boolean;
}
import {
  useWebSocket,
  MessageDeliveryError,
  type WebSocketConnection,
  type WebSocketConnectionFailure,
} from "@/hooks/use-websocket"
import { ResendWaiters, mayResend, sendWithResend, type ResendOwnership } from "./chat-delivery-resend"
import { deriveConnectionNotice, type ConnectionNotice } from "./connection-notice"
import { generateClientMessageId, getApiUrl, getUploadApiUrl, shouldAutoOpenTaskPreview } from "@/lib/utils"
import { apiRequest, classifyUploadError, getApiErrorMessage, isJsonRecord, parseApiResponse } from "@/lib/api-wrapper"
import { clientErrorTranslationKey, isInputReviewErrorCode, readClientErrorCode, type ClientErrorCode } from "@/lib/client-errors"
import { normalizeUploadFileIds } from "@/lib/upload-file-ids"
import type { SessionUploadedFile } from "@/lib/widget-session-upload"
import { useI18n, type Translate } from "@/contexts/i18n-context"
import { normalizeTimestampMs } from "@/lib/time-utils"
import { unwrapFinalAnswerContent } from "@/lib/final-answer"
import { normalizeCompletionOutcome, normalizeTaskCompletedMessage, type TaskCompletionOutcome } from "@/lib/task-completion"
import { emitTaskError } from "@/lib/task-error-events"
import { isStoppedTaskStatus, normalizeTaskStatus, type TaskStatus } from "@/lib/task-status"
import {
  getFinalAnswerStreamActionPayload,
  getFinalAnswerStreamMessageId,
  getWebSocketEventType,
  isFinalAnswerStreamEventType,
  isStreamingFinalAnswerMessage,
  mergeTraceEventsById,
  shouldBufferMessageForHistoricalReplay,
} from "@/lib/streaming-final-answer"
import { extractSharedChatResponse } from "@/lib/chat-response"
import {
  isStableAssistantMessageId,
  stableAssistantMessageId,
} from "@/lib/assistant-message-identity"

// Unique ID generator for messages
let messageIdCounter = 0
const generateMessageId = (prefix: string) => {
  return `${prefix}-${++messageIdCounter}-${Date.now()}-${Math.random().toString(36).substr(2, 5)}`
}

// Providers own their own dedupe cache. The window hook is retained solely for
// legacy hot-reload callers and clears registered provider-local caches.
const duplicateMessageCacheClearers = new Set<() => void>()

// Helper function to compare arrays
const arraysEqual = (a: string[], b: string[]): boolean => {
  if (a === b) return true
  if (a == null || b == null) return false
  if (a.length !== b.length) return false
  return a.every((val, index) => val === b[index])
}

type GeneratedPreviewFile = {
  fileId: string
  fileName: string
}

const normalizeGeneratedPreviewFiles = (files: Array<string | any> | undefined): GeneratedPreviewFile[] => {
  if (!Array.isArray(files)) return []

  return files.map((file) => {
    if (typeof file === 'object' && file !== null) {
      return {
        fileId: file.file_id || '',
        fileName: file.filename || 'unknown',
      }
    }

    return {
      fileId: '',
      fileName: 'unknown',
    }
  }).filter((file) => !!file.fileId)
}

const getAutoOpenGeneratedPreviewIndex = (files: GeneratedPreviewFile[]): number => {
  return files.findIndex((file) => shouldAutoOpenTaskPreview(file.fileName))
}

const dispatchAutoOpenPreview = (
  files: Array<string | any> | undefined,
  dispatch: React.Dispatch<any>,
) => {
  const previewFiles = normalizeGeneratedPreviewFiles(files)
  const autoOpenIndex = getAutoOpenGeneratedPreviewIndex(previewFiles)
  if (autoOpenIndex < 0) return

  const autoOpenFile = previewFiles[autoOpenIndex]
  dispatch({
    type: "OPEN_FILE_PREVIEW",
    payload: {
      fileId: autoOpenFile.fileId,
      fileName: autoOpenFile.fileName,
      files: previewFiles,
      index: autoOpenIndex,
    }
  })
}

const USER_TURN_MESSAGE_PREFIX = "msg-user-turn"
const USER_EVENT_MESSAGE_PREFIX = "msg-user-event"
const USER_MESSAGE_REPLACE_WINDOW_MS = 30000

const userTurnMessageId = (turnId: string): string =>
  `${USER_TURN_MESSAGE_PREFIX}-${turnId}`

const stableUserMessageId = (
  eventData: { turn_id?: unknown } & Record<string, unknown>,
  eventId?: unknown,
): string | null => {
  const turnId = eventData.turn_id
  if (typeof turnId === "string" && turnId.trim()) {
    return userTurnMessageId(turnId.trim())
  }

  if (typeof eventId === "string" && eventId.trim()) {
    return `${USER_EVENT_MESSAGE_PREFIX}-${eventId.trim()}`
  }

  return null
}

const extractTextFromReactNode = (node: React.ReactNode): string => {
  if (typeof node === 'string') return node
  if (typeof node === 'number') return node.toString()
  if (Array.isArray(node)) return node.map(extractTextFromReactNode).join('')
  if (React.isValidElement(node) && node.props.children) {
    return extractTextFromReactNode(node.props.children)
  }
  return ''
}

const normalizeMessageContent = (content: string | React.ReactNode): string => {
  if (typeof content === 'string') {
    return content.trim()
  }
  if (typeof content === 'number') {
    return content.toString()
  }
  if (React.isValidElement(content) || Array.isArray(content)) {
    return extractTextFromReactNode(content).trim()
  }
  return ''
}

// A user message id minted from a stable per-turn identity: the wire's
// `turn_id` / `event_id` (stableUserMessageId) or the sender's own
// client_message_id (userTurnMessageId), which the backend echoes back as
// that turn's id.
const hasStableUserTurnIdentity = (id: string): boolean =>
  id.startsWith(`${USER_TURN_MESSAGE_PREFIX}-`) ||
  id.startsWith(`${USER_EVENT_MESSAGE_PREFIX}-`)

const findOptimisticUserMessageIndex = (
  messages: Message[],
  incomingMessage: Message,
): number => {
  if (incomingMessage.role !== "user") {
    return -1
  }

  // Identity beats text: a message carrying one is reconciled by
  // ADD_MESSAGE's id branch alone. Merging by text instead can drop a turn
  // from the transcript with no error, and repeated text is routine here -
  // a clarification form with no free-text field serializes to a fixed
  // string. Only identity-less legacy events still need text. See the commit
  // for which same-turn pairs this gives up on, and why they are unreachable.
  if (hasStableUserTurnIdentity(incomingMessage.id)) {
    return -1
  }

  const normalizedIncomingContent = normalizeMessageContent(incomingMessage.content)
  if (!normalizedIncomingContent) {
    return -1
  }

  const incomingTimestamp = normalizeTimestampMs(incomingMessage.timestamp)

  for (let index = messages.length - 1; index >= 0; index -= 1) {
    const existingMessage = messages[index]
    if (existingMessage.role !== "user" || !existingMessage.isOptimistic) {
      continue
    }

    if (normalizeMessageContent(existingMessage.content) !== normalizedIncomingContent) {
      continue
    }

    const existingTimestamp = normalizeTimestampMs(existingMessage.timestamp)
    if (
      Number.isFinite(existingTimestamp) &&
      Number.isFinite(incomingTimestamp) &&
      Math.abs(incomingTimestamp - existingTimestamp) > USER_MESSAGE_REPLACE_WINDOW_MS
    ) {
      continue
    }

    return index
  }

  return -1
}

// Expose to window for global access
if (typeof window !== 'undefined') {
  ; (window as any).clearDuplicateMessageCache = () => {
    duplicateMessageCacheClearers.forEach(clear => clear())
  }
}
export const normalizeInteractions = (value: unknown): Interaction[] => {
  if (!Array.isArray(value)) {
    return []
  }

  const seenFields = new Set<string>()

  return value
    .map((item: any, index) => {
      if (!item || typeof item !== "object") {
        return null
      }

      const rawType = item.type
      const type =
        rawType === "input" || rawType === "text" || rawType === "textarea" || rawType === "string"
          ? "text_input"
          : rawType === "file" || rawType === "upload"
            ? "file_upload"
            : rawType === "number" || rawType === "integer"
              ? "number_input"
              : rawType === "boolean"
                ? "confirm"
                : rawType
      const rawField = item.field || item.id || item.name || item.properties?.field || item.properties?.id || `response_${index}`
      const baseField = typeof rawField === "string" && rawField.trim() ? rawField.trim() : `response_${index}`
      const field = seenFields.has(baseField) ? `${baseField}_${index}` : baseField
      seenFields.add(field)
      if (
        !["select_one", "select_multiple", "text_input", "file_upload", "confirm", "number_input", "action_cards", "connect_apps", "teammate_summary"].includes(type) ||
        typeof field !== "string" ||
        !field.trim()
      ) {
        return null
      }

      const normalized: Interaction = {
        type,
        field,
        label: typeof item.label === "string" && item.label.trim() ? item.label : field,
      }

      const rawOptions = Array.isArray(item.options)
        ? item.options
        : Array.isArray(item.actions)
          ? item.actions
          : undefined

      if (Array.isArray(rawOptions)) {
        normalized.options = rawOptions
          .filter((opt: any) => opt && typeof opt.value === "string")
          .map((opt: any) => ({
            value: opt.value,
            label: typeof opt.label === "string" ? opt.label : opt.value,
            description: typeof opt.description === "string" ? opt.description : undefined,
            action_type: typeof opt.action_type === "string" ? opt.action_type : undefined,
          }))
      }

      if (typeof item.description === "string") normalized.description = item.description
      if (typeof item.placeholder === "string") normalized.placeholder = item.placeholder
      if (typeof item.properties?.placeholder === "string") normalized.placeholder = item.properties.placeholder
      if (typeof item.multiline === "boolean") normalized.multiline = item.multiline
      if (typeof item.properties?.multiline === "boolean") normalized.multiline = item.properties.multiline
      if (typeof item.min === "number") normalized.min = item.min
      if (typeof item.max === "number") normalized.max = item.max
      if (typeof item.default !== "undefined") normalized.default = item.default
      if (item.default_value === null || typeof item.default_value === "string" || typeof item.default_value === "boolean" || (typeof item.default_value === "number" && Number.isFinite(item.default_value))) {
        normalized.default_value = item.default_value
      }
      if (Array.isArray(item.accept) || typeof item.accept === "string") normalized.accept = item.accept
      if (typeof item.multiple === "boolean") normalized.multiple = item.multiple
      if (typeof item.group_by_provider === "boolean") normalized.group_by_provider = item.group_by_provider
      if (Array.isArray(item.apps)) {
        normalized.apps = item.apps.filter((app: unknown): app is string => typeof app === "string")
      }

      return normalized
    })
    .filter(Boolean) as Interaction[]
}

const extractClarificationMessage = (raw: unknown): { message?: string; interactions: Interaction[] } | null => {
  const sharedResponse = extractSharedChatResponse(raw)
  const interactions = normalizeInteractions(sharedResponse?.interactions)

  if (interactions.length === 0) {
    return null
  }

  return {
    message: sharedResponse?.message,
    interactions,
  }
}


interface Message {
  id: string
  role: "user" | "assistant"
  content: string | React.ReactNode
  rawContent?: string
  timestamp: string
  status?: "pending" | "running" | "completed" | "failed" | "interrupted"
  isResult?: boolean
  isFileOutput?: boolean
  streamMessageId?: string
  executionSequence?: number
  traceEvents?: TraceEvent[]
  interactions?: Interaction[]
  interactionRequestId?: string
  isSystemNotice?: boolean
  isOptimistic?: boolean
}

export type TaskRuntimeExtensions = Record<string, Record<string, unknown>>

const normalizeTaskRuntimeExtensions = (value: unknown): TaskRuntimeExtensions => {
  if (!isJsonRecord(value)) return {}
  return Object.fromEntries(
    Object.entries(value).filter((entry): entry is [string, Record<string, unknown>] => (
      isJsonRecord(entry[1])
    )),
  )
}

// Why a PAUSED task's run stopped: the server's ``auto_recovery`` view
// (history task_info) or a ``task_paused`` event's ``interruption_reason``.
// ``reason`` is an InterruptionReason value (``user_pause`` when the user
// paused it). The fence prevents a reason from one pause being reused by a
// later, reason-less pause.
export interface TaskAutoRecovery {
  reason: string
  runId?: string
  stateVersion?: number
}

const normalizeAutoRecovery = (
  value: unknown,
  runId?: unknown,
  stateVersion?: unknown,
): TaskAutoRecovery | undefined => {
  if (!isJsonRecord(value) || typeof value.reason !== "string" || !value.reason) {
    return undefined
  }
  const parsedStateVersion = parseInteger(stateVersion)
  return {
    reason: value.reason,
    ...(typeof runId === "string" && parsedStateVersion !== undefined
      ? { runId, stateVersion: parsedStateVersion }
      : {}),
  }
}

// Automatic resume of a paused task, from task_info or the latest
// ``task_recovery_update`` event: scheduled, under way, or stopped
// (``stopReason`` says why). It is tied to the fence it was announced at and
// kept only while the task rests there.
export interface TaskAutoResume {
  status: "scheduled" | "resuming" | "stopped"
  stopReason?: string
  nextAttemptAt?: string
  attempt?: number
  runId: string
  stateVersion: number
}

const AUTO_RESUME_STATUSES = new Set(["scheduled", "resuming", "stopped"])

const parseAutoResumeAtFence = (
  value: unknown,
  runId: unknown,
  stateVersion: unknown,
): TaskAutoResume | undefined => {
  const view = asMessageRecord(value)
  const parsedStateVersion = parseInteger(stateVersion)
  const status = view.status
  if (
    typeof runId !== "string"
    || parsedStateVersion === undefined
    || typeof status !== "string"
    || !AUTO_RESUME_STATUSES.has(status)
  ) return undefined

  return {
    status: status as TaskAutoResume["status"],
    stopReason: typeof view.stop_reason === "string" ? view.stop_reason : undefined,
    nextAttemptAt: typeof view.next_attempt_at === "string" ? view.next_attempt_at : undefined,
    attempt: parseInteger(view.attempt),
    runId,
    stateVersion: parsedStateVersion,
  }
}

const autoResumeSortKey = (notice: TaskAutoResume): [number, number] | undefined => {
  if (notice.attempt === undefined) return undefined
  switch (notice.status) {
    case "resuming":
      return [notice.attempt, 0]
    case "scheduled":
      return [notice.attempt - 1, 1]
    case "stopped":
      return [notice.attempt, 2]
  }
}

const newerAutoResume = (
  current: TaskAutoResume | undefined,
  incoming: TaskAutoResume | undefined,
): TaskAutoResume | undefined => {
  if (!current || !incoming) return incoming ?? current
  if (
    current.runId !== incoming.runId
    || current.stateVersion !== incoming.stateVersion
  ) return incoming

  const currentKey = autoResumeSortKey(current)
  const incomingKey = autoResumeSortKey(incoming)
  if (!currentKey) return incoming
  if (!incomingKey) return current
  if (incomingKey[0] !== currentKey[0]) {
    return incomingKey[0] > currentKey[0] ? incoming : current
  }
  return incomingKey[1] >= currentKey[1] ? incoming : current
}

// ``task_recovery_update`` -> the task it is for and its notice, or nothing
// for a malformed event.
export const parseAutoResumeNotice = (
  message: unknown,
): { taskId: number; reason?: string; notice: TaskAutoResume } | undefined => {
  const root = asMessageRecord(message)
  // useWebSocket moves an unrecognised event's body into ``data`` and keeps
  // the control envelope (task_id, run_id, state_version) at the root.
  const view = asMessageRecord(root.auto_resume ?? asMessageRecord(root.data).auto_resume)
  const taskId = parseInteger(root.task_id)
  const notice = parseAutoResumeAtFence(view, root.run_id, root.state_version)
  if (taskId === undefined || !notice) return undefined
  return {
    taskId,
    reason: typeof view.reason === "string" && view.reason ? view.reason : undefined,
    notice,
  }
}

// Recovery state belongs to the fence where it was learned. Status can be
// inferred as running during history replay, so it must not erase the held
// state; the conversation panel separately gates its display on PAUSED.
const atTaskFence = <T extends { runId?: string; stateVersion?: number }>(
  task: Task,
  value: T | undefined,
): T | undefined => value
  && value.stateVersion === task.stateVersion
  && value.runId === task.runId
  ? value
  : undefined

const clearStaleAutoRecovery = (task: Task | null): Task | null => {
  if (!task) return task
  const autoRecovery = atTaskFence(task, task.autoRecovery)
  const autoResume = atTaskFence(task, task.autoResume)
  const autoResumeEndedAt = atTaskFence(task, task.autoResumeEndedAt)
  return autoRecovery === task.autoRecovery
    && autoResume === task.autoResume
    && autoResumeEndedAt === task.autoResumeEndedAt
    ? task
    : { ...task, autoRecovery, autoResume, autoResumeEndedAt }
}

const mergeTaskSnapshot = (current: Task, incoming: Task): Task => {
  const sameFence = current.runId === incoming.runId
    && current.stateVersion === incoming.stateVersion
  const incomingHasAutoRecovery = hasOwn(incoming, "autoRecovery")
  const incomingHasAutoResume = hasOwn(incoming, "autoResume")
  const incomingHasAutoResumeEndedAt = hasOwn(incoming, "autoResumeEndedAt")
  const merged: Task = {
    ...current,
    ...incoming,
    agentName: incoming.agentName || current.agentName,
    agentLogoUrl: incoming.agentLogoUrl || current.agentLogoUrl,
  }

  if (!sameFence) {
    if (!incomingHasAutoRecovery) merged.autoRecovery = undefined
    if (!incomingHasAutoResume) merged.autoResume = undefined
    if (!incomingHasAutoResumeEndedAt) merged.autoResumeEndedAt = undefined
    return merged
  }

  if (!incomingHasAutoRecovery) merged.autoRecovery = current.autoRecovery
  const endedAt = incoming.autoResumeEndedAt ?? current.autoResumeEndedAt
  if (endedAt) {
    merged.autoResume = undefined
    merged.autoResumeEndedAt = endedAt
  } else if (!incomingHasAutoResume) {
    // An absent view or an overall null ``auto_recovery`` cannot prove a
    // live notice is stale.
    merged.autoResume = current.autoResume
  } else {
    merged.autoResume = newerAutoResume(current.autoResume, incoming.autoResume)
  }
  return merged
}

// Session adoption receives the authoritative task record for the new turn.
// Only the recovery views need reconciliation with live websocket state; a
// whole-record merge would leak stale waiting/DAG fields into the new turn.
const mergeTaskRecoverySnapshot = (current: Task, incoming: Task): Task => {
  const recovery = mergeTaskSnapshot(current, incoming)
  return {
    ...incoming,
    autoRecovery: recovery.autoRecovery,
    autoResume: recovery.autoResume,
    autoResumeEndedAt: recovery.autoResumeEndedAt,
  }
}

export interface Task {
  id: string
  title: string
  status: TaskStatus
  completionOutcome?: TaskCompletionOutcome
  conversationStorageVersion?: number
  description: string
  createdAt: string | number
  updatedAt: string | number
  // Model configuration
  modelId?: string
  smallFastModelId?: string
  visualModelId?: string
  compactModelId?: string
  modelName?: string
  smallFastModelName?: string
  visualModelName?: string
  compactModelName?: string
  executionMode?: "auto" | "flash" | "balanced" | "think"
  isDag?: boolean
  agentId?: number
  agentName?: string
  agentLogoUrl?: string
  runtimeExtensionBindings?: string[]
  waitingQuestion?: string
  waitingInteractions?: Interaction[]
  waitingRequestId?: string
  runId?: string | null
  stateVersion?: number
  controlState?: TaskControlState
  autoRecovery?: TaskAutoRecovery
  autoResume?: TaskAutoResume
  // A fence-matching ``auto_resume: null`` is terminal for that fence. Keep
  // this marker so delayed same-fence events cannot resurrect the notice.
  autoResumeEndedAt?: { runId: string; stateVersion: number }
  // Frontend-only, distinct from updatedAt: stamped once by UPDATE_TASK_STATUS
  // when this run actually terminates (completed/failed), cleared when it
  // starts running again, and deliberately preserved across SET_CURRENT_TASK
  // refreshes for the same task (see that reducer case) - updatedAt is
  // general task metadata that can legitimately change again later (a title
  // edit, another field's update) for reasons that have nothing to do with
  // when this execution actually ended, and the Progress panel's frozen
  // elapsed time must not drift when that happens.
  dagTerminatedAt?: string | number
  // True when dagTerminatedAt was BACKFILLED from mutable task metadata
  // (updatedAt, by withDagTerminatedAt below) rather than stamped by an
  // actual terminal event - a cold history load fetches the Task row before
  // any terminal event replays, and updatedAt may by then reflect a
  // post-execution metadata change (a title edit) rather than the real end
  // time. A later authoritative terminal event may replace a provisional
  // value (see UPDATE_TASK_STATUS); a non-provisional one stays
  // first-write-wins.
  dagTerminatedAtProvisional?: boolean
}

// Exported so every consumer of dagTerminatedAt's "is this task done" gate
// (currently just page-client.tsx's isDagFinished) shares the exact
// definition this field is stamped/cleared against - the two must never
// drift apart, or isDagFinished can read true while dagTerminatedAt was
// never set (or vice versa), leaving the Progress panel's clock either
// stuck or never frozen.
export const isTerminalTaskStatus = (status: TaskStatus | null | undefined): boolean =>
  status === "completed" || status === "failed"

// Applies dagTerminatedAt's full set of rules to a Task about to be stored:
// preserve an already-set value (never re-derive it from a later, unrelated
// updatedAt change), backfill it once from updatedAt if this task arrives
// already terminal without one, and clear it if the task isn't terminal (a
// stale value from a prior run must not linger once it starts running
// again). Shared by every reducer case that can hand the app a whole Task
// object - SET_CURRENT_TASK and ADOPT_SESSION_TASK - so neither can
// individually forget a rule the other already gets right.
const withDagTerminatedAt = (task: Task | null): Task | null => {
  if (!task) return task
  if (!isTerminalTaskStatus(task.status)) {
    return task.dagTerminatedAt === undefined && task.dagTerminatedAtProvisional === undefined
      ? task
      : { ...task, dagTerminatedAt: undefined, dagTerminatedAtProvisional: undefined }
  }
  // Checked for presence, not truthiness, when preserving: updatedAt (what
  // the backfill below uses) is a real epoch value that can legitimately be
  // 0 - a truthy check would treat that as "absent" and re-derive it from a
  // LATER updatedAt on every subsequent refresh, drifting the frozen time
  // exactly the way this field exists to prevent.
  if (task.dagTerminatedAt !== undefined) return task
  // Backfill from updatedAt, but MARKED provisional: updatedAt is mutable
  // metadata, so this is only the best available guess until (if ever) an
  // actual terminal event replays with its own timestamp - which
  // UPDATE_TASK_STATUS lets replace a provisional value, unlike a
  // non-provisional one.
  return { ...task, dagTerminatedAt: task.updatedAt, dagTerminatedAtProvisional: true }
}

type SessionTaskBinding =
  | { present: false }
  | { present: true; valid: false }
  | { present: true; valid: true; taskId: number }

const hasOwn = (
  record: object,
  key: string,
): boolean => Object.prototype.hasOwnProperty.call(record, key)

const extractSessionTaskBinding = (
  message: WebSocketMessage,
): SessionTaskBinding => {
  const root = asMessageRecord(message)
  const data = asMessageRecord(root.data)
  const nestedData = asMessageRecord(data.data)
  const task = asMessageRecord(root.task)
  const dataTask = asMessageRecord(data.task)
  const nestedTask = asMessageRecord(nestedData.task)
  const candidates: unknown[] = []

  const collect = (record: Record<string, unknown>, key: string) => {
    if (hasOwn(record, key) && record[key] !== undefined) {
      candidates.push(record[key])
    }
  }
  collect(root, "task_id")
  collect(task, "id")
  collect(data, "task_id")
  collect(dataTask, "id")
  collect(nestedData, "task_id")
  collect(nestedTask, "id")

  if (candidates.length === 0) return { present: false }
  const parsed = candidates.map(parseInteger)
  if (parsed.some(taskId => taskId === undefined || taskId <= 0)) {
    return { present: true, valid: false }
  }
  const taskIds = new Set(parsed as number[])
  if (taskIds.size !== 1) return { present: true, valid: false }
  return { present: true, valid: true, taskId: parsed[0] as number }
}

const getSessionTaskInfoData = (
  message: WebSocketMessage,
): Record<string, unknown> | null => {
  if (message.type !== "trace_event") return null
  const data = asMessageRecord(message.data)
  const eventType = message.event_type ?? data.event_type
  if (eventType !== "task_info") return null
  const nestedData = asMessageRecord(data.data)
  return Object.keys(nestedData).length > 0 ? nestedData : data
}

// The backend's DAG step status contract, shared verbatim by every UI model
// that projects a step (StepExecution here, progress-panel.tsx's
// ProgressStepView, center-panel.tsx's DAGNode.data) - previously each
// redeclared the same seven-value union independently, so a future backend
// status could be accepted by one and silently fall through to an "unknown"
// rendering in another. Import this instead of redeclaring the union.
//
// "interrupted" and "clarification_invalidated" are both non-terminal (a
// step in either state transitions back to "running" once its blocking
// condition clears - see dag.py's _ready_steps/_invalidate_batch_siblings)
// - they must render and count distinctly from "pending" (never started)
// and from the terminal statuses. "skipped" has no current backend producer
// (dag_step_skipped is never emitted) but is kept for the branch-derivation
// path that can still locally construct it.
export type StepStatus =
  | "pending"
  | "running"
  | "completed"
  | "failed"
  | "skipped"
  | "interrupted"
  | "clarification_invalidated"

interface StepExecution {
  id: string
  name: string
  description: string
  status: StepStatus
  tool_names?: string[]
  dependencies: string[]
  started_at?: string | number
  completed_at?: string | number
  result_data?: unknown
  step_data?: unknown
  file_outputs?: string[]
  conditional_branches?: Record<string, string>
  required_branch?: string | null
  is_conditional?: boolean
}

interface TraceEvent {
  event_id: string
  event_type: string
  step_id?: string
  timestamp: string
  data: unknown
}

const normalizeStepStatus = (status: unknown): StepExecution["status"] => {
  return (
    status === "running"
    || status === "completed"
    || status === "failed"
    || status === "skipped"
    || status === "interrupted"
    || status === "clarification_invalidated"
  )
    ? status
    : "pending"
}

const getString = (value: unknown, fallback = ""): string => typeof value === "string" ? value : fallback
const getStringArray = (value: unknown): string[] => Array.isArray(value) ? value.map(item => String(item)) : []

const taskFromTaskInfoData = (
  taskData: Record<string, unknown>,
  taskId: number,
): Task => {
  const runId = taskData.run_id as string | null | undefined
  const stateVersion = parseInteger(taskData.state_version)
  const taskFence = typeof runId === "string" && stateVersion !== undefined
    ? { runId, stateVersion }
    : undefined
  const autoRecoveryValue = taskData.auto_recovery
  const autoRecoveryView = asMessageRecord(autoRecoveryValue)
  const recoveryRunId = autoRecoveryView.run_id
  const recoveryStateVersion = parseInteger(autoRecoveryView.state_version)
  const recoveryFenceMatchesTask = (
    taskFence !== undefined
    && recoveryRunId === runId
    && recoveryStateVersion === stateVersion
  )
  const autoRecovery = recoveryFenceMatchesTask
    ? normalizeAutoRecovery(autoRecoveryValue, runId, stateVersion)
    : undefined
  const hasAutoResumeField = recoveryFenceMatchesTask
    && hasOwn(autoRecoveryView, "auto_resume")
  const autoResume = hasAutoResumeField
    ? parseAutoResumeAtFence(
      autoRecoveryView.auto_resume,
      recoveryRunId,
      recoveryStateVersion,
    )
    : undefined
  const autoResumeEndedAt = hasAutoResumeField
    && autoRecoveryView.auto_resume === null
    ? taskFence
    : undefined

  return {
    id: String(taskId),
    title: taskData.title as string,
    description: taskData.description as string,
    status: normalizeTaskStatus(taskData.status) || "pending",
    completionOutcome: normalizeCompletionOutcome(taskData.completion_outcome),
    ...(taskData.conversation_storage_version !== undefined
      ? { conversationStorageVersion: taskData.conversation_storage_version as number }
      : {}),
    createdAt: taskData.created_at as string | number,
    updatedAt: taskData.updated_at as string | number,
    modelId: taskData.model_id as string | undefined,
    smallFastModelId: taskData.small_fast_model_id as string | undefined,
    visualModelId: taskData.visual_model_id as string | undefined,
    compactModelId: taskData.compact_model_id as string | undefined,
    modelName: taskData.model_name as string | undefined,
    smallFastModelName: taskData.small_fast_model_name as string | undefined,
    visualModelName: taskData.visual_model_name as string | undefined,
    compactModelName: taskData.compact_model_name as string | undefined,
    executionMode: taskData.execution_mode as Task["executionMode"],
    isDag: taskData.is_dag as boolean | undefined,
    agentId: taskData.agent_id as number | undefined,
    agentName: taskData.agent_name as string | undefined,
    agentLogoUrl: taskData.agent_logo_url as string | undefined,
    runtimeExtensionBindings: getStringArray(taskData.runtime_extension_bindings),
    waitingQuestion: taskData.waiting_question as string | undefined,
    waitingInteractions: normalizeInteractions(taskData.waiting_interactions),
    runId,
    stateVersion,
    controlState: taskData.control_state as TaskControlState | undefined,
    // A whole ``null`` says nothing about recovery at this fence (failed
    // read, no row, fence mismatch, or not paused), so keep what is held
    // until the fence changes. A non-null view is usable only at that fence.
    ...(autoRecovery && recoveryFenceMatchesTask ? { autoRecovery } : {}),
    ...(hasAutoResumeField && (autoRecoveryView.auto_resume === null || autoResume)
      ? { autoResume }
      : {}),
    ...(autoResumeEndedAt ? { autoResumeEndedAt } : {}),
  }
}

const getWebSocketErrorCodeField = (message: WebSocketMessage): {
  present: boolean
  value: unknown
} => {
  const root = message as unknown as Record<string, unknown>
  const data = isJsonRecord(message.data) ? message.data : null
  if (data && Object.prototype.hasOwnProperty.call(data, "error_code")) {
    return { present: true, value: data.error_code }
  }
  if (Object.prototype.hasOwnProperty.call(root, "error_code")) {
    return { present: true, value: root.error_code }
  }
  return { present: false, value: undefined }
}

const getWebSocketErrorMessage = (
  message: WebSocketMessage,
  trustLegacyErrorProse: boolean,
): string => {
  const root = message as unknown as Record<string, unknown>
  const data = isJsonRecord(message.data) ? message.data : null
  if (getWebSocketErrorCodeField(message).present) return "Unknown error"
  if (!trustLegacyErrorProse) return "Unknown error"
  return getString(data?.message) || getString(data?.error) || getString(root.message) || getString(root.error) || "Unknown error"
}

const getWebSocketErrorCode = (message: WebSocketMessage) => {
  const errorCode = getWebSocketErrorCodeField(message)
  return errorCode.present ? readClientErrorCode(errorCode.value) : null
}

// The frame deliberately carries nothing connector-specific beyond the code:
// its audience includes anonymous widget and share-link visitors. Which
// connector, which key, and each key's declared type all come from the
// per-task requirements endpoint, which selects on
// `Task.id == task_id AND Task.user_id == current_user.id`.
const getTaskErrorProjection = (
  message: WebSocketMessage,
): TaskErrorProjection | null => {
  const root = message as unknown as Record<string, unknown>
  const data = isJsonRecord(message.data) ? message.data : null
  const code = getString(data?.code) || getString(root.code)
  return code ? { code } : null
}

const getWebSocketTaskStatus = (message: WebSocketMessage): Task["status"] | null => {
  const root = message as unknown as Record<string, unknown>
  const data = isJsonRecord(message.data) ? message.data : null
  const rootTask = isJsonRecord(root.task) ? root.task : null
  const dataTask = isJsonRecord(data?.task) ? data.task : null
  return normalizeTaskStatus(dataTask?.status) || normalizeTaskStatus(rootTask?.status) || normalizeTaskStatus(data?.status) || normalizeTaskStatus(root.status) || null
}

const shouldStopProcessingForTaskStatus = (status: unknown): boolean =>
  isStoppedTaskStatus(status)

export type ErrorFrameDisplay = {
  /** Terminal (`task_error`) or a rejection on the mixed root `error` channel. */
  isTerminal: boolean
  /** Status carried by the frame, or null when it carries none. */
  taskStatus: Task["status"] | null
  stopsProcessing: boolean
  /** First argument to the dedup check: the server sentence, or the constant
   *  that stands in for it on a transport that marks legacy prose untrusted. */
  dedupText: string
  /** Third argument to the dedup check. Undefined means "no identity, key on
   *  the text alone". */
  occurrenceIdentity: string | undefined
  bubbleContent: string
  isResult: boolean
  /** The frame's own code, once it has cleared the client error table --
   *  null on a non-terminal frame, a terminal frame with no code, or a code
   *  the table does not list (e.g. auto_model_unavailable). Reuses the same
   *  `projectedCode` this function already derives for the bubble; a caller
   *  must not call getTaskErrorProjection a second time to get it. */
  terminalErrorCode: ClientErrorCode | null
  /** The frame is the terminal frame of the task the visitor asked to stop. */
  endsStopIntent: boolean
  /** The frame renders as the visitor's stopped turn rather than a failure. */
  isVisitorStoppedTurn: boolean
}

// One place where a frame on the error/task_error handler becomes the eight
// values the handler needs: the bubble's wording, the dedup text, the dedup
// identity, the result flag, the task status to dispatch, the code that
// opens the connector-runtime dialog, whether the frame ends the stop intent,
// and whether it renders as the stopped turn. Each of those needs a different subset
// of "is this terminal / is legacy prose trusted / did a code survive / is
// there a state version", and deriving each subset at its own use site is
// what let five separate defects land in this handler.
// Pure on purpose: no dispatch, no refs, nothing
// outside its arguments, so every cell of that matrix is unit-testable
// without rendering the provider -- the same shape extractTaskControlEnvelope
// above already uses.
export const projectErrorFrameForDisplay = (
  message: WebSocketMessage,
  options: {
    trustLegacyErrorProse: boolean
    translate: Translate
    controlEnvelope: TaskControlEnvelope
    /** The task the visitor asked to stop, from SessionStop.intentTaskId. */
    stopIntentTaskId: number | null
  },
): ErrorFrameDisplay => {
  const { trustLegacyErrorProse, translate, controlEnvelope, stopIntentTaskId } = options
  const websocketErrorCode = getWebSocketErrorCode(message)
  const dedupText = websocketErrorCode
    ? translate(clientErrorTranslationKey(websocketErrorCode))
    : getWebSocketErrorMessage(message, trustLegacyErrorProse)
  const taskStatus = getWebSocketTaskStatus(message)
  // Only task_error is terminal. Every frame of that type is emitted after
  // the row has been committed FAILED -- task_orchestrator.py's settled
  // branch, and websocket.py's legacy helper, which settles under
  // only_if_running=True and does not broadcast when that update matches
  // no row -- and task_error is also the only frame that carries the
  // structured code. The root "error" type is a mixed
  // channel: rejected chat messages, rejected pause and rejected resume
  // all arrive on it while the viewed task is still RUNNING or
  // WAITING_FOR_USER, and a rejection is not this turn's answer.
  const isTerminal = message.type === "task_error"
  const isInputReviewNotice = !isTerminal && isInputReviewErrorCode(websocketErrorCode)
  const projection = isTerminal ? getTaskErrorProjection(message) : null
  // The frame's own code decides the wording, and one code has one sentence
  // for every audience. This is the same table the root error channel already
  // uses for its error_code field, extended with the connector-runtime codes
  // and the external-cancel interruption code that reach this frame -- not a
  // second vocabulary beside it. It also fixes
  // what the relayed sentence could not: on a transport that marks legacy
  // prose untrusted, getWebSocketErrorMessage returns a constant by design
  // (#1938: never render server free text there), so before this the curated
  // sentence existed for three codes and every other code read "Unknown
  // error". Nothing here relays server prose; the wording is the client's own,
  // selected by code. A code the table does not list keeps the generic
  // prefixed wording.
  const projectedCode = projection ? readClientErrorCode(projection.code) : null
  const codedBubble = projectedCode
    ? translate(clientErrorTranslationKey(projectedCode))
    : isInputReviewNotice ? dedupText : null
  // The dedup identity has to name WHICH occurrence this frame reports, not
  // which class of failure it belongs to. broadcast_to_task stamps every frame
  // of this type with the row's (run_id, state_version) pair before it goes
  // out -- task_error is in websocket.py's _VERSIONED_TASK_EVENT_TYPES -- and
  // state_version is bumped by every control transition that actually changes
  // (status, control_state). So one settlement broadcast twice carries one
  // version and still collapses, while two failed turns are at least two
  // versions apart (the retry takes the lease FAILED -> RUNNING, then settles
  // RUNNING -> FAILED) and both are shown. Keying on the failure's class
  // instead -- the code, the reason, or the rendered sentence -- cannot tell
  // those two apart, and on this handler the collapsed frame is the turn's
  // result. The identity is withheld when the frame carries no version (the
  // row was already gone when it was broadcast, so no state tuple was
  // attached), which falls back to keying on the text alone:
  // canAcceptTaskControlVersion drops such a frame once any versioned event
  // has been seen for the task, and when none has, two of them key on the
  // same text and the second still collapses -- the behaviour that predates
  // this change. Withholding the identity is the honest answer there;
  // attaching a state tuple needs the row, and a settled FAILED task has one.
  const turnId = (message.data as { turn_id?: unknown } | undefined)?.turn_id
  const occurrenceIdentity =
    isInputReviewNotice && typeof turnId === "string" && turnId
      ? `input-review:${turnId}`
      : isTerminal && controlEnvelope.stateVersion !== undefined
      ? `${controlEnvelope.runId ?? ""}:${controlEnvelope.stateVersion}`
      : undefined
  // A stop intent ends with this task's TERMINAL frame only. isTerminal is
  // the discriminator: the root "error" type is a mixed channel that also
  // carries rejected chat messages and rejected pause/resume while the task
  // is still RUNNING, and a rejection is neither this turn's result nor the
  // answer to a stop. Reading a rejection as the stopped turn would both
  // render a live turn as finished and retire the intent before the real
  // terminal frame arrives, leaving that frame to render as a plain failure.
  const endsStopIntent =
    isTerminal && isFrameForStopIntent(stopIntentTaskId, controlEnvelope.taskId)
  return {
    isTerminal,
    taskStatus,
    stopsProcessing: shouldStopProcessingForTaskStatus(taskStatus),
    dedupText,
    occurrenceIdentity,
    bubbleContent:
      codedBubble
      ?? `${translate('agent.logs.event.messages.errorPrefix')} ${dedupText}`,
    // A terminal failure IS this turn's result: without the flag the
    // conversation panel (which renders only user / isResult / system-notice
    // messages) filters the bubble out and falls back to a virtual "unknown
    // error" placeholder until reload. A non-terminal rejection is not, and
    // flagging it would close the live progress indicator and the
    // waiting-answer form of a turn that is still running, and drain this
    // turn's accumulated trace events into the rejection bubble (see the
    // ADD_MESSAGE reducer case's isResult branch, which merges
    // state.traceEvents into the message and clears it).
    isResult: isTerminal,
    terminalErrorCode: projectedCode,
    endsStopIntent,
    // Only a turn the server itself says was interrupted renders as the
    // stopped turn. Any other terminal failure -- a connector-runtime code
    // that raced the stop, or a codeless failure after the stop was lost or
    // timed out -- is a real failure and keeps the red bubble and its own
    // wording, though it still ends the intent.
    isVisitorStoppedTurn:
      endsStopIntent && projectedCode === "external_turn_interrupted",
  }
}

const stepsFromPlanData = (planData: unknown, existingSteps: StepExecution[]): StepExecution[] | null => {
  const planRecord = planData && typeof planData === "object" ? planData as Record<string, unknown> : null
  const planSteps = Array.isArray(planRecord?.steps) ? planRecord.steps : null
  if (!planSteps) {
    return null
  }

  const existingStepsMap = new Map<string, StepExecution>()
  existingSteps.forEach(step => existingStepsMap.set(step.id, step))

  return planSteps.map((rawStep: unknown) => {
    const step = rawStep && typeof rawStep === "object" ? rawStep as Record<string, unknown> : {}
    const id = String(step.id)
    const existingStep = existingStepsMap.get(id)
    const task = getString(step.task)
    const name = getString(step.name, task || id)
    return {
      id,
      name,
      description: getString(step.description, task),
      status: existingStep?.status || normalizeStepStatus(step.status),
      tool_names: step.tool_name ? [String(step.tool_name)] : getStringArray(step.tool_names),
      dependencies: getStringArray(step.dependencies),
      started_at: existingStep?.started_at || getString(step.started_at),
      completed_at: existingStep?.completed_at || getString(step.completed_at),
      result_data: step.result_data ?? step.result,
      step_data: step.step_data,
      file_outputs: getStringArray(step.file_outputs),
      conditional_branches: step.conditional_branches && typeof step.conditional_branches === "object" ? step.conditional_branches as Record<string, string> : {},
      required_branch: typeof step.required_branch === "string" ? step.required_branch : null,
      is_conditional: step.is_conditional === true,
    }
  })
}

// "replanning" and "completion_assessment" are real, live phase values the
// backend emits via on_dag_execution (dag.py) - the type previously omitted
// them, silently treating a normal mid-run replan or completion check as an
// unmodeled state for any consumer that read `.phase` directly.
// "completed"/"failed" are never sent by that backend broadcast (terminal
// state arrives via a separate dag_execute_end/checkpoint flow) but ARE
// constructed locally by handleMessage's own dag_execute_end/agent_error
// handlers below, so they remain valid runtime values of this field.
export type DAGExecutionPhase = "planning" | "replanning" | "executing" | "completion_assessment" | "completed" | "failed"

const DAG_EXECUTION_PHASES: ReadonlySet<string> = new Set<DAGExecutionPhase>([
  "planning", "replanning", "executing", "completion_assessment", "completed", "failed",
])

export interface DAGExecution {
  phase: DAGExecutionPhase
  current_plan: Record<string, unknown>
  created_at: string | number
  updated_at: string | number
  // The backend's existing per-turn identity (runtime.py's _dag_turn_id,
  // read off the current user message's own turn_id - not a new concept,
  // and NOT the same field as the top-level WebSocketMessage.run_id/
  // Task.runId lease identity used elsewhere in this file) - undefined for
  // older backends/patterns that don't set it, or for a dagExecution
  // constructed locally rather than from a raw wire payload (dag_execute_end/
  // agent_error's local phase updates below, which spread the EXISTING
  // dagExecution and so already carry whatever turn_id it had). Lets the
  // dag_execution handlers tell "still this same run" apart from "a new run
  // started" instead of assuming every event belongs to whatever run is
  // already in state.
  turn_id?: string
}

// The backend's on_dag_execution broadcast never actually includes
// current_plan (only counts/step lists depending on phase) despite the
// frontend type declaring it required, and its phase is a raw string with no
// guarantee it's one of DAG_EXECUTION_PHASES (a future backend phase addition
// would otherwise flow through unchecked). Normalizes a raw wire payload
// before it's ever cast to DAGExecution, rather than trusting `as
// DAGExecution` to paper over the mismatch.
//
// Returns null for a payload whose phase is absent, non-string, or unknown -
// callers must DROP that update rather than dispatch it. An earlier version
// defaulted unknown phases to "executing", which synthesized an active DAG
// run out of malformed data (an empty `{}` payload on the bare legacy
// message type was enough to conjure a blank in-progress Progress panel and
// auto-open it); keeping the previous state untouched loses at most one
// unrecognized update, while fabricating "executing" invents a whole run. A
// deliberate future backend phase addition should extend
// DAG_EXECUTION_PHASES and its consumers, not lean on a silent default.
const normalizeDagExecutionPayload = (raw: Record<string, unknown>): DAGExecution | null => {
  const rawPhase = raw.phase
  if (typeof rawPhase !== "string" || !DAG_EXECUTION_PHASES.has(rawPhase)) return null
  const phase = rawPhase as DAGExecutionPhase
  const currentPlan =
    raw.current_plan && typeof raw.current_plan === "object" && !Array.isArray(raw.current_plan)
      ? raw.current_plan as Record<string, unknown>
      : {}
  return {
    ...raw,
    phase,
    current_plan: currentPlan,
  } as DAGExecution
}

export interface AppState {
  streamRecoveryTaskId?: number | null
  messages: Message[]
  // Ids of the user messages that opened a turn the visitor stopped. Kept
  // here rather than on a bubble because a terminal frame that names a
  // message_id adds no bubble. The conversation panel reads it to draw that
  // turn's process as stopped. Live only: a reload does not rebuild it.
  stoppedTurnAnchorIds: string[]
  currentTask: Task | null
  taskRuntimeExtensions: TaskRuntimeExtensions
  dagExecution: DAGExecution | null
  steps: StepExecution[]
  traceEvents: TraceEvent[]
  selectedStepId: string | null
  isProcessing: boolean
  taskId: number | null
  filePreview: {
    isOpen: boolean
    fileId: string
    fileName: string
    content: string
    mimeType?: string
    isLoading: boolean
    error: string | null
    // Support switching between multiple file previews
    availableFiles: Array<{ fileId: string; fileName: string }>
    currentIndex: number
    viewMode: 'preview' | 'code'
  }
  isReplaying: boolean
  replaySpeed: number
  replayProgress: number
  replayEvents: TraceEvent[]
  replayTaskId: number | null
  replayScheduler: ReplayScheduler | null
  replayEventCache: WebSocketMessage[]
  planMemoryInfo: {
    memoriesFound: number
    memoriesUsed: number
    memoryCategory: string
    enhancedGoal?: string
    memories?: Array<{
      content: string
      category?: string
    }>
  } | null
  lastTaskUpdate?: number
  isHistoryLoading: boolean
  // Current context-window usage from the latest LLM call, for the usage gauge.
  contextUsage: { tokens: number; threshold: number } | null
  sessionConversation: SessionConversationState
}

type AppAction =
  | { type: "SET_STREAM_RECOVERY"; payload: number | null }
  | { type: "RECONCILE_STREAM_OUTPUT"; payload: { runId: string; output: string; timestamp: string; interrupted: boolean } }
  | { type: "SESSION_CONVERSATION"; payload: SessionConversationAction }
  | { type: "SET_TASK_ID"; payload: number | null }
  | { type: "ADOPT_SESSION_TASK"; payload: { taskId: number; task: Task } }
  | { type: "RESET_SESSION_CONVERSATION" }
  | { type: "MARK_TURN_STOPPED"; payload: { anchorMessageId: string } }
  | { type: "ADD_MESSAGE"; payload: Message }
  | { type: "UPSERT_STREAMING_FINAL_ANSWER"; payload: { messageId: string; executionSequence?: number; delta?: string; content?: string; status?: Message["status"]; timestamp: string } }
  | { type: "SET_CURRENT_TASK"; payload: Task | null }
  | { type: "SET_TASK_RUNTIME_EXTENSIONS"; payload: { taskId: number; extensions: TaskRuntimeExtensions } }
  | { type: "UPDATE_TASK_STATUS"; payload: { status: Task["status"]; completionOutcome?: TaskCompletionOutcome; waitingQuestion?: string; waitingInteractions?: Interaction[]; waitingRequestId?: string; runId?: string | null; stateVersion?: number; controlState?: TaskControlState; autoRecovery?: TaskAutoRecovery; updatedAt?: string } }
  | { type: "APPLY_AUTO_RESUME_NOTICE"; payload: { taskId: number; reason?: string; notice: TaskAutoResume; knownVersion?: number } }
  | { type: "RECONCILE_AUTO_RESUME_CANCEL"; payload: AutoResumeCancelSnapshot }
  | { type: "TRIGGER_TASK_UPDATE" }
  | { type: "SET_DAG_EXECUTION"; payload: DAGExecution | null }
  | { type: "RESET_DAG_STATE" }
  | { type: "SET_CONTEXT_USAGE"; payload: { tokens: number; threshold: number } | null }
  | { type: "ADD_STEP"; payload: StepExecution }
  | { type: "UPDATE_STEP"; payload: { stepId: string; updates: Partial<StepExecution> } }
  | { type: "SET_STEPS"; payload: StepExecution[] }
  | { type: "ADD_TRACE_EVENT"; payload: TraceEvent }
  | { type: "SET_TRACE_EVENTS"; payload: TraceEvent[] }
  | { type: "SELECT_STEP"; payload: string | null }
  | { type: "SET_PROCESSING"; payload: boolean }
  | {
    type: "CLEAR_MESSAGES";
    payload?: {
      preserveUserMessages?: boolean;
      preserveStreamingFinalAnswers?: boolean;
    };
  }
  | { type: "RESET_STATE" }
  | { type: "OPEN_FILE_PREVIEW"; payload: { fileId: string; fileName: string; files?: Array<{ fileId: string; fileName: string }>; index?: number } }
  | { type: "CLOSE_FILE_PREVIEW" }
  | { type: "SWITCH_FILE_PREVIEW"; payload: { fileId: string; fileName: string; index: number } }
  | { type: "SET_FILE_PREVIEW_CONTENT"; payload: { content: string; mimeType?: string; error: string | null } }
  | { type: "SET_FILE_PREVIEW_LOADING"; payload: boolean }
  | { type: "SET_FILE_PREVIEW_MODE"; payload: 'preview' | 'code' }
  | { type: "START_REPLAY"; payload: { taskId: number; events: TraceEvent[] } }
  | { type: "STOP_REPLAY" }
  | { type: "SET_PLAN_MEMORY_INFO"; payload: AppState["planMemoryInfo"] }
  | { type: "SET_REPLAY_TASK_ID"; payload: number | null }
  | { type: "SET_REPLAY_PLAYING"; payload: boolean }
  | { type: "SET_REPLAY_SPEED"; payload: number }
  | { type: "SET_REPLAY_PROGRESS"; payload: number }
  | { type: "SET_REPLAY_EVENTS"; payload: TraceEvent[] }
  | { type: "SET_REPLAY_SCHEDULER"; payload: ReplayScheduler | null }
  | { type: "ADD_TO_REPLAY_CACHE"; payload: WebSocketMessage }
  | { type: "CLEAR_REPLAY_CACHE" }
  | { type: "SET_HISTORY_LOADING"; payload: boolean }
  | { type: "SYNC_PROCESSING_STATUS" }

export const createInitialState = (): AppState => ({
  messages: [],
  stoppedTurnAnchorIds: [],
  currentTask: null,
  taskRuntimeExtensions: {},
  dagExecution: null,
  steps: [],
  traceEvents: [],
  selectedStepId: null,
  isProcessing: false,
  taskId: null,
  filePreview: {
    isOpen: false,
    fileId: '',
    fileName: '',
    content: '',
    isLoading: false,
    error: null,
    availableFiles: [],
    currentIndex: 0,
    viewMode: 'preview',
  },
  isReplaying: false,
  replaySpeed: 1.0,
  replayProgress: 0, // 0-100
  replayEvents: [],
  replayTaskId: null,
  replayScheduler: null,
  replayEventCache: [],
  planMemoryInfo: null,
  lastTaskUpdate: Date.now(),
  isHistoryLoading: false,
  contextUsage: null,
  sessionConversation: { ...initialSessionConversationState },
})

function settlementTargetMessageIndex(
  messages: Message[],
  event: TraceEvent,
): number {
  const data = (event.data ?? {}) as Record<string, unknown>
  if (data.settlement_delivery !== true) return -1

  const invocationId = typeof data.invocation_id === "string" && data.invocation_id
    ? data.invocation_id
    : undefined
  const toolCallId = typeof data.tool_call_id === "string" && data.tool_call_id
    ? data.tool_call_id
    : undefined
  if (!invocationId && !toolCallId) return -1

  const owningIndexes: number[] = []
  for (let index = messages.length - 1; index >= 0; index--) {
    const ownsInvocation = (messages[index].traceEvents || []).some(candidate => {
      if (candidate?.event_type !== "tool_execution_start") return false
      const candidateData = (candidate.data ?? {}) as Record<string, unknown>
      return invocationId
        ? candidateData.invocation_id === invocationId
        : candidateData.tool_call_id === toolCallId
    })
    if (ownsInvocation) owningIndexes.push(index)
  }

  if (owningIndexes.length === 0) return -1
  if (invocationId || owningIndexes.length === 1) {
    return owningIndexes.length === 1 ? owningIndexes[0] : -1
  }

  // Historical traces have no invocation id. Disambiguate reused provider
  // ids by the original step when exactly one stored message matches it.
  const stepMatches = owningIndexes.filter(index =>
    (messages[index].traceEvents || []).some(candidate => {
      if (candidate?.event_type !== "tool_execution_start") return false
      const candidateData = (candidate.data ?? {}) as Record<string, unknown>
      return candidateData.tool_call_id === toolCallId && candidate.step_id === event.step_id
    }),
  )
  return stepMatches.length === 1 ? stepMatches[0] : -1
}

export function projectAppState(state: AppState, action: AppAction): AppState {
  console.log('🔍 Reducer called with action:', action.type, action)

  switch (action.type) {
    case "SESSION_CONVERSATION":
      return {
        ...state,
        sessionConversation: reduceSessionConversation(
          state.sessionConversation,
          action.payload,
        ),
      }
    case "SET_HISTORY_LOADING":
      return { ...state, isHistoryLoading: action.payload }

    case "SYNC_PROCESSING_STATUS":
      if (shouldStopProcessingForTaskStatus(state.currentTask?.status)) {
        return { ...state, isProcessing: false }
      }
      return state

    case "TRIGGER_TASK_UPDATE":
      return { ...state, lastTaskUpdate: Date.now() }

    case "SET_TASK_ID":
      console.log('🔄 Reducer SET_TASK_ID:', {
        currentTaskId: state.taskId,
        newTaskId: action.payload,
        payloadType: typeof action.payload
      })
      // Clear messages if task ID changes
      const taskChanged = state.taskId !== action.payload
      const messages = taskChanged ? [] : state.messages
      const stoppedTurnAnchorIds = taskChanged ? [] : state.stoppedTurnAnchorIds
      const contextUsage = taskChanged ? null : state.contextUsage
      const taskRuntimeExtensions = taskChanged ? {} : state.taskRuntimeExtensions
      // Also clear the previous task's DAG plan/phase here - otherwise
      // switching tasks via the sidebar (no page reload) leaves the Progress
      // panel showing the OLD task's steps and elapsed time until the new
      // task's own dag_execution history replay arrives.
      const dagExecution = taskChanged ? null : state.dagExecution
      const steps = taskChanged ? [] : state.steps
      const newState = {
        ...state,
        taskId: action.payload,
        messages,
        stoppedTurnAnchorIds,
        contextUsage,
        taskRuntimeExtensions,
        dagExecution,
        steps,
      }
      console.log('🔄 Reducer returning new state:', newState)
      return newState

    case "ADOPT_SESSION_TASK": {
      // A session can adopt a task that's already terminal (e.g. a fast
      // single-call turn that finishes before the adoption handshake
      // completes) - route through the same dagTerminatedAt rules
      // SET_CURRENT_TASK applies, or the Progress panel's elapsed clock would
      // never freeze for it (isDagFinished true, progressEndedAt undefined).
      const adoptedTask = state.currentTask?.id === action.payload.task.id
        ? mergeTaskRecoverySnapshot(state.currentTask, action.payload.task)
        : action.payload.task
      return {
        ...state,
        taskId: action.payload.taskId,
        currentTask: clearStaleAutoRecovery(withDagTerminatedAt(adoptedTask)),
        taskRuntimeExtensions: {},
        // The server re-sends task_info for the same task at the start of
        // every turn, so adopting the task already bound must keep the record
        // of the turns the visitor stopped; only a different task drops it.
        stoppedTurnAnchorIds:
          state.taskId === action.payload.taskId ? state.stoppedTurnAnchorIds : [],
      }
    }

    case "MARK_TURN_STOPPED":
      return state.stoppedTurnAnchorIds.includes(action.payload.anchorMessageId)
        ? state
        : {
            ...state,
            stoppedTurnAnchorIds: [
              ...state.stoppedTurnAnchorIds,
              action.payload.anchorMessageId,
            ],
          }

    case "RESET_SESSION_CONVERSATION":
      return {
        ...createInitialState(),
        lastTaskUpdate: Date.now(),
        sessionConversation: state.sessionConversation,
      }

    case "ADD_MESSAGE": {
      const newMessage = action.payload
      let messageToAdd = newMessage
      let newTraceEvents = state.traceEvents

      if (newMessage.role === "assistant" && newMessage.isResult) {
        messageToAdd = {
          ...newMessage,
          traceEvents: mergeTraceEventsById(newMessage.traceEvents, state.traceEvents)
        }
        newTraceEvents = []
      }

      if (newMessage.role === "assistant" && newMessage.isResult) {
        const replaceMessageAt = (targetIndex: number) => {
          const existingSequence = state.messages[targetIndex].executionSequence
          if (existingSequence !== undefined && newMessage.executionSequence !== undefined
            && newMessage.executionSequence <= existingSequence) return state
          const updatedMessages = state.messages.map((message, index) =>
            index === targetIndex
              ? {
                ...message,
                ...messageToAdd,
                id: message.id,
                status: newMessage.status || "completed",
                traceEvents: mergeTraceEventsById(message.traceEvents, messageToAdd.traceEvents),
              }
              : message
          )
          return { ...state, messages: updatedMessages, traceEvents: newTraceEvents }
        }
        if (newMessage.streamMessageId || newMessage.executionSequence !== undefined) {
          const targetId = newMessage.streamMessageId ?? newMessage.id
          const deliveredIndex = state.messages.findIndex(
            message =>
              message.role === "assistant" && message.id === targetId &&
              (!newMessage.streamMessageId || isStreamingFinalAnswerMessage(message))
          )
          if (deliveredIndex >= 0) {
            return replaceMessageAt(deliveredIndex)
          }
        }
      }

      // One assistant question can be delivered twice -- live, then replayed
      // from the transcript after a reconnect -- under one event identity but
      // with different text, because the replayed copy carries the rendered
      // interaction list. Identity decides, never text: #2250 is the record
      // of what text matching costs. The mounted bubble is kept rather than
      // replaced so an open clarification form is not remounted under the
      // visitor; the re-delivery only fills in what the bubble lacks. Content
      // is deliberately not among those fields: one event id is one question,
      // and the replayed copy differs only by the rendered interaction list
      // the form already draws.
      if (messageToAdd.role === "assistant" && isStableAssistantMessageId(messageToAdd.id)) {
        const deliveredIndex = state.messages.findIndex(
          message => message.role === "assistant" && message.id === messageToAdd.id,
        )
        if (deliveredIndex >= 0) {
          const updatedMessages = state.messages.map((message, index) =>
            index === deliveredIndex
              ? {
                ...message,
                interactions: message.interactions ?? messageToAdd.interactions,
                interactionRequestId:
                  message.interactionRequestId ?? messageToAdd.interactionRequestId,
                traceEvents: mergeTraceEventsById(
                  message.traceEvents,
                  messageToAdd.traceEvents,
                ),
              }
              : message
          )
          return { ...state, messages: updatedMessages, traceEvents: newTraceEvents }
        }
      }

      const optimisticUserMessageIndex = findOptimisticUserMessageIndex(
        state.messages,
        messageToAdd,
      )

      if (messageToAdd.role === "user") {
        const existingUserMessageIndex = state.messages.findIndex(
          message => message.role === "user" && message.id === messageToAdd.id,
        )
        if (existingUserMessageIndex >= 0) {
          const existingMessage = state.messages[existingUserMessageIndex]
          if (messageToAdd.isOptimistic && !existingMessage.isOptimistic) {
            return state
          }

          const updatedMessages = state.messages.map((message, index) =>
            index === existingUserMessageIndex
              ? {
                ...message,
                ...messageToAdd,
                isOptimistic: messageToAdd.isOptimistic ?? false,
              }
              : message
          )
          updatedMessages.sort((a, b) => {
            return normalizeTimestampMs(a.timestamp) - normalizeTimestampMs(b.timestamp)
          })
          return { ...state, messages: updatedMessages, traceEvents: newTraceEvents }
        }
      }

      if (optimisticUserMessageIndex >= 0) {
        const updatedMessages = state.messages.map((message, index) =>
          index === optimisticUserMessageIndex
            ? {
              ...message,
              ...messageToAdd,
              id: messageToAdd.id,
              isOptimistic: messageToAdd.isOptimistic ?? false,
            }
            : message
        )
        updatedMessages.sort((a, b) => {
          return normalizeTimestampMs(a.timestamp) - normalizeTimestampMs(b.timestamp)
        })
        return { ...state, messages: updatedMessages, traceEvents: newTraceEvents }
      }

      const updatedMessages = [...state.messages, messageToAdd]
      updatedMessages.sort((a, b) => {
        return normalizeTimestampMs(a.timestamp) - normalizeTimestampMs(b.timestamp)
      })
      return { ...state, messages: updatedMessages, traceEvents: newTraceEvents }
    }

    case "SET_STREAM_RECOVERY":
      return { ...state, streamRecoveryTaskId: action.payload }

    case "RECONCILE_STREAM_OUTPUT": {
      const { runId, output, timestamp, interrupted } = action.payload
      let resultIndex = -1
      for (let index = state.messages.length - 1; index >= 0; index--) {
        const message = state.messages[index]
        if (message.role === "user") break
        if (message.role === "assistant" && message.isResult) {
          resultIndex = index
          break
        }
      }
      const existing = state.messages[resultIndex]
      // Preserve richer live formatting/files when a complete result already
      // arrived. A partial stream, or a missed result, needs the durable text.
      if (existing?.status === "completed" && !interrupted) return state
      const restored: Message = {
        ...existing,
        id: existing?.id ?? `final_answer_recovered_${runId}`,
        role: "assistant",
        content: output,
        rawContent: output,
        timestamp: existing?.timestamp ?? timestamp,
        status: "completed",
        isResult: true,
      }
      const messages = [...state.messages]
      if (resultIndex >= 0) messages[resultIndex] = restored
      else messages.push(restored)
      return { ...state, messages, streamRecoveryTaskId: null }
    }

    case "UPSERT_STREAMING_FINAL_ANSWER": {
      const { messageId, delta, content, status, timestamp, executionSequence } = action.payload
      const existing = state.messages.find(message => message.id === messageId)
      if (existing?.executionSequence !== undefined) {
        if (executionSequence !== undefined && executionSequence <= existing.executionSequence) {
          // Ownership can end without adding another stream fact. Refresh
          // that start's status, but never downgrade newer or terminal text.
          if (executionSequence === existing.executionSequence
            && status === "interrupted" && existing.status === "running") {
            return { ...state, messages: state.messages.map(message =>
              message.id === messageId ? { ...message, status: "interrupted" } : message
            ) }
          }
          return state
        }
        // Deltas are ephemeral; a durable terminal frame owns the full text.
        if (executionSequence === undefined && existing.status !== "running") return state
      }
      if (!existing) {
        const message: Message = {
          executionSequence,
          id: messageId,
          role: "assistant",
          content: content || delta || "",
          rawContent: content || delta || "",
          timestamp,
          status: status || "running",
          isResult: true,
          traceEvents: [...state.traceEvents],
        }
        return { ...state, messages: [...state.messages, message], traceEvents: [] }
      }
      const updatedMessages = state.messages.map(message => {
        if (message.id !== messageId) {
          return message
        }
        const currentContent =
          typeof message.content === "string" ? message.content : ""
        const nextContent = content !== undefined ? content : currentContent + (delta || "")
        return {
          ...message,
          content: nextContent,
          rawContent: nextContent,
          executionSequence: executionSequence ?? message.executionSequence,
          status: status || message.status || "running",
        }
      })
      return { ...state, messages: updatedMessages }
    }

    case "SET_CURRENT_TASK": {
      const incomingTask = action.payload
        ? {
          ...action.payload,
          status:
            normalizeTaskStatus(action.payload.status) ||
            (state.currentTask?.id === action.payload.id
              ? state.currentTask.status
              : "pending"),
        }
        : null

      const mergedTask = (state.currentTask && incomingTask && state.currentTask.id === incomingTask.id)
        ? mergeTaskSnapshot(state.currentTask, incomingTask)
        : incomingTask
      // A task can arrive here already terminal without ever passing through
      // UPDATE_TASK_STATUS (loading a finished task fresh - page load,
      // switching to it, history replay's own task_info), and a task_info
      // reporting this SAME task back to a non-terminal status (a rerun)
      // never passes through UPDATE_TASK_STATUS either - withDagTerminatedAt
      // backfills the former and clears the latter so a prior run's
      // dagTerminatedAt can't linger into this one.
      const currentTask = clearStaleAutoRecovery(withDagTerminatedAt(mergedTask && {
        ...mergedTask,
        completionOutcome: mergedTask.status === "completed" ? mergedTask.completionOutcome : undefined,
      }))

      return {
        ...state,
        currentTask,
        isProcessing: currentTask && shouldStopProcessingForTaskStatus(currentTask.status)
          ? false
          : state.isProcessing,
      }
    }

    case "SET_TASK_RUNTIME_EXTENSIONS":
      if (state.taskId !== action.payload.taskId) return state
      return {
        ...state,
        taskRuntimeExtensions: action.payload.extensions,
      }

    case "UPDATE_TASK_STATUS": {
      if (!state.currentTask) {
        return state
      }

      const nextStatus = normalizeTaskStatus(action.payload.status)
      if (!nextStatus) {
        return state
      }

      const isWaitingForUser = nextStatus === "waiting_for_user"
      // Set once, on the transition into a terminal status - and cleared
      // when the task starts running again, so a stale prior run's terminal
      // time doesn't linger into the next one. Deliberately NOT recomputed
      // from `updatedAt`: unlike this field, `updatedAt` keeps changing
      // after termination for reasons unrelated to this execution (see the
      // Task.dagTerminatedAt comment), so it can't double as the frozen end
      // time itself. An already-set AUTHORITATIVE (non-provisional) value is
      // preserved (first-write-wins): a second terminal event for the same
      // episode - a duplicate delivery, or an agent_error followed by the
      // formal task_completed broadcast - must not push the frozen elapsed
      // time forward. A PROVISIONAL value (withDagTerminatedAt's backfill
      // from mutable task metadata on a cold history load) is the one thing
      // a terminal event's own timestamp is allowed to replace - the event
      // knows when the run actually ended; the backfill only guessed.
      let dagTerminatedAt: Task["dagTerminatedAt"]
      let dagTerminatedAtProvisional: boolean | undefined
      if (isTerminalTaskStatus(nextStatus)) {
        const previous = state.currentTask.dagTerminatedAt
        const previousProvisional = state.currentTask.dagTerminatedAtProvisional === true
        if (previous !== undefined && !previousProvisional) {
          dagTerminatedAt = previous
        } else if (action.payload.updatedAt !== undefined) {
          dagTerminatedAt = action.payload.updatedAt
        } else if (previous !== undefined) {
          // Still provisional: a terminal event with no timestamp of its own
          // is no more authoritative than the backfill it would replace.
          dagTerminatedAt = previous
          dagTerminatedAtProvisional = true
        } else {
          dagTerminatedAt = new Date().toISOString()
        }
      }
      const replacesWaitingOccurrence = isWaitingForUser
        && action.payload.waitingRequestId !== undefined
        && action.payload.waitingRequestId !== state.currentTask.waitingRequestId
      const nextRunId = action.payload.runId ?? state.currentTask.runId
      const nextStateVersion = action.payload.stateVersion ?? state.currentTask.stateVersion
      const taskAtNextFence: Task = {
        ...state.currentTask,
        status: nextStatus,
        runId: nextRunId,
        stateVersion: nextStateVersion,
      }
      const incomingAutoRecovery = nextStatus === "paused"
        && action.payload.autoRecovery
        && typeof nextRunId === "string"
        && nextStateVersion !== undefined
        ? {
          ...action.payload.autoRecovery,
          runId: nextRunId,
          stateVersion: nextStateVersion,
        }
        : undefined
      return {
        ...state,
        isProcessing: shouldStopProcessingForTaskStatus(nextStatus)
          ? false
          : state.isProcessing,
        currentTask: {
          ...state.currentTask,
          status: nextStatus,
          completionOutcome: nextStatus === "completed"
            ? ("completionOutcome" in action.payload ? action.payload.completionOutcome : state.currentTask.completionOutcome)
            : undefined,
          // Prefer the originating event's own timestamp over the client's
          // current wall-clock time - during historical replay, every event
          // gets processed at "now", so stamping updatedAt with the reducer's
          // own clock would make a long-finished task's Progress panel freeze
          // its elapsed time against the moment it was REPLAYED, not the
          // moment it actually completed.
          updatedAt: action.payload.updatedAt ?? new Date().toISOString(),
          dagTerminatedAt,
          dagTerminatedAtProvisional,
          waitingQuestion: isWaitingForUser
            ? action.payload.waitingQuestion ?? (
              replacesWaitingOccurrence ? undefined : state.currentTask.waitingQuestion
            )
            : undefined,
          waitingInteractions: isWaitingForUser
            ? action.payload.waitingInteractions ?? (
              replacesWaitingOccurrence ? undefined : state.currentTask.waitingInteractions
            )
            : undefined,
          waitingRequestId: isWaitingForUser
            ? action.payload.waitingRequestId ?? (
              action.payload.waitingQuestion === undefined
              && action.payload.waitingInteractions === undefined
                ? state.currentTask.waitingRequestId
                : undefined
            )
            : undefined,
          runId: nextRunId,
          stateVersion: nextStateVersion,
          controlState: action.payload.controlState ?? state.currentTask.controlState,
          // A reason-less update can retain recovery state only at the same
          // fence. Inferred status changes at that fence do not erase it.
          autoRecovery: incomingAutoRecovery
            ?? atTaskFence(taskAtNextFence, state.currentTask.autoRecovery),
          autoResume: atTaskFence(taskAtNextFence, state.currentTask.autoResume),
          autoResumeEndedAt: atTaskFence(taskAtNextFence, state.currentTask.autoResumeEndedAt),
        },
      }
    }

    case "APPLY_AUTO_RESUME_NOTICE": {
      const { taskId, reason, notice, knownVersion } = action.payload
      const task = state.currentTask
      if (!task || task.id !== String(taskId)) return state
      // The task's own version, else the last one a versioned event set.
      const known = task.stateVersion ?? knownVersion
      if (
        task.autoResumeEndedAt?.runId === notice.runId
        && task.autoResumeEndedAt.stateVersion === notice.stateVersion
      ) return state
      if (known !== undefined && notice.stateVersion < known) return state
      if (known === undefined || notice.stateVersion === known) {
        // Nothing to order it against: only annotate a pause already shown,
        // never move a running or finished task. At the known version this
        // is the same fence and follows the same rule.
        if (task.status !== "paused" || (task.runId != null && task.runId !== notice.runId)) {
          return state
        }
        return {
          ...state,
          currentTask: {
            ...task,
            autoResume: newerAutoResume(task.autoResume, notice),
          },
        }
      }
      // A newer fence: the server rests the task paused there (a lease-expiry
      // pause announces nothing else), so apply that pause first.
      const paused = projectAppState(state, {
        type: "UPDATE_TASK_STATUS",
        payload: {
          status: "paused",
          runId: notice.runId,
          stateVersion: notice.stateVersion,
          controlState: "paused",
          autoRecovery: reason ? { reason } : undefined,
        },
      })
      return paused.currentTask
        ? { ...paused, isProcessing: false, currentTask: { ...paused.currentTask, autoResume: notice } }
        : paused
    }

    case "RECONCILE_AUTO_RESUME_CANCEL": {
      const snapshot = action.payload
      const task = state.currentTask
      if (!task || task.id !== String(snapshot.taskId)) return state
      if (task.stateVersion !== undefined && snapshot.stateVersion < task.stateVersion) return state
      if (
        task.stateVersion === snapshot.stateVersion
        && task.runId != null
        && task.runId !== snapshot.runId
      ) return state

      const recoveryView = asMessageRecord(snapshot.autoRecovery)
      const autoResume = parseAutoResumeAtFence(
        recoveryView.auto_resume,
        snapshot.runId,
        snapshot.stateVersion,
      )
      const recoveryExplicitlyEnded = hasOwn(recoveryView, "auto_resume")
        && recoveryView.auto_resume === null
      const outcomeEnded = (
        snapshot.outcome === "cancelled"
        || snapshot.outcome === "already_cancelled"
        || snapshot.outcome === "resume_in_progress"
      )
      const autoResumeEndedAt = !autoResume
        && (recoveryExplicitlyEnded || outcomeEnded)
        && typeof snapshot.runId === "string"
        ? { runId: snapshot.runId, stateVersion: snapshot.stateVersion }
        : undefined

      // The endpoint response is the authoritative view at this fence. Apply
      // it locally even if websocket delivery or a later status replay is
      // unavailable; the task-id guard makes an in-flight task switch safe.
      return projectAppState(state, {
        type: "SET_CURRENT_TASK",
        payload: {
          ...task,
          status: snapshot.status,
          runId: snapshot.runId,
          stateVersion: snapshot.stateVersion,
          controlState: snapshot.controlState,
          autoRecovery: normalizeAutoRecovery(
            snapshot.autoRecovery,
            snapshot.runId,
            snapshot.stateVersion,
          ),
          autoResume,
          autoResumeEndedAt,
        },
      })
    }

    case "SET_DAG_EXECUTION":
      return { ...state, dagExecution: action.payload }

    // Single action for the "clear dagExecution + steps together" couplet
    // needed at every site that isn't a task switch (task switches already
    // get this via SET_TASK_ID's own taskChanged branch) - same-task
    // reconnect and a successful new turn on the same task both need it, and
    // a single action keeps them from drifting out of sync with each other.
    case "RESET_DAG_STATE":
      return { ...state, dagExecution: null, steps: [] }

    case "SET_CONTEXT_USAGE":
      return { ...state, contextUsage: action.payload }

    case "ADD_STEP":
      const newStep = action.payload
      const existingStepIndex = state.steps.findIndex(s => s.id === newStep.id)
      if (existingStepIndex >= 0) {
        // Update existing step - merge data intelligently to preserve existing information
        const existingStep = state.steps[existingStepIndex]
        const shouldUpdate = newStep.name !== existingStep.name ||
          newStep.description !== existingStep.description ||
          !arraysEqual(newStep.tool_names || [], existingStep.tool_names || []) ||
          newStep.status !== existingStep.status

        if (shouldUpdate) {
          const mergedStep = {
            ...existingStep,
            ...newStep,
            // Preserve existing started_at if new one is not provided
            started_at: newStep.started_at || existingStep.started_at,
            // Preserve existing tool_names if new one is not provided
            tool_names: newStep.tool_names || existingStep.tool_names,
            // Preserve existing description if new one is not provided
            description: newStep.description || existingStep.description,
            // Preserve dependencies if new step doesn't have them
            dependencies: newStep.dependencies && newStep.dependencies.length > 0 ? newStep.dependencies : existingStep.dependencies || [],
            // Preserve conditional branch fields if new step doesn't have them
            conditional_branches: newStep.conditional_branches && Object.keys(newStep.conditional_branches).length > 0 ? newStep.conditional_branches : existingStep.conditional_branches || {},
            required_branch: newStep.required_branch ?? existingStep.required_branch ?? null,
            is_conditional: newStep.is_conditional ?? existingStep.is_conditional ?? false,
          }
          return {
            ...state,
            steps: state.steps.map((step, index) =>
              index === existingStepIndex ? mergedStep : step
            )
          }
        } else {
          return state // No update needed
        }
      } else {
        // Add new step
        return { ...state, steps: [...state.steps, action.payload] }
      }

    case "UPDATE_STEP":
      return {
        ...state,
        steps: state.steps.map(step =>
          step.id === action.payload.stepId
            ? { ...step, ...action.payload.updates }
            : step
        ),
      }

    case "SET_STEPS":
      return { ...state, steps: action.payload }

    case "ADD_TRACE_EVENT": {
      const settlementTarget = settlementTargetMessageIndex(state.messages, action.payload)
      if (settlementTarget >= 0) {
        return {
          ...state,
          messages: state.messages.map((message, index) =>
            index === settlementTarget
              ? {
                ...message,
                traceEvents: [...(message.traceEvents || []), action.payload],
              }
              : message,
          ),
        }
      }
      // A settlement with no unique owner must not use the ordinary late-
      // trace fallback below: the last assistant result may belong to a
      // different invocation (or a legacy call with a reused provider id).
      if ((action.payload.data as Record<string, unknown> | undefined)?.settlement_delivery === true) {
        return { ...state, traceEvents: [...state.traceEvents, action.payload] }
      }
      // If the last message is a result message from assistant, append the trace event to that message directly.
      // This ensures that events arriving after the result message (like react_task_end) are correctly displayed.
      const lastMsg = state.messages.length > 0 ? state.messages[state.messages.length - 1] : null
      if (lastMsg && lastMsg.role === "assistant" && lastMsg.isResult) {
        const updatedLastMsg = {
          ...lastMsg,
          traceEvents: [...(lastMsg.traceEvents || []), action.payload]
        }
        return {
          ...state,
          messages: [...state.messages.slice(0, -1), updatedLastMsg]
        }
      }
      return { ...state, traceEvents: [...state.traceEvents, action.payload] }
    }

    case "SET_TRACE_EVENTS":
      return { ...state, traceEvents: action.payload }

    case "SELECT_STEP":
      return { ...state, selectedStepId: action.payload }

    case "SET_PROCESSING":
      return { ...state, isProcessing: action.payload }

    case "CLEAR_MESSAGES":
      if (action.payload) {
        const {
          preserveUserMessages,
          preserveStreamingFinalAnswers,
        } = action.payload
        const messagesToKeep = state.messages.filter(message => {
          if (preserveUserMessages && message.role === "user") {
            return true
          }
          return (
            preserveStreamingFinalAnswers &&
            isStreamingFinalAnswerMessage(message)
          )
        })
        return { ...state, messages: messagesToKeep, stoppedTurnAnchorIds: [] }
      }
      return { ...state, messages: [], stoppedTurnAnchorIds: [] }

    case "RESET_STATE":
      return {
        ...createInitialState(),
        sessionConversation: state.sessionConversation,
      }

    case "OPEN_FILE_PREVIEW":
      // Support passing single file or multiple file list
      const files = action.payload.files || [{ fileId: action.payload.fileId, fileName: action.payload.fileName }]
      const currentIndex = action.payload.index || 0

      return {
        ...state,
        filePreview: {
          ...state.filePreview,
          isOpen: true,
          fileId: files[currentIndex]?.fileId || action.payload.fileId,
          fileName: files[currentIndex]?.fileName || action.payload.fileName,
          content: '',
          isLoading: true,
          error: null,
          availableFiles: files,
          currentIndex: currentIndex,
          viewMode: 'preview',
        }
      }

    case "CLOSE_FILE_PREVIEW":
      return {
        ...state,
        filePreview: {
          ...state.filePreview,
          isOpen: false,
          isLoading: false,
        }
      }

    case "SWITCH_FILE_PREVIEW":
      return {
        ...state,
        filePreview: {
          ...state.filePreview,
          fileId: action.payload.fileId,
          fileName: action.payload.fileName,
          content: '',
          isLoading: true,
          error: null,
          currentIndex: action.payload.index,
          viewMode: 'preview',
        }
      }

    case "SET_FILE_PREVIEW_MODE":
      return {
        ...state,
        filePreview: {
          ...state.filePreview,
          viewMode: action.payload,
        }
      }

    case "SET_FILE_PREVIEW_CONTENT":
      return {
        ...state,
        filePreview: {
          ...state.filePreview,
          content: action.payload.content,
          mimeType: action.payload.mimeType,
          error: action.payload.error,
          isLoading: false,
        }
      }

    case "SET_FILE_PREVIEW_LOADING":
      return {
        ...state,
        filePreview: {
          ...state.filePreview,
          isLoading: action.payload,
        }
      }

    case "START_REPLAY":
      return {
        ...state,
        isReplaying: true, // We start replaying immediately
        replayEvents: action.payload.events,
        replayTaskId: action.payload.taskId,
        replayProgress: 0,
        replaySpeed: state.replaySpeed,
        replayScheduler: null, // Will be initialized when actually starting playback
      }

    case "STOP_REPLAY":
      // Clean up scheduler if it exists
      if (state.replayScheduler) {
        state.replayScheduler.stop()
      }
      return {
        ...state,
        isReplaying: false,
        replayEvents: [],
        replayTaskId: null,
        replayProgress: 0,
        replayScheduler: null,
        replayEventCache: [], // Also clear the event cache
      }

    case "SET_REPLAY_TASK_ID":
      return {
        ...state,
        replayTaskId: action.payload,
      }

    case "SET_REPLAY_PLAYING":
      if (action.payload && state.replayScheduler) {
        // Start playing
        state.replayScheduler.play()
      } else if (!action.payload && state.replayScheduler) {
        // Pause playing
        state.replayScheduler.pause()
      }
      return {
        ...state,
        isReplaying: action.payload,
      }

    case "SET_REPLAY_SPEED":
      if (state.replayScheduler) {
        state.replayScheduler.setPlaybackSpeed(action.payload)
      }
      return {
        ...state,
        replaySpeed: action.payload,
      }

    case "SET_REPLAY_PROGRESS":
      return {
        ...state,
        replayProgress: action.payload,
      }

    case "SET_REPLAY_EVENTS":
      return {
        ...state,
        replayEvents: action.payload,
      }

    case "SET_REPLAY_SCHEDULER":
      return {
        ...state,
        replayScheduler: action.payload,
      }

    case "ADD_TO_REPLAY_CACHE":
      return {
        ...state,
        replayEventCache: [...state.replayEventCache, action.payload],
      }

    case "CLEAR_REPLAY_CACHE":
      return {
        ...state,
        replayEventCache: [],
      }

    case "SET_PLAN_MEMORY_INFO":
      return {
        ...state,
        planMemoryInfo: action.payload,
      }

    default:
      return state
  }
}

type AppStateCommit = { state: AppState }

const commitProjectedAppState = (
  _: AppState,
  commit: AppStateCommit,
): AppState => commit.state

interface PendingMessage {
  message: string
  files?: File[]
  targetTaskId?: number
  force?: boolean
  clientMessageId?: string
  requestId?: string
  start?: () => boolean
  resolve?: () => void
  reject?: (error: Error) => void
}

// The upload-only capability of a Session transport: the composer may collect
// files and the Session sends them by id, while previews, downloads and file
// mentions stay off (filesDisabled is unaffected).
export interface SessionAttachmentsConfig {
  // Comma-separated, lowercase extensions with a leading dot, for an
  // <input type="file"> accept attribute.
  accept: string
  maxFiles: number
  maxFileBytes: number
}

interface SendMessageOptions {
  // Files already uploaded to the Session; only a Session transport that
  // offers `attachments` accepts them, and they travel on the chat frame by id.
  uploadedFiles?: readonly SessionUploadedFile[]
  // UI ownership only, never serialized into task configuration. Checked
  // before adopting a create response; normal navigation after adoption must
  // not cancel delivery of that task's first message.
  canAdoptCreatedTask?: () => boolean
  onCreatedTask?: (taskId: number) => void
}

// Whether the current Session socket has finished attaching: its server has
// sent everything it owes on attach, including any resume replay, and reads
// client frames from here on. "unsupported" means that socket's server does
// not announce it. Every other case is "pending", including no Session.
export type SessionConversationAttachment = "pending" | "attached" | "unsupported"

interface AppContextType {
  state: AppState
  dispatch: React.Dispatch<AppAction>
  filesDisabled: boolean
  agentCardsEnabled: boolean
  voiceInputEnabled: boolean
  taskControlsEnabled: boolean
  sendMessage: (message: string, config?: any, files?: File[], options?: SendMessageOptions) => Promise<void>
  executeTask: (description: string) => void
  pauseTask: () => void
  resumeTask: () => void
  selectStep: (stepId: string | null) => void
  clearMessages: () => void
  isConnected: boolean
  // Counts onConnect's same-task branch: the socket reopened for the task it
  // was last connected to. The first connect for a task does not count.
  sameTaskReconnects: number
  connectionError: Error | null
  connectionNotice: ConnectionNotice
  startNewConversation: () => Promise<void>
  canStopTask: boolean
  stopTask: () => void
  stopState: SessionStopState
  isConversationResetPending: boolean
  isMessageDeliveryPending: boolean
  // Some sendMessage call has not settled yet, on any transport.
  isSendInFlight: boolean
  isSessionInteractionLocked: boolean
  sessionConversationState: SessionConversationState["phase"]
  sessionConversationAttachment: SessionConversationAttachment
  setTaskId: (taskId: number | null, options?: { navigate?: boolean }) => void
  requestStatus: () => void
  getFilePreviewUrl: (fileId: string) => string
  getFileDownloadUrl: (fileId: string) => string
  openFilePreview: (fileId: string, fileName: string, files?: Array<{ fileId: string; fileName: string }>, index?: number) => void
  switchFilePreview: (index: number) => void
  closeFilePreview: () => void
  startReplay: (taskId: number, events: TraceEvent[]) => void
  stopReplay: () => void
  setReplayPlaying: (isPlaying: boolean) => void
  setReplaySpeed: (speed: number) => void
  setReplayProgress: (progress: number) => void
  setPendingMessage: React.Dispatch<React.SetStateAction<PendingMessage | null>>
}

const AppContext = createContext<AppContextType | undefined>(undefined)

type TransportCapabilityState = "enabled" | "disabled"

export interface AppProviderTransportCapabilities {
  files?: TransportCapabilityState
  agentCards?: TransportCapabilityState
  voice?: TransportCapabilityState
  taskControls?: TransportCapabilityState
  // Unlike the capabilities above, this defaults closed for every transport
  // (including "page"): only the embedded Chat Widget opts in, since that is
  // the only surface where an in-tab navigation abandons the visitor's iframe.
  linksOpenInNewTab?: TransportCapabilityState
  // Same default-closed rule as linksOpenInNewTab above: only a transport that
  // explicitly asks for it gets a stop control, because only the delegated
  // session endpoint reads a stop frame at all.
  taskStop?: TransportCapabilityState
}

export interface AppProviderTransportConfig {
  /**
   * Whether no-code error frames may render server prose during a temporary
   * old-backend/new-frontend deployment skew. Public and external-credential
   * transports must opt out; the authenticated page keeps its legacy default.
   */
  legacyErrorProse?: "trusted" | "untrusted"
  buildWebSocketUrl?: (params: { baseUrl: string; taskId: number }) => string
  /**
   * Owns every file URL and request made below this provider. Public
   * transports use this to keep guest credentials instance-scoped.
   */
  fileAccess?: FileAccessPolicy
  uploadFiles?: (files: File[], params: { taskId?: number | null; taskType: string }) => Promise<Array<{ file_id: string; name?: string; size?: number; type?: string }>>
  capabilities?: AppProviderTransportCapabilities
  session?: {
    connection: WebSocketConnection | null
    onConnectionClose: (
      event: CloseEvent,
      connectionIdentity?: string,
    ) => "handled"
    onConnectionFailure: (
      failure: WebSocketConnectionFailure,
      connectionIdentity?: string,
    ) => void
    onConnectionOpen?: (connectionIdentity: string) => void
    allowTasklessChat: true
    supportsConversationReset: true
    history: "none"
    // Stays "disabled": it also closes every request that reads a file back
    // (previews, downloads, mentions). Uploading is `attachments` below.
    files: "disabled"
    attachments?: SessionAttachmentsConfig
    agentCards: "disabled"
    voice: "disabled"
    taskControls: "disabled"
  }
}

interface SessionResetFlight {
  connectionIdentity: string
  deliveryGeneration: number
  promise: Promise<void>
  resolve: () => void
  reject: (error: Error) => void
  timeout: ReturnType<typeof setTimeout>
}

interface SessionMessageOwner {
  connectionIdentity: string
}

// What one physical Session socket has said about attach completion, and the
// connection identity it was written for.
interface SessionAttachmentRecord {
  connectionIdentity: string | null
  capability: "unknown" | "declared" | "absent"
  attached: boolean
}

const UNKNOWN_SESSION_ATTACHMENT: SessionAttachmentRecord = {
  connectionIdentity: null,
  capability: "unknown",
  attached: false,
}

interface SessionPreAdoptionBuffer {
  connectionIdentity: string
  candidate: { message: WebSocketMessage; taskId: number } | null
  frames: WebSocketMessage[]
  bytes: number
  timeout: ReturnType<typeof setTimeout> | null
}

const serializedWebSocketMessageBytes = (message: WebSocketMessage): number =>
  new TextEncoder().encode(JSON.stringify(message)).byteLength

function resolveTransportCapability(
  sessionTransport: AppProviderTransportConfig["session"],
  sessionState: TransportCapabilityState | undefined,
  transportState: TransportCapabilityState | undefined,
): boolean {
  // Session transports are external credential domains and therefore default
  // closed when a required runtime descriptor is malformed. Other transports
  // preserve the existing enabled behavior unless they opt out explicitly.
  return (
    sessionTransport
      ? sessionState ?? "disabled"
      : transportState ?? "enabled"
  ) === "enabled"
}

export function AppProvider({
  children,
  token,
  transport,
}: {
  children: React.ReactNode
  token?: string
  transport?: AppProviderTransportConfig
}) {
  const [state, privateCommit] = useReducer(
    commitProjectedAppState,
    undefined,
    createInitialState,
  )
  const pendingTaskToExecuteRef = useRef<{ description: string } | null>(null)
  const firstGateTaskIdRef = useRef<number | null>(null)
  const startDelayedPlaybackRef = useRef<() => void>(() => {})
  // Read through a ref, not a useCallback dependency, so the dialog
  // provider's state changes never change handleMessage's or sendMessage's
  // identity -- the same shape sessionMessageHandlerRef uses. Uses the
  // "if mounted" form, not useConnectorRuntimeDialogActions(): this context
  // is mounted on the widget/share pages with no ConnectorRuntimeDialogProvider
  // above it, and every call site below that reads connectorRuntimeDialogRef
  // legitimately expects that shape rather than a wiring mistake.
  const connectorRuntimeDialogActions = useConnectorRuntimeDialogActionsIfMounted()
  const connectorRuntimeDialogRef = useRef(connectorRuntimeDialogActions)
  useLayoutEffect(() => {
    connectorRuntimeDialogRef.current = connectorRuntimeDialogActions
  }, [connectorRuntimeDialogActions])
  const isHistoricalDataLoadingRef = useRef(false)
  const historicalDataRequestMapRef = useRef(new Map<number, boolean>())
  const recentMessagesRef = useRef(new Map<string, ReturnType<typeof setTimeout>>())
  const isDuplicateMessage = useCallback((
    content: string | React.ReactNode,
    type = "general",
    force = false,
    shouldCache = true,
    occurrenceIdentity?: string,
  ) => {
    const contentStr = normalizeMessageContent(content)
    const key = JSON.stringify([type, contentStr])
    const occurrenceKey = occurrenceIdentity
      ? JSON.stringify([type, contentStr, occurrenceIdentity])
      : undefined
    const cache = recentMessagesRef.current
    if (!force && cache.has(occurrenceKey || key)) return true
    if (shouldCache) {
      for (const cacheKey of occurrenceKey ? [key, occurrenceKey] : [key]) {
        clearTimeout(cache.get(cacheKey))
        const expiry = setTimeout(() => {
          if (cache.get(cacheKey) === expiry) cache.delete(cacheKey)
        }, 30_000)
        cache.set(cacheKey, expiry)
      }
    }
    return false
  }, [])
  // All actions are projected synchronously so each action observes the state
  // produced by the preceding action before React commits the batch.
  const stateRef = useRef(state)
  const dispatch = useCallback((action: AppAction) => {
    // Whatever cleared the transcript (reconnect, task switch, workforce run
    // swap) will have it replayed back; a surviving 30s entry would swallow
    // the replayed bubbles as duplicates.
    if (action.type === "CLEAR_MESSAGES") recentMessagesRef.current.clear()
    const next = projectAppState(stateRef.current, action)
    stateRef.current = next
    privateCommit({ state: next })
  }, [])
  const sessionConversationRef = useRef<SessionConversationState>(initialSessionConversationState)
  const dispatchSessionConversation = useCallback(
    (action: SessionConversationAction) => {
      const current = sessionConversationRef.current
      const transition = transitionSessionConversation(current, action)
      if (transition.changed) {
        sessionConversationRef.current = transition.next
        dispatch({ type: "SESSION_CONVERSATION", payload: action })
      }
      return transition
    },
    [dispatch],
  )
  useLayoutEffect(() => {
    sessionConversationRef.current = state.sessionConversation
  }, [state.sessionConversation])
  const [pendingMessage, setPendingMessage] = useState<PendingMessage | null>(null)
  const pendingMessageRef = useRef(pendingMessage)
  pendingMessageRef.current = pendingMessage
  useEffect(() => {
    const clear = () => recentMessagesRef.current.clear()
    duplicateMessageCacheClearers.add(clear)
    return () => {
      duplicateMessageCacheClearers.delete(clear)
    }
  }, [])
  const sessionTransport = transport?.session
  const trustLegacyErrorProse = transport?.legacyErrorProse !== "untrusted"
  const filesDisabled = !resolveTransportCapability(
    sessionTransport,
    sessionTransport?.files,
    transport?.capabilities?.files,
  )
  const sessionAttachments = sessionTransport?.attachments ?? null
  // sendMessage reads the attachments through this ref, so a send that
  // started under an earlier render checks its file ids against the ones
  // current when its frame goes out.
  const sessionAttachmentsRef = useRef(sessionAttachments)
  sessionAttachmentsRef.current = sessionAttachments
  const rejectDisabledFileUpload = useCallback(async () => {
    throw new Error("Files are disabled for this conversation.")
  }, [])
  const requestedAgentCardsEnabled = resolveTransportCapability(
    sessionTransport,
    sessionTransport?.agentCards,
    transport?.capabilities?.agentCards,
  )
  const agentCardsEnabled = resolveAgentCardPresentationCapability(
    filesDisabled,
    requestedAgentCardsEnabled,
  )
  // Deliberately not resolveTransportCapability: that helper defaults every
  // other capability to "enabled" for non-session transports, which is the
  // wrong default here — this must stay off everywhere except the transports
  // that explicitly request it.
  const linksOpenInNewTab = transport?.capabilities?.linksOpenInNewTab === "enabled"
  // Default-closed for the same reason as the line above: only the session
  // endpoint reads a stop frame.
  const taskStopEnabled = transport?.capabilities?.taskStop === "enabled"
  const voiceInputEnabled = resolveTransportCapability(
    sessionTransport,
    sessionTransport?.voice,
    transport?.capabilities?.voice,
  )
  const taskControlsEnabled = resolveTransportCapability(
    sessionTransport,
    sessionTransport?.taskControls,
    transport?.capabilities?.taskControls,
  )
  const sessionConnectionIdentity =
    sessionTransport?.connection?.identity ?? null
  const [deliveryGeneration, setDeliveryGeneration] = useState(0)
  const deliveryGenerationRef = useRef(deliveryGeneration)
  deliveryGenerationRef.current = deliveryGeneration
  const [messageDeliveryCount, setMessageDeliveryCount] = useState(0)
  const messageDeliveryCountRef = useRef(0)
  const sessionConnectionIdentityRef = useRef(sessionConnectionIdentity)
  sessionConnectionIdentityRef.current = sessionConnectionIdentity
  const previousSessionConnectionIdentityRef = useRef(
    sessionConnectionIdentity
  )
  const sessionResetFlightRef = useRef<SessionResetFlight | null>(null)
  const sessionPreAdoptionBufferRef = useRef<SessionPreAdoptionBuffer | null>(null)
  const flushingSessionPreAdoptionCandidateRef = useRef<WebSocketMessage | null>(null)
  const retiredSessionTaskIdsRef = useRef(new Set<number>())
  const sessionMessageHandlerRef = useRef<
    (message: WebSocketMessage, owner: SessionMessageOwner) => void
  >(() => {})
  const mountedRef = useRef(false)
  const onConnectTimeoutsRef = useRef(new Set<ReturnType<typeof setTimeout>>())
  // The ref is read synchronously by the frame handlers; stopState mirrors
  // its control for rendering. Every write goes through applySessionStop.
  const sessionStopRef = useRef<SessionStop>(initialSessionStop)
  const [stopState, setStopState] = useState<SessionStopState>("idle")
  const stopTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)

  const clearStopTimeout = useCallback(() => {
    if (stopTimeoutRef.current !== null) {
      clearTimeout(stopTimeoutRef.current)
      stopTimeoutRef.current = null
    }
  }, [])
  const applySessionStop = useCallback(
    function apply(event: SessionStopEvent) {
      const current = sessionStopRef.current
      const { next, effect } = reduceSessionStop(current, event)
      sessionStopRef.current = next
      if (next.control !== current.control) setStopState(next.control)
      if (effect === null) return
      clearStopTimeout()
      if (effect === "arm_timeout") {
        stopTimeoutRef.current = setTimeout(() => {
          stopTimeoutRef.current = null
          apply({ type: "STOP_TIMED_OUT" })
        }, SESSION_STOP_TIMEOUT_MS)
      }
    },
    [clearStopTimeout],
  )
  const { t } = useI18n()
  const router = useRouter()
  const lastConnectedTaskId = useRef<number | null>(null)
  const [sameTaskReconnects, setSameTaskReconnects] = useState(0)
  const sharedStreamRef = useRef<{
    taskId?: number
    runId?: string | null
    attemptId?: string | null
    interrupted: boolean
    prefixSeen: boolean
    complete: boolean
    messageId?: string
    executionSequence?: number
  }>({ interrupted: false, prefixSeen: false, complete: false })
  const taskStateVersionsRef = useRef(
    new Map<number, TaskStateVersionEntry>()
  )

  // Session task ownership is established only by a current-socket task_info;
  // never import a legacy route/storage Task id into this protocol state.
  const sessionTaskIdRef = useRef<number | null>(null)

  // Written only through writeSessionAttachment. It is reset whenever a socket
  // opens or the connection drops, and the exposed value also requires its
  // identity to equal the current connection identity: every Session
  // reconnect comes with a new identity, so a record an earlier connection
  // left behind never reads as current.
  const sessionAttachmentRef = useRef<SessionAttachmentRecord>(
    UNKNOWN_SESSION_ATTACHMENT
  )
  const [sessionAttachment, setSessionAttachment] =
    useState<SessionAttachmentRecord>(UNKNOWN_SESSION_ATTACHMENT)
  const writeSessionAttachment = useCallback((next: SessionAttachmentRecord) => {
    sessionAttachmentRef.current = next
    if (mountedRef.current) setSessionAttachment(next)
  }, [])

  const rejectSessionResetFlight = useCallback(
    (
      resetFlight: SessionResetFlight | null,
      error: Error,
    ): boolean => {
      if (
        !resetFlight
        || sessionResetFlightRef.current !== resetFlight
      ) {
        return false
      }

      sessionResetFlightRef.current = null
      clearTimeout(resetFlight.timeout)
      resetFlight.reject(error)
      return true
    },
    [],
  )

  const discardSessionPreAdoptionBuffer = useCallback(() => {
    const buffer = sessionPreAdoptionBufferRef.current
    if (!buffer) return
    if (buffer.timeout !== null) clearTimeout(buffer.timeout)
    sessionPreAdoptionBufferRef.current = null
  }, [])

  const requireSessionReload = useCallback((error: Error) => {
    discardSessionPreAdoptionBuffer()
    rejectSessionResetFlight(sessionResetFlightRef.current, error)
    dispatchSessionConversation({
      type: "SESSION_RELOAD_REQUIRED",
      connectionIdentity: sessionConnectionIdentityRef.current,
    })
  }, [discardSessionPreAdoptionBuffer, dispatchSessionConversation, rejectSessionResetFlight])

  const beginSessionPreAdoptionBuffer = useCallback((connectionIdentity: string) => {
    discardSessionPreAdoptionBuffer()
    sessionPreAdoptionBufferRef.current = {
      connectionIdentity,
      candidate: null,
      frames: [],
      bytes: 0,
      timeout: null,
    }
  }, [discardSessionPreAdoptionBuffer])

  const activateSessionPreAdoptionBuffer = useCallback((connectionIdentity: string) => {
    const buffer = sessionPreAdoptionBufferRef.current
    if (!buffer || buffer.connectionIdentity !== connectionIdentity) {
      requireSessionReload(
        new Error("Replacement conversation transaction is missing; reload required.")
      )
      return
    }
    if (buffer.timeout !== null) return
    buffer.timeout = setTimeout(() => {
      const buffer = sessionPreAdoptionBufferRef.current
      if (buffer?.connectionIdentity !== connectionIdentity) return
      requireSessionReload(
        new Error("Replacement conversation did not publish task_info before its deadline; reload required.")
      )
    }, SESSION_TASK_ADOPTION_TIMEOUT_MS)
    if (buffer.candidate) {
      flushingSessionPreAdoptionCandidateRef.current = buffer.candidate.message
      try {
        sessionMessageHandlerRef.current(buffer.candidate.message, { connectionIdentity })
      } finally {
        flushingSessionPreAdoptionCandidateRef.current = null
      }
    }
  }, [requireSessionReload])

  const bufferSessionPreAdoptionFrame = useCallback((
    message: WebSocketMessage,
    owner: SessionMessageOwner,
    candidateTaskId?: number,
  ): boolean => {
    const buffer = sessionPreAdoptionBufferRef.current
    if (!buffer || buffer.connectionIdentity !== owner.connectionIdentity) {
      requireSessionReload(
        new Error("Replacement frame ownership is unknown; reload required.")
      )
      return false
    }
    const bytes = serializedWebSocketMessageBytes(message)
    if (candidateTaskId !== undefined && buffer.candidate) {
      if (buffer.candidate.taskId === candidateTaskId) return true
      requireSessionReload(
        new Error("Replacement conversation published conflicting task_info; reload required.")
      )
      return false
    }
    if (
      buffer.frames.length + (buffer.candidate ? 1 : 0) >= MAX_SESSION_PRE_ADOPTION_FRAMES
      || buffer.bytes + bytes > MAX_SESSION_PRE_ADOPTION_BYTES
    ) {
      requireSessionReload(
        new Error("Replacement frame buffer exceeded its safe bound; reload required.")
      )
      return false
    }
    if (candidateTaskId !== undefined) {
      buffer.candidate = { message, taskId: candidateTaskId }
    } else {
      buffer.frames.push(message)
    }
    buffer.bytes += bytes
    return true
  }, [requireSessionReload])

  useEffect(() => {
    mountedRef.current = true
    return () => {
      mountedRef.current = false
      onConnectTimeoutsRef.current.forEach(timeout => clearTimeout(timeout))
      onConnectTimeoutsRef.current.clear()
      resendWaitersRef.current.release(false)
      messageDeliveryCountRef.current = 0
      discardSessionPreAdoptionBuffer()
      rejectSessionResetFlight(
        sessionResetFlightRef.current,
        new Error("Conversation reset was cancelled because chat was closed.")
      )
    }
  }, [discardSessionPreAdoptionBuffer, rejectSessionResetFlight])

  useEffect(() => {
    const taskId = state.taskId
    const hasRuntimeExtensionBinding = (
      state.currentTask?.id === String(taskId)
      && (state.currentTask.runtimeExtensionBindings?.length || 0) > 0
    )
    if (taskId === null || sessionTransport || !hasRuntimeExtensionBinding) return

    let cancelled = false
    const loadRuntimeExtensions = async () => {
      try {
        const response = await apiRequest(
          `${getApiUrl()}/api/chat/task/${taskId}/runtime-extensions`,
          { cache: "no-store" },
        )
        if (!response || !response.ok) return
        const payload = await response.json()
        if (cancelled) return
        dispatch({
          type: "SET_TASK_RUNTIME_EXTENSIONS",
          payload: {
            taskId,
            extensions: normalizeTaskRuntimeExtensions(payload?.runtime_extensions),
          },
        })
      } catch (error) {
        // Runtime metadata only decorates the transcript. A temporary metadata
        // failure must not block loading or running the task itself.
        console.warn("Failed to load task runtime metadata", error)
      }
    }
    void loadRuntimeExtensions()

    return () => {
      cancelled = true
    }
  }, [
    dispatch,
    sessionTransport,
    state.currentTask?.id,
    state.currentTask?.runtimeExtensionBindings,
    state.taskId,
  ])

  const boundSessionTaskId =
    state.sessionConversation.phase === "bound"
      ? state.sessionConversation.taskId
      : null
  useEffect(() => {
    if (boundSessionTaskId === null) return
    applySessionStop({ type: "TASK_BOUND", taskId: boundSessionTaskId })
  }, [applySessionStop, boundSessionTaskId])

  useEffect(() => clearStopTimeout, [clearStopTimeout])

  useEffect(() => {
    const previousIdentity = previousSessionConnectionIdentityRef.current
    previousSessionConnectionIdentityRef.current = sessionConnectionIdentity
    if (previousIdentity === sessionConnectionIdentity) return

    // Per-connection button state only. The stop intent is per task and
    // deliberately survives this: the session token is re-issued 60s before
    // expiry, which changes the connection identity mid-cancel, and the turn's
    // terminal frame must still render as a stopped turn afterwards.
    applySessionStop({ type: "CONNECTION_CHANGED" })

    if (sessionConversationRef.current.phase === "bound") {
      if (sessionConnectionIdentity) {
        dispatchSessionConversation({
          type: "SESSION_BOUND_CONNECTION_REBOUND",
          connectionIdentity: sessionConnectionIdentity,
        })
      }
      return
    }
    if (sessionConversationRef.current.phase !== "unbound") {
      requireSessionReload(
        new Error("Conversation outcome is unknown after a connection refresh; reload required.")
      )
    }
  }, [applySessionStop, dispatchSessionConversation, requireSessionReload, sessionConnectionIdentity])

  const resendWaitersRef = useRef(new ResendWaiters())

  // Tasks a socket has opened for since this provider mounted, keyed by the
  // opened socket's own task: during a task switch stateRef may already name
  // the next task before the old socket is retired.
  const openedTaskIdsRef = useRef(new Set<typeof state.taskId>())

  const onConnect = useCallback((openedTaskId: number | undefined) => {
    openedTaskIdsRef.current.add(openedTaskId ?? null)
    resendWaitersRef.current.release(true)
    if (sessionTransport?.history === "none") {
      writeSessionAttachment({
        connectionIdentity: sessionConnectionIdentityRef.current,
        capability: "unknown",
        attached: false,
      })
      const connectionIdentity = sessionConnectionIdentityRef.current
      if (connectionIdentity && connectionIdentity === sessionConnectionIdentity) {
        sessionTransport.onConnectionOpen?.(connectionIdentity)
      }
      isHistoricalDataLoadingRef.current = false
      dispatch({ type: "SET_HISTORY_LOADING", payload: false })
      return
    }

    // Fix: If we should be in replay mode but got disconnected, restore replay state
    if (stateRef.current.replayTaskId && stateRef.current.taskId === stateRef.current.replayTaskId && !stateRef.current.isReplaying) {
      dispatch({ type: "SET_REPLAY_PLAYING", payload: true })
    }

    // Handle clearing messages on reconnection
    // This prevents stale data issues and fixes race conditions
    if (lastConnectedTaskId.current === stateRef.current.taskId) {
      // Reconnection to SAME task -> Clear messages
      setSameTaskReconnects(count => count + 1)
      dispatch({
        type: "CLEAR_MESSAGES",
        payload: {
          preserveUserMessages: true,
          preserveStreamingFinalAnswers: true,
        },
      })
      dispatch({ type: "SET_TRACE_EVENTS", payload: [] })
      // Clear dagExecution alongside steps - otherwise the Progress panel
      // stays open (it only needs dagExecution to be non-null) rendering an
      // empty step list for the gap between reconnecting and history replay
      // repopulating both together.
      dispatch({ type: "RESET_DAG_STATE" })
    } else {
      // New task connection -> Update tracker, Don't clear (handled by setTaskId)
      lastConnectedTaskId.current = stateRef.current.taskId
    }

    // Set history loading state
    isHistoricalDataLoadingRef.current = true
    dispatch({ type: "SET_HISTORY_LOADING", payload: true })

    // These callbacks belong to this provider and must not dispatch after it
    // unmounts. Remove expired handles so reconnects cannot grow the set.
    const scheduleOnConnect = (callback: () => void, delay: number) => {
      const timeout = setTimeout(() => {
        onConnectTimeoutsRef.current.delete(timeout)
        callback()
      }, delay)
      onConnectTimeoutsRef.current.add(timeout)
    }

    // Safety timeout: if no history arrives within 2 seconds, assume empty or done
    scheduleOnConnect(() => {
      dispatch({ type: "SET_HISTORY_LOADING", payload: false })
    }, 2000)

    // Auto-execute PENDING tasks from Agent Builder
    scheduleOnConnect(() => {
      if (pendingTaskToExecuteRef.current) {
        const hasUserMessages = stateRef.current.messages.some(m => m.role === 'user')
        console.log('🔍 onConnect - checking auto-execute:', {
          hasPendingTask: !!pendingTaskToExecuteRef.current,
          pendingDescription: pendingTaskToExecuteRef.current.description,
          hasUserMessages,
        })

        if (!hasUserMessages) {
          console.log('🚀 Auto-executing PENDING task from Agent Builder (onConnect):', pendingTaskToExecuteRef.current.description)
          // sendChatMessage(pendingTaskToExecute.description, []) // Cannot access sendChatMessage
          pendingTaskToExecuteRef.current = null
        } else {
          console.log('⏭️ Skipping auto-execute, already has user messages')
          pendingTaskToExecuteRef.current = null
        }
      }
    }, 1000)
  }, [
    sessionConnectionIdentity,
    sessionTransport?.history,
    sessionTransport?.onConnectionOpen,
    writeSessionAttachment,
  ])

  const sessionMessageOwner = sessionConnectionIdentity
    ? {
      connectionIdentity: sessionConnectionIdentity,
    }
    : null

  const {
    isConnected,
    connectionError,
    sendMessage: sendRawMessage,
    sendChatMessage,
    executeTask: wsExecuteTask,
    pauseTask: wsPauseTask,
    resumeTask: wsResumeTask,
    requestStatus,
    connect,
    connectionPhase,
    getLoginIdentity,
  } = useWebSocket({
    taskId: state.taskId || undefined,
    token,
    buildWebSocketUrl: transport?.buildWebSocketUrl,
    uploadFiles: filesDisabled
      ? rejectDisabledFileUpload
      : transport?.uploadFiles,
    connection:
      sessionTransport === undefined
        ? undefined
        : sessionTransport.connection,
    deliveryGeneration:
      sessionTransport === undefined
        ? undefined
        : deliveryGeneration,
    legacyErrorProse: trustLegacyErrorProse ? "trusted" : "untrusted",
    onSessionConnectionClose: sessionTransport?.onConnectionClose,
    onSessionConnectionFailure: sessionTransport?.onConnectionFailure,
    onMessage: (message) => {
      if (sessionTransport) {
        if (
          !mountedRef.current
          || !sessionMessageOwner
          || sessionMessageOwner.connectionIdentity
            !== sessionConnectionIdentityRef.current
        ) {
          return
        }
        sessionMessageHandlerRef.current(message, sessionMessageOwner)
        return
      }
      handleMessage(message, dispatch, stateRef.current, { filesDisabled })
    },
    onConnectionCapabilities: sessionTransport
      ? (capabilities) => {
        if (
          !mountedRef.current
          || !sessionMessageOwner
          || sessionMessageOwner.connectionIdentity
            !== sessionConnectionIdentityRef.current
          || sessionAttachmentRef.current.connectionIdentity
            !== sessionMessageOwner.connectionIdentity
        ) {
          return
        }
        writeSessionAttachment({
          ...sessionAttachmentRef.current,
          capability: capabilities.includes("conversation_attached")
            ? "declared"
            : "absent",
        })
      }
      : undefined,
    onConnect: onConnect, // Pass the callback
    autoConnect: true,
  })

  const canStopTask =
    taskStopEnabled
    // A press while the socket is down can only end in "not_sent".
    && isConnected
    && state.isProcessing
    && state.sessionConversation.phase === "bound"

  // The control's own state lasts only as long as the control is available,
  // and availability is wider than "this run is over": a task that pauses to
  // ask the visitor a question also stops counting as processing, and a
  // dropped socket makes the control unavailable too, so a stop still
  // outstanding at that moment loses its "stopping" state and its
  // unconfirmed-timeout window, and the control returns pressable with no
  // record of the earlier press. Accepted as it stands: STOP_UNAVAILABLE
  // leaves the per-task stop intent alone, so the turn still
  // renders as a stopped turn when its own terminal frame says it was
  // interrupted — what is lost is the button's memory of the press, not the
  // outcome of the stop.
  useEffect(() => {
    if (canStopTask) return
    applySessionStop({ type: "STOP_UNAVAILABLE" })
  }, [applySessionStop, canStopTask])

  // The Session's host page reconnects it, so only the other transports end the
  // wait on their phase: `lost` (no reconnect is coming) or `idle` (no task is
  // open, so no connection will open for the send's task).
  useEffect(() => {
    resendWaitersRef.current.setEnded(
      sessionTransport === undefined && (connectionPhase === "lost" || connectionPhase === "idle"),
    )
  }, [connectionPhase, sessionTransport])

  // A send whose connection was lost is sent once more on the next connection
  // if the login, task and Session state it was sent from still hold.
  // `beforeAttempt` runs before each attempt.
  const sendChatWithResend = useCallback((
    args: Parameters<typeof sendChatMessage>,
    beforeAttempt?: () => void,
  ) => {
    const capture = (): ResendOwnership => ({
      loginIdentity: getLoginIdentity(),
      boundTaskId: sessionTransport
        ? sessionConversationRef.current.taskId
        : stateRef.current.taskId,
      session: sessionTransport
        ? {
          deliveryGeneration: deliveryGenerationRef.current,
          phase: sessionConversationRef.current.phase,
        }
        : null,
    })
    const first = capture()
    return sendWithResend(
      () => {
        beforeAttempt?.()
        return sendChatMessage(...args)
      },
      resendWaitersRef.current,
      () => mayResend(first, capture()),
    )
  }, [getLoginIdentity, sendChatMessage, sessionTransport])

  const connectionNotice = deriveConnectionNotice({
    isSessionTransport: sessionTransport !== undefined,
    hadOpen: sessionTransport
      ? openedTaskIdsRef.current.size > 0
      : openedTaskIdsRef.current.has(state.taskId),
    phase: connectionPhase,
    isConnected,
  })

  useEffect(() => {
    if (!sessionTransport || isConnected) return
    if (
      sessionConversationRef.current.phase !== "reset_requested"
      && sessionConversationRef.current.phase !== "replacement_ready"
      && sessionConversationRef.current.phase !== "replacement_sending"
      && sessionConversationRef.current.phase !== "replacement_awaiting_task"
    ) {
      return
    }
    requireSessionReload(
      new Error("Conversation outcome is unknown because the Session disconnected; reload required.")
    )
  }, [isConnected, requireSessionReload, sessionTransport])

  useEffect(() => {
    if (sessionTransport && !isConnected) {
      writeSessionAttachment({
        connectionIdentity: sessionConnectionIdentityRef.current,
        capability: "unknown",
        attached: false,
      })
    }
  }, [isConnected, sessionTransport, writeSessionAttachment])

  // Handle pending messages separately since we need sendChatMessage
  useEffect(() => {
    if (isConnected && pendingMessage) {
      // Ensure we are sending to the correct task
      // If targetTaskId is set, it must match the current connected task
      if (pendingMessage.targetTaskId) {
        if (stateRef.current.taskId !== pendingMessage.targetTaskId) return
        // We use lastConnectedTaskId.current because state.taskId might be updated before the socket is connected
        // But sendChatMessage sends to the currently connected socket.
        // We need to make sure the CURRENT socket corresponds to the targetTaskId.
        // lastConnectedTaskId is updated in onConnect, so it reflects the current socket's task ID.
        if (lastConnectedTaskId.current !== pendingMessage.targetTaskId) {
          console.log('⏳ Pending message target task mismatch, waiting...', {
            target: pendingMessage.targetTaskId,
            current: lastConnectedTaskId.current
          })
          return
        }
      }

      // The queue owns only the connection wait. Once claimed, the transport
      // owns upload cancellation and acknowledgement timeouts/dispositions.
      if (pendingMessageRef.current !== pendingMessage || pendingMessage.start?.() === false) return
      pendingMessageRef.current = null
      setPendingMessage(current => current === pendingMessage ? null : current)

      console.log('📤 Sending pending message:', {
        message: pendingMessage.message,
        hasFiles: pendingMessage.files && pendingMessage.files.length > 0,
        targetTaskId: pendingMessage.targetTaskId
      })
      void Promise.resolve(
        sendChatWithResend([
          pendingMessage.message,
          pendingMessage.files,
          pendingMessage.force,
          pendingMessage.clientMessageId,
          pendingMessage.requestId,
        ])
      ).then(() => {
        pendingMessage.resolve?.()
        setPendingMessage(current => current === pendingMessage ? null : current)
      }).catch((error) => {
        const deliveryError = error instanceof Error ? error : new Error(String(error))
        pendingMessage.reject?.(deliveryError)
        setPendingMessage(current => current === pendingMessage ? null : current)
      })
    }
  }, [isConnected, pendingMessage, sendChatWithResend])

  // A queued message can only ever flush to its target task. If the task is
  // switched away before that socket connects (e.g. the widget's "New
  // conversation" reset), fail it immediately — left queued it would sit out
  // the 30s timeout and vanish as an unhandled rejection with no visible error.
  useEffect(() => {
    if (!pendingMessage?.targetTaskId) return
    if (state.taskId === pendingMessage.targetTaskId) return
    pendingMessage.reject?.(
      new MessageDeliveryError('Message not sent: the conversation was reset before it could be delivered.', 'not_sent')
    )
    setPendingMessage(current => (current === pendingMessage ? null : current))
  }, [pendingMessage, state.taskId])

  const queuePendingMessage = useCallback((message: Omit<PendingMessage, 'start' | 'resolve' | 'reject'>) => {
    return new Promise<void>((resolve, reject) => {
      let waiting = true
      const timeout = window.setTimeout(() => {
        waiting = false
        setPendingMessage(current => (
          current?.clientMessageId === message.clientMessageId ? null : current
        ))
        reject(new MessageDeliveryError('Message not sent: timed out waiting for the task connection.', 'not_sent'))
      }, 30000)
      setPendingMessage({
        ...message,
        start: () => {
          if (!waiting) return false
          waiting = false
          window.clearTimeout(timeout)
          return true
        },
        resolve: () => {
          waiting = false
          window.clearTimeout(timeout)
          resolve()
        },
        reject: (error) => {
          waiting = false
          window.clearTimeout(timeout)
          reject(error)
        },
      })
    })
  }, [])

  // Handle auto-execute pending task separately
  useEffect(() => {
    if (isConnected && pendingTaskToExecuteRef.current) {
      // Logic moved to effect
      // But wait, pendingTaskToExecute is not state, it's a let variable.
      // Effect won't run when it changes.
      // But it runs when isConnected changes.

      const timer = setTimeout(() => {
        if (pendingTaskToExecuteRef.current) {
          const hasUserMessages = stateRef.current.messages.some(m => m.role === 'user')
          if (!hasUserMessages) {
            const description = pendingTaskToExecuteRef.current.description
            const taskId = stateRef.current.taskId
            const clientMessageId = generateClientMessageId()
            // This auto-send bypasses sendMessage entirely (it predates the
            // connector-runtime dialog and must keep this old path's own
            // behavior unchanged, not gain sendMessage's optimistic bubble
            // or send guards), so it never staged a resend candidate for
            // itself. Stage/redeem/discard it here the same way sendMessage's
            // own call sites do, or a terminal task_error this send provokes
            // finds no candidate to offer.
            if (typeof taskId === "number") {
              connectorRuntimeDialogRef.current.stagePendingDelivery({
                taskId, clientMessageId, text: description, files: [],
              })
            }
            sendChatMessage(description, [], false, clientMessageId)
              .then(() => {
                if (typeof taskId === "number") {
                  connectorRuntimeDialogRef.current.recordDelivery({
                    taskId, clientMessageId, text: description, files: [],
                  })
                }
              })
              .catch(() => {
                // Logged, not rethrown. This is a detached promise inside a
                // setTimeout callback: there is no caller above it to receive
                // a rethrow, so one would surface as an unhandled rejection
                // instead of reaching anything that could act on it. The
                // sibling stage/discard sites in sendMessage do rethrow
                // because each of them sits inside a call its own caller
                // awaits. Without this line the send failing here is silent
                // on every surface -- no bubble, no toast, no log.
                console.warn("[connector-runtime] pending-task auto-send failed")
                connectorRuntimeDialogRef.current.discardPendingDelivery(clientMessageId)
              })
            pendingTaskToExecuteRef.current = null
          }
        }
      }, 1000)
      return () => clearTimeout(timer)
    }
  }, [isConnected, sendChatMessage])

  // Debug: Log when taskId is passed to useWebSocket
  useEffect(() => {
    console.log('🔧 useWebSocket taskId prop:', {
      taskId: state.taskId,
      taskIdType: typeof state.taskId
    })
  }, [state.taskId])

  // Track connection state changes
  useEffect(() => {
    console.log('🔄 AppContext - WebSocket connection state changed:', {
      isConnected,
      taskId: state.taskId,
      hasConnectionError: !!connectionError,
      connectionErrorMessage: connectionError?.message,
      timestamp: new Date().toISOString()
    })
  }, [isConnected, state.taskId, connectionError])

  // The single place that answers "this frame ends the turn -- now what?".
  // Each of the three settlement call sites below (task_completed,
  // agent_error, terminal task_error) keeps its own predicate for WHETHER a
  // frame is terminal, because the three frame families prove terminality
  // differently (see each call site's own comment). What they must NOT keep
  // is their own idea of what to do once settled: that lives here, so a
  // fourth frame family added later cannot settle a turn while quietly
  // skipping the stash and pending-candidate cleanup that settlement
  // requires (see the stash lifecycle docs on ConnectorRuntimePendingDelivery).
  //
  // Recreated on every render and captured by handleMessage's useCallback
  // without appearing in its dependency array. That is safe for as long as
  // the body below reads nothing but connectorRuntimeDialogRef.current,
  // which a ref always resolves to the latest value regardless of which
  // render's closure is calling. Anything read here that is not a ref --
  // a prop, a state value, another callback -- makes a stale capture
  // possible, and at that point this has to move behind a ref of its own
  // rather than be added to that array.
  const settleConnectorRuntimeTurn = (taskId: number, opensDialog: boolean): void => {
    // openForTask hands this tab's candidate (staged or already-confirmed)
    // to the request and clears it in the same update: that frame both
    // opens the dialog and settles the turn. Never call forgetDelivery
    // before this for the same frame -- see its own misuse warning.
    if (opensDialog) connectorRuntimeDialogRef.current.openForTask(taskId)
    else connectorRuntimeDialogRef.current.forgetDelivery(taskId)
  }

  const handleMessage = useCallback((
    message: WebSocketMessage,
    rawDispatch: React.Dispatch<AppAction>,
    currentState: AppState,
    options?: {
      skipHistory?: boolean
      filesDisabled?: boolean
    },
  ) => {
    // A task's WebSocket connection is per-task (or, for session transports,
    // multiplexes a sequence of tasks over one socket) - either way, a
    // just-superseded socket/task can still have events in flight after the
    // app has moved on to a different task (e.g. the user starts a new chat
    // while a previous DAG run is still executing in the background). Those
    // stray events must not repaint TASK_SCOPED_ACTION_TYPES's state for
    // whatever task is now on screen - not just DAG/step state, but the chat
    // transcript, trace log, context/memory display, and processing/status
    // flags too, since a background task's reply or tool trace has no
    // business appearing in a different task's conversation. Deliberately
    // keyed ONLY off currentState.taskId (not currentTask.id): switching
    // tasks via setTaskId leaves a real window where taskId has already
    // advanced to the new task but currentTask still describes the old one
    // (until that task's own task_info arrives) - matching against
    // currentTask.id in that window would let the old task's stray events
    // right back through, defeating the whole guard.
    const messageTaskId = (message as unknown as { task_id?: unknown }).task_id
    // No task is even being viewed (currentState.taskId null/undefined) but
    // this message names a specific task - that can only be a stray event
    // for a task other than "the current view", so it counts as "for another
    // task" too (not just the "viewing a *different* task" case).
    const isMessageForOtherTask =
      messageTaskId !== undefined && messageTaskId !== null && messageTaskId !== ""
      && String(messageTaskId) !== String(currentState.taskId)
    const dispatch: React.Dispatch<AppAction> = (action) => {
      if (TASK_SCOPED_ACTION_TYPES.has(action.type) && isMessageForOtherTask) return
      // Stamp every UPDATE_TASK_STATUS dispatched from this handler with the
      // originating event's own timestamp here, once, rather than relying on
      // each call site to remember to pass it - a forgotten `updatedAt` at a
      // future call site would otherwise silently fall back to client-now in
      // the reducer, quietly reintroducing the wrong-elapsed-time-on-replay
      // bug this field exists to fix. External UI callers of UPDATE_TASK_STATUS
      // (outside this handler, e.g. sendMessage's optimistic status flip)
      // don't go through this wrapper and keep their own client-now fallback.
      if (action.type === "UPDATE_TASK_STATUS" && action.payload.updatedAt === undefined) {
        rawDispatch({ ...action, payload: { ...action.payload, updatedAt: message.timestamp } })
        return
      }
      rawDispatch(action)
    }
    if (!isMessageForOtherTask && typeof messageTaskId === "number") {
      let stream = sharedStreamRef.current
      if (stream.taskId !== messageTaskId) {
        stream = { taskId: messageTaskId, interrupted: false, prefixSeen: false, complete: false }
        sharedStreamRef.current = stream
      }
      if (message.type === "stream_unavailable" || message.type === "stream_resync_required") {
        stream.interrupted = true
        dispatch({ type: "SET_STREAM_RECOVERY", payload: messageTaskId })
        return
      }
      if (message.type === "task_stream_snapshot") {
        if (isHistoricalDataLoadingRef.current) return
        const envelope = extractTaskControlEnvelope(message)
        if (!acceptTaskControlVersion(message, envelope, taskStateVersionsRef.current)) return
        const data = asMessageRecord(message.data)
        // A new run starting can't have inherited an interruption from
        // whatever run preceded it - carrying a stale `true` forward would
        // flag the very first snapshot of a brand-new, healthy run. But
        // going from "no run known yet" to "this run" is NOT a run change:
        // stream.runId starts undefined, and the backend reports `null` for
        // a task that hasn't started running yet (both mean "nothing to
        // compare against" the same way) - an explicit stream_unavailable/
        // stream_resync_required for the CURRENT run can set interrupted
        // before its first snapshot with a real run id ever arrives. Only a
        // known-to-different-known transition is a genuine new run.
        const isNewRun =
          stream.runId != null && envelope.runId != null && stream.runId !== envelope.runId
        if (stream.runId !== envelope.runId) {
          stream.runId = envelope.runId
          stream.prefixSeen = false
          stream.complete = false
          if (isNewRun) stream.interrupted = false
        }
        stream.attemptId = typeof data.lease_attempt_id === "string" ? data.lease_attempt_id : null
        // "running with no prefix seen yet" is the ordinary state of every task
        // between the run starting and its final-answer text beginning to
        // stream (planning, tool calls, etc.) - it is NOT evidence anything
        // was missed. This periodic snapshot fires every 5s for every
        // connected task regardless of stream health, so treating that as an
        // interruption flagged the recovery banner on almost every run.
        // Genuine misses are already caught elsewhere: an explicit
        // stream_unavailable/stream_resync_required message above, or a
        // final_answer_delta arriving before its prefix below - both leave
        // positive evidence content was produced without us. Leave
        // stream.interrupted as carried over from those instead of deriving
        // a new value from status alone.
        const active = envelope.status === "running"
        if (envelope.status) {
          dispatch({ type: "UPDATE_TASK_STATUS", payload: {
            status: envelope.status, runId: envelope.runId,
            completionOutcome: normalizeCompletionOutcome(data.completion_outcome),
            stateVersion: envelope.stateVersion, controlState: envelope.controlState,
            ...(envelope.status === "waiting_for_user" ? {
              waitingQuestion: typeof data.question === "string" ? data.question : undefined,
              waitingInteractions: normalizeInteractions(data.interactions),
            } : {}),
          } })
          dispatch({ type: "SET_PROCESSING", payload: active })
        }
        if (typeof data.output === "string" && typeof envelope.runId === "string") {
          dispatch({ type: "RECONCILE_STREAM_OUTPUT", payload: {
            runId: envelope.runId, output: data.output,
            timestamp: message.timestamp, interrupted: stream.interrupted,
          } })
          stream.interrupted = false
          stream.complete = true
        } else if (envelope.status && envelope.status !== "running") {
          stream.interrupted = false
        }
        dispatch({ type: "SET_STREAM_RECOVERY", payload: stream.interrupted ? messageTaskId : null })
        return
      }
      if (message.stream_run_id !== undefined) {
        const known = taskStateVersionsRef.current.get(messageTaskId)
        if (known?.runId !== undefined && known.runId !== message.stream_run_id) {
          const envelope = extractTaskControlEnvelope(message)
          if (!envelope.isStateEvent || envelope.runId !== message.stream_run_id
            || envelope.stateVersion === undefined || envelope.stateVersion <= known.version) return
        }
        if (stream.runId !== message.stream_run_id) {
          stream.runId = message.stream_run_id
          stream.attemptId = message.stream_attempt_id
          stream.prefixSeen = false
          stream.interrupted = false
          stream.complete = false
          dispatch({ type: "SET_STREAM_RECOVERY", payload: null })
        }
        if (stream.attemptId && message.stream_attempt_id !== stream.attemptId) return
      }
      const streamType = getWebSocketEventType(message)
      if (isFinalAnswerStreamEventType(streamType)) {
        const sharedFrame = message.stream_run_id !== undefined
        const data = asMessageRecord(message.data)
        const eventData = message.type === "trace_event"
          ? asMessageRecord(data.data ?? data)
          : { ...data, ...message }
        const executionSequence = message.execution_sequence
        // Historical frames still update their own bubbles below. Only a
        // newer boundary can change which occurrence owns transport flags.
        const updatesCurrentStream = executionSequence === undefined
          || stream.executionSequence === undefined
          || executionSequence > stream.executionSequence
        if (updatesCurrentStream) {
          if (executionSequence !== undefined) {
            if (eventData.message_id !== stream.messageId) {
              stream.complete = false
              stream.prefixSeen = false
              stream.interrupted = false
            }
            stream.messageId = eventData.message_id as string
            stream.executionSequence = executionSequence
          }
          if (stream.complete && executionSequence === undefined
            && (stream.executionSequence === undefined || eventData.message_id === stream.messageId)) return
          if (streamType === "final_answer_start") {
            stream.prefixSeen = true
            stream.interrupted = false
            dispatch({ type: "SET_STREAM_RECOVERY", payload: null })
          }
          const replacesContent = (sharedFrame || executionSequence !== undefined) && (
            (streamType === "final_answer_end" && typeof eventData.content === "string")
            || (streamType === "final_answer_error" && typeof eventData.error === "string")
          )
          if (sharedFrame && streamType === "final_answer_delta"
            && (!stream.prefixSeen || (stream.executionSequence !== undefined && eventData.message_id !== stream.messageId))) {
            stream.interrupted = true
            dispatch({ type: "SET_STREAM_RECOVERY", payload: messageTaskId })
            return
          }
          if (replacesContent) {
            stream.prefixSeen = true
            stream.interrupted = false
            dispatch({ type: "SET_STREAM_RECOVERY", payload: null })
          }
          if (stream.interrupted) return
          if (replacesContent) stream.complete = true
        }
      }
    }
    // The 30s dedup cache below is keyed on message content/type only, not
    // task id - several dedupKeys (e.g. dag-execute-end's "task end, this
    // iteration") are templated purely on generic fields like iteration
    // count, so a background task and the currently-viewed task can produce
    // the exact same key. A stale event for another task never reaches
    // `dispatch` (filtered above), but if it were still allowed to *insert*
    // into the cache, it would silently swallow the viewed task's own
    // legitimate ADD_MESSAGE as a "duplicate" moments later. Skip caching
    // (not skip the check itself) whenever the message belongs elsewhere.
    const isDuplicateMessageForViewedTask = (
      content: string | React.ReactNode,
      type = "general",
      occurrenceIdentity?: string,
    ) => isDuplicateMessage(content, type, false, !isMessageForOtherTask, occurrenceIdentity)
    // Shared by both dag_execution shapes this handler processes below (the
    // modern trace_event-wrapped one, and the legacy bare "dag_execution"
    // message type) - duplicating this logic per call site is exactly how a
    // past version of this fix ended up only covering one of the two and
    // missing the other, so it stays a single function both branches call.
    // A turn_id present on BOTH sides that DIFFERS means this event belongs
    // to a genuinely different DAG execution - e.g. turn 2's DAG starting
    // while turn 1's dagExecution/steps are still in state because
    // sendMessage's RESET_DAG_STATE guard raced and lost. Only that specific
    // case counts as a new run: if turn_id is missing on EITHER side (an
    // older backend, a legacy/history event that predates this field, or
    // some other pattern that never sets it), there's no reliable identity to
    // compare, so this falls back to "not a new run" rather than guessing -
    // a false "new run" here would wipe live steps out from under a mid-run
    // legacy event, which is worse than occasionally missing a real
    // transition this fallback can't detect.
    const applyDagExecutionUpdate = (
      rawEventData: Record<string, unknown>,
      sourceTimestamp: string | number,
    ) => {
      // Malformed frame (absent/unknown phase): drop the WHOLE update -
      // including its steps - before any dispatch, matching the normalizer's
      // own contract. Applying the steps but not the execution object would
      // leave the two halves of DAG state describing different events.
      if (typeof rawEventData.phase !== "string" || !DAG_EXECUTION_PHASES.has(rawEventData.phase)) {
        return
      }
      const incomingTurnId = (rawEventData as { turn_id?: string }).turn_id
      const trackedTurnId = currentState.dagExecution?.turn_id
      const isNewRun = Boolean(incomingTurnId) && Boolean(trackedTurnId) && incomingTurnId !== trackedTurnId
      const steps = stepsFromPlanData(rawEventData, isNewRun ? [] : currentState.steps)
      if (steps) {
        dispatch({ type: "SET_STEPS", payload: steps })
      } else if (isNewRun) {
        // This specific event (e.g. a bare "planning"/"replanning" phase
        // update with no steps field) doesn't itself carry step data, but
        // it's still the first event of a new run - the prior run's steps
        // must not linger just because this event happened not to include a
        // fresh list to replace them with.
        dispatch({ type: "SET_STEPS", payload: [] })
      }
      // The backend's dag_execution payload (dag.py's on_dag_execution) never
      // actually carries a created_at - only completed_step_count/
      // plan_step_count/steps. Without a fallback here, the DAG run never
      // gets a stable "started at" timestamp, so the Progress panel's total
      // elapsed time never renders. Keep whatever created_at this run
      // already established (planning's first event sets it; later phase
      // updates for the SAME run must not reset it) whenever turn_id says
      // this is a continuation; use this event's own timestamp for a
      // genuinely new run instead of inheriting the prior run's.
      const dagCreatedAt =
        !isNewRun
          ? currentState.dagExecution?.created_at
            ?? (rawEventData as { created_at?: string | number }).created_at
            ?? sourceTimestamp
          : (rawEventData as { created_at?: string | number }).created_at
            ?? sourceTimestamp
      // Same gap as created_at above: the backend's dag_execution payload
      // never carries updated_at either, so without this fallback every
      // phase update after the first would leave it undefined despite
      // DAGExecution declaring it required - center-panel.tsx uses it both
      // as a React key and as displayed text. Unlike created_at, this
      // always takes the event's own timestamp - it's meant to track "last
      // touched," not "run started," so a continuation must still advance it.
      const dagUpdatedAt =
        (rawEventData as { updated_at?: string | number }).updated_at ?? sourceTimestamp
      // SET_DAG_EXECUTION replaces the whole object, so a turn_id-less
      // continuation event (a legacy/history shape mid-run) would otherwise
      // silently WIPE the tracked turn_id - and once it's gone, the next
      // genuinely new run's differing turn_id can no longer be recognized as
      // new (the both-sides-present rule above would see tracked=undefined
      // and fall back to "not a new run"), inheriting the old run's
      // created_at and steps. Carrying the tracked id forward through such
      // events keeps the run's identity stable for as long as it lives.
      // (When incomingTurnId is present it always wins - including on a new
      // run, where it IS the new identity; isNewRun can never be true while
      // incomingTurnId is absent, so the fallback only ever applies to
      // continuations.)
      const dagTurnId = incomingTurnId ?? trackedTurnId
      // Can't be null here (the phase was already validated at the top of
      // this function), but the normalizer's null-on-malformed contract is
      // typed, so honor it rather than asserting it away.
      const normalizedDagExecution = normalizeDagExecutionPayload({
        ...rawEventData,
        created_at: dagCreatedAt,
        updated_at: dagUpdatedAt,
        turn_id: dagTurnId,
      })
      if (normalizedDagExecution) {
        dispatch({ type: "SET_DAG_EXECUTION", payload: normalizedDagExecution })
      }
    }
    // Activity events (dag_execute_start, llm_call_start, react_task_start,
    // skill_select_start) optimistically infer "the task is running" from the
    // fact that work is happening. During a history load those same events
    // are REPLAYED for work that already finished - letting them flip an
    // authoritative terminal or paused task back to "running" makes the page
    // briefly believe historical work is live again. For a paused task this
    // also clears its restored auto-resume notice before task_paused is
    // reasserted. Their status during history load comes from task_info and
    // explicit status events, never from inferred liveness. Keyed off the REF, not
    // state.isHistoryLoading: several handlers clear the state flag early
    // (to show live UI as soon as anything renders) while the ref stays true
    // until historical_data_complete actually arrives. Scoped to terminal
    // and paused tasks only, so a stuck ref (a backend that never sends
    // historical_data_complete) can't permanently suppress liveness for a
    // task that was never finished or paused in the first place.
    const dispatchInferredRunningStatus = () => {
      if (
        isHistoricalDataLoadingRef.current
        && (
          isTerminalTaskStatus(currentState.currentTask?.status)
          || currentState.currentTask?.status === "paused"
        )
      ) return
      dispatch({ type: "UPDATE_TASK_STATUS", payload: { status: "running" } })
      dispatch({ type: "SET_PROCESSING", payload: true })
    }
    // If we're in replay mode, don't process immediately - collect for delayed playback
    if (
      !options?.skipHistory
      && shouldBufferMessageForHistoricalReplay({
        isReplaying: currentState.isReplaying,
        isHistoryLoading: currentState.isHistoryLoading || isHistoricalDataLoadingRef.current,
        message,
      })
    ) {
      // A stray background task's message reaching this branch would
      // otherwise get buffered into the VIEWED task's own replay cache (and
      // its historical_data_complete would flip isHistoricalDataLoadingRef -
      // a plain ref, not gated by the dispatch wrapper below - ending the
      // viewed task's history load early based on a different task's data).
      // None of this branch's effects belong to any task but the one
      // currently loading history, so drop it outright rather than only
      // filtering the dispatches inside it.
      if (isMessageForOtherTask) return
      // Add to replay cache
      dispatch({ type: "ADD_TO_REPLAY_CACHE", payload: message })

      // If this is historical_data_complete, start the delayed playback
      const isHistoricalComplete =
        getWebSocketEventType(message) === "historical_data_complete"

      if (isHistoricalComplete) {
        isHistoricalDataLoadingRef.current = false
        dispatch({ type: "SET_HISTORY_LOADING", payload: false })
        dispatch({ type: "SYNC_PROCESSING_STATUS" })
        // Add a small delay to ensure all events are collected before starting playback
        setTimeout(() => {
          startDelayedPlaybackRef.current()
        }, 500) // 500ms delay to collect remaining events
      }

      return
    }

    const controlEnvelope = extractTaskControlEnvelope(message)
    if (controlEnvelope.isStateEvent && controlEnvelope.taskId !== undefined) {
      if (
        !acceptTaskControlVersion(
          message,
          controlEnvelope,
          taskStateVersionsRef.current,
        )
      ) return

      // A late event may have an old semantic type (for example
      // ``task_paused``) after a newer run is already RUNNING. The backend
      // rewrites its state tuple to the canonical row; apply only that tuple
      // and skip the stale event-specific side effects.
      if (!taskEventMatchesControlState(message, controlEnvelope)) {
        if (controlEnvelope.status) {
          dispatch({
            type: "UPDATE_TASK_STATUS",
            payload: {
              status: controlEnvelope.status,
              runId: controlEnvelope.runId,
              stateVersion: controlEnvelope.stateVersion,
              controlState: controlEnvelope.controlState,
            },
          })
        }
        return
      }
    }

    // Normal message processing when not in replay mode
    if (isFinalAnswerStreamEventType(message.type)) {
      const payload = getFinalAnswerStreamActionPayload({
        eventType: message.type,
        eventData: message,
        eventId: message.event_id,
        executionSequence: message.execution_sequence,
        timestamp: message.timestamp,
        fallbackMessageId: generateMessageId("msg-final-answer"),
      })
      if (payload) {
        dispatch({ type: "UPSERT_STREAMING_FINAL_ANSWER", payload })
      }
      return
    }

    switch (message.type) {
      case "trace_event":
        const traceEventData = (message.data ?? {}) as any

        // Check if this has the expected structure with event_type
        // event_type can be in message.event_type (new format) or traceEventData.event_type (old format)
        const eventType = message.event_type || traceEventData.event_type

        if (eventType) {
          // eventData should be the data field from traceEventData, but also include top-level fields
          const eventData = {
            ...(traceEventData.data || traceEventData || {}),
            step_id: message.step_id || traceEventData.step_id || (traceEventData.data || {}).step_id,
            task_id: message.task_id || traceEventData.task_id || (traceEventData.data || {}).task_id,
          }
          const isDelegatedChildEvent =
            eventData.source === "xagent-agent-tool-child"
          const addDelegatedChildTraceEvent = () => {
            dispatch({
              type: "ADD_TRACE_EVENT",
              payload: {
                event_id: message.event_id || eventData.event_id || generateMessageId("trace-agent-child"),
                event_type: eventType,
                step_id: message.step_id || eventData.step_id,
                timestamp: message.timestamp?.toString() || Date.now().toString(),
                data: eventData,
              }
            })
          }

          // V2 completion/AI facts are timeline entries. The owning durable
          // assistant message supplies the bubble, with an explicit stream alias.
          if (eventData.display === "timeline" && (eventType === "task_completion" || eventType === "ai_message")) {
            dispatch({ type: "ADD_TRACE_EVENT", payload: {
              event_id: message.event_id || traceEventData.event_id,
              event_type: eventType,
              step_id: message.step_id || eventData.step_id,
              timestamp: message.timestamp,
              data: eventData,
            } })
            return
          }

          // Handle structured trace events
          if (eventType === "task_info") {
            const taskData = eventData as Record<string, unknown>
            const taskId = parseInteger(taskData.id)
            if (taskId === undefined || taskId <= 0) return
            const task = taskFromTaskInfoData(taskData, taskId)
            const taskStatus = task.status
            console.log('📥 Received task_info event:', {
              taskData,
              status: taskData.status,
              statusType: typeof taskData.status
            })

            // Store pending task for auto-execution - a plain ref write, not
            // gated by the dispatch wrapper's task scoping, so a stray
            // background task's own pending task_info must not overwrite
            // what's about to be auto-sent for the task actually being
            // viewed/connected. A task whose first message went to the first
            // gate is never armed: its description is that message (sendMessage).
            if (taskStatus === 'pending' && task.description && !isMessageForOtherTask && taskId !== firstGateTaskIdRef.current) {
              pendingTaskToExecuteRef.current = { description: task.description }
              console.log('💾 Stored pending task for auto-execution:', taskData.description)
            }

            // Check if status changed and trigger update if so
            if (currentState.currentTask?.id === task.id && currentState.currentTask?.status !== taskStatus) {
              dispatch({ type: "TRIGGER_TASK_UPDATE" })
            }

            dispatch({
              type: "SET_CURRENT_TASK",
              payload: task,
            })
            // Check if this is a new task (created within last 5 seconds)
            // If so, we don't expect historical messages, so stop loading
            // We do NOT stop loading here for new tasks anymore.
            // We wait for the user_message event or the timeout to handle it.
            // This prevents the empty state flash when task_info arrives before user_message.
          } else if (eventType === "dag_execution") {
            dispatch({ type: "SET_HISTORY_LOADING", payload: false })
            applyDagExecutionUpdate(eventData, message.timestamp)
          } else if (eventType === "dag_step_info") {
            dispatch({ type: "SET_HISTORY_LOADING", payload: false })
            const stepInfo = eventData
            const step: StepExecution = {
              id: stepInfo.id,
              name: stepInfo.name || stepInfo.id,
              description: stepInfo.description || "",
              status: stepInfo.status,
              tool_names: stepInfo.tool_name ? [stepInfo.tool_name] : stepInfo.tool_names || [],
              dependencies: stepInfo.dependencies || [],
              started_at: stepInfo.started_at,
              completed_at: stepInfo.completed_at,
              result_data: stepInfo.result_data,
              step_data: stepInfo.step_data,
              file_outputs: stepInfo.file_outputs || [],
              conditional_branches: stepInfo.conditional_branches || {},
              required_branch: stepInfo.required_branch || null,
              is_conditional: stepInfo.is_conditional || false,
            }
            dispatch({ type: "ADD_STEP", payload: step })
          }

          // User Message Events
          else if (eventType === "user_message") {
            // A delegated Agent's task prompt is execution detail, not another
            // user turn in the parent Workforce conversation. Keep it in the
            // trace store so the Agent inspector can still render it live.
            if (isDelegatedChildEvent) {
              addDelegatedChildTraceEvent()
              return
            }
            dispatch({ type: "SET_HISTORY_LOADING", payload: false })
            const messageContent = eventData.message || eventData.content || ""
            const userMessageId = stableUserMessageId(
              eventData,
              message.event_id || traceEventData.event_id,
            )

            // Debug log
            console.log('🔍 User message debug:', {
              eventData,
              messageContent,
              hasMessage: !!eventData.message,
              hasContent: !!eventData.content,
              eventType,
              fullEvent: message,
              messageId: message.event_id,
              timestamp: message.timestamp
            })

            // Modern user-message events carry a stable turn_id (or at least
            // an event_id). The reducer reconciles those identities across
            // live delivery, optimistic rendering, and history replay. Only
            // legacy events without either identity fall back to short-lived
            // content-based deduplication.
            const isDuplicate = userMessageId === null
              ? isDuplicateMessageForViewedTask(messageContent, 'user-message')
              : false
            console.log('🔍 Duplicate check:', {
              messageContent,
              isDuplicate,
              recentMessages: Array.from(recentMessagesRef.current)
            })

            if (isDuplicate) {
              console.log('⚠️ User message filtered as duplicate:', messageContent)
              return
            }

            // Extract files from context.state.file_info (based on the actual WS event structure)
            let files = eventData.files || []
            if (eventData.context && eventData.context.state && eventData.context.state.file_info) {
              files = eventData.context.state.file_info
            }

            console.log('📁 Files extracted:', files)
            console.log('🔍 Context structure:', eventData.context)
            console.log('🔍 State structure:', eventData.context?.state)

            // Create message content with file attachments
            let content: React.ReactNode = messageContent

            if (files.length > 0) {
              content = (
                <UserMessageContent
                  message={messageContent}
                  files={files}
                  onPreview={options?.filesDisabled ? undefined : (file, previewFiles) => {
                    const currentFileId = file.file_id || ""
                    const normalizedFiles = previewFiles.map((previewFile) => ({
                      fileId: previewFile.file_id || "",
                      fileName: previewFile.name,
                    })).filter((item) => !!item.fileId)

                    if (!currentFileId) {
                      return
                    }
                    dispatch({
                      type: "OPEN_FILE_PREVIEW",
                      payload: {
                        fileId: currentFileId,
                        fileName: file.name,
                        files: normalizedFiles,
                        index: normalizedFiles.findIndex((previewFile) => previewFile.fileId === currentFileId)
                      }
                    })
                  }}
                />
              )
            }

            console.log('📤 Dispatching user message:', {
              content,
              filesCount: files.length,
              timestamp: message.timestamp,
              messageId: generateMessageId("msg-user")
            })

            const messagePayload = {
              id: userMessageId || generateMessageId("msg-user"),
              role: "user" as const,
              content: content,
              timestamp: message.timestamp,
              isOptimistic: false,
            }

            console.log('📤 Message payload:', messagePayload)

            dispatch({
              type: "ADD_MESSAGE",
              payload: messagePayload
            })

            console.log('✅ User message dispatched successfully')
          }

          else if (isFinalAnswerStreamEventType(eventType)) {
            const payload = getFinalAnswerStreamActionPayload({
              eventType,
              eventData,
              eventId: message.event_id,
              executionSequence: message.execution_sequence,
              timestamp: message.timestamp,
              fallbackMessageId: generateMessageId("msg-final-answer"),
            })
            if (!payload) {
              return
            }
            dispatch({ type: "UPSERT_STREAMING_FINAL_ANSWER", payload })
          }

          // Agent progress messages belong in the execution timeline, not the chat transcript.
          else if (eventType === "agent_progress") {
            dispatch({
              type: "ADD_TRACE_EVENT",
              payload: {
                event_id: message.event_id || eventData.event_id || generateMessageId("trace-agent-progress"),
                event_type: eventType,
                step_id: message.step_id || eventData.step_id,
                timestamp: message.timestamp?.toString() || Date.now().toString(),
                data: eventData,
              }
            })
          }

          // Workforce delegation events stay in the manager timeline as compact
          // summaries. Their child traces are fetched only after the user opens
          // the agent execution drawer.
          else if (
            eventType === "workforce_delegation_start" ||
            eventType === "workforce_delegation_end" ||
            eventType === "workforce_delegation_error"
          ) {
            dispatch({
              type: "ADD_TRACE_EVENT",
              payload: {
                event_id: message.event_id || eventData.event_id || generateMessageId("trace-workforce-delegation"),
                event_type: eventType,
                step_id: message.step_id || eventData.step_id,
                timestamp: message.timestamp?.toString() || Date.now().toString(),
                data: eventData,
              }
            })
          }

          // Agent-to-user messages, including ask_user_question prompts.
          else if (eventType === "agent_message" || eventType === "ai_message") {
            // Child Agent output belongs exclusively to the on-demand Agent
            // inspector. Rendering it as parent chat content makes live state
            // disagree with historical replay and can expose child clarifiers
            // as if the Workforce manager asked them.
            if (isDelegatedChildEvent) {
              addDelegatedChildTraceEvent()
              return
            }
            const rawMessageContent = eventData.message || eventData.content || ""
            const messageContent =
              typeof rawMessageContent === "string"
                ? unwrapFinalAnswerContent(rawMessageContent)
                : rawMessageContent
            if (!messageContent) {
              return
            }
            const interactions = normalizeInteractions(eventData.metadata?.interactions)
            const interactionRequestId = typeof eventData.request_id === "string"
              ? eventData.request_id
              : undefined
            const isAgentMessage = eventType === "agent_message"
            const isAiMessage = eventType === "ai_message"
            const expectsUserResponse =
              isAgentMessage &&
              eventData.expect_response === true
            const agentMessageDisplay = eventData.display || eventData.metadata?.display
            const isExplicitTranscriptMessage =
              agentMessageDisplay === "chat" ||
              eventData.source === "chat_history" ||
              eventData.role === "assistant"
            const isTimelineAgentMessage =
              eventType === "agent_message" &&
              !isExplicitTranscriptMessage &&
              agentMessageDisplay === "timeline"
            if (isTimelineAgentMessage) {
              dispatch({
                type: "ADD_TRACE_EVENT",
                payload: {
                  event_id: message.event_id || eventData.event_id || generateMessageId("trace-agent-progress"),
                  event_type: "agent_progress",
                  step_id: message.step_id || eventData.step_id,
                  timestamp: message.timestamp?.toString() || Date.now().toString(),
                  data: eventData,
                }
              })
              return
            }
            const shouldHideAgentMessage =
              isAgentMessage &&
              eventData.visible === false
            // Replayed questions belong in the transcript, but must not undo
            // the settled status/outcome already restored by task_info.
            if (expectsUserResponse && !(
              isHistoricalDataLoadingRef.current &&
              isTerminalTaskStatus(currentState.currentTask?.status)
            )) {
              dispatch({
                type: "UPDATE_TASK_STATUS",
                payload: {
                  status: "waiting_for_user",
                  waitingQuestion: messageContent,
                  waitingInteractions: interactions.length > 0 ? interactions : undefined,
                  waitingRequestId: interactionRequestId,
                }
              })
            }
            const canonicalMessageId = typeof eventData.message_id === "string"
              && (eventData.message_id.startsWith("execution_message_") || eventData.message_id.startsWith("final_answer_"))
              ? eventData.message_id : undefined
            const streamMessageId = canonicalMessageId?.startsWith("final_answer_")
              ? canonicalMessageId : isAiMessage
                ? getFinalAnswerStreamMessageId(eventData)
                : undefined
            if (shouldHideAgentMessage) {
              return
            }
            const agentMessageId = isAgentMessage
              ? stableAssistantMessageId(
                message.event_id || traceEventData.event_id || eventData.event_id,
              )
              : null
            // Identical refusals can belong to different turns. The persisted
            // message ID also pairs the live refusal with its history replay.
            const identifiedRefusal = eventData.message_type === "input_review_rejected"
              && agentMessageId !== null
            if (!canonicalMessageId && !streamMessageId && !identifiedRefusal && isDuplicateMessageForViewedTask(
              messageContent,
              'agent-message',
              isAgentMessage ? interactionRequestId : undefined,
            )) {
              return
            }
            const msgId = canonicalMessageId ?? agentMessageId ?? generateMessageId("msg-agent")
            dispatch({
              type: "ADD_MESSAGE",
              payload: {
                id: msgId,
                role: "assistant",
                content: messageContent,
                rawContent: messageContent,
                timestamp: message.timestamp,
                // Legacy chat_history replay rows carry no canonical id, so
                // the failure provenance must win over the id-based status.
                status: eventData.message_type === "task_failure" ? "failed"
                  : canonicalMessageId ? "completed"
                  : eventData.status === "completed" ? "completed" : "running",
                isResult: true,
                streamMessageId,
                executionSequence: message.execution_sequence,
                interactions: interactions.length > 0 ? interactions : undefined,
                interactionRequestId,
              }
            })
            // The refusal bubble is settled. The task's terminal frame owns
            // the overall status and blocked outcome.
            if (eventData.status === "completed" && !identifiedRefusal) {
              dispatch({ type: "UPDATE_TASK_STATUS", payload: { status: "completed" } })
              dispatch({ type: "SET_PROCESSING", payload: false })
            }
          }

          // DAG Plan Events
          else if (eventType === "dag_plan_start") {
            dispatch({ type: "SET_HISTORY_LOADING", payload: false })
            const phase = eventData.phase || "planning"
            const iteration = eventData.iteration || 1
            const content = (
              <>
                <FileText className="h-4 w-4 inline mr-2" />
                {t('agent.logs.event.messages.planStart', { phase })}
              </>
            )

            // Set DAG execution state to planning phase (only if not already executing or completed)
            if (!currentState.dagExecution || currentState.dagExecution.phase === "planning") {
              const dagExecution = normalizeDagExecutionPayload({
                phase,
                current_plan: {},
                created_at: message.timestamp,
                updated_at: message.timestamp,
              })

              // Use consistent string format for deduplication
              const dedupKey = `plan-start:${phase}`
              if (!isDuplicateMessageForViewedTask(dedupKey, 'dag-plan-start')) {
                dispatch({
                  type: "ADD_MESSAGE",
                  payload: {
                    id: generateMessageId("msg-plan-start"),
                    role: "assistant",
                    content,
                    timestamp: message.timestamp,
                    status: "completed",
                  }
                })

                // Set DAG execution state to show loading state - unless the
                // event carried an unrecognized phase string, in which case
                // the normalizer returned null and only the chat message
                // above is kept (fabricating an "executing" run out of an
                // unknown phase is exactly what the normalizer exists to
                // prevent).
                if (dagExecution) {
                  dispatch({ type: "SET_DAG_EXECUTION", payload: dagExecution })
                }
              }
            }
          } else if (eventType === "dag_plan_end") {
            const stepsCount = eventData.steps_count || 0
            const planId = eventData.plan_id || "unknown"
            const planData = eventData.plan_data || {}

            const content = (
              <>
                <CheckCircle className="h-4 w-4 inline mr-2 text-green-500" />
                {t('agent.logs.event.messages.planEnd', { planId, stepsCount })}
                {currentState.planMemoryInfo && (
                  <div className="mt-2">
                    <CollapsibleSection
                      title={t('agent.planDetails.memory.title')}
                      icon={<Brain className="h-4 w-4" />}
                      badge={t('agent.planDetails.badge.memory')}
                    >
                      <div className="grid grid-cols-2 gap-2 text-xs">
                        <div className="flex items-center gap-1 p-2 bg-muted/30 rounded">
                          <Search className="h-3 w-3" />
                          <span>{t('agent.planDetails.memory.stats.found', { count: currentState.planMemoryInfo.memoriesFound })}</span>
                        </div>
                        <div className="flex items-center gap-1 p-2 bg-muted/30 rounded">
                          <Target className="h-3 w-3" />
                          <span>{t('agent.planDetails.memory.stats.used', { count: currentState.planMemoryInfo.memoriesUsed })}</span>
                        </div>
                      </div>
                      {currentState.planMemoryInfo.enhancedGoal && (
                        <div className="mt-2">
                          <div className="text-xs font-medium text-muted-foreground mb-1">{t('agent.planDetails.memory.enhancedGoalTitle')}</div>
                          <div className="text-xs bg-blue-500/10 p-2 rounded border border-blue-500/20">
                            {currentState.planMemoryInfo.enhancedGoal}
                          </div>
                        </div>
                      )}
                      {currentState.planMemoryInfo.memories && currentState.planMemoryInfo.memories.length > 0 && (
                        <div className="mt-2">
                          <div className="text-xs font-medium text-muted-foreground mb-1">{t('agent.planDetails.memory.relatedTitle')}</div>
                          <div className="space-y-1">
                            {currentState.planMemoryInfo.memories.map((memory, index) => (
                              <div
                                key={index}
                                className="text-xs p-2 bg-muted/20 rounded border border-border/50"
                              >
                                <div className="flex items-start gap-1">
                                  <Info className="h-3 w-3 mt-0.5 text-blue-400 flex-shrink-0" />
                                  <span className="whitespace-pre-wrap">{memory.content}</span>
                                </div>
                                {memory.category && (
                                  <Badge variant="outline" className="text-xs mt-1">
                                    {memory.category}
                                  </Badge>
                                )}
                              </div>
                            ))}
                          </div>
                        </div>
                      )}
                    </CollapsibleSection>
                  </div>
                )}
              </>
            )

            // Process step data in the plan, including dependencies
            const steps = stepsFromPlanData(planData, currentState.steps)
            if (steps) {
              dispatch({ type: "SET_STEPS", payload: steps })
            }

            const dedupKey = t('agent.logs.event.messages.planEnd', { planId, stepsCount })
            if (!isDuplicateMessageForViewedTask(dedupKey, 'plan-end')) {
              dispatch({
                type: "ADD_MESSAGE",
                payload: {
                  id: generateMessageId("msg-plan-end"),
                  role: "assistant",
                  content,
                  timestamp: message.timestamp,
                  status: "completed",
                }
              })

              // Update DAG execution state to executing phase (only if not already completed or failed)
              if (currentState.dagExecution && currentState.dagExecution.phase !== "completed" && currentState.dagExecution.phase !== "failed") {
                const updatedDAGExecution = {
                  ...currentState.dagExecution,
                  phase: "executing" as const,
                  current_plan: planData,
                  updated_at: message.timestamp,
                }
                dispatch({ type: "SET_DAG_EXECUTION", payload: updatedDAGExecution })
              }
            }
          }

          // DAG Execution Events
          else if (eventType === "dag_execute_start") {
            const iteration = eventData.iteration || 1
            const taskPreview = eventData.task_preview || t('agent.header.badge.task')

            // Set processing state to true when task execution starts
            dispatchInferredRunningStatus()

            // Update DAG execution state to executing phase
            if (currentState.dagExecution) {
              const updatedDAGExecution = {
                ...currentState.dagExecution,
                phase: "executing" as const,
                updated_at: message.timestamp,
              }
              dispatch({ type: "SET_DAG_EXECUTION", payload: updatedDAGExecution })
            } else {
              const dagExecution: DAGExecution = {
                phase: "executing" as const,
                current_plan: {},
                created_at: message.timestamp,
                updated_at: message.timestamp,
              }
              dispatch({ type: "SET_DAG_EXECUTION", payload: dagExecution })
            }

            // Use consistent string format for deduplication
            const dedupKey = t('agent.logs.event.messages.taskStart', { iteration })
            if (!isDuplicateMessageForViewedTask(dedupKey, 'dag-execute-start')) {
              dispatch({
                type: "ADD_MESSAGE",
                payload: {
                  id: generateMessageId("msg-exec-start"),
                  role: "assistant",
                  content: (
                    <>
                      <Zap className="h-4 w-4 inline mr-2 text-yellow-500" />
                      {t('agent.logs.event.messages.taskStart', { iteration })}
                      <br />
                      <FileText className="h-4 w-4 inline mr-2 mt-1 text-cyan-500" />
                      {t('agent.logs.event.messages.taskDesc', { taskPreview })}
                    </>
                  ),
                  timestamp: message.timestamp,
                  status: "completed",
                }
              })
            }
          } else if (eventType === "dag_execute_end") {
            console.log("DEBUG: Received dag_execute_end event:", eventData)
            const iteration = eventData.iteration || 1
            const taskPreview = eventData.task_preview || t('agent.header.badge.task')
            console.log(`DEBUG: Processing dag_execute_end - GLOBAL iteration: ${iteration}, taskPreview: ${taskPreview}`)

            // Clear processing state when task completes
            dispatch({ type: "SET_PROCESSING", payload: false })

            // Update DAG execution state to completed phase
            if (currentState.dagExecution) {
              const updatedDAGExecution = {
                ...currentState.dagExecution,
                phase: "completed" as const,
                updated_at: message.timestamp,
              }
              dispatch({ type: "SET_DAG_EXECUTION", payload: updatedDAGExecution })
            }

            // Use consistent string format for deduplication
            const dedupKey = t('agent.logs.event.messages.taskEnd', { iteration })
            if (!isDuplicateMessageForViewedTask(dedupKey, 'dag-execute-end')) {
              dispatch({
                type: "ADD_MESSAGE",
                payload: {
                  id: generateMessageId("msg-exec-end"),
                  role: "assistant",
                  content: (
                    <>
                      <CheckCircle className="h-4 w-4 inline mr-2 text-green-500" />
                      {t('agent.logs.event.messages.taskEnd', { iteration })}
                      <br />
                      <FileText className="h-4 w-4 inline mr-2 mt-1 text-cyan-500" />
                      {t('agent.logs.event.messages.taskDesc', { taskPreview })}
                    </>
                  ),
                  timestamp: message.timestamp,
                  status: "completed",
                }
              })
            }
          }
          // Compact Events - All occur within a step, displayed in the corresponding step in the right panel
          else if (eventType === "action_start_compact") {
            const stepId = eventData.step_id
            if (stepId) {
              const traceEvent: TraceEvent = {
                event_id: generateMessageId(`compact-start-${stepId}`),
                event_type: eventType,
                step_id: stepId,
                timestamp: message.timestamp,
                data: {
                  action: t('agent.logs.event.actions.action_start_compact'),
                  message: t('agent.logs.event.messages.compactStart'),
                  compact_type: eventData.compact_type,
                  original_tokens: eventData.original_tokens,
                  threshold: eventData.threshold,
                  compact_model: eventData.compact_model,
                }
              }
              dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
            }
          } else if (eventType === "action_end_compact") {
            const stepId = eventData.step_id
            if (stepId) {
              const traceEvent: TraceEvent = {
                event_id: generateMessageId(`compact-end-${stepId}`),
                event_type: eventType,
                step_id: stepId,
                timestamp: message.timestamp,
                data: {
                  action: t('agent.logs.event.actions.action_end_compact'),
                  message: t('agent.logs.event.messages.compactCompleted'),
                  compact_type: eventData.compact_type,
                  original_tokens: eventData.original_tokens,
                  compacted_tokens: eventData.compacted_tokens,
                  compression_ratio: eventData.compression_ratio,
                  compact_model: eventData.compact_model,
                  error: eventData.error,
                }
              }
              dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })

              // Surface a standalone system notice in the conversation so the
              // user sees that context was compacted without expanding the process.
              const noticeText = t('agent.logs.event.messages.compactNotice', {
                original: eventData.original_tokens ?? '?',
                compacted: eventData.compacted_tokens ?? '?',
              })
              // Key by step + event timestamp so distinct compactions (even in
              // the same step, or with identical token counts) each show, while
              // a re-dispatched same event is still deduped.
              const noticeKey = `compact-notice-${stepId}-${message.timestamp}`
              if (!isDuplicateMessageForViewedTask(noticeText, noticeKey)) {
                dispatch({
                  type: "ADD_MESSAGE",
                  payload: {
                    id: generateMessageId(noticeKey),
                    role: "assistant",
                    content: noticeText,
                    timestamp: message.timestamp,
                    status: "completed",
                    isSystemNotice: true,
                  }
                })
              }
            }
          }

          // DAG Step Events
          else if (eventType === "dag_step_start") {
            const stepName = eventData.step_name || eventData.name || eventData.title || `${t('agent.logs.event.messages.execStepPrefix')}${eventData.step_id || t('common.errors.unknown')}`

            // dag_step_start has step_id, should update the right-side step data, do not display message on the left
            // Find existing step first, preserve dependencies
            const existingStep = currentState.steps.find(s => s.id === (message.step_id || eventData.step_id || stepName))
            const step: StepExecution = {
              id: message.step_id || eventData.step_id || stepName,
              name: stepName,
              description: eventData.description || "",
              status: "running",
              tool_names: eventData.tool_name ? [eventData.tool_name] : eventData.tool_names || [],
              dependencies: eventData.dependencies || existingStep?.dependencies || [],
              started_at: eventData.started_at || message.timestamp,
              completed_at: eventData.completed_at,
              result_data: eventData.result_data,
              step_data: eventData.step_data,
              file_outputs: eventData.file_outputs || [],
              conditional_branches: eventData.conditional_branches || existingStep?.conditional_branches || {},
              required_branch: eventData.required_branch ?? existingStep?.required_branch ?? null,
              is_conditional: eventData.is_conditional ?? existingStep?.is_conditional ?? false,
            }
            dispatch({ type: "ADD_STEP", payload: step })

            // Also add to traceEvents for displaying execution logs
            const traceEvent: TraceEvent = {
              event_id: generateMessageId(`trace-step-start`),
              event_type: eventType,
              step_id: message.step_id || eventData.step_id || stepName,
              timestamp: message.timestamp,
              data: {
                action: t('agent.logs.event.actions.dag_step_start'),
                step_name: stepName,
                description: eventData.description,
                tool_names: eventData.tool_name ? [eventData.tool_name] : eventData.tool_names || [],
                started_at: eventData.started_at || message.timestamp,
              }
            }
            dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
          } else if (eventType === "dag_step_end") {
            const stepName = eventData.step_name || eventData.name || eventData.title || `${t('agent.logs.event.messages.execStepPrefix')}${eventData.step_id || t('common.errors.unknown')}`
            console.log('✅ dag_step_end:', stepName, JSON.stringify(message))
            const resultData = eventData.result_data ?? eventData.result

            // dag_step_end has step_id, should update right-side step data, do not display message on the left
            const stepId = message.step_id || eventData.step_id || stepName
            const existingStep = currentState.steps.find(s => s.id === stepId)
            const step: StepExecution = {
              id: stepId,
              name: stepName,
              description: eventData.description || "",
              status: eventData.status || "completed",
              tool_names: eventData.tool_name ? [eventData.tool_name] : eventData.tool_names || [],
              dependencies: eventData.dependencies || existingStep?.dependencies || [],
              // Don't override started_at from end event to preserve the original start time
              started_at: undefined, // Let the reducer handle preserving existing started_at
              completed_at: eventData.completed_at || message.timestamp,
              result_data: resultData,
              step_data: eventData.step_data,
              file_outputs: eventData.file_outputs || [],
              conditional_branches: eventData.conditional_branches || {},
              required_branch: eventData.required_branch || null,
              is_conditional: eventData.is_conditional || false,
            }
            dispatch({ type: "ADD_STEP", payload: step })

            // Also add to traceEvents for displaying execution logs
            // Preserve the failed outcome in the display event vocabulary;
            // dag_step_end is emitted by the backend for both outcomes.
            const displayEventType = step.status === "failed" ? "dag_step_failed" : eventType
            const traceEvent: TraceEvent = {
              event_id: generateMessageId(`trace-step-end`),
              event_type: displayEventType,
              step_id: message.step_id || eventData.step_id || stepName,
              timestamp: message.timestamp,
              data: {
                action: t(displayEventType === "dag_step_failed"
                  ? 'agent.logs.event.actions.dag_step_failed'
                  : 'agent.logs.event.actions.dag_step_end'),
                error: eventData.error,
                step_name: stepName,
                description: eventData.description,
                tool_names: eventData.tool_name ? [eventData.tool_name] : eventData.tool_names || [],
                completed_at: eventData.completed_at || message.timestamp,
                result: resultData,
                result_data: resultData,
                step_data: eventData.step_data,
                file_outputs: eventData.file_outputs || [],
              }
            }
            dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
          } else if (eventType === "dag_step_failed") {
            const stepName = eventData.step_name || eventData.name || eventData.title || `${t('agent.logs.event.messages.execStepPrefix')}${eventData.step_id || t('common.errors.unknown')}`
            const stepId = message.step_id || eventData.step_id || stepName
            const existingStep = currentState.steps.find(s => s.id === stepId)

            // Update DAG execution state to failed
            if (currentState.dagExecution) {
              const updatedDAGExecution = {
                ...currentState.dagExecution,
                phase: "failed" as const,
                updated_at: message.timestamp,
              }
              dispatch({ type: "SET_DAG_EXECUTION", payload: updatedDAGExecution })
            }

            // Update step status
            const step: StepExecution = {
              id: stepId,
              name: stepName,
              description: eventData.description || "",
              status: "failed",
              tool_names: eventData.tool_name ? [eventData.tool_name] : eventData.tool_names || [],
              dependencies: existingStep?.dependencies || [],
              started_at: eventData.started_at || existingStep?.started_at,
              completed_at: eventData.completed_at || message.timestamp,
              result_data: eventData.result_data,
              step_data: eventData.step_data,
              file_outputs: eventData.file_outputs || [],
              conditional_branches: eventData.conditional_branches || existingStep?.conditional_branches || {},
              required_branch: eventData.required_branch ?? existingStep?.required_branch ?? null,
              is_conditional: eventData.is_conditional ?? existingStep?.is_conditional ?? false,
            }
            dispatch({ type: "ADD_STEP", payload: step })

            // Add to left panel messages
            dispatch({
              type: "ADD_MESSAGE",
              payload: {
                id: generateMessageId("msg-step-failed"),
                role: "assistant",
                content: (
                  <>
                    <XCircle className="h-4 w-4 inline mr-2 text-red-500" />
                    {t('agent.logs.event.messages.stepFailed', { stepName })}
                  </>
                ),
                timestamp: message.timestamp,
                status: "failed",
              }
            })

            // Also add to traceEvents for displaying execution logs
            const traceEvent: TraceEvent = {
              event_id: generateMessageId(`trace-step-failed`),
              event_type: eventType,
              step_id: stepId,
              timestamp: message.timestamp,
              data: {
                action: t('agent.logs.event.actions.dag_step_failed'),
                step_name: stepName,
                description: eventData.description,
                tool_names: eventData.tool_name ? [eventData.tool_name] : eventData.tool_names || [],
                error: eventData.error,
                completed_at: eventData.completed_at || message.timestamp,
              }
            }
            dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
          } else if (eventType === "dag_step_skipped") {
            const stepName = eventData.step_name || eventData.name || eventData.title || `${t('agent.logs.event.messages.execStepPrefix')}${eventData.step_id || t('common.errors.unknown')}`
            dispatch({
              type: "ADD_MESSAGE",
              payload: {
                id: generateMessageId("msg-step-skipped"),
                role: "assistant",
                content: `${t('agent.logs.event.messages.stepSkipped', { stepName })}`,
                timestamp: message.timestamp,
                status: "completed",
              }
            })
          }

          // Task-level LLM Call Events - show as messages (these don't have step_id)
          else if (eventType === "task_start_llm") {
            const modelName = eventData.model_name || "LLM"
            const taskType = eventData.task_type || "LLM Call"

            // Special handling for final answer generation
            if (eventData.task_type === "final_answer_generation") {
              // Check for duplicate final_answer_generation start events
              const content = t('agent.logs.event.messages.finalAnswerGenerating')
              if (!isDuplicateMessageForViewedTask(content, 'final_answer_start')) {
                dispatch({
                  type: "ADD_MESSAGE",
                  payload: {
                    id: generateMessageId("msg-final-answer-start"),
                    role: "assistant",
                    content: (
                      <>
                        <Lightbulb className="h-4 w-4 inline mr-2 text-yellow-500" />
                        {content}
                      </>
                    ),
                    timestamp: message.timestamp,
                    status: "completed",
                  }
                })
              }
            } else if (eventData.task_type === "comprehensive_goal_check") {
              // Show goal check start message
              dispatch({
                type: "ADD_MESSAGE",
                payload: {
                  id: generateMessageId("msg-goal-check-start"),
                  role: "assistant",
                  content: (
                    <div className="flex items-center gap-2">
                      <Target className="h-4 w-4 text-blue-500" />
                      <span className="font-medium">{t('agent.logs.event.messages.goalCheckStart')}</span>
                    </div>
                  ),
                  timestamp: message.timestamp,
                  status: "completed",
                }
              })
            } else {
              dispatch({
                type: "ADD_MESSAGE",
                payload: {
                  id: generateMessageId("msg-task-llm-start"),
                  role: "assistant",
                  content: (
                    <>
                      <Bot className="h-4 w-4 inline mr-2" />
                      {t('agent.logs.event.messages.taskLLMStart', { taskType })}
                    </>
                  ),
                  timestamp: message.timestamp,
                  status: "completed",
                }
              })
            }
            // Task-level LLM Call End Events
          } else if (eventType === "task_end_llm") {
            const modelName = eventData.model_name || "LLM"
            const taskType = eventData.task_type || "LLM Call"

            // Special handling for final answer generation completion
            if (eventData.task_type === "final_answer_generation") {
              // Check for duplicate final_answer_generation end events
              const content = t('agent.logs.event.messages.finalAnswerCompleted')
              if (!isDuplicateMessageForViewedTask(content, 'final_answer_end')) {
                dispatch({
                  type: "ADD_MESSAGE",
                  payload: {
                    id: generateMessageId("msg-final-answer-end"),
                    role: "assistant",
                    content: (
                      <>
                        <CheckCircle className="h-4 w-4 inline mr-2 text-green-500" />
                        {content}
                      </>
                    ),
                    timestamp: message.timestamp,
                    status: "completed",
                  }
                })
              }
            } else if (eventData.task_type === "comprehensive_goal_check") {
              // Display comprehensive goal check results (only in end events)
              const goalAchieved = eventData.goal_achieved || false
              const goalReason = eventData.goal_reason || "No reason provided"
              const goalConfidence = eventData.goal_confidence || 0
              const memoryShouldStore = eventData.memory_should_store || false
              const memoryReason = eventData.memory_reason || "No memory reason provided"

              dispatch({
                type: "ADD_MESSAGE",
                payload: {
                  id: generateMessageId("msg-goal-check-result"),
                  role: "assistant",
                  content: (
                    <div className="space-y-2">
                      <div className="flex items-center gap-2">
                        {goalAchieved ? (
                          <CheckCircle className="h-4 w-4 text-green-500" />
                        ) : (
                          <XCircle className="h-4 w-4 text-red-500" />
                        )}
                        <span className="font-medium">
                          {t('agent.logs.event.messages.goalCheck')}: {goalAchieved ? t('agent.logs.event.messages.goalAchieved') : t('agent.logs.event.messages.goalNotAchieved')}
                        </span>
                        {goalConfidence > 0 && (
                          <span className="text-sm text-gray-500">
                            ({t('agent.logs.event.messages.confidence', { percent: (goalConfidence * 100).toFixed(0) })})
                          </span>
                        )}
                      </div>
                      {goalReason && (
                        <div className="text-sm text-gray-600 bg-gray-50 p-2 rounded">
                          {t('agent.logs.event.messages.reasonLabel', { goalReason })}
                        </div>
                      )}
                      {memoryShouldStore && (
                        <div className="text-sm text-blue-600 bg-blue-50 p-2 rounded">
                          <Brain className="h-3 w-3 inline mr-1" />
                          {t('agent.logs.event.messages.memoryWillStore', { memoryReason })}
                        </div>
                      )}
                    </div>
                  ),
                  timestamp: message.timestamp,
                  status: "completed",
                }
              })
            } else {
              dispatch({
                type: "ADD_MESSAGE",
                payload: {
                  id: generateMessageId("msg-task-llm-end"),
                  role: "assistant",
                  content: (
                    <>
                      <CheckCircle className="h-4 w-4 inline mr-2 text-green-500" />
                      {t('agent.logs.event.messages.taskLLMCompleted', { taskType })}
                    </>
                  ),
                  timestamp: message.timestamp,
                  status: "completed",
                }
              })
            }
          }

          // Step-level LLM Call Events - add to traceEvents for step execution logs
          else if (eventType === "llm_call_start") {
            dispatchInferredRunningStatus()
            if (Number.isFinite(eventData.context_tokens) && Number.isFinite(eventData.context_threshold) && eventData.context_threshold > 0) {
              dispatch({
                type: "SET_CONTEXT_USAGE",
                payload: { tokens: eventData.context_tokens, threshold: eventData.context_threshold },
              })
            }
            if (message.step_id) {
              const modelName = eventData.model_name || "LLM"
              const taskType = eventData.task_type || "LLM Call"

              // Add to traceEvents for step execution logs
              const traceEvent: TraceEvent = {
                event_id: generateMessageId(`trace-llm-start`),
                event_type: eventType,
                step_id: message.step_id,
                timestamp: message.timestamp,
                data: {
                  action: t('agent.logs.event.actions.llm_call_start'),
                  model_name: modelName,
                  task_type: taskType,
                  ...eventData
                }
              }
              dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
            }
          } else if (eventType === "llm_call_end") {
            if (message.step_id) {
              const modelName = eventData.model_name || "LLM"
              const taskType = eventData.task_type || "LLM Call"

              // Add to traceEvents for step execution logs
              const traceEvent: TraceEvent = {
                event_id: generateMessageId(`trace-llm-end`),
                event_type: eventType,
                step_id: message.step_id,
                timestamp: message.timestamp,
                data: {
                  action: t('agent.logs.event.actions.llm_call_end'),
                  model_name: modelName,
                  task_type: taskType,
                  ...eventData
                }
              }
              dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
            }
          }

          // LLM Call Info Events - these are step-level events
          else if (eventType === "llm_call_info") {
            const modelName = eventData.model_name || "LLM"
            const taskType = eventData.task_type || "LLM Call"

            if (!message.step_id) {
              dispatch({
                type: "ADD_MESSAGE",
                payload: {
                  id: generateMessageId("msg-llm-info"),
                  role: "assistant",
                  content: t('agent.logs.event.messages.planLLMSending', { modelName }),
                  timestamp: message.timestamp,
                  status: "completed",
                }
              })
            } else {
              // Add to traceEvents for step execution logs
              const traceEvent: TraceEvent = {
                event_id: generateMessageId(`trace-llm-info`),
                event_type: eventType,
                step_id: message.step_id,
                timestamp: message.timestamp,
                data: {
                  action: t('agent.logs.event.actions.llm_call_info'),
                  model_name: modelName,
                  task_type: taskType,
                  ...eventData
                }
              }
              dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
            }
          }

          // LLM Call Result Events - these are step-level events
          else if (eventType === "llm_call_result") {
            const modelName = eventData.model_name || "LLM"

            if (!message.step_id) {
              dispatch({
                type: "ADD_MESSAGE",
                payload: {
                  id: generateMessageId("msg-llm-result"),
                  role: "assistant",
                  content: (
                    <>
                      <Lightbulb className="h-4 w-4 inline mr-2 text-yellow-500" />
                      {t('agent.logs.event.messages.planLLMResponseCompleted', { modelName })}
                    </>
                  ),
                  timestamp: message.timestamp,
                  status: "completed",
                }
              })
            } else {
              // Add to traceEvents for step execution logs
              const traceEvent: TraceEvent = {
                event_id: generateMessageId(`trace-llm-result`),
                event_type: eventType,
                step_id: message.step_id,
                timestamp: message.timestamp,
                data: {
                  action: t('agent.logs.event.actions.llm_call_result'),
                  model_name: modelName,
                  ...eventData
                }
              }
              dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
            }
          }

          // Tool Execution Events - show as messages if no step_id, otherwise add to traceEvents
          else if (eventType === "tool_execution_start") {
            const toolName = eventData.tool_name || t('nav.tools')
            const stepId = message.step_id || eventData.step_id

            if (!stepId) {
              dispatch({
                type: "ADD_MESSAGE",
                payload: {
                  id: generateMessageId("msg-tool-start"),
                  role: "assistant",
                  content: (
                    <>
                      <Wrench className="h-4 w-4 inline mr-2 text-orange-500" />
                      {t('agent.logs.event.actions.tool_execution_start')}: {toolName}
                    </>
                  ),
                  timestamp: message.timestamp,
                  status: "completed",
                }
              })
            } else {
              // Add to traceEvents for step execution logs
              const traceEvent: TraceEvent = {
                event_id: generateMessageId(`trace-tool-start`),
                event_type: eventType,
                step_id: stepId,
                timestamp: message.timestamp,
                data: {
                  action: t('agent.logs.event.actions.tool_execution_start'),
                  tool_names: [toolName],
                  ...eventData
                }
              }
              dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
            }
          } else if (eventType === "tool_execution_end") {
            const toolName = eventData.tool_name || t('nav.tools')
            const stepId = message.step_id || eventData.step_id

            if (!stepId) {
              dispatch({
                type: "ADD_MESSAGE",
                payload: {
                  id: generateMessageId("msg-tool-end"),
                  role: "assistant",
                  content: (
                    <>
                      <CheckCircle className="h-4 w-4 inline mr-2 text-green-500" />
                      {t('agent.logs.event.actions.tool_execution_end')}: {toolName}
                    </>
                  ),
                  timestamp: message.timestamp,
                  status: "completed",
                }
              })
            } else {
              // Add to traceEvents for step execution logs
              const traceEvent: TraceEvent = {
                event_id: generateMessageId(`trace-tool-end`),
                event_type: eventType,
                step_id: stepId,
                timestamp: message.timestamp,
                data: {
                  action: t('agent.logs.event.actions.tool_execution_end'),
                  tool_names: [toolName],
                  ...eventData
                }
              }
              dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
            }
          } else if (eventType === "tool_execution_failed") {
            const toolName = eventData.tool_name || "Tool"
            const stepId = message.step_id || eventData.step_id

            if (!stepId) {
              dispatch({
                type: "ADD_MESSAGE",
                payload: {
                  id: generateMessageId("msg-tool-failed"),
                  role: "assistant",
                  content: (
                    <>
                      <XCircle className="h-4 w-4 inline mr-2 text-red-500" />
                      {t('agent.logs.event.actions.tool_execution_failed')}: {toolName}
                    </>
                  ),
                  timestamp: message.timestamp,
                  status: "failed",
                }
              })
            } else {
              // Add to traceEvents for step execution logs
              const traceEvent: TraceEvent = {
                event_id: generateMessageId(`trace-tool-failed`),
                event_type: eventType,
                step_id: stepId,
                timestamp: message.timestamp,
                data: {
                  action: t('agent.logs.event.actions.tool_execution_failed'),
                  tool_names: [toolName],
                  ...eventData
                }
              }
              dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
            }
          } else if (eventType === "tool_using") {
            const toolName = eventData.tool_name || t('nav.tools')
            const stepId = message.step_id || eventData.step_id

            if (!stepId) {
              dispatch({
                type: "ADD_MESSAGE",
                payload: {
                  id: generateMessageId("msg-tool-using"),
                  role: "assistant",
                  content: t('agent.logs.event.messages.useTool', { toolName }),
                  timestamp: message.timestamp,
                  status: "completed",
                }
              })
            } else {
              // Add to traceEvents for step execution logs
              const traceEvent: TraceEvent = {
                event_id: generateMessageId(`trace-tool-using`),
                event_type: eventType,
                step_id: stepId,
                timestamp: message.timestamp,
                data: {
                  action: t('agent.logs.event.actions.tool_using'),
                  tool_names: [toolName],
                  ...eventData
                }
              }
              dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
            }
          }

          // Task Completion Events
          else if (eventType === "task_completion") {
            const { result, success } = eventData
            // Check for clarification request in task completion
            const clarification = extractClarificationMessage(eventData)
            if (clarification) {
              const clarificationMessage =
                clarification.message
                || (typeof result?.content === "string" ? result.content : "")
              const msgId = generateMessageId("msg-clarification")
              dispatch({
                type: "ADD_MESSAGE",
                payload: {
                  id: msgId,
                  role: "assistant",
                  content: <div className="space-y-2">
                    <MarkdownRenderer
                      content={clarificationMessage}
                      filesDisabled={options?.filesDisabled}
                      agentCardsEnabled={agentCardsEnabled}
                    />
                    <ClarificationForm
                      interactions={clarification.interactions}
                      messageId={msgId}
                    />
                  </div>,
                  timestamp: message.timestamp,
                  status: "completed",
                  isResult: true,
                  interactions: clarification.interactions,
                }
              })
              return
            }

            // Parse result string into object
            let resultData = {}
            const resultContent = (
              result
              && typeof result === 'object'
              && !Array.isArray(result)
              && ((result as any).file_outputs || (result as any).output || (result as any).content)
            ) ? result : (result?.content || result)
            if (typeof resultContent === 'string') {
              try {
                resultData = JSON.parse(resultContent)
              } catch (e) {
                console.log('Result is not JSON, treating as plain text output:', result.content)
                resultData = { output: resultContent }
              }
            } else if (typeof resultContent === 'object' && resultContent !== null) {
              resultData = resultContent
            } else {
              resultData = { output: resultContent }
            }
            if (
              resultData
              && typeof resultData === 'object'
              && (resultData as any).content
              && !(resultData as any).output
            ) {
              const content = (resultData as any).content
              resultData = {
                ...resultData,
                output: typeof content === "string" ? unwrapFinalAnswerContent(content) : content,
              }
            }

            // 1. Output meta info (excluding output, file_outputs, and history)
            const metaInfo = { ...resultData }
            delete (metaInfo as any).output
            delete (metaInfo as any).content
            delete (metaInfo as any).file_outputs
            delete (metaInfo as any).history
            delete (metaInfo as any).stream_message_id
            delete (metaInfo as any).streamMessageId
            const hasMetaInfo = Object.keys(metaInfo).length > 0 && metaInfo !== null && metaInfo !== undefined

            // 1.5. Extract step data from history and update state.steps
            const history = (resultData as any).history
            if (history && Array.isArray(history) && history.length > 0) {
              const latestIteration = history[history.length - 1] // Latest iteration (the last one)
              if (latestIteration.plan && latestIteration.plan.steps && Array.isArray(latestIteration.plan.steps)) {
                // Create results map for quick lookup
                const resultsMap = new Map<string, any>()
                if (latestIteration.results && Array.isArray(latestIteration.results)) {
                  latestIteration.results.forEach((result: any) => {
                    resultsMap.set(result.step_id, result)
                  })
                }

                // Get active_branches to determine which steps are skipped
                const activeBranches = latestIteration.plan?.active_branches || {}

                // Get existing steps to preserve timing information
                const existingSteps = currentState.steps
                const existingStepsMap = new Map<string, StepExecution>()
                existingSteps.forEach(step => existingStepsMap.set(step.id, step))

                const steps: StepExecution[] = latestIteration.plan.steps.map((step: any) => {
                  // Find corresponding execution result from results
                  const stepResult = resultsMap.get(step.id)
                  // Find existing step
                  const existingStep = existingStepsMap.get(step.id)

                  // If execution result exists, use its status; otherwise use status from plan
                  let finalStatus = step.status || "pending"
                  let startedAt = step.started_at
                  let completedAt = step.completed_at
                  let resultData = step.result

                  if (stepResult) {
                    // Determine status based on result field
                    if (stepResult.result !== undefined && stepResult.result !== null) {
                      finalStatus = "completed"
                    }
                    // Use timing info from stepResult regardless of result existence (if present)
                    if (stepResult.started_at) startedAt = stepResult.started_at
                    if (stepResult.completed_at) completedAt = stepResult.completed_at
                    // If stepResult has result field, use it
                    if (stepResult.result !== undefined && stepResult.result !== null) {
                      resultData = stepResult.result
                    }
                  }

                  // Check if should be skipped: if step requires specific branch but it is not activated
                  if (step.required_branch) {
                    // Find condition node this step depends on
                    const dependencyNodeId = step.dependencies && step.dependencies.length > 0 ? step.dependencies[0] : null
                    if (dependencyNodeId) {
                      const activeBranch = activeBranches[dependencyNodeId]
                      if (activeBranch && activeBranch !== step.required_branch) {
                        // Branch not activated, so this step is skipped
                        finalStatus = "skipped"
                      }
                    }
                  }

                  // Prioritize existing step info (if no explicit info in new data)
                  if (existingStep) {
                    // Prioritize existing step timing info
                    if (!startedAt && existingStep.started_at) startedAt = existingStep.started_at
                    if (!completedAt && existingStep.completed_at) completedAt = existingStep.completed_at

                    // Prioritize existing step status (if new step status is pending or running)
                    // This ensures status from dag_step_end event is not overwritten by plan data
                    if (finalStatus === "pending" || finalStatus === "running") {
                      if (existingStep.status && existingStep.status !== "pending" && existingStep.status !== "running") {
                        finalStatus = existingStep.status
                      }
                    }
                  }

                  return {
                    id: step.id,
                    name: step.name || step.id,
                    description: step.description || "",
                    status: finalStatus,
                    tool_names: step.tool_name ? [step.tool_name] : step.tool_names || [],
                    dependencies: step.dependencies || [],
                    started_at: startedAt,
                    completed_at: completedAt,
                    result_data: resultData,
                    step_data: step.step_data,
                    file_outputs: step.file_outputs || [],
                    conditional_branches: step.conditional_branches || {},
                    required_branch: step.required_branch || null,
                    is_conditional: step.is_conditional || false,
                  }
                })
                dispatch({ type: "SET_STEPS", payload: steps })
              }
            }

            if (hasMetaInfo) {
              const metaContent = (
                <div className="space-y-2">
                  <div className="flex items-center gap-2 text-sm text-purple-400">
                    <Target className="h-4 w-4" />
                    <span>{t('agent.logs.event.messages.metaTitle')}</span>
                  </div>
                  <div className="ml-6">
                    <JsonRenderer
                      data={metaInfo}
                      filesDisabled={options?.filesDisabled}
                      agentCardsEnabled={agentCardsEnabled}
                      onFileClick={options?.filesDisabled ? undefined : openFilePreview}
                      onAgentClick={(agentId) => router.push(getAgentTaskHref(agentId))}
                    />
                  </div>
                </div>
              )
              if (!isDuplicateMessageForViewedTask(`📋 ${t('agent.logs.event.messages.metaTitle')}: ${JSON.stringify(metaInfo)}`, "result")) {
                dispatch({
                  type: "ADD_MESSAGE",
                  payload: {
                    id: generateMessageId("msg-meta-info"),
                    role: "assistant",
                    content: metaContent,
                    timestamp: message.timestamp,
                    status: success ? "completed" : "failed",
                    // @ts-ignore
                    isMetaInfo: true,
                  }
                })
              }
            }

            // 2. Output file outputs
            const fileOutputsData = (resultData as any).file_outputs
            if (fileOutputsData && fileOutputsData.length > 0) {
              const fileCount = fileOutputsData.length
              const fileContent = (
                <>
                  <FileText className="h-4 w-4 inline mr-2 text-green-500" />
                  {t('agent.logs.event.messages.fileOutputsGenerated', { count: fileCount })}:
                  <div className="mt-2 space-y-1">
                    {fileOutputsData.map((file: string | any, index: number) => {
                      let fileName, filePath
                      if (typeof file === 'object' && file !== null) {
                        fileName = file.filename || 'unknown'
                        filePath = file.file_id || ''
                      } else {
                        fileName = 'unknown'
                        filePath = ''
                      }

                      return (
                        <div key={index} className="flex items-center justify-between bg-muted/30 rounded p-2">
                          <span className="text-sm font-mono">{fileName}</span>
                          <button
                            onClick={() => {
                              if (options?.filesDisabled) return
                              // Dispatch custom event to open file preview with all files
                              const allFiles = normalizeGeneratedPreviewFiles(fileOutputsData)

                              if (!filePath) {
                                return
                              }

                              window.dispatchEvent(new CustomEvent('openFilePreview', {
                                detail: {
                                  filePath,
                                  fileName,
                                  allFiles,
                                  currentIndex: index
                                }
                              }))
                            }}
                            disabled={options?.filesDisabled || !filePath}
                            className="text-xs bg-primary/10 hover:bg-primary/20 text-primary px-2 py-1 rounded transition-colors"
                          >
                            {t('agent.logs.event.messages.previewLabel')}
                          </button>
                        </div>
                      )
                    })}
                  </div>
                </>
              )

              if (!isDuplicateMessageForViewedTask(`📁 ${t('agent.logs.event.messages.fileOutputsGenerated', { count: fileCount })}`, "result")) {
                dispatch({
                  type: "ADD_MESSAGE",
                  payload: {
                    id: generateMessageId("msg-file-outputs"),
                    role: "assistant",
                    content: fileContent,
                    timestamp: message.timestamp,
                    status: "completed",
                    isFileOutput: true,
                  }
                })
              }

              if (!options?.filesDisabled) {
                dispatchAutoOpenPreview(fileOutputsData, dispatch)
              }
            }

            // Update task status and trigger sidebar update
            dispatch({
              type: "UPDATE_TASK_STATUS",
              payload: { status: success ? "completed" : "failed" }
            })
          }

          // Execution Log Events
          else if (eventType === "execution_log") {
            const { level, message: logMessage, step_id, step_name } = eventData
            let displayMessage = logMessage
            if (step_name) {
              displayMessage = `[${step_name}] ${logMessage}`
            }

            const getIcon = () => {
              switch (level) {
                case 'info': return <Info className="h-4 w-4 inline mr-2 text-blue-500" />
                case 'warning': return <AlertTriangle className="h-4 w-4 inline mr-2 text-yellow-500" />
                case 'error': return <XCircle className="h-4 w-4 inline mr-2 text-red-500" />
                case 'debug': return <Search className="h-4 w-4 inline mr-2 text-purple-500" />
                case 'success': return <CheckCircle className="h-4 w-4 inline mr-2 text-green-500" />
                default: return <FileText className="h-4 w-4 inline mr-2 text-gray-500" />
              }
            }

            dispatch({
              type: "ADD_MESSAGE",
              payload: {
                id: generateMessageId("msg-exec-log"),
                role: "assistant",
                content: (
                  <>
                    {getIcon()}
                    {displayMessage}
                  </>
                ),
                timestamp: message.timestamp,
                status: level === 'error' ? 'failed' : 'completed',
              }
            })
          }

          // Error Events
          else if (eventType === "trace_error") {
            // Prioritize error_message, if not present use error, finally use default message
            const errorMessage = eventData.error_message || eventData.error || 'Trace error occurred'
            const stepName = eventData.step_name || eventData.name || `${t('agent.logs.event.messages.execStepPrefix')}${eventData.step_id || t('common.errors.unknown')}`
            const stepId = message.step_id || eventData.step_id

            // Debug information
            console.trace('trace_error debug:', {
              message_step_id: message.step_id,
              eventData_step_id: eventData.step_id,
              stepName: stepName,
              stepId: stepId,
              hasStepId: !!stepId,
              eventData: eventData,
              errorMessage: errorMessage
            })

            // Only add to trace events for displaying execution logs, do not mark step as failed
            const traceEvent: TraceEvent = {
              event_id: generateMessageId(`trace-error-${stepId || 'global'}`),
              event_type: eventType,
              step_id: stepId,
              timestamp: message.timestamp,
              data: {
                action: t('agent.logs.event.actions.trace_error'),
                step_name: stepName,
                error: errorMessage,
                error_type: eventData.error_type,
                tool_names: eventData.tool_name ? [eventData.tool_name] : eventData.tool_names || [],
                ...(eventData.execution_time && { execution_time: eventData.execution_time }),
              }
            }
            dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })

            // For step-related errors, do not display in left panel, only in right panel
            // Only display non-step-related global errors in left panel
            if (!stepId || stepId === 'unknown') {
              dispatch({
                type: "ADD_MESSAGE",
                payload: {
                  id: generateMessageId("msg-trace-error"),
                  role: "assistant",
                  content: (
                    <>
                      <XCircle className="h-4 w-4 inline mr-2 text-red-500" />
                      {t('agent.logs.event.messages.errorPrefix')} {errorMessage}
                    </>
                  ),
                  timestamp: message.timestamp,
                  status: "failed",
                }
              })
              // This event alone never decides the task failed (a global
              // trace_error can be logged without the task actually stopping,
              // and some OTHER terminal event - task_completed/agent_error -
              // is what actually settles that) - but if the task is ALREADY
              // known failed (task_info established that on cold history
              // load, backfilling dagTerminatedAt from mutable updatedAt as a
              // PROVISIONAL guess) and no proper terminal broadcast ever
              // followed this trace_error to replace that guess, the frozen
              // elapsed time would stay wrong forever. Re-stamping the
              // ALREADY-failed status with this event's own timestamp lets it
              // replace a provisional value (see UPDATE_TASK_STATUS) without
              // ever using this event to newly decide the outcome.
              if (currentState.currentTask?.status === "failed") {
                dispatch({ type: "UPDATE_TASK_STATUS", payload: { status: "failed" } })
                dispatch({ type: "TRIGGER_TASK_UPDATE" })
              }
            }
          }

          // Visualization Events
          else if (eventType === "visualization_update") {
            dispatch({
              type: "ADD_MESSAGE",
              payload: {
                id: generateMessageId("msg-viz"),
                role: "assistant",
                content: (
                  <>
                    <Activity className="h-4 w-4 inline mr-2 text-blue-500" />
                    {t('agent.logs.event.messages.visualUpdate', { type: eventData.type || 'unknown' })}
                  </>
                ),
                timestamp: message.timestamp,
                status: "completed",
              }
            })
          }

          // ReAct Pattern Events - these should be displayed in the right panel
          else if (eventType === "react_task_start" || eventType === "task_start_react") {
            dispatchInferredRunningStatus()

            // Add to trace events for displaying execution logs
            const traceEvent: TraceEvent = {
              event_id: generateMessageId("react-task-start"),
              event_type: eventType,
              step_id: eventData.step_id,
              timestamp: message.timestamp,
              data: {
                action: t('agent.logs.event.actions.react_task_start'),
                message: t('agent.logs.event.messages.reactTaskStart'),
                ...eventData
              }
            }
            dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
          } else if (eventType === "react_task_end" || eventType === "task_end_react") {
            const traceEvent: TraceEvent = {
              event_id: generateMessageId("react-task-end"),
              event_type: eventType,
              step_id: eventData.step_id,
              timestamp: message.timestamp,
              data: {
                action: t('agent.logs.event.actions.react_task_end'),
                message: t('agent.logs.event.messages.reactTaskCompleted'),
                ...eventData
              }
            }
            dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })

            const result = eventData.result
            const messageContent =
              result && typeof result === "object" && result.status === "waiting_for_user"
                ? result.message || ""
                : ""
            if (messageContent && !isDuplicateMessageForViewedTask(messageContent, 'agent-message')) {
              const interactions = normalizeInteractions(result.interactions)
              const msgId = generateMessageId("msg-agent")
              dispatch({
                type: "ADD_MESSAGE",
                payload: {
                  id: msgId,
                  role: "assistant",
                  content: messageContent,
                  rawContent: messageContent,
                  timestamp: message.timestamp,
                  status: "running",
                  isResult: true,
                  interactions: interactions.length > 0 ? interactions : undefined,
                }
              })
            }
          } else if (eventType === "react_task_failed" || eventType === "task_failed_react") {
            const traceEvent: TraceEvent = {
              event_id: generateMessageId("react-task-failed"),
              event_type: eventType,
              step_id: eventData.step_id,
              timestamp: message.timestamp,
              data: {
                action: t('agent.logs.event.actions.react_task_failed'),
                message: t('agent.logs.event.messages.reactTaskFailed'),
                error: eventData.error || eventData.message,
                ...eventData
              }
            }
            dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
          } else if (eventType === "react_action_start") {
            const stepId = message.step_id || traceEventData.step_id
            const traceEvent: TraceEvent = {
              event_id: generateMessageId("react-action-start"),
              event_type: eventType,
              step_id: stepId,
              timestamp: message.timestamp,
              data: {
                action: t('agent.logs.event.actions.react_action_start') || 'Action Start',
                ...eventData
              }
            }
            dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
          } else if (eventType === "llm_call_start") {
            dispatchInferredRunningStatus()
            const stepId = message.step_id || traceEventData.step_id
            const traceEvent: TraceEvent = {
              event_id: generateMessageId("llm-call-start"),
              event_type: eventType,
              step_id: stepId,
              timestamp: message.timestamp,
              data: {
                action: t('agent.logs.event.actions.llm_call_start'),
                ...eventData
              }
            }
            dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
          } else if (eventType === "llm_call_end") {
            const stepId = message.step_id || traceEventData.step_id
            const traceEvent: TraceEvent = {
              event_id: generateMessageId("llm-call-end"),
              event_type: eventType,
              step_id: stepId,
              timestamp: message.timestamp,
              data: {
                action: t('agent.logs.event.actions.llm_call_end'),
                ...eventData
              }
            }
            dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
          } else if (eventType === "llm_call_failed") {
            const stepId = message.step_id || traceEventData.step_id
            const traceEvent: TraceEvent = {
              event_id: generateMessageId("llm-call-failed"),
              event_type: eventType,
              step_id: stepId,
              timestamp: message.timestamp,
              data: {
                action: t('agent.logs.event.actions.llm_call_failed'),
                ...eventData
              }
            }
            dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
          } else if (eventType === "react_action_end") {
            const stepId = message.step_id || traceEventData.step_id
            const traceEvent: TraceEvent = {
              event_id: generateMessageId("react-action-end"),
              event_type: eventType,
              step_id: stepId,
              timestamp: message.timestamp,
              data: {
                action: t('agent.logs.event.actions.react_action_end') || 'Action End',
                ...eventData
              }
            }
            dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
          } else if (eventType === "task_completion") {
            // Trace task completion event
            const traceEvent: TraceEvent = {
              event_id: generateMessageId("task-completion"),
              event_type: eventType,
              timestamp: message.timestamp,
              data: {
                action: t('agent.logs.event.actions.task_completion'),
                message: t('agent.logs.event.messages.taskCompleted'),
                result: eventData.result,
                success: eventData.success
              }
            }
            dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
          } else if (eventType === "react_task_end" || eventType === "task_end_react") {
            // Add to trace events for execution log display
            const traceEvent: TraceEvent = {
              event_id: generateMessageId("react-task-end"),
              event_type: eventType,
              timestamp: message.timestamp,
              data: {
                action: t('agent.logs.event.actions.react_task_end'),
                message: t('agent.logs.event.messages.reactTaskCompleted'),
                output: eventData.output
              }
            }
            dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
          } else if (eventType === "step_start_react") {
            const stepName = eventData.step_name || 'unknown'
            const stepId = `react-${stepName}`

            // Create or update step
            const step: StepExecution = {
              id: stepId,
              name: stepName,
              description: `ReAct Step: ${stepName}`,
              status: "running",
              tool_names: eventData.tool_name ? [eventData.tool_name] : eventData.tool_names || [],
              dependencies: [],
              started_at: message.timestamp,
              completed_at: undefined,
              result_data: null,
              step_data: eventData,
              file_outputs: [],
            }
            dispatch({ type: "ADD_STEP", payload: step })

            // Add to trace events for displaying execution logs
            const traceEvent: TraceEvent = {
              event_id: generateMessageId(`react-step-start-${stepId}`),
              event_type: eventType,
              step_id: stepId,
              timestamp: message.timestamp,
              data: {
                action: t('agent.logs.event.actions.step_start_react'),
                step_name: stepName,
                tool_names: eventData.tool_name ? [eventData.tool_name] : eventData.tool_names || [],
                message: t('agent.logs.event.messages.reactStepStart', { stepName }),
              }
            }
            dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
          } else if (eventType === "step_end_react") {
            const stepName = eventData.step_name || 'unknown'
            const stepId = `react-${stepName}`

            // Update step status
            const step: StepExecution = {
              id: stepId,
              name: stepName,
              description: `ReAct Step: ${stepName}`,
              status: "completed",
              tool_names: eventData.tool_name ? [eventData.tool_name] : eventData.tool_names || [],
              dependencies: [],
              started_at: undefined, // Preserve original start time
              completed_at: message.timestamp,
              result_data: eventData.result_data,
              step_data: eventData,
              file_outputs: eventData.file_outputs || [],
            }
            dispatch({ type: "ADD_STEP", payload: step })

            // Add to trace events for execution log display
            const traceEvent: TraceEvent = {
              event_id: generateMessageId(`react-step-end-${stepId}`),
              event_type: eventType,
              step_id: stepId,
              timestamp: message.timestamp,
              data: {
                action: t('agent.logs.event.actions.step_end_react'),
                step_name: stepName,
                tool_names: eventData.tool_name ? [eventData.tool_name] : eventData.tool_names || [],
                result_data: eventData.result_data,
                message: t('agent.logs.event.messages.reactStepCompleted', { stepName }),
              }
            }
            dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
          }
          // Skill Selection Events
          else if (eventType === "skill_select_start") {
            dispatchInferredRunningStatus()

            const traceEvent: TraceEvent = {
              event_id: generateMessageId("skill-select-start"),
              event_type: eventType,
              step_id: eventData.step_id,
              timestamp: message.timestamp,
              data: {
                action: t('agent.logs.event.actions.skill_select_start'),
                ...eventData
              }
            }
            dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
          } else if (eventType === "skill_select_end") {
            const traceEvent: TraceEvent = {
              event_id: generateMessageId("skill-select-end"),
              event_type: eventType,
              step_id: eventData.step_id,
              timestamp: message.timestamp,
              data: {
                action: t('agent.logs.event.actions.skill_select_end'),
                ...eventData
              }
            }
            dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
          }
          // Memory Events - Determine display location based on step_id
          else if (eventType === "task_start_memory_generate") {
            const stepId = eventData.step_id

            // If step_id exists, add to corresponding step; otherwise do not display (skip useless start events)
            if (stepId) {
              // ReAct pattern - Display in corresponding step in right panel
              const traceEvent: TraceEvent = {
                event_id: generateMessageId(`memory-generate-start-${stepId}`),
                event_type: eventType,
                step_id: stepId,
                timestamp: message.timestamp,
                data: {
                  action: t('agent.logs.event.actions.task_start_memory_generate'),
                  message: '🧠 ' + t('agent.logs.event.actions.task_start_memory_generate'),
                  task: eventData.task,
                  iterations: eventData.iterations,
                  result_length: eventData.result_length,
                  messages_count: eventData.messages_count,
                }
              }
              dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
            }
            // Skip if no step_id, do not display start event
          } else if (eventType === "task_end_memory_generate") {
            const taskId = eventData.task_id || "unknown"
            const stepId = eventData.step_id

            // If step_id exists, add to corresponding step; otherwise display in left panel
            if (stepId) {
              // ReAct pattern - Display in corresponding step in right panel
              const traceEvent: TraceEvent = {
                event_id: generateMessageId(`memory-generate-end-${stepId}`),
                event_type: eventType,
                step_id: stepId,
                timestamp: message.timestamp,
                data: {
                  action: t('agent.logs.event.actions.task_end_memory_generate'),
                  message: '🧠 ' + t('agent.logs.event.actions.task_end_memory_generate'),
                  insights_generated: eventData.insights_generated,
                  should_store: eventData.should_store,
                  reason: eventData.reason,
                  source: eventData.source,
                }
              }
              dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
            } else {
              // DAG plan-execute pattern - Display in left panel
              const shouldStore = eventData.should_store || false
              const reason = eventData.reason || ""
              const source = eventData.source || "unknown"

              dispatch({
                type: "ADD_MESSAGE",
                payload: {
                  id: generateMessageId("msg-memory-generate-end"),
                  role: "assistant",
                  content: (
                    <>
                      <span>
                        <Brain className="h-4 w-4 inline mr-2" />
                        {t('agent.logs.event.actions.task_end_memory_generate')}
                      </span>
                      <div className="mt-2">
                        <CollapsibleSection
                          title={t('agent.logs.event.messages.detailsTitle')}
                          badge={t('agent.logs.event.messages.memoryBadge')}
                        >
                          <div className="space-y-2">
                            <div className="flex items-center gap-2">
                              <span className="font-medium text-sm">{t('agent.logs.event.messages.insightsLabel')}</span>
                              {eventData.insights_generated ? (
                                <Badge className="bg-green-100 text-green-800 text-xs">{t('agent.logs.event.labels.success')}</Badge>
                              ) : (
                                <Badge variant="destructive" className="text-xs">{t('agent.logs.event.labels.failed')}</Badge>
                              )}
                            </div>
                            <div className="flex items-center gap-2">
                              <span className="font-medium text-sm">{t('agent.logs.event.messages.storeSuggestion')}</span>
                              {shouldStore ? (
                                <Badge className="bg-green-100 text-green-800 text-xs">{t('agent.logs.event.messages.worthStoring')}</Badge>
                              ) : (
                                <Badge variant="secondary" className="text-xs">{t('agent.logs.event.messages.notWorthStoring')}</Badge>
                              )}
                            </div>
                            {reason && (
                              <div className="text-sm">
                                <span className="font-medium">{t('agent.logs.event.messages.reason')}</span> {reason}
                              </div>
                            )}
                          </div>
                        </CollapsibleSection>
                      </div>
                    </>
                  ),
                  timestamp: message.timestamp,
                  status: "completed",
                }
              })
            }
          } else if (eventType === "task_start_memory_store") {
            const taskId = eventData.task_id || "unknown"
            const stepId = eventData.step_id

            // If step_id exists, add to corresponding step; otherwise display in left panel
            if (stepId) {
              // ReAct pattern - Display in corresponding step in right panel
              const traceEvent: TraceEvent = {
                event_id: generateMessageId(`memory-store-start-${stepId}`),
                event_type: eventType,
                step_id: stepId,
                timestamp: message.timestamp,
                data: {
                  action: t('agent.logs.event.actions.task_start_memory_store'),
                  message: '🧠 ' + t('agent.logs.event.actions.task_start_memory_store'),
                  task: eventData.task,
                  memory_category: eventData.memory_category,
                  classification: eventData.classification,
                }
              }
              dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
            } else {
              // DAG plan-execute pattern - Display in left panel
              dispatch({
                type: "ADD_MESSAGE",
                payload: {
                  id: generateMessageId("msg-memory-store-start"),
                  role: "assistant",
                  content: (
                    <>
                      <Brain className="h-4 w-4 inline mr-2" />
                      {t('agent.logs.event.actions.task_start_memory_store')}
                      {eventData.task && (
                        <div className="text-sm text-gray-600 mt-1">
                          {t('agent.logs.event.messages.taskLabel')} {eventData.task.length > 100 ? eventData.task.substring(0, 100) + '...' : eventData.task}
                        </div>
                      )}
                      {eventData.memory_category && (
                        <div className="text-sm text-gray-600 mt-1">
                          {t('agent.logs.event.memory.category')}: {eventData.memory_category}
                        </div>
                      )}
                    </>
                  ),
                  timestamp: message.timestamp,
                  status: "running",
                }
              })
            }
          } else if (eventType === "task_end_memory_store") {
            const taskId = eventData.task_id || "unknown"
            const stepId = eventData.step_id

            // If step_id exists, add to corresponding step; otherwise display in left panel
            if (stepId) {
              // ReAct pattern - Display in corresponding step in right panel
              const traceEvent: TraceEvent = {
                event_id: generateMessageId(`memory-store-end-${stepId}`),
                event_type: eventType,
                step_id: stepId,
                timestamp: message.timestamp,
                data: {
                  action: t('agent.logs.event.actions.task_end_memory_store'),
                  message: '🧠 ' + t('agent.logs.event.actions.task_end_memory_store'),
                  storage_success: eventData.storage_success,
                  reason: eventData.reason,
                  decision: eventData.decision,
                }
              }
              dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
            } else {
              // DAG plan-execute pattern - Display in left panel
              const storageSuccess = eventData.storage_success || false
              const reason = eventData.reason || ""
              const decision = eventData.decision || "unknown"

              dispatch({
                type: "ADD_MESSAGE",
                payload: {
                  id: generateMessageId("msg-memory-store-end"),
                  role: "assistant",
                  content: (
                    <>
                      <span>
                        <Brain className="h-4 w-4 inline mr-2" />
                        {t('agent.logs.event.actions.task_end_memory_store')}
                      </span>
                      <div className="mt-2">
                        <CollapsibleSection
                          title={t('agent.logs.event.messages.detailsTitle')}
                          badge={t('agent.logs.event.messages.memoryBadge')}
                        >
                          <div className="space-y-2">
                            <div className="flex items-center gap-2">
                              <span className="font-medium text-sm">{t('agent.logs.event.messages.storageStatusLabel')}</span>
                              {storageSuccess ? (
                                <Badge className="bg-green-100 text-green-800 text-xs">{t('agent.logs.event.labels.success')}</Badge>
                              ) : (
                                <Badge variant="secondary" className="text-xs">{t('agent.logs.event.messages.notStored')}</Badge>
                              )}
                            </div>
                            {reason && (
                              <div className="text-sm">
                                <span className="font-medium">{t('agent.logs.event.messages.reason')}</span> {reason}
                              </div>
                            )}
                            {decision && decision !== 'unknown' && (
                              <div className="text-sm">
                                <span className="font-medium">{t('agent.logs.event.messages.decisionLabel')}</span> {decision === 'not_worth_storing' ? t('agent.logs.event.messages.notWorthStoring') : decision}
                              </div>
                            )}
                          </div>
                        </CollapsibleSection>
                      </div>
                    </>
                  ),
                  timestamp: message.timestamp,
                  status: "completed",
                }
              })
            }
          } else if (eventType === "task_start_memory_retrieve") {
            const taskId = eventData.task_id || "unknown"
            const stepId = eventData.step_id

            // If step_id exists, add to corresponding step; otherwise display in left panel
            if (stepId) {
              // ReAct pattern - Display in corresponding step in right panel
              const traceEvent: TraceEvent = {
                event_id: generateMessageId(`memory-retrieve-start-${stepId}`),
                event_type: eventType,
                step_id: stepId,
                timestamp: message.timestamp,
                data: {
                  action: t('agent.logs.event.actions.task_start_memory_retrieve'),
                  message: '🔍 ' + t('agent.logs.event.actions.task_start_memory_retrieve'),
                  // Display full data
                  rawData: eventData,
                }
              }
              dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
            } else {
              // DAG plan-execute pattern - Display in left panel
              const stepId = eventData.step_id || "unknown"

              // Memory retrieval start event
              dispatch({
                type: "ADD_MESSAGE",
                payload: {
                  id: generateMessageId(`memory-retrieve-start-${stepId}`),
                  role: "assistant",
                  content: (
                    <>
                      <Search className="h-4 w-4 inline mr-2" />
                      {t('agent.logs.event.actions.task_start_memory_retrieve')}
                      <div className="mt-1">
                        <CollapsibleSection
                          title={t('agent.logs.event.common.fullData')}
                          badge={t('agent.logs.event.messages.memoryBadge')}
                        >
                          <div className="text-xs bg-muted/80 p-2 rounded font-mono text-foreground">
                            {JSON.stringify(eventData, null, 2)}
                          </div>
                        </CollapsibleSection>
                      </div>
                    </>
                  ),
                  timestamp: message.timestamp,
                  status: "running",
                }
              })
            }
          } else if (eventType === "task_end_memory_retrieve") {
            const taskId = eventData.task_id || "unknown"
            const stepId = eventData.step_id

            // If step_id exists, add to corresponding step; otherwise display in left panel
            if (stepId) {
              // ReAct pattern - Display in corresponding step in right panel
              const traceEvent: TraceEvent = {
                event_id: generateMessageId(`memory-retrieve-end-${stepId}`),
                event_type: eventType,
                step_id: stepId,
                timestamp: message.timestamp,
                data: {
                  action: t('agent.logs.event.actions.task_end_memory_retrieve'),
                  message: '🔍 ' + t('agent.logs.event.actions.task_end_memory_retrieve'),
                  // Display full data
                  rawData: eventData,
                }
              }
              dispatch({ type: "ADD_TRACE_EVENT", payload: traceEvent })
            } else {
              // DAG plan-execute pattern - Display in left panel
              const stepId = eventData.step_id || "unknown"
              const memoriesFound = eventData.memories_found || 0
              const memoriesUsed = eventData.memories_used || 0
              const memoryCategory = eventData.memory_category || t('agent.logs.event.messages.categoryUnknown')
              const enhancedGoal = eventData.enhanced_goal
              const memories = eventData.memories || []

              // Store plan memory information for display
              console.log("Setting planMemoryInfo:", { memoriesFound, memoriesUsed, memoryCategory, enhancedGoal, memories })
              dispatch({
                type: "SET_PLAN_MEMORY_INFO",
                payload: {
                  memoriesFound,
                  memoriesUsed,
                  memoryCategory,
                  enhancedGoal,
                  memories: memories.map((mem: any) => ({
                    content: mem.content || mem,
                    category: mem.category
                  }))
                }
              })

              // Memory retrieval end event
              dispatch({
                type: "ADD_MESSAGE",
                payload: {
                  id: generateMessageId(`memory-retrieve-end-${stepId}`),
                  role: "assistant",
                  content: (
                    <>
                      <Search className="h-4 w-4 inline mr-2" />
                      {t('agent.logs.event.actions.task_end_memory_retrieve')}
                      <div className="mt-2">
                        <CollapsibleSection
                          title={t('agent.logs.event.messages.detailsTitle')}
                          badge={t('agent.logs.event.messages.memoryBadge')}
                        >
                          <div className="grid grid-cols-2 gap-2 text-xs">
                            <div className="flex items-center gap-1 p-2 bg-muted/30 rounded">
                              <Search className="h-3 w-3" />
                              <span>{t('agent.logs.event.memory.found')}: {memoriesFound} {t('agent.logs.event.common.itemsSuffix')}</span>
                            </div>
                            <div className="flex items-center gap-1 p-2 bg-muted/30 rounded">
                              <Target className="h-3 w-3" />
                              <span>{t('agent.logs.event.memory.used')}: {memoriesUsed} {t('agent.logs.event.common.itemsSuffix')}</span>
                            </div>
                          </div>
                          {enhancedGoal && (
                            <div className="mt-2">
                              <div className="text-xs font-medium text-muted-foreground mb-1">{t('agent.planDetails.memory.enhancedGoalTitle')}</div>
                              <div className="text-xs bg-blue-500/10 p-2 rounded border border-blue-500/20">
                                {enhancedGoal}
                              </div>
                            </div>
                          )}
                          {memories && memories.length > 0 && (
                            <div className="mt-2">
                              <div className="text-xs font-medium text-muted-foreground mb-1">{t('agent.logs.event.memory.relatedTitle')}:</div>
                              <div className="space-y-1">
                                {memories.map((memory: any, index: number) => (
                                  <div
                                    key={index}
                                    className="text-xs p-2 bg-muted/20 rounded border border-border/50"
                                  >
                                    <div className="flex items-start gap-1">
                                      <Info className="h-3 w-3 mt-0.5 text-blue-400 flex-shrink-0" />
                                      <span className="whitespace-pre-wrap">{memory.content}</span>
                                    </div>
                                    {memory.category && (
                                      <Badge variant="outline" className="text-xs mt-1">
                                        {memory.category}
                                      </Badge>
                                    )}
                                  </div>
                                ))}
                              </div>
                            </div>
                          )}
                        </CollapsibleSection>
                      </div>
                    </>
                  ),
                  timestamp: message.timestamp,
                  status: "completed",
                }
              })
            }
          }

          // Legacy Events
          else if (eventType === "task-info") {
            dispatch({
              type: "ADD_MESSAGE",
              payload: {
                id: generateMessageId("msg-task-info"),
                role: "assistant",
                content: (
                  <>
                    <FileText className="h-4 w-4 inline mr-2" />
                    {t('agent.logs.event.messages.taskInfoLabel')} {eventData.title || 'unknown'}
                  </>
                ),
                timestamp: message.timestamp,
                status: "completed",
              }
            })
          }
          // final-result event type removed - use task_completion instead
          // file-output event type removed - handled in task_completion instead

          // Historical Data Events - handled by the main message handler below
          else if (eventType === "historical_data_complete") {
            // A plain ref write, not gated by the dispatch wrapper's task
            // scoping - a stray background task's own historical_data_complete
            // must not end the VIEWED task's history-loading state early.
            if (!isMessageForOtherTask) isHistoricalDataLoadingRef.current = false
            dispatch({ type: "SET_HISTORY_LOADING", payload: false })
            dispatch({ type: "SYNC_PROCESSING_STATUS" })

            // If we're in replay mode, initialize the replay scheduler
            if (currentState.isReplaying && currentState.replayTaskId && currentState.replayEventCache.length > 0) {
              initializeReplayScheduler()
            } else {
              // Fix: If we have cache but replay mode is not set, force start replay
              if (currentState.replayEventCache.length > 0 && currentState.replayTaskId && !currentState.isReplaying) {
                dispatch({ type: "SET_REPLAY_PLAYING", payload: true })
                setTimeout(() => {
                  initializeReplayScheduler()
                }, 50)
              }
            }
          }

          // Default: add as trace event
          else {
            console.trace('Original message:', JSON.stringify(message), 'Handler: handleMessage (unhandled event_type:', eventType, ')')
            dispatch({ type: "ADD_TRACE_EVENT", payload: traceEventData })
          }
        } else {
          console.trace('Original message:', JSON.stringify(message), 'Handler: handleMessage (no event_type, direct trace event)')
          // Handle direct trace events (without event_type wrapper) - infer type from content
          // Check if this is DAG execution data
          if (traceEventData.phase && (traceEventData.current_plan !== undefined)) {
            // Same shared handler the two explicit dag_execution shapes use -
            // this legacy, unwrapped shape predates it and used to dispatch
            // the raw payload directly, bypassing the phase/current_plan
            // normalizer, the created_at/updated_at backfill, and the
            // turn_id-based new-run detection all at once.
            applyDagExecutionUpdate(
              traceEventData as Record<string, unknown>,
              message.timestamp,
            )
          }
          // Check if this is step data (has id and status)
          else if (traceEventData.id && traceEventData.status) {
            // More strict criteria for step identification
            const hasStepProperties = traceEventData.name || traceEventData.tool_name || traceEventData.tool_names || traceEventData.description
            const hasValidStepId = typeof traceEventData.id === 'string' && traceEventData.id.length > 2
            const isNotNumericId = isNaN(traceEventData.id)

            if (hasStepProperties && hasValidStepId && isNotNumericId) {
              const step: StepExecution = {
                id: traceEventData.id,
                name: traceEventData.name || traceEventData.id,
                description: traceEventData.description || "",
                status: traceEventData.status,
                tool_names: traceEventData.tool_name ? [traceEventData.tool_name] : traceEventData.tool_names || [],
                dependencies: traceEventData.dependencies || [],
                started_at: traceEventData.started_at,
                completed_at: traceEventData.completed_at,
                result_data: traceEventData.result_data,
                step_data: traceEventData.step_data,
                file_outputs: traceEventData.file_outputs || [],
              }
              dispatch({ type: "ADD_STEP", payload: step })
            } else {
              // Add as trace event instead
              dispatch({ type: "ADD_TRACE_EVENT", payload: traceEventData })
            }
          }
          // Check if this is task info (has goal)
          else if (traceEventData.goal) {
            // For now, create a basic task structure
            const task = {
              id: currentState.taskId?.toString() || "unknown",
              title: traceEventData.task_preview || traceEventData.goal,
              description: traceEventData.goal,
              status: "completed" as const,
              createdAt: new Date().toISOString(),
              updatedAt: new Date().toISOString(),
            }
            dispatch({ type: "SET_CURRENT_TASK", payload: task })
          }
          // Check if this is a plan start event (has plan_data or current_plan)
          else if (traceEventData.plan_data || traceEventData.current_plan) {
            const planData = traceEventData
            const phase = planData.phase || "planning"
            const planInfo = planData.plan_data || planData.current_plan

            if (planInfo && planInfo.goal && planInfo.steps) {
              // Detailed plan information
              const stepsCount = planInfo.steps.length || planData.steps_count || 0
              const goal = planInfo.goal
              dispatch({
                type: "ADD_MESSAGE",
                payload: {
                  id: generateMessageId("msg-plan-start"),
                  role: "assistant",
                  content: (
                    <>
                      <FileText className="h-4 w-4 inline mr-2" />
                      {t('agent.logs.event.messages.planStart', { phase })}
                      <br />
                      <Target className="h-4 w-4 inline mr-2 mt-1 text-red-500" />
                      {t('agent.logs.event.messages.goalTitle')}: {goal}
                      <br />
                      <Activity className="h-4 w-4 inline mr-2 mt-1 text-blue-500" />
                      {t('agent.logs.event.messages.stepsCount', { count: stepsCount })}
                    </>
                  ),
                  timestamp: message.timestamp,
                  status: "completed",
                }
              })

              // Add individual step messages
              planInfo.steps.forEach((step: any, index: number) => {
                dispatch({
                  type: "ADD_MESSAGE",
                  payload: {
                    id: generateMessageId(`msg-plan-step-${index}`),
                    role: "assistant",
                    content: (
                      <>
                        <Target className="h-4 w-4 inline mr-2 text-red-500" />
                        {t('agent.logs.event.messages.execStepPrefix')}{index + 1}: {step.name || step.id}
                        <br />
                        <span className="ml-6">{step.description || ''}</span>
                      </>
                    ),
                    timestamp: message.timestamp,
                    status: "completed",
                  }
                })
              })
            } else {
              // Basic plan information
              dispatch({
                type: "ADD_MESSAGE",
                payload: {
                  id: generateMessageId("msg-plan-start"),
                  role: "assistant",
                  content: (
                    <>
                      <FileText className="h-4 w-4 inline mr-2" />
                      {t('agent.logs.event.messages.planStart', { phase })}
                    </>
                  ),
                  timestamp: message.timestamp,
                  status: "completed",
                }
              })
            }
          }
          else {
            // Add to trace events for other types
            dispatch({ type: "ADD_TRACE_EVENT", payload: traceEventData })
          }
        }
        break

      case "task_completed":
        const taskData = normalizeTaskCompletedMessage(message)
        dispatch({
          type: "UPDATE_TASK_STATUS",
          payload: {
            status: taskData.status,
            completionOutcome: taskData.completionOutcome,
            runId: controlEnvelope.runId,
            stateVersion: controlEnvelope.stateVersion,
            controlState: controlEnvelope.controlState,
          }
        })
        dispatch({ type: "TRIGGER_TASK_UPDATE" })
        dispatch({ type: "SET_PROCESSING", payload: false })  // Stop processing on task completion

        if (!isMessageForOtherTask && currentState.taskId && isTerminalTaskStatus(taskData.status)) {
          // A settled turn can no longer be resent, whether it succeeded or
          // failed for a reason other than a missing connector input; see
          // the stash lifecycle in connector-runtime-api.ts's docs.
          // taskData.status is always "completed" or "failed" here
          // (NormalizedTaskCompletion narrows it), so this reads the same
          // terminal-status predicate the agent_error branch below reads,
          // rather than assuming this frame type alone proves settlement.
          // This frame type never opens the dialog itself.
          settleConnectorRuntimeTurn(currentState.taskId, false)
        }

        // Ends the stop intent when this completes the task the visitor
        // asked to stop. Rendering below is untouched.
        applySessionStop({ type: "TASK_COMPLETED", taskId: controlEnvelope.taskId })

        if (!taskData.success) {
          // error_details carries the structured reason ({code, ..., message});
          // fall back to its message when the terminal event omits output. The
          // broadcast always sets `result` === `output`, so `result` is not a
          // distinct source and is intentionally not consulted here.
          const failureReason =
            getString(taskData.output) ||
            getString(taskData.errorDetails?.message)
          // Coded failures (for example a quota-gate refusal, or "model_error"
          // for a model-provider failure) also notify the app layer so it can
          // surface them richly (see task-error-events). Stock xagent mounts a
          // no-op controller, so in stock xagent the bubble below is what the
          // user sees.
          // Not gated on failureReason: the coded dialog carries its own copy
          // and must still fire when the reason is empty. Tag it with the
          // event's own task id (not the currently-viewed one) so a dialog
          // cannot be attributed to the wrong task under a task-switch race.
          if (taskData.errorCode) {
            emitTaskError({
              code: taskData.errorCode,
              details: taskData.errorDetails,
              message: failureReason,
              taskId: controlEnvelope.taskId ?? currentState.taskId ?? null,
            })
          }
          // Surface the reason live as a failed assistant message so the
          // conversation matches what a page reload shows. Guard only against an
          // adjacent duplicate (same reason already the last message) rather than
          // a TTL cache — a re-executed turn re-emits the same terminal event and
          // a content-TTL dedup would drop the bubble, leaving an empty turn.
          const lastMessage = currentState.messages[currentState.messages.length - 1]
          const lastContent =
            typeof lastMessage?.content === "string" ? lastMessage.content : ""
          if (failureReason && (message.message_id || lastContent !== failureReason)) {
            dispatch({
              type: "ADD_MESSAGE",
              payload: {
                id: typeof message.message_id === "string" ? message.message_id : generateMessageId("msg-task-failed"),
                role: "assistant",
                // The reason verbatim, no prefix: a reload replays the
                // persisted transcript row (this same text), so any live-only
                // decoration would make the two views diverge.
                content: failureReason,
                timestamp: message.timestamp,
                status: "failed",
                // Terminal failure IS this turn's result. Without the flag the
                // conversation panel (which only shows user / isResult /
                // system-notice messages) filters the bubble out and falls back
                // to a virtual "unknown error" placeholder until reload.
                isResult: true,
              },
            })
          }
        }

        // Sync DAG execution status to completed/failed - but only for a
        // task that actually had a DAG plan running (currentState.dagExecution
        // already set by an earlier dag_execution/dag_step_* event this turn).
        // Fabricating a fresh DAGExecution for every completed task regardless
        // of pattern (the previous `else` branch here) made every flash/ReAct
        // task look like a completed zero-step DAG run to any DAG-only UI
        // (e.g. the Progress panel), popping it open for plain replies.
        if (currentState.dagExecution) {
          const updatedDAGExecution = {
            ...currentState.dagExecution,
            phase: taskData.status,
            updated_at: message.timestamp,
          }
          dispatch({ type: "SET_DAG_EXECUTION", payload: updatedDAGExecution })
        }

        // Mark that historical data should not be requested again for
        // completed/failed tasks - keyed by this event's OWN task (falling
        // back to the viewed one only if the envelope doesn't carry its
        // own id, matching the emitTaskError pattern above), not
        // unconditionally the viewed task: a background task's own
        // completion must not mark the currently-viewed task as "done
        // requesting history" if the two differ.
        const historicalDataTaskId = controlEnvelope.taskId ?? currentState.taskId
        if (historicalDataTaskId) {
          historicalDataRequestMapRef.current.set(historicalDataTaskId, true)
        }

        // Handle file outputs
        if (taskData.fileOutputs.length > 0) {
          const fileCount = taskData.fileOutputs.length
          const fileContent = (
            <>
              <FileText className="h-4 w-4 inline mr-2 text-green-500" />
              {t('agent.logs.event.messages.fileOutputsGenerated', { count: fileCount })}:
              <div className="mt-2 space-y-1">
                {taskData.fileOutputs.map((file: string | any, index: number) => {
                  let fileName, filePath
                  if (typeof file === 'object' && file !== null) {
                    fileName = file.filename || 'unknown'
                    filePath = file.file_id || ''
                  } else {
                    fileName = 'unknown'
                    filePath = ''
                  }

                  return (
                    <div key={index} className="flex items-center justify-between bg-muted/30 rounded p-2">
                      <span className="text-sm font-mono">{fileName}</span>
                      <button
                        onClick={() => {
                          if (options?.filesDisabled) return
                          // Dispatch custom event to open file preview with all files
                          const allFiles = normalizeGeneratedPreviewFiles(taskData.fileOutputs)

                          if (!filePath) {
                            return
                          }

                          window.dispatchEvent(new CustomEvent('openFilePreview', {
                            detail: {
                              filePath,
                              fileName,
                              allFiles,
                              currentIndex: index
                            }
                          }))
                        }}
                        disabled={options?.filesDisabled || !filePath}
                        className="text-xs bg-primary/10 hover:bg-primary/20 text-primary px-2 py-1 rounded transition-colors"
                      >
                        {t('agent.logs.event.messages.previewLabel')}
                      </button>
                    </div>
                  )
                })}
              </div>
            </>
          )

          if (!isDuplicateMessageForViewedTask(`📁 ${t('agent.logs.event.messages.fileOutputsGenerated', { count: fileCount })}`, "result")) {
            dispatch({
              type: "ADD_MESSAGE",
              payload: {
                id: generateMessageId("msg-file-outputs"),
                role: "assistant",
                content: fileContent,
                timestamp: message.timestamp,
                status: "completed",
                isFileOutput: true,
              }
            })
          }

          if (!options?.filesDisabled) {
            dispatchAutoOpenPreview(taskData.fileOutputs, dispatch)
          }
        }

        dispatch({ type: "SET_PROCESSING", payload: false })
        break

      case "dag_step_info":
        const stepInfo = message.data as {
          id: string
          name?: string
          description?: string
          status: StepExecution["status"]
          tool_name?: string
          tool_names?: string[]
          dependencies?: string[]
          started_at?: string | number
          completed_at?: string | number
          result_data?: unknown
          step_data?: unknown
          file_outputs?: string[]
        }
        const step: StepExecution = {
          id: stepInfo.id,
          name: stepInfo.name || stepInfo.id,
          description: stepInfo.description || "",
          status: stepInfo.status,
          tool_names: stepInfo.tool_name ? [stepInfo.tool_name] : stepInfo.tool_names || [],
          dependencies: stepInfo.dependencies || [],
          started_at: stepInfo.started_at,
          completed_at: stepInfo.completed_at,
          result_data: stepInfo.result_data,
          step_data: stepInfo.step_data,
          file_outputs: stepInfo.file_outputs || [],
        }
        dispatch({ type: "ADD_STEP", payload: step })

        // Update DAG execution status
        // Update overall DAG status based on step status
        if (currentState.dagExecution) {
          const updatedDAGExecution = { ...currentState.dagExecution }

          // Update DAG phase based on step status
          if (stepInfo.status === "running") {
            updatedDAGExecution.phase = "executing" as const
          } else if (stepInfo.status === "completed") {
            // Check if all steps are completed
            const allStepsCompleted = currentState.steps.every(step =>
              step.id === stepInfo.id ? stepInfo.status === "completed" : step.status === "completed"
            )
            if (allStepsCompleted) {
              updatedDAGExecution.phase = "completed" as const
            } else {
              updatedDAGExecution.phase = "executing" as const
            }
          } else if (stepInfo.status === "failed") {
            updatedDAGExecution.phase = "failed" as const
          }

          // Update timestamp
          updatedDAGExecution.updated_at = new Date().toISOString()

          dispatch({ type: "SET_DAG_EXECUTION", payload: updatedDAGExecution })
        }
        break

      case "dag_execution":
        // The bare-message-type shape (as opposed to the trace_event-wrapped
        // one handled above) - this is the one a LIVE single-connection
        // tracer actually uses while a task is running (see
        // create_stream_event's callers), not just a replay/legacy path, so
        // it needs the exact same turn_id-aware reset logic or a live run
        // transition here reintroduces the stale-steps/stale-created_at bug
        // this feature exists to fix.
        applyDagExecutionUpdate((message.data ?? {}) as Record<string, unknown>, message.timestamp)
        break


      case "task_paused": {
        console.trace('Original message:', JSON.stringify(message), 'Handler: handleMessage (task_paused)')
        const pausedReason = asMessageRecord(message.data).interruption_reason
          ?? asMessageRecord(message).interruption_reason
        dispatch({
          type: "UPDATE_TASK_STATUS",
          payload: {
            status: controlEnvelope.status || "paused",
            runId: controlEnvelope.runId,
            stateVersion: controlEnvelope.stateVersion,
            controlState: controlEnvelope.controlState || "paused",
            autoRecovery: normalizeAutoRecovery({ reason: pausedReason }),
          },
        })
        dispatch({ type: "SET_PROCESSING", payload: false })
        break
      }

      case "task_recovery_update": {
        const parsed = parseAutoResumeNotice(message)
        if (!parsed) break
        // Read before the check below records this notice's version.
        const knownVersion = taskStateVersionsRef.current.get(parsed.taskId)?.version
        // Not a versioned control event, but it names the fence it was
        // announced at: an older one is stale.
        if (!acceptTaskControlVersion(
          message,
          {
            isStateEvent: true,
            taskId: parsed.taskId,
            runId: parsed.notice.runId,
            stateVersion: parsed.notice.stateVersion,
          },
          taskStateVersionsRef.current,
        )) break
        dispatch({ type: "APPLY_AUTO_RESUME_NOTICE", payload: { ...parsed, knownVersion } })
        break
      }

      case "task_pause_requested":
        if (controlEnvelope.status) {
          dispatch({
            type: "UPDATE_TASK_STATUS",
            payload: {
              status: controlEnvelope.status,
              runId: controlEnvelope.runId,
              stateVersion: controlEnvelope.stateVersion,
              controlState: controlEnvelope.controlState || "pause_requested",
            },
          })
        }
        break

      case "task_waiting_for_user":
        console.trace('Original message:', JSON.stringify(message), 'Handler: handleMessage (task_waiting_for_user)')
        const waitingRoot = asMessageRecord(message)
        const waitingData = asMessageRecord(message.data)
        const waitingMessage = getString(waitingRoot.question)
          || getString(waitingData.question)
          || getString(waitingRoot.message)
          || getString(waitingData.message)
        const interactions = normalizeInteractions(
          waitingRoot.interactions ?? waitingData.interactions
        )
        const waitingRequestIdValue = waitingRoot.request_id ?? waitingData.request_id
        const waitingRequestId = typeof waitingRequestIdValue === "string"
          ? waitingRequestIdValue
          : undefined
        dispatch({
          type: "UPDATE_TASK_STATUS",
          payload: {
            status: controlEnvelope.status || "waiting_for_user",
            waitingQuestion: waitingMessage && waitingMessage !== "Task waiting for user response" ? waitingMessage : undefined,
            waitingInteractions: interactions.length > 0 ? interactions : undefined,
            waitingRequestId,
            runId: controlEnvelope.runId,
            stateVersion: controlEnvelope.stateVersion,
            controlState: controlEnvelope.controlState || "waiting_for_user",
          }
        })
        dispatch({ type: "SET_PROCESSING", payload: false })
        if (
          waitingRoot.display !== "timeline" && waitingData.display !== "timeline" &&
          waitingMessage &&
          waitingMessage !== "Task waiting for user response" &&
          !isDuplicateMessageForViewedTask(
            waitingMessage,
            'agent-message',
            waitingRequestId,
          )
        ) {
          dispatch({
            type: "ADD_MESSAGE",
            payload: {
              id: generateMessageId("msg-agent"),
              role: "assistant",
              content: waitingMessage,
              rawContent: waitingMessage,
              timestamp: message.timestamp,
              status: "running",
              isResult: true,
              interactions: interactions.length > 0 ? interactions : undefined,
              interactionRequestId: waitingRequestId,
            }
          })
        }
        break

      case "task_resumed":
        console.trace('Original message:', JSON.stringify(message), 'Handler: handleMessage (task_resumed)')
        dispatch({
          type: "UPDATE_TASK_STATUS",
          payload: {
            status: controlEnvelope.status || "running",
            runId: controlEnvelope.runId,
            stateVersion: controlEnvelope.stateVersion,
            controlState: controlEnvelope.controlState || "running",
          },
        })
        break

      case "agent_error":
        console.trace('Original message:', JSON.stringify(message), 'Handler: handleMessage (agent_error)')
        const agentErrorCode = getWebSocketErrorCode(message)
        const agentErrorMessage = agentErrorCode
          ? t(clientErrorTranslationKey(agentErrorCode))
          : getWebSocketErrorMessage(message, trustLegacyErrorProse)
        const agentErrorTaskStatus = getWebSocketTaskStatus(message)

        if (agentErrorTaskStatus) {
          dispatch({
            type: "UPDATE_TASK_STATUS",
            payload: {
              status: agentErrorTaskStatus,
              runId: controlEnvelope.runId,
              stateVersion: controlEnvelope.stateVersion,
              controlState: controlEnvelope.controlState,
            },
          })
          dispatch({ type: "TRIGGER_TASK_UPDATE" })
        }

        if (agentErrorTaskStatus === "failed" && currentState.dagExecution) {
          const updatedDAGExecution = {
            ...currentState.dagExecution,
            phase: "failed" as const,
            updated_at: message.timestamp,
          }
          dispatch({ type: "SET_DAG_EXECUTION", payload: updatedDAGExecution })
        }

        if (shouldStopProcessingForTaskStatus(agentErrorTaskStatus)) {
          dispatch({ type: "SET_PROCESSING", payload: false })
        }

        if (!isMessageForOtherTask && currentState.taskId && isTerminalTaskStatus(agentErrorTaskStatus)) {
          // Unlike task_completed and the terminal task_error frame, this
          // frame type is not on its own proof that the turn is over: its
          // status is a live DB read from a command-execution rejection path
          // (see the stash lifecycle docs) and can just as easily be
          // "running" as "failed". Read the same terminal-status check the
          // task_completed branch above satisfies unconditionally, so a
          // frame that only pauses processing (paused, waiting_for_user)
          // leaves a still-resendable message's stash alone.
          // This frame type never opens the dialog itself.
          settleConnectorRuntimeTurn(currentState.taskId, false)
        }

        dispatch({
          type: "ADD_MESSAGE",
          payload: {
            id: generateMessageId("msg"),
            role: "assistant",
            content: `${t('agent.logs.event.messages.errorPrefix')} ${agentErrorMessage || t('common.errors.unknown')}`,
            timestamp: message.timestamp,
            status: "failed",
          },
        })
        // A stop the server could not confirm is answered on this channel,
        // not on the terminal one, as an agent_error carrying
        // external_stop_not_applied. A stop that found the turn already
        // over, a server that predates that code, and any other
        // external-scope command that fails on this task are answered with
        // the same frame and no code at all. Either way the frame is broadcast
        // to every connection on the task and does not name which stop press
        // it answers, so for the task the visitor asked to stop it releases
        // the control rather than waiting out the local 30-second window and
        // leaves the intent standing (see STOP_NOT_APPLIED in
        // reduceSessionStop). Any other code names a different failure and
        // leaves the control alone.
        if (
          !getWebSocketErrorCodeField(message).present
          || agentErrorCode === "external_stop_not_applied"
        ) {
          applySessionStop({ type: "STOP_NOT_APPLIED", taskId: controlEnvelope.taskId })
        }
        break

      case "error":
      case "task_error": {
        console.trace('Original message:', JSON.stringify(message), 'Handler: handleMessage (error)')
        const errorFrame = projectErrorFrameForDisplay(message, {
          trustLegacyErrorProse,
          translate: t,
          controlEnvelope,
          stopIntentTaskId: sessionStopRef.current.intentTaskId,
        })

        if (errorFrame.taskStatus) {
          dispatch({ type: "UPDATE_TASK_STATUS", payload: { status: errorFrame.taskStatus } })
          dispatch({ type: "TRIGGER_TASK_UPDATE" })
        }
        if (errorFrame.stopsProcessing) {
          dispatch({ type: "SET_PROCESSING", payload: false })
        }

        // errorFrame.isTerminal (message.type === "task_error") is this
        // family's terminal-status predicate: a task_error frame is only
        // ever emitted after its lease owner commits a terminal status, so
        // the frame type itself already reads as terminal here -- unlike
        // agent_error above, which shares this branch's underlying
        // task_status field with a live, possibly non-terminal DB read.
        // The sibling `error` type carries the same task_status field for
        // an unrelated meaning (a rejection while the turn is still
        // running), which is why this checks the frame type and not the
        // status value directly.
        //
        // Kept outside the bubble-dedup guard below, matching the
        // task_completed and agent_error settle-task call sites above: a
        // terminal frame whose dedup text collapses into an existing bubble
        // (most often a version-less frame, since a version makes the dedup
        // key occurrence-specific) must still resolve this turn's dialog and
        // stash even when the bubble it would have added does not render.
        if (errorFrame.isTerminal && !isMessageForOtherTask && currentState.taskId) {
          // A trigger code both opens the dialog and settles the turn in
          // the same call; any other terminal code just settles it. See
          // settleConnectorRuntimeTurn's own docs for what "settles" means.
          settleConnectorRuntimeTurn(
            currentState.taskId,
            errorFrame.terminalErrorCode !== null
              && isConnectorRuntimeDialogTriggerCode(errorFrame.terminalErrorCode),
          )
        }

        const { endsStopIntent, isVisitorStoppedTurn } = errorFrame
        const errorCode = getWebSocketErrorCode(message)
        // The stopped mark is recorded before, and independent of, the bubble
        // check below: a frame that names a message_id adds no bubble, yet its
        // turn is still the stopped one. The turn is identified by the user
        // message that opened it; with no user message there is nothing to
        // anchor to and the turn keeps the failed rendering.
        if (isVisitorStoppedTurn) {
          const anchorMessage = [...currentState.messages]
            .reverse()
            .find((candidate) => candidate.role === "user")
          if (anchorMessage) {
            dispatch({
              type: "MARK_TURN_STOPPED",
              payload: { anchorMessageId: anchorMessage.id },
            })
          }
        }
        // A frame that names a message_id adds no bubble below: that message
        // is drawn from its own display event. It still ends the intent.
        if (
          !message.message_id && !isDuplicateMessageForViewedTask(
            errorFrame.dedupText,
            "agent-error",
            errorFrame.occurrenceIdentity,
          )
        ) {
          dispatch({
            type: "ADD_MESSAGE",
            payload: isVisitorStoppedTurn
              ? {
                  id: generateMessageId("msg-stopped"),
                  role: "assistant",
                  // The client's own sentence for the interruption code, read
                  // from the same table as every other coded bubble and with no
                  // error prefix. A reload replays the persisted English row,
                  // so the two views differ only in language.
                  content: errorFrame.bubbleContent,
                  timestamp: message.timestamp,
                  // The turn ended because the visitor asked it to, so this is
                  // the turn's result. status is not "failed", which keeps the
                  // bubble out of ChatMessage's red branch; isResult lets it
                  // through the conversation panel's filter, which renders
                  // only user / isResult / system-notice messages.
                  status: "completed",
                  isResult: true,
                }
              : {
                  id: generateMessageId("msg-error"),
                  role: "assistant",
                  content: errorFrame.bubbleContent,
                  timestamp: message.timestamp,
                  status: "failed",
                  isResult: errorFrame.isResult,
                  isSystemNotice: errorCode === "message_outcome_unknown"
                    || (!errorFrame.isTerminal && isInputReviewErrorCode(errorCode)),
                },
          })
        }
        if (endsStopIntent) {
          applySessionStop({ type: "STOPPED_TASK_FAILED" })
        }
        break
      }

      case "message_received":
        console.trace('Original message:', JSON.stringify(message), 'Handler: handleMessage (message_received)')
        // User message confirmation
        dispatch({ type: "SET_PROCESSING", payload: true })
        break

      case "historical_data_complete":
        // Historical data loading complete. The ref write is not gated by
        // the dispatch wrapper's task scoping - a stray background task's
        // own historical_data_complete must not end the VIEWED task's
        // history-loading state early.
        if (!isMessageForOtherTask) isHistoricalDataLoadingRef.current = false
        dispatch({ type: "SET_HISTORY_LOADING", payload: false })
        dispatch({ type: "SYNC_PROCESSING_STATUS" })

        // If we're in replay mode, initialize the replay scheduler
        if (currentState.isReplaying && currentState.replayTaskId && currentState.replayEventCache.length > 0) {
          initializeReplayScheduler()
        }
        break
    }
  }, [applySessionStop, trustLegacyErrorProse])

  const handleSessionMessage = (
    message: WebSocketMessage,
    owner: SessionMessageOwner,
  ) => {
    if (!mountedRef.current) return
    if (
      owner.connectionIdentity !== sessionConnectionIdentityRef.current
    ) {
      return
    }

    // Handled ahead of the phase routing below and in every phase, so it is
    // never held with a replacement conversation's pre-adoption frames. It
    // counts only on a socket whose capabilities declared it.
    if (message.type === "conversation_attached") {
      const attachment = sessionAttachmentRef.current
      if (
        attachment.connectionIdentity === owner.connectionIdentity
        && attachment.capability === "declared"
      ) {
        writeSessionAttachment({ ...attachment, attached: true })
      }
      return
    }

    if (message.type === "conversation_reload_required") {
      const binding = extractSessionTaskBinding(message)
      const lifecycle = sessionConversationRef.current
      if (
        !binding.present
        || !binding.valid
        || (
          lifecycle.phase !== "bound"
          && lifecycle.phase !== "reset_requested"
        )
        || lifecycle.connectionIdentity !== owner.connectionIdentity
        || lifecycle.taskId !== binding.taskId
        || sessionTaskIdRef.current !== binding.taskId
      ) {
        return
      }
      requireSessionReload(
        new Error("The current conversation cannot be restored; reload required.")
      )
      return
    }

    if (message.type === "conversation_reset") {
      const resetFlight = sessionResetFlightRef.current
      if (
        !resetFlight
        || resetFlight.connectionIdentity !== owner.connectionIdentity
        || resetFlight.deliveryGeneration !== deliveryGenerationRef.current
      ) {
        return
      }

      const transition = dispatchSessionConversation({
        type: "SESSION_RESET_ACKNOWLEDGED",
        connectionIdentity: owner.connectionIdentity,
      })
      if (!transition.accepted) return

      const retiredTaskId = sessionTaskIdRef.current
      if (retiredTaskId !== null) {
        retiredSessionTaskIdsRef.current.add(retiredTaskId)
        if (
          retiredSessionTaskIdsRef.current.size
          > MAX_RETIRED_SESSION_TASK_IDS
        ) {
          const oldestTaskId =
            retiredSessionTaskIdsRef.current.values().next().value
          if (oldestTaskId !== undefined) {
            retiredSessionTaskIdsRef.current.delete(oldestTaskId)
          }
        }
      }

      sessionResetFlightRef.current = null
      clearTimeout(resetFlight.timeout)
      sessionTaskIdRef.current = null
      taskStateVersionsRef.current.clear()
      stateRef.current.replayScheduler?.stop()
      pendingTaskToExecuteRef.current = null
      lastConnectedTaskId.current = null
      recentMessagesRef.current.clear()
      const pending = pendingMessageRef.current
      pendingMessageRef.current = null
      setPendingMessage(null)
      pending?.reject?.(
        new Error("Message delivery was cancelled by conversation reset.")
      )

      const nextDeliveryGeneration = deliveryGenerationRef.current + 1
      deliveryGenerationRef.current = nextDeliveryGeneration
      setDeliveryGeneration(nextDeliveryGeneration)
      dispatch({ type: "RESET_SESSION_CONVERSATION" })
      resetFlight.resolve()
      return
    }

    const binding = extractSessionTaskBinding(message)
    if (binding.present && !binding.valid) return

    const taskInfoData = getSessionTaskInfoData(message)
    if (taskInfoData) {
      const taskId = parseInteger(taskInfoData.id)
      if (
        taskId === undefined
        || taskId <= 0
        || retiredSessionTaskIdsRef.current.has(taskId)
        || (
          binding.present
          && binding.valid
          && binding.taskId !== taskId
        )
      ) {
        return
      }
      const lifecycle = sessionConversationRef.current
      const isFlushingCandidate =
        flushingSessionPreAdoptionCandidateRef.current === message
      if (
        !isFlushingCandidate
        && (
          lifecycle.phase === "replacement_sending"
          || lifecycle.phase === "replacement_awaiting_task"
        )
      ) {
        if (!bufferSessionPreAdoptionFrame(message, owner, taskId)) return
        const buffer = sessionPreAdoptionBufferRef.current
        if (
          lifecycle.phase === "replacement_awaiting_task"
          && buffer?.timeout != null
        ) {
          flushingSessionPreAdoptionCandidateRef.current = message
          try {
            handleSessionMessage(message, owner)
          } finally {
            flushingSessionPreAdoptionCandidateRef.current = null
          }
        }
        return
      }
      if (
        lifecycle.phase === "reset_requested"
        || lifecycle.phase === "replacement_ready"
        || lifecycle.phase === "reload_required"
      ) {
        return
      }

      const currentTaskId = sessionTaskIdRef.current
      if (
        currentTaskId !== null
        && currentTaskId !== taskId
      ) {
        requireSessionReload(
          new Error("Session task lineage changed without a reset; reload required.")
        )
        return
      }
      const taskInfoEnvelope = extractTaskControlEnvelope(message)
      if (
        taskInfoEnvelope.taskId !== taskId
        || !canAcceptTaskControlVersion(
          message,
          taskInfoEnvelope,
          taskStateVersionsRef.current,
        )
      ) {
        return
      }

      const bufferedFrames = lifecycle.phase === "replacement_awaiting_task"
        ? sessionPreAdoptionBufferRef.current?.frames.slice() ?? []
        : []
      discardSessionPreAdoptionBuffer()
      const transition = dispatchSessionConversation({
        type: "SESSION_TASK_INFO",
        connectionIdentity: owner.connectionIdentity,
        taskId,
      })
      if (!transition.accepted || transition.next.phase !== "bound") return
      if (!acceptTaskControlVersion(
        message,
        taskInfoEnvelope,
        taskStateVersionsRef.current,
      )) return
      sessionTaskIdRef.current = taskId
      dispatch({
        type: "ADOPT_SESSION_TASK",
        payload: {
          taskId,
          task: taskFromTaskInfoData(taskInfoData, taskId),
        },
      })
      for (const bufferedFrame of bufferedFrames) {
        handleSessionMessage(bufferedFrame, owner)
      }
      return
    }

    if (
      binding.present
      && binding.valid
      && retiredSessionTaskIdsRef.current.has(binding.taskId)
    ) {
      return
    }
    if (
      sessionConversationRef.current.phase === "replacement_sending"
      || sessionConversationRef.current.phase === "replacement_awaiting_task"
    ) {
      bufferSessionPreAdoptionFrame(message, owner)
      return
    }
    if (
      sessionConversationRef.current.phase === "reset_requested"
      || sessionConversationRef.current.phase === "replacement_ready"
      || sessionConversationRef.current.phase === "reload_required"
    ) return
    if (binding.present && binding.valid) {
      if (
        sessionTaskIdRef.current === null
      ) {
        return
      }
      if (sessionTaskIdRef.current !== binding.taskId) {
        requireSessionReload(
          new Error("Session task lineage changed without a reset; reload required.")
        )
        return
      }
    }

    handleMessage(message, dispatch, stateRef.current, {
      skipHistory: true,
      filesDisabled,
    })
  }

  useLayoutEffect(() => {
    sessionMessageHandlerRef.current = handleSessionMessage
  }, [handleSessionMessage])

  const getLLMIdsFromConfig = (config?: any) => {
    if (!config || !config.model) {
      return null
    }

    // Debug log to see what config is being passed
    console.log('getLLMIdsFromConfig called with:', config)

    // Always return exactly 4 elements in fixed order: [default, fast_small, vision, compact]
    // Use null for unconfigured models
    const llmIds = [
      config.model,                           // Default model (required)
      config.smallFastModel || null,         // Fast small model (optional)
      config.visualModel || null,            // Vision model (optional)
      config.compactModel || null            // Compact model (optional)
    ]

    return llmIds
  }

  const beginSessionMessageDelivery = useCallback(() => {
    if (!mountedRef.current) return
    const nextCount = messageDeliveryCountRef.current + 1
    messageDeliveryCountRef.current = nextCount
    setMessageDeliveryCount(nextCount)
  }, [])

  const endSessionMessageDelivery = useCallback(() => {
    const nextCount = Math.max(0, messageDeliveryCountRef.current - 1)
    messageDeliveryCountRef.current = nextCount
    if (mountedRef.current) setMessageDeliveryCount(nextCount)
  }, [])

  const sendMessage = useCallback(async (message: string, config?: any, files?: File[], options?: SendMessageOptions) => {
    console.log('🚀 sendMessage called:', { message, files: files?.map(f => f.name), taskId: state.taskId })

    if (sessionTransport && !mountedRef.current) {
      throw new Error("Message not sent: the Session chat is closed.")
    }
    if (
      filesDisabled
      && files
      && files.length > 0
    ) {
      throw new Error("Files are disabled for this conversation.")
    }
    const uploadedFiles = options?.uploadedFiles ?? []
    if (uploadedFiles.length > 0 && !sessionAttachmentsRef.current) {
      throw new Error("Attachments are not available for this conversation.")
    }
    if (sessionTransport && sessionConversationRef.current.phase === "reset_requested") {
      throw new Error(
        "Message delivery is blocked while conversation reset is pending."
      )
    }

    // Mirrors stableUserMessageId's trim guard. `config` is untyped, so a
    // blank id would reach userTurnMessageId and mint a bare
    // `msg-user-turn-` that every other blank-id turn collides on.
    const requestedClientMessageId =
      typeof config?.clientMessageId === 'string'
        ? config.clientMessageId.trim()
        : ''
    const clientMessageId = requestedClientMessageId || generateClientMessageId()
    const requestId = typeof config?.metadata?.request_id === 'string'
      ? config.metadata.request_id
      : undefined
    // The earlier conversation a new one continues from. Only the Session
    // window's taskless chat can carry it, and only on the message that starts
    // a new conversation; the frame check validates its range.
    const sourceTaskId: unknown = config?.sourceTaskId
    if (sourceTaskId !== undefined && typeof sourceTaskId !== "number") {
      throw new MessageDeliveryError("Message not sent: the conversation source is not valid.", "not_sent")
    }
    if (sourceTaskId !== undefined && !sessionTransport?.allowTasklessChat) {
      throw new MessageDeliveryError("A conversation source is not supported for this connection.", "not_sent")
    }
    const sessionDeliveryOwner =
      sessionTransport && sessionConnectionIdentityRef.current
        ? {
          connectionIdentity: sessionConnectionIdentityRef.current,
          deliveryGeneration: deliveryGenerationRef.current,
        }
        : null

    // Optimistic copy of the sender's own bubble, added once delivery is
    // acknowledged. The live user_message trace event only exists after the
    // agent run actually starts — a run refused before that (e.g. the quota
    // gate) never emits it, so without this copy the sender's message stays
    // invisible until a reload replays the persisted transcript row. The
    // reducer reconciles by turn id / content, keeping the persisted event
    // when it already arrived and replacing this copy when it arrives later.
    // Also the one place that stashes this turn as the connector-runtime
    // dialog's resend candidate: this guard is exactly "delivered, and the
    // user is still looking at this task", which is the stash's own
    // definition (see connector-runtime-api.ts's docs).
    const addOptimisticUserMessage = (intendedTaskId: number | null) => {
      // Delivery acknowledgement can arrive after the user has navigated to a
      // different task. Never append this turn to whichever task happens to be
      // active when the async send resumes.
      if (sessionTransport) {
        if (
          !mountedRef.current
          || !sessionDeliveryOwner
          || sessionDeliveryOwner.connectionIdentity
            !== sessionConnectionIdentityRef.current
          || sessionDeliveryOwner.deliveryGeneration
            !== deliveryGenerationRef.current
        ) {
          return
        }
      } else if (
        intendedTaskId === null
        || stateRef.current.taskId !== intendedTaskId
      ) {
        return
      }
      if (typeof intendedTaskId === "number") {
        connectorRuntimeDialogRef.current.recordDelivery({
          taskId: intendedTaskId,
          clientMessageId,
          text: message,
          files: files ?? [],
        })
      }
      let content: React.ReactNode = message
      const bubbleFiles = [
        ...(files ?? []).map(f => ({ name: f.name, type: f.type, size: f.size })),
        ...uploadedFiles.map(f => ({ name: f.name, type: f.type, size: f.size })),
      ]
      if (bubbleFiles.length > 0) {
        content = (
          <UserMessageContent
            message={message}
            files={bubbleFiles}
          />
        )
      }
      dispatch({
        type: "ADD_MESSAGE",
        payload: {
          id: userTurnMessageId(clientMessageId),
          role: "user",
          content: content,
          timestamp: Date.now().toString(),
          isOptimistic: true,
        }
      })
    }

    const targetTaskId = typeof config?.targetTaskId === 'number' ? config.targetTaskId : null
    if (
      sessionTransport
      && targetTaskId !== null
      && state.taskId !== targetTaskId
    ) {
      throw new Error(
        "The Session connection does not own the requested task."
      )
    }

    if (sessionTransport?.allowTasklessChat) {
      if (!sessionDeliveryOwner) {
        throw new MessageDeliveryError(
          "Message not sent: the Session connection is not ready.",
          "not_sent",
          { errorCode: "connection_not_ready" },
        )
      }

      if (sessionConversationRef.current.phase === "reload_required") {
        throw new Error("Conversation outcome is unknown; reload required.")
      }
      if (
        sessionConversationRef.current.phase === "replacement_sending"
        || sessionConversationRef.current.phase === "replacement_awaiting_task"
      ) {
        throw new Error("The replacement conversation is already starting.")
      }
      // Every Session frame omits the task id, so a source sent while a
      // conversation is bound would ride on a follow-up into that conversation,
      // which the session server refuses.
      if (
        sourceTaskId !== undefined
        && sessionConversationRef.current.phase !== "unbound"
        && sessionConversationRef.current.phase !== "replacement_ready"
      ) {
        throw new MessageDeliveryError(
          "Message not sent: a conversation source can only start a new conversation.",
          "not_sent",
        )
      }

      const startsReplacementConversation =
        sessionConversationRef.current.phase === "replacement_ready"
      const replacementSendStillOwned = () => {
        const lifecycle: SessionConversationState = sessionConversationRef.current
        return (
          mountedRef.current
          && sessionConnectionIdentityRef.current === sessionDeliveryOwner.connectionIdentity
          && deliveryGenerationRef.current === sessionDeliveryOwner.deliveryGeneration
          && lifecycle.phase === "replacement_sending"
        )
      }
      if (startsReplacementConversation) {
        const transition = dispatchSessionConversation({
          type: "SESSION_REPLACEMENT_SENDING",
          connectionIdentity: sessionDeliveryOwner.connectionIdentity,
        })
        if (!transition.accepted) {
          throw new Error("The replacement conversation is no longer available.")
        }
        beginSessionPreAdoptionBuffer(sessionDeliveryOwner.connectionIdentity)
      }
      // Staged before the delivery acknowledgement is awaited, keyed by this
      // turn's own clientMessageId, so a terminal frame that arrives first
      // (the transport gives no ordering guarantee between the two) can
      // still claim it in openForTask. Only staged when there is a task to
      // attribute it to -- addOptimisticUserMessage below only records the
      // delivery under the same condition.
      if (typeof state.taskId === "number") {
        connectorRuntimeDialogRef.current.stagePendingDelivery({
          taskId: state.taskId, clientMessageId, text: message, files: files ?? [],
        })
      }
      const fileIds = uploadedFiles.map(file => file.fileId)
      // A send without a source passes the same five arguments as always.
      const chatArgs: Parameters<typeof sendChatMessage> = sourceTaskId === undefined
        ? [message, files, config?.force, clientMessageId, requestId]
        : [message, files, config?.force, clientMessageId, requestId, undefined, sourceTaskId]
      beginSessionMessageDelivery()
      try {
        await sendChatWithResend(
          chatArgs,
          () => {
            // A resend runs on the connection that replaced the lost one.
            sessionDeliveryOwner.connectionIdentity =
              sessionConnectionIdentityRef.current ?? sessionDeliveryOwner.connectionIdentity
            // The ids are checked against the attachments current at each
            // attempt, a resend included: the session that replaced a lost
            // connection may have lowered the limit or withdrawn attachments,
            // and with no limit the frame check refuses the ids.
            if (fileIds.length > 0) {
              chatArgs[5] = { fileIds, maxFileIds: sessionAttachmentsRef.current?.maxFiles }
            }
          },
        )
        if (startsReplacementConversation) {
          if (!replacementSendStillOwned()) {
            return
          }
          const transition = dispatchSessionConversation({
            type: "SESSION_REPLACEMENT_ACCEPTED",
            connectionIdentity: sessionDeliveryOwner.connectionIdentity,
          })
          if (!transition.accepted) return
          activateSessionPreAdoptionBuffer(sessionDeliveryOwner.connectionIdentity)
        }
        addOptimisticUserMessage(state.taskId)
      } catch (error) {
        if (startsReplacementConversation) {
          if (!replacementSendStillOwned()) {
            throw error
          }
          const candidatePresent = sessionPreAdoptionBufferRef.current?.candidate != null
          const disposition = (
            error
            && typeof error === "object"
            && "disposition" in error
            && (
              error.disposition === "not_sent"
              || error.disposition === "rejected"
              || error.disposition === "outcome_unknown"
            )
          )
            ? error.disposition
            : "outcome_unknown"
          if (disposition === "outcome_unknown" || candidatePresent) {
            requireSessionReload(
              error instanceof Error
                ? error
                : new Error("Conversation outcome is unknown; reload required."),
            )
          } else {
            discardSessionPreAdoptionBuffer()
            dispatchSessionConversation({
              type: "SESSION_REPLACEMENT_REJECTED",
              connectionIdentity: sessionDeliveryOwner.connectionIdentity,
            })
          }
        }
        throw error
      } finally {
        endSessionMessageDelivery()
        // A no-op if addOptimisticUserMessage already redeemed the ticket
        // above (recordDelivery removes the pending entry on success): this
        // only has anything to withdraw when the try block threw or
        // returned early before reaching that call.
        connectorRuntimeDialogRef.current.discardPendingDelivery(clientMessageId)
      }
      return
    }

    if (targetTaskId !== null && state.taskId !== targetTaskId) {
      connectorRuntimeDialogRef.current.stagePendingDelivery({
        taskId: targetTaskId, clientMessageId, text: message, files: files ?? [],
      })
      try {
        await queuePendingMessage({
          message,
          files,
          targetTaskId,
          force: config?.force,
          clientMessageId,
        })
      } catch (error) {
        connectorRuntimeDialogRef.current.discardPendingDelivery(clientMessageId)
        throw error
      }
      // The discard above cannot become a `finally` the way the session
      // path's one below is, because the call on the next line -- which is
      // what promotes the staged candidate into the resend stash, through
      // recordDelivery -- sits outside the try. A `finally` would run
      // before it and withdraw the candidate, and recordDelivery ignores a
      // delivery it has no staged entry for, so every message queued for
      // another task would stop leaving a resend candidate behind at all.
      // Making the two paths one shape means moving this promotion inside
      // the try first; that regrouping is tracked in xorbitsai/xagent#2488.
      addOptimisticUserMessage(targetTaskId)
      return
    }

    if (!state.taskId) {
      const canAdoptCreatedTask = () => mountedRef.current && (options?.canAdoptCreatedTask?.() ?? true)
      if (!canAdoptCreatedTask()) return
      let adopted = false
      // Create a new task via API
      try {
        const apiUrl = getApiUrl()

        // Build internal model identifiers from config
        const llmIds = getLLMIdsFromConfig(config)

        // Note: Files will be uploaded via WebSocket after task creation
        // The backend TaskCreateRequest expects JSON with 'files' as a list of filenames (strings)
        // Since we haven't uploaded files yet, we don't include them in the task creation request
        const executionMode = config?.executionMode?.mode || (config?.agentId ? "balanced" : undefined)

        const requestBody: any = {
          title: message,
          description: message,
          memory_similarity_threshold: config?.memorySimilarityThreshold ?? 1.5,
        }
        if (executionMode) {
          requestBody.execution_mode = executionMode
        }

        // Upload files first if present
        if (files && files.length > 0) {
          const filesToUpload = files.filter(f => !(f as any).file_id)
          const uploadedFileIds = files.filter(f => (f as any).file_id).map(f => (f as any).file_id)

          if (filesToUpload.length > 0) {
            const formData = new FormData()
            filesToUpload.forEach(f => formData.append('files', f))
            formData.append('task_type', executionMode ?? 'general')

            try {
              const uploadResponse = await apiRequest(`${getUploadApiUrl()}/api/files/upload`, {
                method: 'POST',
                body: formData
              })

              const parsed = await parseApiResponse(uploadResponse)

              if (
                !uploadResponse.ok
                || !isJsonRecord(parsed.data)
                || parsed.data.success !== true
                || !Array.isArray(parsed.data.files)
              ) {
                const uploadError = classifyUploadError(uploadResponse, parsed)
                throw new Error(t(clientErrorTranslationKey(uploadError.errorCode)))
              }
              const newFileIds = normalizeUploadFileIds(
                parsed.data.files.map(f => isJsonRecord(f) ? f.file_id : null),
                filesToUpload.length,
              )
              if (!newFileIds) {
                throw new Error(t("clientErrors.uploadFailed"))
              }
              uploadedFileIds.push(...newFileIds)
            } catch (e) {
              console.error('Error uploading files before task creation:', e)
              throw e
            }
          }

          const normalizedFileIds = normalizeUploadFileIds(
            uploadedFileIds,
            files.length,
          )
          if (!normalizedFileIds) {
            throw new Error(t("clientErrors.uploadFailed"))
          }
          requestBody.files = normalizedFileIds
        }

        // Agent chats should use the published agent's own model configuration.
        if (llmIds && !config?.agentId) {
          requestBody.llm_ids = llmIds
        }

        if (config?.executionMode?.processDescription) {
          requestBody.process_description = config.executionMode.processDescription
        }
        if (config?.executionMode?.examples) {
          requestBody.examples = config.executionMode.examples
        }
        if (config?.agentId) {
          requestBody.agent_id = config.agentId
        }
        if (config?.agentType) {
          requestBody.agent_type = config.agentType
        }
        if (config?.agentConfig) {
          requestBody.agent_config = config.agentConfig
        }
        if (config?.runtimeExtensions) {
          requestBody.runtime_extensions = config.runtimeExtensions
        }

        // Uploads may have completed after the user left this draft.
        if (!canAdoptCreatedTask()) return
        const response = await apiRequest(`${apiUrl}/api/chat/task/create`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(requestBody),
        })

        if (response.ok) {
          const taskData = await response.json()
          // The server may already have created A, but it no longer owns the
          // route or provider state once the user has opened draft B.
          if (!canAdoptCreatedTask()) return
          adopted = true
          const newTaskId = taskData.task_id
          options?.onCreatedTask?.(newTaskId)

          console.log('✅ Task created successfully:', {
            taskId: newTaskId,
            taskIdType: typeof newTaskId,
            taskData: taskData,
            status: taskData.status
          })

          console.log('🎯 About to call setTaskId with payload:', newTaskId)
          setTaskId(newTaskId)
          console.log('🎯 setTaskId completed')

          dispatch({
            type: "SET_TASK_RUNTIME_EXTENSIONS",
            payload: {
              taskId: newTaskId,
              extensions: normalizeTaskRuntimeExtensions(taskData.runtime_extensions),
            },
          })

          // Create a new task from response
          const newTask: Task = {
            id: newTaskId.toString(),
            title: taskData.title,
            status: normalizeTaskStatus(taskData.status) || "pending",
            description: taskData.description || message,
            createdAt: taskData.created_at,
            updatedAt: taskData.updated_at,
            modelId: taskData.model_id,
            smallFastModelId: taskData.small_fast_model_id,
            visualModelId: taskData.visual_model_id,
            compactModelId: taskData.compact_model_id,
            modelName: taskData.model_name || taskData.modelName, // API response field
            smallFastModelName: taskData.small_fast_model_name || taskData.smallFastModelName, // API response field
            visualModelName: taskData.visual_model_name || taskData.visual_model_name,
            compactModelName: taskData.compact_model_name || taskData.compact_model_name,
            executionMode: taskData.execution_mode,
            isDag: taskData.is_dag,
            agentId: taskData.agent_id,
            agentName: taskData.agent_name,
            agentLogoUrl: taskData.agent_logo_url,
            conversationStorageVersion: taskData.conversation_storage_version,
            waitingQuestion: taskData.waiting_question,
            waitingInteractions: normalizeInteractions(taskData.waiting_interactions),
            runId: taskData.run_id,
            stateVersion: taskData.state_version,
            controlState: taskData.control_state,
          }
          dispatch({ type: "SET_CURRENT_TASK", payload: newTask })
          dispatch({ type: "TRIGGER_TASK_UPDATE" })

          // User message will be handled by backend via trace event

          // A create report with a context value the user can fill here holds
          // the message before it is staged or queued, so nothing of it reaches
          // the transport or the dialog's resend candidates until the dialog
          // ends the hold (FirstGateDecision); the per-turn check still decides
          // whether the turn runs. Opened here, after the create response, not
          // from a mount effect: a gate opened in the provider's mount commit is
          // cleared by its identity effect. The pending-task auto-send never
          // sends this task's description, which is the held text: its ref is
          // cleared here, and this task's pending task_info never arms it.
          if (shouldHoldFirstMessage(taskData.connector_runtime_requirements)) {
            // null: no provider mounted, or an id it rejects; nothing is held.
            const held = connectorRuntimeDialogRef.current.openFirstGate(newTaskId)
            firstGateTaskIdRef.current = newTaskId
            pendingTaskToExecuteRef.current = null
            const decision = held === null ? null : await held
            if (decision === "discarded") return
            if (decision === "cleared") {
              // Fixed, translated text naming nothing the user typed. The new
              // conversation page rethrows it to ChatInput, which shows a userFacing
              // message instead of "please try again"; the agent page's handler
              // toasts any error's message itself.
              throw Object.assign(new Error(t(FIRST_GATE_CLEARED_MESSAGE_KEY)), { userFacing: true })
            }
          }

          // For new tasks, always send chat message to support file uploads
          console.log('💬 Queuing chat message for new task:', {
            taskId: newTaskId,
            taskStatus: taskData.status,
            hasFiles: files && files.length > 0
          })

          // Do not clear the composer until the newly connected task socket
          // confirms that the message was durably accepted.
          connectorRuntimeDialogRef.current.stagePendingDelivery({
            taskId: newTaskId, clientMessageId, text: message, files: files ?? [],
          })
          try {
            await queuePendingMessage({
              message,
              files,
              targetTaskId: newTaskId,
              force: config?.force,
              clientMessageId,
              requestId,
            })
          } catch (error) {
            connectorRuntimeDialogRef.current.discardPendingDelivery(clientMessageId)
            throw error
          }
          addOptimisticUserMessage(newTaskId)
        } else {
          const parsed = await parseApiResponse(response)
          const errorMessage = getApiErrorMessage(
            response,
            parsed,
            t("builds.list.chat.sendFailed") || "Failed to create task",
          )
          console.error('Failed to create task:', errorMessage)
          throw new Error(errorMessage)
        }
      } catch (error) {
        if (!adopted && !canAdoptCreatedTask()) return
        console.error('Error creating task:', error)
        throw error
      }
    }

    // For existing tasks (when task already exists)
    if (state.taskId) {
      console.log('🚀 AppContext sendMessage - sending chat message:', {
        message,
        files: files?.map(f => f.name) || [],
        hasFiles: files && files.length > 0,
        taskId: state.taskId
      })

      // The backend executes the turn as an independent background task and
      // can start broadcasting its own dag_execution/trace events before this
      // ack resolves - capture the pre-send dagExecution (its turn_id and its
      // created_at) so the reset below can detect that case and skip
      // clearing, rather than wiping out the new turn's own freshly-arrived
      // state. The pre-send currentTask is captured for the optimistic
      // status flip further below, for the same reason: events landing
      // during the await must be able to veto it.
      const dagExecutionBeforeSend = stateRef.current.dagExecution
      const dagTurnIdBeforeSend = dagExecutionBeforeSend?.turn_id
      const currentTaskBeforeSend = stateRef.current.currentTask

      // Wait for the server's durable-delivery acknowledgement. If the socket
      // is disconnected or the backend rejects the turn, this throws and the
      // composer keeps both its text and attached files. The DAG reset below
      // deliberately runs only after this succeeds - clearing dagExecution/
      // steps first and then throwing would remove the Progress panel and its
      // header toggle for a run that never actually changed.
      connectorRuntimeDialogRef.current.stagePendingDelivery({
        taskId: state.taskId, clientMessageId, text: message, files: files ?? [],
      })
      try {
        await sendChatWithResend([message, files, config?.force, clientMessageId, requestId])
      } catch (error) {
        connectorRuntimeDialogRef.current.discardPendingDelivery(clientMessageId)
        throw error
      }

      // A prior turn's DAG plan/steps must not linger into this turn - otherwise
      // the Progress panel would auto-open (or stay open) showing stale steps
      // from a different execution mode/run before this turn's own dag_execution
      // event (if any) arrives. But sending into a run that's still actively
      // going - answering a mid-run clarification, or the "live guidance" input
      // ChatInput allows while running/paused/waiting_for_user (see
      // ChatInput.tsx's `allowsLiveGuidanceInput`; the task page never passes
      // onSend/onSendInteraction, so all of these fall back to this same
      // sendMessage) - is a CONTINUATION of that run, not a new turn. Clearing
      // here would wipe out the in-progress DAG plan/steps the Progress panel
      // is actively showing.
      const isContinuingActiveRun =
        state.currentTask?.status === "running"
        || state.currentTask?.status === "paused"
        || state.currentTask?.status === "waiting_for_user"
      // Prefer turn_id equality when BOTH sides actually have one - it sees
      // through the task_completed handler's clone-for-phase-sync (which
      // makes a NEW object with the SAME turn_id, see that handler above),
      // where reference equality alone would wrongly look like "something
      // new arrived" and skip the reset. But turn_id is optional (older
      // backends/patterns that never set it), so a no-turn_id fallback is
      // still needed - and it compares created_at, not object reference:
      // the same clone-for-phase-sync problem applies on this path too (a
      // no-turn_id dagExecution recloned by a racing task_completed changed
      // reference but kept its created_at, so it still correctly reads as
      // stale), while the case the fallback exists to protect - a genuinely
      // new dagExecution arriving from NOTHING during the await - still
      // reads as fresh (created_at went from undefined to a value). A new
      // no-turn_id run arriving OVER an existing old one inherits the old
      // created_at (applyDagExecutionUpdate can't tell legacy runs apart -
      // that's #1433) and so gets reset here; that's the right bias, since a
      // live run repopulates itself on its next event, whereas a wrongly
      // retained stale panel has no later event to ever correct it.
      const dagExecutionStillStale =
        dagTurnIdBeforeSend && stateRef.current.dagExecution?.turn_id
          ? stateRef.current.dagExecution.turn_id === dagTurnIdBeforeSend
          : stateRef.current.dagExecution?.created_at === dagExecutionBeforeSend?.created_at
      if (!isContinuingActiveRun && dagExecutionStillStale) {
        dispatch({ type: "RESET_DAG_STATE" })
      }

      // Optimistically flips a terminal task back to "running" once its
      // retry/new-turn send is acked, so the user isn't staring at a
      // "completed"/"failed" badge while the backend spins the turn up.
      // Three fences, because this dispatch has no task id of its own for
      // the reducer to validate against:
      // - taskId still matches: the user can navigate to a different task
      //   while this send is in flight, and a delayed ack for task A's
      //   retried send must not mark whatever task the user has since
      //   navigated to as "running" (same guard addOptimisticUserMessage
      //   applies to its own dispatch).
      // - the send began FROM a terminal status: the flip is only meaningful
      //   for a rerun of a finished task - a send into an active run has
      //   nothing to flip.
      // - currentTask is untouched since the send began (reference
      //   equality): ANY task update landing during the await - most
      //   critically this new turn's OWN terminal event, when a fast
      //   non-DAG turn completes before the ack resolves - is newer truth
      //   than this optimistic guess. Flipping over it would mark a
      //   genuinely finished run as running again AND clear the
      //   dagTerminatedAt the reducer just stamped, unfreezing the Progress
      //   panel's elapsed clock. Skipping the flip is always safe: if the
      //   turn really is running, the backend's own status events say so
      //   moments later.
      if (
        state.taskId === stateRef.current.taskId
        && stateRef.current.currentTask === currentTaskBeforeSend
        && isTerminalTaskStatus(currentTaskBeforeSend?.status)
      ) {
        dispatch({
          type: "UPDATE_TASK_STATUS",
          payload: { status: 'running' }
        })
        dispatch({ type: "TRIGGER_TASK_UPDATE" })
      }

      addOptimisticUserMessage(state.taskId)
    }
  }, [
    beginSessionMessageDelivery,
    beginSessionPreAdoptionBuffer,
    activateSessionPreAdoptionBuffer,
    discardSessionPreAdoptionBuffer,
    dispatchSessionConversation,
    endSessionMessageDelivery,
    filesDisabled,
    queuePendingMessage,
    sendChatWithResend,
    sessionTransport,
    state.currentTask?.status,
    state.taskId,
  ])

  // The sendMessage every consumer gets, counted from the call until it
  // settles, for isSendInFlight. Counting around the call covers every caller
  // of useApp().sendMessage, and the count rises before sendMessage runs, so no
  // render can show a send that has started without it. The result and any
  // error pass through unchanged.
  const sendCallsInFlightRef = useRef(0)
  const [sendCallsInFlight, setSendCallsInFlight] = useState(0)
  const trackedSendMessage = useCallback<AppContextType["sendMessage"]>(async (...args) => {
    sendCallsInFlightRef.current += 1
    setSendCallsInFlight(sendCallsInFlightRef.current)
    try {
      return await sendMessage(...args)
    } finally {
      sendCallsInFlightRef.current -= 1
      // Defensive only: React already drops an update to an unmounted
      // provider without a warning, so nothing observable depends on this.
      if (mountedRef.current) setSendCallsInFlight(sendCallsInFlightRef.current)
    }
  }, [sendMessage])

  const startNewConversation = useCallback((): Promise<void> => {
    const existingReset = sessionResetFlightRef.current
    if (existingReset) return existingReset.promise
    if (sessionConversationRef.current.phase === "reload_required") {
      return Promise.reject(
        new Error("Conversation outcome is unknown; reload required.")
      )
    }
    if (!sessionTransport?.supportsConversationReset) {
      return Promise.reject(
        new Error("Conversation reset is not supported by this transport.")
      )
    }
    if (!mountedRef.current) {
      return Promise.reject(
        new Error("Conversation reset is unavailable after chat is closed.")
      )
    }
    if (messageDeliveryCountRef.current > 0) {
      return Promise.reject(
        new Error(
          "Conversation reset is blocked while message delivery is pending."
        )
      )
    }
    const establishedSessionTaskId = sessionTaskIdRef.current
    if (establishedSessionTaskId === null) {
      return Promise.reject(
        new Error("Conversation reset requires an established Session task.")
      )
    }
    if (sessionConversationRef.current.phase !== "bound") {
      return Promise.reject(
        new Error(
          "Start the replacement conversation before resetting again."
        )
      )
    }

    const connectionIdentity = sessionConnectionIdentityRef.current
    if (!connectionIdentity || !isConnected) {
      return Promise.reject(
        new Error("Conversation reset requires a connected Session.")
      )
    }

    let resolveReset!: () => void
    let rejectReset!: (error: Error) => void
    const promise = new Promise<void>((resolve, reject) => {
      resolveReset = resolve
      rejectReset = reject
    })
    const resetFlight: SessionResetFlight = {
      connectionIdentity,
      deliveryGeneration: deliveryGenerationRef.current,
      promise,
      resolve: resolveReset,
      reject: rejectReset,
      timeout: setTimeout(() => {
        if (sessionResetFlightRef.current !== resetFlight) return
        requireSessionReload(
          new Error("Conversation reset acknowledgement timed out; reload required.")
        )
      }, SESSION_RESET_ACK_TIMEOUT_MS),
    }
    sessionResetFlightRef.current = resetFlight
    const transition = dispatchSessionConversation({
      type: "SESSION_RESET_REQUESTED",
      connectionIdentity,
      taskId: establishedSessionTaskId,
    })
    if (!transition.accepted) {
      rejectSessionResetFlight(
        resetFlight,
        new Error("Conversation reset is no longer available."),
      )
      return promise
    }

    try {
      const sent = sendRawMessage({ type: "new_conversation" })
      if (sent !== "sent") {
        dispatchSessionConversation({
          type: "SESSION_RESET_NOT_SENT",
          connectionIdentity,
        })
        rejectSessionResetFlight(
          resetFlight,
          new Error("Conversation reset was not sent; retry the request."),
        )
      }
    } catch (error) {
      const resetError =
        error instanceof Error ? error : new Error(String(error))
      requireSessionReload(resetError)
    }
    return promise
  }, [
    isConnected,
    dispatchSessionConversation,
    rejectSessionResetFlight,
    requireSessionReload,
    sendRawMessage,
    sessionTransport?.supportsConversationReset,
  ])

  const stopTask = useCallback(() => {
    // Same belt as the phase guard below, on the other half of the rule: a
    // caller that does not come from the button must not send a stop frame on
    // a transport that never declared the capability.
    if (!taskStopEnabled) return
    const lifecycle = sessionConversationRef.current
    // Guard duplicated on purpose with the caller-side visibility rule: a
    // caller that does not come from the button (a future keyboard shortcut, a
    // console call) must not be able to send a stop frame when this connection
    // has no bound task to attribute it to.
    if (lifecycle.phase !== "bound") return
    const boundTaskId = lifecycle.taskId
    // No try/catch here, unlike startNewConversation above: sendMessage in
    // use-websocket already wraps socket.send and returns "not_sent" instead of
    // throwing, and a stop owns no promise and no session state to roll back.
    // startNewConversation wraps its send because its catch escalates to
    // requireSessionReload; a failed stop must not lock the visitor out.
    if (sendRawMessage({ type: "stop" }) !== "sent") {
      applySessionStop({ type: "STOP_NOT_SENT" })
      return
    }
    applySessionStop({ type: "STOP_SENT", taskId: boundTaskId })
  }, [applySessionStop, sendRawMessage, taskStopEnabled])

  // Initialize the replay scheduler function
  const initializeReplayScheduler = useCallback(() => {
    // Get cached events
    const cachedEvents = state.replayEventCache

    if (cachedEvents.length === 0) {
      return
    }

    // Convert WebSocket messages to replay events
    const replayEvents = cachedEvents.map((wsMessage, index) => ({
      type: 'ws_message' as const,
      data: wsMessage,
      timestamp: wsMessage.timestamp,
      originalIndex: index
    }))

    // Create and configure the replay scheduler
    const scheduler = new ReplayScheduler(
      (event) => {
        // Process the original message using the existing message handling logic
        // but with isReplaying: false to ensure it gets processed for display
        const message = event.data as WebSocketMessage
        const tempState = { ...stateRef.current, isReplaying: false }
        handleMessage(message, dispatch, tempState, { filesDisabled })
      },
      () => {
        // Replay completed
        dispatch({ type: "STOP_REPLAY" })
      },
      true // Skip user message delays by default
    )

    // Set the events and configure the scheduler
    scheduler.setEvents(replayEvents)
    scheduler.setPlaybackSpeed(state.replaySpeed)

    // Store the scheduler in state
    dispatch({ type: "SET_REPLAY_SCHEDULER", payload: scheduler })

    // Always start the scheduler since this function is called when we want to replay
    scheduler.play()
  }, [state.isReplaying, state.replayTaskId, state.replayEventCache, state.replaySpeed, dispatch, filesDisabled])

  const executeTask = useCallback((description: string) => {
    if (!state.taskId) return
    wsExecuteTask(description)
  }, [state.taskId, wsExecuteTask])

  const pauseTask = useCallback(() => {
    if (!state.taskId) return
    wsPauseTask()
  }, [state.taskId, wsPauseTask])

  const resumeTask = useCallback(() => {
    if (!state.taskId) return
    wsResumeTask()
  }, [state.taskId, wsResumeTask])

  const selectStep = useCallback((stepId: string | null) => {
    dispatch({ type: "SELECT_STEP", payload: stepId })
  }, [dispatch])

  const clearMessages = useCallback(() => {
    dispatch({ type: "CLEAR_MESSAGES" })
  }, [dispatch])

  const setTaskId = useCallback((taskId: number | null, options?: { navigate?: boolean }) => {
    // Only reset historical data request flag when changing to a different task
    if (taskId !== stateRef.current.taskId) {
      if (taskId) {
        historicalDataRequestMapRef.current.set(taskId, false)
      }
      // Clear recentMessages cache when switching tasks to prevent false duplicates
      recentMessagesRef.current.clear()
      isHistoricalDataLoadingRef.current = false

      // Clear existing data immediately when switching tasks to prevent stale data display
      // This fixes the issue where messages from the previous task might be cleared
      // by the connection effect AFTER the new task's history has already arrived.
      dispatch({ type: "CLEAR_MESSAGES" })
      dispatch({ type: "SET_TRACE_EVENTS", payload: [] })
      // steps/dagExecution are cleared by the SET_TASK_ID dispatch below (its
      // reducer case resets them whenever taskChanged) rather than here.
    }

    if (options?.navigate !== false) {
      // Update URL to use dynamic route for task detail page
      if (taskId) {
        router.push(`/task/${taskId}`)
      } else {
        router.push('/task')
      }
    }

    dispatch({ type: "SET_TASK_ID", payload: taskId })
    // Set history loading state immediately when switching tasks to prevent empty state flash
    if (taskId) {
      isHistoricalDataLoadingRef.current = true
      dispatch({ type: "SET_HISTORY_LOADING", payload: true })
    } else {
      // The task socket is keyed on taskId, so no terminal WS event will clear this.
      dispatch({ type: "SET_PROCESSING", payload: false })
    }
  }, [dispatch, router])

  const openFilePreview = useCallback((fileId: string, fileName: string, files?: Array<{ fileId: string; fileName: string }>, index?: number) => {
    if (filesDisabled) return
    console.log('🎯 openFilePreview called:', {
      fileId,
      fileName,
      files: files,
      filesLength: files?.length,
      index
    })
    dispatch({ type: "OPEN_FILE_PREVIEW", payload: { fileId, fileName, files, index } })
  }, [dispatch, filesDisabled])

  const switchFilePreview = useCallback((index: number) => {
    if (filesDisabled) return
    const { availableFiles } = state.filePreview
    if (index >= 0 && index < availableFiles.length) {
      const file = availableFiles[index]
      dispatch({ type: "SWITCH_FILE_PREVIEW", payload: { fileId: file.fileId, fileName: file.fileName, index } })
    }
  }, [filesDisabled, state.filePreview.availableFiles])

  const closeFilePreview = useCallback(() => {
    dispatch({ type: "CLOSE_FILE_PREVIEW" })
  }, [dispatch])

  const getFilePreviewUrl = useCallback((fileId: string) => {
    if (filesDisabled) {
      throw new Error("Files are disabled for this conversation.")
    }
    if (transport?.fileAccess) {
      return transport.fileAccess.previewUrl(fileId)
    }
    return `${getApiUrl()}/api/files/preview/${encodeURIComponent(fileId)}`
  }, [filesDisabled, transport])

  const getFileDownloadUrl = useCallback((fileId: string) => {
    if (filesDisabled) {
      throw new Error("Files are disabled for this conversation.")
    }
    if (transport?.fileAccess) {
      return transport.fileAccess.downloadUrl(fileId)
    }
    return `${getApiUrl()}/api/files/download/${encodeURIComponent(fileId)}`
  }, [filesDisabled, transport])


  // Replay control methods
  const startReplay = useCallback((taskId: number, events: TraceEvent[]) => {
    dispatch({ type: "START_REPLAY", payload: { taskId, events } })
  }, [dispatch])

  const stopReplay = useCallback(() => {
    dispatch({ type: "STOP_REPLAY" })
  }, [dispatch])

  const setReplayPlaying = useCallback((isPlaying: boolean) => {
    dispatch({ type: "SET_REPLAY_PLAYING", payload: isPlaying })
  }, [dispatch])

  const setReplaySpeed = useCallback((speed: number) => {
    dispatch({ type: "SET_REPLAY_SPEED", payload: speed })
  }, [dispatch])

  const setReplayProgress = useCallback((progress: number) => {
    dispatch({ type: "SET_REPLAY_PROGRESS", payload: progress })
  }, [dispatch])

  useLayoutEffect(() => {
    startDelayedPlaybackRef.current = initializeReplayScheduler
  }, [initializeReplayScheduler])

  const sessionConversationAttachment: SessionConversationAttachment =
    !sessionTransport
    || !isConnected
    || sessionAttachment.connectionIdentity !== sessionConnectionIdentity
      ? "pending"
      : sessionAttachment.capability === "absent"
        ? "unsupported"
        : sessionAttachment.capability === "declared" && sessionAttachment.attached
          ? "attached"
          : "pending"

  return (
    <AgentCardPresentationCapability.Provider value={agentCardsEnabled}>
      <LinksOpenInNewTabCapability.Provider value={linksOpenInNewTab}>
        <FileAccessProvider policy={transport?.fileAccess}>
          <AppContext.Provider
          value={{
          state,
          dispatch,
          filesDisabled,
          agentCardsEnabled,
          voiceInputEnabled,
          taskControlsEnabled,
          sendMessage: trackedSendMessage,
          executeTask,
          pauseTask,
          resumeTask,
          selectStep,
          clearMessages,
          isConnected,
          sameTaskReconnects,
          connectionError,
          connectionNotice,
          startNewConversation,
          canStopTask,
          stopTask,
          stopState,
          isConversationResetPending:
            state.sessionConversation.phase === "reset_requested",
          isMessageDeliveryPending: messageDeliveryCount > 0,
          isSendInFlight: sendCallsInFlight > 0,
          isSessionInteractionLocked:
            state.sessionConversation.phase === "reload_required",
          sessionConversationState: state.sessionConversation.phase,
          sessionConversationAttachment,
          setTaskId,
          requestStatus,
          getFilePreviewUrl,
          getFileDownloadUrl,
          openFilePreview,
          switchFilePreview,
          closeFilePreview,
          startReplay,
          stopReplay,
          setReplayPlaying,
          setReplaySpeed,
          setReplayProgress,
          setPendingMessage,
          }}
        >
          {children}
          {/*
            A second seam alongside the existing TASK_ERROR_EVENT /
            TaskErrorController mechanism, not a replacement for it. Three
            reasons it is not reused here: (1) that event only fires from the
            task_completed branch above (see emitTaskError), while this
            dialog is driven by the terminal task_error branch -- a
            different frame entirely; (2) TaskErrorController is mounted as
            a sibling of AppProvider (see application-shell.tsx), so it
            cannot reach useApp() the way this component does; (3) that
            controller's own file already documents itself as a seam an
            app-layer overlay may replace, which is not this dialog's role.
            Do not "consolidate" the two without re-checking all three.
          */}
          <ConnectorRuntimeDialog />
          </AppContext.Provider>
        </FileAccessProvider>
      </LinksOpenInNewTabCapability.Provider>
    </AgentCardPresentationCapability.Provider>
  )
}

export function useApp() {
  const context = useContext(AppContext)
  if (context === undefined) {
    throw new Error("useApp must be used within an AppProvider")
  }
  return context
}