{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ai-assistant",
  "title": "AI Assistant",
  "description": "Primitives for AI chat that take the Vercel AI SDK’s useChat as it is: a panel with New conversation and Close around a welcome, the conversation and the message box, a scrolling log that puts each new question at the top with its reply growing below, opens a saved conversation at its last question and reads each reply out once it has finished, messages that show thinking, tool calls, Markdown, files and sources, copy, regenerate and feedback actions, suggested prompts, a welcome, an error with retry, context chips, a message box that attaches files, shows each one uploading, too large or of a type it can’t send, and where Enter sends and Stop halts a reply, and a hook that runs the same chat from any function that streams.",
  "registryDependencies": [
    "https://www.dashboardblocks.com/r/radix/announcements.json",
    "attachment",
    "bubble",
    "button",
    "input-group",
    "message",
    "message-scroller",
    "https://www.dashboardblocks.com/r/radix/ai-chat.json",
    "https://www.dashboardblocks.com/r/radix/block-state.json",
    "https://www.dashboardblocks.com/r/radix/files.json",
    "https://www.dashboardblocks.com/r/radix/format.json"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/ai-assistant.tsx",
      "content": "'use client'\n\nimport { markdownToPlainText } from '@/registry/components/dashboardblocks/ai-markdown'\nimport {\n  type AIChat,\n  type AIChatStatus,\n  type AIFilePart,\n  type AIMessage,\n  type AIMessagePart,\n  type AIMessageVersions,\n  type AIReply,\n  type AIToolApprovalResponse,\n  branchMessages,\n  getMessageFiles,\n  getMessageSources,\n  getMessageText,\n  getStreamingMessageId,\n  getMessageVersion,\n  getToolLabel,\n  isToolPart,\n  selectMessageVersion,\n} from '@/registry/components/dashboardblocks/ai-message'\nimport {\n  AIMessageParts,\n  type AIMessagePartsProps,\n  fileKind,\n  MessageFiles,\n  ThinkingIndicator,\n} from '@/registry/components/dashboardblocks/ai-parts'\nimport {\n  Announcements,\n  useAnnouncements,\n} from '@/registry/components/dashboardblocks/announcements'\nimport {\n  BlockStateProvider,\n  BlockStateRows,\n  type BlockStateProps,\n  type BlockStatus,\n  useBlockState,\n} from '@/registry/components/dashboardblocks/block-state'\nimport {\n  formatFileSize,\n  validateFiles,\n} from '@/registry/components/dashboardblocks/files'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport { formatList } from '@/registry/lib/dashboardblocks/format'\nimport {\n  type FormEvent,\n  type KeyboardEvent,\n  type ReactNode,\n  type Ref,\n  type RefObject,\n  startTransition,\n  useEffect,\n  useId,\n  useImperativeHandle,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from 'react'\nimport { flushSync } from 'react-dom'\n\nimport {\n  Attachment,\n  AttachmentAction,\n  AttachmentActions,\n  AttachmentContent,\n  AttachmentDescription,\n  AttachmentMedia,\n  AttachmentTitle,\n} from '@/components/ui/attachment'\nimport { Bubble, BubbleContent } from '@/components/ui/bubble'\nimport { Button } from '@/components/ui/button'\nimport {\n  InputGroup,\n  InputGroupAddon,\n  InputGroupTextarea,\n} from '@/components/ui/input-group'\nimport {\n  Message,\n  MessageAvatar,\n  MessageContent,\n  MessageFooter,\n} from '@/components/ui/message'\nimport {\n  MessageScroller,\n  MessageScrollerButton,\n  MessageScrollerContent,\n  MessageScrollerItem,\n  MessageScrollerProvider,\n  MessageScrollerViewport,\n  useMessageScroller,\n} from '@/components/ui/message-scroller'\n\nimport { cn } from '@/lib/utils'\n\ntype ChatFeedback = 'up' | 'down'\n\nfunction isBusy(status: AIChatStatus) {\n  return status === 'submitted' || status === 'streaming'\n}\n\n/** What a screen reader hears once a reply ends: its text, and what waits for the person. */\nfunction describeReply(message: AIMessage) {\n  const waiting = message.parts.flatMap((part) =>\n    isToolPart(part) && part.state === 'approval-requested' ? [getToolLabel(part)] : [],\n  )\n  return [\n    markdownToPlainText(getMessageText(message), getMessageSources(message).length),\n    waiting.length > 0 && `Waiting for your approval: ${formatList(waiting)}.`,\n  ]\n    .filter(Boolean)\n    .join(' ')\n}\n\nfunction useCopyToClipboard(timeout = 2000) {\n  const [copied, setCopied] = useState(false)\n  const timer = useRef<ReturnType<typeof setTimeout>>(undefined)\n\n  useEffect(() => () => clearTimeout(timer.current), [])\n\n  const copy = async (text: string) => {\n    try {\n      await navigator.clipboard.writeText(text)\n    } catch {\n      return false\n    }\n    setCopied(true)\n    clearTimeout(timer.current)\n    timer.current = setTimeout(() => setCopied(false), timeout)\n    return true\n  }\n\n  return { copied, copy }\n}\n\nfunction CopyButton({\n  className,\n  label = 'Copy',\n  value,\n}: {\n  className?: string\n  label?: string\n  value: string\n}) {\n  const { copied, copy } = useCopyToClipboard()\n  return (\n    <Button\n      variant='ghost'\n      size='icon-sm'\n      className={className}\n      aria-label={label}\n      onClick={() => void copy(value)}\n    >\n      {copied ? (\n        <IconPlaceholder\n          lucide='CheckIcon'\n          tabler='IconCheck'\n          hugeicons='Tick02Icon'\n          phosphor='CheckIcon'\n          remixicon='RiCheckLine'\n          aria-hidden\n        />\n      ) : (\n        <IconPlaceholder\n          lucide='CopyIcon'\n          tabler='IconCopy'\n          hugeicons='Copy01Icon'\n          phosphor='CopyIcon'\n          remixicon='RiFileCopyLine'\n          aria-hidden\n        />\n      )}\n      <span role='status' className='sr-only'>\n        {copied ? 'Copied' : ''}\n      </span>\n    </Button>\n  )\n}\n\nfunction AssistantAvatar({ className, icon }: { className?: string; icon?: ReactNode }) {\n  return (\n    <span\n      aria-hidden\n      className={cn(\n        'bg-primary text-primary-foreground flex size-7 shrink-0 items-center justify-center rounded-full [&_svg]:size-3.5',\n        className,\n      )}\n    >\n      {icon ?? (\n        <IconPlaceholder\n          lucide='SparklesIcon'\n          tabler='IconSparkles'\n          hugeicons='SparklesIcon'\n          phosphor='SparkleIcon'\n          remixicon='RiSparklingLine'\n        />\n      )}\n    </span>\n  )\n}\n\nfunction ChatHeader({\n  actions,\n  className,\n  description,\n  icon,\n  title = 'Assistant',\n}: {\n  actions?: ReactNode\n  className?: string\n  description?: ReactNode\n  icon?: ReactNode\n  /** @default 'Assistant' */\n  title?: string\n}) {\n  return (\n    <div className={cn('flex min-h-14 items-center gap-3 px-4 py-2', className)}>\n      <AssistantAvatar icon={icon} />\n      <div className='flex min-w-0 flex-1 flex-col'>\n        <h2 className='truncate text-sm font-semibold tracking-tight'>{title}</h2>\n        {description && (\n          <p className='text-muted-foreground truncate text-xs'>{description}</p>\n        )}\n      </div>\n      {actions && <div className='flex shrink-0 items-center gap-1'>{actions}</div>}\n    </div>\n  )\n}\n\nconst QUESTION_PEEK_PX = 64\nconst SCROLL_KEYS = new Set([\n  'ArrowDown',\n  'ArrowUp',\n  'End',\n  'Home',\n  'PageDown',\n  'PageUp',\n  ' ',\n])\n\n// Message Scroller places a saved conversation by its height, which `content-visibility: auto` estimates while the log is off screen.\nconst MEASURED_ITEM = '[content-visibility:visible]'\n\ninterface ChatMessagesProps {\n  children: ReactNode\n  className?: string\n  contentClassName?: string\n  /** @default 'Conversation' */\n  label?: string\n  /** The newest message, read out once it has finished instead of word by word. */\n  latest?: AIMessage\n  /** Moves each new question to the top when the status turns `submitted`, and announces that the assistant is thinking, then the finished reply. Without it, the log follows the end for new questions. */\n  status?: AIChatStatus\n}\n\nfunction lastMessageId(content: HTMLElement | null) {\n  return [...(content?.querySelectorAll<HTMLElement>('[data-message-id]') ?? [])].at(-1)\n    ?.dataset.messageId\n}\n\nfunction latestQuestion(content: HTMLElement | null) {\n  return [...(content?.querySelectorAll<HTMLElement>('[data-chat-question]') ?? [])].at(\n    -1,\n  )\n}\n\nfunction ChatMessages(props: ChatMessagesProps) {\n  const [selecting, setSelecting] = useState(false)\n  return (\n    <MessageScrollerProvider autoScroll={!selecting}>\n      <ChatLog {...props} onSelectingChange={setSelecting} />\n    </MessageScrollerProvider>\n  )\n}\n\nfunction ChatLog({\n  children,\n  className,\n  contentClassName,\n  label = 'Conversation',\n  latest,\n  onSelectingChange,\n  status = 'ready',\n}: ChatMessagesProps & { onSelectingChange: (selecting: boolean) => void }) {\n  const scroller = useMessageScroller()\n  const scrollerRef = useRef(scroller)\n  const viewportRef = useRef<HTMLDivElement>(null)\n  const contentRef = useRef<HTMLDivElement>(null)\n  const heldQuestion = useRef<string | null>(null)\n  const placedTop = useRef<number | null>(null)\n  const placedMargin = useRef(QUESTION_PEEK_PX)\n  const opened = useRef(false)\n  const placedForStatus = useRef(status)\n  const idleLastId = useRef<string | undefined>(undefined)\n  const placeFrame = useRef(0)\n  const [announcement, setAnnouncement] = useState('')\n  const [previousStatus, setPreviousStatus] = useState(status)\n\n  if (status !== previousStatus) {\n    setPreviousStatus(status)\n    if (status === 'submitted') {\n      setAnnouncement('Assistant is thinking')\n    } else if (status === 'ready' && isBusy(previousStatus)) {\n      setAnnouncement(latest?.role === 'assistant' ? describeReply(latest) : '')\n    }\n  }\n\n  // A status region that mounts with its text isn't read: announce a question already on its way once the region is in the page.\n  const mountedStatus = useRef(status)\n  useEffect(() => {\n    if (mountedStatus.current !== 'submitted') return\n    const frame = requestAnimationFrame(() => setAnnouncement('Assistant is thinking'))\n    return () => cancelAnimationFrame(frame)\n  }, [])\n\n  useLayoutEffect(() => {\n    scrollerRef.current = scroller\n  })\n\n  function placeQuestion(id: string, margin = placedMargin.current) {\n    heldQuestion.current = id\n    placedMargin.current = margin\n    scrollerRef.current.scrollToMessage(id, { scrollMargin: margin })\n    placedTop.current = viewportRef.current?.scrollTop ?? null\n  }\n\n  useLayoutEffect(() => {\n    const viewport = viewportRef.current\n    const content = contentRef.current\n    return () => {\n      if (!viewport || !content || viewport.clientHeight === 0) return\n      if (viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight < 2) return\n      const item = content.querySelector<HTMLElement>('[data-message-id]')\n      const id = item?.dataset.messageId\n      if (!item || !id) return\n      const offset =\n        item.getBoundingClientRect().top -\n        viewport.getBoundingClientRect().top -\n        parseFloat(getComputedStyle(content).paddingTop)\n      // Message Scroller goes back to following the end while hidden unless it's mid-jump, so make the current position one.\n      scrollerRef.current.scrollToMessage(id, { scrollMargin: offset })\n    }\n  }, [])\n\n  useLayoutEffect(() => {\n    if (opened.current) return\n    opened.current = true\n    const content = contentRef.current\n    const question = latestQuestion(content)\n    const id = question?.dataset.messageId\n    if (!content || !question || !id || !viewportRef.current) return\n    const rest =\n      content.getBoundingClientRect().bottom -\n      question.getBoundingClientRect().top +\n      QUESTION_PEEK_PX\n    if (rest <= viewportRef.current.clientHeight) return\n    placeQuestion(id, 0)\n  }, [])\n\n  useLayoutEffect(() => {\n    if (!isBusy(status)) idleLastId.current = lastMessageId(contentRef.current)\n  })\n\n  useEffect(() => () => cancelAnimationFrame(placeFrame.current), [])\n\n  useEffect(() => {\n    const before = placedForStatus.current\n    placedForStatus.current = status\n    if (!isBusy(status) || isBusy(before)) return\n    const id = latestQuestion(contentRef.current)?.dataset.messageId\n    const last = lastMessageId(contentRef.current)\n    // A reply that goes on after an approval stays where the reader is.\n    if (!id || (last !== id && last === idleLastId.current)) return\n    heldQuestion.current = id\n    placedMargin.current = QUESTION_PEEK_PX\n    cancelAnimationFrame(placeFrame.current)\n    placeFrame.current = requestAnimationFrame(() => placeQuestion(id))\n  }, [status])\n\n  useEffect(() => {\n    const content = contentRef.current\n    if (!content) return\n    const observer = new ResizeObserver(() => {\n      const id = heldQuestion.current\n      if (!id) return\n      if (latestQuestion(content)?.dataset.messageId !== id) {\n        heldQuestion.current = null\n        return\n      }\n      placeQuestion(id)\n    })\n    observer.observe(content)\n    return () => observer.disconnect()\n  }, [])\n\n  useEffect(() => {\n    function onSelectionChange() {\n      const selection = document.getSelection()\n      const inLog = Boolean(\n        selection &&\n        !selection.isCollapsed &&\n        viewportRef.current?.contains(selection.anchorNode),\n      )\n      if (inLog) heldQuestion.current = null\n      onSelectingChange(inLog)\n    }\n    document.addEventListener('selectionchange', onSelectionChange)\n    return () => document.removeEventListener('selectionchange', onSelectionChange)\n  }, [onSelectingChange])\n\n  function release() {\n    heldQuestion.current = null\n    placedTop.current = null\n  }\n\n  return (\n    <MessageScroller className={cn('flex-1', className)}>\n      <MessageScrollerViewport\n        ref={viewportRef}\n        role='log'\n        aria-label={label}\n        aria-live='off'\n        onScroll={(event) => {\n          const viewport = event.currentTarget\n          const top = placedTop.current\n          const held = heldQuestion.current\n          if (viewport.clientHeight === 0 || top === null || held === null) return\n          if (Math.abs(viewport.scrollTop - top) <= 1) return\n          const clamped =\n            viewport.scrollTop < top &&\n            viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight <= 1\n          if (clamped) placeQuestion(held)\n          else release()\n        }}\n        onWheel={release}\n        onTouchMove={release}\n        onPointerDown={release}\n        onKeyDown={(event) => {\n          if (SCROLL_KEYS.has(event.key)) release()\n        }}\n        className='mask-none focus-visible:ring-ring/50 outline-none [scrollbar-width:thin] focus-visible:ring-3 focus-visible:ring-inset'\n      >\n        <MessageScrollerContent\n          ref={contentRef}\n          role='none'\n          className={cn('p-4', contentClassName)}\n        >\n          {children}\n        </MessageScrollerContent>\n      </MessageScrollerViewport>\n      <MessageScrollerButton\n        behavior='auto'\n        onClick={() => {\n          release()\n          viewportRef.current?.focus({ preventScroll: true })\n        }}\n      >\n        <IconPlaceholder\n          lucide='ArrowDownIcon'\n          tabler='IconArrowDown'\n          hugeicons='ArrowDown01Icon'\n          phosphor='ArrowDownIcon'\n          remixicon='RiArrowDownLine'\n        />\n        <span className='sr-only'>Scroll to latest message</span>\n      </MessageScrollerButton>\n      <div role='status' className='sr-only'>\n        {announcement}\n      </div>\n    </MessageScroller>\n  )\n}\n\ninterface ChatMessageProps extends Pick<\n  AIMessagePartsProps,\n  | 'onToolApprovalResponse'\n  | 'renderApproval'\n  | 'renderToolResult'\n  | 'renderWork'\n  | 'toolLabels'\n> {\n  actions?: ReactNode\n  avatar?: ReactNode\n  /** What the message shows in place of its text, or of a reply's parts in order, such as a question being edited. */\n  children?: ReactNode\n  className?: string\n  footer?: ReactNode\n  message: AIMessage\n  name?: string\n  streaming?: boolean\n}\n\nfunction ChatMessage({\n  actions,\n  avatar,\n  children,\n  className,\n  footer,\n  message,\n  name,\n  onToolApprovalResponse,\n  renderApproval,\n  renderToolResult,\n  renderWork,\n  streaming,\n  toolLabels,\n}: ChatMessageProps) {\n  if (message.role === 'user') {\n    const text = getMessageText(message)\n    return (\n      <MessageScrollerItem\n        messageId={message.id}\n        data-chat-question\n        className={MEASURED_ITEM}\n      >\n        <Message data-role='user' align='end' className={className}>\n          <MessageContent>\n            <span className='sr-only'>{name ?? 'You'}: </span>\n            <MessageFiles files={getMessageFiles(message)} className='justify-end' />\n            {children ??\n              (text && (\n                <Bubble variant='muted' align='end'>\n                  <BubbleContent>\n                    <p className='break-words whitespace-pre-wrap'>{text}</p>\n                  </BubbleContent>\n                </Bubble>\n              ))}\n            {actions}\n          </MessageContent>\n        </Message>\n      </MessageScrollerItem>\n    )\n  }\n  return (\n    <MessageScrollerItem messageId={message.id} className={MEASURED_ITEM}>\n      <Message data-role='assistant' className={className}>\n        <AssistantMessageAvatar avatar={avatar} />\n        <MessageContent aria-busy={streaming}>\n          <Bubble variant='ghost' className='w-full'>\n            <BubbleContent className='w-full'>\n              <span className='sr-only'>{name ?? 'Assistant'}: </span>\n              {children ?? (\n                <AIMessageParts\n                  message={message}\n                  streaming={streaming}\n                  toolLabels={toolLabels}\n                  onToolApprovalResponse={onToolApprovalResponse}\n                  renderApproval={renderApproval}\n                  renderToolResult={renderToolResult}\n                  renderWork={renderWork}\n                />\n              )}\n            </BubbleContent>\n          </Bubble>\n          {footer}\n          {actions && <MessageFooter>{actions}</MessageFooter>}\n        </MessageContent>\n      </Message>\n    </MessageScrollerItem>\n  )\n}\n\nfunction AssistantMessageAvatar({ avatar }: { avatar?: ReactNode }) {\n  return (\n    <MessageAvatar className='self-start group-has-data-[slot=message-footer]/message:translate-y-0'>\n      {avatar ?? <AssistantAvatar className='size-8' />}\n    </MessageAvatar>\n  )\n}\n\ninterface MessageVersion {\n  count: number\n  /** The version showing, from 0. */\n  index: number\n}\n\ninterface ChatMessageActionsProps {\n  className?: string\n  content: string\n  /** Turns the buttons that change the chat off while a reply arrives. */\n  disabled?: boolean\n  feedback?: ChatFeedback | null\n  /** Shows thumbs up and down. */\n  onFeedback?: (feedback: ChatFeedback | null) => void\n  /** Shows a regenerate button, usually on the last reply only. */\n  onRegenerate?: () => void\n  /** Steps to another version of the reply. */\n  onVersionChange?: (index: number) => void\n  /** Shows which version of the reply this is, with buttons to the others. */\n  version?: MessageVersion\n}\n\n/** Which version of a message shows, such as 2 / 3, with buttons to the one before and after. */\nfunction MessageVersions({\n  disabled,\n  onChange,\n  version,\n}: {\n  disabled?: boolean\n  onChange: (index: number) => void\n  version: MessageVersion\n}) {\n  const { count, index } = version\n  return (\n    <div role='group' aria-label='Versions' className='flex items-center'>\n      <Button\n        variant='ghost'\n        size='icon-sm'\n        aria-label='Previous version'\n        disabled={disabled || index === 0}\n        onClick={() => onChange(index - 1)}\n      >\n        <IconPlaceholder\n          lucide='ChevronLeftIcon'\n          tabler='IconChevronLeft'\n          hugeicons='ArrowLeft01Icon'\n          phosphor='CaretLeftIcon'\n          remixicon='RiArrowLeftSLine'\n        />\n      </Button>\n      <span className='min-w-9 text-center text-xs tabular-nums'>\n        <span aria-hidden>\n          {index + 1} / {count}\n        </span>\n        <span className='sr-only'>\n          Version {index + 1} of {count}\n        </span>\n      </span>\n      <Button\n        variant='ghost'\n        size='icon-sm'\n        aria-label='Next version'\n        disabled={disabled || index === count - 1}\n        onClick={() => onChange(index + 1)}\n      >\n        <IconPlaceholder\n          lucide='ChevronRightIcon'\n          tabler='IconChevronRight'\n          hugeicons='ArrowRight01Icon'\n          phosphor='CaretRightIcon'\n          remixicon='RiArrowRightSLine'\n        />\n      </Button>\n    </div>\n  )\n}\n\nfunction ChatMessageActions({\n  className,\n  content,\n  disabled,\n  feedback,\n  onFeedback,\n  onRegenerate,\n  onVersionChange,\n  version,\n}: ChatMessageActionsProps) {\n  return (\n    <div\n      role='group'\n      aria-label='Message actions'\n      className={cn('text-muted-foreground -ms-1.5 flex items-center gap-0.5', className)}\n    >\n      {version && onVersionChange && (\n        <MessageVersions\n          disabled={disabled}\n          version={version}\n          onChange={onVersionChange}\n        />\n      )}\n      {content && <CopyButton label='Copy message' value={content} />}\n      {onRegenerate && (\n        <Button\n          variant='ghost'\n          size='icon-sm'\n          aria-label='Regenerate response'\n          disabled={disabled}\n          onClick={() => onRegenerate()}\n        >\n          <IconPlaceholder\n            lucide='RefreshCwIcon'\n            tabler='IconRefresh'\n            hugeicons='RefreshIcon'\n            phosphor='ArrowClockwiseIcon'\n            remixicon='RiRefreshLine'\n          />\n        </Button>\n      )}\n      {onFeedback && (\n        <>\n          <Button\n            variant='ghost'\n            size='icon-sm'\n            aria-label='Good response'\n            aria-pressed={feedback === 'up'}\n            onClick={() => onFeedback(feedback === 'up' ? null : 'up')}\n            className='aria-pressed:text-foreground'\n          >\n            <IconPlaceholder\n              lucide='ThumbsUpIcon'\n              tabler='IconThumbUp'\n              hugeicons='ThumbsUpIcon'\n              phosphor='ThumbsUpIcon'\n              remixicon='RiThumbUpLine'\n              className={cn(feedback === 'up' && 'fill-current')}\n            />\n          </Button>\n          <Button\n            variant='ghost'\n            size='icon-sm'\n            aria-label='Bad response'\n            aria-pressed={feedback === 'down'}\n            onClick={() => onFeedback(feedback === 'down' ? null : 'down')}\n            className='aria-pressed:text-foreground'\n          >\n            <IconPlaceholder\n              lucide='ThumbsDownIcon'\n              tabler='IconThumbDown'\n              hugeicons='ThumbsDownIcon'\n              phosphor='ThumbsDownIcon'\n              remixicon='RiThumbDownLine'\n              className={cn(feedback === 'down' && 'fill-current')}\n            />\n          </Button>\n        </>\n      )}\n    </div>\n  )\n}\n\nfunction TypingIndicator({\n  className,\n  label,\n}: {\n  className?: string\n  /** @default 'Thinking…' */\n  label?: string\n}) {\n  return (\n    <Message data-role='assistant' className={className}>\n      <AssistantMessageAvatar />\n      <MessageContent>\n        <Bubble variant='ghost' className='w-full'>\n          <BubbleContent className='w-full'>\n            <ThinkingIndicator label={label} />\n          </BubbleContent>\n        </Bubble>\n      </MessageContent>\n    </Message>\n  )\n}\n\ninterface SuggestedPrompt {\n  icon?: ReactNode\n  label: string\n  /** Sent instead of the label, when the question is longer than its label. */\n  prompt?: string\n}\n\ninterface SuggestedPromptsProps {\n  className?: string\n  label?: string\n  onSelect: (prompt: string) => void\n  prompts: SuggestedPrompt[]\n  variant?: 'chips' | 'list'\n}\n\nfunction SuggestedPrompts({\n  className,\n  label = 'Suggested prompts',\n  onSelect,\n  prompts,\n  variant = 'chips',\n}: SuggestedPromptsProps) {\n  return (\n    <ul\n      aria-label={label}\n      className={cn(\n        variant === 'chips'\n          ? 'motion-safe:animate-in motion-safe:fade-in motion-safe:slide-in-from-bottom-2 flex flex-wrap gap-2 duration-300'\n          : 'flex flex-col divide-y border-y',\n        className,\n      )}\n    >\n      {prompts.map((prompt) =>\n        variant === 'chips' ? (\n          <li key={prompt.label} className='flex'>\n            <Button\n              type='button'\n              variant='outline'\n              size='sm'\n              onClick={() => onSelect(prompt.prompt ?? prompt.label)}\n            >\n              {prompt.icon}\n              {prompt.label}\n            </Button>\n          </li>\n        ) : (\n          <li key={prompt.label} className='flex max-w-full'>\n            <button\n              type='button'\n              onClick={() => onSelect(prompt.prompt ?? prompt.label)}\n              className='hover:bg-muted/50 focus-visible:ring-ring/50 -mx-2 flex w-[calc(100%+1rem)] items-center gap-3 rounded-md px-2 py-2.5 text-start text-sm transition-colors outline-none focus-visible:ring-3 motion-reduce:transition-none [&_svg]:size-4 [&_svg]:shrink-0'\n            >\n              {prompt.icon && (\n                <span className='text-muted-foreground flex'>{prompt.icon}</span>\n              )}\n              {prompt.label}\n            </button>\n          </li>\n        ),\n      )}\n    </ul>\n  )\n}\n\nfunction ChatWelcome({\n  children,\n  className,\n  description,\n  title,\n}: {\n  children?: ReactNode\n  className?: string\n  description?: ReactNode\n  title: string\n}) {\n  return (\n    <div className={cn('flex flex-col items-center gap-4 text-center', className)}>\n      <AssistantAvatar className='size-10 [&_svg]:size-5' />\n      <div className='flex flex-col gap-1'>\n        <p className='font-semibold tracking-tight'>{title}</p>\n        {description && (\n          <p className='text-muted-foreground text-sm text-balance'>{description}</p>\n        )}\n      </div>\n      {children && <div className='w-full text-start'>{children}</div>}\n    </div>\n  )\n}\n\nfunction ChatError({\n  className,\n  message = 'Something went wrong. Try again.',\n  onRetry,\n}: {\n  className?: string\n  /** @default 'Something went wrong. Try again.' */\n  message?: string\n  onRetry?: () => void\n}) {\n  return (\n    <div className={cn('flex flex-col items-start gap-2', className)}>\n      <Bubble variant='destructive' role='alert'>\n        <BubbleContent className='flex items-start gap-2'>\n          <IconPlaceholder\n            lucide='TriangleAlertIcon'\n            tabler='IconAlertTriangle'\n            hugeicons='Alert02Icon'\n            phosphor='WarningIcon'\n            remixicon='RiErrorWarningLine'\n            className='mt-1 size-4 shrink-0'\n          />\n          <p className='min-w-0'>{message}</p>\n        </BubbleContent>\n      </Bubble>\n      {onRetry && (\n        <Button variant='outline' size='sm' onClick={onRetry}>\n          <IconPlaceholder\n            lucide='RefreshCwIcon'\n            tabler='IconRefresh'\n            hugeicons='RefreshIcon'\n            phosphor='ArrowClockwiseIcon'\n            remixicon='RiRefreshLine'\n            data-icon='inline-start'\n          />\n          Retry\n        </Button>\n      )}\n    </div>\n  )\n}\n\nfunction ChatContextChip({\n  className,\n  icon,\n  label,\n  onRemove,\n}: {\n  className?: string\n  icon?: ReactNode\n  label: string\n  /** Shows a remove button. */\n  onRemove?: () => void\n}) {\n  return (\n    <Attachment size='xs' className={className}>\n      {icon && <AttachmentMedia>{icon}</AttachmentMedia>}\n      <AttachmentContent>\n        <AttachmentTitle>{label}</AttachmentTitle>\n      </AttachmentContent>\n      {onRemove && (\n        <AttachmentActions>\n          <AttachmentAction\n            type='button'\n            aria-label={`Remove ${label}`}\n            onClick={onRemove}\n          >\n            <IconPlaceholder\n              lucide='XIcon'\n              tabler='IconX'\n              hugeicons='Cancel01Icon'\n              phosphor='XIcon'\n              remixicon='RiCloseLine'\n            />\n          </AttachmentAction>\n        </AttachmentActions>\n      )}\n    </Attachment>\n  )\n}\n\ntype ComposerFile = { id: string; name: string; preview?: string } & (\n  | { controller: AbortController; state: 'uploading' }\n  | { part: AIFilePart; state: 'done' }\n  | { message: string; state: 'error' }\n)\n\ntype ComposerUpload = (\n  file: File,\n  options: { signal: AbortSignal },\n) => Promise<AIFilePart | { message: string; status: 'error' }>\n\nconst TEXT_TYPES: Record<string, string> = {\n  csv: 'text/csv',\n  json: 'application/json',\n  log: 'text/plain',\n  md: 'text/markdown',\n  txt: 'text/plain',\n}\n\n/** A file's media type, from its name when the browser gives none, as for a .log or .md file: model providers refuse application/octet-stream. */\nfunction getMediaType(file: File) {\n  if (file.type) return file.type\n  const extension = file.name.match(/\\.([a-z0-9]+)$/i)?.[1]?.toLowerCase() ?? ''\n  return Object.hasOwn(TEXT_TYPES, extension)\n    ? TEXT_TYPES[extension]\n    : 'application/octet-stream'\n}\n\nfunction readFile(file: File) {\n  return new Promise<AIFilePart>((resolve, reject) => {\n    const reader = new FileReader()\n    reader.onload = () => {\n      if (typeof reader.result !== 'string') return reject(reader.error)\n      const mediaType = getMediaType(file)\n      resolve({\n        filename: file.name,\n        mediaType,\n        type: 'file',\n        url: reader.result.replace(/^data:[^;,]*/, `data:${mediaType}`),\n      })\n    }\n    reader.onerror = () => reject(reader.error)\n    reader.readAsDataURL(file)\n  })\n}\n\nfunction ComposerAttachment({\n  file,\n  onRemove,\n}: {\n  file: ComposerFile\n  onRemove: () => void\n}) {\n  const description =\n    file.state === 'uploading'\n      ? 'Uploading…'\n      : file.state === 'error'\n        ? file.message\n        : fileKind(file.part)\n  return (\n    <Attachment size='xs' state={file.state}>\n      <AttachmentMedia variant={file.preview ? 'image' : 'icon'}>\n        {file.state === 'uploading' ? (\n          <IconPlaceholder\n            lucide='Loader2Icon'\n            tabler='IconLoader'\n            hugeicons='Loading03Icon'\n            phosphor='SpinnerIcon'\n            remixicon='RiLoaderLine'\n            className='animate-spin motion-reduce:animate-none'\n          />\n        ) : file.state === 'error' ? (\n          <IconPlaceholder\n            lucide='TriangleAlertIcon'\n            tabler='IconAlertTriangle'\n            hugeicons='Alert02Icon'\n            phosphor='WarningIcon'\n            remixicon='RiErrorWarningLine'\n          />\n        ) : file.preview ? (\n          // oxlint-disable-next-line nextjs/no-img-element -- blocks install into any React project\n          <img src={file.preview} alt='' />\n        ) : (\n          <IconPlaceholder\n            lucide='FileTextIcon'\n            tabler='IconFileText'\n            hugeicons='File02Icon'\n            phosphor='FileTextIcon'\n            remixicon='RiFileTextLine'\n          />\n        )}\n      </AttachmentMedia>\n      <AttachmentContent className='max-w-48 min-w-0'>\n        <AttachmentTitle className='block truncate'>{file.name}</AttachmentTitle>\n        <AttachmentDescription\n          className='block truncate'\n          title={file.state === 'error' ? file.message : undefined}\n        >\n          {description}\n        </AttachmentDescription>\n      </AttachmentContent>\n      <AttachmentActions>\n        <AttachmentAction\n          type='button'\n          aria-label={`Remove ${file.name}`}\n          onClick={onRemove}\n        >\n          <IconPlaceholder\n            lucide='XIcon'\n            tabler='IconX'\n            hugeicons='Cancel01Icon'\n            phosphor='XIcon'\n            remixicon='RiCloseLine'\n          />\n        </AttachmentAction>\n      </AttachmentActions>\n    </Attachment>\n  )\n}\n\ninterface ChatComposerProps {\n  /** Lets the person attach files of these types, by button, paste or drop, as the file input's `accept` reads it (`image/*,.pdf`). A file of another type shows as one that can't be sent. Leave out for text only. */\n  accept?: string\n  className?: string\n  context?: ReactNode\n  disabled?: boolean\n  label?: string\n  /** The largest file to attach, in bytes. A larger one shows as one that can't be sent. */\n  maxSize?: number\n  onStop?: () => void\n  /** Takes the chat's `sendMessage` as it is. Return `false` to keep the message and its files in the box, as when the page holds it. */\n  onSubmit: (message: { files?: AIFilePart[]; text: string }) => unknown\n  onValueChange?: (value: string) => void\n  /** @default 'Ask anything' */\n  placeholder?: string\n  /** Sending waits until the status is `ready` or `error`. */\n  status?: AIChatStatus\n  textareaRef?: Ref<HTMLTextAreaElement>\n  /** Controls beside Attach files. The message box is a size container, so they can drop their labels when it's narrow (`@md:inline`). */\n  tools?: ReactNode\n  /**\n   * Uploads each file as it's attached, and Send waits until every one is done. Resolve the file part\n   * to send, with the `url` your storage keeps it at, or `{ status: 'error', message }` to refuse it;\n   * a throw shows \"Check your connection and try again.\" Removing the file aborts `signal`.\n   * Without it, files are read in the browser and sent as data URLs.\n   */\n  upload?: ComposerUpload\n  value?: string\n}\n\nfunction ChatComposer({\n  accept,\n  className,\n  context,\n  disabled,\n  label = 'Message',\n  maxSize,\n  onStop,\n  onSubmit,\n  onValueChange,\n  placeholder = 'Ask anything',\n  status = 'ready',\n  textareaRef,\n  tools,\n  upload = readFile,\n  value,\n}: ChatComposerProps) {\n  const hintId = useId()\n  const inner = useRef<HTMLTextAreaElement>(null)\n  const fileInput = useRef<HTMLInputElement>(null)\n  const nextFileId = useRef(0)\n  const [draft, setDraft] = useState('')\n  const [files, setFiles] = useState<ComposerFile[]>([])\n  const [notices, announce] = useAnnouncements()\n  const [dragging, setDragging] = useState(false)\n  const text = value ?? draft\n  const busy = isBusy(status)\n  const canSend = !disabled && !busy\n\n  useImperativeHandle(textareaRef, () => inner.current as HTMLTextAreaElement, [])\n\n  function change(next: string) {\n    setDraft(next)\n    onValueChange?.(next)\n  }\n\n  const previews = useRef(new Set<string>())\n\n  useEffect(() => {\n    const shown = previews.current\n    return () => {\n      for (const url of shown) URL.revokeObjectURL(url)\n      shown.clear()\n    }\n  }, [])\n\n  function preview(file: File) {\n    if (!file.type.startsWith('image/')) return undefined\n    const url = URL.createObjectURL(file)\n    previews.current.add(url)\n    return url\n  }\n\n  function forget(items: ComposerFile[]) {\n    for (const item of items) {\n      if (item.state === 'uploading') item.controller.abort()\n      if (!item.preview) continue\n      URL.revokeObjectURL(item.preview)\n      previews.current.delete(item.preview)\n    }\n  }\n\n  function finish(\n    id: string,\n    name: string,\n    result: AIFilePart | { message: string; status: 'error' },\n  ) {\n    startTransition(() => {\n      if ('status' in result) announce(`${name}: ${result.message}`)\n      setFiles((current) =>\n        current.map((item) =>\n          item.id !== id || item.state !== 'uploading'\n            ? item\n            : 'status' in result\n              ? { id, message: result.message, name: item.name, state: 'error' }\n              : {\n                  id,\n                  name: item.name,\n                  part: result,\n                  preview: item.preview,\n                  state: 'done',\n                },\n        ),\n      )\n    })\n  }\n\n  async function start(id: string, file: File, signal: AbortSignal) {\n    const result = await upload(file, { signal }).catch(() => ({\n      message: 'Check your connection and try again.',\n      status: 'error' as const,\n    }))\n    if (!signal.aborted) finish(id, file.name, result)\n  }\n\n  function attach(list: FileList | File[]) {\n    if (!accept || disabled) return\n    const added = [...list].map((file): ComposerFile => {\n      const id = `${++nextFileId.current}`\n      const [rejected] = validateFiles([file], { accept, maxSize }).rejected\n      if (rejected) {\n        const message =\n          rejected.reason === 'size' && maxSize !== undefined\n            ? `Over ${formatFileSize(maxSize)}. Try a smaller file.`\n            : 'Can’t read this kind of file.'\n        announce(`${file.name}: ${message}`)\n        return { id, message, name: file.name, state: 'error' }\n      }\n      const controller = new AbortController()\n      void start(id, file, controller.signal)\n      return {\n        controller,\n        id,\n        name: file.name,\n        preview: preview(file),\n        state: 'uploading',\n      }\n    })\n    setFiles((current) => [...current, ...added])\n  }\n\n  function remove(id: string) {\n    forget(files.filter((item) => item.id === id))\n    setFiles((current) => current.filter((item) => item.id !== id))\n    inner.current?.focus()\n  }\n\n  const ready = files.flatMap((item) => (item.state === 'done' ? [item.part] : []))\n  const uploading = files.some((item) => item.state === 'uploading')\n\n  function send() {\n    if (!canSend || uploading) return\n    if (!text.trim() && ready.length === 0) return inner.current?.focus()\n    const sent = onSubmit(\n      ready.length > 0 ? { files: ready, text: text.trim() } : { text: text.trim() },\n    )\n    if (sent === false) return inner.current?.focus()\n    change('')\n    forget(files)\n    setFiles([])\n    inner.current?.focus()\n  }\n\n  function onKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {\n    if (event.key !== 'Enter' || event.shiftKey || event.nativeEvent.isComposing) return\n    event.preventDefault()\n    send()\n  }\n\n  const attachments = files.map((file) => (\n    <ComposerAttachment key={file.id} file={file} onRemove={() => remove(file.id)} />\n  ))\n\n  return (\n    <form\n      method='post'\n      className={cn('@container', className)}\n      onSubmit={(event: FormEvent<HTMLFormElement>) => {\n        event.preventDefault()\n        send()\n      }}\n    >\n      <InputGroup\n        onDragOver={(event) => {\n          if (!accept || !event.dataTransfer.types.includes('Files')) return\n          event.preventDefault()\n          setDragging(true)\n        }}\n        onDragLeave={(event) => {\n          if (!event.currentTarget.contains(event.relatedTarget as Node | null))\n            setDragging(false)\n        }}\n        onDrop={(event) => {\n          if (!accept) return\n          event.preventDefault()\n          setDragging(false)\n          attach(event.dataTransfer.files)\n        }}\n      >\n        <Announcements said={notices} />\n        {dragging && (\n          <div\n            aria-hidden\n            className='border-ring bg-background/90 text-muted-foreground pointer-events-none absolute inset-0 z-10 flex items-center justify-center rounded-[inherit] border-2 border-dashed text-sm'\n          >\n            Drop to attach\n          </div>\n        )}\n        {(context || attachments.length > 0) && (\n          <InputGroupAddon align='block-start' className='flex-wrap gap-1.5'>\n            {context}\n            {attachments}\n          </InputGroupAddon>\n        )}\n        <InputGroupTextarea\n          ref={inner}\n          aria-label={label}\n          aria-describedby={hintId}\n          disabled={disabled}\n          placeholder={placeholder}\n          rows={1}\n          value={text}\n          onChange={(event) => change(event.target.value)}\n          onKeyDown={onKeyDown}\n          onPaste={(event) => {\n            if (!accept || event.clipboardData.files.length === 0) return\n            event.preventDefault()\n            attach(event.clipboardData.files)\n          }}\n          className='max-h-48'\n        />\n        <InputGroupAddon align='block-end'>\n          {accept && (\n            <>\n              <input\n                ref={fileInput}\n                type='file'\n                accept={accept}\n                multiple\n                hidden\n                tabIndex={-1}\n                onChange={(event) => {\n                  if (event.target.files) attach(event.target.files)\n                  event.target.value = ''\n                }}\n              />\n              <Button\n                type='button'\n                variant='ghost'\n                size='icon-sm'\n                aria-label='Attach files'\n                disabled={disabled}\n                onClick={() => fileInput.current?.click()}\n              >\n                <IconPlaceholder\n                  lucide='PaperclipIcon'\n                  tabler='IconPaperclip'\n                  hugeicons='Attachment01Icon'\n                  phosphor='PaperclipIcon'\n                  remixicon='RiAttachment2'\n                />\n              </Button>\n            </>\n          )}\n          {tools}\n          {busy && onStop ? (\n            <Button\n              type='button'\n              size='icon-sm'\n              aria-label='Stop generating'\n              onClick={() => {\n                onStop()\n                inner.current?.focus()\n              }}\n              className='ms-auto'\n            >\n              <IconPlaceholder\n                lucide='SquareIcon'\n                tabler='IconPlayerStopFilled'\n                hugeicons='StopIcon'\n                phosphor='StopIcon'\n                remixicon='RiStopFill'\n                className='fill-current'\n              />\n            </Button>\n          ) : (\n            <Button\n              type='submit'\n              size='icon-sm'\n              aria-label={\n                uploading ? 'Send message, once the files have uploaded' : 'Send message'\n              }\n              disabled={!canSend || uploading}\n              className='ms-auto'\n            >\n              <IconPlaceholder\n                lucide='ArrowUpIcon'\n                tabler='IconArrowUp'\n                hugeicons='ArrowUpIcon'\n                phosphor='ArrowUpIcon'\n                remixicon='RiArrowUpLine'\n              />\n            </Button>\n          )}\n        </InputGroupAddon>\n      </InputGroup>\n      <p id={hintId} className='sr-only'>\n        Press Enter to send and Shift+Enter for a new line.\n        {accept && ' Paste or drop files to attach them.'}\n      </p>\n    </form>\n  )\n}\n\ninterface ChatConversationProps extends Pick<\n  AIMessagePartsProps,\n  'renderApproval' | 'renderToolResult' | 'renderWork' | 'toolLabels'\n> {\n  chat: AIChat\n  /** The message box, which Retry focuses as it goes. */\n  composerRef?: RefObject<HTMLTextAreaElement | null>\n  feedback?: Record<string, ChatFeedback | null>\n  /** The questions to suggest under the last reply once it has finished. */\n  followUps?: (reply: AIMessage) => SuggestedPrompt[] | undefined\n  /** More to show under a finished reply, such as its tokens and cost. */\n  footer?: (reply: AIMessage) => ReactNode\n  /** What screen readers call the assistant. @default 'Assistant' */\n  name?: string\n  /** Shows thumbs up and down under each reply. */\n  onFeedback?: (messageId: string, feedback: ChatFeedback | null) => void\n}\n\n/** A question being edited, in place of its bubble: Enter sends it as a new version, Escape puts it back. */\nfunction QuestionEditor({\n  defaultValue,\n  onCancel,\n  onSubmit,\n}: {\n  defaultValue: string\n  onCancel: () => void\n  onSubmit: (text: string) => void\n}) {\n  const [text, setText] = useState(defaultValue)\n  const canSend = text.trim().length > 0\n  const send = () => {\n    if (canSend) onSubmit(text.trim())\n  }\n  return (\n    <form\n      method='post'\n      className='w-full'\n      onSubmit={(event: FormEvent<HTMLFormElement>) => {\n        event.preventDefault()\n        send()\n      }}\n    >\n      <InputGroup>\n        <InputGroupTextarea\n          // oxlint-disable-next-line jsx-a11y/no-autofocus -- Edit opens the question to type in\n          autoFocus\n          aria-label='Edit your message'\n          rows={1}\n          value={text}\n          onChange={(event) => setText(event.target.value)}\n          onFocus={(event) => {\n            const end = event.currentTarget.value.length\n            event.currentTarget.setSelectionRange(end, end)\n          }}\n          onKeyDown={(event) => {\n            if (event.nativeEvent.isComposing) return\n            if (event.key === 'Escape') {\n              event.preventDefault()\n              onCancel()\n            } else if (event.key === 'Enter' && !event.shiftKey) {\n              event.preventDefault()\n              send()\n            }\n          }}\n          className='max-h-48'\n        />\n        <InputGroupAddon align='block-end' className='justify-end gap-2'>\n          <Button type='button' variant='ghost' size='sm' onClick={onCancel}>\n            Cancel\n          </Button>\n          <Button type='submit' size='sm' disabled={!canSend}>\n            Send\n          </Button>\n        </InputGroupAddon>\n      </InputGroup>\n    </form>\n  )\n}\n\n/** Under a question: which version it is, and Copy and Edit, which show on hover. */\nfunction QuestionActions({\n  content,\n  disabled,\n  editId,\n  onEdit,\n  onVersionChange,\n  version,\n}: {\n  content: string\n  disabled?: boolean\n  editId: string\n  onEdit?: () => void\n  onVersionChange?: (index: number) => void\n  version?: MessageVersion\n}) {\n  return (\n    <div\n      role='group'\n      aria-label='Question actions'\n      className='text-muted-foreground -me-1.5 flex items-center justify-end gap-0.5'\n    >\n      <div className='flex items-center gap-0.5 transition-opacity group-focus-within/message:opacity-100 group-hover/message:opacity-100 pointer-fine:opacity-0'>\n        {content && <CopyButton label='Copy message' value={content} />}\n        {onEdit && (\n          <Button\n            id={editId}\n            variant='ghost'\n            size='icon-sm'\n            aria-label='Edit message'\n            disabled={disabled}\n            onClick={onEdit}\n          >\n            <IconPlaceholder\n              lucide='PencilIcon'\n              tabler='IconPencil'\n              hugeicons='PencilEdit02Icon'\n              phosphor='PencilSimpleIcon'\n              remixicon='RiPencilLine'\n            />\n          </Button>\n        )}\n      </div>\n      {version && onVersionChange && (\n        <MessageVersions\n          disabled={disabled}\n          version={version}\n          onChange={onVersionChange}\n        />\n      )}\n    </div>\n  )\n}\n\n/**\n * A chat's messages for `ChatMessages`: each reply with its actions, the follow-ups under the last one,\n * \"Thinking…\" until a reply starts, and a failed reply with Retry. A question can be edited, and a chat\n * that keeps versions (`chat.versions`) shows them under each question and reply, to step between.\n */\nfunction ChatConversation({\n  chat,\n  composerRef,\n  feedback,\n  followUps,\n  footer,\n  name,\n  onFeedback,\n  renderApproval,\n  renderToolResult,\n  renderWork,\n  toolLabels,\n}: ChatConversationProps) {\n  const { messages, status } = chat\n  const id = useId()\n  const [editing, setEditing] = useState<string | null>(null)\n  const streamingId = getStreamingMessageId(messages, status)\n  const busy = isBusy(status)\n  const keepsVersions = chat.selectVersion !== undefined\n  let lastQuestion = messages.length - 1\n  while (lastQuestion >= 0 && messages[lastQuestion]?.role !== 'user') lastQuestion--\n  const selectVersion = (messageId: string) =>\n    chat.selectVersion && ((index: number) => void chat.selectVersion?.(messageId, index))\n\n  const stopEditing = (messageId: string) => {\n    flushSync(() => setEditing(null))\n    document.getElementById(`${id}-edit-${messageId}`)?.focus()\n  }\n\n  return (\n    <>\n      {messages.map((message, index) => {\n        const streaming = message.id === streamingId\n        const lastMessage = index === messages.length - 1\n        const version = getMessageVersion(messages, chat.versions, index)\n        if (message.role === 'user') {\n          const text = getMessageText(message)\n          const isEditing = editing === message.id && !busy\n          return (\n            <ChatMessage\n              key={message.id}\n              message={message}\n              actions={\n                !isEditing && (\n                  <QuestionActions\n                    content={text}\n                    disabled={busy}\n                    editId={`${id}-edit-${message.id}`}\n                    onEdit={\n                      keepsVersions || index === lastQuestion\n                        ? () => setEditing(message.id)\n                        : undefined\n                    }\n                    onVersionChange={selectVersion(message.id)}\n                    version={version}\n                  />\n                )\n              }\n            >\n              {isEditing ? (\n                <QuestionEditor\n                  defaultValue={text}\n                  onCancel={() => stopEditing(message.id)}\n                  onSubmit={(next) => {\n                    setEditing(null)\n                    void chat.sendMessage({\n                      files: getMessageFiles(message),\n                      messageId: message.id,\n                      metadata: message.metadata,\n                      text: next,\n                    })\n                    composerRef?.current?.focus()\n                  }}\n                />\n              ) : undefined}\n            </ChatMessage>\n          )\n        }\n        const failedReply = lastMessage && status === 'error'\n        const waiting = message.parts.some(\n          (part) => isToolPart(part) && part.state === 'approval-requested',\n        )\n        const finishedReply =\n          message.role === 'assistant' && !streaming && !failedReply && !waiting\n        const more = finishedReply ? footer?.(message) : undefined\n        const prompts =\n          finishedReply && lastMessage && status === 'ready'\n            ? followUps?.(message)\n            : undefined\n        return (\n          <ChatMessage\n            key={message.id}\n            message={message}\n            name={message.role === 'assistant' ? name : undefined}\n            streaming={streaming}\n            toolLabels={toolLabels}\n            renderApproval={renderApproval}\n            renderToolResult={renderToolResult}\n            renderWork={renderWork}\n            onToolApprovalResponse={chat.addToolApprovalResponse}\n            footer={\n              <>\n                {more}\n                {prompts && prompts.length > 0 && (\n                  <SuggestedPrompts\n                    label='Follow-up questions'\n                    prompts={prompts}\n                    onSelect={(text) => void chat.sendMessage({ text })}\n                  />\n                )}\n              </>\n            }\n            actions={\n              finishedReply && (\n                <ChatMessageActions\n                  content={getMessageText(message)}\n                  disabled={busy}\n                  feedback={feedback?.[message.id]}\n                  onFeedback={onFeedback && ((value) => onFeedback(message.id, value))}\n                  onRegenerate={\n                    lastMessage\n                      ? () => {\n                          void chat.regenerate()\n                          composerRef?.current?.focus()\n                        }\n                      : undefined\n                  }\n                  onVersionChange={selectVersion(message.id)}\n                  version={version}\n                />\n              )\n            }\n          />\n        )\n      })}\n      {status === 'submitted' && !streamingId && <TypingIndicator />}\n      {status === 'error' && (\n        <ChatError\n          message={chat.error?.message}\n          onRetry={() => {\n            void chat.regenerate()\n            composerRef?.current?.focus()\n          }}\n        />\n      )}\n    </>\n  )\n}\n\ninterface ChatPanelProps\n  extends\n    BlockStateProps,\n    Pick<ChatConversationProps, 'followUps' | 'renderToolResult' | 'toolLabels'> {\n  /**\n   * The chat the panel runs: `useChat()` from `@ai-sdk/react`, or `useChatStream` for any other stream.\n   * The AI SDK sends \"An error occurred.\" for a failed reply unless the route's `onError` returns the message to show.\n   */\n  chat: AIChat\n  className?: string\n  /** Shown in the message box above what the person types, such as a chip for the page the question is about. */\n  context?: ReactNode\n  description?: ReactNode\n  id?: string\n  /** Shows a close button, and Escape in the panel calls it. */\n  onClose?: () => void\n  /** @default 'Ask anything' */\n  placeholder?: string\n  /** While a saved conversation loads or fails to. */\n  status?: BlockStatus\n  /** The questions a new conversation suggests. */\n  suggestions?: SuggestedPrompt[]\n  textareaRef?: Ref<HTMLTextAreaElement>\n  title: string\n}\n\n/** An assistant in a panel: a header with New conversation and Close, a welcome with suggested questions, the conversation, and the message box. */\nfunction ChatPanel({\n  chat,\n  className,\n  context,\n  description,\n  errorMessage,\n  followUps,\n  id,\n  onClose,\n  placeholder,\n  renderToolResult,\n  status: loadStatus,\n  suggestions,\n  textareaRef,\n  title,\n  toolLabels,\n}: ChatPanelProps) {\n  const blockState = useBlockState()\n  const loadState = blockState === 'empty' ? loadStatus : (blockState ?? loadStatus)\n  const composerRef = useRef<HTMLTextAreaElement | null>(null)\n  const { messages, status } = chat\n\n  useImperativeHandle(textareaRef, () => composerRef.current as HTMLTextAreaElement, [])\n\n  function onKeyDown(event: KeyboardEvent<HTMLElement>) {\n    if (event.key !== 'Escape' || event.nativeEvent.isComposing) return\n    if (event.defaultPrevented || !onClose) return\n    if (!event.currentTarget.contains(event.target as Node)) return\n    event.preventDefault()\n    onClose()\n  }\n\n  return (\n    // oxlint-disable-next-line jsx-a11y/no-noninteractive-element-interactions -- Escape from anywhere inside closes the panel\n    <section\n      id={id}\n      aria-label={title}\n      onKeyDown={onKeyDown}\n      className={cn('bg-background flex h-full min-h-0 flex-col', className)}\n    >\n      <ChatHeader\n        title={title}\n        description={description}\n        className='border-b'\n        actions={\n          <>\n            {chat.setMessages && (\n              <Button\n                variant='ghost'\n                size='icon-sm'\n                aria-label='New conversation'\n                disabled={messages.length === 0 || loadState !== undefined}\n                onClick={() => {\n                  void chat.stop()\n                  chat.setMessages?.([])\n                  composerRef.current?.focus()\n                }}\n              >\n                <IconPlaceholder\n                  lucide='SquarePenIcon'\n                  tabler='IconEdit'\n                  hugeicons='PencilEdit02Icon'\n                  phosphor='NotePencilIcon'\n                  remixicon='RiEditBoxLine'\n                />\n              </Button>\n            )}\n            {onClose && (\n              <Button\n                variant='ghost'\n                size='icon-sm'\n                aria-label={`Close ${title}`}\n                onClick={onClose}\n              >\n                <IconPlaceholder\n                  lucide='XIcon'\n                  tabler='IconX'\n                  hugeicons='Cancel01Icon'\n                  phosphor='XIcon'\n                  remixicon='RiCloseLine'\n                />\n              </Button>\n            )}\n          </>\n        }\n      />\n      {loadState ? (\n        <BlockStateProvider errorMessage={errorMessage} state={loadState}>\n          <div className='flex min-h-0 flex-1 flex-col overflow-y-auto px-4 pt-2 [scrollbar-width:thin]'>\n            <BlockStateRows rows={3} />\n          </div>\n        </BlockStateProvider>\n      ) : messages.length === 0 ? (\n        <div className='flex min-h-0 flex-1 flex-col overflow-y-auto p-4 [scrollbar-width:thin]'>\n          <ChatWelcome title={title} description={description} className='m-auto'>\n            {suggestions && suggestions.length > 0 && (\n              <SuggestedPrompts\n                variant='list'\n                prompts={suggestions}\n                onSelect={(text) => void chat.sendMessage({ text })}\n              />\n            )}\n          </ChatWelcome>\n        </div>\n      ) : (\n        <ChatMessages status={status} latest={messages.at(-1)}>\n          <ChatConversation\n            chat={chat}\n            composerRef={composerRef}\n            followUps={followUps}\n            name={title}\n            renderToolResult={renderToolResult}\n            toolLabels={toolLabels}\n          />\n        </ChatMessages>\n      )}\n      <ChatComposer\n        className='p-4 pt-2'\n        context={context}\n        disabled={loadState !== undefined}\n        placeholder={placeholder}\n        status={status}\n        textareaRef={composerRef}\n        onSubmit={chat.sendMessage}\n        onStop={chat.stop}\n      />\n    </section>\n  )\n}\n\nconst STOPPED = 'stopped'\n\ninterface UseChatStreamOptions {\n  initialError?: string\n  initialMessages?: AIMessage[]\n  /** The versions a saved chat kept, as `chat.versions` gave them. */\n  initialVersions?: AIMessageVersions\n  /** Runs when a reply ends, whether it finished or was stopped. */\n  onFinish?: (\n    message: AIMessage,\n    info: { messages: AIMessage[]; stopped: boolean },\n  ) => void\n  /**\n   * Streams the reply to the conversation so far. Each value is the whole reply as it stands: what `readUIMessageStream` from the AI SDK yields, or `replyFromText` around a stream of text.\n   * After a tool approval the conversation ends with the assistant's message, and the values continue it, its earlier parts included.\n   */\n  onSend: (messages: AIMessage[], signal: AbortSignal) => AsyncIterable<AIReply>\n  /** Runs when the person steps to another version of a message, so a saved chat shows it next time. */\n  onVersionChange?: (messageId: string, index: number) => void\n}\n\n// Unique across page loads, so a saved conversation's ids never repeat.\nfunction createId() {\n  // randomUUID exists only on https and localhost.\n  if (typeof crypto.randomUUID === 'function') return crypto.randomUUID()\n  return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`\n}\n\n/** Runs a chat from any function that streams replies, and returns what `useChat` from the AI SDK returns, so the chat blocks take either. */\nfunction useChatStream({\n  initialError,\n  initialMessages = [],\n  initialVersions = {},\n  onFinish,\n  onSend,\n  onVersionChange,\n}: UseChatStreamOptions) {\n  const controller = useRef<AbortController | null>(null)\n  const history = useRef(initialMessages)\n  const kept = useRef(initialVersions)\n  const [messages, setMessagesState] = useState(initialMessages)\n  const [versions, setVersionsState] = useState(initialVersions)\n  const [status, setStatus] = useState<AIChatStatus>(initialError ? 'error' : 'ready')\n  const [error, setError] = useState(() =>\n    initialError === undefined ? undefined : new Error(initialError),\n  )\n\n  useEffect(\n    () => () => {\n      if (!controller.current) return\n      controller.current.abort(STOPPED)\n      controller.current = null\n      setStatus('ready')\n    },\n    [],\n  )\n\n  function setMessages(next: AIMessage[]) {\n    history.current = next\n    setMessagesState(next)\n  }\n\n  function setVersions(next: AIMessageVersions) {\n    kept.current = next\n    setVersionsState(next)\n  }\n\n  /** Runs the conversation with the messages from `index` on replaced by `next`, keeping them as a version. */\n  function branch(index: number, next: AIMessage[]) {\n    const branched = branchMessages(\n      { messages: history.current, versions: kept.current },\n      index,\n      next,\n    )\n    setVersions(branched.versions)\n    void run(branched.messages)\n  }\n\n  async function run(conversation: AIMessage[]) {\n    const current = new AbortController()\n    controller.current = current\n    setMessages(conversation)\n    setStatus('submitted')\n    setError(undefined)\n    const last = conversation.at(-1)\n    const continuing = last?.role === 'assistant'\n    const before = continuing ? conversation.slice(0, -1) : conversation\n    let reply: AIMessage = continuing\n      ? last\n      : { id: createId(), parts: [], role: 'assistant' }\n    try {\n      for await (const snapshot of onSend(conversation, current.signal)) {\n        if (current.signal.aborted) break\n        reply = {\n          ...reply,\n          id: snapshot.id ?? reply.id,\n          metadata: snapshot.metadata ?? reply.metadata,\n          parts: structuredClone(snapshot.parts),\n        }\n        setMessages([...before, reply])\n        setStatus('streaming')\n      }\n    } catch (caught) {\n      if (!current.signal.aborted) {\n        controller.current = null\n        setError(caught instanceof Error ? caught : new Error(String(caught)))\n        setStatus('error')\n        return\n      }\n    }\n    const stopped = current.signal.aborted\n    const keepPartialReply = !stopped || current.signal.reason === STOPPED\n    if (!keepPartialReply) return\n    if (!stopped) {\n      controller.current = null\n      setStatus('ready')\n    }\n    if (reply.parts.length > 0) {\n      onFinish?.(reply, { messages: [...before, reply], stopped })\n    }\n  }\n\n  function sendMessage({\n    files = [],\n    messageId,\n    metadata,\n    text,\n  }: Parameters<AIChat['sendMessage']>[0]) {\n    if (controller.current) return\n    const parts: AIMessagePart[] = [...files]\n    if (text) parts.push({ state: 'done', text, type: 'text' })\n    const question: AIMessage = {\n      id: createId(),\n      metadata,\n      parts,\n      role: 'user',\n    }\n    const edited = history.current.findIndex(\n      (message) => message.id === messageId && message.role === 'user',\n    )\n    branch(edited === -1 ? history.current.length : edited, [question])\n  }\n\n  function regenerate({ messageId }: { messageId?: string } = {}) {\n    if (controller.current) return\n    const conversation = history.current\n    const asked = conversation.findIndex((message) => message.id === messageId)\n    const end = asked === -1 ? conversation.length : asked\n    let question = end - 1\n    while (question >= 0 && conversation[question]?.role !== 'user') question--\n    if (question < 0) return\n    if (status === 'error') void run(conversation.slice(0, question + 1))\n    else branch(question + 1, [])\n  }\n\n  function selectVersion(messageId: string, index: number) {\n    if (controller.current) return\n    const selected = selectMessageVersion(\n      { messages: history.current, versions: kept.current },\n      messageId,\n      index,\n    )\n    if (selected.versions === kept.current) return\n    setMessages(selected.messages)\n    setVersions(selected.versions)\n    onVersionChange?.(messageId, index)\n  }\n\n  function addToolApprovalResponse({ approved, id, reason }: AIToolApprovalResponse) {\n    const conversation = history.current\n    const last = conversation.at(-1)\n    if (controller.current || last?.role !== 'assistant') return\n    const asked = last.parts.some(\n      (part) =>\n        isToolPart(part) &&\n        part.state === 'approval-requested' &&\n        part.approval?.id === id,\n    )\n    // A request that isn't waiting in the last reply anymore: nothing to answer.\n    if (!asked) return\n    const parts = last.parts.map((part) =>\n      isToolPart(part) && part.state === 'approval-requested' && part.approval?.id === id\n        ? {\n            ...part,\n            approval: { ...part.approval, approved, reason },\n            state: 'approval-responded' as const,\n          }\n        : part,\n    )\n    const next = [...conversation.slice(0, -1), { ...last, parts }]\n    const waiting = parts.some(\n      (part) => isToolPart(part) && part.state === 'approval-requested',\n    )\n    if (waiting) setMessages(next)\n    else void run(next)\n  }\n\n  function stop() {\n    controller.current?.abort(STOPPED)\n    controller.current = null\n    setStatus('ready')\n  }\n\n  function replaceMessages(next: AIMessage[]) {\n    controller.current?.abort()\n    controller.current = null\n    setMessages(next)\n    setVersions({})\n    setError(undefined)\n    setStatus('ready')\n  }\n\n  return {\n    addToolApprovalResponse,\n    error,\n    messages,\n    regenerate,\n    selectVersion,\n    sendMessage,\n    setMessages: replaceMessages,\n    status,\n    stop,\n    versions,\n  } satisfies AIChat\n}\n\nexport {\n  AssistantAvatar,\n  AssistantMessageAvatar,\n  ChatComposer,\n  ChatContextChip,\n  ChatConversation,\n  ChatError,\n  ChatHeader,\n  ChatMessage,\n  ChatMessageActions,\n  ChatMessages,\n  ChatPanel,\n  ChatWelcome,\n  SuggestedPrompts,\n  TypingIndicator,\n  getMediaType,\n  isBusy,\n  useChatStream,\n}\n\nexport type {\n  MessageVersion,\n  ChatComposerProps,\n  ChatConversationProps,\n  ChatFeedback,\n  ChatMessageActionsProps,\n  ChatMessageProps,\n  ChatMessagesProps,\n  ChatPanelProps,\n  ComposerUpload,\n  SuggestedPrompt,\n  SuggestedPromptsProps,\n  UseChatStreamOptions,\n}\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/ai-assistant.tsx"
    }
  ],
  "type": "registry:component"
}
