{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ai-chat",
  "title": "AI Chat",
  "description": "The parts every AI block shares: message types that take the Vercel AI SDK’s useChat and UIMessage as they are, Markdown from a model drawn with safe links and no HTML while it streams, each word fading in as it arrives, a reply that leads with one line rolling through what the model is doing beside a ring that spins, then folds its thinking, tool calls and sources into “Used 2 tools in 3.4 s”, tool calls with their state, approval and details, tool results drawn as blocks, attached files, and numbered sources and citations.",
  "dependencies": [
    "marked@^18.1.0",
    "remend@^1.4.0"
  ],
  "registryDependencies": [
    "attachment",
    "button",
    "https://www.dashboardblocks.com/r/radix/agent-ring.json",
    "https://www.dashboardblocks.com/r/radix/disclosure.json",
    "https://www.dashboardblocks.com/r/radix/format.json",
    "https://www.dashboardblocks.com/r/radix/highlighted-code.json",
    "https://www.dashboardblocks.com/r/radix/link.json",
    "https://www.dashboardblocks.com/r/radix/rolling-text.json",
    "https://www.dashboardblocks.com/r/radix/table.json",
    "https://www.dashboardblocks.com/r/radix/text-change.json"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/ai-message.ts",
      "content": "/** The shape of the AI SDK's `UIMessage`, so `useChat().messages` and `readUIMessageStream` pass straight in, and any other provider can build one. */\ninterface AIMessage {\n  id: string\n  /** Anything the server attaches to the reply, such as token usage. */\n  metadata?: unknown\n  parts: AIMessagePart[]\n  role: 'system' | 'user' | 'assistant'\n}\n\ntype AIMessagePart =\n  | AITextPart\n  | AIReasoningPart\n  | AIToolPart\n  | AIDynamicToolPart\n  | AISourceUrlPart\n  | AISourceDocumentPart\n  | AIFilePart\n  | AIDataPart\n  | { type: 'step-start' | 'custom' | 'reasoning-file' | 'steering-message' }\n\ninterface AITextPart {\n  /** What the text cites, as the AI SDK gives it: the page or document, and where in the text when the provider says. */\n  citations?: AICitation[]\n  state?: 'streaming' | 'done'\n  text: string\n  type: 'text'\n}\n\ninterface AICitation {\n  /** Where the cited passage ends in the part's text, when the provider says. */\n  endIndex?: number\n  source:\n    | { id: string; sourceType: 'url'; title?: string; url: string }\n    | { id: string; sourceType: 'document'; title: string }\n}\n\n/** Empty when the provider keeps its reasoning to itself and sends only that it thought. */\ninterface AIReasoningPart {\n  state?: 'streaming' | 'done'\n  text: string\n  type: 'reasoning'\n}\n\ntype AIToolState =\n  | 'input-streaming'\n  | 'input-available'\n  | 'approval-requested'\n  | 'approval-responded'\n  | 'output-available'\n  | 'output-error'\n  | 'output-denied'\n\ninterface AIToolCall {\n  approval?: {\n    approved?: boolean\n    id: string\n    /** The app answered, not the person, such as a call whose tool was turned off while it waited. */\n    isAutomatic?: boolean\n    reason?: string\n    /** Why the server asks, when it says. */\n    requestReason?: string\n  }\n  errorText?: string\n  input?: unknown\n  output?: unknown\n  /** A result the tool will replace with its final one. */\n  preliminary?: boolean\n  state: AIToolState\n  title?: string\n  toolCallId: string\n}\n\ninterface AIToolPart extends AIToolCall {\n  type: `tool-${string}`\n}\n\ninterface AIDynamicToolPart extends AIToolCall {\n  toolName: string\n  type: 'dynamic-tool'\n}\n\ninterface AISourceUrlPart {\n  sourceId: string\n  title?: string\n  type: 'source-url'\n  url: string\n}\n\ninterface AISourceDocumentPart {\n  filename?: string\n  mediaType: string\n  sourceId: string\n  title: string\n  type: 'source-document'\n}\n\ninterface AIFilePart {\n  filename?: string\n  mediaType: string\n  type: 'file'\n  /** A hosted file or a data URL. */\n  url: string\n}\n\ninterface AIDataPart {\n  data: unknown\n  id?: string\n  type: `data-${string}`\n}\n\n/** A reply as it stands while it streams: what `readUIMessageStream` yields, or `replyFromText` for a provider that streams plain text. Its `id`, when the server sends one, is the reply's id from then on. */\ntype AIReply = Pick<AIMessage, 'metadata' | 'parts'> & { id?: string }\n\n/** `submitted` waits for the first part of a reply, `streaming` while parts arrive. */\ntype AIChatStatus = 'ready' | 'submitted' | 'streaming' | 'error'\n\ninterface AIToolApprovalResponse {\n  approved: boolean\n  /** The `approval.id` of the tool part, not its `toolCallId`. */\n  id: string\n  reason?: string\n}\n\n/** What a chat block runs on: `useChat()` from `@ai-sdk/react` as it is, or `useChatStream` for any other stream. */\ninterface AIChat {\n  addToolApprovalResponse?: (response: AIToolApprovalResponse) => unknown\n  error?: Error\n  messages: AIMessage[]\n  /** Writes the reply again: the one `messageId` names, or the last. */\n  regenerate: (options?: { messageId?: string }) => unknown\n  /** Shows that version of the message `messageId` names, and what followed it then. */\n  selectVersion?: (messageId: string, index: number) => unknown\n  /**\n   * `metadata` goes on the person's message, such as what the page shows when they ask. With\n   * `messageId`, the message is an edit of that question, and replaces it and what followed it.\n   */\n  sendMessage: (message: {\n    files?: AIFilePart[]\n    messageId?: string\n    metadata?: unknown\n    text: string\n  }) => unknown\n  /** Called with `[]` to start a new chat. */\n  setMessages?: (messages: []) => void\n  status: AIChatStatus\n  stop: () => unknown\n  /** The versions an edit or a regenerate kept. Leave out when the chat doesn't keep them. */\n  versions?: AIMessageVersions\n}\n\n/**\n * The versions a chat keeps after an edit or a regenerate, by the id of the message before them\n * (`''` before the first): each version of what followed it, and the one showing. The one showing\n * is held as `[]`, since the chat's messages hold it.\n */\ntype AIMessageVersions<Message extends { id: string } = AIMessage> = Record<\n  string,\n  { current: number; versions: Message[][] }\n>\n\ninterface AIBranch<Message extends { id: string }> {\n  messages: Message[]\n  versions: AIMessageVersions<Message>\n}\n\nconst replaceAt = <Item>(items: Item[], index: number, item: Item) =>\n  items.map((current, at) => (at === index ? item : current))\n\nconst versionKey = (messages: { id: string }[], index: number) =>\n  messages[index - 1]?.id ?? ''\n\n/** Replaces the messages from `index` on with `next`, keeping what was there as an earlier version. */\nfunction branchMessages<Message extends { id: string }>(\n  { messages, versions }: AIBranch<Message>,\n  index: number,\n  next: Message[],\n): AIBranch<Message> {\n  const before = messages.slice(0, index)\n  const replaced = messages.slice(index)\n  if (replaced.length === 0) return { messages: [...before, ...next], versions }\n  const key = versionKey(messages, index)\n  const kept = versions[key] ?? { current: 0, versions: [[]] }\n  const all = replaceAt(kept.versions, kept.current, replaced)\n  return {\n    messages: [...before, ...next],\n    versions: {\n      ...versions,\n      [key]: { current: all.length, versions: [...all, []] },\n    },\n  }\n}\n\n/** Shows version `index` of the message `messageId` names, and what followed it then. */\nfunction selectMessageVersion<Message extends { id: string }>(\n  branch: AIBranch<Message>,\n  messageId: string,\n  index: number,\n): AIBranch<Message> {\n  const { messages, versions } = branch\n  const at = messages.findIndex((message) => message.id === messageId)\n  const key = versionKey(messages, at)\n  const kept = versions[key]\n  const shown = kept?.versions[index]\n  if (at === -1 || !kept || index === kept.current || !shown?.length) return branch\n  const all = replaceAt(kept.versions, kept.current, messages.slice(at))\n  return {\n    messages: [...messages.slice(0, at), ...shown],\n    versions: {\n      ...versions,\n      [key]: { current: index, versions: replaceAt(all, index, []) },\n    },\n  }\n}\n\n/** Which version of the message at `index` shows, and how many there are, or `undefined` when it has one. */\nfunction getMessageVersion(\n  messages: { id: string }[],\n  versions: AIMessageVersions<{ id: string }> | undefined,\n  index: number,\n) {\n  const kept = versions?.[versionKey(messages, index)]\n  if (!kept || kept.versions.length < 2) return undefined\n  return { count: kept.versions.length, index: kept.current }\n}\n\n/** A record a reply cites. `[2]` in the reply's text links to its second source. */\ninterface AISource {\n  /** Leave out for a source with nothing to open, such as a document the model was given. */\n  href?: string\n  /** `'query'` shows the label as code. */\n  kind?: 'query'\n  label: string\n}\n\ntype AIAnyToolPart = AIToolPart | AIDynamicToolPart\n\nfunction isToolPart(part: AIMessagePart): part is AIAnyToolPart {\n  return part.type === 'dynamic-tool' || part.type.startsWith('tool-')\n}\n\nfunction getToolName(part: AIAnyToolPart) {\n  return part.type === 'dynamic-tool' ? part.toolName : part.type.slice('tool-'.length)\n}\n\n/** `lookup_order` and `lookupOrder` read \"Lookup order\". */\nfunction getToolLabel(part: AIAnyToolPart) {\n  if (part.title) return part.title\n  const words = getToolName(part)\n    .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n    .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n    .replace(/[_-]+/g, ' ')\n    .trim()\n    .toLowerCase()\n  return words.charAt(0).toUpperCase() + words.slice(1)\n}\n\nconst citationKey = ({ source }: AICitation) =>\n  source.sourceType === 'url' ? source.url : source.id\n\n/** What the reply cites, once each, in the order first cited. */\nfunction getCitations(parts: AIMessagePart[]) {\n  const cited = new Map<string, AICitation>()\n  for (const part of parts) {\n    if (part.type !== 'text') continue\n    for (const citation of byEnd(part)) {\n      const key = citationKey(citation)\n      if (!cited.has(key)) cited.set(key, citation)\n    }\n  }\n  return cited\n}\n\nfunction byEnd(part: AITextPart) {\n  const end = (citation: AICitation) => citation.endIndex ?? part.text.length\n  return [...(part.citations ?? [])].sort((a, b) => end(a) - end(b))\n}\n\n/** The text with `[n]` after each passage it cites, before the space that follows. */\nfunction markCitations(part: AITextPart, cited: string[]) {\n  let text = part.text\n  const marks = new Map<number, string>()\n  for (const citation of byEnd(part)) {\n    const end = Math.min(citation.endIndex ?? text.length, text.length)\n    const mark = `[${cited.indexOf(citationKey(citation)) + 1}]`\n    if (!marks.get(end)?.includes(mark)) marks.set(end, (marks.get(end) ?? '') + mark)\n  }\n  for (const [end, mark] of [...marks].sort(([a], [b]) => b - a)) {\n    const before = text.slice(0, end).trimEnd()\n    text = before + mark + text.slice(before.length)\n  }\n  return text\n}\n\n/**\n * A reply's parts as they read: text parts in a row joined into one, since a provider can split\n * its text wherever a citation starts or ends (Claude's web search does), and `[n]` after each\n * passage the text cites, `n` being the source's place in `getMessageSources`.\n */\nfunction getReadableParts(message: Pick<AIMessage, 'parts'>): AIMessagePart[] {\n  const cited = [...getCitations(message.parts).keys()]\n  const parts: AIMessagePart[] = []\n  message.parts.forEach((part, index) => {\n    if (part.type !== 'text') {\n      parts.push(part)\n      return\n    }\n    const text = part.citations?.length ? markCitations(part, cited) : part.text\n    const previous = parts.at(-1)\n    if (previous?.type === 'text' && message.parts[index - 1]?.type === 'text') {\n      parts[parts.length - 1] = {\n        state: part.state,\n        text: previous.text + text,\n        type: 'text',\n      }\n    } else {\n      parts.push({ state: part.state, text, type: 'text' })\n    }\n  })\n  return parts\n}\n\n/** The reply's text, as written, for copying. */\nfunction getMessageText(message: Pick<AIMessage, 'parts'>) {\n  return getReadableParts(message)\n    .flatMap((part) =>\n      part.type === 'text' && part.text.trim() ? [part.text.trim()] : [],\n    )\n    .join('\\n\\n')\n}\n\n/** The link when it's safe to open from what a model wrote: http(s), mailto, or a path in the app. Anything else, such as `javascript:`, is dropped. */\nfunction hasControlCharacter(value: string) {\n  for (let index = 0; index < value.length; index++) {\n    const code = value.charCodeAt(index)\n    if (code < 32 || code === 127) return true\n  }\n  return false\n}\n\nfunction getSafeHref(href: string | undefined) {\n  const value = href?.trim()\n  if (!value || hasControlCharacter(value)) return undefined\n  if (/^(?:https?:\\/\\/|mailto:)/i.test(value)) return value\n  if (/^(?:\\/(?![/\\\\])|#|\\?)/.test(value)) return value\n  return undefined\n}\n\n/** What `[n]` in the reply links to: the sources its text cites, in the order first cited, or, when it cites none, every source it sent. */\nfunction getMessageSources(message: Pick<AIMessage, 'parts'>): AISource[] {\n  const cited = getCitations(message.parts)\n  if (cited.size > 0) {\n    return [...cited.values()].map(({ source }) => {\n      if (source.sourceType === 'document') return { label: source.title }\n      return { href: getSafeHref(source.url), label: source.title || source.url }\n    })\n  }\n  return message.parts.flatMap((part) => {\n    if (part.type === 'source-url') {\n      return [{ href: getSafeHref(part.url), label: part.title || part.url }]\n    }\n    if (part.type === 'source-document') return [{ label: part.title }]\n    return []\n  })\n}\n\nfunction getMessageFiles(message: Pick<AIMessage, 'parts'>) {\n  return message.parts.filter((part): part is AIFilePart => part.type === 'file')\n}\n\n/** The reply still arriving: the last message, when it's the assistant's and the chat is busy. A reply that goes on after an approval waits as `submitted`, so it counts too. */\nfunction getStreamingMessageId(\n  messages: Pick<AIMessage, 'id' | 'role'>[],\n  status: AIChatStatus,\n) {\n  const last = messages.at(-1)\n  if (last?.role !== 'assistant') return undefined\n  return status === 'streaming' || status === 'submitted' ? last.id : undefined\n}\n\n/** Turns a stream of text chunks into replies for `useChatStream`. */\nasync function* replyFromText(chunks: AsyncIterable<string>): AsyncGenerator<AIReply> {\n  let text = ''\n  for await (const chunk of chunks) {\n    text += chunk\n    yield { parts: [{ state: 'streaming', text, type: 'text' }] }\n  }\n  yield { parts: [{ state: 'done', text, type: 'text' }] }\n}\n\nexport {\n  branchMessages,\n  getMessageFiles,\n  getMessageSources,\n  getMessageText,\n  getSafeHref,\n  getStreamingMessageId,\n  getToolLabel,\n  getMessageVersion,\n  getReadableParts,\n  getToolName,\n  isToolPart,\n  replyFromText,\n  selectMessageVersion,\n}\n\nexport type {\n  AIAnyToolPart,\n  AIBranch,\n  AIChat,\n  AICitation,\n  AIChatStatus,\n  AIDataPart,\n  AIDynamicToolPart,\n  AIFilePart,\n  AIMessage,\n  AIMessagePart,\n  AIMessageVersions,\n  AIReasoningPart,\n  AIReply,\n  AISource,\n  AISourceDocumentPart,\n  AISourceUrlPart,\n  AITextPart,\n  AIToolApprovalResponse,\n  AIToolCall,\n  AIToolPart,\n  AIToolState,\n}\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/ai-message.ts"
    },
    {
      "path": "registry/components/dashboardblocks/ai-sources.tsx",
      "content": "'use client'\n\nimport type { AISource } from '@/registry/components/dashboardblocks/ai-message'\nimport { isPlainClick, useLinkNavigate } from '@/registry/components/dashboardblocks/link'\nimport type { ReactNode } from 'react'\n\n/**\n * A link from a model's reply or its sources. Takes an href `getSafeHref` passed; a web address opens in a new tab.\n * A plain `<a>`, not the app's router link, which may fetch an in-app path the model chose as soon as it shows; a click on an in-app path opens it with `LinkProvider`'s `navigate`.\n */\nfunction AILink({\n  children,\n  className,\n  href,\n}: {\n  children: ReactNode\n  className?: string\n  href: string\n}) {\n  const navigate = useLinkNavigate()\n  const external = /^https?:/i.test(href)\n  const inApp = /^[/?#]/.test(href)\n  return (\n    <a\n      href={href}\n      onClick={(event) => {\n        if (!inApp || !navigate || event.defaultPrevented || !isPlainClick(event)) return\n        event.preventDefault()\n        navigate(href)\n      }}\n      target={external ? '_blank' : undefined}\n      rel={external ? 'noopener noreferrer' : undefined}\n      className={className}\n    >\n      {children}\n      {external && <span className='sr-only'> (opens in a new tab)</span>}\n    </a>\n  )\n}\n\n/** A cited `[n]`: the number, linked to its source, with the source's name for screen readers. */\nfunction Citation({ index, source }: { index: number; source: AISource }) {\n  const label = (\n    <>\n      <span aria-hidden>{index}</span>\n      <span className='sr-only'>\n        Source {index}: {source.label}\n      </span>\n    </>\n  )\n  return (\n    <sup data-slot='citation' className='ms-0.5'>\n      {source.href ? (\n        <AILink\n          href={source.href}\n          className='text-primary font-medium tabular-nums underline underline-offset-2'\n        >\n          {label}\n        </AILink>\n      ) : (\n        <span className='text-muted-foreground font-medium tabular-nums'>{label}</span>\n      )}\n    </sup>\n  )\n}\n\nfunction SourceList({\n  heading = 'Sources',\n  headingLevel: Heading = 'h4',\n  id,\n  numbers,\n  sources,\n}: {\n  /** @default 'Sources' */\n  heading?: string\n  /** @default 'h4' */\n  headingLevel?: 'h3' | 'h4'\n  id: string\n  /** Lists only these sources, keeping their numbers; leave it out to list them all. */\n  numbers?: number[]\n  sources: AISource[]\n}) {\n  const listed = (numbers ?? sources.map((_, index) => index + 1)).flatMap((number) => {\n    const source = sources[number - 1]\n    return source ? [{ number, source }] : []\n  })\n  if (listed.length === 0) return null\n  return (\n    <div data-slot='source-list' className='flex flex-col gap-1.5 text-sm'>\n      <Heading id={`${id}-sources`} className='text-muted-foreground'>\n        {heading}\n      </Heading>\n      <ol\n        aria-labelledby={`${id}-sources`}\n        className='marker:text-muted-foreground flex list-decimal flex-col gap-1 ps-5 marker:tabular-nums'\n      >\n        {listed.map(({ number, source }) => {\n          const label =\n            source.kind === 'query' ? (\n              <code className='font-mono text-xs break-all'>{source.label}</code>\n            ) : (\n              source.label\n            )\n          return (\n            <li key={number} value={number} className='min-w-0 break-words'>\n              {source.href ? (\n                <AILink href={source.href} className='underline underline-offset-4'>\n                  {label}\n                </AILink>\n              ) : (\n                label\n              )}\n            </li>\n          )\n        })}\n      </ol>\n    </div>\n  )\n}\n\nexport { AILink, Citation, SourceList }\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/ai-sources.tsx"
    },
    {
      "path": "registry/components/dashboardblocks/ai-markdown.tsx",
      "content": "'use client'\n\nimport {\n  type AISource,\n  getSafeHref,\n} from '@/registry/components/dashboardblocks/ai-message'\nimport { AILink, Citation } from '@/registry/components/dashboardblocks/ai-sources'\nimport { HighlightedCode } from '@/registry/components/dashboardblocks/highlighted-code'\nimport {\n  DataTable,\n  DataTableBody,\n  DataTableCell,\n  DataTableHead,\n  DataTableHeader,\n  DataTableRow,\n} from '@/registry/components/dashboardblocks/table'\nimport { TextChange } from '@/registry/components/dashboardblocks/text-change'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport { fenceLanguage } from '@/registry/lib/dashboardblocks/markdown-fences'\nimport { Lexer, type Token, type Tokens } from 'marked'\nimport { Fragment, type ReactNode } from 'react'\nimport remend from 'remend'\n\nimport { cn } from '@/lib/utils'\n\nconst PARTIAL_CITATION = /\\s*\\[\\d{0,3}$/\nconst CHANGE_MARKS = {\n  added: ['\\uE000', '\\uE001'],\n  removed: ['\\uE002', '\\uE003'],\n} as const\nconst CHANGE_MARK = /([\\uE000-\\uE003])/\nconst CHANGE_MARKS_ALL = /[\\uE000-\\uE003]/g\nconst CITATION = /\\[(\\d{1,3})\\]/g\n\nconst ENTITIES: Record<string, string> = {\n  amp: '&',\n  apos: \"'\",\n  bull: '\\u2022',\n  cent: '¢',\n  copy: '©',\n  darr: '↓',\n  deg: '°',\n  divide: '÷',\n  euro: '€',\n  ge: '≥',\n  gt: '>',\n  hellip: '…',\n  larr: '←',\n  ldquo: '“',\n  le: '≤',\n  lsquo: '‘',\n  lt: '<',\n  mdash: '—',\n  middot: '\\u00b7',\n  nbsp: '\\u00a0',\n  ndash: '–',\n  ne: '≠',\n  plusmn: '±',\n  pound: '£',\n  quot: '\"',\n  rarr: '→',\n  rdquo: '”',\n  reg: '®',\n  rsquo: '’',\n  times: '×',\n  trade: '™',\n  uarr: '↑',\n  yen: '¥',\n}\n\n// marked decodes numeric entities in text but leaves named ones (`&amp;`) as typed. React escapes the result, so it stays text.\nfunction decodeEntities(text: string) {\n  return text.replace(\n    /&(#x[\\da-f]{1,6}|#\\d{1,7}|[a-z][a-z\\d]{1,31});/gi,\n    (match, name: string) => {\n      if (name.startsWith('#')) {\n        const code =\n          name[1] === 'x' || name[1] === 'X'\n            ? parseInt(name.slice(2), 16)\n            : Number(name.slice(1))\n        return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : match\n      }\n      return Object.hasOwn(ENTITIES, name) ? ENTITIES[name] : match\n    },\n  )\n}\n\n/** Closes what a reply has opened but not finished yet (`**bold`, a backtick, a link), and holds back a citation or a table row still being written, so raw syntax never shows while it streams. */\nfunction completeMarkdown(text: string) {\n  return remend(text.replace(PARTIAL_CITATION, ''), {\n    images: false,\n    inlineKatex: false,\n    katex: false,\n    linkMode: 'text-only',\n  })\n}\n\nfunction lex(text: string, streaming: boolean) {\n  const tokens = new Lexer({ breaks: true, gfm: true }).lex(\n    streaming ? completeMarkdown(text) : text,\n  )\n  if (!streaming) return tokens\n  const last = tokens.findLast((token) => token.type !== 'space')\n  // A table's first row reads as text until the line under it arrives.\n  if (last?.type === 'paragraph' && last.raw.trimStart().startsWith('|')) {\n    return tokens.slice(0, tokens.lastIndexOf(last))\n  }\n  return tokens\n}\n\nconst BLOCKS = new Set(['blockquote', 'code', 'heading', 'list', 'paragraph', 'table'])\n\nfunction plainText(tokens: Token[], sourceCount: number): string {\n  return tokens\n    .map(\n      (token) => plainTextOf(token, sourceCount) + (BLOCKS.has(token.type) ? '\\n' : ''),\n    )\n    .join('')\n}\n\nfunction plainTextOf(token: Token, sourceCount: number): string {\n  if ('tokens' in token && token.tokens) return plainText(token.tokens, sourceCount)\n  if (token.type === 'list') {\n    return (token as Tokens.List).items\n      .map((item) => plainText(item.tokens, sourceCount))\n      .join('\\n')\n  }\n  if (token.type === 'table') {\n    const table = token as Tokens.Table\n    return [table.header, ...table.rows]\n      .map((row) => row.map((cell) => plainText(cell.tokens, sourceCount)).join(', '))\n      .join('\\n')\n  }\n  if (token.type === 'space') return '\\n'\n  if (token.type === 'hr' || token.type === 'checkbox') return ''\n  if (token.type === 'codespan' || token.type === 'code') return token.text\n  if (!('text' in token)) return ''\n  return decodeEntities(token.text).replace(\n    /\\s*\\[(\\d{1,3})\\]/g,\n    (match, number: string) =>\n      Number(number) >= 1 && Number(number) <= sourceCount ? '' : match,\n  )\n}\n\n/** What a reply says without its Markdown, for a screen reader's announcement. Citations of its `sourceCount` sources are left out. */\nfunction markdownToPlainText(text: string, sourceCount = 0) {\n  return plainText(lex(text.replace(CHANGE_MARKS_ALL, ''), false), sourceCount)\n    .replace(/\\n{2,}/g, '\\n')\n    .trim()\n}\n\n/** The sources a text cites, in order and once each, out of `sourceCount`. */\nfunction getCitedNumbers(text: string, sourceCount: number) {\n  const cited = new Set<number>()\n  for (const match of text.matchAll(CITATION)) {\n    const number = Number(match[1])\n    if (number >= 1 && number <= sourceCount) cited.add(number)\n  }\n  return [...cited].sort((a, b) => a - b)\n}\n\ninterface RenderContext {\n  /** The change the text being drawn is inside, from `markChange`, as it carries across inline tokens. */\n  change: 'added' | 'removed' | null\n  fences: AIMarkdownFences\n  writing?: Token\n  sources: AISource[]\n  streaming: boolean\n}\n\nfunction fadeInWords(text: string, key: string): ReactNode[] {\n  return (text.match(/\\s*\\S+\\s*|\\s+/g) ?? []).map((word, index) => (\n    <span\n      key={`${key}-${index}`}\n      className='motion-safe:animate-in motion-safe:fade-in duration-500'\n    >\n      {word}\n    </span>\n  ))\n}\n\nfunction renderText(raw: string, context: RenderContext, key: string): ReactNode {\n  if (!CHANGE_MARK.test(raw)) {\n    const node = renderWords(raw, context, key)\n    return context.change ? <TextChange change={context.change}>{node}</TextChange> : node\n  }\n  return raw.split(CHANGE_MARK).map((piece, index) => {\n    if (piece === CHANGE_MARKS.added[0]) context.change = 'added'\n    else if (piece === CHANGE_MARKS.removed[0]) context.change = 'removed'\n    else if (piece === CHANGE_MARKS.added[1] || piece === CHANGE_MARKS.removed[1])\n      context.change = null\n    else if (piece) {\n      const node = renderWords(piece, context, `${key}-${index}`)\n      return context.change ? (\n        <TextChange key={index} change={context.change}>\n          {node}\n        </TextChange>\n      ) : (\n        <Fragment key={index}>{node}</Fragment>\n      )\n    }\n    return null\n  })\n}\n\nfunction renderWords(raw: string, context: RenderContext, key: string): ReactNode {\n  const text = decodeEntities(raw)\n  // One flat list of words, so a word keeps its node when a citation after it completes.\n  const show = (value: string, at: number): ReactNode[] =>\n    context.streaming ? fadeInWords(value, `${key}-${at}`) : [value]\n  if (context.sources.length === 0 || !text.includes('[')) return show(text, 0)\n  const parts: ReactNode[] = []\n  let last = 0\n  for (const match of text.matchAll(CITATION)) {\n    const source = context.sources[Number(match[1]) - 1]\n    if (!source) continue\n    // The space before a citation would sit between the word and its number.\n    parts.push(...show(text.slice(last, match.index).replace(/\\s+$/, ''), last))\n    const citation = (\n      <Citation key={`${key}-${match.index}`} index={Number(match[1])} source={source} />\n    )\n    parts.push(\n      context.streaming ? (\n        <span\n          key={`${key}-${match.index}`}\n          className='motion-safe:animate-in motion-safe:fade-in duration-500'\n        >\n          {citation}\n        </span>\n      ) : (\n        citation\n      ),\n    )\n    last = match.index + match[0].length\n  }\n  parts.push(...show(text.slice(last), last))\n  return parts\n}\n\nfunction renderInline(tokens: Token[], context: RenderContext, prefix = ''): ReactNode[] {\n  return tokens.map((token, index) => {\n    const key = `${prefix}${index}`\n    switch (token.type) {\n      case 'strong':\n        return (\n          <strong key={key} className='font-semibold'>\n            {renderInline((token as Tokens.Strong).tokens, context, `${key}-`)}\n          </strong>\n        )\n      case 'em':\n        return (\n          <em key={key}>\n            {renderInline((token as Tokens.Em).tokens, context, `${key}-`)}\n          </em>\n        )\n      case 'del':\n        return (\n          <del key={key}>\n            {renderInline((token as Tokens.Del).tokens, context, `${key}-`)}\n          </del>\n        )\n      case 'codespan':\n        return (\n          <code\n            key={key}\n            className='bg-muted rounded-sm px-1 py-0.5 font-mono text-[0.85em]'\n          >\n            {(token as Tokens.Codespan).text}\n          </code>\n        )\n      case 'br':\n        return <br key={key} />\n      case 'link':\n      case 'image': {\n        const link = token as Tokens.Link | Tokens.Image\n        const label =\n          link.type === 'link'\n            ? renderInline(link.tokens, context, `${key}-`)\n            : link.text || link.href\n        const href = getSafeHref(link.href)\n        if (!href) return <span key={key}>{label}</span>\n        return (\n          <AILink\n            key={key}\n            href={href}\n            className='font-medium underline underline-offset-4'\n          >\n            {label}\n          </AILink>\n        )\n      }\n      case 'text': {\n        const text = token as Tokens.Text\n        return text.tokens ? (\n          <span key={key}>{renderInline(text.tokens, context, `${key}-`)}</span>\n        ) : (\n          <span key={key}>{renderText(text.text, context, key)}</span>\n        )\n      }\n      case 'escape':\n        return <span key={key}>{(token as Tokens.Escape).text}</span>\n      case 'html':\n        return <span key={key}>{token.raw}</span>\n      default:\n        return null\n    }\n  })\n}\n\nfunction renderListItem(item: Tokens.ListItem, context: RenderContext, key: string) {\n  const content = item.tokens.filter((token) => token.type !== 'checkbox')\n  const body = renderBlocks(content, context, `${key}-`, !item.loose)\n  if (!item.task) {\n    return (\n      <li key={key} className='marker:text-muted-foreground ps-1'>\n        {body}\n      </li>\n    )\n  }\n  return (\n    <li key={key} className='-ms-5 flex list-none items-start gap-2'>\n      {item.checked ? (\n        <IconPlaceholder\n          lucide='CircleCheckIcon'\n          tabler='IconCircleCheck'\n          hugeicons='CheckmarkCircle02Icon'\n          phosphor='CheckCircleIcon'\n          remixicon='RiCheckboxCircleLine'\n          aria-hidden\n          className='mt-1 size-4 shrink-0 text-emerald-700 dark:text-emerald-400'\n        />\n      ) : (\n        <IconPlaceholder\n          lucide='CircleIcon'\n          tabler='IconCircle'\n          hugeicons='CircleIcon'\n          phosphor='CircleIcon'\n          remixicon='RiCircleLine'\n          aria-hidden\n          className='text-muted-foreground mt-1 size-4 shrink-0'\n        />\n      )}\n      <span className='sr-only'>{item.checked ? 'Done: ' : 'To do: '}</span>\n      <div className='min-w-0 flex-1'>{body}</div>\n    </li>\n  )\n}\n\nfunction lastToken(tokens: Token[]): Token | undefined {\n  const last = tokens.findLast((token) => token.type !== 'space')\n  if (!last) return undefined\n  const children =\n    last.type === 'list'\n      ? (last as Tokens.List).items\n      : 'tokens' in last && last.type !== 'paragraph' && last.type !== 'text'\n        ? (last.tokens as Token[] | undefined)\n        : undefined\n  return (children && lastToken(children)) ?? last\n}\n\nfunction renderBlocks(\n  tokens: Token[],\n  context: RenderContext,\n  prefix = '',\n  tight = false,\n): ReactNode[] {\n  return tokens.map((token, index) => {\n    const key = `${prefix}${index}`\n    switch (token.type) {\n      case 'paragraph':\n        return (\n          <p key={key}>\n            {renderInline((token as Tokens.Paragraph).tokens, context, `${key}-`)}\n          </p>\n        )\n      case 'text': {\n        const text = token as Tokens.Text\n        const inline = renderInline(text.tokens ?? [text], context, `${key}-`)\n        return tight ? <span key={key}>{inline}</span> : <p key={key}>{inline}</p>\n      }\n      case 'heading':\n        return (\n          <p key={key} className='font-semibold'>\n            {renderInline((token as Tokens.Heading).tokens, context, `${key}-`)}\n          </p>\n        )\n      case 'list': {\n        const list = token as Tokens.List\n        const List = list.ordered ? 'ol' : 'ul'\n        const start = typeof list.start === 'number' ? list.start : 1\n        return (\n          <List\n            key={key}\n            start={list.ordered && start !== 1 ? start : undefined}\n            className={cn(\n              'flex flex-col gap-1 ps-5',\n              list.ordered ? 'list-decimal' : 'list-disc',\n            )}\n          >\n            {list.items.map((item, itemIndex) =>\n              renderListItem(item, context, `${key}-${itemIndex}`),\n            )}\n          </List>\n        )\n      }\n      case 'blockquote':\n        return (\n          <blockquote\n            key={key}\n            className='text-muted-foreground flex flex-col gap-2 border-s-2 ps-3'\n          >\n            {renderBlocks((token as Tokens.Blockquote).tokens, context, `${key}-`)}\n          </blockquote>\n        )\n      case 'code': {\n        const code = token as Tokens.Code\n        const language = fenceLanguage(code)\n        const fence = Object.hasOwn(context.fences, language)\n          ? context.fences[language]\n          : undefined\n        if (fence) {\n          return (\n            <Fragment key={key}>\n              {fence({\n                code: code.text,\n                writing: token === context.writing,\n              })}\n            </Fragment>\n          )\n        }\n        return (\n          <HighlightedCode\n            key={key}\n            code={code.text}\n            language={language}\n            title={language || 'code'}\n          />\n        )\n      }\n      case 'table': {\n        const table = token as Tokens.Table\n        const align = (value: Tokens.TableCell['align']) =>\n          value === 'right' ? 'end' : value === 'center' ? 'center' : 'start'\n        return (\n          <DataTable key={key} density='compact'>\n            <DataTableHeader>\n              <DataTableRow>\n                {table.header.map((cell, cellIndex) => (\n                  <DataTableHead key={cellIndex} align={align(cell.align)}>\n                    {renderInline(cell.tokens, context, `${key}-h${cellIndex}-`)}\n                  </DataTableHead>\n                ))}\n              </DataTableRow>\n            </DataTableHeader>\n            <DataTableBody>\n              {table.rows.map((row, rowIndex) => (\n                <DataTableRow key={rowIndex}>\n                  {row.map((cell, cellIndex) => (\n                    <DataTableCell\n                      key={cellIndex}\n                      align={align(cell.align)}\n                      className={cn(cell.align !== 'right' && 'min-w-32')}\n                    >\n                      {renderInline(\n                        cell.tokens,\n                        context,\n                        `${key}-${rowIndex}-${cellIndex}-`,\n                      )}\n                    </DataTableCell>\n                  ))}\n                </DataTableRow>\n              ))}\n            </DataTableBody>\n          </DataTable>\n        )\n      }\n      case 'hr':\n        return <hr key={key} className='border-border' />\n      case 'html':\n        return <p key={key}>{token.raw.trim()}</p>\n      default:\n        return null\n    }\n  })\n}\n\n/** What a fenced block holds: its text, and whether the model is still writing it. */\ninterface AIMarkdownFence {\n  code: string\n  /** True while the reply streams and the block is the last thing in it, so its text may be cut short. */\n  writing: boolean\n}\n\n/** Parts that draw a fenced block of the language they're keyed by (```chart), in place of the code. */\ntype AIMarkdownFences = Record<string, (fence: AIMarkdownFence) => ReactNode>\n\ninterface AIMarkdownProps {\n  /** Draws the words `markChange` marked as added or removed. Off, as for a model's own reply, the marks are dropped. */\n  changes?: boolean\n  className?: string\n  /** Draws fenced blocks of these languages with your own part, such as a chart from the JSON a model wrote. Others show as code. */\n  fences?: AIMarkdownFences\n  /** `[n]` in the text links to the nth source. */\n  sources?: AISource[]\n  /** Closes unfinished syntax and holds back half-written table rows and citations. */\n  streaming?: boolean\n  text: string\n}\n\n/** Wraps text so `AIMarkdown` shows it as added or removed, as a document's changes do. Mark the words inside a line or a table cell, after any list or heading marker. */\nfunction markChange(text: string, change: 'added' | 'removed') {\n  const [start, end] = CHANGE_MARKS[change]\n  return text ? `${start}${text}${end}` : ''\n}\n\ninterface MarkdownBlock {\n  /** The blank lines and spaces after it, so the blocks join back into the same text. */\n  after: string\n  /** The block's Markdown: a paragraph, a heading, a whole list or table, a code block. */\n  source: string\n}\n\n/** Splits Markdown into its top-level blocks, which `joinMarkdownBlocks` puts back together as they were. */\nfunction markdownBlocks(text: string): MarkdownBlock[] {\n  const blocks: MarkdownBlock[] = []\n  for (const token of new Lexer({ breaks: true, gfm: true }).lex(text)) {\n    const last = blocks.at(-1)\n    if (token.type === 'space') {\n      if (last) last.after += token.raw\n      continue\n    }\n    const source = token.raw.trimEnd()\n    blocks.push({ after: token.raw.slice(source.length), source })\n  }\n  return blocks\n}\n\nfunction joinMarkdownBlocks(blocks: MarkdownBlock[]) {\n  return blocks.map((block) => block.source + block.after).join('')\n}\n\nconst NO_FENCES: AIMarkdownFences = {}\n\n/** Markdown a model wrote: GitHub's tables, lists, task lists, quotes, links and code. HTML shows as text; links open only http(s), mailto and in-app paths; images show as links. */\nfunction AIMarkdown({\n  changes = false,\n  className,\n  fences = NO_FENCES,\n  sources = [],\n  streaming = false,\n  text,\n}: AIMarkdownProps) {\n  const source = changes ? text : text.replace(CHANGE_MARKS_ALL, '')\n  const tokens = lex(source, streaming)\n  const blocks = renderBlocks(tokens, {\n    change: null,\n    fences,\n    sources,\n    streaming,\n    writing: streaming ? lastToken(tokens) : undefined,\n  })\n  if (blocks.every((block) => block === null)) return null\n  return (\n    <div\n      data-slot='ai-markdown'\n      className={cn('flex min-w-0 flex-col gap-3 leading-relaxed break-words', className)}\n    >\n      {blocks}\n    </div>\n  )\n}\n\nexport {\n  AIMarkdown,\n  completeMarkdown,\n  getCitedNumbers,\n  joinMarkdownBlocks,\n  markChange,\n  markdownBlocks,\n  markdownToPlainText,\n}\n\nexport type { AIMarkdownFence, AIMarkdownFences, AIMarkdownProps, MarkdownBlock }\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/ai-markdown.tsx"
    },
    {
      "path": "registry/lib/dashboardblocks/markdown-fences.ts",
      "content": "import { Lexer, type Token, type Tokens } from 'marked'\n\n/** The language a fenced block names, without the words after it (`chart` in ```chart title). */\nconst fenceLanguage = (code: Tokens.Code) => (code.lang ?? '').split(/\\s/)[0]\n\nfunction collect(tokens: Token[], language: string, found: string[]) {\n  for (const token of tokens) {\n    if (token.type === 'code' && fenceLanguage(token as Tokens.Code) === language) {\n      found.push((token as Tokens.Code).text)\n    } else if (token.type === 'list') {\n      for (const item of (token as Tokens.List).items)\n        collect(item.tokens, language, found)\n    } else if (token.type === 'blockquote') {\n      collect((token as Tokens.Blockquote).tokens, language, found)\n    }\n  }\n  return found\n}\n\n/** The text of every fenced block of `language` in a Markdown text, in order, found as `AIMarkdown` finds the blocks it hands to `fences`. Runs on the server too. */\nfunction fencedBlocks(text: string, language: string): string[] {\n  return collect(new Lexer({ breaks: true, gfm: true }).lex(text), language, [])\n}\n\nexport { fenceLanguage, fencedBlocks }\n",
      "type": "registry:lib",
      "target": "@lib/dashboardblocks/markdown-fences.ts"
    },
    {
      "path": "registry/components/dashboardblocks/ai-parts.tsx",
      "content": "'use client'\n\nimport {\n  AgentRing,\n  type AgentRingStatus,\n} from '@/registry/components/dashboardblocks/agent-ring'\nimport {\n  AIMarkdown,\n  completeMarkdown,\n} from '@/registry/components/dashboardblocks/ai-markdown'\nimport {\n  type AIAnyToolPart,\n  type AIFilePart,\n  type AIMessage,\n  type AISource,\n  type AIToolApprovalResponse,\n  getMessageFiles,\n  getMessageSources,\n  getReadableParts,\n  getToolLabel,\n  getToolName,\n  isToolPart,\n} from '@/registry/components/dashboardblocks/ai-message'\nimport { SourceList } from '@/registry/components/dashboardblocks/ai-sources'\nimport {\n  Disclosure,\n  DisclosureContent,\n  DisclosureTrigger,\n} from '@/registry/components/dashboardblocks/disclosure'\nimport { HighlightedCode } from '@/registry/components/dashboardblocks/highlighted-code'\nimport { RollingText } from '@/registry/components/dashboardblocks/rolling-text'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport { formatDuration } from '@/registry/lib/dashboardblocks/format'\nimport {\n  type ReactNode,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from 'react'\n\nimport {\n  Attachment,\n  AttachmentContent,\n  AttachmentDescription,\n  AttachmentMedia,\n  AttachmentTitle,\n} from '@/components/ui/attachment'\nimport { Button } from '@/components/ui/button'\n\nimport { cn } from '@/lib/utils'\n\ninterface WorkLineProps {\n  /** What the line folds: the steps behind it. Leave out for a line alone. */\n  children?: ReactNode\n  className?: string\n  line: string\n  status: AgentRingStatus\n}\n\n/** The line a reply leads with while a model works: a ring that spins, the step it's on rolling to the next, then what it did, folding the steps under it. */\nfunction WorkLine({ children, className, line, status }: WorkLineProps) {\n  const text = (\n    <RollingText\n      text={line}\n      className={cn(\n        'h-5 text-sm',\n        status === 'running' && 'shimmer',\n        status === 'waiting' && 'text-orange-700 dark:text-orange-400',\n      )}\n    />\n  )\n  const ring = (\n    <AgentRing status={status} className='size-6 [--agent-ring-icon:0.75rem]' />\n  )\n  if (!children) {\n    return (\n      <div\n        data-slot='work-line'\n        className={cn(\n          'text-muted-foreground flex min-h-7.5 min-w-0 items-center gap-2.5',\n          className,\n        )}\n      >\n        {ring}\n        <div className='min-w-0 flex-1'>{text}</div>\n      </div>\n    )\n  }\n  return (\n    <Disclosure data-slot='work-line' className={cn('gap-3', className)}>\n      <div className='flex min-h-7.5 w-full min-w-0 items-center gap-2.5'>\n        {ring}\n        <DisclosureTrigger className='min-w-0 items-center [&_svg]:mt-0'>\n          {text}\n        </DisclosureTrigger>\n      </div>\n      <DisclosureContent className='gap-3 ps-8.5'>{children}</DisclosureContent>\n    </Disclosure>\n  )\n}\n\n/** The line a reply shows while the model works, before it has anything to show. */\nfunction ThinkingIndicator({\n  className,\n  label = 'Thinking…',\n}: {\n  className?: string\n  /** @default 'Thinking…' */\n  label?: string\n}) {\n  return <WorkLine className={className} line={label} status='running' />\n}\n\ninterface ThinkingProps {\n  className?: string\n  /** Shown before the model's reasoning arrives too, so the line doesn't move when it does. */\n  streaming: boolean\n  /** The model's reasoning. Empty when the provider doesn't send it. */\n  text: string\n}\n\n/** A model's reasoning: \"Thinking…\" while it works, then one line, \"Thought for 4.2 s\", that opens what it thought. It never opens by itself, so nothing under it moves. */\nfunction Thinking({ className, streaming, text }: ThinkingProps) {\n  const [durationMs, setDurationMs] = useState<number | null>(null)\n\n  useEffect(() => {\n    if (!streaming) return\n    const startedAt = performance.now()\n    return () => setDurationMs(performance.now() - startedAt)\n  }, [streaming])\n\n  if (streaming) {\n    return (\n      <p\n        data-slot='thinking'\n        className={cn('text-muted-foreground shimmer text-sm', className)}\n      >\n        Thinking…\n      </p>\n    )\n  }\n  const label =\n    durationMs === null ? 'Reasoning' : `Thought for ${formatDuration(durationMs)}`\n  if (!text.trim()) {\n    if (durationMs === null) return null\n    return (\n      <p data-slot='thinking' className={cn('text-muted-foreground text-sm', className)}>\n        {label}\n      </p>\n    )\n  }\n  return (\n    <Disclosure data-slot='thinking' className={className}>\n      <DisclosureTrigger>{label}</DisclosureTrigger>\n      <DisclosureContent>\n        <p className='text-muted-foreground border-s-2 ps-3 text-sm text-pretty break-words whitespace-pre-line'>\n          {text.trim()}\n        </p>\n      </DisclosureContent>\n    </Disclosure>\n  )\n}\n\nfunction stringify(value: unknown) {\n  if (typeof value === 'string') return value\n  return JSON.stringify(value, null, 2) ?? String(value)\n}\n\ninterface ToolValueProps {\n  /** What the value is, such as `Input`, `Output` or `Arguments`. */\n  label: string\n  /** The tool it belongs to, added to the region's name for screen readers. */\n  tool?: string\n  /** A string shows as written, highlighted when it's JSON; anything else as JSON. */\n  value: unknown\n}\n\nfunction isJson(text: string) {\n  if (!/^\\s*[[{]/.test(text)) return false\n  try {\n    JSON.parse(text)\n    return true\n  } catch {\n    return false\n  }\n}\n\n/** A tool's input or output, or any JSON a model call sent or got back: highlighted, in a code block with copy. */\nfunction ToolValue({ label, tool, value }: ToolValueProps) {\n  const code = stringify(value)\n  const name = tool ? `${label} of ${tool}` : label\n  return (\n    <div data-slot='tool-value' className='flex max-h-80 w-full min-w-0 flex-col'>\n      <HighlightedCode\n        code={code}\n        language={typeof value !== 'string' || isJson(value) ? 'json' : ''}\n        title={label}\n        copyLabel={`Copy ${name.toLowerCase()}`}\n        label={name}\n        wrap\n      />\n    </div>\n  )\n}\n\n/** Whether a tool call never ended: it was still running, or approved and running, when the reply stopped. */\nfunction isToolUnfinished(part: AIAnyToolPart) {\n  switch (part.state) {\n    case 'input-streaming':\n    case 'input-available':\n      return true\n    case 'approval-responded':\n      return part.approval?.approved !== false\n    case 'output-available':\n      return part.preliminary === true\n    default:\n      return false\n  }\n}\n\nfunction ToolStateIcon({ part, stopped }: { part: AIAnyToolPart; stopped: boolean }) {\n  const className = 'mt-0.5 size-4 shrink-0'\n  if (stopped) {\n    return (\n      <IconPlaceholder\n        lucide='CircleMinusIcon'\n        tabler='IconCircleMinus'\n        hugeicons='MinusSignCircleIcon'\n        phosphor='MinusCircleIcon'\n        remixicon='RiIndeterminateCircleLine'\n        aria-hidden\n        className={cn(className, 'text-muted-foreground')}\n      />\n    )\n  }\n  switch (part.state) {\n    case 'output-available':\n      return part.preliminary ? (\n        <ToolSpinner className={className} />\n      ) : (\n        <IconPlaceholder\n          lucide='CircleCheckIcon'\n          tabler='IconCircleCheck'\n          hugeicons='CheckmarkCircle02Icon'\n          phosphor='CheckCircleIcon'\n          remixicon='RiCheckboxCircleLine'\n          aria-hidden\n          className={cn(className, 'text-emerald-700 dark:text-emerald-400')}\n        />\n      )\n    case 'output-error':\n      return (\n        <IconPlaceholder\n          lucide='CircleAlertIcon'\n          tabler='IconAlertCircle'\n          hugeicons='AlertCircleIcon'\n          phosphor='WarningCircleIcon'\n          remixicon='RiErrorWarningLine'\n          aria-hidden\n          className={cn(className, 'text-red-700 dark:text-red-400')}\n        />\n      )\n    case 'output-denied':\n      return (\n        <IconPlaceholder\n          lucide='CircleXIcon'\n          tabler='IconCircleX'\n          hugeicons='CancelCircleIcon'\n          phosphor='XCircleIcon'\n          remixicon='RiCloseCircleLine'\n          aria-hidden\n          className={cn(className, 'text-muted-foreground')}\n        />\n      )\n    case 'approval-requested':\n      return (\n        <IconPlaceholder\n          lucide='CirclePauseIcon'\n          tabler='IconPlayerPause'\n          hugeicons='PauseIcon'\n          phosphor='PauseCircleIcon'\n          remixicon='RiPauseCircleLine'\n          aria-hidden\n          className={cn(className, 'text-orange-700 dark:text-orange-400')}\n        />\n      )\n    case 'approval-responded':\n      return part.approval?.approved === false ? (\n        <IconPlaceholder\n          lucide='CircleXIcon'\n          tabler='IconCircleX'\n          hugeicons='CancelCircleIcon'\n          phosphor='XCircleIcon'\n          remixicon='RiCloseCircleLine'\n          aria-hidden\n          className={cn(className, 'text-muted-foreground')}\n        />\n      ) : (\n        <ToolSpinner className={className} />\n      )\n    default:\n      return <ToolSpinner className={className} />\n  }\n}\n\nfunction ToolSpinner({ className }: { className: string }) {\n  return (\n    <IconPlaceholder\n      lucide='Loader2Icon'\n      tabler='IconLoader'\n      hugeicons='Loading03Icon'\n      phosphor='SpinnerIcon'\n      remixicon='RiLoaderLine'\n      aria-hidden\n      className={cn(\n        className,\n        'text-muted-foreground animate-spin motion-reduce:animate-none',\n      )}\n    />\n  )\n}\n\nfunction getToolStatus(part: AIAnyToolPart, stopped: boolean) {\n  if (stopped) return 'Not finished'\n  switch (part.state) {\n    case 'input-streaming':\n      return 'Preparing…'\n    case 'input-available':\n      return 'Running…'\n    case 'approval-requested':\n      return 'Waiting for approval'\n    case 'approval-responded':\n      return part.approval?.approved === false ? 'Denied' : 'Approved. Running…'\n    case 'output-available':\n      return part.preliminary ? 'Running…' : null\n    case 'output-error':\n      return `Failed: ${part.errorText ?? 'the tool returned an error.'}`\n    case 'output-denied':\n      return part.approval?.reason ? `Denied: ${part.approval.reason}` : 'Denied'\n  }\n}\n\ninterface ToolCallProps {\n  className?: string\n  /** The reply is still arriving. Once it isn't, a call that never ended reads \"Not finished\" instead of spinning. @default true */\n  inProgress?: boolean\n  /** What the row calls the tool. @default the part's `title`, or its name in words */\n  label?: string\n  /** Answers a tool that waits for approval. Leave out to show that it waits, with no buttons. */\n  onApprovalResponse?: (response: AIToolApprovalResponse) => void\n  part: AIAnyToolPart\n  /** The tool's result drawn as a block, such as a chart or a table, under the row. */\n  result?: ReactNode\n}\n\n/** One tool call: its state, its input and output under Details, Approve and Deny when it waits for a person, and its result drawn as a block when the block gives one. */\nfunction ToolCall({\n  className,\n  inProgress = true,\n  label,\n  onApprovalResponse,\n  part,\n  result,\n}: ToolCallProps) {\n  const name = label ?? getToolLabel(part)\n  const stopped = !inProgress && isToolUnfinished(part)\n  const status = getToolStatus(part, stopped)\n  const rowRef = useRef<HTMLDivElement>(null)\n  const waiting = part.state === 'approval-requested' && part.approval\n  const hasDetails =\n    part.state !== 'input-streaming' &&\n    (part.input !== undefined || part.output !== undefined)\n\n  function answer(approved: boolean) {\n    if (!part.approval) return\n    onApprovalResponse?.({ approved, id: part.approval.id })\n    // The buttons go once it's answered: keep focus on the call they answered.\n    rowRef.current?.focus()\n  }\n\n  return (\n    <div data-slot='tool-call' className={cn('flex min-w-0 flex-col gap-3', className)}>\n      <div\n        ref={rowRef}\n        tabIndex={-1}\n        className='flex min-w-0 items-start gap-2 rounded-sm outline-none'\n      >\n        <ToolStateIcon part={part} stopped={stopped} />\n        <div className='flex min-w-0 flex-1 flex-col gap-1'>\n          <p className='text-sm font-medium break-words'>{name}</p>\n          {status && (\n            <p\n              className={cn(\n                'text-xs break-words',\n                part.state === 'output-error'\n                  ? 'text-red-700 dark:text-red-400'\n                  : part.state === 'approval-requested'\n                    ? 'text-orange-700 dark:text-orange-400'\n                    : 'text-muted-foreground',\n              )}\n            >\n              {status}\n              {waiting &&\n                part.approval?.requestReason &&\n                `: ${part.approval.requestReason}`}\n            </p>\n          )}\n          {waiting && onApprovalResponse && (\n            <div className='mt-1 flex flex-wrap gap-2'>\n              <Button size='sm' onClick={() => answer(true)}>\n                Approve\n                <span className='sr-only'> {name}</span>\n              </Button>\n              <Button variant='outline' size='sm' onClick={() => answer(false)}>\n                Deny\n                <span className='sr-only'> {name}</span>\n              </Button>\n            </div>\n          )}\n          {hasDetails && (\n            <Disclosure className='mt-1'>\n              <DisclosureTrigger>\n                Details<span className='sr-only'> of {name}</span>\n              </DisclosureTrigger>\n              <DisclosureContent>\n                {part.input !== undefined && (\n                  <ToolValue label='Input' tool={name} value={part.input} />\n                )}\n                {part.output !== undefined && (\n                  <ToolValue label='Output' tool={name} value={part.output} />\n                )}\n              </DisclosureContent>\n            </Disclosure>\n          )}\n        </div>\n      </div>\n      {result && <div className='flex min-w-0 flex-col gap-1.5'>{result}</div>}\n    </div>\n  )\n}\n\n// Only a file the browser already holds: a URL from a reply would load, unasked, from wherever the model chose.\nfunction isLocalUrl(url: string) {\n  return /^(?:data|blob):/i.test(url)\n}\n\nfunction FileIcon({ file }: { file: AIFilePart }) {\n  if (file.mediaType.startsWith('image/') && isLocalUrl(file.url)) {\n    return (\n      <AttachmentMedia variant='image'>\n        {/* oxlint-disable-next-line nextjs/no-img-element -- blocks install into any React project */}\n        <img src={file.url} alt='' />\n      </AttachmentMedia>\n    )\n  }\n  return (\n    <AttachmentMedia>\n      <IconPlaceholder\n        lucide='FileTextIcon'\n        tabler='IconFileText'\n        hugeicons='File02Icon'\n        phosphor='FileTextIcon'\n        remixicon='RiFileTextLine'\n      />\n    </AttachmentMedia>\n  )\n}\n\nfunction fileKind({ filename, mediaType }: AIFilePart) {\n  const extension = filename?.match(/\\.([a-z0-9]{1,5})$/i)?.[1]\n  if (extension) return extension.toUpperCase()\n  const [type, subtype] = mediaType.split('/')\n  if (subtype && subtype !== '*') return subtype.split(/[+.;]/)[0].toUpperCase()\n  return type.charAt(0).toUpperCase() + type.slice(1)\n}\n\n/** The files a message carries, such as what the person attached. */\nfunction MessageFiles({ className, files }: { className?: string; files: AIFilePart[] }) {\n  if (files.length === 0) return null\n  return (\n    <ul\n      data-slot='message-files'\n      aria-label={files.length === 1 ? 'Attached file' : 'Attached files'}\n      className={cn('flex max-w-full flex-wrap gap-2', className)}\n    >\n      {files.map((file, index) => (\n        <li key={`${file.url}-${index}`} className='flex max-w-full min-w-0'>\n          <Attachment size='sm'>\n            <FileIcon file={file} />\n            <AttachmentContent>\n              <AttachmentTitle>{file.filename ?? 'File'}</AttachmentTitle>\n              <AttachmentDescription>{fileKind(file)}</AttachmentDescription>\n            </AttachmentContent>\n          </Attachment>\n        </li>\n      ))}\n    </ul>\n  )\n}\n\ntype AIMessageGroup =\n  | { key: string; type: 'thinking'; streaming: boolean; text: string }\n  | { key: string; part: AIAnyToolPart; type: 'tool' }\n  | { key: string; streaming: boolean; text: string; type: 'text' }\n\n/** A reply's parts as it shows them: reasoning in a row joined into one thinking group, text with its citations, and each tool call. */\nfunction groupParts(message: AIMessage, streaming: boolean): AIMessageGroup[] {\n  const groups: AIMessageGroup[] = []\n  const parts = getReadableParts(message)\n  parts.forEach((part, index) => {\n    const previous = groups.at(-1)\n    // A stopped reply can leave a part marked streaming.\n    const partStreaming = streaming && 'state' in part && part.state === 'streaming'\n    if (part.type === 'reasoning') {\n      if (previous?.type === 'thinking' && parts[index - 1]?.type === 'reasoning') {\n        previous.text += `\\n\\n${part.text}`\n        previous.streaming ||= partStreaming\n      } else {\n        groups.push({\n          key: `thinking-${index}`,\n          streaming: partStreaming,\n          text: part.text,\n          type: 'thinking',\n        })\n      }\n    } else if (part.type === 'text') {\n      groups.push({\n        key: `text-${index}`,\n        // A stopped reply's last text is cut mid-word: still close what it opened and drop a half-written citation.\n        streaming: part.state === 'streaming',\n        text: part.text,\n        type: 'text',\n      })\n    } else if (isToolPart(part)) {\n      groups.push({ key: part.toolCallId, part, type: 'tool' })\n    } else if (part.type === 'step-start' && streaming && index === parts.length - 1) {\n      // A step that has nothing to show yet: the model is thinking, so show the line its reasoning will fill.\n      groups.push({\n        key: `thinking-${index + 1}`,\n        streaming: true,\n        text: '',\n        type: 'thinking',\n      })\n    }\n  })\n  return groups\n}\n\n/** What a tool is called: once it has run, or `{ running, done }` to say what it's doing while it runs, such as `Looking up MRR by plan`. */\ntype AIToolLabel = string | { done: string; running: string }\n\n// A model can call a tool by any name, `__proto__` and `toString` included.\nfunction resolveToolLabel(\n  labels: Record<string, AIToolLabel> | undefined,\n  part: AIAnyToolPart,\n) {\n  const name = getToolName(part)\n  const label = labels && Object.hasOwn(labels, name) ? labels[name] : undefined\n  if (typeof label === 'string') return { done: label, running: label }\n  if (label && typeof label.done === 'string' && typeof label.running === 'string') {\n    return { done: label.done, running: `${label.running}…` }\n  }\n  const fallback = getToolLabel(part)\n  return { done: fallback, running: fallback }\n}\n\nfunction plural(count: number, word: string) {\n  return `${count} ${count === 1 ? word : `${word}s`}`\n}\n\ninterface WorkSummary {\n  durationMs: number | null\n  reasoned: boolean\n  stopped: boolean\n  tools: AIAnyToolPart[]\n}\n\nfunction describeWork({ durationMs, reasoned, stopped, tools }: WorkSummary) {\n  const turnedDown = tools.filter(\n    (part) => part.state === 'output-denied' || part.approval?.approved === false,\n  ).length\n  const failed = tools.filter((part) => part.state === 'output-error').length\n  const time = durationMs === null ? null : formatDuration(durationMs)\n  const facts: string[] = []\n  if (stopped) {\n    facts.push(\n      tools.length > 0 ? `Stopped after ${plural(tools.length, 'tool')}` : 'Stopped',\n    )\n  } else if (tools.length > 0) {\n    facts.push(`Used ${plural(tools.length, 'tool')}${time ? ` in ${time}` : ''}`)\n  } else if (reasoned) {\n    facts.push(time ? `Thought for ${time}` : 'Thought it over')\n  }\n  if (failed > 0) facts.push(`${failed} failed`)\n  if (turnedDown > 0) facts.push(`${turnedDown} denied`)\n  return facts.join(', ')\n}\n\nfunction isWork(group: AIMessageGroup) {\n  return (\n    group.type === 'thinking' ||\n    (group.type === 'tool' && group.part.state !== 'approval-requested')\n  )\n}\n\ninterface AIMessagePartsProps {\n  className?: string\n  message: AIMessage\n  /** Answers a tool call that waits for approval: pass the chat's `addToolApprovalResponse`. Approve and Deny show once the reply has stopped streaming. */\n  onToolApprovalResponse?: (response: AIToolApprovalResponse) => void\n  /** Draws a tool call that waits for the person in place of its Approve and Deny row, such as an approval card with what the call will change. Return nothing to keep the row. */\n  renderApproval?: (part: AIAnyToolPart) => ReactNode\n  /** Draws a tool's result as a block, such as a chart or a headline number, at the top of the answer. Return nothing to show only the step. */\n  renderToolResult?: (part: AIAnyToolPart) => ReactNode\n  /** Draws a reply's work (its thinking, tool calls and sources) in place of the line that folds it, such as a research run. Return nothing to keep the line. */\n  renderWork?: (reply: AIMessage, streaming: boolean) => ReactNode\n  /** Lists the sources a reply cites, under its steps once it's done, unless `renderWork` draws the work. Turn it off when the block lists them itself. @default true */\n  showSources?: boolean\n  /** What `[n]` in the reply cites, when the block holds the sources rather than the reply's `source-url` parts. */\n  sources?: AISource[]\n  /** The reply is still arriving. */\n  streaming?: boolean\n  /** What each tool is called, by its name. Others read as their name in words. */\n  toolLabels?: Record<string, AIToolLabel>\n}\n\n/** Whether a reply holds anything to show: a tool call, or text that reads as more than a cut-off citation such as `[1`. */\nfunction hasAnswer(reply: Pick<AIMessage, 'parts'>) {\n  return reply.parts.some(\n    (part) =>\n      isToolPart(part) ||\n      (part.type === 'text' &&\n        (part.state === 'streaming' ? completeMarkdown(part.text) : part.text).trim() !==\n          ''),\n  )\n}\n\n/** Everything a reply holds: one line that rolls through what the model is doing and folds its thinking, tool calls and sources once it's done, then tool results drawn as blocks, approvals, the text and files. */\nfunction AIMessageParts({\n  className,\n  message,\n  onToolApprovalResponse,\n  renderApproval,\n  renderToolResult,\n  renderWork,\n  showSources = true,\n  sources: sourcesProp,\n  streaming = false,\n  toolLabels,\n}: AIMessagePartsProps) {\n  const sourcesId = useId()\n  const groups = groupParts(message, streaming)\n  const sources = sourcesProp ?? getMessageSources(message)\n  const listedSources = showSources && !streaming && sources.length > 0\n  const files = getMessageFiles(message)\n  const tools = groups.flatMap((group) => (group.type === 'tool' ? [group.part] : []))\n  const last = groups.at(-1)\n  const working = streaming && last?.type !== 'text'\n  const [startedLive] = useState(streaming)\n  const [durationMs, setDurationMs] = useState<number | null>(null)\n\n  useLayoutEffect(() => {\n    if (!working) return\n    const startedAt = performance.now()\n    return () =>\n      setDurationMs((previous) => (previous ?? 0) + performance.now() - startedAt)\n  }, [working])\n\n  const waiting = tools.find((part) => part.state === 'approval-requested')\n  const stopped =\n    !streaming &&\n    (tools.some(isToolUnfinished) ||\n      message.parts.some(\n        (part) =>\n          (part.type === 'reasoning' || part.type === 'text') &&\n          part.state === 'streaming',\n      ))\n  const work = groups.filter(isWork)\n  const drawnWork = renderWork?.(message, streaming)\n\n  let status: AgentRingStatus = 'done'\n  let line = describeWork({\n    durationMs,\n    reasoned: groups.some((group) => group.type === 'thinking'),\n    stopped,\n    tools,\n  })\n  if (waiting) {\n    status = 'waiting'\n    line = 'Waiting for you to approve'\n  } else if (working || (startedLive && !stopped && durationMs === null)) {\n    status = 'running'\n    line =\n      last?.type === 'tool' && isToolUnfinished(last.part)\n        ? resolveToolLabel(toolLabels, last.part).running\n        : 'Thinking…'\n  } else if (stopped) {\n    status = 'stopped'\n  }\n\n  return (\n    <div\n      data-slot='ai-message-parts'\n      className={cn('flex min-w-0 flex-col gap-4', className)}\n    >\n      {drawnWork ??\n        ((work.length > 0 || working || waiting) && (\n          <WorkLine line={line} status={status}>\n            {work.length > 0 && (\n              <>\n                {work.map((group) =>\n                  group.type === 'thinking' ? (\n                    <Thinking\n                      key={group.key}\n                      streaming={group.streaming}\n                      text={group.text}\n                    />\n                  ) : group.type === 'tool' ? (\n                    <ToolCall\n                      key={group.key}\n                      part={group.part}\n                      inProgress={streaming}\n                      label={resolveToolLabel(toolLabels, group.part).done}\n                    />\n                  ) : null,\n                )}\n                {listedSources && <SourceList id={sourcesId} sources={sources} />}\n              </>\n            )}\n          </WorkLine>\n        ))}\n      {groups.map((group) => {\n        if (group.type === 'text') {\n          return (\n            <AIMarkdown\n              key={group.key}\n              text={group.text}\n              sources={sources}\n              streaming={group.streaming}\n            />\n          )\n        }\n        if (group.type !== 'tool') return null\n        const { part } = group\n        if (part.state === 'approval-requested') {\n          const drawn = streaming ? null : renderApproval?.(part)\n          if (drawn) return <div key={group.key}>{drawn}</div>\n          return (\n            <ToolCall\n              key={group.key}\n              part={part}\n              inProgress={streaming}\n              label={resolveToolLabel(toolLabels, part).done}\n              onApprovalResponse={streaming ? undefined : onToolApprovalResponse}\n            />\n          )\n        }\n        const result =\n          part.state === 'output-available' && !part.preliminary\n            ? renderToolResult?.(part)\n            : null\n        if (!result) return null\n        return (\n          <div\n            key={group.key}\n            className='motion-safe:animate-in motion-safe:fade-in motion-safe:slide-in-from-bottom-2 flex min-w-0 flex-col gap-5 duration-300'\n          >\n            {result}\n          </div>\n        )\n      })}\n      <MessageFiles files={files} />\n      {!drawnWork && work.length === 0 && listedSources && (\n        <SourceList id={sourcesId} sources={sources} />\n      )}\n    </div>\n  )\n}\n\nexport {\n  AIMessageParts,\n  fileKind,\n  groupParts,\n  hasAnswer,\n  isToolUnfinished,\n  MessageFiles,\n  Thinking,\n  ThinkingIndicator,\n  ToolCall,\n  ToolValue,\n}\n\nexport type {\n  AIMessageGroup,\n  AIMessagePartsProps,\n  AIToolLabel,\n  ThinkingProps,\n  ToolCallProps,\n  ToolValueProps,\n}\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/ai-parts.tsx"
    }
  ],
  "type": "registry:component"
}
