{
  "name": "ai-tool-calls",
  "type": "registry:component",
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "files": [
    {
      "type": "registry:component",
      "content": "\"use client\";\n\n/**\n * @author: @kokonutui\n * @description: AI Tool Calls\n * @version: 1.1.0\n * @date: 2026-10-31\n * @license: MIT\n * @website: https://kokonutui.com\n * @github: https://github.com/kokonut-labs/kokonutui\n */\n\nimport {\n  CalendarCheck,\n  ChevronRight,\n  FileText,\n  Search,\n  Wrench,\n} from \"lucide-react\";\nimport { AnimatePresence, MotionConfig, motion } from \"motion/react\";\nimport { type ReactNode, useEffect, useId, useRef, useState } from \"react\";\nimport { cn } from \"@/lib/utils\";\n\n/**\n * The states an AI SDK tool part goes through, so `part.state` can be passed\n * straight in. `output-available`, `output-error` and `output-denied` end\n * a call; the rest show it running.\n */\nexport type ToolCallState =\n  | \"input-streaming\"\n  | \"input-available\"\n  | \"approval-requested\"\n  | \"approval-responded\"\n  | \"output-available\"\n  | \"output-error\"\n  | \"output-denied\";\n\nexport interface ToolCallItem {\n  /** Stable across renders, e.g. the part's `toolCallId`. */\n  id: string;\n  /** The tool's name, such as `web_search`. Picks the icon. */\n  tool: string;\n  /** While it runs, e.g. \"Searching the web\". Defaults to the tool's name. */\n  running?: string;\n  /** Once done, e.g. \"Searched the web\". Defaults to `running`. */\n  done?: string;\n  /** The main argument: a query, a URL, a file. */\n  detail?: string;\n  /** A short result, e.g. \"8 results\". */\n  result?: string;\n  /**\n   * Where the call is. Give every call a state to drive the list from your\n   * stream; leave them all out and the calls play through on `duration`.\n   */\n  state?: ToolCallState;\n  /** Shown in place of the result when the call fails. */\n  error?: string;\n  /** Demo only: how long the call takes, in ms. */\n  duration?: number;\n  icon?: ReactNode;\n}\n\nexport interface AIToolCallsProps {\n  /** The user's message, drawn as a bubble. Only the demo draws one by default. */\n  prompt?: string;\n  /** The calls in this reply, oldest first. Demo calls when omitted. */\n  calls?: ToolCallItem[];\n  /** The reply under the calls, shown once every call has ended. */\n  answer?: ReactNode;\n  className?: string;\n}\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\nconst FOLD_DELAY = 650;\nconst DEMO_DURATION = 1000;\nconst SEARCH_TOOL = /search/;\nconst READ_TOOL = /read|fetch|page|file/;\nconst BOOK_TOOL = /calendar|availab|book/;\nconst SEPARATORS = /[_-]+/g;\n\nconst DEMO_PROMPT = \"Find me a quiet hotel in Alfama for Nov 14–16, under €200\";\n\nconst DEMO_CALLS: ToolCallItem[] = [\n  {\n    id: \"search\",\n    tool: \"web_search\",\n    running: \"Searching the web\",\n    done: \"Searched the web\",\n    detail: \"quiet hotels Alfama Lisbon\",\n    result: \"8 results\",\n    duration: 1300,\n  },\n  {\n    id: \"read\",\n    tool: \"read_page\",\n    running: \"Reading\",\n    done: \"Read\",\n    detail: \"memmo-alfama.com/rooms\",\n    result: \"1 page\",\n    duration: 900,\n  },\n  {\n    id: \"rooms\",\n    tool: \"check_availability\",\n    running: \"Checking rooms\",\n    done: \"Checked rooms\",\n    detail: \"Memmo Alfama · Nov 14–16\",\n    result: \"€184 / night\",\n    duration: 1200,\n  },\n];\n\nconst DEMO_ANSWER =\n  \"Memmo Alfama has a terrace room free for Nov 14–16 at €184 a night. It sits on a pedestrian lane above the river, so it stays quiet after dark, and breakfast is included.\";\n\nconst iconFor = (tool: string) => {\n  if (SEARCH_TOOL.test(tool)) {\n    return Search;\n  }\n  if (READ_TOOL.test(tool)) {\n    return FileText;\n  }\n  if (BOOK_TOOL.test(tool)) {\n    return CalendarCheck;\n  }\n  return Wrench;\n};\n\nconst seconds = (ms: number) => `${(ms / 1000).toFixed(1)}s`;\n\nconst ended = (state?: ToolCallState) =>\n  state === \"output-available\" ||\n  state === \"output-error\" ||\n  state === \"output-denied\";\n\nconst failed = (state?: ToolCallState) =>\n  state === \"output-error\" || state === \"output-denied\";\n\nconst runningLabel = (call: ToolCallItem) =>\n  call.running ?? call.tool.replace(SEPARATORS, \" \");\n\n/**\n * Plays calls one after another on their `duration`, as the states a stream\n * would give them. Only runs while `active`.\n */\nfunction usePlayback(calls: ToolCallItem[], active: boolean) {\n  const [current, setCurrent] = useState(0);\n\n  useEffect(() => {\n    if (!active || current >= calls.length) {\n      return;\n    }\n    const next = setTimeout(\n      () => setCurrent((i) => i + 1),\n      calls[current].duration ?? DEMO_DURATION\n    );\n    return () => clearTimeout(next);\n  }, [active, current, calls]);\n\n  return calls\n    .slice(0, Math.min(current + 1, calls.length))\n    .map<ToolCallItem>((call, i) => ({\n      ...call,\n      state: i < current ? \"output-available\" : \"input-available\",\n    }));\n}\n\n/**\n * When each call started and ended, as this component saw it. Calls that\n * were already over when it mounted (an older message) have no times, so\n * their reply shows no duration rather than a wrong one.\n */\nfunction useTimings(calls: ToolCallItem[]) {\n  const times = useRef(new Map<string, { start?: number; end?: number }>());\n  const mounted = useRef(false);\n  const [now, setNow] = useState(0);\n  const anyRunning = calls.some((call) => !ended(call.state));\n\n  for (const call of calls) {\n    const entry = times.current.get(call.id);\n    if (!entry) {\n      const fresh = mounted.current || !ended(call.state);\n      times.current.set(call.id, fresh ? { start: performance.now() } : {});\n    } else if (ended(call.state) && entry.start !== undefined && !entry.end) {\n      entry.end = performance.now();\n    }\n  }\n\n  useEffect(() => {\n    mounted.current = true;\n  }, []);\n\n  useEffect(() => {\n    if (!anyRunning) {\n      return;\n    }\n    const tick = setInterval(() => setNow(performance.now()), 100);\n    return () => clearInterval(tick);\n  }, [anyRunning]);\n\n  const elapsed = (id: string) => {\n    const entry = times.current.get(id);\n    if (entry?.start === undefined) {\n      return;\n    }\n    return (entry.end ?? Math.max(now, entry.start)) - entry.start;\n  };\n\n  return { elapsed };\n}\n\n/** A value, or the demo's when the component runs as the demo. */\nfunction withDemo<T>(value: T | undefined, isDemo: boolean, demo: T) {\n  return value ?? (isDemo ? demo : undefined);\n}\n\n/** The calls as they stand: from props when they carry states, else played. */\nfunction useCalls(source: ToolCallItem[]) {\n  const playing = source.every((call) => call.state === undefined);\n  const played = usePlayback(source, playing);\n  return playing ? played : source;\n}\n\n/** What the header and the screen reader line say about the calls. */\nfunction summarize(\n  calls: ToolCallItem[],\n  elapsed: (id: string) => number | undefined\n) {\n  const finished = calls.length > 0 && calls.every((call) => ended(call.state));\n  const failures = calls.filter((call) => failed(call.state)).length;\n  const durations = calls.map((call) => elapsed(call.id));\n  const timed = calls.length > 0 && durations.every((d) => d !== undefined);\n  const noun = calls.length === 1 ? \"tool\" : \"tools\";\n  const failedNote = failures > 0 ? `, ${failures} failed` : \"\";\n  return {\n    finished,\n    summary: `Used ${calls.length} ${noun}${failedNote}`,\n    total: timed\n      ? durations.reduce<number>((sum, d) => sum + (d ?? 0), 0)\n      : undefined,\n    active: calls.find((call) => !ended(call.state)),\n  };\n}\n\n/**\n * Folds the list away a beat after the last call ends, then shows the\n * answer. A reply that was already done when it mounted starts folded.\n */\nfunction useFold(finished: boolean) {\n  const [doneAtMount] = useState(finished);\n  const [open, setOpen] = useState(!doneAtMount);\n  const [answered, setAnswered] = useState(doneAtMount);\n\n  useEffect(() => {\n    if (!finished) {\n      setAnswered(false);\n      return;\n    }\n    if (answered) {\n      return;\n    }\n    const fold = setTimeout(() => {\n      setOpen(false);\n      setAnswered(true);\n    }, FOLD_DELAY);\n    return () => clearTimeout(fold);\n  }, [finished, answered]);\n\n  return { doneAtMount, open, setOpen, answered };\n}\n\nexport default function AIToolCalls({\n  prompt,\n  calls: callsProp,\n  answer,\n  className,\n}: AIToolCallsProps) {\n  const listId = useId();\n  const isDemo = callsProp === undefined;\n  const calls = useCalls(callsProp ?? DEMO_CALLS);\n  const { elapsed } = useTimings(calls);\n  const { finished, summary, total, active } = summarize(calls, elapsed);\n  const { doneAtMount, open, setOpen, answered } = useFold(finished);\n  // The demo brings its own question and answer; a real reply only shows\n  // what it's given, since the app draws the conversation around it.\n  const shownPrompt = withDemo(prompt, isDemo, DEMO_PROMPT);\n  const shownAnswer = withDemo(answer, isDemo, DEMO_ANSWER);\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <div\n        className={cn(\"flex w-full max-w-md flex-col gap-4\", className)}\n        data-state={finished ? \"done\" : \"running\"}\n      >\n        {shownPrompt ? (\n          <p className=\"max-w-[85%] self-end rounded-2xl rounded-br-md bg-zinc-100 px-3.5 py-2 text-[14px] text-zinc-800 leading-snug dark:bg-zinc-800 dark:text-zinc-100\">\n            {shownPrompt}\n          </p>\n        ) : null}\n\n        <div>\n          <button\n            aria-controls={listId}\n            aria-expanded={open}\n            className=\"group flex h-7 items-center gap-2 rounded-md text-[13px] outline-hidden focus-visible:ring-2 focus-visible:ring-zinc-400/50\"\n            disabled={!finished}\n            onClick={() => setOpen((o) => !o)}\n            type=\"button\"\n          >\n            <AnimatePresence initial={false} mode=\"popLayout\">\n              {finished ? (\n                <motion.span\n                  animate={{ opacity: 1 }}\n                  className=\"flex items-center\"\n                  initial={{ opacity: 0 }}\n                  key=\"stack\"\n                  transition={{ duration: 0.2 }}\n                >\n                  <IconStack calls={calls} still={doneAtMount} />\n                </motion.span>\n              ) : (\n                <motion.span\n                  className=\"flex size-5 items-center justify-center\"\n                  exit={{ opacity: 0 }}\n                  key=\"spin\"\n                >\n                  <Spinner />\n                </motion.span>\n              )}\n            </AnimatePresence>\n            <AnimatePresence initial={false} mode=\"popLayout\">\n              <motion.span\n                animate={{ opacity: 1, y: 0, filter: \"blur(0px)\" }}\n                className={cn(\n                  \"font-medium transition-colors duration-150\",\n                  finished\n                    ? \"text-zinc-600 group-hover:text-zinc-900 dark:text-zinc-400 dark:group-hover:text-zinc-100\"\n                    : \"text-zinc-900 dark:text-zinc-100\"\n                )}\n                exit={{ opacity: 0, y: -4, filter: \"blur(2px)\" }}\n                initial={{ opacity: 0, y: 4, filter: \"blur(2px)\" }}\n                key={finished ? \"used\" : \"working\"}\n                transition={{ duration: 0.2, ease: EASE_OUT }}\n              >\n                {finished ? summary : \"Working\"}\n              </motion.span>\n            </AnimatePresence>\n            {total === undefined ? null : (\n              <span className=\"font-mono text-[11.5px] text-zinc-400 tabular-nums dark:text-zinc-500\">\n                {seconds(total)}\n              </span>\n            )}\n            {finished && (\n              <ChevronRight\n                aria-hidden=\"true\"\n                className={cn(\n                  \"size-3.5 text-zinc-400 transition-transform duration-200 dark:text-zinc-500\",\n                  open && \"rotate-90\"\n                )}\n              />\n            )}\n          </button>\n\n          <AnimatePresence initial={false}>\n            {open && calls.length > 0 && (\n              <motion.div\n                animate={{ height: \"auto\", opacity: 1 }}\n                className=\"overflow-hidden\"\n                exit={{ height: 0, opacity: 0 }}\n                id={listId}\n                initial={{ height: 0, opacity: 0 }}\n                transition={{ duration: 0.3, ease: EASE_OUT }}\n              >\n                <ol className=\"ml-[9.5px] border-zinc-200 border-l pt-1 pl-[18px] dark:border-zinc-700/80\">\n                  <AnimatePresence initial={false}>\n                    {calls.map((call) => (\n                      <CallRow\n                        call={call}\n                        elapsed={elapsed(call.id)}\n                        key={call.id}\n                      />\n                    ))}\n                  </AnimatePresence>\n                </ol>\n              </motion.div>\n            )}\n          </AnimatePresence>\n        </div>\n\n        <AnimatePresence>\n          {answered && shownAnswer ? (\n            <motion.div\n              animate={{ opacity: 1, filter: \"blur(0px)\", y: 0 }}\n              className=\"text-[15px] text-zinc-800 leading-7 dark:text-zinc-200\"\n              initial={\n                doneAtMount ? false : { opacity: 0, filter: \"blur(4px)\", y: 4 }\n              }\n              transition={{ duration: 0.4, ease: EASE_OUT, delay: 0.1 }}\n            >\n              {shownAnswer}\n            </motion.div>\n          ) : null}\n        </AnimatePresence>\n        <p aria-live=\"polite\" className=\"sr-only\">\n          {finished ? summary : active && runningLabel(active)}\n        </p>\n      </div>\n    </MotionConfig>\n  );\n}\n\nfunction IconStack({\n  calls,\n  still,\n}: {\n  calls: ToolCallItem[];\n  still: boolean;\n}) {\n  return calls.map((call, i) => {\n    const Icon = iconFor(call.tool);\n    return (\n      <motion.span\n        animate={{ x: 0, opacity: 1 }}\n        className={cn(\n          \"-ml-1.5 flex size-5 items-center justify-center rounded-full bg-white ring-1 first:ml-0 dark:bg-zinc-900\",\n          failed(call.state)\n            ? \"text-rose-500 ring-rose-500/30\"\n            : \"text-zinc-500 ring-black/[0.08] dark:text-zinc-400 dark:ring-white/10\"\n        )}\n        initial={still ? false : { x: -6 * i, opacity: 0 }}\n        key={call.id}\n        style={{ zIndex: calls.length - i }}\n        transition={{ duration: 0.3, ease: EASE_OUT }}\n      >\n        {call.icon ?? <Icon className=\"size-2.5\" />}\n      </motion.span>\n    );\n  });\n}\n\nfunction CallRow({ call, elapsed }: { call: ToolCallItem; elapsed?: number }) {\n  const Icon = iconFor(call.tool);\n  const running = !ended(call.state);\n  const error = failed(call.state);\n  let trailing: ReactNode = call.result;\n  if (running) {\n    trailing = elapsed === undefined ? null : seconds(elapsed);\n  } else if (error) {\n    trailing =\n      call.error ?? (call.state === \"output-denied\" ? \"Denied\" : \"Failed\");\n  }\n  return (\n    <motion.li\n      animate={{ height: \"auto\", opacity: 1, filter: \"blur(0px)\" }}\n      className=\"list-none\"\n      data-state={running ? \"running\" : call.state}\n      initial={{ height: 0, opacity: 0, filter: \"blur(3px)\" }}\n      transition={{ duration: 0.3, ease: EASE_OUT }}\n    >\n      <div className=\"flex h-8 items-center gap-2 text-[13px]\">\n        <Icon\n          aria-hidden=\"true\"\n          className=\"size-3.5 shrink-0 text-zinc-400 dark:text-zinc-500\"\n        />\n        <span\n          className={cn(\n            \"shrink-0\",\n            running\n              ? \"text-zinc-900 dark:text-zinc-100\"\n              : \"text-zinc-600 dark:text-zinc-400\"\n          )}\n        >\n          {running ? runningLabel(call) : (call.done ?? runningLabel(call))}\n        </span>\n        {call.detail ? (\n          <span className=\"min-w-0 truncate font-mono text-[11.5px] text-zinc-400 dark:text-zinc-500\">\n            {call.detail}\n          </span>\n        ) : null}\n        <span className=\"ml-auto shrink-0 pl-2 text-[12px] tabular-nums\">\n          <AnimatePresence initial={false} mode=\"popLayout\">\n            <motion.span\n              animate={{ opacity: 1, y: 0, filter: \"blur(0px)\" }}\n              className={cn(\n                \"block\",\n                running &&\n                  \"font-mono text-[11.5px] text-zinc-400 dark:text-zinc-500\",\n                !running && error && \"text-rose-600 dark:text-rose-400\",\n                !(running || error) && \"text-zinc-600 dark:text-zinc-300\"\n              )}\n              exit={{ opacity: 0, y: -4, filter: \"blur(2px)\" }}\n              initial={{ opacity: 0, y: 4, filter: \"blur(2px)\" }}\n              key={running ? \"time\" : \"result\"}\n              transition={{ duration: 0.18, ease: EASE_OUT }}\n            >\n              {trailing}\n            </motion.span>\n          </AnimatePresence>\n        </span>\n      </div>\n    </motion.li>\n  );\n}\n\nfunction Spinner() {\n  return (\n    <motion.svg\n      animate={{ rotate: 360 }}\n      aria-hidden=\"true\"\n      className=\"size-3.5 text-zinc-900 dark:text-zinc-100\"\n      fill=\"none\"\n      transition={{\n        duration: 0.6,\n        ease: \"linear\",\n        repeat: Number.POSITIVE_INFINITY,\n      }}\n      viewBox=\"0 0 16 16\"\n    >\n      <circle\n        cx=\"8\"\n        cy=\"8\"\n        opacity=\"0.15\"\n        r=\"6.25\"\n        stroke=\"currentColor\"\n        strokeWidth=\"1.5\"\n      />\n      <path\n        d=\"M8 1.75a6.25 6.25 0 0 1 6.25 6.25\"\n        stroke=\"currentColor\"\n        strokeLinecap=\"round\"\n        strokeWidth=\"1.5\"\n      />\n    </motion.svg>\n  );\n}\n",
      "path": "/components/kokonutui/ai-tool-calls.tsx",
      "target": "components/kokonutui/ai-tool-calls.tsx"
    }
  ]
}