Skip to content
Molecules

Agent plan

An agent's steps as they run.

Installation

  1. Run the CLI

    Run pnpm dlx asta-ui@latest init once, then this. The file lands in components/astabyte/ and the colour tokens go into your CSS.

    $ pnpm dlx asta-ui@latest add agent-plan

    Or with the shadcn CLI: pnpm dlx shadcn@latest add https://ui.astabyte.com/r/agent-plan.json

  2. Or install the package

    Don’t want the file? Import from asta-ui/agent-plan and update with pnpm update asta-ui. Add the stylesheet once. More.

    $ pnpm add asta-ui
    import { AgentPlan } from "asta-ui/agent-plan";
  3. Or copy it by hand

    Copy this file. Keep the paths, or fix the @/ imports. Then add the tokens from globals.css.

    "use client";
    
    import { useEffect, useRef, useState, type ReactNode, type RefObject } from "react";
    
    const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
    const CURVE = "cubic-bezier(.16,1,.3,1)";
    
    const KEYFRAMES = `@keyframes asta-plan-spin { to { transform: rotate(360deg) } }
    @keyframes asta-plan-pop { from { opacity: 0; transform: scale(.6) } }
    @keyframes asta-plan-draw { from { stroke-dashoffset: 1 } }
    @keyframes asta-plan-in { from { opacity: 0; transform: translateY(4px) } }
    @media (prefers-reduced-motion: reduce) { .asta-plan-a, .asta-plan-a * { animation: none !important; transition-duration: 0s !important } }`;
    
    export type PlanStepStatus = "pending" | "running" | "done" | "skipped" | "failed";
    
    export interface PlanStep {
      id: string;
      title: string;
      status: PlanStepStatus;
      /** The live log line while running, or a short result or reason once settled. */
      detail?: string;
      /** When the step started (epoch ms). A running step counts up from here. */
      startedAt?: number;
      /** How long it took in ms, once settled. */
      duration?: number;
      /** Smaller steps inside this one. They show when the row is open. */
      substeps?: PlanStep[];
    }
    
    export interface AgentPlanProps {
      /** What the agent is doing, e.g. "Migrate billing to usage-based plans". */
      title: string;
      steps: PlanStep[];
      /** Something on the right of the header, e.g. a Stop button. */
      action?: ReactNode;
      /** Shown under the list, e.g. Retry after a failure. */
      footer?: ReactNode;
      className?: string;
    }
    
    /** 4200 → "4.2s", 75000 → "1m 15s". */
    export const formatStepTime = (ms: number) => {
      const s = Math.max(0, ms) / 1000;
      if (s < 10) return `${s.toFixed(1)}s`;
      if (s < 60) return `${Math.floor(s)}s`;
      return `${Math.floor(s / 60)}m ${String(Math.floor(s % 60)).padStart(2, "0")}s`;
    };
    
    const settled = (s: PlanStepStatus) => s === "done" || s === "skipped" || s === "failed";
    
    /** Current time while something runs, ticking four times a second. Rests offscreen and in hidden tabs. */
    function useNow(on: boolean, el: RefObject<HTMLElement | null>) {
      const [now, setNow] = useState(0);
      useEffect(() => {
        if (!on) return;
        const node = el.current;
        let seen = true;
        let timer: ReturnType<typeof setInterval> | undefined;
        const tick = () => setNow(Date.now());
        const sync = () => {
          clearInterval(timer);
          timer = undefined;
          if (seen && !document.hidden) {
            tick();
            timer = setInterval(tick, 250);
          }
        };
        const io = node
          ? new IntersectionObserver(([e]) => {
              seen = e.isIntersecting;
              sync();
            })
          : null;
        if (node) io?.observe(node);
        document.addEventListener("visibilitychange", sync);
        sync();
        return () => {
          clearInterval(timer);
          io?.disconnect();
          document.removeEventListener("visibilitychange", sync);
        };
      }, [on, el]);
      return now;
    }
    
    function StatusIcon({ status, small }: { status: PlanStepStatus; small?: boolean }) {
      const box = small ? "h-3.5 w-3.5" : "h-[18px] w-[18px]";
      if (status === "running")
        return (
          <svg viewBox="0 0 18 18" className={cx(box, "asta-plan-a shrink-0 animate-[asta-plan-spin_.8s_linear_infinite] text-brand")} fill="none" aria-hidden>
            <circle cx="9" cy="9" r="7" stroke="currentColor" strokeOpacity=".2" strokeWidth="2" />
            <path d="M16 9a7 7 0 0 0-7-7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
          </svg>
        );
      if (status === "done")
        return (
          <span className={cx(box, "asta-plan-a grid shrink-0 place-items-center rounded-full bg-brand text-on-brand animate-[asta-plan-pop_.35s_cubic-bezier(.16,1,.3,1)_both]")} aria-hidden>
            <svg viewBox="0 0 24 24" className="h-[70%] w-[70%]" fill="none" stroke="currentColor" strokeWidth="3.3" strokeLinecap="round" strokeLinejoin="round">
              <path d="m5 12.5 4.5 4.5L19 7.5" pathLength={1} strokeDasharray={1} className="asta-plan-a animate-[asta-plan-draw_.45s_cubic-bezier(.16,1,.3,1)_.1s_both]" />
            </svg>
          </span>
        );
      if (status === "failed")
        return (
          <span className={cx(box, "asta-plan-a grid shrink-0 place-items-center rounded-full bg-ink text-paper animate-[asta-plan-pop_.35s_cubic-bezier(.16,1,.3,1)_both]")} aria-hidden>
            <svg viewBox="0 0 24 24" className="h-[70%] w-[70%]" fill="none" stroke="currentColor" strokeWidth="3.3" strokeLinecap="round">
              <path d="M12 7.5v5" />
              <path d="M12 16h.01" />
            </svg>
          </span>
        );
      if (status === "skipped")
        return (
          <span className={cx(box, "grid shrink-0 place-items-center rounded-full text-mute shadow-[inset_0_0_0_1.5px_color-mix(in_srgb,var(--color-ink)_20%,transparent)]")} aria-hidden>
            <svg viewBox="0 0 24 24" className="h-[70%] w-[70%]" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
              <path d="M5 12h14" />
            </svg>
          </span>
        );
      return <span className={cx(box, "shrink-0 rounded-full shadow-[inset_0_0_0_1.5px_color-mix(in_srgb,var(--color-ink)_20%,transparent)]")} aria-hidden />;
    }
    
    const WORD: Record<PlanStepStatus, string> = { pending: "Pending", running: "Running", done: "Done", skipped: "Skipped", failed: "Failed" };
    
    function elapsed(s: PlanStep, now: number) {
      if (s.status === "running" && s.startedAt) return Math.max(0, (now || s.startedAt) - s.startedAt);
      return s.duration;
    }
    
    /**
     * A task list an agent works through while you watch. Steps go from pending to running to done, skipped or
     * failed, each with its own timer. The running step opens by itself to show its live log line, and its check
     * draws in when it finishes. Failures use a word and an icon, not red.
     */
    export function AgentPlan({ title, steps, action, footer, className }: AgentPlanProps) {
      const root = useRef<HTMLElement>(null);
      const [pinned, setPinned] = useState<Record<string, boolean>>({});
      const running = steps.some((s) => s.status === "running" || s.substeps?.some((x) => x.status === "running"));
      const now = useNow(running, root);
    
      const total = steps.length;
      const doneCount = steps.filter((s) => settled(s.status)).length;
      const failedAt = steps.findIndex((s) => s.status === "failed");
      const current = steps.findIndex((s) => s.status === "running");
      const allDone = total > 0 && doneCount === total && failedAt < 0;
      const spent = steps.reduce((a, s) => a + (elapsed(s, now) ?? 0), 0);
    
      const state = failedAt >= 0 ? `Stopped at step ${failedAt + 1}` : allDone ? "Done" : running ? "Running" : doneCount === 0 ? "Not started" : "Paused";
      const live =
        failedAt >= 0
          ? `Step ${failedAt + 1} failed: ${steps[failedAt].title}.`
          : current >= 0
            ? `Step ${current + 1} of ${total}: ${steps[current].title}.`
            : allDone
              ? `All ${total} steps done.`
              : "";
    
      return (
        <section
          ref={root}
          aria-label={title}
          className={cx(
            "asta-plan-a flex w-full flex-col rounded-[14px] bg-paper text-ink shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_9%,transparent),0_1px_2px_rgb(0_0_0/0.04)]",
            className,
          )}
        >
          <style href="asta-agent-plan" precedence="asta">{KEYFRAMES}</style>
          <p className="sr-only" aria-live="polite">
            {live}
          </p>
          <header className="flex flex-col gap-3 px-4 pb-3 pt-4">
            <div className="flex items-start justify-between gap-3">
              <div className="min-w-0">
                <p className="flex items-center gap-1.5 text-[12px] text-mute">
                  {running && <span aria-hidden className="h-1.5 w-1.5 rounded-full bg-brand animate-[asta-plan-pop_1.2s_ease-in-out_infinite_alternate]" />}
                  <span className={cx(failedAt >= 0 && "font-medium text-ink")}>{state}</span>
                  {spent > 0 && <span className="tabular-nums">· {formatStepTime(spent)}</span>}
                </p>
                <h3 className="mt-0.5 text-[14.5px] font-medium leading-snug tracking-[-0.01em]">{title}</h3>
              </div>
              {action}
            </div>
            <div className="flex items-center gap-3">
              <div className="relative h-1 flex-1 overflow-hidden rounded-full bg-paper-2">
                <span
                  className={cx("absolute inset-0 origin-left transition-[transform,background-color] duration-700 motion-reduce:transition-none", failedAt >= 0 ? "bg-ink" : "bg-brand")}
                  style={{ transform: `scaleX(${total ? doneCount / total : 0})`, transitionTimingFunction: CURVE }}
                />
              </div>
              <p className="shrink-0 text-[12px] tabular-nums text-mute">
                <span className="font-medium text-ink">{doneCount}</span> of {total}
              </p>
            </div>
          </header>
    
          {total === 0 ? (
            <p className="px-4 pb-5 text-[13px] text-mute">The plan shows up here once the agent has one.</p>
          ) : (
            <ol className="flex flex-col px-2 pb-2">
              {steps.map((s, i) => {
                const subs = s.substeps ?? [];
                const canOpen = !!s.detail || subs.length > 0;
                const open = canOpen && (pinned[s.id] ?? (s.status === "running" || s.status === "failed"));
                const t = elapsed(s, now);
                const bodyId = `plan-${s.id}`;
                const row = (
                  <>
                    <StatusIcon key={s.status} status={s.status} />
                    <span
                      className={cx(
                        "min-w-0 flex-1 text-left text-[13.5px] leading-snug [overflow-wrap:anywhere]",
                        s.status === "pending" && "text-mute",
                        s.status === "running" && "font-medium text-ink",
                        s.status === "done" && "text-ink-2",
                        s.status === "skipped" && "text-mute line-through decoration-[color-mix(in_srgb,var(--color-ink)_30%,transparent)]",
                        s.status === "failed" && "font-medium text-ink",
                      )}
                    >
                      {s.title}
                    </span>
                    {(s.status === "skipped" || s.status === "failed") && (
                      <span className={cx("shrink-0 rounded px-1.5 py-px text-[11px]", s.status === "failed" ? "bg-ink font-medium text-paper" : "bg-paper-2 text-mute")}>{WORD[s.status]}</span>
                    )}
                    {t !== undefined && s.status !== "skipped" && <span className="w-12 shrink-0 text-right text-[12px] tabular-nums text-mute">{formatStepTime(t)}</span>}
                    {canOpen && (
                      <svg
                        viewBox="0 0 24 24"
                        aria-hidden
                        className={cx("h-3.5 w-3.5 shrink-0 text-mute transition-transform duration-300", open && "rotate-90")}
                        style={{ transitionTimingFunction: CURVE }}
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="2.55"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                      >
                        <path d="m9.5 6 6 6-6 6" />
                      </svg>
                    )}
                  </>
                );
                return (
                  <li key={s.id} className="relative">
                    {i < total - 1 && (
                      <span aria-hidden className="pointer-events-none absolute bottom-[-6px] left-[17px] top-[30px] w-px bg-[color-mix(in_srgb,var(--color-ink)_10%,transparent)]" />
                    )}
                    {canOpen ? (
                      <button
                        type="button"
                        aria-expanded={open}
                        aria-controls={bodyId}
                        onClick={() => setPinned((p) => ({ ...p, [s.id]: !open }))}
                        className="flex min-h-10 w-full items-center gap-2.5 rounded-lg px-2 py-2 outline-none transition-colors duration-200 hover:bg-paper-2 focus-visible:ring-2 focus-visible:ring-brand/50"
                      >
                        {row}
                        <span className="sr-only">, {WORD[s.status]}</span>
                      </button>
                    ) : (
                      <div className="flex min-h-10 w-full items-center gap-2.5 px-2 py-2">
                        {row}
                        <span className="sr-only">, {WORD[s.status]}</span>
                      </div>
                    )}
                    {open && (
                      <div id={bodyId} className="asta-plan-a flex flex-col gap-1.5 pb-2 pl-[38px] pr-2 animate-[asta-plan-in_.3s_cubic-bezier(.16,1,.3,1)_both]">
                        {s.detail && (
                          <p
                            key={s.detail}
                            className={cx(
                              "asta-plan-a truncate text-[12px] leading-relaxed animate-[asta-plan-in_.3s_cubic-bezier(.16,1,.3,1)_both]",
                              s.status === "running" ? "font-mono text-mute" : s.status === "failed" ? "whitespace-normal text-ink" : "text-mute",
                            )}
                            title={s.detail}
                          >
                            {s.detail}
                          </p>
                        )}
                        {subs.length > 0 && (
                          <ul className="flex flex-col gap-1">
                            {subs.map((x) => (
                              <li key={x.id} className="flex items-center gap-2 text-[12.5px]">
                                <StatusIcon key={x.status} status={x.status} small />
                                <span className={cx("min-w-0 flex-1 truncate", x.status === "pending" ? "text-mute" : x.status === "running" ? "text-ink" : "text-ink-2")}>{x.title}</span>
                                <span className="sr-only">, {WORD[x.status]}</span>
                              </li>
                            ))}
                          </ul>
                        )}
                      </div>
                    )}
                  </li>
                );
              })}
            </ol>
          )}
          {footer && <div className="px-4 pb-4">{footer}</div>}
        </section>
      );
    }
    
    export default AgentPlan;
    
  4. Or ask your AI agent

    Paste this into Claude Code, Cursor, Codex, v0 or Lovable. Fill in the last line. More in Prompts.

    Add the Astabyte UI Agent plan component to my project.
    
    An agent's steps as they run.
    It includes: AgentPlan, step states, sub-steps, timers, live log, progress.
    
    Install it:
    ```sh
    pnpm dlx asta-ui@latest add agent-plan --radix
    ```
    Or with the shadcn CLI:
    ```sh
    pnpm dlx shadcn@latest add https://ui.astabyte.com/r/agent-plan.json
    ```
    If the project isn't set up yet, run `pnpm dlx asta-ui@latest init --radix` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4).
    
    Import it like this:
    ```tsx
    import { AgentPlan, type PlanStep } from "@/components/astabyte/agent-plan";
    ```
    
    Usage example and props: https://ui.astabyte.com/agent-plan
    Full catalogue for context: https://ui.astabyte.com/llms.txt
    
    Rules:
    - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS.
    - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback.
    - Keep keyboard, focus and ARIA behaviour.
    - Use fake data and fake brand names in examples.
    
    Use it to: [describe where it goes and what it should do]
  5. Or use plain HTML + CSS

    Not on React? Use it from Django, Rails, Laravel, Go html/template, htmx or a static page. Load asta.css and asta.js once (the head.html tab), then paste the markup. The ui.astabyte.com/cdn link is temporary: pin a version from jsDelivr for production. More in HTML + CSS.

    <!-- Static markup: your server (or htmx) re-renders it as the agent works. data-status on each step draws its icon. Open the running step's details, and asta.js counts data-asta-elapsed up from that time. -->
    <section class="asta-agent-plan" aria-label="Migrate billing to usage-based plans" style="max-width:520px">
      <header class="asta-agent-plan-head">
        <p class="asta-agent-plan-state">Running · 9.4s</p>
        <h3 class="asta-agent-plan-title">Migrate billing to usage-based plans</h3>
        <div class="asta-agent-plan-progress"><span class="asta-agent-plan-track"><span style="--value:.43"></span></span><span><b>3</b> of 7</span></div>
      </header>
      <ol class="asta-agent-plan-steps">
        <li class="asta-agent-plan-step" data-status="done"><details><summary class="asta-agent-plan-row"><span class="asta-agent-plan-icon"></span><span class="asta-agent-plan-name">Read the current plan schema</span><span class="asta-agent-plan-time">1.6s</span><svg class="asta-agent-plan-chevron" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 4 4 4-4 4"/></svg></summary>
          <div class="asta-agent-plan-body"><p class="asta-agent-plan-detail">4 plans, 2,318 active subscriptions</p></div></details></li>
        <li class="asta-agent-plan-step" data-status="done"><details><summary class="asta-agent-plan-row"><span class="asta-agent-plan-icon"></span><span class="asta-agent-plan-name">Map seat plans to usage tiers</span><span class="asta-agent-plan-time">2.4s</span><svg class="asta-agent-plan-chevron" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 4 4 4-4 4"/></svg></summary>
          <div class="asta-agent-plan-body"><ul class="asta-agent-plan-subs"><li data-status="done"><span class="asta-agent-plan-icon"></span>Starter → Usage Lite</li><li data-status="done"><span class="asta-agent-plan-icon"></span>Team → Usage Standard</li><li data-status="done"><span class="asta-agent-plan-icon"></span>Business → Usage Pro</li></ul></div></details></li>
        <li class="asta-agent-plan-step" data-status="done"><div class="asta-agent-plan-row"><span class="asta-agent-plan-icon"></span><span class="asta-agent-plan-name">Write migration 0042_usage_pricing.sql</span><span class="asta-agent-plan-time">1.8s</span></div></li>
        <li class="asta-agent-plan-step" data-status="running"><details open><summary class="asta-agent-plan-row"><span class="asta-agent-plan-icon"></span><span class="asta-agent-plan-name">Backfill 90 days of usage events</span><span class="asta-agent-plan-time">3.6s</span><svg class="asta-agent-plan-chevron" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 4 4 4-4 4"/></svg></summary>
          <div class="asta-agent-plan-body"><p class="asta-agent-plan-detail">backfilled 640k of 1.28M events</p></div></details></li>
        <li class="asta-agent-plan-step" data-status="pending"><div class="asta-agent-plan-row"><span class="asta-agent-plan-icon"></span><span class="asta-agent-plan-name">Dry-run invoices for 20 sample accounts</span></div></li>
        <li class="asta-agent-plan-step" data-status="skipped"><div class="asta-agent-plan-row"><span class="asta-agent-plan-icon"></span><span class="asta-agent-plan-name">Email Enterprise admins about the change</span><span class="asta-agent-plan-badge">Skipped</span></div></li>
        <li class="asta-agent-plan-step" data-status="pending"><div class="asta-agent-plan-row"><span class="asta-agent-plan-icon"></span><span class="asta-agent-plan-name">Open a pull request</span></div></li>
      </ol>
    </section>
    
    <!-- After a failure: data-failed on the section, the failed step open with its reason. -->
    <section class="asta-agent-plan" aria-label="Rotate API keys" data-failed style="max-width:520px;margin-top:24px">
      <header class="asta-agent-plan-head">
        <p class="asta-agent-plan-state">Stopped at step 2 · 3.1s</p>
        <h3 class="asta-agent-plan-title">Rotate the production API keys</h3>
        <div class="asta-agent-plan-progress"><span class="asta-agent-plan-track"><span style="--value:.67"></span></span><span><b>2</b> of 3</span></div>
      </header>
      <ol class="asta-agent-plan-steps">
        <li class="asta-agent-plan-step" data-status="done"><div class="asta-agent-plan-row"><span class="asta-agent-plan-icon"></span><span class="asta-agent-plan-name">Create new keys in the vault</span><span class="asta-agent-plan-time">1.2s</span></div></li>
        <li class="asta-agent-plan-step" data-status="failed"><details open><summary class="asta-agent-plan-row"><span class="asta-agent-plan-icon"></span><span class="asta-agent-plan-name">Update the worker secrets</span><span class="asta-agent-plan-badge">Failed</span><span class="asta-agent-plan-time">1.9s</span><svg class="asta-agent-plan-chevron" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 4 4 4-4 4"/></svg></summary>
          <div class="asta-agent-plan-body"><p class="asta-agent-plan-detail">The deploy token can't write secrets. Give it the Secrets: write scope and retry.</p></div></details></li>
        <li class="asta-agent-plan-step" data-status="pending"><div class="asta-agent-plan-row"><span class="asta-agent-plan-icon"></span><span class="asta-agent-plan-name">Revoke the old keys</span></div></li>
      </ol>
    </section>

