Agent Run
A running agent in one card. Its steps, the tools each one calls, the reasoning behind them, and the answer it lands on.
Installation
Copy and paste the following code into your project.
1'use client';23import { motion, useReducedMotion } from 'motion/react';4import * as React from 'react';5import { Context } from '../ai/context';6import { Reasoning } from '../ai/reasoning';7import { Response } from '../ai/response';8import { Task, type TaskStatus } from '../ai/task';9import { Tool, type ToolStatus } from '../ai/tool';10import { cn } from '../lib/cn';1112type IconProps = React.SVGProps<SVGSVGElement> & {13 size?: number | string;14};1516function CheckIcon({ size = 24, strokeWidth = 1.5, ...props }: IconProps) {17 return (18 <svg19 xmlns="http://www.w3.org/2000/svg"20 width={size}21 height={size}22 viewBox="0 0 24 24"23 fill="none"24 stroke="currentColor"25 strokeWidth={strokeWidth}26 strokeLinecap="round"27 strokeLinejoin="round"28 aria-hidden="true"29 {...props}30 >31 <path d="M20 6 9 17l-5-5" />32 </svg>33 );34}3536function LoaderIcon({ size = 24, strokeWidth = 1.5, ...props }: IconProps) {37 return (38 <svg39 xmlns="http://www.w3.org/2000/svg"40 width={size}41 height={size}42 viewBox="0 0 24 24"43 fill="none"44 stroke="currentColor"45 strokeWidth={strokeWidth}46 strokeLinecap="round"47 strokeLinejoin="round"48 aria-hidden="true"49 {...props}50 >51 <path d="M12 3a9 9 0 1 0 9 9" />52 </svg>53 );54}5556function AlertIcon({ size = 24, strokeWidth = 1.5, ...props }: IconProps) {57 return (58 <svg59 xmlns="http://www.w3.org/2000/svg"60 width={size}61 height={size}62 viewBox="0 0 24 24"63 fill="none"64 stroke="currentColor"65 strokeWidth={strokeWidth}66 strokeLinecap="round"67 strokeLinejoin="round"68 aria-hidden="true"69 {...props}70 >71 <circle cx="12" cy="12" r="9" />72 <path d="M12 8v4" />73 <path d="M12 16h.01" />74 </svg>75 );76}7778function DotIcon({ size = 24, ...props }: IconProps) {79 return (80 <svg81 xmlns="http://www.w3.org/2000/svg"82 width={size}83 height={size}84 viewBox="0 0 24 24"85 fill="currentColor"86 aria-hidden="true"87 {...props}88 >89 <circle cx="12" cy="12" r="4" />90 </svg>91 );92}9394const SPIN_ANIMATE = { rotate: 360 };95const SPIN_TRANSITION = { repeat: Infinity, duration: 1, ease: 'linear' } as const;96const BAR_TRANSITION = { type: 'spring', stiffness: 220, damping: 30 } as const;9798type AgentRunStatus = 'idle' | 'running' | 'complete' | 'error';99100interface AgentTool {101 id: string;102 name: string;103 status: ToolStatus;104 description?: string;105 input?: unknown;106 output?: unknown;107 error?: boolean;108}109110interface AgentStep {111 id: string;112 title: string;113 status: TaskStatus;114 detail?: string;115 reasoning?: string;116 tools?: AgentTool[];117 files?: string[];118}119120interface AgentRunLabels {121 idle: string;122 running: string;123 complete: string;124 error: string;125 input: string;126 output: string;127 progress: (done: number, total: number) => string;128}129130const DEFAULT_LABELS: AgentRunLabels = {131 idle: 'Waiting',132 running: 'Running',133 complete: 'Done',134 error: 'Failed',135 input: 'Input',136 output: 'Output',137 progress: (done, total) => `${done} of ${total} steps`,138};139140const STATUS_ICON: Record<AgentRunStatus, React.ComponentType<IconProps>> = {141 idle: DotIcon,142 running: LoaderIcon,143 complete: CheckIcon,144 error: AlertIcon,145};146147const STATUS_TONE: Record<AgentRunStatus, string> = {148 idle: 'text-muted-foreground border-border',149 running: 'text-foreground border-border',150 complete: 'text-success-text border-success-border',151 error: 'text-destructive-text border-destructive-border',152};153154interface AgentRunContextValue {155 title?: string;156 status: AgentRunStatus;157 steps: AgentStep[];158 answer?: React.ReactNode;159 usage?: { used: number; max: number };160 startedAt?: Date | number;161 finishedAt?: Date | number;162 labels: AgentRunLabels;163 defaultOpen?: boolean;164}165166const AgentRunContext = React.createContext<AgentRunContextValue | null>(null);167168const useAgentRun = (): AgentRunContextValue => {169 const context = React.use(AgentRunContext);170 if (!context) {171 throw new Error('AgentRun components must be used within AgentRun');172 }173 return context;174};175176function agentRunProgress(steps: AgentStep[]): { done: number; total: number; ratio: number } {177 const total = steps.length;178 const done = steps.filter((step) => step.status === 'complete').length;179 return { done, total, ratio: total === 0 ? 0 : done / total };180}181182function toMillis(value: Date | number): number {183 return value instanceof Date ? value.getTime() : value;184}185186function formatElapsed(ms: number): string {187 const seconds = Math.max(0, Math.floor(ms / 1000));188 if (seconds < 60) return `${seconds}s`;189 const minutes = Math.floor(seconds / 60);190 const rest = seconds % 60;191 return `${minutes}m ${rest.toString().padStart(2, '0')}s`;192}193194function useElapsed(195 startedAt: Date | number | undefined,196 finishedAt: Date | number | undefined,197 live: boolean,198): string | null {199 const [now, setNow] = React.useState<number | null>(null);200201 React.useEffect(() => {202 if (!live || startedAt === undefined || finishedAt !== undefined) return;203 const tick = () => setNow(Date.now());204 const first = setTimeout(tick, 0);205 const interval = setInterval(tick, 1000);206 return () => {207 clearTimeout(first);208 clearInterval(interval);209 };210 }, [live, startedAt, finishedAt]);211212 if (startedAt === undefined) return null;213 const start = toMillis(startedAt);214 const end =215 finishedAt !== undefined216 ? toMillis(finishedAt)217 : live && now !== null218 ? Math.max(now, start)219 : start;220 return formatElapsed(end - start);221}222223function useAutoOpen(224 status: string,225 initialOpen: boolean,226 shouldOpen: (status: string) => boolean,227 enabled: boolean,228) {229 const [open, setOpen] = React.useState(initialOpen);230 const [seenStatus, setSeenStatus] = React.useState(status);231232 if (seenStatus !== status) {233 setSeenStatus(status);234 if (enabled && shouldOpen(status) && !open) setOpen(true);235 }236237 return [open, setOpen] as const;238}239240const opensStep = (status: string) => status === 'active' || status === 'error';241const opensTool = (status: string) => status === 'error';242243interface AgentRunProps extends React.HTMLAttributes<HTMLDivElement> {244 title?: string;245 status?: AgentRunStatus;246 steps: AgentStep[];247 answer?: React.ReactNode;248 usage?: { used: number; max: number };249 startedAt?: Date | number;250 finishedAt?: Date | number;251 labels?: Partial<AgentRunLabels>;252 defaultOpen?: boolean;253}254255type AgentRunHeaderProps = React.HTMLAttributes<HTMLDivElement>;256type AgentRunStepsProps = React.HTMLAttributes<HTMLDivElement>;257type AgentRunProgressProps = React.HTMLAttributes<HTMLDivElement>;258type AgentRunAnswerProps = React.HTMLAttributes<HTMLDivElement>;259type AgentRunFooterProps = React.HTMLAttributes<HTMLDivElement>;260261const AgentRunRoot = ({262 className,263 title,264 status = 'idle',265 steps,266 answer,267 usage,268 startedAt,269 finishedAt,270 labels,271 defaultOpen,272 children,273 ref,274 ...props275}: AgentRunProps & { ref?: React.Ref<HTMLDivElement> }) => {276 const mergedLabels = React.useMemo<AgentRunLabels>(277 () => ({ ...DEFAULT_LABELS, ...labels }),278 [labels],279 );280281 const value = React.useMemo<AgentRunContextValue>(282 () => ({283 title,284 status,285 steps,286 answer,287 usage,288 startedAt,289 finishedAt,290 labels: mergedLabels,291 defaultOpen,292 }),293 [title, status, steps, answer, usage, startedAt, finishedAt, mergedLabels, defaultOpen],294 );295296 return (297 <AgentRunContext value={value}>298 <div299 ref={ref}300 data-status={status}301 className={cn(302 'border-border bg-card text-card-foreground divide-rule flex w-full flex-col divide-y overflow-hidden rounded-lg border',303 className,304 )}305 {...props}306 >307 {children ?? (308 <>309 <AgentRunHeader />310 <AgentRunProgress />311 <AgentRunSteps />312 <AgentRunAnswer />313 <AgentRunFooter />314 </>315 )}316 </div>317 </AgentRunContext>318 );319};320321AgentRunRoot.displayName = 'AgentRun';322323const AgentRunHeader = ({324 className,325 children,326 ref,327 ...props328}: AgentRunHeaderProps & { ref?: React.Ref<HTMLDivElement> }) => {329 const { title, status, startedAt, finishedAt, labels } = useAgentRun();330 const shouldReduceMotion = useReducedMotion();331 const StatusIcon = STATUS_ICON[status];332 const elapsed = useElapsed(startedAt, finishedAt, status === 'running');333334 return (335 <div ref={ref} className={cn('flex items-center gap-3 px-4 py-3', className)} {...props}>336 <span className="text-foreground min-w-0 flex-1 truncate text-sm font-medium">337 {children ?? title}338 </span>339 {elapsed ? (340 <span className="text-muted-foreground shrink-0 font-mono text-xs tabular-nums">341 {elapsed}342 </span>343 ) : null}344 <span345 role="status"346 aria-atomic="true"347 data-status={status}348 className={cn(349 'inline-flex shrink-0 items-center gap-1.5 rounded-full border px-2 py-0.5 font-mono text-[11px]',350 STATUS_TONE[status],351 )}352 >353 {status === 'running' && !shouldReduceMotion ? (354 <motion.span className="flex" animate={SPIN_ANIMATE} transition={SPIN_TRANSITION}>355 <StatusIcon size={12} />356 </motion.span>357 ) : (358 <span className="flex">359 <StatusIcon size={12} />360 </span>361 )}362 {labels[status]}363 </span>364 </div>365 );366};367368AgentRunHeader.displayName = 'AgentRunHeader';369370const AgentRunProgress = ({371 className,372 ref,373 ...props374}: AgentRunProgressProps & { ref?: React.Ref<HTMLDivElement> }) => {375 const { steps, labels } = useAgentRun();376 const shouldReduceMotion = useReducedMotion();377 const { done, total, ratio } = agentRunProgress(steps);378379 return (380 <div381 ref={ref}382 role="progressbar"383 aria-valuemin={0}384 aria-valuemax={total}385 aria-valuenow={done}386 aria-label={labels.progress(done, total)}387 className={cn('bg-secondary relative h-1 w-full', className)}388 {...props}389 >390 <motion.div391 className="bg-foreground absolute inset-y-0 start-0"392 initial={false}393 animate={{ width: `${ratio * 100}%` }}394 transition={shouldReduceMotion ? { duration: 0 } : BAR_TRANSITION}395 />396 </div>397 );398};399400AgentRunProgress.displayName = 'AgentRunProgress';401402function StepTool({ tool, labels }: { tool: AgentTool; labels: AgentRunLabels }) {403 const [open, setOpen] = useAutoOpen(tool.status, opensTool(tool.status), opensTool, true);404405 return (406 <Tool status={tool.status} open={open} onOpenChange={setOpen}>407 <Tool.Header name={tool.name} description={tool.description} />408 <Tool.Content>409 {tool.input !== undefined ? <Tool.Input label={labels.input} value={tool.input} /> : null}410 {tool.output !== undefined ? (411 <Tool.Output label={labels.output} value={tool.output} error={tool.error} />412 ) : null}413 </Tool.Content>414 </Tool>415 );416}417418function StepTools({ tools, labels }: { tools: AgentTool[]; labels: AgentRunLabels }) {419 return (420 <div className="flex flex-col gap-2">421 {tools.map((tool) => (422 <StepTool key={tool.id} tool={tool} labels={labels} />423 ))}424 </div>425 );426}427428function AgentRunStep({429 step,430 labels,431 defaultOpen,432}: {433 step: AgentStep;434 labels: AgentRunLabels;435 defaultOpen: boolean | undefined;436}) {437 const [open, setOpen] = useAutoOpen(438 step.status,439 defaultOpen ?? opensStep(step.status),440 opensStep,441 defaultOpen === undefined,442 );443444 return (445 <Task open={open} onOpenChange={setOpen}>446 <Task.Trigger title={step.title} status={step.status} />447 <Task.Content>448 {step.detail ? <Task.Item>{step.detail}</Task.Item> : null}449 {step.files?.length ? (450 <Task.Item>451 {step.files.map((file) => (452 <Task.File key={file}>{file}</Task.File>453 ))}454 </Task.Item>455 ) : null}456 {step.reasoning ? (457 <Reasoning isStreaming={step.status === 'active'} defaultOpen={false}>458 <Reasoning.Trigger />459 <Reasoning.Content>{step.reasoning}</Reasoning.Content>460 </Reasoning>461 ) : null}462 {step.tools?.length ? <StepTools tools={step.tools} labels={labels} /> : null}463 </Task.Content>464 </Task>465 );466}467468const AgentRunSteps = ({469 className,470 ref,471 ...props472}: AgentRunStepsProps & { ref?: React.Ref<HTMLDivElement> }) => {473 const { steps, labels, defaultOpen } = useAgentRun();474475 return (476 <div ref={ref} className={cn('flex flex-col gap-3 px-4 py-3', className)} {...props}>477 {steps.map((step) => (478 <AgentRunStep key={step.id} step={step} labels={labels} defaultOpen={defaultOpen} />479 ))}480 </div>481 );482};483484AgentRunSteps.displayName = 'AgentRunSteps';485486const AgentRunAnswer = ({487 className,488 children,489 ref,490 ...props491}: AgentRunAnswerProps & { ref?: React.Ref<HTMLDivElement> }) => {492 const { status, answer } = useAgentRun();493 const body = children ?? answer;494495 if (status === 'running' && body === undefined) {496 return (497 <div ref={ref} className={cn('px-4 py-3', className)} {...props}>498 <Response.Skeleton />499 </div>500 );501 }502503 if (body === undefined || body === null) return null;504505 return (506 <div ref={ref} className={cn('px-4 py-3', className)} {...props}>507 <Response isStreaming={status === 'running'}>{body}</Response>508 </div>509 );510};511512AgentRunAnswer.displayName = 'AgentRunAnswer';513514const AgentRunFooter = ({515 className,516 children,517 ref,518 ...props519}: AgentRunFooterProps & { ref?: React.Ref<HTMLDivElement> }) => {520 const { usage, steps, labels } = useAgentRun();521 const { done, total } = agentRunProgress(steps);522523 if (!usage && !children) return null;524525 return (526 <div527 ref={ref}528 className={cn('flex items-center justify-between gap-3 px-4 py-2', className)}529 {...props}530 >531 <span className="text-muted-foreground font-mono text-xs tabular-nums">532 {labels.progress(done, total)}533 </span>534 {children ??535 (usage ? (536 <Context maxTokens={usage.max} usedTokens={usage.used}>537 <Context.Trigger />538 <Context.Content align="end">539 <Context.Header />540 </Context.Content>541 </Context>542 ) : null)}543 </div>544 );545};546547AgentRunFooter.displayName = 'AgentRunFooter';548549const AgentRun = Object.assign(AgentRunRoot, {550 Header: AgentRunHeader,551 Progress: AgentRunProgress,552 Steps: AgentRunSteps,553 Answer: AgentRunAnswer,554 Footer: AgentRunFooter,555});556557export { AgentRun, agentRunProgress, useAgentRun };558export type {559 AgentRunAnswerProps,560 AgentRunFooterProps,561 AgentRunHeaderProps,562 AgentRunLabels,563 AgentRunProgressProps,564 AgentRunProps,565 AgentRunStatus,566 AgentRunStepsProps,567 AgentStep,568 AgentTool,569};
Update the import paths to match your project structure.
Anatomy
1import { AgentRun, type AgentStep } from '@/hybrids/agent-run';
1<AgentRun2 title="Refactoring the auth module"3 status="running"4 steps={steps}5 startedAt={startedAt}6 usage={{ used: 38400, max: 200000 }}7 answer={<p>The session and token stores now share one interface.</p>}8/>
Hand it the run as data and it lays the whole thing out: a header with the status and the elapsed time, a progress bar, one
Task per step, the answer as a Response, and the token usage as a Context meter in the footer. Pass children instead to pick and order the parts yourself.Composition
AgentRun is a hybrid: it is made of elements you already have, wired in order. Open the file and you will find them in this shape:AgentRunโโโ AgentRun.Headerโโโ AgentRun.Progressโโโ AgentRun.Stepsโ โโโ Task (one per step)โ โโโ Task.Triggerโ โโโ Task.Contentโ โโโ Task.Itemโ โโโ Task.Fileโ โโโ Reasoningโ โโโ Toolโ โโโ Tool.Headerโ โโโ Tool.Inputโ โโโ Tool.Outputโโโ AgentRun.Answerโ โโโ Responseโโโ AgentRun.Footerโโโ Context
Step shape
Each entry in
steps is an AgentStep. Only id, title and status are required; the rest shows up when present.| Field | Type | Description |
|---|---|---|
id | string | Stable key |
title | string | Label of the step |
status | 'pending' | 'active' | 'complete' | 'error' | Drives the Task icon and which step opens |
detail | string | One line under the title |
files | string[] | Rendered as Task.File chips |
reasoning | string | Rendered in a Reasoning panel, closed |
tools | AgentTool[] | Rendered as Tool cards with input and output |
An
AgentTool is { id, name, status, description?, input?, output?, error? }, with status being the Tool element's own ToolStatus. A tool that failed opens by default so the error is not hidden behind a click.Live
The active step opens on its own and finished ones fold, the bar advances with every completed step, the answer streams with a caret once it starts, and the elapsed time stops when the run does.
Adding a composer to the docsWaiting
1'use client';23import { useEffect, useRef, useState } from 'react';4import { AgentRun, type AgentRunStatus, type AgentStep } from '@/hybrids/agent-run';56const PLAN: AgentStep[] = [7 { id: 'read', title: 'Read the docs page', status: 'pending', detail: 'Fetching llms.txt' },8 {9 id: 'find',10 title: 'Find the component',11 status: 'pending',12 reasoning: 'The request mentions a composer with attachments, which matches prompt-input.',13 tools: [14 {15 id: 'search',16 name: 'search_registry',17 status: 'complete',18 input: { query: 'composer attachments' },19 output: { slug: 'ai/prompt-input', score: 0.93 },20 },21 ],22 },23 {24 id: 'install',25 title: 'Install it',26 status: 'pending',27 files: ['prompt-input.tsx', 'attachments.tsx'],28 },29 { id: 'verify', title: 'Type check', status: 'pending', detail: 'tsc --noEmit' },30];3132const ANSWER =33 'Installed prompt-input and attachments into components/ui. The type check passes and the demo is on the page.';3435const STEP_MS = 1400;36const CHAR_MS = 18;3738export function Live() {39 const [status, setStatus] = useState<AgentRunStatus>('idle');40 const [steps, setSteps] = useState<AgentStep[]>(PLAN);41 const [answer, setAnswer] = useState('');42 const [startedAt, setStartedAt] = useState<number | undefined>();43 const [finishedAt, setFinishedAt] = useState<number | undefined>();44 const timers = useRef<number[]>([]);4546 const clear = () => {47 timers.current.forEach((timer) => window.clearTimeout(timer));48 timers.current = [];49 };5051 useEffect(() => clear, []);5253 const start = () => {54 clear();55 setStatus('running');56 setSteps(PLAN.map((step, index) => ({ ...step, status: index === 0 ? 'active' : 'pending' })));57 setAnswer('');58 setStartedAt(Date.now());59 setFinishedAt(undefined);6061 PLAN.forEach((_, index) => {62 timers.current.push(63 window.setTimeout(64 () => {65 setSteps((current) =>66 current.map((step, position) => {67 if (position <= index) return { ...step, status: 'complete' };68 if (position === index + 1) return { ...step, status: 'active' };69 return step;70 }),71 );72 },73 STEP_MS * (index + 1),74 ),75 );76 });7778 const answerStart = STEP_MS * (PLAN.length + 1);79 for (let index = 1; index <= ANSWER.length; index += 1) {80 timers.current.push(81 window.setTimeout(() => setAnswer(ANSWER.slice(0, index)), answerStart + CHAR_MS * index),82 );83 }84 timers.current.push(85 window.setTimeout(86 () => {87 setStatus('complete');88 setFinishedAt(Date.now());89 },90 answerStart + CHAR_MS * ANSWER.length + 200,91 ),92 );93 };9495 return (96 <div className="flex w-full max-w-xl flex-col gap-4">97 <button98 type="button"99 onClick={start}100 disabled={status === 'running'}101 className="bg-card hover:bg-muted w-fit rounded-full px-3 py-1.5 text-xs shadow-sm transition-colors disabled:opacity-40"102 >103 {status === 'running' ? 'Running' : status === 'complete' ? 'Run again' : 'Start the run'}104 </button>105 <AgentRun106 title="Adding a composer to the docs"107 status={status}108 steps={steps}109 startedAt={startedAt}110 finishedAt={finishedAt}111 answer={answer ? <p>{answer}</p> : undefined}112 />113 </div>114 );115}
API Reference
AgentRun
| Prop | Type | Default | Description |
|---|---|---|---|
steps | AgentStep[] | - | The run, one entry per step |
status | 'idle' | 'running' | 'complete' | 'error' | 'idle' | State of the whole run |
title | string | - | Printed in the header |
answer | ReactNode | - | The final response, rendered inside Response |
usage | { used: number; max: number } | - | Token usage for the footer meter |
startedAt | Date | number | - | Start of the elapsed clock |
finishedAt | Date | number | - | Stops the clock |
labels | Partial<AgentRunLabels> | English | Status names, input and output labels, progress text |
defaultOpen | boolean | - | Forces every step open or closed |
children | ReactNode | - | Replaces the default layout with your own parts |
className | string | - | Additional CSS classes |
AgentRun.Header
| Prop | Type | Default | Description |
|---|---|---|---|
children | ReactNode | - | Replaces the title |
className | string | - | Additional CSS classes |
AgentRun.Progress
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | - | Additional CSS classes |
AgentRun.Steps
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | - | Additional CSS classes |
AgentRun.Answer
| Prop | Type | Default | Description |
|---|---|---|---|
children | ReactNode | - | Replaces the answer prop |
className | string | - | Additional CSS classes |
AgentRun.Footer
| Prop | Type | Default | Description |
|---|---|---|---|
children | ReactNode | - | Replaces the usage meter on the right |
className | string | - | Additional CSS classes |
Helpers
agentRunProgress(steps) returns { done, total, ratio }, the same numbers the bar and the footer print. useAgentRun() reads the run from context inside custom parts.Found something to improve?
Notice a bug, typo, or missing detail on this page? Help us make the documentation better by opening a GitHub issue.