AI agent UI in React: tool calls, approvals, run traces and streaming
Build the UI for an AI agent in React: a live run trace, tool call results, human approval before risky tools, token usage and a stop button. Provider agnostic.
By Aman Kaushik, MiniDev20 min read
A chat UI shows a conversation. An agent UI shows work: the agent searches, reads, calls tools, sometimes asks before it acts, and finishes with a result. People need to see what it did, stop it when it goes wrong and approve the steps that matter. This guide builds that interface in React with free MiniDev UI components and plain fetch, so it works with any model provider or agent framework. If you are building a conversational assistant, start with the AI chat UI guide instead; the two share the streaming approach.
The components and what each one does
| Component | Job in an agent UI | Key props |
|---|---|---|
| AgentTrace | The whole run as a timeline of steps | steps (id, name, status, duration, detail), title, meta |
| ApprovalCard | Human-in-the-loop decision before a tool runs | title, requester, summary, onApprove, onReject, labels |
| ToolCallCard | One tool call inside a chat turn | name, args, status, duration, children |
| ToolResultPanel | A tool's output as formatted JSON | name, status, output |
| InlineCodeDiff | A single edit the agent made | before, after |
| ArtifactPreview | Something the agent produced, framed with copy and expand | title, copyValue, onExpand |
| CitationChip | An inline source for a claim in the answer | index, href |
| AiComposer | The task input; its send button becomes stop while running | value, onSubmit, streaming, onStop |
| TokenUsageMeter | Tokens used against a budget | used, limit, label, note |
npx shadcn@latest add @minidev/agent-trace @minidev/approval-card @minidev/tool-result-panel @minidev/inline-code-diff @minidev/ai-composer @minidev/token-usage-meter
Files land in components/ui. The components read MiniDev's semantic tokens, so add the token stylesheet to your global CSS once.
Model the run as events
The server streams one JSON object per line (NDJSON). There are five event types: a tool started, a tool finished, the agent needs approval, some answer text, and a token count. The client folds them into a Run with a pure reducer, which is easy to test and replays the same way every time. Steps are upserted by id, so a step that waited for approval turns into the running step without a duplicate row.
export type StepStatus = "pending" | "running" | "done" | "error"
export type ToolStep = { id: string; name: string; args: string; status: StepStatus; ms?: number; output?: unknown }
export type Approval = { id: string; title: string; summary: string }
export type RunEvent =
| { type: "tool_start"; id: string; name: string; args: string }
| { type: "tool_end"; id: string; ok: boolean; ms: number; output: unknown }
| { type: "approval"; id: string; name: string; args: string; title: string; summary: string }
| { type: "text"; delta: string }
| { type: "usage"; tokens: number }
export type Run = {
status: "running" | "waiting" | "done" | "error"
steps: ToolStep[]
approval: Approval | null
text: string
tokens: number
}
export const emptyRun: Run = { status: "running", steps: [], approval: null, text: "", tokens: 0 }
// Upsert by id: a step that waited for approval becomes the running step with the same id.
const upsert = (steps: ToolStep[], step: ToolStep) =>
steps.some((s) => s.id === step.id) ? steps.map((s) => (s.id === step.id ? step : s)) : [...steps, step]
export function reduce(run: Run, e: RunEvent): Run {
switch (e.type) {
case "tool_start":
return { ...run, steps: upsert(run.steps, { id: e.id, name: e.name, args: e.args, status: "running" }) }
case "tool_end":
return {
...run,
steps: run.steps.map((s) => (s.id === e.id ? { ...s, status: e.ok ? "done" : "error", ms: e.ms, output: e.output } : s)),
}
case "approval":
return {
...run,
status: "waiting",
approval: { id: e.id, title: e.title, summary: e.summary },
steps: upsert(run.steps, { id: e.id, name: e.name, args: e.args, status: "pending" }),
}
case "text":
return { ...run, text: run.text + e.delta }
case "usage":
return { ...run, tokens: e.tokens }
}
}
export async function* readEvents(res: Response): AsyncGenerator<RunEvent> {
const reader = res.body!.getReader()
const decoder = new TextDecoder()
let buf = ""
for (;;) {
const { done, value } = await reader.read()
if (done) break
buf += decoder.decode(value, { stream: true })
const lines = buf.split("\n")
buf = lines.pop() ?? ""
for (const line of lines) if (line.trim()) yield JSON.parse(line) as RunEvent
}
if (buf.trim()) yield JSON.parse(buf) as RunEvent
}
The switch has no default branch on purpose: with strict on, TypeScript reports a missing return if you add an event type and forget to handle it.
A hook with start, approve and stop
The hook owns one AbortController per request and remembers the run id the server returns in a header. Starting a run and answering an approval are the same call with a different body, because both stream the rest of the run back. A stopped run ends as done, a failed request as error, and partial steps stay on screen either way.
"use client"
import * as React from "react"
import { emptyRun, readEvents, reduce, type Run } from "@/lib/agent-run"
export function useAgentRun() {
const [run, setRun] = React.useState<Run | null>(null)
const runId = React.useRef<string | null>(null)
const ctrl = React.useRef<AbortController | null>(null)
const stream = React.useCallback(async (body: Record<string, unknown>) => {
ctrl.current = new AbortController()
setRun((r) => ({ ...(r ?? emptyRun), status: "running", approval: null }))
try {
const res = await fetch("/api/agent", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
signal: ctrl.current.signal,
})
if (!res.ok) throw new Error(`Agent request failed: ${res.status}`)
runId.current = res.headers.get("x-run-id") ?? runId.current
for await (const e of readEvents(res)) setRun((r) => reduce(r ?? emptyRun, e))
// The stream ended: the run is finished unless it paused for an approval.
setRun((r) => (r && r.status === "running" ? { ...r, status: "done" } : r))
} catch {
setRun((r) => (r ? { ...r, status: ctrl.current?.signal.aborted ? "done" : "error" } : r))
}
}, [])
const start = (goal: string) => {
runId.current = null
setRun(emptyRun)
return stream({ goal })
}
const decide = (approvalId: string, approved: boolean) => stream({ runId: runId.current, approvalId, approved })
const stop = () => ctrl.current?.abort()
return { run, start, decide, stop }
}
The page: trace, approval, answer
AgentTrace gets the steps directly; their statuses (pending, running, done, error) match its own. detail holds the arguments and, once the tool returns, its output, which the trace shows in a disclosure. The approval card appears under the trace only while the run is waiting.
"use client"
import * as React from "react"
import { AgentTrace } from "@/components/ui/agent-trace"
import { ApprovalCard } from "@/components/ui/approval-card"
import { AiComposer } from "@/components/ui/ai-composer"
import { TokenUsageMeter } from "@/components/ui/token-usage-meter"
import { useAgentRun } from "@/hooks/use-agent-run"
import type { ToolStep } from "@/lib/agent-run"
const seconds = (ms?: number) => (ms == null ? undefined : `${(ms / 1000).toFixed(1)}s`)
const detail = (s: ToolStep) => (s.output === undefined ? s.args : `${s.args}\n\n${JSON.stringify(s.output, null, 2)}`)
export default function AgentPage() {
const { run, start, decide, stop } = useAgentRun()
const [draft, setDraft] = React.useState("")
return (
<div className="mx-auto grid max-w-3xl gap-4 p-4">
{run ? (
<>
<AgentTrace
className="max-w-none"
meta={`${run.steps.filter((s) => s.status === "done").length}/${run.steps.length} tools`}
steps={run.steps.map((s) => ({ id: s.id, name: s.name, status: s.status, duration: seconds(s.ms), detail: detail(s) }))}
/>
{run.approval ? (
<ApprovalCard
className="max-w-none"
title={run.approval.title}
requester="Your agent"
summary={run.approval.summary}
approveLabel="Run it"
rejectLabel="Skip"
onApprove={() => decide(run.approval!.id, true)}
onReject={() => decide(run.approval!.id, false)}
/>
) : null}
{run.text ? <p className="whitespace-pre-wrap text-sm text-fg">{run.text}</p> : null}
{run.status === "error" ? <p className="text-sm text-danger">The run failed. Try again.</p> : null}
<TokenUsageMeter used={run.tokens} limit={200_000} label="Tokens this run" note="of the per-run budget" />
</>
) : null}
<p aria-live="polite" className="sr-only">
{run?.status === "waiting" ? "The agent is waiting for your approval." : run?.status === "done" ? "The agent finished." : ""}
</p>
<AiComposer
label="Task for the agent"
placeholder="Find unpaid invoices over 30 days and draft reminders"
value={draft}
onChange={setDraft}
streaming={run?.status === "running"}
onStop={stop}
onSubmit={(goal) => {
start(goal)
setDraft("")
}}
/>
</div>
)
}
- Always pass
requestertoApprovalCard; it shows who is asking, and here that is the agent, not a person. - Approval labels should name the action ("Send 12 emails", "Run it") rather than a bare OK. The summary says what will happen and what it touches.
- The
aria-liveline tells screen reader users when the run pauses or finishes without moving their focus. Do not move focus to the approval card automatically; people may be reading the trace. AiComposerturns its send button into a stop button whilestreamingis true and callsonStop, which aborts the request.
Show tool output by kind
A raw JSON dump is fine for debugging and poor for everyone else. Map known tools to a better view and fall back to ToolResultPanel for the rest. A file edit reads best as a diff; a generated document or chart as an ArtifactPreview.
import { InlineCodeDiff } from "@/components/ui/inline-code-diff"
import { ToolResultPanel } from "@/components/ui/tool-result-panel"
import type { ToolStep } from "@/lib/agent-run"
type Edit = { before: string; after: string }
const isEdit = (v: unknown): v is Edit =>
typeof v === "object" && v !== null && typeof (v as Edit).before === "string" && typeof (v as Edit).after === "string"
export function StepOutput({ step }: { step: ToolStep }) {
if (step.name === "edit_file" && isEdit(step.output)) return <InlineCodeDiff before={step.output.before} after={step.output.after} />
const status = step.status === "error" ? "error" : step.status === "done" ? "success" : "running"
return <ToolResultPanel name={step.name} status={status} output={step.output} />
}
For answers built from retrieved documents, put a CitationChip after each sentence it supports, with href set to the source. Agents that cite are easier to check, and the chip is a real link or button, so it is reachable by keyboard.
The server route
The route streams whatever your agent loop emits. runAgent is your code: it calls the model, runs tools and calls send for each event. When a tool needs approval it saves the run state under runId, sends an approval event and returns, which ends the stream. The next request carries the decision; runAgent loads the state and continues from there.
import { runAgent } from "@/lib/agent"
import type { RunEvent } from "@/lib/agent-run"
export async function POST(req: Request) {
const body = await req.json()
const runId: string = body.runId ?? crypto.randomUUID()
const encoder = new TextEncoder()
const stream = new ReadableStream({
async start(controller) {
const send = (e: RunEvent) => controller.enqueue(encoder.encode(JSON.stringify(e) + "\n"))
try {
await runAgent({
runId,
goal: body.goal,
decision: body.approvalId ? { id: String(body.approvalId), approved: body.approved === true } : undefined,
send,
signal: req.signal,
})
} finally {
controller.close()
}
},
})
return new Response(stream, { headers: { "content-type": "application/x-ndjson", "x-run-id": runId } })
}
Treat the approval request as untrusted input. On the server, check that the run belongs to the signed-in user and that approvalId is the step actually waiting, before running the tool. Otherwise anyone who can call the endpoint can approve anything.
Which steps should ask first
| Tool does | Ask first? | Why |
|---|---|---|
| Reads data the user can already see | No | Asking for every read makes people approve on autopilot |
| Writes a draft (not sent, not published) | No | Easy to review and undo afterwards |
| Sends email, messages or notifications | Yes | Cannot be unsent |
| Moves money, changes a plan, refunds | Yes | Financial and often irreversible |
| Deletes or overwrites records or files | Yes | Data loss |
| Runs code or shell commands | Yes, or sandbox it | Arbitrary side effects |
Keep the list short and explicit in your tool definitions, not in a prompt. If approvals pile up, batch them: one card that says "Send 12 reminder emails" with the list in the summary is better than twelve cards.
Finishing touches
- Show the run's cost or tokens with
TokenUsageMeter, or put a short summary inAgentTrace'smeta, for example "4 tools · 3.1s". - Keep finished runs. Persist the event list and replay it through the same reducer to show history; no second renderer needed.
- Collapse long traces: after a run completes, show the final answer first and the trace folded under it.
- Inside a chat, render each tool call with ToolCallCard in the assistant turn instead of a separate trace; the chat guide shows that layout.
- Respect reduced motion. MiniDev's spinners and pulses already do; anything you add should too.
Components used in this guide
Frequently asked questions
What is human-in-the-loop UI for AI agents?
An interface that pauses the agent before a consequential action, such as sending email or issuing a refund, shows what it is about to do and waits for a person to approve or reject it. The agent then continues with that decision.
How do I show AI tool calls in a React UI?
Stream an event when each tool starts and finishes, keep the calls in state by id, and render them as a trace or as cards with name, arguments, status and duration. Put outputs behind a disclosure so the run stays readable.
Do these components work with the Vercel AI SDK, LangGraph or the Claude Agent SDK?
Yes. They are presentational React components with plain props. Map the events or message parts your framework produces to the step shape AgentTrace expects and to ApprovalCard's callbacks.
How do I let users stop an AI agent?
Create an AbortController per request, pass its signal to fetch, and call abort from a stop button. On the server, pass the request's signal into your agent loop so it stops calling the model and tools too.