{
  "schemaVersion": 1,
  "target": "react",
  "name": "web-search",
  "version": "0.1.0",
  "category": "ai-elements",
  "title": "Web Search",
  "description": "A live trail of a research agent's web search: queries run and pages opened, joined by a line that extends as steps land, a growing stack of sources, and a working timer, folding into one line when done.",
  "tags": [
    "ai",
    "agent",
    "search",
    "research",
    "sources",
    "trail",
    "timeline",
    "browsing"
  ],
  "requires": {
    "projectTypes": [
      "next",
      "vite-react"
    ],
    "styling": "tailwind-v4"
  },
  "npmDependencies": {
    "@base-ui/react": "^1.9.0"
  },
  "registryDependencies": [
    {
      "name": "agent-state",
      "version": "0.1.0"
    },
    {
      "name": "sources",
      "version": "0.1.0"
    }
  ],
  "docsPath": "/components/web-search",
  "props": [
    {
      "name": "steps",
      "type": "WebSearchStep[]",
      "description": "What the agent did, in order: { id, kind: \"search\", query, results? } or { id, kind: \"page\", title, url, domain?, icon? }, each with an optional status (running, done, failed). Append as steps land."
    },
    {
      "name": "status",
      "type": "\"running\" | \"done\" | \"failed\"",
      "default": "\"running\"",
      "description": "Running shows the working row and timer; done and failed fold the trail into a summary."
    },
    {
      "name": "startedAt",
      "type": "number | string | Date",
      "default": "mount time",
      "description": "When the search started, for the timer."
    },
    {
      "name": "durationMs",
      "type": "number",
      "description": "Total time shown once done. Defaults to the timer's last reading."
    },
    {
      "name": "label",
      "type": "ReactNode",
      "default": "\"Researching\"",
      "description": "Heading while running."
    },
    {
      "name": "workingLabel",
      "type": "string",
      "default": "\"Working\"",
      "description": "Text of the working row at the tail."
    },
    {
      "name": "collapseOnDone",
      "type": "boolean",
      "default": "true",
      "description": "Folds the trail into its summary when the search finishes."
    },
    {
      "name": "defaultOpen",
      "type": "boolean",
      "description": "Opens the trail at first even when the search is done."
    },
    {
      "name": "stackSize",
      "type": "number",
      "default": "5",
      "description": "How many favicons stack in the heading."
    },
    {
      "name": "summarizeWebSearch",
      "type": "(steps) => string",
      "description": "Helper: \"Searched twice, read 3 pages\"."
    }
  ],
  "accessibility": [
    "The heading is a Base UI Collapsible trigger (a button with aria-expanded) that opens and closes the trail at any time.",
    "Steps are an ordered list; page titles are links that open in a new tab and say so to screen readers.",
    "A polite status region announces each step as it lands (\"Searched rate limiter 429, 12 results\", \"Read Rate limits and quotas\") and the summary with its duration when done. The ticking timer is hidden from screen readers.",
    "Status reads in text: Searching, Failed, and result counts, with the red glyph only reinforcing a failure.",
    "With reduced motion rows appear without growing or blurring, the connecting line does not draw, the trail folds instantly, and the working mark is a still frame."
  ],
  "states": [
    "running",
    "step landing",
    "done",
    "collapsed",
    "failed"
  ],
  "files": [
    {
      "path": "agent/web-search.tsx",
      "content": "\"use client\";\n\nimport { Collapsible } from \"@base-ui/react/collapsible\";\nimport { type ReactNode, useEffect, useRef, useState } from \"react\";\nimport { AgentMark } from \"./agent-state\";\nimport { SourceIcon, sourceDomain } from \"./sources\";\n\nfunction cx(...classes: (string | false | null | undefined)[]) {\n  return classes.filter(Boolean).join(\" \");\n}\n\nconst ease = \"ease-[cubic-bezier(0.23,1,0.32,1)]\";\n\nexport type WebSearchStatus = \"running\" | \"done\" | \"failed\";\nexport type WebSearchStepStatus = \"running\" | \"done\" | \"failed\";\n\nexport interface WebSearchQueryStep {\n  id: string;\n  kind: \"search\";\n  /** What the agent searched for. */\n  query: string;\n  /** How many results came back. */\n  results?: number;\n  /** @default \"done\" */\n  status?: WebSearchStepStatus;\n}\n\nexport interface WebSearchPageStep {\n  id: string;\n  kind: \"page\";\n  /** Page title. */\n  title: string;\n  url: string;\n  /** Defaults to the URL's host without `www.`. */\n  domain?: string;\n  /** Favicon URL. Falls back to the domain's initial. */\n  icon?: string;\n  /** @default \"done\" */\n  status?: WebSearchStepStatus;\n}\n\nexport type WebSearchStep = WebSearchQueryStep | WebSearchPageStep;\n\nexport interface WebSearchProps {\n  /** What the agent has done so far, in order. Append steps as they land. */\n  steps: WebSearchStep[];\n  /** running shows the working row and timer; done and failed fold the trail into one line. @default \"running\" */\n  status?: WebSearchStatus;\n  /** When the search started, for the working timer. Defaults to when the component mounted. */\n  startedAt?: number | string | Date;\n  /** Total time, shown once the search is done. Defaults to the timer's last reading. */\n  durationMs?: number;\n  /** Replaces the heading while running. @default \"Researching\" */\n  label?: ReactNode;\n  /** What the working row says. @default \"Working\" */\n  workingLabel?: string;\n  /** Folds the trail into its summary when the search finishes. @default true */\n  collapseOnDone?: boolean;\n  /** Opens the trail at first even when the search is done. */\n  defaultOpen?: boolean;\n  /** How many favicons stack in the heading. @default 5 */\n  stackSize?: number;\n  className?: string;\n}\n\nfunction formatSeconds(ms: number) {\n  return ms < 60_000 ? `${(ms / 1000).toFixed(1)}s` : `${Math.floor(ms / 60_000)}m ${Math.round((ms % 60_000) / 1000)}s`;\n}\n\nfunction plural(count: number, one: string, many: string) {\n  return `${count} ${count === 1 ? one : many}`;\n}\n\n/** \"Searched 3 times, read 5 pages\". */\nexport function summarizeWebSearch(steps: WebSearchStep[]): string {\n  const searches = steps.filter((step) => step.kind === \"search\").length;\n  const pages = steps.filter((step) => step.kind === \"page\").length;\n  const parts: string[] = [];\n  if (searches) parts.push(`Searched ${searches === 1 ? \"once\" : searches === 2 ? \"twice\" : `${searches} times`}`);\n  if (pages) parts.push(`${parts.length ? \"read\" : \"Read\"} ${plural(pages, \"page\", \"pages\")}`);\n  return parts.join(\", \") || \"No searches\";\n}\n\n/**\n * A live trail of what a research agent did on the web: the queries it ran and the pages it\n * opened, joined by a line that extends as each step lands, with a growing stack of source\n * favicons and a working timer at the tail. When the search finishes the trail folds into one line.\n */\nexport function WebSearch({\n  steps,\n  status = \"running\",\n  startedAt,\n  durationMs,\n  label,\n  workingLabel = \"Working\",\n  collapseOnDone = true,\n  defaultOpen,\n  stackSize = 5,\n  className,\n}: WebSearchProps) {\n  const running = status === \"running\";\n  const [open, setOpen] = useState(defaultOpen ?? (running || !collapseOnDone));\n  const started = useRef<number>(startedAt != null ? new Date(startedAt).getTime() : Date.now());\n  const [elapsed, setElapsed] = useState(0);\n  const timerRef = useRef<HTMLSpanElement>(null);\n  const [announcement, setAnnouncement] = useState(\"\");\n  const seen = useRef(new Set(steps.map((step) => step.id)));\n\n  useEffect(() => {\n    if (startedAt != null) started.current = new Date(startedAt).getTime();\n  }, [startedAt]);\n\n  // Fold when the search finishes; open again if it restarts.\n  const previous = useRef(status);\n  useEffect(() => {\n    if (previous.current === status) return;\n    if (status !== \"running\" && collapseOnDone) setOpen(false);\n    if (status === \"running\") setOpen(true);\n    previous.current = status;\n  }, [status, collapseOnDone]);\n\n  // The timer writes straight to the DOM ten times a second instead of re-rendering the trail.\n  useEffect(() => {\n    if (!running) {\n      setElapsed(Date.now() - started.current);\n      return;\n    }\n    const write = () => {\n      const ms = Date.now() - started.current;\n      if (timerRef.current) timerRef.current.textContent = formatSeconds(ms);\n    };\n    write();\n    const interval = setInterval(write, 100);\n    return () => clearInterval(interval);\n  }, [running]);\n\n  // Announce each step as it lands.\n  useEffect(() => {\n    const landed = steps.filter((step) => !seen.current.has(step.id) && (step.status ?? \"done\") !== \"running\");\n    if (!landed.length) return;\n    landed.forEach((step) => seen.current.add(step.id));\n    const last = landed[landed.length - 1]!;\n    setAnnouncement(\n      last.kind === \"search\"\n        ? `Searched ${last.query}${last.results != null ? `, ${plural(last.results, \"result\", \"results\")}` : \"\"}`\n        : `Read ${last.title}`,\n    );\n  }, [steps]);\n\n  const pages = steps.filter((step): step is WebSearchPageStep => step.kind === \"page\");\n  const stack = pages.slice(-stackSize);\n  const total = durationMs ?? elapsed;\n  const heading = running ? (label ?? \"Researching\") : status === \"failed\" ? `Stopped. ${summarizeWebSearch(steps)}` : summarizeWebSearch(steps);\n\n  return (\n    <Collapsible.Root open={open} onOpenChange={setOpen} className={cx(\"w-full text-left\", className)}>\n      <Collapsible.Trigger\n        className={cx(\n          \"group -ml-1.5 flex min-h-8 w-[calc(100%+0.375rem)] cursor-pointer items-center gap-2.5 rounded-lg py-1 pr-2 pl-1.5 text-left text-sm\",\n          \"text-zinc-600 transition-[background-color,color] duration-150 ease-out motion-reduce:transition-none\",\n          \"hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:text-zinc-400 dark:hover:bg-white/[0.06] dark:hover:text-white\",\n          \"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500 focus-visible:outline-solid\",\n        )}\n      >\n        <span aria-hidden=\"true\" className=\"flex h-5 shrink-0 items-center\">\n          {stack.length ? (\n            stack.map((page, index) => (\n              <SourceIcon\n                key={page.id}\n                source={{ title: page.title, url: page.url, domain: page.domain, icon: page.icon }}\n                className={cx(\n                  \"ring-2 ring-white dark:ring-black\",\n                  index > 0 && \"-ml-1.5\",\n                  `transition-[opacity,scale,translate,filter] duration-300 ${ease} motion-reduce:transition-none`,\n                  \"starting:-translate-x-1 starting:scale-75 starting:opacity-0 starting:blur-[2px]\",\n                )}\n              />\n            ))\n          ) : (\n            <span className=\"flex size-5 items-center justify-center rounded-full text-zinc-500 shadow-[inset_0_0_0_1px_rgb(9_9_11/0.1)] dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.16)]\">\n              <SearchGlyph />\n            </span>\n          )}\n        </span>\n        <span\n          key={running ? \"running\" : status}\n          className={cx(\n            \"min-w-0 flex-1 truncate\",\n            running ? \"\" : \"font-medium\",\n            `transition-[opacity,filter] duration-300 ${ease} starting:opacity-0 starting:blur-[2px] motion-reduce:transition-none`,\n          )}\n        >\n          {heading}\n        </span>\n        <span className=\"shrink-0 font-mono text-xs text-zinc-500 tabular-nums\">\n          {running ? plural(pages.length, \"source\", \"sources\") : formatSeconds(total)}\n        </span>\n        <svg\n          aria-hidden=\"true\"\n          viewBox=\"0 0 16 16\"\n          fill=\"none\"\n          className={cx(\n            \"size-4 shrink-0 text-zinc-400 dark:text-zinc-500\",\n            `transition-[rotate,color] duration-200 ${ease} motion-reduce:transition-none`,\n            \"group-hover:text-current group-data-panel-open:rotate-180\",\n          )}\n        >\n          <path d=\"m4.5 6.25 3.5 3.5 3.5-3.5\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n        </svg>\n      </Collapsible.Trigger>\n\n      <Collapsible.Panel\n        className={cx(\n          \"h-(--collapsible-panel-height) overflow-hidden\",\n          `transition-[height,opacity] duration-300 ${ease} motion-reduce:transition-none`,\n          \"data-starting-style:h-0 data-starting-style:opacity-0\",\n          \"data-ending-style:h-0 data-ending-style:opacity-0 data-ending-style:duration-200\",\n        )}\n      >\n        <ol aria-label=\"Search steps\" className=\"pt-2 pb-1\">\n          {steps.map((step, index) => (\n            <Row key={step.id} step={step} last={index === steps.length - 1 && !running} toTail={index === steps.length - 1 && running} />\n          ))}\n          {running ? (\n            <li className={reveal}>\n              <div className=\"min-h-0 overflow-hidden\">\n                <div className=\"flex h-6 items-center gap-2.5\">\n                  <span aria-hidden=\"true\" className=\"flex size-5 shrink-0 items-center justify-center\">\n                    <AgentMark activity=\"searching\" size={14} className=\"text-zinc-950 dark:text-white\" />\n                  </span>\n                  <span className=\"min-w-0 truncate text-sm text-zinc-600 dark:text-zinc-400\">{workingLabel}</span>\n                  <span ref={timerRef} aria-hidden=\"true\" className=\"shrink-0 font-mono text-xs text-zinc-500 tabular-nums\" />\n                </div>\n              </div>\n            </li>\n          ) : null}\n        </ol>\n      </Collapsible.Panel>\n\n      <span role=\"status\" className=\"sr-only\">\n        {running ? announcement : `${heading}, ${formatSeconds(total)}`}\n      </span>\n    </Collapsible.Root>\n  );\n}\n\n// A landed row grows from nothing, lifting out of a light blur; the outer grid animates height.\nconst reveal = cx(\n  \"grid grid-rows-[1fr] opacity-100\",\n  `transition-[grid-template-rows,opacity,filter,translate] duration-400 ${ease} motion-reduce:transition-none`,\n  \"starting:grid-rows-[0fr] starting:translate-y-1 starting:opacity-0 starting:blur-[3px]\",\n);\n\nfunction Row({ step, last, toTail }: { step: WebSearchStep; last: boolean; toTail: boolean }) {\n  const status = step.status ?? \"done\";\n  return (\n    <li className={reveal}>\n      <div className=\"relative min-h-0 overflow-hidden\">\n        <div className=\"flex items-center gap-2.5 pb-2.5\">\n          <span aria-hidden=\"true\" className=\"relative flex size-5 shrink-0 items-center justify-center\">\n            {status === \"failed\" ? (\n              <FailedGlyph />\n            ) : step.kind === \"search\" ? (\n              <span\n                className={cx(\n                  \"flex size-5 items-center justify-center rounded-full shadow-[inset_0_0_0_1px_rgb(9_9_11/0.1)] dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.16)]\",\n                  status === \"running\" ? \"text-zinc-400 dark:text-zinc-500\" : \"text-zinc-600 dark:text-zinc-300\",\n                )}\n              >\n                <SearchGlyph />\n              </span>\n            ) : (\n              <SourceIcon source={{ title: step.title, url: step.url, domain: step.domain, icon: step.icon }} />\n            )}\n          </span>\n          {step.kind === \"search\" ? (\n            <>\n              <span className={cx(\"min-w-0 flex-1 truncate text-sm\", status === \"done\" ? \"text-zinc-950 dark:text-white\" : \"text-zinc-500\")}>\n                {step.query}\n              </span>\n              <span className=\"shrink-0 font-mono text-xs text-zinc-500 tabular-nums\">\n                {status === \"failed\" ? \"Failed\" : status === \"running\" ? \"Searching\" : step.results != null ? plural(step.results, \"result\", \"results\") : null}\n              </span>\n            </>\n          ) : (\n            <>\n              <a\n                href={step.url}\n                target=\"_blank\"\n                rel=\"noreferrer\"\n                className={cx(\n                  \"min-w-0 flex-1 truncate rounded-sm text-sm\",\n                  status === \"done\" ? \"text-zinc-700 hover:text-zinc-950 dark:text-zinc-300 dark:hover:text-white\" : \"text-zinc-500\",\n                  \"decoration-zinc-950/30 underline-offset-2 hover:underline dark:decoration-white/40\",\n                  \"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500 focus-visible:outline-solid\",\n                )}\n              >\n                {step.title}\n                <span className=\"sr-only\"> (opens in a new tab)</span>\n              </a>\n              <span className=\"max-w-[40%] shrink-0 truncate text-xs text-zinc-500\">\n                {status === \"failed\" ? \"Failed\" : (step.domain ?? sourceDomain(step.url))}\n              </span>\n            </>\n          )}\n        </div>\n        {/* The line to the next step draws downward once that step exists; dashed while it leads to work in progress. */}\n        {last ? null : (\n          <span\n            aria-hidden=\"true\"\n            className={cx(\n              \"absolute top-[23px] bottom-[3px] left-[9.5px] w-0 origin-top border-l\",\n              toTail ? \"border-dashed border-zinc-950/20 dark:border-white/25\" : \"border-solid border-zinc-950/15 dark:border-white/20\",\n              `transition-[scale] duration-300 ${ease} starting:scale-y-0 motion-reduce:transition-none`,\n            )}\n          />\n        )}\n      </div>\n    </li>\n  );\n}\n\nfunction SearchGlyph() {\n  return (\n    <svg viewBox=\"0 0 16 16\" fill=\"none\" className=\"size-3\">\n      <circle cx=\"7\" cy=\"7\" r=\"4.25\" stroke=\"currentColor\" strokeWidth=\"1.6\" />\n      <path d=\"m10.25 10.25 3 3\" stroke=\"currentColor\" strokeWidth=\"1.6\" strokeLinecap=\"round\" />\n    </svg>\n  );\n}\n\nfunction FailedGlyph() {\n  return (\n    <svg viewBox=\"0 0 16 16\" fill=\"none\" className=\"size-4 text-red-600 dark:text-red-400\">\n      <circle cx=\"8\" cy=\"8\" r=\"6.25\" stroke=\"currentColor\" strokeWidth=\"1.5\" />\n      <path d=\"m6 6 4 4m0-4-4 4\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" />\n    </svg>\n  );\n}\n"
    }
  ],
  "example": {
    "content": "\"use client\";\n\nimport { type WebSearchStep, WebSearch } from \"@/components/shaken/agent/web-search\";\n\nconst steps: WebSearchStep[] = [\n  { id: \"q1\", kind: \"search\", query: \"postgres uuid v7 vs bigint primary key performance\", results: 9 },\n  { id: \"p1\", kind: \"page\", title: \"UUIDv7 in PostgreSQL 18: what changes for indexes\", url: \"https://www.postgresql.org/docs/18/functions-uuid.html\" },\n  { id: \"p2\", kind: \"page\", title: \"Benchmarking UUIDv7 against bigserial keys\", url: \"https://planetscale.com/blog/the-problem-with-using-a-uuid-primary-key-in-mysql\" },\n  { id: \"q2\", kind: \"search\", query: \"online migration integer id to uuid zero downtime\", results: 14 },\n  { id: \"p3\", kind: \"page\", title: \"Changing primary key types without locking the table\", url: \"https://github.blog/engineering/infrastructure/\" },\n];\n\nconst finished: WebSearchStep[] = [\n  { id: \"a1\", kind: \"search\", query: \"stripe webhook retry idempotency\", results: 11 },\n  { id: \"a2\", kind: \"page\", title: \"Idempotent requests\", url: \"https://docs.stripe.com/api/idempotent_requests\" },\n  { id: \"a3\", kind: \"page\", title: \"Best practices for using webhooks\", url: \"https://docs.stripe.com/webhooks\" },\n  { id: \"a4\", kind: \"search\", query: \"duplicate invoice after webhook timeout\", results: 6 },\n  { id: \"a5\", kind: \"page\", title: \"Handling duplicate events\", url: \"https://hookdeck.com/webhooks/guides/implement-webhook-idempotency\" },\n];\n\nexport default function WebSearchExample() {\n  return (\n    <div className=\"grid w-full max-w-md gap-6\">\n      <WebSearch steps={steps} workingLabel=\"Reading the PostgreSQL docs\" />\n      <WebSearch steps={finished} status=\"done\" durationMs={8400} />\n    </div>\n  );\n}\n"
  }
}
