# Tool Confirmation

> Asks a person to confirm before an agent's action changes anything.

Page: https://uicontext.com/docs/components/tool-confirmation

Group: Agents.

## When to use

Asks a person to confirm before an agent's action changes anything. Use [Approval](https://uicontext.com/docs/components/approval.md) instead when the agent asks in the conversation.

## Usage

```ts
import { AgentConfirm } from "./ui/uicontext/components/agent/AgentConfirm.ts"

export const App = Html.component({ name: "App", model: Schema.Struct({}), message: Schema.Never }).make({
	init: () => ({}),
	update: ($) => $.model,
	view: (h) => h.main.children(h.h1.children("Billing"), AgentConfirm(h, {})),
})
```

## Examples

Each example is a complete file. Its imports point where the CLI installs the source.

### A refund that can't be undone

The agent asks to refund an order. Nothing happens until a person allows it; Deny, Escape or no answer refuses it.

```ts title="src/demo.ts" source="www/src/examples/tool-confirmation/demo.ts"
import { Command, UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Effect, Schema } from "effect"
import * as Agent from "./ui/uicontext/components/agent/Agent.ts"
import { AgentConfirm } from "./ui/uicontext/components/agent/AgentConfirm.ts"
import { Button } from "./ui/uicontext/components/Button.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { color, font, space } from "./ui/uicontext/components/tokens.stylex.ts"
import { callTool, outcomeOf } from "./agent.ts"

const Refund = Schema.Struct({ id: Schema.String, customer: Schema.String, amount: Schema.String, refunded: Schema.Boolean })

const Message = UiSchema.TaggedEnum({
	ClickedRefund: { id: Schema.String },
	ClickedAskAgent: {},
	CompletedAskAgent: { outcome: Schema.String },
})

type Model = { readonly refunds: ReadonlyArray<typeof Refund.Type>; readonly outcome: string }

// The refunds list tells agents what it shows and what they may do: the same refund a person clicks.
const RefundsAgent = Agent.contract({
	component: "Refunds",
	message: Message,
	id: () => "refunds-4471",
	label: () => "Refund requests",
	snapshot: { schema: Schema.Struct({ refunds: Schema.Array(Refund) }), from: (model: Model) => ({ refunds: model.refunds }) },
	actions: {
		ClickedRefund: {
			description: "Refund an order to the customer's card",
			consequential: true,
			check: (model, _props, m: { readonly id: string }) =>
				model.refunds.some((r) => r.id === m.id && !r.refunded) ? undefined : `Order ${m.id} has no open refund.`,
			targetOf: (model, _props, m: { readonly id: string }) => model.refunds.find((r) => r.id === m.id) ?? null,
		},
	},
})

// What a browser agent would send: refund #4471, naming the refund as it saw it.
const AskAgent = Command.make("AskAgentToRefund", { args: { target: Refund } }, ({ target }) =>
	callTool("page_act", { steps: [{ id: "refunds-4471", action: "ClickedRefund", input: { id: target.id }, target }] }, [
		"Refunds.*",
	]).pipe(
		Effect.map((result) =>
			Message.CompletedAskAgent({
				outcome: outcomeOf(result, { done: `Refunded ${target.amount} to ${target.customer}.`, denied: "Denied. Nothing was refunded." }),
			}),
		),
	),
)

const styles = stylex.create({
	frame: { display: "grid", gap: space.lg, inlineSize: "min(100%, 30rem)" },
	row: { display: "flex", flexWrap: "wrap", alignItems: "center", gap: space.md },
	order: { flexGrow: 1, flexShrink: 1, flexBasis: "12rem", margin: 0, fontSize: font.base, color: color.fg },
	muted: { color: color.muted },
	outcome: { margin: 0, minBlockSize: "1.5em", fontSize: font.sm, color: color.muted },
})

export const RefundRequests = Html.component({
	name: "RefundRequests",
	model: Schema.Struct({ refunds: Schema.Array(Refund), outcome: Schema.String }),
	message: Message,
}).make({
	init: () => ({
		refunds: [{ id: "4471", customer: "Maya Okafor", amount: "$248.00", refunded: false }],
		outcome: "",
	}),
	subscriptions: ($) => [RefundsAgent($)],
	update: {
		ClickedRefund: ($, { id }) => $.evolve({ refunds: (all) => all.map((r) => (r.id === id ? { ...r, refunded: true } : r)) }),
		ClickedAskAgent: ($) => {
			const target = $.model.refunds[0]!
			return $.evolve({ outcome: "Waiting for your answer…" }).run(AskAgent.make({ target }))
		},
		CompletedAskAgent: ($, { outcome }) => $.evolve({ outcome }),
	},
	view: (h, model) => {
		const refund = model.refunds[0]!
		return h.div.attrs(sx(styles.frame)).children(
			h.div.attrs(sx(styles.row)).children(
				h.p.attrs(sx(styles.order)).children(
					`Order #${refund.id} · ${refund.customer} · ${refund.amount}`,
					refund.refunded && h.span.attrs(sx(styles.muted)).children(" · Refunded"),
				),
				Button(h, {})
					.disabled(refund.refunded)
					.on("click", Message.ClickedAskAgent())
					.children(refund.refunded ? "Refunded" : "Ask the agent to refund it"),
			),
			h.p.attrs({ role: "status", ...sx(styles.outcome) }).children(model.outcome),
			// once per app; a second one stays quiet while the first is mounted
			AgentConfirm(h, {}),
		)
	},
})
```

### An action that can be undone

Archiving can be reversed, so the dialog offers to stop asking for it until the page reloads.

```ts title="src/reversible.ts" source="www/src/examples/tool-confirmation/reversible.ts"
import { Command, UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Effect, Schema } from "effect"
import * as Agent from "./ui/uicontext/components/agent/Agent.ts"
import { AgentConfirm } from "./ui/uicontext/components/agent/AgentConfirm.ts"
import { Button } from "./ui/uicontext/components/Button.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { color, font, space } from "./ui/uicontext/components/tokens.stylex.ts"
import { callTool, outcomeOf } from "./agent.ts"

