

A compact row per AI SDK tool part: name, status, summary, and elapsed time, expanding to syntax-colored input and output. Handles retry and approval, and groups the calls of one step under a single row.
Free to install. No account needed.
@shadcn
aisdkagents Looks amazing. A registry of agents makes so much sense. I like this distribution method.
Join AI Engineers from these companies
Install with CLI adds the component and its dependencies. To paste the file by hand, add these first.
Packages
pnpm add @hugeicons/core-free-icons @hugeicons/react ai motion reactRegistry dependencies
npx shadcn@latest add utilsWith the shadcn CLI
npx shadcn@latest add https://www.aisdkagents.com/r/styles/new-york-v4/tool-call-card.json"use client";
import {
AlertCircleIcon,
ArrowDown01Icon,
Loading03Icon,
ShieldKeyIcon,
Tick02Icon,
UnavailableIcon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import type { IconSvgElement } from "@hugeicons/react";
import type { DynamicToolUIPart, ToolUIPart } from "ai";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import {
useEffect,
useId,
useRef,
useState,
useSyncExternalStore,
} from "react";
import type { CSSProperties, ReactNode } from "react";
import { cn } from "@/lib/utils";
export type ToolCallStatus =
| "streaming"
| "running"
| "approval"
| "done"
| "error"
| "denied";
export interface ToolCall {
id: string;
/** Tool name as the model called it, such as `search_web`. */
name: string;
/** Human title from the tool definition. Shown instead of `name`. */
title?: string;
status: ToolCallStatus;
/** Arguments. May be partial while `status` is `streaming`. */
input?: unknown;
output?: unknown;
errorText?: string;
/** Pass back to `addToolApprovalResponse` from `onApprove` or `onDeny`. */
approvalId?: string;
/** Why approval is asked for, or why the call was denied. */
reason?: string;
/** Epoch ms the call started. Without it the card times what it sees. */
startedAt?: number;
/** Final duration. Without it the card times what it sees. */
durationMs?: number;
}
/** A tool part from `useChat` messages, typed or dynamic. */
export type ToolCallPart = ToolUIPart | DynamicToolUIPart;
export type ToolCallTiming = Pick<ToolCall, "startedAt" | "durationMs">;
const TOOL_PREFIX = "tool-";
export const isToolCallPart = (part: { type: string }): part is ToolCallPart =>
part.type === "dynamic-tool" || part.type.startsWith(TOOL_PREFIX);
export const toolCallStatus = (part: ToolCallPart): ToolCallStatus => {
if (part.state === "input-streaming") {
return "streaming";
}
if (part.state === "approval-requested") {
return "approval";
}
if (part.state === "approval-responded") {
return part.approval.approved ? "running" : "denied";
}
if (part.state === "output-available") {
return part.preliminary ? "running" : "done";
}
if (part.state === "output-error") {
return "error";
}
if (part.state === "output-denied") {
return "denied";
}
return "running";
};
/**
* Maps an AI SDK tool part to the card's shape. Parts carry no timestamps, so
* pass `timing` when the server recorded one (for example in message
* metadata). Otherwise the card times the states it sees.
*
* @example
* message.parts.filter(isToolCallPart).map((part) => (
* <ToolCallCard key={part.toolCallId} part={part} />
* ));
*/
export const toolCallFromPart = (
part: ToolCallPart,
timing?: ToolCallTiming
): ToolCall => ({
approvalId: part.approval?.id,
durationMs: timing?.durationMs,
errorText: part.errorText,
id: part.toolCallId,
input: part.input,
name:
part.type === "dynamic-tool"
? part.toolName
: part.type.slice(TOOL_PREFIX.length),
output: part.output,
reason: part.approval?.reason ?? part.approval?.requestReason,
startedAt: timing?.startedAt,
status: toolCallStatus(part),
title: part.title,
});
/** Every tool call in a message, in order. */
export const toolCallsFromMessage = (message: {
parts: readonly { type: string }[];
}): ToolCall[] =>
message.parts.filter(isToolCallPart).map((part) => toolCallFromPart(part));
const ACTIVE: ReadonlySet<ToolCallStatus> = new Set(["streaming", "running"]);
export const isToolCallActive = (status: ToolCallStatus): boolean =>
ACTIVE.has(status);
/** `0.4s`, `1.7s`, `12s`, `1m 04s`. */
export const formatDuration = (ms: number): string => {
const value = Number.isFinite(ms) ? Math.max(0, ms) : 0;
if (value < 9950) {
return `${(value / 1000).toFixed(1)}s`;
}
const seconds = Math.round(value / 1000);
if (seconds < 60) {
return `${seconds}s`;
}
const rest = String(seconds % 60).padStart(2, "0");
return `${Math.floor(seconds / 60)}m ${rest}s`;
};
export interface ToolCallBody {
text: string;
/** True when `text` is pretty-printed JSON and can be highlighted. */
json: boolean;
}
const looksLikeJson = (text: string): boolean =>
text.startsWith("{") || text.startsWith("[");
/** Display text for arguments or a result. JSON strings are re-indented. */
export const toolCallBody = (value: unknown): ToolCallBody => {
if (value === undefined) {
return { json: false, text: "" };
}
if (typeof value === "string") {
const trimmed = value.trim();
if (!looksLikeJson(trimmed)) {
return { json: false, text: value };
}
try {
return {
json: true,
text: JSON.stringify(JSON.parse(trimmed), null, 2),
};
} catch {
return { json: false, text: value };
}
}
try {
const text = JSON.stringify(value, null, 2);
return text === undefined
? { json: false, text: String(value) }
: { json: true, text };
} catch {
return { json: false, text: String(value) };
}
};
const previewValue = (value: unknown): string => {
if (typeof value === "string") {
return JSON.stringify(value);
}
if (Array.isArray(value)) {
return "[…]";
}
if (value !== null && typeof value === "object") {
return "{…}";
}
return String(value);
};
const previewText = (input: unknown): string => {
if (input === undefined) {
return "";
}
if (typeof input === "string") {
return input.replaceAll(/\s+/gu, " ").trim();
}
if (Array.isArray(input)) {
return `${input.length} ${input.length === 1 ? "item" : "items"}`;
}
if (input !== null && typeof input === "object") {
return Object.entries(input)
.filter(([, value]) => value !== undefined)
.map(([key, value]) => `${key}: ${previewValue(value)}`)
.join(", ");
}
return String(input);
};
/** One line of arguments for the collapsed row: `query: "crm", limit: 5`. */
export const toolCallPreview = (input: unknown, max = 96): string => {
const text = previewText(input);
return text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text;
};
export type ToolCallTokenKind =
| "key"
| "string"
| "number"
| "literal"
| "punctuation"
| "plain";
export interface ToolCallToken {
kind: ToolCallTokenKind;
offset: number;
text: string;
}
const JSON_TOKEN =
/"(?:[^"\\]|\\.)*"?|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|\b(?:true|false|null)\b|[{}[\],:]/gu;
const KEY_SUFFIX = /\s*:/uy;
const jsonTokenKind = (
value: string,
source: string,
end: number
): ToolCallTokenKind => {
if (value.startsWith('"')) {
KEY_SUFFIX.lastIndex = end;
return KEY_SUFFIX.test(source) ? "key" : "string";
}
if (value === "true" || value === "false" || value === "null") {
return "literal";
}
if (value.length === 1 && "{}[],:".includes(value)) {
return "punctuation";
}
return "number";
};
/** Splits JSON text into colored tokens. Unfinished strings still tokenize. */
export const tokenizeJson = (source: string): ToolCallToken[] => {
const tokens: ToolCallToken[] = [];
let cursor = 0;
for (const match of source.matchAll(JSON_TOKEN)) {
const [value] = match;
const offset = match.index;
if (offset > cursor) {
tokens.push({
kind: "plain",
offset: cursor,
text: source.slice(cursor, offset),
});
}
cursor = offset + value.length;
tokens.push({
kind: jsonTokenKind(value, source, cursor),
offset,
text: value,
});
}
if (cursor < source.length) {
tokens.push({ kind: "plain", offset: cursor, text: source.slice(cursor) });
}
return tokens;
};
export interface ToolCallGroupSummary {
status: ToolCallStatus;
title: string;
detail: string;
}
const countLabel = (count: number): string =>
`${count} ${count === 1 ? "tool" : "tools"}`;
const displayName = (call: ToolCall): string => call.title ?? call.name;
/** The one line a group shows for all of its calls. */
export const toolCallGroupSummary = (
calls: readonly ToolCall[]
): ToolCallGroupSummary => {
const active = calls.filter((call) => isToolCallActive(call.status));
const waiting = calls.filter((call) => call.status === "approval");
const failed = calls.filter((call) => call.status === "error").length;
const denied = calls.filter((call) => call.status === "denied").length;
if (active.length > 0) {
const settled = calls.length - active.length - waiting.length;
return {
detail: `${settled} of ${calls.length} done`,
status: "running",
title: "Running tools",
};
}
if (waiting.length > 0) {
return {
detail: waiting.map(displayName).join(", "),
status: "approval",
title: "Waiting for approval",
};
}
const title = `Ran ${countLabel(calls.length)}`;
if (failed > 0) {
return { detail: `${failed} failed`, status: "error", title };
}
if (denied > 0) {
return { detail: `${denied} denied`, status: "denied", title };
}
return {
detail: [...new Set(calls.map(displayName))].join(", "),
status: "done",
title: calls.length === 0 ? "No tools ran" : title,
};
};
export type ToolCallSummary = string | ((call: ToolCall) => string | undefined);
export interface ToolCallClassNames {
root?: string;
header?: string;
list?: string;
row?: string;
name?: string;
summary?: string;
duration?: string;
detail?: string;
section?: string;
code?: string;
/** The wrapper around what `renderOutput` returns. */
output?: string;
actions?: string;
}
interface ToolCallActions {
/** Replaces the argument preview on the collapsed row. */
summary?: ToolCallSummary;
/** Rendered on failed calls only when passed. */
onRetry?: (call: ToolCall) => void;
/** Rendered on calls waiting for approval only when passed. */
onApprove?: (call: ToolCall) => void;
/** Rendered on calls waiting for approval only when passed. */
onDeny?: (call: ToolCall) => void;
/**
* Draws a call's result your way when the row is open, in place of the
* highlighted output: a form the tool asks for, a chart, a preview. Return
* `undefined` to keep the built-in result for that call.
*/
renderOutput?: (call: ToolCall) => ReactNode;
}
export interface ToolCallCardProps extends ToolCallActions {
/** A tool part from `useChat`. Wins over `call`. */
part?: ToolCallPart;
/**
* A call in the card's own shape, for non AI SDK sources. With neither
* `part` nor `call`, nothing renders.
*/
call?: ToolCall;
/** Uncontrolled open state. Calls waiting for approval start open. */
defaultOpen?: boolean;
open?: boolean;
onOpenChange?: (open: boolean) => void;
className?: string;
classNames?: ToolCallClassNames;
/** Handy for overriding the --tool-call-* theme vars inline */
style?: CSSProperties;
}
export interface ToolCallGroupProps extends ToolCallActions {
/** Tool parts from one `useChat` message. Wins over `calls`. */
parts?: readonly ToolCallPart[];
/** With no parts and no calls, nothing renders. */
calls?: readonly ToolCall[];
/**
* Uncontrolled open state. Left out, the group stays open while any call
* is unfinished and folds to its summary once they all succeed.
*/
defaultOpen?: boolean;
open?: boolean;
onOpenChange?: (open: boolean) => void;
className?: string;
classNames?: ToolCallClassNames;
/** Handy for overriding the --tool-call-* theme vars inline */
style?: CSSProperties;
}
const NO_CALLS: readonly ToolCall[] = [];
const COPIED_MS = 1600;
const TICK_MS = 100;
const HIGHLIGHT_LIMIT = 40_000;
const EASE = [0.4, 0, 0.2, 1] as const;
const ENTER_CLASS =
"fade-in-0 slide-in-from-bottom-2 animate-in fill-mode-both duration-300 ease-out motion-reduce:animate-none";
const THEME_VARS = [
"[--tool-call-done:#15803d] dark:[--tool-call-done:#4ade80]",
"[--tool-call-error:var(--destructive)]",
"[--tool-call-approval:#a3472c] dark:[--tool-call-approval:#e39278]",
"[--tool-call-key:#005cc5] dark:[--tool-call-key:#79b8ff]",
"[--tool-call-string:#032f62] dark:[--tool-call-string:#9ecbff]",
"[--tool-call-number:#b35900] dark:[--tool-call-number:#ffab70]",
"[--tool-call-literal:#d73a49] dark:[--tool-call-literal:#f97583]",
"[--tool-call-shadow:0_0_0_1px_rgba(0,0,0,0.06),0_1px_2px_-1px_rgba(0,0,0,0.06),0_2px_4px_0px_rgba(0,0,0,0.04)]",
"[--tool-call-shadow-hover:0_0_0_1px_rgba(0,0,0,0.08),0_1px_2px_-1px_rgba(0,0,0,0.08),0_2px_4px_0px_rgba(0,0,0,0.06)]",
"dark:[--tool-call-shadow:0_0_0_1px_rgba(255,255,255,0.08)]",
"dark:[--tool-call-shadow-hover:0_0_0_1px_rgba(255,255,255,0.13)]",
].join(" ");
const ROOT_CLASS =
"flex w-full max-w-full min-w-0 flex-col rounded-2xl bg-card p-2 text-card-foreground shadow-(--tool-call-shadow) transition-shadow duration-150 ease-out hover:shadow-(--tool-call-shadow-hover)";
const STATUS_META: Record<
ToolCallStatus,
{ icon: IconSvgElement; label: string; tone: string; well: string }
> = {
approval: {
icon: ShieldKeyIcon,
label: "Needs approval",
tone: "text-(--tool-call-approval)",
well: "bg-[color-mix(in_oklab,var(--tool-call-approval)_14%,transparent)]",
},
denied: {
icon: UnavailableIcon,
label: "Denied",
tone: "text-muted-foreground",
well: "bg-foreground/6",
},
done: {
icon: Tick02Icon,
label: "Finished",
tone: "text-(--tool-call-done)",
well: "bg-[color-mix(in_oklab,var(--tool-call-done)_12%,transparent)]",
},
error: {
icon: AlertCircleIcon,
label: "Failed",
tone: "text-(--tool-call-error)",
well: "bg-[color-mix(in_oklab,var(--tool-call-error)_12%,transparent)]",
},
running: {
icon: Loading03Icon,
label: "Running",
tone: "text-muted-foreground",
well: "bg-foreground/6",
},
streaming: {
icon: Loading03Icon,
label: "Preparing",
tone: "text-muted-foreground",
well: "bg-foreground/6",
},
};
const TOKEN_CLASS: Record<ToolCallTokenKind, string | undefined> = {
key: "text-(--tool-call-key)",
literal: "text-(--tool-call-literal)",
number: "text-(--tool-call-number)",
plain: undefined,
punctuation: "text-muted-foreground",
string: "text-(--tool-call-string)",
};
interface Stopwatch {
/** Epoch ms the current run started, or null while stopped. */
since: number | null;
/** Time banked from earlier runs. */
elapsed: number;
}
const advanceStopwatch = (
watch: Stopwatch | undefined,
running: boolean,
stamp: number
): Stopwatch | undefined => {
if (running) {
return watch?.since === null || watch === undefined
? { elapsed: watch?.elapsed ?? 0, since: stamp }
: watch;
}
if (watch === undefined || watch.since === null) {
return watch;
}
return { elapsed: watch.elapsed + stamp - watch.since, since: null };
};
interface StopwatchStore {
advance: (entries: readonly [string, boolean][], stamp: number) => void;
read: () => Record<string, Stopwatch>;
subscribe: (listener: () => void) => () => void;
}
const NO_WATCHES: Record<string, Stopwatch> = {};
const createStopwatchStore = (): StopwatchStore => {
let watches = NO_WATCHES;
const listeners = new Set<() => void>();
return {
advance: (entries, stamp) => {
const next = { ...watches };
let changed = false;
for (const [id, on] of entries) {
const watch = advanceStopwatch(watches[id], on, stamp);
if (watch && watch !== watches[id]) {
next[id] = watch;
changed = true;
}
}
if (!changed) {
return;
}
watches = next;
for (const listener of listeners) {
listener();
}
},
read: () => watches,
subscribe: (listener) => {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
};
};
const readNoWatches = () => NO_WATCHES;
/**
* One stopwatch per id. Each runs while its flag is true and banks the time
* when it stops, so a wait for approval is not counted as tool time.
*/
const useStopwatches = (
running: Record<string, boolean>
): Record<string, Stopwatch> => {
const [store] = useState(createStopwatchStore);
const watches = useSyncExternalStore(
store.subscribe,
store.read,
readNoWatches
);
const signature = JSON.stringify(Object.entries(running));
useEffect(() => {
const entries: [string, boolean][] = JSON.parse(signature);
store.advance(entries, Date.now());
}, [signature, store]);
return watches;
};
const resolveWatch = (
call: ToolCall,
watch: Stopwatch | undefined
): Stopwatch | undefined => {
if (call.durationMs !== undefined) {
return { elapsed: call.durationMs, since: null };
}
if (call.startedAt !== undefined && isToolCallActive(call.status)) {
return { elapsed: 0, since: call.startedAt };
}
return watch;
};
const Elapsed = ({
className,
watch,
}: {
className?: string;
watch: Stopwatch | undefined;
}) => {
const since = watch?.since ?? null;
const [now, setNow] = useState<number | null>(null);
useEffect(() => {
if (since === null) {
return;
}
const tick = () => {
setNow(Date.now());
};
const first = setTimeout(tick, 0);
const timer = setInterval(tick, TICK_MS);
return () => {
clearTimeout(first);
clearInterval(timer);
};
}, [since]);
if (!watch || (since === null && watch.elapsed <= 0)) {
return null;
}
const live = since !== null && now !== null ? Math.max(0, now - since) : 0;
return (
<span
className={cn(
"flex-none text-xs leading-4 text-muted-foreground tabular-nums",
className
)}
data-slot="tool-call-duration"
>
{formatDuration(watch.elapsed + live)}
</span>
);
};
const Shimmer = ({
children,
className,
}: {
children: ReactNode;
className?: string;
}) => {
const reduce = useReducedMotion();
if (reduce) {
return <span className={className}>{children}</span>;
}
return (
<motion.span
animate={{ backgroundPosition: ["100% 0", "-100% 0"] }}
className={cn(
"bg-[linear-gradient(90deg,var(--muted-foreground)_35%,var(--card-foreground)_50%,var(--muted-foreground)_65%)] bg-size-[200%_100%] bg-clip-text text-transparent",
className
)}
transition={{
duration: 1.6,
ease: "linear",
repeat: Number.POSITIVE_INFINITY,
}}
>
{children}
</motion.span>
);
};
const StatusIcon = ({ status }: { status: ToolCallStatus }) => {
const reduce = useReducedMotion();
const meta = STATUS_META[status];
const spinning = isToolCallActive(status);
return (
<span
className={cn(
"relative inline-flex size-5 flex-none items-center justify-center rounded-md transition-colors duration-200 ease-out motion-reduce:transition-none",
meta.well,
meta.tone
)}
data-slot="tool-call-status"
data-status={status}
>
<AnimatePresence initial={false} mode="popLayout">
<motion.span
animate={{ filter: "blur(0px)", opacity: 1, scale: 1 }}
className="absolute inset-0 inline-flex items-center justify-center"
exit={{ filter: "blur(4px)", opacity: 0, scale: 0.25 }}
initial={{ filter: "blur(4px)", opacity: 0, scale: 0.25 }}
key={spinning ? "active" : status}
transition={
reduce
? { duration: 0 }
: { bounce: 0, duration: 0.3, type: "spring" }
}
>
<HugeiconsIcon
aria-hidden="true"
className={cn(
"size-3",
spinning && "animate-spin motion-reduce:animate-none"
)}
icon={meta.icon}
strokeWidth={2}
/>
</motion.span>
</AnimatePresence>
</span>
);
};
const Chevron = ({ open }: { open: boolean }) => (
<HugeiconsIcon
aria-hidden="true"
className={cn(
"size-3 flex-none text-muted-foreground transition-transform duration-150 ease-out motion-reduce:transition-none",
open ? "rotate-0" : "-rotate-90"
)}
icon={ArrowDown01Icon}
strokeWidth={2}
/>
);
const ActionButton = ({
slot,
variant,
onClick,
children,
}: {
slot: string;
variant: "ghost" | "primary";
onClick: () => void;
children: string;
}) => (
<button
className={cn(
"relative z-0 inline-flex h-6 flex-none cursor-pointer items-center rounded-full border-0 px-2.5 text-xs leading-none font-medium transition-transform duration-150 ease-out after:absolute after:inset-x-0 after:-inset-y-2 after:content-[''] focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none active:scale-[0.96] motion-reduce:transition-none dark:focus-visible:ring-ring/80",
"before:absolute before:inset-0 before:-z-1 before:rounded-full before:transition-colors before:duration-150 before:ease-out before:content-['']",
variant === "ghost" &&
"text-card-foreground before:bg-foreground/6 hover:before:bg-foreground/10",
variant === "primary" &&
"text-primary-foreground before:bg-primary hover:before:bg-primary/90"
)}
data-slot={slot}
onClick={onClick}
type="button"
>
{children}
</button>
);
const CopyButton = ({ label, text }: { label: string; text: string }) => {
const [copied, setCopied] = useState(false);
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(
() => () => {
if (timer.current) {
clearTimeout(timer.current);
}
},
[]
);
const copy = async () => {
try {
await navigator.clipboard.writeText(text);
} catch {
return;
}
setCopied(true);
if (timer.current) {
clearTimeout(timer.current);
}
timer.current = setTimeout(() => {
setCopied(false);
}, COPIED_MS);
};
return (
<>
<button
aria-label={`Copy ${label.toLowerCase()}`}
className="relative inline-flex h-5 flex-none cursor-pointer items-center rounded-md border-0 bg-transparent px-1.5 text-[11px] leading-none font-medium text-muted-foreground transition-[background-color,color,transform] duration-150 ease-out after:absolute after:-inset-1 after:content-[''] hover:bg-foreground/6 hover:text-card-foreground focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none active:scale-[0.96] motion-reduce:transition-none dark:focus-visible:ring-ring/80"
data-slot="tool-call-copy"
onClick={() => {
void copy();
}}
type="button"
>
{copied ? "Copied" : "Copy"}
</button>
<span className="sr-only" role="status">
{copied ? `Copied ${label.toLowerCase()}` : ""}
</span>
</>
);
};
const CodeText = ({ body }: { body: ToolCallBody }) => {
if (!body.json || body.text.length > HIGHLIGHT_LIMIT) {
return body.text;
}
return tokenizeJson(body.text).map((token) => (
<span className={TOKEN_CLASS[token.kind]} key={token.offset}>
{token.text}
</span>
));
};
const ToolCallSection = ({
body,
classNames,
label,
placeholder,
tone,
}: {
body: ToolCallBody;
classNames?: ToolCallClassNames;
label: string;
/** Shown, shimmering, while there is nothing to print yet. */
placeholder?: string;
tone?: "error";
}) => (
<div
className={cn(
"flex min-w-0 flex-col rounded-lg bg-muted dark:bg-background",
classNames?.section
)}
data-slot="tool-call-section"
>
<div className="flex h-7 items-center justify-between gap-2 pr-1 pl-2">
<span className="text-[11px] leading-none font-medium text-muted-foreground">
{label}
</span>
{body.text ? <CopyButton label={label} text={body.text} /> : null}
</div>
{body.text ? (
<pre
className={cn(
"m-0 max-h-60 overflow-auto px-2 pb-2 font-mono text-xs leading-4 wrap-break-word whitespace-pre-wrap",
tone === "error"
? "text-(--tool-call-error)"
: "text-card-foreground",
classNames?.code
)}
data-slot="tool-call-code"
>
<CodeText body={body} />
</pre>
) : (
<div className="px-2 pb-2 text-xs leading-4 text-muted-foreground">
{placeholder ? <Shimmer>{placeholder}</Shimmer> : "Nothing returned"}
</div>
)}
</div>
);
const resultSection = (
call: ToolCall
): { body: ToolCallBody; label: string; placeholder?: string } | null => {
if (call.status === "error") {
return {
body: { json: false, text: call.errorText ?? "The tool call failed." },
label: "Error",
};
}
if (call.status === "denied") {
return {
body: { json: false, text: call.reason ?? "Denied before it ran." },
label: "Result",
};
}
if (call.status === "approval") {
return null;
}
return {
body: toolCallBody(call.output),
label: "Result",
placeholder: call.status === "done" ? undefined : "Running…",
};
};
const ToolCallDetail = ({
call,
classNames,
id,
onApprove,
onDeny,
renderOutput,
}: {
call: ToolCall;
classNames?: ToolCallClassNames;
id: string;
onApprove?: (call: ToolCall) => void;
onDeny?: (call: ToolCall) => void;
renderOutput?: (call: ToolCall) => ReactNode;
}) => {
const reduce = useReducedMotion();
const custom = renderOutput?.(call);
const result = custom === undefined ? resultSection(call) : null;
const decides = call.status === "approval" && (onApprove || onDeny);
return (
<motion.div
animate={{ height: "auto", opacity: 1 }}
className="overflow-hidden"
exit={{ height: 0, opacity: 0 }}
id={id}
initial={{ height: 0, opacity: 0 }}
transition={{ duration: reduce ? 0 : 0.2, ease: EASE }}
>
<div
className={cn("flex flex-col gap-1.5 pt-1.5", classNames?.detail)}
data-slot="tool-call-detail"
>
<ToolCallSection
body={toolCallBody(call.input)}
classNames={classNames}
label="Arguments"
placeholder={
call.status === "streaming" ? "Reading arguments…" : undefined
}
/>
{custom === undefined ? null : (
<div
className={cn("min-w-0", classNames?.output)}
data-slot="tool-call-output"
>
{custom}
</div>
)}
{result ? (
<ToolCallSection
body={result.body}
classNames={classNames}
label={result.label}
placeholder={result.placeholder}
tone={call.status === "error" ? "error" : undefined}
/>
) : null}
{call.status === "approval" ? (
<div
className={cn(
"flex min-h-6 min-w-0 items-center gap-1.5 p-0.5",
classNames?.actions
)}
data-slot="tool-call-approval"
>
<span className="min-w-0 flex-1 text-xs leading-4 text-pretty text-muted-foreground">
{call.reason ?? "Runs once you approve it."}
</span>
{decides && onDeny ? (
<ActionButton
onClick={() => {
onDeny(call);
}}
slot="tool-call-deny"
variant="ghost"
>
Deny
</ActionButton>
) : null}
{decides && onApprove ? (
<ActionButton
onClick={() => {
onApprove(call);
}}
slot="tool-call-approve"
variant="primary"
>
Approve
</ActionButton>
) : null}
</div>
) : null}
</div>
</motion.div>
);
};
const firstLine = (text: string): string =>
text.trim().split("\n").at(0)?.trim() ?? "";
const rowSummary = (
call: ToolCall,
summary: ToolCallSummary | undefined
): string => {
if (call.status === "error") {
return firstLine(call.errorText ?? "") || "Failed";
}
if (call.status === "approval") {
return "Needs approval";
}
const custom = typeof summary === "function" ? summary(call) : summary;
const text = custom ?? toolCallPreview(call.input);
if (call.status === "denied") {
return text ? `Denied · ${text}` : "Denied";
}
return text;
};
const TOGGLE_CLASS =
"h-7 min-w-0 cursor-pointer items-center rounded-lg border-0 bg-transparent py-0 pr-1.5 pl-1 text-left transition-colors duration-150 ease-out hover:bg-foreground/6 focus-visible:ring-2 focus-visible:ring-ring/50 dark:focus-visible:ring-ring/80 focus-visible:outline-none focus-visible:ring-inset motion-reduce:transition-none";
const ToolCallRow = ({
call,
classNames,
onApprove,
onDeny,
onRetry,
onToggle,
open,
renderOutput,
summary,
watch,
}: ToolCallActions & {
call: ToolCall;
classNames?: ToolCallClassNames;
onToggle: () => void;
open: boolean;
watch: Stopwatch | undefined;
}) => {
const detailId = useId();
const active = isToolCallActive(call.status);
const text = rowSummary(call, summary);
const summaryClass = cn(
"min-w-0 flex-1 truncate text-[13px] leading-4",
call.status === "error"
? "text-(--tool-call-error)"
: "text-muted-foreground",
call.status === "approval" && "text-(--tool-call-approval)",
classNames?.summary
);
return (
<div
className="flex min-w-0 flex-col"
data-slot="tool-call"
data-state={open ? "open" : "closed"}
data-status={call.status}
>
<div
className={cn(
"grid min-w-0 grid-cols-[minmax(0,1fr)_auto_auto] items-center",
classNames?.row
)}
data-slot="tool-call-row"
>
<button
aria-controls={open ? detailId : undefined}
aria-expanded={open}
className={cn(
TOGGLE_CLASS,
"col-span-3 col-start-1 row-start-1 grid grid-cols-subgrid"
)}
data-slot="tool-call-trigger"
onClick={onToggle}
type="button"
>
<span className="flex min-w-0 items-center gap-2">
<StatusIcon status={call.status} />
<span
className={cn(
"max-w-[60%] flex-none truncate leading-4 font-medium",
call.title
? "text-[13px] tracking-[-0.01em]"
: "font-mono text-xs",
call.status === "denied" &&
"text-muted-foreground line-through",
classNames?.name
)}
data-slot="tool-call-name"
>
{displayName(call)}
</span>
{active && text ? (
<Shimmer className={summaryClass}>{text}</Shimmer>
) : (
<span className={summaryClass} data-slot="tool-call-summary">
{text}
</span>
)}
<span className="sr-only">{STATUS_META[call.status].label}</span>
</span>
<span className="col-start-3 flex items-center gap-2 pl-2">
<Elapsed className={classNames?.duration} watch={watch} />
<Chevron open={open} />
</span>
</button>
{call.status === "error" && onRetry ? (
<span className="z-1 col-start-2 row-start-1 flex pl-2">
<ActionButton
onClick={() => {
onRetry(call);
}}
slot="tool-call-retry"
variant="ghost"
>
Retry
</ActionButton>
</span>
) : null}
</div>
<AnimatePresence initial={false}>
{open ? (
<ToolCallDetail
call={call}
classNames={classNames}
id={detailId}
key="detail"
onApprove={onApprove}
onDeny={onDeny}
renderOutput={renderOutput}
/>
) : null}
</AnimatePresence>
</div>
);
};
const announce = (title: string, detail: string): string =>
detail ? `${title}, ${detail}` : title;
/**
* One tool call on one line: status, name, a short summary, and a live timer.
* Opens to the highlighted arguments and result.
*
* @example
* const { messages, addToolApprovalResponse } = useChat();
* <ToolCallCard
* onApprove={(call) =>
* addToolApprovalResponse({ approved: true, id: call.approvalId ?? "" })
* }
* part={part}
* />
*/
export const ToolCallCard = ({
part,
call: callProp,
...props
}: ToolCallCardProps) => {
const call = part ? toolCallFromPart(part) : callProp;
return call ? <ToolCallCardView call={call} {...props} /> : null;
};
const ToolCallCardView = ({
call,
summary,
defaultOpen,
open,
onOpenChange,
onRetry,
onApprove,
onDeny,
renderOutput,
className,
classNames,
style,
}: Omit<ToolCallCardProps, "call" | "part"> & { call: ToolCall }) => {
const [chosen, setChosen] = useState(defaultOpen);
const watches = useStopwatches({ [call.id]: isToolCallActive(call.status) });
const isOpen = open ?? chosen ?? call.status === "approval";
const label = STATUS_META[call.status].label.toLowerCase();
return (
<section
aria-label={`${displayName(call)}, ${label}`}
className={cn(
THEME_VARS,
ENTER_CLASS,
ROOT_CLASS,
className,
classNames?.root
)}
data-slot="tool-call-card"
data-status={call.status}
style={style}
>
<ToolCallRow
call={call}
classNames={classNames}
onApprove={onApprove}
onDeny={onDeny}
onRetry={onRetry}
onToggle={() => {
if (open === undefined) {
setChosen(!isOpen);
}
onOpenChange?.(!isOpen);
}}
open={isOpen}
renderOutput={renderOutput}
summary={summary}
watch={resolveWatch(call, watches[call.id])}
/>
<output aria-live="polite" className="sr-only">
{announce(displayName(call), label)}
</output>
</section>
);
};
const GROUP_WATCH = "tool-call-group";
const groupWatch = (
calls: readonly ToolCall[],
watch: Stopwatch | undefined
): Stopwatch | undefined => {
const recorded = calls.every((call) => call.durationMs !== undefined);
if (!recorded || calls.length === 0) {
return watch;
}
let elapsed = 0;
for (const call of calls) {
elapsed += call.durationMs ?? 0;
}
return { elapsed, since: null };
};
/**
* The tool calls of one step under a single row that sums them up. Each call
* opens on its own.
*
* @example
* <ToolCallGroup parts={message.parts.filter(isToolCallPart)} />
*/
export const ToolCallGroup = ({
parts,
calls: callsProp,
summary,
defaultOpen,
open,
onOpenChange,
onRetry,
onApprove,
onDeny,
renderOutput,
className,
classNames,
style,
}: ToolCallGroupProps) => {
const reduce = useReducedMotion();
const listId = useId();
const calls =
parts?.map((part) => toolCallFromPart(part)) ?? callsProp ?? NO_CALLS;
const [chosen, setChosen] = useState(defaultOpen);
const [rows, setRows] = useState<Record<string, boolean>>({});
const running: Record<string, boolean> = {
[GROUP_WATCH]: calls.some((call) => isToolCallActive(call.status)),
};
for (const call of calls) {
running[call.id] = isToolCallActive(call.status);
}
const watches = useStopwatches(running);
const group = toolCallGroupSummary(calls);
const unfinished = calls.some((call) => call.status !== "done");
const isOpen = open ?? chosen ?? unfinished;
const transition = { duration: reduce ? 0 : 0.2, ease: EASE };
const toggleRow = (call: ToolCall, rowOpen: boolean) => {
setRows((current) => ({ ...current, [call.id]: !rowOpen }));
// Reading a call pins the group open, so finishing does not fold it away.
setChosen((current) => current ?? true);
};
if (calls.length === 0) {
return null;
}
return (
<section
aria-label={announce(group.title, group.detail)}
className={cn(
THEME_VARS,
ENTER_CLASS,
ROOT_CLASS,
className,
classNames?.root
)}
data-slot="tool-call-group"
data-state={isOpen ? "open" : "closed"}
data-status={group.status}
style={style}
>
<button
aria-controls={isOpen ? listId : undefined}
aria-expanded={isOpen}
className={cn(TOGGLE_CLASS, "flex flex-none gap-2", classNames?.header)}
data-slot="tool-call-group-trigger"
onClick={() => {
if (open === undefined) {
setChosen(!isOpen);
}
onOpenChange?.(!isOpen);
}}
type="button"
>
<StatusIcon status={group.status} />
<span className="flex-none text-[13px] leading-4 font-medium tracking-[-0.01em]">
{group.status === "running" ? (
<Shimmer>{group.title}</Shimmer>
) : (
group.title
)}
</span>
<span
className={cn(
"min-w-0 flex-1 truncate text-[13px] leading-4",
group.status === "error"
? "text-(--tool-call-error)"
: "text-muted-foreground"
)}
data-slot="tool-call-group-detail"
>
{group.detail}
</span>
<Elapsed
className={classNames?.duration}
watch={groupWatch(calls, watches[GROUP_WATCH])}
/>
<Chevron open={isOpen} />
</button>
<AnimatePresence initial={false}>
{isOpen && calls.length > 0 ? (
<motion.div
animate={{ height: "auto", opacity: 1 }}
className="overflow-hidden"
exit={{ height: 0, opacity: 0 }}
id={listId}
initial={{ height: 0, opacity: 0 }}
key="list"
transition={transition}
>
<ul
className={cn(
"m-0 mt-1.5 flex list-none flex-col gap-px border-t border-foreground/6 p-0 pt-1.5",
classNames?.list
)}
data-slot="tool-call-list"
>
<AnimatePresence initial={false}>
{calls.map((call) => {
const rowOpen = rows[call.id] ?? call.status === "approval";
return (
<motion.li
animate={{ height: "auto", opacity: 1 }}
className="-mx-0.5 overflow-hidden px-0.5"
exit={{ height: 0, opacity: 0 }}
initial={{ height: 0, opacity: 0 }}
key={call.id}
transition={transition}
>
<ToolCallRow
call={call}
classNames={classNames}
onApprove={onApprove}
onDeny={onDeny}
onRetry={onRetry}
onToggle={() => {
toggleRow(call, rowOpen);
}}
open={rowOpen}
renderOutput={renderOutput}
summary={summary}
watch={resolveWatch(call, watches[call.id])}
/>
</motion.li>
);
})}
</AnimatePresence>
</ul>
</motion.div>
) : null}
</AnimatePresence>
<output aria-live="polite" className="sr-only">
{announce(group.title, group.detail)}
</output>
</section>
);
};