{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "thought-trail-chat-demo",
  "type": "registry:block",
  "title": "Thought Trail: Chat Reasoning",
  "description": "AI Reasoning Steps example, Chat Reasoning: A chat reply that thinks first. The message's parts are shaped like the AI SDK's, and each reasoning or tool part becomes a step. The trail folds into \"Thought for 9s\" as soon as the answer starts streaming below it. A take on the AI thinking state (reasoning). Fits features and app UI sections.",
  "author": "KeyframeUI <https://keyframeui.com>",
  "categories": [
    "features",
    "app-ui",
    "ai-thinking-state",
    "steps",
    "accordion",
    "ai-chat",
    "ai",
    "status",
    "motion"
  ],
  "docs": "Live preview, examples and props: https://keyframeui.com/components/thought-trail#thought-trail-chat-demo",
  "registryDependencies": [
    "https://keyframeui.com/r/thought-trail.json"
  ],
  "files": [
    {
      "path": "components/thought-trail-chat-demo.tsx",
      "type": "registry:component",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { useInView } from \"motion/react\";\n\nimport { ThoughtTrail, ThoughtTrailStep } from \"@/components/ui/thought-trail\";\n\n/* Parts shaped like the AI SDK's UIMessage parts. With useChat, drop the\n * script below and render:\n *\n *   <ReasoningTrail parts={message.parts} streaming={status === \"streaming\"} />\n */\ntype ToolState = \"input-streaming\" | \"input-available\" | \"output-available\" | \"output-error\";\ntype Page = { title: string; path: string };\ntype Part =\n  | { type: \"reasoning\"; text: string; state: \"streaming\" | \"done\" }\n  | {\n      type: \"tool-searchDocs\";\n      toolCallId: string;\n      state: ToolState;\n      input: { query: string };\n      output?: { pages: Page[] };\n    }\n  | {\n      type: \"tool-readPage\";\n      toolCallId: string;\n      state: ToolState;\n      input: { path: string };\n      output?: { title: string; excerpt: string };\n    }\n  | { type: \"text\"; text: string; state: \"streaming\" | \"done\" };\n\n/** Every part but the answer becomes a step. The last one works until the next begins, as it does in a stream. */\nfunction ReasoningTrail({ parts, streaming }: { parts: Part[]; streaming: boolean }) {\n  const steps = parts.filter((part) => part.type !== \"text\");\n  const answering = parts.some((part) => part.type === \"text\");\n  return (\n    <ThoughtTrail\n      running={streaming && !answering}\n      label=\"Thinking\"\n      doneLabel={({ seconds }) => (seconds ? `Thought for ${seconds}s` : \"Thought\")}\n      icon={<Sparkle />}\n    >\n      {steps.map((part, i) => {\n        const last = i === steps.length - 1 && streaming && !answering;\n        const failed = \"toolCallId\" in part && part.state === \"output-error\";\n        const status = failed ? \"error\" : last ? \"active\" : \"done\";\n        return <PartStep key={\"toolCallId\" in part ? part.toolCallId : `reasoning-${i}`} part={part} status={status} />;\n      })}\n    </ThoughtTrail>\n  );\n}\n\nfunction PartStep({ part, status }: { part: Part; status: \"active\" | \"done\" | \"error\" }) {\n  switch (part.type) {\n    case \"reasoning\": {\n      // Reasoning summaries open with a bold heading; it names the step.\n      const [, heading, body] = part.text.match(/^\\*\\*(.+?)\\*\\*\\s*([\\s\\S]*)$/) ?? [null, \"Thinking\", part.text];\n      return (\n        <ThoughtTrailStep status={status} title={heading}>\n          {body ? <p className=\"text-pretty\">{body}</p> : null}\n        </ThoughtTrailStep>\n      );\n    }\n    case \"tool-searchDocs\":\n      return (\n        <ThoughtTrailStep\n          status={status}\n          title=\"Searching the React docs\"\n          summary={part.output ? `Found ${part.output.pages.length} pages` : \"Search failed\"}\n          icon={<SearchIcon />}\n        >\n          <p className=\"text-zinc-400 dark:text-zinc-500\">“{part.input.query}”</p>\n          {part.output ? (\n            <ul className=\"mt-1.5 space-y-1\">\n              {part.output.pages.map((page) => (\n                <li key={page.path} className=\"flex min-w-0 items-baseline gap-2\">\n                  <span className=\"shrink-0 text-zinc-700 dark:text-zinc-300\">{page.title}</span>\n                  <span className=\"truncate font-mono text-[11px] text-zinc-400 dark:text-zinc-500\">{page.path}</span>\n                </li>\n              ))}\n            </ul>\n          ) : null}\n        </ThoughtTrailStep>\n      );\n    case \"tool-readPage\":\n      return (\n        <ThoughtTrailStep\n          status={status}\n          title={`Reading react.dev${part.input.path}`}\n          summary={part.output ? `Read “${part.output.title}”` : \"Couldn't read the page\"}\n          icon={<PageIcon />}\n        >\n          {part.output ? (\n            <blockquote className=\"border-l-2 border-zinc-200 pl-3 text-pretty text-zinc-600 dark:border-zinc-700 dark:text-zinc-400\">\n              {part.output.excerpt}\n            </blockquote>\n          ) : (\n            <p className=\"font-mono text-[11px] text-zinc-400 dark:text-zinc-500\">GET react.dev{part.input.path}</p>\n          )}\n        </ThoughtTrailStep>\n      );\n    default:\n      return null;\n  }\n}\n\n/* ── The scripted reply ─────────────────────────────────── */\n\nconst question = \"Why does my useEffect run twice in development?\";\n\nconst thoughts = [\n  \"**Considering Strict Mode**\\n\\nAn effect that fires twice, but only in development, is almost always Strict Mode remounting the component. Worth checking the docs for the exact behavior before answering.\",\n  \"**Drafting the answer**\\n\\nConfirmed: development only, setup → cleanup → setup. The fix is a cleanup function, not turning Strict Mode off. A connection makes the clearest example.\",\n];\n\nconst pages: Page[] = [\n  { title: \"<StrictMode>\", path: \"/reference/react/StrictMode\" },\n  { title: \"Synchronizing with Effects\", path: \"/learn/synchronizing-with-effects\" },\n  { title: \"useEffect\", path: \"/reference/react/useEffect\" },\n  { title: \"You Might Not Need an Effect\", path: \"/learn/you-might-not-need-an-effect\" },\n];\n\nconst answer = [\n  \"That's Strict Mode, and it only happens in development. React mounts each component, unmounts it and mounts it again, so every effect runs setup, cleanup, then setup. It's there to catch effects that don't clean up after themselves.\",\n  \"Keep Strict Mode on. Return a cleanup that undoes what the effect did:\",\n  \"```useEffect(() => {\\n  const connection = createConnection(roomId);\\n  connection.connect();\\n  return () => connection.disconnect();\\n}, [roomId]);\",\n  \"With the cleanup in place the second run is harmless, and production runs the effect once.\",\n];\n\n// When each part starts and finishes, in ms.\nconst T = {\n  think: [600, 3300],\n  search: [3300, 4800], // the tool returns at 4.8s; the step works until the next part\n  read: [5600, 7000],\n  draft: [7800, 9700],\n  answer: [9900, 13900],\n};\n\nconst words = (text: string, share: number) => {\n  const all = text.split(\" \");\n  return all.slice(0, Math.ceil(all.length * Math.min(1, Math.max(0, share)))).join(\" \");\n};\nconst share = (t: number, [from, to]: number[]) => (t - from) / (to - from);\n\n/** The message's parts at `t` ms. */\nfunction partsAt(t: number): Part[] {\n  const parts: Part[] = [];\n  const reasoning = (text: string, span: number[]) => {\n    if (t < span[0]) return;\n    const done = t >= span[1];\n    // The heading lands whole, then the body streams.\n    const [heading, body] = text.split(\"\\n\\n\");\n    parts.push({ type: \"reasoning\", text: `${heading}\\n\\n${words(body, share(t, span) * 1.1)}`, state: done ? \"done\" : \"streaming\" });\n  };\n  reasoning(thoughts[0], T.think);\n  if (t >= T.search[0]) {\n    parts.push({\n      type: \"tool-searchDocs\",\n      toolCallId: \"call_search\",\n      state: t >= T.search[1] ? \"output-available\" : \"input-available\",\n      input: { query: \"useEffect runs twice in development\" },\n      output: t >= T.search[1] ? { pages } : undefined,\n    });\n  }\n  if (t >= T.read[0]) {\n    parts.push({\n      type: \"tool-readPage\",\n      toolCallId: \"call_read\",\n      state: t >= T.read[1] ? \"output-available\" : \"input-available\",\n      input: { path: \"/reference/react/StrictMode\" },\n      output:\n        t >= T.read[1]\n          ? {\n              title: \"<StrictMode>\",\n              excerpt:\n                \"Your components will re-run Effects an extra time to find bugs caused by missing Effect cleanup.\",\n            }\n          : undefined,\n    });\n  }\n  reasoning(thoughts[1], T.draft);\n  if (t >= T.answer[0]) {\n    const chars = answer.join(\"\\n\\n\").length * Math.min(1, share(t, T.answer));\n    let left = Math.ceil(chars);\n    const shown: string[] = [];\n    for (const block of answer) {\n      if (left <= 0) break;\n      shown.push(block.slice(0, left));\n      left -= block.length + 2;\n    }\n    parts.push({ type: \"text\", text: shown.join(\"\\n\\n\"), state: t >= T.answer[1] ? \"done\" : \"streaming\" });\n  }\n  return parts;\n}\n\n/** Milliseconds into the current run, from when the demo first scrolls into view. Stops at `end`. */\nfunction usePlayhead(run: number, playing: boolean, end: number) {\n  const [clock, setClock] = React.useState({ run, t: 0 });\n  React.useEffect(() => {\n    if (!playing) return;\n    const start = performance.now();\n    const timer = window.setInterval(() => {\n      const t = Math.min(end, performance.now() - start);\n      setClock({ run, t });\n      if (t >= end) window.clearInterval(timer);\n    }, 50);\n    return () => window.clearInterval(timer);\n  }, [run, playing, end]);\n  return clock.run === run ? clock.t : 0;\n}\n\n/** Keeps a scrolling box at its bottom while its content grows, until the reader scrolls up. */\nfunction useStickToBottom(ref: React.RefObject<HTMLDivElement | null>) {\n  React.useEffect(() => {\n    const box = ref.current;\n    const content = box?.firstElementChild;\n    if (!box || !content) return;\n    let stuck = true;\n    const onScroll = () => {\n      stuck = box.scrollHeight - box.scrollTop - box.clientHeight < 24;\n    };\n    const observer = new ResizeObserver(() => {\n      if (stuck) box.scrollTop = box.scrollHeight;\n    });\n    observer.observe(content);\n    box.addEventListener(\"scroll\", onScroll, { passive: true });\n    return () => {\n      observer.disconnect();\n      box.removeEventListener(\"scroll\", onScroll);\n    };\n  }, [ref]);\n}\n\n// A chat reply that thinks first. The trail opens under the question, folds\n// into \"Thought for 9s\" once the answer starts, and the answer streams below.\nexport function ThoughtTrailChatDemo() {\n  const ref = React.useRef<HTMLDivElement>(null);\n  const scrollRef = React.useRef<HTMLDivElement>(null);\n  const playing = useInView(ref, { once: true, amount: 0.4 });\n  const [run, setRun] = React.useState(0);\n  const t = usePlayhead(run, playing, T.answer[1]);\n  const parts = playing ? partsAt(t) : [];\n  const text = parts.find((part) => part.type === \"text\");\n  useStickToBottom(scrollRef);\n\n  return (\n    <div\n      ref={ref}\n      className=\"flex h-[34rem] w-full max-w-2xl flex-col overflow-hidden rounded-2xl border border-zinc-200 bg-white shadow-sm shadow-zinc-950/5 dark:border-zinc-800 dark:bg-zinc-950 dark:shadow-black/40\"\n    >\n      <div className=\"flex h-12 shrink-0 items-center justify-between gap-3 border-b border-zinc-100 px-4 dark:border-zinc-800/80\">\n        <p className=\"text-sm font-medium text-zinc-900 dark:text-zinc-100\">React help</p>\n        <button\n          type=\"button\"\n          onClick={() => setRun((r) => r + 1)}\n          className=\"inline-flex h-8 items-center gap-1.5 rounded-lg px-2.5 text-xs font-medium text-zinc-600 transition-[background-color,color,scale] duration-150 outline-none select-none hover:bg-zinc-100 hover:text-zinc-950 focus-visible:ring-2 focus-visible:ring-zinc-400 active:scale-[0.96] dark:text-zinc-400 dark:hover:bg-zinc-800 dark:hover:text-zinc-50 dark:focus-visible:ring-zinc-600\"\n        >\n          Ask again\n        </button>\n      </div>\n\n      <div ref={scrollRef} className=\"min-h-0 flex-1 overflow-y-auto\">\n        <div className=\"flex flex-col gap-5 px-4 py-5 sm:px-6\">\n          <p className=\"max-w-[80%] self-end rounded-2xl rounded-br-md bg-zinc-100 px-3.5 py-2 text-sm text-zinc-900 dark:bg-zinc-800 dark:text-zinc-100\">\n            {question}\n          </p>\n          {playing ? (\n            <div className=\"min-w-0\">\n              <ReasoningTrail parts={parts} streaming={t < T.answer[1]} />\n              {text && text.type === \"text\" ? <Answer text={text.text} /> : null}\n            </div>\n          ) : null}\n        </div>\n      </div>\n\n      <div className=\"shrink-0 border-t border-zinc-100 p-3 dark:border-zinc-800/80\">\n        <div className=\"flex h-10 items-center rounded-xl border border-zinc-200 px-3.5 text-sm text-zinc-400 dark:border-zinc-800 dark:text-zinc-500\">\n          Ask a follow-up…\n        </div>\n      </div>\n    </div>\n  );\n}\n\nfunction Answer({ text }: { text: string }) {\n  return (\n    <div className=\"mt-3 space-y-3 text-sm leading-relaxed text-pretty text-zinc-800 dark:text-zinc-200\">\n      {text.split(\"\\n\\n\").map((block, i) =>\n        block.startsWith(\"```\") ? (\n          <pre\n            key={i}\n            className=\"overflow-x-auto rounded-lg border border-zinc-200 bg-zinc-50 px-3.5 py-2.5 font-mono text-[12px] leading-5 text-zinc-700 dark:border-zinc-800 dark:bg-zinc-900 dark:text-zinc-300\"\n          >\n            {block.slice(3)}\n          </pre>\n        ) : (\n          <p key={i}>{block}</p>\n        ),\n      )}\n    </div>\n  );\n}\n\nfunction Sparkle() {\n  return (\n    <svg viewBox=\"0 0 16 16\" fill=\"none\">\n      <path\n        d=\"M8 1.75c.35 2.9 1.35 3.9 4.25 4.25-2.9.35-3.9 1.35-4.25 4.25C7.65 7.35 6.65 6.35 3.75 6 6.65 5.65 7.65 4.65 8 1.75Z M12.5 10.5c.15 1.2.55 1.6 1.75 1.75-1.2.15-1.6.55-1.75 1.75-.15-1.2-.55-1.6-1.75-1.75 1.2-.15 1.6-.55 1.75-1.75Z\"\n        fill=\"currentColor\"\n      />\n    </svg>\n  );\n}\n\nfunction SearchIcon() {\n  return (\n    <svg viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden>\n      <circle cx=\"7\" cy=\"7\" r=\"4.25\" stroke=\"currentColor\" strokeWidth=\"1.5\" />\n      <path d=\"M10.25 10.25 13.5 13.5\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" />\n    </svg>\n  );\n}\n\nfunction PageIcon() {\n  return (\n    <svg viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden>\n      <path d=\"M4 1.75h5L12.25 5v9.25H4z M9 1.75V5h3.25\" stroke=\"currentColor\" strokeWidth=\"1.4\" strokeLinejoin=\"round\" />\n    </svg>\n  );\n}\n"
    }
  ]
}