# Confirmation

Asks for approval before a tool runs.

Source: https://webjs.dev/ui/docs/ai-elements/confirmation

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { bubbleClass, bubbleContentClass } from '#components/ui/bubble.ts';
import { buttonClass } from '#components/ui/button.ts';
import {
  itemClass, itemActionsClass, itemContentClass, itemDescriptionClass,
  itemMediaClass, itemTitleClass,
} from '#components/ui/item.ts';
import { messageClass, messageContentClass } from '#components/ui/message.ts';
import {
  traceClass, traceLineClass, traceIconClass, traceTitleClass,
  traceCollapsibleClass, traceCollapsibleTriggerClass, traceCollapsibleContentClass,
} from '#components/ui/trace.ts';
import { ChevronRightIcon, CircleCheckIcon, TerminalIcon } from '#lib/ui/lucide.ts';

const reasoning =
  'The build output lives in dist. Deleting it cannot be undone, so I should ask before I run the command.';

// The turn waiting on the person: the thinking has settled, and the command
// asks for a yes or no. A pending approval is a prompt, not activity, so it
// sits outside the trace. Deny and Approve are the reader's to wire.
export default function ConfirmationDemo() {
  return html`
    <div class="flex min-h-72 w-full max-w-sm flex-col gap-4 py-6 text-sm">
      <div data-slot="message" data-align="end" class=${messageClass()}>
        <div data-slot="message-content" class=${messageContentClass()}>
          <div data-slot="bubble" data-variant="muted" data-align="end" class=${bubbleClass({ variant: 'muted' })}>
            <div data-slot="bubble-content" class=${bubbleContentClass()}>Clean up the build folder.</div>
          </div>
        </div>
      </div>
      <div data-slot="message" data-align="start" class=${messageClass()}>
        <div data-slot="message-content" class=${cn(messageContentClass(), 'gap-4')}>
          <div data-slot="trace" class=${traceClass()}>
            <details data-slot="trace-collapsible" class=${cn(traceCollapsibleClass(), 'group/trace-collapsible')}>
              <summary data-slot="trace-collapsible-trigger" class=${traceCollapsibleTriggerClass()}>
                <span data-slot="trace-line" class=${traceLineClass()}>
                  <span data-slot="trace-icon" aria-hidden="true" class=${traceIconClass()}>${CircleCheckIcon()}</span>
                  <span data-slot="trace-title" class=${traceTitleClass()}>Thought</span>
                </span>
                <span data-slot="trace-icon" aria-hidden="true" class=${cn(traceIconClass(), 'transition-transform group-open/trace-collapsible:rotate-90')}>${ChevronRightIcon()}</span>
              </summary>
              <div data-slot="trace-collapsible-content" class=${cn(traceCollapsibleContentClass(), 'whitespace-pre-wrap')}>${reasoning}</div>
            </details>
          </div>
          <div data-slot="item" data-variant="outline" data-size="sm" class=${itemClass({ variant: 'outline', size: 'sm' })}>
            <div data-slot="item-media" data-variant="icon" class=${itemMediaClass({ variant: 'icon' })}>
              ${TerminalIcon()}
            </div>
            <div data-slot="item-content" class=${itemContentClass()}>
              <div data-slot="item-title" class=${itemTitleClass()}>Run rm -rf dist?</div>
              <p data-slot="item-description" class=${itemDescriptionClass()}>The command runs in this project.</p>
            </div>
            <div data-slot="item-actions" class=${itemActionsClass()}>
              <button type="button" data-slot="button" data-variant="outline" data-size="sm" class=${buttonClass({ variant: 'outline', size: 'sm' })}>Deny</button>
              <button type="button" data-slot="button" data-variant="default" data-size="sm" class=${buttonClass({ size: 'sm' })}>Approve</button>
            </div>
          </div>
        </div>
      </div>
      <button type="button" data-slot="button" data-variant="outline" data-size="sm" class=${cn(buttonClass({ variant: 'outline', size: 'sm' }), 'mt-auto self-start')}>
        Reset
      </button>
    </div>
  `;
}
```

Confirmation asks the person for a yes or no before a tool runs. The question is an [Item](https://webjs.dev/ui/docs/components/item) with Deny and Approve buttons. Once the person answers, the call becomes a [Tool](https://webjs.dev/ui/docs/ai-elements/tool) line.

## Installation

Confirmation is built with the [Item](https://webjs.dev/ui/docs/components/item) and [Button](https://webjs.dev/ui/docs/components/button) components.

```bash
npx @webjsdev/ui add item button
```

### Install the following dependencies:

```bash
npx @webjsdev/ui add item button
```

### Copy and paste the following code into your project.

````ts title="components/ui/item.ts"
/**
 * Item: a flexible row for lists of things (a person, a file, a setting), with
 * media, a title and description, and actions. Tier-1 class helper; compose
 * with a plain element, or an `<a>` / `<button>` when the whole row acts.
 *
 * shadcn parity:
 *   ItemGroup / ItemSeparator          → itemGroupClass() / itemSeparatorClass()
 *   Item (variant: default | outline | muted, size: default | sm | xs)
 *                                      → itemClass({ variant, size }), alias itemVariants
 *   ItemMedia (variant: default | icon | image)
 *                                      → itemMediaClass({ variant }), alias itemMediaVariants
 *   ItemContent / ItemTitle / ItemDescription / ItemActions / ItemHeader / ItemFooter
 *                                      → itemContentClass() ... itemFooterClass()
 *
 * Every part takes its `data-slot` (shown on each helper), which is what the
 * styles use to lay the parts out relative to each other.
 *
 * A11y (required for accessible output): a group of items is a list, so render
 * it as `<ul role="list">` with each item an `<li>`, or keep `role="list"` /
 * `role="listitem"` on divs. A whole-row link is a real `<a>` holding the
 * content, never a click handler on a div. Media that only decorates takes
 * `alt=""` or `aria-hidden="true"`, and an icon-only action needs
 * `aria-label`.
 *
 * Design tokens used: --border, --muted, --muted-foreground, --accent, --ring.
 *
 * @example
 * ```html
 * <div class=${itemClass({ variant: 'outline' })} data-slot="item" data-variant="outline">
 *   <div class=${itemContentClass()} data-slot="item-content">
 *     <div class=${itemTitleClass()} data-slot="item-title">Two-factor authentication</div>
 *     <p class=${itemDescriptionClass()} data-slot="item-description">Verify it is you with a code.</p>
 *   </div>
 *   <div class=${itemActionsClass()} data-slot="item-actions">
 *     <button class=${buttonClass({ variant: 'outline', size: 'sm' })} type="button">Enable</button>
 *   </div>
 * </div>
 * ```
 */
import { cn } from '../lib/utils.ts';

/** Set `data-slot="item-group"` on the element. */
export function itemGroupClass(): string {
  return 'group/item-group flex w-full flex-col';
}

/**
 * Set `data-slot="item-separator"` on the element. shadcn's ItemSeparator is a
 * horizontal Separator, so the line's own size and colour come with it, and
 * the style adds its margin.
 */
export function itemSeparatorClass(): string {
  return 'my-0 h-px w-full shrink-0 bg-border';
}

const ITEM_BASE =
  'rounded-md border border-transparent text-sm [a]:hover:bg-accent/50 group/item flex w-full flex-wrap items-center transition-colors duration-100 outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 [a]:transition-colors';

const ITEM_VARIANTS = {
  default: 'bg-transparent',
  outline: 'border-border',
  muted: 'bg-muted/50',
} as const;

const ITEM_SIZES = {
  default: 'gap-4 p-4',
  sm: 'gap-2.5 px-4 py-3',
  xs: '',
} as const;

/** The part, with its variant options. Set its `data-slot` and any `data-variant` / `data-size` to match. */
export function itemClass(opts: { variant?: keyof typeof ITEM_VARIANTS; size?: keyof typeof ITEM_SIZES } & { className?: string } = {}): string {
  return cn(ITEM_BASE, ITEM_VARIANTS[opts.variant ?? 'default'], ITEM_SIZES[opts.size ?? 'default'], opts.className);
}

/**
 * shadcn's name for {@link itemClass}, so shadcn code ports verbatim. Like cva,
 * it merges a `className` into the result.
 */
export function itemVariants(opts: { variant?: keyof typeof ITEM_VARIANTS; size?: keyof typeof ITEM_SIZES } & { className?: string } = {}): string {
  return itemClass(opts);
}

const ITEM_MEDIA_BASE =
  'gap-2 group-has-[[data-slot=item-description]]/item:translate-y-0.5 group-has-[[data-slot=item-description]]/item:self-start flex shrink-0 items-center justify-center [&_svg]:pointer-events-none';

const ITEM_MEDIA_VARIANTS = {
  default: 'bg-transparent',
  icon: "size-8 rounded-sm border bg-muted [&_svg:not([class*='size-'])]:size-4",
  image: 'size-10 overflow-hidden rounded-sm [&_img]:size-full [&_img]:object-cover',
} as const;

/** The part, with its variant options. Set its `data-slot` and any `data-variant` / `data-size` to match. */
export function itemMediaClass(opts: { variant?: keyof typeof ITEM_MEDIA_VARIANTS } & { className?: string } = {}): string {
  return cn(ITEM_MEDIA_BASE, ITEM_MEDIA_VARIANTS[opts.variant ?? 'default'], opts.className);
}

/**
 * shadcn's name for {@link itemMediaClass}, so shadcn code ports verbatim. Like cva,
 * it merges a `className` into the result.
 */
export function itemMediaVariants(opts: { variant?: keyof typeof ITEM_MEDIA_VARIANTS } & { className?: string } = {}): string {
  return itemMediaClass(opts);
}

/** Set `data-slot="item-content"` on the element. */
export function itemContentClass(): string {
  return 'gap-1 flex flex-1 flex-col [&+[data-slot=item-content]]:flex-none';
}

/** Set `data-slot="item-title"` on the element. */
export function itemTitleClass(): string {
  return 'gap-2 text-sm leading-snug font-medium line-clamp-1 flex w-fit items-center';
}

/** Set `data-slot="item-description"` on the element. */
export function itemDescriptionClass(): string {
  return 'text-sm leading-normal text-balance text-muted-foreground line-clamp-2 font-normal [&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary';
}

/** Set `data-slot="item-actions"` on the element. */
export function itemActionsClass(): string {
  return 'gap-2 flex items-center';
}

/** Set `data-slot="item-header"` on the element. */
export function itemHeaderClass(): string {
  return 'gap-2 flex basis-full items-center justify-between';
}

/** Set `data-slot="item-footer"` on the element. */
export function itemFooterClass(): string {
  return 'gap-2 flex basis-full items-center justify-between';
}
````

### Update the import paths to match your project setup.

## Usage

```ts
<div data-slot="item" data-variant="outline" data-size="sm" class=${itemClass({ variant: 'outline', size: 'sm' })}>
  <div data-slot="item-media" data-variant="icon" class=${itemMediaClass({ variant: 'icon' })}>
    ${TerminalIcon()}
  </div>
  <div data-slot="item-content" class=${itemContentClass()}>
    <div data-slot="item-title" class=${itemTitleClass()}>Run ${part.input.command}?</div>
    <p data-slot="item-description" class=${itemDescriptionClass()}>The command runs in this project.</p>
  </div>
  <div data-slot="item-actions" class=${itemActionsClass()}>
    <button type="button" data-slot="button" data-variant="outline" data-size="sm" class=${buttonClass({ variant: 'outline', size: 'sm' })} @click=${() => this.deny()}>
      Deny
    </button>
    <button type="button" data-slot="button" data-variant="default" data-size="sm" class=${buttonClass({ size: 'sm' })} @click=${() => this.approve()}>
      Approve
    </button>
  </div>