const Message = UiSchema.TaggedEnum({
	ClickedArchive: { channel: Schema.String },
	ClickedRestore: {},
	ClickedAskAgent: {},
	CompletedAskAgent: { outcome: Schema.String },
})

type Model = { readonly open: ReadonlyArray<string>; readonly archived: ReadonlyArray<string>; readonly outcome: string }

const ChannelsAgent = Agent.contract({
	component: "Channels",
	message: Message,
	id: () => "channels-archive",
	label: () => "Quiet channels",
	snapshot: { schema: Schema.Struct({ open: Schema.Array(Schema.String) }), from: (model: Model) => ({ open: model.open }) },
	actions: {
		ClickedArchive: {
			description: "Archive a channel. Its messages stay searchable, and it can be restored.",
			consequential: true,
			// a person may allow it for the rest of the session
			reversible: true,
			check: (model, _props, m: { readonly channel: string }) =>
				model.open.includes(m.channel) ? undefined : `#${m.channel} isn't open.`,
			targetOf: (_model, _props, m: { readonly channel: string }) => ({ channel: m.channel }),
		},
	},
})

const AskAgent = Command.make("AskAgentToArchive", { args: { channel: Schema.String } }, ({ channel }) =>
	callTool(
		"page_act",
		{ steps: [{ id: "channels-archive", action: "ClickedArchive", input: { channel }, target: { channel } }] },
		["Channels.*"],
	).pipe(
		Effect.map((result) =>
			Message.CompletedAskAgent({ outcome: outcomeOf(result, { done: `Archived #${channel}.`, denied: `Denied. #${channel} stays open.` }) }),
		),
	),
)

const styles = stylex.create({
	frame: { display: "grid", gap: space.md, inlineSize: "min(100%, 30rem)" },
	list: { margin: 0, paddingInlineStart: space.xl, color: color.fg, fontSize: font.base },
	row: { display: "flex", flexWrap: "wrap", gap: space.md },
	outcome: { margin: 0, minBlockSize: "1.5em", fontSize: font.sm, color: color.muted },
})

