Skip to content
Shaken UI
Sign in

Web Search

Save

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.

Category
AI elements
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Web Search preview

Why did 6% of API requests fail with 429 on Tuesday?

  1. Working

Installation

npx @shakenui/cli add web-search

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add web-search --dry-run

Usage

web-search-example.tsx
"use client";

import { type WebSearchStep, WebSearch } from "@/components/shaken/agent/web-search";

const steps: WebSearchStep[] = [
  { id: "q1", kind: "search", query: "postgres uuid v7 vs bigint primary key performance", results: 9 },
  { id: "p1", kind: "page", title: "UUIDv7 in PostgreSQL 18: what changes for indexes", url: "https://www.postgresql.org/docs/18/functions-uuid.html" },
  { 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" },
  { id: "q2", kind: "search", query: "online migration integer id to uuid zero downtime", results: 14 },
  { id: "p3", kind: "page", title: "Changing primary key types without locking the table", url: "https://github.blog/engineering/infrastructure/" },
];

const finished: WebSearchStep[] = [
  { id: "a1", kind: "search", query: "stripe webhook retry idempotency", results: 11 },
  { id: "a2", kind: "page", title: "Idempotent requests", url: "https://docs.stripe.com/api/idempotent_requests" },
  { id: "a3", kind: "page", title: "Best practices for using webhooks", url: "https://docs.stripe.com/webhooks" },
  { id: "a4", kind: "search", query: "duplicate invoice after webhook timeout", results: 6 },
  { id: "a5", kind: "page", title: "Handling duplicate events", url: "https://hookdeck.com/webhooks/guides/implement-webhook-idempotency" },
];

export default function WebSearchExample() {
  return (
    <div className="grid w-full max-w-md gap-6">
      <WebSearch steps={steps} workingLabel="Reading the PostgreSQL docs" />
      <WebSearch steps={finished} status="done" durationMs={8400} />
    </div>
  );
}

API

PropTypeDefaultDescription
stepsWebSearchStep[]—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.
status"running" | "done" | "failed""running"Running shows the working row and timer; done and failed fold the trail into a summary.
startedAtnumber | string | Datemount timeWhen the search started, for the timer.
durationMsnumber—Total time shown once done. Defaults to the timer's last reading.
labelReactNode"Researching"Heading while running.
workingLabelstring"Working"Text of the working row at the tail.
collapseOnDonebooleantrueFolds the trail into its summary when the search finishes.
defaultOpenboolean—Opens the trail at first even when the search is done.
stackSizenumber5How many favicons stack in the heading.
summarizeWebSearch(steps) => string—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.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/agent/web-search.tsxweb-search
  • Also installs agent-state@0.1.0registry dependency
  • Also installs sources@0.1.0registry dependency
  • npm packages: @base-ui/react@^1.9.0React and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/web-search/0.1.0.json.

agent/web-search.tsxShow
agent/web-search.tsx
"use client";

import { Collapsible } from "@base-ui/react/collapsible";
import { type ReactNode, useEffect, useRef, useState } from "react";
import { AgentMark } from "./agent-state";
import { SourceIcon, sourceDomain } from "./sources";

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

const ease = "ease-[cubic-bezier(0.23,1,0.32,1)]";

export type WebSearchStatus = "running" | "done" | "failed";
export type WebSearchStepStatus = "running" | "done" | "failed";

export interface WebSearchQueryStep {
  id: string;
  kind: "search";
  /** What the agent searched for. */
  query: string;
  /** How many results came back. */
  results?: number;
  /** @default "done" */
  status?: WebSearchStepStatus;
}

export interface WebSearchPageStep {
  id: string;
  kind: "page";
  /** Page title. */
  title: string;
  url: string;
  /** Defaults to the URL's host without `www.`. */
  domain?: string;
  /** Favicon URL. Falls back to the domain's initial. */
  icon?: string;
  /** @default "done" */
  status?: WebSearchStepStatus;
}

export type WebSearchStep = WebSearchQueryStep | WebSearchPageStep;

export interface WebSearchProps {
  /** What the agent has done so far, in order. Append steps as they land. */
  steps: WebSearchStep[];
  /** running shows the working row and timer; done and failed fold the trail into one line. @default "running" */
  status?: WebSearchStatus;
  /** When the search started, for the working timer. Defaults to when the component mounted. */
  startedAt?: number | string | Date;
  /** Total time, shown once the search is done. Defaults to the timer's last reading. */
  durationMs?: number;
  /** Replaces the heading while running. @default "Researching" */
  label?: ReactNode;
  /** What the working row says. @default "Working" */
  workingLabel?: string;
  /** Folds the trail into its summary when the search finishes. @default true */
  collapseOnDone?: boolean;
  /** Opens the trail at first even when the search is done. */
  defaultOpen?: boolean;
  /** How many favicons stack in the heading. @default 5 */
  stackSize?: number;
  className?: string;
}

function formatSeconds(ms: number) {
  return ms < 60_000 ? `${(ms / 1000).toFixed(1)}s` : `${Math.floor(ms / 60_000)}m ${Math.round((ms % 60_000) / 1000)}s`;
}

function plural(count: number, one: string, many: string) {
  return `${count} ${count === 1 ? one : many}`;
}

/** "Searched 3 times, read 5 pages". */
export function summarizeWebSearch(steps: WebSearchStep[]): string {
  const searches = steps.filter((step) => step.kind === "search").length;
  const pages = steps.filter((step) => step.kind === "page").length;
  const parts: string[] = [];
  if (searches) parts.push(`Searched ${searches === 1 ? "once" : searches === 2 ? "twice" : `${searches} times`}`);
  if (pages) parts.push(`${parts.length ? "read" : "Read"} ${plural(pages, "page", "pages")}`);
  return parts.join(", ") || "No searches";
}

/**
 * A live trail of what a research agent did on the web: the queries it ran and the pages it
 * opened, joined by a line that extends as each step lands, with a growing stack of source
 * favicons and a working timer at the tail. When the search finishes the trail folds into one line.
 */
export function WebSearch({
  steps,
  status = "running",
  startedAt,
  durationMs,
  label,
  workingLabel = "Working",
  collapseOnDone = true,
  defaultOpen,
  stackSize = 5,
  className,
}: WebSearchProps) {
  const running = status === "running";
  const [open, setOpen] = useState(defaultOpen ?? (running || !collapseOnDone));
  const started = useRef<number>(startedAt != null ? new Date(startedAt).getTime() : Date.now());
  const [elapsed, setElapsed] = useState(0);
  const timerRef = useRef<HTMLSpanElement>(null);
  const [announcement, setAnnouncement] = useState("");
  const seen = useRef(new Set(steps.map((step) => step.id)));

  useEffect(() => {
    if (startedAt != null) started.current = new Date(startedAt).getTime();
  }, [startedAt]);

  // Fold when the search finishes; open again if it restarts.
  const previous = useRef(status);
  useEffect(() => {
    if (previous.current === status) return;
    if (status !== "running" && collapseOnDone) setOpen(false);
    if (status === "running") setOpen(true);
    previous.current = status;
  }, [status, collapseOnDone]);

  // The timer writes straight to the DOM ten times a second instead of re-rendering the trail.
  useEffect(() => {
    if (!running) {
      setElapsed(Date.now() - started.current);
      return;
    }
    const write = () => {
      const ms = Date.now() - started.current;
      if (timerRef.current) timerRef.current.textContent = formatSeconds(ms);
    };
    write();
    const interval = setInterval(write, 100);
    return () => clearInterval(interval);
  }, [running]);

  // Announce each step as it lands.
  useEffect(() => {
    const landed = steps.filter((step) => !seen.current.has(step.id) && (step.status ?? "done") !== "running");
    if (!landed.length) return;
    landed.forEach((step) => seen.current.add(step.id));
    const last = landed[landed.length - 1]!;
    setAnnouncement(
      last.kind === "search"
        ? `Searched ${last.query}${last.results != null ? `, ${plural(last.results, "result", "results")}` : ""}`
        : `Read ${last.title}`,
    );
  }, [steps]);

  const pages = steps.filter((step): step is WebSearchPageStep => step.kind === "page");
  const stack = pages.slice(-stackSize);
  const total = durationMs ?? elapsed;
  const heading = running ? (label ?? "Researching") : status === "failed" ? `Stopped. ${summarizeWebSearch(steps)}` : summarizeWebSearch(steps);

  return (
    <Collapsible.Root open={open} onOpenChange={setOpen} className={cx("w-full text-left", className)}>
      <Collapsible.Trigger
        className={cx(
          "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",
          "text-zinc-600 transition-[background-color,color] duration-150 ease-out motion-reduce:transition-none",
          "hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:text-zinc-400 dark:hover:bg-white/[0.06] dark:hover:text-white",
          "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500 focus-visible:outline-solid",
        )}
      >
        <span aria-hidden="true" className="flex h-5 shrink-0 items-center">
          {stack.length ? (
            stack.map((page, index) => (
              <SourceIcon
                key={page.id}
                source={{ title: page.title, url: page.url, domain: page.domain, icon: page.icon }}
                className={cx(
                  "ring-2 ring-white dark:ring-black",
                  index > 0 && "-ml-1.5",
                  `transition-[opacity,scale,translate,filter] duration-300 ${ease} motion-reduce:transition-none`,
                  "starting:-translate-x-1 starting:scale-75 starting:opacity-0 starting:blur-[2px]",
                )}
              />
            ))
          ) : (
            <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)]">
              <SearchGlyph />
            </span>
          )}
        </span>
        <span
          key={running ? "running" : status}
          className={cx(
            "min-w-0 flex-1 truncate",
            running ? "" : "font-medium",
            `transition-[opacity,filter] duration-300 ${ease} starting:opacity-0 starting:blur-[2px] motion-reduce:transition-none`,
          )}
        >
          {heading}
        </span>
        <span className="shrink-0 font-mono text-xs text-zinc-500 tabular-nums">
          {running ? plural(pages.length, "source", "sources") : formatSeconds(total)}
        </span>
        <svg
          aria-hidden="true"
          viewBox="0 0 16 16"
          fill="none"
          className={cx(
            "size-4 shrink-0 text-zinc-400 dark:text-zinc-500",
            `transition-[rotate,color] duration-200 ${ease} motion-reduce:transition-none`,
            "group-hover:text-current group-data-panel-open:rotate-180",
          )}
        >
          <path d="m4.5 6.25 3.5 3.5 3.5-3.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </Collapsible.Trigger>

      <Collapsible.Panel
        className={cx(
          "h-(--collapsible-panel-height) overflow-hidden",
          `transition-[height,opacity] duration-300 ${ease} motion-reduce:transition-none`,
          "data-starting-style:h-0 data-starting-style:opacity-0",
          "data-ending-style:h-0 data-ending-style:opacity-0 data-ending-style:duration-200",
        )}
      >
        <ol aria-label="Search steps" className="pt-2 pb-1">
          {steps.map((step, index) => (
            <Row key={step.id} step={step} last={index === steps.length - 1 && !running} toTail={index === steps.length - 1 && running} />
          ))}
          {running ? (
            <li className={reveal}>
              <div className="min-h-0 overflow-hidden">
                <div className="flex h-6 items-center gap-2.5">
                  <span aria-hidden="true" className="flex size-5 shrink-0 items-center justify-center">
                    <AgentMark activity="searching" size={14} className="text-zinc-950 dark:text-white" />
                  </span>
                  <span className="min-w-0 truncate text-sm text-zinc-600 dark:text-zinc-400">{workingLabel}</span>
                  <span ref={timerRef} aria-hidden="true" className="shrink-0 font-mono text-xs text-zinc-500 tabular-nums" />
                </div>
              </div>
            </li>
          ) : null}
        </ol>
      </Collapsible.Panel>

      <span role="status" className="sr-only">
        {running ? announcement : `${heading}, ${formatSeconds(total)}`}
      </span>
    </Collapsible.Root>
  );
}

