# Tool approval

Show what a tool did or ask for permission to run it.

## Preview

tool-preview-1.jsx

```jsx
import { useState as useState3 } from "react";
import { forwardRef, useEffect, useRef, useState as useState2 } from "react";
import { Plus } from "lucide-react";
import {
  Composer,
  ComposerAction,
  ComposerAttachments,
  ComposerInput,
  ComposerSubmit,
  ComposerToolbar,
} from "@/components/ui/composer";
import { FileUpload } from "@/components/ui/file-upload";
import { useState } from "react";
import { Check, ChevronDown } from "lucide-react";
import { Select } from "@/components/ui/select";
import { TooltipHint } from "@/components/ui/tooltip";
import { Snippet } from "@/components/ui/snippet";
import { ToolApproval } from "@/components/ui/tool-approval";

export default function Example() {
  return (
    <PreviewWide>
      <div
        style={{
          display: "grid",
          gap: "var(--space-3)",
        }}
      >
        <RequestApproval kind="email" />
        <ChatComposer onSubmit={() => undefined} />
      </div>
    </PreviewWide>
  );
}

var MODEL_OPTIONS = [
  {
    value: "chatgpt-sol-6-1",
    label: "Sol 6.1",
  },
  {
    value: "chatgpt-sol-6",
    label: "Sol 6",
  },
  {
    value: "chatgpt-luna-6",
    label: "Luna 6",
  },
];

function ModelSelect({
  disabled,
  value: controlledValue,
  onValueChange,
  options = MODEL_OPTIONS,
} = {}) {
  const [uncontrolledValue, setUncontrolledValue] = useState(
    () => options.find((item) => !item.disabled)?.value ?? null,
  );
  const value =
    controlledValue === undefined ? uncontrolledValue : controlledValue;
  const fullLabel =
    options.find((item) => item.value === value)?.label ?? "Choose a model";
  const change = (next) => {
    if (controlledValue === undefined && next) setUncontrolledValue(next);
    onValueChange?.(next);
  };
  return (
    <Select.Root
      items={options}
      value={value}
      onValueChange={change}
      disabled={disabled}
    >
      <TooltipHint content={fullLabel}>
        <Select.Trigger
          compact
          variant="ghost"
          className="model-select__trigger"
          aria-label="Model"
          aria-description={fullLabel}
        >
          <Select.Value placeholder="Choose a model" />
          <Select.Icon>
            <ChevronDown size={14} aria-hidden="true" />
          </Select.Icon>
        </Select.Trigger>
      </TooltipHint>
      <Select.Portal>
        <Select.Positioner>
          <Select.Popup className="model-select__popup" aria-label="Models">
            {options.map((item) => (
              <Select.Item
                key={item.value}
                value={item.value}
                disabled={item.disabled}
              >
                <Select.ItemText>{item.label}</Select.ItemText>
                <Select.ItemIndicator>
                  <Check size={14} aria-hidden="true" />
                </Select.ItemIndicator>
              </Select.Item>
            ))}
          </Select.Popup>
        </Select.Positioner>
      </Select.Portal>
    </Select.Root>
  );
}

function fileFromNative(file, id, url) {
  return {
    id,
    name: file.name,
    mediaType: file.type || undefined,
    size: file.size,
    url,
    status: "ready",
  };
}

var ChatComposer = forwardRef(function ChatComposer2(
  {
    defaultValue = "",
    defaultAttachments = [],
    value,
    onValueChange,
    status = "ready",
    feedbackPlacement = "inline",
    initialRows,
    maxRows,
    disabled,
    readOnly,
    error,
    description,
    secondary,
    attachmentSize = "sm",
    onSubmit,
    onStop,
    onRetry,
  },
  ref,
) {
  const fileCounter = useRef(0);
  const objectUrls = useRef(/* @__PURE__ */ new Map());
  const pendingUrls = useRef(/* @__PURE__ */ new Map());
  const acknowledgedFiles = useRef(/* @__PURE__ */ new WeakMap());
  const mounted = useRef(true);
  const [files, setFiles] = useState2(defaultAttachments);
  const filesRef = useRef(files);
  const [model, setModel] = useState2(MODEL_OPTIONS[0].value);
  useEffect(() => {
    mounted.current = true;
    return () => {
      mounted.current = false;
      for (const url of objectUrls.current.values()) URL.revokeObjectURL(url);
      objectUrls.current.clear();
      pendingUrls.current.clear();
      acknowledgedFiles.current = /* @__PURE__ */ new WeakMap();
    };
  }, []);
  const updateFiles = (next) => {
    const resolved = typeof next === "function" ? next(filesRef.current) : next;
    filesRef.current = resolved;
    setFiles(resolved);
  };
  const releaseUrl = (file) => {
    if (!file.url || pendingUrls.current.has(file.id)) return;
    const url = objectUrls.current.get(file.id);
    if (url) {
      objectUrls.current.delete(file.id);
      URL.revokeObjectURL(url);
    }
  };
  const remove = (file) => {
    updateFiles((current) => current.filter((item) => item.id !== file.id));
    releaseUrl(file);
  };
  const submit = async (submission) => {
    const submittedIds = new Set(submission.attachments.map((file) => file.id));
    const submittedFiles = new Map(
      filesRef.current
        .filter((file) => submittedIds.has(file.id))
        .map((file) => [file.id, file]),
    );
    for (const file of submission.attachments) {
      if (file.url) pendingUrls.current.set(file.id, file.url);
    }
    try {
      await onSubmit(submission, {
        model,
      });
      for (const id of submittedIds) pendingUrls.current.delete(id);
      if (!mounted.current) return;
      for (const [id, file] of submittedFiles) {
        if (!filesRef.current.some((item) => item.id === id)) releaseUrl(file);
      }
      acknowledgedFiles.current.set(submission, submittedFiles);
    } catch (error2) {
      for (const file of submission.attachments) {
        pendingUrls.current.delete(file.id);
        const captured = submittedFiles.get(file.id) ?? file;
        if (!filesRef.current.some((current) => current.id === file.id))
          releaseUrl(captured);
      }
      throw error2;
    }
  };
  const submitted = (submission) => {
    const captured = acknowledgedFiles.current.get(submission);
    acknowledgedFiles.current.delete(submission);
    if (!captured || !mounted.current) return;
    updateFiles((current) => current.filter((file) => !captured.has(file.id)));
  };
  return (
    <FileUpload.Root
      multiple
      disabled={disabled || readOnly}
      aria-label="Message files"
      onFilesSelect={({ accepted }) => {
        const selected = accepted.map((file) => {
          fileCounter.current += 1;
          const previewable =
            /^(image\/(png|jpeg|webp|gif|avif)|application\/pdf|text\/(plain|csv))$/.test(
              file.type,
            );
          const url =
            previewable && typeof URL.createObjectURL === "function"
              ? URL.createObjectURL(file)
              : undefined;
          if (url)
            objectUrls.current.set(`local-file-${fileCounter.current}`, url);
          return fileFromNative(file, `local-file-${fileCounter.current}`, url);
        });
        if (selected.length)
          updateFiles((current) => [...current, ...selected]);
      }}
    >
      <Composer
        ref={ref}
        defaultValue={defaultValue}
        value={value}
        onValueChange={onValueChange}
        attachments={files}
        status={status}
        feedbackPlacement={feedbackPlacement}
        initialRows={initialRows}
        maxRows={maxRows}
        disabled={disabled}
        readOnly={readOnly}
        error={error}
        description={description}
        onStop={onStop}
        onRetry={onRetry}
        onSubmit={submit}
        onSubmitted={submitted}
        secondary={secondary}
        attachmentContent={
          <ComposerAttachments size={attachmentSize} onRemove={remove} />
        }
      >
        <ComposerInput placeholder="Ask a follow-up…" />
        <ComposerToolbar>
          <ComposerToolbar.Start>
            <FileUpload.Trigger
              render={
                <ComposerAction aria-label="Attach files" icon={<Plus />} />
              }
            />
          </ComposerToolbar.Start>
          <ComposerToolbar.End>
            <ModelSelect
              disabled={disabled || readOnly}
              value={model}
              onValueChange={(value2) => {
                if (value2) setModel(value2);
              }}
            />
            <ComposerSubmit />
          </ComposerToolbar.End>
        </ComposerToolbar>
        <FileUpload.Input />
      </Composer>
    </FileUpload.Root>
  );
});

function PreviewWide({ children }) {
  return <div data-preview-wide>{children}</div>;
}

function RequestApproval({ kind = "file" }) {
  const [state, setState] = useState3("pending");
  const payload = (
    <>
      <small>Gmail · to product-team@example.com</small>
      <Snippet
        value="The workspace experiment is ready for review. Start with a sample workspace, then ask teams to connect their account."
        title="Weekly product update · 21 October"
        contentType="text"
        variant="block"
      />
    </>
  );
  return (
    <ToolApproval
      approvalId={`weekly-${"email"}`}
      prompt={"Send the weekly update?"}
      state={state}
      onApprove={() => setState("approved")}
      onDeny={() => setState("denied")}
    >
      {payload}
    </ToolApproval>
  );
}

```

tool-preview-1.css

```css
/* apps/web/src/demos/library/model-select.css */
.model-select__trigger {
  gap: var(--space-2);
  min-inline-size: 0;
  max-inline-size: calc(100vw - (var(--space-4) * 2));
}
.ui-popup.ui-select-popup.model-select__popup {
  max-inline-size: calc(100vw - (var(--space-4) * 2));
}
.ui-select-trigger.model-select__trigger[data-compact] {
  max-inline-size: min(100%, 272px, calc(100vw - (var(--space-4) * 2)));
}

```

## Design guidance

Use Tool approval to ask for permission, Tool to show one operation’s details, and Activity for a sequence. Keep a pending decision visible even when execution details are collapsed.

By default, approval actions follow the content they refer to. Use actionsPlacement="header" for inline actions. They move below the content in a container at or below 22rem. Deny and Allow become disabled while a decision is submitted or awaiting acknowledgement. Show Retry with the error and keep approved, denied, failed, and expired outcomes distinct. Errors are announced in an alert region.

MessageParts renders a Tool summary by default. Supplying part.input/part.output does not automatically serialize payloads or render decision buttons. Use its caller-owned tool renderer with ToolInput, ToolOutput, Snippet and an independently reachable ToolApproval for the complete composition. Only expose content the application has validated for this reader.

