About
Tool calls from an AI agent as they happen: input streams in, an edit asks for approval with Allow and Deny, a command shows a live timer, and each result folds down to its output and timing.
Built with React and Tailwind. Copy the prompt and paste it into Claude Code, Cursor or Lovable: your agent adds Tool Call to your project and fits it to your theme.
Code
How Tool Call is used: the demo's code. The component's own source comes with a free account.
Usage.tsx
"use client"
import * as React from "react"
import { CopyButton, ToolCall, ToolCallCode, ToolCallProps, ToolCallSection, ToolDisplayState } from "@/components/ui/tool-call"
/** Opens with the search done and the file being read, so the first frame is mid run. */
const START_MS = 1400
/** How long a choice holds a tour before it carries on. */
const RESUME_MS = 1800
/** True until `RESUME_MS` after the last `hold()`, for tours with their own state. */
function useHold() {
const [held, setHeld] = React.useState(false)
const timer = React.useRef(0)
React.useEffect(() => () => window.clearTimeout(timer.current), [])
const hold = React.useCallback(() => {
setHeld(true)
window.clearTimeout(timer.current)
timer.current = window.setTimeout(() => setHeld(false), RESUME_MS)
}, [])
return [held, hold] as const
}
const reducedMotion = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches
const LOOP_MS = 9_600
/**
* One call per beat, as [ms from the start of the loop]: when it appears, when its input has
* streamed, when it asks (edit only), when it was allowed, and when its output lands.
*/
interface Call {
id: string
name: string
input: Record<string, string>
output: string
meta?: string
durationMs: number
at: number
streamed: number
ask?: number
allowed?: number
done: number
}
const FILE = "src/lib/format-date.ts"
const CALLS: Call[] = [
{
id: "search",
name: "search_code",
input: { pattern: "formatRunDate(" },
output: `src/lib/format-date.ts:8 export function formatRunDate(date: Date) {
src/components/recent-runs.tsx:31 {formatRunDate(run.startedAt)}
src/components/run-header.tsx:12 formatRunDate(run.finishedAt)`,
meta: "3 matches",
durationMs: 184,
at: 0,
streamed: 400,
done: 900,
},
{
id: "read",
name: "read_file",
input: { path: FILE },
output: `export function formatRunDate(date: Date) {
// Uses the machine locale: "Oct 21" here, "21 Oct" in CI.
return date.toLocaleDateString(undefined, { month: "short", day: "numeric" })
}`,
meta: "4 lines",
durationMs: 42,
at: 1300,
streamed: 1600,
done: 2000,
},
{
id: "edit",
name: "edit_file",
input: {
path: FILE,
old: "toLocaleDateString(undefined, {",
new: "toLocaleDateString('en-US', { timeZone: 'UTC',",
},
output: "Updated src/lib/format-date.ts",
meta: "+1 -1",
durationMs: 63,
at: 2600,
streamed: 3200,
ask: 3200,
allowed: 4500,
done: 4900,
},
{
id: "test",
name: "run_command",
input: { command: "pnpm test recent-runs" },
output: `✓ src/lib/format-date.test.ts (4 tests) 11ms
✓ src/components/recent-runs.test.tsx (6 tests) 238ms
Tests 10 passed (10)`,
meta: "exit 0",
durationMs: 1460,
at: 5500,
streamed: 5800,
done: 7200,
},
]
const FIT_CSS = "html,body{overflow:hidden}[data-fit-small] [data-fit-hide]{display:none!important}"
/**
* 21st shows a demo in a small frame: about 674 by 421 on a component page, 358 by 224 on a
* phone and 245 by 139 on a profile card. A demo taller than its frame gets scrollbars, which
* render white on dark pages. FitFrame fills the frame exactly instead.
*
* - "scale": the content shrinks until it fits, centered. For visuals such as orbs.
* - "crop": the content stays at full size from the top and fades out at the bottom. For text
* that streams in, where a changing scale would make the page breathe.
*
* `minWidth` lays out a wide demo (a table, a two column panel) at that width and scales it down
* to the frame, instead of letting it collapse to a narrow layout. The frame centers it, so it
* shrinks evenly on both sides.
*
* Anything marked `data-fit-hide` (state buttons, the chatcn.dev line) drops out in frames
* shorter than `hideBelow`, so a profile card shows the visual alone.
*/
function FitFrame({
children,
mode = "scale",
hideBelow = 360,
minWidth,
}: {
children: React.ReactNode
mode?: "scale" | "crop"
hideBelow?: number
minWidth?: string
}) {
const content = React.useRef<HTMLDivElement>(null)
const [cropped, setCropped] = React.useState(false)
React.useLayoutEffect(() => {
const el = content.current
if (!el) return
const measure = () => {
const vw = window.innerWidth
const vh = window.innerHeight
el.toggleAttribute("data-fit-small", vh < hideBelow)
// Layout sizes ignore the transform, so measuring never feeds back.
const w = Math.max(el.offsetWidth, el.scrollWidth)
const h = Math.max(el.offsetHeight, el.scrollHeight)
const scale = mode === "scale" ? Math.min(1, vw / w, vh / h) : 1
el.style.transform = scale < 1 ? `scale(${scale})` : ""
setCropped(mode === "crop" && h > vh + 1)
}
measure()
const observer = new ResizeObserver(measure)
observer.observe(el)
// Content that changes inside a fixed width box (a headline that cycles words) never resizes
// the box itself, so changes below it measure again on the next frame.
let frame = 0
const mutations = new MutationObserver(() => {
cancelAnimationFrame(frame)
frame = requestAnimationFrame(measure)
})
mutations.observe(el, { subtree: true, childList: true, characterData: true })
window.addEventListener("resize", measure)
return () => {
observer.disconnect()
mutations.disconnect()
cancelAnimationFrame(frame)
window.removeEventListener("resize", measure)
}
}, [mode, hideBelow])
const fade = "linear-gradient(to bottom, #000 calc(100% - 40px), transparent)"
return (
<div
className="flex w-full justify-center overflow-hidden"
style={{
height: "100dvh",
alignItems: mode === "crop" ? "flex-start" : "center",
maskImage: cropped ? fade : undefined,
WebkitMaskImage: cropped ? fade : undefined,
}}
>
<style>{FIT_CSS}</style>
<div
ref={content}
className="w-full shrink-0"
style={{ transformOrigin: mode === "crop" ? "top center" : "center", minWidth }}
>
{children}
</div>
</div>
)
}
/**
* Holds the transcript to a fixed height and follows its newest line, the way a chat sticks to
* the bottom: older calls glide up and fade under the top edge as new ones open.
*/
function Follow({ children }: { children: React.ReactNode }) {
const outer = React.useRef<HTMLDivElement>(null)
const inner = React.useRef<HTMLDivElement>(null)
const [offset, setOffset] = React.useState(0)
React.useLayoutEffect(() => {
const a = outer.current
const b = inner.current
if (!a || !b) return
const measure = () => setOffset(Math.max(0, b.offsetHeight - a.clientHeight))
measure()
const observer = new ResizeObserver(measure)
observer.observe(b)
observer.observe(a)
return () => observer.disconnect()
}, [])
const fade = "linear-gradient(to bottom, transparent, #000 2.5rem)"
return (
<div
ref={outer}
className="h-[25.5rem] w-full max-w-xl overflow-hidden"
style={offset > 0 ? { maskImage: fade, WebkitMaskImage: fade } : undefined}
>
<div
ref={inner}
className="ease-(--chatcn-ease-out) flex flex-col gap-3 transition-transform duration-300 motion-reduce:transition-none"
style={{ transform: `translateY(${-offset}px)` }}
>
{children}
</div>
</div>
)
}
function stateOf(call: Call, t: number): ToolDisplayState {
if (t < call.streamed) return "input-streaming"
if (call.ask !== undefined && call.allowed !== undefined) {
if (t < call.allowed) return "approval-requested"
if (t < call.done) return "approval-responded"
}
if (t < call.done) return "input-available"
return "output-available"
}
/** The raw JSON the model has written so far, for the streaming input view. */
function streamedText(call: Call, t: number) {
const raw = JSON.stringify(call.input)
const span = Math.max(1, call.streamed - call.at)
const n = Math.ceil((Math.max(0, t - call.at) / span) * raw.length)
return raw.slice(0, Math.max(2, n))
}
/** The live counter of a long running command, in whole seconds like the component's own. */
function runningLabel(call: Call, t: number) {
const ms = t - call.streamed
return ms < 1000 ? "Running" : `${Math.floor(ms / 1000)} s`
}
const REASON = "Pin the date format to en-US and UTC, so CI renders Oct 21 like your machine does."
/** The edit's output, as the two lines it changed. */
function EditDiff({ call }: { call: Call }) {
return (
<ToolCallCode>
<span className="text-(color:--chatcn-red)">- {call.input.old}</span>
{"\n"}
<span className="text-(color:--chatcn-green)">+ {call.input.new}</span>
</ToolCallCode>
)
}
/**
* A finished call folds its input away and keeps only what came back, so the newest result gets
* the room and the panel holds one height.
*/
function Result({ call, decision }: { call: Call; decision?: ToolCallProps["decision"] }) {
return (
<>
<ToolCallSection
label="Output"
action={<CopyButton size="icon-xs" value={call.output} label="Copy output" />}
>
{call.id === "edit" ? <EditDiff call={call} /> : <ToolCallCode>{call.output}</ToolCallCode>}
</ToolCallSection>
{decision?.approved ? (
<p className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-subtle)">Allowed once</p>
) : null}
</>
)
}
/** The agent's answer lands after the tests pass. */
const ANSWER_MS = 7600
/** The line under each 21st demo that points back to the kit. */
function MoreOn({ slug, children }: { slug: string; children: React.ReactNode }) {
return (
<p data-fit-hide className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-faint) text-center text-balance">
{children}{" "}
<a
href={`https://chatcn.dev/docs/components/${slug}`}
target="_blank"
rel="noopener"
className="text-(color:--chatcn-fg-subtle) hover:text-(color:--chatcn-fg) underline underline-offset-2"
>
chatcn.dev
</a>
</p>
)
}
/**
* A coding agent fixes a date bug: it searches, reads the file, asks before it edits, then runs
* the tests. The newest call opens while older ones fold to one line. Allow the edit, deny it or
* open any call and the run waits a moment, then carries on.
*/
export default function ToolCallPreview() {
const [clock, setClock] = React.useState(START_MS)
const [held, hold] = useHold()
const [opened, setOpened] = React.useState<Record<string, boolean>>({})
const [denied, setDenied] = React.useState<string>()
React.useEffect(() => {
if (held) return
if (reducedMotion()) {
setClock(LOOP_MS - 1)
return
}
const began = performance.now() - clock
const id = window.setInterval(() => {
const t = performance.now() - began
if (t >= LOOP_MS) {
// A new loop starts clean: every call folds back and a denied edit is forgotten.
setOpened({})
setDenied(undefined)
}
setClock(t % LOOP_MS)
}, 50)
return () => window.clearInterval(id)
// biome-ignore lint/correctness/useExhaustiveDependencies: resumes from the clock it held at.
}, [held])
const t = clock
const visible = CALLS.filter((c) => t >= c.at && !(denied && c.id === "test"))
const newest = visible[visible.length - 1]?.id
const edit = CALLS.find((c) => c.id === "edit")!
return (
<FitFrame minWidth="36rem">
<div
className="flex w-full flex-col items-center justify-center gap-5 p-6"
onPointerDownCapture={hold}
onKeyDownCapture={hold}
>
<Follow>
<p className="bg-(color:--chatcn-fill) text-[0.875rem]/[1.25rem] tracking-[-0.003em] text-(color:--chatcn-fg) rounded-(--chatcn-radius-xl) max-w-[85%] self-end px-3.5 py-2 text-pretty">
Run dates show as 21 Oct in CI but Oct 21 locally. Fix it.
</p>
<div className="flex flex-col gap-2">
{visible.map((call) => {
let state = stateOf(call, t)
let decision: ToolCallProps["decision"]
if (call.id === "edit") {
if (denied) {
state = "output-denied"
decision = { approved: false, reason: denied }
} else if (state === "approval-responded" || (state === "output-available" && call.ask))
decision = { approved: true, scope: "once" }
}
const done = state === "output-available"
return (
<ToolCall
key={call.id}
name={call.name}
state={state}
input={call.input}
inputText={state === "input-streaming" ? streamedText(call, t) : undefined}
output={call.output}
meta={done ? call.meta : undefined}
durationMs={call.durationMs}
statusLabel={
state === "input-available" && call.id === "test"
? runningLabel(call, t)
: undefined
}
approval={
call.ask !== undefined ? { id: `approve-${call.id}`, reason: REASON } : undefined
}
decision={decision}
onApprove={() => setClock(edit.allowed ?? t)}
onDeny={(_, reason) => setDenied(reason ?? "Keep the machine locale.")}
open={opened[call.id] ?? call.id === newest}
onOpenChange={(open) => setOpened((o) => ({ ...o, [call.id]: open }))}
>
{done ? <Result call={call} decision={decision} /> : undefined}
</ToolCall>
)
})}
</div>
{t >= ANSWER_MS && !denied ? (
<p className="text-[0.875rem]/[1.25rem] tracking-[-0.003em] text-(color:--chatcn-fg) ease-(--chatcn-ease-out-soft) px-1 text-pretty transition-opacity duration-200 starting:opacity-0">
Fixed. formatRunDate now pins en-US and UTC, so runs read Oct 21 on every machine,
and all 10 tests pass.
</p>
) : null}
</Follow>
<MoreOn slug="tool-call">
Streaming input, approvals, output and errors for every tool your agent calls. On
</MoreOn>
</div>
</FitFrame>
)
}
















