{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ai-chat",
  "title": "AI Chat",
  "description": "A Mac OS 9 AI chat window: transcript with streaming replies, thinking state, tool calls with approvals, suggested prompts, model picker and composer.",
  "registryDependencies": [
    "https://nostalgia-ui.com/r/nostalgia-theme.json",
    "https://nostalgia-ui.com/r/retro-ai.json",
    "https://nostalgia-ui.com/r/retro-approval.json",
    "https://nostalgia-ui.com/r/retro-message.json",
    "https://nostalgia-ui.com/r/retro-model-picker.json",
    "https://nostalgia-ui.com/r/retro-prompt-input.json",
    "https://nostalgia-ui.com/r/retro-suggested-prompts.json",
    "https://nostalgia-ui.com/r/retro-thinking.json",
    "https://nostalgia-ui.com/r/retro-tool-call.json",
    "https://nostalgia-ui.com/r/retro-window.json"
  ],
  "files": [
    {
      "path": "registry/new-york/blocks/ai-chat.tsx",
      "content": "\"use client\"\n\n/*\n * AI Chat: a Mac OS 9 chat window for an AI assistant.\n *\n * Drive it from the Vercel AI SDK's useChat (pass `messages`, `status`,\n * `onSubmit`, `onStop`, `onToolApproval`), or leave `messages` out and it runs\n * a scripted demo assistant with no backend, including a tool call that asks\n * for approval.\n */\n\nimport * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\nimport {\n  isToolPart,\n  type RetroChatMessage,\n  type RetroChatStatus,\n  type RetroMessagePart,\n  type RetroToolPart,\n} from \"@/registry/new-york/lib/retro-ai\"\nimport { RetroApproval } from \"@/registry/new-york/ui/retro-approval\"\nimport {\n  RetroAssistantIcon,\n  RetroMessage,\n  RetroMessageActions,\n  RetroMessageThread,\n} from \"@/registry/new-york/ui/retro-message\"\nimport { RetroModelPicker, type RetroModel } from \"@/registry/new-york/ui/retro-model-picker\"\nimport { RetroPromptInput } from \"@/registry/new-york/ui/retro-prompt-input\"\nimport { RetroSuggestedPrompts } from \"@/registry/new-york/ui/retro-suggested-prompts\"\nimport { RetroThinking } from \"@/registry/new-york/ui/retro-thinking\"\nimport { RetroToolCall } from \"@/registry/new-york/ui/retro-tool-call\"\nimport { RetroWindow } from \"@/registry/new-york/ui/retro-window\"\n\n/* ------------------------------------------------------------------ */\n/*  Demo conversation: a scripted assistant, so the block works with   */\n/*  no backend. Pass `messages` to drive the block from useChat.      */\n/* ------------------------------------------------------------------ */\n\ntype Step =\n  | { kind: \"pause\"; ms: number }\n  | { kind: \"reasoning\"; text: string }\n  | { kind: \"text\"; text: string }\n  | { kind: \"tool\"; name: string; input: unknown; output: unknown; ms?: number }\n  | {\n      kind: \"approval\"\n      name: string\n      input: unknown\n      output: unknown\n      approved: Step[]\n      denied: Step[]\n    }\n\ninterface Script {\n  match: RegExp\n  steps: Step[]\n}\n\nconst DEMO_SCRIPTS: Script[] = [\n  {\n    match: /tidy|clean|desktop|organi[sz]e/i,\n    steps: [\n      { kind: \"pause\", ms: 700 },\n      {\n        kind: \"reasoning\",\n        text: \"The desktop has loose files. I should look at what's there first, group them by kind, and ask before moving anything.\",\n      },\n      {\n        kind: \"tool\",\n        name: \"listFolder\",\n        input: { path: \"Macintosh HD:Desktop Folder\" },\n        output: {\n          items: 14,\n          kinds: { \"SimpleText document\": 6, \"JPEG image\": 5, \"StuffIt archive\": 3 },\n        },\n        ms: 1100,\n      },\n      {\n        kind: \"approval\",\n        name: \"moveFiles\",\n        input: {\n          moves: [\n            { kind: \"SimpleText document\", to: \"Documents\" },\n            { kind: \"JPEG image\", to: \"Pictures\" },\n            { kind: \"StuffIt archive\", to: \"Downloads\" },\n          ],\n        },\n        output: { moved: 14, skipped: 0 },\n        approved: [\n          { kind: \"pause\", ms: 300 },\n          {\n            kind: \"text\",\n            text: \"Done. I moved 14 items:\\n\\n• 6 documents to **Documents**\\n• 5 pictures to **Pictures**\\n• 3 archives to **Downloads**\\n\\nYour desktop now just has the hard disk and the Trash. Want me to empty the Trash too?\",\n          },\n        ],\n        denied: [\n          { kind: \"pause\", ms: 300 },\n          { kind: \"text\", text: \"No problem, I left everything where it was. I can suggest folders instead if you'd rather sort them yourself.\" },\n        ],\n      },\n    ],\n  },\n  {\n    match: /read ?me|write/i,\n    steps: [\n      { kind: \"pause\", ms: 600 },\n      {\n        kind: \"text\",\n        text: \"Here's a short Read Me you can paste into SimpleText:\\n\\n```\\nREAD ME — Kaleidoscope Schemes\\n\\n1. Drag the schemes onto the Kaleidoscope folder.\\n2. Restart your Macintosh.\\n3. Choose a scheme in the Kaleidoscope control panel.\\n```\\n\\nKeep it under 32K so SimpleText can open it.\",\n      },\n    ],\n  },\n  {\n    match: /slow|memory|ram|speed/i,\n    steps: [\n      { kind: \"pause\", ms: 800 },\n      {\n        kind: \"reasoning\",\n        text: \"Slowness on OS 9 is usually memory: apps get a fixed partition. Check what's running and how much is free.\",\n      },\n      {\n        kind: \"tool\",\n        name: \"getMemoryUsage\",\n        input: {},\n        output: {\n          builtIn: \"128 MB\",\n          virtualMemory: \"off\",\n          largestUnusedBlock: \"9.8 MB\",\n          apps: [\n            { name: \"Mac OS\", used: \"41.2 MB\" },\n            { name: \"Netscape Communicator\", used: \"48.0 MB\" },\n            { name: \"Photoshop\", used: \"28.5 MB\" },\n          ],\n        },\n        ms: 900,\n      },\n      {\n        kind: \"text\",\n        text: \"Your Mac has only 9.8 MB free. Two things will help:\\n\\n• **Quit Netscape** when you're not using it. It's holding 48 MB.\\n• **Turn on Virtual Memory** in the Memory control panel, then restart.\\n\\nPhotoshop will feel faster straight away.\",\n      },\n    ],\n  },\n]\n\nconst DEMO_FALLBACK: Step[] = [\n  { kind: \"pause\", ms: 600 },\n  {\n    kind: \"text\",\n    text: \"I'm a demo assistant, so I only know a few tricks. Try asking me to **tidy your desktop**, **write a Read Me**, or **why your Mac is slow**.\",\n  },\n]\n\nlet demoId = 0\nconst nextId = (p: string) => `${p}-${++demoId}`\n\nfunction useDemoChat() {\n  const [messages, setMessages] = React.useState<RetroChatMessage[]>([])\n  const [status, setStatus] = React.useState<RetroChatStatus>(\"ready\")\n  const run = React.useRef(0)\n  const pendingApproval = React.useRef<((approved: boolean) => void) | null>(null)\n\n  /* edit the last assistant message */\n  const patchLast = React.useCallback((fn: (parts: RetroMessagePart[]) => RetroMessagePart[]) => {\n    setMessages((all) => {\n      const last = all[all.length - 1]\n      if (!last || last.role !== \"assistant\") return all\n      return [...all.slice(0, -1), { ...last, parts: fn(last.parts) }]\n    })\n  }, [])\n\n  const stop = React.useCallback(() => {\n    run.current++\n    pendingApproval.current = null\n    patchLast((parts) =>\n      parts.map((p) => {\n        if ((p.type === \"text\" || p.type === \"reasoning\") && p.state === \"streaming\") return { ...p, state: \"done\" }\n        /* a tool cut off mid-run reports that it was stopped */\n        if (isToolPart(p) && (p.state === \"input-streaming\" || p.state === \"input-available\"))\n          return { ...p, state: \"output-error\", errorText: \"Stopped.\" }\n        return p\n      })\n    )\n    setStatus(\"ready\")\n  }, [patchLast])\n\n  const play = React.useCallback(\n    async (steps: Step[], id: number) => {\n      const alive = () => run.current === id\n      const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))\n\n      /* stream text into a new part in uneven chunks, like a network would */\n      const stream = async (type: \"text\" | \"reasoning\", text: string) => {\n        patchLast((parts) => [...parts, { type, text: \"\", state: \"streaming\" }])\n        setStatus(\"streaming\")\n        let i = 0\n        while (i < text.length) {\n          if (!alive()) return\n          i = Math.min(text.length, i + 3 + Math.floor(Math.random() * 14))\n          const slice = text.slice(0, i)\n          patchLast((parts) => {\n            const copy = [...parts]\n            copy[copy.length - 1] = { type, text: slice, state: \"streaming\" }\n            return copy\n          })\n          await sleep(45 + Math.random() * 70)\n        }\n        patchLast((parts) => {\n          const copy = [...parts]\n          copy[copy.length - 1] = { type, text, state: \"done\" }\n          return copy\n        })\n      }\n\n      const setTool = (toolCallId: string, patch: Partial<RetroToolPart>) =>\n        patchLast((parts) => parts.map((p) => (isToolPart(p) && p.toolCallId === toolCallId ? { ...p, ...patch } : p)))\n\n      const queue = [...steps]\n      while (queue.length) {\n        const step = queue.shift()!\n        if (!alive()) return\n        if (step.kind === \"pause\") await sleep(step.ms)\n        else if (step.kind === \"text\" || step.kind === \"reasoning\") await stream(step.kind, step.text)\n        else if (step.kind === \"tool\") {\n          const toolCallId = nextId(\"call\")\n          patchLast((parts) => [\n            ...parts,\n            { type: `tool-${step.name}`, toolCallId, state: \"input-available\", input: step.input },\n          ])\n          setStatus(\"streaming\")\n          await sleep(step.ms ?? 900)\n          if (!alive()) return\n          setTool(toolCallId, { state: \"output-available\", output: step.output })\n          await sleep(250)\n        } else if (step.kind === \"approval\") {\n          const toolCallId = nextId(\"call\")\n          const approvalId = nextId(\"approval\")\n          patchLast((parts) => [\n            ...parts,\n            {\n              type: `tool-${step.name}`,\n              toolCallId,\n              state: \"approval-requested\",\n              input: step.input,\n              approval: { id: approvalId },\n            },\n          ])\n          setStatus(\"ready\")\n          const approved = await new Promise<boolean>((resolve) => {\n            pendingApproval.current = resolve\n          })\n          if (!alive()) return\n          setStatus(\"streaming\")\n          if (approved) {\n            setTool(toolCallId, { state: \"input-available\", approval: { id: approvalId, approved: true } })\n            await sleep(1000)\n            if (!alive()) return\n            setTool(toolCallId, { state: \"output-available\", output: step.output })\n            queue.unshift(...step.approved)\n          } else {\n            setTool(toolCallId, { state: \"output-denied\", approval: { id: approvalId, approved: false } })\n            queue.unshift(...step.denied)\n          }\n        }\n      }\n    },\n    [patchLast]\n  )\n\n  const submit = React.useCallback(\n    async (text: string) => {\n      const id = ++run.current\n      pendingApproval.current = null\n      setMessages((all) => [\n        ...all,\n        { id: nextId(\"user\"), role: \"user\", parts: [{ type: \"text\", text }] },\n        { id: nextId(\"assistant\"), role: \"assistant\", parts: [] },\n      ])\n      setStatus(\"submitted\")\n      const script = DEMO_SCRIPTS.find((s) => s.match.test(text))?.steps ?? DEMO_FALLBACK\n      await play(script, id)\n      if (run.current === id && !pendingApproval.current) setStatus(\"ready\")\n    },\n    [play]\n  )\n\n  const respond = React.useCallback((approved: boolean) => {\n    const resolve = pendingApproval.current\n    pendingApproval.current = null\n    resolve?.(approved)\n  }, [])\n\n  return { messages, status, submit, stop, respond }\n}\n\n/* ------------------------------------------------------------------ */\n/*  Block                                                              */\n/* ------------------------------------------------------------------ */\n\nconst DEFAULT_MODELS: RetroModel[] = [\n  { id: \"quick\", name: \"Quick\", description: \"Fast answers for everyday questions\" },\n  { id: \"thorough\", name: \"Thorough\", description: \"Thinks longer, uses tools\" },\n]\n\nconst DEFAULT_SUGGESTIONS = [\"Tidy my desktop\", \"Write a Read Me\", \"Why is my Mac slow?\"]\n\n/* what an approval card says for a tool, in plain words */\nfunction approvalCopy(part: RetroToolPart) {\n  const input = (part.input ?? {}) as { moves?: { kind: string; to: string }[] }\n  if (input.moves) {\n    return {\n      title: \"Allow the assistant to move files on your desktop?\",\n      description: \"Items will be moved into folders in your home folder. You can move them back at any time.\",\n      details: input.moves.map((m) => `${m.kind}s → ${m.to}`),\n    }\n  }\n  return {}\n}\n\ninterface ToolProps {\n  part: RetroToolPart\n  onToolApproval?: (part: RetroToolPart, approved: boolean, always: boolean) => void\n}\n\nfunction ToolWithApproval({ part, onToolApproval }: ToolProps) {\n  const rowRef = React.useRef<HTMLDivElement>(null)\n  const asked = part.approval !== undefined\n  return (\n    <div className=\"my-[3px] flex flex-col gap-[6px]\">\n      <RetroToolCall ref={rowRef} part={part} />\n      {asked && (\n        <RetroApproval\n          part={part}\n          anchorRef={rowRef}\n          {...approvalCopy(part)}\n          onApprove={(always) => onToolApproval?.(part, true, always)}\n          onDeny={() => onToolApproval?.(part, false, false)}\n        />\n      )}\n    </div>\n  )\n}\n\ninterface AiChatBlockProps\n  extends Omit<React.ComponentPropsWithoutRef<typeof RetroWindow>, \"title\" | \"children\" | \"onSubmit\"> {\n  /** Window title. Defaults to \"Assistant\". */\n  title?: string\n  /** Messages to show, e.g. from useChat. Leave out to run the built-in demo. */\n  messages?: RetroChatMessage[]\n  /** Chat status, e.g. from useChat. */\n  status?: RetroChatStatus\n  /** Runs with the composer's text when the user sends. */\n  onSubmit?: (text: string) => void\n  /** Stops the current reply (Stop button, ⌘-period, Escape). */\n  onStop?: () => void\n  /** Runs when the user answers a tool approval. */\n  onToolApproval?: (part: RetroToolPart, approved: boolean, always: boolean) => void\n  /** Runs when the user asks to regenerate the last reply. */\n  onRetry?: () => void\n  /** Models for the picker. Pass an empty array to hide it. */\n  models?: RetroModel[]\n  model?: string\n  onModelChange?: (id: string) => void\n  /** Starter prompts shown while the conversation is empty. */\n  suggestions?: string[]\n}\n\nfunction AiChatBlock({\n  title = \"Assistant\",\n  messages: messagesProp,\n  status: statusProp,\n  onSubmit,\n  onStop,\n  onToolApproval,\n  onRetry,\n  models = DEFAULT_MODELS,\n  model,\n  onModelChange,\n  suggestions = DEFAULT_SUGGESTIONS,\n  className,\n  ...props\n}: AiChatBlockProps) {\n  const demo = useDemoChat()\n  const isDemo = messagesProp === undefined\n  const messages = isDemo ? demo.messages : messagesProp\n  const status = isDemo ? demo.status : (statusProp ?? \"ready\")\n\n  const [draft, setDraft] = React.useState(\"\")\n  const [modelId, setModelId] = React.useState(model ?? models[0]?.id ?? \"\")\n  const inputRef = React.useRef<HTMLTextAreaElement>(null)\n\n  const send = (text: string) => (isDemo ? demo.submit(text) : onSubmit?.(text))\n  const stop = () => (isDemo ? demo.stop() : onStop?.())\n  const answer = (part: RetroToolPart, approved: boolean, always: boolean) => {\n    if (isDemo) demo.respond(approved)\n    else onToolApproval?.(part, approved, always)\n    inputRef.current?.focus()\n  }\n\n  const busy = status === \"submitted\" || status === \"streaming\"\n  const last = messages[messages.length - 1]\n  /* \"submitted\": the reply hasn't produced anything yet */\n  const thinking = busy && (!last || last.role !== \"assistant\" || last.parts.length === 0)\n\n  return (\n    <RetroWindow title={title} active className={cn(\"w-full max-w-[560px]\", className)} {...props}>\n      <div className=\"flex h-[520px] flex-col gap-[8px]\">\n        <RetroMessageThread streaming={busy} className=\"min-h-0 flex-1\">\n          {messages.length === 0 ? (\n            <div className=\"flex h-full min-h-[300px] flex-col items-center justify-center gap-[10px] px-4 text-center\">\n              <RetroAssistantIcon className=\"size-[32px]\" />\n              <p className=\"font-[family-name:var(--os9-font-heading)] text-[12px] text-os9-black\">How can I help?</p>\n              <RetroSuggestedPrompts\n                className=\"justify-center\"\n                suggestions={suggestions}\n                onSelect={(prompt) => send(prompt)}\n              />\n            </div>\n          ) : (\n            messages.map((message, i) => {\n              const isLast = i === messages.length - 1\n              const streamingThis = isLast && message.role === \"assistant\" && status === \"streaming\"\n              const finished = message.role === \"assistant\" && !(isLast && busy) && message.parts.length > 0\n              if (message.role === \"assistant\" && message.parts.length === 0) return null\n              return (\n                <RetroMessage\n                  key={message.id}\n                  message={message}\n                  streaming={streamingThis}\n                  renderTool={(part) => <ToolWithApproval part={part} onToolApproval={answer} />}\n                >\n                  {finished && hasText(message.parts) && (\n                    <RetroMessageActions message={message} onRetry={isLast && onRetry ? onRetry : undefined} />\n                  )}\n                </RetroMessage>\n              )\n            })\n          )}\n          {thinking && <RetroThinking />}\n        </RetroMessageThread>\n\n        <RetroPromptInput\n          inputRef={inputRef}\n          value={draft}\n          onValueChange={setDraft}\n          onSubmit={send}\n          onStop={stop}\n          status={status}\n          placeholder=\"Ask anything…\"\n          toolbar={\n            models.length > 0 ? (\n              <RetroModelPicker\n                models={models}\n                value={model ?? modelId}\n                onValueChange={(id) => {\n                  setModelId(id)\n                  onModelChange?.(id)\n                }}\n              />\n            ) : undefined\n          }\n        />\n      </div>\n    </RetroWindow>\n  )\n}\n\nfunction hasText(parts: RetroMessagePart[]) {\n  return parts.some((p) => p.type === \"text\" && p.text.length > 0)\n}\n\nexport { AiChatBlock }\nexport type { AiChatBlockProps }\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:block"
}