Reasoning trace
A vertical step trace for showing what an assistant or automated job is doing. Each step has a type icon, a title, a status (pending, running, done, error or skipped), a live duration and a collapsible card with its input and output as key/value pairs or preformatted text. The rail fills down as steps finish, the running step pulses and its title shimmers. Steps can nest with their own sub-rail, and a header shows the step count, elapsed time and a segmented progress bar whose segments jump to and open their step. Failed steps offer a retry, status is always written as text, completions are announced politely, and motion stops when reduced motion is on.
Source
"use client";
import * as React from "react";
import { CheckCircle2, ChevronRight, FileText, PenLine, RotateCcw, Search, Sparkles, Wrench } from "lucide-react";
import { cn } from "@/lib/utils";
export type TraceKind = "think" | "search" | "tool" | "read" | "write" | "done";
export type TraceStatus = "pending" | "running" | "done" | "error" | "skipped";
export type TracePayload = string | Record<string, unknown>;
export type TraceStep = {
id: string;
kind: TraceKind;
title: string;
status: TraceStatus;
/** Epoch milliseconds. */
startedAt?: number;
endedAt?: number;
input?: TracePayload;
output?: TracePayload;
/** Error text shown on an error step. */
error?: string;
children?: TraceStep[];
};
export type ReasoningTraceProps = {
steps: TraceStep[];
/** Which steps start open. */
defaultExpanded?: "running" | "errors" | "none" | "all";
/** Ticks running durations every second and keeps the running step in view. */
live?: boolean;
onRetry?: (stepId: string) => void;
title?: string;
className?: string;
};
const ICONS: Record<TraceKind, typeof Sparkles> = {
think: Sparkles,
search: Search,
tool: Wrench,
read: FileText,
write: PenLine,
done: CheckCircle2,
};
const STATUS_TEXT: Record<TraceStatus, string> = {
pending: "Pending",
running: "Running",
done: "Done",
error: "Failed",
skipped: "Skipped",
};
const NODE: Record<TraceStatus, string> = {
pending: "border-border bg-card text-muted-foreground",
running: "border-primary bg-primary text-primary-foreground",
done: "border-emerald-600/30 bg-emerald-500/12 text-emerald-700 dark:border-emerald-400/30 dark:text-emerald-300",
error: "border-destructive/40 bg-destructive/10 text-destructive",
skipped: "border-dashed border-border bg-card text-muted-foreground",
};
const SEGMENT: Record<TraceStatus, string> = {
pending: "bg-muted",
running: "bg-primary",
done: "bg-emerald-500 dark:bg-emerald-400",
error: "bg-destructive",
skipped: "bg-muted-foreground/30",
};
const KEYFRAMES = `@keyframes rt-shimmer{from{background-position:150% 0}to{background-position:-50% 0}}
@keyframes rt-pulse{0%{transform:scale(1);opacity:.55}100%{transform:scale(1.9);opacity:0}}`;
export function formatDuration(ms: number) {
if (ms < 1000) return `${Math.max(0, Math.round(ms))}ms`;
const seconds = ms / 1000;
if (seconds < 60) return `${seconds.toFixed(seconds < 10 ? 1 : 0)}s`;
const minutes = Math.floor(seconds / 60);
return `${minutes}m ${String(Math.floor(seconds % 60)).padStart(2, "0")}s`;
}
function flatten(steps: TraceStep[], depth = 0): { step: TraceStep; depth: number }[] {
return steps.flatMap((step) => [{ step, depth }, ...flatten(step.children ?? [], depth + 1)]);
}
function stepDuration(step: TraceStep, now: number) {
if (step.startedAt == null) return null;
const end = step.endedAt ?? (step.status === "running" ? now : null);
return end == null ? null : end - step.startedAt;
}
function useNow(active: boolean) {
const [now, setNow] = React.useState(() => Date.now());
React.useEffect(() => {
if (!active) return;
setNow(Date.now());
const timer = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(timer);
}, [active]);
return now;
}
export function ReasoningTrace({
steps,
defaultExpanded = "running",
live = false,
onRetry,
title = "Run trace",
className,
}: ReasoningTraceProps) {
const uid = React.useId();
const flat = React.useMemo(() => flatten(steps), [steps]);
const hasRunning = flat.some(({ step }) => step.status === "running");
const now = useNow(live && hasRunning);
const [overrides, setOverrides] = React.useState<Record<string, boolean>>({});
const stepRefs = React.useRef(new Map<string, HTMLElement>());
const [announcement, setAnnouncement] = React.useState("");
const previous = React.useRef(new Map<string, TraceStatus>());
const isOpen = (step: TraceStep) => {
if (step.id in overrides) return overrides[step.id];
if (defaultExpanded === "all") return true;
if (defaultExpanded === "errors") return step.status === "error";
if (defaultExpanded === "running") return step.status === "running" || step.status === "error";
return false;
};
const toggle = (step: TraceStep) => setOverrides((current) => ({ ...current, [step.id]: !isOpen(step) }));
// Announce completions and failures politely.
React.useEffect(() => {
const messages: string[] = [];
for (const { step } of flat) {
const before = previous.current.get(step.id);
if (before && before !== step.status) {
const took = stepDuration(step, Date.now());
if (step.status === "done") messages.push(`${step.title} done${took != null ? ` in ${formatDuration(took)}` : ""}.`);
if (step.status === "error") messages.push(`${step.title} failed.`);
}
previous.current.set(step.id, step.status);
}
if (messages.length) setAnnouncement(messages.join(" "));
}, [flat]);
// Keep the running step in view while live.
const runningId = [...flat].reverse().find(({ step }) => step.status === "running")?.step.id;
React.useEffect(() => {
if (!live || !runningId) return;
const node = stepRefs.current.get(runningId);
const reduce = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
node?.scrollIntoView?.({ block: "nearest", behavior: reduce ? "auto" : "smooth" });
}, [live, runningId]);
const counted = flat.length;
const finished = flat.filter(({ step }) => step.status === "done" || step.status === "skipped").length;
const starts = flat.map(({ step }) => step.startedAt).filter((value): value is number => value != null);
const ends = flat.map(({ step }) => step.endedAt ?? (step.status === "running" ? now : undefined)).filter((value): value is number => value != null);
const elapsed = starts.length && ends.length ? Math.max(...ends) - Math.min(...starts) : 0;
const errors = flat.filter(({ step }) => step.status === "error").length;
const jumpTo = (step: TraceStep) => {
setOverrides((current) => ({ ...current, [step.id]: true }));
requestAnimationFrame(() => {
const node = stepRefs.current.get(step.id);
const reduce = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
node?.scrollIntoView?.({ block: "nearest", behavior: reduce ? "auto" : "smooth" });
node?.querySelector<HTMLElement>("[data-step-toggle]")?.focus({ preventScroll: true });
});
};
const renderSteps = (list: TraceStep[], depth: number): React.ReactNode => (
<ol className={cn("relative", depth > 0 && "mt-2")}>
{list.map((step, index) => {
const Icon = ICONS[step.kind];
const open = isOpen(step);
const last = index === list.length - 1;
const took = stepDuration(step, now);
const detailId = `${uid}-${step.id}-detail`;
const hasDetail = step.input != null || step.output != null || step.error != null;
const filled = step.status === "done" || step.status === "skipped" || step.status === "error";
return (
<li
key={step.id}
ref={(node) => {
if (node) stepRefs.current.set(step.id, node);
else stepRefs.current.delete(step.id);
}}
className="relative pb-4 pl-10 last:pb-0"
>
{/* Rail to the next sibling: grey track with a fill that grows down once this step settles. */}
{!last && (
<span aria-hidden="true" className="absolute bottom-0 left-[13px] top-7 w-0.5 overflow-hidden rounded-full bg-border">
<span
className={cn(
"block size-full origin-top motion-safe:transition-transform motion-safe:duration-500 motion-safe:ease-out",
step.status === "error" ? "bg-destructive/60" : "bg-emerald-500/70 dark:bg-emerald-400/70",
)}
style={{ transform: `scaleY(${filled ? 1 : 0})` }}
/>
</span>
)}
{/* Node */}
<span aria-hidden="true" className="absolute left-0 top-0 grid size-7 place-items-center">
{step.status === "running" && (
<span className="absolute inset-0 rounded-full bg-primary/40 motion-safe:[animation:rt-pulse_1.6s_ease-out_infinite]" />
)}
<span className={cn("relative grid size-7 place-items-center rounded-full border", NODE[step.status])}>
<Icon className="size-3.5" strokeWidth={2.25} />
</span>
</span>
<div className="flex min-h-7 flex-wrap items-center gap-x-2 gap-y-1">
<button
type="button"
data-step-toggle
aria-expanded={hasDetail ? open : undefined}
aria-controls={hasDetail ? detailId : undefined}
disabled={!hasDetail}
onClick={() => toggle(step)}
className={cn(
"group -mx-1.5 flex min-w-0 max-w-full items-center gap-1.5 rounded-md px-1.5 py-1 text-left text-sm outline-none",
"focus-visible:ring-2 focus-visible:ring-ring",
hasDetail ? "hover:bg-accent" : "cursor-default",
)}
>
{hasDetail && (
<ChevronRight
aria-hidden="true"
className={cn("size-3.5 shrink-0 text-muted-foreground motion-safe:transition-transform", open && "rotate-90")}
/>
)}
<span
className={cn(
"min-w-0 truncate font-medium",
step.status === "pending" && "text-muted-foreground",
step.status === "skipped" && "text-muted-foreground line-through",
step.status === "error" && "text-destructive",
(step.status === "done" || step.status === "running") && "text-foreground",
step.status === "running" &&
"motion-safe:bg-[linear-gradient(90deg,var(--foreground)_35%,var(--muted-foreground)_50%,var(--foreground)_65%)] motion-safe:bg-[length:250%_100%] motion-safe:bg-clip-text motion-safe:text-transparent motion-safe:[animation:rt-shimmer_1.8s_linear_infinite]",
)}
>
{step.title}
</span>
<span className="sr-only">, {STATUS_TEXT[step.status]}</span>
</button>
<span className="ml-auto flex shrink-0 items-center gap-2">
{step.status === "error" && onRetry && (
<button
type="button"
onClick={() => onRetry(step.id)}
className="inline-flex h-6 items-center gap-1 rounded-md border border-border bg-background px-2 text-xs font-medium text-foreground outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"
>
<RotateCcw aria-hidden="true" className="size-3" />
Retry
<span className="sr-only"> {step.title}</span>
</button>
)}
<span
className={cn(
"text-xs tabular-nums",
step.status === "running" ? "text-foreground" : "text-muted-foreground",
)}
>
{took != null ? formatDuration(took) : step.status === "pending" ? "Queued" : step.status === "skipped" ? "Skipped" : ""}
</span>
</span>
</div>
{hasDetail && (
<div id={detailId} hidden={!open} className="mt-1.5">
<div className="overflow-hidden rounded-lg border border-border bg-muted/40 text-xs">
{step.input != null && <Payload label="Input" value={step.input} />}
{step.output != null && <Payload label="Output" value={step.output} />}
{step.error != null && (
<div className="border-t border-border px-3 py-2 first:border-t-0">
<div className="mb-1 text-[10px] font-medium uppercase tracking-wider text-destructive">Error</div>
<pre className="whitespace-pre-wrap break-words font-mono text-[12px] leading-relaxed text-destructive">{step.error}</pre>
</div>
)}
</div>
</div>
)}
{step.children?.length ? <div className="relative mt-1 border-l border-dashed border-border pl-4">{renderSteps(step.children, depth + 1)}</div> : null}
</li>
);
})}
</ol>
);
return (
<section aria-label={title} className={cn("min-w-0 rounded-xl border border-border bg-card text-card-foreground", className)}>
<style href="chm-reasoning-trace" precedence="default">{KEYFRAMES}</style>
<header className="border-b border-border px-4 py-3 sm:px-5">
<div className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1">
<h3 className="text-sm font-semibold text-foreground">{title}</h3>
<p className="text-xs tabular-nums text-muted-foreground">
{counted} steps · {formatDuration(elapsed)}
{errors > 0 && <span className="text-destructive"> · {errors} failed</span>}
<span className="sr-only">, {finished} finished</span>
</p>
</div>
<div role="group" aria-label="Jump to step" className="mt-2.5 flex gap-1">
{flat.map(({ step, depth }, index) => (
<button
key={step.id}
type="button"
aria-label={`Step ${index + 1}: ${step.title}, ${STATUS_TEXT[step.status]}`}
title={step.title}
onClick={() => jumpTo(step)}
className={cn(
"relative h-1.5 min-w-0 flex-1 rounded-full outline-none motion-safe:transition-colors",
"before:absolute before:-inset-y-2 before:inset-x-0 hover:opacity-80 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-card",
SEGMENT[step.status],
depth > 0 && "scale-y-[0.66]",
step.status === "running" && "motion-safe:animate-pulse",
)}
/>
))}
</div>
</header>
<div className="px-4 py-4 sm:px-5">{renderSteps(steps, 0)}</div>
<div aria-live="polite" className="sr-only">
{announcement}
</div>
</section>
);
}
function Payload({ label, value }: { label: string; value: TracePayload }) {
return (
<div className="border-t border-border px-3 py-2 first:border-t-0">
<div className="mb-1 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">{label}</div>
{typeof value === "string" ? (
<pre className="max-h-48 overflow-auto whitespace-pre-wrap break-words font-mono text-[12px] leading-relaxed text-foreground">{value}</pre>
) : (
<dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-0.5 font-mono text-[12px] leading-relaxed">
{Object.entries(value).map(([key, item]) => (
<React.Fragment key={key}>
<dt className="text-muted-foreground">{key}</dt>
<dd className="min-w-0 break-words text-foreground">{typeof item === "string" ? item : JSON.stringify(item)}</dd>
</React.Fragment>
))}
</dl>
)}
</div>
);
}
