# AI search composer

> Grounded AI search bar with a tool switcher, run-limit indicators, active tool pill, live source reading trace and cited summary.

- Kind: block · Category: AI · Interactivity: script
- Install: `npx shadcn@latest add @haze/ai-input-search`
- File: `src/components/haze/blocks/ai-input-search.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/blocks/ai-input-search

## Use when
- Offering an AI answer bar that shows which live sources are being read before summarizing
- Letting users toggle specialized search tools with visible quota dot indicators
- Pairing a prompt input with clickable citation cards and a stoppable search trace

## Avoid when
- You need instant local keyword filtering across static workspace records; use ai-search-bar instead
- You do not need source verification or tool selection; use ai-prompt instead

## Alternatives
- [ai-search-bar](https://hazeui.com/blocks/ai-search-bar.md)
- [ai-prompt](https://hazeui.com/blocks/ai-prompt.md)
- [ai-citations](https://hazeui.com/blocks/ai-citations.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` | "haze-ai-input-search" | no | Unique prefix for form labels and tool menu controls. |
| heading | `string` | "Answers with links you can check" | no | Header hint shown in the outer search tray. |
| placeholder | `string` | "Look something up" | no | Placeholder text inside the search textarea. |
| initialQuery | `string` | "" | no | Optional pre-filled query inside the search box. |
| tools | `{ id: string; label: string; description: string; remaining: number; limit: number }[]` | 5 demo tools | no | Tools displayed in the Change / menu with quota dots. |
| models | `string[]` | ["Sonnet 5.5", "Opus 5.5", "Flash 4.0"] | no | Model options available in the toolbar selector. |
| sources | `{ initials: string; title: string; domain: string; href: string; snippet: string }[]` | 4 demo sources | no | Source entries stacked during the live trace and linked below. |
| class | `string` |  | no | Extra classes on the outer section. |

## Accessibility
- The tool switcher exposes aria-expanded and aria-controls, while run-limit dot rows carry readable aria-label quota counts.
- Tool changes, file attachments, source reading progress and stop actions announce via a polite role="status" region.
- Key Tab: Move across the Change / menu trigger, active tool pill, query field, controls and citation links
- Key Enter / Space: Toggle the tool menu, choose a tool, remove pills, attach files or start and stop a search

## Agent prompts

### Install and use

Install the Haze UI block "AI search composer" with `npx shadcn@latest add @haze/ai-input-search`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import AiInputSearch from "@/components/haze/blocks/ai-input-search.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/blocks/ai-input-search.md

### Customize with real content

Adapt the Haze ai-input-search block for our product. Replace the demo values of these props with our real content: id, heading, placeholder, initialQuery, tools, models, sources, class. Keep the layout, the heading level rules and these accessibility details: The tool switcher exposes aria-expanded and aria-controls, while run-limit dot rows carry readable aria-label quota counts. Tool changes, file attachments, source reading progress and stop actions announce via a polite role="status" region. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using ai-input-search, check it fits: use it when offering an ai answer bar that shows which live sources are being read before summarizing; letting users toggle specialized search tools with visible quota dot indicators; pairing a prompt input with clickable citation cards and a stoppable search trace. Avoid it when you need instant local keyword filtering across static workspace records; use ai-search-bar instead; you do not need source verification or tool selection; use ai-prompt instead. Alternatives: @haze/ai-search-bar, @haze/ai-prompt, @haze/ai-citations.

## Example requests that should lead here
- Create an AI search composer with a tool picker, active tool pill, model selector and live source reading trace
- Add a grounded answer prompt box that stacks source avatars one by one before showing clickable citation links

## Source

