Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

34.5 KB
Raw Blame
/**
 * Trace observation: a
 * CUDA-profiling-style two-dimensional lane chart.
 *
 * Trace records completion times; the server infers segments from "model
 * messages are produced serially (autoregressive decoding)" and groups by Task:
 * - Each Task has its own independent timeline (Tasks far apart in time would
 *   leave large gaps if sharing one axis);
 * - Bars come in only five kinds, each with a fixed color (no gray/black/white):
 *   thinking, model reply, tool-call generation (model lane), approval wait,
 *   tool-call execution (one row per tool name; same-name calls that don't
 *   overlap in time share the row, overlapping ones split into extra rows —
 *   see lane-packing.ts);
 * - Highlighting is always expressed as "fade out the rest", never an outline:
 *   hovering a segment highlights just that segment (by its unique key, so
 *   adjacent segments at the same timestamp aren't highlighted together), and
 *   it's linked by timestamp to the event list below (onHighlight); clicking a
 *   segment jumps to and briefly highlights the corresponding message row (onJump);
 * - Hovering a legend item highlights matching segments (fading out the rest);
 * - Time-axis zoom/pan: drag the slider below the legend (drag the body to
 *   pan, drag either handle to zoom, double-click to reset), similar to
 *   Premiere's timeline navigator. Scroll-wheel zoom is deliberately
 *   unsupported — to avoid accidentally changing zoom while scrolling the page.
 */
import { Fragment, useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
import type { CSSProperties, PointerEvent as ReactPointerEvent, ReactNode } from "react";
import type { TraceModelSegment, TraceOtherSpan, TraceToolSpan } from "@adelie/server/api";
import { Dot, Legend, TimelineBar, namedHint } from "@adelie/ui";
import type { ChartPaint, LegendItem } from "@adelie/ui";
import { S } from "../../lib/strings";
import { humanizeDuration } from "../../lib/format";
import { packToolLanes, toolSpanBounds } from "./lane-packing";
import type { PackedLane } from "./lane-packing";

/**
 * Linked highlighting: `ts` is the anchor shared by both sides; `key` /
 * `rowKey` uniquely identify a bar / message row.
 *
 * **Only one bar and one message light up at a time**: multiple elements
 * often share the same millisecond (a tool_call and its request_end), so
 * matching by `ts` alone would highlight adjacent items together. The
 * initiating side supplies its own unique key; the other side takes the
 * first element at that timestamp.
 */
export interface TraceHighlight {
  ts?: string;
  /** Unique bar identifier (generated internally by the timeline). */
  key?: string;
  /** Unique message-row identifier (generated by the event list). */
  rowKey?: string;
}

/**
 * The theme's palette slot each of the five bar kinds paints with (0-based; see the UI
 * package's chart style): thinking violet, model reply sky, tool-call generation amber, approval
 * wait rose, tool execution emerald. Identities, not judgements, so every theme keeps them and
 * picks its own shade of each.
 */
const KIND_SLOT = { thinking: 0, text: 2, toolgen: 1, approvalWait: 3, exec: 4 } as const;
type BarKind = keyof typeof KIND_SLOT | "other";

/**
 * Non-tool auxiliary phases (MCP connect) are their own legend category, not tool execution —
 * deliberately muted, since background bookkeeping should not outshine the work: the neutral
 * gray rather than a palette slot.
 */
const OTHER_CLASS = "bg-gray-400 dark:bg-gray-500";

/** A bar kind's paint: its palette slot, or the neutral for the auxiliary phases. */
const kindPaint = (kind: BarKind): ChartPaint =>
  kind === "other"
    ? { ink: "text-gray-400 dark:text-gray-500", swatch: OTHER_CLASS }
    : { series: KIND_SLOT[kind] };

/**
 * Left-side label column: sticky-pinned to the far left during horizontal
 * scroll/zoom, so labels don't scroll away with the timeline.
 * Must be an opaque block the **same height** as a lane (h-4) — otherwise a
 * bar scrolled underneath the label would peek out above/below the text's
 * line height, looking like the bar is overlapping the label text. Width
 * lines up with the task label row's `pl-[5.5rem]`.
 */
const LABEL_STICKY =
  "sticky left-0 z-10 flex h-4 w-[5.5rem] shrink-0 items-center justify-end bg-white pr-2 dark:bg-gray-950";
/** Label text (truncated when too long). */
const LABEL_TEXT = "truncate font-mono text-xs";
/** Zoom range (time-axis multiplier). */
const ZOOM_MIN = 0.25;
const ZOOM_MAX = 24;
/** Slider window's max width corresponds to zoom=1 (window = the whole content); zoom<1 (a compressed overview) is triggered via the −/+ buttons or by dragging the slider. */
const MIN_WIN = 1 / ZOOM_MAX;

const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));

