{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "run-02",
  "title": "Trace waterfall",
  "description": "Every call of a run on one time axis, nested by agent, where the bars grow behind a playhead that travels, with filters, search, a drag to zoom and the critical path.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/agent-run.json",
    "https://ui.ndekocode.dev/r/badge.json",
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/hatch.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/input.json",
    "https://ui.ndekocode.dev/r/json-view.json",
    "https://ui.ndekocode.dev/r/live-duration.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/motion-presets.json",
    "https://ui.ndekocode.dev/r/replay-button.json",
    "https://ui.ndekocode.dev/r/run-session.json",
    "https://ui.ndekocode.dev/r/segments.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/toggle.json",
    "https://ui.ndekocode.dev/r/use-kept-height.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/use-session.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/run/run-02.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\nimport { useEffect, useRef, useState } from 'react';\n\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { useSession } from '@/registry/ndeko/hooks/use-session';\nimport {\n  emptyRun,\n  seriesColorOf,\n  type AgentStatus,\n  type RunAgent,\n  type RunEvent,\n  type RunSnapshot,\n  type RunStatus,\n  type SeriesSlot,\n  type ToolCall,\n} from '@/registry/ndeko/lib/agent-run';\nimport { SearchIcon, XIcon, ZoomOutIcon } from '@/registry/ndeko/lib/icons';\nimport {\n  applyBatchAt,\n  batch,\n  reduceBatch,\n  restingOf,\n  type RunStep,\n} from '@/registry/ndeko/lib/run-session';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Fold, Swap } from '@/registry/ndeko/ui/chat-motion';\nimport { Input } from '@/registry/ndeko/ui/input';\nimport { Toggle } from '@/registry/ndeko/ui/toggle';\n\nimport { hatchOf } from '@/registry/ndeko/lib/hatch';\nimport { JsonView } from '@/registry/ndeko/ui/json-view';\nimport {\n  ClockGate,\n  LiveDuration,\n  useLiveNow,\n} from '@/registry/ndeko/ui/live-duration';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport {\n  fadePresence,\n  rowPresenceOf,\n} from '@/registry/ndeko/lib/motion-presets';\nimport { ReplayButton } from '@/registry/ndeko/ui/replay-button';\nimport {\n  EMAIL_INPUT,\n  EMAIL_OUTPUT,\n  PAGE_ERROR,\n  PAGE_INPUT,\n  PAGE_OUTPUT,\n  PLANNER,\n  RESEARCHER,\n  RUN_TITLE,\n  SCRIPT_INPUT,\n  SCRIPT_OUTPUT,\n  SEARCH_INPUT,\n  SEARCH_OUTPUT,\n  SHEET_INPUT,\n  SHEET_OUTPUT,\n  WRITER,\n} from './_parts/scenario';\nimport { Segments, type Segment } from '@/registry/ndeko/ui/segments';\n\ntype TraceKind = 'agent' | 'call';\n\ntype TraceStatus = 'queued' | 'running' | 'waiting' | 'done' | 'failed';\n\ntype TraceRow = {\n  id: string;\n  kind: TraceKind;\n  depth: number;\n  name: string;\n  label: string;\n  status: TraceStatus;\n  series: SeriesSlot;\n  agentName: string;\n  startedAt: number;\n  endedAt?: number;\n  model?: string;\n  input?: unknown;\n  output?: unknown;\n  error?: string;\n};\n\ntype TraceNode = {\n  row: TraceRow;\n  children: TraceNode[];\n};\n\ntype TimeWindow = {\n  from: number;\n  to: number;\n};\n\ntype Filter = 'all' | 'errors' | 'slow';\n\ntype Brush = {\n  startX: number;\n  currentX: number;\n};\n\n/** Where a bar starts and ends, in percent of the time window. */\ntype BarSpan = {\n  start: number;\n  end: number;\n};\n\ntype LabelSide = 'after' | 'before' | 'inside';\n\ntype Reframe = {\n  windowKey: string;\n  at: number | null;\n};\n\nconst FILTERS: Segment<Filter>[] = [\n  { value: 'all', label: 'All' },\n  { value: 'errors', label: 'Errors' },\n  { value: 'slow', label: 'Slow' },\n];\n\nconst FILTER_WORD: Record<Filter, string> = {\n  all: 'every call',\n  errors: 'errors',\n  slow: 'slow calls',\n};\n\nconst STATUS_WORD: Record<TraceStatus, string> = {\n  queued: 'queued',\n  running: 'running',\n  waiting: 'waiting on you',\n  done: 'done',\n  failed: 'failed',\n};\n\nconst RUN_STATUS_LOOK: Record<\n  RunStatus,\n  { label: string; variant: 'secondary' | 'success' | 'destructive' }\n> = {\n  idle: { label: 'Not started', variant: 'secondary' },\n  running: { label: 'Running', variant: 'secondary' },\n  waiting: { label: 'Waiting on you', variant: 'secondary' },\n  done: { label: 'Done', variant: 'success' },\n  failed: { label: 'Failed', variant: 'destructive' },\n  cancelled: { label: 'Stopped', variant: 'secondary' },\n};\n\nconst ORPHAN_SERIES: SeriesSlot = 1;\n\n/** Two dispatches in one tick can land a few milliseconds apart: one call ending and the next starting. */\nconst HANDOFF_SLACK_MS = 30;\n\nconst MIN_ZOOM_MS = 200;\n\nconst MIN_BRUSH_PX = 8;\n\nconst LIVE_MARGIN_MS = 1500;\n\nconst HORIZONS = [2000, 3000, 4000, 5000, 6000, 8000, 10000, 12000, 15000];\n\nconst TICK_STEPS = [\n  50, 100, 200, 250, 500, 1000, 2000, 2500, 5000, 10000, 15000, 30000, 60000,\n];\n\nconst MAX_TICKS = 5;\n\nconst INDENT_PX = 12;\n\n/**\n * A running bar and the playhead are drawn one step ahead and travel there at a constant speed, so\n * one transition plays per step. `GROW` below lasts exactly as long.\n */\nconst GROW_STEP_MS = 1000;\n\nconst MIN_BAR_PERCENT = 0.6;\n\nconst GROW =\n  'transition-transform duration-1000 ease-linear motion-reduce:transition-none';\n\nconst GLIDE =\n  'transition-transform duration-300 ease-(--ease-in-out-strong) motion-reduce:transition-none';\n\n/**\n * A bar is a clip that ends where the bar ends, holding a fill that starts where the bar starts.\n * Both move by transform and their offsets add up, so the bar keeps its corners, its ring and its\n * hatch while it grows.\n */\nconst BAR_CLIP = 'absolute inset-0 my-auto h-2.5 overflow-hidden rounded-[3px]';\n\nconst BAR_FILL = 'absolute inset-0 rounded-[3px]';\n\nconst LABEL_LANE: Record<LabelSide, string> = {\n  after: 'absolute inset-0 flex items-center justify-start ps-1.5',\n  before: 'absolute inset-0 flex items-center justify-end pe-1.5',\n  inside: 'absolute inset-0 flex items-center justify-end pe-1.5',\n};\n\n/**\n * A call that is running starts from nothing, so its bar is seen growing from the first frame. A\n * bar that arrives finished is drawn whole.\n */\nconst CLIP_BIRTH = 'starting:[transform:translateX(var(--bar-closed))]';\n\nconst FILL_BIRTH = 'starting:[transform:translateX(100%)]';\n\nconst LABEL_BIRTH = 'starting:[transform:translateX(var(--label-from))]';\n\nfunction agentStatusOf(status: AgentStatus): TraceStatus {\n  if (status === 'idle') {\n    return 'queued';\n  }\n  return status;\n}\n\nfunction agentRowOf(agent: RunAgent, depth: number): TraceRow | null {\n  if (agent.startedAt === undefined) {\n    return null;\n  }\n  return {\n    id: agent.id,\n    kind: 'agent',\n    depth,\n    name: agent.name,\n    label: agent.task ?? agent.name,\n    status: agentStatusOf(agent.status),\n    series: agent.series,\n    agentName: agent.name,\n    startedAt: agent.startedAt,\n    endedAt: agent.endedAt,\n    model: agent.model,\n  };\n}\n\nfunction callRowOf(\n  call: ToolCall,\n  depth: number,\n  series: SeriesSlot,\n  agentName: string\n): TraceRow | null {\n  if (call.startedAt === undefined) {\n    return null;\n  }\n  return {\n    id: call.id,\n    kind: 'call',\n    depth,\n    name: call.tool,\n    label: call.label,\n    status: call.status,\n    series,\n    agentName,\n    startedAt: call.startedAt,\n    endedAt: call.endedAt,\n    input: call.input,\n    output: call.output,\n    error: call.error,\n  };\n}\n\nfunction byStart(first: TraceNode, second: TraceNode) {\n  return first.row.startedAt - second.row.startedAt;\n}\n\nfunction nodeOfAgent(\n  agent: RunAgent,\n  depth: number,\n  run: RunSnapshot\n): TraceNode | null {\n  const row = agentRowOf(agent, depth);\n  if (!row) {\n    return null;\n  }\n  const childDepth = depth + 1;\n  const children: TraceNode[] = [];\n  for (const call of run.calls) {\n    if (call.agentId !== agent.id) {\n      continue;\n    }\n    const callRow = callRowOf(call, childDepth, agent.series, agent.name);\n    if (callRow) {\n      children.push({ row: callRow, children: [] });\n    }\n  }\n  for (const child of run.agents) {\n    if (child.parentId !== agent.id) {\n      continue;\n    }\n    const childNode = nodeOfAgent(child, childDepth, run);\n    if (childNode) {\n      children.push(childNode);\n    }\n  }\n  children.sort(byStart);\n  return { row, children };\n}\n\nfunction treeOf(run: RunSnapshot) {\n  const roots: TraceNode[] = [];\n  for (const agent of run.agents) {\n    if (agent.parentId !== undefined) {\n      continue;\n    }\n    const node = nodeOfAgent(agent, 0, run);\n    if (node) {\n      roots.push(node);\n    }\n  }\n  for (const call of run.calls) {\n    if (call.agentId !== undefined) {\n      continue;\n    }\n    const callRow = callRowOf(call, 0, ORPHAN_SERIES, 'Run');\n    if (callRow) {\n      roots.push({ row: callRow, children: [] });\n    }\n  }\n  roots.sort(byStart);\n  return roots;\n}\n\nfunction flattenInto(nodes: TraceNode[], rows: TraceRow[]) {\n  for (const node of nodes) {\n    rows.push(node.row);\n    flattenInto(node.children, rows);\n  }\n}\n\nfunction rowsOf(tree: TraceNode[]) {\n  const rows: TraceRow[] = [];\n  flattenInto(tree, rows);\n  return rows;\n}\n\nfunction endOf(row: TraceRow, now: number) {\n  if (row.endedAt !== undefined) {\n    return row.endedAt;\n  }\n  return Math.max(now, row.startedAt);\n}\n\nfunction durationOf(row: TraceRow, now: number) {\n  const end = endOf(row, now);\n  return end - row.startedAt;\n}\n\nfunction lastEndingBefore(nodes: TraceNode[], cursor: number, now: number) {\n  let best: TraceNode | undefined;\n  let bestEnd = -Infinity;\n  const limit = cursor + HANDOFF_SLACK_MS;\n  for (const node of nodes) {\n    const end = endOf(node.row, now);\n    const fits = end <= limit;\n    const isLater = end > bestEnd;\n    if (fits && isLater) {\n      best = node;\n      bestEnd = end;\n    }\n  }\n  return best;\n}\n\n/** Walks back from the end: the child that finished last, then the one that finished before it started, and so on. */\nfunction collectCritical(node: TraceNode, now: number, ids: Set<string>) {\n  ids.add(node.row.id);\n  const remaining = [...node.children];\n  let cursor = endOf(node.row, now);\n  let next = lastEndingBefore(remaining, cursor, now);\n  while (next) {\n    collectCritical(next, now, ids);\n    cursor = next.row.startedAt;\n    const taken = next;\n    const index = remaining.indexOf(taken);\n    remaining.splice(index, 1);\n    next = lastEndingBefore(remaining, cursor, now);\n  }\n}\n\nfunction criticalIdsOf(tree: TraceNode[], now: number) {\n  const ids = new Set<string>();\n  for (const root of tree) {\n    collectCritical(root, now, ids);\n  }\n  return ids;\n}\n\nfunction matchesFilter(\n  row: TraceRow,\n  filter: Filter,\n  slowAfterMs: number,\n  now: number\n) {\n  if (filter === 'errors') {\n    return row.status === 'failed';\n  }\n  if (filter === 'slow') {\n    const isCall = row.kind === 'call';\n    const isSlow = durationOf(row, now) >= slowAfterMs;\n    return isCall && isSlow;\n  }\n  return true;\n}\n\nfunction matchingRowsOf(\n  rows: TraceRow[],\n  filter: Filter,\n  slowAfterMs: number,\n  now: number\n) {\n  return rows.filter((row) => matchesFilter(row, filter, slowAfterMs, now));\n}\n\n/** How many rows a filter keeps at a given moment, counted from the run itself for the announcement. */\nfunction matchingCountOf(\n  run: RunSnapshot,\n  filter: Filter,\n  slowAfterMs: number,\n  now: number\n) {\n  const tree = treeOf(run);\n  const rows = rowsOf(tree);\n  const matching = matchingRowsOf(rows, filter, slowAfterMs, now);\n  return matching.length;\n}\n\nfunction matchesQuery(row: TraceRow, query: string) {\n  const needle = query.trim().toLowerCase();\n  if (needle === '') {\n    return true;\n  }\n  const inName = row.name.toLowerCase().includes(needle);\n  const inLabel = row.label.toLowerCase().includes(needle);\n  return inName || inLabel;\n}\n\nfunction steppedHorizonOf(elapsed: number) {\n  const needed = elapsed + LIVE_MARGIN_MS;\n  const horizon = HORIZONS.find((candidate) => candidate >= needed);\n  if (horizon !== undefined) {\n    return horizon;\n  }\n  const minutes = Math.ceil(needed / 60000);\n  return minutes * 60000;\n}\n\n/** The fixed window holds as long as the run fits in it: bars only grow, none of them moves. */\nfunction fixedHorizonOf(spent: number, windowMs: number | undefined) {\n  if (windowMs === undefined) {\n    return null;\n  }\n  if (spent > windowMs) {\n    return null;\n  }\n  return windowMs;\n}\n\nfunction horizonOf(\n  run: RunSnapshot,\n  now: number,\n  windowMs: number | undefined\n) {\n  if (run.startedAt === undefined) {\n    return windowMs ?? HORIZONS[0];\n  }\n  if (run.endedAt !== undefined) {\n    const total = run.endedAt - run.startedAt;\n    const fixed = fixedHorizonOf(total, windowMs);\n    if (fixed !== null) {\n      return fixed;\n    }\n    return Math.max(total, MIN_ZOOM_MS);\n  }\n  const elapsed = now - run.startedAt;\n  const fixed = fixedHorizonOf(elapsed, windowMs);\n  if (fixed !== null) {\n    return fixed;\n  }\n  return steppedHorizonOf(elapsed);\n}\n\nfunction tickStepOf(span: number) {\n  for (const step of TICK_STEPS) {\n    const count = span / step;\n    if (count <= MAX_TICKS) {\n      return step;\n    }\n  }\n  const minutes = Math.ceil(span / (MAX_TICKS * 60000));\n  return minutes * 60000;\n}\n\nfunction ticksOf(timeWindow: TimeWindow) {\n  const span = timeWindow.to - timeWindow.from;\n  const step = tickStepOf(span);\n  const firstIndex = Math.ceil(timeWindow.from / step);\n  const ticks: number[] = [];\n  for (let tick = firstIndex * step; tick <= timeWindow.to; tick += step) {\n    ticks.push(tick);\n  }\n  return ticks;\n}\n\nfunction tickLabelOf(milliseconds: number) {\n  if (milliseconds === 0) {\n    return '0';\n  }\n  if (milliseconds < 1000) {\n    return `${milliseconds}ms`;\n  }\n  const seconds = milliseconds / 1000;\n  const rounded = Number(seconds.toFixed(2));\n  return `${rounded}s`;\n}\n\nfunction percentOf(milliseconds: number, timeWindow: TimeWindow) {\n  const span = timeWindow.to - timeWindow.from;\n  const offset = milliseconds - timeWindow.from;\n  return (offset / span) * 100;\n}\n\nfunction tickAlignOf(left: number) {\n  if (left < 4) {\n    return 'translate-x-0';\n  }\n  if (left > 96) {\n    return '-translate-x-full';\n  }\n  return '-translate-x-1/2';\n}\n\nfunction clampWindow(timeWindow: TimeWindow, horizon: number): TimeWindow {\n  const span = timeWindow.to - timeWindow.from;\n  const boundedSpan = Math.min(span, horizon);\n  const latestFrom = horizon - boundedSpan;\n  const from = Math.min(Math.max(0, timeWindow.from), latestFrom);\n  return { from, to: from + boundedSpan };\n}\n\nfunction zoomedIn(timeWindow: TimeWindow, horizon: number) {\n  const span = timeWindow.to - timeWindow.from;\n  const center = timeWindow.from + span / 2;\n  const nextSpan = Math.max(MIN_ZOOM_MS, span / 2);\n  const half = nextSpan / 2;\n  return clampWindow({ from: center - half, to: center + half }, horizon);\n}\n\nfunction zoomedOut(timeWindow: TimeWindow, horizon: number) {\n  const span = timeWindow.to - timeWindow.from;\n  const nextSpan = span * 2;\n  if (nextSpan >= horizon) {\n    return null;\n  }\n  const center = timeWindow.from + span / 2;\n  const half = nextSpan / 2;\n  return clampWindow({ from: center - half, to: center + half }, horizon);\n}\n\nfunction panned(timeWindow: TimeWindow, direction: number, horizon: number) {\n  const span = timeWindow.to - timeWindow.from;\n  const shift = span * 0.2 * direction;\n  const moved = { from: timeWindow.from + shift, to: timeWindow.to + shift };\n  return clampWindow(moved, horizon);\n}\n\nfunction windowFromBrush(\n  brush: Brush,\n  width: number,\n  timeWindow: TimeWindow,\n  horizon: number\n) {\n  const span = timeWindow.to - timeWindow.from;\n  const startPx = Math.min(brush.startX, brush.currentX);\n  const endPx = Math.max(brush.startX, brush.currentX);\n  const from = timeWindow.from + (startPx / width) * span;\n  const to = timeWindow.from + (endPx / width) * span;\n  const center = (from + to) / 2;\n  const nextSpan = Math.max(MIN_ZOOM_MS, to - from);\n  const half = nextSpan / 2;\n  return clampWindow({ from: center - half, to: center + half }, horizon);\n}\n\nfunction panDirectionOf(key: string) {\n  if (key === 'ArrowLeft') {\n    return -1;\n  }\n  return 1;\n}\n\nfunction brushStyleOf(brush: Brush): React.CSSProperties {\n  const left = Math.min(brush.startX, brush.currentX);\n  const width = Math.abs(brush.currentX - brush.startX);\n  return { left, width };\n}\n\nfunction zoomMessageOf(timeWindow: TimeWindow) {\n  const from = tickLabelOf(Math.round(timeWindow.from));\n  const to = tickLabelOf(Math.round(timeWindow.to));\n  return `Zoomed to ${from} to ${to}`;\n}\n\nconst FAILED_TINT = 'color-mix(in oklab, var(--destructive) 12%, transparent)';\n\nconst FAILED_RING = 'color-mix(in oklab, var(--destructive) 50%, transparent)';\n\n/** The outline of a bar that has one: a failed call, or an agent, whose bar is a light tint. */\nfunction ringColorOf(row: TraceRow) {\n  if (row.status === 'failed') {\n    return FAILED_RING;\n  }\n  if (row.kind === 'agent') {\n    const series = seriesColorOf(row.series);\n    return `color-mix(in oklab, ${series} 45%, transparent)`;\n  }\n  return null;\n}\n\nfunction fillLookOf(row: TraceRow): React.CSSProperties {\n  const series = seriesColorOf(row.series);\n  if (row.status === 'failed') {\n    return {\n      backgroundColor: FAILED_TINT,\n      backgroundImage: hatchOf('var(--destructive)', 55),\n    };\n  }\n  if (row.kind === 'agent') {\n    return {\n      backgroundColor: `color-mix(in oklab, ${series} 18%, transparent)`,\n    };\n  }\n  return { backgroundColor: series };\n}\n\nfunction outlineOf(ring: string | null) {\n  if (ring === null) {\n    return undefined;\n  }\n  return `inset 0 0 0 var(--hairline) ${ring}`;\n}\n\n/** The fill is cut at the end of the bar, so the clip draws that side of the outline. */\nfunction endOutlineOf(ring: string | null) {\n  if (ring === null) {\n    return undefined;\n  }\n  return `inset calc(var(--hairline) * -1) 0 0 0 ${ring}`;\n}\n\n/** Without motion nothing travels, so nothing is drawn ahead of the present. */\nfunction leadOf(shouldReduceMotion: boolean | null) {\n  if (shouldReduceMotion) {\n    return 0;\n  }\n  return GROW_STEP_MS;\n}\n\n/** A running bar reaches one step past the present: it gets there as the step ends. */\nfunction reachOf(row: TraceRow, now: number, lead: number) {\n  if (row.endedAt !== undefined) {\n    return row.endedAt;\n  }\n  const present = Math.max(now, row.startedAt);\n  if (row.status === 'running') {\n    return present + lead;\n  }\n  return present;\n}\n\nfunction spanOf(\n  row: TraceRow,\n  runStart: number,\n  timeWindow: TimeWindow,\n  now: number,\n  lead: number\n): BarSpan {\n  const startMs = row.startedAt - runStart;\n  const reach = reachOf(row, now, lead);\n  const endMs = reach - runStart;\n  const start = percentOf(startMs, timeWindow);\n  const reached = percentOf(endMs, timeWindow);\n  const shortest = start + MIN_BAR_PERCENT;\n  const end = Math.max(reached, shortest);\n  return { start, end };\n}\n\nfunction clipStyleOf(row: TraceRow, span: BarSpan) {\n  const offset = span.end - 100;\n  const closed = span.start - 100;\n  const ring = ringColorOf(row);\n  return {\n    transform: `translateX(${offset}%)`,\n    boxShadow: endOutlineOf(ring),\n    '--bar-closed': `${closed}%`,\n  } as React.CSSProperties;\n}\n\nfunction fillStyleOf(row: TraceRow, span: BarSpan): React.CSSProperties {\n  const width = span.end - span.start;\n  const offset = 100 - width;\n  const ring = ringColorOf(row);\n  return {\n    ...fillLookOf(row),\n    boxShadow: outlineOf(ring),\n    transform: `translateX(${offset}%)`,\n  };\n}\n\nfunction labelSideOf(span: BarSpan): LabelSide {\n  if (span.end <= 80) {\n    return 'after';\n  }\n  if (span.start >= 20) {\n    return 'before';\n  }\n  return 'inside';\n}\n\nfunction labelOffsetOf(side: LabelSide, span: BarSpan) {\n  if (side === 'after') {\n    return span.end;\n  }\n  if (side === 'before') {\n    return span.start - 100;\n  }\n  return 0;\n}\n\nfunction labelStyleOf(side: LabelSide, span: BarSpan) {\n  const offset = labelOffsetOf(side, span);\n  return {\n    transform: `translateX(${offset}%)`,\n    '--label-from': `${span.start}%`,\n  } as React.CSSProperties;\n}\n\nfunction barMotionOf(isRunning: boolean, isReframing: boolean) {\n  const isGrowing = isRunning && !isReframing;\n  if (isGrowing) {\n    return GROW;\n  }\n  return GLIDE;\n}\n\n/**\n * True from the render where the time window changes until the next tick of the clock, so a running\n * bar glides to the new scale with the others instead of crawling there.\n */\nfunction useReframing(timeWindow: TimeWindow, now: number) {\n  const windowKey = `${timeWindow.from}:${timeWindow.to}`;\n  const [reframe, setReframe] = useState<Reframe>({ windowKey, at: null });\n  const hasNewWindow = reframe.windowKey !== windowKey;\n  if (hasNewWindow) {\n    setReframe({ windowKey, at: now });\n  }\n  return reframe.at === now;\n}\n\nfunction dimOf(isDimmed: boolean) {\n  if (isDimmed) {\n    return 'opacity-30';\n  }\n  return 'opacity-100';\n}\n\nfunction tabIndexOf(isTabbable: boolean) {\n  if (isTabbable) {\n    return 0;\n  }\n  return -1;\n}\n\nfunction tabbableIdOf(activeId: string | null, visibleIds: string[]) {\n  const isActiveVisible = activeId !== null && visibleIds.includes(activeId);\n  if (isActiveVisible) {\n    return activeId;\n  }\n  return visibleIds[0] ?? null;\n}\n\nfunction callCountOf(run: RunSnapshot) {\n  const count = run.calls.length;\n  if (count === 1) {\n    return '1 call';\n  }\n  return `${count} calls`;\n}\n\nfunction rowCountOf(count: number) {\n  if (count === 1) {\n    return '1 row';\n  }\n  return `${count} rows`;\n}\n\nfunction Highlighted({ text, query }: { text: string; query: string }) {\n  const needle = query.trim().toLowerCase();\n  if (needle === '') {\n    return text;\n  }\n  const start = text.toLowerCase().indexOf(needle);\n  if (start === -1) {\n    return text;\n  }\n  const end = start + needle.length;\n  const before = text.slice(0, start);\n  const match = text.slice(start, end);\n  const after = text.slice(end);\n  return (\n    <>\n      {before}\n      <mark className='bg-primary/15 text-foreground rounded-[3px]'>\n        {match}\n      </mark>\n      {after}\n    </>\n  );\n}\n\nfunction IndentGuides({ depth }: { depth: number }) {\n  const levels = Array.from({ length: depth }, (_, level) => level);\n  const width = depth * INDENT_PX;\n\n  return (\n    <span\n      aria-hidden='true'\n      className='relative shrink-0 self-stretch'\n      style={{ width }}\n    >\n      {levels.map((level) => (\n        <span\n          key={level}\n          className='bg-border absolute inset-y-0 w-(--hairline)'\n          style={{ left: level * INDENT_PX + 5 }}\n        />\n      ))}\n    </span>\n  );\n}\n\nfunction RowName({ row, query }: { row: TraceRow; query: string }) {\n  const dotStyle = { backgroundColor: seriesColorOf(row.series) };\n\n  if (row.kind === 'agent') {\n    return (\n      <span className='flex min-w-0 items-center gap-1.5'>\n        <span className='size-2 shrink-0 rounded-full' style={dotStyle} />\n        <span className='truncate text-[13px] font-medium'>\n          <Highlighted text={row.name} query={query} />\n        </span>\n      </span>\n    );\n  }\n  return (\n    <span className='min-w-0 truncate font-mono text-xs'>\n      <Highlighted text={row.name} query={query} />\n    </span>\n  );\n}\n\nfunction GridLines({\n  ticks,\n  timeWindow,\n}: {\n  ticks: number[];\n  timeWindow: TimeWindow;\n}) {\n  return (\n    <>\n      {ticks.map((tick) => {\n        const offset = percentOf(tick, timeWindow);\n        return (\n          <span\n            key={tick}\n            aria-hidden='true'\n            className={cn(\n              'border-foreground/[0.05] hairline-l absolute inset-0',\n              GLIDE\n            )}\n            style={{ transform: `translateX(${offset}%)` }}\n          />\n        );\n      })}\n    </>\n  );\n}\n\ntype TraceBarProps = {\n  row: TraceRow;\n  runStart: number;\n  timeWindow: TimeWindow;\n  isDimmed: boolean;\n};\n\nfunction TraceBar({ row, runStart, timeWindow, isDimmed }: TraceBarProps) {\n  const isRunning = row.status === 'running';\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const now = useLiveNow(GROW_STEP_MS, isRunning);\n  const isReframing = useReframing(timeWindow, now);\n  const lead = leadOf(shouldReduceMotion);\n  const span = spanOf(row, runStart, timeWindow, now, lead);\n  const side = labelSideOf(span);\n  const followsEnd = side === 'after' && isRunning;\n  const travel = barMotionOf(isRunning, isReframing);\n\n  return (\n    <span\n      className={cn(\n        'absolute inset-0 transition-opacity duration-300',\n        dimOf(isDimmed)\n      )}\n    >\n      <span\n        aria-hidden='true'\n        className={cn(BAR_CLIP, isRunning && CLIP_BIRTH, travel)}\n        style={clipStyleOf(row, span)}\n      >\n        <span\n          className={cn(BAR_FILL, isRunning && FILL_BIRTH, travel)}\n          style={fillStyleOf(row, span)}\n        />\n      </span>\n      <span\n        key={side}\n        className={cn(LABEL_LANE[side], followsEnd && LABEL_BIRTH, travel)}\n        style={labelStyleOf(side, span)}\n      >\n        <LiveDuration\n          item={row}\n          isRunning={isRunning}\n          className='text-muted-foreground text-[11px] whitespace-nowrap'\n        />\n      </span>\n    </span>\n  );\n}\n\ntype PlayheadProps = {\n  runStart: number;\n  timeWindow: TimeWindow;\n};\n\n/** The present, as a line that crosses the rows: it travels one step at a time, like the running bars it leads. */\nfunction Playhead({ runStart, timeWindow }: PlayheadProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const now = useLiveNow(GROW_STEP_MS, true);\n  const present = Math.max(now, runStart);\n  const elapsed = present - runStart;\n  const lead = leadOf(shouldReduceMotion);\n  const ahead = elapsed + lead;\n  const from = percentOf(elapsed, timeWindow);\n  const to = percentOf(ahead, timeWindow);\n  const style = {\n    transform: `translateX(${to}%)`,\n    '--playhead-from': `${from}%`,\n  } as React.CSSProperties;\n\n  return (\n    <span\n      className={cn(\n        'absolute inset-0 starting:[transform:translateX(var(--playhead-from))]',\n        GROW\n      )}\n      style={style}\n    >\n      <span className='bg-primary/70 absolute inset-y-0 start-0 w-px' />\n    </span>\n  );\n}\n\nfunction DetailMeta({ row, runStart }: { row: TraceRow; runStart: number }) {\n  const offset = row.startedAt - runStart;\n  const startedAt = tickLabelOf(Math.round(offset));\n  const isRunning = row.status === 'running';\n\n  return (\n    <dl className='text-muted-foreground grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-xs'>\n      <dt>Agent</dt>\n      <dd className='text-foreground'>{row.agentName}</dd>\n      <dt>Started</dt>\n      <dd className='text-foreground tabular-nums'>at {startedAt}</dd>\n      <dt>Took</dt>\n      <dd className='text-foreground'>\n        <LiveDuration item={row} isRunning={isRunning} />\n      </dd>\n      {row.model && (\n        <>\n          <dt>Model</dt>\n          <dd className='text-foreground'>{row.model}</dd>\n        </>\n      )}\n    </dl>\n  );\n}\n\nfunction RowDetail({ row, runStart }: { row: TraceRow; runStart: number }) {\n  const hasInput = row.input !== undefined;\n  const hasOutput = row.output !== undefined;\n  const isFailed = row.status === 'failed';\n\n  return (\n    <div className='bg-card relative flex flex-col gap-3 px-2 pt-1 pb-3'>\n      <p className='text-[13px] leading-5'>{row.label}</p>\n      <DetailMeta row={row} runStart={runStart} />\n      {hasInput && (\n        <div>\n          <p className='text-muted-foreground mb-1 text-xs font-medium'>\n            Input\n          </p>\n          <JsonView value={row.input} />\n        </div>\n      )}\n      {hasOutput && (\n        <div>\n          <p className='text-muted-foreground mb-1 text-xs font-medium'>\n            Output\n          </p>\n          <JsonView value={row.output} />\n        </div>\n      )}\n      {isFailed && (\n        <div>\n          <p className='text-muted-foreground mb-1 text-xs font-medium'>\n            Error\n          </p>\n          <p className='bg-destructive/10 text-destructive-ink rounded-lg p-2.5 font-mono text-xs leading-relaxed'>\n            {row.error}\n          </p>\n        </div>\n      )}\n    </div>\n  );\n}\n\nconst ROW_GRID = 'grid grid-cols-[7.5rem_1fr] @lg:grid-cols-[10rem_1fr]';\n\n/** Where the time column of `ROW_GRID` starts, for what is drawn across every row at once. */\nconst TIME_COLUMN = 'start-[7.5rem] @lg:start-[10rem]';\n\ntype TraceRowItemProps = {\n  row: TraceRow;\n  runStart: number;\n  timeWindow: TimeWindow;\n  ticks: number[];\n  query: string;\n  isOpen: boolean;\n  isDimmed: boolean;\n  tabIndex: number;\n  onToggle: (rowId: string) => void;\n  onFocusRow: (rowId: string) => void;\n  onKeyDown: (\n    event: React.KeyboardEvent<HTMLButtonElement>,\n    row: TraceRow\n  ) => void;\n  registerButton: (rowId: string, node: HTMLButtonElement | null) => void;\n};\n\nfunction TraceRowItem({\n  row,\n  runStart,\n  timeWindow,\n  ticks,\n  query,\n  isOpen,\n  isDimmed,\n  tabIndex,\n  onToggle,\n  onFocusRow,\n  onKeyDown,\n  registerButton,\n}: TraceRowItemProps) {\n  const detailId = `trace-detail-${row.id}`;\n  const statusWord = STATUS_WORD[row.status];\n\n  return (\n    <div>\n      <button\n        ref={(node) => registerButton(row.id, node)}\n        type='button'\n        tabIndex={tabIndex}\n        aria-expanded={isOpen}\n        aria-controls={detailId}\n        onClick={() => onToggle(row.id)}\n        onFocus={() => onFocusRow(row.id)}\n        onKeyDown={(event) => onKeyDown(event, row)}\n        className={cn(\n          ROW_GRID,\n          'hover:bg-foreground/[0.03] focus-visible:ring-ring/25 aria-expanded:bg-foreground/[0.03] h-8 w-full cursor-pointer items-center rounded-md text-start outline-none focus-visible:ring-[3px]'\n        )}\n      >\n        <span className='flex h-full min-w-0 items-center gap-1 ps-2 pe-2'>\n          <IndentGuides depth={row.depth} />\n          <RowName row={row} query={query} />\n          <span className='sr-only'>\n            , {row.label}, {statusWord}\n          </span>\n        </span>\n        <span className='relative h-full min-w-0 overflow-hidden'>\n          <GridLines ticks={ticks} timeWindow={timeWindow} />\n          <TraceBar\n            row={row}\n            runStart={runStart}\n            timeWindow={timeWindow}\n            isDimmed={isDimmed}\n          />\n        </span>\n      </button>\n      <Fold open={isOpen} id={detailId}>\n        <RowDetail row={row} runStart={runStart} />\n      </Fold>\n    </div>\n  );\n}\n\ntype AxisProps = {\n  ticks: number[];\n  timeWindow: TimeWindow;\n  horizon: number;\n  isZoomed: boolean;\n  onZoom: (timeWindow: TimeWindow | null, message: string) => void;\n};\n\nfunction TimeAxis({ ticks, timeWindow, horizon, isZoomed, onZoom }: AxisProps) {\n  const [brush, setBrush] = useState<Brush | null>(null);\n\n  function positionOf(event: React.PointerEvent<HTMLDivElement>) {\n    const rect = event.currentTarget.getBoundingClientRect();\n    const offset = event.clientX - rect.left;\n    return Math.min(Math.max(0, offset), rect.width);\n  }\n\n  function startBrush(event: React.PointerEvent<HTMLDivElement>) {\n    if (event.button !== 0) {\n      return;\n    }\n    event.currentTarget.setPointerCapture(event.pointerId);\n    const x = positionOf(event);\n    setBrush({ startX: x, currentX: x });\n  }\n\n  function moveBrush(event: React.PointerEvent<HTMLDivElement>) {\n    if (!brush) {\n      return;\n    }\n    const x = positionOf(event);\n    setBrush({ ...brush, currentX: x });\n  }\n\n  function endBrush(event: React.PointerEvent<HTMLDivElement>) {\n    if (!brush) {\n      return;\n    }\n    const width = event.currentTarget.getBoundingClientRect().width;\n    const draggedPx = Math.abs(brush.currentX - brush.startX);\n    setBrush(null);\n    if (draggedPx < MIN_BRUSH_PX) {\n      return;\n    }\n    const next = windowFromBrush(brush, width, timeWindow, horizon);\n    onZoom(next, zoomMessageOf(next));\n  }\n\n  function cancelBrush() {\n    setBrush(null);\n  }\n\n  function zoomFromKeys(event: React.KeyboardEvent<HTMLDivElement>) {\n    const isZoomIn = event.key === '+' || event.key === '=';\n    if (isZoomIn) {\n      event.preventDefault();\n      const next = zoomedIn(timeWindow, horizon);\n      onZoom(next, zoomMessageOf(next));\n      return;\n    }\n    if (event.key === '-') {\n      event.preventDefault();\n      const next = zoomedOut(timeWindow, horizon);\n      if (next) {\n        onZoom(next, zoomMessageOf(next));\n        return;\n      }\n      onZoom(null, 'Zoom reset');\n      return;\n    }\n    const isPan = event.key === 'ArrowLeft' || event.key === 'ArrowRight';\n    if (isPan && isZoomed) {\n      event.preventDefault();\n      const direction = panDirectionOf(event.key);\n      const next = panned(timeWindow, direction, horizon);\n      onZoom(next, zoomMessageOf(next));\n      return;\n    }\n    const isReset = event.key === '0' || event.key === 'Escape';\n    if (isReset && isZoomed) {\n      event.preventDefault();\n      onZoom(null, 'Zoom reset');\n    }\n  }\n\n  return (\n    <div\n      tabIndex={0}\n      role='group'\n      aria-label='Time axis. Drag across it to zoom, or press plus and minus. Arrows move the zoomed range.'\n      onPointerDown={startBrush}\n      onPointerMove={moveBrush}\n      onPointerUp={endBrush}\n      onPointerCancel={cancelBrush}\n      onKeyDown={zoomFromKeys}\n      className='focus-visible:ring-ring/25 relative h-7 cursor-crosshair touch-none overflow-hidden rounded-md outline-none select-none focus-visible:ring-[3px]'\n    >\n      {ticks.map((tick) => {\n        const offset = percentOf(tick, timeWindow);\n        return (\n          <span\n            key={tick}\n            className='absolute inset-x-0 top-1.5 transition-[transform,opacity] duration-300 ease-(--ease-in-out-strong) motion-reduce:transition-none starting:opacity-0'\n            style={{ transform: `translateX(${offset}%)` }}\n          >\n            <span\n              className={cn(\n                'text-muted-foreground absolute start-0 top-0 text-[11px] tabular-nums',\n                tickAlignOf(offset)\n              )}\n            >\n              {tickLabelOf(tick)}\n            </span>\n          </span>\n        );\n      })}\n      {brush && (\n        <span\n          aria-hidden='true'\n          className='bg-primary/10 border-primary/50 hairline-x absolute inset-y-0'\n          style={brushStyleOf(brush)}\n        />\n      )}\n    </div>\n  );\n}\n\nfunction ZoomControl({\n  isZoomed,\n  onReset,\n}: {\n  isZoomed: boolean;\n  onReset: () => void;\n}) {\n  const swapKey = String(isZoomed);\n\n  return (\n    <Swap swapKey={swapKey} className='h-7'>\n      {isZoomed && (\n        <Button type='button' variant='secondary' size='sm' onClick={onReset}>\n          <ZoomOutIcon />\n          Reset zoom\n        </Button>\n      )}\n      {!isZoomed && (\n        <span className='text-muted-foreground text-xs'>\n          Drag across the time axis to zoom\n        </span>\n      )}\n    </Swap>\n  );\n}\n\nfunction shownCriticalIdsOf(tree: TraceNode[], now: number, isShown: boolean) {\n  if (!isShown) {\n    return null;\n  }\n  return criticalIdsOf(tree, now);\n}\n\n/** True once a live run has lasted longer than its fixed window: from then on the axis follows the clock. */\nfunction useHasOutlasted(run: RunSnapshot, windowMs: number | undefined) {\n  const [outlastedStart, setOutlastedStart] = useState<number | null>(null);\n  const startedAt = run.startedAt;\n  const isRunning = run.status === 'running';\n\n  useEffect(() => {\n    if (windowMs === undefined) {\n      return;\n    }\n    if (startedAt === undefined) {\n      return;\n    }\n    if (!isRunning) {\n      return;\n    }\n    const endsAt = startedAt + windowMs;\n    const left = endsAt - Date.now();\n    const delay = Math.max(0, left);\n    const timer = setTimeout(() => setOutlastedStart(startedAt), delay);\n    return () => clearTimeout(timer);\n  }, [windowMs, startedAt, isRunning]);\n\n  return outlastedStart === startedAt;\n}\n\nexport type TraceWaterfallProps = {\n  run: RunSnapshot;\n  slowAfterMs?: number;\n  /**\n   * How long the time axis spans from the start of the run. While the run fits in it the window\n   * holds still and bars only grow. Without it the axis stretches as the run goes on.\n   */\n  windowMs?: number;\n  className?: string;\n};\n\nexport function TraceWaterfall({\n  run,\n  slowAfterMs = 1500,\n  windowMs,\n  className,\n}: TraceWaterfallProps) {\n  const [filter, setFilter] = useState<Filter>('all');\n  const [query, setQuery] = useState('');\n  const [isCriticalShown, setIsCriticalShown] = useState(false);\n  const [zoom, setZoom] = useState<TimeWindow | null>(null);\n  const [openIds, setOpenIds] = useState<string[]>([]);\n  const [activeId, setActiveId] = useState<string | null>(null);\n  const [message, setMessage] = useState('');\n  const buttons = useRef(new Map<string, HTMLButtonElement>());\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const rowPresence = rowPresenceOf(shouldReduceMotion);\n  const fade = fadePresence();\n  const isRunning = run.status === 'running';\n  const hasOutlasted = useHasOutlasted(run, windowMs);\n  const hasFixedWindow = windowMs !== undefined;\n  const followsClock = !hasFixedWindow || hasOutlasted;\n  const watchesRows = filter === 'slow' || isCriticalShown;\n  const needsClock = followsClock || watchesRows;\n  const isTicking = isRunning && needsClock;\n  const now = useLiveNow(1000, isTicking);\n  const runStart = run.startedAt ?? now;\n  const horizon = horizonOf(run, now, windowMs);\n  const fullWindow = { from: 0, to: horizon };\n  const timeWindow = zoom ?? fullWindow;\n  const windowKey = `${timeWindow.from}:${timeWindow.to}`;\n  const isZoomed = zoom !== null;\n  const ticks = ticksOf(timeWindow);\n  const tree = treeOf(run);\n  const allRows = rowsOf(tree);\n  const criticalIds = shownCriticalIdsOf(tree, now, isCriticalShown);\n  const filteredRows = matchingRowsOf(allRows, filter, slowAfterMs, now);\n  const visibleRows = filteredRows.filter((row) => matchesQuery(row, query));\n  const visibleIds = visibleRows.map((row) => row.id);\n  const tabbableId = tabbableIdOf(activeId, visibleIds);\n  const hasRows = allRows.length > 0;\n  const hasVisibleRows = visibleRows.length > 0;\n  const isFilteredEmpty = hasRows && !hasVisibleRows;\n  const hasQuery = query !== '';\n  const isFiltered = filter !== 'all' || query.trim() !== '';\n  const statusLook = RUN_STATUS_LOOK[run.status];\n  const runSpan = { startedAt: run.startedAt, endedAt: run.endedAt };\n  const hasStarted = run.startedAt !== undefined;\n  const showsPlayhead = isRunning && hasStarted;\n\n  function registerButton(rowId: string, node: HTMLButtonElement | null) {\n    if (node) {\n      buttons.current.set(rowId, node);\n      return;\n    }\n    buttons.current.delete(rowId);\n  }\n\n  function focusRow(rowId: string | undefined) {\n    if (rowId === undefined) {\n      return;\n    }\n    buttons.current.get(rowId)?.focus();\n  }\n\n  function toggleRow(rowId: string) {\n    const isOpen = openIds.includes(rowId);\n    if (isOpen) {\n      setOpenIds(openIds.filter((id) => id !== rowId));\n      return;\n    }\n    setOpenIds([...openIds, rowId]);\n  }\n\n  function closeRow(rowId: string) {\n    setOpenIds(openIds.filter((id) => id !== rowId));\n  }\n\n  function moveFromKeys(\n    event: React.KeyboardEvent<HTMLButtonElement>,\n    row: TraceRow\n  ) {\n    const index = visibleIds.indexOf(row.id);\n    if (event.key === 'ArrowDown') {\n      event.preventDefault();\n      focusRow(visibleIds[index + 1]);\n      return;\n    }\n    if (event.key === 'ArrowUp') {\n      event.preventDefault();\n      focusRow(visibleIds[index - 1]);\n      return;\n    }\n    if (event.key === 'Home') {\n      event.preventDefault();\n      focusRow(visibleIds[0]);\n      return;\n    }\n    if (event.key === 'End') {\n      event.preventDefault();\n      const lastIndex = visibleIds.length - 1;\n      focusRow(visibleIds[lastIndex]);\n      return;\n    }\n    const isOpen = openIds.includes(row.id);\n    const isEscape = event.key === 'Escape';\n    if (isEscape && isOpen) {\n      event.preventDefault();\n      closeRow(row.id);\n    }\n  }\n\n  function changeFilter(next: Filter) {\n    setFilter(next);\n    const pickedAt = Date.now();\n    const matching = matchingCountOf(run, next, slowAfterMs, pickedAt);\n    const count = rowCountOf(matching);\n    setMessage(`Showing ${FILTER_WORD[next]}, ${count}`);\n  }\n\n  function changeQuery(event: React.ChangeEvent<HTMLInputElement>) {\n    setQuery(event.target.value);\n  }\n\n  function clearQueryFromKeys(event: React.KeyboardEvent<HTMLInputElement>) {\n    if (event.key === 'Escape' && hasQuery) {\n      event.preventDefault();\n      setQuery('');\n    }\n  }\n\n  function clearQuery() {\n    setQuery('');\n  }\n\n  function clearFilters() {\n    setFilter('all');\n    setQuery('');\n    setMessage('Showing every call');\n  }\n\n  function toggleCritical(pressed: boolean) {\n    setIsCriticalShown(pressed);\n    if (pressed) {\n      setMessage('Critical path shown, other calls faded');\n      return;\n    }\n    setMessage('Critical path hidden');\n  }\n\n  function changeZoom(next: TimeWindow | null, zoomMessage: string) {\n    setZoom(next);\n    setMessage(zoomMessage);\n  }\n\n  function resetZoom() {\n    changeZoom(null, 'Zoom reset');\n  }\n\n  function isDimmed(row: TraceRow) {\n    if (criticalIds === null) {\n      return false;\n    }\n    return !criticalIds.has(row.id);\n  }\n\n  return (\n    <section\n      aria-label={`Trace of ${run.title}`}\n      className={cn(\n        'bg-card hairline-ring ring-border @container flex flex-col gap-3 rounded-xl p-3 shadow-[0_1px_2px_rgb(0_0_0/0.04)] sm:p-4',\n        className\n      )}\n    >\n      <header className='flex items-start justify-between gap-3 px-1'>\n        <div className='min-w-0'>\n          <h3 className='truncate text-sm font-medium'>{run.title}</h3>\n          <p className='text-muted-foreground flex items-center gap-2 text-xs tabular-nums'>\n            <span>{callCountOf(run)}</span>\n            {hasStarted && (\n              <LiveDuration item={runSpan} isRunning={isRunning} />\n            )}\n          </p>\n        </div>\n        <Badge variant={statusLook.variant}>\n          <Swap swapKey={run.status}>{statusLook.label}</Swap>\n        </Badge>\n      </header>\n\n      <div className='flex flex-wrap items-center gap-2'>\n        <Segments\n          value={filter}\n          segments={FILTERS}\n          onValueChange={changeFilter}\n          label='Show calls'\n        />\n        <Toggle\n          size='sm'\n          variant='outline'\n          pressed={isCriticalShown}\n          onPressedChange={toggleCritical}\n          className='h-7 rounded-lg px-2.5 text-xs'\n        >\n          Critical path\n        </Toggle>\n        <div className='relative min-w-40 flex-1'>\n          <SearchIcon className='text-muted-foreground pointer-events-none absolute start-2 top-1/2 size-3.5 -translate-y-1/2' />\n          <Input\n            type='search'\n            size='sm'\n            value={query}\n            onChange={changeQuery}\n            onKeyDown={clearQueryFromKeys}\n            placeholder='Search calls'\n            aria-label='Search calls'\n            className='ps-7 pe-7'\n          />\n          {hasQuery && (\n            <button\n              type='button'\n              aria-label='Clear the search'\n              onClick={clearQuery}\n              className='text-muted-foreground hover:text-foreground hover:bg-foreground/5 focus-visible:ring-ring/25 absolute end-1 top-1/2 inline-flex size-5 -translate-y-1/2 cursor-pointer items-center justify-center rounded-[5px] outline-none focus-visible:ring-[3px]'\n            >\n              <XIcon className='size-3' />\n            </button>\n          )}\n        </div>\n      </div>\n\n      <div className='flex flex-1 flex-col'>\n        <div className={cn(ROW_GRID, 'items-center')}>\n          <span className='text-muted-foreground ps-2 text-xs'>Call</span>\n          <TimeAxis\n            ticks={ticks}\n            timeWindow={timeWindow}\n            horizon={horizon}\n            isZoomed={isZoomed}\n            onZoom={changeZoom}\n          />\n        </div>\n        <div className='relative'>\n          <div\n            aria-hidden='true'\n            className={cn(\n              'pointer-events-none absolute inset-y-0 end-0 overflow-hidden',\n              TIME_COLUMN\n            )}\n          >\n            <AnimatePresence initial={false}>\n              {showsPlayhead && (\n                <motion.div\n                  key={windowKey}\n                  className='absolute inset-0'\n                  {...fade}\n                >\n                  <Playhead runStart={runStart} timeWindow={timeWindow} />\n                </motion.div>\n              )}\n            </AnimatePresence>\n          </div>\n          <ul aria-label='Calls on the time axis' className='flex flex-col'>\n            <AnimatePresence initial={false}>\n              {visibleRows.map((row) => (\n                <motion.li\n                  key={row.id}\n                  className='overflow-hidden'\n                  {...rowPresence}\n                >\n                  <TraceRowItem\n                    row={row}\n                    runStart={runStart}\n                    timeWindow={timeWindow}\n                    ticks={ticks}\n                    query={query}\n                    isOpen={openIds.includes(row.id)}\n                    isDimmed={isDimmed(row)}\n                    tabIndex={tabIndexOf(row.id === tabbableId)}\n                    onToggle={toggleRow}\n                    onFocusRow={setActiveId}\n                    onKeyDown={moveFromKeys}\n                    registerButton={registerButton}\n                  />\n                </motion.li>\n              ))}\n            </AnimatePresence>\n          </ul>\n        </div>\n        {!hasRows && (\n          <p className='text-muted-foreground px-2 py-6 text-center text-[13px]'>\n            The trace fills in as the run makes its first call\n          </p>\n        )}\n        {isFilteredEmpty && (\n          <div className='flex flex-col items-center gap-2 px-2 py-6 text-center'>\n            <p className='text-muted-foreground text-[13px]'>\n              No call matches these filters\n            </p>\n            <Button\n              type='button'\n              variant='outline'\n              size='sm'\n              onClick={clearFilters}\n            >\n              Show every call\n            </Button>\n          </div>\n        )}\n      </div>\n\n      <div className='flex min-h-7 items-center justify-between gap-2 px-1'>\n        <ZoomControl isZoomed={isZoomed} onReset={resetZoom} />\n        {isFiltered && (\n          <span className='text-muted-foreground text-xs tabular-nums'>\n            {rowCountOf(visibleRows.length)}\n          </span>\n        )}\n      </div>\n      <LiveRegion message={message} />\n    </section>\n  );\n}\n\nconst INITIAL_RUN = emptyRun({\n  id: 'brightmoor-trace',\n  title: RUN_TITLE,\n  agents: [\n    { ...PLANNER, task: 'Plan the quarterly review and check the result' },\n    { ...RESEARCHER, task: 'Gather what Brightmoor charged and lists in Q3' },\n    { ...WRITER, task: 'Compare the prices and draft the email' },\n  ],\n});\n\nfunction callStart(\n  id: string,\n  agentId: string,\n  tool: string,\n  label: string,\n  input: Record<string, unknown>\n): RunEvent {\n  return {\n    type: 'call.started',\n    call: { id, agentId, tool, label, input, status: 'running' },\n  };\n}\n\nfunction callDone(id: string, output: unknown): RunEvent {\n  return { type: 'call.updated', id, patch: { status: 'done', output } };\n}\n\nfunction agentState(id: string, status: 'running' | 'done'): RunEvent {\n  return { type: 'agent.updated', id, patch: { status } };\n}\n\nconst PAGE_FAILED: RunEvent = {\n  type: 'call.updated',\n  id: 'page',\n  patch: { status: 'failed', error: PAGE_ERROR },\n};\n\nconst SCRIPT: RunStep[] = [\n  batch(500, { type: 'run.started' }, agentState('planner', 'running')),\n  batch(\n    150,\n    callStart(\n      'plan',\n      'planner',\n      'plan_review',\n      'Split the review into research and writing',\n      { vendor: 'Brightmoor Supply', quarter: 'Q3' }\n    )\n  ),\n  batch(\n    500,\n    callDone('plan', { steps: 4, agents: 2 }),\n    agentState('researcher', 'running')\n  ),\n  batch(\n    100,\n    callStart(\n      'search',\n      'researcher',\n      'web_search',\n      'Searched the web for Brightmoor prices',\n      SEARCH_INPUT\n    )\n  ),\n  batch(\n    120,\n    callStart(\n      'sheet',\n      'researcher',\n      'read_sheet',\n      'Read the Q3 invoices spreadsheet',\n      SHEET_INPUT\n    )\n  ),\n  batch(\n    1000,\n    callDone('search', SEARCH_OUTPUT),\n    callStart(\n      'page',\n      'researcher',\n      'fetch_page',\n      'Read the Brightmoor pricing page',\n      PAGE_INPUT\n    )\n  ),\n  batch(350, callDone('sheet', SHEET_OUTPUT)),\n  batch(450, PAGE_FAILED),\n  batch(\n    300,\n    callStart(\n      'page-again',\n      'researcher',\n      'fetch_page',\n      'Read the pricing page again',\n      PAGE_INPUT\n    )\n  ),\n  batch(\n    900,\n    callDone('page-again', PAGE_OUTPUT),\n    agentState('researcher', 'done')\n  ),\n  batch(100, agentState('writer', 'running')),\n  batch(\n    150,\n    callStart(\n      'script',\n      'writer',\n      'run_script',\n      'Compared invoice lines with the price list',\n      SCRIPT_INPUT\n    )\n  ),\n  batch(\n    3200,\n    callDone('script', SCRIPT_OUTPUT),\n    callStart(\n      'email',\n      'writer',\n      'draft_email',\n      'Drafted the email to Brightmoor accounts',\n      EMAIL_INPUT\n    )\n  ),\n  batch(1000, callDone('email', EMAIL_OUTPUT), agentState('writer', 'done')),\n  batch(\n    100,\n    callStart(\n      'check',\n      'planner',\n      'check_totals',\n      'Checked the totals against the invoices',\n      { invoices: 117, overpaid: 1840.2 }\n    )\n  ),\n  batch(\n    400,\n    callDone('check', { matches: true }),\n    agentState('planner', 'done'),\n    { type: 'run.finished', status: 'done' }\n  ),\n];\n\n/** The run takes about nine seconds, so every bar of the demo fits in a window that never moves. */\nconst WINDOW_MS = 10_000;\n\nconst SESSION = {\n  reducer: reduceBatch,\n  initial: INITIAL_RUN,\n  resting: restingOf(INITIAL_RUN, SCRIPT, applyBatchAt),\n  script: SCRIPT,\n  loopAfter: 3000,\n};\n\nexport default function Run02() {\n  const { ref, isInView, isAutoplaying, state, isFinished, restart } =\n    useSession(SESSION);\n  const canReplay = isFinished && !isAutoplaying;\n\n  useKeptHeight(ref);\n\n  return (\n    <div\n      ref={ref}\n      className='@container flex w-full max-w-[45rem] flex-col gap-2'\n    >\n      <ClockGate isActive={isInView}>\n        <TraceWaterfall\n          run={state}\n          windowMs={WINDOW_MS}\n          className='min-h-[36.5rem] @lg:min-h-[34rem]'\n        />\n      </ClockGate>\n      <div className='flex h-7 items-center justify-end'>\n        <ReplayButton isShown={canReplay} onReplay={restart} />\n      </div>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/run/run-02.tsx"
    },
    {
      "path": "registry/ndeko/components/run/_parts/scenario.ts",
      "content": "import type { RunAgent } from '@/registry/ndeko/lib/agent-run';\n\nexport const RUN_TITLE = 'Quarterly vendor review for Brightmoor Supply';\n\nexport const PLANNER: RunAgent = {\n  id: 'planner',\n  name: 'Planner',\n  series: 1,\n  status: 'idle',\n  model: 'Claude Opus',\n  role: 'Lead',\n};\n\nexport const RESEARCHER: RunAgent = {\n  id: 'researcher',\n  name: 'Researcher',\n  series: 2,\n  status: 'idle',\n  model: 'Claude Sonnet',\n  parentId: 'planner',\n};\n\nexport const WRITER: RunAgent = {\n  id: 'writer',\n  name: 'Writer',\n  series: 3,\n  status: 'idle',\n  model: 'Claude Haiku',\n  parentId: 'planner',\n};\n\nexport const PRICING_URL = 'https://brightmoor-supply.example/pricing';\n\nexport const SEARCH_INPUT = {\n  query: 'Brightmoor Supply wholesale price list',\n  limit: 5,\n};\n\nexport const SEARCH_OUTPUT = {\n  results: 5,\n  top: PRICING_URL,\n};\n\nexport const PAGE_INPUT = {\n  url: PRICING_URL,\n  timeoutMs: 8000,\n};\n\nexport const PAGE_ERROR = '403 Forbidden: the site refused the reader';\n\nexport const PAGE_OUTPUT = {\n  title: 'Wholesale pricing',\n  tables: 3,\n  updated: '2026-10-02',\n};\n\nexport const SHEET_INPUT = {\n  file: 'q3-invoices.xlsx',\n  sheet: 'Brightmoor',\n  range: 'A1:F118',\n};\n\nexport const SHEET_OUTPUT = {\n  rows: 117,\n  total: 48210.5,\n  currency: 'USD',\n  flagged: false,\n};\n\nexport const SCRIPT_INPUT = {\n  script: 'compare_prices.py',\n  args: ['--quarter', 'Q3'],\n};\n\nexport const SCRIPT_OUTPUT = {\n  items: 42,\n  aboveList: 6,\n  overpaid: 1840.2,\n};\n\nexport const EMAIL_INPUT = {\n  to: 'accounts@brightmoor-supply.example',\n  subject: 'Q3 pricing review',\n};\n\nexport const EMAIL_OUTPUT = {\n  words: 186,\n  attachments: 1,\n};\n",
      "type": "registry:component",
      "target": "components/run/_parts/scenario.ts"
    }
  ],
  "categories": [
    "components",
    "run"
  ],
  "type": "registry:component"
}