Component · New
Agent run
A live timeline for multi-step jobs: streaming logs, per-step timers, cancel, and retry from the failed step.
Answer a support ticketReady
0/5 stepsA scripted run. The third step fails on its first attempt so you can try Retry.
Usage
<AgentRun
title="Answer a support ticket"
steps={[
{
id: "crawl",
title: "Crawl the docs site",
async run({ log, signal }) {
const pages = await crawl("/docs", { signal });
log(`Found ${pages.length} pages`);
},
},
{ id: "reply", title: "Draft the reply", run: draftReply },
]}
/>Source
Copy both files into your project. The component has no dependencies beyond React.
"use client";
import { useEffect, useRef, useState } from "react";
import styles from "./agent-run.module.css";
export type AgentStep = {
id: string;
title: string;
/** Do the work. Call log() as you go, throw to fail, and stop when the signal aborts. */
run: (context: { log: (line: string) => void; signal: AbortSignal; attempt: number }) => Promise<void>;
};
type StepStatus = "queued" | "running" | "done" | "failed" | "cancelled";
type StepState = { status: StepStatus; logs: string[]; startedAt: number | null; endedAt: number | null; error?: string };
type RunStatus = "idle" | "running" | "done" | "failed" | "cancelled";
type AgentRunProps = {
title: string;
steps: AgentStep[];
autoStart?: boolean;
};
const queued: StepState = { status: "queued", logs: [], startedAt: null, endedAt: null };
function clock(ms: number) {
return ms < 10_000 ? `${(ms / 1000).toFixed(1)}s` : `${Math.round(ms / 1000)}s`;
}
export function AgentRun({ title, steps, autoStart = false }: AgentRunProps) {
const [state, setState] = useState<Record<string, StepState>>({});
const [status, setStatus] = useState<RunStatus>("idle");
const [openId, setOpenId] = useState<string | null>(null);
const [now, setNow] = useState(0);
const [began, setBegan] = useState<number | null>(null);
const [ended, setEnded] = useState<number | null>(null);
const controller = useRef<AbortController | null>(null);
const attempts = useRef<Record<string, number>>({});
useEffect(() => {
if (status !== "running") return;
const id = window.setInterval(() => setNow(performance.now()), 100);
return () => window.clearInterval(id);
}, [status]);
useEffect(() => {
if (autoStart) runFrom(0, true);
return () => controller.current?.abort();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
async function runFrom(index: number, fresh: boolean) {
controller.current?.abort();
const current = new AbortController();
controller.current = current;
const live = () => controller.current === current;
const t0 = performance.now();
if (fresh) {
attempts.current = {};
setState({});
setBegan(t0);
}
setEnded(null);
setNow(t0);
setStatus("running");
for (let at = index; at < steps.length; at += 1) {
const step = steps[at];
const attempt = (attempts.current[step.id] = (attempts.current[step.id] ?? 0) + 1);
const patch = (change: (step: StepState) => StepState) => {
if (live()) setState((all) => ({ ...all, [step.id]: change(all[step.id] ?? queued) }));
};
patch(() => ({ status: "running", logs: [], startedAt: performance.now(), endedAt: null }));
setOpenId(step.id);
try {
await step.run({
log: (line) => patch((value) => ({ ...value, logs: [...value.logs, line] })),
signal: current.signal,
attempt,
});
if (current.signal.aborted) throw new DOMException("Aborted", "AbortError");
patch((value) => ({ ...value, status: "done", endedAt: performance.now() }));
} catch (error) {
if (!live()) return;
const cancelled = current.signal.aborted;
patch((value) => ({
...value,
status: cancelled ? "cancelled" : "failed",
endedAt: performance.now(),
error: cancelled ? undefined : error instanceof Error ? error.message : "Step failed",
}));
setStatus(cancelled ? "cancelled" : "failed");
setEnded(performance.now());
return;
}
}
if (live()) {
setStatus("done");
setEnded(performance.now());
}
}
const states = steps.map((step) => state[step.id] ?? queued);
const doneCount = states.filter((step) => step.status === "done").length;
const failedAt = states.findIndex((step) => step.status === "failed");
const total = began === null ? 0 : (ended ?? now) - began;
return (
<div className={styles.run} data-status={status}>
<header className={styles.head}>
<div className={styles.heading}>
<strong>{title}</strong>
<span className={styles.pill} data-status={status}>
{status === "idle" ? "Ready" : status === "running" ? "Running" : status === "done" ? "Completed" : status === "failed" ? "Failed" : "Cancelled"}
</span>
</div>
<span className={styles.total}>
{doneCount}/{steps.length} steps{began !== null ? ` · ${clock(Math.max(0, total))}` : ""}
</span>
<div className={styles.controls}>
{status === "running" ? (
<button type="button" onClick={() => controller.current?.abort()}>
Cancel
</button>
) : null}
{status === "failed" ? (
<button type="button" data-primary="true" onClick={() => runFrom(failedAt, false)}>
Retry step
</button>
) : null}
{status !== "running" ? (
<button type="button" data-primary={status === "idle" ? "true" : "false"} onClick={() => runFrom(0, true)}>
{status === "idle" ? "Run" : "Run again"}
</button>
) : null}
</div>
</header>
<div className={styles.track} aria-hidden="true">
<span style={{ transform: `scaleX(${doneCount / steps.length})` }} />
</div>
<ol className={styles.steps}>
{steps.map((step, index) => {
const value = states[index];
const open = openId === step.id && value.status !== "queued";
const took = value.startedAt === null ? null : (value.endedAt ?? now) - value.startedAt;
return (
<li key={step.id} data-status={value.status}>
<button
type="button"
className={styles.step}
aria-expanded={open}
disabled={value.status === "queued"}
onClick={() => setOpenId((id) => (id === step.id ? null : step.id))}
>
<span className={styles.mark} data-status={value.status} aria-hidden="true">
{value.status === "done" ? (
<svg viewBox="0 0 12 12">
<path d="M2.500 6.300 5 8.800 9.500 3.500" />
</svg>
) : null}
{value.status === "failed" ? (
<svg viewBox="0 0 12 12">
<path d="M3.500 3.500l5 5M8.500 3.500l-5 5" />
</svg>
) : null}
{value.status === "cancelled" ? (
<svg viewBox="0 0 12 12">
<path d="M3.500 6h5" />
</svg>
) : null}
</span>
<span className={styles.title}>{step.title}</span>
{(attempts.current[step.id] ?? 0) > 1 ? <span className={styles.attempt}>attempt {attempts.current[step.id]}</span> : null}
<span className={styles.took}>{took === null ? "" : clock(Math.max(0, took))}</span>
</button>
{open ? (
<div className={styles.logs}>
{value.logs.map((line, at) => (
<p key={at}>{line}</p>
))}
{value.status === "running" ? <p className={styles.cursor}>▍</p> : null}
{value.error ? <p className={styles.error}>✕ {value.error}</p> : null}
</div>
) : null}
</li>
);
})}
</ol>
</div>
);
}