/** Model-lane segment kind: thinking / text (model reply) / tool_call (tool-call generation). */
function segmentKind(kind: TraceModelSegment["kind"]): BarKind {
  if (kind === "thinking") return "thinking";
  if (kind === "text") return "text";
  return "toolgen";
}

function segmentLabel(kind: TraceModelSegment["kind"]): string {
  if (kind === "thinking") return S.traces.kindThinking;
  if (kind === "text") return S.traces.kindModelReply;
  return S.traces.kindToolGen;
}

/** Legend key a segment belongs to (used for hover-linked fade-out). */
function segmentLegendKey(kind: TraceModelSegment["kind"]): string {
  if (kind === "thinking") return "thinking";
  if (kind === "text") return "text";
  return "toolgen";
}

/** Normalize an invalid/missing timestamp to null (treated as unclosed), so a single NaN doesn't propagate. */
function msOf(ts: string | undefined): number | null {
  if (ts === undefined) return null;
  const ms = Date.parse(ts);
  return Number.isFinite(ms) ? ms : null;
}

interface PlacedSegment {
  kind: TraceModelSegment["kind"];
  name?: string;
  ts: string;
  startMs: number;
  endMs: number;
}

interface PlacedSpan {
  name: string;
  toolCallId: string;
  callTs: string;
  approvalTsRaw?: string;
  outputTsRaw?: string;
  callMs: number;
  approvalMs: number | null;
  outputMs: number | null;
  failed: boolean;
  status?: string;
  decision?: string;
}

interface TaskGroup {
  taskIndex: number;
  segs: PlacedSegment[];
  others: PlacedOther[];
  t0: number;
  total: number;
  /** Tool rows after lane packing: one row per (name, lane), same-name lanes adjacent. */
  toolRows: PackedLane<PlacedSpan>[];
}

/** A placed "other" bar (non-tool auxiliary phase, e.g. MCP connect): one lane per span. */
interface PlacedOther {
  key: string;
  name: string;
  ts: string;
  startMs: number;
  endMs: number;
  failed: boolean;
}

