Skip to content

Confirmation

Asks the person to approve or deny a tool call before the agent runs it.

Installation

pnpm dlx shadcn@latest add @silkware/ai-confirmation

To copy the pattern by hand, install the components it composes:

pnpm dlx shadcn@latest add @silkware/bubble @silkware/button @silkware/item @silkware/message @silkware/trace

Then the packages:

pnpm add ai @ai-sdk/react @shadcn/helpers lucide-react

Copy the source into components/ai-elements/confirmation.tsx. The file also needs @/lib/ai:

components/ai-elements/confirmation.tsx
"use client"
import * as React from "react"import { useChat } from "@ai-sdk/react"import {  lastAssistantMessageIsCompleteWithApprovalResponses,  type UIDataTypes,  type UIMessage,} from "ai"import { CircleCheckIcon, LoaderCircleIcon, TerminalIcon } from "lucide-react"
import { createChat, getMessageText } from "@/lib/ai"import { Bubble, BubbleContent } from "@/components/ui/bubble"import { Button } from "@/components/ui/button"import {  Item,  ItemActions,  ItemContent,  ItemDescription,  ItemMedia,  ItemTitle,} from "@/components/ui/item"import { Message, MessageContent } from "@/components/ui/message"import {  Trace,  TraceCollapsible,  TraceCollapsibleContent,  TraceCollapsibleTrigger,  TraceIcon,  TraceLine,  TraceTitle,} from "@/components/ui/trace"
type ChatMessage = UIMessage<  unknown,  UIDataTypes,  {    runCommand: {      input: { command: string }      output: { stdout: string }    }  }>
const chat = createChat<ChatMessage>()  .user("Clean up the build folder.")  .sleep(600)  .assistant(({ writer }) => {    writer.reasoning(      "The build output lives in dist. Deleting it cannot be undone, so I should ask before I run the command."    )    writer.sleep(400)    writer.tool("runCommand", {      input: { command: "rm -rf dist" },      needsApproval: true,      output: { stdout: "" },    })  })  .assistant(({ writer, toolCall }) => {    writer.sleep(600)    writer.text(      toolCall?.approved        ? "Removed the dist folder."        : "Okay, I left the dist folder in place."    )  })
const initialMessages = chat.get(0)const transport = chat.transport({ delayMs: 20 })
export function ConfirmationDemo() {  const {    messages,    sendMessage,    setMessages,    status,    addToolApprovalResponse,  } = useChat({    messages: initialMessages,    transport,    sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses,  })  const nextMessage = chat.next(messages)  const busy = status === "submitted" || status === "streaming"
  return (    <div className="flex min-h-72 w-full max-w-sm flex-col gap-4 py-6 text-sm">      {messages.map((message) => {        if (message.role === "user") {          return (            <Message key={message.id} align="end">              <MessageContent>                <Bubble align="end" variant="muted">                  <BubbleContent>{getMessageText(message)}</BubbleContent>                </Bubble>              </MessageContent>            </Message>          )        }
        return (          <Message key={message.id}>            <MessageContent className="gap-4">              {message.parts.map((part, index) => {                if (part.type === "text") {                  return <p key={index}>{part.text}</p>                }
                if (part.type === "reasoning") {                  return (                    <Trace key={index}>                      <ReasoningRow                        text={part.text}                        running={part.state === "streaming"}                      />                    </Trace>                  )                }
                if (part.type !== "tool-runCommand") {                  return null                }
                if (part.state === "approval-requested") {                  return (                    <Item key={part.toolCallId} variant="outline" size="sm">                      <ItemMedia variant="icon">                        <TerminalIcon />                      </ItemMedia>                      <ItemContent>                        <ItemTitle>Run {part.input.command}?</ItemTitle>                        <ItemDescription>                          The command runs in this project.                        </ItemDescription>                      </ItemContent>                      <ItemActions>                        <Button                          size="sm"                          variant="outline"                          autoFocus                          onPress={() =>                            addToolApprovalResponse({                              id: part.approval.id,                              approved: false,                            })                          }                        >                          Deny                        </Button>                        <Button                          size="sm"                          onPress={() =>                            addToolApprovalResponse({                              id: part.approval.id,                              approved: true,                            })                          }                        >                          Approve                        </Button>                      </ItemActions>                    </Item>                  )                }
                const denied =                  part.state === "output-denied" ||                  (part.state === "approval-responded" &&                    !part.approval.approved)
                return (                  <Trace key={part.toolCallId}>                    <TraceLine                      status={                        !denied && part.state !== "output-available"                          ? "running"                          : undefined                      }                    >                      <TraceIcon>                        <TerminalIcon />                      </TraceIcon>                      <TraceTitle>                        {denied                          ? "Denied"                          : part.state === "output-available"                            ? "Ran"                            : "Running"}{" "}                        {part.input?.command}                      </TraceTitle>                    </TraceLine>                  </Trace>                )              })}            </MessageContent>          </Message>        )      })}      {!busy && (        <Button          variant="outline"          size="sm"          className="mt-auto self-start"          onPress={() =>            nextMessage              ? sendMessage(nextMessage)              : setMessages(initialMessages)          }        >          {nextMessage ? "Send message" : "Reset"}        </Button>      )}    </div>  )}