</div>
```

## AI SDK

While the part is `approval-requested`, answer with the approval id. Your component sends the answer back to the `'use server'` action that streams the turn (`send` below is your component's own method that calls it), and the action streams the rest of the turn once every approval has an answer.

```ts
async approve(part: ToolPart) {
  await this.send({ approvalId: part.approval.id, approved: true });
}
```

Approve streams the tool output. Deny streams `output-denied`. Either way, the part becomes a Tool line. See [Tool](https://webjs.dev/ui/docs/ai-elements/tool#approval), and [AI SDK](https://webjs.dev/ui/docs/helpers/ai-sdk) for streaming the parts from a server action.

## AI SDK Helper

To script an approval, yield the tool part in the `approval-requested` state from the action and stop. The next call carries the answer, and the action reads it to stream the rest of the turn.

```ts
'use server';

export async function* cleanUp(answer?: { approved: boolean }) {
  if (!answer) {
    yield {
      type: 'tool-runCommand',
      toolCallId: 'clean',
      state: 'approval-requested',
      input: { command: 'rm -rf dist' },
      approval: { id: 'clean' },
    };
    return;
  }
  yield {
    type: 'text',
    text: answer.approved ? 'Removed the dist folder.' : 'Okay, I left the dist folder in place.',
  };
}
```

## Migrating from AI SDK Elements

If you used Confirmation from [AI SDK Elements](https://elements.ai-sdk.dev), its wrapper lives in `components/ai-elements/confirmation.tsx`. In a WebJs app it becomes this pattern, built from WebJs UI components. Each export of the wrapper maps onto a part:

| AI SDK Elements | WebJs UI |
| --- | --- |
| `Confirmation` | An item with `itemClass({ variant: 'outline', size: 'sm' })`, in place of an Alert. Keep the approval and its state in your component. |
| `ConfirmationTitle` | An item content holding an item title. |
| `ConfirmationActions` | An item actions container, `itemActionsClass()`. |
| `ConfirmationAction` | A button with `buttonClass({ size: 'sm' })`. |
| `ConfirmationRequest, ConfirmationAccepted, ConfirmationRejected` | A branch on the part's state in your render: the item while it is `approval-requested`, a trace line once it is answered. |
