Skip to content
2k
On This Page

Confirmation

Asks for approval before a tool runs.

// Inline SVG icons from Lucide (https://lucide.dev), ISC License, Copyright (c) Lucide Icons and Contributors.
import { For, createSignal, createMemo } from "solid-js"

import {
  type UIDataTypes,
  type UIMessage,
  useDemoChat,
  createChat,
  getMessageText
} from "~/lib/ai-demo-chat"
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 default function ConfirmationDemo() {
  const {
    messages,
    sendMessage,
    setMessages,
    status,
    addToolApprovalResponse
  } = useDemoChat({
    messages: initialMessages,
    transport
  })
  const nextMessage = () => chat.next(messages())
  const busy = () => status() === "submitted" || status() === "streaming"

  return (
    <div class="flex min-h-72 w-full max-w-sm flex-col gap-4 py-6 text-sm">
      {
        <For each={messages()}>
          {(message) => {
            const content = createMemo(() => {
              if (message.role === "user") {
                return (
                  <Message align="end">
                    <MessageContent>
                      <Bubble align="end" variant="muted">
                        <BubbleContent>{getMessageText(message)}</BubbleContent>
                      </Bubble>
                    </MessageContent>
                  </Message>
                )
              }

              return (
                <Message>
                  <MessageContent class="gap-4">
                    {
                      <For each={message.parts}>
                        {(part) => {
                          const content = createMemo(() => {
                            if (part.type === "text") {
                              return <p>{part.text}</p>
                            }

                            if (part.type === "reasoning") {
                              return (
                                <Trace>
                                  <ReasoningRow
                                    text={part.text}
                                    running={part.state === "streaming"}
                                  />
                                </Trace>
                              )
                            }

                            if (part.type !== "tool-runCommand") {
                              return null
                            }

                            // A pending approval is a prompt, not activity, so it sits outside Trace.
                            if (part.state === "approval-requested") {
                              return (
                                <Item variant="outline" size="sm">
                                  <ItemMedia variant="icon">
                                    <svg
                                      width="24"
                                      height="24"
                                      viewBox="0 0 24 24"
                                      fill="none"
                                      stroke="currentColor"
                                      stroke-width="2"
                                      stroke-linecap="round"
                                      stroke-linejoin="round"
                                      aria-hidden="true"
                                    >
                                      <path d="M12 19h8" />
                                      <path d="m4 17 6-6-6-6" />
                                    </svg>
                                  </ItemMedia>
                                  <ItemContent>
                                    <ItemTitle>
                                      Run {part.input.command}?
                                    </ItemTitle>
                                    <ItemDescription>
                                      The command runs in this project.
                                    </ItemDescription>
                                  </ItemContent>
                                  <ItemActions>
                                    <Button
                                      size="sm"
                                      variant="outline"
                                      onClick={() =>
                                        addToolApprovalResponse({
                                          id: part.approval.id,
                                          approved: false
                                        })
                                      }
                                    >
                                      Deny
                                    </Button>
                                    <Button
                                      size="sm"
                                      onClick={() =>
                                        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>
                                <TraceLine
                                  status={
                                    !denied && part.state !== "output-available"
                                      ? "running"
                                      : undefined
                                  }
                                >
                                  <TraceIcon>
                                    <svg
                                      width="24"
                                      height="24"
                                      viewBox="0 0 24 24"
                                      fill="none"
                                      stroke="currentColor"
                                      stroke-width="2"
                                      stroke-linecap="round"
                                      stroke-linejoin="round"
                                      aria-hidden="true"
                                    >
                                      <path d="M12 19h8" />
                                      <path d="m4 17 6-6-6-6" />
                                    </svg>
                                  </TraceIcon>
                                  <TraceTitle>
                                    {denied
                                      ? "Denied"
                                      : part.state === "output-available"
                                        ? "Ran"
                                        : "Running"}{" "}
                                    {part.input?.command}
                                  </TraceTitle>
                                </TraceLine>
                              </Trace>
                            )
                          })
                          return <>{content()}</>
                        }}
                      </For>
                    }
                  </MessageContent>
                </Message>
              )
            })
            return <>{content()}</>
          }}
        </For>
      }
      {!busy() && (
        <Button
          variant="outline"
          size="sm"
          class="mt-auto self-start"
          onClick={() =>
            nextMessage()
              ? sendMessage(nextMessage())
              : setMessages(initialMessages)
          }
        >
          {nextMessage() ? "Send message" : "Reset"}
        </Button>
      )}
    </div>
  )
}

function ReasoningRow(componentProps: { text: string; running: boolean }) {
  const [open, setOpen] = createSignal<boolean>()
  const content = createMemo(() => {
    const { text, running } = componentProps
    return (
      <TraceCollapsible open={open() ?? running} onOpenChange={setOpen}>
        <TraceCollapsibleTrigger>
          <TraceLine status={running ? "running" : undefined}>
            <TraceIcon>
              {running ? (
                <svg
                  width="24"
                  height="24"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  aria-hidden="true"
                  class="animate-spin"
                >
                  <path d="M21 12a9 9 0 1 1-6.219-8.56" />
                </svg>
              ) : (
                <svg
                  width="24"
                  height="24"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  aria-hidden="true"
                >
                  <circle cx="12" cy="12" r="10" />
                  <path d="m16 9-5.5 5.5L8 12" />
                </svg>
              )}
            </TraceIcon>
            <TraceTitle>{running ? "Thinking" : "Thought"}</TraceTitle>
          </TraceLine>
        </TraceCollapsibleTrigger>
        <TraceCollapsibleContent class="whitespace-pre-wrap">
          {text}
        </TraceCollapsibleContent>
      </TraceCollapsible>
    )
  })
  return <>{content()}</>
}

Confirmation asks the person for a yes or no before a tool runs. The question is an Item with Deny and Approve buttons. Once the person answers, the call becomes a Tool line.

Installation

Confirmation is built with the Item and Button components.

pnpm dlx solidui-cli@latest add item button

Install the required Solid UI dependencies:

pnpm dlx solidui-cli@latest add item button

Copy and paste the following code into your project.

components/ui/item.tsx
import {
  dynamic,
  type ComponentProps,
  type JSX,
  type ValidComponent
} from "@solidjs/web"
import { cva, type VariantProps } from "class-variance-authority"
import { isStatic, merge, omit } from "solid-js"

import { cn } from "~/lib/utils"
import { Separator, type SeparatorProps } from "~/components/ui/separator"

type ItemGroupProps = ComponentProps<"div">

const ItemGroup = (props: ItemGroupProps) => (
  <div
    data-slot="item-group"
    role="list"
    {...props}
    class={cn(
      "group/item-group gap-4 has-data-[size=sm]:gap-2.5 has-data-[size=xs]:gap-2 flex w-full flex-col",
      props.class
    )}
  />
)

type ItemSeparatorProps = SeparatorProps

const ItemSeparator = (props: ItemSeparatorProps) => (
  <Separator
    data-slot="item-separator"
    orientation="horizontal"
    {...props}
    class={cn("my-2", props.class)}
  />
)

const itemVariants = cva(
  "group/item rounded-lg border text-sm [a]:hover:bg-muted 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",
  {
    variants: {
      variant: {
        default: "border-transparent",
        outline: "border-border",
        muted: "border-transparent bg-muted/50"
      },
      size: {
        default: "gap-2.5 px-3 py-2.5",
        sm: "gap-2.5 px-3 py-2.5",
        xs: "gap-2 px-2.5 py-2 in-data-[slot=menu-content]:p-0"
      }
    },
    defaultVariants: {
      variant: "default",
      size: "default"
    }
  }
)

type ItemProps<T extends ValidComponent = "div"> = {
  as?: T
  class?: string | undefined
  children?: JSX.Element
} & VariantProps<typeof itemVariants> &
  Omit<ComponentProps<T>, "as" | "class" | "children">

const Item = <T extends ValidComponent = "div">(rawProps: ItemProps<T>) => {
  const local = merge(
    { as: "div" as T, variant: "default", size: "default" } as const,
    rawProps
  ) as ItemProps
  const others = omit(rawProps as ItemProps, "as", "class", "variant", "size")
  const Comp = dynamic(() => local.as ?? "div", {
    static: isStatic(rawProps, "as")
  })
  return (
    <Comp
      class={cn(
        itemVariants({ variant: local.variant, size: local.size }),
        local.class
      )}
      data-size={local.size}
      data-slot="item"
      data-variant={local.variant}
      {...others}
    />
  )
}

const itemMediaVariants = cva(
  "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",
  {
    variants: {
      variant: {
        default: "bg-transparent",
        icon: "[&_svg:not([class*='size-'])]:size-4",
        image: "size-10 overflow-hidden rounded-sm group-data-[size=sm]/item:size-8 group-data-[size=xs]/item:size-6 [&_img]:size-full [&_img]:object-cover"
      }
    },
    defaultVariants: {
      variant: "default"
    }
  }
)

type ItemMediaProps = ComponentProps<"div"> &
  VariantProps<typeof itemMediaVariants>

const ItemMedia = (rawProps: ItemMediaProps) => {
  const local = merge({ variant: "default" } as const, rawProps)
  const others = omit(rawProps, "class", "variant")
  return (
    <div
      class={cn(itemMediaVariants({ variant: local.variant }), local.class)}
      data-slot="item-media"
      data-variant={local.variant}
      {...others}
    />
  )
}

type ItemContentProps = ComponentProps<"div">

const ItemContent = (props: ItemContentProps) => (
  <div
    data-slot="item-content"
    {...props}
    class={cn(
      "gap-1 group-data-[size=xs]/item:gap-0 flex flex-1 flex-col [&+[data-slot=item-content]]:flex-none",
      props.class
    )}
  />
)

type ItemTitleProps = ComponentProps<"div">

const ItemTitle = (props: ItemTitleProps) => (
  <div
    data-slot="item-title"
    {...props}
    class={cn(
      "gap-2 text-sm leading-snug font-medium underline-offset-4 line-clamp-1 flex w-fit items-center",
      props.class
    )}
  />
)

type ItemDescriptionProps = ComponentProps<"p">

const ItemDescription = (props: ItemDescriptionProps) => (
  <p
    data-slot="item-description"
    {...props}
    class={cn(
      "text-left text-sm leading-normal text-muted-foreground group-data-[size=xs]/item:text-xs line-clamp-2 font-normal [&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",
      props.class
    )}
  />
)

type ItemActionsProps = ComponentProps<"div">

const ItemActions = (props: ItemActionsProps) => (
  <div
    data-slot="item-actions"
    {...props}
    class={cn("gap-2 flex items-center", props.class)}
  />
)

type ItemHeaderProps = ComponentProps<"div">

const ItemHeader = (props: ItemHeaderProps) => (
  <div
    data-slot="item-header"
    {...props}
    class={cn(
      "gap-2 flex basis-full items-center justify-between",
      props.class
    )}
  />
)

type ItemFooterProps = ComponentProps<"div">

const ItemFooter = (props: ItemFooterProps) => (
  <div
    data-slot="item-footer"
    {...props}
    class={cn(
      "gap-2 flex basis-full items-center justify-between",
      props.class
    )}
  />
)

export {
  Item,
  ItemActions,
  ItemContent,
  ItemDescription,
  ItemFooter,
  ItemGroup,
  ItemHeader,
  ItemMedia,
  itemMediaVariants,
  ItemSeparator,
  ItemTitle,
  itemVariants
}

Update the import paths to match your project setup.

Usage

<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" onClick={deny}>
      Deny
    </Button>
    <Button size="sm" onClick={approve}>
      Approve
    </Button>
  </ItemActions>
</Item>

AI SDK

While the part is approval-requested, answer with the approval id. Pass sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses so the chat continues once every approval has an answer.

addToolApprovalResponse({
  id: part.approval.id,
  approved: true
})
const chatOptions = {
  sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses
}

Approve streams the tool output. Deny streams output-denied. Either way, the part becomes a Tool line.

See Tool.

AI SDK Helper

To script an approval with createChat, set needsApproval on the tool. The output streams after approval, and the next agent turn reads toolCall.approved.

The preview runs the conversation locally. Add its helper with npx solidui-cli@latest add ai-demo-chat.

const chat = createChat()
  .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."
        : "Okay, I left the dist folder in place."
    )
  })

Migrating from AI SDK Elements

If you added Confirmation from AI SDK Elements, your project has a components/ai-elements/confirmation.tsx wrapper. Paste this prompt into your coding agent to rebuild it on Item and Button. Every export keeps its name and props, so the code that uses it keeps working.

Prompt
Migrate components/ai-elements/confirmation.tsx from AI SDK Elements to the Solid UI Item and Button components.
 
Keep every export, with the same name and props, so the code that imports it keeps working. Only change how each part renders.
 
1. Install the components: npx solidui-cli@latest add item button
2. Read https://www.solid-ui.com/docs/ai-elements/confirmation.md and build Confirmation the same way.
3. Rebuild each part:
   - Confirmation renders an Item with variant="outline" and size="sm", instead of an Alert. Keep the approval and state props and the context they feed.
   - ConfirmationTitle renders an ItemContent with an ItemTitle.
   - ConfirmationActions renders an ItemActions.
   - ConfirmationAction renders a Button with size="sm".
   - Keep ConfirmationRequest, ConfirmationAccepted and ConfirmationRejected as they are.
4. Remove the imports the file no longer uses.
5. Run the type checker and fix any errors.