{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "incident-review",
  "type": "registry:block",
  "title": "Incident review",
  "description": "A post-incident review that puts the summary, the release, latency, the slowest trace, and the timeline on one page.",
  "categories": [
    "blocks"
  ],
  "dependencies": [
    "@tabler/icons-react"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "src/registry/overtrue/incident-review.tsx",
      "type": "registry:component",
      "target": "components/overtrue/incident-review.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { IconAlertTriangle, IconClockHour4 } from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { InsightCard, type InsightSource } from \"./insight-card\";\nimport { LatencyHistogram } from \"./latency-histogram\";\nimport { TraceWaterfall, type TraceSpan } from \"./trace-waterfall\";\nimport { DeployPipeline, type PipelineStage } from \"./deploy-pipeline\";\nimport { LogStream, type LogEntry } from \"./log-stream\";\n\nexport type IncidentSeverity = \"sev1\" | \"sev2\" | \"sev3\";\nexport type IncidentState = \"investigating\" | \"mitigated\" | \"resolved\";\n\nexport interface IncidentReviewData {\n  id: string;\n  title: string;\n  service: string;\n  severity: IncidentSeverity;\n  state: IncidentState;\n  /** Human-readable duration, e.g. \"18 min\". */\n  duration: string;\n  /** Summary with optional `{{metric:…}}` and `{{cite:n}}` tokens. */\n  summary: string;\n  sources?: InsightSource[];\n  latency: {\n    /** Request latencies before the incident, in milliseconds. */\n    before: number[];\n    /** Request latencies during the incident. */\n    during: number[];\n    /** Objective drawn on the histogram. */\n    threshold: number;\n  };\n  trace: { title: string; spans: TraceSpan[] };\n  release: { title: string; meta?: React.ReactNode; stages: PipelineStage[] };\n  events: LogEntry[];\n}\n\nexport interface IncidentReviewProps\n  extends Omit<React.ComponentProps<\"section\">, \"title\"> {\n  incident: IncidentReviewData;\n  /** Ask your model for a new summary; the card shows a thinking state meanwhile. */\n  onRegenerate?: () => void;\n  /** Stream the summary in; leave false to show it complete. */\n  streaming?: boolean;\n}\n\nconst severityStyle: Record<IncidentSeverity, string> = {\n  sev1: \"bg-destructive text-white\",\n  sev2: \"bg-amber-500 text-black\",\n  sev3: \"bg-muted text-foreground\",\n};\nconst stateStyle: Record<IncidentState, string> = {\n  investigating: \"border-destructive/30 bg-destructive/10 text-destructive\",\n  mitigated:\n    \"border-amber-500/30 bg-amber-500/10 text-amber-800 dark:text-amber-300\",\n  resolved:\n    \"border-emerald-500/30 bg-emerald-500/10 text-emerald-800 dark:text-emerald-300\",\n};\nconst stateLabel: Record<IncidentState, string> = {\n  investigating: \"Investigating\",\n  mitigated: \"Mitigated\",\n  resolved: \"Resolved\",\n};\n\n/** A post-incident review: what happened, the evidence, and what changed. */\nexport function IncidentReview({\n  incident,\n  onRegenerate,\n  streaming = false,\n  className,\n  ...props\n}: IncidentReviewProps) {\n  return (\n    <section\n      data-slot=\"incident-review\"\n      aria-label={`${incident.id}: ${incident.title}`}\n      className={cn(\n        \"@container/incident flex min-w-0 flex-col gap-3 text-foreground sm:gap-4\",\n        className,\n      )}\n      {...props}\n    >\n      <header\n        data-slot=\"incident-review-header\"\n        className=\"flex flex-wrap items-end justify-between gap-3\"\n      >\n        <div className=\"flex min-w-0 items-center gap-3\">\n          <span\n            className={cn(\n              \"inline-flex h-6 shrink-0 items-center gap-1 rounded-md px-2 font-mono text-[11px] font-semibold uppercase\",\n              severityStyle[incident.severity],\n            )}\n          >\n            <IconAlertTriangle aria-hidden=\"true\" className=\"size-3.5\" stroke={2.25} />\n            {incident.severity}\n          </span>\n          <div className=\"min-w-0\">\n            <h2 className=\"truncate text-base font-semibold tracking-tight\">\n              {incident.title}\n            </h2>\n            <p className=\"truncate font-mono text-xs text-muted-foreground\">\n              {incident.id} · {incident.service}\n            </p>\n          </div>\n        </div>\n        <div className=\"flex items-center gap-2 text-xs\">\n          <span className=\"inline-flex items-center gap-1 text-muted-foreground tabular-nums\">\n            <IconClockHour4 aria-hidden=\"true\" className=\"size-3.5\" />\n            {incident.duration}\n          </span>\n          <span\n            className={cn(\n              \"inline-flex h-6 items-center rounded-full border px-2.5 font-medium\",\n              stateStyle[incident.state],\n            )}\n          >\n            {stateLabel[incident.state]}\n          </span>\n        </div>\n      </header>\n\n      <div className=\"grid gap-3 sm:gap-4\">\n        <div className=\"grid gap-3 sm:gap-4 @4xl/incident:grid-cols-[minmax(0,1.1fr)_minmax(0,1fr)]\">\n          <InsightCard\n            title=\"What happened\"\n            source=\"Incident summary\"\n            text={incident.summary}\n            status={streaming ? \"streaming\" : \"done\"}\n            sources={incident.sources}\n            onRegenerate={onRegenerate}\n          />\n          <DeployPipeline\n            title={incident.release.title}\n            meta={incident.release.meta}\n            stages={incident.release.stages}\n            orientation=\"auto\"\n          />\n        </div>\n        <LatencyHistogram\n          title=\"Latency during the incident\"\n          description=\"Checkout requests, compared with the hour before\"\n          values={incident.latency.during}\n          compare={incident.latency.before}\n          compareLabel=\"Before\"\n          seriesLabel=\"During\"\n          threshold={incident.latency.threshold}\n          thresholdLabel=\"SLO\"\n        />\n        <TraceWaterfall\n          title={incident.trace.title}\n          description=\"Slowest trace in the incident window\"\n          spans={incident.trace.spans}\n          height={340}\n        />\n        <LogStream\n          entries={incident.events}\n          title=\"Timeline\"\n          height={220}\n          live={false}\n        />\n      </div>\n    </section>\n  );\n}\n\n/* Sample incident ---------------------------------------------------------- */\n\nfunction random(seed: number) {\n  return () => {\n    seed |= 0;\n    seed = (seed + 0x6d2b79f5) | 0;\n    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);\n    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n  };\n}\nfunction logNormal(count: number, median: number, spread: number, seed: number) {\n  const next = random(seed);\n  return Array.from({ length: count }, () => {\n    const u = Math.max(next(), 1e-9);\n    const v = next();\n    const z = Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);\n    return Math.round(median * Math.exp(spread * z));\n  });\n}\n\nconst at = (minute: number, second = 0) =>\n  Date.UTC(2026, 9, 14, 14, minute, second);\n\n/** A fictional checkout regression, for demos and tests. */\nexport const sampleIncident: IncidentReviewData = {\n  id: \"INC-2041\",\n  title: \"Checkout latency regression after release\",\n  service: \"checkout-api\",\n  severity: \"sev2\",\n  state: \"resolved\",\n  duration: \"18 min\",\n  summary:\n    \"p95 checkout latency rose to {{metric:p95|412 ms|negative}} two minutes after release web@4f9c2ab reached production {{cite:1}}. The slowest traces spend most of their time in pricing.quote, which ran one promotions query per cart item {{cite:2}}. Rolling back restored p95 to {{metric:p95|186 ms|positive}} within six minutes {{cite:3}}. Follow-up: batch the promotions lookup and give the pricing service a query budget.\",\n  sources: [\n    { id: \"1\", label: \"Release web@4f9c2ab\" },\n    { id: \"2\", label: \"Trace 9c41e2\" },\n    { id: \"3\", label: \"Latency dashboard\" },\n  ],\n  latency: {\n    before: logNormal(3000, 168, 0.42, 7),\n    during: [\n      ...logNormal(2100, 236, 0.48, 11),\n      ...logNormal(900, 520, 0.38, 13),\n    ],\n    threshold: 400,\n  },\n  trace: {\n    title: \"POST /api/checkout\",\n    spans: [\n      { id: \"root\", name: \"POST /api/checkout\", service: \"gateway\", start: 0, duration: 1240 },\n      { id: \"auth\", parentId: \"root\", name: \"auth.verify_session\", service: \"auth\", start: 6, duration: 38 },\n      { id: \"sess\", parentId: \"auth\", name: \"GET session\", service: \"redis\", start: 9, duration: 3 },\n      { id: \"cart\", parentId: \"root\", name: \"cart.load\", service: \"cart\", start: 48, duration: 84 },\n      { id: \"cartdb\", parentId: \"cart\", name: \"SELECT cart_items\", service: \"postgres\", start: 56, duration: 61 },\n      { id: \"price\", parentId: \"root\", name: \"pricing.quote\", service: \"pricing\", start: 136, duration: 962, attributes: { \"cart.items\": 14, \"db.queries\": 15 } },\n      ...Array.from({ length: 12 }, (_, index) => ({\n        id: `promo-${index}`,\n        parentId: \"price\",\n        name: \"SELECT promotions WHERE sku = $1\",\n        service: \"postgres\",\n        start: 148 + index * 76,\n        duration: 66 + ((index * 17) % 9),\n        attributes: { \"db.rows\": 1 + (index % 3) },\n      })),\n      { id: \"tax\", parentId: \"price\", name: \"tax.calculate\", service: \"pricing\", start: 1060, duration: 30 },\n      { id: \"pay\", parentId: \"root\", name: \"payments.authorize\", service: \"payments\", start: 1104, duration: 118 },\n      { id: \"psp\", parentId: \"pay\", name: \"POST provider /authorize\", service: \"payments\", start: 1110, duration: 104 },\n    ],\n  },\n  release: {\n    title: \"web@4f9c2ab\",\n    meta: \"Rolled back to 7d1e3fa\",\n    stages: [\n      { id: \"build\", label: \"Build\", jobs: [{ id: \"compile\", label: \"Compile\", status: \"success\", duration: 72000 }] },\n      {\n        id: \"test\",\n        label: \"Test\",\n        jobs: [\n          { id: \"unit\", label: \"Unit\", status: \"success\", duration: 48000 },\n          { id: \"e2e\", label: \"E2E\", status: \"success\", duration: 161000 },\n        ],\n      },\n      { id: \"canary\", label: \"Canary 10%\", jobs: [{ id: \"canary-job\", label: \"Canary\", status: \"success\", duration: 300000, detail: \"p95 within budget at 10% traffic\" }] },\n      { id: \"prod\", label: \"Production\", jobs: [{ id: \"prod-job\", label: \"Rollout\", status: \"canceled\", duration: 240000, detail: \"Stopped at 100% by rollback\" }] },\n      { id: \"rollback\", label: \"Rollback\", jobs: [{ id: \"rollback-job\", label: \"7d1e3fa\", status: \"success\", duration: 96000 }] },\n    ],\n  },\n  events: [\n    { id: \"e1\", time: at(2, 10), level: \"info\", source: \"deploy\", message: \"web@4f9c2ab promoted to 100% of production traffic\" },\n    { id: \"e2\", time: at(4, 32), level: \"warn\", source: \"alerts\", message: \"checkout p95 412 ms over 400 ms objective for 2 min\" },\n    { id: \"e3\", time: at(5, 5), level: \"info\", source: \"pager\", message: \"On-call acknowledged INC-2041\" },\n    { id: \"e4\", time: at(9, 48), level: \"error\", source: \"pricing\", message: \"pricing.quote issued 15 queries for a 14-item cart\" },\n    { id: \"e5\", time: at(11, 20), level: \"info\", source: \"deploy\", message: \"Rollback to 7d1e3fa started\" },\n    { id: \"e6\", time: at(14, 2), level: \"info\", source: \"alerts\", message: \"checkout p95 186 ms, back within objective\" },\n    { id: \"e7\", time: at(20, 0), level: \"info\", source: \"pager\", message: \"INC-2041 resolved; follow-up PRICE-311 created\" },\n  ],\n};\n"
    },
    {
      "path": "src/registry/overtrue/insight-card.tsx",
      "type": "registry:component",
      "target": "components/overtrue/insight-card.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport {\n  IconAlertTriangle as AlertTriangle,\n  IconArrowDownRight as ArrowDownRight,\n  IconArrowUpRight as ArrowUpRight,\n  IconCheck as Check,\n  IconCopy as Copy,\n  IconFileAnalytics as FileAnalytics,\n  IconPlayerStopFilled as Stop,\n  IconRefresh as Refresh,\n  IconThumbDown as ThumbDown,\n  IconThumbDownFilled as ThumbDownFilled,\n  IconThumbUp as ThumbUp,\n  IconThumbUpFilled as ThumbUpFilled,\n} from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport type InsightStatus =\n  \"idle\" | \"thinking\" | \"streaming\" | \"done\" | \"error\";\nexport type InsightTone = \"positive\" | \"negative\" | \"neutral\";\nexport type InsightFeedback = \"up\" | \"down\" | null;\n\n/**\n * An inline token parsed from `{{kind:arg|arg|arg}}`.\n * Built in: `{{metric:Label|+12.8%}}`, `{{metric:Churn|-0.4 pts|positive}}`, `{{cite:1}}`.\n */\nexport interface InsightToken {\n  /** The word before the colon, e.g. \"metric\" or \"cite\". */\n  kind: string;\n  /** First argument: the metric label or the source number / id. */\n  label: string;\n  /** Second argument: the metric value. */\n  value?: string;\n  /** Third argument when it is positive, negative or neutral; otherwise inferred from the value's sign. */\n  tone: InsightTone;\n  /** Which way the value moved, from its sign: drives the arrow, while tone drives the color. */\n  direction: \"up\" | \"down\" | \"flat\";\n  /** Every argument after the colon, trimmed. */\n  args: string[];\n  /** The original markup. */\n  raw: string;\n}\n\nexport type InsightSegment = string | InsightToken;\n\nexport interface InsightSource {\n  id: string;\n  label: string;\n  href?: string;\n}\n\nexport interface InsightCardLabels {\n  thinking: string;\n  streaming: string;\n  idle: string;\n  generate: string;\n  regenerate: string;\n  stop: string;\n  copy: string;\n  copied: string;\n  helpful: string;\n  notHelpful: string;\n  sources: string;\n  feedback: string;\n  error: string;\n  retry: string;\n}\n\nexport interface InsightCardColors {\n  /** Caret, summary icon and the optional moving border. */\n  accent?: string;\n  /** Enables the working border and glow with this second color. */\n  glow?: string;\n  positive?: string;\n  negative?: string;\n}\n\nexport interface InsightCardProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"title\" | \"children\" | \"onCopy\"\n> {\n  title?: React.ReactNode;\n  /** Model, dataset or time range, shown at the top right. */\n  source?: React.ReactNode;\n  /** Replaces the summary icon. */\n  icon?: React.ReactNode;\n  /** The insight, with optional `{{kind:arg|arg}}` tokens. Append to it while streaming. */\n  text?: string;\n  /** Shorthand for `status=\"streaming\"` while you append to `text`. */\n  streaming?: boolean;\n  /** Defaults to streaming, done or idle from `streaming`, `text` and `stream`. */\n  status?: InsightStatus;\n  /** Consumed internally; drives thinking, streaming, done and error. Pass a new iterable to regenerate. */\n  stream?: AsyncIterable<string>;\n  /** Message for the error state. */\n  error?: React.ReactNode;\n  sources?: InsightSource[];\n  /** Shows Regenerate, and Try again in the error state. */\n  onRegenerate?: () => void;\n  /** Shows Stop while thinking or streaming. */\n  onStop?: () => void;\n  /** Called with the plain text. Without it, Copy writes to the clipboard. */\n  onCopy?: (text: string) => void;\n  feedback?: InsightFeedback;\n  defaultFeedback?: InsightFeedback;\n  onFeedback?: (feedback: InsightFeedback) => void;\n  /** Render a token yourself. Return `undefined` to keep the built-in rendering. */\n  renderToken?: (\n    token: InsightToken,\n    index: number,\n  ) => React.ReactNode | undefined;\n  /** Replace the token parser. */\n  parse?: (text: string) => InsightSegment[];\n  /** Characters per second for revealing new text. 0 shows it immediately. */\n  speed?: number;\n  /** Called once streamed text has fully revealed. */\n  onStreamEnd?: () => void;\n  /** Extra buttons after Copy. */\n  actions?: React.ReactNode;\n  colors?: InsightCardColors;\n  labels?: Partial<InsightCardLabels>;\n}\n\nconst LABELS: InsightCardLabels = {\n  thinking: \"Thinking…\",\n  streaming: \"Writing…\",\n  idle: \"No insight yet.\",\n  generate: \"Generate\",\n  regenerate: \"Regenerate\",\n  stop: \"Stop\",\n  copy: \"Copy\",\n  copied: \"Copied\",\n  helpful: \"Helpful\",\n  notHelpful: \"Not helpful\",\n  sources: \"Sources\",\n  feedback: \"Feedback\",\n  error: \"Couldn’t generate this insight.\",\n  retry: \"Try again\",\n};\n\nconst TOKEN = /\\{\\{\\s*([A-Za-z][\\w-]*)\\s*:([^{}]*?)\\}\\}/g;\nconst TONES = new Set<string>([\"positive\", \"negative\", \"neutral\"]);\n\nfunction direction(value: string | undefined): InsightToken[\"direction\"] {\n  const sign = value?.trim()[0];\n  if (sign === \"+\" || sign === \"↑\") return \"up\";\n  if (sign === \"-\" || sign === \"−\" || sign === \"↓\") return \"down\";\n  return \"flat\";\n}\n\n/** Split text into strings and tokens. A token cut off at the end is dropped while it streams in. */\nexport function parseInsight(text: string): InsightSegment[] {\n  const segments: InsightSegment[] = [];\n  let from = 0;\n  for (const match of text.matchAll(TOKEN)) {\n    if (match.index > from) segments.push(text.slice(from, match.index));\n    const args = match[2].split(\"|\").map((arg) => arg.trim());\n    const [label = \"\", value, third] = args;\n    const moved = direction(value);\n    segments.push({\n      kind: match[1].toLowerCase(),\n      label,\n      value,\n      direction: moved,\n      tone:\n        third && TONES.has(third)\n          ? (third as InsightTone)\n          : moved === \"up\"\n            ? \"positive\"\n            : moved === \"down\"\n              ? \"negative\"\n              : \"neutral\",\n      args,\n      raw: match[0],\n    });\n    from = match.index + match[0].length;\n  }\n  let rest = text.slice(from);\n  const open = rest.lastIndexOf(\"{{\");\n  if (open !== -1 && !rest.includes(\"}}\", open)) rest = rest.slice(0, open);\n  if (rest) segments.push(rest);\n  return segments;\n}\n\n/** Plain text for copying and screen readers: metrics read \"Revenue +12.8%\", citations \"[1]\". */\nexport function insightToPlainText(\n  text: string,\n  parse: (text: string) => InsightSegment[] = parseInsight,\n) {\n  return parse(text)\n    .map((segment) =>\n      typeof segment === \"string\"\n        ? segment\n        : segment.kind === \"cite\"\n          ? `[${segment.label}]`\n          : [segment.label, segment.value].filter(Boolean).join(\" \"),\n    )\n    .join(\"\")\n    .trim();\n}\n\nconst focusRing =\n  \"outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-1 focus-visible:ring-offset-card\";\n\nconst useIsoLayoutEffect =\n  typeof window === \"undefined\" ? React.useEffect : React.useLayoutEffect;\n\nconst REDUCED = \"(prefers-reduced-motion: reduce)\";\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (callback) => {\n      const query = window.matchMedia(REDUCED);\n      query.addEventListener(\"change\", callback);\n      return () => query.removeEventListener(\"change\", callback);\n    },\n    () => window.matchMedia(REDUCED).matches,\n    () => false,\n  );\n}\n\n// One reader per iterable, so StrictMode's double effects and remounts share progress.\ninterface StreamSession {\n  text: string;\n  status: \"thinking\" | \"streaming\" | \"done\" | \"error\";\n  error?: unknown;\n  listeners: Set<() => void>;\n  stop: () => void;\n}\nconst sessions = new WeakMap<AsyncIterable<string>, StreamSession>();\n\nfunction openSession(stream: AsyncIterable<string>) {\n  const existing = sessions.get(stream);\n  if (existing) return existing;\n  const iterator = stream[Symbol.asyncIterator]();\n  let stopped = false;\n  const session: StreamSession = {\n    text: \"\",\n    status: \"thinking\",\n    listeners: new Set(),\n    stop: () => {\n      if (stopped) return;\n      stopped = true;\n      if (session.status === \"thinking\" || session.status === \"streaming\")\n        session.status = \"done\";\n      void iterator.return?.();\n    },\n  };\n  const emit = () => session.listeners.forEach((listener) => listener());\n  sessions.set(stream, session);\n  void (async () => {\n    try {\n      while (!stopped) {\n        const result = await iterator.next();\n        if (stopped) return;\n        if (result.done) break;\n        session.text += String(result.value ?? \"\");\n        session.status = \"streaming\";\n        emit();\n      }\n      if (!stopped) {\n        session.status = \"done\";\n        emit();\n      }\n    } catch (error) {\n      if (stopped) return;\n      session.status = \"error\";\n      session.error = error;\n      emit();\n    }\n  })();\n  return session;\n}\n\nfunction useStreamSession(stream: AsyncIterable<string> | undefined) {\n  const [, rerender] = React.useReducer((count: number) => count + 1, 0);\n  React.useEffect(() => {\n    if (!stream) return;\n    const session = openSession(stream);\n    session.listeners.add(rerender);\n    rerender();\n    return () => {\n      session.listeners.delete(rerender);\n      // Stop reading only if nothing resubscribed (StrictMode remounts immediately).\n      window.setTimeout(() => {\n        if (!session.listeners.size) session.stop();\n      }, 0);\n    };\n  }, [stream]);\n  return stream ? (sessions.get(stream) ?? null) : null;\n}\n\n/** Move a reveal position past a whole token so chips appear complete. */\nfunction snap(text: string, position: number) {\n  const open = text.lastIndexOf(\"{{\", position - 1);\n  if (open === -1) return position;\n  const close = text.indexOf(\"}}\", open);\n  if (close === -1) return open;\n  return close + 2 > position ? close + 2 : position;\n}\n\nfunction useReveal(text: string, animate: boolean, speed: number) {\n  const [shown, setShown] = React.useState(() => (animate ? 0 : text.length));\n  const shownRef = React.useRef(shown);\n  const previous = React.useRef(text);\n\n  useIsoLayoutEffect(() => {\n    const set = (value: number) => {\n      shownRef.current = value;\n      setShown(value);\n    };\n    let start = shownRef.current;\n    // Replaced rather than appended: start over.\n    if (!text.startsWith(previous.current.slice(0, start))) start = 0;\n    previous.current = text;\n    if (!animate || !(speed > 0) || !Number.isFinite(speed))\n      start = text.length;\n    start = Math.min(start, text.length);\n    set(start);\n    if (start >= text.length) return;\n\n    let frame = 0;\n    let last = performance.now();\n    let carry = start;\n    const tick = (now: number) => {\n      const dt = Math.min(now - last, 100);\n      last = now;\n      // Catch up when the source runs ahead, so the reveal never lags by more than ~2s.\n      const backlog = text.length - carry;\n      carry = Math.min(\n        text.length,\n        carry + (speed * Math.max(1, backlog / (speed * 2)) * dt) / 1000,\n      );\n      const next = snap(text, Math.floor(carry));\n      if (next > shownRef.current) set(next);\n      // Wait for the rest of a half-received token before going on.\n      if (next < Math.floor(carry)) return;\n      if (next < text.length) frame = requestAnimationFrame(tick);\n    };\n    frame = requestAnimationFrame(tick);\n    return () => cancelAnimationFrame(frame);\n  }, [text, animate, speed]);\n\n  return Math.min(shown, text.length);\n}\n\nconst toneClass: Record<InsightTone, string> = {\n  positive:\n    \"border-(--insight-positive)/25 bg-(--insight-positive)/8 [--chip:var(--insight-positive)]\",\n  negative:\n    \"border-(--insight-negative)/25 bg-(--insight-negative)/8 [--chip:var(--insight-negative)]\",\n  neutral: \"border-border bg-muted/60 [--chip:var(--color-muted-foreground)]\",\n};\n\nfunction MetricChip({ token }: { token: InsightToken }) {\n  const Arrow =\n    token.direction === \"up\"\n      ? ArrowUpRight\n      : token.direction === \"down\"\n        ? ArrowDownRight\n        : null;\n  return (\n    <span\n      data-slot=\"insight-token\"\n      data-kind=\"metric\"\n      data-tone={token.tone}\n      className={cn(\n        \"mx-px inline-flex translate-y-[-1px] items-center gap-1 rounded-md border px-1.5 align-middle text-[12.5px] leading-5 whitespace-nowrap\",\n        \"transition-[opacity,scale] duration-300 ease-out starting:scale-90 starting:opacity-0 motion-reduce:transition-none\",\n        toneClass[token.tone],\n      )}\n    >\n      {token.label && (\n        <span className=\"font-medium text-foreground\">{token.label}</span>\n      )}\n      {token.value && (\n        <span className=\"inline-flex items-center gap-0.5 font-mono text-[12px] font-medium text-[color-mix(in_oklab,var(--chip)_82%,var(--color-foreground))] tabular-nums\">\n          {Arrow && (\n            <Arrow className=\"size-3\" aria-hidden=\"true\" stroke={2.25} />\n          )}\n          {token.value}\n        </span>\n      )}\n    </span>\n  );\n}\n\nconst styles = `@property --insight-angle{syntax:\"<angle>\";inherits:false;initial-value:0deg}@keyframes insight-spin{to{--insight-angle:360deg}}@keyframes insight-shimmer{from{background-position:100% 0}to{background-position:-100% 0}}@keyframes insight-caret{0%,50%{opacity:1}50.01%,100%{opacity:0}}`;\n\nconst ring =\n  \"conic-gradient(from var(--insight-angle), transparent 0%, var(--insight-accent) 12%, var(--insight-glow) 22%, transparent 34%, transparent 50%, var(--insight-glow) 62%, var(--insight-accent) 72%, transparent 84%)\";\n\nconst ringMask: React.CSSProperties = {\n  padding: 1,\n  WebkitMask:\n    \"linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0)\",\n  WebkitMaskComposite: \"xor\",\n  mask: \"linear-gradient(#000 0 0) content-box exclude, linear-gradient(#000 0 0)\",\n};\n\n/**\n * An AI summary for dashboards: streams text with a caret, turns `{{metric:…}}` markup\n * into delta chips, cites numbered sources, and offers regenerate, copy and feedback.\n */\nexport function InsightCard({\n  title = \"Insight\",\n  source,\n  icon,\n  text = \"\",\n  streaming,\n  status: statusProp,\n  stream,\n  error,\n  sources,\n  onRegenerate,\n  onStop,\n  onCopy,\n  feedback: feedbackProp,\n  defaultFeedback = null,\n  onFeedback,\n  renderToken,\n  parse = parseInsight,\n  speed = 90,\n  onStreamEnd,\n  actions,\n  colors,\n  labels: labelsProp,\n  className,\n  style,\n  ...props\n}: InsightCardProps) {\n  const labels = { ...LABELS, ...labelsProp };\n  const reduced = useReducedMotion();\n  const session = useStreamSession(stream);\n\n  const fullText = stream ? (session?.text ?? \"\") : text;\n  const sourceStatus: InsightStatus = stream\n    ? (statusProp ?? session?.status ?? \"thinking\")\n    : (statusProp ?? (streaming ? \"streaming\" : text ? \"done\" : \"idle\"));\n  const active = sourceStatus === \"thinking\" || sourceStatus === \"streaming\";\n\n  const [feedbackState, setFeedbackState] =\n    React.useState<InsightFeedback>(defaultFeedback);\n  const feedback = feedbackProp !== undefined ? feedbackProp : feedbackState;\n\n  // \"Live\" spans one generation: from thinking/streaming until the reveal catches up.\n  const [live, setLive] = React.useState(active);\n  if (active && !live) {\n    setLive(true);\n    // Feedback belongs to the previous answer.\n    setFeedbackState(null);\n  }\n\n  // Hold the reveal while thinking, so text supplied early still streams in afterwards.\n  const revealText = sourceStatus === \"thinking\" ? \"\" : fullText;\n  const shown = useReveal(revealText, live && !reduced, speed);\n  const revealing = shown < revealText.length;\n  const status: InsightStatus =\n    sourceStatus === \"error\"\n      ? \"error\"\n      : sourceStatus === \"thinking\"\n        ? \"thinking\"\n        : sourceStatus === \"streaming\" || (live && revealing)\n          ? \"streaming\"\n          : fullText\n            ? \"done\"\n            : \"idle\";\n\n  const onStreamEndRef = React.useRef(onStreamEnd);\n  onStreamEndRef.current = onStreamEnd;\n  React.useEffect(() => {\n    if (live && !active && !revealing) {\n      setLive(false);\n      if (sourceStatus === \"done\") onStreamEndRef.current?.();\n    }\n  }, [live, active, revealing, sourceStatus]);\n\n  const setFeedback = (value: InsightFeedback) => {\n    const next = value === feedback ? null : value;\n    if (feedbackProp === undefined) setFeedbackState(next);\n    onFeedback?.(next);\n  };\n\n  const [copied, setCopied] = React.useState(false);\n  React.useEffect(() => {\n    if (!copied) return;\n    const timer = window.setTimeout(() => setCopied(false), 1600);\n    return () => window.clearTimeout(timer);\n  }, [copied]);\n\n  const [hoveredSource, setHoveredSource] = React.useState<string | null>(null);\n\n  const plain = React.useMemo(\n    () => insightToPlainText(fullText, parse),\n    [fullText, parse],\n  );\n  const visible =\n    shown >= fullText.length ? fullText : fullText.slice(0, shown);\n  const segments = React.useMemo(() => parse(visible), [parse, visible]);\n\n  const copy = async () => {\n    if (onCopy) onCopy(plain);\n    else {\n      try {\n        await navigator.clipboard?.writeText(plain);\n      } catch {\n        return;\n      }\n    }\n    setCopied(true);\n  };\n\n  const findSource = (ref: string) => {\n    if (!sources) return undefined;\n    const index = /^\\d+$/.test(ref)\n      ? Number(ref) - 1\n      : sources.findIndex((item) => item.id === ref);\n    return index >= 0 && index < sources.length\n      ? { source: sources[index], number: index + 1 }\n      : undefined;\n  };\n\n  const renderSegment = (\n    segment: InsightSegment,\n    index: number,\n  ): React.ReactNode => {\n    if (typeof segment === \"string\") return segment;\n    const custom = renderToken?.(segment, index);\n    if (custom !== undefined) return custom;\n    if (segment.kind === \"metric\") return <MetricChip token={segment} />;\n    if (segment.kind === \"cite\") {\n      const found = findSource(segment.label);\n      const number = found?.number ?? segment.label;\n      const chip = cn(\n        \"mx-px inline-flex h-4 min-w-4 -translate-y-px items-center justify-center rounded-[4px] bg-muted px-1 align-middle font-mono text-[10px] leading-none font-medium text-muted-foreground transition-colors\",\n        \"transition-[opacity,background-color,color] duration-300 starting:opacity-0 motion-reduce:transition-none\",\n      );\n      const highlight = {\n        onPointerEnter: () => found && setHoveredSource(found.source.id),\n        onPointerLeave: () => setHoveredSource(null),\n        onFocus: () => found && setHoveredSource(found.source.id),\n        onBlur: () => setHoveredSource(null),\n      };\n      return found?.source.href ? (\n        <a\n          data-slot=\"insight-token\"\n          data-kind=\"cite\"\n          href={found.source.href}\n          target=\"_blank\"\n          rel=\"noreferrer\"\n          aria-label={`${labels.sources} ${number}: ${found.source.label}`}\n          className={cn(\n            chip,\n            \"hover:bg-(--insight-accent)/12 hover:text-(--insight-accent)\",\n            focusRing,\n          )}\n          {...highlight}\n        >\n          {number}\n        </a>\n      ) : (\n        <span\n          data-slot=\"insight-token\"\n          data-kind=\"cite\"\n          title={found?.source.label}\n          className={cn(\n            chip,\n            found &&\n              \"cursor-default hover:bg-(--insight-accent)/12 hover:text-(--insight-accent)\",\n          )}\n          {...highlight}\n        >\n          {number}\n        </span>\n      );\n    }\n    return (\n      <span\n        data-slot=\"insight-token\"\n        data-kind={segment.kind}\n        className=\"font-medium\"\n      >\n        {segment.label}\n      </span>\n    );\n  };\n\n  // Paragraphs on blank lines, line breaks on single newlines. A paragraph made only\n  // of tokens becomes a row of highlights.\n  const paragraphs: { nodes: React.ReactNode[]; prose: boolean }[] = [\n    { nodes: [], prose: false },\n  ];\n  let attachedCitation = -1;\n  segments.forEach((segment, index) => {\n    if (index === attachedCitation) return;\n    if (typeof segment !== \"string\") {\n      paragraphs[paragraphs.length - 1].nodes.push(\n        <React.Fragment key={index}>\n          {renderSegment(segment, index)}\n        </React.Fragment>,\n      );\n      return;\n    }\n    // Keep a citation with its last word, including in narrow previews.\n    const next = segments[index + 1];\n    const lastWord =\n      typeof next === \"object\" && next.kind === \"cite\" && !/[\\r\\n]$/.test(segment)\n        ? segment.match(/(\\S+[^\\S\\r\\n]*)$/)\n        : null;\n    const content = lastWord ? segment.slice(0, lastWord.index) : segment;\n    content.split(/\\n{2,}/).forEach((chunk, part) => {\n      if (part > 0) paragraphs.push({ nodes: [], prose: false });\n      chunk.split(\"\\n\").forEach((line, row) => {\n        const target = paragraphs[paragraphs.length - 1];\n        if (row > 0)\n          target.nodes.push(<br key={`${index}-${part}-${row}-br`} />);\n        if (line.trim()) target.prose = true;\n        if (line)\n          target.nodes.push(\n            <React.Fragment key={`${index}-${part}-${row}`}>\n              {line}\n            </React.Fragment>,\n          );\n      });\n    });\n    if (lastWord) {\n      const target = paragraphs[paragraphs.length - 1];\n      target.prose = true;\n      target.nodes.push(\n        <span key={`${index}-citation`} className=\"inline-block max-w-full\">\n          {lastWord[0]}\n          {renderSegment(next, index + 1)}\n        </span>,\n      );\n      attachedCitation = index + 1;\n    }\n  });\n\n  const busy = status === \"thinking\" || status === \"streaming\";\n  const colorVars = colors\n    ? ({\n        ...(colors.accent && { \"--insight-accent\": colors.accent }),\n        ...(colors.glow && { \"--insight-glow\": colors.glow }),\n        ...(colors.positive && { \"--insight-positive\": colors.positive }),\n        ...(colors.negative && { \"--insight-negative\": colors.negative }),\n      } as React.CSSProperties)\n    : undefined;\n\n  const button = cn(\n    \"inline-flex h-7 items-center justify-center gap-1.5 rounded-md text-xs font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-40 motion-reduce:transition-none\",\n    focusRing,\n  );\n\n  return (\n    <div\n      data-slot=\"insight-card\"\n      data-status={status}\n      aria-busy={busy || undefined}\n      className={cn(\n        \"@container/insight relative isolate flex min-w-0 flex-col rounded-xl border bg-card text-card-foreground shadow-xs\",\n        \"[--insight-accent:var(--color-primary)] [--insight-glow:var(--color-chart-4)] [--insight-negative:var(--color-destructive)] [--insight-positive:var(--color-emerald-600)] dark:[--insight-positive:var(--color-emerald-400)]\",\n        className,\n      )}\n      style={{ ...colorVars, ...style }}\n      {...props}\n    >\n      <style href=\"overtrue-insight-card\" precedence=\"default\">\n        {styles}\n      </style>\n\n      {colors?.glow && (\n        <>\n          <span\n            aria-hidden=\"true\"\n            data-slot=\"insight-glow\"\n            className={cn(\n              \"pointer-events-none absolute -inset-px -z-10 rounded-[inherit] blur-md transition-opacity duration-700 motion-safe:animate-[insight-spin_3.2s_linear_infinite] motion-reduce:transition-none\",\n              busy ? \"opacity-35 dark:opacity-45\" : \"opacity-0\",\n            )}\n            style={{ background: ring }}\n          />\n          <span\n            aria-hidden=\"true\"\n            className=\"pointer-events-none absolute inset-0 -z-5 rounded-[inherit] bg-card\"\n          />\n          <span\n            aria-hidden=\"true\"\n            className={cn(\n              \"pointer-events-none absolute -inset-px rounded-[inherit] transition-opacity duration-700 motion-safe:animate-[insight-spin_3.2s_linear_infinite] motion-reduce:transition-none\",\n              busy ? \"opacity-100\" : \"opacity-0\",\n            )}\n            style={{ ...ringMask, background: ring }}\n          />\n        </>\n      )}\n\n      <div className=\"relative flex flex-wrap items-center gap-x-3 gap-y-2 px-4 pt-3.5 @sm/insight:px-5 @sm/insight:pt-4\">\n        <div className=\"flex min-w-0 flex-1 basis-full items-center gap-2.5 @lg/insight:basis-44\">\n          <span\n            aria-hidden=\"true\"\n            className=\"flex size-7 shrink-0 items-center justify-center rounded-lg bg-muted text-(--insight-accent)\"\n          >\n            {icon ?? (\n              <FileAnalytics className=\"size-4\" stroke={1.75} />\n            )}\n          </span>\n          <div className=\"flex min-w-0 flex-wrap items-baseline gap-x-2 gap-y-0.5\">\n            <div className=\"text-sm leading-5 font-semibold tracking-tight [overflow-wrap:anywhere]\">\n              {title}\n            </div>\n            {busy && (\n              <div\n                data-slot=\"insight-progress\"\n                className=\"hidden shrink-0 bg-linear-to-r from-muted-foreground @xs/insight:block via-foreground to-muted-foreground bg-size-[200%_100%] bg-clip-text text-xs text-transparent motion-safe:animate-[insight-shimmer_1.8s_linear_infinite] motion-reduce:text-muted-foreground\"\n              >\n                {status === \"thinking\" ? labels.thinking : labels.streaming}\n              </div>\n            )}\n          </div>\n        </div>\n        {source && (\n          <div\n            data-slot=\"insight-source-label\"\n            className=\"flex min-w-0 items-center gap-1.5 pl-9.5 text-xs leading-5 text-muted-foreground [overflow-wrap:anywhere] @lg/insight:pl-0\"\n          >\n            {source}\n          </div>\n        )}\n      </div>\n\n      <div className=\"relative px-4 pt-3 pb-4 @sm/insight:px-5\">\n        {status === \"thinking\" ? (\n          <div\n            data-slot=\"insight-skeleton\"\n            className=\"space-y-2.5 py-1\"\n            aria-hidden=\"true\"\n          >\n            {[92, 100, 78, 56].map((width, index) => (\n              <div\n                key={index}\n                className=\"h-2.5 rounded-full bg-linear-to-r from-muted via-foreground/[0.07] to-muted bg-size-[200%_100%] motion-safe:animate-[insight-shimmer_1.6s_linear_infinite] dark:via-foreground/[0.1]\"\n                style={{\n                  width: `${width}%`,\n                  animationDelay: `${index * 120}ms`,\n                }}\n              />\n            ))}\n          </div>\n        ) : status === \"error\" ? (\n          <div\n            data-slot=\"insight-error\"\n            role=\"alert\"\n            className=\"flex items-start gap-3 rounded-lg border border-destructive/25 bg-destructive/[0.06] p-3\"\n          >\n            <AlertTriangle\n              className=\"mt-0.5 size-4 shrink-0 text-destructive\"\n              aria-hidden=\"true\"\n            />\n            <div className=\"min-w-0 flex-1\">\n              <div className=\"text-sm font-medium\">{labels.error}</div>\n              {error && (\n                <div className=\"mt-0.5 text-xs leading-5 text-muted-foreground\">\n                  {error}\n                </div>\n              )}\n              {onRegenerate && (\n                <button\n                  type=\"button\"\n                  onClick={onRegenerate}\n                  className={cn(\n                    \"mt-2 inline-flex h-7 items-center gap-1.5 rounded-md border bg-card px-2.5 text-xs font-medium shadow-xs transition-colors hover:bg-muted motion-reduce:transition-none\",\n                    focusRing,\n                  )}\n                >\n                  <Refresh className=\"size-3.5\" aria-hidden=\"true\" />\n                  {labels.retry}\n                </button>\n              )}\n            </div>\n          </div>\n        ) : status === \"idle\" ? (\n          <div className=\"flex items-center justify-between gap-3 rounded-lg border border-dashed px-3 py-2.5\">\n            <span className=\"text-sm text-muted-foreground\">{labels.idle}</span>\n            {onRegenerate && (\n              <button\n                type=\"button\"\n                onClick={onRegenerate}\n                className={cn(\n                  \"inline-flex h-7 items-center gap-1.5 rounded-md bg-primary px-2.5 text-xs font-medium text-primary-foreground shadow-xs transition-opacity hover:opacity-90 motion-reduce:transition-none\",\n                  focusRing,\n                )}\n              >\n                <FileAnalytics className=\"size-3.5\" aria-hidden=\"true\" />\n                {labels.generate}\n              </button>\n            )}\n          </div>\n        ) : (\n          <div\n            data-slot=\"insight-body\"\n            className=\"space-y-3 text-sm leading-6 text-pretty text-foreground/90\"\n          >\n            {paragraphs.map((paragraph, index) => {\n              const caret = status === \"streaming\" &&\n                index === paragraphs.length - 1 && (\n                  <span\n                    aria-hidden=\"true\"\n                    data-slot=\"insight-caret\"\n                    className=\"ml-0.5 inline-block h-[1.05em] w-[2px] translate-y-[0.18em] rounded-full bg-(--insight-accent) motion-safe:animate-[insight-caret_1s_linear_infinite]\"\n                  />\n                );\n              return paragraph.prose || paragraph.nodes.length === 0 ? (\n                <p key={index} className=\"break-words\">\n                  {paragraph.nodes}\n                  {caret}\n                </p>\n              ) : (\n                <div\n                  key={index}\n                  data-slot=\"insight-highlights\"\n                  className=\"flex flex-wrap items-center gap-1.5 [&_[data-slot=insight-token]]:mx-0\"\n                >\n                  {paragraph.nodes}\n                  {caret}\n                </div>\n              );\n            })}\n          </div>\n        )}\n\n        {status === \"done\" && sources && sources.length > 0 && (\n          <div\n            data-slot=\"insight-sources\"\n            className=\"mt-3.5 flex flex-wrap items-center gap-1.5 transition-[opacity,translate] duration-500 ease-out starting:translate-y-1 starting:opacity-0 motion-reduce:transition-none\"\n          >\n            <span className=\"mr-0.5 text-xs text-muted-foreground\">\n              {labels.sources}\n            </span>\n            {sources.map((item, index) => {\n              const content = (\n                <>\n                  <span className=\"flex h-4 min-w-4 items-center justify-center rounded-[4px] bg-muted px-1 font-mono text-[10px] leading-none font-medium text-muted-foreground\">\n                    {index + 1}\n                  </span>\n                  <span className=\"min-w-0 truncate\">{item.label}</span>\n                  {item.href && (\n                    <ArrowUpRight\n                      className=\"size-3 shrink-0 text-muted-foreground\"\n                      aria-hidden=\"true\"\n                    />\n                  )}\n                </>\n              );\n              const chip = cn(\n                \"inline-flex h-6 max-w-full min-w-0 items-center gap-1.5 rounded-md border bg-card pr-2 pl-1 text-xs transition-colors motion-reduce:transition-none\",\n                hoveredSource === item.id &&\n                  \"border-(--insight-accent)/40 bg-(--insight-accent)/[0.06]\",\n              );\n              return item.href ? (\n                <a\n                  key={item.id}\n                  data-slot=\"insight-source\"\n                  data-active={hoveredSource === item.id || undefined}\n                  href={item.href}\n                  target=\"_blank\"\n                  rel=\"noreferrer\"\n                  className={cn(chip, \"hover:bg-muted\", focusRing)}\n                >\n                  {content}\n                </a>\n              ) : (\n                <span\n                  key={item.id}\n                  data-slot=\"insight-source\"\n                  data-active={hoveredSource === item.id || undefined}\n                  className={chip}\n                >\n                  {content}\n                </span>\n              );\n            })}\n          </div>\n        )}\n      </div>\n\n      {status !== \"idle\" && status !== \"error\" && (\n        <div\n          data-slot=\"insight-actions\"\n          className=\"relative mt-auto flex items-center gap-1 border-t px-2 py-1.5 @sm/insight:px-3\"\n        >\n          {busy && onStop ? (\n            <button\n              type=\"button\"\n              onClick={onStop}\n              className={cn(button, \"px-2\")}\n            >\n              <Stop className=\"size-3\" aria-hidden=\"true\" />\n              {labels.stop}\n            </button>\n          ) : (\n            onRegenerate && (\n              <button\n                type=\"button\"\n                onClick={onRegenerate}\n                disabled={busy}\n                aria-label={labels.regenerate}\n                title={labels.regenerate}\n                className={cn(button, \"px-2\")}\n              >\n                <Refresh className=\"size-3.5\" aria-hidden=\"true\" />\n                <span className=\"hidden @xs/insight:inline\">\n                  {labels.regenerate}\n                </span>\n              </button>\n            )\n          )}\n          <button\n            type=\"button\"\n            onClick={copy}\n            disabled={busy || !plain}\n            aria-label={copied ? labels.copied : labels.copy}\n            title={labels.copy}\n            className={cn(button, \"px-2\")}\n          >\n            {copied ? (\n              <Check\n                className=\"size-3.5 text-(--insight-positive)\"\n                aria-hidden=\"true\"\n              />\n            ) : (\n              <Copy className=\"size-3.5\" aria-hidden=\"true\" />\n            )}\n            <span className=\"hidden @xs/insight:inline\">\n              {copied ? labels.copied : labels.copy}\n            </span>\n          </button>\n          {actions}\n          <div\n            className=\"ml-auto flex items-center gap-0.5\"\n            role=\"group\"\n            aria-label={labels.feedback}\n          >\n            <button\n              type=\"button\"\n              aria-pressed={feedback === \"up\"}\n              aria-label={labels.helpful}\n              title={labels.helpful}\n              disabled={busy || status !== \"done\"}\n              onClick={() => setFeedback(\"up\")}\n              className={cn(\n                button,\n                \"size-7\",\n                feedback === \"up\" &&\n                  \"text-(--insight-accent) hover:text-(--insight-accent)\",\n              )}\n            >\n              {feedback === \"up\" ? (\n                <ThumbUpFilled className=\"size-3.5\" aria-hidden=\"true\" />\n              ) : (\n                <ThumbUp className=\"size-3.5\" aria-hidden=\"true\" />\n              )}\n            </button>\n            <button\n              type=\"button\"\n              aria-pressed={feedback === \"down\"}\n              aria-label={labels.notHelpful}\n              title={labels.notHelpful}\n              disabled={busy || status !== \"done\"}\n              onClick={() => setFeedback(\"down\")}\n              className={cn(\n                button,\n                \"size-7\",\n                feedback === \"down\" && \"text-foreground\",\n              )}\n            >\n              {feedback === \"down\" ? (\n                <ThumbDownFilled className=\"size-3.5\" aria-hidden=\"true\" />\n              ) : (\n                <ThumbDown className=\"size-3.5\" aria-hidden=\"true\" />\n              )}\n            </button>\n          </div>\n        </div>\n      )}\n\n      {/* Announce once: the finished text, not every token. */}\n      <div className=\"sr-only\" aria-live=\"polite\" aria-atomic=\"true\">\n        {status === \"done\"\n          ? plain\n          : status === \"thinking\"\n            ? labels.thinking\n            : \"\"}\n      </div>\n    </div>\n  );\n}\n"
    },
    {
      "path": "src/registry/overtrue/latency-histogram.tsx",
      "type": "registry:component",
      "target": "components/overtrue/latency-histogram.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { IconX as X } from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport type LatencyScale = \"linear\" | \"log\";\n\nexport type LatencyRange = [min: number, max: number];\n\nexport interface LatencyBucket {\n  /** Inclusive lower edge. */\n  start: number;\n  /** Exclusive upper edge. */\n  end: number;\n  count: number;\n}\n\n/** One bar as drawn, passed to `renderTooltip`. */\nexport interface LatencyHistogramBucket extends LatencyBucket {\n  index: number;\n  /** Share of all requests in this bucket, 0–1. */\n  share: number;\n  /** Share of requests at or below this bucket's upper edge, 0–1. */\n  cumulative: number;\n  /** Raw comparison count in the same range, when `compare` is set. */\n  compare?: number;\n  /** Comparison share of its own total, 0–1. */\n  compareShare?: number;\n  /** The catch-all bar for values past the linear domain. */\n  overflow: boolean;\n  /** Whether the bucket lies past `threshold`. */\n  overThreshold: boolean;\n}\n\nexport interface LatencyHistogramColors {\n  bar: string;\n  compare: string;\n  threshold: string;\n  marker: string;\n  selection: string;\n}\n\nexport interface LatencyHistogramProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"title\" | \"children\" | \"color\"\n> {\n  /** Raw samples. Bucketed for you, with exact percentiles. */\n  values?: number[];\n  /** Pre-bucketed counts, used when `values` is not given. Percentiles are interpolated. */\n  buckets?: LatencyBucket[];\n  /** A comparison distribution, e.g. yesterday. Scaled to the main total so shapes compare. */\n  compare?: number[] | LatencyBucket[];\n  /** Name of the comparison in the legend and tooltip. */\n  compareLabel?: string;\n  /** Name of the main series in the legend. */\n  seriesLabel?: string;\n  /** Draw the comparison as a stepped line or as outlined bars. */\n  compareStyle?: \"step\" | \"outline\";\n  /** Percentiles to mark, as numbers such as 50 or 99.9. */\n  percentiles?: number[];\n  /** Latency objective. The slow tail past it is shaded and measured. */\n  threshold?: number;\n  thresholdLabel?: string;\n  /** X scale. Pass with `onScaleChange` to control the built-in toggle. */\n  scale?: LatencyScale;\n  defaultScale?: LatencyScale;\n  onScaleChange?: (scale: LatencyScale) => void;\n  /** Show the linear/log toggle. Defaults to true. */\n  showScaleToggle?: boolean;\n  /** Brushed range. Pass `null` for none; leave undefined to let the component manage it. */\n  range?: LatencyRange | null;\n  defaultRange?: LatencyRange | null;\n  onRangeChange?: (range: LatencyRange | null) => void;\n  title?: React.ReactNode;\n  description?: React.ReactNode;\n  /** Controls placed at the top right, before the scale toggle. */\n  actions?: React.ReactNode;\n  /** Unit of the values. Defaults to \"ms\"; ms readouts switch to seconds from 1,000. */\n  unit?: string;\n  /** Formats latencies in readouts, markers, and ticks. */\n  valueFormatter?: (value: number) => string;\n  /** Target number of bars. Defaults to 40. */\n  bucketCount?: number;\n  /** Fix the latency domain. Linear charts otherwise end near p99.5 and gather the rest in an overflow bar. */\n  domain?: LatencyRange;\n  /** Plot height in pixels. Defaults to a third of the plot width, between 140 and 220. */\n  height?: number;\n  /** Override any series color with a CSS color. */\n  colors?: Partial<LatencyHistogramColors>;\n  /** Replaces the hover tooltip content. */\n  renderTooltip?: (bucket: LatencyHistogramBucket) => React.ReactNode;\n  /** Show the percentile summary above the plot. Defaults to true. */\n  showSummary?: boolean;\n}\n\n/* ------------------------------------------------------------------------ */\n/* Formatting                                                                */\n/* ------------------------------------------------------------------------ */\n\nconst tidy = (value: number) => +value.toPrecision(12);\nconst compact = new Intl.NumberFormat(\"en-US\", {\n  notation: \"compact\",\n  maximumFractionDigits: 1,\n});\nconst whole = new Intl.NumberFormat(\"en-US\");\n\nfunction makeFormatter(unit: string) {\n  const tight = unit.length <= 2;\n  const join = (text: string, u: string) =>\n    u ? `${text}${tight ? \"\" : \" \"}${u}` : text;\n  return (value: number) => {\n    if (!Number.isFinite(value)) return \"—\";\n    const a = Math.abs(value);\n    if (unit === \"ms\" && a >= 1000)\n      return `${tidy(+(value / 1000).toFixed(a >= 10_000 ? 1 : 2))}s`;\n    const digits = a >= 100 || a === 0 ? 0 : a >= 10 ? 1 : a >= 1 ? 2 : 3;\n    return join(String(tidy(+value.toFixed(digits))), unit);\n  };\n}\n\nfunction makeTickFormatter(unit: string) {\n  const tight = unit.length <= 2;\n  return (value: number) => {\n    if (value === 0) return \"0\";\n    if (unit === \"ms\" && Math.abs(value) >= 1000)\n      return `${tidy(value / 1000)}s`;\n    return `${tidy(value)}${tight ? \"\" : \" \"}${unit}`;\n  };\n}\n\nfunction percentLabel(share: number) {\n  const pct = share * 100;\n  if (pct === 0) return \"0%\";\n  if (pct < 0.1) return \"<0.1%\";\n  if (pct > 99.9 && pct < 100) return \">99.9%\";\n  return `${pct >= 10 ? pct.toFixed(1) : pct.toFixed(2)}%`;\n}\n\nfunction niceStep(raw: number) {\n  if (!(raw > 0)) return 1;\n  const magnitude = 10 ** Math.floor(Math.log10(raw));\n  const r = raw / magnitude;\n  return (\n    (r <= 1 ? 1 : r <= 2 ? 2 : r <= 2.5 ? 2.5 : r <= 5 ? 5 : 10) * magnitude\n  );\n}\n\n/** Round down or up to the nearest 1, 2, or 5 times a power of ten. */\nfunction nice125(value: number, up: boolean) {\n  const magnitude = 10 ** Math.floor(Math.log10(value));\n  const r = value / magnitude;\n  const steps = [1, 2, 5, 10];\n  if (up) return (steps.find((s) => s >= r - 1e-9) ?? 10) * magnitude;\n  return ([...steps].reverse().find((s) => s <= r + 1e-9) ?? 1) * magnitude;\n}\n\nfunction lowerBound(sorted: Float64Array, value: number) {\n  let lo = 0;\n  let hi = sorted.length;\n  while (lo < hi) {\n    const mid = (lo + hi) >> 1;\n    if (sorted[mid] < value) lo = mid + 1;\n    else hi = mid;\n  }\n  return lo;\n}\n\nfunction upperBound(sorted: Float64Array, value: number) {\n  let lo = 0;\n  let hi = sorted.length;\n  while (lo < hi) {\n    const mid = (lo + hi) >> 1;\n    if (sorted[mid] <= value) lo = mid + 1;\n    else hi = mid;\n  }\n  return lo;\n}\n\n/* ------------------------------------------------------------------------ */\n/* Model                                                                     */\n/* ------------------------------------------------------------------------ */\n\ninterface Bar extends LatencyBucket {\n  overflow: boolean;\n  /** Left and right edges as 0–1 positions. */\n  x0: number;\n  x1: number;\n}\n\ninterface Distribution {\n  sorted: Float64Array | null;\n  buckets: LatencyBucket[] | null;\n  total: number;\n  min: number;\n  max: number;\n  mean: number;\n}\n\nfunction distributionOf(\n  values?: number[],\n  buckets?: LatencyBucket[],\n): Distribution {\n  if (values) {\n    const clean = values.filter((value) => Number.isFinite(value));\n    const sorted = Float64Array.from(clean).sort();\n    let sum = 0;\n    for (const value of sorted) sum += value;\n    return {\n      sorted,\n      buckets: null,\n      total: sorted.length,\n      min: sorted.length ? sorted[0] : 0,\n      max: sorted.length ? sorted[sorted.length - 1] : 0,\n      mean: sorted.length ? sum / sorted.length : 0,\n    };\n  }\n  const list = (buckets ?? [])\n    .filter(\n      (b) =>\n        Number.isFinite(b.start) && Number.isFinite(b.end) && b.end > b.start,\n    )\n    .sort((a, b) => a.start - b.start);\n  let total = 0;\n  let sum = 0;\n  for (const b of list) {\n    total += Math.max(0, b.count);\n    sum += (Math.max(0, b.count) * (b.start + b.end)) / 2;\n  }\n  return {\n    sorted: null,\n    buckets: list,\n    total,\n    min: list.length ? list[0].start : 0,\n    max: list.length ? list[list.length - 1].end : 0,\n    mean: total ? sum / total : 0,\n  };\n}\n\n/** Nearest-rank percentile from samples; interpolated inside buckets otherwise. */\nfunction quantile(d: Distribution, p: number) {\n  if (!d.total) return 0;\n  if (d.sorted)\n    return d.sorted[\n      Math.min(d.total - 1, Math.max(0, Math.ceil(p * d.total) - 1))\n    ];\n  const target = p * d.total;\n  let cumulative = 0;\n  for (const b of d.buckets!) {\n    if (cumulative + b.count >= target && b.count > 0)\n      return b.start + ((target - cumulative) / b.count) * (b.end - b.start);\n    cumulative += b.count;\n  }\n  return d.max;\n}\n\n/** Requests with a value in [a, b]. Partial buckets count in proportion. */\nfunction countBetween(d: Distribution, a: number, b: number) {\n  if (d.sorted) return upperBound(d.sorted, b) - lowerBound(d.sorted, a);\n  let count = 0;\n  for (const bucket of d.buckets!) {\n    const overlap = Math.min(b, bucket.end) - Math.max(a, bucket.start);\n    if (overlap > 0)\n      count += (bucket.count * overlap) / (bucket.end - bucket.start);\n  }\n  return count;\n}\n\nfunction countAbove(d: Distribution, value: number) {\n  if (d.sorted) return d.total - upperBound(d.sorted, value);\n  return countBetween(d, value, Infinity);\n}\n\ninterface Layout {\n  bars: Bar[];\n  lo: number;\n  hi: number;\n  /** Largest value covered, including the overflow bar. */\n  top: number;\n  pos: (value: number) => number;\n  inv: (x: number) => number;\n}\n\nfunction layoutOf(\n  d: Distribution,\n  scale: LatencyScale,\n  bucketCount: number,\n  reach: number,\n  domain?: LatencyRange,\n): Layout {\n  const count = Math.max(4, Math.round(bucketCount));\n  // Pre-bucketed data keeps its own edges.\n  if (d.buckets) {\n    const list = d.buckets;\n    const first = list[0]?.start ?? 0;\n    const last = list[list.length - 1]?.end ?? 1;\n    if (scale === \"log\") {\n      const positive =\n        list.find((b) => b.start > 0)?.start ?? list[0]?.end ?? 1;\n      const lo = first > 0 ? first : positive / 2;\n      const span = Math.log(last / lo) || 1;\n      const pos = (v: number) =>\n        Math.min(1, Math.max(0, Math.log(Math.max(v, lo) / lo) / span));\n      const inv = (x: number) => lo * Math.exp(x * span);\n      return {\n        bars: list.map((b) => ({\n          ...b,\n          overflow: false,\n          x0: pos(b.start),\n          x1: pos(b.end),\n        })),\n        lo,\n        hi: last,\n        top: last,\n        pos,\n        inv,\n      };\n    }\n    const span = last - first || 1;\n    const pos = (v: number) => Math.min(1, Math.max(0, (v - first) / span));\n    const inv = (x: number) => first + x * span;\n    return {\n      bars: list.map((b) => ({\n        ...b,\n        overflow: false,\n        x0: pos(b.start),\n        x1: pos(b.end),\n      })),\n      lo: first,\n      hi: last,\n      top: last,\n      pos,\n      inv,\n    };\n  }\n\n  const sorted = d.sorted!;\n  if (scale === \"log\") {\n    const positive = sorted[lowerBound(sorted, Number.MIN_VALUE)] ?? 1;\n    const lo =\n      domain?.[0] && domain[0] > 0\n        ? domain[0]\n        : nice125(Math.max(positive, 1e-9), false);\n    const hi = Math.max(\n      domain?.[1] ?? nice125(Math.max(d.max, lo * 10), true),\n      lo * 1.0001,\n    );\n    const span = Math.log(hi / lo);\n    const step = span / count;\n    const bars: Bar[] = Array.from({ length: count }, (_, i) => ({\n      start: lo * Math.exp(i * step),\n      end: lo * Math.exp((i + 1) * step),\n      count: 0,\n      overflow: false,\n      x0: i / count,\n      x1: (i + 1) / count,\n    }));\n    for (const v of sorted) {\n      const i = v <= lo ? 0 : Math.floor(Math.log(v / lo) / step);\n      bars[Math.min(count - 1, Math.max(0, i))].count += 1;\n    }\n    const pos = (v: number) =>\n      Math.min(1, Math.max(0, Math.log(Math.max(v, lo) / lo) / span));\n    return { bars, lo, hi, top: hi, pos, inv: (x) => lo * Math.exp(x * span) };\n  }\n\n  const lo = domain?.[0] ?? (d.min >= 0 ? 0 : -niceStep(-d.min));\n  const wanted = domain?.[1] ?? Math.max(reach, lo + 1e-9);\n  const step = niceStep((wanted - lo) / count);\n  const n = Math.max(1, Math.ceil((wanted - lo) / step - 1e-9));\n  const hi = lo + n * step;\n  const overflowCount = d.total - upperBound(sorted, hi);\n  const units = overflowCount > 0 ? n + 1.7 : n;\n  const bars: Bar[] = Array.from({ length: n }, (_, i) => ({\n    start: tidy(lo + i * step),\n    end: tidy(lo + (i + 1) * step),\n    count: 0,\n    overflow: false,\n    x0: i / units,\n    x1: (i + 1) / units,\n  }));\n  for (\n    let k = lowerBound(sorted, lo), end = upperBound(sorted, hi);\n    k < end;\n    k++\n  )\n    bars[Math.min(n - 1, Math.floor((sorted[k] - lo) / step))].count += 1;\n  // Values below a fixed domain fold into the first bar.\n  bars[0].count += lowerBound(sorted, lo);\n  const top = Math.max(hi, d.max);\n  if (overflowCount > 0)\n    bars.push({\n      start: hi,\n      end: top,\n      count: overflowCount,\n      overflow: true,\n      x0: (n + 0.7) / units,\n      x1: 1,\n    });\n  const mainEnd = n / units;\n  const overflowStart = (n + 0.7) / units;\n  const pos = (v: number) => {\n    if (v <= hi) return Math.max(0, ((v - lo) / (hi - lo)) * mainEnd);\n    if (overflowCount <= 0 || top <= hi) return mainEnd;\n    return Math.min(\n      1,\n      overflowStart + ((v - hi) / (top - hi)) * (1 - overflowStart),\n    );\n  };\n  const inv = (x: number) => {\n    if (x <= mainEnd) return lo + (x / mainEnd) * (hi - lo);\n    if (x < overflowStart || overflowCount <= 0) return hi;\n    return hi + ((x - overflowStart) / (1 - overflowStart)) * (top - hi);\n  };\n  return { bars, lo, hi, top, pos, inv };\n}\n\n/** Bin a comparison into the main bars' edges. */\nfunction binCompare(compare: number[] | LatencyBucket[], bars: Bar[]) {\n  const counts = new Array<number>(bars.length).fill(0);\n  if (!bars.length) return { counts, total: 0 };\n  const find = (v: number) => {\n    let lo = 0;\n    let hi = bars.length - 1;\n    while (lo < hi) {\n      const mid = (lo + hi + 1) >> 1;\n      if (bars[mid].start <= v) lo = mid;\n      else hi = mid - 1;\n    }\n    return lo;\n  };\n  let total = 0;\n  for (const item of compare as (number | LatencyBucket)[]) {\n    if (typeof item === \"number\") {\n      if (!Number.isFinite(item)) continue;\n      counts[find(item)] += 1;\n      total += 1;\n    } else if (Number.isFinite(item.count)) {\n      counts[find((item.start + item.end) / 2)] += item.count;\n      total += item.count;\n    }\n  }\n  return { counts, total };\n}\n\n/* ------------------------------------------------------------------------ */\n/* Hooks                                                                     */\n/* ------------------------------------------------------------------------ */\n\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (onChange) => {\n      const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n      query.addEventListener(\"change\", onChange);\n      return () => query.removeEventListener(\"change\", onChange);\n    },\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\nfunction useControllable<T>(\n  value: T | undefined,\n  defaultValue: T,\n  onChange?: (value: T) => void,\n) {\n  const [inner, setInner] = React.useState(defaultValue);\n  const controlled = value !== undefined;\n  const set = React.useCallback(\n    (next: T) => {\n      if (!controlled) setInner(next);\n      onChange?.(next);\n    },\n    [controlled, onChange],\n  );\n  return [controlled ? value : inner, set] as const;\n}\n\nconst focusRing =\n  \"outline-none focus-visible:ring-2 focus-visible:ring-ring/50\";\nconst percentileName = (p: number) => `p${tidy(p)}`;\n\n/* ------------------------------------------------------------------------ */\n/* LatencyHistogram                                                          */\n/* ------------------------------------------------------------------------ */\n\n/**\n * A latency distribution: bucketed requests with percentile markers, an SLO tail,\n * an optional comparison, and brushing to measure any range.\n */\nexport function LatencyHistogram({\n  values,\n  buckets,\n  compare,\n  compareLabel = \"Previous\",\n  seriesLabel = \"Current\",\n  compareStyle = \"step\",\n  percentiles = [50, 90, 95, 99],\n  threshold,\n  thresholdLabel = \"SLO\",\n  scale: scaleProp,\n  defaultScale = \"linear\",\n  onScaleChange,\n  showScaleToggle = true,\n  range: rangeProp,\n  defaultRange = null,\n  onRangeChange,\n  title,\n  description,\n  actions,\n  unit = \"ms\",\n  valueFormatter,\n  bucketCount = 40,\n  domain,\n  height,\n  colors: colorsProp,\n  renderTooltip,\n  showSummary = true,\n  className,\n  ...props\n}: LatencyHistogramProps) {\n  const id = React.useId();\n  const reduced = useReducedMotion();\n  const format = React.useMemo(\n    () => valueFormatter ?? makeFormatter(unit),\n    [valueFormatter, unit],\n  );\n  const formatTick = React.useMemo(\n    () => valueFormatter ?? makeTickFormatter(unit),\n    [valueFormatter, unit],\n  );\n  const colors: LatencyHistogramColors = {\n    bar: \"var(--color-chart-1)\",\n    compare: \"var(--color-muted-foreground)\",\n    threshold: \"var(--color-destructive)\",\n    marker: \"var(--color-foreground)\",\n    selection: \"var(--color-primary)\",\n    ...colorsProp,\n  };\n  const [scale, setScale] = useControllable(\n    scaleProp,\n    defaultScale,\n    onScaleChange,\n  );\n  const [range, setRange] = useControllable<LatencyRange | null>(\n    rangeProp,\n    defaultRange,\n    onRangeChange,\n  );\n  const hasThreshold = threshold != null && Number.isFinite(threshold);\n\n  const dist = React.useMemo(\n    () => distributionOf(values, buckets),\n    [values, buckets],\n  );\n  const sortedPercentiles = React.useMemo(\n    () =>\n      [...new Set(percentiles.filter((p) => p > 0 && p < 100))].sort(\n        (a, b) => a - b,\n      ),\n    [percentiles],\n  );\n  const empty = dist.total === 0;\n  const marks = React.useMemo(\n    () =>\n      dist.total === 0\n        ? []\n        : sortedPercentiles.map((p) => ({ p, value: quantile(dist, p / 100) })),\n    [dist, sortedPercentiles],\n  );\n\n  // Linear charts end just past the slow tail (and the SLO); the rest lands in an overflow bar.\n  const reach = Math.max(\n    quantile(dist, 0.995),\n    (marks[marks.length - 1]?.value ?? 0) * 1.04,\n    hasThreshold ? threshold! * 1.12 : 0,\n  );\n  const layout = React.useMemo(\n    () => layoutOf(dist, scale, bucketCount, reach, domain),\n    [dist, scale, bucketCount, reach, domain],\n  );\n  const { bars, pos, inv } = layout;\n\n  const comparison = React.useMemo(() => {\n    if (!compare?.length) return null;\n    const { counts, total } = binCompare(compare, bars);\n    const percentilesOf = (() => {\n      if (typeof compare[0] === \"number\") {\n        const d = distributionOf(compare as number[]);\n        return sortedPercentiles.map((p) => quantile(d, p / 100));\n      }\n      const d = distributionOf(undefined, compare as LatencyBucket[]);\n      return sortedPercentiles.map((p) => quantile(d, p / 100));\n    })();\n    const factor = total ? dist.total / total : 0;\n    return {\n      counts,\n      total,\n      scaled: counts.map((c) => c * factor),\n      percentiles: percentilesOf,\n    };\n  }, [compare, bars, dist.total, sortedPercentiles]);\n\n  const maxCount = Math.max(\n    1,\n    ...bars.map((b) => b.count),\n    ...(comparison?.scaled ?? [0]),\n  );\n  // The tallest bar fills the plot; gridlines sit at round counts below it.\n  const yMax = maxCount * 1.06;\n  const yStep = niceStep(maxCount / 3.2);\n  const yTicks = Array.from(\n    { length: Math.floor(yMax / yStep + 1e-9) + 1 },\n    (_, i) => tidy(i * yStep),\n  );\n\n  const over = hasThreshold ? countAbove(dist, threshold!) : 0;\n  const overShare = dist.total ? over / dist.total : 0;\n  const thresholdX = hasThreshold ? pos(threshold!) : 1;\n\n  const cumulative = React.useMemo(() => {\n    let running = 0;\n    return bars.map((b) => (running += b.count) / (dist.total || 1));\n  }, [bars, dist.total]);\n\n  const bucketAt = (index: number): LatencyHistogramBucket => {\n    const b = bars[index];\n    return {\n      index,\n      start: b.start,\n      end: b.end,\n      count: b.count,\n      share: dist.total ? b.count / dist.total : 0,\n      cumulative: cumulative[index] ?? 0,\n      compare: comparison ? comparison.counts[index] : undefined,\n      compareShare: comparison?.total\n        ? comparison.counts[index] / comparison.total\n        : undefined,\n      overflow: b.overflow,\n      overThreshold: hasThreshold && b.start >= threshold!,\n    };\n  };\n\n  /* -------------------------------------------------------------- layout */\n\n  const plotRef = React.useRef<HTMLDivElement>(null);\n  const [width, setWidth] = React.useState(0);\n  React.useLayoutEffect(() => {\n    const el = plotRef.current;\n    if (!el) return;\n    const measure = () => setWidth(el.clientWidth);\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, []);\n  const W = width || 560;\n\n  // Percentile chips stack into lanes only when they would collide.\n  // With the summary on show, crowded chips drop their values, which the summary repeats.\n  const chips = React.useMemo(() => {\n    const place = (withValue: boolean) => {\n      const lanes: number[] = [];\n      return marks.map((mark) => {\n        const text = withValue\n          ? `${percentileName(mark.p)} ${format(mark.value)}`\n          : percentileName(mark.p);\n        const w = text.length * 6.1 + 14;\n        const x = pos(mark.value) * W;\n        const left = Math.min(Math.max(0, x - w / 2), Math.max(0, W - w));\n        let lane = lanes.findIndex((right) => right + 4 <= left);\n        if (lane < 0) lane = lanes.push(0) - 1;\n        lanes[lane] = left + w;\n        return { ...mark, x, left, lane, w, withValue };\n      });\n    };\n    const full = place(true);\n    if (!showSummary || full.every((chip) => chip.lane === 0)) return full;\n    return place(false);\n  }, [marks, pos, W, format, showSummary]);\n  const laneCount = Math.max(1, ...chips.map((chip) => chip.lane + 1));\n  const chipTop = laneCount * 20 + 6;\n  // Without a fixed height the plot follows the card width, shorter on narrow cards.\n  const H = Math.max(\n    80,\n    height ?? Math.round(Math.min(220, Math.max(140, W * 0.34))),\n  );\n  const barsHeight = H - chipTop;\n\n  const xTicks = React.useMemo(() => {\n    const ticks: number[] = [];\n    if (empty) return ticks;\n    if (scale === \"log\" || dist.buckets) {\n      if (scale === \"log\") {\n        const lo = layout.lo;\n        const hi = layout.hi;\n        const candidates: number[] = [];\n        for (\n          let e = Math.floor(Math.log10(lo));\n          e <= Math.ceil(Math.log10(hi));\n          e++\n        )\n          for (const m of [1, 2, 5]) {\n            const v = tidy(m * 10 ** e);\n            if (v >= lo * 0.999 && v <= hi * 1.001) candidates.push(v);\n          }\n        // Thin out 2s and then 5s until labels have room.\n        for (const keep of [[1, 2, 5], [1, 5], [1]]) {\n          const list = candidates.filter((v) =>\n            keep.includes(\n              Math.round(v / 10 ** Math.floor(Math.log10(v) + 1e-9)),\n            ),\n          );\n          let ok = true;\n          for (let i = 1; i < list.length; i++)\n            if ((pos(list[i]) - pos(list[i - 1])) * W < 44) ok = false;\n          if (ok || keep.length === 1) return list;\n        }\n      }\n    }\n    const lo = layout.lo;\n    const hi = layout.hi;\n    const step = niceStep((hi - lo) / Math.max(2, Math.floor(W / 76)));\n    for (\n      let v = Math.ceil(lo / step - 1e-9) * step;\n      v <= hi + step * 1e-6;\n      v += step\n    )\n      ticks.push(tidy(v));\n    return ticks;\n  }, [scale, dist.buckets, layout, pos, W, empty]);\n\n  /* ----------------------------------------------------------- animation */\n\n  // Bars grow in on mount and whenever the bucket layout changes; data updates tween.\n  // Keyed on scale and bar count only, so live data with a drifting tail tweens instead of regrowing.\n  const structure = `${scale}:${bars.length}`;\n  const [grown, setGrown] = React.useState<string | null>(null);\n  const [intro, setIntro] = React.useState(true);\n  React.useEffect(() => {\n    if (reduced) {\n      setGrown(structure);\n      setIntro(false);\n      return;\n    }\n    setIntro(true);\n    let frame = requestAnimationFrame(() => {\n      frame = requestAnimationFrame(() => setGrown(structure));\n    });\n    const timer = window.setTimeout(\n      () => setIntro(false),\n      900 + bars.length * 9,\n    );\n    return () => {\n      cancelAnimationFrame(frame);\n      window.clearTimeout(timer);\n    };\n  }, [structure, reduced, bars.length]);\n  const isGrown = grown === structure;\n\n  /* --------------------------------------------------------- interaction */\n\n  const [hover, setHover] = React.useState<number | null>(null);\n  const [active, setActive] = React.useState<number | null>(null);\n  const [brush, setBrush] = React.useState<LatencyRange | null>(null);\n  const drag = React.useRef<{\n    x: number;\n    value: number;\n    moved: boolean;\n  } | null>(null);\n  const anchor = React.useRef<number | null>(null);\n\n  const xToFraction = (clientX: number) => {\n    const rect = plotRef.current!.getBoundingClientRect();\n    return Math.min(1, Math.max(0, (clientX - rect.left) / (rect.width || 1)));\n  };\n  const barAt = (x: number) => {\n    for (let i = 0; i < bars.length; i++)\n      if (x >= bars[i].x0 && x <= bars[i].x1) return i;\n    // In a gap: the nearest bar.\n    let best = -1;\n    let distance = Infinity;\n    bars.forEach((b, i) => {\n      const dd = Math.min(Math.abs(x - b.x0), Math.abs(x - b.x1));\n      if (dd < distance) {\n        distance = dd;\n        best = i;\n      }\n    });\n    return best < 0 ? null : best;\n  };\n\n  const clampRange = (a: number, b: number): LatencyRange => [\n    Math.min(a, b),\n    Math.max(a, b),\n  ];\n\n  const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {\n    if (event.button !== 0 || !bars.length) return;\n    const x = xToFraction(event.clientX);\n    drag.current = { x: event.clientX, value: inv(x), moved: false };\n    event.currentTarget.setPointerCapture(event.pointerId);\n  };\n  const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {\n    if (!bars.length) return;\n    const x = xToFraction(event.clientX);\n    const d = drag.current;\n    if (d) {\n      if (!d.moved && Math.abs(event.clientX - d.x) > 3) d.moved = true;\n      if (d.moved) {\n        setBrush(clampRange(d.value, inv(x)));\n        setHover(null);\n        return;\n      }\n    }\n    setHover(barAt(x));\n  };\n  const onPointerUp = (event: React.PointerEvent<HTMLDivElement>) => {\n    const d = drag.current;\n    drag.current = null;\n    if (!d) return;\n    if (d.moved) {\n      const next = clampRange(d.value, inv(xToFraction(event.clientX)));\n      setBrush(null);\n      setRange(next[1] - next[0] > 0 ? next : null);\n    } else if (range) setRange(null);\n  };\n\n  const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    if (!bars.length) return;\n    const current = active ?? -1;\n    const step = (delta: number) =>\n      Math.min(\n        bars.length - 1,\n        Math.max(\n          0,\n          current < 0 ? (delta > 0 ? 0 : bars.length - 1) : current + delta,\n        ),\n      );\n    let next: number | null = null;\n    if (event.key === \"ArrowRight\") next = step(1);\n    else if (event.key === \"ArrowLeft\") next = step(-1);\n    else if (event.key === \"Home\") next = 0;\n    else if (event.key === \"End\") next = bars.length - 1;\n    else if (event.key === \"Enter\" && current >= 0) {\n      setRange([bars[current].start, bars[current].end]);\n      event.preventDefault();\n      return;\n    } else if (event.key === \"Escape\") {\n      if (range) setRange(null);\n      else setActive(null);\n      anchor.current = null;\n      event.preventDefault();\n      return;\n    }\n    if (next == null) return;\n    event.preventDefault();\n    if (event.shiftKey) {\n      if (anchor.current == null) anchor.current = current < 0 ? next : current;\n      const a = Math.min(anchor.current, next);\n      const b = Math.max(anchor.current, next);\n      setRange([bars[a].start, bars[b].end]);\n    } else anchor.current = null;\n    setActive(next);\n  };\n\n  const shownRange = brush ?? range;\n  const rangeCount = shownRange\n    ? countBetween(dist, shownRange[0], shownRange[1])\n    : 0;\n  const rangeShare = dist.total ? rangeCount / dist.total : 0;\n  const focusIndex = hover ?? active;\n  const focusBucket =\n    focusIndex != null && bars[focusIndex] ? bucketAt(focusIndex) : null;\n\n  /* -------------------------------------------------------------- render */\n\n  const describeBucket = (b: LatencyHistogramBucket) =>\n    `${b.overflow ? `${format(b.start)} and above` : `${format(b.start)} to ${format(b.end)}`}: ${whole.format(Math.round(b.count))} requests, ${percentLabel(b.share)}`;\n  const summaryText = [\n    `${whole.format(Math.round(dist.total))} requests.`,\n    marks\n      .map((mark) => `${percentileName(mark.p)} ${format(mark.value)}`)\n      .join(\", \") + \".\",\n    hasThreshold\n      ? `${percentLabel(overShare)} over the ${thresholdLabel} of ${format(threshold!)}.`\n      : \"\",\n  ]\n    .filter(Boolean)\n    .join(\" \");\n  const hasHeader =\n    title != null || description != null || actions != null || showScaleToggle;\n  const transition = intro\n    ? \"transform 760ms cubic-bezier(.16,1,.3,1)\"\n    : \"transform 520ms cubic-bezier(.16,1,.3,1)\";\n  const barFill = (color: string) =>\n    `color-mix(in oklab, ${color} 72%, var(--color-card))`;\n\n  // The comparison as one stepped path across the bars.\n  const comparePath = React.useMemo(() => {\n    if (!comparison || compareStyle !== \"step\") return null;\n    let path = \"\";\n    let previousEnd = -1;\n    bars.forEach((b, i) => {\n      const y = 100 - (comparison.scaled[i] / yMax) * 100;\n      const x0 = b.x0 * 1000;\n      const x1 = b.x1 * 1000;\n      if (Math.abs(x0 - previousEnd) > 0.5)\n        path += `${path ? \"V100\" : \"\"}M${x0.toFixed(2)} 100`;\n      path += `V${y.toFixed(2)}H${x1.toFixed(2)}`;\n      previousEnd = x1;\n    });\n    return path + \"V100\";\n  }, [comparison, compareStyle, bars, yMax]);\n\n  return (\n    <div\n      data-slot=\"latency-histogram\"\n      data-scale={scale}\n      data-brushing={brush ? true : undefined}\n      className={cn(\n        \"@container/histogram flex min-w-0 flex-col rounded-xl border bg-card text-card-foreground shadow-xs\",\n        className,\n      )}\n      {...props}\n    >\n      {hasHeader && (\n        <div className=\"flex items-start gap-3 px-4 pt-3.5\">\n          <div className=\"min-w-0 flex-1 space-y-1\">\n            {title != null && (\n              <h3 className=\"truncate text-sm leading-6 font-semibold tracking-tight\">\n                {title}\n              </h3>\n            )}\n            {description != null && (\n              <p\n                id={`${id}-description`}\n                className=\"text-xs text-muted-foreground\"\n              >\n                {description}\n              </p>\n            )}\n          </div>\n          <div className=\"flex shrink-0 items-center gap-2\">\n            {actions}\n            {showScaleToggle && (\n              <div\n                role=\"group\"\n                aria-label=\"X axis scale\"\n                data-slot=\"histogram-scale-toggle\"\n                className=\"inline-flex h-7 items-center rounded-md border bg-muted/40 p-0.5\"\n              >\n                {([\"linear\", \"log\"] as const).map((option) => (\n                  <button\n                    key={option}\n                    type=\"button\"\n                    aria-pressed={scale === option}\n                    onClick={() => setScale(option)}\n                    className={cn(\n                      \"h-full rounded-[5px] px-2 text-xs font-medium text-muted-foreground transition-colors hover:text-foreground aria-pressed:bg-card aria-pressed:text-foreground aria-pressed:shadow-xs motion-reduce:transition-none\",\n                      focusRing,\n                    )}\n                  >\n                    {option === \"linear\" ? \"Linear\" : \"Log\"}\n                  </button>\n                ))}\n              </div>\n            )}\n          </div>\n        </div>\n      )}\n\n      {showSummary && (marks.length > 0 || hasThreshold) && (\n        // Narrow cards trade the stat grid for one line, so the distribution stays in view.\n        <dl\n          data-slot=\"histogram-summary-compact\"\n          className={cn(\n            \"mx-4 flex flex-wrap items-baseline gap-x-3 gap-y-1 text-xs @md/histogram:hidden\",\n            hasHeader ? \"mt-1.5\" : \"mt-4\",\n          )}\n        >\n          {marks.map((mark, i) => {\n            const previous = comparison?.percentiles[i];\n            const delta = previous != null ? mark.value - previous : null;\n            const hot = hasThreshold && mark.value > threshold!;\n            return (\n              <div key={mark.p} className=\"flex items-baseline gap-1\">\n                <dt className=\"font-mono text-[11px] text-muted-foreground\">\n                  {percentileName(mark.p)}\n                </dt>\n                <dd\n                  className={cn(\n                    \"font-semibold tabular-nums\",\n                    hot && \"text-destructive\",\n                  )}\n                >\n                  {format(mark.value)}\n                </dd>\n                {delta != null && Math.abs(delta) > 0 && (\n                  <dd\n                    className={cn(\n                      \"font-mono text-[10px] tabular-nums\",\n                      delta > 0\n                        ? \"text-destructive\"\n                        : \"text-emerald-700 dark:text-emerald-400\",\n                    )}\n                  >\n                    {delta > 0 ? \"▲\" : \"▼\"}\n                    {format(Math.abs(delta))}\n                  </dd>\n                )}\n              </div>\n            );\n          })}\n          {hasThreshold && (\n            <div className=\"flex items-baseline gap-1\">\n              <dd\n                className={cn(\n                  \"font-semibold tabular-nums\",\n                  over > 0\n                    ? \"text-destructive\"\n                    : \"text-emerald-700 dark:text-emerald-400\",\n                )}\n              >\n                {percentLabel(overShare)}\n              </dd>\n              <dt className=\"text-[11px] text-muted-foreground\">\n                over {thresholdLabel}\n              </dt>\n            </div>\n          )}\n        </dl>\n      )}\n\n      {showSummary && (marks.length > 0 || hasThreshold) && (\n        <dl\n          data-slot=\"histogram-summary\"\n          className={cn(\n            \"mx-4 hidden overflow-hidden rounded-lg bg-muted/50 @md/histogram:grid dark:bg-muted/30\",\n            hasHeader ? \"mt-3\" : \"mt-4\",\n          )}\n          style={{\n            gridTemplateColumns: `repeat(${marks.length + (hasThreshold ? 1 : 0)}, minmax(0, 1fr))`,\n          }}\n        >\n          {marks.map((mark, i) => {\n            const previous = comparison?.percentiles[i];\n            const delta = previous != null ? mark.value - previous : null;\n            const hot = hasThreshold && mark.value > threshold!;\n            return (\n              <div\n                key={mark.p}\n                className=\"min-w-0 border-s border-border/60 px-2 py-1.5 first:border-s-0 @sm/histogram:px-2.5 @md/histogram:px-3 @md/histogram:py-2\"\n              >\n                <dt className=\"font-mono text-[11px] leading-4 text-muted-foreground\">\n                  {percentileName(mark.p)}\n                </dt>\n                <dd\n                  className={cn(\n                    \"truncate text-sm leading-6 font-semibold tracking-tight tabular-nums @sm/histogram:text-base @md/histogram:text-lg\",\n                    hot && \"text-destructive\",\n                  )}\n                >\n                  {format(mark.value)}\n                </dd>\n                {delta != null && Math.abs(delta) > 0 && (\n                  <dd\n                    className={cn(\n                      \"truncate font-mono text-[11px] leading-4 whitespace-nowrap tabular-nums\",\n                      delta > 0\n                        ? \"text-destructive\"\n                        : \"text-emerald-700 dark:text-emerald-400\",\n                    )}\n                    title={`${compareLabel}: ${format(previous!)}`}\n                  >\n                    {delta > 0 ? \"▲\" : \"▼\"} {format(Math.abs(delta))}\n                  </dd>\n                )}\n              </div>\n            );\n          })}\n          {hasThreshold && (\n            <div className=\"min-w-0 border-s border-border/60 px-2 py-1.5 first:border-s-0 @sm/histogram:px-2.5 @md/histogram:px-3 @md/histogram:py-2\">\n              <dt className=\"truncate text-[11px] leading-4 text-muted-foreground\">\n                Over {thresholdLabel}\n              </dt>\n              <dd\n                className={cn(\n                  \"truncate text-sm leading-6 font-semibold tracking-tight tabular-nums @sm/histogram:text-base @md/histogram:text-lg\",\n                  over > 0\n                    ? \"text-destructive\"\n                    : \"text-emerald-700 dark:text-emerald-400\",\n                )}\n              >\n                {percentLabel(overShare)}\n              </dd>\n              <dd className=\"truncate font-mono text-[11px] leading-4 text-muted-foreground tabular-nums\">\n                {whole.format(Math.round(over))}\n                <span className=\"hidden @sm/histogram:inline\">\n                  {\" \"}\n                  of {compact.format(dist.total).replace(\"K\", \"k\")}\n                </span>\n              </dd>\n            </div>\n          )}\n        </dl>\n      )}\n\n      <div className=\"mt-3 flex px-4 @md/histogram:mt-4\">\n        <div className=\"min-w-0 flex-1\">\n          <div\n            ref={plotRef}\n            data-slot=\"histogram-plot\"\n            role=\"group\"\n            aria-roledescription=\"histogram\"\n            aria-label={`${typeof title === \"string\" ? `${title}. ` : \"\"}${summaryText} Use the arrow keys to read buckets, Shift to select a range.`}\n            aria-describedby={\n              description != null ? `${id}-description` : undefined\n            }\n            tabIndex={0}\n            onPointerDown={onPointerDown}\n            onPointerMove={onPointerMove}\n            onPointerUp={onPointerUp}\n            onPointerCancel={() => {\n              drag.current = null;\n              setBrush(null);\n            }}\n            onPointerLeave={() => {\n              if (!drag.current) setHover(null);\n            }}\n            onKeyDown={onKeyDown}\n            onBlur={() => setActive(null)}\n            className={cn(\n              \"relative cursor-crosshair touch-pan-y rounded-sm select-none\",\n              \"outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-4 focus-visible:ring-offset-card\",\n            )}\n            style={{ height: H }}\n          >\n            {empty && (\n              <p className=\"absolute inset-0 grid place-items-center text-xs text-muted-foreground\">\n                No requests to show.\n              </p>\n            )}\n\n            {/* Value grid */}\n            <div\n              aria-hidden=\"true\"\n              className=\"pointer-events-none absolute inset-x-0 bottom-0\"\n              style={{ top: chipTop }}\n            >\n              {yTicks.map((tick) => (\n                <span\n                  key={tick}\n                  className={cn(\n                    \"absolute inset-x-0 h-px\",\n                    tick === 0 ? \"bg-border\" : \"bg-border/55\",\n                  )}\n                  style={{ bottom: `${(tick / yMax) * 100}%` }}\n                />\n              ))}\n            </div>\n\n            {/* SLO tail */}\n            {hasThreshold && thresholdX < 1 && (\n              <div\n                aria-hidden=\"true\"\n                data-slot=\"histogram-threshold-region\"\n                className=\"pointer-events-none absolute inset-y-0 right-0\"\n                style={{\n                  left: `${thresholdX * 100}%`,\n                  background: `linear-gradient(to bottom, color-mix(in oklab, ${colors.threshold} 9%, transparent), color-mix(in oklab, ${colors.threshold} 3%, transparent)), repeating-linear-gradient(-45deg, color-mix(in oklab, ${colors.threshold} 9%, transparent) 0 1px, transparent 1px 6px)`,\n                }}\n              />\n            )}\n\n            {/* Bars */}\n            <div\n              aria-hidden=\"true\"\n              className=\"pointer-events-none absolute inset-x-0 bottom-0\"\n              style={{ top: chipTop }}\n            >\n              {comparison &&\n                compareStyle === \"outline\" &&\n                bars.map((b, i) => (\n                  <span\n                    key={`c-${structure}-${i}`}\n                    className=\"absolute bottom-0 origin-bottom rounded-t-[2px] border border-b-0 border-dashed\"\n                    style={{\n                      left: `calc(${b.x0 * 100}% + 1px)`,\n                      width: `calc(${(b.x1 - b.x0) * 100}% - 2px)`,\n                      height: `${(comparison.scaled[i] / yMax) * 100}%`,\n                      borderColor: `color-mix(in oklab, ${colors.compare} 70%, transparent)`,\n                      transform: `scaleY(${isGrown ? 1 : 0})`,\n                      transition: reduced ? undefined : transition,\n                    }}\n                  />\n                ))}\n              {bars.map((b, i) => {\n                const h = b.count / yMax;\n                const inRange = shownRange\n                  ? b.end > shownRange[0] && b.start < shownRange[1]\n                  : true;\n                const dim =\n                  (focusIndex != null && focusIndex !== i) || !inRange;\n                const split =\n                  hasThreshold && b.start < threshold! && b.end > threshold!;\n                const hot = hasThreshold && b.start >= threshold!;\n                const color = hot ? colors.threshold : colors.bar;\n                const cut = split\n                  ? ((thresholdX - b.x0) / (b.x1 - b.x0)) * 100\n                  : 0;\n                const fill = split\n                  ? `linear-gradient(to right, ${barFill(colors.bar)} ${cut}%, ${barFill(colors.threshold)} ${cut}%)`\n                  : barFill(color);\n                const cap = split\n                  ? `linear-gradient(to right, ${colors.bar} ${cut}%, ${colors.threshold} ${cut}%)`\n                  : color;\n                return (\n                  <span\n                    key={`${structure}-${i}`}\n                    data-slot=\"histogram-bar\"\n                    data-index={i}\n                    data-over={hot || undefined}\n                    data-overflow={b.overflow || undefined}\n                    className={cn(\n                      \"absolute inset-y-0 transition-opacity duration-200 motion-reduce:transition-none\",\n                      dim &&\n                        (shownRange && !inRange ? \"opacity-30\" : \"opacity-55\"),\n                    )}\n                    style={{\n                      left: `${b.x0 * 100}%`,\n                      width: `${(b.x1 - b.x0) * 100}%`,\n                    }}\n                  >\n                    <span\n                      className=\"absolute inset-x-px bottom-0 h-full origin-bottom @lg/histogram:inset-x-[1.5px]\"\n                      style={{\n                        transform: `scaleY(${isGrown ? h : 0})`,\n                        transition: reduced ? undefined : transition,\n                        transitionDelay:\n                          intro && !reduced ? `${i * 9}ms` : undefined,\n                      }}\n                    >\n                      <span\n                        className={cn(\n                          \"absolute inset-0 rounded-t-[2px]\",\n                          b.overflow &&\n                            \"[mask-image:repeating-linear-gradient(-45deg,#000_0_3px,rgb(0_0_0/0.55)_3px_5px)]\",\n                        )}\n                        style={{ background: fill }}\n                      />\n                    </span>\n                    {/* The cap is drawn unscaled so it stays a crisp line at any height. */}\n                    {b.count > 0 && (\n                      <span\n                        className=\"absolute inset-x-px h-[1.5px] rounded-full @lg/histogram:inset-x-[1.5px]\"\n                        style={{\n                          bottom: `calc(${(isGrown ? h : 0) * 100}% - 1px)`,\n                          background: cap,\n                          transition: reduced\n                            ? undefined\n                            : intro\n                              ? \"bottom 760ms cubic-bezier(.16,1,.3,1)\"\n                              : \"bottom 520ms cubic-bezier(.16,1,.3,1)\",\n                          transitionDelay:\n                            intro && !reduced ? `${i * 9}ms` : undefined,\n                        }}\n                      />\n                    )}\n                  </span>\n                );\n              })}\n              {comparePath && (\n                <svg\n                  data-slot=\"histogram-compare\"\n                  className=\"absolute inset-0 size-full origin-bottom overflow-visible\"\n                  viewBox=\"0 0 1000 100\"\n                  preserveAspectRatio=\"none\"\n                  style={{\n                    transform: `scaleY(${isGrown ? 1 : 0})`,\n                    transition: reduced ? undefined : transition,\n                  }}\n                >\n                  <path\n                    d={comparePath}\n                    fill=\"none\"\n                    stroke={colors.compare}\n                    strokeWidth={1.5}\n                    strokeDasharray=\"4 3\"\n                    strokeLinejoin=\"round\"\n                    vectorEffect=\"non-scaling-stroke\"\n                    opacity={0.85}\n                  />\n                </svg>\n              )}\n            </div>\n\n            {/* Selection */}\n            {shownRange && (\n              <div\n                aria-hidden=\"true\"\n                data-slot=\"histogram-selection\"\n                className=\"pointer-events-none absolute inset-y-0\"\n                style={{\n                  left: `${pos(shownRange[0]) * 100}%`,\n                  width: `${Math.max(0, pos(shownRange[1]) - pos(shownRange[0])) * 100}%`,\n                  background: `color-mix(in oklab, ${colors.selection} 9%, transparent)`,\n                  boxShadow: `inset 1.5px 0 0 ${colors.selection}, inset -1.5px 0 0 ${colors.selection}`,\n                }}\n              >\n                <span\n                  className=\"absolute top-1/2 -left-[3px] h-5 w-1.5 -translate-y-1/2 rounded-full border border-card\"\n                  style={{ background: colors.selection }}\n                />\n                <span\n                  className=\"absolute top-1/2 -right-[3px] h-5 w-1.5 -translate-y-1/2 rounded-full border border-card\"\n                  style={{ background: colors.selection }}\n                />\n              </div>\n            )}\n\n            {/* Threshold line */}\n            {hasThreshold && thresholdX < 1 && (\n              <div\n                aria-hidden=\"true\"\n                data-slot=\"histogram-threshold\"\n                className=\"pointer-events-none absolute bottom-0\"\n                style={{ left: `${thresholdX * 100}%`, top: chipTop - 2 }}\n              >\n                <span\n                  className=\"absolute inset-y-0 w-0 border-l-[1.5px] border-dashed\"\n                  style={{ borderColor: colors.threshold }}\n                />\n                <span\n                  className=\"absolute top-1 left-1 rounded-sm bg-card/85 px-1 font-mono text-[10px] leading-4 font-medium whitespace-nowrap\"\n                  style={{ color: colors.threshold }}\n                >\n                  {thresholdLabel} {format(threshold!)}\n                </span>\n              </div>\n            )}\n\n            {/* Percentile markers */}\n            {chips.map((chip) => {\n              const hot = hasThreshold && chip.value > threshold!;\n              const color = hot ? colors.threshold : colors.marker;\n              return (\n                <div\n                  key={chip.p}\n                  data-slot=\"histogram-marker\"\n                  data-percentile={chip.p}\n                  aria-hidden=\"true\"\n                  className=\"pointer-events-none\"\n                >\n                  <span\n                    className=\"absolute bottom-0 w-0 border-l border-dashed opacity-55\"\n                    style={{\n                      left: chip.x,\n                      top: chip.lane * 20 + 18,\n                      borderColor: color,\n                    }}\n                  />\n                  <span\n                    className={cn(\n                      \"absolute flex h-[18px] items-center gap-1 rounded-[5px] border bg-card px-1.5 font-mono text-[10px] leading-none whitespace-nowrap shadow-xs tabular-nums\",\n                      intro &&\n                        !reduced &&\n                        \"motion-safe:animate-[histogram-rise_.5s_.35s_cubic-bezier(.16,1,.3,1)_both]\",\n                    )}\n                    style={{\n                      left: chip.left,\n                      top: chip.lane * 20,\n                      borderColor: `color-mix(in oklab, ${color} 28%, var(--color-border))`,\n                    }}\n                  >\n                    <span className=\"text-muted-foreground\">\n                      {percentileName(chip.p)}\n                    </span>\n                    {chip.withValue && (\n                      <span className=\"font-semibold\" style={{ color }}>\n                        {format(chip.value)}\n                      </span>\n                    )}\n                  </span>\n                </div>\n              );\n            })}\n\n            {/* Tooltip */}\n            {focusBucket && !brush && (\n              <div\n                data-slot=\"histogram-tooltip\"\n                aria-hidden=\"true\"\n                className=\"pointer-events-none absolute z-10 min-w-36 rounded-lg border bg-popover px-2.5 py-2 text-xs text-popover-foreground shadow-md\"\n                style={{\n                  top: chipTop + 4,\n                  // Sit beside the bar, on the side with more room, so it never hides it.\n                  ...(bars[focusBucket.index].x0 + bars[focusBucket.index].x1 <\n                  1\n                    ? { left: bars[focusBucket.index].x1 * W + 8 }\n                    : { right: W - bars[focusBucket.index].x0 * W + 8 }),\n                }}\n              >\n                {renderTooltip ? (\n                  renderTooltip(focusBucket)\n                ) : (\n                  <>\n                    <p className=\"font-mono text-[11px] text-muted-foreground tabular-nums\">\n                      {focusBucket.overflow\n                        ? `≥ ${format(focusBucket.start)}`\n                        : `${format(focusBucket.start)} – ${format(focusBucket.end)}`}\n                    </p>\n                    <p className=\"mt-0.5 flex items-baseline gap-1.5\">\n                      <span className=\"text-sm font-semibold tabular-nums\">\n                        {whole.format(Math.round(focusBucket.count))}\n                      </span>\n                      <span className=\"text-muted-foreground tabular-nums\">\n                        {percentLabel(focusBucket.share)}\n                      </span>\n                    </p>\n                    <p className=\"mt-1 text-[11px] text-muted-foreground tabular-nums\">\n                      {percentLabel(focusBucket.cumulative)} at or faster\n                    </p>\n                    {focusBucket.compare != null && comparison && (\n                      <p className=\"mt-1.5 flex items-center gap-1.5 border-t border-dashed pt-1.5 text-[11px] text-muted-foreground tabular-nums\">\n                        <span\n                          aria-hidden=\"true\"\n                          className=\"w-3 border-t-[1.5px] border-dashed\"\n                          style={{ borderColor: colors.compare }}\n                        />\n                        {compareLabel}\n                        <span className=\"ml-auto font-medium text-foreground\">\n                          {whole.format(Math.round(focusBucket.compare))}\n                        </span>\n                        <span>\n                          {percentLabel(focusBucket.compareShare ?? 0)}\n                        </span>\n                      </p>\n                    )}\n                  </>\n                )}\n              </div>\n            )}\n          </div>\n\n          {/* Latency axis */}\n          <div\n            aria-hidden=\"true\"\n            className=\"relative mt-1.5 h-4 font-mono text-[10px] leading-4 text-muted-foreground tabular-nums\"\n          >\n            {xTicks.map((tick, i) => {\n              const x = pos(tick);\n              if (x > layout.pos(layout.hi) + 1e-6) return null;\n              return (\n                <span\n                  key={tick}\n                  className={cn(\n                    \"absolute whitespace-nowrap\",\n                    i === 0 && x < 0.02\n                      ? \"\"\n                      : x > 0.97\n                        ? \"-translate-x-full\"\n                        : \"-translate-x-1/2\",\n                  )}\n                  style={{ left: `${x * 100}%` }}\n                >\n                  {formatTick(tick)}\n                </span>\n              );\n            })}\n            {bars[bars.length - 1]?.overflow && (\n              <span\n                className=\"absolute -translate-x-1/2 whitespace-nowrap\"\n                style={{\n                  left: `${((bars[bars.length - 1].x0 + 1) / 2) * 100}%`,\n                }}\n              >\n                +\n              </span>\n            )}\n          </div>\n        </div>\n        <div\n          aria-hidden=\"true\"\n          className=\"relative ml-2 w-8 shrink-0\"\n          style={{ height: H }}\n        >\n          {yTicks.map((tick) => (\n            <span\n              key={tick}\n              className=\"absolute right-0 translate-y-1/2 font-mono text-[10px] leading-none text-muted-foreground tabular-nums\"\n              style={{ bottom: `${(tick / yMax) * (barsHeight / H) * 100}%` }}\n            >\n              {tick === 0 ? \"0\" : compact.format(tick).replace(\"K\", \"k\")}\n            </span>\n          ))}\n        </div>\n      </div>\n\n      <div\n        data-slot=\"histogram-footer\"\n        className=\"mt-3 flex min-h-11 flex-wrap items-center justify-between gap-x-4 gap-y-2 border-t px-4 py-2\"\n      >\n        <div\n          data-slot=\"histogram-status\"\n          className=\"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5 text-xs\"\n        >\n          {shownRange ? (\n            <>\n              <span\n                className=\"rounded-[4px] px-1.5 py-px font-mono text-[11px] tabular-nums\"\n                style={{\n                  background: `color-mix(in oklab, ${colors.selection} 10%, transparent)`,\n                  color: colors.selection,\n                }}\n              >\n                {format(shownRange[0])} – {format(shownRange[1])}\n              </span>\n              <span className=\"font-semibold tabular-nums\">\n                {percentLabel(rangeShare)}\n              </span>\n              <span className=\"text-muted-foreground tabular-nums\">\n                {whole.format(Math.round(rangeCount))} of{\" \"}\n                {whole.format(Math.round(dist.total))} requests\n              </span>\n              {!brush && (\n                <button\n                  type=\"button\"\n                  onClick={() => setRange(null)}\n                  className={cn(\n                    \"inline-flex size-5 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground\",\n                    focusRing,\n                  )}\n                >\n                  <X className=\"size-3.5\" aria-hidden=\"true\" />\n                  <span className=\"sr-only\">Clear selection</span>\n                </button>\n              )}\n            </>\n          ) : (\n            <span className=\"text-muted-foreground tabular-nums\">\n              <span className=\"font-medium text-foreground\">\n                {whole.format(Math.round(dist.total))}\n              </span>{\" \"}\n              requests\n              <span aria-hidden=\"true\"> · </span>mean{\" \"}\n              <span className=\"font-medium text-foreground\">\n                {format(dist.mean)}\n              </span>\n              <span className=\"hidden @md/histogram:inline\">\n                <span aria-hidden=\"true\"> · </span>max{\" \"}\n                <span className=\"font-medium text-foreground\">\n                  {format(dist.max)}\n                </span>\n              </span>\n              <span className=\"hidden @lg/histogram:inline\">\n                {\" \"}\n                · drag to measure a range\n              </span>\n            </span>\n          )}\n        </div>\n        {comparison && (\n          <div\n            data-slot=\"histogram-legend\"\n            className=\"flex items-center gap-3 text-[11px] text-muted-foreground\"\n          >\n            <span className=\"flex items-center gap-1.5\">\n              <span\n                aria-hidden=\"true\"\n                className=\"size-2.5 rounded-[2px]\"\n                style={{\n                  background: barFill(colors.bar),\n                  boxShadow: `inset 0 1.5px 0 ${colors.bar}`,\n                }}\n              />\n              {seriesLabel}\n            </span>\n            <span className=\"flex items-center gap-1.5\">\n              <span\n                aria-hidden=\"true\"\n                className=\"w-3.5 border-t-[1.5px] border-dashed\"\n                style={{ borderColor: colors.compare }}\n              />\n              {compareLabel}\n            </span>\n          </div>\n        )}\n      </div>\n\n      <div className=\"sr-only\">\n        <table>\n          <caption>{summaryText}</caption>\n          <thead>\n            <tr>\n              <th scope=\"col\">Latency</th>\n              <th scope=\"col\">Requests</th>\n              {comparison && <th scope=\"col\">{compareLabel}</th>}\n            </tr>\n          </thead>\n          <tbody>\n            {bars.map((b, i) =>\n              b.count > 0 || comparison?.counts[i] ? (\n                <tr key={i}>\n                  <th scope=\"row\">\n                    {b.overflow\n                      ? `${format(b.start)} and above`\n                      : `${format(b.start)} to ${format(b.end)}`}\n                  </th>\n                  <td>{whole.format(Math.round(b.count))}</td>\n                  {comparison && (\n                    <td>{whole.format(Math.round(comparison.counts[i]))}</td>\n                  )}\n                </tr>\n              ) : null,\n            )}\n          </tbody>\n        </table>\n      </div>\n      <p className=\"sr-only\" aria-live=\"polite\">\n        {active != null && bars[active]\n          ? describeBucket(bucketAt(active))\n          : range\n            ? `Selected ${format(range[0])} to ${format(range[1])}: ${percentLabel(dist.total ? countBetween(dist, range[0], range[1]) / dist.total : 0)} of requests.`\n            : \"\"}\n      </p>\n\n      <style href=\"overtrue-latency-histogram\" precedence=\"default\">\n        {`@keyframes histogram-rise{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}`}\n      </style>\n    </div>\n  );\n}\n"
    },
    {
      "path": "src/registry/overtrue/trace-waterfall.tsx",
      "type": "registry:component",
      "target": "components/overtrue/trace-waterfall.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport {\n  IconAlertTriangleFilled as AlertTriangle,\n  IconChevronRight as ChevronRight,\n  IconFoldDown as FoldDown,\n  IconFoldUp as FoldUp,\n  IconRoute as Route,\n  IconX as X,\n  IconZoomReset as ZoomReset,\n} from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport type TraceSpanStatus = \"ok\" | \"error\";\n\nexport type TraceSpanAttributeValue = string | number | boolean;\n\nexport interface TraceSpan {\n  id: string;\n  /** The calling span. Spans without a known parent are drawn as roots. */\n  parentId?: string | null;\n  /** Operation name, e.g. \"POST /api/checkout\" or \"SELECT orders\". */\n  name: string;\n  /** Emitting service. Spans of one service share a color. */\n  service: string;\n  /** Milliseconds from the start of the trace. */\n  start: number;\n  /** Milliseconds. */\n  duration: number;\n  status?: TraceSpanStatus;\n  attributes?: Record<string, TraceSpanAttributeValue>;\n}\n\n/** Everything derived about one span, passed to `renderDetail`. */\nexport interface TraceSpanInfo {\n  span: TraceSpan;\n  parent: TraceSpan | null;\n  children: TraceSpan[];\n  depth: number;\n  /** All spans below this one, at any depth. */\n  descendantCount: number;\n  /** Time not covered by any child span, in milliseconds. */\n  selfTime: number;\n  /** Duration as a 0–1 share of the whole trace. */\n  share: number;\n  /** Whether the span is on the trace's critical path. */\n  critical: boolean;\n  /** The resolved service color. */\n  color: string;\n  /** Start and end of the whole trace, in milliseconds. */\n  trace: { start: number; end: number; duration: number };\n}\n\nexport type TraceTimeRange = [start: number, end: number];\n\nexport interface TraceWaterfallProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"title\" | \"children\"\n> {\n  spans: TraceSpan[];\n  title?: React.ReactNode;\n  description?: React.ReactNode;\n  /** Controls placed at the top right, before the built-in tools. */\n  actions?: React.ReactNode;\n  /** Selected span. Pass `null` for none; leave undefined to let the component manage it. */\n  selectedId?: string | null;\n  defaultSelectedId?: string | null;\n  onSelectedChange?: (id: string | null, span: TraceSpan | null) => void;\n  /** Emphasise the longest blocking chain. Pass with `onHighlightCriticalPathChange` to control it. */\n  highlightCriticalPath?: boolean;\n  defaultHighlightCriticalPath?: boolean;\n  onHighlightCriticalPathChange?: (highlight: boolean) => void;\n  /** Spans that start collapsed. */\n  defaultCollapsedIds?: string[];\n  /** Colors by service name. Unlisted services take the chart palette in order of appearance. */\n  serviceColors?: Record<string, string>;\n  /** Formats every duration and offset except axis ticks. */\n  durationFormatter?: (ms: number) => string;\n  /** Replaces the attribute table in the detail panel. Compose `TraceSpanAttributes` to keep it. */\n  renderDetail?: (span: TraceSpan, info: TraceSpanInfo) => React.ReactNode;\n  /** Row height in pixels. Defaults to 28. */\n  rowHeight?: number;\n  /** Maximum height of the scrolling span list in pixels. Defaults to 360. */\n  height?: number;\n  /** Width of the span tree as a 0.2–0.7 share of the card. Drag the divider to change it. */\n  treeWidth?: number;\n  /** Show the whole-trace minimap above the list. Defaults to true. */\n  showOverview?: boolean;\n  /** Show the service legend, which doubles as a filter. Defaults to true. */\n  showLegend?: boolean;\n  /** Called when the visible time range changes, with `null` when zoom resets. */\n  onZoomChange?: (range: TraceTimeRange | null) => void;\n}\n\n/* ------------------------------------------------------------------------ */\n/* Formatting                                                                */\n/* ------------------------------------------------------------------------ */\n\nfunction formatDuration(ms: number) {\n  if (!Number.isFinite(ms)) return \"—\";\n  const a = Math.abs(ms);\n  if (a === 0) return \"0ms\";\n  if (a < 1) return `${Math.round(ms * 1000)}µs`;\n  if (a < 10) return `${ms.toFixed(2)}ms`;\n  if (a < 100) return `${ms.toFixed(1)}ms`;\n  if (a < 1000) return `${Math.round(ms)}ms`;\n  if (a < 10_000) return `${(ms / 1000).toFixed(2)}s`;\n  if (a < 60_000) return `${(ms / 1000).toFixed(1)}s`;\n  const minutes = Math.floor(ms / 60_000);\n  return `${minutes}m ${Math.round((ms - minutes * 60_000) / 1000)}s`;\n}\n\nfunction formatPercent(share: number) {\n  const pct = share * 100;\n  if (pct > 0 && pct < 0.1) return \"<0.1%\";\n  return `${pct >= 10 ? pct.toFixed(0) : pct.toFixed(1)}%`;\n}\n\nconst tidy = (value: number) => +value.toPrecision(12);\n\nfunction niceStep(span: number, count: number) {\n  const raw = span / Math.max(1, count);\n  const magnitude = 10 ** Math.floor(Math.log10(raw));\n  const r = raw / magnitude;\n  return (\n    (r <= 1 ? 1 : r <= 2 ? 2 : r <= 2.5 ? 2.5 : r <= 5 ? 5 : 10) * magnitude\n  );\n}\n\n/** Tick labels carry exactly the precision of the step, so neighbors never read alike. */\nfunction tickLabel(value: number, step: number) {\n  if (value === 0) return \"0\";\n  if (step >= 1000 || (Math.abs(value) >= 1000 && step >= 100)) {\n    const digits = Math.max(0, -Math.floor(Math.log10(step / 1000) + 1e-9));\n    return `${(value / 1000).toFixed(Math.min(3, digits))}s`;\n  }\n  if (step < 1 && step < 0.01) return `${tidy(value * 1000)}µs`;\n  const digits = Math.max(0, -Math.floor(Math.log10(step) + 1e-9));\n  return `${value.toFixed(Math.min(3, digits))}ms`;\n}\n\n/* ------------------------------------------------------------------------ */\n/* Model                                                                     */\n/* ------------------------------------------------------------------------ */\n\ninterface TraceNode {\n  span: TraceSpan;\n  order: number;\n  parent: TraceNode | null;\n  children: TraceNode[];\n  depth: number;\n  end: number;\n  self: number;\n  descendants: number;\n  critical: boolean;\n}\n\ninterface TraceModel {\n  nodes: Map<string, TraceNode>;\n  roots: TraceNode[];\n  /** Every node in tree order. */\n  ordered: TraceNode[];\n  start: number;\n  end: number;\n  duration: number;\n  services: { name: string; count: number; errors: number }[];\n  errors: number;\n}\n\nconst PALETTE = [\n  \"var(--color-chart-1)\",\n  \"var(--color-chart-2)\",\n  \"var(--color-chart-3)\",\n  \"var(--color-chart-4)\",\n  \"var(--color-chart-5)\",\n  // Blends of the theme's own chart colors keep extra services on-palette.\n  \"color-mix(in oklab, var(--color-chart-1) 50%, var(--color-chart-2))\",\n  \"color-mix(in oklab, var(--color-chart-2) 50%, var(--color-chart-3))\",\n  \"color-mix(in oklab, var(--color-chart-4) 55%, var(--color-chart-5))\",\n];\n\nconst DESTRUCTIVE = \"var(--color-destructive)\";\nconst errorFill = `repeating-linear-gradient(-45deg, ${DESTRUCTIVE} 0 3px, color-mix(in oklab, ${DESTRUCTIVE} 58%, var(--color-card)) 3px 6px)`;\n\nfunction buildModel(spans: TraceSpan[]): TraceModel {\n  const nodes = new Map<string, TraceNode>();\n  spans.forEach((span, order) => {\n    if (nodes.has(span.id)) return;\n    const start = Number.isFinite(span.start) ? span.start : 0;\n    const duration = Number.isFinite(span.duration)\n      ? Math.max(0, span.duration)\n      : 0;\n    nodes.set(span.id, {\n      span,\n      order,\n      parent: null,\n      children: [],\n      depth: 0,\n      end: start + duration,\n      self: duration,\n      descendants: 0,\n      critical: false,\n    });\n  });\n\n  const roots: TraceNode[] = [];\n  for (const node of nodes.values()) {\n    const parentId = node.span.parentId;\n    const parent =\n      parentId != null && parentId !== node.span.id\n        ? nodes.get(parentId)\n        : undefined;\n    if (parent) {\n      node.parent = parent;\n      parent.children.push(node);\n    } else roots.push(node);\n  }\n\n  const byStart = (a: TraceNode, b: TraceNode) =>\n    a.span.start - b.span.start || a.order - b.order;\n  const ordered: TraceNode[] = [];\n  const visited = new Set<TraceNode>();\n  const visit = (node: TraceNode, depth: number) => {\n    visited.add(node);\n    node.depth = depth;\n    ordered.push(node);\n    node.children = node.children\n      .filter((child) => !visited.has(child))\n      .sort(byStart);\n    let descendants = 0;\n    for (const child of node.children) {\n      visit(child, depth + 1);\n      descendants += 1 + child.descendants;\n    }\n    node.descendants = descendants;\n    // Self time: the span's duration minus the union of its children's time inside it.\n    const start = node.span.start;\n    const intervals = node.children\n      .map(\n        (child) =>\n          [\n            Math.max(child.span.start, start),\n            Math.min(child.end, node.end),\n          ] as const,\n      )\n      .filter(([a, b]) => b > a)\n      .sort((a, b) => a[0] - b[0]);\n    let covered = 0;\n    let cursor = -Infinity;\n    for (const [a, b] of intervals) {\n      if (b <= cursor) continue;\n      covered += b - Math.max(a, cursor);\n      cursor = b;\n    }\n    node.self = Math.max(0, node.end - start - covered);\n  };\n  roots.sort(byStart);\n  for (const root of roots) visit(root, 0);\n  // Spans caught in a parent cycle are never reached from a root; draw them as roots.\n  for (const node of nodes.values())\n    if (!visited.has(node)) {\n      node.parent = null;\n      roots.push(node);\n      visit(node, 0);\n    }\n\n  let start = 0;\n  let end = 0;\n  let errors = 0;\n  const services = new Map<\n    string,\n    { name: string; count: number; errors: number }\n  >();\n  for (const node of ordered) {\n    start = Math.min(start, node.span.start);\n    end = Math.max(end, node.end);\n    const isError = node.span.status === \"error\";\n    if (isError) errors += 1;\n    const entry = services.get(node.span.service) ?? {\n      name: node.span.service,\n      count: 0,\n      errors: 0,\n    };\n    entry.count += 1;\n    if (isError) entry.errors += 1;\n    services.set(node.span.service, entry);\n  }\n\n  // Critical path: from the longest root, walk back from each span's end through the\n  // child that finished last, then whatever finished before that child started.\n  const markCritical = (node: TraceNode) => {\n    node.critical = true;\n    let cursor = node.end + 1e-9;\n    const byEnd = [...node.children].sort((a, b) => b.end - a.end);\n    for (const child of byEnd) {\n      if (child.end <= cursor && child.end > node.span.start) {\n        markCritical(child);\n        cursor = child.span.start + 1e-9;\n      }\n    }\n  };\n  const main = roots.reduce<TraceNode | null>(\n    (best, root) =>\n      !best || root.end - root.span.start > best.end - best.span.start\n        ? root\n        : best,\n    null,\n  );\n  if (main) markCritical(main);\n\n  return {\n    nodes,\n    roots,\n    ordered,\n    start,\n    end,\n    duration: end - start || 1,\n    services: [...services.values()],\n    errors,\n  };\n}\n\ninterface TraceRowModel {\n  node: TraceNode;\n  depth: number;\n  /** For each ancestor column, whether a guide line continues through this row. */\n  lines: boolean[];\n  last: boolean;\n  childCount: number;\n  collapsed: boolean;\n  hiddenCount: number;\n  /** Descendants hidden by collapsing, drawn as a faint summary. */\n  summary: TraceNode[];\n  parentId: string | null;\n  position: number;\n  setSize: number;\n}\n\nfunction visibleChildren(\n  children: TraceNode[],\n  hidden: Set<string>,\n): TraceNode[] {\n  if (!hidden.size) return children;\n  let lifted = false;\n  const out: TraceNode[] = [];\n  for (const child of children) {\n    if (hidden.has(child.span.service)) {\n      lifted = true;\n      out.push(...visibleChildren(child.children, hidden));\n    } else out.push(child);\n  }\n  return lifted\n    ? out.sort((a, b) => a.span.start - b.span.start || a.order - b.order)\n    : out;\n}\n\nfunction buildRows(\n  model: TraceModel,\n  collapsed: Set<string>,\n  hidden: Set<string>,\n) {\n  const rows: TraceRowModel[] = [];\n  const flat: TraceNode[] = [];\n  const collect = (node: TraceNode, into: TraceNode[]) => {\n    for (const child of visibleChildren(node.children, hidden)) {\n      into.push(child);\n      collect(child, into);\n    }\n  };\n  const visit = (\n    node: TraceNode,\n    depth: number,\n    lines: boolean[],\n    last: boolean,\n    parentId: string | null,\n    position: number,\n    setSize: number,\n  ) => {\n    const kids = visibleChildren(node.children, hidden);\n    const isCollapsed = kids.length > 0 && collapsed.has(node.span.id);\n    const summary: TraceNode[] = [];\n    if (isCollapsed) collect(node, summary);\n    rows.push({\n      node,\n      depth,\n      lines,\n      last,\n      childCount: kids.length,\n      collapsed: isCollapsed,\n      hiddenCount: summary.length,\n      summary: summary.slice(0, 60),\n      parentId,\n      position,\n      setSize,\n    });\n    if (isCollapsed) return;\n    const childLines = depth === 0 ? [] : [...lines, !last];\n    kids.forEach((kid, i) =>\n      visit(\n        kid,\n        depth + 1,\n        childLines,\n        i === kids.length - 1,\n        node.span.id,\n        i + 1,\n        kids.length,\n      ),\n    );\n  };\n  const roots = visibleChildren(model.roots, hidden);\n  roots.forEach((root, i) =>\n    visit(root, 0, [], i === roots.length - 1, null, i + 1, roots.length),\n  );\n  // The overview ignores collapsing but follows the service filter.\n  for (const root of roots) {\n    flat.push(root);\n    collect(root, flat);\n  }\n  return { rows, flat };\n}\n\n/* ------------------------------------------------------------------------ */\n/* Hooks                                                                     */\n/* ------------------------------------------------------------------------ */\n\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (onChange) => {\n      const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n      query.addEventListener(\"change\", onChange);\n      return () => query.removeEventListener(\"change\", onChange);\n    },\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\nfunction useControllable<T>(\n  value: T | undefined,\n  defaultValue: T,\n  onChange?: (value: T) => void,\n) {\n  const [inner, setInner] = React.useState(defaultValue);\n  const controlled = value !== undefined;\n  const current = controlled ? value : inner;\n  const set = React.useCallback(\n    (next: T) => {\n      if (!controlled) setInner(next);\n      onChange?.(next);\n    },\n    [controlled, onChange],\n  );\n  return [current, set] as const;\n}\n\nconst focusRing =\n  \"outline-none focus-visible:ring-2 focus-visible:ring-ring/50\";\nconst toolButton = cn(\n  \"inline-flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-40 aria-pressed:bg-muted aria-pressed:text-foreground motion-reduce:transition-none\",\n  focusRing,\n);\n\n/** Position inside the timeline column from the animated view variables. */\nconst at = (ms: number) =>\n  `calc((${tidy(ms)} - var(--trace-v0)) / var(--trace-vs) * 100%)`;\nconst span = (ms: number) => `calc(${tidy(ms)} / var(--trace-vs) * 100%)`;\n\nconst INDENT = 12;\nconst PAD = 10;\n\n/* ------------------------------------------------------------------------ */\n/* Row                                                                       */\n/* ------------------------------------------------------------------------ */\n\ninterface TraceRowProps {\n  row: TraceRowModel;\n  index: number;\n  rowHeight: number;\n  color: string;\n  colorOf: (service: string) => string;\n  selected: boolean;\n  tabStop: boolean;\n  emphasis: \"critical\" | \"dim\" | \"normal\";\n  labelSide: \"after\" | \"before\" | \"inside\";\n  /** The span lies outside the zoomed time range. */\n  outside: boolean;\n  format: (ms: number) => string;\n  onToggle: (id: string) => void;\n  onActivate: (id: string) => void;\n  onFocusRow: (id: string) => void;\n}\n\nconst TraceRow = React.memo(function TraceRow({\n  row,\n  index,\n  rowHeight,\n  color,\n  colorOf,\n  selected,\n  tabStop,\n  emphasis,\n  labelSide,\n  outside,\n  format,\n  onToggle,\n  onActivate,\n  onFocusRow,\n}: TraceRowProps) {\n  const { node, depth } = row;\n  const { span: s } = node;\n  const isError = s.status === \"error\";\n  const barHeight = Math.max(6, Math.round(rowHeight * 0.43));\n  const elbowX = (column: number) => PAD + column * INDENT + 7;\n  const duration = format(s.duration);\n\n  return (\n    <div\n      role=\"treeitem\"\n      data-slot=\"trace-row\"\n      data-span-id={s.id}\n      data-selected={selected || undefined}\n      data-outside={outside || undefined}\n      data-error={isError || undefined}\n      data-critical={node.critical || undefined}\n      aria-level={depth + 1}\n      aria-setsize={row.setSize}\n      aria-posinset={row.position}\n      aria-expanded={row.childCount > 0 ? !row.collapsed : undefined}\n      aria-selected={selected}\n      aria-label={`${s.name}, ${s.service}, ${duration}${isError ? \", error\" : \"\"}${row.collapsed ? `, ${row.hiddenCount} hidden` : \"\"}`}\n      tabIndex={tabStop ? 0 : -1}\n      onFocus={() => onFocusRow(s.id)}\n      onClick={() => onActivate(s.id)}\n      className={cn(\n        \"group/row absolute inset-x-0 grid cursor-default grid-cols-(--trace-cols) transition-colors duration-100 outline-none motion-reduce:transition-none\",\n        \"hover:bg-muted/55 focus-visible:z-[1] focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-inset\",\n        selected &&\n          \"bg-primary/[0.07] shadow-[inset_2px_0_0_var(--color-primary)] hover:bg-primary/10\",\n      )}\n      style={{ top: index * rowHeight, height: rowHeight }}\n    >\n      <div\n        data-slot=\"trace-row-label\"\n        className=\"relative flex min-w-0 items-center gap-1.5 border-r pr-2.5\"\n        style={{ paddingLeft: PAD + depth * INDENT }}\n      >\n        {depth > 0 && (\n          <span\n            aria-hidden=\"true\"\n            className=\"pointer-events-none absolute inset-y-0 left-0\"\n          >\n            {row.lines.map((continues, column) =>\n              continues ? (\n                <span\n                  key={column}\n                  className=\"absolute inset-y-0 w-px bg-border\"\n                  style={{ left: elbowX(column) }}\n                />\n              ) : null,\n            )}\n            <span\n              className=\"absolute top-0 w-px bg-border\"\n              style={{\n                left: elbowX(depth - 1),\n                height: row.last ? \"50%\" : \"100%\",\n              }}\n            />\n            <span\n              className=\"absolute top-1/2 h-px bg-border\"\n              style={{\n                left: elbowX(depth - 1),\n                width: row.childCount > 0 ? 6 : 12,\n              }}\n            />\n          </span>\n        )}\n        {row.childCount > 0 ? (\n          // Not a tab stop: the row itself takes Left and Right to collapse and expand.\n          <span\n            aria-hidden=\"true\"\n            data-slot=\"trace-row-toggle\"\n            onClick={(event) => {\n              event.stopPropagation();\n              onToggle(s.id);\n            }}\n            className=\"relative -mx-px inline-flex size-3.5 shrink-0 cursor-pointer items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground\"\n          >\n            <ChevronRight\n              className={cn(\n                \"size-3 transition-transform duration-150 motion-reduce:transition-none\",\n                !row.collapsed && \"rotate-90\",\n              )}\n              strokeWidth={2.25}\n            />\n          </span>\n        ) : (\n          <span aria-hidden=\"true\" className=\"w-3.5 shrink-0\" />\n        )}\n        <span\n          aria-hidden=\"true\"\n          className=\"relative size-2 shrink-0 rounded-full\"\n          style={{\n            background: color,\n            boxShadow: `0 0 0 2px color-mix(in oklab, ${color} 18%, transparent)`,\n          }}\n        />\n        <span\n          className={cn(\n            \"min-w-0 truncate text-xs transition-opacity duration-200 motion-reduce:transition-none\",\n            depth === 0 ? \"font-semibold\" : \"font-medium text-foreground/90\",\n            outside && \"opacity-45\",\n          )}\n        >\n          {s.name}\n        </span>\n        {isError && (\n          <AlertTriangle\n            aria-hidden=\"true\"\n            className=\"size-3 shrink-0 text-destructive\"\n          />\n        )}\n        {row.collapsed && (\n          <span className=\"shrink-0 rounded-[4px] border px-1 font-mono text-[10px] leading-3.5 text-muted-foreground tabular-nums\">\n            +{row.hiddenCount}\n          </span>\n        )}\n        <span\n          className={cn(\n            \"ml-auto shrink-0 pl-1 font-mono text-[11px] tabular-nums @max-sm/trace:hidden\",\n            isError\n              ? \"text-destructive\"\n              : emphasis === \"critical\"\n                ? \"font-medium text-foreground\"\n                : \"text-muted-foreground\",\n          )}\n        >\n          {duration}\n        </span>\n      </div>\n\n      <div\n        data-slot=\"trace-row-timeline\"\n        className=\"relative min-w-0 overflow-hidden\"\n      >\n        {row.collapsed &&\n          row.summary.map((child) => (\n            <span\n              key={child.span.id}\n              aria-hidden=\"true\"\n              className=\"absolute h-[3px] rounded-full opacity-60\"\n              style={{\n                left: at(child.span.start),\n                width: `max(2px, ${span(child.end - child.span.start)})`,\n                bottom: Math.max(\n                  2,\n                  Math.round((rowHeight - barHeight) / 2) - 5,\n                ),\n                background:\n                  child.span.status === \"error\"\n                    ? DESTRUCTIVE\n                    : colorOf(child.span.service),\n              }}\n            />\n          ))}\n        <span\n          data-slot=\"trace-bar\"\n          aria-hidden=\"true\"\n          className={cn(\n            \"absolute top-1/2 -translate-y-1/2 rounded-[3px] transition-[opacity,box-shadow,filter] duration-200 motion-reduce:transition-none\",\n            emphasis === \"dim\" && \"opacity-40 group-hover/row:opacity-75\",\n            selected && \"ring-2 ring-primary/55 ring-offset-1 ring-offset-card\",\n            isError && \"ring-1 ring-destructive/70 ring-inset\",\n          )}\n          style={{\n            left: at(s.start),\n            width: `max(2px, ${span(node.end - s.start)})`,\n            height: barHeight,\n            background: isError ? errorFill : color,\n            boxShadow:\n              emphasis === \"critical\" && !selected\n                ? `0 0 0 1px color-mix(in oklab, ${color} 55%, transparent), 0 1px 6px -1px color-mix(in oklab, ${color} 55%, transparent)`\n                : undefined,\n          }}\n        >\n          <span\n            className={cn(\n              \"pointer-events-none absolute top-1/2 -translate-y-1/2 rounded-[3px] font-mono text-[10px] leading-4 whitespace-nowrap tabular-nums opacity-0 transition-opacity duration-150 group-hover/row:opacity-100 motion-reduce:transition-none @max-sm/trace:opacity-100\",\n              selected && \"opacity-100\",\n              labelSide === \"after\" && \"left-full ml-1.5 text-foreground\",\n              labelSide === \"before\" && \"right-full mr-1.5 text-foreground\",\n              labelSide === \"inside\" &&\n                \"right-1 bg-card/90 px-1 text-foreground shadow-xs\",\n            )}\n          >\n            {duration}\n          </span>\n        </span>\n      </div>\n    </div>\n  );\n});\n\n/* ------------------------------------------------------------------------ */\n/* Attributes                                                                */\n/* ------------------------------------------------------------------------ */\n\nexport interface TraceSpanAttributesProps extends React.ComponentProps<\"dl\"> {\n  attributes?: Record<string, TraceSpanAttributeValue>;\n}\n\n/** The default attribute table of the detail panel, exported for custom detail layouts. */\nexport function TraceSpanAttributes({\n  attributes,\n  className,\n  ...props\n}: TraceSpanAttributesProps) {\n  const entries = Object.entries(attributes ?? {});\n  if (!entries.length)\n    return (\n      <p className=\"py-1 text-xs text-muted-foreground\">\n        No attributes recorded.\n      </p>\n    );\n  return (\n    <dl\n      data-slot=\"trace-attributes\"\n      className={cn(\n        \"grid grid-cols-[minmax(6rem,auto)_minmax(0,1fr)] gap-x-5 text-xs\",\n        className,\n      )}\n      {...props}\n    >\n      {entries.map(([key, value]) => (\n        <React.Fragment key={key}>\n          <dt className=\"truncate border-t border-dashed py-1.5 font-mono text-[11px] text-muted-foreground first-of-type:border-t-0\">\n            {key}\n          </dt>\n          <dd\n            className={cn(\n              \"min-w-0 border-t border-dashed py-1.5 font-mono text-[11px] break-all tabular-nums first-of-type:border-t-0\",\n              typeof value === \"boolean\" &&\n                (value\n                  ? \"text-emerald-700 dark:text-emerald-400\"\n                  : \"text-muted-foreground\"),\n              typeof value === \"number\" && \"text-foreground\",\n            )}\n          >\n            {typeof value === \"number\"\n              ? value.toLocaleString(\"en-US\")\n              : String(value)}\n          </dd>\n        </React.Fragment>\n      ))}\n    </dl>\n  );\n}\n\n/* ------------------------------------------------------------------------ */\n/* TraceWaterfall                                                            */\n/* ------------------------------------------------------------------------ */\n\n/**\n * A distributed-trace waterfall: a collapsible span tree beside a time axis. Drag across\n * the axis to zoom, click a span for its detail, and follow the critical path at a glance.\n */\nexport function TraceWaterfall({\n  spans,\n  title,\n  description,\n  actions,\n  selectedId: selectedProp,\n  defaultSelectedId = null,\n  onSelectedChange,\n  highlightCriticalPath: highlightProp,\n  defaultHighlightCriticalPath = true,\n  onHighlightCriticalPathChange,\n  defaultCollapsedIds,\n  serviceColors,\n  durationFormatter = formatDuration,\n  renderDetail,\n  rowHeight = 28,\n  height = 360,\n  treeWidth,\n  showOverview = true,\n  showLegend = true,\n  onZoomChange,\n  className,\n  style,\n  ...props\n}: TraceWaterfallProps) {\n  const id = React.useId();\n  const reduced = useReducedMotion();\n  const model = React.useMemo(() => buildModel(spans), [spans]);\n  const format = durationFormatter;\n\n  const colors = React.useMemo(() => {\n    const map = new Map<string, string>();\n    model.services.forEach((service, i) =>\n      map.set(\n        service.name,\n        serviceColors?.[service.name] ?? PALETTE[i % PALETTE.length],\n      ),\n    );\n    return map;\n  }, [model, serviceColors]);\n  const colorOf = React.useCallback(\n    (service: string) => colors.get(service) ?? PALETTE[0],\n    [colors],\n  );\n\n  const [selectedId, setSelectedRaw] = useControllable<string | null>(\n    selectedProp,\n    defaultSelectedId,\n  );\n  const [highlight, setHighlight] = useControllable(\n    highlightProp,\n    defaultHighlightCriticalPath,\n    onHighlightCriticalPathChange,\n  );\n  const [collapsed, setCollapsed] = React.useState(\n    () => new Set(defaultCollapsedIds ?? []),\n  );\n  const [hidden, setHidden] = React.useState<Set<string>>(() => new Set());\n  const [view, setViewState] = React.useState<TraceTimeRange | null>(null);\n  const [focusId, setFocusId] = React.useState<string | null>(null);\n  const [frac, setFrac] = React.useState<number | null>(null);\n  const [width, setWidth] = React.useState(0);\n  const [axisWidth, setAxisWidth] = React.useState(0);\n  const [scroll, setScroll] = React.useState({ top: 0, height });\n\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const scrollRef = React.useRef<HTMLDivElement>(null);\n  const axisRef = React.useRef<HTMLDivElement>(null);\n  const treeRef = React.useRef<HTMLDivElement>(null);\n  const cursorRef = React.useRef<HTMLDivElement>(null);\n  const readoutRef = React.useRef<HTMLDivElement>(null);\n  const brushRef = React.useRef<HTMLDivElement>(null);\n  const overviewCursorRef = React.useRef<HTMLDivElement>(null);\n  const pendingFocus = React.useRef<string | null>(null);\n  const suppressClick = React.useRef(false);\n\n  const selectedNode = selectedId\n    ? (model.nodes.get(selectedId) ?? null)\n    : null;\n\n  const select = React.useCallback(\n    (next: string | null) => {\n      setSelectedRaw(next);\n      onSelectedChange?.(\n        next,\n        next ? (model.nodes.get(next)?.span ?? null) : null,\n      );\n    },\n    [model, onSelectedChange, setSelectedRaw],\n  );\n\n  // A selection inside a collapsed branch opens the branch so the row can be seen.\n  React.useEffect(() => {\n    if (!selectedNode) return;\n    setCollapsed((current) => {\n      let next: Set<string> | null = null;\n      for (let p = selectedNode.parent; p; p = p.parent)\n        if (current.has(p.span.id))\n          (next ??= new Set(current)).delete(p.span.id);\n      return next ?? current;\n    });\n  }, [selectedNode]);\n\n  const { rows, flat } = React.useMemo(\n    () => buildRows(model, collapsed, hidden),\n    [model, collapsed, hidden],\n  );\n  const indexOf = React.useMemo(() => {\n    const map = new Map<string, number>();\n    rows.forEach((row, i) => map.set(row.node.span.id, i));\n    return map;\n  }, [rows]);\n\n  /* ---------------------------------------------------------------- view */\n\n  const t0 = model.start;\n  const total = model.duration;\n  const target = view ?? ([t0, t0 + total] as TraceTimeRange);\n  const v0 = target[0];\n  const vs = Math.max(1e-6, target[1] - target[0]);\n  const zoomed = view != null;\n  const displayed = React.useRef({ v0, vs });\n\n  const setView = React.useCallback(\n    (next: TraceTimeRange | null) => {\n      setViewState(next);\n      onZoomChange?.(next);\n    },\n    [onZoomChange],\n  );\n\n  // Clear a zoom that no longer fits new data.\n  React.useEffect(() => {\n    setViewState((current) =>\n      current && (current[1] <= model.start || current[0] >= model.end)\n        ? null\n        : current,\n    );\n  }, [model]);\n\n  // Tween the view variables; React only renders the target, so zooming never re-renders per frame.\n  React.useLayoutEffect(() => {\n    const root = rootRef.current;\n    if (!root) return;\n    const apply = (a: number, s: number) => {\n      displayed.current = { v0: a, vs: s };\n      root.style.setProperty(\"--trace-v0\", String(tidy(a)));\n      root.style.setProperty(\"--trace-vs\", String(tidy(s)));\n    };\n    const from = displayed.current;\n    if (\n      reduced ||\n      (Math.abs(from.v0 - v0) < 1e-9 && Math.abs(from.vs - vs) < 1e-9)\n    ) {\n      apply(v0, vs);\n      return;\n    }\n    apply(from.v0, from.vs);\n    const started = performance.now();\n    let frame = 0;\n    const tick = (now: number) => {\n      const p = Math.min(1, (now - started) / 460);\n      const e = 1 - (1 - p) ** 4;\n      // Interpolate the span geometrically so zooming feels even at every scale.\n      const s = from.vs * (vs / from.vs) ** e;\n      const fromCenter = from.v0 + from.vs / 2;\n      const toCenter = v0 + vs / 2;\n      apply(fromCenter + (toCenter - fromCenter) * e - s / 2, s);\n      if (p < 1) frame = requestAnimationFrame(tick);\n      else apply(v0, vs);\n    };\n    frame = requestAnimationFrame(tick);\n    return () => cancelAnimationFrame(frame);\n  }, [v0, vs, reduced]);\n\n  const isEmpty = model.ordered.length === 0;\n  const ticks = React.useMemo(() => {\n    if (isEmpty) return { step: 1, list: [] };\n    const count = Math.max(2, Math.floor((axisWidth || 360) / 84));\n    const step = niceStep(vs, count);\n    const out: { value: number; label: string }[] = [];\n    for (\n      let t = Math.ceil(v0 / step - 1e-9) * step;\n      t <= v0 + vs + step * 1e-6;\n      t += step\n    )\n      out.push({ value: tidy(t), label: tickLabel(tidy(t), step) });\n    return { step, list: out };\n  }, [v0, vs, axisWidth, isEmpty]);\n\n  // After zooming, bring the first span inside the new range into view if none is showing.\n  React.useEffect(() => {\n    const el = scrollRef.current;\n    if (!view || !el) return;\n    const overlaps = (row: TraceRowModel) =>\n      row.depth > 0 &&\n      row.node.end >= view[0] &&\n      row.node.span.start <= view[1];\n    const top = Math.floor(el.scrollTop / rowHeight);\n    const bottom = Math.ceil((el.scrollTop + el.clientHeight - 28) / rowHeight);\n    if (rows.slice(top, bottom).some(overlaps)) return;\n    const index = rows.findIndex(overlaps);\n    if (index < 0) return;\n    el.scrollTo({\n      top: Math.max(0, (index - 1) * rowHeight),\n      behavior: reduced ? \"auto\" : \"smooth\",\n    });\n    // Rows are only read when the zoom changes, not when they do.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [view]);\n\n  /* -------------------------------------------------------------- layout */\n\n  React.useLayoutEffect(() => {\n    const root = rootRef.current;\n    const axis = axisRef.current;\n    if (!root || !axis) return;\n    const measure = () => {\n      setWidth(root.clientWidth);\n      setAxisWidth(axis.clientWidth);\n    };\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(root);\n    observer.observe(axis);\n    return () => observer.disconnect();\n  }, []);\n\n  const treeShare = Math.min(\n    0.7,\n    Math.max(0.2, frac ?? treeWidth ?? (width && width < 560 ? 0.5 : 0.4)),\n  );\n  const contentHeight = rows.length * rowHeight;\n  // The axis row is 28px; an empty list keeps room for its message.\n  const viewportHeight = rows.length\n    ? Math.min(height, contentHeight + 28)\n    : 128;\n\n  const onScroll = () => {\n    const el = scrollRef.current;\n    if (!el) return;\n    const top = el.scrollTop;\n    const h = el.clientHeight;\n    setScroll((current) =>\n      Math.floor(current.top / rowHeight) === Math.floor(top / rowHeight) &&\n      current.height === h\n        ? current\n        : { top, height: h },\n    );\n  };\n\n  const overscan = 8;\n  const first = Math.max(0, Math.floor(scroll.top / rowHeight) - overscan);\n  const last = Math.min(\n    rows.length,\n    Math.ceil((scroll.top + scroll.height) / rowHeight) + overscan,\n  );\n  const stopId =\n    focusId && indexOf.has(focusId)\n      ? focusId\n      : selectedId && indexOf.has(selectedId)\n        ? selectedId\n        : (rows[0]?.node.span.id ?? null);\n  const stopIndex = stopId ? (indexOf.get(stopId) ?? -1) : -1;\n\n  const scrollToIndex = React.useCallback(\n    (index: number, center = false) => {\n      const el = scrollRef.current;\n      if (!el || index < 0) return;\n      const header = 28;\n      const top = index * rowHeight;\n      const view = el.clientHeight - header;\n      if (center) {\n        if (top < el.scrollTop || top + rowHeight > el.scrollTop + view)\n          el.scrollTop = Math.max(0, top - view / 2 + rowHeight / 2);\n      } else if (top < el.scrollTop) el.scrollTop = top;\n      else if (top + rowHeight > el.scrollTop + view)\n        el.scrollTop = top + rowHeight - view;\n    },\n    [rowHeight],\n  );\n\n  // Bring an outside selection into view.\n  const lastSelected = React.useRef<string | null>(null);\n  React.useLayoutEffect(() => {\n    if (selectedId === lastSelected.current) return;\n    lastSelected.current = selectedId;\n    if (selectedId && indexOf.has(selectedId))\n      scrollToIndex(indexOf.get(selectedId)!, true);\n  }, [selectedId, indexOf, scrollToIndex]);\n\n  React.useLayoutEffect(() => {\n    const target = pendingFocus.current;\n    if (!target) return;\n    pendingFocus.current = null;\n    const element = treeRef.current?.querySelector<HTMLElement>(\n      `[data-span-id=\"${CSS.escape(target)}\"]`,\n    );\n    element?.focus({ preventScroll: true });\n  });\n\n  /* --------------------------------------------------------- interaction */\n\n  const toggle = React.useCallback((spanId: string) => {\n    setCollapsed((current) => {\n      const next = new Set(current);\n      if (next.has(spanId)) next.delete(spanId);\n      else next.add(spanId);\n      return next;\n    });\n  }, []);\n\n  const selectedRef = React.useRef(selectedId);\n  selectedRef.current = selectedId;\n  const activate = React.useCallback(\n    (spanId: string) => {\n      if (suppressClick.current) return;\n      setFocusId(spanId);\n      select(selectedRef.current === spanId ? null : spanId);\n    },\n    [select],\n  );\n\n  const moveFocus = (index: number) => {\n    const row = rows[Math.max(0, Math.min(rows.length - 1, index))];\n    if (!row) return;\n    pendingFocus.current = row.node.span.id;\n    setFocusId(row.node.span.id);\n    scrollToIndex(indexOf.get(row.node.span.id)!);\n  };\n\n  const onTreeKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    const target = event.target as HTMLElement;\n    const spanId = target.dataset.spanId;\n    if (!spanId || target.dataset.slot !== \"trace-row\") return;\n    const index = indexOf.get(spanId) ?? 0;\n    const row = rows[index];\n    const page = Math.max(1, Math.floor((scroll.height - 28) / rowHeight) - 1);\n    switch (event.key) {\n      case \"ArrowDown\":\n        moveFocus(index + 1);\n        break;\n      case \"ArrowUp\":\n        moveFocus(index - 1);\n        break;\n      case \"Home\":\n        moveFocus(0);\n        break;\n      case \"End\":\n        moveFocus(rows.length - 1);\n        break;\n      case \"PageDown\":\n        moveFocus(index + page);\n        break;\n      case \"PageUp\":\n        moveFocus(index - page);\n        break;\n      case \"ArrowRight\":\n        if (row.childCount > 0 && row.collapsed) toggle(spanId);\n        else if (row.childCount > 0) moveFocus(index + 1);\n        break;\n      case \"ArrowLeft\":\n        if (row.childCount > 0 && !row.collapsed) toggle(spanId);\n        else if (row.parentId && indexOf.has(row.parentId))\n          moveFocus(indexOf.get(row.parentId)!);\n        break;\n      case \"Enter\":\n      case \" \":\n        select(selectedId === spanId ? null : spanId);\n        break;\n      case \"Escape\":\n        if (selectedId) select(null);\n        else if (zoomed) setView(null);\n        else return;\n        break;\n      default:\n        return;\n    }\n    event.preventDefault();\n  };\n\n  // Pointer: hover draws a cursor with a time readout; dragging across the axis zooms.\n  const drag = React.useRef<{ x: number; id: number; active: boolean } | null>(\n    null,\n  );\n  const axisRect = () => axisRef.current?.getBoundingClientRect() ?? null;\n  const timeAtX = (x: number, rect: DOMRect) => {\n    const f = Math.min(1, Math.max(0, (x - rect.left) / (rect.width || 1)));\n    return displayed.current.v0 + f * displayed.current.vs;\n  };\n\n  const showCursor = (clientX: number | null) => {\n    const rect = axisRect();\n    const cursor = cursorRef.current;\n    const readout = readoutRef.current;\n    const overview = overviewCursorRef.current;\n    const inside =\n      rect && clientX !== null && clientX >= rect.left && clientX <= rect.right;\n    for (const el of [cursor, readout, overview])\n      if (el) el.style.opacity = inside ? \"1\" : \"0\";\n    if (!inside || !rect) return;\n    const x = clientX - rect.left;\n    const time = timeAtX(clientX, rect);\n    if (cursor) cursor.style.transform = `translateX(${x}px)`;\n    if (readout) {\n      const brush = drag.current?.active ? drag.current : null;\n      if (brush) {\n        const a = timeAtX(brush.x, rect);\n        const [lo, hi] = a < time ? [a, time] : [time, a];\n        readout.textContent = `${tickLabel(lo, vs / 50)} – ${tickLabel(hi, vs / 50)} · ${format(hi - lo)}`;\n      } else readout.textContent = format(time - t0);\n      const w = readout.offsetWidth;\n      readout.style.transform = `translateX(${Math.min(Math.max(0, x - w / 2), rect.width - w)}px)`;\n    }\n    if (overview) overview.style.left = `${((time - t0) / total) * 100}%`;\n  };\n\n  const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {\n    if (event.button !== 0 || event.pointerType === \"touch\") return;\n    const rect = axisRect();\n    if (!rect || event.clientX < rect.left || event.clientX > rect.right)\n      return;\n    if ((event.target as HTMLElement).closest('[role=\"separator\"]')) return;\n    drag.current = { x: event.clientX, id: event.pointerId, active: false };\n  };\n\n  const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {\n    const d = drag.current;\n    const rect = axisRect();\n    if (d && rect && event.pointerId === d.id) {\n      if (!d.active && Math.abs(event.clientX - d.x) > 4) {\n        d.active = true;\n        event.currentTarget.setPointerCapture(event.pointerId);\n      }\n      if (d.active && brushRef.current) {\n        const a = Math.min(Math.max(d.x, rect.left), rect.right) - rect.left;\n        const b =\n          Math.min(Math.max(event.clientX, rect.left), rect.right) - rect.left;\n        brushRef.current.style.display = \"block\";\n        brushRef.current.style.left = `${Math.min(a, b)}px`;\n        brushRef.current.style.width = `${Math.abs(b - a)}px`;\n      }\n    }\n    showCursor(event.clientX);\n  };\n\n  const endDrag = (\n    event: React.PointerEvent<HTMLDivElement>,\n    commit: boolean,\n  ) => {\n    const d = drag.current;\n    drag.current = null;\n    if (brushRef.current) brushRef.current.style.display = \"none\";\n    if (!d?.active) return;\n    const rect = axisRect();\n    if (commit && rect) {\n      const a = timeAtX(d.x, rect);\n      const b = timeAtX(event.clientX, rect);\n      const lo = Math.max(t0, Math.min(a, b));\n      const hi = Math.min(t0 + total, Math.max(a, b));\n      if (hi - lo > Math.max(total / 5000, 1e-3)) setView([lo, hi]);\n    }\n    suppressClick.current = true;\n    window.setTimeout(() => (suppressClick.current = false), 0);\n    showCursor(event.clientX);\n  };\n\n  const onDoubleClick = (event: React.MouseEvent<HTMLDivElement>) => {\n    const rect = axisRect();\n    if (\n      zoomed &&\n      rect &&\n      event.clientX >= rect.left &&\n      event.clientX <= rect.right\n    )\n      setView(null);\n  };\n\n  // Column divider: drag or use the arrow keys.\n  const onSeparatorPointerDown = (\n    event: React.PointerEvent<HTMLDivElement>,\n  ) => {\n    if (event.button !== 0) return;\n    event.preventDefault();\n    const root = rootRef.current;\n    if (!root) return;\n    const rect =\n      scrollRef.current?.getBoundingClientRect() ??\n      root.getBoundingClientRect();\n    const target = event.currentTarget;\n    target.setPointerCapture(event.pointerId);\n    const move = (e: PointerEvent) =>\n      setFrac(\n        Math.min(0.7, Math.max(0.2, (e.clientX - rect.left) / rect.width)),\n      );\n    const up = () => {\n      target.removeEventListener(\"pointermove\", move);\n      target.removeEventListener(\"pointerup\", up);\n      target.removeEventListener(\"pointercancel\", up);\n    };\n    target.addEventListener(\"pointermove\", move);\n    target.addEventListener(\"pointerup\", up);\n    target.addEventListener(\"pointercancel\", up);\n  };\n\n  const collapsibleIds = React.useMemo(\n    () =>\n      model.ordered\n        .filter((node) => node.depth > 0 && node.children.length > 0)\n        .map((node) => node.span.id),\n    [model],\n  );\n  const anyCollapsed = rows.some((row) => row.collapsed);\n\n  /* ------------------------------------------------------------ derived */\n\n  const emphasisOf = (node: TraceNode): TraceRowProps[\"emphasis\"] =>\n    highlight ? (node.critical ? \"critical\" : \"dim\") : \"normal\";\n  const labelSideOf = (node: TraceNode): TraceRowProps[\"labelSide\"] => {\n    const a = (node.span.start - v0) / vs;\n    const b = (node.end - v0) / vs;\n    if (b < 0.78) return \"after\";\n    if (a > 0.22) return \"before\";\n    return \"inside\";\n  };\n\n  const info = (node: TraceNode): TraceSpanInfo => ({\n    span: node.span,\n    parent: node.parent?.span ?? null,\n    children: node.children.map((child) => child.span),\n    depth: node.depth,\n    descendantCount: node.descendants,\n    selfTime: node.self,\n    share: (node.end - node.span.start) / total,\n    critical: node.critical,\n    color: colorOf(node.span.service),\n    trace: { start: t0, end: t0 + total, duration: total },\n  });\n\n  // Keep the last span while the panel animates closed.\n  const [shownNode, setShownNode] = React.useState<TraceNode | null>(\n    selectedNode,\n  );\n  if (selectedNode && selectedNode !== shownNode) setShownNode(selectedNode);\n\n  const label = typeof title === \"string\" ? title : \"Trace spans\";\n  const services = model.services;\n  const renderIndices: number[] = [];\n  for (let i = first; i < last; i++) renderIndices.push(i);\n  if (stopIndex >= 0 && (stopIndex < first || stopIndex >= last))\n    renderIndices.push(stopIndex);\n\n  return (\n    <div\n      ref={rootRef}\n      data-slot=\"trace-waterfall\"\n      data-zoomed={zoomed || undefined}\n      className={cn(\n        \"@container/trace flex min-w-0 flex-col overflow-hidden rounded-xl border bg-card text-card-foreground shadow-xs\",\n        className,\n      )}\n      style={\n        {\n          \"--trace-v0\": tidy(v0),\n          \"--trace-vs\": tidy(vs),\n          \"--trace-t0\": tidy(t0),\n          \"--trace-total\": tidy(total),\n          \"--trace-tree\": `${(treeShare * 100).toFixed(2)}%`,\n          \"--trace-cols\": \"minmax(0, var(--trace-tree)) minmax(0, 1fr)\",\n          ...style,\n        } as React.CSSProperties\n      }\n      {...props}\n    >\n      <div\n        data-slot=\"trace-header\"\n        className=\"flex items-start gap-3 px-4 pt-3.5 pb-3\"\n      >\n        <div className=\"min-w-0 flex-1 space-y-1\">\n          {title != null && (\n            <h3 className=\"truncate text-sm leading-5 font-semibold tracking-tight\">\n              {title}\n            </h3>\n          )}\n          <div\n            data-slot=\"trace-summary\"\n            className=\"flex flex-wrap items-center gap-x-2 gap-y-1 font-mono text-[11px] leading-4 text-muted-foreground tabular-nums\"\n          >\n            <span>\n              <span className=\"font-medium text-foreground\">\n                {isEmpty ? \"—\" : format(total)}\n              </span>\n            </span>\n            <span aria-hidden=\"true\" className=\"text-border\">\n              /\n            </span>\n            <span>\n              {spans.length} {spans.length === 1 ? \"span\" : \"spans\"}\n            </span>\n            <span\n              aria-hidden=\"true\"\n              className=\"hidden text-border @sm/trace:inline\"\n            >\n              /\n            </span>\n            <span className=\"hidden @sm/trace:inline\">\n              {services.length} {services.length === 1 ? \"service\" : \"services\"}\n            </span>\n            {model.errors > 0 && (\n              <span className=\"inline-flex items-center gap-1 rounded-full bg-destructive/10 px-1.5 font-sans text-[11px] font-medium text-destructive\">\n                <AlertTriangle aria-hidden=\"true\" className=\"size-3\" />\n                {model.errors} {model.errors === 1 ? \"error\" : \"errors\"}\n              </span>\n            )}\n          </div>\n          {description != null && (\n            <p\n              id={`${id}-description`}\n              className=\"text-xs text-muted-foreground\"\n            >\n              {description}\n            </p>\n          )}\n        </div>\n        <div className=\"flex shrink-0 items-center gap-1\">\n          {actions}\n          <div\n            role=\"toolbar\"\n            aria-label=\"Trace tools\"\n            className=\"flex items-center gap-0.5\"\n          >\n            <button\n              type=\"button\"\n              className={toolButton}\n              aria-pressed={highlight}\n              title=\"Highlight the critical path\"\n              onClick={() => setHighlight(!highlight)}\n            >\n              <Route className=\"size-4\" aria-hidden=\"true\" />\n              <span className=\"sr-only\">Highlight the critical path</span>\n            </button>\n            <button\n              type=\"button\"\n              className={toolButton}\n              title={anyCollapsed ? \"Expand all\" : \"Collapse all\"}\n              disabled={!collapsibleIds.length}\n              onClick={() =>\n                setCollapsed(anyCollapsed ? new Set() : new Set(collapsibleIds))\n              }\n            >\n              {anyCollapsed ? (\n                <FoldDown className=\"size-4\" aria-hidden=\"true\" />\n              ) : (\n                <FoldUp className=\"size-4\" aria-hidden=\"true\" />\n              )}\n              <span className=\"sr-only\">\n                {anyCollapsed ? \"Expand all\" : \"Collapse all\"}\n              </span>\n            </button>\n            <button\n              type=\"button\"\n              className={toolButton}\n              title=\"Reset zoom\"\n              disabled={!zoomed}\n              onClick={() => setView(null)}\n            >\n              <ZoomReset className=\"size-4\" aria-hidden=\"true\" />\n              <span className=\"sr-only\">Reset zoom</span>\n            </button>\n          </div>\n        </div>\n      </div>\n\n      {showOverview && !isEmpty && (\n        <TraceOverview\n          nodes={flat}\n          start={t0}\n          total={total}\n          zoomed={zoomed}\n          colorOf={colorOf}\n          highlight={highlight}\n          cursorRef={overviewCursorRef}\n          onRange={setView}\n          viewStart={target[0]}\n          viewEnd={target[1]}\n        />\n      )}\n\n      <div\n        ref={scrollRef}\n        data-slot=\"trace-scroll\"\n        className=\"relative mt-3 touch-pan-y overflow-y-auto overscroll-contain border-t select-none\"\n        style={{ height: viewportHeight }}\n        onScroll={onScroll}\n        onPointerDown={onPointerDown}\n        onPointerMove={onPointerMove}\n        onPointerUp={(event) => endDrag(event, true)}\n        onPointerCancel={(event) => endDrag(event, false)}\n        onPointerLeave={() => {\n          if (!drag.current?.active) showCursor(null);\n        }}\n        onDoubleClick={onDoubleClick}\n      >\n        <div\n          data-slot=\"trace-axis\"\n          className=\"sticky top-0 z-20 grid h-7 grid-cols-(--trace-cols) border-b bg-card\"\n        >\n          <div className=\"flex min-w-0 items-center justify-between gap-2 border-r pr-2.5 pl-3 font-mono text-[10.5px] text-muted-foreground\">\n            <span className=\"truncate\">Span</span>\n            <span className=\"@max-sm/trace:hidden\">Duration</span>\n          </div>\n          <div\n            ref={axisRef}\n            className={cn(\n              \"relative min-w-0 overflow-hidden\",\n              zoomed ? \"cursor-zoom-out\" : \"cursor-crosshair\",\n            )}\n            title={\n              zoomed\n                ? \"Drag to zoom further, double-click to reset\"\n                : \"Drag across the axis to zoom\"\n            }\n          >\n            {ticks.list.map((tick) => (\n              <span\n                key={`${ticks.step}-${tick.value}`}\n                className=\"absolute inset-y-0 flex items-center border-l border-border pl-1 font-mono text-[10px] leading-none whitespace-nowrap text-muted-foreground tabular-nums motion-safe:animate-[trace-fade_.35s_ease-out_both]\"\n                style={{ left: at(tick.value) }}\n              >\n                {/* A label that would be clipped at the right edge keeps only its line. */}\n                {(tick.value - v0) / vs <= 0.93 ? tick.label : null}\n              </span>\n            ))}\n            <div\n              ref={readoutRef}\n              aria-hidden=\"true\"\n              className=\"pointer-events-none absolute top-1/2 left-0 z-10 -mt-2 h-4 rounded-[4px] bg-foreground px-1.5 font-mono text-[10px] leading-4 whitespace-nowrap text-background tabular-nums opacity-0 shadow-sm\"\n            />\n          </div>\n          <div\n            role=\"separator\"\n            aria-orientation=\"vertical\"\n            aria-label=\"Resize span column\"\n            aria-valuemin={20}\n            aria-valuemax={70}\n            aria-valuenow={Math.round(treeShare * 100)}\n            tabIndex={0}\n            onPointerDown={onSeparatorPointerDown}\n            onKeyDown={(event) => {\n              const delta =\n                event.key === \"ArrowLeft\"\n                  ? -0.02\n                  : event.key === \"ArrowRight\"\n                    ? 0.02\n                    : 0;\n              if (!delta) return;\n              event.preventDefault();\n              setFrac(Math.min(0.7, Math.max(0.2, treeShare + delta)));\n            }}\n            className=\"group/sep absolute inset-y-0 z-10 w-2 -translate-x-1/2 cursor-col-resize outline-none\"\n            style={{ left: \"var(--trace-tree)\" }}\n          >\n            <span className=\"absolute inset-y-1 left-1/2 w-0.5 -translate-x-1/2 rounded-full bg-transparent transition-colors group-hover/sep:bg-primary/60 group-focus-visible/sep:bg-ring\" />\n          </div>\n        </div>\n\n        {rows.length === 0 ? (\n          <p className=\"py-10 text-center text-xs text-muted-foreground\">\n            {spans.length\n              ? \"Every service is filtered out.\"\n              : \"No spans in this trace.\"}\n          </p>\n        ) : (\n          <div\n            ref={treeRef}\n            role=\"tree\"\n            aria-label={label}\n            aria-describedby={\n              description != null ? `${id}-description` : undefined\n            }\n            onKeyDown={onTreeKeyDown}\n            onBlur={(event) => {\n              if (!event.currentTarget.contains(event.relatedTarget as Node))\n                setFocusId(null);\n            }}\n            className=\"relative\"\n            style={{ height: contentHeight }}\n          >\n            <div\n              aria-hidden=\"true\"\n              className=\"pointer-events-none absolute inset-0 grid grid-cols-(--trace-cols)\"\n            >\n              <div />\n              <div className=\"relative overflow-hidden\">\n                {ticks.list.map((tick) => (\n                  <span\n                    key={`${ticks.step}-${tick.value}`}\n                    className=\"absolute inset-y-0 w-px bg-border/55 motion-safe:animate-[trace-fade_.35s_ease-out_both]\"\n                    style={{ left: at(tick.value) }}\n                  />\n                ))}\n              </div>\n            </div>\n\n            {renderIndices.map((i) => {\n              const row = rows[i];\n              const node = row.node;\n              return (\n                <TraceRow\n                  key={node.span.id}\n                  row={row}\n                  index={i}\n                  rowHeight={rowHeight}\n                  color={colorOf(node.span.service)}\n                  colorOf={colorOf}\n                  selected={node.span.id === selectedId}\n                  tabStop={node.span.id === stopId}\n                  emphasis={emphasisOf(node)}\n                  labelSide={labelSideOf(node)}\n                  outside={\n                    zoomed && (node.end < v0 || node.span.start > v0 + vs)\n                  }\n                  format={format}\n                  onToggle={toggle}\n                  onActivate={activate}\n                  onFocusRow={setFocusId}\n                />\n              );\n            })}\n\n            <div\n              aria-hidden=\"true\"\n              className=\"pointer-events-none absolute inset-0 z-10 grid grid-cols-(--trace-cols)\"\n            >\n              <div />\n              <div className=\"relative overflow-hidden\">\n                <div\n                  ref={cursorRef}\n                  className=\"absolute inset-y-0 left-0 w-px bg-foreground/45 opacity-0 transition-opacity duration-100\"\n                />\n                <div\n                  ref={brushRef}\n                  className=\"absolute inset-y-0 hidden border-x border-primary/70 bg-primary/10\"\n                />\n              </div>\n            </div>\n          </div>\n        )}\n      </div>\n\n      <TraceDetail\n        node={shownNode}\n        open={selectedNode != null}\n        info={shownNode ? info(shownNode) : null}\n        format={format}\n        renderDetail={renderDetail}\n        onClose={() => select(null)}\n        onSelect={select}\n      />\n\n      {showLegend && services.length > 0 && (\n        <div\n          data-slot=\"trace-legend\"\n          className=\"flex flex-wrap items-center gap-1 border-t px-3 py-2\"\n          role=\"group\"\n          aria-label=\"Show or hide services\"\n        >\n          {services.map((service) => {\n            const visible = !hidden.has(service.name);\n            const color = colorOf(service.name);\n            return (\n              <button\n                key={service.name}\n                type=\"button\"\n                aria-pressed={visible}\n                title={\n                  visible ? `Hide ${service.name}` : `Show ${service.name}`\n                }\n                onClick={() =>\n                  setHidden((current) => {\n                    const next = new Set(current);\n                    if (next.has(service.name)) next.delete(service.name);\n                    else next.add(service.name);\n                    return next;\n                  })\n                }\n                className={cn(\n                  \"inline-flex h-6 items-center gap-1.5 rounded-md border px-1.5 text-xs transition-colors motion-reduce:transition-none\",\n                  visible\n                    ? \"border-transparent text-foreground hover:bg-muted\"\n                    : \"border-dashed border-border text-muted-foreground line-through decoration-muted-foreground/50 hover:text-foreground\",\n                  focusRing,\n                )}\n              >\n                <span\n                  aria-hidden=\"true\"\n                  className=\"size-2 rounded-[2px]\"\n                  style={\n                    visible\n                      ? { background: color }\n                      : { boxShadow: `inset 0 0 0 1px ${color}` }\n                  }\n                />\n                <span className=\"font-medium\">{service.name}</span>\n                <span className=\"font-mono text-[10.5px] text-muted-foreground tabular-nums\">\n                  {service.count}\n                </span>\n                {service.errors > 0 && (\n                  <span\n                    className=\"inline-flex items-center gap-0.5 font-mono text-[10.5px] text-destructive tabular-nums\"\n                    title={`${service.errors} ${service.errors === 1 ? \"error\" : \"errors\"}`}\n                  >\n                    <AlertTriangle aria-hidden=\"true\" className=\"size-2.5\" />\n                    {service.errors}\n                    <span className=\"sr-only\">\n                      {\" \"}\n                      {service.errors === 1 ? \"error\" : \"errors\"}\n                    </span>\n                  </span>\n                )}\n              </button>\n            );\n          })}\n          {hidden.size > 0 && (\n            <button\n              type=\"button\"\n              onClick={() => setHidden(new Set())}\n              className={cn(\n                \"ml-auto h-6 rounded-md px-2 text-xs font-medium text-primary hover:bg-muted\",\n                focusRing,\n              )}\n            >\n              Show all\n            </button>\n          )}\n        </div>\n      )}\n\n      <style href=\"overtrue-trace-waterfall\" precedence=\"default\">\n        {`@keyframes trace-fade{from{opacity:0}to{opacity:1}}`}\n      </style>\n    </div>\n  );\n}\n\n/* ------------------------------------------------------------------------ */\n/* Overview                                                                  */\n/* ------------------------------------------------------------------------ */\n\ninterface TraceOverviewProps {\n  nodes: TraceNode[];\n  start: number;\n  total: number;\n  viewStart: number;\n  viewEnd: number;\n  zoomed: boolean;\n  colorOf: (service: string) => string;\n  highlight: boolean;\n  cursorRef: React.RefObject<HTMLDivElement | null>;\n  onRange: (range: TraceTimeRange | null) => void;\n}\n\nconst TraceOverview = React.memo(function TraceOverview({\n  nodes,\n  start,\n  total,\n  viewStart,\n  viewEnd,\n  zoomed,\n  colorOf,\n  highlight,\n  cursorRef,\n  onRange,\n}: TraceOverviewProps) {\n  const ref = React.useRef<HTMLDivElement>(null);\n  const brushRef = React.useRef<HTMLDivElement>(null);\n  const drag = React.useRef<{ x: number; active: boolean } | null>(null);\n  // A mini icicle: one band per depth, split into lanes only where siblings overlap.\n  const lanes = React.useMemo(() => {\n    const byDepth = new Map<number, TraceNode[]>();\n    for (const node of nodes) {\n      const list = byDepth.get(node.depth) ?? [];\n      list.push(node);\n      byDepth.set(node.depth, list);\n    }\n    const placed: { node: TraceNode; lane: number }[] = [];\n    let offset = 0;\n    for (const depth of [...byDepth.keys()].sort((a, b) => a - b)) {\n      const ends: number[] = [];\n      const list = byDepth\n        .get(depth)!\n        .sort((a, b) => a.span.start - b.span.start);\n      for (const node of list) {\n        let lane = ends.findIndex((end) => end <= node.span.start + 1e-9);\n        if (lane < 0) lane = ends.push(0) - 1;\n        ends[lane] = node.end;\n        placed.push({ node, lane: offset + lane });\n      }\n      offset += ends.length;\n    }\n    return { placed, count: offset };\n  }, [nodes]);\n  const laneHeight = Math.min(7, 30 / Math.max(1, lanes.count));\n  const lens = (a: number) =>\n    `calc((var(--trace-v0) - ${tidy(start)}) / ${tidy(total)} * 100% + ${a}px)`;\n\n  const timeAt = (clientX: number) => {\n    const rect = ref.current!.getBoundingClientRect();\n    return (\n      start +\n      Math.min(1, Math.max(0, (clientX - rect.left) / rect.width)) * total\n    );\n  };\n\n  return (\n    <div className=\"px-4\">\n      <div\n        ref={ref}\n        data-slot=\"trace-overview\"\n        aria-hidden=\"true\"\n        className=\"relative h-10 cursor-crosshair touch-pan-y overflow-hidden rounded-md border bg-muted/25 select-none\"\n        onPointerDown={(event) => {\n          if (event.button !== 0) return;\n          drag.current = { x: event.clientX, active: false };\n          event.currentTarget.setPointerCapture(event.pointerId);\n        }}\n        onPointerMove={(event) => {\n          const rect = event.currentTarget.getBoundingClientRect();\n          const cursor = cursorRef.current;\n          if (cursor) {\n            cursor.style.opacity = \"1\";\n            cursor.style.left = `${((event.clientX - rect.left) / rect.width) * 100}%`;\n          }\n          const d = drag.current;\n          if (!d) return;\n          if (!d.active && Math.abs(event.clientX - d.x) > 3) d.active = true;\n          if (d.active && brushRef.current) {\n            const a =\n              Math.min(Math.max(d.x, rect.left), rect.right) - rect.left;\n            const b =\n              Math.min(Math.max(event.clientX, rect.left), rect.right) -\n              rect.left;\n            brushRef.current.style.display = \"block\";\n            brushRef.current.style.left = `${Math.min(a, b)}px`;\n            brushRef.current.style.width = `${Math.abs(b - a)}px`;\n          }\n        }}\n        onPointerUp={(event) => {\n          const d = drag.current;\n          drag.current = null;\n          if (brushRef.current) brushRef.current.style.display = \"none\";\n          if (!d) return;\n          if (d.active) {\n            const a = timeAt(d.x);\n            const b = timeAt(event.clientX);\n            if (Math.abs(b - a) > total / 5000)\n              onRange([Math.min(a, b), Math.max(a, b)]);\n          } else if (zoomed) {\n            // A click recenters the zoom window on that moment.\n            const width = viewEnd - viewStart;\n            const center = timeAt(event.clientX);\n            const lo = Math.min(\n              Math.max(start, center - width / 2),\n              start + total - width,\n            );\n            onRange([lo, lo + width]);\n          }\n        }}\n        onPointerLeave={() => {\n          if (cursorRef.current) cursorRef.current.style.opacity = \"0\";\n        }}\n        onDoubleClick={() => onRange(null)}\n      >\n        <div className=\"absolute inset-x-1 inset-y-1\">\n          {lanes.placed.map(({ node, lane }) => {\n            const isError = node.span.status === \"error\";\n            return (\n              <span\n                key={node.span.id}\n                className={cn(\n                  \"absolute rounded-[1.5px]\",\n                  highlight && !node.critical && !isError && \"opacity-35\",\n                )}\n                style={{\n                  left: `${(((node.span.start - start) / total) * 100).toFixed(3)}%`,\n                  width: `max(2px, ${(((node.end - node.span.start) / total) * 100).toFixed(3)}%)`,\n                  top: lane * laneHeight,\n                  height: Math.max(\n                    1,\n                    laneHeight - (laneHeight > 3 ? 1.5 : 0.5),\n                  ),\n                  background: isError ? errorFill : colorOf(node.span.service),\n                }}\n              />\n            );\n          })}\n        </div>\n        {zoomed && (\n          <>\n            <div\n              className=\"absolute inset-y-0 left-0 bg-card/70\"\n              style={{ width: lens(0) }}\n            />\n            <div\n              className=\"absolute inset-y-0 right-0 bg-card/70\"\n              style={{\n                left: `calc((var(--trace-v0) + var(--trace-vs) - ${tidy(start)}) / ${tidy(total)} * 100%)`,\n              }}\n            />\n            <div\n              className=\"absolute inset-y-0 rounded-[3px] border-x-2 border-primary shadow-[0_0_0_1px_color-mix(in_oklab,var(--color-primary)_25%,transparent)]\"\n              style={{\n                left: lens(0),\n                width: `max(4px, calc(var(--trace-vs) / ${tidy(total)} * 100%))`,\n              }}\n            />\n          </>\n        )}\n        <div\n          ref={cursorRef}\n          className=\"pointer-events-none absolute inset-y-0 w-px bg-foreground/50 opacity-0 transition-opacity duration-100\"\n        />\n        <div\n          ref={brushRef}\n          className=\"pointer-events-none absolute inset-y-0 hidden border-x border-primary bg-primary/15\"\n        />\n      </div>\n    </div>\n  );\n});\n\n/* ------------------------------------------------------------------------ */\n/* Detail                                                                    */\n/* ------------------------------------------------------------------------ */\n\ninterface TraceDetailProps {\n  node: TraceNode | null;\n  info: TraceSpanInfo | null;\n  open: boolean;\n  format: (ms: number) => string;\n  renderDetail?: (span: TraceSpan, info: TraceSpanInfo) => React.ReactNode;\n  onClose: () => void;\n  onSelect: (id: string | null) => void;\n}\n\nfunction TraceDetail({\n  node,\n  info,\n  open,\n  format,\n  renderDetail,\n  onClose,\n  onSelect,\n}: TraceDetailProps) {\n  const s = node?.span;\n  const isError = s?.status === \"error\";\n  return (\n    <div\n      data-slot=\"trace-detail\"\n      data-open={open || undefined}\n      className=\"grid grid-rows-[0fr] transition-[grid-template-rows] duration-300 ease-out data-[open]:grid-rows-[1fr] motion-reduce:transition-none\"\n      inert={!open}\n    >\n      <div className=\"min-h-0 overflow-hidden\">\n        {s && info && (\n          <section\n            aria-label={`Span detail: ${s.name}`}\n            className=\"border-t bg-muted/20\"\n          >\n            <div className=\"flex items-start gap-2.5 px-4 pt-3\">\n              <span\n                aria-hidden=\"true\"\n                className=\"mt-1.5 size-2 shrink-0 rounded-full\"\n                style={{ background: info.color }}\n              />\n              <div className=\"min-w-0 flex-1\">\n                <div className=\"flex flex-wrap items-center gap-x-2 gap-y-1\">\n                  <h4 className=\"min-w-0 truncate text-sm font-semibold tracking-tight\">\n                    {s.name}\n                  </h4>\n                  {isError ? (\n                    <span className=\"inline-flex items-center gap-1 rounded-full bg-destructive/10 px-1.5 py-px text-[11px] font-medium text-destructive\">\n                      <AlertTriangle aria-hidden=\"true\" className=\"size-3\" />\n                      Error\n                    </span>\n                  ) : (\n                    <span className=\"inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-1.5 py-px text-[11px] font-medium text-emerald-700 dark:text-emerald-400\">\n                      <span\n                        aria-hidden=\"true\"\n                        className=\"size-1.5 rounded-full bg-emerald-500\"\n                      />\n                      OK\n                    </span>\n                  )}\n                  {info.critical && (\n                    <span className=\"inline-flex items-center gap-1 rounded-full bg-primary/10 px-1.5 py-px text-[11px] font-medium text-primary\">\n                      <Route aria-hidden=\"true\" className=\"size-3\" />\n                      Critical path\n                    </span>\n                  )}\n                </div>\n                <p className=\"mt-0.5 flex min-w-0 flex-wrap gap-x-2 font-mono text-[11px] text-muted-foreground\">\n                  <span>{s.service}</span>\n                  <span aria-hidden=\"true\" className=\"text-border\">\n                    /\n                  </span>\n                  <span className=\"truncate\">{s.id}</span>\n                  {info.parent && (\n                    <>\n                      <span aria-hidden=\"true\" className=\"text-border\">\n                        /\n                      </span>\n                      <button\n                        type=\"button\"\n                        onClick={() => onSelect(info.parent!.id)}\n                        className={cn(\n                          \"truncate rounded-sm text-primary hover:underline\",\n                          focusRing,\n                        )}\n                      >\n                        ↑ {info.parent.name}\n                      </button>\n                    </>\n                  )}\n                </p>\n              </div>\n              <button\n                type=\"button\"\n                onClick={onClose}\n                className={cn(toolButton, \"-mt-0.5 -mr-1.5\")}\n                title=\"Close\"\n              >\n                <X className=\"size-4\" aria-hidden=\"true\" />\n                <span className=\"sr-only\">Close span detail</span>\n              </button>\n            </div>\n\n            <dl\n              data-slot=\"trace-detail-timing\"\n              className=\"mx-4 mt-3 grid grid-cols-2 gap-px overflow-hidden rounded-lg border bg-border @lg/trace:grid-cols-4\"\n            >\n              {(\n                [\n                  [\"Start\", `+${format(s.start - info.trace.start)}`],\n                  [\"Duration\", format(s.duration)],\n                  [\"Self time\", format(info.selfTime)],\n                  [\"Share of trace\", formatPercent(info.share)],\n                ] as const\n              ).map(([term, value]) => (\n                <div key={term} className=\"bg-card px-3 py-2\">\n                  <dt className=\"text-[11px] text-muted-foreground\">{term}</dt>\n                  <dd className=\"font-mono text-sm font-medium tabular-nums\">\n                    {value}\n                  </dd>\n                </div>\n              ))}\n            </dl>\n            <div\n              aria-hidden=\"true\"\n              className=\"relative mx-4 mt-2.5 h-1.5 rounded-full bg-muted\"\n            >\n              <span\n                className=\"absolute inset-y-0 rounded-full\"\n                style={{\n                  left: `${((s.start - info.trace.start) / info.trace.duration) * 100}%`,\n                  width: `max(3px, ${(info.share * 100).toFixed(3)}%)`,\n                  background: isError ? DESTRUCTIVE : info.color,\n                }}\n              />\n            </div>\n\n            <div data-slot=\"trace-detail-body\" className=\"px-4 pt-3 pb-4\">\n              {renderDetail ? (\n                renderDetail(s, info)\n              ) : (\n                <>\n                  <p className=\"mb-1.5 flex items-baseline gap-1.5 text-xs font-medium\">\n                    Attributes\n                    <span className=\"font-mono text-[10.5px] font-normal text-muted-foreground tabular-nums\">\n                      {Object.keys(s.attributes ?? {}).length}\n                    </span>\n                  </p>\n                  <TraceSpanAttributes attributes={s.attributes} />\n                </>\n              )}\n            </div>\n          </section>\n        )}\n      </div>\n    </div>\n  );\n}\n"
    },
    {
      "path": "src/registry/overtrue/deploy-pipeline.tsx",
      "type": "registry:component",
      "target": "components/overtrue/deploy-pipeline.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport {\n  IconBan as Ban,\n  IconCircleCheckFilled as CircleCheck,\n  IconCircleDashed as CircleDashed,\n  IconCircleMinus as CircleMinus,\n  IconCircleXFilled as CircleX,\n  IconClock as Clock,\n  IconRefresh as Refresh,\n  IconX as X,\n} from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport type PipelineStatus =\n  \"queued\" | \"running\" | \"success\" | \"failed\" | \"skipped\" | \"canceled\";\n\nexport interface PipelineJob {\n  id: string;\n  label: string;\n  status: PipelineStatus;\n  /** Wall time in milliseconds. Leave it out while running and pass `startedAt` instead. */\n  duration?: number;\n  /** Epoch milliseconds. Drives the live elapsed timer while the job runs. */\n  startedAt?: number;\n  /** A short secondary line: runner, exit code, retry count. */\n  detail?: string;\n}\n\nexport interface PipelineStage {\n  id: string;\n  label: string;\n  jobs: PipelineJob[];\n}\n\nexport type PipelineOrientation = \"auto\" | \"horizontal\" | \"vertical\";\nexport type PipelineStatusLabels = Record<PipelineStatus, string>;\n/** Any CSS color per status, e.g. `{ running: \"var(--color-chart-4)\" }`. */\nexport type PipelineColors = Partial<Record<PipelineStatus, string>>;\n\nexport interface DeployPipelineLabels {\n  retry: string;\n  close: string;\n  total: string;\n  progress: string;\n  stages: string;\n}\n\nexport interface DeployPipelineProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"title\" | \"children\"\n> {\n  /** Stages run left to right; jobs inside a stage run in parallel. */\n  stages: PipelineStage[];\n  title?: React.ReactNode;\n  /** Commit, branch, author… rendered under the title. */\n  meta?: React.ReactNode;\n  /** Buttons or menus at the top right. */\n  actions?: React.ReactNode;\n  /** Override the run status derived from the jobs. */\n  status?: PipelineStatus;\n  /** Override the total duration (ms) derived from the slowest job of each stage. */\n  duration?: number;\n  /** `auto` lays stages out horizontally when each gets at least `minStageWidth`, else as a vertical timeline. */\n  orientation?: PipelineOrientation;\n  /** Narrowest stage column, in px, before `auto` switches to the vertical timeline. */\n  minStageWidth?: number;\n  selectedJobId?: string | null;\n  defaultSelectedJobId?: string | null;\n  onSelectedJobChange?: (jobId: string | null, job: PipelineJob | null) => void;\n  /** Shows a retry button on failed jobs. */\n  onRetry?: (job: PipelineJob, stage: PipelineStage) => void;\n  /** Content for the panel that opens under the selected job. Falls back to `job.detail`. */\n  renderJobDetail?: (job: PipelineJob, stage: PipelineStage) => React.ReactNode;\n  durationFormatter?: (ms: number) => string;\n  statusLabels?: Partial<PipelineStatusLabels>;\n  labels?: Partial<DeployPipelineLabels>;\n  colors?: PipelineColors;\n  /** Show the per-job progress ticks under the header. */\n  showProgress?: boolean;\n}\n\nconst STATUS_LABELS: PipelineStatusLabels = {\n  queued: \"Queued\",\n  running: \"Running\",\n  success: \"Passed\",\n  failed: \"Failed\",\n  skipped: \"Skipped\",\n  canceled: \"Canceled\",\n};\n\nconst LABELS: DeployPipelineLabels = {\n  retry: \"Retry\",\n  close: \"Close details\",\n  total: \"Total duration\",\n  progress: \"Jobs finished\",\n  stages: \"Pipeline stages\",\n};\n\nconst GAP = 32;\nconst PAD = 16;\nconst FINISHED = new Set<PipelineStatus>([\n  \"success\",\n  \"failed\",\n  \"skipped\",\n  \"canceled\",\n]);\n\nconst focusRing =\n  \"outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-1 focus-visible:ring-offset-card\";\n\nconst useIsoLayoutEffect =\n  typeof window === \"undefined\" ? React.useEffect : React.useLayoutEffect;\n\nconst pad = (value: number) => String(value).padStart(2, \"0\");\n\n/** 950 → \"<1s\", 42 000 → \"42s\", 64 000 → \"1m 04s\", 3 720 000 → \"1h 02m\". */\nexport function formatPipelineDuration(ms: number) {\n  if (!Number.isFinite(ms) || ms < 0) return \"—\";\n  if (ms < 1000) return ms <= 0 ? \"0s\" : \"<1s\";\n  const seconds = Math.floor(ms / 1000);\n  if (seconds < 60) return `${seconds}s`;\n  const minutes = Math.floor(seconds / 60);\n  if (minutes < 60) return `${minutes}m ${pad(seconds % 60)}s`;\n  return `${Math.floor(minutes / 60)}h ${pad(minutes % 60)}m`;\n}\n\n/** Roll a set of job statuses up into one: used for stages and for the whole run. */\nexport function summarizePipelineStatus(\n  statuses: PipelineStatus[],\n): PipelineStatus {\n  if (statuses.length === 0) return \"queued\";\n  if (statuses.includes(\"running\")) return \"running\";\n  if (statuses.includes(\"failed\")) return \"failed\";\n  if (statuses.includes(\"canceled\")) return \"canceled\";\n  if (statuses.every((status) => status === \"skipped\")) return \"skipped\";\n  if (statuses.every((status) => status === \"success\" || status === \"skipped\"))\n    return \"success\";\n  if (statuses.every((status) => status === \"queued\")) return \"queued\";\n  // Some jobs finished and the rest are waiting for a runner.\n  return \"running\";\n}\n\nconst tone = (status: PipelineStatus) =>\n  ({ \"--tone\": `var(--pipeline-${status})` }) as React.CSSProperties;\n\n/** Status glyph used by the pipeline. Color comes from the `--pipeline-<status>` variables. */\nexport function PipelineStatusIcon({\n  status,\n  className,\n  ...props\n}: { status: PipelineStatus } & React.ComponentProps<\"span\">) {\n  const icon = \"size-full\";\n  return (\n    <span\n      data-slot=\"pipeline-status-icon\"\n      data-status={status}\n      aria-hidden=\"true\"\n      style={tone(status)}\n      className={cn(\"inline-flex size-4 shrink-0 text-(--tone)\", className)}\n      {...props}\n    >\n      {status === \"running\" ? (\n        <svg\n          viewBox=\"0 0 16 16\"\n          fill=\"none\"\n          className={cn(icon, \"motion-safe:animate-spin\")}\n          style={{ animationDuration: \"1.1s\" }}\n        >\n          <circle\n            cx=\"8\"\n            cy=\"8\"\n            r=\"6\"\n            stroke=\"currentColor\"\n            strokeOpacity=\"0.2\"\n            strokeWidth=\"2\"\n          />\n          <path\n            d=\"M8 2a6 6 0 0 1 6 6\"\n            stroke=\"currentColor\"\n            strokeWidth=\"2\"\n            strokeLinecap=\"round\"\n          />\n          <circle\n            cx=\"8\"\n            cy=\"8\"\n            r=\"1.75\"\n            fill=\"currentColor\"\n            className=\"motion-safe:hidden\"\n          />\n        </svg>\n      ) : status === \"success\" ? (\n        <CircleCheck className={icon} />\n      ) : status === \"failed\" ? (\n        <CircleX className={icon} />\n      ) : status === \"skipped\" ? (\n        <CircleMinus className={icon} stroke={1.75} />\n      ) : status === \"canceled\" ? (\n        <Ban className={icon} stroke={1.75} />\n      ) : (\n        <CircleDashed className={icon} stroke={1.75} />\n      )}\n    </span>\n  );\n}\n\nfunction useNow(active: boolean) {\n  const [now, setNow] = React.useState<number | null>(null);\n  React.useEffect(() => {\n    if (!active) return;\n    setNow(Date.now());\n    const timer = window.setInterval(() => setNow(Date.now()), 500);\n    return () => window.clearInterval(timer);\n  }, [active]);\n  return now;\n}\n\nfunction elapsed(job: PipelineJob, now: number | null) {\n  if (job.duration !== undefined) return job.duration;\n  if (job.status === \"running\" && job.startedAt !== undefined && now !== null)\n    return Math.max(0, now - job.startedAt);\n  return undefined;\n}\n\ntype EdgeEnd = { job: string } | { stage: string };\ninterface EdgeGeometry {\n  key: string;\n  d: string;\n  from: EdgeEnd;\n  to: EdgeEnd;\n}\ninterface Geometry {\n  edges: EdgeGeometry[];\n  ports: { key: string; x: number; y: number; job: string }[];\n}\n\ntype EdgeState = \"active\" | \"done\" | \"blocked\" | \"pending\";\n\nfunction edgeState(from: PipelineStatus, to: PipelineStatus): EdgeState {\n  if (to === \"running\") return \"active\";\n  if (to === \"success\" || to === \"failed\") return \"done\";\n  if (\n    from === \"failed\" ||\n    from === \"canceled\" ||\n    to === \"canceled\" ||\n    to === \"skipped\"\n  )\n    return \"blocked\";\n  return \"pending\";\n}\n\nconst curve = (x1: number, y1: number, x2: number, y2: number) => {\n  const mid = (x1 + x2) / 2;\n  return `M${x1.toFixed(1)} ${y1.toFixed(1)}C${mid.toFixed(1)} ${y1.toFixed(1)} ${mid.toFixed(1)} ${y2.toFixed(1)} ${x2.toFixed(1)} ${y2.toFixed(1)}`;\n};\n\nfunction Shimmer({ className }: { className?: string }) {\n  return (\n    <span\n      aria-hidden=\"true\"\n      className={cn(\n        \"pointer-events-none absolute overflow-hidden motion-reduce:hidden\",\n        className,\n      )}\n    >\n      <span className=\"block h-full w-1/2 animate-[pipeline-sweep_1.6s_cubic-bezier(0.4,0,0.2,1)_infinite] bg-linear-to-r from-transparent via-(--tone) to-transparent\" />\n    </span>\n  );\n}\n\nconst styles = `@keyframes pipeline-sweep{from{transform:translateX(-100%)}to{transform:translateX(200%)}}@keyframes pipeline-flow{from{stroke-dashoffset:100}to{stroke-dashoffset:0}}@keyframes pipeline-rail{from{background-position:0 -24px}to{background-position:0 0}}`;\n\n/**\n * A CI/CD run as stages of parallel jobs: live timers, flowing connectors into the\n * running stage, retry on failure, and a detail panel for the selected job.\n */\nexport function DeployPipeline({\n  stages,\n  title = \"Pipeline\",\n  meta,\n  actions,\n  status: statusProp,\n  duration: durationProp,\n  orientation = \"auto\",\n  minStageWidth = 104,\n  selectedJobId: selectedProp,\n  defaultSelectedJobId = null,\n  onSelectedJobChange,\n  onRetry,\n  renderJobDetail,\n  durationFormatter = formatPipelineDuration,\n  statusLabels: statusLabelsProp,\n  labels: labelsProp,\n  colors,\n  showProgress = true,\n  className,\n  style,\n  ref,\n  onKeyDown,\n  ...props\n}: DeployPipelineProps) {\n  const statusLabels = { ...STATUS_LABELS, ...statusLabelsProp };\n  const labels = { ...LABELS, ...labelsProp };\n  const rootRef = React.useRef<HTMLDivElement | null>(null);\n  const graphRef = React.useRef<HTMLDivElement | null>(null);\n  const jobRefs = React.useRef(new Map<string, HTMLButtonElement>());\n  const nodeRefs = React.useRef(new Map<string, HTMLDivElement>());\n  // Row to return to while arrowing across stages of different heights.\n  const rowMemory = React.useRef<number | null>(null);\n\n  const [width, setWidth] = React.useState<number | null>(null);\n  const [selectedState, setSelectedState] = React.useState<string | null>(\n    defaultSelectedJobId,\n  );\n  const selectedId = selectedProp !== undefined ? selectedProp : selectedState;\n  const [focusId, setFocusId] = React.useState<string | null>(null);\n  const [geometry, setGeometry] = React.useState<Geometry>({\n    edges: [],\n    ports: [],\n  });\n\n  const setRoot = React.useCallback(\n    (node: HTMLDivElement | null) => {\n      rootRef.current = node;\n      if (typeof ref === \"function\") ref(node);\n      else if (ref) ref.current = node;\n    },\n    [ref],\n  );\n\n  useIsoLayoutEffect(() => {\n    const element = rootRef.current;\n    if (!element) return;\n    setWidth(element.clientWidth);\n    const observer = new ResizeObserver(([entry]) =>\n      setWidth(entry.contentRect.width),\n    );\n    observer.observe(element);\n    return () => observer.disconnect();\n  }, []);\n\n  const count = stages.length;\n  const layout: \"horizontal\" | \"vertical\" =\n    orientation === \"auto\"\n      ? width === null ||\n        width >= count * minStageWidth + (count - 1) * GAP + PAD * 2\n        ? \"horizontal\"\n        : \"vertical\"\n      : orientation;\n\n  // Flat lookup tables, rebuilt only when the run changes.\n  const { jobs, jobStatus, stageStatus, position } = React.useMemo(() => {\n    const jobs: {\n      job: PipelineJob;\n      stage: PipelineStage;\n      stageIndex: number;\n      row: number;\n    }[] = [];\n    const jobStatus = new Map<string, PipelineStatus>();\n    const stageStatus = new Map<string, PipelineStatus>();\n    const position = new Map<string, number>();\n    stages.forEach((stage, stageIndex) => {\n      stage.jobs.forEach((job, row) => {\n        position.set(job.id, jobs.length);\n        jobs.push({ job, stage, stageIndex, row });\n        jobStatus.set(job.id, job.status);\n      });\n      stageStatus.set(\n        stage.id,\n        summarizePipelineStatus(stage.jobs.map((job) => job.status)),\n      );\n    });\n    return { jobs, jobStatus, stageStatus, position };\n  }, [stages]);\n\n  const running = jobs.some(\n    ({ job }) => job.status === \"running\" && job.duration === undefined,\n  );\n  const now = useNow(running);\n  const runStatus =\n    statusProp ?? summarizePipelineStatus(jobs.map(({ job }) => job.status));\n  const finished = jobs.filter(({ job }) => FINISHED.has(job.status)).length;\n\n  const stageTimes = stages.map((stage) => {\n    let longest: number | undefined;\n    for (const job of stage.jobs) {\n      const time = elapsed(job, now);\n      if (time !== undefined) longest = Math.max(longest ?? 0, time);\n    }\n    return longest;\n  });\n  const total =\n    durationProp ??\n    (stageTimes.some((time) => time !== undefined)\n      ? stageTimes.reduce<number>((sum, time) => sum + (time ?? 0), 0)\n      : undefined);\n\n  const selected = selectedId\n    ? jobs[position.get(selectedId) ?? -1]\n    : undefined;\n  const select = (id: string | null) => {\n    const next = id && position.has(id) ? id : null;\n    if (next === selectedId) return;\n    if (selectedProp === undefined) setSelectedState(next);\n    onSelectedJobChange?.(next, next ? jobs[position.get(next)!].job : null);\n  };\n\n  // The one job reachable with Tab; arrows move it.\n  const tabStop =\n    (focusId && position.has(focusId) && focusId) ||\n    (selected && selected.job.id) ||\n    jobs.find(({ job }) => job.status === \"running\" || job.status === \"failed\")\n      ?.job.id ||\n    jobs[0]?.job.id;\n\n  const stagesRef = React.useRef(stages);\n  stagesRef.current = stages;\n  const structure = stages\n    .map((stage) => `${stage.id}:${stage.jobs.map((job) => job.id).join(\",\")}`)\n    .join(\"|\");\n\n  // Measure node edges and draw connectors between neighboring stages.\n  useIsoLayoutEffect(() => {\n    const graph = graphRef.current;\n    if (layout !== \"horizontal\" || !graph) {\n      setGeometry((current) =>\n        current.edges.length ? { edges: [], ports: [] } : current,\n      );\n      return;\n    }\n    const measure = () => {\n      const stages = stagesRef.current;\n      const edges: EdgeGeometry[] = [];\n      const ports = new Map<\n        string,\n        { key: string; x: number; y: number; job: string }\n      >();\n      const point = (job: PipelineJob, side: \"left\" | \"right\") => {\n        const node = nodeRefs.current.get(job.id);\n        if (!node) return null;\n        // Layout offsets, not client rects, so a scaled preview still lines up.\n        let left = 0;\n        let top = 0;\n        for (\n          let element: HTMLElement | null = node;\n          element && element !== graph;\n          element = element.offsetParent as HTMLElement | null\n        ) {\n          left += element.offsetLeft;\n          top += element.offsetTop;\n        }\n        const x = side === \"left\" ? left : left + node.offsetWidth;\n        const y = top + node.offsetHeight / 2;\n        ports.set(`${job.id}:${side}`, {\n          key: `${job.id}:${side}`,\n          x,\n          y,\n          job: job.id,\n        });\n        return { x, y, id: job.id };\n      };\n      for (let index = 0; index < stages.length - 1; index++) {\n        const from = stages[index];\n        const to = stages[index + 1];\n        const sources = from.jobs\n          .map((job) => point(job, \"right\"))\n          .filter((value) => value !== null);\n        const targets = to.jobs\n          .map((job) => point(job, \"left\"))\n          .filter((value) => value !== null);\n        if (!sources.length || !targets.length) continue;\n        if (sources.length > 1 && targets.length > 1) {\n          // Many-to-many: merge through one junction instead of drawing every pair.\n          const x =\n            (Math.max(...sources.map((s) => s.x)) +\n              Math.min(...targets.map((t) => t.x))) /\n            2;\n          const y = (sources[0].y + targets[0].y) / 2;\n          for (const s of sources)\n            edges.push({\n              key: `${s.id}>${to.id}`,\n              d: curve(s.x, s.y, x, y),\n              from: { job: s.id },\n              to: { stage: to.id },\n            });\n          for (const t of targets)\n            edges.push({\n              key: `${from.id}>${t.id}`,\n              d: curve(x, y, t.x, t.y),\n              from: { stage: from.id },\n              to: { job: t.id },\n            });\n        } else {\n          for (const s of sources)\n            for (const t of targets)\n              edges.push({\n                key: `${s.id}>${t.id}`,\n                d: curve(s.x, s.y, t.x, t.y),\n                from: { job: s.id },\n                to: { job: t.id },\n              });\n        }\n      }\n      setGeometry({ edges, ports: [...ports.values()] });\n    };\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(graph);\n    return () => observer.disconnect();\n  }, [layout, structure]);\n\n  const endStatus = (end: EdgeEnd) =>\n    (\"job\" in end ? jobStatus.get(end.job) : stageStatus.get(end.stage)) ??\n    \"queued\";\n\n  const moveFocus = (id: string | undefined) => {\n    if (!id) return;\n    setFocusId(id);\n    jobRefs.current.get(id)?.focus();\n  };\n\n  const handleJobKey = (event: React.KeyboardEvent, index: number) => {\n    const current = jobs[index];\n    const stageJobs = (stageIndex: number) => stages[stageIndex]?.jobs ?? [];\n    const toStage = (delta: number) => {\n      let stageIndex = current.stageIndex + delta;\n      while (\n        stageIndex >= 0 &&\n        stageIndex < stages.length &&\n        stageJobs(stageIndex).length === 0\n      )\n        stageIndex += delta;\n      const list = stageJobs(stageIndex);\n      rowMemory.current ??= current.row;\n      return list[Math.min(rowMemory.current, list.length - 1)]?.id;\n    };\n    const within = (delta: number) =>\n      stageJobs(current.stageIndex)[current.row + delta]?.id;\n    const flat = (delta: number) => jobs[index + delta]?.job.id;\n    const horizontal = layout === \"horizontal\";\n    let target: string | undefined;\n    if (event.key !== \"ArrowLeft\" && event.key !== \"ArrowRight\")\n      rowMemory.current = null;\n    switch (event.key) {\n      case \"ArrowRight\":\n        target = toStage(1);\n        break;\n      case \"ArrowLeft\":\n        target = toStage(-1);\n        break;\n      case \"ArrowDown\":\n        target = horizontal ? within(1) : flat(1);\n        break;\n      case \"ArrowUp\":\n        target = horizontal ? within(-1) : flat(-1);\n        break;\n      case \"Home\":\n        target = jobs[0]?.job.id;\n        break;\n      case \"End\":\n        target = jobs[jobs.length - 1]?.job.id;\n        break;\n      case \"Enter\":\n        event.preventDefault();\n        select(current.job.id);\n        return;\n      default:\n        return;\n    }\n    event.preventDefault();\n    moveFocus(target);\n  };\n\n  const colorVars = colors\n    ? (Object.fromEntries(\n        Object.entries(colors).map(([key, value]) => [\n          `--pipeline-${key}`,\n          value,\n        ]),\n      ) as React.CSSProperties)\n    : undefined;\n\n  const showDetail = (job: PipelineJob) =>\n    Boolean(renderJobDetail || job.detail);\n  const detailContent = (job: PipelineJob, stage: PipelineStage) =>\n    renderJobDetail ? (\n      renderJobDetail(job, stage)\n    ) : (\n      <div className=\"font-mono text-xs leading-5 break-words whitespace-pre-wrap text-muted-foreground\">\n        {job.detail}\n      </div>\n    );\n\n  const jobTime = (job: PipelineJob) => {\n    const time = elapsed(job, now);\n    if (\n      job.status === \"queued\" ||\n      job.status === \"skipped\" ||\n      job.status === \"canceled\"\n    )\n      return time !== undefined && job.status === \"canceled\"\n        ? durationFormatter(time)\n        : statusLabels[job.status];\n    return time !== undefined\n      ? durationFormatter(time)\n      : statusLabels[job.status];\n  };\n\n  const jobButton = (entry: (typeof jobs)[number], index: number) => {\n    const { job, stage } = entry;\n    const isSelected = selectedId === job.id;\n    const time = elapsed(job, now);\n    return (\n      <button\n        type=\"button\"\n        ref={(node) => {\n          if (node) jobRefs.current.set(job.id, node);\n          else jobRefs.current.delete(job.id);\n        }}\n        data-slot=\"pipeline-job-trigger\"\n        tabIndex={tabStop === job.id ? 0 : -1}\n        aria-pressed={isSelected}\n        aria-label={`${stage.label}: ${job.label}, ${statusLabels[job.status]}${time !== undefined ? `, ${durationFormatter(time)}` : \"\"}`}\n        title={job.detail}\n        onFocus={() => setFocusId(job.id)}\n        onClick={() => {\n          rowMemory.current = null;\n          select(isSelected ? null : job.id);\n        }}\n        onKeyDown={(event) => handleJobKey(event, index)}\n        className={cn(\"absolute inset-0 rounded-[inherit]\", focusRing)}\n      />\n    );\n  };\n\n  const retryButton = (\n    job: PipelineJob,\n    stage: PipelineStage,\n    className?: string,\n  ) =>\n    onRetry && job.status === \"failed\" ? (\n      <button\n        type=\"button\"\n        data-slot=\"pipeline-retry\"\n        title={`${labels.retry} ${job.label}`}\n        aria-label={`${labels.retry} ${job.label}`}\n        onClick={(event) => {\n          event.stopPropagation();\n          onRetry(job, stage);\n        }}\n        className={cn(\n          \"pointer-events-auto relative inline-flex shrink-0 items-center justify-center gap-1 rounded-md text-xs font-medium text-muted-foreground transition-colors hover:bg-(--pipeline-failed)/10 hover:text-(--pipeline-failed) motion-reduce:transition-none\",\n          focusRing,\n          className,\n        )}\n      >\n        <Refresh className=\"size-3.5\" aria-hidden=\"true\" />\n      </button>\n    ) : null;\n\n  const stageMeta = (stage: PipelineStage, index: number) => {\n    const time = stageTimes[index];\n    const status = stageStatus.get(stage.id) ?? \"queued\";\n    if (time === undefined) return null;\n    return (\n      <span\n        className={cn(\n          \"shrink-0 font-mono text-[11px] tabular-nums\",\n          status === \"running\" ? \"text-(--tone)\" : \"text-muted-foreground\",\n        )}\n        style={tone(status)}\n      >\n        {durationFormatter(time)}\n      </span>\n    );\n  };\n\n  const detailPanel =\n    selected && showDetail(selected.job) ? (\n      <div\n        key={selected.job.id}\n        data-slot=\"pipeline-detail\"\n        className=\"transition-[opacity,translate] duration-200 ease-out starting:-translate-y-1 starting:opacity-0 motion-reduce:transition-none\"\n      >\n        {layout === \"horizontal\" && (\n          <div\n            className=\"flex items-center gap-2 px-4 pt-3\"\n            style={tone(selected.job.status)}\n          >\n            <PipelineStatusIcon\n              status={selected.job.status}\n              className=\"size-3.5\"\n            />\n            <div className=\"min-w-0 truncate text-[13px] font-medium\">\n              <span className=\"text-muted-foreground\">\n                {selected.stage.label} /{\" \"}\n              </span>\n              {selected.job.label}\n            </div>\n            <span className=\"font-mono text-[11px] text-muted-foreground tabular-nums\">\n              {jobTime(selected.job)}\n            </span>\n            <span className=\"ml-auto flex items-center gap-1\">\n              {retryButton(selected.job, selected.stage, \"h-6 px-1.5\")}\n              <button\n                type=\"button\"\n                aria-label={labels.close}\n                title={labels.close}\n                onClick={() => {\n                  select(null);\n                  moveFocus(selected.job.id);\n                }}\n                className={cn(\n                  \"inline-flex size-6 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground motion-reduce:transition-none\",\n                  focusRing,\n                )}\n              >\n                <X className=\"size-3.5\" aria-hidden=\"true\" />\n              </button>\n            </span>\n          </div>\n        )}\n        <div\n          className={layout === \"horizontal\" ? \"px-4 pt-2 pb-4\" : \"px-3 py-2.5\"}\n        >\n          {detailContent(selected.job, selected.stage)}\n        </div>\n      </div>\n    ) : null;\n\n  return (\n    <div\n      ref={setRoot}\n      data-slot=\"deploy-pipeline\"\n      data-status={runStatus}\n      data-orientation={layout}\n      className={cn(\n        \"@container/pipeline flex min-w-0 flex-col overflow-hidden rounded-xl border bg-card text-card-foreground shadow-xs\",\n        \"[--pipeline-canceled:var(--color-muted-foreground)] [--pipeline-failed:var(--color-destructive)] [--pipeline-queued:var(--color-muted-foreground)] [--pipeline-running:var(--color-primary)] [--pipeline-skipped:var(--color-muted-foreground)] [--pipeline-success:var(--color-emerald-500)]\",\n        className,\n      )}\n      style={{ ...colorVars, ...style }}\n      onKeyDown={(event) => {\n        onKeyDown?.(event);\n        if (event.key === \"Escape\" && selectedId && !event.defaultPrevented) {\n          event.stopPropagation();\n          select(null);\n        }\n      }}\n      {...props}\n    >\n      <style href=\"overtrue-deploy-pipeline\" precedence=\"default\">\n        {styles}\n      </style>\n\n      <div className=\"flex items-start gap-3 px-4 pt-3.5 pb-3\">\n        <div className=\"min-w-0 flex-1\">\n          <div className=\"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1\">\n            <div className=\"min-w-0 text-sm leading-6 font-semibold tracking-tight break-words\">\n              {title}\n            </div>\n            <span\n              role=\"status\"\n              data-slot=\"pipeline-status\"\n              style={tone(runStatus)}\n              className=\"inline-flex shrink-0 items-center gap-1.5 rounded-full border border-(--tone)/25 bg-(--tone)/8 px-2 py-px text-[11px] leading-4 font-medium text-[color-mix(in_oklab,var(--tone)_78%,var(--color-foreground))]\"\n            >\n              <span className=\"relative flex size-1.5\" aria-hidden=\"true\">\n                {runStatus === \"running\" && (\n                  <span className=\"absolute inline-flex size-full animate-ping rounded-full bg-(--tone) opacity-70 motion-reduce:hidden\" />\n                )}\n                <span className=\"relative inline-flex size-1.5 rounded-full bg-(--tone)\" />\n              </span>\n              {statusLabels[runStatus]}\n            </span>\n          </div>\n          {meta && (\n            <div className=\"mt-0.5 flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground\">\n              {meta}\n            </div>\n          )}\n        </div>\n        <div className=\"flex shrink-0 items-center gap-1.5\">\n          <span\n            data-slot=\"pipeline-duration\"\n            title={labels.total}\n            className=\"inline-flex h-7 items-center gap-1.5 font-mono text-xs text-foreground tabular-nums\"\n          >\n            <Clock\n              className=\"size-3.5 text-muted-foreground\"\n              aria-hidden=\"true\"\n            />\n            <span className=\"sr-only\">{labels.total}: </span>\n            {total !== undefined ? durationFormatter(total) : \"—\"}\n          </span>\n          {actions}\n        </div>\n      </div>\n\n      {showProgress && jobs.length > 0 && (\n        <div className=\"flex items-center gap-3 px-4 pb-3.5\">\n          <div\n            data-slot=\"pipeline-progress\"\n            role=\"progressbar\"\n            aria-label={labels.progress}\n            aria-valuemin={0}\n            aria-valuemax={jobs.length}\n            aria-valuenow={finished}\n            className=\"flex min-w-0 flex-1 items-center gap-2.5\"\n          >\n            {stages.map((stage) =>\n              stage.jobs.length ? (\n                <span\n                  key={stage.id}\n                  className=\"flex min-w-0 basis-0 gap-0.5\"\n                  style={{ flexGrow: stage.jobs.length }}\n                >\n                  {stage.jobs.map((job) => (\n                    <span\n                      key={job.id}\n                      title={`${job.label} · ${statusLabels[job.status]}`}\n                      style={tone(job.status)}\n                      className={cn(\n                        \"relative h-1.5 min-w-1 flex-1 overflow-hidden rounded-full transition-colors duration-500 motion-reduce:transition-none\",\n                        job.status === \"queued\"\n                          ? \"bg-muted\"\n                          : job.status === \"skipped\" ||\n                              job.status === \"canceled\"\n                            ? \"bg-(--tone)/25\"\n                            : job.status === \"running\"\n                              ? \"bg-(--tone)/25\"\n                              : \"bg-(--tone)\",\n                      )}\n                    >\n                      {job.status === \"running\" && (\n                        <Shimmer className=\"inset-0\" />\n                      )}\n                    </span>\n                  ))}\n                </span>\n              ) : null,\n            )}\n          </div>\n          <span className=\"shrink-0 font-mono text-[11px] text-muted-foreground tabular-nums\">\n            {finished}/{jobs.length}\n          </span>\n        </div>\n      )}\n\n      <div className=\"border-t bg-muted/20\" style={{ padding: PAD }}>\n        <div\n          ref={graphRef}\n          role=\"group\"\n          aria-label={labels.stages}\n          data-slot=\"pipeline-graph\"\n          className=\"relative\"\n        >\n          {layout === \"horizontal\" ? (\n            <>\n              <svg\n                aria-hidden=\"true\"\n                className=\"pointer-events-none absolute inset-0 size-full overflow-visible\"\n              >\n                {geometry.edges.map((edge) => {\n                  const state = edgeState(\n                    endStatus(edge.from),\n                    endStatus(edge.to),\n                  );\n                  return (\n                    <g\n                      key={edge.key}\n                      data-slot=\"pipeline-connector\"\n                      data-state={state}\n                    >\n                      <path\n                        d={edge.d}\n                        fill=\"none\"\n                        strokeWidth={1.5}\n                        strokeLinecap=\"round\"\n                        strokeDasharray={\n                          state === \"pending\" || state === \"blocked\"\n                            ? \"2 4\"\n                            : undefined\n                        }\n                        className={cn(\n                          \"transition-[stroke] duration-500 motion-reduce:transition-none\",\n                          state === \"active\"\n                            ? \"stroke-(--pipeline-running)/35 motion-reduce:stroke-(--pipeline-running)\"\n                            : state === \"done\"\n                              ? \"stroke-(--pipeline-success)/55\"\n                              : state === \"blocked\"\n                                ? \"stroke-muted-foreground/30\"\n                                : \"stroke-muted-foreground/45\",\n                        )}\n                      />\n                      {state === \"active\" && (\n                        <>\n                          <path\n                            d={edge.d}\n                            fill=\"none\"\n                            pathLength={100}\n                            strokeWidth={6}\n                            strokeLinecap=\"round\"\n                            strokeDasharray=\"16 84\"\n                            className=\"animate-[pipeline-flow_1.5s_linear_infinite] stroke-(--pipeline-running)/20 motion-reduce:hidden\"\n                          />\n                          <path\n                            d={edge.d}\n                            fill=\"none\"\n                            pathLength={100}\n                            strokeWidth={2}\n                            strokeLinecap=\"round\"\n                            strokeDasharray=\"16 84\"\n                            className=\"animate-[pipeline-flow_1.5s_linear_infinite] stroke-(--pipeline-running) motion-reduce:hidden\"\n                          />\n                        </>\n                      )}\n                    </g>\n                  );\n                })}\n                {geometry.ports.map((port) => {\n                  const status = jobStatus.get(port.job) ?? \"queued\";\n                  return (\n                    <circle\n                      key={port.key}\n                      cx={port.x}\n                      cy={port.y}\n                      r={2.5}\n                      strokeWidth={1.5}\n                      style={tone(status)}\n                      className={cn(\n                        \"fill-card transition-[stroke] duration-500 motion-reduce:transition-none\",\n                        status === \"queued\" ||\n                          status === \"skipped\" ||\n                          status === \"canceled\"\n                          ? \"stroke-muted-foreground/45\"\n                          : \"stroke-(--tone)\",\n                      )}\n                    />\n                  );\n                })}\n              </svg>\n              <div\n                className=\"relative grid\"\n                style={{\n                  gridTemplateColumns: `repeat(${Math.max(count, 1)}, minmax(0, 1fr))`,\n                  columnGap: GAP,\n                }}\n              >\n                {stages.map((stage, stageIndex) => (\n                  <div\n                    key={stage.id}\n                    role=\"group\"\n                    aria-label={stage.label}\n                    data-slot=\"pipeline-stage\"\n                    data-status={stageStatus.get(stage.id)}\n                    className=\"min-w-0\"\n                  >\n                    <div className=\"mb-2 flex h-5 items-center justify-between gap-2\">\n                      <div\n                        className=\"min-w-0 truncate text-xs font-medium text-muted-foreground\"\n                        title={stage.label}\n                      >\n                        {stage.label}\n                      </div>\n                      {stageMeta(stage, stageIndex)}\n                    </div>\n                    <div className=\"flex flex-col gap-2\">\n                      {stage.jobs.map((job) => {\n                        const index = position.get(job.id)!;\n                        const isSelected = selectedId === job.id;\n                        const muted =\n                          job.status === \"queued\" ||\n                          job.status === \"skipped\" ||\n                          job.status === \"canceled\";\n                        return (\n                          <div\n                            key={job.id}\n                            ref={(node) => {\n                              if (node) nodeRefs.current.set(job.id, node);\n                              else nodeRefs.current.delete(job.id);\n                            }}\n                            data-slot=\"pipeline-job\"\n                            data-status={job.status}\n                            data-selected={isSelected || undefined}\n                            style={tone(job.status)}\n                            className={cn(\n                              \"group/job relative h-11 rounded-lg border bg-card transition-[border-color,box-shadow,background-color] duration-200 motion-reduce:transition-none\",\n                              muted ? \"border-dashed shadow-none\" : \"shadow-xs\",\n                              job.status === \"running\" && \"border-(--tone)/40\",\n                              job.status === \"failed\" &&\n                                \"border-(--tone)/35 bg-[color-mix(in_oklab,var(--tone)_5%,var(--color-card))]\",\n                              isSelected\n                                ? \"border-primary ring-2 ring-primary/20\"\n                                : \"hover:border-foreground/20\",\n                            )}\n                          >\n                            {jobButton(jobs[index], index)}\n                            <div className=\"pointer-events-none relative flex h-full items-center gap-2 pr-1.5 pl-2.5\">\n                              <PipelineStatusIcon\n                                status={job.status}\n                                className=\"size-3.5\"\n                              />\n                              <div\n                                className=\"min-w-0 flex-1\"\n                                aria-hidden=\"true\"\n                              >\n                                <div\n                                  className={cn(\n                                    \"truncate text-[13px] leading-4 font-medium\",\n                                    muted && \"text-muted-foreground\",\n                                  )}\n                                >\n                                  {job.label}\n                                </div>\n                                <div\n                                  className={cn(\n                                    \"truncate font-mono text-[11px] leading-4 tabular-nums\",\n                                    job.status === \"running\"\n                                      ? \"text-[color-mix(in_oklab,var(--tone)_80%,var(--color-foreground))]\"\n                                      : job.status === \"failed\"\n                                        ? \"text-[color-mix(in_oklab,var(--tone)_80%,var(--color-foreground))]\"\n                                        : \"text-muted-foreground\",\n                                  )}\n                                >\n                                  {jobTime(job)}\n                                </div>\n                              </div>\n                              {retryButton(job, stage, \"size-6\")}\n                            </div>\n                            {job.status === \"running\" && (\n                              <>\n                                <Shimmer className=\"inset-x-2 bottom-0 h-px\" />\n                                <Shimmer className=\"inset-0 rounded-[inherit] opacity-[0.07]\" />\n                              </>\n                            )}\n                          </div>\n                        );\n                      })}\n                    </div>\n                  </div>\n                ))}\n              </div>\n            </>\n          ) : (\n            <ol className=\"relative\">\n              {stages.map((stage, stageIndex) => {\n                const status = stageStatus.get(stage.id) ?? \"queued\";\n                const next = stages[stageIndex + 1];\n                const rail = next\n                  ? edgeState(status, stageStatus.get(next.id) ?? \"queued\")\n                  : null;\n                return (\n                  <li\n                    key={stage.id}\n                    data-slot=\"pipeline-stage\"\n                    data-status={status}\n                    aria-label={stage.label}\n                    className=\"relative grid grid-cols-[16px_minmax(0,1fr)] gap-x-3 pb-3.5 last:pb-0\"\n                  >\n                    <div className=\"relative flex justify-center\">\n                      <span className=\"relative z-10 flex h-5 items-center bg-[color-mix(in_oklab,var(--color-muted)_20%,var(--color-card))]\">\n                        <PipelineStatusIcon status={status} />\n                      </span>\n                      {rail && (\n                        <span\n                          aria-hidden=\"true\"\n                          data-slot=\"pipeline-connector\"\n                          data-state={rail}\n                          className={cn(\n                            \"absolute top-6 -bottom-1 left-1/2 w-0 -translate-x-1/2\",\n                            rail === \"active\"\n                              ? \"w-[1.5px] bg-(--pipeline-running)/35 motion-safe:animate-[pipeline-rail_0.9s_linear_infinite] motion-safe:bg-[linear-gradient(to_bottom,transparent_0,var(--pipeline-running)_50%,transparent_100%)] motion-safe:bg-size-[100%_24px] motion-safe:bg-repeat-y\"\n                              : rail === \"done\"\n                                ? \"w-[1.5px] bg-(--pipeline-success)/55\"\n                                : \"border-l-[1.5px] border-dashed border-muted-foreground/35\",\n                          )}\n                        />\n                      )}\n                    </div>\n                    <div className=\"min-w-0\">\n                      <div className=\"flex h-5 items-center justify-between gap-2\">\n                        <div className=\"min-w-0 truncate text-[13px] font-semibold tracking-tight\">\n                          {stage.label}\n                        </div>\n                        {stageMeta(stage, stageIndex)}\n                      </div>\n                      <div className=\"mt-1.5 divide-y overflow-hidden rounded-lg border bg-card shadow-xs\">\n                        {stage.jobs.map((job) => {\n                          const index = position.get(job.id)!;\n                          const isSelected = selectedId === job.id;\n                          const muted =\n                            job.status === \"queued\" ||\n                            job.status === \"skipped\" ||\n                            job.status === \"canceled\";\n                          return (\n                            <div key={job.id} data-slot=\"pipeline-job-group\">\n                              <div\n                                ref={(node) => {\n                                  if (node) nodeRefs.current.set(job.id, node);\n                                  else nodeRefs.current.delete(job.id);\n                                }}\n                                data-slot=\"pipeline-job\"\n                                data-status={job.status}\n                                data-selected={isSelected || undefined}\n                                style={tone(job.status)}\n                                className={cn(\n                                  \"relative h-9 transition-colors duration-200 motion-reduce:transition-none\",\n                                  isSelected\n                                    ? \"bg-muted/70\"\n                                    : \"hover:bg-muted/40\",\n                                  job.status === \"failed\" &&\n                                    !isSelected &&\n                                    \"bg-[color-mix(in_oklab,var(--tone)_5%,var(--color-card))]\",\n                                )}\n                              >\n                                {jobButton(jobs[index], index)}\n                                {isSelected && (\n                                  <span\n                                    aria-hidden=\"true\"\n                                    className=\"absolute inset-y-0 left-0 w-0.5 bg-primary\"\n                                  />\n                                )}\n                                <div className=\"pointer-events-none relative flex h-full items-center gap-2.5 pr-2 pl-3\">\n                                  <PipelineStatusIcon\n                                    status={job.status}\n                                    className=\"size-3.5\"\n                                  />\n                                  <div\n                                    aria-hidden=\"true\"\n                                    className={cn(\n                                      \"min-w-0 truncate text-[13px] font-medium\",\n                                      muted && \"text-muted-foreground\",\n                                    )}\n                                  >\n                                    {job.label}\n                                  </div>\n                                  <div\n                                    aria-hidden=\"true\"\n                                    className=\"hidden min-w-0 flex-1 truncate text-xs text-muted-foreground @sm/pipeline:block\"\n                                  >\n                                    {job.detail}\n                                  </div>\n                                  <span className=\"flex-1 @sm/pipeline:hidden\" />\n                                  <span\n                                    aria-hidden=\"true\"\n                                    className={cn(\n                                      \"shrink-0 font-mono text-[11px] tabular-nums\",\n                                      job.status === \"running\" ||\n                                        job.status === \"failed\"\n                                        ? \"text-[color-mix(in_oklab,var(--tone)_80%,var(--color-foreground))]\"\n                                        : \"text-muted-foreground\",\n                                    )}\n                                  >\n                                    {jobTime(job)}\n                                  </span>\n                                  {retryButton(job, stage, \"size-6\")}\n                                </div>\n                                {job.status === \"running\" && (\n                                  <>\n                                    <Shimmer className=\"inset-x-0 bottom-0 h-px\" />\n                                    <Shimmer className=\"inset-0 opacity-[0.07]\" />\n                                  </>\n                                )}\n                              </div>\n                              {isSelected && detailPanel && (\n                                <div className=\"border-t bg-muted/30\">\n                                  {detailPanel}\n                                </div>\n                              )}\n                            </div>\n                          );\n                        })}\n                      </div>\n                    </div>\n                  </li>\n                );\n              })}\n            </ol>\n          )}\n        </div>\n      </div>\n\n      {layout === \"horizontal\" && detailPanel && (\n        <div className=\"border-t\">{detailPanel}</div>\n      )}\n    </div>\n  );\n}\n"
    },
    {
      "path": "src/registry/overtrue/log-stream.tsx",
      "type": "registry:component",
      "target": "components/overtrue/log-stream.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport {\n  IconArrowDown as ArrowDown,\n  IconPlayerPause as Pause,\n  IconPlayerPlay as Play,\n  IconSearch as Search,\n  IconTextWrap as TextWrap,\n  IconTrash as Trash,\n  IconX as X,\n} from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport interface LogEntry {\n  id: string;\n  time: Date | number | string;\n  level: LogLevel;\n  /** Service, job or component that emitted the line. */\n  source?: string;\n  message: string;\n}\n\nexport interface LogStreamProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"children\" | \"title\"\n> {\n  /** Events, oldest first. Append new entries to the end. */\n  entries: LogEntry[];\n  title?: React.ReactNode;\n  description?: React.ReactNode;\n  /** Height of the scrolling log in pixels. */\n  height?: number;\n  /** Render at most this many of the newest matching rows. */\n  maxEntries?: number;\n  /** Follow the tail. Pass with `onFollowChange` to control it. */\n  follow?: boolean;\n  defaultFollow?: boolean;\n  onFollowChange?: (follow: boolean) => void;\n  /** Called by the clear action. Without it, clearing hides the current entries locally. */\n  onClear?: () => void;\n  /** A live source shows a Live/Paused badge, a follow control, and a cursor. Set false for archived logs. */\n  live?: boolean;\n  /** Levels shown initially. */\n  defaultLevels?: LogLevel[];\n  /** Initial text filter, matched against messages and sources. */\n  defaultQuery?: string;\n  /** Wrap long messages instead of truncating them. Rows can still be expanded one at a time. */\n  defaultWrap?: boolean;\n  /** Format timestamps in local time or UTC. */\n  timeZone?: \"local\" | \"utc\";\n}\n\nconst LEVELS: LogLevel[] = [\"debug\", \"info\", \"warn\", \"error\"];\n\nconst levelStyle: Record<LogLevel, { label: string; pill: string; dot: string }> = {\n  debug: {\n    label: \"Debug\",\n    pill: \"bg-muted text-muted-foreground\",\n    dot: \"bg-muted-foreground/50\",\n  },\n  info: {\n    label: \"Info\",\n    pill: \"bg-sky-500/10 text-sky-700 dark:text-sky-300\",\n    dot: \"bg-sky-500\",\n  },\n  warn: {\n    label: \"Warn\",\n    pill: \"bg-amber-500/12 text-amber-700 dark:text-amber-400\",\n    dot: \"bg-amber-500\",\n  },\n  error: {\n    label: \"Error\",\n    pill: \"bg-destructive/12 text-rose-700 dark:text-rose-400\",\n    dot: \"bg-destructive\",\n  },\n};\n\nconst focusRing =\n  \"outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-1 focus-visible:ring-offset-card\";\n\nfunction lastIndexOfId(entries: LogEntry[], id: string) {\n  for (let i = entries.length - 1; i >= 0; i--) if (entries[i].id === id) return i;\n  return -1;\n}\n\nconst pad = (value: number, size = 2) => String(value).padStart(size, \"0\");\n\nfunction formatTime(time: LogEntry[\"time\"], zone: \"local\" | \"utc\") {\n  const date = time instanceof Date ? time : new Date(time);\n  if (Number.isNaN(date.getTime())) return [\"--:--:--\", \".---\", undefined] as const;\n  const utc = zone === \"utc\";\n  const hms = `${pad(utc ? date.getUTCHours() : date.getHours())}:${pad(utc ? date.getUTCMinutes() : date.getMinutes())}:${pad(utc ? date.getUTCSeconds() : date.getSeconds())}`;\n  return [hms, `.${pad(utc ? date.getUTCMilliseconds() : date.getMilliseconds(), 3)}`, date.toISOString()] as const;\n}\n\nfunction highlight(text: string, query: string) {\n  if (!query) return text;\n  const lower = text.toLowerCase();\n  const parts: React.ReactNode[] = [];\n  let from = 0;\n  let at = lower.indexOf(query, from);\n  while (at !== -1) {\n    if (at > from) parts.push(text.slice(from, at));\n    parts.push(\n      <mark key={at} className=\"rounded-[2px] bg-amber-300/50 text-inherit dark:bg-amber-400/30\">\n        {text.slice(at, at + query.length)}\n      </mark>,\n    );\n    from = at + query.length;\n    at = lower.indexOf(query, from);\n  }\n  if (from < text.length) parts.push(text.slice(from));\n  return parts;\n}\n\ninterface RowProps {\n  entry: LogEntry;\n  query: string;\n  wrap: boolean;\n  expanded: boolean;\n  enter: boolean;\n  zone: \"local\" | \"utc\";\n  onToggle: (id: string) => void;\n}\n\nconst LogRow = React.memo(function LogRow({\n  entry,\n  query,\n  wrap,\n  expanded,\n  enter,\n  zone,\n  onToggle,\n}: RowProps) {\n  const [hms, ms, iso] = formatTime(entry.time, zone);\n  const open = wrap || expanded;\n  const level = levelStyle[entry.level] ?? levelStyle.info;\n  return (\n    <div\n      data-level={entry.level}\n      data-expanded={expanded || undefined}\n      onClick={wrap ? undefined : () => onToggle(entry.id)}\n      className={cn(\n        \"relative flex items-start gap-3 px-4 py-[5px] leading-[18px]\",\n        entry.level === \"error\"\n          ? \"bg-destructive/[0.06] hover:bg-destructive/10 dark:bg-destructive/10 dark:hover:bg-destructive/15\"\n          : \"hover:bg-muted/60\",\n        enter &&\n          \"transition-[opacity,translate] duration-300 ease-out starting:translate-y-1 starting:opacity-0 motion-reduce:transition-none\",\n      )}\n    >\n      {entry.level === \"error\" && (\n        <span aria-hidden=\"true\" className=\"absolute inset-y-0 left-0 w-0.5 bg-destructive\" />\n      )}\n      <time\n        dateTime={iso}\n        className=\"w-[84px] shrink-0 text-muted-foreground tabular-nums\"\n      >\n        {hms}\n        <span className=\"opacity-55\">{ms}</span>\n      </time>\n      <span\n        className={cn(\n          \"mt-px inline-flex h-4 w-12 shrink-0 items-center justify-center rounded-[4px] text-[10.5px] leading-none font-semibold tracking-wide uppercase\",\n          level.pill,\n        )}\n      >\n        {entry.level}\n      </span>\n      {entry.source !== undefined && (\n        <span className=\"hidden w-16 shrink-0 truncate text-muted-foreground @md/log:block\" title={entry.source}>\n          {entry.source}\n        </span>\n      )}\n      <span\n        className={cn(\n          \"min-w-0 flex-1 text-foreground\",\n          open ? \"break-words whitespace-pre-wrap\" : \"truncate\",\n          entry.level === \"debug\" && \"text-muted-foreground\",\n        )}\n        title={open ? undefined : entry.message}\n      >\n        {entry.source !== undefined && (\n          <span className=\"text-muted-foreground @md/log:hidden\">{entry.source} · </span>\n        )}\n        {highlight(entry.message, query)}\n      </span>\n    </div>\n  );\n});\n\n/** A live, terminal-style event stream that follows the tail until someone scrolls up to read. */\nexport function LogStream({\n  entries,\n  title = \"Events\",\n  description,\n  height = 320,\n  maxEntries = 500,\n  follow: followProp,\n  defaultFollow = true,\n  onFollowChange,\n  onClear,\n  live = true,\n  defaultLevels = LEVELS,\n  defaultQuery = \"\",\n  defaultWrap = false,\n  timeZone = \"local\",\n  className,\n  onKeyDown,\n  ...props\n}: LogStreamProps) {\n  const id = React.useId();\n  const scrollRef = React.useRef<HTMLDivElement>(null);\n  const searchRef = React.useRef<HTMLInputElement>(null);\n  const pausedBy = React.useRef<\"scroll\" | \"user\" | null>(null);\n\n  const [followState, setFollowState] = React.useState(defaultFollow);\n  const following = followProp ?? followState;\n  const [frozen, setFrozen] = React.useState<LogEntry[] | null>(null);\n  const [levels, setLevels] = React.useState<ReadonlySet<LogLevel>>(() => new Set(defaultLevels));\n  const [search, setSearch] = React.useState(defaultQuery);\n  const [wrap, setWrap] = React.useState(defaultWrap);\n  const [expanded, setExpanded] = React.useState<ReadonlySet<string>>(() => new Set());\n  const [clearedAfter, setClearedAfter] = React.useState<string | null>(null);\n  const [mounted, setMounted] = React.useState(false);\n  React.useEffect(() => setMounted(true), []);\n\n  const setFollowing = React.useCallback(\n    (next: boolean, reason: \"scroll\" | \"user\" = \"user\") => {\n      pausedBy.current = next ? null : reason;\n      // Freeze what is on screen so reading is never interrupted by the stream.\n      setFrozen(next ? null : entries);\n      if (followProp === undefined) setFollowState(next);\n      onFollowChange?.(next);\n    },\n    [entries, followProp, onFollowChange],\n  );\n\n  // Keep a controlled `follow={false}` frozen too.\n  React.useLayoutEffect(() => {\n    if (!following && !frozen) setFrozen(entries);\n    if (following && frozen) setFrozen(null);\n  }, [following, frozen, entries]);\n\n  const visibleSource = React.useMemo(() => {\n    const source = frozen ?? entries;\n    if (clearedAfter === null) return source;\n    const index = lastIndexOfId(source, clearedAfter);\n    return index === -1 ? source : source.slice(index + 1);\n  }, [frozen, entries, clearedAfter]);\n\n  const query = search.trim().toLowerCase();\n  const { rows, counts, matching } = React.useMemo(() => {\n    const counts: Record<LogLevel, number> = { debug: 0, info: 0, warn: 0, error: 0 };\n    const rows: LogEntry[] = [];\n    for (const entry of visibleSource) {\n      if (\n        query &&\n        !entry.message.toLowerCase().includes(query) &&\n        !entry.source?.toLowerCase().includes(query)\n      )\n        continue;\n      counts[entry.level] = (counts[entry.level] ?? 0) + 1;\n      if (levels.has(entry.level)) rows.push(entry);\n    }\n    const matching = rows.length;\n    return { rows: rows.length > maxEntries ? rows.slice(-maxEntries) : rows, counts, matching };\n  }, [visibleSource, query, levels, maxEntries]);\n\n  const pending = React.useMemo(() => {\n    if (following || !frozen) return 0;\n    const last = frozen[frozen.length - 1];\n    const index = last ? lastIndexOfId(entries, last.id) : -1;\n    let count = 0;\n    for (let i = index + 1; i < entries.length; i++) if (levels.has(entries[i].level)) count++;\n    return count;\n  }, [following, frozen, entries, levels]);\n\n  // Stay pinned to the newest row while following.\n  React.useLayoutEffect(() => {\n    const element = scrollRef.current;\n    if (following && element) element.scrollTop = element.scrollHeight;\n  }, [following, rows]);\n\n  const handleScroll = () => {\n    const element = scrollRef.current;\n    if (!element) return;\n    const distance = element.scrollHeight - element.scrollTop - element.clientHeight;\n    if (following && distance > 24) setFollowing(false, \"scroll\");\n    else if (!following && pausedBy.current === \"scroll\" && distance < 2) setFollowing(true);\n  };\n\n  const toggleRow = React.useCallback((rowId: string) => {\n    if (window.getSelection()?.toString()) return;\n    setExpanded((current) => {\n      const next = new Set(current);\n      if (!next.delete(rowId)) next.add(rowId);\n      return next;\n    });\n  }, []);\n\n  const toggleLevel = (level: LogLevel) =>\n    setLevels((current) => {\n      const next = new Set(current);\n      if (!next.delete(level)) next.add(level);\n      return next;\n    });\n\n  const clear = () => {\n    setExpanded(new Set());\n    if (onClear) onClear();\n    else setClearedAfter(entries[entries.length - 1]?.id ?? null);\n    if (!following) setFollowing(true);\n  };\n\n  const resetFilters = () => {\n    setSearch(\"\");\n    setLevels(new Set(LEVELS));\n  };\n\n  const total = visibleSource.length;\n  const filtered = query !== \"\" || levels.size < LEVELS.length;\n\n  return (\n    <div\n      data-slot=\"log-stream\"\n      data-following={following || undefined}\n      className={cn(\n        \"@container/log flex min-w-0 flex-col overflow-hidden rounded-xl border bg-card text-card-foreground shadow-xs\",\n        className,\n      )}\n      onKeyDown={(event) => {\n        onKeyDown?.(event);\n        const target = event.target as HTMLElement;\n        if (\n          event.key === \"/\" &&\n          !event.defaultPrevented &&\n          !(target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement)\n        ) {\n          event.preventDefault();\n          searchRef.current?.focus();\n        }\n      }}\n      {...props}\n    >\n      <div className=\"flex items-start gap-3 px-4 pt-3.5 pb-3\">\n        <div className=\"min-w-0 flex-1\">\n          <div className=\"flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1\">\n            <p id={`${id}-title`} className=\"min-w-0 text-sm leading-6 font-semibold tracking-tight break-words\">\n              {title}\n            </p>\n            {live && (\n              <span\n                className={cn(\n                  \"inline-flex shrink-0 items-center gap-1.5 rounded-full border px-2 py-px text-[11px] leading-4 font-medium\",\n                  following ? \"text-emerald-700 dark:text-emerald-400\" : \"text-amber-700 dark:text-amber-400\",\n                )}\n              >\n                <span className=\"relative flex size-1.5\" aria-hidden=\"true\">\n                  {following && (\n                    <span className=\"absolute inline-flex size-full animate-ping rounded-full bg-emerald-500 opacity-70 motion-reduce:hidden\" />\n                  )}\n                  <span\n                    className={cn(\n                      \"relative inline-flex size-1.5 rounded-full\",\n                      following ? \"bg-emerald-500\" : \"bg-amber-500\",\n                    )}\n                  />\n                </span>\n                {following ? \"Live\" : \"Paused\"}\n              </span>\n            )}\n          </div>\n          {description && <p className=\"truncate text-xs text-muted-foreground\">{description}</p>}\n        </div>\n        <div className=\"flex shrink-0 items-center gap-1\">\n          <button\n            type=\"button\"\n            aria-pressed={wrap}\n            title=\"Wrap long lines\"\n            onClick={() => setWrap((value) => !value)}\n            className={cn(\n              \"inline-flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground aria-pressed:bg-muted aria-pressed:text-foreground motion-reduce:transition-none\",\n              focusRing,\n            )}\n          >\n            <TextWrap className=\"size-4\" aria-hidden=\"true\" />\n            <span className=\"sr-only\">Wrap long lines</span>\n          </button>\n          <button\n            type=\"button\"\n            title=\"Clear\"\n            onClick={clear}\n            className={cn(\n              \"inline-flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground motion-reduce:transition-none\",\n              focusRing,\n            )}\n          >\n            <Trash className=\"size-4\" aria-hidden=\"true\" />\n            <span className=\"sr-only\">Clear events</span>\n          </button>\n          {live && (\n            <button\n              type=\"button\"\n              title={following ? \"Pause the tail\" : \"Resume following\"}\n              aria-label={following ? \"Pause following\" : \"Resume following\"}\n              onClick={() => setFollowing(!following)}\n              className={cn(\n                \"ml-1 inline-flex h-7 items-center gap-1.5 rounded-md border bg-card px-2 text-xs font-medium shadow-xs transition-colors hover:bg-muted motion-reduce:transition-none @md/log:px-2.5\",\n                focusRing,\n              )}\n            >\n              {following ? (\n                <Pause className=\"size-3.5\" aria-hidden=\"true\" />\n              ) : (\n                <Play className=\"size-3.5\" aria-hidden=\"true\" />\n              )}\n              <span className=\"sr-only @md/log:not-sr-only\">{following ? \"Pause\" : \"Resume\"}</span>\n            </button>\n          )}\n        </div>\n      </div>\n\n      <div className=\"flex flex-wrap items-center gap-2 border-y bg-muted/30 px-4 py-2\">\n        <div role=\"group\" aria-label=\"Levels\" className=\"flex flex-wrap items-center gap-1\">\n          {LEVELS.map((level) => {\n            const active = levels.has(level);\n            return (\n              <button\n                key={level}\n                type=\"button\"\n                aria-pressed={active}\n                onClick={() => toggleLevel(level)}\n                className={cn(\n                  \"inline-flex h-6 items-center gap-1 rounded-md border px-1.5 text-xs transition-colors motion-reduce:transition-none @md/log:gap-1.5 @md/log:px-2\",\n                  active\n                    ? \"border-border bg-card text-foreground shadow-xs\"\n                    : \"border-transparent text-muted-foreground hover:text-foreground\",\n                  focusRing,\n                )}\n              >\n                <span\n                  aria-hidden=\"true\"\n                  className={cn(\n                    \"size-1.5 rounded-full\",\n                    active ? levelStyle[level].dot : \"bg-transparent ring-1 ring-muted-foreground/50 ring-inset\",\n                  )}\n                />\n                {levelStyle[level].label}\n                <span className=\"font-mono text-[11px] text-muted-foreground tabular-nums\">{counts[level]}</span>\n              </button>\n            );\n          })}\n        </div>\n        <div className=\"relative ml-auto min-w-36 flex-1 @lg/log:max-w-60\">\n          <Search\n            aria-hidden=\"true\"\n            className=\"pointer-events-none absolute top-1/2 left-2 size-3.5 -translate-y-1/2 text-muted-foreground\"\n          />\n          <input\n            ref={searchRef}\n            type=\"text\"\n            value={search}\n            onChange={(event) => setSearch(event.target.value)}\n            onKeyDown={(event) => {\n              if (event.key === \"Escape\" && search) {\n                event.stopPropagation();\n                setSearch(\"\");\n              }\n            }}\n            placeholder=\"Filter…\"\n            aria-label=\"Filter messages\"\n            spellCheck={false}\n            className=\"h-7 w-full rounded-md border border-input bg-card pr-7 pl-7 text-xs text-foreground shadow-xs transition-[border-color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/30 motion-reduce:transition-none\"\n          />\n          {search ? (\n            <button\n              type=\"button\"\n              onClick={() => {\n                setSearch(\"\");\n                searchRef.current?.focus();\n              }}\n              className={cn(\n                \"absolute top-1/2 right-1 inline-flex size-5 -translate-y-1/2 items-center justify-center rounded text-muted-foreground hover:text-foreground\",\n                focusRing,\n              )}\n            >\n              <X className=\"size-3\" aria-hidden=\"true\" />\n              <span className=\"sr-only\">Clear filter</span>\n            </button>\n          ) : (\n            <kbd className=\"pointer-events-none absolute top-1/2 right-1.5 hidden -translate-y-1/2 rounded border bg-muted px-1 font-mono text-[10px] leading-4 text-muted-foreground @md/log:block\">\n              /\n            </kbd>\n          )}\n        </div>\n      </div>\n\n      <div className=\"relative\">\n        <div\n          ref={scrollRef}\n          role=\"log\"\n          aria-live=\"polite\"\n          aria-relevant=\"additions\"\n          aria-labelledby={`${id}-title`}\n          tabIndex={0}\n          onScroll={handleScroll}\n          className=\"overflow-y-auto overscroll-contain py-1.5 font-mono text-xs outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-inset\"\n          style={{ height }}\n        >\n          {rows.map((entry) => (\n            <LogRow\n              key={entry.id}\n              entry={entry}\n              query={query}\n              wrap={wrap}\n              expanded={expanded.has(entry.id)}\n              enter={mounted}\n              zone={timeZone}\n              onToggle={toggleRow}\n            />\n          ))}\n          {rows.length === 0 && (\n            <div className=\"flex h-full flex-col items-center justify-center gap-2 px-4 text-center font-sans\">\n              {total === 0 ? (\n                <p className=\"text-xs text-muted-foreground\">\n                  {live ? \"Waiting for events…\" : \"No events yet.\"}\n                </p>\n              ) : (\n                <>\n                  <p className=\"text-xs text-muted-foreground\">No events match these filters.</p>\n                  <button\n                    type=\"button\"\n                    onClick={resetFilters}\n                    className={cn(\"rounded-md px-2 py-1 text-xs font-medium text-primary hover:bg-muted\", focusRing)}\n                  >\n                    Show all events\n                  </button>\n                </>\n              )}\n            </div>\n          )}\n          {rows.length > 0 && live && following && (\n            <div aria-hidden=\"true\" className=\"px-4 py-[5px] leading-[18px]\">\n              <span className=\"inline-block h-3.5 w-[7px] translate-y-[3px] animate-pulse bg-foreground/35 motion-reduce:animate-none\" />\n            </div>\n          )}\n        </div>\n        <div\n          aria-hidden=\"true\"\n          className=\"pointer-events-none absolute inset-x-0 top-0 h-4 bg-linear-to-b from-card to-transparent\"\n        />\n        {!following && (\n          <button\n            type=\"button\"\n            onClick={() => setFollowing(true)}\n            className={cn(\n              \"absolute bottom-3 left-1/2 inline-flex h-7 -translate-x-1/2 items-center gap-1.5 rounded-full bg-foreground px-3 text-xs font-medium text-background shadow-lg transition-[opacity,translate] duration-200 starting:translate-y-1 starting:opacity-0 motion-reduce:transition-none\",\n              focusRing,\n            )}\n          >\n            <ArrowDown className=\"size-3.5\" aria-hidden=\"true\" />\n            Jump to latest\n            {pending > 0 && (\n              <span className=\"rounded-full bg-background/20 px-1.5 font-mono text-[11px] tabular-nums\">\n                {pending > 999 ? \"999+\" : pending} new\n              </span>\n            )}\n          </button>\n        )}\n      </div>\n\n      <div className=\"flex items-center justify-between gap-3 border-t px-4 py-1.5 font-mono text-[11px] text-muted-foreground tabular-nums\">\n        <span>\n          {filtered ? `${matching.toLocaleString(\"en-US\")} of ${total.toLocaleString(\"en-US\")}` : total.toLocaleString(\"en-US\")}{\" \"}\n          {total === 1 ? \"event\" : \"events\"}\n          {rows.length < matching && ` · showing last ${rows.length.toLocaleString(\"en-US\")}`}\n        </span>\n        <span>{timeZone === \"utc\" ? \"UTC\" : \"Local time\"}</span>\n      </div>\n    </div>\n  );\n}\n"
    }
  ],
  "docs": "Documentation: https://ui.overtrue.xyz/blocks/incident-review. Requires an initialized shadcn/ui project with Tailwind CSS v4."
}