Use the [runtime approval command](/libraries/ai-runtime#identity) to respond to native approval requests. With bindApproval directly, provide a live getCurrent and guard against duplicate or stale decisions in your app. Show acknowledgement, execution, and remote cancellation from their own events. Use Dialog or AlertDialog for general confirmation and Questionnaire for clarification.

Tool output can be present while state="running"; render it as a preview. output-ready means known final output. Error/cancellation takes precedence over retained content. See [subagent](/ai-elements/activity#subagents), [process](/ai-elements/activity#terminal) and [test result](/ai-elements/activity#test-results) compositions for these different host facts.

**Also known as**

Tool approval, Permission confirmation.

These names describe the approval state within Tool. The caller grants permission and executes the operation; approval is not execution.

## Installation

```sh
npx shadcn@latest add https://ghost-ui.com/r/tool.json
```

## Basic usage

The caller owns the decision state. Connect the callbacks to your application or runtime. An approved decision does not imply successful execution.

```tsx
import { useState } from "react";
import {
  ToolApproval,
  type ToolApprovalState,
} from "@/components/ui/tool-approval";

export function SaveApproval() {
  const [state, setState] = useState<ToolApprovalState>("pending");
  return (
    <ToolApproval
      approvalId="save-weekly-update"
      state={state}
      prompt="Save weekly update?"
      onApprove={() => setState("approved")}
      onDeny={() => setState("denied")}
    >
      docs/weekly-update.md
    </ToolApproval>
  );
}
```

Execution has a separate lifecycle. Render only the safe input and output content your caller has; Tool does not execute operations or serialize those values.

```tsx
import { Tool, ToolInput, ToolOutput } from "@/components/ui/tool";

export function ToolExample() {
  return (
    <Tool name="Find receipt" state="output-ready">
      <ToolInput>Order 4815</ToolInput>
      <ToolOutput>Receipt details are ready for review.</ToolOutput>
    </Tool>
  );
}
```

## Structures

- ToolApproval
- Tool (optional execution details)
  - ToolHeader
  - ToolInput
  - ToolOutput
  - ToolError

ToolApproval can stand alone or attach to Composer. Tool groups optional execution details; a direct approval child stays visible outside its collapsed detail.

## Examples

Review execution lifecycle first, then approval states, SDK integrations, and optional product compositions.

### Running

The running state names the operation and shows only caller-provided input.

tool-running-2.jsx

```jsx
import { Tool, ToolInput } from "@/components/ui/tool";

export default function Example() {
  return (
    <PreviewWide>
      <Tool name="Find receipt" state="running" defaultOpen>
        <ToolInput>Searching the order history.</ToolInput>
      </Tool>
    </PreviewWide>
  );
}

function PreviewWide({ children }) {
  return <div data-preview-wide>{children}</div>;
}

```

### Result details

The quiet result summary opens only when the user asks to inspect the returned details.

tool-result-details-3.jsx

```jsx
import { Tool, ToolOutput } from "@/components/ui/tool";

export default function Example() {
  return (
    <PreviewWide>
      <Tool name="Find receipt" state="output-ready">
        <ToolOutput>{result}</ToolOutput>
      </Tool>
    </PreviewWide>
  );
}

var result = <p>Receipt details are ready for review.</p>;

function PreviewWide({ children }) {
  return <div data-preview-wide>{children}</div>;
}

```

### Failure and retry

The error remains visible and retry is available only when the caller supplies it.

tool-failure-and-retry-4.jsx

```jsx
import { useState as useState3 } from "react";
import { Button } from "@/components/ui/button";
import { Tool, ToolError, ToolOutput } from "@/components/ui/tool";

export default function Example() {
  const [attempts, setAttempts] = useState3(0);
  const failed = attempts === 0;
  return (
    <PreviewWide>
      <Tool
        name="Find receipt"
        state={failed ? "error" : "output-ready"}
        defaultOpen
      >
        {failed ? (
          <ToolError>
            <span>Receipt lookup failed. Try again.</span>
            <Button
              type="button"
              variant="text"
              size="xs"
              onClick={() => setAttempts((value) => value + 1)}
            >
              Try again
            </Button>
          </ToolError>
        ) : (
          <ToolOutput>{result}</ToolOutput>
        )}
      </Tool>
    </PreviewWide>
  );
}

var result = <p>Receipt details are ready for review.</p>;

function PreviewWide({ children }) {
  return <div data-preview-wide>{children}</div>;
}

```

### Cancelled

Cancelled operations remain readable and do not claim completion.

tool-cancelled-5.jsx

```jsx
import { Tool, ToolOutput } from "@/components/ui/tool";

export default function Example() {
  return (
    <PreviewWide>
      <Tool name="Find receipt" state="cancelled" defaultOpen>
        <ToolOutput>The lookup stopped before it changed anything.</ToolOutput>
      </Tool>
    </PreviewWide>
  );
}

function PreviewWide({ children }) {
  return <div data-preview-wide>{children}</div>;
}

```

### Custom result

Custom result content stays caller-rendered and is not serialized by Tool.

tool-custom-result-6.jsx

```jsx
import { Snippet } from "@/components/ui/snippet";
import { Tool, ToolOutput } from "@/components/ui/tool";

export default function Example() {
  return (
    <PreviewWide>
      <Tool name="Find receipt" state="output-ready" defaultOpen>
        <ToolOutput>
          <Snippet
            value={"order_id: 4815\nstatus: ready"}
            contentType="text"
            title="Receipt result"
            variant="block"
          />
        </ToolOutput>
      </Tool>
    </PreviewWide>
  );
}

function PreviewWide({ children }) {
  return <div data-preview-wide>{children}</div>;
}

```

### Approval

Approval is a separate decision. Approve or deny updates the caller-owned record immediately.

tool-approval-7.jsx

```jsx
import { useState as useState3 } from "react";
import { Tool } from "@/components/ui/tool";
import { ToolApproval } from "@/components/ui/tool-approval";

export default function Example() {
  const [state, setState] = useState3("pending");
  return (
    <PreviewWide>
      <Tool
        name="Share receipt"
        state={state === "pending" ? "approval-required" : "approval-resolved"}
        defaultOpen
      >
        <ToolApproval
          approvalId="share-receipt"
          state={state}
          onApprove={() => setState("approved")}
          onDeny={() => setState("denied")}
        >
          Allow the assistant to share this receipt with the support team?
        </ToolApproval>
      </Tool>
    </PreviewWide>
  );
}

function PreviewWide({ children }) {
  return <div data-preview-wide>{children}</div>;
}

```

### Standalone approval

The decision remains visible without a disclosure.

tool-standalone-approval-8.jsx

```jsx
import { useState as useState3 } from "react";
import { ToolApproval } from "@/components/ui/tool-approval";

export default function Example() {
  const [state, setState] = useState3("pending");
  return (
    <ToolApproval
      prompt="Save weekly update?"
      approvalId="standalone-weekly"
      actionsPlacement="content"
      state={state}
      onApprove={() => setState("approved")}
      onDeny={() => setState("denied")}
    >
      docs/weekly-update.md
    </ToolApproval>
  );
}

```

### Submitting a decision

Actions stay disabled until the caller acknowledges the decision.

tool-submitting-a-decision-9.jsx

```jsx
import { ToolApproval } from "@/components/ui/tool-approval";

export default function Example() {
  return (
    <ToolApproval approvalId="submitting-weekly" state="submitting">
      docs/weekly-update.md
    </ToolApproval>
  );
}

```

### Approval failure and retry

Retry returns to the pending request. A failed submission retains the request.

tool-approval-failure-and-retry-10.jsx

```jsx
import { useState as useState3 } from "react";
import { ToolApproval } from "@/components/ui/tool-approval";

export default function Example() {
  const [failed, setFailed] = useState3(true);
  return (
    <ToolApproval
      prompt="Save weekly update?"
      approvalId="failed-weekly"
      state={failed ? "failed" : "pending"}
      error="The decision could not be submitted."
      onRetry={() => setFailed(false)}
      onApprove={() => {
        throw new Error("The decision could not be submitted.");
      }}
      onDeny={() => {
        throw new Error("The decision could not be submitted.");
      }}
    >
      docs/weekly-update.md
    </ToolApproval>
  );
}

```

### Failed decision in the Composer layer

Retry the decision without implying that the operation has run.

tool-failed-decision-in-the-composer-layer-11.jsx

```jsx
import { useState as useState3 } from "react";
import { forwardRef, useEffect, useRef, useState as useState2 } from "react";
import { Plus } from "lucide-react";
import {
  Composer,
  ComposerAction,
  ComposerAttachments,
  ComposerInput,
  ComposerSubmit,
  ComposerToolbar,
} from "@/components/ui/composer";
import { FileUpload } from "@/components/ui/file-upload";
import { useState } from "react";
import { Check, ChevronDown } from "lucide-react";
import { Select } from "@/components/ui/select";
import { TooltipHint } from "@/components/ui/tooltip";
import { ToolApproval } from "@/components/ui/tool-approval";

export default function Example() {
  const [state, setState] = useState3("failed");
  return (
    <PreviewWide>
      <ChatComposer
        onSubmit={() => undefined}
        secondary={
          <ToolApproval
            prompt="Save weekly update?"
            approvalId="failed-layer-weekly"
            state={state}
            error="The decision could not be submitted."
            onRetry={() => setState("pending")}
            onApprove={() => setState("approved")}
            onDeny={() => setState("denied")}
          >
            docs/weekly-update.md
          </ToolApproval>
        }
      />
    </PreviewWide>
  );
}

var MODEL_OPTIONS = [
  {
    value: "chatgpt-sol-6-1",
    label: "Sol 6.1",
  },
  {
    value: "chatgpt-sol-6",
    label: "Sol 6",
  },
  {
    value: "chatgpt-luna-6",
    label: "Luna 6",
  },
];

function ModelSelect({
  disabled,
  value: controlledValue,
  onValueChange,
  options = MODEL_OPTIONS,
} = {}) {
  const [uncontrolledValue, setUncontrolledValue] = useState(
    () => options.find((item) => !item.disabled)?.value ?? null,
  );
  const value =
    controlledValue === undefined ? uncontrolledValue : controlledValue;
  const fullLabel =
    options.find((item) => item.value === value)?.label ?? "Choose a model";
  const change = (next) => {
    if (controlledValue === undefined && next) setUncontrolledValue(next);
    onValueChange?.(next);
  };
  return (
    <Select.Root
      items={options}
      value={value}
      onValueChange={change}
      disabled={disabled}
    >
      <TooltipHint content={fullLabel}>
        <Select.Trigger
          compact
          variant="ghost"
          className="model-select__trigger"
          aria-label="Model"
          aria-description={fullLabel}
        >
          <Select.Value placeholder="Choose a model" />
          <Select.Icon>
            <ChevronDown size={14} aria-hidden="true" />
          </Select.Icon>
        </Select.Trigger>
      </TooltipHint>
      <Select.Portal>
        <Select.Positioner>
          <Select.Popup className="model-select__popup" aria-label="Models">
            {options.map((item) => (
              <Select.Item
                key={item.value}
                value={item.value}
                disabled={item.disabled}
              >
                <Select.ItemText>{item.label}</Select.ItemText>
                <Select.ItemIndicator>
                  <Check size={14} aria-hidden="true" />
                </Select.ItemIndicator>
              </Select.Item>
            ))}
          </Select.Popup>
        </Select.Positioner>
      </Select.Portal>
    </Select.Root>
  );
}

function fileFromNative(file, id, url) {
  return {
    id,
    name: file.name,
    mediaType: file.type || undefined,
    size: file.size,
    url,
    status: "ready",
  };
}

var ChatComposer = forwardRef(function ChatComposer2(
  {
    defaultValue = "",
    defaultAttachments = [],
    value,
    onValueChange,
    status = "ready",
    feedbackPlacement = "inline",
    initialRows,
    maxRows,
    disabled,
    readOnly,
    error,
    description,
    secondary,
    attachmentSize = "sm",
    onSubmit,
    onStop,
    onRetry,
  },
  ref,
) {
  const fileCounter = useRef(0);
  const objectUrls = useRef(/* @__PURE__ */ new Map());
  const pendingUrls = useRef(/* @__PURE__ */ new Map());
  const acknowledgedFiles = useRef(/* @__PURE__ */ new WeakMap());
  const mounted = useRef(true);
  const [files, setFiles] = useState2(defaultAttachments);
  const filesRef = useRef(files);
  const [model, setModel] = useState2(MODEL_OPTIONS[0].value);
  useEffect(() => {
    mounted.current = true;
    return () => {
      mounted.current = false;
      for (const url of objectUrls.current.values()) URL.revokeObjectURL(url);
      objectUrls.current.clear();
      pendingUrls.current.clear();
      acknowledgedFiles.current = /* @__PURE__ */ new WeakMap();
    };
  }, []);
  const updateFiles = (next) => {
    const resolved = typeof next === "function" ? next(filesRef.current) : next;
    filesRef.current = resolved;
    setFiles(resolved);
  };
  const releaseUrl = (file) => {
    if (!file.url || pendingUrls.current.has(file.id)) return;
    const url = objectUrls.current.get(file.id);
    if (url) {
      objectUrls.current.delete(file.id);
      URL.revokeObjectURL(url);
    }
  };
  const remove = (file) => {
    updateFiles((current) => current.filter((item) => item.id !== file.id));
    releaseUrl(file);
  };
  const submit = async (submission) => {
    const submittedIds = new Set(submission.attachments.map((file) => file.id));
    const submittedFiles = new Map(
      filesRef.current
        .filter((file) => submittedIds.has(file.id))
        .map((file) => [file.id, file]),
    );
    for (const file of submission.attachments) {
      if (file.url) pendingUrls.current.set(file.id, file.url);
    }
    try {
      await onSubmit(submission, {
        model,
      });
      for (const id of submittedIds) pendingUrls.current.delete(id);
      if (!mounted.current) return;
      for (const [id, file] of submittedFiles) {
        if (!filesRef.current.some((item) => item.id === id)) releaseUrl(file);
      }
      acknowledgedFiles.current.set(submission, submittedFiles);
    } catch (error2) {
      for (const file of submission.attachments) {
        pendingUrls.current.delete(file.id);
        const captured = submittedFiles.get(file.id) ?? file;
        if (!filesRef.current.some((current) => current.id === file.id))
          releaseUrl(captured);
      }
      throw error2;
    }
  };
  const submitted = (submission) => {
    const captured = acknowledgedFiles.current.get(submission);
    acknowledgedFiles.current.delete(submission);
    if (!captured || !mounted.current) return;
    updateFiles((current) => current.filter((file) => !captured.has(file.id)));
  };
  return (
    <FileUpload.Root
      multiple
      disabled={disabled || readOnly}
      aria-label="Message files"
      onFilesSelect={({ accepted }) => {
        const selected = accepted.map((file) => {
          fileCounter.current += 1;
          const previewable =
            /^(image\/(png|jpeg|webp|gif|avif)|application\/pdf|text\/(plain|csv))$/.test(
              file.type,
            );
          const url =
            previewable && typeof URL.createObjectURL === "function"
              ? URL.createObjectURL(file)
              : undefined;
          if (url)
            objectUrls.current.set(`local-file-${fileCounter.current}`, url);
          return fileFromNative(file, `local-file-${fileCounter.current}`, url);
        });
        if (selected.length)
          updateFiles((current) => [...current, ...selected]);
      }}
    >
      <Composer
        ref={ref}
        defaultValue={defaultValue}
        value={value}
        onValueChange={onValueChange}
        attachments={files}
        status={status}
        feedbackPlacement={feedbackPlacement}
        initialRows={initialRows}
        maxRows={maxRows}
        disabled={disabled}
        readOnly={readOnly}
        error={error}
        description={description}
        onStop={onStop}
        onRetry={onRetry}
        onSubmit={submit}
        onSubmitted={submitted}
        secondary={secondary}
        attachmentContent={
          <ComposerAttachments size={attachmentSize} onRemove={remove} />
        }
      >
        <ComposerInput placeholder="Ask a follow-up…" />
        <ComposerToolbar>
          <ComposerToolbar.Start>
            <FileUpload.Trigger
              render={
                <ComposerAction aria-label="Attach files" icon={<Plus />} />
              }
            />
          </ComposerToolbar.Start>
          <ComposerToolbar.End>
            <ModelSelect
              disabled={disabled || readOnly}
              value={model}
              onValueChange={(value2) => {
                if (value2) setModel(value2);
              }}
            />
            <ComposerSubmit />
          </ComposerToolbar.End>
        </ComposerToolbar>
        <FileUpload.Input />
      </Composer>
    </FileUpload.Root>
  );
});

function PreviewWide({ children }) {
  return <div data-preview-wide>{children}</div>;
}

```

tool-failed-decision-in-the-composer-layer-11.css

```css
/* apps/web/src/demos/library/model-select.css */
.model-select__trigger {
  gap: var(--space-2);
  min-inline-size: 0;
  max-inline-size: calc(100vw - (var(--space-4) * 2));
}
.ui-popup.ui-select-popup.model-select__popup {
  max-inline-size: calc(100vw - (var(--space-4) * 2));
}
.ui-select-trigger.model-select__trigger[data-compact] {
  max-inline-size: min(100%, 272px, calc(100vw - (var(--space-4) * 2)));
}

```

### Expired approval

An expired request cannot send another decision.

tool-expired-approval-12.jsx

```jsx
import { ToolApproval } from "@/components/ui/tool-approval";

export default function Example() {
  return (
    <ToolApproval approvalId="expired-weekly" state="expired">
      docs/weekly-update.md
    </ToolApproval>
  );
}

```

### Long approval

The affected path wraps while the two actions remain usable.

tool-long-approval-13.jsx

```jsx
import { useState as useState3 } from "react";
import { ToolApproval } from "@/components/ui/tool-approval";

export default function Example() {
  const [state, setState] = useState3("pending");
  return (
    <ToolApproval
      prompt="Save weekly customer feedback and rollout review?"
      approvalId="long-weekly"
      state={state}
      onApprove={() => setState("approved")}
      onDeny={() => setState("denied")}
    >
      docs/research/weekly-customer-feedback-and-rollout-review.md
    </ToolApproval>
  );
}

```

### Scoped approval choices

Scope choices use the same action group in every placement. Wide hosts keep it at the top right while the prompt flows around its actual size. Hosts at or below 22rem put the group after the review content. Reading and keyboard order remain content-first at both sizes.

The default Allow menu offers Allow once in every placement. approveOptions adds only choices the host can honor. This example records a local choice; your application owns permission storage and enforcement. The Vercel and TanStack examples use their supported one-time approval command.

tool-scoped-approval-choices-14.jsx

```jsx
import { useState as useState3 } from "react";
import { Card } from "@/components/ui/card";
import { ToolApproval } from "@/components/ui/tool-approval";

export default function Example() {
  const [state, setState] = useState3("pending");
  const [scope, setScope] = useState3("");
  const options = [
    {
      id: "once",
      label: "Allow once",
    },
    {
      id: "session",
      label: "Allow for this session",
    },
    {
      id: "workspace",
      label: "Always allow in this workspace",
    },
  ];
  return (
    <PreviewWide>
      <ToolApproval
        approvalId="scoped-weekly"
        prompt="Save weekly update?"
        state={state}
        approveOptions={options}
        onApprove={(optionId) => {
          setScope(
            options.find((option) => option.id === optionId)?.label ?? "",
          );
          setState("approved");
        }}
        onDeny={() => setState("denied")}
      >
        <Card.Root density="compact">
          <code>docs/weekly-update.md</code>
        </Card.Root>
      </ToolApproval>
      {scope ? <p role="status">{scope}</p> : null}
    </PreviewWide>
  );
}

function PreviewWide({ children }) {
  return <div data-preview-wide>{children}</div>;
}

```

### Placement

actionsPlacement="header" is the default: actions share the title row and align right, with Allow last. Set actionsPlacement="content" to put them below the review content, aligned left with Allow first.

#### Inside composer

Place ToolApproval in Composer.secondary. The containing surface owns its padding; the approval adds no background or border. Its nested review surface uses an outline. Supply the decision question through prompt and the affected file or action through children.

tool-inside-composer-15.jsx

```jsx
import { useState as useState3 } from "react";
import { forwardRef, useEffect, useRef, useState as useState2 } from "react";
import { Plus } from "lucide-react";
import {
  Composer,
  ComposerAction,
  ComposerAttachments,
  ComposerInput,
  ComposerSubmit,
  ComposerToolbar,
} from "@/components/ui/composer";
import { FileUpload } from "@/components/ui/file-upload";
import { useState } from "react";
import { Check, ChevronDown } from "lucide-react";
import { Select } from "@/components/ui/select";
import { TooltipHint } from "@/components/ui/tooltip";
import { ToolApproval } from "@/components/ui/tool-approval";

export default function Example() {
  const [state, setState] = useState3("pending");
  const [sent, setSent] = useState3(false);
  return (
    <PreviewWide>
      <ChatComposer
        defaultValue=""
        onSubmit={() => setSent(true)}
        secondary={
          <ToolApproval
            prompt="Save weekly update?"
            approvalId="save-weekly-update"
            state={state}
            onApprove={() => setState("approved")}
            onDeny={() => setState("denied")}
          >
            docs/weekly-update.md
          </ToolApproval>
        }
      />
      {sent ? <p role="status">Message sent.</p> : null}
    </PreviewWide>
  );
}

var MODEL_OPTIONS = [
  {
    value: "chatgpt-sol-6-1",
    label: "Sol 6.1",
  },
  {
    value: "chatgpt-sol-6",
    label: "Sol 6",
  },
  {
    value: "chatgpt-luna-6",
    label: "Luna 6",
  },
];

function ModelSelect({
  disabled,
  value: controlledValue,
  onValueChange,
  options = MODEL_OPTIONS,
} = {}) {
  const [uncontrolledValue, setUncontrolledValue] = useState(
    () => options.find((item) => !item.disabled)?.value ?? null,
  );
  const value =
    controlledValue === undefined ? uncontrolledValue : controlledValue;
  const fullLabel =
    options.find((item) => item.value === value)?.label ?? "Choose a model";
  const change = (next) => {
    if (controlledValue === undefined && next) setUncontrolledValue(next);
    onValueChange?.(next);
  };
  return (
    <Select.Root
      items={options}
      value={value}
      onValueChange={change}
      disabled={disabled}
    >
      <TooltipHint content={fullLabel}>
        <Select.Trigger
          compact
          variant="ghost"
          className="model-select__trigger"
          aria-label="Model"
          aria-description={fullLabel}
        >
          <Select.Value placeholder="Choose a model" />
          <Select.Icon>
            <ChevronDown size={14} aria-hidden="true" />
          </Select.Icon>
        </Select.Trigger>
      </TooltipHint>
      <Select.Portal>
        <Select.Positioner>
          <Select.Popup className="model-select__popup" aria-label="Models">
            {options.map((item) => (
              <Select.Item
                key={item.value}
                value={item.value}
                disabled={item.disabled}
              >
                <Select.ItemText>{item.label}</Select.ItemText>
                <Select.ItemIndicator>
                  <Check size={14} aria-hidden="true" />
                </Select.ItemIndicator>
              </Select.Item>
            ))}
          </Select.Popup>
        </Select.Positioner>
      </Select.Portal>
    </Select.Root>
  );
}

function fileFromNative(file, id, url) {
  return {
    id,
    name: file.name,
    mediaType: file.type || undefined,
    size: file.size,
    url,
    status: "ready",
  };
}

var ChatComposer = forwardRef(function ChatComposer2(
  {
    defaultValue = "",
    defaultAttachments = [],
    value,
    onValueChange,
    status = "ready",
    feedbackPlacement = "inline",
    initialRows,
    maxRows,
    disabled,
    readOnly,
    error,
    description,
    secondary,
    attachmentSize = "sm",
    onSubmit,
    onStop,
    onRetry,
  },
  ref,
) {
  const fileCounter = useRef(0);
  const objectUrls = useRef(/* @__PURE__ */ new Map());
  const pendingUrls = useRef(/* @__PURE__ */ new Map());
  const acknowledgedFiles = useRef(/* @__PURE__ */ new WeakMap());
  const mounted = useRef(true);
  const [files, setFiles] = useState2(defaultAttachments);
  const filesRef = useRef(files);
  const [model, setModel] = useState2(MODEL_OPTIONS[0].value);
  useEffect(() => {
    mounted.current = true;
    return () => {
      mounted.current = false;
      for (const url of objectUrls.current.values()) URL.revokeObjectURL(url);
      objectUrls.current.clear();
      pendingUrls.current.clear();
      acknowledgedFiles.current = /* @__PURE__ */ new WeakMap();
    };
  }, []);
  const updateFiles = (next) => {
    const resolved = typeof next === "function" ? next(filesRef.current) : next;
    filesRef.current = resolved;
    setFiles(resolved);
  };
  const releaseUrl = (file) => {
    if (!file.url || pendingUrls.current.has(file.id)) return;
    const url = objectUrls.current.get(file.id);
    if (url) {
      objectUrls.current.delete(file.id);
      URL.revokeObjectURL(url);
    }
  };
  const remove = (file) => {
    updateFiles((current) => current.filter((item) => item.id !== file.id));
    releaseUrl(file);
  };
  const submit = async (submission) => {
    const submittedIds = new Set(submission.attachments.map((file) => file.id));
    const submittedFiles = new Map(
      filesRef.current
        .filter((file) => submittedIds.has(file.id))
        .map((file) => [file.id, file]),
    );
    for (const file of submission.attachments) {
      if (file.url) pendingUrls.current.set(file.id, file.url);
    }
    try {
      await onSubmit(submission, {
        model,
      });
      for (const id of submittedIds) pendingUrls.current.delete(id);
      if (!mounted.current) return;
      for (const [id, file] of submittedFiles) {
        if (!filesRef.current.some((item) => item.id === id)) releaseUrl(file);
      }
      acknowledgedFiles.current.set(submission, submittedFiles);
    } catch (error2) {
      for (const file of submission.attachments) {
        pendingUrls.current.delete(file.id);
        const captured = submittedFiles.get(file.id) ?? file;
        if (!filesRef.current.some((current) => current.id === file.id))
          releaseUrl(captured);
      }
      throw error2;
    }
  };
  const submitted = (submission) => {
    const captured = acknowledgedFiles.current.get(submission);
    acknowledgedFiles.current.delete(submission);
    if (!captured || !mounted.current) return;
    updateFiles((current) => current.filter((file) => !captured.has(file.id)));
  };
  return (
    <FileUpload.Root
      multiple
      disabled={disabled || readOnly}
      aria-label="Message files"
      onFilesSelect={({ accepted }) => {
        const selected = accepted.map((file) => {
          fileCounter.current += 1;
          const previewable =
            /^(image\/(png|jpeg|webp|gif|avif)|application\/pdf|text\/(plain|csv))$/.test(
              file.type,
            );
          const url =
            previewable && typeof URL.createObjectURL === "function"
              ? URL.createObjectURL(file)
              : undefined;
          if (url)
            objectUrls.current.set(`local-file-${fileCounter.current}`, url);
          return fileFromNative(file, `local-file-${fileCounter.current}`, url);
        });
        if (selected.length)
          updateFiles((current) => [...current, ...selected]);
      }}
    >
      <Composer
        ref={ref}
        defaultValue={defaultValue}
        value={value}
        onValueChange={onValueChange}
        attachments={files}
        status={status}
        feedbackPlacement={feedbackPlacement}
        initialRows={initialRows}
        maxRows={maxRows}
        disabled={disabled}
        readOnly={readOnly}
        error={error}
        description={description}
        onStop={onStop}
        onRetry={onRetry}
        onSubmit={submit}
        onSubmitted={submitted}
        secondary={secondary}
        attachmentContent={
          <ComposerAttachments size={attachmentSize} onRemove={remove} />
        }
      >
        <ComposerInput placeholder="Ask a follow-up…" />
        <ComposerToolbar>
          <ComposerToolbar.Start>
            <FileUpload.Trigger
              render={
                <ComposerAction aria-label="Attach files" icon={<Plus />} />
              }
            />
          </ComposerToolbar.Start>
          <ComposerToolbar.End>
            <ModelSelect
              disabled={disabled || readOnly}
              value={model}
              onValueChange={(value2) => {
                if (value2) setModel(value2);
              }}
            />
            <ComposerSubmit />
          </ComposerToolbar.End>
        </ComposerToolbar>
        <FileUpload.Input />
      </Composer>
    </FileUpload.Root>
  );
});

function PreviewWide({ children }) {
  return <div data-preview-wide>{children}</div>;
}

```

tool-inside-composer-15.css

```css
/* apps/web/src/demos/library/model-select.css */
.model-select__trigger {
  gap: var(--space-2);
  min-inline-size: 0;
  max-inline-size: calc(100vw - (var(--space-4) * 2));
}
.ui-popup.ui-select-popup.model-select__popup {
  max-inline-size: calc(100vw - (var(--space-4) * 2));
}
.ui-select-trigger.model-select__trigger[data-compact] {
  max-inline-size: min(100%, 272px, calc(100vw - (var(--space-4) * 2)));
}

```

#### Outside composer

The approval supplies its own compact outline card, with a subtle nested review surface. No additional Card wrapper is needed.

tool-outside-composer-16.jsx

```jsx
import { useState as useState3 } from "react";
import { forwardRef, useEffect, useRef, useState as useState2 } from "react";
import { Plus } from "lucide-react";
import {
  Composer,
  ComposerAction,
  ComposerAttachments,
  ComposerInput,
  ComposerSubmit,
  ComposerToolbar,
} from "@/components/ui/composer";
import { FileUpload } from "@/components/ui/file-upload";
import { useState } from "react";
import { Check, ChevronDown } from "lucide-react";
import { Select } from "@/components/ui/select";
import { TooltipHint } from "@/components/ui/tooltip";
import { Snippet } from "@/components/ui/snippet";
import { ToolApproval } from "@/components/ui/tool-approval";

export default function Example() {
  return (
    <PreviewWide>
      <div
        style={{
          display: "grid",
          gap: "var(--space-3)",
        }}
      >
        <RequestApproval kind="email" />
        <ChatComposer onSubmit={() => undefined} />
      </div>
    </PreviewWide>
  );
}

var MODEL_OPTIONS = [
  {
    value: "chatgpt-sol-6-1",
    label: "Sol 6.1",
  },
  {
    value: "chatgpt-sol-6",
    label: "Sol 6",
  },
  {
    value: "chatgpt-luna-6",
    label: "Luna 6",
  },
];

function ModelSelect({
  disabled,
  value: controlledValue,
  onValueChange,
  options = MODEL_OPTIONS,
} = {}) {
  const [uncontrolledValue, setUncontrolledValue] = useState(
    () => options.find((item) => !item.disabled)?.value ?? null,
  );
  const value =
    controlledValue === undefined ? uncontrolledValue : controlledValue;
  const fullLabel =
    options.find((item) => item.value === value)?.label ?? "Choose a model";
  const change = (next) => {
    if (controlledValue === undefined && next) setUncontrolledValue(next);
    onValueChange?.(next);
  };
  return (
    <Select.Root
      items={options}
      value={value}
      onValueChange={change}
      disabled={disabled}
    >
      <TooltipHint content={fullLabel}>
        <Select.Trigger
          compact
          variant="ghost"
          className="model-select__trigger"
          aria-label="Model"
          aria-description={fullLabel}
        >
          <Select.Value placeholder="Choose a model" />
          <Select.Icon>
            <ChevronDown size={14} aria-hidden="true" />
          </Select.Icon>
        </Select.Trigger>
      </TooltipHint>
      <Select.Portal>
        <Select.Positioner>
          <Select.Popup className="model-select__popup" aria-label="Models">
            {options.map((item) => (
              <Select.Item
                key={item.value}
                value={item.value}
                disabled={item.disabled}
              >
                <Select.ItemText>{item.label}</Select.ItemText>
                <Select.ItemIndicator>
                  <Check size={14} aria-hidden="true" />
                </Select.ItemIndicator>
              </Select.Item>
            ))}
          </Select.Popup>
        </Select.Positioner>
      </Select.Portal>
    </Select.Root>
  );
}

function fileFromNative(file, id, url) {
  return {
    id,
    name: file.name,
    mediaType: file.type || undefined,
    size: file.size,
    url,
    status: "ready",
  };
}

var ChatComposer = forwardRef(function ChatComposer2(
  {
    defaultValue = "",
    defaultAttachments = [],
    value,
    onValueChange,
    status = "ready",
    feedbackPlacement = "inline",
    initialRows,
    maxRows,
    disabled,
    readOnly,
    error,
    description,
    secondary,
    attachmentSize = "sm",
    onSubmit,
    onStop,
    onRetry,
  },
  ref,
) {
  const fileCounter = useRef(0);
  const objectUrls = useRef(/* @__PURE__ */ new Map());
  const pendingUrls = useRef(/* @__PURE__ */ new Map());
  const acknowledgedFiles = useRef(/* @__PURE__ */ new WeakMap());
  const mounted = useRef(true);
  const [files, setFiles] = useState2(defaultAttachments);
  const filesRef = useRef(files);
  const [model, setModel] = useState2(MODEL_OPTIONS[0].value);
  useEffect(() => {
    mounted.current = true;
    return () => {
      mounted.current = false;
      for (const url of objectUrls.current.values()) URL.revokeObjectURL(url);
      objectUrls.current.clear();
      pendingUrls.current.clear();
      acknowledgedFiles.current = /* @__PURE__ */ new WeakMap();
    };
  }, []);
  const updateFiles = (next) => {
    const resolved = typeof next === "function" ? next(filesRef.current) : next;
    filesRef.current = resolved;
    setFiles(resolved);
  };
  const releaseUrl = (file) => {
    if (!file.url || pendingUrls.current.has(file.id)) return;
    const url = objectUrls.current.get(file.id);
    if (url) {
      objectUrls.current.delete(file.id);
      URL.revokeObjectURL(url);
    }
  };
  const remove = (file) => {
    updateFiles((current) => current.filter((item) => item.id !== file.id));
    releaseUrl(file);
  };
  const submit = async (submission) => {
    const submittedIds = new Set(submission.attachments.map((file) => file.id));
    const submittedFiles = new Map(
      filesRef.current
        .filter((file) => submittedIds.has(file.id))
        .map((file) => [file.id, file]),
    );
    for (const file of submission.attachments) {
      if (file.url) pendingUrls.current.set(file.id, file.url);
    }
    try {
      await onSubmit(submission, {
        model,
      });
      for (const id of submittedIds) pendingUrls.current.delete(id);
      if (!mounted.current) return;
      for (const [id, file] of submittedFiles) {
        if (!filesRef.current.some((item) => item.id === id)) releaseUrl(file);
      }
      acknowledgedFiles.current.set(submission, submittedFiles);
    } catch (error2) {
      for (const file of submission.attachments) {
        pendingUrls.current.delete(file.id);
        const captured = submittedFiles.get(file.id) ?? file;
        if (!filesRef.current.some((current) => current.id === file.id))
          releaseUrl(captured);
      }
      throw error2;
    }
  };
  const submitted = (submission) => {
    const captured = acknowledgedFiles.current.get(submission);
    acknowledgedFiles.current.delete(submission);
    if (!captured || !mounted.current) return;
    updateFiles((current) => current.filter((file) => !captured.has(file.id)));
  };
  return (
    <FileUpload.Root
      multiple
      disabled={disabled || readOnly}
      aria-label="Message files"
      onFilesSelect={({ accepted }) => {
        const selected = accepted.map((file) => {
          fileCounter.current += 1;
          const previewable =
            /^(image\/(png|jpeg|webp|gif|avif)|application\/pdf|text\/(plain|csv))$/.test(
              file.type,
            );
          const url =
            previewable && typeof URL.createObjectURL === "function"
              ? URL.createObjectURL(file)
              : undefined;
          if (url)
            objectUrls.current.set(`local-file-${fileCounter.current}`, url);
          return fileFromNative(file, `local-file-${fileCounter.current}`, url);
        });
        if (selected.length)
          updateFiles((current) => [...current, ...selected]);
      }}
    >
      <Composer
        ref={ref}
        defaultValue={defaultValue}
        value={value}
        onValueChange={onValueChange}
        attachments={files}
        status={status}
        feedbackPlacement={feedbackPlacement}
        initialRows={initialRows}
        maxRows={maxRows}
        disabled={disabled}
        readOnly={readOnly}
        error={error}
        description={description}
        onStop={onStop}
        onRetry={onRetry}
        onSubmit={submit}
        onSubmitted={submitted}
        secondary={secondary}
        attachmentContent={
          <ComposerAttachments size={attachmentSize} onRemove={remove} />
        }
      >
        <ComposerInput placeholder="Ask a follow-up…" />
        <ComposerToolbar>
          <ComposerToolbar.Start>
            <FileUpload.Trigger
              render={
                <ComposerAction aria-label="Attach files" icon={<Plus />} />
              }
            />
          </ComposerToolbar.Start>
          <ComposerToolbar.End>
            <ModelSelect
              disabled={disabled || readOnly}
              value={model}
              onValueChange={(value2) => {
                if (value2) setModel(value2);
              }}
            />
            <ComposerSubmit />
          </ComposerToolbar.End>
        </ComposerToolbar>
        <FileUpload.Input />
      </Composer>
    </FileUpload.Root>
  );
});

function PreviewWide({ children }) {
  return <div data-preview-wide>{children}</div>;
}

function RequestApproval({ kind = "file" }) {
  const [state, setState] = useState3("pending");
  const payload = (
    <>
      <small>Gmail · to product-team@example.com</small>
      <Snippet
        value="The workspace experiment is ready for review. Start with a sample workspace, then ask teams to connect their account."
        title="Weekly product update · 21 October"
        contentType="text"
        variant="block"
      />
    </>
  );
  return (
    <ToolApproval
      approvalId={`weekly-${"email"}`}
      prompt={"Send the weekly update?"}
      state={state}
      onApprove={() => setState("approved")}
      onDeny={() => setState("denied")}
    >
      {payload}
    </ToolApproval>
  );
}

```

tool-outside-composer-16.css

```css
/* apps/web/src/demos/library/model-select.css */
.model-select__trigger {
  gap: var(--space-2);
  min-inline-size: 0;
  max-inline-size: calc(100vw - (var(--space-4) * 2));
}
.ui-popup.ui-select-popup.model-select__popup {
  max-inline-size: calc(100vw - (var(--space-4) * 2));
}
.ui-select-trigger.model-select__trigger[data-compact] {
  max-inline-size: min(100%, 272px, calc(100vw - (var(--space-4) * 2)));
}

```

##### Approval in an agent message

Review the proposed email as part of the assistant response.

tool-approval-in-an-agent-message-17.jsx

```jsx
import { useState as useState3 } from "react";
import { Snippet } from "@/components/ui/snippet";
import { ToolApproval } from "@/components/ui/tool-approval";
import { Message, MessageBody, MessageContent } from "@/components/ui/message";

export default function Example() {
  return (
    <PreviewWide>
      <Message actor="assistant">
        <MessageContent>
          <MessageBody
            style={{
              display: "grid",
              gap: "var(--space-3)",
            }}
          >
            <p>The weekly update is drafted.</p>
            <RequestApproval kind="email" />
          </MessageBody>
        </MessageContent>
      </Message>
    </PreviewWide>
  );
}

function PreviewWide({ children }) {
  return <div data-preview-wide>{children}</div>;
}

function RequestApproval({ kind = "file" }) {
  const [state, setState] = useState3("pending");
  const prompt =
    kind === "email" ? "Send the weekly update?" : "Save weekly update?";
  const payload =
    kind === "email" ? (
      <>
        <small>Gmail · to product-team@example.com</small>
        <Snippet
          value="The workspace experiment is ready for review. Start with a sample workspace, then ask teams to connect their account."
          title="Weekly product update · 21 October"
          contentType="text"
          variant="block"
        />
      </>
    ) : (
      "docs/weekly-update.md"
    );
  return (
    <ToolApproval
      approvalId={`weekly-${kind}`}
      prompt={prompt}
      state={state}
      onApprove={() => setState("approved")}
      onDeny={() => setState("denied")}
    >
      {payload}
    </ToolApproval>
  );
}

```

#### Inside activity

Place the decision in ActivityContent. The branch keeps its left rail; the approval and its nested review surface use the same treatment as outside Composer.

tool-inside-activity-18.jsx

```jsx
import { useState as useState3 } from "react";
import {
  Activity,
  ActivityContent,
  ActivitySummary,
} from "@/components/ui/activity";
import { Snippet } from "@/components/ui/snippet";
import { ToolApproval } from "@/components/ui/tool-approval";

export default function Example() {
  return (
    <PreviewWide>
      <Activity defaultOpen status="pending">
        <ActivitySummary state="pending">
          Preparing the weekly update
        </ActivitySummary>
        <ActivityContent>
          <RequestApproval kind="email" />
        </ActivityContent>
      </Activity>
    </PreviewWide>
  );
}

function PreviewWide({ children }) {
  return <div data-preview-wide>{children}</div>;
}

function RequestApproval({ kind = "file" }) {
  const [state, setState] = useState3("pending");
  const prompt =
    kind === "email" ? "Send the weekly update?" : "Save weekly update?";
  const payload =
    kind === "email" ? (
      <>
        <small>Gmail · to product-team@example.com</small>
        <Snippet
          value="The workspace experiment is ready for review. Start with a sample workspace, then ask teams to connect their account."
          title="Weekly product update · 21 October"
          contentType="text"
          variant="block"
        />
      </>
    ) : (
      "docs/weekly-update.md"
    );
  return (
    <ToolApproval
      approvalId={`weekly-${kind}`}
      prompt={prompt}
      state={state}
      onApprove={() => setState("approved")}
      onDeny={() => setState("denied")}
    >
      {payload}
    </ToolApproval>
  );
}

```

## Integrations

### Vercel AI SDK

An actual installed SDK hook and deterministic native transport drive approval and output.

tool-vercel-ai-sdk-19.jsx

```jsx
import { Button as Button2 } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { FileText, FolderCheck, ListChecks } from "lucide-react";
import { useId as useId2, useRef, useState as useState2 } from "react";
import { useId } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import { simulateReadableStream } from "ai";
import {
  INTERRUPT_BINDING_VERSION,
  hashSchemaInput,
  normalizeApprovalSchema,
  toolDefinition,
  withInterruptBinding,
} from "@tanstack/ai";
import { z } from "zod";
import { useChat as useAiSdkChat } from "@ai-sdk/react";
import "@tanstack/ai-react";
import {
  Activity as Activity2,
  ActivityContent,
  ActivityList,
  ActivitySummary,
} from "@/components/ui/activity";
import { AgentTodoList } from "@/components/ui/agent-todo-list";
import { Tool, ToolOutput } from "@/components/ui/tool";
import { ToolApproval } from "@/components/ui/tool-approval";
import { createAiSdkAdapter } from "@/lib/chat-adapters/ai-sdk";
import { createTanStackAdapter } from "@/lib/chat-adapters/tanstack";

export default function Example() {
  const sessionId = useId2();
  const [run, setRun] = useState2(0);
  return (
    <AiSdkAgentRun
      key={run}
      sessionId={`${sessionId}-${run}`}
      onReplay={() => setRun((value) => value + 1)}
    />
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: "Review the weekly update and save it.",
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? pendingIndicator : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={undefined}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {undefined}
    </div>
  );
}

var output = {
  path: "docs/weekly-update.md",
  saved: true,
};

var activityEvents = [
  {
    id: "read-update",
    kind: "read",
    state: "complete",
    label: "Read the weekly update",
    icon: <FileText />,
  },
  {
    id: "check-destination",
    kind: "check",
    state: "complete",
    label: "Check the destination",
    icon: <FolderCheck />,
  },
];

var todoItems = [
  {
    id: "review-draft",
    label: "Review the update",
    status: "complete",
  },
  {
    id: "save-draft",
    label: "Save the approved update",
    status: "active",
  },
];

var aiInitialMessages = [
  {
    id: "weekly-update-request",
    role: "user",
    parts: [
      {
        type: "text",
        text: "Save the reviewed weekly update.",
      },
    ],
  },
  {
    id: "weekly-update-agent",
    role: "assistant",
    parts: [
      {
        type: "tool-saveWeeklyUpdate",
        toolCallId: "save-weekly-update-call",
        state: "approval-requested",
        input: {
          path: "docs/weekly-update.md",
        },
        approval: {
          id: "save-weekly-update-approval",
          requestReason: "Save the reviewed weekly update?",
        },
      },
    ],
  },
];

var saveTool = toolDefinition({
  name: "saveWeeklyUpdate",
  description: "Save the reviewed weekly update.",
  needsApproval: true,
  inputSchema: z.object({
    path: z.string(),
  }),
  outputSchema: z.object({
    path: z.string(),
    saved: z.boolean(),
  }),
}).client();

var approvalSchema = normalizeApprovalSchema(undefined, saveTool.inputSchema);

var tanStackResumeSnapshot = {
  resumeState: {
    threadId: "weekly-update",
    runId: "weekly-update-paused",
  },
  pendingInterrupts: [
    withInterruptBinding(
      {
        id: "save-weekly-update-approval",
        reason: "tool_call",
        toolCallId: "save-weekly-update-call",
        message: "Save weekly update?",
        responseSchema: approvalSchema.responseSchema,
      },
      {
        v: INTERRUPT_BINDING_VERSION,
        kind: "tool-approval",
        interruptId: "save-weekly-update-approval",
        interruptedRunId: "weekly-update-paused",
        generation: 0,
        toolName: saveTool.name,
        toolCallId: "save-weekly-update-call",
        originalArgs: {
          path: "docs/weekly-update.md",
        },
        inputSchemaHash: hashSchemaInput(saveTool.inputSchema),
        approvalSchemaHash: approvalSchema.approvalSchemaHash,
        responseSchemaHash: approvalSchema.responseSchemaHash,
      },
    ),
  ],
};

var aiSdkTransport = {
  async sendMessages({ messages }) {
    await new Promise((resolve) => setTimeout(resolve, 35));
    const tool = messages
      .flatMap((message) => ("parts" in message ? message.parts : []))
      .find((part) => part.type === "tool-saveWeeklyUpdate");
    if (!tool || tool.type !== "tool-saveWeeklyUpdate")
      throw new Error("The weekly update request is unavailable.");
    const chunks =
      tool.state === "approval-responded" && tool.approval?.approved
        ? [
            {
              type: "tool-output-available",
              toolCallId: "save-weekly-update-call",
              output,
            },
            {
              type: "start",
              messageId: "weekly-update-result",
            },
            {
              type: "text-start",
              id: "weekly-update-answer",
            },
            ..."The update is saved in docs/weekly-update.md."
              .match(/\S+\s*/g)
              .map((delta) => ({
                type: "text-delta",
                id: "weekly-update-answer",
                delta,
              })),
            {
              type: "text-end",
              id: "weekly-update-answer",
            },
            {
              type: "finish",
              finishReason: "stop",
            },
          ]
        : tool.state === "approval-responded" &&
            tool.approval?.approved === false
          ? [
              {
                type: "tool-output-denied",
                toolCallId: "save-weekly-update-call",
              },
              {
                type: "finish",
                finishReason: "stop",
              },
            ]
          : [];
    return simulateReadableStream({
      chunks,
      chunkDelayInMs: 80,
    });
  },
  async reconnectToStream() {
    return null;
  },
};

var aiSdkAdapter = createAiSdkAdapter();

var tanStackAdapter = createTanStackAdapter();

function AgentWork({ messages, onApprove, onDeny, onReplay, status, onStop }) {
  const currentTool = messages
    .flatMap((message) => message.parts)
    .find((part) => part.type === "tool");
  const approvalGranted =
    currentTool?.approval?.state === "approved" ||
    currentTool?.state === "output-ready";
  const completed = currentTool?.state === "output-ready";
  const denied =
    currentTool?.approval?.state === "denied" ||
    currentTool?.state === "cancelled";
  const decisionState = approvalGranted
    ? "approved"
    : denied
      ? "denied"
      : "pending";
  const currentTodos = todoItems.map((item) =>
    item.id === "save-draft"
      ? {
          ...item,
          status: completed ? "complete" : denied ? "cancelled" : "active",
        }
      : item,
  );
  const parts = messages
    .filter((message) => message.actor === "assistant")
    .flatMap((message) => message.parts)
    .filter((part) => part.type === "text")
    .map((part) => ({
      ...part,
      state: status === "streaming" ? "streaming" : "complete",
    }));
  const response = {
    id: "weekly-update-response",
    actor: "assistant",
    author: activityAgent,
    status,
    parts: parts.length
      ? parts
      : denied
        ? [
            {
              type: "text",
              id: "denied",
              text: "The save was declined. No update was saved.",
            },
          ]
        : [],
  };
  return (
    <ActivityConversationTurn
      prompt="Review the weekly update and save it."
      response={response}
      onReplay={onReplay}
      pendingIndicator={<ThinkingActivity />}
      footer={
        status === "streaming" ? (
          <Button2 type="button" variant="outline" size="sm" onClick={onStop}>
            Stop
          </Button2>
        ) : status === "stopped" ? (
          <span role="status">Response stopped.</span>
        ) : null
      }
    >
      <div
        style={{
          display: "grid",
          gap: "var(--space-1)",
        }}
      >
        <Activity2 status="complete" defaultOpen>
          <ActivitySummary icon={<ListChecks />} state="complete">
            Reviewed the weekly update
          </ActivitySummary>
          <ActivityContent>
            <ActivityList events={activityEvents} />
          </ActivityContent>
        </Activity2>
        <AgentTodoList title="Weekly update" items={currentTodos} />
        {!completed && !denied ? (
          <ToolApproval
            approvalId={"save-weekly-update-approval"}
            state={decisionState}
            prompt="Save weekly update?"
            onApprove={onApprove}
            onDeny={onDeny}
          >
            <Card.Root density="compact">
              <code>docs/weekly-update.md</code>
            </Card.Root>
          </ToolApproval>
        ) : denied ? null : (
          <Tool name="Save weekly update" state="output-ready" defaultOpen>
            <ToolOutput>
              <code>
                {typeof currentTool?.output === "string"
                  ? currentTool.output
                  : JSON.stringify(currentTool?.output)}
              </code>
            </ToolOutput>
          </Tool>
        )}
      </div>
    </ActivityConversationTurn>
  );
}

function AiSdkAgentRun({ onReplay, sessionId }) {
  const [stopped, setStopped] = useState2(false);
  const { messages, addToolApprovalResponse, error, status, stop } =
    useAiSdkChat({
      id: sessionId,
      messages: aiInitialMessages,
      transport: aiSdkTransport,
      sendAutomaticallyWhen: ({ messages: current2 }) =>
        current2.some((message) =>
          message.parts.some(
            (part) =>
              part.type === "tool-saveWeeklyUpdate" &&
              part.state === "approval-responded" &&
              part.approval?.approved !== undefined,
          ),
        ),
    });
  const normalized = aiSdkAdapter.normalizeMessages(messages);
  const latestTool = normalized
    .flatMap((message) => message.parts)
    .find((part) => part.type === "tool");
  const current = useRef(latestTool);
  current.current = latestTool;
  const bind = (id) =>
    aiSdkAdapter.bindApproval({
      approvalId: id,
      addToolApprovalResponse: async (response) => {
        await addToolApprovalResponse(response);
      },
      getCurrent: () => current.current,
    });
  return (
    <div
      data-preview-wide
      style={{
        width: 560,
        maxWidth: "100%",
      }}
    >
      {error ? <p role="alert">{error.message}</p> : null}
      <AgentWork
        messages={normalized}
        status={
          stopped
            ? "stopped"
            : status === "streaming" || status === "submitted"
              ? "streaming"
              : status === "error"
                ? "error"
                : "complete"
        }
        onReplay={onReplay}
        onStop={() => {
          setStopped(true);
          void stop();
        }}
        onApprove={async () => {
          await bind("save-weekly-update-approval")(true);
        }}
        onDeny={async () => {
          await bind("save-weekly-update-approval")(false);
        }}
      />
    </div>
  );
}

```

### TanStack AI

The TanStack v1 hook restores a native paused run and resolves a bound tool-approval interrupt. The local connection receives its native continuation; it calls no model or filesystem.

tool-tanstack-ai-20.jsx

```jsx
import { Button as Button2 } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { FileText, FolderCheck, ListChecks } from "lucide-react";
import { useId as useId2, useRef, useState as useState2 } from "react";
import { useId } from "react";
import {
  Activity,
  ActivityLine,
  ActivityTitle,
} from "@/components/ui/activity";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
  Conversation,
  ConversationContent,
  ConversationItem,
} from "@/components/ui/conversation";
import { Ellipsis } from "@/components/ui/loader";
import {
  Message,
  MessageAvatar,
  MessageBody,
  MessageContent,
  MessageFooter,
  MessageHeader,
} from "@/components/ui/message";
import { MessageParts } from "@/components/ui/message-parts";
import {
  EventType,
  INTERRUPT_BINDING_VERSION,
  hashSchemaInput,
  normalizeApprovalSchema,
  toolDefinition,
  withInterruptBinding,
} from "@tanstack/ai";
import { z } from "zod";
import { useChat as useTanStackChat } from "@tanstack/ai-react";
import {
  Activity as Activity2,
  ActivityContent,
  ActivityList,
  ActivitySummary,
} from "@/components/ui/activity";
import { AgentTodoList } from "@/components/ui/agent-todo-list";
import { Tool, ToolOutput } from "@/components/ui/tool";
import { ToolApproval } from "@/components/ui/tool-approval";
import { createAiSdkAdapter } from "@/lib/chat-adapters/ai-sdk";
import { createTanStackAdapter } from "@/lib/chat-adapters/tanstack";

export default function Example() {
  const sessionId = useId2();
  const [run, setRun] = useState2(0);
  return (
    <TanStackAgentRun
      key={run}
      sessionId={`${sessionId}-${run}`}
      onReplay={() => setRun((value) => value + 1)}
    />
  );
}

var user = {
  id: "user",
  name: "You",
  kind: "human",
};

var activityAgent = {
  id: "release-assistant",
  name: "Release assistant",
  kind: "agent",
};

var participants = [user, activityAgent];

function ThinkingActivity() {
  return (
    <Activity status="active">
      <ActivityLine state="active">
        <ActivityTitle>
          Thinking
          <Ellipsis />
        </ActivityTitle>
      </ActivityLine>
    </Activity>
  );
}

function ActivityConversationTurn({
  prompt,
  response,
  children,
  composer,
  footer,
  renderers,
  onReplay,
  pendingIndicator,
  participants: roster = participants,
}) {
  const turnId = useId();
  const request = {
    id: `${turnId}-prompt`,
    actor: "user",
    author: user,
    parts: [
      {
        type: "text",
        text: "Review the weekly update and save it.",
      },
    ],
  };
  const hasActivity = response.parts.some((part) => part.type === "activity");
  const thinking =
    response.status === "streaming" &&
    !children &&
    !response.parts.some(
      (part) => part.type !== "text" || part.text.length > 0,
    );
  return (
    <div
      data-preview-wide
      style={{
        display: "grid",
        gap: "var(--space-4)",
        width: 560,
        maxWidth: "100%",
      }}
    >
      <Conversation
        label="Activity conversation"
        currentUserId={user.id}
        participants={roster}
        initialPosition="start"
        follow="never"
        style={{
          "--conversation-height": "auto",
        }}
      >
        <ConversationContent>
          <ConversationItem id={request.id} message={request}>
            <Message actor="user">
              <MessageBody>
                <MessageParts parts={request.parts} />
              </MessageBody>
            </Message>
          </ConversationItem>
          <ConversationItem id={`${turnId}-response`} message={response}>
            <Message
              actor="assistant"
              status={response.status}
              className="ui-activity-demo-message"
            >
              <MessageAvatar
                style={
                  hasActivity
                    ? {
                        marginBlockStart:
                          "calc((var(--space-8) - var(--space-6)) / 2)",
                      }
                    : undefined
                }
              >
                <Avatar
                  name={response.author?.name ?? activityAgent.name}
                  kind="agent"
                  seed={response.author?.id ?? activityAgent.id}
                  aria-hidden="true"
                />
              </MessageAvatar>
              <MessageContent>
                {!hasActivity ? (
                  <MessageHeader>
                    {response.author?.name ?? activityAgent.name}
                  </MessageHeader>
                ) : null}
                <MessageBody>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "minmax(0, 1fr)",
                      gap: "var(--space-2)",
                    }}
                  >
                    {thinking ? pendingIndicator : null}
                    {children}
                    <MessageParts
                      parts={response.parts}
                      renderers={undefined}
                      activityLabel={
                        hasActivity && roster.length > 2 ? (
                          <MessageHeader render={<ActivityTitle />}>
                            {response.author?.name ?? activityAgent.name}
                          </MessageHeader>
                        ) : undefined
                      }
                    />
                  </div>
                </MessageBody>
                <MessageFooter>
                  {footer}
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onReplay}
                  >
                    Replay
                  </Button>
                </MessageFooter>
              </MessageContent>
            </Message>
          </ConversationItem>
        </ConversationContent>
      </Conversation>
      {undefined}
    </div>
  );
}

var output = {
  path: "docs/weekly-update.md",
  saved: true,
};

var activityEvents = [
  {
    id: "read-update",
    kind: "read",
    state: "complete",
    label: "Read the weekly update",
    icon: <FileText />,
  },
  {
    id: "check-destination",
    kind: "check",
    state: "complete",
    label: "Check the destination",
    icon: <FolderCheck />,
  },
];

var todoItems = [
  {
    id: "review-draft",
    label: "Review the update",
    status: "complete",
  },
  {
    id: "save-draft",
    label: "Save the approved update",
    status: "active",
  },
];

var tanStackInitialMessages = [
  {
    id: "weekly-update-request",
    role: "user",
    parts: [
      {
        type: "text",
        content: "Save the reviewed weekly update.",
      },
    ],
  },
  {
    id: "weekly-update-agent",
    role: "assistant",
    parts: [
      {
        type: "tool-call",
        id: "save-weekly-update-call",
        name: "saveWeeklyUpdate",
        arguments: '{"path":"docs/weekly-update.md"}',
        state: "approval-requested",
        input: {
          path: "docs/weekly-update.md",
        },
        approval: {
          id: "save-weekly-update-approval",
          needsApproval: true,
        },
      },
    ],
  },
];

var saveTool = toolDefinition({
  name: "saveWeeklyUpdate",
  description: "Save the reviewed weekly update.",
  needsApproval: true,
  inputSchema: z.object({
    path: z.string(),
  }),
  outputSchema: z.object({
    path: z.string(),
    saved: z.boolean(),
  }),
}).client();

var approvalSchema = normalizeApprovalSchema(undefined, saveTool.inputSchema);

var tanStackResumeSnapshot = {
  resumeState: {
    threadId: "weekly-update",
    runId: "weekly-update-paused",
  },
  pendingInterrupts: [
    withInterruptBinding(
      {
        id: "save-weekly-update-approval",
        reason: "tool_call",
        toolCallId: "save-weekly-update-call",
        message: "Save weekly update?",
        responseSchema: approvalSchema.responseSchema,
      },
      {
        v: INTERRUPT_BINDING_VERSION,
        kind: "tool-approval",
        interruptId: "save-weekly-update-approval",
        interruptedRunId: "weekly-update-paused",
        generation: 0,
        toolName: saveTool.name,
        toolCallId: "save-weekly-update-call",
        originalArgs: {
          path: "docs/weekly-update.md",
        },
        inputSchemaHash: hashSchemaInput(saveTool.inputSchema),
        approvalSchemaHash: approvalSchema.approvalSchemaHash,
        responseSchemaHash: approvalSchema.responseSchemaHash,
      },
    ),
  ],
};

var tanStackConnection = {
  async *connect(_messages, _data, signal, context) {
    await new Promise((resolve) => setTimeout(resolve, 35));
    const resolution = context?.resume?.find(
      (item) => item.interruptId === "save-weekly-update-approval",
    );
    const payload =
      resolution?.status === "resolved" ? resolution.payload : undefined;
    if (
      context?.parentRunId !== tanStackResumeSnapshot.resumeState.runId ||
      context.resume?.length !== 1 ||
      !payload ||
      typeof payload !== "object" ||
      !("approved" in payload) ||
      typeof payload.approved !== "boolean"
    ) {
      throw new Error("The native approval continuation is unavailable.");
    }
    const approved = payload.approved;
    const threadId = context?.threadId ?? "weekly-update";
    const runId = context?.runId ?? "weekly-update-run";
    yield {
      type: EventType.RUN_STARTED,
      threadId,
      runId,
    };
    if (!approved) {
      yield {
        type: EventType.RUN_FINISHED,
        threadId,
        runId,
      };
      return;
    }
    if (signal?.aborted) return;
    yield {
      type: EventType.TOOL_CALL_RESULT,
      messageId: "weekly-update-result",
      toolCallId: "save-weekly-update-call",
      content: JSON.stringify(output),
      role: "tool",
    };
    yield {
      type: EventType.TEXT_MESSAGE_START,
      messageId: "weekly-update-answer",
      role: "assistant",
    };
    for (const delta of "The update is saved in docs/weekly-update.md.".match(
      /\S+\s*/g,
    )) {
      await new Promise((resolve) => setTimeout(resolve, 80));
      if (signal?.aborted) return;
      yield {
        type: EventType.TEXT_MESSAGE_CONTENT,
        messageId: "weekly-update-answer",
        delta,
      };
    }
    yield {
      type: EventType.TEXT_MESSAGE_END,
      messageId: "weekly-update-answer",
    };
    yield {
      type: EventType.RUN_FINISHED,
      threadId,
      runId,
    };
  },
};

var aiSdkAdapter = createAiSdkAdapter();

var tanStackAdapter = createTanStackAdapter();

function AgentWork({ messages, onApprove, onDeny, onReplay, status, onStop }) {
  const currentTool = messages
    .flatMap((message) => message.parts)
    .find((part) => part.type === "tool");
  const approvalGranted =
    currentTool?.approval?.state === "approved" ||
    currentTool?.state === "output-ready";
  const completed = currentTool?.state === "output-ready";
  const denied =
    currentTool?.approval?.state === "denied" ||
    currentTool?.state === "cancelled";
  const decisionState = approvalGranted
    ? "approved"
    : denied
      ? "denied"
      : "pending";
  const currentTodos = todoItems.map((item) =>
    item.id === "save-draft"
      ? {
          ...item,
          status: completed ? "complete" : denied ? "cancelled" : "active",
        }
      : item,
  );
  const parts = messages
    .filter((message) => message.actor === "assistant")
    .flatMap((message) => message.parts)
    .filter((part) => part.type === "text")
    .map((part) => ({
      ...part,
      state: status === "streaming" ? "streaming" : "complete",
    }));
  const response = {
    id: "weekly-update-response",
    actor: "assistant",
    author: activityAgent,
    status,
    parts: parts.length
      ? parts
      : denied
        ? [
            {
              type: "text",
              id: "denied",
              text: "The save was declined. No update was saved.",
            },
          ]
        : [],
  };
  return (
    <ActivityConversationTurn
      prompt="Review the weekly update and save it."
      response={response}
      onReplay={onReplay}
      pendingIndicator={<ThinkingActivity />}
      footer={
        status === "streaming" ? (
          <Button2 type="button" variant="outline" size="sm" onClick={onStop}>
            Stop
          </Button2>
        ) : status === "stopped" ? (
          <span role="status">Response stopped.</span>
        ) : null
      }
    >
      <div
        style={{
          display: "grid",
          gap: "var(--space-1)",
        }}
      >
        <Activity2 status="complete" defaultOpen>
          <ActivitySummary icon={<ListChecks />} state="complete">
            Reviewed the weekly update
          </ActivitySummary>
          <ActivityContent>
            <ActivityList events={activityEvents} />
          </ActivityContent>
        </Activity2>
        <AgentTodoList title="Weekly update" items={currentTodos} />
        {!completed && !denied ? (
          <ToolApproval
            approvalId={"save-weekly-update-approval"}
            state={decisionState}
            prompt="Save weekly update?"
            onApprove={onApprove}
            onDeny={onDeny}
          >
            <Card.Root density="compact">
              <code>docs/weekly-update.md</code>
            </Card.Root>
          </ToolApproval>
        ) : denied ? null : (
          <Tool name="Save weekly update" state="output-ready" defaultOpen>
            <ToolOutput>
              <code>
                {typeof currentTool?.output === "string"
                  ? currentTool.output
                  : JSON.stringify(currentTool?.output)}
              </code>
            </ToolOutput>
          </Tool>
        )}
      </div>
    </ActivityConversationTurn>
  );
}

function TanStackAgentRun({ onReplay, sessionId }) {
  const [stopped, setStopped] = useState2(false);
  const [resumeSnapshot] = useState2(() => ({
    ...tanStackResumeSnapshot,
    resumeState: {
      ...tanStackResumeSnapshot.resumeState,
      threadId: sessionId,
    },
  }));
  const chat = useTanStackChat({
    threadId: sessionId,
    initialMessages: tanStackInitialMessages,
    initialResumeSnapshot: resumeSnapshot,
    tools: [saveTool],
    connection: tanStackConnection,
  });
  const { messages, error, interruptErrors, status, stop } = chat;
  const normalized = tanStackAdapter.normalizeMessages(messages);
  const current = useRef(chat);
  current.current = chat;
  const decide = async (approved) => {
    const interrupt = current.current.interrupts.find(
      (item) => item.id === "save-weekly-update-approval",
    );
    if (interrupt?.kind !== "tool-approval")
      throw new Error("This approval is no longer available.");
    await tanStackAdapter.bindApproval({
      interrupt,
      getCurrent: () => current.current,
    })(approved);
  };
  return (
    <div
      data-preview-wide
      style={{
        width: 560,
        maxWidth: "100%",
      }}
    >
      {error ? <p role="alert">{error.message}</p> : null}
      {interruptErrors.map((issue, index) => (
        <p key={index} role="alert">
          {issue.message}
        </p>
      ))}
      <AgentWork
        messages={normalized}
        status={
          stopped
            ? "stopped"
            : status === "streaming" || status === "submitted"
              ? "streaming"
              : status === "error"
                ? "error"
                : "complete"
        }
        onReplay={onReplay}
        onStop={() => {
          setStopped(true);
          void stop();
        }}
        onApprove={async () => {
          await decide(true);
        }}
        onDeny={async () => {
          await decide(false);
        }}
      />
    </div>
  );
}

```

## API reference

ToolState is "input-streaming" | "input-ready" | "approval-required" | "approval-resolved" | "running" | "output-ready" | "error" | "cancelled". A missing or unsupported runtime state displays “Unsupported state”; it does not imply completion. Explicit name, state and error override corresponding part fields.

Tool accepts open, defaultOpen (default false) and onOpenChange(open, details?). Pass open back from the callback when controlling the disclosure. Native attributes and its div ref are forwarded to Activity.

input and output, including those in part, do not serialize or render data automatically. Put already-safe content in ToolInput and ToolOutput children; both omit their section when children are absent and forward native attributes and refs. ToolError renders caller children in an alert region. An error string supplies the fallback error region when no direct ToolError child is provided.

Tool execution properties

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| part | Pick<ToolPart, "name" \| "state" \| "input" \| "output" \| "error"> | — | Optional runtime data. Explicit name, state, and error props override the same fields in part. Payload fields are not rendered automatically. |
| name | string | — | Operation label. Falls back to part.name, then Tool. |
| state | ToolState | — | Declared lifecycle state. Falls back to part.state; absent or unsupported values show Unsupported state. |
| input / output | unknown | — | Data only; it is not serialized or displayed. Render validated content as ToolInput or ToolOutput children. |
| error | string | — | Error text fallback when there is no direct ToolError child. |
| open / defaultOpen | boolean | false (uncontrolled) | Controlled or initial detail disclosure state. |
| onOpenChange | (open: boolean, details?: unknown) => void | — | Receives disclosure changes from the composed Activity; update open in controlled use. |
| children | ReactNode | — | Optional ToolHeader, ToolInput, ToolOutput, ToolError, or direct ToolApproval children. |
| native attributes / ref | HTMLAttributes<HTMLDivElement>; Ref<HTMLDivElement> | — | Forwarded to the Activity root, including its accessible name. |

Tool parts

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| ToolHeader.name / state | string / ToolState \| "unknown" | — | Required operation label and lifecycle state for a caller-supplied header. |
| ToolHeader.glyphState / icon | "pending" \| "active" \| "complete" \| "error" \| "cancelled" / ReactNode | — | Optional Activity marker state and replacement icon; header props otherwise follow ActivityTrigger. |
| ToolInput / ToolOutput.children | ReactNode | — | Optional caller-rendered content. With no children, the section is omitted; native div attributes and refs are forwarded. |
| ToolError.children | ReactNode | — | Optional error content; defaults to The tool failed. Native div attributes and ref are forwarded, with role=alert by default. |

Tool approval properties

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| state | "pending" \| "submitting" \| "approved" \| "denied" \| "failed" \| "expired" | pending | Caller-owned decision lifecycle. Pending decisions permit input; submitting keeps the decision actions visible and disabled while awaiting acknowledgement. |
| approvalId | string | — | Request identity. A new ID invalidates late results from the previous decision; falls back to the root id. |
| onApprove | (optionId?: string) => void \| Promise<void> | — | Receives the selected option ID; without approveOptions it receives undefined. The caller owns authorization and persistence. |
| onDeny / onRetry | () => void \| Promise<void> | — | Caller-owned denial and failed-decision recovery callbacks. |
| approveOptions | readonly ToolApprovalOption[] | — | Host-supplied unique IDs, labels and optional disabled flags. Undefined offers Allow once; an explicit empty list disables approval. |
| error / approveLabel | string / string | — / Allow | Optional error text and Allow button label. |
| actionsPlacement | "header" \| "content" | header | Header places actions at the title’s right edge, with Allow last. Content places actions below the review target, aligned left with Allow first. DOM and keyboard order follow placement. |
| layout | "default" \| "compact" | default | Sets data-layout on the approval section. The component stylesheet does not style either value; use it only as a caller-facing marker. |
| prompt / children | ReactNode / ReactNode | — | Caller-owned decision question and affected content. |
| disabled | boolean | false | Disables approval and denial actions. |
| native attributes / ref | HTMLAttributes<HTMLDivElement>; Ref<HTMLDivElement> | — | Forwarded to the approval section. |

Import decisions from @/components/ui/tool-approval. Existing @/components/ui/tool imports remain compatible. Tool names an execution; ToolApproval names the decision. Approval acknowledgement does not imply a successful result. AI SDK uses bindApproval({ approvalId, addToolApprovalResponse, getCurrent }); [TanStack v1](/libraries/ai-runtime-tanstack#approval) uses { interrupt, getCurrent } with the current native interrupt state. Both reject obsolete requests before dispatch; the host owns authorization and persistence.