// A landed row grows from nothing, lifting out of a light blur; the outer grid animates height.
const reveal = cx(
  "grid grid-rows-[1fr] opacity-100",
  `transition-[grid-template-rows,opacity,filter,translate] duration-400 ${ease} motion-reduce:transition-none`,
  "starting:grid-rows-[0fr] starting:translate-y-1 starting:opacity-0 starting:blur-[3px]",
);

function Row({ step, last, toTail }: { step: WebSearchStep; last: boolean; toTail: boolean }) {
  const status = step.status ?? "done";
  return (
    <li className={reveal}>
      <div className="relative min-h-0 overflow-hidden">
        <div className="flex items-center gap-2.5 pb-2.5">
          <span aria-hidden="true" className="relative flex size-5 shrink-0 items-center justify-center">
            {status === "failed" ? (
              <FailedGlyph />
            ) : step.kind === "search" ? (
              <span
                className={cx(
                  "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)]",
                  status === "running" ? "text-zinc-400 dark:text-zinc-500" : "text-zinc-600 dark:text-zinc-300",
                )}
              >
                <SearchGlyph />
              </span>
            ) : (
              <SourceIcon source={{ title: step.title, url: step.url, domain: step.domain, icon: step.icon }} />
            )}
          </span>
          {step.kind === "search" ? (
            <>
              <span className={cx("min-w-0 flex-1 truncate text-sm", status === "done" ? "text-zinc-950 dark:text-white" : "text-zinc-500")}>
                {step.query}
              </span>
              <span className="shrink-0 font-mono text-xs text-zinc-500 tabular-nums">
                {status === "failed" ? "Failed" : status === "running" ? "Searching" : step.results != null ? plural(step.results, "result", "results") : null}
              </span>
            </>
          ) : (
            <>
              <a
                href={step.url}
                target="_blank"
                rel="noreferrer"
                className={cx(
                  "min-w-0 flex-1 truncate rounded-sm text-sm",
                  status === "done" ? "text-zinc-700 hover:text-zinc-950 dark:text-zinc-300 dark:hover:text-white" : "text-zinc-500",
                  "decoration-zinc-950/30 underline-offset-2 hover:underline dark:decoration-white/40",
                  "focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500 focus-visible:outline-solid",
                )}
              >
                {step.title}
                <span className="sr-only"> (opens in a new tab)</span>
              </a>
              <span className="max-w-[40%] shrink-0 truncate text-xs text-zinc-500">
                {status === "failed" ? "Failed" : (step.domain ?? sourceDomain(step.url))}
              </span>
            </>
          )}
        </div>
        {/* The line to the next step draws downward once that step exists; dashed while it leads to work in progress. */}
        {last ? null : (
          <span
            aria-hidden="true"
            className={cx(
              "absolute top-[23px] bottom-[3px] left-[9.5px] w-0 origin-top border-l",
              toTail ? "border-dashed border-zinc-950/20 dark:border-white/25" : "border-solid border-zinc-950/15 dark:border-white/20",
              `transition-[scale] duration-300 ${ease} starting:scale-y-0 motion-reduce:transition-none`,
            )}
          />
        )}
      </div>
    </li>
  );
}

function SearchGlyph() {
  return (
    <svg viewBox="0 0 16 16" fill="none" className="size-3">
      <circle cx="7" cy="7" r="4.25" stroke="currentColor" strokeWidth="1.6" />
      <path d="m10.25 10.25 3 3" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
    </svg>
  );
}

function FailedGlyph() {
  return (
    <svg viewBox="0 0 16 16" fill="none" className="size-4 text-red-600 dark:text-red-400">
      <circle cx="8" cy="8" r="6.25" stroke="currentColor" strokeWidth="1.5" />
      <path d="m6 6 4 4m0-4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
    </svg>
  );
}