# AI tool approval

> Inline chat tool approval card with standard Allow/Deny controls, session trust toggle, press-and-hold destructive guard and trace fold.

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

## Use when
- Gating a single agent command inside an active chat turn before execution
- Adding a press-and-hold safeguard on destructive SQL or shell operations while keeping routine calls quick
- Folding resolved approvals into a compact expandable output trace

## Avoid when
- Reviewing a multi-item backlog of approvals across several background agents; use agent-approvals
- Confirming a standalone non-chat action outside an assistant conversation; use hold-to-confirm

## Alternatives
- [agent-approvals](https://hazeui.com/blocks/agent-approvals.md)
- [hold-to-confirm](https://hazeui.com/ui/hold-to-confirm.md)
- [ai-tool-calls](https://hazeui.com/blocks/ai-tool-calls.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` | "haze-ai-tool-approval" | no | Unique prefix for heading, checkbox and hint IDs. |
| heading | `string` | "Inline tool approval" | no | Card header title. |
| standardScenario | `ApprovalScenario` | bash test suite command | no | Default non-destructive tool call scenario. |
| destructiveScenario | `ApprovalScenario` | SQL DROP TABLE command | no | Destructive tool call scenario guarded by press-and-hold. |
| class | `string` |  | no | Extra classes on the outer section. |

## Accessibility
- The destructive hold button supports pointer press, holding Space or Enter, Escape to cancel, instant completion under reduced motion and an explicit secondary confirm disclosure.
- Mode switches, approval decisions and resets announce concise updates through a polite role="status" live region.
- Key Tab: Move across mode buttons, trust checkbox, Deny, Allow or hold confirmation and Reset
- Key Space / Enter (hold): Fill and confirm the destructive tool approval button
- Key Escape: Cancel an active keyboard hold before completion

## Agent prompts

### Install and use

Install the Haze UI block "AI tool approval" with `npx shadcn@latest add @haze/ai-tool-approval`. 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 AiToolApproval from "@/components/haze/blocks/ai-tool-approval.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-tool-approval.md

### Customize with real content

Adapt the Haze ai-tool-approval block for our product. Replace the demo values of these props with our real content: id, heading, standardScenario, destructiveScenario, class. Keep the layout, the heading level rules and these accessibility details: The destructive hold button supports pointer press, holding Space or Enter, Escape to cancel, instant completion under reduced motion and an explicit secondary confirm disclosure. Mode switches, approval decisions and resets announce concise updates through a polite role="status" live region. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using ai-tool-approval, check it fits: use it when gating a single agent command inside an active chat turn before execution; adding a press-and-hold safeguard on destructive sql or shell operations while keeping routine calls quick; folding resolved approvals into a compact expandable output trace. Avoid it when reviewing a multi-item backlog of approvals across several background agents; use agent-approvals; confirming a standalone non-chat action outside an assistant conversation; use hold-to-confirm. Alternatives: @haze/agent-approvals, @haze/hold-to-confirm, @haze/ai-tool-calls.

## Example requests that should lead here
- Build an inline AI tool approval card inside a chat turn with standard Allow/Deny and a press-and-hold destructive SQL guard
- Create an agent permission prompt that folds into an expandable command output trace once approved or denied

## Source

```astro
---
import { Check, ChevronDown, Database, Lock, RotateCcw, Terminal, X } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface ApprovalScenario {
  id: string;
  label: string;
  prompt: string;
  title: string;
  tool: string;
  command: string;
  rationale: string;
  destructive: boolean;
  output: string;
}

interface Props {
  id?: string;
  heading?: string;
  standardScenario?: ApprovalScenario;
  destructiveScenario?: ApprovalScenario;
  class?: string;
}

const {
  id = "haze-ai-tool-approval",
  heading = "Tool approval",
  standardScenario = {
    id: "standard",
    label: "Standard example",
    prompt: "Run the billing test suite before we tag the release.",
    title: "Run a command",
    tool: "bash",
    command: "pnpm test --filter billing",
    rationale: "Check the billing tests before changing the invoice form.",
    destructive: false,
    output: "PASS packages/billing/invoice.spec.ts (48 passed, 0 failed) · 1.24s",
  },
  destructiveScenario = {
    id: "destructive",
    label: "Destructive example",
    prompt: "Clear out the old staging invoices table before seeding.",
    title: "Drop staging table",
    tool: "sql",
    command: "DROP TABLE staging_invoices;",
    rationale: "Permanently deletes 14,280 rows with no automatic rollback snapshot.",
    destructive: true,
    output: "DROP TABLE — staging_invoices removed (14,280 rows deleted) · 0.18s",
  },
  class: className,
} = Astro.props;
---

<section aria-labelledby={`${id}-title`} data-haze-ai-tool-approval 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-md rounded-2xl border border-border bg-card p-5 shadow-lift">
    {/* Standard approval view */}
    <div data-ata-card="standard">
      <div class="flex flex-wrap items-center justify-between gap-2">
        <div class="flex min-w-0 items-center gap-2.5">
          <span class="grid size-6 shrink-0 place-items-center rounded-md bg-muted text-muted-foreground" aria-hidden="true">
            <Terminal class="size-3.5" />
          </span>
          <h3 class="text-sm/5 font-semibold text-foreground">{standardScenario.title}</h3>
          <span class="font-mono text-xs text-muted-foreground">{standardScenario.tool}</span>
        </div>
        <button
          type="button"
          data-ata-switch="destructive"
          class="inline-flex min-h-8 shrink-0 cursor-pointer items-center rounded-md px-1.5 text-xs text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
        >
          {destructiveScenario.label}
        </button>
      </div>

      <pre class="mt-3.5 overflow-x-auto rounded-xl border border-border bg-muted/50 px-3.5 py-2.5 font-mono text-sm/6 text-foreground"><span class="select-none text-muted-foreground">$ </span><code>{standardScenario.command}</code></pre>
      <p class="mt-3 text-xs/5 text-muted-foreground">{standardScenario.rationale}</p>

      <div class="mt-5 flex flex-wrap items-center justify-between gap-3">
        <label for={`${id}-trust`} class="inline-flex min-h-8 cursor-pointer items-center gap-2 text-xs/5 text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground">
          <span class="relative inline-grid size-4 shrink-0 place-items-center">
            <input
              id={`${id}-trust`}
              type="checkbox"
              data-ata-trust
              class="peer col-start-1 row-start-1 size-4 shrink-0 cursor-pointer appearance-none rounded-sm border border-border-strong bg-field transition-[background-color,border-color,scale] duration-150 ease-snappy hover:border-foreground active:scale-90 checked:border-primary checked:bg-primary focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring forced-colors:appearance-auto"
            />
            <Check class="pointer-events-none col-start-1 row-start-1 size-3 scale-50 text-primary-foreground opacity-0 transition-[opacity,scale] duration-200 ease-spring peer-checked:scale-100 peer-checked:opacity-100 forced-colors:hidden" stroke-width={3} aria-hidden="true" />
          </span>
          <span>Don&apos;t ask again for <span class="font-mono">{standardScenario.tool}</span></span>
        </label>

        <div class="flex items-center gap-2">
          <button
            type="button"
            data-ata-deny="standard"
            class="inline-flex h-9 cursor-pointer items-center rounded-full px-3.5 text-sm font-medium text-muted-foreground transition-colors duration-150 ease-snappy hover:bg-muted/60 hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
          >
            Deny
          </button>
          <button
            type="button"
            data-ata-allow="standard"
            class="inline-flex h-9 cursor-pointer items-center rounded-full bg-primary px-4 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"
          >
            Allow
          </button>
        </div>
      </div>
    </div>

    {/* Destructive approval view */}
    <div data-ata-card="destructive" hidden>
      <div class="flex flex-wrap items-center justify-between gap-2">
        <div class="flex min-w-0 items-center gap-2.5">
          <span class="grid size-6 shrink-0 place-items-center rounded-md bg-destructive/14 text-destructive" aria-hidden="true">
            <Database class="size-3.5" />
          </span>
          <h3 class="text-sm/5 font-semibold text-foreground">{destructiveScenario.title}</h3>
          <span class="font-mono text-xs text-muted-foreground">{destructiveScenario.tool}</span>
        </div>
        <button
          type="button"
          data-ata-switch="standard"
          class="inline-flex min-h-8 shrink-0 cursor-pointer items-center rounded-md px-1.5 text-xs text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
        >
          {standardScenario.label}
        </button>
      </div>

      <pre class="mt-3.5 overflow-x-auto rounded-xl border border-frame-destructive bg-destructive/8 px-3.5 py-2.5 font-mono text-sm/6 text-destructive"><code>{destructiveScenario.command}</code></pre>
      <p class="mt-3 text-xs/5 text-muted-foreground">{destructiveScenario.rationale}</p>

      <div class="mt-5 flex flex-wrap items-center justify-between gap-3">
        <p id={`${id}-hold-hint`} data-ata-hold-hint class="text-xs/5 text-muted-foreground">Hold 0.8s (or Space / Enter).</p>

        <div class="flex items-center gap-2">
          <button
            type="button"
            data-ata-deny="destructive"
            class="inline-flex h-9 cursor-pointer items-center rounded-full px-3.5 text-sm font-medium text-muted-foreground transition-colors duration-150 ease-snappy hover:bg-muted/60 hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
          >
            Deny
          </button>
          <button
            type="button"
            data-ata-hold
            aria-describedby={`${id}-hold-hint`}
            class="relative inline-grid h-9 max-w-full touch-manipulation cursor-pointer items-center overflow-hidden rounded-full border border-frame-destructive bg-field text-sm font-medium text-destructive select-none transition-[background-color,scale] duration-150 ease-snappy hover:bg-destructive/10 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring data-[holding]:scale-[0.98]"
          >
            <span class="flex min-w-0 items-center justify-center gap-1.5 px-4">
              <Lock class="size-3.5 shrink-0" aria-hidden="true" />
              <span>Hold to allow</span>
            </span>
            <span
              data-ata-hold-fill
              aria-hidden="true"
              class="pointer-events-none absolute inset-0 flex items-center justify-center gap-1.5 bg-destructive px-4 text-destructive-foreground [clip-path:inset(0_calc(100%_-_var(--hold-p,0)_*_100%)_0_0)]"
            >
              <Lock class="size-3.5 shrink-0" />
              <span>Hold to allow</span>
            </span>
          </button>
        </div>
      </div>

      <details class="group/alt mt-3 border-t border-border pt-2.5">
        <summary class="flex min-h-7 cursor-pointer list-none items-center gap-1 rounded-sm text-xs/5 text-muted-foreground transition-colors duration-150 ease-snappy hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring [&::-webkit-details-marker]:hidden">
          Confirm without holding
          <ChevronDown class="size-3.5 transition-transform duration-150 ease-snappy group-open/alt:rotate-180" aria-hidden="true" />
        </summary>
        <div class="mt-2 flex justify-end">
          <button
            type="button"
            data-ata-allow-direct
            class="inline-flex h-8 cursor-pointer items-center gap-1.5 rounded-full bg-destructive px-3.5 text-xs font-medium text-destructive-foreground transition-opacity duration-150 ease-snappy hover:opacity-90 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
          >
            <Check class="size-3.5" aria-hidden="true" />
            Confirm drop table
          </button>
        </div>
      </details>
    </div>

    {/* Folded 1-line trace after a decision */}
    <div data-ata-trace hidden class="animate-rise">
      <div class="flex items-start justify-between gap-2">
        <details data-ata-trace-details class="group min-w-0 flex-1">
          <summary class="flex min-h-8 cursor-pointer list-none items-center gap-2 rounded-md text-xs/5 text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring [&::-webkit-details-marker]:hidden">
            <span data-ata-trace-ok class="grid size-5 shrink-0 place-items-center rounded-md bg-success/14 text-success" aria-hidden="true">
              <Check class="size-3" />
            </span>
            <span data-ata-trace-no hidden class="grid size-5 shrink-0 place-items-center rounded-md bg-destructive/14 text-destructive" aria-hidden="true">
              <X class="size-3" />
            </span>
            <span data-ata-trace-label class="shrink-0 font-medium text-foreground">Allowed</span>
            <span data-ata-trace-tool class="shrink-0 font-mono text-muted-foreground">{standardScenario.tool}</span>
            <span data-ata-trace-cmd class="min-w-0 truncate font-mono text-muted-foreground">{standardScenario.command}</span>
            <ChevronDown class="size-3.5 shrink-0 text-muted-foreground transition-transform duration-150 ease-snappy group-open:rotate-180" aria-hidden="true" />
          </summary>
          <pre data-ata-trace-output class="mt-3 overflow-x-auto rounded-xl border border-border bg-muted/50 px-3 py-2 font-mono text-xs/5 text-muted-foreground"></pre>
        </details>
        <button
          type="button"
          data-ata-reset
          class="inline-flex min-h-8 shrink-0 cursor-pointer items-center gap-1 rounded-full px-2.5 text-xs font-medium text-muted-foreground transition-colors duration-150 ease-snappy hover:bg-muted/60 hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
        >
          <RotateCcw class="size-3" aria-hidden="true" />
          Reset
        </button>
      </div>
    </div>
  </div>

  <div
    hidden
    data-ata-config
    data-std-tool={standardScenario.tool}
    data-std-cmd={standardScenario.command}
    data-std-out={standardScenario.output}
    data-dst-tool={destructiveScenario.tool}
    data-dst-cmd={destructiveScenario.command}
    data-dst-out={destructiveScenario.output}
  ></div>

  <p data-ata-status role="status" class="sr-only"></p>
</section>

<script>
  function initAiToolApproval() {
    document.querySelectorAll<HTMLElement>("[data-haze-ai-tool-approval]").forEach((root) => {
      if (root.hasAttribute("data-enhanced")) return;
      root.setAttribute("data-enhanced", "");

      const cfg = root.querySelector<HTMLElement>("[data-ata-config]");
      const stdCard = root.querySelector<HTMLElement>('[data-ata-card="standard"]');
      const dstCard = root.querySelector<HTMLElement>('[data-ata-card="destructive"]');
      const traceWrap = root.querySelector<HTMLElement>("[data-ata-trace]");
      const traceDetails = root.querySelector<HTMLDetailsElement>("[data-ata-trace-details]");
      const traceOk = root.querySelector<HTMLElement>("[data-ata-trace-ok]");
      const traceNo = root.querySelector<HTMLElement>("[data-ata-trace-no]");
      const traceLabel = root.querySelector<HTMLElement>("[data-ata-trace-label]");
      const traceTool = root.querySelector<HTMLElement>("[data-ata-trace-tool]");
      const traceCmd = root.querySelector<HTMLElement>("[data-ata-trace-cmd]");
      const traceOut = root.querySelector<HTMLElement>("[data-ata-trace-output]");
      const trustBox = root.querySelector<HTMLInputElement>("[data-ata-trust]");
      const holdBtn = root.querySelector<HTMLButtonElement>("[data-ata-hold]");
      const holdFill = root.querySelector<HTMLElement>("[data-ata-hold-fill]");
      const holdHint = root.querySelector<HTMLElement>("[data-ata-hold-hint]");
      const status = root.querySelector<HTMLElement>("[data-ata-status]");
      const switchBtns = root.querySelectorAll<HTMLButtonElement>("[data-ata-switch]");

      if (!cfg || !stdCard || !dstCard || !traceWrap || !traceLabel || !traceTool || !traceCmd || !traceOut) return;

      type Mode = "standard" | "destructive";
      let mode: Mode = "standard";
      let decided = false;
      let holdFrame = 0;
      let holdInput: number | string | null = null;
      const HOLD_MS = 800;
      const idleHint = "Hold 0.8s (or Space / Enter).";

      const getData = (m: Mode) =>
        m === "standard"
          ? {
              tool: cfg.dataset.stdTool ?? "bash",
              cmd: cfg.dataset.stdCmd ?? "",
              out: cfg.dataset.stdOut ?? "",
            }
          : {
              tool: cfg.dataset.dstTool ?? "sql",
              cmd: cfg.dataset.dstCmd ?? "",
              out: cfg.dataset.dstOut ?? "",
            };

      const stopHold = (resetFill: boolean) => {
        cancelAnimationFrame(holdFrame);
        if (typeof holdInput === "number" && holdBtn?.hasPointerCapture(holdInput)) {
          holdBtn.releasePointerCapture(holdInput);
        }
        holdInput = null;
        holdBtn?.removeAttribute("data-holding");
        if (resetFill && holdFill) holdFill.style.setProperty("--hold-p", "0");
        if (holdHint) holdHint.textContent = idleHint;
      };

      const renderView = () => {
        stdCard.hidden = decided || mode !== "standard";
        dstCard.hidden = decided || mode !== "destructive";
        traceWrap.hidden = !decided;
      };

      const decide = (decision: "Allowed" | "Denied") => {
        stopHold(true);
        decided = true;
        const d = getData(mode);
        const remembered = decision === "Allowed" && mode === "standard" && Boolean(trustBox?.checked);

        traceTool.textContent = d.tool;
        traceCmd.textContent = d.cmd;
        if (traceOk) traceOk.hidden = decision !== "Allowed";
        if (traceNo) traceNo.hidden = decision === "Allowed";

        if (decision === "Allowed") {
          traceLabel.textContent = remembered ? "Allowed · saved" : "Allowed";
          traceOut.textContent = d.out;
        } else {
          traceLabel.textContent = "Denied";
          traceOut.textContent = "Execution skipped by user. No changes were applied.";
        }
        if (traceDetails) traceDetails.open = false;
        renderView();
        if (status) {
          status.textContent =
            decision === "Allowed"
              ? `Allowed ${d.tool} call (${d.cmd})${remembered ? " and remembered preference." : "."}`
              : `Denied ${d.tool} call (${d.cmd}).`;
        }
      };

      const startHold = (input: number | string) => {
        if (decided || holdInput !== null || !holdBtn || !holdFill) return;
        if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
          holdFill.style.setProperty("--hold-p", "1");
          decide("Allowed");
          return;
        }
        holdInput = input;
        const started = performance.now();
        holdBtn.setAttribute("data-holding", "");
        if (holdHint) holdHint.textContent = "Keep holding to confirm…";
        const tick = (now: number) => {
          const progress = Math.min(1, Math.max(0, (now - started) / HOLD_MS));
          holdFill.style.setProperty("--hold-p", String(progress));
          if (progress < 1) {
            holdFrame = requestAnimationFrame(tick);
          } else {
            decide("Allowed");
          }
        };
        holdFrame = requestAnimationFrame(tick);
      };

      switchBtns.forEach((btn) => {
        btn.addEventListener("click", () => {
          const next: Mode = btn.dataset.ataSwitch === "destructive" ? "destructive" : "standard";
          stopHold(true);
          mode = next;
          decided = false;
          renderView();
          if (status) status.textContent = `Switched to ${next} tool approval example.`;
        });
      });

      root.querySelector<HTMLButtonElement>('[data-ata-allow="standard"]')?.addEventListener("click", () => decide("Allowed"));
      root.querySelector<HTMLButtonElement>("[data-ata-allow-direct]")?.addEventListener("click", () => decide("Allowed"));
      root.querySelectorAll<HTMLButtonElement>("[data-ata-deny]").forEach((btn) => {
        btn.addEventListener("click", () => decide("Denied"));
      });

      root.querySelector<HTMLButtonElement>("[data-ata-reset]")?.addEventListener("click", () => {
        stopHold(true);
        decided = false;
        if (trustBox) trustBox.checked = false;
        renderView();
        if (status) status.textContent = "Reset tool approval card.";
      });

      if (holdBtn && holdFill) {
        holdFill.style.setProperty("--hold-p", "0");
        holdBtn.addEventListener("pointerdown", (ev) => {
          if (!ev.isPrimary || ev.button !== 0 || decided || holdInput !== null) return;
          holdBtn.setPointerCapture(ev.pointerId);
          startHold(ev.pointerId);
        });
        holdBtn.addEventListener("pointermove", (ev) => {
          if (holdInput !== ev.pointerId) return;
          const rect = holdBtn.getBoundingClientRect();
          const pad = ev.pointerType === "touch" ? 16 : 4;
          if (ev.clientX < rect.left - pad || ev.clientX > rect.right + pad || ev.clientY < rect.top - pad || ev.clientY > rect.bottom + pad) {
            stopHold(true);
          }
        });
        for (const evType of ["pointerup", "pointercancel", "lostpointercapture"] as const) {
          holdBtn.addEventListener(evType, (ev) => {
            if (holdInput === ev.pointerId) stopHold(true);
          });
        }
        holdBtn.addEventListener("contextmenu", (ev) => {
          if (holdInput !== null) ev.preventDefault();
        });
        holdBtn.addEventListener("keydown", (ev) => {
          if (ev.key === "Escape" && holdInput !== null) {
            ev.preventDefault();
            stopHold(true);
          } else if (ev.key === " " || ev.key === "Enter") {
            ev.preventDefault();
            if (!ev.repeat) startHold(ev.key);
          }
        });
        holdBtn.addEventListener("keyup", (ev) => {
          if (holdInput === ev.key) stopHold(true);
        });
        holdBtn.addEventListener("blur", () => stopHold(true));
      }

      renderView();
    });
  }
  initAiToolApproval();
  document.addEventListener("astro:page-load", initAiToolApproval);
</script>
```