Usage

The demo above, as code.

"use client";

import { useEffect, useRef, useState, type Dispatch, type SetStateAction } from "react";
import { AgentPlan, type PlanStep } from "@/components/astabyte/agent-plan";

type Spec = { id: string; title: string; ms: number; logs?: string[]; result?: string; subs?: string[]; skip?: string; fail?: string };

const PLAN: Spec[] = [
  { id: "read", title: "Read the current plan schema", ms: 1600, logs: ["read billing/plans.ts", "select plan, count(*) from subscriptions"], result: "4 plans, 2,318 active subscriptions" },
  { id: "map", title: "Map seat plans to usage tiers", ms: 2400, subs: ["Starter → Usage Lite", "Team → Usage Standard", "Business → Usage Pro"], result: "3 tiers mapped. Enterprise stays on contracts." },
  { id: "sql", title: "Write migration 0042_usage_pricing.sql", ms: 1800, logs: ["create table meter_events", "alter table plans add unit_price_cents"], result: "+128 −14 lines" },
  { id: "fill", title: "Backfill 90 days of usage events", ms: 4200, logs: ["backfilled 210k of 1.28M events", "backfilled 640k of 1.28M events", "backfilled 1.05M of 1.28M events"], result: "1.28M events in 4 batches" },
  {
    id: "dry",
    title: "Dry-run invoices for 20 sample accounts",
    ms: 2600,
    logs: ["rendering invoice 7 of 20", "rendering invoice 16 of 20"],
    result: "19 of 20 within ±2%. One is 6% cheaper.",
    fail: "Account 1043 comes out 14% higher than today. Its overage cap isn't mapped yet.",
  },
  { id: "mail", title: "Email Enterprise admins about the change", ms: 0, skip: "Enterprise stays on contract pricing." },
  { id: "pr", title: "Open a pull request", ms: 1400, logs: ["git push origin feat/usage-pricing"], result: "#418 ready for review" },
];