const CHANNELS = ["launch-2025", "offsite-planning", "q3-hiring", "old-website"]

export const QuietChannels = Html.component({
	name: "QuietChannels",
	model: Schema.Struct({ open: Schema.Array(Schema.String), archived: Schema.Array(Schema.String), outcome: Schema.String }),
	message: Message,
}).make({
	init: () => ({ open: CHANNELS, archived: [], outcome: "" }),
	subscriptions: ($) => [ChannelsAgent($)],
	update: {
		ClickedArchive: ($, { channel }) =>
			$.evolve({ open: (all) => all.filter((c) => c !== channel), archived: (all) => [...all, channel] }),
		ClickedRestore: ($) => $.evolve({ open: CHANNELS, archived: [], outcome: "" }),
		ClickedAskAgent: ($) => {
			const next = $.model.open[0]
			return next === undefined
				? $.model
				: $.evolve({ outcome: "Waiting for your answer…" }).run(AskAgent.make({ channel: next }))
		},
		CompletedAskAgent: ($, { outcome }) => $.evolve({ outcome }),
	},
	view: (h, model) =>
		h.div.attrs(sx(styles.frame)).children(
			model.open.length > 0
				? h.ul.attrs(sx(styles.list)).children(...model.open.map((c) => h.li.key(c).children(`#${c}`)))
				: h.p.attrs(sx(styles.outcome)).children("Every quiet channel is archived."),
			h.div.attrs(sx(styles.row)).children(
				Button(h, {})
					.disabled(model.open.length === 0)
					.on("click", Message.ClickedAskAgent())
					.children("Ask the agent to archive the next one"),
				Button(h, { emphasis: "ghost" })
					.disabled(model.archived.length === 0)
					.on("click", Message.ClickedRestore())
					.children("Restore all"),
			),
			h.p.attrs({ role: "status", ...sx(styles.outcome) }).children(model.outcome),
			AgentConfirm(h, {}),
		),
})
```

### Several steps waiting

Three agents ask at once. The dialog shows the oldest first and says how many more wait.

```ts title="src/several-steps.ts" source="www/src/examples/tool-confirmation/several-steps.ts"
import { Command, UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Effect, Schema } from "effect"
import * as Agent from "./ui/uicontext/components/agent/Agent.ts"
import { AgentConfirm } from "./ui/uicontext/components/agent/AgentConfirm.ts"
import { Button } from "./ui/uicontext/components/Button.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { color, font, space } from "./ui/uicontext/components/tokens.stylex.ts"
import { callTool, errorOf } from "./agent.ts"

const Issue = Schema.Struct({ key: Schema.String, title: Schema.String, closed: Schema.Boolean })

const Message = UiSchema.TaggedEnum({
	ClickedClose: { key: Schema.String },
	ClickedReopen: {},
	ClickedAskAgents: {},
	CompletedAskAgents: { outcome: Schema.String },
})

type Model = { readonly issues: ReadonlyArray<typeof Issue.Type>; readonly outcome: string }

const IssuesAgent = Agent.contract({
	component: "StaleIssues",
	message: Message,
	id: () => "stale-issues",
	label: () => "Stale issues in Mobile",
	snapshot: { schema: Schema.Struct({ issues: Schema.Array(Issue) }), from: (model: Model) => ({ issues: model.issues }) },
	actions: {
		ClickedClose: {
			description: "Close an issue as won't fix",
			consequential: true,
			check: (model, _props, m: { readonly key: string }) =>
				model.issues.some((i) => i.key === m.key && !i.closed) ? undefined : `${m.key} isn't open.`,
			targetOf: (model, _props, m: { readonly key: string }) => model.issues.find((i) => i.key === m.key) ?? null,
		},
	},
})

const ISSUES = [
	{ key: "MOB-88", title: "Splash screen flickers on Android 12", closed: false },
	{ key: "MOB-102", title: "Offline banner overlaps the tab bar", closed: false },
	{ key: "MOB-131", title: "Old onboarding copy in Portuguese", closed: false },
]

