Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(trace): dense timeline renderer with a maps-style viewport (#16133)

Nikita Kabardine947e6436c5b
diff --git a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.stories.tsx b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.stories.tsx
new file mode 100644
index 0000000000..31c74f87a3
--- /dev/null
+++ b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.stories.tsx
@@ -0,0 +1,423 @@
+import { expect, waitFor } from "storybook/test";
+import preview from "../../../../../.storybook/preview";
+import { TimelineDense } from "./TimelineDense";
+import {
+ manySpans,
+ reporterTrace,
+ threeSpans,
+ longTailTrace,
+} from "../../fns/timeline/__tests__/timelineV2.fixtures";
+
+const meta = preview.meta({
+ component: TimelineDense,
+});
+
+/**
+ * A phone-shaped box: narrow and tall, which is the case this spike is for.
+ * 658px leaves exactly 600px of surface once the frame, toolbar, axis and
+ * readout are taken β€” room for 150 rows at the 4px floor, so the "at the floor"
+ * story really is at the floor.
+ */
+const PHONE = { width: 360, height: 658 };
+/** The peek panel: narrow and short. */
+const PEEK = { width: 320, height: 300 };
+/**
+ * A full-width desktop pane. Every other box here is narrow, which is the case
+ * the spike was written for β€” but the same layout has to hold when the lane is
+ * ten times wider, and that is a different question: whether extreme density is
+ * still the right answer when there is plenty of room.
+ */
+const DESKTOP = { width: 1280, height: 658 };
+
+export const FiftySpansOnAPhone = meta.story({
+ args: {
+ roots: manySpans(50),
+ box: PHONE,
+ gutter: "auto",
+ pointer: "fine",
+ barColor: "neutral",
+ compress: false,
+ showReadout: true,
+ },
+});
+
+export const OneHundredFiftySpansExactlyAtTheFloor = meta.story({
+ args: {
+ roots: manySpans(150),
+ box: PHONE,
+ gutter: "auto",
+ pointer: "fine",
+ barColor: "neutral",
+ compress: false,
+ showReadout: true,
+ },
+});
+
+/** More rows than 4px each can show: the extra are panned to, maps-style. */
+export const FiveHundredSpansPannable = meta.story({
+ args: {
+ roots: manySpans(500),
+ box: PHONE,
+ gutter: "auto",
+ pointer: "fine",
+ barColor: "neutral",
+ compress: false,
+ showReadout: true,
+ },
+});
+
+export const TypeColouredBars = meta.story({
+ args: {
+ roots: manySpans(150),
+ box: PHONE,
+ gutter: "auto",
+ pointer: "fine",
+ barColor: "type",
+ compress: false,
+ showReadout: true,
+ },
+});
+
+/** Few enough rows that they stay comfortable and keep their text. */
+export const ShortTraceStaysReadable = meta.story({
+ args: {
+ roots: threeSpans(),
+ box: PHONE,
+ gutter: "auto",
+ pointer: "fine",
+ barColor: "neutral",
+ compress: false,
+ showReadout: true,
+ },
+});
+
+export const ReporterShapeInAPeek = meta.story({
+ args: {
+ roots: reporterTrace(),
+ box: PEEK,
+ gutter: "auto",
+ pointer: "fine",
+ barColor: "neutral",
+ compress: false,
+ showReadout: true,
+ },
+});
+
+/** The gutter forced open: what the left side becomes when there is room. */
+export const NamesExpanded = meta.story({
+ args: {
+ roots: manySpans(150),
+ box: PHONE,
+ gutter: "expanded",
+ pointer: "fine",
+ barColor: "neutral",
+ compress: false,
+ showReadout: true,
+ },
+});
+
+export const FullWidthDesktop = meta.story({
+ args: {
+ roots: manySpans(150),
+ box: DESKTOP,
+ gutter: "auto",
+ pointer: "fine",
+ barColor: "type",
+ compress: false,
+ showReadout: true,
+ },
+});
+
+/**
+ * Full width with the gutter open. Few enough rows that they are readable, which
+ * is what the gutter needs β€” 150 rows in this box are 4px, and a name in a 4px
+ * row is not a name, so the gutter would refuse to open at all.
+ */
+export const FullWidthWithNames = meta.story({
+ args: {
+ roots: manySpans(24),
+ box: DESKTOP,
+ gutter: "expanded",
+ pointer: "fine",
+ barColor: "type",
+ compress: false,
+ showReadout: true,
+ },
+});
+
+/** Full width, past the row floor: 500 spans with 150 on screen. */
+export const FullWidthManySpans = meta.story({
+ args: {
+ roots: manySpans(500),
+ box: DESKTOP,
+ gutter: "auto",
+ pointer: "fine",
+ barColor: "type",
+ compress: false,
+ showReadout: true,
+ },
+});
+
+/** Touch: no hover, so the rail toggles on tap. */
+export const TouchTapToToggle = meta.story({
+ args: {
+ roots: manySpans(150),
+ box: PHONE,
+ gutter: "auto",
+ pointer: "coarse",
+ barColor: "type",
+ compress: false,
+ showReadout: true,
+ },
+});
+
+export const LongTailCompressed = meta.story({
+ args: {
+ roots: longTailTrace(),
+ box: PHONE,
+ gutter: "auto",
+ pointer: "fine",
+ barColor: "type",
+ compress: true,
+ showReadout: true,
+ },
+});
+
+export const NeitherAxisScrolls = meta.story({
+ name: "(Test) Neither Axis Scrolls",
+ args: {
+ roots: manySpans(150),
+ box: PHONE,
+ gutter: "auto",
+ pointer: "fine",
+ barColor: "neutral",
+ compress: false,
+ showReadout: true,
+ },
+ play: async ({ canvasElement }) => {
+ const surface = canvasElement.querySelector<HTMLElement>(
+ '[data-testid="timeline-dense-surface"]',
+ );
+ if (!surface) throw new Error("dense surface not found");
+
+ // The whole claim of this spike: nothing scrolls in either axis. The surface
+ // is a map β€” it pans β€” so there must be no scrollable overflow at all.
+ await expect(surface.scrollWidth).toBeLessThanOrEqual(surface.clientWidth);
+ await expect(surface.scrollHeight).toBeLessThanOrEqual(
+ surface.clientHeight,
+ );
+
+ const bars = canvasElement.querySelectorAll<HTMLElement>(
+ '[data-testid="timeline-dense-bar"]',
+ );
+ await expect(bars.length).toBe(150);
+
+ const surfaceRect = surface.getBoundingClientRect();
+ for (const bar of bars) {
+ const rect = bar.getBoundingClientRect();
+ await expect(rect.right).toBeLessThanOrEqual(surfaceRect.right + 0.5);
+ await expect(rect.top).toBeGreaterThanOrEqual(surfaceRect.top - 0.5);
+ await expect(rect.bottom).toBeLessThanOrEqual(surfaceRect.bottom + 0.5);
+ await expect(rect.height).toBeGreaterThan(0);
+ }
+ },
+});
+
+export const ScrollPansPinchZooms = meta.story({
+ name: "(Test) Scroll Pans, Pinch Zooms",
+ args: {
+ roots: manySpans(150),
+ box: PHONE,
+ gutter: "auto",
+ pointer: "fine",
+ barColor: "neutral",
+ compress: false,
+ showReadout: true,
+ },
+ play: async ({ canvasElement }) => {
+ const surface = canvasElement.querySelector<HTMLElement>(
+ '[data-testid="timeline-dense-surface"]',
+ );
+ if (!surface) throw new Error("dense surface not found");
+ const rowHeight = () =>
+ canvasElement.querySelector<HTMLElement>(
+ '[data-testid="dense-rowheight"]',
+ )?.textContent ?? "";
+ const rowWindow = () =>
+ canvasElement.querySelector<HTMLElement>('[data-testid="dense-rows"]')
+ ?.textContent ?? "";
+
+ const rect = surface.getBoundingClientRect();
+ const wheel = (init: WheelEventInit) =>
+ surface.dispatchEvent(
+ new WheelEvent("wheel", {
+ bubbles: true,
+ cancelable: true,
+ clientX: rect.left + rect.width / 2,
+ clientY: rect.top + rect.height / 2,
+ ...init,
+ }),
+ );
+
+ // Zoom in a little first, so there is somewhere to pan to AND headroom
+ // left below the max row height for the last assertion.
+ wheel({ deltaY: -40, ctrlKey: true });
+ await waitFor(() => expect(rowHeight()).not.toContain("4.0px"));
+ const heightBefore = rowHeight();
+ const windowBefore = rowWindow();
+
+ // A macOS two-finger scroll is a PLAIN wheel. It must pan, never zoom β€”
+ // this is the whole bug: treating it as zoom made scrolling around resize
+ // the rows.
+ wheel({ deltaY: 30 });
+ await waitFor(() => expect(rowWindow()).not.toBe(windowBefore));
+ await expect(rowHeight()).toBe(heightBefore);
+
+ // A pinch carries ctrlKey, and that zooms.
+ wheel({ deltaY: -40, ctrlKey: true });
+ await waitFor(() => expect(rowHeight()).not.toBe(heightBefore));
+ },
+});
+
+export const HoverPeeksTheNames = meta.story({
+ name: "(Test) Hover Peeks The Names",
+ args: {
+ roots: manySpans(40),
+ box: PHONE,
+ gutter: "auto",
+ pointer: "fine",
+ barColor: "type",
+ compress: false,
+ showReadout: true,
+ },
+ play: async ({ canvasElement }) => {
+ const surface = canvasElement.querySelector<HTMLElement>(
+ '[data-testid="timeline-dense-surface"]',
+ );
+ if (!surface) throw new Error("dense surface not found");
+ // Names live in the peek overlay OR in the in-flow gutter, depending on
+ // whether the open is a peek or a committed one.
+ const names = () =>
+ canvasElement.querySelectorAll(
+ '[data-testid="timeline-dense-peek"] span[title], [data-testid="timeline-dense-content"] > div span[title]',
+ ).length;
+ const rect = surface.getBoundingClientRect();
+ const move = (offsetX: number) =>
+ surface.dispatchEvent(
+ new PointerEvent("pointermove", {
+ bubbles: true,
+ pointerType: "mouse",
+ clientX: rect.left + offsetX,
+ clientY: rect.top + 120,
+ }),
+ );
+
+ const barGeometry = () => {
+ const bar = canvasElement.querySelector<HTMLElement>(
+ '[data-testid="timeline-dense-bar"]',
+ );
+ if (!bar) return null;
+ const box = bar.getBoundingClientRect();
+ return `${Math.round(box.left)}:${Math.round(box.width)}`;
+ };
+
+ // 40 rows in this box are 15px β€” readable, but below where the gutter opens
+ // on its own. Hovering the rail is what peeks at the names.
+ await expect(names()).toBe(0);
+ const beforePeek = barGeometry();
+ move(4);
+ await waitFor(() => expect(names()).toBeGreaterThan(0));
+
+ // The peek floats OVER the timeline. It must not take width from the lane,
+ // because re-laying out the bars while you look at them moves the very thing
+ // you are trying to read.
+ await expect(barGeometry()).toBe(beforePeek);
+
+ // Moving into the chart hands the space straight back.
+ move(rect.width * 0.7);
+ await waitFor(() => expect(names()).toBe(0));
+ await expect(barGeometry()).toBe(beforePeek);
+ },
+});
+
+export const DoubleClickFocusesBothAxes = meta.story({
+ name: "(Test) Double Click Focuses Both Axes",
+ args: {
+ roots: manySpans(150),
+ box: PHONE,
+ gutter: "auto",
+ pointer: "fine",
+ barColor: "neutral",
+ compress: false,
+ showReadout: true,
+ },
+ play: async ({ canvasElement }) => {
+ const readout = () =>
+ canvasElement.querySelector<HTMLElement>(
+ '[data-testid="timeline-dense-readout"]',
+ )?.textContent ?? "";
+
+ await expect(readout()).toContain("fitted");
+ await expect(readout()).toContain("4.0px rows");
+
+ const row = canvasElement.querySelectorAll<HTMLElement>(
+ '[data-testid="timeline-dense-content"] > div',
+ )[40];
+ if (!row) throw new Error("expected a row to double-click");
+ row.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));
+
+ // Both axes move: the rows reach a readable height AND the time window
+ // narrows onto the element, rather than only zooming the clock. The focus
+ // FLIES rather than jumping, so this is the landing, not the first frame.
+ await waitFor(() => expect(readout()).toContain("zoomed"));
+ await waitFor(() => expect(readout()).toContain("26.0px rows"));
+ await expect(readout()).not.toContain("rows 0.0–150.0 of 150");
+ },
+});
+
+export const HoverOpensATooltip = meta.story({
+ name: "(Test) Hover Opens A Tooltip",
+ args: {
+ roots: manySpans(150),
+ box: PHONE,
+ gutter: "auto",
+ pointer: "fine",
+ barColor: "neutral",
+ compress: false,
+ showReadout: true,
+ },
+ play: async ({ canvasElement }) => {
+ const surface = canvasElement.querySelector<HTMLElement>(
+ '[data-testid="timeline-dense-surface"]',
+ );
+ const content = canvasElement.querySelector<HTMLElement>(
+ '[data-testid="timeline-dense-content"]',
+ );
+ if (!surface || !content) throw new Error("dense surface not found");
+
+ const heightBefore = content.getBoundingClientRect().height;
+ const rect = surface.getBoundingClientRect();
+ surface.dispatchEvent(
+ new PointerEvent("pointermove", {
+ bubbles: true,
+ clientX: rect.left + rect.width / 2,
+ clientY: rect.top + rect.height / 2,
+ }),
+ );
+
+ // Hover names what you are on β€” this layout spends no row pixels on text.
+ await waitFor(() =>
+ expect(
+ canvasElement.querySelector('[data-testid="timeline-dense-tooltip"]'),
+ ).not.toBeNull(),
+ );
+ // And hovering must not move anything: no reflow, no new scroll.
+ await expect(content.getBoundingClientRect().height).toBeCloseTo(
+ heightBefore,
+ 1,
+ );
+ await expect(surface.scrollHeight).toBeLessThanOrEqual(
+ surface.clientHeight,
+ );
+ },
+});
diff --git a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx
new file mode 100644
index 0000000000..7d9ab647d4
--- /dev/null
+++ b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx
@@ -0,0 +1,1059 @@
+/**
+ * Throwaway renderer for the extreme-density spike.
+ *
+ * The question it exists to answer: in a narrow, tall layout, does killing the
+ * names and the text and spending every pixel on shape make you FEEL the
+ * timeline β€” where a 26px row with a duration label next to a 4px bar reads as
+ * a list of numbers instead?
+ *
+ * At rest: no name gutter, a 10px rail carrying type as a small square in the
+ * type's own hue, rows shrunk to fit the box, and no text at all.
+ *
+ * Then it is driven **like a map**, because that is what exploring a dense
+ * surface wants:
+ * - The left side is adaptive: a bare colour rail by default, opening into the
+ * real tree gutter β€” the observation's own icon and name, indented by depth β€”
+ * as the rows grow past ~20px, and peekable earlier by hovering it (tapping it
+ * on touch). It cannot open below ~14px rows, because there is no name to show
+ * in a 4px row; the hover tooltip is what names a row at that density.
+ * Working in the chart hands the space straight back.
+ * - Two-finger scroll pans both axes; pinch (and a discrete mouse notch) zooms
+ * BOTH axes about the cursor, so the time window narrows and the rows grow
+ * together. Zoom is exponential in a zoom level and deltas accumulate per
+ * frame, as in mapping libraries β€” see the rate constants below.
+ * - Drag pans both axes too. There are no scrollbars by design: a map has none,
+ * and the viewport clamps to the content so there is nowhere to get lost.
+ * - Double-click an element focuses it β€” the time window onto its own extent,
+ * the rows at a height a human reads, the element centred.
+ * - What a row shows follows from how tall it has become: the type square grows
+ * around 10px, text returns around 20px. Zooming in makes the timeline grow
+ * its labels back rather than switching mode.
+ *
+ * A magnifying lens (rows near the pointer expanding, borrowing space from the
+ * rest) is implemented and tested in fns/timeline/focusLens.ts and deliberately
+ * NOT wired up: a fisheye needs an invertible transform to hit-test correctly,
+ * and absolutely-positioned rows are the wrong substrate. That is the next spike.
+ *
+ * Not production code.
+ */
+
+import {
+ useCallback,
+ useMemo,
+ useRef,
+ useState,
+ type PointerEvent as ReactPointerEvent,
+ type ReactNode,
+} from "react";
+import {
+ Maximize2,
+ Minus,
+ PanelLeftClose,
+ PanelLeftOpen,
+ Plus,
+} from "lucide-react";
+import { ItemBadge, type LangfuseItemType } from "@/src/components/ItemBadge";
+import { cn } from "@/src/utils/tailwind";
+import { type Density, type PointerModality } from "../../fns/timeline/density";
+import {
+ formatDurationMs,
+ layout,
+ prepareTimeline,
+ timeCompressionFor,
+ type LayoutNode,
+ type PositionedNode,
+} from "../../fns/timeline/layout";
+import { createTextMeasurer } from "../../fns/timeline/textMeasurer";
+import { traceSpaceOf, type Box } from "../../fns/timeline/viewTransform";
+import {
+ HUMAN_ROW_HEIGHT,
+ interpolateViewport,
+ rowCountBounds,
+ viewportsEqual,
+ clampViewport,
+ fitViewport,
+ focusViewport,
+ isViewportFitted,
+ panViewport,
+ presentationForRowHeight,
+ rowHeightOf,
+ rowIndexAtOffset,
+ visibleRowRange,
+ zoomViewport,
+ type Viewport,
+} from "../../fns/timeline/viewport";
+
+/** Reuses ItemBadge's type→hue mapping, so a colour means what it already means. */
+const TYPE_COLOR: Record<string, string> = {
+ TRACE: "bg-dark-green",
+ GENERATION: "bg-muted-magenta",
+ EVENT: "bg-muted-green",
+ SPAN: "bg-muted-blue",
+ AGENT: "bg-purple-600",
+ TOOL: "bg-orange-600",
+ CHAIN: "bg-pink-600",
+ RETRIEVER: "bg-teal-600",
+ EMBEDDING: "bg-amber-600",
+ GUARDRAIL: "bg-red-600",
+};
+const FALLBACK_COLOR = "bg-muted-gray";
+
+const RAIL_WIDTH = 10;
+const RAIL_INDENT = 2;
+const RAIL_MAX_DEPTH = 4;
+/** Indent per level once the gutter is open, matching the production gutter. */
+const GUTTER_INDENT = 10;
+const TOOLBAR_HEIGHT = 22;
+const AXIS_HEIGHT = 16;
+const READOUT_HEIGHT = 18;
+const FRAME_BORDER = 1;
+/**
+ * Zoom is exponential in a zoom LEVEL β€” one level doubles the scale β€” and input
+ * deltas accumulate into level deltas, which is how every mapping library does
+ * it. The rate has to depend on the input device, and mapping libraries ship two
+ * constants for exactly this reason: macOS sends pinch deltas of only a few
+ * units while a mouse notch is ~100, so one divisor cannot serve both. A single
+ * linear factor per event with a /100 divisor moved ~1% per pinch event, which
+ * is why it felt like a lot of touching to get anywhere.
+ */
+const PINCH_ZOOM_RATE = 1 / 40;
+const WHEEL_ZOOM_RATE = 1 / 160;
+/** A deltaMode-0 event bigger than this is a mouse notch, not a trackpad. */
+const WHEEL_DELTA_THRESHOLD = 40;
+/** Step for the toolbar buttons and the keyboard, in zoom levels. */
+const BUTTON_ZOOM_LEVELS = 0.6;
+const DRAG_THRESHOLD_PX = 3;
+const MAX_BAR_HEIGHT = 18;
+/** Below this a row cannot hold a name, so the gutter stays a rail. */
+const NAME_MIN_ROW_HEIGHT = 14;
+/** The chart never shrinks below this to make room for names. */
+const MIN_LANE_WIDTH = 140;
+/**
+ * A focus flies rather than teleports. An instant jump reads as "the bar I
+ * clicked got bigger" β€” you cannot see that the window moved, especially when
+ * the rows around it were already full width. Maps animate their zoom for the
+ * same reason.
+ */
+const FOCUS_ANIMATION_MS = 320;
+/** Slack around the rail so the peek zone is reachable at 10px wide. */
+const PEEK_MARGIN_PX = 6;
+
+/**
+ * How wide the left side is once something has asked for it to open. The chart
+ * keeps priority: if opening would leave the lane below MIN_LANE_WIDTH it stays a
+ * rail, because the timeline is the point of the surface.
+ */
+function resolveGutterWidth(input: {
+ open: boolean;
+ contentWidth: number;
+}): number {
+ if (!input.open) return RAIL_WIDTH;
+ const wanted = Math.min(Math.max(input.contentWidth * 0.38, 96), 168);
+ return input.contentWidth - wanted >= MIN_LANE_WIDTH ? wanted : RAIL_WIDTH;
+}
+
+export type TimelineDenseProps = {
+ roots: LayoutNode[];
+ /** The measured box. Required β€” there is no fallback size. */
+ box: Box;
+ /**
+ * Starting gutter mode. `auto` derives it from row height β€” a hairline row
+ * cannot hold a name, a 26px row can β€” which is the default and the point of
+ * this layout.
+ */
+ gutter: GutterMode;
+ /**
+ * Input modality. `fine` peeks the gutter on hover; `coarse` has no hover, so
+ * it toggles on a tap of the rail.
+ */
+ pointer: PointerModality;
+ /** Colour the bars by type too, or leave them neutral and let the rail carry it. */
+ barColor: "neutral" | "type";
+ compress: boolean;
+ showReadout: boolean;
+};
+
+export type GutterMode = "auto" | "expanded" | "collapsed";
+
+export function TimelineDense({
+ roots,
+ box,
+ gutter,
+ pointer,
+ barColor,
+ compress,
+ showReadout,
+}: TimelineDenseProps) {
+ const [viewport, setViewport] = useState<Viewport | null>(null);
+ const [focusIndex, setFocusIndex] = useState<number | null>(null);
+ const [pointerPos, setPointerPos] = useState<{ x: number; y: number } | null>(
+ null,
+ );
+ const [selectedIndex, setSelectedIndex] = useState<number | null>(null);
+ const [dragging, setDragging] = useState(false);
+
+ const prepared = useMemo(() => prepareTimeline(roots), [roots]);
+ // Rendered at 10px, so measured at 10px: layout() decides which side a label
+ // goes on, and that decision is only as good as the font it measured.
+ const measurer = useMemo(() => createTextMeasurer("10px ui-sans-serif"), []);
+
+ // A manual override lives until you touch the chart again, which is what
+ // "expand to look, then get out of my way" means in practice.
+ const [override, setOverride] = useState<GutterMode | null>(null);
+ // Desktop peek: hovering the left edge opens it, moving into the chart closes
+ // it again. No click to look, no click to get out of the way.
+ const [peeking, setPeeking] = useState(false);
+ const gutterMode = override ?? gutter;
+ const contentWidth = Math.max(box.width - FRAME_BORDER * 2, 0);
+ const surfaceHeight = Math.max(
+ box.height -
+ FRAME_BORDER * 2 -
+ TOOLBAR_HEIGHT -
+ AXIS_HEIGHT -
+ (showReadout ? READOUT_HEIGHT : 0),
+ 0,
+ );
+
+ // Resolve the VERTICAL window first. It depends only on the row count and the
+ // height, never on the width, so row height is known before the gutter width
+ // β€” which is what breaks the cycle (gutter β†’ lane β†’ compression β†’ viewport).
+ // Deciding the gutter from the *resting* row height instead left it a rail
+ // forever, however far you zoomed in.
+ const rowBounds = rowCountBounds({
+ rowCount: prepared.rows.length,
+ boxHeight: surfaceHeight,
+ });
+ const liveRowCount = Math.min(
+ Math.max(viewport?.rows.count ?? rowBounds.max, rowBounds.min),
+ rowBounds.max,
+ );
+ const liveRowHeight =
+ liveRowCount > 0 ? surfaceHeight / liveRowCount : HUMAN_ROW_HEIGHT;
+
+ // The left side is the key to the lines β€” the tree gutter, names and all. It
+ // can only open when the rows are tall enough to hold a name: at 4px there is
+ // no name to show, and the hover tooltip is what names a row at that density.
+ const canShowNames = liveRowHeight >= NAME_MIN_ROW_HEIGHT;
+
+ // A COMMITTED open takes real space and re-lays out the chart, because you
+ // asked for it to stay. A PEEK must not: it floats over the timeline instead,
+ // so hovering the edge never shoves the bars sideways while you are reading
+ // them. Same content, different claim on the layout.
+ const committedOpen =
+ canShowNames &&
+ (override === "collapsed"
+ ? false
+ : override === "expanded" ||
+ gutterMode === "expanded" ||
+ (gutterMode === "auto" && liveRowHeight >= HUMAN_ROW_HEIGHT - 6));
+ const railWidth = resolveGutterWidth({ open: committedOpen, contentWidth });
+ const laneWidth = Math.max(contentWidth - railWidth, 0);
+
+ const chartBox = useMemo(
+ () => ({ width: laneWidth, height: surfaceHeight }),
+ [laneWidth, surfaceHeight],
+ );
+ const compression = useMemo(
+ () => timeCompressionFor(prepared, chartBox, compress),
+ [prepared, chartBox, compress],
+ );
+
+ const limits = useMemo(
+ () => ({
+ traceSpace: traceSpaceOf(compression.compressedDurationMs),
+ rowCount: prepared.rows.length,
+ boxHeight: surfaceHeight,
+ }),
+ [compression.compressedDurationMs, prepared.rows.length, surfaceHeight],
+ );
+
+ // Re-clamped every render, so a resize can never leave the viewport looking
+ // outside the content.
+ const current = useMemo(
+ () => (viewport ? clampViewport(viewport, limits) : fitViewport(limits)),
+ [viewport, limits],
+ );
+ const rowHeight = rowHeightOf(current, surfaceHeight);
+ const isOpen = railWidth > RAIL_WIDTH;
+ const namesVisible = isOpen;
+ // The overlay is not bound by MIN_LANE_WIDTH: it costs the chart no width.
+ const peekWidth =
+ !isOpen && canShowNames && peeking
+ ? Math.min(Math.max(contentWidth * 0.38, 96), 168)
+ : 0;
+ const gutterWidth = Math.max(railWidth, peekWidth);
+ const presentation = presentationForRowHeight(rowHeight);
+ const fitted = isViewportFitted(current, limits);
+ const barHeight = Math.max(Math.min(rowHeight - 1, MAX_BAR_HEIGHT), 1);
+
+ const density: Density = useMemo(
+ () => ({
+ pointer,
+ rowHeight,
+ barHeight: Math.max(Math.min(rowHeight - 1, MAX_BAR_HEIGHT), 1),
+ labelFontPx: 11,
+ labelPaddingPx: 4,
+ labelGapPx: 6,
+ minBarWidthPx: presentation === "hairline" ? 2 : 4,
+ }),
+ [rowHeight, presentation, pointer],
+ );
+
+ const rowRange = visibleRowRange(current, prepared.rows.length);
+ const result = layout({
+ roots,
+ box: chartBox,
+ density,
+ measurer,
+ view: current.time,
+ compress,
+ prepared,
+ compression,
+ rowRange,
+ });
+
+ const zoomBy = useCallback(
+ (factor: number, xRatio: number, yRatio: number) =>
+ setViewport((from) => {
+ const { limits: live } = layoutRef.current;
+ return zoomViewport(
+ from ? clampViewport(from, live) : fitViewport(live),
+ live,
+ { factor, xRatio, yRatio },
+ );
+ }),
+ [],
+ );
+
+ const panBy = useCallback(
+ (dxPx: number, dyPx: number) =>
+ setViewport((from) => {
+ const { limits: live, laneWidth: width } = layoutRef.current;
+ return panViewport(
+ from ? clampViewport(from, live) : fitViewport(live),
+ live,
+ { dxPx, dyPx, boxWidth: width },
+ );
+ }),
+ [],
+ );
+
+ const surfaceRef = useRef<HTMLDivElement | null>(null);
+ const gesture = useRef({ down: false, dragging: false, x: 0, y: 0 });
+ const tween = useRef(0);
+
+ const cancelTween = useCallback(() => {
+ if (tween.current) cancelAnimationFrame(tween.current);
+ tween.current = 0;
+ }, []);
+
+ // The gesture path reads the viewport from a ref, not from render scope: a
+ // trackpad fires many events per frame and each must build on the last, not on
+ // whatever React had rendered when the burst started.
+ const viewportRef = useRef(current);
+ viewportRef.current = current;
+
+ // Layout the gesture handlers read through a ref rather than closing over.
+ // Closing over it made every handler change identity whenever the gutter
+ // opened, which re-ran the surface ref β€” and its cleanup cancelled an
+ // in-flight focus animation at the exact moment the rows crossed the height
+ // that opens the gutter. It also re-attached the wheel listener on every
+ // layout change, for nothing.
+ const layoutRef = useRef({ limits, laneWidth, railWidth, peekWidth });
+ layoutRef.current = { limits, laneWidth, railWidth, peekWidth };
+
+ // Deltas accumulate and apply once per animation frame β€” the other half of
+ // what makes map zoom feel immediate instead of laggy under a burst.
+ const pending = useRef({
+ levels: 0,
+ dxPx: 0,
+ dyPx: 0,
+ xRatio: 0.5,
+ yRatio: 0.5,
+ frame: 0,
+ });
+
+ const releaseOverride = useCallback(() => {
+ setOverride((held) => (held === "expanded" ? null : held));
+ setPeeking(false);
+ }, []);
+
+ const flushGesture = useCallback(() => {
+ const queued = pending.current;
+ queued.frame = 0;
+ const { limits: live, laneWidth: width } = layoutRef.current;
+ let next = viewportRef.current;
+ if (queued.levels !== 0) {
+ next = zoomViewport(next, live, {
+ factor: 2 ** queued.levels,
+ xRatio: queued.xRatio,
+ yRatio: queued.yRatio,
+ });
+ }
+ if (queued.dxPx !== 0 || queued.dyPx !== 0) {
+ next = panViewport(next, live, {
+ dxPx: queued.dxPx,
+ dyPx: queued.dyPx,
+ boxWidth: width,
+ });
+ }
+ queued.levels = 0;
+ queued.dxPx = 0;
+ queued.dyPx = 0;
+ if (viewportsEqual(next, viewportRef.current)) return;
+ viewportRef.current = next;
+ setViewport(next);
+ }, []);
+
+ /** Ease-in-out, so the flight starts and lands softly. */
+ const flyTo = useCallback(
+ (target: Viewport) => {
+ cancelTween();
+ const from = viewportRef.current;
+ const startedAt = performance.now();
+ const step = (now: number) => {
+ const linear = Math.min((now - startedAt) / FOCUS_ANIMATION_MS, 1);
+ const eased =
+ linear < 0.5 ? 2 * linear * linear : 1 - (-2 * linear + 2) ** 2 / 2;
+ const next = interpolateViewport(from, target, eased);
+ viewportRef.current = next;
+ setViewport(next);
+ tween.current = linear < 1 ? requestAnimationFrame(step) : 0;
+ };
+ tween.current = requestAnimationFrame(step);
+ },
+ [cancelTween],
+ );
+
+ const scheduleGesture = useCallback(() => {
+ // Any gesture on the chart hands the space back: an expanded gutter is for
+ // looking, and the moment you work in the chart it gets out of the way. It
+ // also takes over from an animation in flight rather than fighting it.
+ cancelTween();
+ releaseOverride();
+ if (pending.current.frame) return;
+ pending.current.frame = requestAnimationFrame(flushGesture);
+ }, [flushGesture, releaseOverride, cancelTween]);
+
+ /**
+ * Wheel and trackpad pinch on a non-passive listener, so the page never takes
+ * the gesture. Both zoom, like a map: a Mac pinch arrives as wheel + ctrlKey
+ * and needs no special case; shift or a horizontal wheel pans instead.
+ */
+ const attachSurface = useCallback(
+ (element: HTMLDivElement | null) => {
+ surfaceRef.current = element;
+ if (!element) return;
+
+ const onWheel = (event: WheelEvent) => {
+ const rect = element.getBoundingClientRect();
+ const queued = pending.current;
+ const rail = layoutRef.current.railWidth;
+ // A macOS pinch is the ONLY wheel event that carries ctrlKey. A
+ // two-finger scroll is a plain wheel, so it must pan β€” treating it as
+ // zoom is what made scrolling around zoom the rows instead.
+ const pinch = event.ctrlKey || event.metaKey;
+
+ if (pinch) {
+ queued.xRatio =
+ rect.width > 0
+ ? (event.clientX - rect.left - rail) /
+ Math.max(rect.width - rail, 1)
+ : 0.5;
+ queued.yRatio =
+ rect.height > 0 ? (event.clientY - rect.top) / rect.height : 0.5;
+ queued.levels += -event.deltaY * PINCH_ZOOM_RATE;
+ event.preventDefault();
+ scheduleGesture();
+ return;
+ }
+
+ // A discrete mouse notch has no pan intent behind it, so it zooms, at
+ // its own much slower rate per unit of delta.
+ const isMouseNotch =
+ event.deltaMode !== 0 ||
+ Math.abs(event.deltaY) >= WHEEL_DELTA_THRESHOLD;
+ if (isMouseNotch && event.deltaX === 0 && !event.shiftKey) {
+ queued.xRatio =
+ rect.width > 0
+ ? (event.clientX - rect.left - rail) /
+ Math.max(rect.width - rail, 1)
+ : 0.5;
+ queued.yRatio =
+ rect.height > 0 ? (event.clientY - rect.top) / rect.height : 0.5;
+ queued.levels += -event.deltaY * WHEEL_ZOOM_RATE;
+ event.preventDefault();
+ scheduleGesture();
+ return;
+ }
+
+ // Two-finger scroll: pan both axes. Shift maps a vertical wheel to time.
+ const dxPx = event.shiftKey ? -event.deltaY : -event.deltaX;
+ const dyPx = event.shiftKey ? 0 : -event.deltaY;
+ const wouldMove = panViewport(
+ viewportRef.current,
+ layoutRef.current.limits,
+ { dxPx, dyPx, boxWidth: layoutRef.current.laneWidth },
+ );
+ // Only swallow the gesture if it actually moves us; at a clamp the page
+ // keeps its scroll instead of being trapped.
+ if (viewportsEqual(wouldMove, viewportRef.current)) return;
+ event.preventDefault();
+ queued.dxPx += dxPx;
+ queued.dyPx += dyPx;
+ scheduleGesture();
+ };
+
+ element.addEventListener("wheel", onWheel, { passive: false });
+ return () => {
+ cancelTween();
+ element.removeEventListener("wheel", onWheel);
+ };
+ },
+ // Stable: everything live is read from layoutRef, so the listener attaches
+ // once and an animation is never cancelled by a re-attach.
+ [scheduleGesture, cancelTween],
+ );
+
+ const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {
+ // Touch has no hover, so a tap on the rail is the toggle.
+ const offsetX =
+ event.clientX - event.currentTarget.getBoundingClientRect().left;
+ if (
+ (pointer === "coarse" || event.pointerType === "touch") &&
+ offsetX <= Math.max(railWidth, peekWidth) + PEEK_MARGIN_PX
+ ) {
+ setOverride(isOpen ? "collapsed" : "expanded");
+ return;
+ }
+ gesture.current = {
+ down: true,
+ dragging: false,
+ x: event.clientX,
+ y: event.clientY,
+ };
+ };
+
+ const onPointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {
+ const state = gesture.current;
+ if (state.down) {
+ const dx = event.clientX - state.x;
+ const dy = event.clientY - state.y;
+ if (!state.dragging && Math.hypot(dx, dy) >= DRAG_THRESHOLD_PX) {
+ state.dragging = true;
+ setDragging(true);
+ // Capture only once it really is a drag, so a click still reaches a row.
+ event.currentTarget.setPointerCapture(event.pointerId);
+ }
+ if (state.dragging) {
+ releaseOverride();
+ panBy(dx, dy);
+ state.x = event.clientX;
+ state.y = event.clientY;
+ return;
+ }
+ }
+
+ const rect = event.currentTarget.getBoundingClientRect();
+ const offsetY = event.clientY - rect.top;
+ const offsetX = event.clientX - rect.left;
+
+ // Peek is hover-driven on a fine pointer only: a coarse pointer has no
+ // hover, so it toggles on tap instead (see onPointerDown).
+ if (pointer === "fine" && event.pointerType !== "touch") {
+ setPeeking(offsetX <= Math.max(railWidth, peekWidth) + PEEK_MARGIN_PX);
+ }
+
+ setFocusIndex(
+ rowIndexAtOffset(current, offsetY, rowHeight, prepared.rows.length),
+ );
+ setPointerPos({ x: offsetX, y: offsetY });
+ };
+
+ const endGesture = useCallback(() => {
+ gesture.current.down = false;
+ gesture.current.dragging = false;
+ setDragging(false);
+ }, []);
+
+ const clearFocus = useCallback(() => {
+ setFocusIndex(null);
+ setPointerPos(null);
+ setPeeking(false);
+ endGesture();
+ }, [endGesture]);
+
+ /** Double-click an element: both axes move to put it on screen, readably. */
+ const focusRow = (index: number) => {
+ const positioned = result.nodes.find((node) => node.index === index);
+ if (!positioned) return;
+ setSelectedIndex(index);
+ const startMs = compression.toCompressedMs(positioned.startMs);
+ flyTo(
+ focusViewport(limits, {
+ rowIndex: index,
+ startMs,
+ durationMs: compression.toCompressedMs(positioned.endMs) - startMs,
+ }),
+ );
+ };
+
+ const focused =
+ focusIndex == null
+ ? null
+ : (result.nodes.find((node) => node.index === focusIndex) ?? null);
+
+ const windowLabel = formatDurationMs(
+ compression.toRealMs(current.time.start + current.time.duration) -
+ compression.toRealMs(current.time.start),
+ );
+
+ return (
+ <div
+ className="bg-background border-border text-foreground flex flex-col overflow-hidden rounded border select-none"
+ style={{ width: `${box.width}px`, height: `${box.height}px` }}
+ >
+ <div
+ className="border-border flex shrink-0 items-center gap-1 border-b px-1"
+ style={{ height: `${TOOLBAR_HEIGHT}px` }}
+ >
+ <ToolbarButton
+ label="Zoom out"
+ onClick={() => zoomBy(2 ** -BUTTON_ZOOM_LEVELS, 0.5, 0.5)}
+ >
+ <Minus className="h-3 w-3" />
+ </ToolbarButton>
+ <ToolbarButton
+ label="Zoom in"
+ onClick={() => zoomBy(2 ** BUTTON_ZOOM_LEVELS, 0.5, 0.5)}
+ >
+ <Plus className="h-3 w-3" />
+ </ToolbarButton>
+ <ToolbarButton
+ label="Fit whole trace"
+ onClick={() => flyTo(fitViewport(limits))}
+ >
+ <Maximize2 className="h-3 w-3" />
+ </ToolbarButton>
+ <ToolbarButton
+ label={isOpen ? "Collapse names" : "Show names"}
+ onClick={() => setOverride(isOpen ? "collapsed" : "expanded")}
+ >
+ {isOpen ? (
+ <PanelLeftClose className="h-3 w-3" />
+ ) : (
+ <PanelLeftOpen className="h-3 w-3" />
+ )}
+ </ToolbarButton>
+ <span
+ className="text-muted-foreground truncate"
+ style={{ fontSize: "10px" }}
+ title={
+ fitted
+ ? "scroll to pan Β· pinch to zoom Β· double-click to focus"
+ : `${rowHeight.toFixed(1)}px rows Β· ${windowLabel} window`
+ }
+ >
+ {fitted
+ ? "scroll to pan Β· pinch to zoom Β· double-click to focus"
+ : `${rowHeight.toFixed(1)}px rows Β· ${windowLabel} window`}
+ </span>
+ </div>
+
+ <div
+ className="border-border relative shrink-0 border-b"
+ style={{ height: `${AXIS_HEIGHT}px` }}
+ >
+ <div
+ className="absolute inset-y-0"
+ style={{ left: `${railWidth}px`, width: `${laneWidth}px` }}
+ >
+ {result.ticks.map((tick) => (
+ <div
+ key={tick.realMs}
+ className="border-border-contrast absolute inset-y-0 border-l"
+ style={{ left: `${tick.x}px` }}
+ >
+ <span
+ className="text-muted-foreground absolute left-1 whitespace-nowrap"
+ style={{ fontSize: "9px" }}
+ >
+ {tick.label}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {/* The map surface. No scrollbars: panning is the gesture, and the
+ viewport clamps to the content so there is nowhere to get lost. */}
+ <div
+ ref={attachSurface}
+ className={cn(
+ "relative min-h-0 flex-1 overflow-hidden",
+ dragging ? "cursor-grabbing" : "cursor-grab",
+ )}
+ style={{ touchAction: "none" }}
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={endGesture}
+ onPointerLeave={clearFocus}
+ onPointerCancel={clearFocus}
+ data-testid="timeline-dense-surface"
+ >
+ {/* The row layer clips its own rows. A row straddling the bottom edge
+ is real and should be drawn, but it must not become overflow on the
+ surface β€” a map has no scrollable extent. */}
+ <div
+ className="absolute inset-0 overflow-hidden"
+ data-testid="timeline-dense-content"
+ >
+ <div
+ className="pointer-events-none absolute inset-y-0"
+ style={{ left: `${railWidth}px`, width: `${laneWidth}px` }}
+ >
+ {result.ticks.map((tick) => (
+ <div
+ key={tick.realMs}
+ className="border-border/40 absolute inset-y-0 border-l"
+ style={{ left: `${tick.x}px` }}
+ />
+ ))}
+ {result.gaps.map((gap) => (
+ <div
+ key={`${gap.x}-${gap.durationMs}`}
+ className="bg-muted border-border-contrast absolute inset-y-0 border-x border-dashed"
+ style={{ left: `${gap.x}px`, width: `${gap.width}px` }}
+ title={`${gap.label} of idle time, collapsed`}
+ />
+ ))}
+ </div>
+
+ {result.nodes.map((node) => {
+ const y = (node.index - current.rows.start) * rowHeight;
+ if (y + rowHeight < 0 || y > surfaceHeight) return null;
+
+ const isFocused = node.index === focusIndex;
+ const isSelected = node.index === selectedIndex;
+ const typeColor = TYPE_COLOR[node.type] ?? FALLBACK_COLOR;
+
+ return (
+ <div
+ key={node.id}
+ className={cn(
+ "absolute inset-x-0",
+ // At 4px a tint is not enough to find yourself by, so the
+ // hovered row takes a full-width accent wash.
+ isSelected && "bg-primary-accent/20",
+ isFocused && !isSelected && "bg-primary-accent/15",
+ )}
+ style={{ top: `${y}px`, height: `${rowHeight}px` }}
+ onClick={() => setSelectedIndex(node.index)}
+ onDoubleClick={() => focusRow(node.index)}
+ >
+ <GutterContent
+ node={node}
+ width={railWidth}
+ rowHeight={rowHeight}
+ barHeight={barHeight}
+ showName={namesVisible}
+ />
+
+ <div
+ className="absolute inset-y-0 overflow-hidden"
+ style={{ left: `${railWidth}px`, width: `${laneWidth}px` }}
+ >
+ {/* A span outside the time window is clamped to the lane edge
+ by layout(). Drawing it as a bar stacked every out-of-view
+ span into a column of marks that corresponds to nothing β€”
+ so it becomes a caret at the edge it lies beyond, and the
+ row itself stays for hover and selection. */}
+ {node.offscreen ? (
+ <div
+ className={cn(
+ "absolute w-[2px] opacity-40",
+ barColor === "type"
+ ? typeColor
+ : "bg-muted-foreground/60",
+ )}
+ style={{
+ left: node.x <= 0 ? "0px" : undefined,
+ right: node.x <= 0 ? undefined : "0px",
+ top: `${Math.max((rowHeight - barHeight) / 2, 0)}px`,
+ height: `${barHeight}px`,
+ }}
+ title={`Outside the time window β€” starts at ${formatDurationMs(node.startMs)}`}
+ data-testid="timeline-dense-offscreen"
+ />
+ ) : (
+ <div
+ className={cn(
+ "absolute rounded-[1px]",
+ barColor === "type"
+ ? typeColor
+ : "bg-muted-foreground/60",
+ (isFocused || isSelected) && "bg-primary-accent",
+ )}
+ style={{
+ left: `${node.x}px`,
+ width: `${node.width}px`,
+ top: `${Math.max((rowHeight - barHeight) / 2, 0)}px`,
+ height: `${barHeight}px`,
+ }}
+ data-testid="timeline-dense-bar"
+ />
+ )}
+ {/* Text comes back on its own as the rows grow β€” and it goes
+ on whichever side layout() measured room for, rather than
+ always after the bar, which clipped a full-width bar's
+ label at the lane edge. */}
+ {presentation === "labelled" &&
+ node.label &&
+ !node.offscreen &&
+ node.labelPlacement !== "hidden" ? (
+ <span
+ className={cn(
+ "absolute whitespace-nowrap",
+ node.labelPlacement === "inside"
+ ? "text-foreground"
+ : "text-muted-foreground",
+ )}
+ style={{
+ left: `${node.labelX}px`,
+ maxWidth: `${Math.max(laneWidth - node.labelX, 0)}px`,
+ top: `${Math.max((rowHeight - 12) / 2, 0)}px`,
+ fontSize: "10px",
+ }}
+ >
+ {node.label}
+ </span>
+ ) : null}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+
+ {/* Peek: the same gutter content, floating OVER the chart. The bars keep
+ their geometry, so looking at the names never moves what you are
+ looking at. */}
+ {peekWidth > 0 ? (
+ <div
+ className="border-border bg-background/95 absolute inset-y-0 left-0 overflow-hidden border-r backdrop-blur-[2px]"
+ style={{ width: `${peekWidth}px` }}
+ data-testid="timeline-dense-peek"
+ >
+ {result.nodes.map((node) => {
+ const y = (node.index - current.rows.start) * rowHeight;
+ if (y + rowHeight < 0 || y > surfaceHeight) return null;
+ return (
+ <div
+ key={node.id}
+ className={cn(
+ "absolute inset-x-0",
+ node.index === selectedIndex && "bg-primary-accent/20",
+ node.index === focusIndex &&
+ node.index !== selectedIndex &&
+ "bg-primary-accent/15",
+ )}
+ style={{ top: `${y}px`, height: `${rowHeight}px` }}
+ >
+ <GutterContent
+ node={node}
+ width={peekWidth}
+ rowHeight={rowHeight}
+ barHeight={barHeight}
+ showName
+ />
+ </div>
+ );
+ })}
+ </div>
+ ) : null}
+
+ {/* The tooltip is what names a row when the gutter cannot. */}
+ {focused && pointerPos && !dragging && pointerPos.x > gutterWidth ? (
+ <div
+ className="border-border bg-background text-foreground pointer-events-none absolute z-10 flex max-w-[90%] items-center gap-1 rounded border px-1.5 py-1 shadow-md"
+ style={{
+ left:
+ pointerPos.x > box.width * 0.55
+ ? undefined
+ : `${Math.round(pointerPos.x + 12)}px`,
+ right:
+ pointerPos.x > box.width * 0.55
+ ? `${Math.round(Math.max(box.width - pointerPos.x + 12, 4))}px`
+ : undefined,
+ top: `${Math.round(
+ Math.min(
+ Math.max(pointerPos.y + 12, 2),
+ Math.max(surfaceHeight - 26, 2),
+ ),
+ )}px`,
+ fontSize: "10px",
+ }}
+ data-testid="timeline-dense-tooltip"
+ >
+ <span
+ className={cn(
+ "h-2 w-2 shrink-0 rounded-[1px]",
+ TYPE_COLOR[focused.type] ?? FALLBACK_COLOR,
+ )}
+ />
+ <span className="truncate" title={focused.name}>
+ {focused.name}
+ </span>
+ <span className="text-muted-foreground shrink-0">
+ {focused.durationMs == null
+ ? "β€”"
+ : formatDurationMs(focused.durationMs)}
+ </span>
+ <span className="text-muted-foreground shrink-0">
+ @{formatDurationMs(focused.startMs)}
+ </span>
+ </div>
+ ) : null}
+ </div>
+
+ {showReadout ? (
+ <div
+ className="border-border text-muted-foreground flex shrink-0 items-center gap-2 overflow-hidden border-t px-1 whitespace-nowrap"
+ style={{ height: `${READOUT_HEIGHT}px`, fontSize: "10px" }}
+ data-testid="timeline-dense-readout"
+ >
+ <span>
+ {box.width}Γ—{box.height} Β· lane {laneWidth}
+ </span>
+ <span data-testid="dense-rowheight">
+ {rowHeight.toFixed(1)}px rows ({presentation})
+ </span>
+ <span data-testid="dense-rows">
+ rows {current.rows.start.toFixed(1)}–
+ {(current.rows.start + current.rows.count).toFixed(1)} of{" "}
+ {prepared.rows.length}
+ </span>
+ <span>{result.pxPerMs.toFixed(3)} px/ms</span>
+ <span>{fitted ? "fitted" : "zoomed"}</span>
+ </div>
+ ) : null}
+ </div>
+ );
+}
+
+/**
+ * The left side of one row: type square when closed, and the production gutter's
+ * own vocabulary when open β€” connector rails, the observation's ItemBadge icon,
+ * its name, indented by depth. Shared by the in-flow rail and the peek overlay so
+ * the two cannot drift apart.
+ */
+function GutterContent({
+ node,
+ width,
+ rowHeight,
+ barHeight,
+ showName,
+}: {
+ node: PositionedNode;
+ width: number;
+ rowHeight: number;
+ barHeight: number;
+ showName: boolean;
+}) {
+ const depth = Math.min(node.depth, RAIL_MAX_DEPTH);
+ const squareSize = Math.max(Math.min(barHeight, 6), 2);
+ const indent = showName ? depth * GUTTER_INDENT : depth * RAIL_INDENT + 1;
+ const typeColor = TYPE_COLOR[node.type] ?? FALLBACK_COLOR;
+
+ return (
+ <div
+ className="absolute inset-y-0 overflow-hidden"
+ style={{ width: `${width}px` }}
+ >
+ {showName
+ ? node.treeLines
+ .slice(0, depth)
+ .map((continues, level) =>
+ continues ? (
+ <div
+ key={level}
+ className="bg-border-contrast absolute inset-y-0 w-px"
+ style={{ left: `${level * GUTTER_INDENT + 5}px` }}
+ />
+ ) : null,
+ )
+ : null}
+ {showName && depth > 0 ? (
+ <>
+ <div
+ className={cn(
+ "bg-border-contrast absolute top-0 w-px",
+ node.isLastSibling ? "h-1/2" : "bottom-0",
+ )}
+ style={{ left: `${(depth - 1) * GUTTER_INDENT + 5}px` }}
+ />
+ <div
+ className="bg-border-contrast absolute top-1/2 h-px"
+ style={{
+ left: `${(depth - 1) * GUTTER_INDENT + 5}px`,
+ width: `${GUTTER_INDENT}px`,
+ }}
+ />
+ </>
+ ) : null}
+ {showName ? (
+ <div
+ className="absolute flex items-center gap-1 overflow-hidden"
+ style={{
+ left: `${indent + 6}px`,
+ right: "2px",
+ top: `${Math.max((rowHeight - 16) / 2, 0)}px`,
+ height: "16px",
+ }}
+ >
+ <span className="shrink-0">
+ <ItemBadge type={node.type as LangfuseItemType} isSmall />
+ </span>
+ <span
+ className="text-foreground truncate"
+ style={{ fontSize: "10px" }}
+ title={node.name}
+ >
+ {node.name}
+ </span>
+ </div>
+ ) : (
+ <div
+ className={cn("absolute rounded-[1px]", typeColor)}
+ style={{
+ left: `${indent}px`,
+ top: `${Math.max((rowHeight - squareSize) / 2, 0)}px`,
+ width: `${squareSize}px`,
+ height: `${squareSize}px`,
+ }}
+ />
+ )}
+ </div>
+ );
+}
+
+function ToolbarButton({
+ label,
+ onClick,
+ children,
+}: {
+ label: string;
+ onClick: () => void;
+ children: ReactNode;
+}) {
+ return (
+ <button
+ type="button"
+ aria-label={label}
+ title={label}
+ onClick={onClick}
+ className="hover:bg-muted flex h-4 w-4 shrink-0 items-center justify-center rounded"
+ >
+ {children}
+ </button>
+ );
+}
diff --git a/web/src/features/traces/fns/timeline/__tests__/timelineV2.fixtures.ts b/web/src/features/traces/fns/timeline/__tests__/timelineV2.fixtures.ts
index f5f69d2b4b..343cdeb2fc 100644
--- a/web/src/features/traces/fns/timeline/__tests__/timelineV2.fixtures.ts
+++ b/web/src/features/traces/fns/timeline/__tests__/timelineV2.fixtures.ts
@@ -85,12 +85,51 @@ export const deepNesting = (levels = 12): LayoutNode[] => {
return build([child!]);
};
+/**
+ * The observation types a real agent trace actually contains, in roughly the
+ * proportions you see one: mostly spans and model calls, with tools, retrievers
+ * and the occasional guardrail. Generated traces used to be all SPAN and
+ * GENERATION, which made anything colour-coded by type look like it was not
+ * colour-coded at all.
+ */
+const REALISTIC_TYPES = [
+ "SPAN",
+ "GENERATION",
+ "SPAN",
+ "TOOL",
+ "GENERATION",
+ "CHAIN",
+ "SPAN",
+ "RETRIEVER",
+ "GENERATION",
+ "EMBEDDING",
+ "SPAN",
+ "AGENT",
+ "GENERATION",
+ "EVENT",
+ "SPAN",
+ "GUARDRAIL",
+] as const;
+
+const NAME_BY_TYPE: Record<string, string> = {
+ SPAN: "step",
+ GENERATION: "openai.chat",
+ TOOL: "stripe.refund",
+ CHAIN: "sequence",
+ RETRIEVER: "vector-search",
+ EMBEDDING: "embed-query",
+ AGENT: "planner",
+ EVENT: "checkpoint",
+ GUARDRAIL: "output-guard",
+};
+
/** A root plus `count - 1` descendants in a balanced arity-6 tree. */
export const manySpans = (count: number): LayoutNode[] => {
const random = seededRandom(count);
const totalMs = 24_000;
const root: SpanSpec = {
name: "agent-run",
+ type: "AGENT",
startMs: 0,
durationMs: totalMs,
children: [],
@@ -108,9 +147,10 @@ export const manySpans = (count: number): LayoutNode[] => {
random() * Math.max(parent.startMs + parentDuration - startMs, 2),
),
);
+ const type = REALISTIC_TYPES[i % REALISTIC_TYPES.length]!;
const spec: SpanSpec = {
- name: i % 4 === 0 ? `openai.chat.${i}` : `step-${i}`,
- type: i % 4 === 0 ? "GENERATION" : "SPAN",
+ name: `${NAME_BY_TYPE[type] ?? "step"}-${i}`,
+ type,
startMs,
durationMs,
children: [],
diff --git a/web/src/features/traces/fns/timeline/focusLens.clienttest.ts b/web/src/features/traces/fns/timeline/focusLens.clienttest.ts
new file mode 100644
index 0000000000..5ce0e55836
--- /dev/null
+++ b/web/src/features/traces/fns/timeline/focusLens.clienttest.ts
@@ -0,0 +1,117 @@
+import { describe, expect, it } from "vitest";
+import { applyFocusLens, rowIndexAtY } from "./focusLens";
+
+describe("applyFocusLens", () => {
+ const total = 600;
+ const rowCount = 150;
+
+ it("always sums to the height it was given, lens or no lens", () => {
+ const sum = (rows: ReturnType<typeof applyFocusLens>) =>
+ rows.reduce((acc, row) => acc + row.height, 0);
+
+ const resting = applyFocusLens({
+ rowCount,
+ totalHeight: total,
+ focusIndex: null,
+ radius: 12,
+ magnification: 8,
+ });
+ expect(sum(resting)).toBeCloseTo(total, 6);
+ expect(resting.every((row) => row.height === total / rowCount)).toBe(true);
+
+ for (const focusIndex of [0, 1, 74, 148, rowCount - 1]) {
+ const lensed = applyFocusLens({
+ rowCount,
+ totalHeight: total,
+ focusIndex,
+ radius: 12,
+ magnification: 8,
+ });
+ // This is the no-scroll invariant: magnified rows can only borrow.
+ expect(sum(lensed)).toBeCloseTo(total, 6);
+ expect(lensed[focusIndex]!.height).toBeGreaterThan(total / rowCount);
+ expect(lensed[0]!.y).toBe(0);
+ for (const row of lensed) expect(Number.isFinite(row.height)).toBe(true);
+ }
+ });
+
+ it("tapers off with distance and leaves far rows untouched", () => {
+ const rows = applyFocusLens({
+ rowCount,
+ totalHeight: total,
+ focusIndex: 75,
+ radius: 12,
+ magnification: 8,
+ });
+
+ // Monotonically smaller as you walk away from the focus, then flat.
+ expect(rows[75]!.height).toBeGreaterThan(rows[78]!.height);
+ expect(rows[78]!.height).toBeGreaterThan(rows[84]!.height);
+ expect(rows[87]!.magnification).toBe(1);
+ expect(rows[10]!.height).toBeCloseTo(rows[140]!.height, 6);
+ });
+
+ it("is total on degenerate input", () => {
+ expect(
+ applyFocusLens({
+ rowCount: 0,
+ totalHeight: 600,
+ focusIndex: 3,
+ radius: 5,
+ magnification: 4,
+ }),
+ ).toEqual([]);
+
+ for (const rows of [
+ applyFocusLens({
+ rowCount: 5,
+ totalHeight: 0,
+ focusIndex: 2,
+ radius: 2,
+ magnification: 4,
+ }),
+ applyFocusLens({
+ rowCount: 5,
+ totalHeight: NaN,
+ focusIndex: NaN,
+ radius: NaN,
+ magnification: NaN,
+ }),
+ // Out-of-range focus clamps rather than producing a hole.
+ applyFocusLens({
+ rowCount: 5,
+ totalHeight: 100,
+ focusIndex: 99,
+ radius: 0,
+ magnification: 4,
+ }),
+ ]) {
+ expect(rows).toHaveLength(5);
+ for (const row of rows) {
+ expect(Number.isFinite(row.height)).toBe(true);
+ expect(Number.isFinite(row.y)).toBe(true);
+ }
+ }
+ });
+});
+
+describe("rowIndexAtY", () => {
+ it("finds the row under a pointer through a distorted layout", () => {
+ const rows = applyFocusLens({
+ rowCount: 150,
+ totalHeight: 600,
+ focusIndex: 75,
+ radius: 12,
+ magnification: 8,
+ });
+
+ expect(rowIndexAtY(rows, -1)).toBeNull();
+ expect(rowIndexAtY(rows, 0)).toBe(0);
+ expect(rowIndexAtY(rows, 600.5)).toBeNull();
+ // The row reported for its own midpoint is itself, magnified or not.
+ for (const index of [0, 40, 75, 76, 149]) {
+ const row = rows[index]!;
+ expect(rowIndexAtY(rows, row.y + row.height / 2)).toBe(index);
+ }
+ });
+});
diff --git a/web/src/features/traces/fns/timeline/focusLens.ts b/web/src/features/traces/fns/timeline/focusLens.ts
new file mode 100644
index 0000000000..f48a06a071
--- /dev/null
+++ b/web/src/features/traces/fns/timeline/focusLens.ts
@@ -0,0 +1,131 @@
+/**
+ * A focus+context lens over a list of rows β€” GROUNDWORK, not in use.
+ *
+ * The idea: rows near the pointer expand to a readable height while the rest
+ * give up their space, so the total never changes and nothing scrolls. Dragging
+ * a finger down the trace moves the lens through it. The maths hold β€” heights
+ * are weight-normalised, so they sum to exactly the height given at any
+ * magnification, which is the property that keeps it scroll-free.
+ *
+ * It is deliberately NOT wired into the renderer. Hit-testing a fisheye needs
+ * the transform to be invertible: test in distorted space and the lens feeds on
+ * its own output (the row moves out from under the cursor); test in resting
+ * space and the row that expands is not the one under the cursor. Neither is
+ * acceptable, and absolutely-positioned rows are the wrong substrate for the
+ * analytic inverse. This is the starting point for that spike, on a canvas
+ * surface where the inverse is natural.
+ *
+ * Uniform rows do have an analytic inverse β€” see `rowIndexAtOffset` in
+ * viewport.ts, which is what the renderer actually uses.
+ */
+
+const finite = (value: number, fallback: number) =>
+ Number.isFinite(value) ? value : fallback;
+
+const clamp = (value: number, min: number, max: number) =>
+ Math.min(Math.max(value, min), max);
+
+export type LensRow = {
+ index: number;
+ y: number;
+ height: number;
+ /** 1 = untouched by the lens; higher = magnified. */
+ magnification: number;
+};
+
+/**
+ * Focus+context lens over a fixed total height.
+ *
+ * Heights are assigned by weight and then normalised to `totalHeight`, so the
+ * sum is exactly the height we were given no matter how strong the lens is.
+ * That is the property that keeps it scroll-free: the magnified rows can only
+ * borrow their space from the rows furthest from the focus.
+ *
+ * `focusIndex: null` is the resting state β€” uniform rows, no lens.
+ */
+export function applyFocusLens(input: {
+ rowCount: number;
+ /** The height the rows must sum to. */
+ totalHeight: number;
+ focusIndex: number | null;
+ /** Rows either side of the focus the lens reaches. */
+ radius: number;
+ /** How many times its share the focused row takes. */
+ magnification: number;
+}): LensRow[] {
+ const rowCount = Math.max(Math.floor(finite(input.rowCount, 0)), 0);
+ if (rowCount === 0) return [];
+
+ const totalHeight = Math.max(finite(input.totalHeight, 0), 0);
+ const uniform = totalHeight / rowCount;
+
+ const focusIndex =
+ input.focusIndex == null
+ ? null
+ : clamp(Math.round(finite(input.focusIndex, 0)), 0, rowCount - 1);
+ const radius = Math.max(finite(input.radius, 0), 0);
+ const magnification = Math.max(finite(input.magnification, 1), 1);
+
+ if (focusIndex == null || magnification === 1) {
+ return Array.from({ length: rowCount }, (_, index) => ({
+ index,
+ y: index * uniform,
+ height: uniform,
+ magnification: 1,
+ }));
+ }
+
+ // Raised-cosine falloff: the lens has no edge to catch the eye on, which is
+ // what makes dragging through it feel like a lens rather than a moving block.
+ const weights = new Array<number>(rowCount);
+ let totalWeight = 0;
+ for (let index = 0; index < rowCount; index++) {
+ const distance = Math.abs(index - focusIndex);
+ const falloff =
+ radius <= 0
+ ? distance === 0
+ ? 1
+ : 0
+ : distance >= radius
+ ? 0
+ : 0.5 * (1 + Math.cos((Math.PI * distance) / radius));
+ const weight = 1 + (magnification - 1) * falloff;
+ weights[index] = weight;
+ totalWeight += weight;
+ }
+
+ const rows: LensRow[] = new Array(rowCount);
+ let y = 0;
+ for (let index = 0; index < rowCount; index++) {
+ const height =
+ totalWeight > 0 ? (totalHeight * weights[index]!) / totalWeight : 0;
+ rows[index] = { index, y, height, magnification: weights[index]! };
+ y += height;
+ }
+ return rows;
+}
+
+/**
+ * Which row a pointer at `y` is over, given lens-distorted row heights.
+ * Binary search: the lens recomputes on every pointer move, so this must not
+ * walk the list.
+ */
+export function rowIndexAtY(
+ rows: readonly LensRow[],
+ y: number,
+): number | null {
+ if (rows.length === 0) return null;
+ const target = finite(y, 0);
+ if (target < 0) return null;
+
+ let low = 0;
+ let high = rows.length - 1;
+ while (low <= high) {
+ const mid = (low + high) >> 1;
+ const row = rows[mid]!;
+ if (target < row.y) high = mid - 1;
+ else if (target >= row.y + row.height) low = mid + 1;
+ else return mid;
+ }
+ return null;
+}
diff --git a/web/src/features/traces/fns/timeline/viewport.clienttest.ts b/web/src/features/traces/fns/timeline/viewport.clienttest.ts
new file mode 100644
index 0000000000..c5c5bdbcb9
--- /dev/null
+++ b/web/src/features/traces/fns/timeline/viewport.clienttest.ts
@@ -0,0 +1,303 @@
+import { describe, expect, it } from "vitest";
+import { traceSpaceOf } from "./viewTransform";
+import {
+ HUMAN_ROW_HEIGHT,
+ MAX_ROW_HEIGHT,
+ MIN_ROW_HEIGHT,
+ clampViewport,
+ fitViewport,
+ focusViewport,
+ isViewportFitted,
+ panViewport,
+ rowHeightOf,
+ viewportsEqual,
+ interpolateViewport,
+ visibleRowRange,
+ zoomViewport,
+ type Viewport,
+} from "./viewport";
+
+// 600px of rows over a 24s trace, one row per span.
+const limits = {
+ traceSpace: traceSpaceOf(24_000),
+ rowCount: 500,
+ boxHeight: 600,
+};
+const BOX_WIDTH = 340;
+
+describe("viewport", () => {
+ it("fits to the densest row window the height allows", () => {
+ const fitted = fitViewport(limits);
+ // 600px at the 4px floor shows 150 of the 500 rows; the rest is panned to.
+ expect(fitted.rows.count).toBe(limits.boxHeight / MIN_ROW_HEIGHT);
+ expect(fitted.rows.start).toBe(0);
+ expect(rowHeightOf(fitted, limits.boxHeight)).toBe(MIN_ROW_HEIGHT);
+ expect(fitted.time).toEqual(limits.traceSpace);
+ expect(isViewportFitted(fitted, limits)).toBe(true);
+
+ // A trace that fits entirely shows every row and still floors at 4px.
+ const forty = { ...limits, rowCount: 40 };
+ expect(fitViewport(forty).rows.count).toBe(40);
+ expect(rowHeightOf(fitViewport(forty), 600)).toBe(15);
+
+ // A SHORT trace must not stretch its rows to fill the box: the window
+ // over-hangs the content instead, so the rows cap at the human height and
+ // the leftover space stays empty. Three rows in 600px are 26px, not 200px.
+ for (const rowCount of [1, 3, 12]) {
+ const short = { ...limits, rowCount };
+ const height = rowHeightOf(fitViewport(short), 600);
+ expect(height).toBeLessThanOrEqual(HUMAN_ROW_HEIGHT + 0.001);
+ expect(height).toBeCloseTo(HUMAN_ROW_HEIGHT, 6);
+ // Nothing to pan to when the whole trace is on screen.
+ expect(fitViewport(short).rows.start).toBe(0);
+ }
+
+ // Zooming in can still take rows past the resting cap, up to the ceiling.
+ const short = { ...limits, rowCount: 3 };
+ const zoomedIn = zoomViewport(fitViewport(short), short, {
+ factor: 100,
+ xRatio: 0.5,
+ yRatio: 0.5,
+ });
+ expect(rowHeightOf(zoomedIn, 600)).toBeCloseTo(MAX_ROW_HEIGHT, 6);
+ });
+
+ it("zooms both axes about the anchor and holds the content under it", () => {
+ const zoomed = zoomViewport(fitViewport(limits), limits, {
+ factor: 2,
+ xRatio: 0.5,
+ yRatio: 0.5,
+ });
+
+ // Time halves about the midpoint...
+ expect(zoomed.time.duration).toBeCloseTo(12_000, 6);
+ expect(zoomed.time.start).toBeCloseTo(6_000, 6);
+ // ...and so does the row window, so the rows get twice as tall.
+ expect(zoomed.rows.count).toBeCloseTo(75, 6);
+ expect(rowHeightOf(zoomed, limits.boxHeight)).toBeCloseTo(8, 6);
+ expect(isViewportFitted(zoomed, limits)).toBe(false);
+
+ // The row under the anchor stays under the anchor.
+ const before = fitViewport(limits);
+ const anchorRowBefore = before.rows.start + before.rows.count * 0.25;
+ const anchored = zoomViewport(before, limits, {
+ factor: 3,
+ xRatio: 0.25,
+ yRatio: 0.25,
+ });
+ expect(anchored.rows.start + anchored.rows.count * 0.25).toBeCloseTo(
+ anchorRowBefore,
+ 6,
+ );
+ });
+
+ it("clamps row height between the floor and the ceiling", () => {
+ const deep = zoomViewport(fitViewport(limits), limits, {
+ factor: 1_000,
+ xRatio: 0.5,
+ yRatio: 0.5,
+ });
+ expect(rowHeightOf(deep, limits.boxHeight)).toBeCloseTo(MAX_ROW_HEIGHT, 6);
+
+ const out = zoomViewport(deep, limits, {
+ factor: 0.0001,
+ xRatio: 0.5,
+ yRatio: 0.5,
+ });
+ expect(rowHeightOf(out, limits.boxHeight)).toBeCloseTo(MIN_ROW_HEIGHT, 6);
+ expect(out.time.duration).toBeCloseTo(limits.traceSpace.duration, 6);
+ });
+
+ it("pans both axes and cannot leave the content", () => {
+ const zoomed = zoomViewport(fitViewport(limits), limits, {
+ factor: 4,
+ xRatio: 0.5,
+ yRatio: 0.5,
+ });
+
+ const panned = panViewport(zoomed, limits, {
+ dxPx: -50,
+ dyPx: -80,
+ boxWidth: BOX_WIDTH,
+ });
+ expect(panned.time.start).toBeGreaterThan(zoomed.time.start);
+ expect(panned.rows.start).toBeGreaterThan(zoomed.rows.start);
+ // Zoom is untouched by a pan.
+ expect(panned.time.duration).toBeCloseTo(zoomed.time.duration, 6);
+ expect(panned.rows.count).toBeCloseTo(zoomed.rows.count, 6);
+
+ // Dragging past either end stops at the end rather than running off.
+ const overshot = panViewport(zoomed, limits, {
+ dxPx: -100_000,
+ dyPx: -100_000,
+ boxWidth: BOX_WIDTH,
+ });
+ expect(overshot.rows.start + overshot.rows.count).toBeCloseTo(
+ limits.rowCount,
+ 6,
+ );
+ expect(overshot.time.start + overshot.time.duration).toBeCloseTo(
+ limits.traceSpace.duration,
+ 6,
+ );
+ const backAtStart = panViewport(zoomed, limits, {
+ dxPx: 100_000,
+ dyPx: 100_000,
+ boxWidth: BOX_WIDTH,
+ });
+ expect(backAtStart.rows.start).toBe(0);
+ expect(backAtStart.time.start).toBe(0);
+ });
+
+ it("focuses one element on both axes at a readable row height", () => {
+ const focused = focusViewport(limits, {
+ rowIndex: 300,
+ startMs: 10_000,
+ durationMs: 400,
+ });
+
+ // Rows land at the human height, with the target centred.
+ expect(rowHeightOf(focused, limits.boxHeight)).toBeCloseTo(
+ HUMAN_ROW_HEIGHT,
+ 6,
+ );
+ expect(focused.rows.start + focused.rows.count / 2).toBeCloseTo(300.5, 6);
+ // And the time window is the span plus breathing room, not the whole trace.
+ expect(focused.time.start).toBeCloseTo(9_900, 6);
+ expect(focused.time.duration).toBeCloseTo(600, 6);
+
+ // A zero-duration span still gets a usable window instead of a collapse.
+ const instant = focusViewport(limits, {
+ rowIndex: 0,
+ startMs: 5_000,
+ durationMs: 0,
+ });
+ expect(instant.time.duration).toBeGreaterThan(0);
+ expect(instant.rows.start).toBe(0);
+
+ // Focusing the last row keeps the window inside the content.
+ const last = focusViewport(limits, {
+ rowIndex: 499,
+ startMs: 23_000,
+ durationMs: 100,
+ });
+ expect(last.rows.start + last.rows.count).toBeLessThanOrEqual(
+ limits.rowCount + 0.001,
+ );
+ });
+
+ it("windows the rows it renders", () => {
+ const zoomed = zoomViewport(fitViewport(limits), limits, {
+ factor: 8,
+ xRatio: 0.5,
+ yRatio: 0.5,
+ });
+ const range = visibleRowRange(zoomed, limits.rowCount);
+ expect(range.endIndex - range.startIndex + 1).toBeLessThan(30);
+ expect(range.startIndex).toBeGreaterThanOrEqual(0);
+ expect(range.endIndex).toBeLessThan(limits.rowCount);
+
+ expect(visibleRowRange(fitViewport(limits), 0)).toEqual({
+ startIndex: 0,
+ endIndex: -1,
+ });
+ });
+
+ it("reports whether a gesture actually moved the window", () => {
+ const fitted = fitViewport(limits);
+ expect(viewportsEqual(fitted, fitViewport(limits))).toBe(true);
+
+ // Panning up at the very top is clamped away, so nothing moved β€” that is
+ // what lets the surface hand the scroll back to the page instead of eating it.
+ const pinnedTop = panViewport(fitted, limits, {
+ dxPx: 0,
+ dyPx: 200,
+ boxWidth: BOX_WIDTH,
+ });
+ expect(viewportsEqual(pinnedTop, fitted)).toBe(true);
+
+ const zoomed = zoomViewport(fitted, limits, {
+ factor: 2,
+ xRatio: 0.5,
+ yRatio: 0.5,
+ });
+ expect(viewportsEqual(zoomed, fitted)).toBe(false);
+ const moved = panViewport(zoomed, limits, {
+ dxPx: 0,
+ dyPx: -40,
+ boxWidth: BOX_WIDTH,
+ });
+ expect(viewportsEqual(moved, zoomed)).toBe(false);
+ });
+
+ it("interpolates a focus geometrically on the scales", () => {
+ const from = fitViewport(limits);
+ const to = focusViewport(limits, {
+ rowIndex: 300,
+ startMs: 10_000,
+ durationMs: 400,
+ });
+
+ expect(interpolateViewport(from, to, 0)).toEqual(from);
+ const landed = interpolateViewport(from, to, 1);
+ expect(landed.time.duration).toBeCloseTo(to.time.duration, 3);
+ expect(landed.rows.count).toBeCloseTo(to.rows.count, 3);
+
+ // Halfway is the geometric mean of the two scales, not the arithmetic one β€”
+ // a linear tween crawls at the wide end and then lurches.
+ const half = interpolateViewport(from, to, 0.5);
+ expect(half.time.duration).toBeCloseTo(
+ Math.sqrt(from.time.duration * to.time.duration),
+ 3,
+ );
+ expect(half.rows.count).toBeCloseTo(
+ Math.sqrt(from.rows.count * to.rows.count),
+ 3,
+ );
+
+ // Monotone, so the animation never doubles back on itself.
+ let previous = from.time.duration;
+ for (const t of [0.2, 0.4, 0.6, 0.8, 1]) {
+ const step = interpolateViewport(from, to, t).time.duration;
+ expect(step).toBeLessThan(previous);
+ previous = step;
+ }
+
+ for (const t of [NaN, -1, 2]) {
+ const step = interpolateViewport(from, to, t);
+ expect(Number.isFinite(step.time.duration)).toBe(true);
+ expect(Number.isFinite(step.rows.count)).toBe(true);
+ }
+ });
+
+ it("is total on degenerate input", () => {
+ const degenerate = [
+ { traceSpace: traceSpaceOf(0), rowCount: 0, boxHeight: 0 },
+ { traceSpace: traceSpaceOf(NaN), rowCount: NaN, boxHeight: NaN },
+ { traceSpace: traceSpaceOf(1_000), rowCount: 1, boxHeight: 0 },
+ ];
+
+ for (const limit of degenerate) {
+ const fitted = fitViewport(limit);
+ const nan: Viewport = {
+ time: { start: NaN, duration: NaN },
+ rows: { start: NaN, count: NaN },
+ };
+ for (const viewport of [
+ fitted,
+ clampViewport(nan, limit),
+ zoomViewport(fitted, limit, { factor: NaN, xRatio: NaN, yRatio: NaN }),
+ panViewport(fitted, limit, { dxPx: NaN, dyPx: NaN, boxWidth: NaN }),
+ focusViewport(limit, { rowIndex: NaN, startMs: NaN, durationMs: NaN }),
+ ]) {
+ expect(Number.isFinite(viewport.time.start)).toBe(true);
+ expect(Number.isFinite(viewport.time.duration)).toBe(true);
+ expect(Number.isFinite(viewport.rows.start)).toBe(true);
+ expect(Number.isFinite(viewport.rows.count)).toBe(true);
+ expect(Number.isFinite(rowHeightOf(viewport, limit.boxHeight))).toBe(
+ true,
+ );
+ }
+ }
+ });
+});
diff --git a/web/src/features/traces/fns/timeline/viewport.ts b/web/src/features/traces/fns/timeline/viewport.ts
new file mode 100644
index 0000000000..a5a26ef7de
--- /dev/null
+++ b/web/src/features/traces/fns/timeline/viewport.ts
@@ -0,0 +1,340 @@
+/**
+ * A 2D viewport over the trace, driven like a map.
+ *
+ * The one-dimensional view model (a time window) was enough while row height was
+ * a fixed, resolved value. It is not enough for a dense timeline you explore:
+ * there, zoom has to work on BOTH axes at once β€” narrowing the time window and
+ * growing the rows together β€” and you have to be able to pan anywhere.
+ *
+ * Content space is time Γ— rows:
+ * - `time` is a window in compressed ms, exactly as before.
+ * - `rows` is a window in ROW INDICES: which row sits at the top (fractional,
+ * so panning is smooth) and how many are visible. Row height is therefore
+ * `boxHeight / rows.count` β€” vertical zoom IS the visible row count, which is
+ * what makes "zoom until the rows are readable" a single number.
+ *
+ * Both axes clamp to content, so the viewport can never leave the trace, and a
+ * single `factor` drives both β€” a map does not zoom one axis at a time.
+ */
+
+import { clampView, type TimeSpan } from "./viewTransform";
+
+/** Rows never render thinner than this, so "everything visible" has a limit. */
+export const MIN_ROW_HEIGHT = 4;
+/** Nor thicker than this, so zooming in cannot end at one giant row. */
+export const MAX_ROW_HEIGHT = 40;
+/** The row height a human reads comfortably β€” what double-click aims for. */
+export const HUMAN_ROW_HEIGHT = 26;
+
+export type RowPresentation =
+ /** Bar, duration label and name. */
+ | "labelled"
+ /** Bar plus a type square. No text. */
+ | "compact"
+ /** Bar and type square only β€” no text fits. */
+ | "hairline";
+
+/** What a row can show follows from how tall it is, never the other way round. */
+export function presentationForRowHeight(rowHeight: number): RowPresentation {
+ const height = Number.isFinite(rowHeight) ? rowHeight : 0;
+ if (height >= 20) return "labelled";
+ if (height >= 10) return "compact";
+ return "hairline";
+}
+
+export type RowWindow = {
+ /** Index of the topmost visible row; fractional while panning. */
+ start: number;
+ /** How many rows are visible. */
+ count: number;
+};
+
+export type Viewport = { time: TimeSpan; rows: RowWindow };
+
+export type ViewportLimits = {
+ traceSpace: TimeSpan;
+ rowCount: number;
+ boxHeight: number;
+};
+
+const finite = (value: number, fallback: number) =>
+ Number.isFinite(value) ? value : fallback;
+
+const clamp = (value: number, min: number, max: number) =>
+ Math.min(Math.max(value, min), max);
+
+/**
+ * Widest and narrowest row windows the height allows, in rows.
+ *
+ * The window is allowed to be TALLER THAN THE CONTENT, and that is the load
+ * bearing part: three rows in a 600px box must not become three 200px rows.
+ * Expressing the ceiling as a minimum row count cannot prevent that, because
+ * you cannot show fewer rows than a trace has. Expressing it as a window that
+ * over-hangs the content can β€” three rows render at the human height and the
+ * remaining space stays empty, which is the standing decision that density must
+ * not grow into a tall box's slack.
+ *
+ * So the resting window is the row count clamped into
+ * `[height / humanHeight, height / minHeight]`:
+ * - a short trace floors at `height / 26`, so rows cap at ~26px;
+ * - a long trace ceilings at `height / 4`, so rows never go below the hairline
+ * and the rest is panned to.
+ *
+ * Exported because the vertical window depends only on the row count and the
+ * height β€” never on the width. That is what lets a caller resolve row height
+ * BEFORE deciding how wide the name gutter should be, without a cycle.
+ */
+export function rowCountBounds(limits: {
+ rowCount: number;
+ boxHeight: number;
+}): { min: number; max: number } {
+ const rowCount = Math.max(Math.floor(finite(limits.rowCount, 0)), 0);
+ const boxHeight = Math.max(finite(limits.boxHeight, 0), 0);
+ if (rowCount === 0 || boxHeight === 0) {
+ return { min: Math.max(rowCount, 1), max: Math.max(rowCount, 1) };
+ }
+ const max = clamp(
+ rowCount,
+ Math.max(boxHeight / HUMAN_ROW_HEIGHT, 1),
+ Math.max(boxHeight / MIN_ROW_HEIGHT, 1),
+ );
+ const min = clamp(boxHeight / MAX_ROW_HEIGHT, 1, max);
+ return { min, max };
+}
+
+export function fitViewport(limits: ViewportLimits): Viewport {
+ const bounds = rowCountBounds(limits);
+ return {
+ time: {
+ start: limits.traceSpace.start,
+ duration: limits.traceSpace.duration,
+ },
+ rows: { start: 0, count: bounds.max },
+ };
+}
+
+export function clampViewport(
+ viewport: Viewport,
+ limits: ViewportLimits,
+): Viewport {
+ const rowCount = Math.max(Math.floor(finite(limits.rowCount, 0)), 0);
+ const bounds = rowCountBounds(limits);
+ const count = clamp(
+ finite(viewport.rows.count, bounds.max),
+ bounds.min,
+ bounds.max,
+ );
+ const start = clamp(
+ finite(viewport.rows.start, 0),
+ 0,
+ Math.max(rowCount - count, 0),
+ );
+ return {
+ time: clampView(viewport.time, limits.traceSpace),
+ rows: { start, count },
+ };
+}
+
+/**
+ * Zoom both axes about a point in the box, given as ratios of its width and
+ * height. `factor > 1` zooms in. The content under the anchor stays under it.
+ */
+export function zoomViewport(
+ viewport: Viewport,
+ limits: ViewportLimits,
+ options: { factor: number; xRatio: number; yRatio: number },
+): Viewport {
+ const factor = finite(options.factor, 1);
+ if (factor <= 0) return clampViewport(viewport, limits);
+
+ const xRatio = clamp(finite(options.xRatio, 0.5), 0, 1);
+ const yRatio = clamp(finite(options.yRatio, 0.5), 0, 1);
+
+ const anchorMs = viewport.time.start + viewport.time.duration * xRatio;
+ const timeDuration = viewport.time.duration / factor;
+
+ const anchorRow = viewport.rows.start + viewport.rows.count * yRatio;
+ const rowsCount = viewport.rows.count / factor;
+
+ return clampViewport(
+ {
+ time: {
+ start: anchorMs - timeDuration * xRatio,
+ duration: timeDuration,
+ },
+ rows: { start: anchorRow - rowsCount * yRatio, count: rowsCount },
+ },
+ limits,
+ );
+}
+
+/** Pan by a pixel delta β€” the drag gesture, in both axes at once. */
+export function panViewport(
+ viewport: Viewport,
+ limits: ViewportLimits,
+ options: { dxPx: number; dyPx: number; boxWidth: number },
+): Viewport {
+ const boxWidth = Math.max(finite(options.boxWidth, 0), 0);
+ const boxHeight = Math.max(finite(limits.boxHeight, 0), 0);
+
+ const msPerPx = boxWidth > 0 ? viewport.time.duration / boxWidth : 0;
+ const rowsPerPx = boxHeight > 0 ? viewport.rows.count / boxHeight : 0;
+
+ return clampViewport(
+ {
+ time: {
+ start: viewport.time.start - finite(options.dxPx, 0) * msPerPx,
+ duration: viewport.time.duration,
+ },
+ rows: {
+ start: viewport.rows.start - finite(options.dyPx, 0) * rowsPerPx,
+ count: viewport.rows.count,
+ },
+ },
+ limits,
+ );
+}
+
+/**
+ * Double-click target: put one span on screen at a height a human reads, with
+ * its own time extent filling the width. Both axes move β€” that is the whole
+ * point, "focus on this element" rather than "zoom the clock".
+ */
+export function focusViewport(
+ limits: ViewportLimits,
+ target: { rowIndex: number; startMs: number; durationMs: number },
+ paddingRatio = 0.25,
+): Viewport {
+ const bounds = rowCountBounds(limits);
+ const boxHeight = Math.max(finite(limits.boxHeight, 0), 0);
+
+ const count = clamp(
+ boxHeight > 0 ? boxHeight / HUMAN_ROW_HEIGHT : bounds.min,
+ bounds.min,
+ bounds.max,
+ );
+ const rowIndex = Math.max(finite(target.rowIndex, 0), 0);
+
+ // A zero-duration span still needs a window, so fall back to a slice of the
+ // trace rather than collapsing the time axis onto it.
+ const durationMs = Math.max(finite(target.durationMs, 0), 0);
+ const fallback = limits.traceSpace.duration * 0.05;
+ const span = durationMs > 0 ? durationMs : Math.max(fallback, 1);
+ const padding = span * clamp(finite(paddingRatio, 0), 0, 2);
+
+ return clampViewport(
+ {
+ time: {
+ start: finite(target.startMs, 0) - padding,
+ duration: span + padding * 2,
+ },
+ rows: { start: rowIndex + 0.5 - count / 2, count },
+ },
+ limits,
+ );
+}
+
+/**
+ * Which row sits at a pixel offset in the box β€” the analytic inverse of the
+ * render mapping `y = (index - rows.start) * rowHeight`. Exact by construction,
+ * which is what a lens over non-uniform rows cannot offer.
+ */
+export function rowIndexAtOffset(
+ viewport: Viewport,
+ offsetY: number,
+ rowHeight: number,
+ rowCount: number,
+): number | null {
+ if (!(rowHeight > 0)) return null;
+ const index = Math.floor(
+ finite(viewport.rows.start, 0) + finite(offsetY, -1) / rowHeight,
+ );
+ const total = Math.max(Math.floor(finite(rowCount, 0)), 0);
+ return index >= 0 && index < total ? index : null;
+}
+
+/** Row height implied by the vertical window. */
+export function rowHeightOf(viewport: Viewport, boxHeight: number): number {
+ const count = Math.max(finite(viewport.rows.count, 0), 0);
+ const height = Math.max(finite(boxHeight, 0), 0);
+ return count > 0 ? height / count : 0;
+}
+
+/** Inclusive row index range to render β€” windowing falls out of the viewport. */
+export function visibleRowRange(
+ viewport: Viewport,
+ rowCount: number,
+ overscan = 2,
+): { startIndex: number; endIndex: number } {
+ const total = Math.max(Math.floor(finite(rowCount, 0)), 0);
+ if (total === 0) return { startIndex: 0, endIndex: -1 };
+ const start = Math.max(
+ Math.floor(finite(viewport.rows.start, 0)) - overscan,
+ 0,
+ );
+ const end = Math.min(
+ Math.ceil(finite(viewport.rows.start, 0) + finite(viewport.rows.count, 0)) +
+ overscan,
+ total - 1,
+ );
+ return { startIndex: start, endIndex: Math.max(end, start) };
+}
+
+/**
+ * A point on the way from one viewport to another, for animating a focus.
+ *
+ * Scales interpolate GEOMETRICALLY and offsets linearly. A linear interpolation
+ * of a duration reads wrong β€” it crawls at the wide end and then lurches β€” which
+ * is the same reason zoom is exponential in a level: halving is halving whether
+ * you are at 24s or 240ms.
+ */
+export function interpolateViewport(
+ from: Viewport,
+ to: Viewport,
+ t: number,
+): Viewport {
+ const progress = clamp(finite(t, 1), 0, 1);
+ const lerp = (a: number, b: number) =>
+ finite(a, b) + (finite(b, 0) - finite(a, b)) * progress;
+ const scaleLerp = (a: number, b: number) => {
+ const from_ = Math.max(finite(a, 1), 1e-6);
+ const to_ = Math.max(finite(b, 1), 1e-6);
+ return from_ * (to_ / from_) ** progress;
+ };
+
+ return {
+ time: {
+ start: lerp(from.time.start, to.time.start),
+ duration: scaleLerp(from.time.duration, to.time.duration),
+ },
+ rows: {
+ start: lerp(from.rows.start, to.rows.start),
+ count: scaleLerp(from.rows.count, to.rows.count),
+ },
+ };
+}
+
+/** Same window, within a pixel-ish tolerance β€” used to tell a consumed gesture
+ * from one that hit a clamp, so a trapped scroll can be handed back to the page. */
+export function viewportsEqual(a: Viewport, b: Viewport): boolean {
+ const close = (x: number, y: number, epsilon: number) =>
+ Math.abs(finite(x, 0) - finite(y, 0)) < epsilon;
+ return (
+ close(a.time.start, b.time.start, 0.001) &&
+ close(a.time.duration, b.time.duration, 0.001) &&
+ close(a.rows.start, b.rows.start, 0.0001) &&
+ close(a.rows.count, b.rows.count, 0.0001)
+ );
+}
+
+export const isViewportFitted = (
+ viewport: Viewport,
+ limits: ViewportLimits,
+): boolean => {
+ const bounds = rowCountBounds(limits);
+ return (
+ viewport.time.duration >= limits.traceSpace.duration - 0.5 &&
+ viewport.rows.count >= bounds.max - 0.001 &&
+ viewport.rows.start <= 0.001
+ );
+};