const fresh = (): PlanStep[] => PLAN.map((p) => ({ id: p.id, title: p.title, status: "pending", substeps: p.subs?.map((t, i) => ({ id: `${p.id}${i}`, title: t, status: "pending" })) }));

type Setters = { steps: Dispatch<SetStateAction<PlanStep[]>>; failed: (on: boolean) => void; fade: (on: boolean) => void };

/** Plays the plan on timers. Every other lap the dry run fails, so the stopped state shows too. */
function runner(set: Setters) {
  let timers: ReturnType<typeof setTimeout>[] = [];
  let lap = 0;
  const later = (ms: number, f: () => void) => timers.push(setTimeout(f, ms));
  const stop = () => (timers.forEach(clearTimeout), (timers = []));
  const patch = (id: string, p: Partial<PlanStep>) => set.steps((all) => all.map((s) => (s.id === id ? { ...s, ...p } : s)));
  const tick = (p: Spec, k: number) =>
    set.steps((all) => all.map((s) => (s.id === p.id ? { ...s, substeps: s.substeps?.map((x, j) => ({ ...x, status: j <= k ? "done" : j === k + 1 ? "running" : "pending" })) } : s)));

  function play(from: number, failDry: boolean) {
    stop();
    let at = 400;
    for (let i = from; i < PLAN.length; i++) {
      const p = PLAN[i];
      if (p.skip) {
        later(at, () => patch(p.id, { status: "skipped", detail: p.skip }));
        at += 500;
        continue;
      }
      const start = at;
      later(start, () => patch(p.id, { status: "running", startedAt: Date.now(), detail: p.logs?.[0] }));
      p.logs?.forEach((l, k) => k && later(start + (p.ms / p.logs!.length) * k, () => patch(p.id, { detail: l })));
      p.subs?.forEach((_, k) => later(start + (p.ms / p.subs!.length) * (k + 0.5), () => tick(p, k)));
      if (failDry && p.fail) {
        later(start + p.ms, () => {
          patch(p.id, { status: "failed", detail: p.fail, duration: p.ms });
          set.failed(true);
        });
        later(start + p.ms + 4200, restart);
        return;
      }
      later(start + p.ms, () => patch(p.id, { status: "done", detail: p.result, duration: p.ms }));
      at = start + p.ms + 350;
    }
    later(at + 3600, restart);
  }

  function begin() {
    set.steps(fresh());
    set.failed(false);
    set.fade(false);
    play(0, lap % 2 === 1);
  }

  // Fade out, reset, fade back in and go again.
  function restart() {
    set.fade(true);
    later(450, () => {
      lap += 1;
      begin();
    });
  }

  const retry = () => {
    patch("dry", { status: "pending", detail: undefined, duration: undefined });
    set.failed(false);
    play(4, false);
  };

  return { begin, retry, stop };
}