// Three agents, each with its own call: a person answers them one at a time.
const AskAgents = Command.make("AskAgentsToClose", { args: { issues: Schema.Array(Issue) } }, ({ issues }) =>
	Effect.forEach(
		issues,
		(issue) =>
			callTool(
				"page_act",
				{ steps: [{ id: "stale-issues", action: "ClickedClose", input: { key: issue.key }, target: issue }] },
				["StaleIssues.*"],
			),
		{ concurrency: "unbounded" },
	).pipe(
		Effect.map((results) => {
			const closed = results.filter((r) => errorOf(r) === undefined).length
			return Message.CompletedAskAgents({ outcome: `Closed ${closed} of ${results.length}.` })
		}),
	),
)

const styles = stylex.create({
	frame: { display: "grid", gap: space.md, inlineSize: "min(100%, 32rem)" },
	list: { margin: 0, paddingInlineStart: space.xl, fontSize: font.base, color: color.fg },
	closed: { color: color.faint, textDecorationLine: "line-through" },
	row: { display: "flex", flexWrap: "wrap", gap: space.md },
	outcome: { margin: 0, minBlockSize: "1.5em", fontSize: font.sm, color: color.muted },
})

export const StaleIssues = Html.component({
	name: "StaleIssues",
	model: Schema.Struct({ issues: Schema.Array(Issue), outcome: Schema.String }),
	message: Message,
}).make({
	init: () => ({ issues: ISSUES, outcome: "" }),
	subscriptions: ($) => [IssuesAgent($)],
	update: {
		ClickedClose: ($, { key }) => $.evolve({ issues: (all) => all.map((i) => (i.key === key ? { ...i, closed: true } : i)) }),
		ClickedReopen: ($) => $.evolve({ issues: ISSUES, outcome: "" }),
		ClickedAskAgents: ($) =>
			$.evolve({ outcome: "Waiting for your answers…" }).run(
				AskAgents.make({ issues: $.model.issues.filter((i) => !i.closed) }),
			),
		CompletedAskAgents: ($, { outcome }) => $.evolve({ outcome }),
	},
	view: (h, model) => {
		const open = model.issues.filter((i) => !i.closed).length
		return h.div.attrs(sx(styles.frame)).children(
			h.ul
				.attrs(sx(styles.list))
				.children(
					...model.issues.map((i) =>
						h.li.key(i.key).attrs(sx(i.closed && styles.closed)).children(`${i.key} · ${i.title}`),
					),
				),
			h.div.attrs(sx(styles.row)).children(
				Button(h, {})
					.disabled(open === 0)
					.on("click", Message.ClickedAskAgents())
					.children(`Ask agents to close ${open === 1 ? "it" : `all ${open}`}`),
				Button(h, { emphasis: "ghost" })
					.disabled(open === ISSUES.length)
					.on("click", Message.ClickedReopen())
					.children("Reopen all"),
			),
			h.p.attrs({ role: "status", ...sx(styles.outcome) }).children(model.outcome),
			AgentConfirm(h, {}),
		)
	},
})
```

### Sample data

The examples above import these files.

```ts title="src/agent.ts" source="www/src/examples/_shared/agent.ts"
import { Effect } from "effect"
import { AgentRegistry, type Json } from "./ui/uicontext/components/agent/Agent.ts"
import { AgentPolicy, makeTools } from "./ui/uicontext/components/agent/AgentPage.ts"

// Stands in for a browser agent in the examples: it calls the page's own tools, as an agent does
// through WebMCP, so the examples work in any browser. In an app, agents call these tools themselves.

type ToolName = "page_snapshot" | "page_query" | "page_act"

/** Calls one of the page's tools with the given allow list, and resolves with its JSON result. */
export const callTool = (name: ToolName, input: { readonly [key: string]: Json }, allow: ReadonlyArray<string>) =>
	Effect.gen(function* () {
		const registry = yield* AgentRegistry
		const policy = yield* AgentPolicy
		const tool = makeTools({ registry, allow: { actions: allow }, policy }).find((t) => t.name === name)!
		return yield* Effect.promise((signal) => tool.execute(input, signal))
	})