function buildGroups(
  segments: TraceModelSegment[],
  toolSpans: TraceToolSpan[],
  otherSpans: TraceOtherSpan[],
): TaskGroup[] {
  const byTask = new Map<
    number,
    { segs: PlacedSegment[]; spans: PlacedSpan[]; others: PlacedOther[] }
  >();
  const bucket = (i: number) => {
    let b = byTask.get(i);
    if (!b) {
      b = { segs: [], spans: [], others: [] };
      byTask.set(i, b);
    }
    return b;
  };

  for (const s of segments) {
    const startMs = msOf(s.startTs);
    const endMs = msOf(s.endTs);
    if (startMs === null || endMs === null) continue;
    bucket(s.taskIndex).segs.push({
      kind: s.kind,
      ...(s.name !== undefined ? { name: s.name } : {}),
      ts: s.endTs,
      startMs,
      endMs,
    });
  }
  for (const t of toolSpans) {
    const callMs = msOf(t.callTs);
    if (callMs === null) continue;
    bucket(t.taskIndex).spans.push({
      name: t.name || t.toolCallId,
      toolCallId: t.toolCallId,
      callTs: t.callTs,
      ...(t.approvalTs !== undefined ? { approvalTsRaw: t.approvalTs } : {}),
      ...(t.outputTs !== undefined ? { outputTsRaw: t.outputTs } : {}),
      callMs,
      approvalMs: msOf(t.approvalTs),
      outputMs: msOf(t.outputTs),
      failed: t.stopReason !== undefined && t.stopReason !== "completed",
      ...(t.stopReason !== undefined ? { status: t.stopReason } : {}),
      ...(t.decision !== undefined ? { decision: t.decision } : {}),
    });
  }

  for (const o of otherSpans) {
    const startMs = msOf(o.startTs);
    const endMs = msOf(o.endTs);
    if (startMs === null || endMs === null) continue;
    bucket(o.taskIndex).others.push({
      key: o.key,
      name: o.name,
      // Event-list linkage anchors on the closing event's timestamp (the mcp_connect_end row).
      ts: o.endTs,
      startMs,
      endMs,
      failed: o.failed === true,
    });
  }

  const groups: TaskGroup[] = [];
  for (const [taskIndex, { segs, spans, others }] of [...byTask.entries()].sort(
    (a, b) => a[0] - b[0],
  )) {
    if (segs.length === 0 && spans.length === 0 && others.length === 0) continue;
    const starts = [
      ...segs.map((s) => s.startMs),
      ...spans.map((s) => s.callMs),
      ...others.map((o) => o.startMs),
    ];
    const ends = [
      ...segs.map((s) => s.endMs),
      ...spans.map((s) => s.outputMs ?? s.approvalMs ?? s.callMs),
      ...others.map((o) => o.endMs),
    ];
    const t0 = Math.min(...starts);
    const tEnd = Math.max(...ends, ...starts);
    const total = Math.max(1, tEnd - t0);
    spans.sort((a, b) => a.callMs - b.callMs);
    others.sort((a, b) => a.startMs - b.startMs);
    const toolRows = packToolLanes(spans.map((s) => ({ ...s, ...toolSpanBounds(s, t0 + total) })));
    groups.push({ taskIndex, segs, others, t0, total, toolRows });
  }
  return groups;
}

/** Track: the gray-background container for bars (no rounded corners; overflow-hidden keeps bars from overlapping adjacent text). */
function Track({ children }: { children: ReactNode }) {
  return (
    <div
      data-part="grid"
      className="relative h-4 min-w-0 flex-1 overflow-hidden bg-gray-100 dark:bg-gray-800/60"
    >
      {children}
    </div>
  );
}

function Lane({ label, children }: { label: string; children: ReactNode }) {
  return (
    <div className="flex items-center">
      <span
        className={`${LABEL_STICKY} text-gray-400 dark:text-gray-500`}
        data-tooltip={label}
        data-tooltip-content="text"
      >
        <span className={LABEL_TEXT}>{label}</span>
      </span>
      <Track>{children}</Track>
    </div>
  );
}

/**
 * Time-tick row: the first tick left-aligns, the last right-aligns, the rest
 * center — otherwise `-translate-x-1/2` would overflow the first and last
 * labels by half a character width, and the horizontal scroll container
 * would clip the last label (`591ms` truncated to `591`).
 * This way the default width (zoom=1) already fits the rightmost coordinate, with no extra padding needed.
 */
function Ticks({ total }: { total: number }) {
  const fracs = [0, 0.25, 0.5, 0.75, 1];
  return (
    <div className="flex items-center">
      <span className={LABEL_STICKY} />
      <div className="relative h-4 min-w-0 flex-1">
        {fracs.map((f, i) => (
          <span
            key={i}
            className={`absolute top-0 font-mono text-xs text-fg-subtle ${
              i === 0 ? "" : i === fracs.length - 1 ? "-translate-x-full" : "-translate-x-1/2"
            }`}
            style={{ left: `${f * 100}%` }}
          >
            {humanizeDuration(f * total)}
          </span>
        ))}
      </div>
    </div>
  );
}

/**
 * The mark on a bar that is still open: an approval still pending, a tool still running. An open
 * bar always runs to its lane's right edge (its end is the chart's "now"), so the mark sits there —
 * a pulsing state dot, the live signal a theme can re-time, while the bar itself holds still.
 * `dim` is the bar's fade, so a highlight elsewhere fades the mark with its bar.
 */
function LiveEnd({ tone, dim }: { tone: "attention" | "success"; dim: string }) {
  return (
    <span className={`pointer-events-none absolute inset-y-0 right-0.5 flex items-center ${dim}`}>
      <Dot tone={tone} pulse />
    </span>
  );
}

/** The default for a caller with no other spans: one shared array, so the grouping memo (and the
 * view effect keyed on it) stays put across renders instead of rerunning on a fresh `[]`. */
