{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "run-replay",
  "type": "registry:block",
  "title": "Run Replay",
  "description": "Watch an agent work a task from start to finish: plan steps tick off, tool calls stream into a log, it stops to ask before sending anything, and the draft it's writing fills in beside it.",
  "categories": [
    "screen",
    "AI"
  ],
  "dependencies": [
    "motion",
    "lucide-react"
  ],
  "registryDependencies": [
    "utils",
    "https://coss.com/ui/r/badge.json",
    "https://coss.com/ui/r/button.json",
    "https://coss.com/ui/r/checkbox.json",
    "https://coss.com/ui/r/menu.json",
    "https://coss.com/ui/r/skeleton.json",
    "https://coss.com/ui/r/tabs.json"
  ],
  "files": [
    {
      "path": "registry/devl/run-replay.tsx",
      "type": "registry:component",
      "content": "\"use client\";\n\nimport {\n  AnimatePresence,\n  MotionConfig,\n  motion,\n  useReducedMotion,\n  useSpring,\n  useTransform,\n} from \"motion/react\";\nimport {\n  BanIcon,\n  BotIcon,\n  BracesIcon,\n  CheckIcon,\n  ChevronDownIcon,\n  CopyIcon,\n  DatabaseIcon,\n  EllipsisIcon,\n  FileTextIcon,\n  HandIcon,\n  LinkIcon,\n  ListChecksIcon,\n  type LucideIcon,\n  MinusIcon,\n  PauseIcon,\n  PlayIcon,\n  RotateCcwIcon,\n  SearchIcon,\n  SendIcon,\n  ShieldAlertIcon,\n  SparklesIcon,\n  SquareTerminalIcon,\n  TriangleAlertIcon,\n  XIcon,\n} from \"lucide-react\";\nimport { useEffect, useId, useMemo, useReducer, useRef, useState } from \"react\";\nimport { Badge } from \"@/components/ui/badge\";\nimport { Button } from \"@/components/ui/button\";\nimport { Checkbox } from \"@/components/ui/checkbox\";\nimport { Menu, MenuItem, MenuPopup, MenuSeparator, MenuTrigger } from \"@/components/ui/menu\";\nimport { Skeleton } from \"@/components/ui/skeleton\";\nimport { Tabs, TabsList, TabsTab } from \"@/components/ui/tabs\";\nimport { cn } from \"@/lib/utils\";\n\nexport type RunToolKind = \"db\" | \"search\" | \"code\" | \"doc\" | \"send\" | \"task\";\n\nexport interface RunToolCall {\n  name: string;\n  kind: RunToolKind;\n  args: Record<string, string | number | boolean>;\n  result: string;\n  ms: number;\n  tokens: number;\n  failsOnce?: string;\n}\n\nexport interface RunStep {\n  title: string;\n  tools?: RunToolCall[];\n  thought?: string;\n  reveal?: \"accounts\" | \"email\";\n  approval?: { title: string; description: string; tool: RunToolCall };\n  fail?: string;\n}\n\nexport interface RunAccount {\n  company: string;\n  contact: string;\n  email: string;\n  score: number;\n  arr: string;\n}\n\nexport interface RunEmail {\n  to: string;\n  subject: string;\n  highlights: string[];\n  body: string;\n}\n\nexport interface RunReplayProps {\n  agentName?: string;\n  runId?: string;\n  task?: string;\n  model?: string;\n  steps?: RunStep[];\n  accounts?: RunAccount[];\n  email?: RunEmail;\n  autoApproveAfter?: number;\n  speed?: number;\n  className?: string;\n}\n\ntype StepStatus = \"pending\" | \"running\" | \"done\" | \"waiting\" | \"skipped\" | \"failed\";\n\ntype LogEntry =\n  | {\n      kind: \"tool\";\n      id: string;\n      step: number;\n      call: RunToolCall;\n      status: \"running\" | \"done\" | \"denied\" | \"failed\";\n      result?: string;\n      retry?: boolean;\n      at: number;\n      end?: number;\n    }\n  | { kind: \"thought\"; id: string; step: number; text: string; at: number }\n  | { kind: \"approval\"; id: string; step: number; status: \"waiting\" | \"approved\" | \"denied\"; count: number; at: number };\n\ntype Ev =\n  | { k: \"step\"; i: number; s: StepStatus; d: number }\n  | { k: \"tool\"; id: string; step: number; call: RunToolCall; d: number; retry?: boolean }\n  | { k: \"toolDone\"; id: string; d: number }\n  | { k: \"toolFail\"; id: string; message: string; d: number }\n  | { k: \"halt\"; id: string; step: number; message: string; d: number }\n  | { k: \"denied\"; id: string; step: number; call: RunToolCall; d: number }\n  | { k: \"thought\"; id: string; step: number; text: string; d: number }\n  | { k: \"row\"; d: number }\n  | { k: \"words\"; n: number; d: number }\n  | { k: \"approval\"; id: string; step: number; d: number }\n  | { k: \"finish\"; d: number };\n\ninterface RunState {\n  cursor: number;\n  steps: StepStatus[];\n  log: LogEntry[];\n  tokens: number;\n  rows: number;\n  words: number;\n  awaiting: { id: string; step: number } | null;\n  finished: boolean;\n  cancelled: boolean;\n  decision: { approve: boolean; count: number } | null;\n  failure: { id: string; step: number; message: string } | null;\n  retried: boolean;\n}\n\ntype Action =\n  | { type: \"ev\"; ev: Ev; at: number }\n  | { type: \"decide\"; approve: boolean; count: number }\n  | { type: \"cancel\" }\n  | { type: \"retry\" }\n  | { type: \"reset\"; steps: number };\n\nconst easeOut = [0.23, 1, 0.32, 1] as const;\nconst spring = { type: \"spring\", duration: 0.3, bounce: 0 } as const;\nconst enter = { duration: 0.2, ease: easeOut } as const;\nconst press = \"transition-[transform,box-shadow,background-color] duration-150 ease-out active:scale-[0.97]\";\n\nconst toolMeta: Record<RunToolKind, { icon: LucideIcon; text: string; bar: string }> = {\n  db: { icon: DatabaseIcon, text: \"text-teal-600 dark:text-teal-400\", bar: \"bg-teal-500\" },\n  search: { icon: SearchIcon, text: \"text-info-foreground\", bar: \"bg-info\" },\n  code: { icon: SquareTerminalIcon, text: \"text-amber-600 dark:text-amber-400\", bar: \"bg-amber-500\" },\n  doc: { icon: FileTextIcon, text: \"text-orange-600 dark:text-orange-400\", bar: \"bg-orange-500\" },\n  send: { icon: SendIcon, text: \"text-violet-600 dark:text-violet-400\", bar: \"bg-violet-500\" },\n  task: { icon: ListChecksIcon, text: \"text-success-foreground\", bar: \"bg-success\" },\n};\n\nconst defaultAccounts: RunAccount[] = [\n  { company: \"Halcyon Freight\", contact: \"Ines Duarte\", email: \"ines@halcyon.example\", score: 0.86, arr: \"$84k\" },\n  { company: \"Brightwater Labs\", contact: \"Theo Marsh\", email: \"theo@brightwater.example\", score: 0.81, arr: \"$62k\" },\n  { company: \"Copperline\", contact: \"Ana Petrov\", email: \"ana@copperline.example\", score: 0.77, arr: \"$45k\" },\n  { company: \"Northgate Health\", contact: \"Sam Okoro\", email: \"sam@northgate.example\", score: 0.72, arr: \"$120k\" },\n  { company: \"Juniper & Vale\", contact: \"Lena Fischer\", email: \"lena@junipervale.example\", score: 0.69, arr: \"$38k\" },\n  { company: \"Orbit Supply\", contact: \"Kai Tanaka\", email: \"kai@orbitsupply.example\", score: 0.67, arr: \"$29k\" },\n  { company: \"Mosswood\", contact: \"Priya Nair\", email: \"priya@mosswood.example\", score: 0.65, arr: \"$51k\" },\n  { company: \"Tidewell\", contact: \"Owen Price\", email: \"owen@tidewell.example\", score: 0.64, arr: \"$33k\" },\n  { company: \"Larkspur Media\", contact: \"Rosa Lind\", email: \"rosa@larkspur.example\", score: 0.63, arr: \"$26k\" },\n  { company: \"Fieldnote\", contact: \"Ben Adler\", email: \"ben@fieldnote.example\", score: 0.62, arr: \"$41k\" },\n  { company: \"Cinder Robotics\", contact: \"Mei Chen\", email: \"mei@cinder.example\", score: 0.61, arr: \"$97k\" },\n  { company: \"Paloma Travel\", contact: \"Luis Ortega\", email: \"luis@paloma.example\", score: 0.6, arr: \"$22k\" },\n];\n\nconst defaultSteps: RunStep[] = [\n  {\n    title: \"Pull renewals due in 90 days\",\n    tools: [\n      {\n        name: \"crm.search_accounts\",\n        kind: \"db\",\n        args: { renews_within: \"90d\", segment: \"mid-market\" },\n        result: \"41 accounts\",\n        ms: 1100,\n        tokens: 820,\n      },\n    ],\n    thought: \"41 is too many to personalise well. Narrowing with support signals first.\",\n  },\n  {\n    title: \"Read recent support threads\",\n    tools: [\n      { name: \"helpdesk.list_threads\", kind: \"search\", args: { accounts: 41, since: \"30d\" }, result: \"128 threads\", ms: 1300, tokens: 2400 },\n      {\n        name: \"helpdesk.sentiment\",\n        kind: \"search\",\n        args: { threads: 128 },\n        result: \"19 accounts trending negative\",\n        ms: 1100,\n        tokens: 1900,\n        failsOnce: \"429 Too Many Requests · retrying in 2s\",\n      },\n    ],\n  },\n  {\n    title: \"Score churn risk\",\n    tools: [\n      { name: \"python.run\", kind: \"code\", args: { script: \"score_churn.py\", accounts: 19 }, result: \"12 accounts ≥ 0.60\", ms: 1500, tokens: 1300 },\n    ],\n    reveal: \"accounts\",\n    thought: \"Halcyon and Brightwater both raised the September double charge. Leading with the billing fix.\",\n  },\n  {\n    title: \"Draft personalised outreach\",\n    tools: [\n      { name: \"docs.create_draft\", kind: \"doc\", args: { template: \"renewal-check-in\", accounts: 12 }, result: \"12 drafts\", ms: 900, tokens: 3100 },\n    ],\n    reveal: \"email\",\n  },\n  {\n    title: \"Send emails via Postbox\",\n    approval: {\n      title: \"Send renewal emails?\",\n      description: \"Renewal Scout wants to send from maya@relay.example. Untick anyone you'd rather call.\",\n      tool: { name: \"postbox.send_batch\", kind: \"send\", args: { from: \"maya@relay.example\", template: \"renewal-check-in\" }, result: \"{n} sent · 0 bounced\", ms: 1400, tokens: 400 },\n    },\n  },\n  {\n    title: \"Log follow-ups in CRM\",\n    tools: [\n      { name: \"crm.create_tasks\", kind: \"task\", args: { owner: \"maya\", due: \"+3d\" }, result: \"Follow-ups due Friday\", ms: 900, tokens: 600 },\n    ],\n  },\n];\n\nconst defaultEmail: RunEmail = {\n  to: \"Ines Duarte <ines@halcyon.example>\",\n  subject: \"Your September invoice, and your renewal\",\n  highlights: [\"Sep double charge\", \"Renews Nov 14\", \"Route planning ask\"],\n  body: \"Hi Ines,\\n\\nThanks for flagging the double charge on your September invoice. You were right, and the fix ships with the October billing run. I've credited the difference to your account, so there's nothing more to do on your side.\\n\\nBefore your renewal on November 14, I'd love 20 minutes to walk through the new route-planning limits your dispatch team asked about. Would Tuesday or Thursday afternoon work?\\n\\nBest,\\nMaya\",\n};\n\nfunction buildEvents(\n  steps: RunStep[],\n  rows: number,\n  words: number,\n  decision: RunState[\"decision\"],\n  retried: boolean,\n): Ev[] {\n  const ev: Ev[] = [];\n  for (let i = 0; i < steps.length; i++) {\n    const step = steps[i];\n    ev.push({ k: \"step\", i, s: \"running\", d: i === 0 ? 700 : 450 });\n    const tools = step.tools ?? [];\n    for (let j = 0; j < tools.length; j++) {\n      const call = tools[j];\n      const id = `${i}-${j}`;\n      ev.push({ k: \"tool\", id, step: i, call, d: 380 });\n      if (call.failsOnce) {\n        ev.push({ k: \"toolFail\", id, message: call.failsOnce, d: Math.round(call.ms * 0.6) });\n        ev.push({ k: \"tool\", id: `${id}-r`, step: i, call, d: 2000, retry: true });\n        ev.push({ k: \"toolDone\", id: `${id}-r`, d: call.ms });\n      } else if (step.fail && j === tools.length - 1) {\n        ev.push({ k: \"halt\", id, step: i, message: step.fail, d: Math.round(call.ms * 0.8) });\n        if (!retried) return ev;\n        ev.push({ k: \"tool\", id: `${id}-r`, step: i, call, d: 450, retry: true });\n        ev.push({ k: \"toolDone\", id: `${id}-r`, d: call.ms });\n      } else {\n        ev.push({ k: \"toolDone\", id, d: call.ms });\n      }\n    }\n    if (step.reveal === \"accounts\") for (let r = 0; r < rows; r++) ev.push({ k: \"row\", d: r === 0 ? 300 : 140 });\n    if (step.reveal === \"email\") for (let w = 0; w < words; w += 3) ev.push({ k: \"words\", n: 3, d: w === 0 ? 400 : 55 });\n    if (step.thought) ev.push({ k: \"thought\", id: `t-${i}`, step: i, text: step.thought, d: 650 });\n    if (step.approval) {\n      ev.push({ k: \"approval\", id: `ap-${i}`, step: i, d: 600 });\n      if (!decision) return ev;\n      const id = `${i}-send`;\n      if (decision.approve) {\n        const call = { ...step.approval.tool, result: step.approval.tool.result.replace(\"{n}\", String(decision.count)) };\n        ev.push({ k: \"tool\", id, step: i, call, d: 350 });\n        ev.push({ k: \"toolDone\", id, d: call.ms });\n      } else {\n        ev.push({ k: \"denied\", id, step: i, call: step.approval.tool, d: 300 });\n      }\n      ev.push({ k: \"step\", i, s: decision.approve ? \"done\" : \"skipped\", d: 350 });\n      continue;\n    }\n    ev.push({ k: \"step\", i, s: \"done\", d: 350 });\n  }\n  ev.push({ k: \"finish\", d: 500 });\n  return ev;\n}\n\nfunction initState(steps: number): RunState {\n  return {\n    cursor: 0,\n    steps: Array.from({ length: steps }, () => \"pending\" as StepStatus),\n    log: [],\n    tokens: 0,\n    rows: 0,\n    words: 0,\n    awaiting: null,\n    finished: false,\n    cancelled: false,\n    decision: null,\n    failure: null,\n    retried: false,\n  };\n}\n\nfunction reducer(state: RunState, action: Action): RunState {\n  if (action.type === \"reset\") return initState(action.steps);\n  if (action.type === \"cancel\") {\n    return {\n      ...state,\n      finished: true,\n      cancelled: true,\n      awaiting: null,\n      failure: null,\n      steps: state.steps.map((s) => (s === \"running\" || s === \"waiting\" || s === \"failed\" ? \"skipped\" : s)),\n      log: state.log.map((e) =>\n        e.kind === \"tool\" && e.status === \"running\"\n          ? { ...e, status: \"denied\", result: \"Cancelled\" }\n          : e.kind === \"approval\" && e.status === \"waiting\"\n            ? { ...e, status: \"denied\" }\n            : e,\n      ),\n    };\n  }\n  if (action.type === \"retry\") {\n    const f = state.failure;\n    if (!f) return state;\n    return {\n      ...state,\n      failure: null,\n      retried: true,\n      steps: state.steps.map((s, i) => (i === f.step ? \"running\" : s)),\n    };\n  }\n  if (action.type === \"decide\") {\n    const aw = state.awaiting;\n    if (!aw) return state;\n    return {\n      ...state,\n      awaiting: null,\n      decision: { approve: action.approve, count: action.count },\n      steps: state.steps.map((s, i) => (i === aw.step ? \"running\" : s)),\n      log: state.log.map((e) =>\n        e.kind === \"approval\" && e.id === aw.id ? { ...e, status: action.approve ? \"approved\" : \"denied\", count: action.count } : e,\n      ),\n    };\n  }\n  const ev = action.ev;\n  const at = action.at;\n  const next = { ...state, cursor: state.cursor + 1 };\n  switch (ev.k) {\n    case \"step\":\n      next.steps = state.steps.map((s, i) => (i === ev.i ? ev.s : s));\n      break;\n    case \"tool\":\n      next.log = [...state.log, { kind: \"tool\", id: ev.id, step: ev.step, call: ev.call, status: \"running\", retry: ev.retry, at }];\n      break;\n    case \"toolFail\":\n      next.log = state.log.map((e) => (e.kind === \"tool\" && e.id === ev.id ? { ...e, status: \"failed\", result: ev.message, end: at } : e));\n      break;\n    case \"halt\":\n      next.log = state.log.map((e) => (e.kind === \"tool\" && e.id === ev.id ? { ...e, status: \"failed\", result: ev.message, end: at } : e));\n      next.failure = { id: ev.id, step: ev.step, message: ev.message };\n      next.steps = state.steps.map((s, i) => (i === ev.step ? \"failed\" : s));\n      break;\n    case \"toolDone\": {\n      const entry = state.log.find((e) => e.id === ev.id);\n      next.log = state.log.map((e) => (e.kind === \"tool\" && e.id === ev.id ? { ...e, status: \"done\", result: e.call.result, end: at } : e));\n      next.tokens = state.tokens + (entry?.kind === \"tool\" ? entry.call.tokens : 0);\n      break;\n    }\n    case \"denied\":\n      next.log = [...state.log, { kind: \"tool\", id: ev.id, step: ev.step, call: ev.call, status: \"denied\", result: \"Denied by reviewer\", at, end: at }];\n      break;\n    case \"thought\":\n      next.log = [...state.log, { kind: \"thought\", id: ev.id, step: ev.step, text: ev.text, at }];\n      next.tokens = state.tokens + 180;\n      break;\n    case \"row\":\n      next.rows = state.rows + 1;\n      break;\n    case \"words\":\n      next.words = state.words + ev.n;\n      next.tokens = state.tokens + 14;\n      break;\n    case \"approval\":\n      next.awaiting = { id: ev.id, step: ev.step };\n      next.steps = state.steps.map((s, i) => (i === ev.step ? \"waiting\" : s));\n      next.log = [...state.log, { kind: \"approval\", id: ev.id, step: ev.step, status: \"waiting\", count: 0, at }];\n      break;\n    case \"finish\":\n      next.finished = true;\n      break;\n  }\n  return next;\n}\n\ntype Tone = \"info\" | \"warning\" | \"success\" | \"muted\" | \"destructive\";\nconst toneBg: Record<Tone, string> = {\n  destructive: \"bg-destructive\",\n  info: \"bg-info\",\n  warning: \"bg-warning\",\n  success: \"bg-success\",\n  muted: \"bg-muted-foreground\",\n};\n\nfunction LiveDot({ tone, live }: { tone: Tone; live: boolean }) {\n  return (\n    <span aria-hidden className=\"relative inline-flex size-4 shrink-0 items-center justify-center\">\n      {live && (\n        <motion.span\n          animate={{ scale: [1, 2.2], opacity: [0.45, 0] }}\n          className={cn(\"absolute size-2 rounded-full\", toneBg[tone])}\n          key={tone}\n          transition={{ duration: 1.6, repeat: Infinity, ease: \"easeOut\" }}\n        />\n      )}\n      <span className={cn(\"relative size-2 rounded-full transition-colors duration-300\", toneBg[tone])} />\n    </span>\n  );\n}\n\nfunction Rolling({ value, format }: { value: number; format: (n: number) => string }) {\n  const reduce = useReducedMotion();\n  const mv = useSpring(value, { stiffness: 120, damping: 22 });\n  useEffect(() => {\n    if (reduce) mv.jump(value);\n    else mv.set(value);\n  }, [value, reduce, mv]);\n  const text = useTransform(mv, format);\n  return <motion.span className=\"tabular-nums\">{text}</motion.span>;\n}\n\nconst nodeIn = { opacity: 0, scale: 0.9 };\nconst nodeShown = { opacity: 1, scale: 1 };\n\nfunction StepNode({ status }: { status: StepStatus }) {\n  const solid = \"flex size-5 items-center justify-center rounded-full\";\n  return (\n    <span className=\"relative z-10 flex size-5 shrink-0 items-center justify-center bg-background\">\n      <AnimatePresence initial={false} mode=\"popLayout\">\n        {status === \"done\" ? (\n          <motion.span animate={nodeShown} className={cn(solid, \"bg-success text-white\")} exit={nodeIn} initial={nodeIn} key=\"done\" transition={enter}>\n            <CheckIcon className=\"size-3\" strokeWidth={3} />\n          </motion.span>\n        ) : status === \"running\" ? (\n          <motion.span animate={nodeShown} className=\"relative size-5\" exit={nodeIn} initial={nodeIn} key=\"run\" transition={enter}>\n            <span className=\"absolute inset-0 rounded-full border-2 border-info/24\" />\n            <svg aria-hidden className=\"absolute inset-0 size-5 animate-spin text-info motion-reduce:animate-none\" viewBox=\"0 0 20 20\">\n              <circle cx=\"10\" cy=\"10\" fill=\"none\" r=\"8\" stroke=\"currentColor\" strokeDasharray=\"14 60\" strokeLinecap=\"round\" strokeWidth=\"2.5\" />\n            </svg>\n          </motion.span>\n        ) : status === \"waiting\" ? (\n          <motion.span animate={nodeShown} className={cn(solid, \"relative bg-warning text-white\")} exit={nodeIn} initial={nodeIn} key=\"wait\" transition={enter}>\n            <motion.span\n              animate={{ scale: [1, 1.8], opacity: [0.5, 0] }}\n              className=\"absolute inset-0 rounded-full bg-warning\"\n              transition={{ duration: 1.4, repeat: Infinity, ease: \"easeOut\" }}\n            />\n            <HandIcon className=\"relative size-3\" strokeWidth={2.5} />\n          </motion.span>\n        ) : status === \"failed\" ? (\n          <motion.span animate={nodeShown} className={cn(solid, \"bg-destructive text-white\")} exit={nodeIn} initial={nodeIn} key=\"fail\" transition={enter}>\n            <XIcon className=\"size-3\" strokeWidth={3} />\n          </motion.span>\n        ) : status === \"skipped\" ? (\n          <motion.span animate={nodeShown} className={cn(solid, \"bg-muted text-muted-foreground\")} exit={nodeIn} initial={nodeIn} key=\"skip\" transition={enter}>\n            <MinusIcon className=\"size-3\" strokeWidth={3} />\n          </motion.span>\n        ) : (\n          <motion.span animate={nodeShown} className=\"size-5 rounded-full border-2 border-input border-dashed\" exit={nodeIn} initial={nodeIn} key=\"pending\" transition={enter} />\n        )}\n      </AnimatePresence>\n    </span>\n  );\n}\n\nfunction formatArgs(args: RunToolCall[\"args\"]) {\n  return Object.entries(args)\n    .map(([k, v]) => `${k}: ${typeof v === \"string\" ? `\"${v}\"` : String(v)}`)\n    .join(\", \");\n}\n\nconst secs = (ms: number) => `${(ms / 1000).toFixed(1)}s`;\n\nfunction Waterfall({ start, ms, total, tone, live }: { start: number; ms: number; total: number; tone: string; live: boolean }) {\n  return (\n    <span aria-hidden className=\"relative block h-1.5 w-28 overflow-hidden rounded-full bg-muted\">\n      <motion.span\n        animate={{ scaleX: 1, opacity: live ? [0.5, 1, 0.5] : 1 }}\n        className={cn(\"absolute inset-y-0 block min-w-0.5 origin-left rounded-full\", tone)}\n        initial={{ scaleX: 0 }}\n        style={{ left: `${(start / total) * 100}%`, width: `${Math.max((ms / total) * 100, 2)}%` }}\n        transition={live ? { scaleX: spring, opacity: { duration: 1.2, repeat: Infinity, ease: \"easeInOut\" } } : spring}\n      />\n    </span>\n  );\n}\n\nfunction ToolEntry({ entry, total }: { entry: Extract<LogEntry, { kind: \"tool\" }>; total: number }) {\n  const [open, setOpen] = useState(false);\n  const meta = toolMeta[entry.call.kind];\n  const panelId = useId();\n  const failed = entry.status === \"failed\" || entry.status === \"denied\";\n  const span = entry.end !== undefined ? Math.max(entry.end - entry.at, 1) : entry.call.ms;\n  return (\n    <div className={cn(\"rounded-lg transition-colors duration-150\", open && \"bg-muted/48\")}>\n      <button\n        aria-controls={panelId}\n        aria-expanded={open}\n        className=\"grid w-full cursor-pointer grid-cols-[2.5rem_1rem_minmax(0,1fr)_auto] items-start gap-x-3 rounded-lg px-2 py-2 text-left outline-none transition-colors duration-150 hover:bg-accent/50 focus-visible:ring-2 focus-visible:ring-ring\"\n        onClick={() => setOpen((o) => !o)}\n        type=\"button\"\n      >\n        <time className=\"pt-px text-right font-mono text-[11px] text-muted-foreground tabular-nums\">{secs(entry.at)}</time>\n        <meta.icon className={cn(\"mt-px size-4\", failed ? \"text-destructive-foreground\" : meta.text)} />\n        <span className=\"min-w-0\">\n          <span className=\"flex items-center gap-2\">\n            <span className={cn(\"truncate font-medium font-mono text-xs\", failed && \"text-destructive-foreground\")}>{entry.call.name}</span>\n            {entry.retry && <span className=\"shrink-0 rounded bg-muted px-1.5 text-[11px] text-muted-foreground\">retry</span>}\n          </span>\n          <span className=\"mt-0.5 block truncate font-mono text-[11px] text-muted-foreground\">{formatArgs(entry.call.args)}</span>\n          <AnimatePresence initial={false}>\n            {entry.result && (\n              <motion.span\n                animate={{ opacity: 1, height: \"auto\" }}\n                className=\"block overflow-hidden\"\n                initial={{ opacity: 0, height: 0 }}\n                transition={spring}\n              >\n                <span className={cn(\"mt-1 block text-xs\", failed ? \"text-destructive-foreground\" : \"text-foreground\")}>{entry.result}</span>\n              </motion.span>\n            )}\n          </AnimatePresence>\n        </span>\n        <span className=\"flex items-center gap-3 pt-px\">\n          <span className=\"hidden @md:block\">\n            <Waterfall live={entry.status === \"running\"} ms={span} start={entry.at} tone={failed ? \"bg-destructive\" : meta.bar} total={total} />\n          </span>\n          <span className=\"flex w-14 items-center justify-end gap-1 text-muted-foreground text-xs tabular-nums\">\n            <AnimatePresence initial={false} mode=\"popLayout\">\n              {entry.status === \"running\" ? (\n                <motion.span animate={{ opacity: 1 }} className=\"flex items-center gap-1.5\" exit={{ opacity: 0 }} initial={{ opacity: 0 }} key=\"r\" transition={enter}>\n                  <span className=\"size-1.5 animate-pulse rounded-full bg-info motion-reduce:animate-none\" />\n                  running\n                </motion.span>\n              ) : entry.status === \"denied\" ? (\n                <motion.span animate={{ opacity: 1 }} className=\"flex items-center gap-1 text-destructive-foreground\" initial={{ opacity: 0 }} key=\"x\" transition={enter}>\n                  <BanIcon className=\"size-3\" />\n                  blocked\n                </motion.span>\n              ) : entry.status === \"failed\" ? (\n                <motion.span animate={{ opacity: 1 }} className=\"flex items-center gap-1 text-destructive-foreground\" initial={{ opacity: 0 }} key=\"f\" transition={enter}>\n                  <TriangleAlertIcon className=\"size-3\" />\n                  failed\n                </motion.span>\n              ) : (\n                <motion.span animate={{ opacity: 1 }} initial={{ opacity: 0 }} key=\"d\" transition={enter}>\n                  {secs(entry.call.ms)}\n                </motion.span>\n              )}\n            </AnimatePresence>\n          </span>\n          <ChevronDownIcon className={cn(\"size-3.5 shrink-0 text-muted-foreground transition-transform duration-200\", open && \"rotate-180\")} />\n        </span>\n      </button>\n      <AnimatePresence initial={false}>\n        {open && (\n          <motion.div\n            animate={{ height: \"auto\", opacity: 1 }}\n            className=\"overflow-hidden\"\n            exit={{ height: 0, opacity: 0 }}\n            id={panelId}\n            initial={{ height: 0, opacity: 0 }}\n            transition={spring}\n          >\n            <div className=\"ms-[4.75rem] me-2 mb-2 grid gap-2 rounded-lg border bg-background p-3 font-mono text-xs dark:bg-input/24\">\n              <div className=\"flex items-center gap-1.5 text-muted-foreground\">\n                <BracesIcon className=\"size-3\" />\n                arguments\n              </div>\n              <pre className=\"overflow-x-auto whitespace-pre text-foreground\">{JSON.stringify(entry.call.args, null, 2)}</pre>\n              <div className=\"flex flex-wrap gap-x-4 gap-y-1 border-t pt-2 text-muted-foreground\">\n                <span>{entry.call.tokens.toLocaleString(\"en-US\")} tokens</span>\n                <span>{entry.call.ms} ms</span>\n                <span>started at {secs(entry.at)}</span>\n              </div>\n            </div>\n          </motion.div>\n        )}\n      </AnimatePresence>\n    </div>\n  );\n}\n\nfunction CountdownRing({ value, total }: { value: number; total: number }) {\n  const c = 2 * Math.PI * 9;\n  return (\n    <span className=\"relative flex size-7 shrink-0 items-center justify-center\">\n      <svg aria-hidden className=\"absolute inset-0 -rotate-90\" viewBox=\"0 0 24 24\">\n        <circle className=\"stroke-warning/20\" cx=\"12\" cy=\"12\" fill=\"none\" r=\"9\" strokeWidth=\"2.5\" />\n        <motion.circle\n          animate={{ strokeDashoffset: c * (1 - value / total) }}\n          className=\"stroke-warning\"\n          cx=\"12\"\n          cy=\"12\"\n          fill=\"none\"\n          r=\"9\"\n          strokeDasharray={c}\n          strokeLinecap=\"round\"\n          strokeWidth=\"2.5\"\n          transition={{ duration: 0.9, ease: \"linear\" }}\n        />\n      </svg>\n      <span className=\"font-medium text-[10px] tabular-nums\">{value}</span>\n    </span>\n  );\n}\n\nfunction ApprovalCard({\n  approval,\n  accounts,\n  selected,\n  onToggle,\n  countdown,\n  autoTotal,\n  onApprove,\n  onDeny,\n}: {\n  approval: NonNullable<RunStep[\"approval\"]>;\n  accounts: RunAccount[];\n  selected: string[];\n  onToggle: (email: string) => void;\n  countdown: number | null;\n  autoTotal: number;\n  onApprove: () => void;\n  onDeny: () => void;\n}) {\n  const [all, setAll] = useState(false);\n  const shown = all ? accounts : accounts.slice(0, 4);\n  return (\n    <motion.section\n      animate={{ opacity: 1, y: 0, scale: 1 }}\n      aria-label=\"Approval needed\"\n      className=\"mx-4 mt-4 shrink-0 rounded-2xl border border-warning/40 bg-warning/6 p-4\"\n      exit={{ opacity: 0, y: -6, scale: 0.98 }}\n      initial={{ opacity: 0, y: -6, scale: 0.98 }}\n      layout\n      transition={{ ...enter, layout: spring }}\n    >\n      <div className=\"flex items-start gap-3\">\n        <span className=\"flex size-8 shrink-0 items-center justify-center rounded-lg bg-warning/16 text-warning-foreground\">\n          <ShieldAlertIcon className=\"size-4\" />\n        </span>\n        <div className=\"min-w-0 flex-1\">\n          <h3 className=\"text-balance font-medium\">\n            {approval.title} <span className=\"text-muted-foreground tabular-nums\">({selected.length})</span>\n          </h3>\n          <p className=\"mt-0.5 text-pretty text-muted-foreground text-xs\">{approval.description}</p>\n        </div>\n        {countdown !== null && <CountdownRing total={autoTotal} value={countdown} />}\n      </div>\n\n      <ul className=\"mt-3 grid max-h-52 gap-1 overflow-y-auto @md:grid-cols-2\">\n        <AnimatePresence initial={false}>\n          {shown.map((a) => {\n            const on = selected.includes(a.email);\n            return (\n              <motion.li\n                animate={{ opacity: 1, height: \"auto\" }}\n                exit={{ opacity: 0, height: 0 }}\n                initial={{ opacity: 0, height: 0 }}\n                key={a.email}\n                transition={spring}\n              >\n                <label\n                  className={cn(\n                    \"flex cursor-pointer items-center gap-2.5 rounded-lg px-2 py-1.5 transition-colors hover:bg-warning/8\",\n                    !on && \"opacity-56\",\n                  )}\n                >\n                  <Checkbox checked={on} onCheckedChange={() => onToggle(a.email)} />\n                  <span className=\"min-w-0 flex-1\">\n                    <span className={cn(\"block truncate font-medium text-xs\", !on && \"line-through\")}>{a.contact}</span>\n                    <span className=\"block truncate text-muted-foreground text-xs\">{a.company}</span>\n                  </span>\n                  <span className=\"text-muted-foreground text-xs tabular-nums\">{a.score.toFixed(2)}</span>\n                </label>\n              </motion.li>\n            );\n          })}\n        </AnimatePresence>\n      </ul>\n      {accounts.length > 4 && (\n        <button\n          className=\"mt-1 inline-flex h-8 cursor-pointer items-center rounded-md px-2 text-muted-foreground text-xs underline-offset-2 outline-none hover:text-foreground hover:underline focus-visible:ring-2 focus-visible:ring-ring\"\n          onClick={() => setAll((v) => !v)}\n          type=\"button\"\n        >\n          {all ? \"Show fewer\" : `Show all ${accounts.length}`}\n        </button>\n      )}\n\n      <div className=\"mt-3 flex flex-wrap items-center gap-2\">\n        <Button className={press} disabled={selected.length === 0} onClick={onApprove} size=\"sm\">\n          <SendIcon />\n          <span>\n            Approve &amp; send <span className=\"tabular-nums\">{selected.length}</span>\n          </span>\n        </Button>\n        <Button className={press} onClick={onDeny} size=\"sm\" variant=\"outline\">\n          Deny\n        </Button>\n        <span className=\"text-pretty text-muted-foreground text-xs tabular-nums\">\n          {countdown !== null ? `Demo auto-approves in ${countdown}s · any change pauses it` : \"Waiting for you\"}\n        </span>\n      </div>\n    </motion.section>\n  );\n}\n\nfunction FailureCard({\n  step,\n  stepTitle,\n  toolName,\n  message,\n  onRetry,\n  onCancel,\n}: {\n  step: number;\n  stepTitle: string;\n  toolName?: string;\n  message: string;\n  onRetry: () => void;\n  onCancel: () => void;\n}) {\n  return (\n    <motion.section\n      animate={{ opacity: 1, y: 0, scale: 1 }}\n      aria-label=\"Run failed\"\n      className=\"mx-4 mt-4 shrink-0 rounded-2xl border border-destructive/32 bg-destructive/4 p-4\"\n      exit={{ opacity: 0, y: -6, scale: 0.98 }}\n      initial={{ opacity: 0, y: -6, scale: 0.98 }}\n      layout\n      role=\"alert\"\n      transition={{ ...enter, layout: spring }}\n    >\n      <div className=\"flex items-start gap-3\">\n        <span className=\"flex size-8 shrink-0 items-center justify-center rounded-lg bg-destructive/12 text-destructive-foreground\">\n          <TriangleAlertIcon className=\"size-4\" />\n        </span>\n        <div className=\"min-w-0 flex-1\">\n          <h3 className=\"text-balance font-medium\">\n            Step {step + 1} failed: {stepTitle}\n          </h3>\n          <p className=\"mt-0.5 text-pretty text-muted-foreground text-xs\">\n            {toolName && <span className=\"font-mono\">{toolName}</span>}\n            {toolName && \" failed: \"}\n            <span className=\"text-destructive-foreground\">{message}</span>. Nothing after this step has run.\n          </p>\n        </div>\n      </div>\n      <div className=\"mt-3 flex flex-wrap items-center gap-2 ps-11\">\n        <Button className={press} onClick={onRetry} size=\"sm\">\n          <RotateCcwIcon />\n          Retry step\n        </Button>\n        <Button className={press} onClick={onCancel} size=\"sm\" variant=\"outline\">\n          Cancel run\n        </Button>\n      </div>\n    </motion.section>\n  );\n}\n\nfunction ActivityLog({ log, steps, total }: { log: LogEntry[]; steps: RunStep[]; total: number }) {\n  return (\n    <ol className=\"flex flex-col\">\n      <AnimatePresence initial={false}>\n        {log.map((e, i) => {\n          const first = i === 0 || log[i - 1].step !== e.step;\n          return (\n            <motion.li\n              animate={{ opacity: 1, y: 0 }}\n              initial={{ opacity: 0, y: 4 }}\n              key={e.id}\n              layout=\"position\"\n              transition={{ ...enter, layout: spring }}\n            >\n              {first && (\n                <div className={cn(\"flex items-center gap-2 px-2 pb-1 text-muted-foreground text-xs\", i === 0 ? \"pt-0\" : \"pt-4\")}>\n                  <span className=\"flex size-4 items-center justify-center rounded bg-muted font-medium text-[10px] tabular-nums\">{e.step + 1}</span>\n                  <span className=\"truncate font-medium\">{steps[e.step]?.title}</span>\n                </div>\n              )}\n              {e.kind === \"tool\" ? (\n                <ToolEntry entry={e} total={total} />\n              ) : (\n                <div className=\"grid grid-cols-[2.5rem_1rem_minmax(0,1fr)] items-start gap-x-3 px-2 py-2 text-xs\">\n                  <time className=\"pt-px text-right font-mono text-[11px] text-muted-foreground tabular-nums\">{secs(e.at)}</time>\n                  {e.kind === \"thought\" ? (\n                    <>\n                      <SparklesIcon className=\"mt-px size-4 text-muted-foreground\" />\n                      <span className=\"text-pretty text-muted-foreground italic leading-relaxed\">{e.text}</span>\n                    </>\n                  ) : (\n                    <>\n                      {e.status === \"waiting\" ? (\n                        <HandIcon className=\"mt-px size-4 text-warning-foreground\" />\n                      ) : e.status === \"approved\" ? (\n                        <CheckIcon className=\"mt-px size-4 text-success-foreground\" />\n                      ) : (\n                        <BanIcon className=\"mt-px size-4 text-destructive-foreground\" />\n                      )}\n                      <span\n                        className={cn(\n                          \"pt-px\",\n                          e.status === \"waiting\" && \"font-medium text-warning-foreground\",\n                          e.status === \"approved\" && \"text-foreground\",\n                          e.status === \"denied\" && \"text-destructive-foreground\",\n                        )}\n                      >\n                        {e.status === \"waiting\"\n                          ? \"Paused for your approval\"\n                          : e.status === \"approved\"\n                            ? `Approved by you · ${e.count} recipients`\n                            : \"Denied by you · nothing sent\"}\n                      </span>\n                    </>\n                  )}\n                </div>\n              )}\n            </motion.li>\n          );\n        })}\n      </AnimatePresence>\n    </ol>\n  );\n}\n\nfunction TraceStrip({\n  log,\n  total,\n  head,\n  next,\n  duration,\n}: {\n  log: LogEntry[];\n  total: number;\n  head: number;\n  next: number;\n  duration: number;\n}) {\n  const reduce = useReducedMotion();\n  const tools = log.filter((e) => e.kind === \"tool\") as Extract<LogEntry, { kind: \"tool\" }>[];\n  const marks = log.filter((e) => e.kind !== \"tool\");\n  const target = Math.min(next / total, 1);\n  return (\n    <div className=\"flex items-center gap-3 border-b px-4 py-2.5\">\n      <span className=\"hidden w-14 shrink-0 font-medium text-muted-foreground text-xs @md:block\">Timeline</span>\n      <div className=\"relative h-5 min-w-0 flex-1\">\n        <div className=\"absolute inset-x-0 top-1/2 h-px -translate-y-1/2 bg-border\" />\n        <motion.div\n          animate={{ scaleX: target }}\n          className=\"absolute inset-y-0 left-0 w-full origin-left rounded-sm bg-foreground/[0.04] dark:bg-foreground/[0.06]\"\n          initial={false}\n          transition={reduce ? { duration: 0 } : { duration, ease: \"linear\" }}\n        />\n        {tools.map((e) => {\n          const meta = toolMeta[e.call.kind];\n          const failed = e.status === \"failed\" || e.status === \"denied\";\n          const span = e.end !== undefined ? Math.max(e.end - e.at, 1) : e.call.ms;\n          return (\n            <motion.span\n              animate={{ opacity: 1, scaleY: 1 }}\n              className={cn(\"absolute top-1/2 h-2.5 -translate-y-1/2 rounded-[calc(var(--radius)*0.3)]\", failed ? \"bg-destructive\" : meta.bar, e.status === \"running\" && \"animate-pulse motion-reduce:animate-none\")}\n              initial={{ opacity: 0, scaleY: 0.4 }}\n              key={e.id}\n              style={{ left: `${(e.at / total) * 100}%`, width: `max(3px, ${(span / total) * 100}%)` }}\n              title={`${e.call.name} · ${secs(span)}`}\n              transition={enter}\n            />\n          );\n        })}\n        {marks.map((e) => (\n          <span\n            className={cn(\n              \"absolute top-1/2 size-1.5 -translate-x-1/2 -translate-y-1/2 rounded-full\",\n              e.kind === \"approval\" ? \"bg-warning\" : \"bg-muted-foreground/56\",\n            )}\n            key={e.id}\n            style={{ left: `${(e.at / total) * 100}%` }}\n          />\n        ))}\n        <motion.div\n          animate={{ x: `${target * 100}%` }}\n          aria-hidden\n          className=\"pointer-events-none absolute inset-0\"\n          initial={false}\n          transition={reduce ? { duration: 0 } : { duration, ease: \"linear\" }}\n        >\n          <span className=\"absolute inset-y-0 left-0 w-px bg-foreground/48\" />\n        </motion.div>\n      </div>\n      <span className=\"shrink-0 whitespace-nowrap text-right font-mono text-[11px] text-muted-foreground tabular-nums\">\n        {secs(head)} / {secs(total)}\n      </span>\n    </div>\n  );\n}\n\nfunction DraftOutput({\n  accounts,\n  email,\n  rows,\n  words,\n  sendState,\n}: {\n  accounts: RunAccount[];\n  email: RunEmail;\n  rows: number;\n  words: number;\n  sendState: \"drafting\" | \"ready\" | \"sent\" | \"held\";\n}) {\n  const allWords = email.body.split(\" \");\n  const streaming = words > 0 && words < allWords.length;\n  const visibleRows = accounts.slice(0, Math.min(rows, 5));\n  const [copied, setCopied] = useState(false);\n  useEffect(() => {\n    if (!copied) return;\n    const t = setTimeout(() => setCopied(false), 1400);\n    return () => clearTimeout(t);\n  }, [copied]);\n\n  const badge = {\n    drafting: <Badge variant=\"info\">Drafting</Badge>,\n    ready: <Badge variant=\"warning\">Ready for review</Badge>,\n    sent: <Badge variant=\"success\">Sent</Badge>,\n    held: <Badge variant=\"secondary\">Kept as draft</Badge>,\n  }[sendState];\n\n  return (\n    <div className=\"rounded-2xl border bg-card\">\n      <div className=\"flex items-center gap-3 border-b p-4\">\n        <span className=\"flex size-8 items-center justify-center rounded-lg bg-orange-500/12 text-orange-700 dark:bg-orange-400/14 dark:text-orange-300\">\n          <FileTextIcon className=\"size-4\" />\n        </span>\n        <div className=\"min-w-0 flex-1\">\n          <div className=\"truncate font-medium\">Q3 renewal outreach</div>\n          <div className=\"text-muted-foreground text-xs tabular-nums\">{rows > 0 ? `${accounts.length} accounts · draft 1 of ${accounts.length}` : \"Waiting for data\"}</div>\n        </div>\n        <AnimatePresence initial={false} mode=\"popLayout\">\n          <motion.span\n            animate={{ scale: 1, opacity: 1 }}\n            exit={{ scale: 0.95, opacity: 0 }}\n            initial={{ scale: 0.95, opacity: 0 }}\n            key={sendState}\n            transition={enter}\n          >\n            {badge}\n          </motion.span>\n        </AnimatePresence>\n      </div>\n\n      <div className=\"p-4\">\n        <h4 className=\"mb-2 font-medium text-muted-foreground text-xs\">Flagged accounts</h4>\n        <div className=\"rounded-xl border\">\n          {rows === 0\n            ? [0, 1, 2].map((i) => (\n                <div className=\"flex items-center gap-3 border-b px-3 py-2.5 last:border-0\" key={i}>\n                  <Skeleton className=\"h-3 w-28\" />\n                  <Skeleton className=\"ms-auto h-1.5 w-16 rounded-full\" />\n                  <Skeleton className=\"h-3 w-8\" />\n                </div>\n              ))\n            : (\n              <AnimatePresence initial={false}>\n                {visibleRows.map((a) => (\n                  <motion.div\n                    animate={{ opacity: 1, x: 0 }}\n                    className=\"flex items-center gap-3 border-b px-3 py-2 last:border-0\"\n                    initial={{ opacity: 0, x: -6 }}\n                    key={a.email}\n                    transition={enter}\n                  >\n                    <span className=\"min-w-0 flex-1\">\n                      <span className=\"block truncate font-medium text-xs\">{a.company}</span>\n                      <span className=\"block truncate text-muted-foreground text-xs\">{a.contact}</span>\n                    </span>\n                    <span className=\"h-1.5 w-16 overflow-hidden rounded-full bg-muted\">\n                      <motion.span\n                        animate={{ scaleX: a.score }}\n                        className={cn(\"block h-full origin-left rounded-full\", a.score >= 0.75 ? \"bg-destructive\" : \"bg-warning\")}\n                        initial={{ scaleX: 0 }}\n                        transition={{ ...spring, delay: 0.1 }}\n                      />\n                    </span>\n                    <span className=\"w-8 text-right font-medium text-xs tabular-nums\">{a.score.toFixed(2)}</span>\n                    <span className=\"hidden w-11 text-right text-muted-foreground text-xs tabular-nums @md:block\">{a.arr}</span>\n                  </motion.div>\n                ))}\n              </AnimatePresence>\n            )}\n          {rows >= 5 && accounts.length > 5 && (\n            <div className=\"px-3 py-2 text-muted-foreground text-xs\">+{accounts.length - 5} more</div>\n          )}\n        </div>\n\n        <h4 className=\"mt-5 mb-2 font-medium text-muted-foreground text-xs\">Email draft</h4>\n        <div className=\"rounded-xl border p-3\">\n          <dl className=\"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 border-b pb-2.5 text-xs\">\n            <dt className=\"text-muted-foreground\">To</dt>\n            <dd className=\"truncate\">{words > 0 ? email.to : <Skeleton className=\"mt-0.5 h-3 w-40\" />}</dd>\n            <dt className=\"text-muted-foreground\">Subject</dt>\n            <dd className=\"truncate font-medium\">{words > 0 ? email.subject : <Skeleton className=\"mt-0.5 h-3 w-52\" />}</dd>\n          </dl>\n          <div className=\"mt-2.5 flex min-h-6 flex-wrap gap-1\">\n            {words === 0\n              ? email.highlights.map((h) => <Skeleton className=\"h-6 w-24 rounded-full\" key={h} />)\n              : email.highlights.map((h, i) => (\n                <motion.span\n                  animate={{ opacity: 1, scale: 1 }}\n                  className=\"rounded-full bg-info/10 px-2 py-0.5 text-info-foreground text-xs\"\n                  initial={{ opacity: 0, scale: 0.95 }}\n                  key={h}\n                  transition={{ ...enter, delay: 0.03 * i }}\n                >\n                  {h}\n                </motion.span>\n              ))}\n          </div>\n          <div className=\"mt-2.5 min-h-24 whitespace-pre-line text-sm/6\">\n            {words === 0 ? (\n              <div className=\"flex flex-col gap-2 pt-1\">\n                <Skeleton className=\"h-3 w-full\" />\n                <Skeleton className=\"h-3 w-11/12\" />\n                <Skeleton className=\"h-3 w-3/4\" />\n              </div>\n            ) : (\n              <>\n                {allWords.slice(0, words).join(\" \")}\n                {streaming && (\n                  <motion.span\n                    animate={{ opacity: [1, 0.2, 1] }}\n                    className=\"ms-0.5 inline-block h-4 w-1.5 translate-y-0.5 rounded-full bg-foreground/60\"\n                    transition={{ duration: 0.9, repeat: Infinity, ease: \"easeInOut\" }}\n                  />\n                )}\n              </>\n            )}\n          </div>\n        </div>\n        <div className=\"mt-3 flex gap-2\">\n          <Button\n            disabled={words < allWords.length}\n            onClick={() => {\n              navigator.clipboard?.writeText(email.body).catch(() => {});\n              setCopied(true);\n            }}\n            className={cn(press, \"min-w-22\")}\n            size=\"sm\"\n            variant=\"outline\"\n          >\n            {copied ? <CheckIcon /> : <CopyIcon />}\n            {copied ? \"Copied\" : \"Copy\"}\n          </Button>\n          <Button className={press} disabled={words < allWords.length} size=\"sm\" variant=\"ghost\">\n            Open all {accounts.length} drafts\n          </Button>\n        </div>\n      </div>\n    </div>\n  );\n}\n\nexport function RunReplay({\n  agentName = \"Renewal Scout\",\n  runId = \"run_8f3k21\",\n  task = \"Find Q3 renewals at risk and draft outreach for each account owner.\",\n  model = \"relay-2-large\",\n  steps = defaultSteps,\n  accounts = defaultAccounts,\n  email = defaultEmail,\n  autoApproveAfter = 12,\n  speed = 1,\n  className,\n}: RunReplayProps) {\n  const [state, dispatch] = useReducer(reducer, steps.length, initState);\n  const [paused, setPaused] = useState(false);\n  const [elapsed, setElapsed] = useState(0);\n  const [tab, setTab] = useState<\"activity\" | \"draft\">(\"activity\");\n  const [selected, setSelected] = useState<string[]>(() => accounts.map((a) => a.email));\n  const [countdown, setCountdown] = useState<number | null>(null);\n  const [seenDraft, setSeenDraft] = useState(0);\n  const [planOpen, setPlanOpen] = useState(false);\n  const logRef = useRef<HTMLDivElement>(null);\n  const tabsId = useId();\n\n  const wordCount = useMemo(() => email.body.split(\" \").length, [email.body]);\n  const rowCount = Math.min(accounts.length, 5);\n  const events = useMemo(\n    () => buildEvents(steps, rowCount, wordCount, state.decision, state.retried),\n    [steps, rowCount, wordCount, state.decision, state.retried],\n  );\n\n  const offsets = useMemo(() => {\n    let t = 0;\n    return events.map((e) => (t += e.d));\n  }, [events]);\n  const total = useMemo(\n    () => buildEvents(steps, rowCount, wordCount, { approve: true, count: accounts.length }, true).reduce((n, e) => n + e.d, 0),\n    [steps, rowCount, wordCount, accounts.length],\n  );\n\n  const halted = state.failure !== null;\n\n  useEffect(() => {\n    if (paused || state.awaiting || state.finished || halted) return;\n    const ev = events[state.cursor];\n    if (!ev) return;\n    const t = setTimeout(() => dispatch({ type: \"ev\", ev, at: offsets[state.cursor] }), ev.d / speed);\n    return () => clearTimeout(t);\n  }, [events, offsets, state.cursor, state.awaiting, state.finished, halted, paused, speed]);\n\n  useEffect(() => {\n    if (paused || state.finished || halted) return;\n    const t = setInterval(() => setElapsed((s) => s + 1), 1000);\n    return () => clearInterval(t);\n  }, [paused, state.finished, halted]);\n\n  useEffect(() => {\n    if (state.awaiting && autoApproveAfter > 0) setCountdown(autoApproveAfter);\n    if (!state.awaiting) setCountdown(null);\n  }, [state.awaiting, autoApproveAfter]);\n\n  useEffect(() => {\n    if (countdown === null || paused) return;\n    if (countdown <= 0) {\n      dispatch({ type: \"decide\", approve: true, count: selected.length });\n      return;\n    }\n    const t = setTimeout(() => setCountdown((c) => (c === null ? c : c - 1)), 1000);\n    return () => clearTimeout(t);\n  }, [countdown, paused, selected.length]);\n\n  useEffect(() => {\n    const el = logRef.current;\n    if (!el || el.scrollHeight <= el.clientHeight) return;\n    el.scrollTo({ top: el.scrollHeight, behavior: \"smooth\" });\n  }, [state.log.length, state.awaiting, halted]);\n\n  useEffect(() => {\n    if (tab === \"draft\") setSeenDraft(state.rows + state.words);\n  }, [tab, state.rows, state.words]);\n\n  const replay = () => {\n    dispatch({ type: \"reset\", steps: steps.length });\n    setElapsed(0);\n    setPaused(false);\n    setSelected(accounts.map((a) => a.email));\n  };\n\n  const approvalStep = state.awaiting ? steps[state.awaiting.step]?.approval : undefined;\n  const doneCount = state.steps.filter((s) => s === \"done\" || s === \"skipped\").length;\n  const toolCalls = state.log.filter((e) => e.kind === \"tool\").length;\n  const liveStep = state.steps.findIndex((s) => s === \"running\" || s === \"waiting\" || s === \"failed\");\n  const lastTouched = state.steps.findLastIndex((s) => s !== \"pending\");\n  const activeStep = liveStep >= 0 ? liveStep : Math.max(lastTouched, 0);\n  const failedStep = state.failure ? steps[state.failure.step] : undefined;\n  const failedCall = state.failure ? state.log.find((e) => e.id === state.failure?.id) : undefined;\n\n  const status: { label: string; tone: Tone; live: boolean } = state.cancelled\n    ? { label: \"Cancelled\", tone: \"muted\", live: false }\n    : halted\n      ? { label: \"Failed\", tone: \"destructive\", live: false }\n    : state.finished\n      ? { label: \"Completed\", tone: \"success\", live: false }\n      : state.awaiting\n        ? { label: \"Needs approval\", tone: \"warning\", live: true }\n        : paused\n          ? { label: \"Paused\", tone: \"muted\", live: false }\n          : { label: \"Running\", tone: \"info\", live: true };\n  const cancel = () => dispatch({ type: \"cancel\" });\n\n  const emailStep = steps.findIndex((s) => s.approval);\n  const sendState: \"drafting\" | \"ready\" | \"sent\" | \"held\" =\n    state.decision?.approve && state.steps[emailStep] === \"done\"\n      ? \"sent\"\n      : state.decision && !state.decision.approve\n        ? \"held\"\n        : state.words >= wordCount\n          ? \"ready\"\n          : \"drafting\";\n\n  const head = state.cursor > 0 ? (offsets[state.cursor - 1] ?? 0) : 0;\n  const moving = !paused && !state.awaiting && !state.finished && !halted && state.cursor < events.length;\n\n  const draftFresh = tab !== \"draft\" && state.rows + state.words > seenDraft;\n  const mmss = `${String(Math.floor(elapsed / 60)).padStart(2, \"0\")}:${String(elapsed % 60).padStart(2, \"0\")}`;\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <div\n        className={cn(\n          \"@container relative isolate flex h-[760px] w-full flex-col overflow-hidden bg-background text-foreground text-sm\",\n          className,\n        )}\n      >\n        <header className=\"flex shrink-0 flex-wrap items-center gap-x-3 gap-y-2 border-b px-4 py-2.5\">\n          <span className=\"flex size-8 shrink-0 items-center justify-center rounded-lg border bg-card text-foreground shadow-xs/5\">\n            <BotIcon className=\"size-4\" />\n          </span>\n          <div className=\"min-w-48 flex-1\">\n            <div className=\"flex items-center gap-2\">\n              <h2 className=\"truncate font-medium\">{agentName}</h2>\n              <span className=\"hidden truncate rounded-md bg-muted px-1.5 font-mono text-[11px] text-muted-foreground @md:inline\">{runId}</span>\n            </div>\n            <p className=\"truncate text-muted-foreground text-xs\">{task}</p>\n          </div>\n          <div className=\"ms-auto flex items-center gap-2\">\n            <span\n              aria-live=\"polite\"\n              className=\"inline-flex h-7 items-center gap-1.5 rounded-full border bg-card ps-2 pe-2.5 font-medium text-xs\"\n            >\n              <LiveDot live={status.live} tone={status.tone} />\n              <AnimatePresence initial={false} mode=\"wait\">\n                <motion.span\n                  animate={{ opacity: 1, y: 0 }}\n                  exit={{ opacity: 0, y: -6 }}\n                  initial={{ opacity: 0, y: 6 }}\n                  key={status.label}\n                  transition={enter}\n                >\n                  {status.label}\n                </motion.span>\n              </AnimatePresence>\n            </span>\n            <time className=\"w-10 text-center text-muted-foreground text-xs tabular-nums\">{mmss}</time>\n            {state.finished ? (\n              <Button className={press} onClick={replay} size=\"sm\" variant=\"outline\">\n                <RotateCcwIcon />\n                Replay\n              </Button>\n            ) : (\n              <Button\n                aria-label={paused ? \"Resume run\" : \"Pause run\"}\n                className={press}\n                disabled={halted}\n                onClick={() => setPaused((p) => !p)}\n                size=\"icon-sm\"\n                variant=\"outline\"\n              >\n                {paused ? <PlayIcon /> : <PauseIcon />}\n              </Button>\n            )}\n            <Menu>\n              <MenuTrigger render={<Button aria-label=\"Run options\" className={press} size=\"icon-sm\" variant=\"ghost\" />}>\n                <EllipsisIcon />\n              </MenuTrigger>\n              <MenuPopup align=\"end\">\n                <MenuItem>\n                  <LinkIcon />\n                  Copy run link\n                </MenuItem>\n                <MenuItem>\n                  <BracesIcon />\n                  Export trace as JSON\n                </MenuItem>\n                <MenuSeparator />\n                <MenuItem disabled={state.finished} onClick={cancel} variant=\"destructive\">\n                  <BanIcon />\n                  Cancel run\n                </MenuItem>\n              </MenuPopup>\n            </Menu>\n          </div>\n        </header>\n\n        <TraceStrip\n          duration={moving ? (events[state.cursor]?.d ?? 0) / speed / 1000 : 0.2}\n          head={head}\n          log={state.log}\n          next={moving ? (offsets[state.cursor] ?? head) : head}\n          total={total}\n        />\n\n        <div className=\"grid min-h-0 flex-1 auto-rows-max grid-cols-[minmax(0,1fr)] overflow-y-auto @3xl:auto-rows-auto @3xl:grid-cols-[17.5rem_minmax(0,1fr)] @3xl:overflow-hidden @6xl:grid-cols-[17.5rem_minmax(0,1fr)_minmax(0,26rem)]\">\n          <aside className=\"flex flex-col gap-4 border-b p-4 @3xl:overflow-y-auto @3xl:border-e @3xl:border-b-0\">\n            <div>\n              <div className=\"mb-2 flex items-baseline justify-between\">\n                <h3 className=\"font-medium\">Plan</h3>\n                <span className=\"text-muted-foreground text-xs tabular-nums\">\n                  {doneCount} of {steps.length}\n                </span>\n              </div>\n              <div className=\"h-1 overflow-hidden rounded-full bg-muted\">\n                <motion.div\n                  animate={{ scaleX: doneCount / steps.length }}\n                  className=\"h-full origin-left rounded-full bg-success\"\n                  initial={false}\n                  transition={spring}\n                />\n              </div>\n            </div>\n            <ol className=\"flex flex-col\">\n              {steps.map((s, i) => {\n                const st = state.steps[i];\n                const calls = state.log.filter((e) => e.kind === \"tool\" && e.step === i) as Extract<LogEntry, { kind: \"tool\" }>[];\n                const secs = calls.reduce((n, c) => n + (c.status === \"done\" ? c.call.ms : 0), 0) / 1000;\n                const last = i === steps.length - 1;\n                const collapsed = !planOpen && i !== activeStep;\n                return (\n                  <li\n                    className={cn(\"relative gap-3 pb-4 last:pb-0 @3xl:flex\", collapsed ? \"hidden\" : \"flex\", !planOpen && \"@max-3xl:pb-0\")}\n                    key={s.title}\n                  >\n                    {!last && (\n                      <span\n                        aria-hidden\n                        className={cn(\"absolute top-6 bottom-1 left-[9px] w-0.5 overflow-hidden rounded-full bg-border\", !planOpen && \"hidden @3xl:block\")}\n                      >\n                        <motion.span\n                          animate={{ scaleY: st === \"done\" || st === \"skipped\" ? 1 : 0 }}\n                          className=\"block h-full origin-top bg-success\"\n                          initial={false}\n                          transition={spring}\n                        />\n                      </span>\n                    )}\n                    <StepNode status={st} />\n                    <div className=\"min-w-0 flex-1\">\n                      <div\n                        className={cn(\n                          \"font-medium transition-colors\",\n                          st === \"pending\" && \"text-muted-foreground\",\n                          st === \"skipped\" && \"text-muted-foreground line-through\",\n                          st === \"failed\" && \"text-destructive-foreground\",\n                        )}\n                      >\n                        {s.title}\n                      </div>\n                      <div className=\"text-muted-foreground text-xs tabular-nums\">\n                        {st === \"running\"\n                          ? calls.length > 0\n                            ? `Calling ${calls.at(-1)?.call.name}`\n                            : \"Thinking…\"\n                          : st === \"waiting\"\n                            ? \"Waiting for your approval\"\n                            : st === \"failed\"\n                              ? \"Failed · waiting for retry\"\n                            : st === \"done\"\n                              ? calls.length\n                                ? `${calls.length} tool call${calls.length > 1 ? \"s\" : \"\"} · ${secs.toFixed(1)}s`\n                                : \"Done\"\n                              : st === \"skipped\"\n                                ? \"Skipped\"\n                                : s.approval\n                                  ? \"Needs approval\"\n                                  : \"Queued\"}\n                      </div>\n                    </div>\n                  </li>\n                );\n              })}\n            </ol>\n            <button\n              aria-expanded={planOpen}\n              className=\"-my-2 -ms-2 flex h-8 cursor-pointer items-center gap-1 self-start rounded-md px-2 text-muted-foreground text-xs outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring @3xl:hidden\"\n              onClick={() => setPlanOpen((o) => !o)}\n              type=\"button\"\n            >\n              {planOpen ? \"Show current step\" : `Show all ${steps.length} steps`}\n              <ChevronDownIcon className={cn(\"size-3.5 transition-transform\", planOpen && \"rotate-180\")} />\n            </button>\n            <dl className=\"grid grid-cols-3 gap-x-3 gap-y-1.5 border-t pt-3 text-xs @3xl:mt-auto @3xl:grid-cols-1\">\n              {[\n                { label: \"Tokens\", node: <Rolling format={(n) => Math.round(n).toLocaleString(\"en-US\")} value={state.tokens} /> },\n                { label: \"Cost\", node: <Rolling format={(n) => `$${((n / 1000) * 0.006).toFixed(3)}`} value={state.tokens} /> },\n                { label: \"Tool calls\", node: <Rolling format={(n) => String(Math.round(n))} value={toolCalls} /> },\n                { label: \"Model\", node: <span className=\"font-mono text-[11px]\">{model}</span> },\n              ].map((s) => (\n                <div className={cn(\"flex min-w-0 flex-col gap-0.5 @3xl:flex-row @3xl:justify-between\", s.label === \"Model\" && \"hidden @3xl:flex\")} key={s.label}>\n                  <dt className=\"text-muted-foreground\">{s.label}</dt>\n                  <dd className=\"truncate font-medium tabular-nums\">{s.node}</dd>\n                </div>\n              ))}\n            </dl>\n          </aside>\n\n          <section className=\"flex min-h-0 flex-col @3xl:overflow-hidden\" aria-label=\"Run activity\">\n            <Tabs className=\"shrink-0 px-4 pt-4 @6xl:hidden\" onValueChange={(v) => setTab(v as \"activity\" | \"draft\")} value={tab}>\n              <TabsList>\n                <TabsTab aria-controls={`${tabsId}-activity`} value=\"activity\">\n                  Activity\n                  <span className=\"text-muted-foreground text-xs tabular-nums\">{state.log.length}</span>\n                </TabsTab>\n                <TabsTab aria-controls={`${tabsId}-draft`} value=\"draft\">\n                  Draft\n                  <AnimatePresence>\n                    {draftFresh && (\n                      <motion.span\n                        animate={{ opacity: 1, scale: 1 }}\n                        aria-label=\"new\"\n                        className=\"size-1.5 rounded-full bg-info\"\n                        exit={{ opacity: 0, scale: 0.9 }}\n                        initial={{ opacity: 0, scale: 0.9 }}\n                        transition={enter}\n                      />\n                    )}\n                  </AnimatePresence>\n                </TabsTab>\n              </TabsList>\n            </Tabs>\n\n            <AnimatePresence initial={false}>\n              {approvalStep && (\n                <ApprovalCard\n                  accounts={accounts}\n                  approval={approvalStep}\n                  autoTotal={autoApproveAfter}\n                  countdown={countdown}\n                  key=\"approval\"\n                  onApprove={() => dispatch({ type: \"decide\", approve: true, count: selected.length })}\n                  onDeny={() => dispatch({ type: \"decide\", approve: false, count: 0 })}\n                  onToggle={(email) => {\n                    setCountdown(null);\n                    setSelected((s) => (s.includes(email) ? s.filter((x) => x !== email) : [...s, email]));\n                  }}\n                  selected={selected}\n                />\n              )}\n              {state.failure && failedStep && (\n                <FailureCard\n                  key=\"failure\"\n                  message={state.failure.message}\n                  onCancel={cancel}\n                  onRetry={() => dispatch({ type: \"retry\" })}\n                  step={state.failure.step}\n                  stepTitle={failedStep.title}\n                  toolName={failedCall?.kind === \"tool\" ? failedCall.call.name : undefined}\n                />\n              )}\n            </AnimatePresence>\n            <div\n              className={cn(\n                \"flex min-h-0 flex-1 flex-col gap-3 p-4 @3xl:overflow-y-auto\",\n                approvalStep || halted\n                  ? \"@3xl:[mask-image:linear-gradient(to_bottom,transparent_0.75rem,black_2.75rem)]\"\n                  : \"@3xl:[mask-image:linear-gradient(to_bottom,transparent,black_1.25rem)]\",\n              )}\n              ref={logRef}\n            >\n              <div\n                className={cn(tab === \"activity\" ? \"block\" : \"hidden\", \"@6xl:block\")}\n                id={`${tabsId}-activity`}\n                role=\"tabpanel\"\n              >\n                <h3 className=\"mb-2 hidden font-medium @6xl:block\">Activity</h3>\n                {state.log.length === 0 ? (\n                  <div className=\"flex items-center gap-2 px-1 py-2 text-muted-foreground text-xs\">\n                    <span className=\"size-1.5 animate-pulse rounded-full bg-info motion-reduce:animate-none\" />\n                    Reading the task…\n                  </div>\n                ) : (\n                  <ActivityLog log={state.log} steps={steps} total={total} />\n                )}\n              </div>\n              <div className={cn(tab === \"draft\" ? \"block\" : \"hidden\", \"@6xl:hidden\")} id={`${tabsId}-draft`} role=\"tabpanel\">\n                <DraftOutput accounts={accounts} email={email} rows={state.rows} sendState={sendState} words={state.words} />\n              </div>\n            </div>\n          </section>\n\n          <section aria-label=\"Draft output\" className=\"hidden border-s p-4 @6xl:block @6xl:overflow-y-auto\">\n            <h3 className=\"mb-2 font-medium\">Output</h3>\n            <DraftOutput accounts={accounts} email={email} rows={state.rows} sendState={sendState} words={state.words} />\n          </section>\n        </div>\n      </div>\n    </MotionConfig>\n  );\n}\n"
    }
  ]
}