function ReasoningRow({ text, running }: { text: string; running: boolean }) {  const [open, setOpen] = React.useState<boolean>()
  return (    <TraceCollapsible isExpanded={open ?? running} onExpandedChange={setOpen}>      <TraceCollapsibleTrigger>        <TraceLine status={running ? "running" : undefined}>          <TraceIcon>            {running ? (              <LoaderCircleIcon className="animate-spin" />            ) : (              <CircleCheckIcon />            )}          </TraceIcon>          <TraceTitle>{running ? "Thinking" : "Thought"}</TraceTitle>        </TraceLine>      </TraceCollapsibleTrigger>      <TraceCollapsibleContent className="whitespace-pre-wrap">        {text}      </TraceCollapsibleContent>    </TraceCollapsible>  )}

Usage

The prompt is an outlined Item: an icon, a question with its detail, and two buttons.

import { TerminalIcon } from "lucide-react"
import { Button } from "@/components/ui/button"import {  Item,  ItemActions,  ItemContent,  ItemDescription,  ItemMedia,  ItemTitle,} from "@/components/ui/item"
<Item variant="outline" size="sm">  <ItemMedia variant="icon">    <TerminalIcon />  </ItemMedia>  <ItemContent>    <ItemTitle>Run {part.input.command}?</ItemTitle>    <ItemDescription>The command runs in this project.</ItemDescription>  </ItemContent>  <ItemActions>    <Button      size="sm"      variant="outline"      onPress={() => addToolApprovalResponse({ id: part.approval.id, approved: false })}    >      Deny    </Button>    <Button      size="sm"      onPress={() => addToolApprovalResponse({ id: part.approval.id, approved: true })}    >      Approve    </Button>  </ItemActions></Item>

Render the prompt only while part.state === "approval-requested". Once the person answers, replace it with a Tool line that says what was decided.

Examples

Prompt and outcomes

The prompt before the decision, and the two lines that replace it afterwards. The description says what happens and whether it can be undone. The outcome lines say who decided.

Publish the Q1 price list?

Raises 212 prices by 4% for all Brevia Manufacturing customers. Customers see the new prices at once.

Approved by Giulia: published the Q1 price listDenied by Luca: Q1 price list not published

In a conversation

The agent reasons, stops on the call and waits. Pressing Approve or Deny sends the answer, and the scripted agent continues with the branch that matches. The Send message button advances the scripted conversation; in your app the person types.

AI SDK

A tool that needs approval reaches useChat as a tool part in the approval-requested state, with an approval.id. Answer it with addToolApprovalResponse, and let the hook send the follow-up request when every pending approval has an answer:

import { useChat } from "@ai-sdk/react"import { lastAssistantMessageIsCompleteWithApprovalResponses } from "ai"
const { messages, addToolApprovalResponse } = useChat({  sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses,})

On the server, mark the tool as needing approval on the agent. toolApproval takes "user-approval", or a function of the parsed input, so only the risky calls ask:

import { ToolLoopAgent, tool } from "ai"import { z } from "zod"
const agent = new ToolLoopAgent({  model: "anthropic/claude-sonnet-4.5",  tools: {    sendOrder: tool({      inputSchema: z.object({ orderId: z.string(), supplier: z.string() }),      execute: async ({ orderId, supplier }) => placeOrder(orderId, supplier),    }),  },  toolApproval: {    sendOrder: "user-approval",  },})

After the answer, the part moves to approval-responded (check part.approval.approved), then to output-available, output-error or output-denied. An approval that the server decided on its own has part.approval.isAutomatic; do not show a prompt for it. A reason the server attaches is in part.approval.requestReason: show it in the description.

Scripted streams in development

createChat pauses a call behind approval with needsApproval: true. The output you give is what streams after the person approves, and a denial streams the denied state for you:

