{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"ai-assistant","type":"registry:block","title":"AI assistant","description":"A whole assistant screen: starter cards, reasoning, tool calls, an approval before it emails anyone, and a streamed answer, with past conversations beside it.","dependencies":["lucide-react"],"registryDependencies":["https://dashral.com/r/utils.json","https://dashral.com/r/approval-card.json","https://dashral.com/r/button.json","https://dashral.com/r/conversation.json","https://dashral.com/r/message.json","https://dashral.com/r/prompt-composer.json","https://dashral.com/r/prompt-suggestions.json","https://dashral.com/r/reasoning.json","https://dashral.com/r/select.json","https://dashral.com/r/tool-activity.json","https://dashral.com/r/tooltip.json"],"files":[{"path":"registry/dashral/blocks/ai-assistant.tsx","type":"registry:file","target":"components/dashral/blocks/ai-assistant.tsx","content":"\"use client\"\n\nimport { useEffect, useRef, useState } from \"react\"\nimport { Globe, MessageSquarePlus, Receipt, Sparkles, TrendingUp, UsersRound } from \"lucide-react\"\nimport { ApprovalCard } from \"../approval-card\"\nimport { Button } from \"../button\"\nimport { Conversation } from \"../conversation\"\nimport { Message } from \"../message\"\nimport { PromptComposer, type PromptStatus } from \"../prompt-composer\"\nimport { PromptSuggestions } from \"../prompt-suggestions\"\nimport { Reasoning } from \"../reasoning\"\nimport { Select } from \"../select\"\nimport { ToolActivity, type ToolStep } from \"../tool-activity\"\nimport { Tooltip } from \"../tooltip\"\nimport { cn } from \"../lib/utils\"\n\n// An assistant for a dashboard. Without `onAsk` it plays scripted answers, so it works without a model. With it, your\n// model drives the same turn: call run.think, run.tool, run.approve and run.write as your stream (the Vercel AI SDK's\n// streamText, say) brings reasoning, tool calls and text:\n//\n//   <AiAssistant\n//     onAsk={async (prompt, run) => {\n//       const result = streamText({ model, prompt, tools, abortSignal: run.signal })\n//       for await (const part of result.fullStream) {\n//         if (part.type === \"reasoning-delta\") run.think(part.text)\n//         if (part.type === \"text-delta\") run.write(part.text)\n//         if (part.type === \"tool-call\") calls[part.toolCallId] = run.tool(part.toolName, part.input)\n//         if (part.type === \"tool-result\") calls[part.toolCallId]?.done(part.output)\n//       }\n//     }}\n//   />\n\n/** What an action needs approved before it runs, on the approval card. */\nexport type ApprovalRequest = { title: string; description?: string; details?: { label: string; value: string }[]; approveLabel?: string; result?: string }\n/** One answer in the making, for your model's stream to fill in. */\nexport type AssistantRun = {\n  /** Adds to the reasoning shown above the answer (folded away once the answer starts). */\n  think: (text: string) => void\n  /** Shows a tool call running; call done or fail on what it returns when it finishes. */\n  tool: (name: string, input?: unknown) => { done: (output?: unknown, description?: string) => void; fail: (description?: string) => void }\n  /** Shows the approval card and waits: true once approved, false when denied. */\n  approve: (request: ApprovalRequest) => Promise<boolean>\n  /** Adds to the answer, as it streams in. */\n  write: (text: string) => void\n  /** Aborted when Stop is pressed or a new conversation starts: pass it to your model's call. */\n  signal: AbortSignal\n}\nexport type AssistantSuggestion = { icon?: React.ReactNode; label: string; description?: string; prompt: string }\n\ntype Tool = { name: string; input?: unknown; output?: unknown; description: string; ms: number }\ntype Script = {\n  thoughts?: string[]\n  tools?: Tool[]\n  /** Asks before acting; what runs and what it says after each choice. */\n  approval?: {\n    title: string\n    description: string\n    details: { label: string; value: string }[]\n    approveLabel: string\n    result: string\n    then: Tool\n    approved: string\n    denied: string\n  }\n  answer: string\n}\n\nconst scripts: Record<string, Script> = {\n  revenue: {\n    thoughts: [\n      \"This month means October so far. I need paid orders and their total, then the same for September to compare.\",\n      \"Revenue is $48,920 against $43,480: up 12.5%. I'll check which plan drove it.\",\n    ],\n    tools: [\n      { name: \"Search orders\", input: { from: \"2026-10-01\", to: \"2026-10-31\", status: \"paid\" }, output: { orders: 1284, revenue: 48920 }, description: \"1,284 paid orders, $48,920\", ms: 900 },\n      { name: \"Compare with September\", input: { metric: \"revenue\", groupBy: \"plan\" }, output: { change: \"+12.5%\", topPlan: \"Team\" }, description: \"Up 12.5%, led by the Team plan\", ms: 800 },\n    ],\n    answer:\n      \"October has brought in $48,920 so far, 12.5% more than September, from 1,284 orders. Most of the rise came from the Team plan: 31 new subscriptions against 19 last month. Refunds stayed low at 1.8%.\",\n  },\n  unpaid: {\n    tools: [{ name: \"Find unpaid invoices\", input: { status: \"past_due\" }, output: { invoices: 3, total: 2520 }, description: \"3 invoices past due, $2,520 in all\", ms: 800 }],\n    approval: {\n      title: \"Send 3 payment reminders\",\n      description: \"Each customer gets the friendly first reminder, with their invoice attached.\",\n      details: [\n        { label: \"To\", value: \"Northwind, Sagara Resorts, Kopi Senja\" },\n        { label: \"Total due\", value: \"$2,520\" },\n      ],\n      approveLabel: \"Send reminders\",\n      result: \"Reminders sent\",\n      then: { name: \"Send 3 reminders\", description: \"Delivered to all three\", ms: 1100 },\n      approved: \"Done: the three reminders went out. I'll tell you when any of them pays.\",\n      denied: \"OK, I won't send them. The invoices stay open in Billing if you change your mind.\",\n    },\n    answer: \"\",\n  },\n  traffic: {\n    thoughts: [\"Tuesday is October 14. I'll compare its visits by source with the Tuesdays before it.\"],\n    tools: [{ name: \"Read traffic by source\", input: { day: \"2026-10-14\" }, output: { email: \"-61%\", search: \"+2%\", direct: \"-1%\" }, description: \"Email visits fell 61%; the rest held\", ms: 900 }],\n    answer:\n      \"Traffic dipped on Tuesday because the newsletter went out a day late: visits from email fell 61% that day, while search and direct held steady. Sign-ups recovered on Wednesday, and the week ended 4% up.\",\n  },\n  other: {\n    thoughts: [\"This demo has sample answers for three questions; anything else gets a word on how it works.\"],\n    answer:\n      \"This is a demo with sample data, so I can answer three questions: revenue this month, unpaid invoices and Tuesday's traffic dip. In your app, connect a model and give it your dashboards as tools, and I'll answer anything about them.\",\n  },\n}\n\nconst sampleSuggestions: AssistantSuggestion[] = [\n  { icon: <TrendingUp />, label: \"Revenue this month\", description: \"Totals, the change and what drove it\", prompt: \"How's revenue this month?\" },\n  { icon: <Receipt />, label: \"Unpaid invoices\", description: \"Remind the customers who owe you\", prompt: \"Remind the customers who haven't paid yet.\" },\n  { icon: <Globe />, label: \"Tuesday's traffic dip\", description: \"What happened, and whether it recovered\", prompt: \"Why did traffic dip on Tuesday?\" },\n  { icon: <UsersRound />, label: \"Best customers\", description: \"This quarter's top accounts\", prompt: \"Who are our biggest customers this quarter?\" },\n]\n\nconst sampleHistory = [\n  { title: \"October revenue\", prompt: \"How's revenue this month?\" },\n  { title: \"Payment reminders\", prompt: \"Remind the customers who haven't paid yet.\" },\n  { title: \"Tuesday's traffic dip\", prompt: \"Why did traffic dip on Tuesday?\" },\n]\n\nconst scriptFor = (prompt: string) =>\n  /revenue|sales/i.test(prompt) ? scripts.revenue! : /paid|invoice|remind/i.test(prompt) ? scripts.unpaid! : /traffic|visit/i.test(prompt) ? scripts.traffic! : scripts.other!\n\ntype Turn =\n  | { id: number; from: \"user\"; text: string }\n  | {\n      id: number\n      from: \"assistant\"\n      prompt: string\n      thoughts?: { text: string; done: boolean }\n      tools: ToolStep[]\n      /** What ran after the approval, shown under it. */\n      after: ToolStep[]\n      approval?: { request: ApprovalRequest; asking: boolean; done: boolean; stopped?: boolean }\n      /** Your model's call threw: what it said. */\n      error?: string\n      answer: string\n      streaming: boolean\n    }\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))\n\nexport type AiAssistantProps = {\n  title?: string\n  description?: string\n  /** The empty conversation's words, and the cards that start one. */\n  empty?: { title: string; description: string }\n  suggestions?: AssistantSuggestion[]\n  /** Past conversations beside it on wide screens; none hides the column. */\n  history?: { title: string; prompt: string }[]\n  /** The models to pick from, in the header; none hides the picker. */\n  models?: { value: string; label: string; description?: string }[]\n  /** The Search toggle in the composer. */\n  webSearch?: boolean\n  placeholder?: string\n  /** Your model: fill the turn as its stream comes in (see AssistantRun). Throw to show an error on the answer. Without it, scripted sample answers. */\n  onAsk?: (prompt: string, run: AssistantRun, options: { model?: string; web: boolean; files: File[] }) => Promise<void> | void\n  /** Good or bad response on an answer. */\n  onFeedback?: (answer: { prompt: string; text: string }, feedback: \"up\" | \"down\" | null) => void\n}\n\nexport function AiAssistant({\n  title = \"Assistant\",\n  description = \"Answers from your sales, customers and traffic\",\n  empty = { title: \"What would you like to know?\", description: \"Ask about revenue, invoices, customers or traffic. The answers come from your dashboards.\" },\n  suggestions = sampleSuggestions,\n  history = sampleHistory,\n  models = [\n    { value: \"fast\", label: \"Fast\", description: \"Quick answers\" },\n    { value: \"deep\", label: \"Deep\", description: \"Slower, for analysis\" },\n  ],\n  webSearch = true,\n  placeholder = \"Ask about revenue, invoices or traffic…\",\n  onAsk,\n  onFeedback,\n}: AiAssistantProps) {\n  const [turns, setTurns] = useState<Turn[]>([])\n  const [status, setStatus] = useState<PromptStatus>(\"ready\")\n  const [model, setModel] = useState(models[0]?.value)\n  const [web, setWeb] = useState(false)\n  const run = useRef(0)\n  const nextId = useRef(1)\n  const decide = useRef<((choice: \"approve\" | \"deny\") => void) | null>(null)\n  const abort = useRef<AbortController | null>(null)\n\n  useEffect(\n    () => () => {\n      run.current++\n      abort.current?.abort()\n    },\n    []\n  )\n\n  /** Asks: your model through onAsk, or the scripted sample. */\n  function ask(prompt: string, files: File[] = []) {\n    if (onAsk) void askModel(prompt, files)\n    else void play(prompt)\n  }\n\n  async function askModel(prompt: string, files: File[]) {\n    const current = ++run.current\n    const alive = () => run.current === current\n    const controller = new AbortController()\n    abort.current = controller\n    const question = nextId.current++\n    const id = nextId.current++\n    const patch = (change: (turn: Extract<Turn, { from: \"assistant\" }>) => Partial<Extract<Turn, { from: \"assistant\" }>>) =>\n      alive() && setTurns((all) => all.map((turn) => (turn.id === id && turn.from === \"assistant\" ? { ...turn, ...change(turn) } : turn)))\n    setTurns((all) => [...all, { id: question, from: \"user\", text: prompt }, { id, from: \"assistant\", prompt, tools: [], after: [], answer: \"\", streaming: false }])\n    setStatus(\"submitted\")\n    // Tool calls before the approval show above it, the ones after it under it.\n    let list: \"tools\" | \"after\" = \"tools\"\n    const handle: AssistantRun = {\n      signal: controller.signal,\n      think: (text) => patch((turn) => ({ thoughts: { text: (turn.thoughts?.text ?? \"\") + text, done: false } })),\n      tool(name, input) {\n        const where = list\n        const started = performance.now()\n        let index = -1\n        patch((turn) => {\n          index = turn[where].length\n          return { [where]: [...turn[where], { name, status: \"running\", input }] }\n        })\n        const finish = (step: Partial<ToolStep>) =>\n          patch((turn) => ({ [where]: turn[where].map((s, i) => (i === index ? { ...s, ...step, duration: Math.round(performance.now() - started) } : s)) }))\n        return {\n          done: (output, description) => finish({ status: \"done\", output, description }),\n          fail: (description) => finish({ status: \"error\", description }),\n        }\n      },\n      async approve(request) {\n        patch(() => ({ approval: { request, asking: true, done: false } }))\n        setStatus(\"ready\")\n        const choice = await new Promise<\"approve\" | \"deny\">((resolve) => (decide.current = resolve))\n        decide.current = null\n        list = \"after\"\n        if (alive()) setStatus(\"streaming\")\n        if (choice === \"approve\") patch((turn) => ({ approval: turn.approval && { ...turn.approval, asking: false, done: true } }))\n        return choice === \"approve\"\n      },\n      write(text) {\n        if (!alive()) return\n        setStatus(\"streaming\")\n        patch((turn) => ({ answer: turn.answer + text, streaming: true, thoughts: turn.thoughts && { ...turn.thoughts, done: true } }))\n      },\n    }\n    try {\n      await onAsk!(prompt, handle, { model, web, files })\n      patch((turn) => ({ streaming: false, thoughts: turn.thoughts && { ...turn.thoughts, done: true } }))\n    } catch (e) {\n      if (!controller.signal.aborted) patch((turn) => ({ streaming: false, error: e instanceof Error ? e.message : \"Couldn't finish this answer.\", thoughts: turn.thoughts && { ...turn.thoughts, done: true } }))\n    }\n    if (alive()) setStatus(\"ready\")\n  }\n\n  async function play(prompt: string) {\n    const current = ++run.current\n    const alive = () => run.current === current\n    const script = scriptFor(prompt)\n    const question = nextId.current++\n    const id = nextId.current++\n    const patch = (change: (turn: Extract<Turn, { from: \"assistant\" }>) => Partial<Extract<Turn, { from: \"assistant\" }>>) =>\n      setTurns((all) => all.map((turn) => (turn.id === id && turn.from === \"assistant\" ? { ...turn, ...change(turn) } : turn)))\n    setTurns((all) => [\n      ...all,\n      { id: question, from: \"user\", text: prompt },\n      { id, from: \"assistant\", prompt, thoughts: script.thoughts && { text: \"\", done: false }, tools: [], after: [], answer: \"\", streaming: false },\n    ])\n    setStatus(\"submitted\")\n\n    for (const thought of script.thoughts ?? []) {\n      await sleep(900)\n      if (!alive()) return\n      patch((turn) => ({ thoughts: { text: turn.thoughts!.text ? `${turn.thoughts!.text}\\n\\n${thought}` : thought, done: false } }))\n    }\n    if (script.thoughts) patch((turn) => ({ thoughts: { ...turn.thoughts!, done: true } }))\n\n    // A tool call: running, then done with what it found. `list` is where it shows: before the approval, or after it.\n    async function runTool(tool: Tool, list: \"tools\" | \"after\" = \"tools\") {\n      patch((turn) => ({ [list]: [...turn[list], { name: tool.name, status: \"running\", input: tool.input }] }))\n      await sleep(tool.ms)\n      if (!alive()) return false\n      patch((turn) => ({\n        [list]: turn[list].map((step, i) => (i === turn[list].length - 1 ? { ...step, status: \"done\", output: tool.output, description: tool.description, duration: tool.ms } : step)),\n      }))\n      return true\n    }\n    for (const tool of script.tools ?? []) if (!(await runTool(tool))) return\n\n    let answer = script.answer\n    if (script.approval) {\n      const { title, description, details, approveLabel, result } = script.approval\n      patch(() => ({ approval: { request: { title, description, details, approveLabel, result }, asking: true, done: false } }))\n      setStatus(\"ready\")\n      const choice = await new Promise<\"approve\" | \"deny\">((resolve) => (decide.current = resolve))\n      decide.current = null\n      if (!alive()) return\n      setStatus(\"streaming\")\n      if (choice === \"approve\") {\n        if (!(await runTool(script.approval.then, \"after\"))) return\n        patch((turn) => ({ approval: turn.approval && { ...turn.approval, asking: false, done: true } }))\n        answer = script.approval.approved\n      } else answer = script.approval.denied\n    }\n\n    setStatus(\"streaming\")\n    patch(() => ({ streaming: true }))\n    const words = answer.split(\" \")\n    for (let shown = 1; shown <= words.length; shown++) {\n      await sleep(35)\n      if (!alive()) return\n      patch(() => ({ answer: words.slice(0, shown).join(\" \") }))\n    }\n    patch(() => ({ streaming: false }))\n    setStatus(\"ready\")\n  }\n\n  function stop() {\n    run.current++\n    abort.current?.abort()\n    decide.current = null\n    setTurns((all) =>\n      all.map((turn) =>\n        turn.from === \"assistant\"\n          ? {\n              ...turn,\n              streaming: false,\n              thoughts: turn.thoughts && { ...turn.thoughts, done: true },\n              // An approval still waiting when it's stopped won't run: it reads as denied.\n              approval: turn.approval?.asking ? { ...turn.approval, asking: false, stopped: true } : turn.approval,\n              tools: turn.tools.map((step) => (step.status === \"running\" ? { ...step, status: \"error\", description: \"Stopped\" } : step)),\n              after: turn.after.map((step) => (step.status === \"running\" ? { ...step, status: \"error\", description: \"Stopped\" } : step)),\n            }\n          : turn\n      )\n    )\n    setStatus(\"ready\")\n  }\n\n  function newChat() {\n    stop()\n    setTurns([])\n  }\n\n  const busy = status !== \"ready\"\n\n  return (\n    // The whole frame, as the app would be: it fills the window (its height too, so the composer is always in view).\n    <div className=\"flex h-svh min-h-[32rem] bg-card text-card-foreground\">\n      {/* Past conversations, on wide screens. */}\n      {history.length > 0 && (\n        <aside aria-label=\"Conversations\" className=\"hidden w-60 shrink-0 flex-col border-e bg-muted/30 lg:flex\">\n          <div className=\"p-3\">\n            <Button variant=\"outline\" size=\"sm\" className=\"w-full justify-start\" onClick={newChat}>\n              <MessageSquarePlus /> New conversation\n            </Button>\n          </div>\n          <p className=\"px-4 pt-2 pb-1 text-xs font-medium text-muted-foreground\">Recent</p>\n          <ul className=\"grid gap-0.5 px-2\">\n            {history.map((item) => (\n              <li key={item.title}>\n                <button\n                  type=\"button\"\n                  onClick={() => {\n                    newChat()\n                    ask(item.prompt)\n                  }}\n                  className=\"w-full truncate rounded-md px-2 py-1.5 text-start text-sm text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50\"\n                >\n                  {item.title}\n                </button>\n              </li>\n            ))}\n          </ul>\n        </aside>\n      )}\n\n      <section aria-label=\"Assistant\" className=\"flex min-w-0 flex-1 flex-col\">\n        <header className=\"flex items-center gap-2 border-b px-4 py-3\">\n          <span aria-hidden className=\"grid size-8 shrink-0 place-items-center rounded-full bg-primary/10 text-primary-text\">\n            <Sparkles className=\"size-4\" />\n          </span>\n          <div className=\"min-w-0 flex-1\">\n            <h2 className=\"truncate text-sm font-medium\">{title}</h2>\n            {description && <p className=\"truncate text-xs text-muted-foreground\">{description}</p>}\n          </div>\n          {models.length > 0 && (\n            <Select\n              aria-label=\"Model\"\n              size=\"sm\"\n              value={model}\n              onValueChange={setModel}\n              options={models}\n              className=\"w-auto gap-1.5 border-0 bg-transparent text-muted-foreground shadow-none hover:bg-accent hover:text-foreground\"\n            />\n          )}\n          <Tooltip content=\"New conversation\">\n            <Button variant=\"ghost\" size=\"icon-sm\" aria-label=\"New conversation\" onClick={newChat} disabled={!turns.length} className=\"text-muted-foreground lg:hidden\">\n              <MessageSquarePlus />\n            </Button>\n          </Tooltip>\n        </header>\n\n        <Conversation\n          classNames={{ content: \"mx-auto w-full max-w-2xl px-4 sm:px-6\" }}\n          empty={{\n            icon: <Sparkles />,\n            title: empty.title,\n            description: empty.description,\n            actions: suggestions.length > 0 && <PromptSuggestions variant=\"cards\" suggestions={suggestions} onSelect={(prompt) => ask(prompt)} className=\"mt-2 max-w-xl text-start\" />,\n          }}\n        >\n          {turns.map((turn) =>\n            turn.from === \"user\" ? (\n              <Message key={turn.id} from=\"user\">\n                {turn.text}\n              </Message>\n            ) : (\n              <Message\n                key={turn.id}\n                from=\"assistant\"\n                status={turn.error ? \"error\" : turn.streaming ? \"streaming\" : \"done\"}\n                error={turn.error}\n                showActions={!turn.streaming && (turn.answer || turn.error) ? \"hover\" : false}\n                copyText={turn.answer}\n                onRegenerate={busy ? undefined : () => ask(turn.prompt)}\n                onFeedbackChange={(feedback) => onFeedback?.({ prompt: turn.prompt, text: turn.answer }, feedback)}\n              >\n                {turn.thoughts && <Reasoning status={turn.thoughts.done ? \"done\" : \"thinking\"}>{turn.thoughts.text}</Reasoning>}\n                {turn.tools.length > 0 && <ToolActivity steps={turn.tools} className={cn(turn.thoughts && \"mt-2\")} />}\n                {turn.approval && (\n                  <ApprovalCard\n                    className=\"mt-3\"\n                    title={turn.approval.request.title}\n                    description={turn.approval.request.description}\n                    details={turn.approval.request.details}\n                    approveLabel={turn.approval.request.approveLabel}\n                    status={turn.approval.stopped ? \"denied\" : undefined}\n                    result={turn.approval.done ? turn.approval.request.result : undefined}\n                    onApprove={() => decide.current?.(\"approve\")}\n                    onDeny={() => decide.current?.(\"deny\")}\n                  />\n                )}\n                {turn.after.length > 0 && <ToolActivity steps={turn.after} className=\"mt-3\" />}\n                {turn.answer && <p className={cn((turn.thoughts || turn.tools.length > 0 || turn.approval) && \"mt-3\")}>{turn.answer}</p>}\n                {!turn.answer && !turn.error && !turn.thoughts && turn.tools.length === 0 && <span className=\"text-muted-foreground\">Thinking</span>}\n              </Message>\n            )\n          )}\n        </Conversation>\n\n        <div className=\"mx-auto w-full max-w-2xl px-4 pb-4 sm:px-6\">\n          <PromptComposer\n            placeholder={placeholder}\n            status={status}\n            onStop={stop}\n            attachments={{ accept: \"image/*,.pdf,.csv\", maxFiles: 4, maxSize: 10 * 1024 * 1024 }}\n            onSubmit={({ text, files }) => ask(text || \"What's in these files?\", files)}\n            actions={\n              webSearch && (\n                <Button\n                  type=\"button\"\n                  variant=\"ghost\"\n                  size=\"sm\"\n                  aria-pressed={web}\n                  onClick={() => setWeb(!web)}\n                  className={cn(\"rounded-full\", web && \"bg-primary/10 text-primary-text hover:bg-primary/15\")}\n                >\n                  <Globe aria-hidden /> Search\n                </Button>\n              )\n            }\n          />\n        </div>\n      </section>\n    </div>\n  )\n}\n"}],"cssVars":{"theme":{"color-primary-text":"var(--primary-text, var(--primary))"},"light":{},"dark":{}}}