Skip to content

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 , 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.

Loading the live Agent Trace…
Agent TraceAgentTrace: each step reports its status and time; details fold out.Docs

The components and what each one does

ComponentJob in an agent UIKey props
AgentTraceThe whole run as a timeline of stepssteps (id, name, status, duration, detail), title, meta
ApprovalCardHuman-in-the-loop decision before a tool runstitle, requester, summary, onApprove, onReject, labels
ToolCallCardOne tool call inside a chat turnname, args, status, duration, children
ToolResultPanelA tool's output as formatted JSONname, status, output
InlineCodeDiffA single edit the agent madebefore, after
ArtifactPreviewSomething the agent produced, framed with copy and expandtitle, copyValue, onExpand
CitationChipAn inline source for a claim in the answerindex, href
AiComposerThe task input; its send button becomes stop while runningvalue, onSubmit, streaming, onStop
TokenUsageMeterTokens used against a budgetused, limit, label, note
bash
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.

lib/agent-run.tsts
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.

hooks/use-agent-run.tsts
"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.

app/agent/page.tsxtsx
"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 requester to ApprovalCard; 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-live line 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.
  • AiComposer turns its send button into a stop button while streaming is true and calls onStop, which aborts the request.
Approval CarduiReact request card for approval workflows showing the requester avatar, title and summary, with Reject and Approve buttons wired to your callbacks.npx shadcn@latest add @minidev/approval-card

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.

components/agent/step-output.tsxtsx
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.

app/api/agent/route.tsts
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 doesAsk first?Why
Reads data the user can already seeNoAsking for every read makes people approve on autopilot
Writes a draft (not sent, not published)NoEasy to review and undo afterwards
Sends email, messages or notificationsYesCannot be unsent
Moves money, changes a plan, refundsYesFinancial and often irreversible
Deletes or overwrites records or filesYesData loss
Runs code or shell commandsYes, or sandbox itArbitrary 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 in AgentTrace's meta, 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

Agent TraceuiReact timeline of an AI agent run: each tool step shows pending, running, done or error, reports its duration and folds out details. The header sums up the run.npx shadcn@latest add @minidev/agent-traceApproval CarduiReact request card for approval workflows showing the requester avatar, title and summary, with Reject and Approve buttons wired to your callbacks.npx shadcn@latest add @minidev/approval-cardTool Call CarduiAgent tool call card showing the tool name, argument preview, duration and a running, done or failed status chip, with collapsible monospace output below.npx shadcn@latest add @minidev/tool-call-cardTool Result PaneluiTool result panel with the tool name, a success, error or running status badge and the output shown in a JSON code block. Built in React for AI agent UIs.npx shadcn@latest add @minidev/tool-result-panelAi ComposeruiChat input for AI apps with a multiline textarea, Enter to send, suggestion chips, attach button, model picker and a stop button while a response streams.npx shadcn@latest add @minidev/ai-composerToken Usage MeteruiLLM token usage meter showing tokens used against a monthly limit, a labelled progress bar and a percent of budget note with the reset date. Useful in AI apps.npx shadcn@latest add @minidev/token-usage-meterInline Code DiffuiA two line code diff showing the removed line in red with a minus and the added line in green with a plus, in monospace. Suits AI edit suggestions.npx shadcn@latest add @minidev/inline-code-diffArtifact PreviewuiFramed preview for AI generated artifacts such as code, documents or UI, with a title bar, copy button and optional expand action for a full view.npx shadcn@latest add @minidev/artifact-preview

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.

More guides