export default function AgentPlanDemo() {
  const [steps, setSteps] = useState(fresh);
  const [fade, setFade] = useState(false);
  const [visible, setVisible] = useState(true);
  const [failed, setFailed] = useState(false);
  const root = useRef<HTMLDivElement>(null);
  const run = useRef<ReturnType<typeof runner> | null>(null);

  // Rest while offscreen or in a hidden tab, and start the lap over when back.
  useEffect(() => {
    const el = root.current;
    if (!el) return;
    let seen = true;
    const sync = () => setVisible(seen && !document.hidden);
    const io = new IntersectionObserver(([e]) => {
      seen = e.isIntersecting;
      sync();
    });
    io.observe(el);
    document.addEventListener("visibilitychange", sync);
    return () => {
      io.disconnect();
      document.removeEventListener("visibilitychange", sync);
    };
  }, []);

  useEffect(() => {
    if (!visible) return;
    const r = runner({ steps: setSteps, failed: setFailed, fade: setFade });
    run.current = r;
    const t = setTimeout(r.begin, 0);
    return () => {
      clearTimeout(t);
      r.stop();
    };
  }, [visible]);

  return (
    <div ref={root} className="flex min-h-[560px] w-full items-center justify-center p-4 sm:p-10">
      <div className="w-full max-w-[520px] transition-opacity duration-[450ms]" style={{ opacity: fade ? 0 : 1, transitionTimingFunction: "cubic-bezier(.16,1,.3,1)" }}>
        <AgentPlan
          title="Migrate billing to usage-based plans"
          steps={steps}
          footer={
            failed && (
              <div className="flex items-center justify-between gap-3 rounded-lg bg-paper-2 px-3 py-2 text-[12.5px] text-ink-2 animate-[asta-plan-in_.3s_cubic-bezier(.16,1,.3,1)_both]">
                <span>The agent stopped and is waiting for you.</span>
                <button
                  type="button"
                  onClick={() => run.current?.retry()}
                  className="h-7 shrink-0 rounded-md bg-ink px-2.5 text-[12px] font-medium text-paper outline-none transition-transform duration-150 active:scale-[0.97] focus-visible:ring-2 focus-visible:ring-brand/50 focus-visible:ring-offset-2 focus-visible:ring-offset-paper-2"
                >
                  Retry step
                </button>
              </div>
            )
          }
        />
      </div>
    </div>
  );
}