/** The first step's error from a `page_act` result, or undefined when every step ran. */
export const errorOf = (result: Json): string | undefined => {
	const top = result as { readonly error?: string; readonly results?: ReadonlyArray<{ readonly error?: string }> }
	return top.error ?? top.results?.find((r) => r.error !== undefined)?.error
}

/** What happened, for the person: `done` when it ran, `denied` when nobody allowed it, or the error. */
export const outcomeOf = (result: Json, words: { readonly done: string; readonly denied: string }): string => {
	const error = errorOf(result)
	if (error === undefined) return words.done
	return error.includes("confirm") ? words.denied : error
}
```

## API reference

**Options**

| Name | Type | Description |
| --- | --- | --- |
| `request` (required) | `Omit<ConfirmRequest, "id" \| "expiresAt" \| "more"> & { readonly more?: number }` | — |
| `remember` | `boolean` | — |
| `timeLeft` | `number` | — |

## Keyboard and accessibility

- The request shows in a modal alert dialog that says what the agent wants to do, on what, and the exact values it applies to.
- Deny has focus first, and Escape denies. A step nobody answers in time is refused.
- An action that can be undone can be allowed for the rest of the session; one that can't is asked every time. Agents can't answer it.

## Installation

```sh
pnpm dlx shadcn@latest add checkfu/uicontext/tool-confirmation
```

With npm: `npx shadcn@latest add checkfu/uicontext/tool-confirmation`. With yarn: `yarn dlx shadcn@latest add checkfu/uicontext/tool-confirmation`. With bun: `bunx --bun shadcn@latest add checkfu/uicontext/tool-confirmation`.

It writes these files:

- `src/ui/uicontext/components/Button.ts`
- `src/ui/uicontext/components/Dialog.ts`
- `src/ui/uicontext/components/Sx.ts`
- `src/ui/uicontext/components/agent/Agent.ts`
- `src/ui/uicontext/components/agent/AgentApp.ts`
- `src/ui/uicontext/components/agent/AgentConfirm.ts`
- `src/ui/uicontext/components/agent/AgentPage.ts`
- `src/ui/uicontext/components/agent/WebMcp.ts`
- `src/ui/uicontext/components/button.stylex.ts`
- `src/ui/uicontext/components/safeArea.stylex.ts`
- `src/ui/uicontext/components/tokens.stylex.ts`
- `src/ui/uicontext/components/variants.ts`

And installs the npm packages `@stylexjs/stylex`, `effect`.

## Source

- [src/agent/AgentConfirm.ts](https://github.com/checkfu/uicontext/blob/main/src/agent/AgentConfirm.ts)

## Used in

- [Chat](https://uicontext.com/blocks/ai-chat.md)
- [Work](https://uicontext.com/blocks/work.md)
- [Bots](https://uicontext.com/blocks/bot-console.md)

## Related

- [Agent Tools](https://uicontext.com/docs/components/agent-tools.md) (`agent-tools`): Lets agents in the browser read the page and act through the same controls people use.
- [Prompt Template](https://uicontext.com/docs/components/prompt-template.md) (`prompt-template`): Write a prompt with {{variables}} the app fills in: they stand out, unknown ones are flagged, and a preview shows it with samples.
- [Agent Settings](https://uicontext.com/docs/components/agent-settings.md) (`agent-settings`): Edit an agent's name, instructions, tools and model.
- [Computer](https://uicontext.com/docs/components/computer.md) (`computer`): The machine an agent works on: a live view of its screen, full size or as a thumbnail with Take over, and its browser with tabs and an address bar.
- [Persona Avatar](https://uicontext.com/docs/components/persona-avatar.md) (`persona-avatar`): An agent's face: a shape and a color with eyes that move with what it's doing.
- [Agent List](https://uicontext.com/docs/components/agent-list.md) (`agent-list`): Agents listed like conversations, each with its face, last message time and status.
