{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "assistant-panel",
  "type": "registry:component",
  "title": "Assistant panel",
  "description": "A copilot conversation with tool activity, streamed markdown with metric chips and citations, feedback, and a model-aware composer.",
  "categories": [
    "ai"
  ],
  "dependencies": [
    "@tabler/icons-react"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "src/registry/overtrue/assistant-panel.tsx",
      "type": "registry:component",
      "target": "components/overtrue/assistant-panel.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport {\n  IconAlertTriangle as AlertTriangle,\n  IconArrowDown as ArrowDown,\n  IconArrowDownRight as ArrowDownRight,\n  IconArrowUp as ArrowUp,\n  IconArrowUpRight as ArrowUpRight,\n  IconBulb as Bulb,\n  IconCheck as Check,\n  IconChevronRight as ChevronRight,\n  IconCopy as Copy,\n  IconDatabase as Database,\n  IconEdit as NewChat,\n  IconLoader2 as Loader,\n  IconPlayerStopFilled as Stop,\n  IconRefresh as Refresh,\n  IconSearch as Search,\n  IconSelector as Selector,\n  IconMessage2 as Message,\n  IconThumbDown as ThumbDown,\n  IconThumbDownFilled as ThumbDownFilled,\n  IconThumbUp as ThumbUp,\n  IconThumbUpFilled as ThumbUpFilled,\n  IconTool as Tool,\n  IconX as X,\n} from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/* -------------------------------------------------------------------------------------------------\n * Types\n * -----------------------------------------------------------------------------------------------*/\n\nexport type AssistantRole = \"user\" | \"assistant\";\nexport type AssistantMessageStatus = \"streaming\" | \"done\" | \"error\";\nexport type AssistantStepKind = \"search\" | \"query\" | \"tool\" | \"think\";\nexport type AssistantStepStatus = \"running\" | \"done\" | \"error\";\nexport type AssistantFeedback = \"up\" | \"down\";\nexport type AssistantDensity = \"comfortable\" | \"compact\";\nexport type AssistantTone = \"positive\" | \"negative\" | \"neutral\";\n\n/** One unit of work the assistant did before (or while) answering. */\nexport interface AssistantStep {\n  id: string;\n  /** What happened, e.g. \"Searched incidents\". Update it as the step finishes. */\n  label: string;\n  /** Picks the icon. Defaults to \"tool\". */\n  kind?: AssistantStepKind;\n  status: AssistantStepStatus;\n  /** Query, command or raw output, shown in monospace when the step is expanded. */\n  detail?: string;\n  /** Milliseconds. */\n  duration?: number;\n}\n\nexport interface AssistantCitation {\n  id: string;\n  label: string;\n  href?: string;\n}\n\nexport interface AssistantMessage {\n  id: string;\n  role: AssistantRole;\n  /** Markdown-lite for assistant messages; plain text for user messages. */\n  content: string;\n  steps?: AssistantStep[];\n  /** Referenced from the content with `{{cite:1}}` (1-based) or `{{cite:id}}`. */\n  citations?: AssistantCitation[];\n  /** Assistant messages only. Defaults to \"done\". */\n  status?: AssistantMessageStatus;\n  createdAt?: Date | string;\n}\n\nexport type AssistantModel =\n  | string\n  | { value: string; label?: string; disabled?: boolean };\n\nexport type AssistantSuggestion =\n  | string\n  | {\n      label: string;\n      /** Sent instead of the label. */\n      prompt?: string;\n      icon?: React.ReactNode;\n    };\n\nexport interface AssistantSendOptions {\n  model?: string;\n}\n\n/** An inline `{{kind:arg|arg|arg}}` token from assistant markdown. */\nexport interface AssistantToken {\n  /** \"metric\", \"cite\", or your own kind. */\n  kind: string;\n  /** Every argument after the colon, trimmed. */\n  args: string[];\n  /** First argument: the metric label or citation reference. */\n  label: string;\n  /** Second argument: the metric value. */\n  value?: string;\n  /** Third argument when it is positive, negative or neutral; otherwise inferred from the value's sign. */\n  tone: AssistantTone;\n  direction: \"up\" | \"down\" | \"flat\";\n  raw: string;\n}\n\nexport interface AssistantMessageRenderContext {\n  index: number;\n  /** The newest message of its role. */\n  isLast: boolean;\n  /** The built-in rendering, to wrap or reuse. */\n  children: React.ReactNode;\n}\n\nexport interface AssistantPanelLabels {\n  title: string;\n  newChat: string;\n  placeholder: string;\n  send: string;\n  stop: string;\n  copy: string;\n  copied: string;\n  copyCode: string;\n  regenerate: string;\n  helpful: string;\n  notHelpful: string;\n  feedback: string;\n  jumpToLatest: string;\n  emptyTitle: string;\n  emptyDescription: string;\n  thinking: string;\n  writing: string;\n  sources: string;\n  error: string;\n  retry: string;\n  model: string;\n  conversation: string;\n  you: string;\n  assistant: string;\n  activity: string;\n  /** Summary for a finished step list, e.g. \"3 steps · 1.9s\". */\n  steps: (count: number, duration: string | null) => string;\n  /** Summary when some steps failed. */\n  stepsFailed: (failed: number, count: number) => string;\n}\n\nexport interface AssistantPanelProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"title\" | \"children\" | \"onCopy\" | \"defaultValue\"\n> {\n  /** The conversation, oldest first. Append and update messages as the answer streams. */\n  messages: AssistantMessage[];\n  /** \"streaming\" swaps Send for Stop and blocks sending. */\n  status?: \"idle\" | \"streaming\";\n  onSend?: (text: string, options: AssistantSendOptions) => void;\n  onStop?: () => void;\n  /** Shows Regenerate on the latest answer and Try again on failed ones. */\n  onRegenerate?: (id: string) => void;\n  /** Shows thumbs up and down on finished answers. */\n  onFeedback?: (id: string, value: AssistantFeedback) => void;\n  /** Feedback by message id. Leave undefined to let the panel remember it. */\n  feedback?: Record<string, AssistantFeedback | undefined>;\n  /** Shows the New chat action. */\n  onNewChat?: () => void;\n  /** Called with the plain text. Without it, Copy writes to the clipboard. */\n  onCopy?: (text: string, message: AssistantMessage) => void;\n  /** Prompts offered in the empty state. */\n  suggestions?: AssistantSuggestion[];\n  /** Adds a model picker to the composer. */\n  models?: AssistantModel[];\n  model?: string;\n  defaultModel?: string;\n  onModelChange?: (model: string) => void;\n  title?: React.ReactNode;\n  placeholder?: string;\n  /** The composer draft. Pass with `onValueChange` to control it. */\n  value?: string;\n  defaultValue?: string;\n  onValueChange?: (value: string) => void;\n  /** Buttons at the start of the composer toolbar, such as attach. */\n  composerActions?: React.ReactNode;\n  /** Buttons at the end of the header, such as close. */\n  headerActions?: React.ReactNode;\n  /** Small print under the composer. */\n  footer?: React.ReactNode;\n  /** Replaces the empty state. */\n  emptyState?: React.ReactNode;\n  density?: AssistantDensity;\n  disabled?: boolean;\n  autoFocus?: boolean;\n  /** Tallest the composer grows before scrolling, in pixels. */\n  maxComposerHeight?: number;\n  composerRef?: React.Ref<HTMLTextAreaElement>;\n  /** Draw a message yourself. Return `undefined` to keep the built-in rendering. */\n  renderMessage?: (\n    message: AssistantMessage,\n    context: AssistantMessageRenderContext,\n  ) => React.ReactNode | undefined;\n  /** Draw a step row yourself. Return `undefined` to keep the built-in row. */\n  renderStep?: (\n    step: AssistantStep,\n    message: AssistantMessage,\n  ) => React.ReactNode | undefined;\n  /** Draw an inline token yourself. Return `undefined` to keep the built-in chip. */\n  renderToken?: (\n    token: AssistantToken,\n    message: AssistantMessage,\n  ) => React.ReactNode | undefined;\n  /** Formats step durations (milliseconds). */\n  formatDuration?: (ms: number) => string;\n  /** Formats message times shown next to the actions. */\n  formatTime?: (date: Date) => string;\n  labels?: Partial<AssistantPanelLabels>;\n}\n\nconst LABELS: AssistantPanelLabels = {\n  title: \"Assistant\",\n  newChat: \"New chat\",\n  placeholder: \"Ask anything…\",\n  send: \"Send message\",\n  stop: \"Stop generating\",\n  copy: \"Copy\",\n  copied: \"Copied\",\n  copyCode: \"Copy code\",\n  regenerate: \"Regenerate\",\n  helpful: \"Good response\",\n  notHelpful: \"Bad response\",\n  feedback: \"Feedback\",\n  jumpToLatest: \"Jump to latest\",\n  emptyTitle: \"How can I help?\",\n  emptyDescription: \"Ask about metrics, incidents or anything in this workspace.\",\n  thinking: \"Thinking…\",\n  writing: \"Writing…\",\n  sources: \"Sources\",\n  error: \"Something went wrong while answering.\",\n  retry: \"Try again\",\n  model: \"Model\",\n  conversation: \"Conversation\",\n  you: \"You\",\n  assistant: \"Assistant\",\n  activity: \"Activity\",\n  steps: (count, duration) =>\n    `${count} ${count === 1 ? \"step\" : \"steps\"}${duration ? ` · ${duration}` : \"\"}`,\n  stepsFailed: (failed, count) =>\n    `${failed} of ${count} ${count === 1 ? \"step\" : \"steps\"} failed`,\n};\n\n/* -------------------------------------------------------------------------------------------------\n * Shared helpers\n * -----------------------------------------------------------------------------------------------*/\n\nconst focusRing =\n  \"outline-none focus-visible:ring-2 focus-visible:ring-primary/30 focus-visible:shadow-[0_0_14px_-2px_color-mix(in_oklab,var(--color-primary)_45%,transparent)]\";\n\nconst useIsoLayoutEffect =\n  typeof window === \"undefined\" ? React.useEffect : React.useLayoutEffect;\n\nconst REDUCED = \"(prefers-reduced-motion: reduce)\";\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (callback) => {\n      const query = window.matchMedia(REDUCED);\n      query.addEventListener(\"change\", callback);\n      return () => query.removeEventListener(\"change\", callback);\n    },\n    () => window.matchMedia(REDUCED).matches,\n    () => false,\n  );\n}\n\nconst subscribeNothing = () => () => {};\nfunction useMounted() {\n  return React.useSyncExternalStore(\n    subscribeNothing,\n    () => true,\n    () => false,\n  );\n}\n\nasync function writeClipboard(text: string) {\n  try {\n    await navigator.clipboard.writeText(text);\n    return true;\n  } catch {\n    // Fallback for insecure contexts and older browsers.\n    try {\n      const area = document.createElement(\"textarea\");\n      area.value = text;\n      area.setAttribute(\"readonly\", \"\");\n      area.style.position = \"fixed\";\n      area.style.opacity = \"0\";\n      document.body.appendChild(area);\n      area.select();\n      const ok = document.execCommand(\"copy\");\n      area.remove();\n      return ok;\n    } catch {\n      return false;\n    }\n  }\n}\n\nfunction useCopy(timeout = 1600) {\n  const [copied, setCopied] = React.useState(false);\n  React.useEffect(() => {\n    if (!copied) return;\n    const timer = window.setTimeout(() => setCopied(false), timeout);\n    return () => window.clearTimeout(timer);\n  }, [copied, timeout]);\n  const copy = React.useCallback(async (text: string, handler?: (text: string) => void) => {\n    if (handler) handler(text);\n    else if (!(await writeClipboard(text))) return;\n    setCopied(true);\n  }, []);\n  return [copied, copy] as const;\n}\n\nexport function formatAssistantDuration(ms: number) {\n  if (!Number.isFinite(ms) || ms < 0) return \"\";\n  if (ms < 100) return `${Math.round(ms)}ms`;\n  if (ms < 10_000) return `${(ms / 1000).toFixed(1)}s`;\n  if (ms < 60_000) return `${Math.round(ms / 1000)}s`;\n  const minutes = Math.floor(ms / 60_000);\n  const seconds = Math.round((ms % 60_000) / 1000);\n  return seconds ? `${minutes}m ${seconds}s` : `${minutes}m`;\n}\n\nconst defaultTimeFormat = (date: Date) =>\n  date.toLocaleTimeString(undefined, { hour: \"numeric\", minute: \"2-digit\" });\n\n/* -------------------------------------------------------------------------------------------------\n * Markdown-lite: a small, safe parser. Everything renders as React elements; nothing is injected\n * as HTML. Supports paragraphs, headings, emphasis, inline code, fenced code, lists (nested),\n * quotes, tables, links, and `{{kind:args}}` tokens.\n * -----------------------------------------------------------------------------------------------*/\n\ntype Inline =\n  | { t: \"text\"; v: string }\n  | { t: \"br\" }\n  | { t: \"code\"; v: string }\n  | { t: \"strong\" | \"em\" | \"del\"; c: Inline[] }\n  | { t: \"link\"; href: string; c: Inline[] }\n  | { t: \"token\"; token: AssistantToken };\n\ntype Align = \"left\" | \"center\" | \"right\" | null;\n\ntype Block =\n  | { t: \"p\"; text: string }\n  | { t: \"h\"; level: number; text: string }\n  | { t: \"code\"; lang: string; code: string; open: boolean }\n  | { t: \"list\"; ordered: boolean; start: number; items: Block[][] }\n  | { t: \"quote\"; blocks: Block[] }\n  | { t: \"table\"; align: Align[]; head: string[]; rows: string[][] }\n  | { t: \"hr\" };\n\nconst FENCE = /^ {0,3}(`{3,}|~{3,})[ \\t]*([^\\s`]*)[^`]*$/;\nconst HEADING = /^ {0,3}(#{1,6})[ \\t]+(.*?)(?:[ \\t]+#+)?[ \\t]*$/;\nconst QUOTE = /^ {0,3}>[ \\t]?(.*)$/;\nconst HR = /^ {0,3}([-*_])(?:[ \\t]*\\1){2,}[ \\t]*$/;\nconst LIST_ITEM = /^( *)([-*+]|\\d{1,9}[.)])(?:[ \\t]+(.*))?$/;\nconst TABLE_SEP = /^ {0,3}\\|?[ \\t]*:?-+:?[ \\t]*(?:\\|[ \\t]*:?-+:?[ \\t]*)*\\|?[ \\t]*$/;\nconst TOKEN_BODY = /^\\s*([A-Za-z][\\w-]*)\\s*:([\\s\\S]*)$/;\nconst TONES = new Set([\"positive\", \"negative\", \"neutral\"]);\n\nfunction splitRow(line: string) {\n  let row = line.trim();\n  if (row.startsWith(\"|\")) row = row.slice(1);\n  if (row.endsWith(\"|\") && !row.endsWith(\"\\\\|\")) row = row.slice(0, -1);\n  const cells: string[] = [];\n  let cell = \"\";\n  let code = false;\n  for (let i = 0; i < row.length; i++) {\n    const ch = row[i];\n    if (ch === \"\\\\\" && row[i + 1] === \"|\") {\n      cell += \"|\";\n      i++;\n    } else if (ch === \"`\") {\n      code = !code;\n      cell += ch;\n    } else if (ch === \"|\" && !code) {\n      cells.push(cell.trim());\n      cell = \"\";\n    } else cell += ch;\n  }\n  cells.push(cell.trim());\n  return cells;\n}\n\nfunction isTableStart(lines: string[], i: number) {\n  return (\n    lines[i].includes(\"|\") &&\n    i + 1 < lines.length &&\n    TABLE_SEP.test(lines[i + 1]) &&\n    lines[i + 1].includes(\"-\") &&\n    (lines[i + 1].includes(\"|\") || lines[i].trim().startsWith(\"|\"))\n  );\n}\n\nfunction startsBlock(lines: string[], i: number) {\n  const line = lines[i];\n  return (\n    FENCE.test(line) ||\n    HEADING.test(line) ||\n    QUOTE.test(line) ||\n    HR.test(line) ||\n    (LIST_ITEM.test(line) && LIST_ITEM.exec(line)![3] !== undefined) ||\n    isTableStart(lines, i)\n  );\n}\n\nconst indentOf = (line: string) => line.length - line.trimStart().length;\n\nfunction parseList(lines: string[], start: number) {\n  const first = LIST_ITEM.exec(lines[start])!;\n  const base = first[1].length;\n  const ordered = /\\d/.test(first[2]);\n  const items: string[][] = [];\n  let content = base + first[2].length + 1;\n  let i = start;\n  while (i < lines.length) {\n    const line = lines[i];\n    const match = LIST_ITEM.exec(line);\n    if (match && match[1].length === base && /\\d/.test(match[2]) === ordered) {\n      items.push([match[3] ?? \"\"]);\n      content = base + match[2].length + 1;\n      i++;\n      continue;\n    }\n    if (!line.trim()) {\n      // A blank line continues the list only if more of it follows.\n      let next = i + 1;\n      while (next < lines.length && !lines[next].trim()) next++;\n      if (next >= lines.length) break;\n      const nextMatch = LIST_ITEM.exec(lines[next]);\n      const continues =\n        indentOf(lines[next]) > base ||\n        (nextMatch && nextMatch[1].length === base && /\\d/.test(nextMatch[2]) === ordered);\n      if (!continues) break;\n      items[items.length - 1].push(\"\");\n      i++;\n      continue;\n    }\n    if (indentOf(line) > base) {\n      items[items.length - 1].push(line.slice(Math.min(indentOf(line), content)));\n      i++;\n      continue;\n    }\n    // Lazy continuation of the item's paragraph.\n    const previous = lines[i - 1];\n    if (previous?.trim() && !startsBlock(lines, i)) {\n      items[items.length - 1].push(line.trim());\n      i++;\n      continue;\n    }\n    break;\n  }\n  const block: Block = {\n    t: \"list\",\n    ordered,\n    start: ordered ? Number.parseInt(first[2], 10) : 1,\n    items: items.map((item) => parseBlocks(item.join(\"\\n\"))),\n  };\n  return { block, next: i };\n}\n\n/** Parse markdown-lite into blocks. Unclosed fences stay open so code can stream in. */\nfunction parseBlocks(source: string): Block[] {\n  const lines = source.replace(/\\r\\n?/g, \"\\n\").split(\"\\n\");\n  const blocks: Block[] = [];\n  let i = 0;\n  while (i < lines.length) {\n    const line = lines[i];\n    if (!line.trim()) {\n      i++;\n      continue;\n    }\n    const fence = FENCE.exec(line);\n    if (fence) {\n      const marker = fence[1];\n      const body: string[] = [];\n      let closed = false;\n      i++;\n      while (i < lines.length) {\n        const candidate = lines[i].trim();\n        if (\n          candidate.length >= marker.length &&\n          candidate[0] === marker[0] &&\n          new RegExp(`^\\\\${marker[0]}{${marker.length},}$`).test(candidate)\n        ) {\n          closed = true;\n          i++;\n          break;\n        }\n        body.push(lines[i]);\n        i++;\n      }\n      blocks.push({ t: \"code\", lang: fence[2] ?? \"\", code: body.join(\"\\n\"), open: !closed });\n      continue;\n    }\n    const heading = HEADING.exec(line);\n    if (heading) {\n      blocks.push({ t: \"h\", level: heading[1].length, text: heading[2] });\n      i++;\n      continue;\n    }\n    if (HR.test(line)) {\n      blocks.push({ t: \"hr\" });\n      i++;\n      continue;\n    }\n    if (QUOTE.test(line)) {\n      const body: string[] = [];\n      while (i < lines.length && lines[i].trim() && QUOTE.test(lines[i])) {\n        body.push(QUOTE.exec(lines[i])![1]);\n        i++;\n      }\n      blocks.push({ t: \"quote\", blocks: parseBlocks(body.join(\"\\n\")) });\n      continue;\n    }\n    if (LIST_ITEM.test(line) && LIST_ITEM.exec(line)![3] !== undefined) {\n      const { block, next } = parseList(lines, i);\n      blocks.push(block);\n      i = next;\n      continue;\n    }\n    if (isTableStart(lines, i)) {\n      const head = splitRow(line);\n      const align = splitRow(lines[i + 1]).map<Align>((cell) =>\n        cell.startsWith(\":\") && cell.endsWith(\":\")\n          ? \"center\"\n          : cell.endsWith(\":\")\n            ? \"right\"\n            : cell.startsWith(\":\")\n              ? \"left\"\n              : null,\n      );\n      const rows: string[][] = [];\n      i += 2;\n      while (i < lines.length && lines[i].trim() && lines[i].includes(\"|\")) {\n        rows.push(splitRow(lines[i]));\n        i++;\n      }\n      blocks.push({ t: \"table\", align, head, rows });\n      continue;\n    }\n    const body = [line];\n    i++;\n    while (i < lines.length && lines[i].trim() && !startsBlock(lines, i)) {\n      body.push(lines[i]);\n      i++;\n    }\n    blocks.push({ t: \"p\", text: body.map((part) => part.trim()).join(\"\\n\") });\n  }\n  return blocks;\n}\n\nfunction directionOf(value: string | undefined): AssistantToken[\"direction\"] {\n  const sign = value?.trim()[0];\n  if (sign === \"+\" || sign === \"↑\") return \"up\";\n  if (sign === \"-\" || sign === \"−\" || sign === \"↓\") return \"down\";\n  return \"flat\";\n}\n\nfunction makeToken(kind: string, body: string, raw: string): AssistantToken {\n  const args = body.split(\"|\").map((arg) => arg.trim());\n  const [label = \"\", value, third] = args;\n  const direction = directionOf(value);\n  return {\n    kind: kind.toLowerCase(),\n    args,\n    label,\n    value,\n    direction,\n    tone:\n      third && TONES.has(third)\n        ? (third as AssistantTone)\n        : direction === \"up\"\n          ? \"positive\"\n          : direction === \"down\"\n            ? \"negative\"\n            : \"neutral\",\n    raw,\n  };\n}\n\nfunction safeHref(href: string) {\n  if (!href) return false;\n  const scheme = /^([a-z][a-z\\d+.-]*):/i.exec(href);\n  return !scheme || /^(https?|mailto|tel)$/i.test(scheme[1]);\n}\n\nconst ESCAPABLE = \"\\\\`*_{}[]()#+-.!|~>\";\nconst WORD = /[\\p{L}\\p{N}]/u;\nconst SPACE = /\\s/;\n\nfunction matchBracket(src: string, from: number) {\n  let depth = 0;\n  for (let i = from; i < src.length; i++) {\n    const ch = src[i];\n    if (ch === \"\\\\\") i++;\n    else if (ch === \"[\") depth++;\n    else if (ch === \"]\" && --depth === 0) return i;\n  }\n  return -1;\n}\n\n/** Index of a closing run for an emphasis opener of `size` characters, or -1. */\nfunction findCloser(src: string, from: number, ch: string, size: number) {\n  let i = from;\n  while (i < src.length) {\n    const c = src[i];\n    if (c === \"\\\\\") {\n      i += 2;\n      continue;\n    }\n    if (c === \"`\") {\n      let run = 1;\n      while (src[i + run] === \"`\") run++;\n      const end = src.indexOf(\"`\".repeat(run), i + run);\n      i = end === -1 ? i + run : end + run;\n      continue;\n    }\n    if (c === ch) {\n      let run = 1;\n      while (src[i + run] === ch) run++;\n      const before = src[i - 1] ?? \" \";\n      const after = src[i + run] ?? \" \";\n      const closes =\n        i > from &&\n        !SPACE.test(before) &&\n        !(ch === \"_\" && WORD.test(after));\n      if (closes) {\n        if (run === size) return i;\n        if (size === 1 && run === 3) return i + 2;\n        if (size === 2 && run === 3) return i + 1;\n        if (size === 3 && run > 3) return i;\n      }\n      i += run;\n      continue;\n    }\n    i++;\n  }\n  return -1;\n}\n\nfunction wrapEmphasis(size: number, ch: string, children: Inline[]): Inline {\n  if (ch === \"~\") return { t: \"del\", c: children };\n  if (size === 1) return { t: \"em\", c: children };\n  if (size === 2) return { t: \"strong\", c: children };\n  return { t: \"strong\", c: [{ t: \"em\", c: children }] };\n}\n\n/**\n * Parse inline markdown. With `open`, the text is the streaming tail: unclosed emphasis and code\n * render optimistically and half-received tokens or links are held back, so nothing flickers.\n */\nfunction parseInline(src: string, open = false): Inline[] {\n  const out: Inline[] = [];\n  let text = \"\";\n  const flush = () => {\n    if (text) out.push({ t: \"text\", v: text });\n    text = \"\";\n  };\n  const push = (...nodes: Inline[]) => {\n    flush();\n    out.push(...nodes);\n  };\n  let i = 0;\n  const n = src.length;\n  while (i < n) {\n    const ch = src[i];\n    if (ch === \"\\\\\" && i + 1 < n && ESCAPABLE.includes(src[i + 1])) {\n      text += src[i + 1];\n      i += 2;\n      continue;\n    }\n    if (ch === \"\\n\") {\n      push({ t: \"br\" });\n      i++;\n      continue;\n    }\n    if (ch === \"`\") {\n      let run = 1;\n      while (src[i + run] === \"`\") run++;\n      const end = src.indexOf(\"`\".repeat(run), i + run);\n      if (end !== -1) {\n        let value = src.slice(i + run, end);\n        if (value.length > 2 && value.startsWith(\" \") && value.endsWith(\" \")) value = value.slice(1, -1);\n        push({ t: \"code\", v: value });\n        i = end + run;\n        continue;\n      }\n      if (open) {\n        const value = src.slice(i + run);\n        if (value) push({ t: \"code\", v: value });\n        i = n;\n        continue;\n      }\n      text += \"`\".repeat(run);\n      i += run;\n      continue;\n    }\n    if (ch === \"{\" && src[i + 1] === \"{\") {\n      const end = src.indexOf(\"}}\", i + 2);\n      if (end !== -1) {\n        const match = TOKEN_BODY.exec(src.slice(i + 2, end));\n        if (match) {\n          push({ t: \"token\", token: makeToken(match[1], match[2], src.slice(i, end + 2)) });\n          i = end + 2;\n          continue;\n        }\n      } else if (open && /^\\{\\{[^{}]*$/.test(src.slice(i))) {\n        i = n;\n        continue;\n      }\n    }\n    if (ch === \"[\") {\n      const close = matchBracket(src, i);\n      if (close !== -1 && src[close + 1] === \"(\") {\n        const end = src.indexOf(\")\", close + 2);\n        const label = src.slice(i + 1, close);\n        if (end !== -1) {\n          const href = src\n            .slice(close + 2, end)\n            .trim()\n            .replace(/^<(.*)>$/, \"$1\")\n            .split(/\\s+/)[0];\n          if (safeHref(href)) push({ t: \"link\", href, c: parseInline(label) });\n          else push(...parseInline(label));\n          i = end + 1;\n          continue;\n        }\n        if (open) {\n          push(...parseInline(label));\n          i = n;\n          continue;\n        }\n      }\n    }\n    if (ch === \"*\" || ch === \"_\" || ch === \"~\") {\n      let run = 1;\n      while (src[i + run] === ch) run++;\n      if (ch === \"~\" && run !== 2) {\n        text += ch.repeat(run);\n        i += run;\n        continue;\n      }\n      const before = src[i - 1] ?? \" \";\n      const after = src[i + run] ?? \"\";\n      const canOpen = after !== \"\" && !SPACE.test(after) && !(ch === \"_\" && WORD.test(before));\n      if (canOpen) {\n        const size = ch === \"~\" ? 2 : Math.min(run, 3);\n        const end = findCloser(src, i + size, ch, size);\n        if (end !== -1) {\n          push(wrapEmphasis(size, ch, parseInline(src.slice(i + size, end))));\n          i = end + size;\n          continue;\n        }\n        if (open) {\n          const rest = src.slice(i + size);\n          if (rest) push(wrapEmphasis(size, ch, parseInline(rest, true)));\n          i = n;\n          continue;\n        }\n      }\n      text += ch.repeat(run);\n      i += run;\n      continue;\n    }\n    if (ch === \"h\" && (i === 0 || /[\\s([\"'<]/.test(src[i - 1]))) {\n      const match = /^https?:\\/\\/[^\\s<>\"'`]+/.exec(src.slice(i, i + 2048));\n      if (match) {\n        const url = match[0].replace(/[.,:;!?)\\]}*_~]+$/, \"\");\n        push({ t: \"link\", href: url, c: [{ t: \"text\", v: url }] });\n        i += url.length;\n        continue;\n      }\n    }\n    text += ch;\n    i++;\n  }\n  flush();\n  return out;\n}\n\n/** Plain text for copying: markdown kept, metric tokens read \"Label value\", citations \"[1]\". */\nexport function assistantToPlainText(content: string) {\n  return content\n    .replace(/\\{\\{\\s*([A-Za-z][\\w-]*)\\s*:([^{}]*?)\\}\\}/g, (raw, kind: string, body: string) => {\n      const token = makeToken(kind, body, raw);\n      if (token.kind === \"cite\")\n        return token.args\n          .join(\",\")\n          .split(\",\")\n          .map((ref) => `[${ref.trim()}]`)\n          .join(\"\");\n      return [token.label, token.value].filter(Boolean).join(\" \");\n    })\n    .trim();\n}\n\n/* -------------------------------------------------------------------------------------------------\n * Code highlighting: a tiny tokenizer for the languages admin answers use most.\n * -----------------------------------------------------------------------------------------------*/\n\ninterface Grammar {\n  pattern: RegExp;\n  keywords: Set<string>;\n  caseInsensitive?: boolean;\n}\n\nconst words = (list: string) => new Set(list.split(\" \"));\nconst SQL: Grammar = {\n  pattern:\n    /(--[^\\n]*|\\/\\*[\\s\\S]*?(?:\\*\\/|$))|('(?:[^']|'')*'?|\"(?:[^\"\\\\\\n]|\\\\.)*\"?)|(\\b\\d+(?:\\.\\d+)?\\b)|([A-Za-z_][\\w$]*)/g,\n  keywords: words(\n    \"select from where and or not in is null as join left right inner outer full cross on group by order having limit offset with union all distinct case when then else end insert into values update set delete create table index view drop alter asc desc between like ilike exists returning interval filter over partition count sum avg min max coalesce cast true false now date_trunc percentile_cont within extract\",\n  ),\n  caseInsensitive: true,\n};\nconst SCRIPT: Grammar = {\n  pattern:\n    /(\\/\\/[^\\n]*|\\/\\*[\\s\\S]*?(?:\\*\\/|$))|('(?:[^'\\\\\\n]|\\\\.)*'?|\"(?:[^\"\\\\\\n]|\\\\.)*\"?|`(?:[^`\\\\]|\\\\.)*`?)|(\\b\\d+(?:\\.\\d+)?\\b)|([A-Za-z_$][\\w$]*)/g,\n  keywords: words(\n    \"const let var function return if else for while do switch case break continue new class extends import export from default async await try catch finally throw typeof instanceof in of this null undefined true false yield interface type enum implements package func go defer struct map range nil\",\n  ),\n};\nconst HASH: Grammar = {\n  pattern:\n    /(#[^\\n]*)|('(?:[^'\\\\\\n]|\\\\.)*'?|\"(?:[^\"\\\\\\n]|\\\\.)*\"?)|(\\b\\d+(?:\\.\\d+)?\\b)|([A-Za-z_][\\w-]*)/g,\n  keywords: words(\n    \"def return if elif else for while in import from as class with try except finally raise lambda None True False and or not is pass yield async await then fi do done case esac export echo function local\",\n  ),\n};\nconst GRAMMARS: Record<string, Grammar> = {\n  sql: SQL,\n  postgres: SQL,\n  postgresql: SQL,\n  mysql: SQL,\n  js: SCRIPT,\n  jsx: SCRIPT,\n  ts: SCRIPT,\n  tsx: SCRIPT,\n  javascript: SCRIPT,\n  typescript: SCRIPT,\n  json: SCRIPT,\n  go: SCRIPT,\n  py: HASH,\n  python: HASH,\n  sh: HASH,\n  bash: HASH,\n  shell: HASH,\n  zsh: HASH,\n  yaml: HASH,\n  yml: HASH,\n};\n\nfunction highlightCode(code: string, lang: string): React.ReactNode[] {\n  const grammar = GRAMMARS[lang.toLowerCase()];\n  if (!grammar) return [code];\n  const pattern = new RegExp(grammar.pattern.source, \"g\");\n  const out: React.ReactNode[] = [];\n  let last = 0;\n  let match: RegExpExecArray | null;\n  while ((match = pattern.exec(code))) {\n    const [whole, comment, string, number, word] = match;\n    if (!whole) {\n      pattern.lastIndex++;\n      continue;\n    }\n    if (match.index > last) out.push(code.slice(last, match.index));\n    const className = comment\n      ? \"text-muted-foreground italic\"\n      : string\n        ? \"text-chart-2\"\n        : number\n          ? \"text-chart-1\"\n          : word && grammar.keywords.has(grammar.caseInsensitive ? word.toLowerCase() : word)\n            ? \"text-chart-4\"\n            : undefined;\n    out.push(\n      className ? (\n        <span key={match.index} className={className}>\n          {whole}\n        </span>\n      ) : (\n        whole\n      ),\n    );\n    last = match.index + whole.length;\n  }\n  if (last < code.length) out.push(code.slice(last));\n  return out;\n}\n\n/* -------------------------------------------------------------------------------------------------\n * Markdown rendering\n * -----------------------------------------------------------------------------------------------*/\n\nconst styles = `@keyframes assistant-caret{0%,40%{opacity:1}70%,100%{opacity:.18}}@keyframes assistant-shimmer{from{background-position:100% 0}to{background-position:-100% 0}}@keyframes assistant-check{from{stroke-dashoffset:22}to{stroke-dashoffset:0}}@keyframes assistant-pop{0%{transform:scale(.6);opacity:0}60%{transform:scale(1.12);opacity:1}100%{transform:scale(1)}}`;\n\nconst shimmer =\n  \"bg-linear-to-r from-muted-foreground via-foreground to-muted-foreground bg-size-[200%_100%] bg-clip-text text-transparent motion-safe:animate-[assistant-shimmer_1.8s_linear_infinite] motion-reduce:bg-none motion-reduce:text-muted-foreground\";\n\nconst caret = (\n  <span\n    aria-hidden=\"true\"\n    data-slot=\"assistant-caret\"\n    className=\"ml-0.5 inline-block h-[1.1em] w-[2px] translate-y-[0.2em] rounded-full bg-primary shadow-[0_0_6px_1px_color-mix(in_oklab,var(--color-primary)_65%,transparent),0_0_14px_2px_color-mix(in_oklab,var(--color-primary)_30%,transparent)] motion-safe:animate-[assistant-caret_1.1s_ease-in-out_infinite_alternate]\"\n  />\n);\n\ninterface MarkdownContext {\n  citations?: AssistantCitation[];\n  activeCitation: string | null;\n  setActiveCitation: (id: string | null) => void;\n  renderToken?: (token: AssistantToken) => React.ReactNode | undefined;\n  compact: boolean;\n  labels: Pick<AssistantPanelLabels, \"sources\" | \"copy\" | \"copied\" | \"copyCode\">;\n}\n\nconst toneClass: Record<AssistantTone, string> = {\n  positive:\n    \"border-emerald-600/20 bg-emerald-500/[0.07] [--metric:var(--color-emerald-700)] dark:border-emerald-400/25 dark:[--metric:var(--color-emerald-400)]\",\n  negative:\n    \"border-destructive/20 bg-destructive/[0.06] [--metric:var(--color-destructive)] dark:border-destructive/30\",\n  neutral: \"border-border bg-muted/60 [--metric:var(--color-muted-foreground)]\",\n};\n\nfunction MetricChip({ token }: { token: AssistantToken }) {\n  const Arrow =\n    token.direction === \"up\" ? ArrowUpRight : token.direction === \"down\" ? ArrowDownRight : null;\n  return (\n    <span\n      data-slot=\"assistant-metric\"\n      data-tone={token.tone}\n      className={cn(\n        \"mx-px inline-flex -translate-y-px items-center gap-1 rounded-md border px-1.5 align-middle text-[0.86em] leading-[1.55] font-normal whitespace-nowrap\",\n        \"transition-[opacity,scale] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)] starting:scale-95 starting:opacity-0 motion-reduce:transition-none\",\n        toneClass[token.tone],\n      )}\n    >\n      {token.label && <span className=\"text-foreground/80\">{token.label}</span>}\n      {token.value && (\n        <span className=\"inline-flex items-center gap-px font-semibold text-(--metric) tabular-nums\">\n          {Arrow && <Arrow className=\"size-3\" aria-hidden=\"true\" stroke={2.25} />}\n          {token.value}\n        </span>\n      )}\n    </span>\n  );\n}\n\nfunction findCitation(citations: AssistantCitation[] | undefined, ref: string) {\n  if (!citations?.length) return undefined;\n  const index = /^\\d+$/.test(ref)\n    ? Number(ref) - 1\n    : citations.findIndex((item) => item.id === ref);\n  return index >= 0 && index < citations.length\n    ? { citation: citations[index], number: index + 1 }\n    : undefined;\n}\n\nfunction CitationMarker({ reference, context }: { reference: string; context: MarkdownContext }) {\n  const found = findCitation(context.citations, reference);\n  const number = found?.number ?? reference;\n  const active = found && context.activeCitation === found.citation.id;\n  const className = cn(\n    \"mx-px inline-flex h-[15px] min-w-[15px] -translate-y-[0.12em] items-center justify-center rounded-[4px] px-[3px] align-middle text-[10px] leading-none font-semibold tabular-nums no-underline transition-colors motion-reduce:transition-none\",\n    \"starting:opacity-0\",\n    active ? \"bg-primary/15 text-primary\" : \"bg-muted text-muted-foreground\",\n  );\n  const highlight = {\n    onPointerEnter: () => found && context.setActiveCitation(found.citation.id),\n    onPointerLeave: () => context.setActiveCitation(null),\n    onFocus: () => found && context.setActiveCitation(found.citation.id),\n    onBlur: () => context.setActiveCitation(null),\n  };\n  if (found?.citation.href)\n    return (\n      <a\n        data-slot=\"assistant-citation-marker\"\n        href={found.citation.href}\n        target=\"_blank\"\n        rel=\"noreferrer\"\n        aria-label={`${context.labels.sources} ${number}: ${found.citation.label}`}\n        className={cn(className, \"hover:bg-primary/15 hover:text-primary\", focusRing)}\n        {...highlight}\n      >\n        {number}\n      </a>\n    );\n  return (\n    <span\n      data-slot=\"assistant-citation-marker\"\n      title={found?.citation.label}\n      aria-label={found ? `${context.labels.sources} ${number}: ${found.citation.label}` : undefined}\n      className={cn(className, found && \"cursor-default hover:bg-primary/15 hover:text-primary\")}\n      {...highlight}\n    >\n      {number}\n    </span>\n  );\n}\n\nfunction renderToken(token: AssistantToken, context: MarkdownContext): React.ReactNode {\n  const custom = context.renderToken?.(token);\n  if (custom !== undefined) return custom;\n  if (token.kind === \"metric\") return <MetricChip token={token} />;\n  if (token.kind === \"cite\")\n    return token.args\n      .join(\",\")\n      .split(\",\")\n      .map((ref) => ref.trim())\n      .filter(Boolean)\n      .map((ref, index) => <CitationMarker key={index} reference={ref} context={context} />);\n  return (\n    <span data-slot=\"assistant-token\" data-kind={token.kind} className=\"font-medium\">\n      {token.label}\n    </span>\n  );\n}\n\nfunction renderInlines(nodes: Inline[], context: MarkdownContext, key = \"i\"): React.ReactNode[] {\n  return nodes.map((node, index) => {\n    const k = `${key}.${index}`;\n    switch (node.t) {\n      case \"text\":\n        return <React.Fragment key={k}>{node.v}</React.Fragment>;\n      case \"br\":\n        return <br key={k} />;\n      case \"code\":\n        return (\n          <code\n            key={k}\n            className=\"rounded-[5px] border border-border/70 bg-muted/70 px-[0.3em] py-px font-mono text-[0.86em] break-words text-foreground\"\n          >\n            {node.v}\n          </code>\n        );\n      case \"strong\":\n        return (\n          <strong key={k} className=\"font-semibold text-foreground\">\n            {renderInlines(node.c, context, k)}\n          </strong>\n        );\n      case \"em\":\n        return (\n          <em key={k} className=\"italic\">\n            {renderInlines(node.c, context, k)}\n          </em>\n        );\n      case \"del\":\n        return (\n          <del key={k} className=\"text-muted-foreground\">\n            {renderInlines(node.c, context, k)}\n          </del>\n        );\n      case \"link\": {\n        const external = /^https?:/i.test(node.href);\n        return (\n          <a\n            key={k}\n            href={node.href}\n            target={external ? \"_blank\" : undefined}\n            rel={external ? \"noreferrer\" : undefined}\n            className={cn(\n              \"font-medium text-primary underline decoration-primary/30 underline-offset-[3px] transition-colors hover:decoration-primary motion-reduce:transition-none\",\n              focusRing,\n              \"rounded-[2px]\",\n            )}\n          >\n            {renderInlines(node.c, context, k)}\n          </a>\n        );\n      }\n      case \"token\":\n        return <React.Fragment key={k}>{renderToken(node.token, context)}</React.Fragment>;\n    }\n  });\n}\n\nfunction CodeBlock({\n  block,\n  tail,\n  context,\n}: {\n  block: Extract<Block, { t: \"code\" }>;\n  tail?: React.ReactNode;\n  context: MarkdownContext;\n}) {\n  const [copied, copy] = useCopy();\n  const highlighted = React.useMemo(\n    () => highlightCode(block.code, block.lang),\n    [block.code, block.lang],\n  );\n  return (\n    <div\n      data-slot=\"assistant-code\"\n      data-language={block.lang || undefined}\n      className=\"overflow-hidden rounded-xl bg-muted/40 ring-1 ring-border/60 ring-inset\"\n    >\n      <div className=\"flex h-8 items-center justify-between gap-2 border-b border-border/60 pr-1 pl-3\">\n        <span className=\"truncate font-mono text-[11px] text-muted-foreground\">\n          {block.lang || \"text\"}\n        </span>\n        <button\n          type=\"button\"\n          onClick={() => copy(block.code)}\n          disabled={!block.code}\n          aria-label={copied ? context.labels.copied : context.labels.copyCode}\n          className={cn(\n            \"inline-flex h-6 items-center gap-1 rounded-md px-1.5 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40 motion-reduce:transition-none\",\n            focusRing,\n          )}\n        >\n          {copied ? (\n            <Check className=\"size-3.5 text-emerald-700 dark:text-emerald-400\" aria-hidden=\"true\" />\n          ) : (\n            <Copy className=\"size-3.5\" aria-hidden=\"true\" />\n          )}\n          {copied ? context.labels.copied : context.labels.copy}\n        </button>\n      </div>\n      <pre\n        className={cn(\n          \"overflow-x-auto px-3 py-2.5 font-mono leading-5 text-foreground/90 [font-variant-ligatures:none] [tab-size:2]\",\n          context.compact ? \"text-[11.5px]\" : \"text-[12.5px]\",\n        )}\n      >\n        <code>\n          {highlighted}\n          {tail}\n        </code>\n      </pre>\n    </div>\n  );\n}\n\nfunction renderBlocks(\n  blocks: Block[],\n  context: MarkdownContext,\n  options: { streaming: boolean; tail?: React.ReactNode; tight?: boolean },\n  key = \"b\",\n): React.ReactNode[] {\n  return blocks.map((block, index) => {\n    const last = index === blocks.length - 1;\n    const tail = last ? options.tail : undefined;\n    const open = options.streaming && last;\n    const k = `${key}.${index}`;\n    switch (block.t) {\n      case \"p\": {\n        const content = (\n          <>\n            {renderInlines(parseInline(block.text, open), context, k)}\n            {tail}\n          </>\n        );\n        return options.tight && blocks.length === 1 ? (\n          <React.Fragment key={k}>{content}</React.Fragment>\n        ) : (\n          <p key={k} className=\"break-words\">\n            {content}\n          </p>\n        );\n      }\n      case \"h\": {\n        const Tag = (block.level <= 2 ? \"h3\" : \"h4\") as \"h3\" | \"h4\";\n        return (\n          <Tag\n            key={k}\n            className={cn(\n              \"font-semibold tracking-tight text-foreground\",\n              block.level <= 2 ? \"pt-1 text-[1.07em]\" : \"text-[1em]\",\n            )}\n          >\n            {renderInlines(parseInline(block.text, open), context, k)}\n            {tail}\n          </Tag>\n        );\n      }\n      case \"code\":\n        return <CodeBlock key={k} block={block} tail={tail} context={context} />;\n      case \"hr\":\n        return <hr key={k} className=\"border-border\" />;\n      case \"quote\":\n        return (\n          <blockquote\n            key={k}\n            className=\"space-y-2 border-l-2 border-border pl-3 text-muted-foreground\"\n          >\n            {renderBlocks(block.blocks, context, { streaming: open, tail }, k)}\n          </blockquote>\n        );\n      case \"list\": {\n        const Tag = block.ordered ? \"ol\" : \"ul\";\n        return (\n          <Tag\n            key={k}\n            start={block.ordered && block.start !== 1 ? block.start : undefined}\n            className={cn(\n              \"space-y-1 pl-[1.35em]\",\n              block.ordered\n                ? \"list-decimal marker:text-muted-foreground marker:tabular-nums\"\n                : \"list-disc marker:text-muted-foreground/60\",\n            )}\n          >\n            {block.items.map((item, itemIndex) => {\n              const lastItem = itemIndex === block.items.length - 1;\n              return (\n                <li key={itemIndex} className=\"pl-1 [&>ol]:mt-1 [&>p+*]:mt-1.5 [&>ul]:mt-1\">\n                  {renderBlocks(\n                    item,\n                    context,\n                    {\n                      streaming: open && lastItem,\n                      tail: lastItem ? tail : undefined,\n                      tight: true,\n                    },\n                    `${k}.${itemIndex}`,\n                  )}\n                </li>\n              );\n            })}\n          </Tag>\n        );\n      }\n      case \"table\":\n        return (\n          <div key={k} className=\"overflow-x-auto rounded-xl ring-1 ring-border/60 ring-inset\">\n            <table className=\"w-full border-collapse text-[0.93em] tabular-nums\">\n              <thead className=\"bg-muted/40\">\n                <tr>\n                  {block.head.map((cell, cellIndex) => (\n                    <th\n                      key={cellIndex}\n                      scope=\"col\"\n                      style={{ textAlign: block.align[cellIndex] ?? undefined }}\n                      className=\"px-3 py-1.5 text-left font-medium whitespace-nowrap text-muted-foreground\"\n                    >\n                      {renderInlines(parseInline(cell), context, `${k}.h${cellIndex}`)}\n                    </th>\n                  ))}\n                </tr>\n              </thead>\n              <tbody>\n                {block.rows.map((row, rowIndex) => (\n                  <tr key={rowIndex} className=\"border-t border-border/60\">\n                    {block.head.map((_, cellIndex) => (\n                      <td\n                        key={cellIndex}\n                        style={{ textAlign: block.align[cellIndex] ?? undefined }}\n                        className=\"px-3 py-1.5 align-top\"\n                      >\n                        {renderInlines(\n                          parseInline(row[cellIndex] ?? \"\"),\n                          context,\n                          `${k}.${rowIndex}.${cellIndex}`,\n                        )}\n                        {rowIndex === block.rows.length - 1 &&\n                          cellIndex === block.head.length - 1 &&\n                          tail}\n                      </td>\n                    ))}\n                  </tr>\n                ))}\n              </tbody>\n            </table>\n          </div>\n        );\n    }\n  });\n}\n\nexport interface AssistantMarkdownProps extends Omit<React.ComponentProps<\"div\">, \"children\"> {\n  /** Markdown-lite with `{{metric:Label|Value|tone}}` and `{{cite:n}}` tokens. */\n  content: string;\n  citations?: AssistantCitation[];\n  /** Shows a caret and renders the unfinished tail optimistically. */\n  streaming?: boolean;\n  density?: AssistantDensity;\n  renderToken?: (token: AssistantToken) => React.ReactNode | undefined;\n  /** Citation highlighted from outside, e.g. while hovering a source. */\n  activeCitation?: string | null;\n  onActiveCitationChange?: (id: string | null) => void;\n  labels?: Partial<AssistantPanelLabels>;\n}\n\n/** Renders assistant markdown-lite safely as React elements. Used by AssistantPanel; usable alone. */\nexport function AssistantMarkdown({\n  content,\n  citations,\n  streaming = false,\n  density = \"comfortable\",\n  renderToken,\n  activeCitation: activeProp,\n  onActiveCitationChange,\n  labels: labelsProp,\n  className,\n  ...props\n}: AssistantMarkdownProps) {\n  const [activeState, setActiveState] = React.useState<string | null>(null);\n  const activeCitation = activeProp !== undefined ? activeProp : activeState;\n  const labels = { ...LABELS, ...labelsProp };\n  const blocks = React.useMemo(() => parseBlocks(content), [content]);\n  const compact = density === \"compact\";\n  const context: MarkdownContext = {\n    citations,\n    activeCitation,\n    setActiveCitation: (id) => {\n      if (activeProp === undefined) setActiveState(id);\n      onActiveCitationChange?.(id);\n    },\n    renderToken,\n    compact,\n    labels,\n  };\n  const tail = streaming ? caret : undefined;\n  return (\n    <div\n      data-slot=\"assistant-markdown\"\n      className={cn(\n        \"min-w-0 text-pretty text-foreground/90\",\n        compact ? \"space-y-2.5 text-[13px] leading-[1.65]\" : \"space-y-3 text-sm leading-6\",\n        className,\n      )}\n      {...props}\n    >\n      {blocks.length ? renderBlocks(blocks, context, { streaming, tail }) : streaming ? <p>{caret}</p> : null}\n    </div>\n  );\n}\n\n/* -------------------------------------------------------------------------------------------------\n * Steps\n * -----------------------------------------------------------------------------------------------*/\n\nconst stepIcon: Record<AssistantStepKind, typeof Search> = {\n  search: Search,\n  query: Database,\n  tool: Tool,\n  think: Bulb,\n};\n\nfunction StepRow({\n  step,\n  compact,\n  formatDuration,\n}: {\n  step: AssistantStep;\n  compact: boolean;\n  formatDuration: (ms: number) => string;\n}) {\n  const [open, setOpen] = React.useState(step.status === \"error\");\n  const detailId = React.useId();\n  const Icon = stepIcon[step.kind ?? \"tool\"] ?? Tool;\n  const duration =\n    step.status !== \"running\" && step.duration !== undefined ? formatDuration(step.duration) : null;\n  const expandable = Boolean(step.detail);\n  const label = (\n    <>\n      <span\n        aria-hidden=\"true\"\n        className={cn(\n          \"relative z-10 flex size-5 shrink-0 items-center justify-center rounded-full border bg-card transition-colors duration-300 motion-reduce:transition-none\",\n          step.status === \"error\" && \"border-destructive/35 bg-destructive/[0.06] text-destructive\",\n          step.status === \"running\" && \"border-transparent text-primary\",\n          step.status === \"done\" &&\n            \"border-emerald-600/25 bg-emerald-500/[0.08] text-emerald-700 dark:border-emerald-400/30 dark:text-emerald-400\",\n        )}\n      >\n        {step.status === \"running\" ? (\n          <>\n            {/* The kind icon, ringed by a turning arc. */}\n            <span className=\"absolute inset-0 rounded-full border border-primary/20\" />\n            <span className=\"absolute inset-0 rounded-full border border-transparent border-t-primary motion-safe:animate-spin\" />\n            <Icon className=\"size-3\" stroke={2} />\n          </>\n        ) : step.status === \"error\" ? (\n          <X className=\"size-3 motion-safe:animate-[assistant-pop_400ms_cubic-bezier(0.22,1,0.36,1)]\" stroke={2.5} />\n        ) : (\n          <svg\n            viewBox=\"0 0 24 24\"\n            className=\"size-3 motion-safe:animate-[assistant-pop_400ms_cubic-bezier(0.22,1,0.36,1)]\"\n            fill=\"none\"\n            stroke=\"currentColor\"\n            strokeWidth={3}\n            strokeLinecap=\"round\"\n            strokeLinejoin=\"round\"\n          >\n            <path\n              d=\"M5 12.5l4.5 4.5L19 7.5\"\n              strokeDasharray={22}\n              className=\"motion-safe:animate-[assistant-check_420ms_cubic-bezier(0.22,1,0.36,1)_80ms_backwards]\"\n            />\n          </svg>\n        )}\n      </span>\n      <span className=\"flex min-w-0 flex-1 items-baseline gap-1.5\">\n        <span\n          className={cn(\n            \"min-w-0 truncate\",\n            step.status === \"running\"\n              ? shimmer\n              : step.status === \"error\"\n                ? \"text-destructive\"\n                : \"text-foreground/80\",\n          )}\n        >\n          {step.label}\n        </span>\n        {duration && (\n          <span className=\"shrink-0 text-muted-foreground tabular-nums\">· {duration}</span>\n        )}\n        <span className=\"sr-only\">\n          {step.status === \"running\" ? \"in progress\" : step.status === \"error\" ? \"failed\" : \"done\"}\n        </span>\n      </span>\n      {expandable && (\n        <ChevronRight\n          aria-hidden=\"true\"\n          className={cn(\n            \"size-3.5 shrink-0 text-muted-foreground opacity-0 transition-[opacity,rotate] duration-200 group-hover/step:opacity-100 group-focus-visible/step:opacity-100 motion-reduce:transition-none\",\n            open && \"rotate-90 opacity-100\",\n          )}\n        />\n      )}\n    </>\n  );\n  const row = cn(\n    \"group/step flex w-full items-center gap-2.5 rounded-md text-left\",\n    compact ? \"min-h-6 py-0.5 text-xs\" : \"min-h-7 py-1 text-[13px]\",\n  );\n  return (\n    <li\n      data-slot=\"assistant-step\"\n      data-status={step.status}\n      data-kind={step.kind ?? \"tool\"}\n      className=\"relative transition-[opacity,translate] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)] starting:-translate-y-0.5 starting:opacity-0 motion-reduce:transition-none\"\n    >\n      {expandable ? (\n        <button\n          type=\"button\"\n          aria-expanded={open}\n          aria-controls={detailId}\n          onClick={() => setOpen((value) => !value)}\n          className={cn(row, \"-mx-1 w-[calc(100%+0.5rem)] px-1 hover:bg-muted/60\", focusRing)}\n        >\n          {label}\n        </button>\n      ) : (\n        <div className={row}>{label}</div>\n      )}\n      {expandable && (\n        <div\n          id={detailId}\n          className={cn(\n            \"grid transition-[grid-template-rows] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none\",\n            open ? \"grid-rows-[1fr]\" : \"grid-rows-[0fr]\",\n          )}\n        >\n          <div className=\"min-h-0 overflow-hidden\">\n            <pre\n              className={cn(\n                \"mt-1 mb-1.5 ml-[30px] max-h-48 overflow-auto rounded-xl bg-muted/40 px-3 py-2 font-mono leading-[1.6] break-words whitespace-pre-wrap ring-1 ring-border/60 ring-inset\",\n                compact ? \"text-[11px]\" : \"text-[11.5px]\",\n                step.status === \"error\" ? \"text-destructive\" : \"text-muted-foreground\",\n              )}\n            >\n              {step.detail}\n            </pre>\n          </div>\n        </div>\n      )}\n    </li>\n  );\n}\n\nfunction StepList({\n  message,\n  compact,\n  labels,\n  formatDuration,\n  renderStep,\n}: {\n  message: AssistantMessage;\n  compact: boolean;\n  labels: AssistantPanelLabels;\n  formatDuration: (ms: number) => string;\n  renderStep?: AssistantPanelProps[\"renderStep\"];\n}) {\n  const steps = message.steps ?? [];\n  const listId = React.useId();\n  const [userOpen, setUserOpen] = React.useState<boolean | null>(null);\n  const running = steps.find((step) => step.status === \"running\");\n  const failed = steps.filter((step) => step.status === \"error\").length;\n  const streaming = message.status === \"streaming\";\n  const autoOpen = Boolean(running) || (streaming && !message.content) || failed > 0;\n  const open = userOpen ?? autoOpen;\n  const total = steps.reduce((sum, step) => sum + (step.duration ?? 0), 0);\n  const summary = running\n    ? running.label\n    : failed\n      ? labels.stepsFailed(failed, steps.length)\n      : labels.steps(steps.length, total > 0 ? formatDuration(total) : null);\n\n  return (\n    <div data-slot=\"assistant-steps\" data-open={open || undefined}>\n      <button\n        type=\"button\"\n        aria-expanded={open}\n        aria-controls={listId}\n        onClick={() => setUserOpen(!open)}\n        className={cn(\n          \"group/summary -mx-1 inline-flex max-w-full items-center gap-1.5 rounded-md px-1 text-muted-foreground transition-colors hover:text-foreground motion-reduce:transition-none\",\n          compact ? \"h-6 text-xs\" : \"h-7 text-[13px]\",\n          focusRing,\n        )}\n      >\n        {running ? (\n          <Loader aria-hidden=\"true\" className=\"size-3.5 shrink-0 text-primary motion-safe:animate-spin\" stroke={2.25} />\n        ) : failed ? (\n          <AlertTriangle aria-hidden=\"true\" className=\"size-3.5 shrink-0 text-destructive\" />\n        ) : (\n          <Check aria-hidden=\"true\" className=\"size-3.5 shrink-0\" stroke={2.25} />\n        )}\n        <span className={cn(\"truncate\", running && shimmer)}>{summary}</span>\n        <ChevronRight\n          aria-hidden=\"true\"\n          className={cn(\n            \"size-3.5 shrink-0 transition-transform duration-200 motion-reduce:transition-none\",\n            open && \"rotate-90\",\n          )}\n        />\n      </button>\n      <div\n        className={cn(\n          \"grid transition-[grid-template-rows,opacity] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none\",\n          open ? \"grid-rows-[1fr] opacity-100\" : \"grid-rows-[0fr] opacity-0\",\n        )}\n      >\n        <div className=\"min-h-0 overflow-hidden\">\n          <ol\n            id={listId}\n            aria-label={labels.activity}\n            className=\"relative mt-1 mb-0.5 before:absolute before:top-3 before:bottom-3 before:left-[9.5px] before:w-px before:bg-border\"\n          >\n            {steps.map((step) => {\n              const custom = renderStep?.(step, message);\n              return custom !== undefined ? (\n                <li key={step.id} data-slot=\"assistant-step\" data-status={step.status}>\n                  {custom}\n                </li>\n              ) : (\n                <StepRow key={step.id} step={step} compact={compact} formatDuration={formatDuration} />\n              );\n            })}\n          </ol>\n        </div>\n      </div>\n    </div>\n  );\n}\n\n/* -------------------------------------------------------------------------------------------------\n * Messages\n * -----------------------------------------------------------------------------------------------*/\n\nfunction IconButton({\n  label,\n  pressed,\n  className,\n  children,\n  ...props\n}: React.ComponentProps<\"button\"> & { label: string; pressed?: boolean }) {\n  return (\n    <button\n      type=\"button\"\n      aria-label={label}\n      title={label}\n      aria-pressed={pressed}\n      className={cn(\n        \"inline-flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-40 motion-reduce:transition-none\",\n        focusRing,\n        className,\n      )}\n      {...props}\n    >\n      {children}\n    </button>\n  );\n}\n\ninterface AssistantMessageViewProps {\n  message: AssistantMessage;\n  isLast: boolean;\n  compact: boolean;\n  labels: AssistantPanelLabels;\n  feedback: AssistantFeedback | undefined;\n  onFeedback?: (value: AssistantFeedback) => void;\n  onRegenerate?: () => void;\n  onCopy?: (text: string, message: AssistantMessage) => void;\n  renderStep?: AssistantPanelProps[\"renderStep\"];\n  renderToken?: AssistantPanelProps[\"renderToken\"];\n  formatDuration: (ms: number) => string;\n  formatTime: (date: Date) => string;\n}\n\nfunction AssistantAnswer({\n  message,\n  isLast,\n  compact,\n  labels,\n  feedback,\n  onFeedback,\n  onRegenerate,\n  onCopy,\n  renderStep,\n  renderToken,\n  formatDuration,\n  formatTime,\n}: AssistantMessageViewProps) {\n  const status = message.status ?? \"done\";\n  const streaming = status === \"streaming\";\n  const mounted = useMounted();\n  const [copied, copy] = useCopy();\n  const [activeCitation, setActiveCitation] = React.useState<string | null>(null);\n  const steps = message.steps ?? [];\n  const running = steps.some((step) => step.status === \"running\");\n  const citations = message.citations ?? [];\n  const date = message.createdAt ? new Date(message.createdAt) : null;\n  const time = mounted && date && !Number.isNaN(date.getTime()) ? formatTime(date) : null;\n\n  return (\n    <>\n      {steps.length > 0 && (\n        <StepList\n          message={message}\n          compact={compact}\n          labels={labels}\n          formatDuration={formatDuration}\n          renderStep={renderStep}\n        />\n      )}\n\n      {streaming && !message.content && !running && (\n        <div className={cn(\"flex items-center gap-2\", compact ? \"text-xs\" : \"text-[13px]\")}>\n          <Loader aria-hidden=\"true\" className=\"size-3.5 text-muted-foreground motion-safe:animate-spin\" />\n          <span className={shimmer}>{labels.thinking}</span>\n        </div>\n      )}\n\n      {message.content && (\n        <AssistantMarkdown\n          content={message.content}\n          citations={citations}\n          streaming={streaming}\n          density={compact ? \"compact\" : \"comfortable\"}\n          renderToken={renderToken ? (token) => renderToken(token, message) : undefined}\n          activeCitation={activeCitation}\n          onActiveCitationChange={setActiveCitation}\n          labels={labels}\n        />\n      )}\n\n      {status === \"error\" && (\n        <div\n          data-slot=\"assistant-error\"\n          role=\"alert\"\n          className=\"flex items-start gap-2.5 rounded-xl border border-destructive/25 bg-destructive/[0.05] px-3 py-2.5\"\n        >\n          <AlertTriangle className=\"mt-0.5 size-4 shrink-0 text-destructive\" aria-hidden=\"true\" />\n          <div className=\"min-w-0 flex-1 text-[13px] leading-5\">\n            <p className=\"font-medium text-foreground\">{labels.error}</p>\n            {onRegenerate && (\n              <button\n                type=\"button\"\n                onClick={onRegenerate}\n                className={cn(\n                  \"mt-2 inline-flex h-7 items-center gap-1.5 rounded-md border bg-card px-2.5 text-xs font-medium shadow-xs transition-colors hover:bg-muted motion-reduce:transition-none\",\n                  focusRing,\n                )}\n              >\n                <Refresh className=\"size-3.5\" aria-hidden=\"true\" />\n                {labels.retry}\n              </button>\n            )}\n          </div>\n        </div>\n      )}\n\n      {!streaming && citations.length > 0 && (\n        <div\n          data-slot=\"assistant-sources\"\n          className=\"flex flex-wrap items-center gap-1.5 transition-[opacity,translate] duration-500 ease-[cubic-bezier(0.22,1,0.36,1)] starting:translate-y-1 starting:opacity-0 motion-reduce:transition-none\"\n        >\n          <span className=\"mr-0.5 text-xs text-muted-foreground\">{labels.sources}</span>\n          {citations.map((item, index) => {\n            const active = activeCitation === item.id;\n            const content = (\n              <>\n                <span\n                  className={cn(\n                    \"flex h-4 min-w-4 items-center justify-center rounded-[4px] px-1 text-[10px] leading-none font-semibold tabular-nums transition-colors\",\n                    active ? \"bg-primary/15 text-primary\" : \"bg-muted text-muted-foreground\",\n                  )}\n                >\n                  {index + 1}\n                </span>\n                <span className=\"min-w-0 truncate\">{item.label}</span>\n                {item.href && (\n                  <ArrowUpRight className=\"size-3 shrink-0 text-muted-foreground\" aria-hidden=\"true\" />\n                )}\n              </>\n            );\n            const chip = cn(\n              \"inline-flex h-6 max-w-full min-w-0 items-center gap-1.5 rounded-md border bg-card pr-2 pl-1 text-xs text-foreground/85 transition-colors motion-reduce:transition-none\",\n              active && \"border-primary/35 bg-primary/[0.05]\",\n            );\n            const hover = {\n              onPointerEnter: () => setActiveCitation(item.id),\n              onPointerLeave: () => setActiveCitation(null),\n            };\n            return item.href ? (\n              <a\n                key={item.id}\n                data-slot=\"assistant-source\"\n                data-active={active || undefined}\n                href={item.href}\n                target=\"_blank\"\n                rel=\"noreferrer\"\n                className={cn(chip, \"hover:bg-muted\", focusRing)}\n                onFocus={() => setActiveCitation(item.id)}\n                onBlur={() => setActiveCitation(null)}\n                {...hover}\n              >\n                {content}\n              </a>\n            ) : (\n              <span\n                key={item.id}\n                data-slot=\"assistant-source\"\n                data-active={active || undefined}\n                className={chip}\n                {...hover}\n              >\n                {content}\n              </span>\n            );\n          })}\n        </div>\n      )}\n\n      {!streaming && (message.content || status === \"error\") && (\n        <div\n          data-slot=\"assistant-message-actions\"\n          className={cn(\n            \"-mt-1 -ml-1.5 flex h-7 items-center gap-0.5 transition-opacity duration-150 motion-reduce:transition-none\",\n            !isLast &&\n              \"opacity-0 group-focus-within/message:opacity-100 group-hover/message:opacity-100 [@media(hover:none)]:opacity-100\",\n          )}\n        >\n          {message.content && (\n            <IconButton\n              label={copied ? labels.copied : labels.copy}\n              onClick={() =>\n                copy(\n                  assistantToPlainText(message.content),\n                  onCopy ? (text) => onCopy(text, message) : undefined,\n                )\n              }\n            >\n              {copied ? (\n                <Check className=\"size-3.5 text-emerald-700 dark:text-emerald-400\" aria-hidden=\"true\" />\n              ) : (\n                <Copy className=\"size-3.5\" aria-hidden=\"true\" />\n              )}\n            </IconButton>\n          )}\n          {onRegenerate && isLast && status !== \"error\" && (\n            <IconButton label={labels.regenerate} onClick={onRegenerate}>\n              <Refresh className=\"size-3.5\" aria-hidden=\"true\" />\n            </IconButton>\n          )}\n          {onFeedback && status === \"done\" && (\n            <div role=\"group\" aria-label={labels.feedback} className=\"flex items-center gap-0.5\">\n              <IconButton\n                label={labels.helpful}\n                pressed={feedback === \"up\"}\n                onClick={() => onFeedback(\"up\")}\n                className={cn(feedback === \"up\" && \"text-primary hover:text-primary\")}\n              >\n                {feedback === \"up\" ? (\n                  <ThumbUpFilled className=\"size-3.5\" aria-hidden=\"true\" />\n                ) : (\n                  <ThumbUp className=\"size-3.5\" aria-hidden=\"true\" />\n                )}\n              </IconButton>\n              <IconButton\n                label={labels.notHelpful}\n                pressed={feedback === \"down\"}\n                onClick={() => onFeedback(\"down\")}\n                className={cn(feedback === \"down\" && \"text-foreground\")}\n              >\n                {feedback === \"down\" ? (\n                  <ThumbDownFilled className=\"size-3.5\" aria-hidden=\"true\" />\n                ) : (\n                  <ThumbDown className=\"size-3.5\" aria-hidden=\"true\" />\n                )}\n              </IconButton>\n            </div>\n          )}\n          {time && (\n            <time\n              dateTime={date!.toISOString()}\n              className=\"ml-1.5 text-[11px] text-muted-foreground tabular-nums\"\n            >\n              {time}\n            </time>\n          )}\n        </div>\n      )}\n    </>\n  );\n}\n\n/* -------------------------------------------------------------------------------------------------\n * Composer pieces\n * -----------------------------------------------------------------------------------------------*/\n\nfunction normalizeModel(model: AssistantModel) {\n  return typeof model === \"string\"\n    ? { value: model, label: model, disabled: false }\n    : { value: model.value, label: model.label ?? model.value, disabled: model.disabled ?? false };\n}\n\nfunction ModelPicker({\n  models,\n  value,\n  onChange,\n  label,\n  disabled,\n}: {\n  models: AssistantModel[];\n  value: string | undefined;\n  onChange: (value: string) => void;\n  label: string;\n  disabled?: boolean;\n}) {\n  const options = models.map(normalizeModel);\n  const current = options.find((option) => option.value === value) ?? options[0];\n  return (\n    <span\n      data-slot=\"assistant-model\"\n      className={cn(\n        \"relative inline-flex h-7 min-w-0 items-center rounded-md text-xs font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground motion-reduce:transition-none\",\n        \"has-[select:focus-visible]:ring-2 has-[select:focus-visible]:ring-ring/50\",\n        disabled && \"pointer-events-none opacity-50\",\n      )}\n    >\n      <span aria-hidden=\"true\" className=\"truncate pr-6 pl-2\">\n        {current?.label}\n      </span>\n      <Selector aria-hidden=\"true\" className=\"pointer-events-none absolute right-1.5 size-3.5 opacity-70\" />\n      <select\n        aria-label={label}\n        value={current?.value}\n        disabled={disabled}\n        onChange={(event) => onChange(event.target.value)}\n        className=\"absolute inset-0 cursor-pointer appearance-none opacity-0 outline-none\"\n      >\n        {options.map((option) => (\n          <option key={option.value} value={option.value} disabled={option.disabled}>\n            {option.label}\n          </option>\n        ))}\n      </select>\n    </span>\n  );\n}\n\n/* -------------------------------------------------------------------------------------------------\n * AssistantPanel\n * -----------------------------------------------------------------------------------------------*/\n\n/**\n * An AI copilot conversation for admin apps: tool activity, streamed markdown with metric chips\n * and citations, feedback, and a composer with a model picker. Fills its parent's height.\n */\nexport function AssistantPanel({\n  messages,\n  status = \"idle\",\n  onSend,\n  onStop,\n  onRegenerate,\n  onFeedback,\n  feedback: feedbackProp,\n  onNewChat,\n  onCopy,\n  suggestions,\n  models,\n  model: modelProp,\n  defaultModel,\n  onModelChange,\n  title,\n  placeholder,\n  value: valueProp,\n  defaultValue = \"\",\n  onValueChange,\n  composerActions,\n  headerActions,\n  footer,\n  emptyState,\n  density = \"comfortable\",\n  disabled = false,\n  autoFocus = false,\n  maxComposerHeight = 200,\n  composerRef,\n  renderMessage,\n  renderStep,\n  renderToken,\n  formatDuration = formatAssistantDuration,\n  formatTime = defaultTimeFormat,\n  labels: labelsProp,\n  className,\n  ...props\n}: AssistantPanelProps) {\n  const labels = { ...LABELS, ...labelsProp };\n  const compact = density === \"compact\";\n  const reduced = useReducedMotion();\n  const busy = status === \"streaming\";\n  const id = React.useId();\n\n  // Draft\n  const [draftState, setDraftState] = React.useState(defaultValue);\n  const draft = valueProp ?? draftState;\n  const setDraft = (next: string) => {\n    if (valueProp === undefined) setDraftState(next);\n    onValueChange?.(next);\n  };\n\n  // Model\n  const firstModel = models?.length ? normalizeModel(models[0]).value : undefined;\n  const [modelState, setModelState] = React.useState(defaultModel ?? firstModel);\n  const model = modelProp ?? modelState ?? firstModel;\n  const setModel = (next: string) => {\n    if (modelProp === undefined) setModelState(next);\n    onModelChange?.(next);\n  };\n\n  // Feedback\n  const [feedbackState, setFeedbackState] = React.useState<Record<string, AssistantFeedback>>({});\n  const feedback = feedbackProp ?? feedbackState;\n  const giveFeedback = (messageId: string, value: AssistantFeedback) => {\n    if (feedbackProp === undefined) setFeedbackState((current) => ({ ...current, [messageId]: value }));\n    onFeedback?.(messageId, value);\n  };\n\n  // Textarea\n  const textareaRef = React.useRef<HTMLTextAreaElement>(null);\n  const setTextareaRef = React.useCallback(\n    (node: HTMLTextAreaElement | null) => {\n      textareaRef.current = node;\n      if (typeof composerRef === \"function\") composerRef(node);\n      else if (composerRef) (composerRef as React.RefObject<HTMLTextAreaElement | null>).current = node;\n    },\n    [composerRef],\n  );\n  useIsoLayoutEffect(() => {\n    const element = textareaRef.current;\n    if (!element) return;\n    element.style.height = \"auto\";\n    const height = Math.min(element.scrollHeight, maxComposerHeight);\n    element.style.height = `${height}px`;\n    element.style.overflowY = element.scrollHeight > maxComposerHeight ? \"auto\" : \"hidden\";\n  }, [draft, maxComposerHeight, density]);\n\n  // Scrolling: follow the newest content only while the reader is at the bottom.\n  const scrollRef = React.useRef<HTMLDivElement>(null);\n  const contentRef = React.useRef<HTMLDivElement>(null);\n  const stick = React.useRef(true);\n  const lastTop = React.useRef(0);\n  const jumping = React.useRef(false);\n  const [away, setAway] = React.useState(false);\n\n  const pin = React.useCallback(() => {\n    const element = scrollRef.current;\n    if (!element) return;\n    element.scrollTop = element.scrollHeight;\n    lastTop.current = element.scrollTop;\n  }, []);\n\n  React.useEffect(() => {\n    const content = contentRef.current;\n    if (!content) return;\n    const observer = new ResizeObserver(() => {\n      if (stick.current) pin();\n      else {\n        const element = scrollRef.current;\n        if (element) setAway(element.scrollHeight - element.scrollTop - element.clientHeight > 32);\n      }\n    });\n    observer.observe(content);\n    return () => observer.disconnect();\n  }, [pin]);\n\n  // A new question from the reader always brings the conversation back to the bottom.\n  const lastMessage = messages[messages.length - 1];\n  const lastId = lastMessage?.id;\n  const lastRole = lastMessage?.role;\n  useIsoLayoutEffect(() => {\n    if (lastRole === \"user\") {\n      stick.current = true;\n      setAway(false);\n    }\n    if (stick.current) pin();\n  }, [lastId, lastRole, pin]);\n\n  const handleScroll = () => {\n    const element = scrollRef.current;\n    if (!element) return;\n    const top = element.scrollTop;\n    const distance = element.scrollHeight - top - element.clientHeight;\n    if (jumping.current) {\n      if (distance < 4) jumping.current = false;\n      lastTop.current = top;\n      return;\n    }\n    if (top < lastTop.current - 2) stick.current = false;\n    if (distance < 24) stick.current = true;\n    lastTop.current = top;\n    setAway(!stick.current && distance > 32);\n  };\n\n  const jumpToLatest = () => {\n    const element = scrollRef.current;\n    if (!element) return;\n    stick.current = true;\n    jumping.current = !reduced;\n    setAway(false);\n    element.scrollTo({ top: element.scrollHeight, behavior: reduced ? \"auto\" : \"smooth\" });\n  };\n\n  const send = (text: string) => {\n    const value = text.trim();\n    if (!value || busy || disabled) return;\n    onSend?.(value, { model });\n    if (text === draft) setDraft(\"\");\n    stick.current = true;\n    requestAnimationFrame(() => textareaRef.current?.focus());\n  };\n\n  const composing = React.useRef(false);\n  const handleKeyDown = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {\n    if (event.key !== \"Enter\" || event.shiftKey) return;\n    // Ignore Enter that confirms an IME composition (keyCode 229 covers Safari's late events).\n    if (event.nativeEvent.isComposing || composing.current || event.keyCode === 229) return;\n    event.preventDefault();\n    send(draft);\n  };\n\n  const lastAssistantId = [...messages].reverse().find((message) => message.role === \"assistant\")?.id;\n  const lastUserId = [...messages].reverse().find((message) => message.role === \"user\")?.id;\n  const latest = messages[messages.length - 1];\n  const working =\n    busy && latest?.role === \"assistant\"\n      ? latest.content\n        ? labels.writing\n        : labels.thinking\n      : busy\n        ? labels.thinking\n        : null;\n  const canSend = draft.trim().length > 0 && !busy && !disabled;\n  const toolbar = Boolean(composerActions) || Boolean(models?.length);\n  const submit = busy ? (\n    <button\n      type=\"button\"\n      onClick={() => {\n        onStop?.();\n        textareaRef.current?.focus();\n      }}\n      disabled={!onStop}\n      aria-label={labels.stop}\n      title={labels.stop}\n      className={cn(\n        \"inline-flex size-8 items-center justify-center rounded-xl bg-foreground text-background shadow-xs transition-opacity duration-150 hover:opacity-85 disabled:opacity-40 motion-reduce:transition-none\",\n        focusRing,\n      )}\n    >\n      <Stop className=\"size-3.5\" aria-hidden=\"true\" />\n    </button>\n  ) : (\n    <button\n      type=\"submit\"\n      disabled={!canSend}\n      aria-label={labels.send}\n      title={labels.send}\n      className={cn(\n        \"inline-flex size-8 items-center justify-center rounded-xl bg-primary text-primary-foreground shadow-xs transition-[background-color,color,opacity,scale,box-shadow] duration-150 hover:opacity-90 active:scale-95 disabled:bg-muted disabled:text-muted-foreground disabled:shadow-none motion-reduce:transition-none\",\n        focusRing,\n      )}\n    >\n      <ArrowUp className=\"size-4\" aria-hidden=\"true\" stroke={2.25} />\n    </button>\n  );\n  const modelBadge = !models?.length && modelProp ? modelProp : null;\n\n  return (\n    <div\n      data-slot=\"assistant-panel\"\n      data-density={density}\n      data-status={status}\n      aria-busy={busy || undefined}\n      className={cn(\n        \"@container/assistant relative isolate flex h-full min-h-0 min-w-0 flex-col overflow-hidden rounded-2xl border border-border/70 bg-card text-card-foreground shadow-[0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.10)] dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.05),0_1px_2px_rgb(0_0_0/0.5)]\",\n        className,\n      )}\n      {...props}\n    >\n      <style href=\"overtrue-assistant-panel\" precedence=\"default\">\n        {styles}\n      </style>\n      <div\n        data-slot=\"assistant-header\"\n        className={cn(\n          \"flex shrink-0 items-center gap-2 border-b border-border/60\",\n          compact ? \"h-11 pr-2 pl-3\" : \"h-12 pr-2.5 pl-4\",\n        )}\n      >\n        <span\n          aria-hidden=\"true\"\n          className={cn(\n            \"flex shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground\",\n            compact ? \"size-6\" : \"size-7\",\n          )}\n        >\n          <Message className={compact ? \"size-3.5\" : \"size-4\"} stroke={1.75} />\n        </span>\n        <div className=\"flex min-w-0 flex-1 items-baseline gap-2\">\n          <h2\n            id={`${id}-title`}\n            className=\"truncate text-sm leading-5 font-semibold tracking-tight\"\n          >\n            {title ?? labels.title}\n          </h2>\n          {modelBadge && (\n            <span className=\"hidden shrink-0 rounded-md border px-1.5 font-mono text-[11px] leading-[18px] text-muted-foreground @[18rem]/assistant:inline\">\n              {modelBadge}\n            </span>\n          )}\n          {working && (\n            <span\n              className={cn(\"hidden shrink-0 text-xs @[20rem]/assistant:inline\", shimmer)}\n              aria-hidden=\"true\"\n            >\n              {working}\n            </span>\n          )}\n        </div>\n        <div className=\"flex shrink-0 items-center gap-0.5\">\n          {onNewChat && (\n            <button\n              type=\"button\"\n              onClick={() => {\n                onNewChat();\n                requestAnimationFrame(() => textareaRef.current?.focus());\n              }}\n              disabled={messages.length === 0 && !draft}\n              aria-label={labels.newChat}\n              title={labels.newChat}\n              className={cn(\n                \"inline-flex h-7 items-center gap-1.5 rounded-md px-1.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-40 motion-reduce:transition-none @[26rem]/assistant:px-2\",\n                focusRing,\n              )}\n            >\n              <NewChat className=\"size-4\" aria-hidden=\"true\" stroke={1.75} />\n              <span className=\"hidden @[26rem]/assistant:inline\">{labels.newChat}</span>\n            </button>\n          )}\n          {headerActions}\n        </div>\n      </div>\n\n      <div className=\"relative flex min-h-0 flex-1 flex-col\">\n        <div\n          ref={scrollRef}\n          role=\"log\"\n          aria-live=\"polite\"\n          aria-label={labels.conversation}\n          onScroll={handleScroll}\n          onWheel={(event) => {\n            if (event.deltaY < 0) stick.current = false;\n          }}\n          className=\"min-h-0 flex-1 overflow-y-auto overscroll-contain\"\n        >\n          <div\n            ref={contentRef}\n            className={cn(\n              \"flex min-h-full flex-col\",\n              compact ? \"gap-5 px-3 pt-4 pb-5\" : \"gap-7 px-4 pt-5 pb-6 @lg/assistant:px-5\",\n            )}\n          >\n            {messages.length === 0\n              ? (emptyState ?? (\n                  <div\n                    data-slot=\"assistant-empty\"\n                    className=\"m-auto flex w-full max-w-sm flex-col items-center py-4 text-center\"\n                  >\n                    <span\n                      aria-hidden=\"true\"\n                      className=\"flex size-11 items-center justify-center rounded-2xl bg-muted text-muted-foreground\"\n                    >\n                      <Message className=\"size-5\" stroke={1.6} />\n                    </span>\n                    <p className=\"mt-3.5 text-[15px] font-semibold tracking-tight text-foreground\">\n                      {labels.emptyTitle}\n                    </p>\n                    <p className=\"mt-1 max-w-72 text-[13px] leading-5 text-pretty text-muted-foreground\">\n                      {labels.emptyDescription}\n                    </p>\n                    {suggestions && suggestions.length > 0 && (\n                      <ul\n                        data-slot=\"assistant-suggestions\"\n                        className=\"mt-5 flex w-full flex-col gap-1.5\"\n                      >\n                        {suggestions.map((suggestion, index) => {\n                          const item =\n                            typeof suggestion === \"string\"\n                              ? { label: suggestion, prompt: suggestion, icon: undefined }\n                              : suggestion;\n                          return (\n                            <li\n                              key={index}\n                              className=\"transition-[opacity,translate] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)] starting:translate-y-1 starting:opacity-0 motion-reduce:transition-none\"\n                              style={{ transitionDelay: `${index * 50}ms` }}\n                            >\n                              <button\n                                type=\"button\"\n                                disabled={busy || disabled}\n                                onClick={() => send(item.prompt ?? item.label)}\n                                className={cn(\n                                  \"group/suggestion flex w-full items-center gap-2.5 rounded-xl border border-border/70 bg-card/80 px-3 py-2 text-left text-[13px] leading-5 text-foreground/85 shadow-[0_1px_2px_rgb(0_0_0/0.04)] transition-[border-color,background-color,color,box-shadow] duration-150 hover:border-primary/25 hover:bg-card hover:text-foreground hover:shadow-[0_6px_18px_-10px_color-mix(in_oklab,var(--color-primary)_55%,transparent)] disabled:opacity-50 motion-reduce:transition-none\",\n                                  focusRing,\n                                )}\n                              >\n                                <span aria-hidden=\"true\" className=\"shrink-0 text-muted-foreground transition-colors duration-150 group-hover/suggestion:text-primary [&_svg]:size-4\">\n                                  {item.icon ?? <Message className=\"size-4\" stroke={1.75} />}\n                                </span>\n                                <span className=\"min-w-0 flex-1\">{item.label}</span>\n                                <ArrowUp\n                                  aria-hidden=\"true\"\n                                  className=\"size-3.5 shrink-0 rotate-45 text-muted-foreground opacity-0 transition-opacity group-hover/suggestion:opacity-100 group-focus-visible/suggestion:opacity-100\"\n                                />\n                              </button>\n                            </li>\n                          );\n                        })}\n                      </ul>\n                    )}\n                  </div>\n                ))\n              : messages.map((message, index) => {\n                  const isLast =\n                    message.id === (message.role === \"assistant\" ? lastAssistantId : lastUserId);\n                  const status = message.status ?? \"done\";\n                  const builtIn =\n                    message.role === \"user\" ? (\n                      <div\n                        className={cn(\n                          \"max-w-[85%] rounded-2xl rounded-br-md bg-muted px-3.5 py-2 break-words whitespace-pre-wrap text-foreground\",\n                          compact ? \"text-[13px] leading-[1.6]\" : \"text-sm leading-6\",\n                        )}\n                      >\n                        <span className=\"sr-only\">{labels.you}: </span>\n                        {message.content}\n                      </div>\n                    ) : (\n                      <AssistantAnswer\n                        message={message}\n                        isLast={isLast}\n                        compact={compact}\n                        labels={labels}\n                        feedback={feedback[message.id]}\n                        onFeedback={onFeedback ? (value) => giveFeedback(message.id, value) : undefined}\n                        onRegenerate={onRegenerate && !busy ? () => onRegenerate(message.id) : undefined}\n                        onCopy={onCopy}\n                        renderStep={renderStep}\n                        renderToken={renderToken}\n                        formatDuration={formatDuration}\n                        formatTime={formatTime}\n                      />\n                    );\n                  const custom = renderMessage?.(message, { index, isLast, children: builtIn });\n                  return (\n                    <article\n                      key={message.id}\n                      data-slot=\"assistant-message\"\n                      data-role={message.role}\n                      data-status={message.role === \"assistant\" ? status : undefined}\n                      aria-busy={status === \"streaming\" || undefined}\n                      aria-label={message.role === \"user\" ? labels.you : labels.assistant}\n                      className={cn(\n                        \"group/message flex min-w-0 flex-col transition-[opacity,translate] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)] starting:translate-y-1.5 starting:opacity-0 motion-reduce:transition-none\",\n                        message.role === \"user\" ? \"items-end\" : compact ? \"gap-2.5\" : \"gap-3\",\n                      )}\n                    >\n                      {custom !== undefined ? custom : builtIn}\n                    </article>\n                  );\n                })}\n          </div>\n        </div>\n\n        {away && messages.length > 0 && (\n          <button\n            type=\"button\"\n            onClick={jumpToLatest}\n            className={cn(\n              \"absolute bottom-3 left-1/2 inline-flex h-7 -translate-x-1/2 items-center gap-1.5 rounded-full border border-border/70 bg-popover/90 pr-3 pl-2.5 text-xs font-medium text-popover-foreground shadow-xl backdrop-blur-md transition-[opacity,translate,background-color] duration-300 ease-[cubic-bezier(0.22,1,0.36,1)] hover:bg-muted starting:translate-y-2 starting:opacity-0 motion-reduce:transition-none\",\n              focusRing,\n            )}\n          >\n            <ArrowDown className=\"size-3.5\" aria-hidden=\"true\" />\n            {labels.jumpToLatest}\n          </button>\n        )}\n      </div>\n\n      <form\n        data-slot=\"assistant-composer\"\n        data-disabled={disabled || undefined}\n        onSubmit={(event) => {\n          event.preventDefault();\n          send(draft);\n        }}\n        className={cn(\"shrink-0\", compact ? \"px-2.5 pb-2.5\" : \"px-3 pb-3 @lg/assistant:px-4 @lg/assistant:pb-4\")}\n      >\n        <div\n          className={cn(\n            \"rounded-2xl border border-border/80 bg-background/70 shadow-[0_1px_2px_rgb(0_0_0/0.04)] transition-[border-color,box-shadow] duration-150 focus-within:border-primary/40 focus-within:shadow-[0_0_0_4px_color-mix(in_oklab,var(--color-primary)_10%,transparent)] dark:focus-within:shadow-[0_0_0_4px_color-mix(in_oklab,var(--color-primary)_10%,transparent),0_10px_30px_-12px_color-mix(in_oklab,var(--color-primary)_45%,transparent)] motion-reduce:transition-none dark:bg-background/40\",\n            disabled && \"opacity-60\",\n          )}\n        >\n          <div className={cn(!toolbar && \"flex items-end\")}>\n            <textarea\n              ref={setTextareaRef}\n              rows={1}\n              value={draft}\n              disabled={disabled}\n              autoFocus={autoFocus}\n              placeholder={placeholder ?? labels.placeholder}\n              aria-label={placeholder ?? labels.placeholder}\n              onChange={(event) => setDraft(event.target.value)}\n              onKeyDown={handleKeyDown}\n              onCompositionStart={() => {\n                composing.current = true;\n              }}\n              onCompositionEnd={() => {\n                // Safari fires keydown after compositionend; release on the next tick.\n                window.setTimeout(() => {\n                  composing.current = false;\n                }, 0);\n              }}\n              className={cn(\n                \"block w-full min-w-0 resize-none bg-transparent text-foreground outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed\",\n                compact ? \"px-3 text-[13px] leading-5\" : \"px-3.5 text-sm leading-6\",\n                toolbar\n                  ? compact\n                    ? \"pt-2.5 pb-1\"\n                    : \"pt-3 pb-1.5\"\n                  : compact\n                    ? \"flex-1 py-2.5\"\n                    : \"flex-1 py-3\",\n              )}\n            />\n            {!toolbar && <div className={cn(\"shrink-0\", compact ? \"p-1\" : \"p-1.5\")}>{submit}</div>}\n          </div>\n          {toolbar && (\n            <div className={cn(\"flex items-center gap-1\", compact ? \"px-1.5 pb-1.5\" : \"px-2 pb-2\")}>\n              {composerActions && (\n                <div className=\"flex min-w-0 items-center gap-0.5 text-muted-foreground\">{composerActions}</div>\n              )}\n              {models && models.length > 0 && (\n                <ModelPicker\n                  models={models}\n                  value={model}\n                  onChange={setModel}\n                  label={labels.model}\n                  disabled={disabled}\n                />\n              )}\n              <div className=\"ml-auto flex shrink-0 items-center gap-2\">{submit}</div>\n            </div>\n          )}\n        </div>\n        {footer && (\n          <div className=\"mt-2 text-center text-[11px] leading-4 text-muted-foreground\">{footer}</div>\n        )}\n      </form>\n    </div>\n  );\n}\n"
    }
  ],
  "docs": "Documentation: https://ui.overtrue.xyz/components/assistant-panel. Requires an initialized shadcn/ui project with Tailwind CSS v4."
}