```astro
---
import {
  ArrowUpRight,
  Brain,
  Check,
  ChevronDown,
  Code,
  Compass,
  CornerDownLeft,
  Globe,
  PenLine,
  Plus,
  Square,
  X,
} from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface SearchTool {
  id: string;
  label: string;
  description: string;
  remaining: number;
  limit: number;
}

interface GroundedSource {
  initials: string;
  title: string;
  domain: string;
  href: string;
  snippet: string;
}

interface Props {
  id?: string;
  heading?: string;
  placeholder?: string;
  initialQuery?: string;
  tools?: SearchTool[];
  models?: string[];
  sources?: GroundedSource[];
  class?: string;
}

const {
  id = "haze-ai-input-search",
  heading = "Answers with links you can check",
  placeholder = "Look something up",
  initialQuery = "",
  tools = [
    { id: "browse", label: "Browse sources", description: "Fetch and cite live documentation", remaining: 4, limit: 5 },
    { id: "investigate", label: "Investigate", description: "Multi-step deep link verification", remaining: 3, limit: 5 },
    { id: "draft", label: "Draft", description: "Write structured memos with references", remaining: 5, limit: 5 },
    { id: "code", label: "Run code", description: "Execute snippets to confirm metrics", remaining: 2, limit: 5 },
    { id: "reason", label: "Reason", description: "Extended analytical decomposition", remaining: 3, limit: 5 },
  ],
  models = ["Sonnet 5.5", "Opus 5.5", "Flash 4.0"],
  sources = [
    {
      initials: "ED",
      title: "Edge Cache-Control and Stale-While-Revalidate Patterns",
      domain: "docs.edgegrid.example",
      href: "#source-edge-cache",
      snippet: "Pairing 60s s-maxage with a 300s stale-while-revalidate window cuts origin load by 74%.",
    },
    {
      initials: "CL",
      title: "Multi-Region Read Replicas and Cache Invalidation",
      domain: "engineering.cloudloom.example",
      href: "#source-read-replicas",
      snippet: "Tag-based surrogate purges converge across global PoPs in under 250ms.",
    },
    {
      initials: "RF",
      title: "HTTP Caching Semantics for Dynamic JSON Endpoints",
      domain: "specs.rfcnotes.example",
      href: "#source-http-caching",
      snippet: "Use Vary headers narrowly on authorization and locale to preserve cache hit ratio.",
    },
    {
      initials: "AP",
      title: "P99 Tail Latency Benchmarks at Regional Gateways",
      domain: "bench.apipulse.example",
      href: "#source-tail-latency",
      snippet: "Tiered shielding absorbs regional cold starts without spiking database connections.",
    },
  ],
  class: className,
} = Astro.props;

const activeDefaultTool = tools[0] ?? {
  id: "browse",
  label: "Browse sources",
  description: "Fetch and cite live documentation",
  remaining: 4,
  limit: 5,
};
const defaultModel = models[0] ?? "Sonnet 5.5";
---

<section
  aria-labelledby={`${id}-title`}
  data-haze-ai-input-search
  data-sources={JSON.stringify(sources)}
  class={cn("bg-background px-4 py-10 sm:px-6 sm:py-14", className)}
>
  <h2 id={`${id}-title`} class="sr-only">{heading}</h2>

  <div class="mx-auto max-w-xl space-y-3">
    <div class="rounded-2xl border border-border bg-muted/40 p-1.5 shadow-lift transition-[color,background-color,border-color,box-shadow] duration-150 ease-snappy has-[:is(input,textarea):focus-visible]:border-ring has-[:is(input,textarea):focus-visible]:ring-3 has-[:is(input,textarea):focus-visible]:ring-ring/24">
      <div class="flex flex-wrap items-center justify-between gap-2 px-3 py-1.5">
        <div class="flex min-w-0 items-center gap-2">
          <Globe class="size-4 shrink-0 text-muted-foreground" aria-hidden="true" />
          <p class="wrap-anywhere text-sm/5 text-muted-foreground">{heading}</p>
        </div>

        <button
          type="button"
          data-ais-tools-toggle
          aria-expanded="false"
          aria-controls={`${id}-tools-menu`}
          class="inline-flex min-h-8 shrink-0 cursor-pointer items-center gap-1.5 rounded-lg border border-frame bg-field px-2.5 py-1 text-xs font-medium text-foreground shadow-key transition-colors duration-150 ease-snappy hover:border-frame-strong hover:bg-accent aria-expanded:border-frame-strong aria-expanded:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
        >
          <span>Change</span>
          <kbd class="rounded-sm border border-frame bg-muted/60 px-1.5 py-0.5 font-mono text-[0.6875rem]/3 text-muted-foreground">/</kbd>
        </button>
      </div>

      <form
        data-ais-form
        class="rounded-xl border border-border bg-card p-3.5 shadow-key"
      >
        <div data-ais-files hidden class="mb-2 flex flex-wrap items-center gap-1.5"></div>

        <label for={`${id}-query`} class="sr-only">Search question</label>
        <textarea
          id={`${id}-query`}
          data-ais-input
          rows="2"
          placeholder={placeholder}
          class="max-h-40 w-full resize-none bg-transparent px-1 py-0.5 text-[0.9375rem]/6 text-foreground placeholder:text-muted-foreground outline-hidden"
        >{initialQuery}</textarea>

        <div
          id={`${id}-tools-menu`}
          data-ais-tools-panel
          hidden
          class="mt-2.5 rounded-xl border border-border bg-popover p-1.5 shadow-float"
        >
          <p class="px-2.5 py-1 text-xs font-medium text-muted-foreground">Tools</p>
          <ul role="list" class="grid gap-0.5">
            {
              tools.map((tool) => (
                <li>
                  <button
                    type="button"
                    data-ais-tool-pick={tool.id}
                    data-ais-tool-label={tool.label}
                    aria-pressed={tool.id === activeDefaultTool.id ? "true" : "false"}
                    class={cn(
                      "flex w-full cursor-pointer items-center justify-between gap-3 rounded-lg px-2.5 py-2 text-left transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring",
                      tool.id === activeDefaultTool.id && "bg-accent/60"
                    )}
                  >
                    <span class="flex min-w-0 items-center gap-2.5">
                      <span class="grid size-7 shrink-0 place-items-center rounded-md border border-frame bg-field text-muted-foreground" aria-hidden="true">
                        {tool.id === "browse" && <Globe class="size-3.5 text-muted-foreground" />}
                        {tool.id === "investigate" && <Compass class="size-3.5" />}
                        {tool.id === "draft" && <PenLine class="size-3.5" />}
                        {tool.id === "code" && <Code class="size-3.5" />}
                        {tool.id === "reason" && <Brain class="size-3.5" />}
                      </span>
                      <span class="min-w-0">
                        <span class="block text-sm/5 font-medium text-foreground">{tool.label}</span>
                        <span class="block truncate text-xs/4 text-muted-foreground">{tool.description}</span>
                      </span>
                    </span>
                    <span class="flex shrink-0 items-center gap-1" aria-label={`${tool.remaining} of ${tool.limit} runs remaining`}>
                      {Array.from({ length: tool.limit }).map((_, idx) => (
                        <span
                          aria-hidden="true"
                          class={cn(
                            "size-1.5 rounded-full",
                            idx < tool.remaining ? "bg-foreground" : "bg-muted-foreground/30"
                          )}
                        />
                      ))}
                    </span>
                  </button>
                </li>
              ))
            }
          </ul>
        </div>

        <div
          id={`${id}-model-menu`}
          data-ais-model-panel
          hidden
          class="mt-2.5 rounded-xl border border-border bg-popover p-1.5 shadow-float"
        >
          <ul role="list" class="grid gap-0.5">
            {
              models.map((m) => (
                <li>
                  <button
                    type="button"
                    data-ais-model-option={m}
                    aria-pressed={m === defaultModel ? "true" : "false"}
                    class={cn(
                      "flex w-full cursor-pointer items-center justify-between gap-3 rounded-lg px-3 py-2 text-left text-sm/5 transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring",
                      m === defaultModel && "bg-accent/60 font-medium text-foreground"
                    )}
                  >
                    <span>{m}</span>
                    <Check
                      data-ais-model-check
                      class={cn("size-4 shrink-0 text-foreground", m !== defaultModel && "opacity-0")}
                      aria-hidden="true"
                    />
                  </button>
                </li>
              ))
            }
          </ul>
        </div>

        <div class="mt-3 flex flex-wrap items-center justify-between gap-2 pt-1">
          <div class="flex flex-wrap items-center gap-1.5">
            <button
              type="button"
              data-ais-attach
              aria-label="Attach file"
              class="inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-full border border-border bg-transparent text-muted-foreground transition-colors duration-150 ease-snappy hover:border-border-strong hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-95 active:duration-75"
            >
              <Plus class="size-4" aria-hidden="true" />
            </button>

            <div data-ais-active-wrap class="inline-flex min-w-0 items-center gap-0.5">
              <button
                type="button"
                data-ais-tool-trigger
                aria-expanded="false"
                aria-controls={`${id}-tools-menu`}
                class="inline-flex min-h-8 max-w-full cursor-pointer items-center gap-1.5 rounded-lg px-2 py-1 text-sm font-medium text-foreground transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring"
              >
                <Globe class="size-4 shrink-0 text-muted-foreground" aria-hidden="true" />
                <span data-ais-active-text class="truncate">{activeDefaultTool.label}</span>
                <ChevronDown class="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
              </button>

              <button
                type="button"
                data-ais-clear-tool
                aria-label={`Remove ${activeDefaultTool.label} tool`}
                class="inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-full text-muted-foreground transition-colors duration-150 ease-snappy hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring"
              >
                <X class="size-3.5" aria-hidden="true" />
              </button>
            </div>
          </div>

          <div class="flex shrink-0 items-center gap-1.5">
            <button
              type="button"
              data-ais-model-toggle
              aria-expanded="false"
              aria-controls={`${id}-model-menu`}
              class="inline-flex min-h-8 cursor-pointer items-center gap-1 rounded-lg px-2 py-1 text-sm text-muted-foreground transition-colors duration-150 ease-snappy hover:bg-accent hover:text-foreground aria-expanded:bg-accent aria-expanded:text-foreground focus-visible:outline-2 focus-visible:outline-ring"
            >
              <span data-ais-model-label>{defaultModel}</span>
              <ChevronDown class="size-3.5" aria-hidden="true" />
            </button>

            <button
              type="submit"
              data-ais-ask
              class="inline-flex min-h-8 cursor-pointer items-center gap-1.5 rounded-full bg-muted px-3.5 text-sm font-medium text-muted-foreground transition-[background-color,color,opacity,scale] duration-150 ease-snappy hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-[0.97] active:duration-75"
            >
              <span>Ask</span>
              <CornerDownLeft class="size-3.5" aria-hidden="true" />
            </button>

            <button
              type="button"
              data-ais-stop
              hidden
              class="inline-flex min-h-8 cursor-pointer items-center gap-1.5 rounded-full bg-primary px-3.5 text-sm font-medium text-primary-foreground transition-[opacity,scale] duration-150 ease-snappy hover:opacity-90 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-[0.97] active:duration-75"
            >
              <Square class="size-3 fill-current" aria-hidden="true" />
              <span>Stop</span>
            </button>
          </div>
        </div>
      </form>
    </div>

    <div
      data-ais-trace
      hidden
      class="rounded-2xl border border-border bg-card p-4 shadow-key"
    >
      <div class="flex flex-wrap items-center justify-between gap-2">
        <div class="flex min-w-0 items-center gap-2.5">
          <div data-ais-avatars class="flex shrink-0 -space-x-1.5"></div>
          <p data-ais-trace-label class="wrap-anywhere text-sm/5 font-medium text-foreground">
            Reading sources…
          </p>
        </div>
        <span
          data-ais-trace-badge
          class="rounded-full border border-frame bg-muted px-2.5 py-0.5 text-xs font-medium text-foreground"
        >
          Searching
        </span>
      </div>

      <ul data-ais-steps role="list" class="mt-3 grid gap-1.5"></ul>

      <div data-ais-answer hidden class="mt-4 border-t border-border pt-3.5">
        <p data-ais-answer-body class="text-sm/6 text-pretty text-foreground"></p>

        <div data-ais-links class="mt-3 grid gap-2 sm:grid-cols-2">
          {
            sources.map((src) => (
              <a
                href={src.href}
                data-ais-source-link={src.title}
                class="group flex min-w-0 items-start justify-between gap-2 rounded-xl border border-border bg-muted/20 p-2.5 transition-colors duration-150 ease-snappy hover:border-border-strong hover:bg-accent/50 focus-visible:outline-2 focus-visible:outline-ring"
              >
                <span class="min-w-0">
                  <span class="block wrap-anywhere text-xs/4 font-medium text-foreground">{src.title}</span>
                  <span class="mt-0.5 block truncate font-mono text-[0.6875rem]/4 text-muted-foreground">{src.domain}</span>
                </span>
                <ArrowUpRight class="size-3.5 shrink-0 text-muted-foreground transition-colors duration-150 group-hover:text-muted-foreground" aria-hidden="true" />
              </a>
            ))
          }
        </div>
      </div>
    </div>

    <p data-ais-status role="status" class="sr-only"></p>
  </div>
</section>

<script>
  interface SourceItem {
    initials: string;
    title: string;
    domain: string;
    href: string;
    snippet: string;
  }

  function initAiInputSearch() {
    document.querySelectorAll<HTMLElement>("[data-haze-ai-input-search]").forEach((root) => {
      if (root.hasAttribute("data-enhanced")) return;
      root.setAttribute("data-enhanced", "");

      const toolsToggle = root.querySelector<HTMLButtonElement>("[data-ais-tools-toggle]");
      const toolTrigger = root.querySelector<HTMLButtonElement>("[data-ais-tool-trigger]");
      const toolsPanel = root.querySelector<HTMLElement>("[data-ais-tools-panel]");
      const modelToggle = root.querySelector<HTMLButtonElement>("[data-ais-model-toggle]");
      const modelPanel = root.querySelector<HTMLElement>("[data-ais-model-panel]");
      const modelLabel = root.querySelector<HTMLElement>("[data-ais-model-label]");
      const activeWrap = root.querySelector<HTMLElement>("[data-ais-active-wrap]");
      const activeText = root.querySelector<HTMLElement>("[data-ais-active-text]");
      const clearToolBtn = root.querySelector<HTMLButtonElement>("[data-ais-clear-tool]");
      const filesWrap = root.querySelector<HTMLElement>("[data-ais-files]");
      const attachBtn = root.querySelector<HTMLButtonElement>("[data-ais-attach]");
      const form = root.querySelector<HTMLFormElement>("[data-ais-form]");
      const input = root.querySelector<HTMLTextAreaElement>("[data-ais-input]");
      const askBtn = root.querySelector<HTMLButtonElement>("[data-ais-ask]");
      const stopBtn = root.querySelector<HTMLButtonElement>("[data-ais-stop]");
      const traceBox = root.querySelector<HTMLElement>("[data-ais-trace]");
      const avatars = root.querySelector<HTMLElement>("[data-ais-avatars]");
      const traceLabel = root.querySelector<HTMLElement>("[data-ais-trace-label]");
      const traceBadge = root.querySelector<HTMLElement>("[data-ais-trace-badge]");
      const stepsList = root.querySelector<HTMLElement>("[data-ais-steps]");
      const answerWrap = root.querySelector<HTMLElement>("[data-ais-answer]");
      const answerBody = root.querySelector<HTMLElement>("[data-ais-answer-body]");
      const status = root.querySelector<HTMLElement>("[data-ais-status]");

      let parsedSources: SourceItem[] = [];
      try {
        parsedSources = JSON.parse(root.dataset.sources ?? "[]") as SourceItem[];
      } catch {
        parsedSources = [];
      }

      const demoAttachments = ["api-gateway.yaml", "cdn-metrics.csv", "slo-budget.md"];
      const fallbackQuery = "Compare edge caching TTL strategies for multi-region APIs";
      let attachIdx = 0;
      let activeToolLabel = activeText?.textContent?.trim() ?? "Browse sources";
      let currentModel = modelLabel?.textContent?.trim() ?? "Sonnet 5.5";
      let stepTimer: number | undefined;
      const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

      const announce = (msg: string) => {
        if (status) status.textContent = msg;
      };

      const syncAskButton = () => {
        if (!askBtn || !input) return;
        const hasText = input.value.trim().length > 0;
        askBtn.classList.toggle("bg-primary", hasText);
        askBtn.classList.toggle("text-primary-foreground", hasText);
        askBtn.classList.toggle("bg-muted", !hasText);
        askBtn.classList.toggle("text-muted-foreground", !hasText);
      };

      const setToolsOpen = (open: boolean) => {
        if (toolsPanel) toolsPanel.hidden = !open;
        toolsToggle?.setAttribute("aria-expanded", String(open));
        toolTrigger?.setAttribute("aria-expanded", String(open));
        if (open && modelPanel) {
          modelPanel.hidden = true;
          modelToggle?.setAttribute("aria-expanded", "false");
        }
      };

      const setModelOpen = (open: boolean) => {
        if (modelPanel) modelPanel.hidden = !open;
        modelToggle?.setAttribute("aria-expanded", String(open));
        if (open) setToolsOpen(false);
      };

      const toggleTools = () => {
        const isHidden = Boolean(toolsPanel ? toolsPanel.hidden : true);
        setToolsOpen(isHidden);
      };

      toolsToggle?.addEventListener("click", toggleTools);
      toolTrigger?.addEventListener("click", toggleTools);

      modelToggle?.addEventListener("click", () => {
        const isHidden = Boolean(modelPanel ? modelPanel.hidden : true);
        setModelOpen(isHidden);
      });

      root.querySelectorAll<HTMLButtonElement>("[data-ais-model-option]").forEach((opt) => {
        opt.addEventListener("click", () => {
          const name = opt.dataset.aisModelOption ?? "Sonnet 5.5";
          currentModel = name;
          if (modelLabel) modelLabel.textContent = name;
          root.querySelectorAll<HTMLButtonElement>("[data-ais-model-option]").forEach((item) => {
            const match = item === opt;
            item.setAttribute("aria-pressed", String(match));
            item.classList.toggle("bg-accent/60", match);
            item.classList.toggle("font-medium", match);
            const check = item.querySelector<HTMLElement>("[data-ais-model-check]");
            check?.classList.toggle("opacity-0", !match);
          });
          setModelOpen(false);
          announce(`Model switched to ${name}.`);
        });
      });

      root.querySelectorAll<HTMLButtonElement>("[data-ais-tool-pick]").forEach((btn) => {
        btn.addEventListener("click", () => {
          const label = btn.dataset.aisToolLabel ?? "Browse sources";
          activeToolLabel = label;
          if (activeWrap) activeWrap.hidden = false;
          if (activeText) activeText.textContent = label;
          clearToolBtn?.setAttribute("aria-label", `Remove ${label} tool`);

          root.querySelectorAll<HTMLButtonElement>("[data-ais-tool-pick]").forEach((item) => {
            const match = item === btn;
            item.setAttribute("aria-pressed", String(match));
            item.classList.toggle("bg-accent/60", match);
          });

          setToolsOpen(false);
          announce(`Selected tool: ${label}.`);
        });
      });

      clearToolBtn?.addEventListener("click", () => {
        activeToolLabel = "";
        if (activeWrap) activeWrap.hidden = true;
        root.querySelectorAll<HTMLButtonElement>("[data-ais-tool-pick]").forEach((item) => {
          item.setAttribute("aria-pressed", "false");
          item.classList.remove("bg-accent/60");
        });
        announce("Removed active search tool.");
      });

      attachBtn?.addEventListener("click", () => {
        if (!filesWrap) return;
        filesWrap.hidden = false;
        const name = demoAttachments[attachIdx % demoAttachments.length];
        attachIdx++;

        const chip = document.createElement("span");
        chip.setAttribute("data-ais-chip", "");
        chip.className =
          "inline-flex max-w-full items-center gap-1.5 rounded-lg border border-border bg-muted/40 px-2.5 py-1 text-xs/4 text-foreground";

        const label = document.createElement("span");
        label.className = "truncate";
        label.textContent = name;

        const rm = document.createElement("button");
        rm.type = "button";
        rm.setAttribute("data-ais-rm-file", "");
        rm.setAttribute("aria-label", `Remove ${name}`);
        rm.className =
          "inline-flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring";
        rm.textContent = "×";

        chip.append(label, rm);
        filesWrap.append(chip);
        announce(`Attached ${name}.`);
      });

      filesWrap?.addEventListener("click", (ev) => {
        const rm = (ev.target as HTMLElement | null)?.closest<HTMLButtonElement>("[data-ais-rm-file]");
        if (!rm) return;
        const chip = rm.closest<HTMLElement>("[data-ais-chip]");
        const name = chip?.querySelector("span")?.textContent ?? "file";
        chip?.remove();
        if (filesWrap.children.length === 0) filesWrap.hidden = true;
        announce(`Removed ${name}.`);
      });

      input?.addEventListener("input", () => {
        syncAskButton();
        if (input.value === "/") {
          setToolsOpen(true);
        }
      });

      input?.addEventListener("keydown", (ev) => {
        if (ev.key === "Escape") {
          setToolsOpen(false);
          setModelOpen(false);
        }
      });

      root.querySelectorAll<HTMLAnchorElement>("[data-ais-source-link]").forEach((link) => {
        link.addEventListener("click", (ev) => {
          ev.preventDefault();
          const title = link.dataset.aisSourceLink ?? "source";
          announce(`Opened citation preview: ${title}.`);
        });
      });

      const appendSourceNode = (src: SourceItem) => {
        if (avatars) {
          const av = document.createElement("span");
          av.title = src.title;
          av.className =
            "grid size-7 animate-pop place-items-center rounded-full border-2 border-card bg-muted font-mono text-[0.6875rem] font-semibold text-foreground";
          av.textContent = src.initials;
          avatars.append(av);
        }
        if (stepsList) {
          const li = document.createElement("li");
          li.className =
            "flex min-w-0 animate-rise items-center gap-2 rounded-lg border border-border bg-muted/40 px-2.5 py-1.5 text-xs/4";

          const dot = document.createElement("span");
          dot.className = "size-2 shrink-0 rounded-full bg-success";
          dot.setAttribute("aria-hidden", "true");

          const title = document.createElement("span");
          title.className = "min-w-0 flex-1 truncate font-medium text-foreground";
          title.textContent = src.title;

          const domain = document.createElement("span");
          domain.className = "hidden shrink-0 font-mono text-[0.6875rem] text-muted-foreground sm:inline";
          domain.textContent = src.domain;

          li.append(dot, title, domain);
          stepsList.append(li);
        }
      };

      const setRunningState = (running: boolean) => {
        if (askBtn) askBtn.hidden = running;
        if (stopBtn) stopBtn.hidden = !running;
      };

      const finishSearch = (stopped: boolean, query: string) => {
        if (stepTimer !== undefined) {
          window.clearInterval(stepTimer);
          stepTimer = undefined;
        }
        setRunningState(false);
        if (traceBadge) {
          traceBadge.textContent = stopped ? "Stopped" : "Grounded";
          traceBadge.className = stopped
            ? "rounded-full border border-frame-warning bg-warning/14 px-2.5 py-0.5 text-xs font-medium text-warning"
            : "rounded-full border border-frame-success bg-success/14 px-2.5 py-0.5 text-xs font-medium text-success";
        }
        if (!stopped && answerWrap && answerBody) {
          answerWrap.hidden = false;
          const toolNote = activeToolLabel ? ` via ${activeToolLabel}` : "";
          answerBody.textContent = `Synthesized with ${currentModel}${toolNote} for "${query.slice(0, 72)}": pair 30–60s edge s-maxage TTLs with stale-while-revalidate and surrogate purges to keep regional p99 latency low without serving stale writes.`;
        }
        announce(stopped ? "Search stopped." : `Finished reading ${parsedSources.length} sources.`);
      };

      stopBtn?.addEventListener("click", () => {
        finishSearch(true, input?.value.trim() || fallbackQuery);
      });

      form?.addEventListener("submit", (ev) => {
        ev.preventDefault();
        let query = input?.value.trim() ?? "";
        if (!query) {
          query = fallbackQuery;
          if (input) input.value = query;
          syncAskButton();
        }
        setToolsOpen(false);
        setModelOpen(false);
        setRunningState(true);
        if (traceBox) traceBox.hidden = false;
        if (avatars) avatars.replaceChildren();
        if (stepsList) stepsList.replaceChildren();
        if (answerWrap) answerWrap.hidden = true;
        if (traceLabel) traceLabel.textContent = "Reading sources…";
        if (traceBadge) {
          traceBadge.textContent = "Searching";
          traceBadge.className =
            "rounded-full border border-frame bg-muted px-2.5 py-0.5 text-xs font-medium text-foreground";
        }

        announce(`Searching sources with ${currentModel}…`);

        if (reducedMotion) {
          parsedSources.forEach(appendSourceNode);
          if (traceLabel) traceLabel.textContent = `Read ${parsedSources.length} verified sources`;
          finishSearch(false, query);
          return;
        }

        let idx = 0;
        stepTimer = window.setInterval(() => {
          const src = parsedSources[idx];
          if (src) {
            appendSourceNode(src);
            idx++;
            if (traceLabel) {
              traceLabel.textContent =
                idx < parsedSources.length
                  ? `Reading source ${idx} of ${parsedSources.length}…`
                  : `Read ${parsedSources.length} verified sources`;
            }
          }
          if (idx >= parsedSources.length) {
            finishSearch(false, query);
          }
        }, 300);
      });

      syncAskButton();
    });
  }

  initAiInputSearch();
  document.addEventListener("astro:page-load", initAiInputSearch);
</script>
```