const NO_OTHER_SPANS: TraceOtherSpan[] = [];

export function TimelineChart({
  segments,
  toolSpans,
  otherSpans = NO_OTHER_SPANS,
  highlight,
  onHighlight,
  onJump,
  hideTaskLabel = false,
}: {
  segments: TraceModelSegment[];
  toolSpans: TraceToolSpan[];
  /** Non-tool auxiliary phases (MCP connect): rendered in their own lanes under the "other" legend. */
  otherSpans?: TraceOtherSpan[];
  highlight?: TraceHighlight | null;
  onHighlight?: (h: TraceHighlight | null) => void;
  /** Click a bar: jump to and briefly highlight the message at that moment. */
  onJump?: (ts: string) => void;
  /** Hide the "Round N" label when embedded in the "grouped by Task" view (the group header already shows it). */
  hideTaskLabel?: boolean;
}) {
  const groups = useMemo(
    () => buildGroups(segments, toolSpans, otherSpans),
    [segments, toolSpans, otherSpans],
  );
  /**
   * This chart's bar index: timestamp → the **first** bar's key (in render
   * order), plus the set of every bar's key.
   * - Highlights initiated by the event list carry only `ts`; `firstBarKeyByTs`
   *   degrades that into "only one bar lights up", so adjacent bars at the
   *   same instant aren't dragged along;
   * - `barKeys` decides whether the highlight target **belongs to this
   *   chart**: when grouped by Task, each round renders its own TimelineChart
   *   but they share the same highlight — without this scope check, hovering
   *   a bar in round 1 would fade out round 2's entire timeline too.
   */
  const { firstBarKeyByTs, barKeys } = useMemo(() => {
    const m = new Map<string, string>();
    const keys = new Set<string>();
    const put = (ts: string, key: string) => {
      keys.add(key);
      if (!m.has(ts)) m.set(ts, key);
    };
    for (const g of groups) {
      g.segs.forEach((s, i) => put(s.ts, `s-${g.taskIndex}-${i}`));
      // Walked row by row, so "first bar at this timestamp" stays the topmost
      // one on screen — packing reorders tool bars relative to their call order.
      for (const row of g.toolRows) {
        for (const s of row.spans) {
          if (s.approvalMs !== null && s.approvalMs > s.callMs) {
            put(s.approvalTsRaw ?? s.callTs, `w-${s.toolCallId}`);
          }
          if (s.approvalMs === null && s.outputMs === null) put(s.callTs, `p-${s.toolCallId}`);
          else put(s.outputTsRaw ?? s.callTs, `e-${s.toolCallId}`);
        }
      }
      for (const o of g.others) put(o.ts, `o-${o.key}`);
    }
    return { firstBarKeyByTs: m, barKeys: keys };
  }, [groups]);
  // Hovering the legend highlights matching segments; null = none.
  const [legendKey, setLegendKey] = useState<string | null>(null);
  // Time-axis zoom multiplier + visible window (derived from scroll).
  const [zoom, setZoom] = useState(1);
  const [view, setView] = useState({ left: 0, width: 1 });
  const scrollRef = useRef<HTMLDivElement>(null);
  const trackRef = useRef<HTMLDivElement>(null);
  const viewRef = useRef(view);
  viewRef.current = view;
  const zoomRef = useRef(zoom);
  zoomRef.current = zoom;
  // Target scrollLeft to apply after reflow once zoom changes the content width (keeps the anchor point).
  const pendingScroll = useRef<((el: HTMLDivElement) => number) | null>(null);
  // Cleanup for an in-progress drag (removes the window listener as a fallback on unmount/interruption).
  const dragCleanup = useRef<(() => void) | null>(null);

  const updateView = useCallback(() => {
    const el = scrollRef.current;
    if (!el) return;
    const sw = el.scrollWidth || 1;
    const left = el.scrollLeft / sw;
    const width = Math.min(1, el.clientWidth / sw);
    // Same window, same state object: a layout effect that measures must not re-render for nothing.
    setView((v) => (v.left === left && v.width === width ? v : { left, width }));
  }, []);

  useLayoutEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    if (pendingScroll.current) {
      const max = el.scrollWidth - el.clientWidth;
      el.scrollLeft = clamp(pendingScroll.current(el), 0, Math.max(0, max));
      pendingScroll.current = null;
    }
    updateView();
  }, [zoom, groups, updateView]);

  // Recompute the slider window after the container size changes (window resize / sidebar collapse), so the thumb's position/width don't get distorted.
  useLayoutEffect(() => {
    const el = scrollRef.current;
    if (!el || typeof ResizeObserver === "undefined") return;
    const ro = new ResizeObserver(() => updateView());
    ro.observe(el);
    return () => ro.disconnect();
  }, [updateView]);

  // Fallback cleanup of an in-progress drag listener on unmount (pointercancel / mid-drag unmount don't fire pointerup).
  useLayoutEffect(() => () => dragCleanup.current?.(), []);

  if (groups.length === 0) return <p className="text-xs text-gray-400">{S.common.none}</p>;

  const hlTs = highlight?.ts;
  const hlKey = highlight?.key;
  const enter = (key: string, ts: string | undefined) => onHighlight?.(ts ? { ts, key } : null);
  const leave = () => onHighlight?.(null);

  // The one bar that lights up: use the highlight's own key if it has one;
  // otherwise, with only ts (from the event list), take the first bar at that instant.
  // If the target isn't in this chart (the highlight belongs to another Task), treat it as no highlight — otherwise this chart would fade out entirely.
  const target = hlKey ?? (hlTs !== undefined ? firstBarKeyByTs.get(hlTs) : undefined);
  const activeBarKey = target !== undefined && barKeys.has(target) ? target : undefined;
  const hlOn = activeBarKey !== undefined;
  const isActive = (key: string): boolean => activeBarKey === key;

  /** Highlight/legend filtering is always expressed as "fade out the rest", never an outline. */
  const dimClass = (active: boolean, legendMatch: boolean) =>
    (legendKey !== null && !legendMatch) || (hlOn && !active) ? "opacity-15" : "";

  // Position strictly by exact timestamp (no minimum width, no right-edge
  // pull-back): segments sit flush against each other with no overlap, and
  // highlighting lands only on the current segment without bleeding into
  // neighbors (per the user's requirement). left/width are clamped to [0,100] to prevent overflow.
  const placeExact = (startMs: number, endMs: number, t0: number, total: number): CSSProperties => {
    const left = clamp(((startMs - t0) / total) * 100, 0, 100);
    const width = clamp(((endMs - startMs) / total) * 100, 0, 100 - left);
    // A zero-duration segment landing exactly on the right edge: min-w-[2px]
    // would push it out of the track, and the track's overflow-hidden would
    // clip it entirely (invisible, unhoverable). Pull that 2px back into the
    // track with a -2px margin, while the start point stays exactly aligned.
    if (left >= 100) return { left: "100%", width: "0%", marginLeft: "-2px" };
    return { left: `${left}%`, width: `${width}%` };
  };

  const legendItem = (key: BarKind, label: string): LegendItem => ({
    key,
    label,
    paint: kindPaint(key),
    shape: "chip",
  });
  const legendItems = [
    legendItem("thinking", S.traces.kindThinking),
    legendItem("text", S.traces.kindModelReply),
    legendItem("toolgen", S.traces.kindToolGen),
    legendItem("approvalWait", S.traces.legendApprovalWait),
    legendItem("exec", S.traces.legendToolExec),
    legendItem("other", S.traces.legendOther),
  ];

  // —— Slider (Premiere-style): drag the body to pan, drag either handle to zoom, double-click to reset ——
  const applyWindow = (left: number, width: number) => {
    const w = clamp(width, MIN_WIN, 1);
    const next = clamp(1 / w, ZOOM_MIN, ZOOM_MAX);
    const l = clamp(left, 0, 1 - w);
    pendingScroll.current = (el) => l * el.scrollWidth;
    setZoom(next);
  };

  const beginPan = (e: ReactPointerEvent) => {
    e.preventDefault();
    const track = trackRef.current;
    const el = scrollRef.current;
    if (!track || !el) return;
    const trackW = track.getBoundingClientRect().width || 1;
    const startX = e.clientX;
    const startScroll = el.scrollLeft;
    const max = Math.max(0, el.scrollWidth - el.clientWidth);
    const move = (ev: PointerEvent) => {
      const dxFrac = (ev.clientX - startX) / trackW;
      el.scrollLeft = clamp(startScroll + dxFrac * el.scrollWidth, 0, max);
      updateView();
    };
    const up = () => {
      window.removeEventListener("pointermove", move);
      window.removeEventListener("pointerup", up);
      window.removeEventListener("pointercancel", up);
      dragCleanup.current = null;
    };
    window.addEventListener("pointermove", move);
    window.addEventListener("pointerup", up);
    window.addEventListener("pointercancel", up);
    dragCleanup.current = up;
  };

  const beginResize = (side: "left" | "right") => (e: ReactPointerEvent) => {
    e.preventDefault();
    e.stopPropagation();
    const track = trackRef.current;
    if (!track) return;
    const rect = track.getBoundingClientRect();
    const move = (ev: PointerEvent) => {
      const frac = clamp((ev.clientX - rect.left) / (rect.width || 1), 0, 1);
      const cur = viewRef.current;
      if (side === "right") {
        applyWindow(cur.left, frac - cur.left);
      } else {
        const right = cur.left + cur.width;
        applyWindow(frac, right - frac);
      }
    };
    const up = () => {
      window.removeEventListener("pointermove", move);
      window.removeEventListener("pointerup", up);
      window.removeEventListener("pointercancel", up);
      dragCleanup.current = null;
    };
    window.addEventListener("pointermove", move);
    window.addEventListener("pointerup", up);
    window.addEventListener("pointercancel", up);
    dragCleanup.current = up;
  };

  const resetZoom = () => {
    pendingScroll.current = () => 0;
    setZoom(1);
  };

  /** −/+ buttons: zoom anchored at the viewport center (covers the full range from <1 overview to >1 zoomed-in). */
  const zoomStep = (factor: number) => {
    const el = scrollRef.current;
    const next = clamp(zoomRef.current * factor, ZOOM_MIN, ZOOM_MAX);
    if (next === zoomRef.current) return;
    if (el) {
      const px = el.clientWidth / 2;
      const contentFrac = (el.scrollLeft + px) / (el.scrollWidth || 1);
      pendingScroll.current = (node) => contentFrac * node.scrollWidth - px;
    }
    setZoom(next);
  };

  return (
    // ui-chart: a theme may redraw the parts — the lane tracks (grid) and the bars.
    <div className="ui-chart space-y-3">
      {/* Timeline (horizontal scroll container; native scrollbar hidden in favor of the slider below). overflow-y-hidden avoids a spurious vertical scrollbar. */}
      <div ref={scrollRef} className="no-scrollbar overflow-x-auto overflow-y-hidden">
        <div className="space-y-4" style={{ width: `${zoom * 100}%` }}>
          {groups.map((g) => {
            return (
              <div key={g.taskIndex} className="space-y-1">
                {!hideTaskLabel && (
                  <div className="flex items-center gap-2 pl-[5.5rem]">
                    <span className="rounded bg-gray-100 px-1.5 py-0.5 text-xs font-medium text-fg-muted dark:bg-gray-800">
                      {S.traces.task(g.taskIndex + 1)}
                    </span>
                    <span className="font-mono text-xs text-gray-400">
                      {humanizeDuration(g.total)}
                    </span>
                  </div>
                )}

                {/* Model lane: serial segments (thinking / model reply / tool-call generation) */}
                <Lane label={S.traces.laneLLM}>
                  {g.segs.map((s, i) => {
                    const lk = segmentLegendKey(s.kind);
                    const legendMatch = legendKey === null || legendKey === lk;
                    const barKey = `s-${g.taskIndex}-${i}`;
                    const active = isActive(barKey);
                    return (
                      <TimelineBar
                        key={i}
                        onMouseEnter={() => enter(barKey, s.ts)}
                        onMouseLeave={leave}
                        onClick={() => onJump?.(s.ts)}
                        {...namedHint(
                          `${segmentLabel(s.kind)}${s.name ? ` ${s.name}` : ""} · ${humanizeDuration(s.endMs - s.startMs)}`,
                        )}
                        className={`cursor-pointer ${dimClass(active, legendMatch)}`}
                        paint={kindPaint(segmentKind(s.kind))}
                        place={placeExact(s.startMs, s.endMs, g.t0, g.total)}
                      />
                    );
                  })}
                </Lane>

                {/* Tool rows: one per (name, lane) — non-overlapping same-name calls share the row, each rendered as approval wait → execution */}
                {g.toolRows.map((row, rowIdx) => (
                  <div key={`${rowIdx}-${row.name}`} className="flex items-center">
                    <span
                      className={`${LABEL_STICKY} text-gray-500 dark:text-gray-400`}
                      data-tooltip={row.name}
                      data-tooltip-content="text"
                    >
                      <span className={LABEL_TEXT}>{row.name}</span>
                    </span>
                    <Track>
                      {row.spans.map((s) => {
                        const execStart = s.approvalMs ?? s.callMs;
                        const open = s.outputMs === null;
                        const endMs = s.outputMs ?? g.t0 + g.total;
                        const approvalTs = s.approvalTsRaw ?? s.callTs;
                        const execTs = s.outputTsRaw ?? s.callTs;
                        return (
                          <Fragment key={s.toolCallId}>
                            {/* Approval-wait segment (positioned exactly, flush against the execution segment) */}
                            {s.approvalMs !== null && s.approvalMs > s.callMs && (
                              <TimelineBar
                                onMouseEnter={() => enter(`w-${s.toolCallId}`, approvalTs)}
                                onMouseLeave={leave}
                                onClick={() => onJump?.(approvalTs)}
                                {...namedHint(
                                  `${s.name} · ${S.traces.legendApprovalWait}${s.decision ? ` (${s.decision})` : ""} · ${humanizeDuration(s.approvalMs - s.callMs)}`,
                                )}
                                className={`cursor-pointer ${dimClass(
                                  isActive(`w-${s.toolCallId}`),
                                  legendKey === null || legendKey === "approvalWait",
                                )}`}
                                paint={kindPaint("approvalWait")}
                                place={placeExact(s.callMs, s.approvalMs, g.t0, g.total)}
                              />
                            )}
                            {/* Approval still pending (with its live mark) / execution segment */}
                            {s.approvalMs === null && open
                              ? (() => {
                                  const dim = dimClass(
                                    isActive(`p-${s.toolCallId}`),
                                    legendKey === null || legendKey === "approvalWait",
                                  );
                                  return (
                                    <>
                                      <TimelineBar
                                        onMouseEnter={() => enter(`p-${s.toolCallId}`, s.callTs)}
                                        onMouseLeave={leave}
                                        onClick={() => onJump?.(s.callTs)}
                                        {...namedHint(
                                          `${s.name} · ${S.traces.legendApprovalWait} · ${S.traces.inProgress}`,
                                        )}
                                        className={`cursor-pointer ${dim}`}
                                        paint={kindPaint("approvalWait")}
                                        place={placeExact(s.callMs, endMs, g.t0, g.total)}
                                      />
                                      <LiveEnd tone="attention" dim={dim} />
                                    </>
                                  );
                                })()
                              : (() => {
                                  // Fade-out and the "running" translucency share the same opacity property: fade-out takes priority to avoid the two overriding each other.
                                  const dim = dimClass(
                                    isActive(`e-${s.toolCallId}`),
                                    legendKey === null || legendKey === "exec",
                                  );
                                  const running = open && !dim;
                                  return (
                                    <>
                                      <TimelineBar
                                        onMouseEnter={() => enter(`e-${s.toolCallId}`, execTs)}
                                        onMouseLeave={leave}
                                        onClick={() => onJump?.(execTs)}
                                        {...namedHint(
                                          `${s.name} · ${S.traces.legendToolExec} · ${
                                            open
                                              ? S.traces.inProgress
                                              : humanizeDuration(endMs - execStart)
                                          }${s.failed ? ` · ${s.status}` : ""}`,
                                        )}
                                        className={`cursor-pointer ${
                                          s.failed ? "ring-1 ring-red-500" : ""
                                        } ${running ? "opacity-70" : dim}`}
                                        paint={kindPaint("exec")}
                                        place={placeExact(execStart, endMs, g.t0, g.total)}
                                      />
                                      {open && <LiveEnd tone="success" dim={dim} />}
                                    </>
                                  );
                                })()}
                          </Fragment>
                        );
                      })}
                    </Track>
                  </div>
                ))}

                {/* Non-tool auxiliary phases (MCP connect): one lane each, own legend category */}
                {g.others.map((o) => {
                  const dim = dimClass(
                    isActive(`o-${o.key}`),
                    legendKey === null || legendKey === "other",
                  );
                  return (
                    <div key={o.key} className="flex items-center">
                      <span
                        className={`${LABEL_STICKY} text-gray-500 dark:text-gray-400`}
                        data-tooltip={o.name}
                        data-tooltip-content="text"
                      >
                        <span className={LABEL_TEXT}>{o.name}</span>
                      </span>
                      <Track>
                        <TimelineBar
                          onMouseEnter={() => enter(`o-${o.key}`, o.ts)}
                          onMouseLeave={leave}
                          onClick={() => onJump?.(o.ts)}
                          {...namedHint(
                            `${o.name} · ${S.traces.legendOther} · ${humanizeDuration(o.endMs - o.startMs)}`,
                          )}
                          className={`cursor-pointer ${
                            o.failed ? "ring-1 ring-red-500" : ""
                          } ${dim}`}
                          paint={kindPaint("other")}
                          place={placeExact(o.startMs, o.endMs, g.t0, g.total)}
                        />
                      </Track>
                    </div>
                  );
                })}

                {/* Time-axis ticks */}
                <Ticks total={g.total} />
              </div>
            );
          })}
        </div>
      </div>

      {/* Legend: hovering highlights matching segments — same convention as the bars, non-matching items fade out, no background color */}
      <div className="border-t border-line-muted pt-2.5">
        <Legend items={legendItems} active={legendKey} onHover={setLegendKey} />
      </div>

      {/* Premiere-style zoom/pan slider: drag the body to pan, drag either handle to zoom, double-click to reset; −/+ covers the full range from <1 to >1 */}
      <div className="flex items-center gap-2">
        <span className="shrink-0 text-xs text-gray-400">{S.traces.zoom}</span>
        <button
          type="button"
          aria-label={S.traces.zoomOut}
          data-tooltip={S.traces.zoomOut}
          onClick={() => zoomStep(1 / 1.4)}
          className="flex h-4 w-4 shrink-0 items-center justify-center rounded border border-gray-200 text-gray-500 transition-colors duration-150 hover:bg-gray-100 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-800"
        >
          <span className="text-xs leading-none">−</span>
        </button>
        <div
          ref={trackRef}
          onDoubleClick={resetZoom}
          data-tooltip={S.traces.zoomReset}
          className="relative h-3 min-w-0 flex-1 rounded bg-gray-100 dark:bg-gray-800"
        >
          <div
            role="scrollbar"
            aria-label={S.traces.zoom}
            onPointerDown={beginPan}
            className="absolute inset-y-0 flex cursor-grab items-center justify-between rounded bg-gray-400/70 active:cursor-grabbing dark:bg-gray-500/70"
            style={{ left: `${view.left * 100}%`, width: `${Math.max(view.width * 100, 3)}%` }}
          >
            <span
              onPointerDown={beginResize("left")}
              className="h-full w-1.5 shrink-0 cursor-ew-resize rounded-l bg-gray-500/80 dark:bg-gray-400/80"
            />
            <span
              onPointerDown={beginResize("right")}
              className="h-full w-1.5 shrink-0 cursor-ew-resize rounded-r bg-gray-500/80 dark:bg-gray-400/80"
            />
          </div>
        </div>
        <button
          type="button"
          aria-label={S.traces.zoomIn}
          data-tooltip={S.traces.zoomIn}
          onClick={() => zoomStep(1.4)}
          className="flex h-4 w-4 shrink-0 items-center justify-center rounded border border-gray-200 text-gray-500 transition-colors duration-150 hover:bg-gray-100 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-800"
        >
          <span className="text-xs leading-none">+</span>
        </button>
        <span className="w-9 shrink-0 text-right font-mono text-xs tabular-nums text-gray-400">
          {zoom.toFixed(2)}×
        </span>
      </div>

      {onHighlight && (
        <p className="text-xs text-gray-400 dark:text-gray-600">{S.traces.linkHint}</p>
      )}
    </div>
  );
}