const chat = createChat<ChatMessage>()  .user("Clean up the build folder.")  .assistant(({ writer }) => {    writer.tool("runCommand", {      input: { command: "rm -rf dist" },      needsApproval: true,      output: { stdout: "" },    })  })  .assistant(({ writer, toolCall }) => {    writer.text(toolCall?.approved ? "Removed the dist folder." : "Left the dist folder in place.")  })

The second assistant call is a continuation. It runs when the follow-up request arrives, and toolCall.approved or toolCall.denied carries the decision. Keep continuations pure: regenerating re-runs them against the current transcript.

Accessibility

KeyAction
TabMoves focus between Deny and Approve.
ShiftTabMoves focus back to the previous control.
EnterPresses the focused button.
SpacePresses the focused button.

The composed components provide:

  • Two real buttons that fire onPress for mouse, touch, pen and keyboard, with a visible focus ring.
  • An Item that keeps the title and description in one block next to the actions, so the question and its detail stay together in the reading order.

You provide:

  • Focus. When the prompt appears, focus moves to Deny, the choice that changes nothing, so a keyboard or screen reader user lands on the question and knows the agent is waiting. Keep that when you change the buttons: put autoFocus on the safe one. After the answer the buttons leave the page, so move focus to the next control or to the result yourself.
  • The same state in words after the decision. "Approved by Giulia" and "Denied by Luca" are in the text, not in a colour.
  • A description for every prompt. A title alone ("Run rm -rf dist?") does not say what the command does or whether it can be undone.
  • Button labels that name the action when the default Deny and Approve are not clear enough, for example "Send order" and "Don’t send".

Guidelines

When to use

  • Before a call the person cannot take back: deleting, sending, publishing, paying, changing a price list that customers see.
  • Before a call that acts on other people's data or on a system the person does not own.
  • When the agent is unsure which of two options the person wants and a wrong guess is costly.

When not to use

  • For a read-only call. Show it as a Tool line and keep the agent moving. Asking about every read teaches people to press Approve without reading.
  • To ask for information, not permission. Use a question in the message and a Suggestion for the likely answers.
  • For a destructive action in your own interface, outside an agent. Use an Alert Dialog.

Content

  • Ask in the form "Verb the object?": "Send order BM-2041 to Marco & Sons?".
  • Say the consequence in the description: what changes, for whom, and whether it can be undone. Include the figures the person needs to decide: 120 gaskets, EUR 1,840.
  • Name the buttons for the action. Use Deny and Approve only when the question already says everything.
  • After the decision, leave one line behind that says what was decided and by whom.
Send order BM-2041 to Marco & Sons?

Orders 120 gaskets for EUR 1,840. The supplier is notified at once and the order cannot be recalled.

Do

Ask about one concrete action, say what it changes and whether it can be undone, and name the buttons for it.

Are you sure?
Don’t

Don’t ask "Are you sure?" with OK and Cancel. The person cannot tell what they are agreeing to.

Human in the loop

This pattern is where the person keeps control. These rules apply to every agent that uses it.

  • Before. The person sees the exact action and its input, not a summary of it. If the agent will run a command, show the command. If it will change 212 prices, say 212 and by how much.
  • Stop. Nothing runs while the prompt is open. The agent waits, and a long wait does not count as consent. Do not auto-approve after a timeout.
  • Deny. A denial is a normal answer. The agent acknowledges it, does not retry the same call and says what it did instead. Tell the model not to retry an unapproved call in its instructions.
  • Approve once. An approval covers the one call shown. Do not turn it into a standing permission without a separate, visible setting.
  • After. Keep the decision in the transcript, with who decided. A person who reads the conversation tomorrow must see what was approved.
  • Undo. If the action can be reversed, offer the reversal next to the outcome line. If it cannot, say so in the prompt, before the person approves.
  • Who approves. Show the prompt to a person who has the authority to approve the action, not only to the person who started the conversation.

Composition

ComponentWhat it does here
ItemLays out the prompt: icon, title, description and the two actions.
ButtonThe Deny and Approve controls, and the demo's reset control.
TraceShows the reasoning and the outcome line after the decision.
MessagePlaces the conversation in turns.
BubbleWraps the person's own message.

components/ai-elements/confirmation.tsx exports ConfirmationDemo, a scripted chat that pauses on a runCommand call with needsApproval, shows the prompt and continues on the answer. Copy the prompt block and the outcome row into your app and wire them to useChat as shown above.