πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(trace): pure layout core for the timeline (#16124)
Nikita Kabardin91970f83d287
diff --git a/web/src/features/traces/components/TraceTimelineV2/TimelineV2.mdx b/web/src/features/traces/components/TraceTimelineV2/TimelineV2.mdxnew file mode 100644index 0000000000..e69e06613c--- /dev/null+++ b/web/src/features/traces/components/TraceTimelineV2/TimelineV2.mdx@@ -0,0 +1,199 @@+import { Canvas, Meta } from "@storybook/addon-docs/blocks";+import * as TimelineV2Stories from "./TimelineV2.stories";+import * as SizeStories from "./TimelineV2Sizes.stories";+import * as CompressionStories from "./TimelineV2Compression.stories";+import * as MobileStories from "./TimelineV2Mobile.stories";++<Meta of={TimelineV2Stories} name="Findings" />++# Size-adaptive timeline β spike findings++A throwaway renderer over a pure `layout()`, built to answer one question before+any production code moves: **does fit-to-box + zoom + time compression read+better than today's fixed 900px canvas, at every size and shape?**++**Verdict: yes, and by a wide margin.** The model holds at every cell of the+matrix. Two things it does not solve on its own are called out below: the name+gutter below ~480px, and what a collapsed gap should look like.++## What to look at, in order++1. **Sizes β Variant Matrix.** The same nine-observation trace at 320 / 480 /+ 768 / 1280 / 1920. Every bar is inside every box. Nothing scrolls sideways at+ any width. The scale readout under each cell shows the px/ms the box bought.+2. **Timeline V2 β Reporter Shape.** The exact trace from the community report,+ in the peek-width lane it was reported in. Compare against the screenshot on+ that issue.+3. **Compression β Long Tail Honest, then Long Tail Compressed.** The whole+ trade-off in two cells.+4. **Mobile β Variant Matrix.** Five takes on the gutter problem at 320px.+5. **Timeline V2 β Ten Thousand Spans.** Ctrl-scroll (or pinch) inside the+ chart to zoom; double-click a bar to fit it; double-click again to reset.++## Does the model win?++<Canvas of={SizeStories.VariantMatrix} />++At 320px the trace is whole, the axis is honest and the durations are readable.+That is the claim, and it holds without a single conditional on viewport width:+`layout()` gets the measured box and everything else follows. The 1920px cell+gets 3.37 px/ms for the same trace, from the same code path.++Where it does **not** win on its own:++- **Names.** At 320px the gutter is 127px, so `RunnableSequence` renders as+ `Runnaβ¦`. Fit-to-box fixed time, not identity. See the mobile section.+- **Zero-information cells.** All-instantaneous and missing-`endTime` traces+ render a column of dashed minimum-width markers. That is honest β there is+ genuinely no duration to draw β but a trace where nothing has an end would+ read better as a list than as a chart. Worth a Phase 2 decision, not a+ renderer change.++## Two bugs the spike caught in its own first render++Both are the exact failure class the architecture exists to remove, and both are+worth remembering for Phase 2:++1. **The frame border.** The component sized its lanes from the `box` prop while+ the actual content area was 2px narrower, so `gutter + lane` exceeded the+ viewport and produced 2px of horizontal scroll. Fixed by measuring the scroll+ viewport's own client box with a `ResizeObserver` rather than deriving it.+2. **The scrollbar.** On a platform with classic scrollbars the same arithmetic+ is wrong by another ~15px. Measuring covers both. **Phase 2 must measure the+ element that scrolls, not the element that contains it.**++## Design question 1 β mobile composition++<Canvas of={MobileStories.VariantMatrix} />++| Take | Lane | Verdict |+| --------------------------------- | ----- | ----------------------------------------------------------------------- |+| `split` β gutter beside chart | 191px | Correlation kept, names useless (`Chatβ¦`) |+| `icons` β gutter is icon + caret | 272px | Chart readable, identity gone entirely |+| `overlay` β names over the bars | 318px | Worst: name, duration and bar fight for the same pixels, depth lost |+| `stacked` β name above, bar below | 318px | **Best.** Full names, full-width chart, depth by indent, durations kept |+| `modes` β tree β timeline toggle | 318px | Honest, but correlating a name to a bar costs a mode flip |++**Recommendation: `stacked` for `pointer: coarse` / narrow boxes, `split`+above ~480px.** It is the only take that keeps all three of identity, duration+and position, and it costs only row height β which touch density was already+spending (44px). Note this moved `density`'s second axis somewhere the plan did+not anticipate: `resolveDensity` takes `lines: 1 | 2`, because a row that stacks+a name over a bar needs two text lines' worth of height.++**Density is not a function of box height.** The first revision grew rows into+the slack of a tall box (a 3-row trace got 34px rows in a 420px box); review+rejected it on sight β density is the whole point of the parent ticket, so the+box decides how many rows are visible, never how tall they are. Row height+resolves from modality and lines-per-row only: 26px fine, 44px coarse, 38px+stacked.++**Does this need a designer?** For the _choice_, no β `stacked` is clearly+ahead. For the _finish_, yes: row separation, what a selected row looks like,+and whether the type icon stays on the name line are visual calls, and the+stacked row is a new pattern in this product rather than a tweak to an existing+one.++## Design question 2 β compression on by default?++<Canvas of={CompressionStories.LongTailHonest} />++Fitted honestly, a 36.02s trace whose real work is three 40ms spans gives+0.005 px/ms: three 4px slivers pinned to the minimum bar width. This is exactly+the "36.02s root drawn as a sliver" complaint, reproduced.++<Canvas of={CompressionStories.LongTailCompressed} />++Compressed: **0.372 px/ms, a 74Γ change**, and the spans are real bars with+readable labels. Two collapsed bands cost 28px each β 29% of a 191px lane spent+saying "nothing happened here".++**Recommendation: default OFF, one click away, and auto-suggested.** Reasons:++- Compression is only ever a large win on long-tail traces. On a dense trace it+ correctly does nothing (see _Dense Trace Compressed_), so defaulting it on+ would change nothing for most traces while making a minority of traces lie.+- It genuinely misleads. A user reading proportion off a compressed axis reads+ it wrong, and that is a support cost we would be creating.+- The cheap middle path: when `layout()` reports gaps that _would_ collapse,+ offer it in place β "36.02s, 99.6% idle Β· compress?" β rather than making+ every user carry a preference.++Two things compression needs before it ships, both learned here:++- **Ticks at the gap boundaries.** Without them every nice-step tick falls+ inside a collapsed gap and the axis degrades to a lone `0ms`. With them the+ axis reads `0ms Β· 17.95s Β· 35.91s` and the visible jump across a 28px band is+ what explains the band.+- **A better band than `β―`.** The current treatment is a dashed grey column+ with a hover title. It is legible-but-mute, and 28px cannot hold `17.84s`.+ This is a small design ask.++## Performance β the React-vs-imperative call++The plan bets that vertical virtualization keeps the mounted row count low+enough that recomputing every visible bar per frame in React is affordable, so+we can adopt Sentry's 146-line space model and skip its 2447-line imperative+view manager. **The bet is correct, with three orders of magnitude to spare.**++Measured on the 10k-span story, 768Γ420 box, 486px lane:++| Measurement | Result |+| ---------------------------------------------------- | -------------------------------------- |+| Mounted bars for 10,000 rows | **20** |+| `layout()`, 40-row window, per call | **0.0070 ms** (0.0046 ms compressed) |+| Frame time, 235 frames of continuous ctrl-wheel zoom | p50 **8.3 ms**, p95 9.3 ms, max 9.4 ms |+| Frames over 16.7 ms | **0** |+| Same measurement with no zoom driven (baseline) | p50 8.3 ms, max 9.4 ms |+| Zoom range actually swept during the run | 0.02 β 486 px/ms |+| `prepareTimeline(10k)` β memoized on tree + collapse | 1.92 ms |+| `timeCompressionFor(10k)` β memoized on box width | 2.05 ms |++Frame time under continuous zoom is **indistinguishable from idle**, and the+pure math is ~0.007ms against a 16.7ms budget. Measured in Storybook's dev+build, so React is unminified and in development mode β production is faster,+making these numbers a pessimistic bound.++**Conclusion: adopt the space model, skip the view manager.** If a future shape+ever does drop frames, `layout()` is the seam an imperative write path plugs+into without redesigning anything above it β the two calls that are not cheap+(`prepareTimeline`, `timeCompressionFor`) are already memoized out of the frame+loop.++## Deviations from the Sentry originals++- **Time compression prices its label buffer at the wrong scale.** Sentry+ converts `DURATION_LABEL_BUFFER_PX = 48` to milliseconds using the+ _uncompressed_ px/ms. In a 320px lane that reserves ~5.4 seconds around each+ span of a 36s trace, and compression becomes a no-op precisely where it is+ needed most. One fixed-point step β compress with no buffer, then re-compress+ with the buffer priced at the resulting scale β takes the long-tail case from+ ~15px of legible bar to ~41px.+- **Clamping holds the zoom, not the pan.** At the right edge Sentry holds+ `trace_view.x` and shrinks the window; we hold the window and pull `x` back.+ Panning past the end should stop, not silently zoom out.+- **A plain scalar transform replaces `mat3`.** Both spaces are+ one-dimensional in time, so the matrix composition buys nothing.+- **No `gl-matrix`, no `TraceScheduler`, no DOM-ref write path.**++## What Phase 2 inherits++Pure and tested, no React: `layout()`, the four-space view model, compression,+the text measurer, density resolution. `TreeNode` already satisfies `LayoutNode`+structurally, so there is no adapter to write.++Suggested sub-issue split:++1. **Land the renderer** behind the existing timeline entry point β measured box+ β `layout()` β absolute placement, `SCALE_WIDTH` deleted, gutter/chart split,+ virtualization, playhead and selection kept working. Closes the community+ issue; its acceptance test is _Reporter Shape_ at peek width.+2. **Zoom/pan as real state** β toolbar, double-tap-to-fit, URL persistence if+ we want shareable zoom.+3. **Touch + density** β pinch, drag, the `stacked` composition below 480px,+ `pointer: coarse` resolution, and a tap equivalent for every hover-only+ affordance in `TimelineBar`.+4. **Compression, with the gap-boundary ticks and a designed band**, behind the+ suggest-in-place affordance rather than a preference.+5. **The density follow-ups** β gutter header dead space, observation names+ weighted like the trace tree.diff --git a/web/src/features/traces/components/TraceTimelineV2/TimelineV2.stories.tsx b/web/src/features/traces/components/TraceTimelineV2/TimelineV2.stories.tsxnew file mode 100644index 0000000000..9b36dc904d--- /dev/null+++ b/web/src/features/traces/components/TraceTimelineV2/TimelineV2.stories.tsx@@ -0,0 +1,468 @@+import { useState } from "react";+import { expect, userEvent, waitFor } from "storybook/test";+import preview from "../../../../../.storybook/preview";+import { TimelineV2, type TimelineV2Props } from "./TimelineV2";+import {+ TIMELINE_SHAPES,+ allInstantaneous,+ deepNesting,+ longTailTrace,+ manySpans,+ missingEndTimes,+ reporterTrace,+ singleSpan,+ threeSpans,+ zeroDurationTrace,+} from "./__tests__/timelineV2.fixtures";++const meta = preview.meta({+ component: TimelineV2,+});++/** A comfortable desktop lane; the size axis lives in TimelineV2Sizes. */+const DESKTOP = { width: 768, height: 420 };+/** Roughly the peek panel β the lane the community bug was reported in. */+const PEEK = { width: 320, height: 260 };++export const ReporterShape = meta.story({+ args: {+ roots: reporterTrace(),+ box: PEEK,+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+});++export const SingleSpan = meta.story({+ args: {+ roots: singleSpan(),+ box: DESKTOP,+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+});++export const ThreeSpans = meta.story({+ args: {+ roots: threeSpans(),+ box: DESKTOP,+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+});++export const DeepNesting = meta.story({+ args: {+ roots: deepNesting(12),+ box: DESKTOP,+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+});++export const FiveHundredSpans = meta.story({+ args: {+ roots: manySpans(500),+ box: DESKTOP,+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+});++export const TenThousandSpans = meta.story({+ args: {+ roots: manySpans(10_000),+ box: DESKTOP,+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+});++export const LongTail = meta.story({+ args: {+ roots: longTailTrace(),+ box: DESKTOP,+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+});++export const AllInstantaneous = meta.story({+ args: {+ roots: allInstantaneous(),+ box: DESKTOP,+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+});++export const MissingEndTimes = meta.story({+ args: {+ roots: missingEndTimes(),+ box: DESKTOP,+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+});++export const ZeroDuration = meta.story({+ args: {+ roots: zeroDurationTrace(),+ box: DESKTOP,+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+});++export const CoarsePointer = meta.story({+ args: {+ roots: reporterTrace(),+ box: DESKTOP,+ pointer: "coarse",+ compress: false,+ composition: "split",+ showReadout: true,+ },+});++/** Every shape in the peek-width lane β the column that matters most. */+export const VariantMatrix = meta.story({+ args: {+ roots: reporterTrace(),+ box: PEEK,+ pointer: "fine",+ compress: true,+ composition: "split",+ showReadout: true,+ },+ render: (args) => (+ <div className="flex flex-wrap gap-4">+ {Object.entries(TIMELINE_SHAPES).map(([shape, makeRoots]) => (+ <div key={shape} className="flex flex-col gap-1">+ <span className="text-muted-foreground text-xs">{shape}</span>+ <TimelineV2 {...args} roots={makeRoots()} />+ </div>+ ))}+ </div>+ ),+});++export const FitsTheBox = meta.story({+ name: "(Test) Fits The Box",+ args: {+ roots: reporterTrace(),+ box: PEEK,+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+ play: async ({ canvasElement }) => {+ const scroll = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-v2-scroll"]',+ );+ if (!scroll) throw new Error("timeline scroll container not found");++ // The invariant the community bug is about: nothing to scroll sideways to.+ await expect(scroll.scrollWidth).toBeLessThanOrEqual(scroll.clientWidth);++ const lane = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-v2-lane"]',+ );+ const bars = canvasElement.querySelectorAll<HTMLElement>(+ '[data-testid="timeline-v2-bar"]',+ );+ if (!lane) throw new Error("timeline lane not found");+ await expect(bars.length).toBeGreaterThan(0);++ const laneRect = lane.getBoundingClientRect();+ for (const bar of bars) {+ const rect = bar.getBoundingClientRect();+ await expect(rect.left).toBeGreaterThanOrEqual(laneRect.left - 0.5);+ await expect(rect.right).toBeLessThanOrEqual(laneRect.right + 0.5);+ await expect(rect.width).toBeGreaterThan(0);+ }+ },+});++export const ClickSelectsARow = meta.story({+ name: "(Test) Click Selects A Row",+ args: {+ roots: reporterTrace(),+ box: PEEK,+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+ play: async ({ canvasElement }) => {+ const scroll = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-v2-scroll"]',+ );+ const row = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-v2-content"] > div',+ );+ if (!scroll || !row) throw new Error("timeline row not found");++ // Pointer capture retargets the derived click to the capture element, so+ // capturing on pointerdown silently kills row selection. userEvent's+ // synthetic events ignore capture and cannot see that, so assert the+ // handler's contract directly: a press that does not move must not capture.+ const captured: number[] = [];+ scroll.setPointerCapture = (pointerId: number) => {+ captured.push(pointerId);+ };+ const press = (type: string, clientX: number) =>+ scroll.dispatchEvent(+ new PointerEvent(type, { pointerId: 1, clientX, bubbles: true }),+ );++ press("pointerdown", 100);+ press("pointermove", 102);+ press("pointerup", 102);+ await expect(captured).toHaveLength(0);++ press("pointerdown", 100);+ press("pointermove", 160);+ await expect(captured).toHaveLength(1);+ press("pointerup", 160);++ await userEvent.click(row);+ await waitFor(() =>+ expect(row.className).toContain("bg-primary-accent/10"),+ );+ },+});++export const DraggingMovesContentWithThePointer = meta.story({+ name: "(Test) Dragging Moves Content With The Pointer",+ args: {+ roots: reporterTrace(),+ box: PEEK,+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+ play: async ({ canvasElement }) => {+ const scroll = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-v2-scroll"]',+ );+ if (!scroll) throw new Error("timeline scroll not found");+ const readout = () =>+ canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-v2-readout"]',+ )?.textContent ?? "";+ const viewStart = () => {+ const match = /view (\d+)ms/.exec(readout());+ if (!match) throw new Error(`no view window in "${readout()}"`);+ return Number(match[1]);+ };++ // Zoom into the LAST span to start, so the window has somewhere to go in+ // both directions β zooming one that starts at the origin leaves the window+ // pinned to 0 and a leftward drag with nothing to prove.+ const bars = [+ ...canvasElement.querySelectorAll<HTMLElement>(+ '[data-testid="timeline-v2-bar"]',+ ),+ ];+ const target = bars.reduce<HTMLElement | null>(+ (latest, bar) =>+ !latest ||+ bar.getBoundingClientRect().left > latest.getBoundingClientRect().left+ ? bar+ : latest,+ null,+ );+ if (!target) throw new Error("expected a bar to double-click");+ await userEvent.dblClick(target);+ await waitFor(() => expect(viewStart()).toBeGreaterThan(0));++ const pointer = (type: string, clientX: number, pointerId = 1) =>+ scroll.dispatchEvent(+ new PointerEvent(type, { pointerId, clientX, bubbles: true }),+ );++ // Grab and drag RIGHT: the moment under the cursor has to come with it, which+ // means the window moves EARLIER. The other sign slides the bars against the+ // finger, which is the one thing a drag-to-pan must never do.+ const startedAt = viewStart();+ pointer("pointerdown", 200);+ pointer("pointermove", 260);+ pointer("pointerup", 260);+ await waitFor(() => expect(viewStart()).toBeLessThan(startedAt));++ const afterDragRight = viewStart();+ pointer("pointerdown", 260);+ pointer("pointermove", 200);+ pointer("pointerup", 200);+ await waitFor(() => expect(viewStart()).toBeGreaterThan(afterDragRight));++ // Lifting one finger of a two-finger pinch leaves the gesture live. The+ // survivor's next move must pan from where IT is, not jump by the finger+ // separation it inherited from the finger that left.+ const beforeRelease = viewStart();+ pointer("pointerdown", 100, 1);+ pointer("pointerdown", 260, 2);+ pointer("pointerup", 260, 2);+ // 1px is under the drag threshold, so re-anchored this does nothing at all;+ // inheriting the departed finger's 260 makes it a 159px pan instead.+ pointer("pointermove", 101, 1);+ await expect(viewStart()).toBe(beforeRelease);+ pointer("pointerup", 101, 1);+ },+});++/**+ * Compression and the box under the user's thumb, so a story can change either+ * one mid-zoom β both replace the coordinate space a stored view addresses.+ */+let resize: (width: number) => void = () => undefined;++function WithCompressionToggle(props: TimelineV2Props) {+ const [compress, setCompress] = useState(props.compress);+ const [width, setWidth] = useState(props.box.width);+ resize = setWidth;+ return (+ <div className="flex flex-col items-start gap-1">+ <button type="button" onClick={() => setCompress((on) => !on)}>+ toggle compression+ </button>+ <TimelineV2+ {...props}+ compress={compress}+ box={{ ...props.box, width }}+ />+ </div>+ );+}++export const CompressionChangeDropsTheView = meta.story({+ name: "(Test) Compression Change Drops The View",+ args: {+ roots: longTailTrace(),+ box: PEEK,+ pointer: "fine",+ compress: true,+ composition: "split",+ showReadout: true,+ },+ render: (args) => <WithCompressionToggle {...args} />,+ play: async ({ canvasElement }) => {+ const readout = () =>+ canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-v2-readout"]',+ )?.textContent ?? "";++ const bars = canvasElement.querySelectorAll<HTMLElement>(+ '[data-testid="timeline-v2-bar"]',+ );+ const target = bars[bars.length - 1];+ if (!target) throw new Error("expected a bar to double-click");+ // Zoom onto the last span, so the window starts well after the origin.+ await expect(readout()).toContain("view 0msβ");+ await userEvent.dblClick(target);+ await waitFor(() => expect(readout()).not.toContain("view 0msβ"));++ // A zoomed window is expressed in COMPRESSED ms. Turning compression off+ // replaces the space those numbers live in, so keeping them would draw an+ // unrelated window instead of an obviously broken one.+ const toggle = canvasElement.querySelector("button");+ if (!toggle) throw new Error("expected the compression toggle");+ await userEvent.click(toggle);+ await waitFor(() => expect(readout()).toContain("view 0msβ"));++ // A RESIZE is the same hazard: collapsed gaps are priced in physical px, so+ // a narrower box rescales the compressed space around a window that still+ // addresses the old one.+ await userEvent.click(toggle); // compression back on+ const compressedBars = canvasElement.querySelectorAll<HTMLElement>(+ '[data-testid="timeline-v2-bar"]',+ );+ const last = compressedBars[compressedBars.length - 1];+ if (!last) throw new Error("expected a bar to zoom into");+ await userEvent.dblClick(last);+ await waitFor(() => expect(readout()).not.toContain("view 0msβ"));+ resize(240);+ await waitFor(() => expect(readout()).toContain("view 0msβ"));+ },+});++export const DoubleClickingTheChevronDoesNotZoom = meta.story({+ name: "(Test) Double Clicking The Chevron Does Not Zoom",+ args: {+ roots: reporterTrace(),+ box: PEEK,+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+ play: async ({ canvasElement }) => {+ const readout = () =>+ canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-v2-readout"]',+ )?.textContent ?? "";+ const chevron = canvasElement.querySelector<HTMLElement>(+ 'button[aria-label="Collapse"], button[aria-label="Expand"]',+ );+ if (!chevron) throw new Error("expected a collapse chevron");++ const before = readout();+ await userEvent.dblClick(chevron);+ // Collapsing twice is a no-op you cannot see, so a jumped view would be the+ // only visible result of an impatient click on the chevron.+ await expect(readout()).toBe(before);+ },+});++export const ZoomsToASpan = meta.story({+ name: "(Test) Zooms To A Span",+ args: {+ roots: reporterTrace(),+ box: PEEK,+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+ play: async ({ canvasElement }) => {+ const readout = () =>+ canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-v2-readout"]',+ )?.textContent ?? "";++ await expect(readout()).toContain("view 0msβ486ms");++ const bars = canvasElement.querySelectorAll<HTMLElement>(+ '[data-testid="timeline-v2-bar"]',+ );+ const chatGroq = bars[4];+ if (!chatGroq) throw new Error("expected a bar to double-click");+ await userEvent.dblClick(chatGroq);++ // Double-tap-to-fit narrows the window instead of scrolling a canvas.+ await waitFor(() => expect(readout()).not.toContain("view 0msβ486ms"));+ },+});diff --git a/web/src/features/traces/components/TraceTimelineV2/TimelineV2.tsx b/web/src/features/traces/components/TraceTimelineV2/TimelineV2.tsxnew file mode 100644index 0000000000..f6a2a3f6ce--- /dev/null+++ b/web/src/features/traces/components/TraceTimelineV2/TimelineV2.tsx@@ -0,0 +1,813 @@+/**+ * Throwaway renderer for the size-adaptive timeline spike.+ *+ * Its only job is to make `layout()` visible: measured box in, absolutely+ * placed boxes out. Every coordinate on screen comes from the pure function β+ * no flex, no min-width and no intrinsic content sizing participates in where a+ * bar lands. There is deliberately no horizontal scroll anywhere: the whole+ * trace fits the box by default, and detail is reached by zooming the view.+ *+ * Not production code. Phase 2 lands this behind the real timeline entry point+ * with selection, playhead and the resizable gutter kept working.+ */++import {+ useCallback,+ useMemo,+ useRef,+ useState,+ type PointerEvent as ReactPointerEvent,+ type ReactNode,+} from "react";+import { useVirtualizer } from "@tanstack/react-virtual";+import { ChevronRight, Maximize2, Minus, Plus } from "lucide-react";+import { ItemBadge, type LangfuseItemType } from "@/src/components/ItemBadge";+import { cn } from "@/src/utils/tailwind";+import {+ detectPointerModality,+ resolveDensity,+ type PointerModality,+} from "./density";+import {+ formatDurationMs,+ layout,+ prepareTimeline,+ timeCompressionFor,+ type LayoutNode,+ type PositionedNode,+} from "./layout";+import { createTextMeasurer } from "./textMeasurer";+import {+ fitView,+ isFitted,+ panView,+ traceSpaceOf,+ zoomToSpan,+ zoomView,+ type Box,+ type TimeSpan,+} from "./viewTransform";++/**+ * The four takes on "what happens to the name gutter below ~480px", so the+ * design call can be made from renders instead of prose.+ */+export type TimelineComposition =+ /** Name gutter beside the chart, as today. */+ | "split"+ /** Gutter collapses to the type icon and the depth rail. */+ | "icons"+ /** No gutter: names ride on top of the bars. */+ | "overlay"+ /** No gutter: name above, bar below, both full width. */+ | "stacked"+ /** Full-width tree or full-width timeline, one at a time. */+ | "modes";++export type TimelineV2Props = {+ roots: LayoutNode[];+ /** The measured box. Required β there is no fallback canvas width. */+ box: Box;+ /** `null` resolves from `(pointer: coarse)` once, on mount. */+ pointer: PointerModality | null;+ compress: boolean;+ composition: TimelineComposition;+ /** View window + scale readout under the chart; the spike's instrument panel. */+ showReadout: boolean;+};++const FRAME_BORDER = 1;+const TOOLBAR_HEIGHT = 30;+const AXIS_HEIGHT = 20;+const READOUT_HEIGHT = 18;+const GUTTER_INDENT = 10;+const GUTTER_MAX_DEPTH = 6;+const ICON_GUTTER_WIDTH = 46;+const ZOOM_STEP = 1.6;+/** Movement before a press becomes a pan rather than a click. */+const DRAG_THRESHOLD_PX = 4;++export function TimelineV2({+ roots,+ box,+ pointer,+ compress,+ composition,+ showReadout,+}: TimelineV2Props) {+ const [detectedPointer] = useState(detectPointerModality);+ const [view, setView] = useState<TimeSpan | null>(null);+ const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(+ () => new Set<string>(),+ );+ const [selectedId, setSelectedId] = useState<string | null>(null);+ const [mode, setMode] = useState<"tree" | "timeline">("timeline");++ const modality = pointer ?? detectedPointer;+ const prepared = useMemo(+ () => prepareTimeline(roots, collapsed),+ [roots, collapsed],+ );++ // The scroll viewport's own client box, not an arithmetic guess at it. The+ // guess was wrong by the frame border and again by the scrollbar β two+ // constants the math would never have seen, which is the whole failure mode+ // this renderer exists to remove. Measure first; everything below derives.+ const [viewport, setViewport] = useState<Box | null>(null);+ const estimated = {+ width: Math.max(box.width - FRAME_BORDER * 2, 0),+ height: Math.max(+ box.height -+ FRAME_BORDER * 2 -+ TOOLBAR_HEIGHT -+ AXIS_HEIGHT -+ (showReadout ? READOUT_HEIGHT : 0),+ 0,+ ),+ };+ const contentWidth = viewport?.width ?? estimated.width;+ const viewportHeight = viewport?.height ?? estimated.height;++ const gutterWidth = resolveGutterWidth({ composition, contentWidth, mode });+ const chartWidth = Math.max(contentWidth - gutterWidth, 0);+ const chartBox = useMemo(+ () => ({ width: chartWidth, height: viewportHeight }),+ [chartWidth, viewportHeight],+ );++ const density = useMemo(+ () =>+ resolveDensity({+ pointer: modality,+ lines: composition === "stacked" ? 2 : 1,+ }),+ [modality, composition],+ );+ const measurer = useMemo(+ () => createTextMeasurer(`${density.labelFontPx}px ui-sans-serif`),+ [density.labelFontPx],+ );+ const compression = useMemo(+ () => timeCompressionFor(prepared, chartBox, compress),+ [prepared, chartBox, compress],+ );++ // The view is a window in COMPRESSED ms, so it only means anything relative to+ // the compression that produced it. Switch trace or switch compression off and+ // the stored numbers quietly address somewhere else β layout() clamps them into+ // the new space and draws an unrelated window rather than an obviously broken+ // one. So the window is dropped when the space it belongs to is replaced;+ // fitted is the only view that means the same thing in every space.+ //+ // Compressed duration is part of that identity, not just the flags: collapsed+ // gaps are priced in PHYSICAL px (`min(28, width / (gaps + 1))`), so resizing+ // the pane while zoomed in with compression on rescales the whole space around+ // a window that still addresses the old one. Collapsing a node is deliberately+ // not in the key β it changes which rows exist, not what a ms means.+ const spaceKey = `${compress}:${compression.compressedDurationMs}`;+ const spaceRef = useRef({ roots, spaceKey });+ if (+ spaceRef.current.roots !== roots ||+ spaceRef.current.spaceKey !== spaceKey+ ) {+ spaceRef.current = { roots, spaceKey };+ if (view !== null) setView(null);+ }++ const scrollRef = useRef<HTMLDivElement | null>(null);+ const virtualizer = useVirtualizer({+ count: prepared.rows.length,+ getScrollElement: () => scrollRef.current,+ estimateSize: () => density.rowHeight,+ overscan: 6,+ // Key by node id, not index: an index-keyed cache and id-keyed DOM drift+ // apart the moment rows are collapsed away.+ getItemKey: (index) => prepared.rows[index]?.node.id ?? index,+ });++ const virtualItems = virtualizer.getVirtualItems();+ const rowRange = virtualItems.length+ ? {+ startIndex: virtualItems[0]!.index,+ endIndex: virtualItems[virtualItems.length - 1]!.index,+ }+ : // Before the virtualizer has measured its scroll element, fill the box.+ {+ startIndex: 0,+ endIndex: Math.ceil(viewportHeight / density.rowHeight) + 1,+ };++ const result = layout({+ roots,+ box: chartBox,+ density,+ measurer,+ view,+ compress,+ prepared,+ compression,+ rowRange,+ });++ const traceSpace = useMemo(+ () => traceSpaceOf(compression.compressedDurationMs),+ [compression.compressedDurationMs],+ );+ const fitted = isFitted(result.view, traceSpace);+ const viewStartMs = compression.toRealMs(result.view.start);+ const viewEndMs = compression.toRealMs(+ result.view.start + result.view.duration,+ );++ const zoomBy = useCallback(+ (factor: number, anchorRatio: number) =>+ setView((current) =>+ zoomView(current ?? fitView(traceSpace), traceSpace, {+ factor,+ anchorRatio,+ }),+ ),+ [traceSpace],+ );++ /**+ * `deltaPx` is how far the CONTENT moves, so the grabbed moment stays under+ * the pointer: dragging right shows earlier time, which means the window start+ * goes DOWN. Without the negation the bars slid the opposite way to the finger+ * β and to the wheel, whose caller negates the scroll delta for the same+ * reason.+ */+ const panBy = useCallback(+ (deltaPx: number) =>+ setView((current) => {+ const from = current ?? fitView(traceSpace);+ const pxPerMs = chartWidth > 0 ? chartWidth / from.duration : 0;+ return panView(from, traceSpace, pxPerMs > 0 ? -deltaPx / pxPerMs : 0);+ }),+ [traceSpace, chartWidth],+ );++ /**+ * The viewport ref does two things React cannot express declaratively: a+ * non-passive wheel listener (React's own onWheel is passive, so it cannot+ * stop the page scrolling during a zoom) and a ResizeObserver for the+ * measured box. Both are external browser systems, wired through React 19's+ * ref cleanup rather than an effect.+ */+ const attachViewport = useCallback(+ (element: HTMLDivElement | null) => {+ scrollRef.current = element;+ if (!element) return;++ const measure = () =>+ setViewport((current) =>+ current?.width === element.clientWidth &&+ current?.height === element.clientHeight+ ? current+ : { width: element.clientWidth, height: element.clientHeight },+ );+ const observer = new ResizeObserver(measure);+ observer.observe(element);+ measure();++ const onWheel = (event: WheelEvent) => {+ const zooming = event.ctrlKey || event.metaKey;+ const panning = !zooming && (event.shiftKey || event.deltaX !== 0);+ if (!zooming && !panning) return; // plain wheel scrolls the row list++ event.preventDefault();+ if (zooming) {+ const rect = element.getBoundingClientRect();+ const anchorRatio =+ chartWidth > 0+ ? (event.clientX - rect.left - gutterWidth) / chartWidth+ : 0.5;+ zoomBy(event.deltaY < 0 ? ZOOM_STEP : 1 / ZOOM_STEP, anchorRatio);+ } else {+ panBy(-(event.deltaX || event.deltaY));+ }+ };++ element.addEventListener("wheel", onWheel, { passive: false });+ return () => {+ observer.disconnect();+ element.removeEventListener("wheel", onWheel);+ };+ },+ [chartWidth, gutterWidth, zoomBy, panBy],+ );++ const gesture = useRef<{+ pointers: Map<number, number>;+ startX: number;+ lastX: number;+ pinchDistance: number;+ dragging: boolean;+ }>({+ pointers: new Map(),+ startX: 0,+ lastX: 0,+ pinchDistance: 0,+ dragging: false,+ });++ const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {+ gesture.current.pointers.set(event.pointerId, event.clientX);+ gesture.current.startX = event.clientX;+ gesture.current.lastX = event.clientX;+ gesture.current.dragging = false;+ if (gesture.current.pointers.size === 2) {+ const [a, b] = [...gesture.current.pointers.values()];+ gesture.current.pinchDistance = Math.abs((a ?? 0) - (b ?? 0));+ }+ // Deliberately NOT capturing here. Pointer capture retargets the derived+ // `click` to the capture element, so capturing on pointerdown means a plain+ // click lands on this scroll container and no row is ever selected.+ // Capture is taken on the first move past DRAG_THRESHOLD_PX instead, which+ // also gives us "a drag does not select" for free.+ };++ const onPointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {+ const state = gesture.current;+ if (!state.pointers.has(event.pointerId)) return;+ state.pointers.set(event.pointerId, event.clientX);++ if (state.pointers.size >= 2) {+ const [a, b] = [...state.pointers.values()];+ const distance = Math.abs((a ?? 0) - (b ?? 0));+ if (state.pinchDistance > 0 && distance > 0) {+ const rect = event.currentTarget.getBoundingClientRect();+ const midpoint = ((a ?? 0) + (b ?? 0)) / 2 - rect.left - gutterWidth;+ zoomBy(+ distance / state.pinchDistance,+ chartWidth > 0 ? midpoint / chartWidth : 0.5,+ );+ }+ state.pinchDistance = distance;+ return;+ }++ if (!state.dragging) {+ if (Math.abs(event.clientX - state.startX) < DRAG_THRESHOLD_PX) return;+ state.dragging = true;+ // Now that this really is a drag, capture so it survives leaving the box.+ event.currentTarget.setPointerCapture(event.pointerId);+ }++ panBy(event.clientX - state.lastX);+ state.lastX = event.clientX;+ };++ const onPointerUp = (event: ReactPointerEvent<HTMLDivElement>) => {+ const state = gesture.current;+ state.pointers.delete(event.pointerId);+ state.pinchDistance = 0;+ state.dragging = false;+ // Lifting one finger of a pinch does not end the gesture, and startX/lastX+ // still hold where the OTHER finger went down β so the survivor's next small+ // move would clear the drag threshold at once and pan by the whole finger+ // separation. Re-anchor both on the finger that is still there.+ const survivor = state.pointers.values().next().value;+ if (survivor !== undefined) {+ state.startX = survivor;+ state.lastX = survivor;+ }+ };++ const toggleCollapsed = (id: string) =>+ setCollapsed((current) => {+ const next = new Set(current);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ });++ /** Double-tap a bar to fit it; double-tap again to go back to the whole trace. */+ const zoomToNode = (node: PositionedNode) => {+ const target = {+ start: compression.toCompressedMs(node.startMs),+ duration: Math.max(+ compression.toCompressedMs(node.endMs) -+ compression.toCompressedMs(node.startMs),+ 0,+ ),+ };+ setView((current) => {+ const next = zoomToSpan(target, traceSpace);+ const isAlreadyThere =+ current != null &&+ Math.abs(current.start - next.start) < 1 &&+ Math.abs(current.duration - next.duration) < 1;+ return isAlreadyThere ? null : next;+ });+ };++ const showGutter = gutterWidth > 0;+ const showChart = chartWidth > 0;++ return (+ <div+ className="bg-background border-border text-foreground flex flex-col overflow-hidden rounded border"+ 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` }}+ >+ {composition === "modes" ? (+ <div className="flex gap-0.5">+ {(["tree", "timeline"] as const).map((candidate) => (+ <button+ key={candidate}+ type="button"+ onClick={() => setMode(candidate)}+ className={cn(+ "rounded px-2 py-0.5 text-xs capitalize",+ mode === candidate ? "bg-muted" : "hover:bg-muted/60",+ )}+ >+ {candidate}+ </button>+ ))}+ </div>+ ) : null}+ <ToolbarButton+ label="Zoom out"+ onClick={() => zoomBy(1 / ZOOM_STEP, 0.5)}+ >+ <Minus className="h-3 w-3" />+ </ToolbarButton>+ <ToolbarButton label="Zoom in" onClick={() => zoomBy(ZOOM_STEP, 0.5)}>+ <Plus className="h-3 w-3" />+ </ToolbarButton>+ <ToolbarButton label="Fit whole trace" onClick={() => setView(null)}>+ <Maximize2 className="h-3 w-3" />+ </ToolbarButton>+ <span+ className="text-muted-foreground truncate text-xs"+ title="Zoom state"+ >+ {fitted+ ? "whole trace"+ : `${formatDurationMs(viewEndMs - viewStartMs)} window`}+ </span>+ </div>++ <div+ className="border-border relative shrink-0 border-b"+ style={{ height: `${AXIS_HEIGHT}px` }}+ >+ {showChart ? (+ <div+ className="absolute inset-y-0"+ style={{ left: `${gutterWidth}px`, width: `${chartWidth}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 top-0.5 left-1 whitespace-nowrap"+ style={{ fontSize: `${density.labelFontPx - 1}px` }}+ >+ {tick.label}+ </span>+ </div>+ ))}+ </div>+ ) : null}+ </div>++ <div className="relative min-h-0 flex-1">+ {showChart ? (+ <div+ className="pointer-events-none absolute inset-y-0"+ style={{ left: `${gutterWidth}px`, width: `${chartWidth}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 flex items-center justify-center border-x border-dashed"+ style={{ left: `${gap.x}px`, width: `${gap.width}px` }}+ title={`${gap.label} of idle time, collapsed`}+ >+ <span+ className="text-muted-foreground"+ style={{ fontSize: `${density.labelFontPx}px` }}+ >+ β―+ </span>+ </div>+ ))}+ </div>+ ) : null}++ <div+ ref={attachViewport}+ className="h-full overflow-x-hidden overflow-y-auto"+ data-testid="timeline-v2-scroll"+ style={{ touchAction: "pan-y" }}+ onPointerDown={showChart ? onPointerDown : undefined}+ onPointerMove={showChart ? onPointerMove : undefined}+ onPointerUp={onPointerUp}+ onPointerCancel={onPointerUp}+ >+ <div+ className="relative"+ style={{ height: `${result.contentHeight}px` }}+ data-testid="timeline-v2-content"+ >+ {result.nodes.map((node) => (+ <div+ key={node.id}+ className={cn(+ // select-none: the whole row is a click target (select, and+ // double-click to fit), so dragging over it must not select+ // the names and duration labels it is made of.+ // `group` so hovering anywhere in the row recolours its bar.+ // transition-COLORS only β a bare `transition` would also ease+ // left/width and make zoom lag a frame behind the gesture.+ "group absolute inset-x-0 flex cursor-pointer items-center transition-colors duration-150 select-none",+ // Selected takes an accent tint rather than a deeper neutral:+ // the bars are bg-muted, so a neutral selected row swallows+ // them. Hover is the neutral one.+ selectedId === node.id+ ? "bg-primary-accent/10"+ : "hover:bg-muted",+ )}+ style={{ top: `${node.y}px`, height: `${node.height}px` }}+ onClick={() => setSelectedId(node.id)}+ onDoubleClick={() => zoomToNode(node)}+ >+ {selectedId === node.id ? (+ <div className="bg-primary-accent absolute inset-y-0 left-0 w-0.5" />+ ) : null}+ {showGutter ? (+ <GutterCell+ node={node}+ width={gutterWidth}+ compact={composition === "icons"}+ fontPx={density.labelFontPx}+ isSelected={selectedId === node.id}+ onToggleCollapsed={() => toggleCollapsed(node.id)}+ />+ ) : null}+ {showChart ? (+ <ChartCell+ node={node}+ width={chartWidth}+ barHeight={density.barHeight}+ fontPx={density.labelFontPx}+ nameMode={+ composition === "overlay"+ ? "overlay"+ : composition === "stacked"+ ? "stacked"+ : "none"+ }+ isSelected={selectedId === node.id}+ />+ ) : null}+ </div>+ ))}+ </div>+ </div>+ </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-v2-readout"+ >+ <span>+ {box.width}Γ{box.height} Β· gutter {gutterWidth} Β· lane {chartWidth}+ </span>+ <span>+ view {formatDurationMs(viewStartMs)}β{formatDurationMs(viewEndMs)}+ </span>+ <span>{result.pxPerMs.toFixed(3)} px/ms</span>+ <span>+ {result.rowCount} rows @ {density.rowHeight}px ({modality})+ </span>+ {compression.enabled ? (+ <span>{compression.gaps.length} gaps collapsed</span>+ ) : null}+ </div>+ ) : null}+ </div>+ );+}++function resolveGutterWidth(args: {+ composition: TimelineComposition;+ contentWidth: number;+ mode: "tree" | "timeline";+}): number {+ const { composition, contentWidth, mode } = args;+ if (composition === "overlay" || composition === "stacked") return 0;+ if (composition === "icons") return Math.min(ICON_GUTTER_WIDTH, contentWidth);+ if (composition === "modes") return mode === "tree" ? contentWidth : 0;+ return Math.round(Math.min(Math.max(contentWidth * 0.4, 96), 280));+}++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-5 w-5 items-center justify-center rounded"+ >+ {children}+ </button>+ );+}++function GutterCell({+ node,+ width,+ compact,+ fontPx,+ isSelected,+ onToggleCollapsed,+}: {+ node: PositionedNode;+ width: number;+ compact: boolean;+ fontPx: number;+ isSelected: boolean;+ onToggleCollapsed: () => void;+}) {+ // Depth indentation is capped so a 20-level trace still leaves room for names.+ const indent = Math.min(node.depth, GUTTER_MAX_DEPTH) * GUTTER_INDENT;++ return (+ <div+ className="flex h-full shrink-0 items-center gap-1 overflow-hidden pr-1"+ style={{ width: `${width}px`, paddingLeft: `${indent + 2}px` }}+ >+ {node.hasChildren ? (+ <button+ type="button"+ aria-label={node.isCollapsed ? "Expand" : "Collapse"}+ aria-expanded={!node.isCollapsed}+ onClick={(event) => {+ event.stopPropagation();+ onToggleCollapsed();+ }}+ // The row zooms to its span on double-click. Collapsing twice in+ // quick succession is a no-op the user cannot see, so without this the+ // only visible outcome of an impatient click is the view jumping.+ onDoubleClick={(event) => event.stopPropagation()}+ className="hover:bg-muted-foreground/10 flex h-4 w-4 shrink-0 items-center justify-center rounded"+ >+ <ChevronRight+ className={cn("h-3 w-3", !node.isCollapsed && "rotate-90")}+ />+ </button>+ ) : (+ <span className="w-4 shrink-0" />+ )}+ <span className="shrink-0">+ <ItemBadge type={node.type as LangfuseItemType} isSmall />+ </span>+ {compact ? null : (+ <span+ className={cn("truncate", isSelected && "font-bold")}+ style={{ fontSize: `${fontPx}px` }}+ title={node.name}+ >+ {node.name}+ </span>+ )}+ </div>+ );+}++function ChartCell({+ node,+ width,+ barHeight,+ fontPx,+ nameMode,+ isSelected,+}: {+ node: PositionedNode;+ width: number;+ barHeight: number;+ fontPx: number;+ nameMode: "none" | "overlay" | "stacked";+ isSelected: boolean;+}) {+ return (+ <div+ className="relative h-full shrink-0 overflow-hidden"+ style={{ width: `${width}px` }}+ data-testid="timeline-v2-lane"+ >+ {node.offscreen ? null : (+ <>+ <div+ className={cn(+ "absolute border transition-colors duration-150",+ nameMode === "stacked" ? "bottom-1" : "top-1/2 -translate-y-1/2",+ node.durationMs == null && "border-dashed",+ !node.clippedLeft && "rounded-l-sm",+ !node.clippedRight && "rounded-r-sm",+ // The bar itself takes the focus colour on row hover, and a+ // stronger fill plus a ring when the row is the selected one.+ isSelected+ ? "bg-primary-accent/40 border-primary-accent ring-primary-accent ring-2"+ : "bg-muted border-border group-hover:bg-primary-accent/25 group-hover:border-primary-accent/40",+ )}+ style={{+ left: `${node.x}px`,+ width: `${node.width}px`,+ height: `${barHeight}px`,+ }}+ data-testid="timeline-v2-bar"+ />+ {node.firstTokenX == null ? null : (+ <div+ className={cn(+ "bg-border-contrast absolute w-px",+ nameMode === "stacked"+ ? "bottom-1"+ : "top-1/2 -translate-y-1/2",+ )}+ style={{+ left: `${node.firstTokenX}px`,+ height: `${barHeight}px`,+ }}+ title="Time to first token"+ />+ )}+ {node.labelPlacement === "hidden" ? null : (+ <span+ className={cn(+ "absolute whitespace-nowrap",+ nameMode === "stacked"+ ? "bottom-1"+ : "top-1/2 -translate-y-1/2",+ node.labelPlacement === "inside"+ ? "text-foreground"+ : "text-muted-foreground",+ )}+ style={{+ left: `${node.labelX}px`,+ maxWidth: `${Math.max(width - node.labelX, 0)}px`,+ fontSize: `${fontPx}px`,+ }}+ >+ {node.label}+ </span>+ )}+ </>+ )}+ {nameMode === "overlay" ? (+ // Names ride over the bars: a gradient keeps them readable without+ // stealing a column from the chart.+ <span+ className="from-background via-background/90 pointer-events-none absolute top-1/2 left-1 max-w-[70%] -translate-y-1/2 truncate bg-gradient-to-r to-transparent pr-3"+ style={{ fontSize: `${fontPx}px` }}+ title={node.name}+ >+ {node.name}+ </span>+ ) : null}+ {nameMode === "stacked" ? (+ // Name above, bar below: the chart keeps the full width and the name+ // keeps its full length, at the cost of a taller row.+ <span+ className="text-foreground pointer-events-none absolute top-0 right-1 truncate"+ style={{+ left: `${Math.min(node.depth, GUTTER_MAX_DEPTH) * GUTTER_INDENT + 4}px`,+ fontSize: `${fontPx}px`,+ }}+ title={node.name}+ >+ {node.name}+ </span>+ ) : null}+ </div>+ );+}diff --git a/web/src/features/traces/components/TraceTimelineV2/TimelineV2Compression.stories.tsx b/web/src/features/traces/components/TraceTimelineV2/TimelineV2Compression.stories.tsxnew file mode 100644index 0000000000..1d2c828742--- /dev/null+++ b/web/src/features/traces/components/TraceTimelineV2/TimelineV2Compression.stories.tsx@@ -0,0 +1,71 @@+import preview from "../../../../../.storybook/preview";+import { TimelineV2 } from "./TimelineV2";+import { longTailTrace, manySpans } from "./__tests__/timelineV2.fixtures";++const meta = preview.meta({+ component: TimelineV2,+});++const PEEK = { width: 320, height: 260 };+const DESKTOP = { width: 1280, height: 360 };++/**+ * One 36s span, three 40ms spans. Fitted honestly the work is invisible;+ * compressed it is legible but the axis no longer reads linearly. Both halves+ * of the trade-off, same shape, same box.+ */+export const LongTailHonest = meta.story({+ args: {+ roots: longTailTrace(),+ box: PEEK,+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+});++export const LongTailCompressed = meta.story({+ args: {+ roots: longTailTrace(),+ box: PEEK,+ pointer: "fine",+ compress: true,+ composition: "split",+ showReadout: true,+ },+});++export const LongTailHonestWide = meta.story({+ args: {+ roots: longTailTrace(),+ box: DESKTOP,+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+});++export const LongTailCompressedWide = meta.story({+ args: {+ roots: longTailTrace(),+ box: DESKTOP,+ pointer: "fine",+ compress: true,+ composition: "split",+ showReadout: true,+ },+});++/** A dense trace with no real idle stretch: compression should do nothing. */+export const DenseTraceCompressed = meta.story({+ args: {+ roots: manySpans(500),+ box: DESKTOP,+ pointer: "fine",+ compress: true,+ composition: "split",+ showReadout: true,+ },+});diff --git a/web/src/features/traces/components/TraceTimelineV2/TimelineV2Mobile.stories.tsx b/web/src/features/traces/components/TraceTimelineV2/TimelineV2Mobile.stories.tsxnew file mode 100644index 0000000000..435630c59e--- /dev/null+++ b/web/src/features/traces/components/TraceTimelineV2/TimelineV2Mobile.stories.tsx@@ -0,0 +1,97 @@+import preview from "../../../../../.storybook/preview";+import { TimelineV2, type TimelineComposition } from "./TimelineV2";+import { reporterTrace } from "./__tests__/timelineV2.fixtures";++const meta = preview.meta({+ component: TimelineV2,+});++/**+ * Fit-to-box fixes the time axis. What still breaks below ~480px is the name+ * gutter and the chart sharing one row, so these are the takes on that.+ */+const PHONE = { width: 320, height: 300 };+const COMPOSITIONS: TimelineComposition[] = [+ "split",+ "icons",+ "overlay",+ "stacked",+ "modes",+];++export const GutterAndChart = meta.story({+ args: {+ roots: reporterTrace(),+ box: PHONE,+ pointer: "coarse",+ compress: false,+ composition: "split",+ showReadout: true,+ },+});++export const IconGutter = meta.story({+ args: {+ roots: reporterTrace(),+ box: PHONE,+ pointer: "coarse",+ compress: false,+ composition: "icons",+ showReadout: true,+ },+});++export const NamesOverBars = meta.story({+ args: {+ roots: reporterTrace(),+ box: PHONE,+ pointer: "coarse",+ compress: false,+ composition: "overlay",+ showReadout: true,+ },+});++export const NameAboveBar = meta.story({+ args: {+ roots: reporterTrace(),+ box: PHONE,+ pointer: "coarse",+ compress: false,+ composition: "stacked",+ showReadout: true,+ },+});++export const ModeToggle = meta.story({+ args: {+ roots: reporterTrace(),+ box: PHONE,+ pointer: "coarse",+ compress: false,+ composition: "modes",+ showReadout: true,+ },+});++/** All four takes side by side, at touch density. */+export const VariantMatrix = meta.story({+ args: {+ roots: reporterTrace(),+ box: PHONE,+ pointer: "coarse",+ compress: false,+ composition: "split",+ showReadout: true,+ },+ render: (args) => (+ <div className="flex flex-wrap gap-4">+ {COMPOSITIONS.map((composition) => (+ <div key={composition} className="flex flex-col gap-1">+ <span className="text-muted-foreground text-xs">{composition}</span>+ <TimelineV2 {...args} composition={composition} />+ </div>+ ))}+ </div>+ ),+});diff --git a/web/src/features/traces/components/TraceTimelineV2/TimelineV2Sizes.stories.tsx b/web/src/features/traces/components/TraceTimelineV2/TimelineV2Sizes.stories.tsxnew file mode 100644index 0000000000..78ddd2bb4f--- /dev/null+++ b/web/src/features/traces/components/TraceTimelineV2/TimelineV2Sizes.stories.tsx@@ -0,0 +1,144 @@+import preview from "../../../../../.storybook/preview";+import { TimelineV2 } from "./TimelineV2";+import { reporterTrace } from "./__tests__/timelineV2.fixtures";++const meta = preview.meta({+ component: TimelineV2,+});++/** The five review widths; short and tall so density resolution is visible too. */+const WIDTHS = [320, 480, 768, 1280, 1920];+const SHORT = 220;+const TALL = 560;++export const Narrow320Short = meta.story({+ args: {+ roots: reporterTrace(),+ box: { width: 320, height: SHORT },+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+});++export const Narrow320Tall = meta.story({+ args: {+ roots: reporterTrace(),+ box: { width: 320, height: TALL },+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+});++export const Mobile480Short = meta.story({+ args: {+ roots: reporterTrace(),+ box: { width: 480, height: SHORT },+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+});++export const Mobile480Tall = meta.story({+ args: {+ roots: reporterTrace(),+ box: { width: 480, height: TALL },+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+});++export const Tablet768Short = meta.story({+ args: {+ roots: reporterTrace(),+ box: { width: 768, height: SHORT },+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+});++export const Tablet768Tall = meta.story({+ args: {+ roots: reporterTrace(),+ box: { width: 768, height: TALL },+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+});++export const Desktop1280Short = meta.story({+ args: {+ roots: reporterTrace(),+ box: { width: 1280, height: SHORT },+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+});++export const Desktop1280Tall = meta.story({+ args: {+ roots: reporterTrace(),+ box: { width: 1280, height: TALL },+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+});++export const Wide1920Short = meta.story({+ args: {+ roots: reporterTrace(),+ box: { width: 1920, height: SHORT },+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+});++export const Wide1920Tall = meta.story({+ args: {+ roots: reporterTrace(),+ box: { width: 1920, height: TALL },+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+});++/** Every width at once: the same trace, whole, in each box. */+export const VariantMatrix = meta.story({+ args: {+ roots: reporterTrace(),+ box: { width: 320, height: 300 },+ pointer: "fine",+ compress: false,+ composition: "split",+ showReadout: true,+ },+ render: (args) => (+ <div className="flex flex-col gap-4">+ {WIDTHS.map((width) => (+ <div key={width} className="flex flex-col gap-1">+ <span className="text-muted-foreground text-xs">{width}px</span>+ <TimelineV2 {...args} box={{ width, height: 300 }} />+ </div>+ ))}+ </div>+ ),+});diff --git a/web/src/features/traces/components/TraceTimelineV2/__tests__/timelineV2.fixtures.ts b/web/src/features/traces/components/TraceTimelineV2/__tests__/timelineV2.fixtures.tsnew file mode 100644index 0000000000..ed66c69bea--- /dev/null+++ b/web/src/features/traces/components/TraceTimelineV2/__tests__/timelineV2.fixtures.ts@@ -0,0 +1,272 @@+/**+ * The shape matrix for the timeline-renderer spike: one generator per trace+ * shape the renderer has to survive, deterministic so the Storybook cells and+ * the tests look at the same pixels.+ */++import type { LayoutNode } from "@/src/features/traces/components/TraceTimelineV2/layout";++const BASE_START = new Date("2024-01-01T00:00:00.000Z").getTime();++type SpanSpec = {+ name: string;+ type?: string;+ /** ms after the trace origin */+ startMs: number;+ /** ms; null β no endTime at all */+ durationMs: number | null;+ children?: SpanSpec[];+ latency?: number;+};++function toNode(spec: SpanSpec, path: string): LayoutNode {+ const startTime = new Date(BASE_START + spec.startMs);+ return {+ id: path,+ name: spec.name,+ type: spec.type ?? "SPAN",+ startTime,+ endTime:+ spec.durationMs == null+ ? null+ : new Date(BASE_START + spec.startMs + spec.durationMs),+ latency: spec.latency,+ children: (spec.children ?? []).map((child, index) =>+ toNode(child, `${path}.${index}`),+ ),+ };+}++const build = (specs: SpanSpec[]): LayoutNode[] =>+ specs.map((spec, index) => toNode(spec, `n${index}`));++/** Deterministic pseudo-random so 500- and 10k-span cells never flicker. */+function seededRandom(seed: number) {+ let state = seed;+ return () => {+ state = (state * 1_664_525 + 1_013_904_223) % 4_294_967_296;+ return state / 4_294_967_296;+ };+}++export const singleSpan = (): LayoutNode[] =>+ build([+ { name: "openai.chat", type: "GENERATION", startMs: 0, durationMs: 1_240 },+ ]);++export const threeSpans = (): LayoutNode[] =>+ build([+ {+ name: "handle-request",+ startMs: 0,+ durationMs: 1_800,+ children: [+ { name: "retrieve-docs", startMs: 40, durationMs: 320 },+ {+ name: "openai.chat",+ type: "GENERATION",+ startMs: 380,+ durationMs: 1_350,+ },+ ],+ },+ ]);++export const deepNesting = (levels = 12): LayoutNode[] => {+ let child: SpanSpec | undefined;+ for (let level = levels - 1; level >= 0; level--) {+ child = {+ name: `level-${level}`,+ startMs: level * 12,+ durationMs: 900 - level * 60,+ children: child ? [child] : [],+ };+ }+ return build([child!]);+};++/** 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",+ startMs: 0,+ durationMs: totalMs,+ children: [],+ };++ const open: SpanSpec[] = [root];+ for (let i = 1; i < count; i++) {+ const parent = open[Math.floor(random() * Math.min(open.length, 32))]!;+ const parentDuration = parent.durationMs ?? totalMs;+ const startMs =+ parent.startMs + Math.floor(random() * Math.max(parentDuration - 20, 1));+ const durationMs = Math.max(+ 2,+ Math.floor(+ random() * Math.max(parent.startMs + parentDuration - startMs, 2),+ ),+ );+ const spec: SpanSpec = {+ name: i % 4 === 0 ? `openai.chat.${i}` : `step-${i}`,+ type: i % 4 === 0 ? "GENERATION" : "SPAN",+ startMs,+ durationMs,+ children: [],+ };+ parent.children!.push(spec);+ if (+ (parent.children!.length >= 6 || parentDuration < 40) &&+ open.length > 1+ ) {+ open.splice(open.indexOf(parent), 1);+ }+ open.push(spec);+ }++ return build([root]);+};++/** Nimar's complaint, generalised: real work is 0.3% of the wall clock. */+export const longTailTrace = (): LayoutNode[] =>+ build([+ {+ name: "nightly-batch",+ startMs: 0,+ durationMs: 36_020,+ children: [+ { name: "load-config", startMs: 10, durationMs: 40 },+ {+ name: "openai.chat",+ type: "GENERATION",+ startMs: 18_000,+ durationMs: 40,+ },+ { name: "write-results", startMs: 35_960, durationMs: 40 },+ ],+ },+ ]);++export const allInstantaneous = (): LayoutNode[] =>+ build([+ {+ name: "fanout",+ startMs: 0,+ durationMs: 0,+ children: [+ { name: "event-a", startMs: 0, durationMs: 0 },+ { name: "event-b", startMs: 0, durationMs: 0 },+ { name: "event-c", startMs: 0, durationMs: 0 },+ ],+ },+ ]);++export const missingEndTimes = (): LayoutNode[] =>+ build([+ {+ name: "in-flight-run",+ startMs: 0,+ durationMs: null,+ children: [+ { name: "retrieve-docs", startMs: 120, durationMs: null },+ {+ name: "openai.chat",+ type: "GENERATION",+ startMs: 260,+ durationMs: null,+ },+ ],+ },+ ]);++/** Single instantaneous span: the fully collapsed trace. */+export const zeroDurationTrace = (): LayoutNode[] =>+ build([{ name: "ping", startMs: 0, durationMs: 0 }]);++/**+ * The shape from the community report: a sub-second LangGraph tree, nine nested+ * observations, rendered in a peek-width lane. This is the acceptance cell.+ */+export const reporterTrace = (): LayoutNode[] =>+ build([+ {+ name: "LangGraph",+ type: "CHAIN",+ startMs: 0,+ durationMs: 486,+ children: [+ {+ name: "ideator",+ type: "CHAIN",+ startMs: 4,+ durationMs: 232,+ children: [+ {+ name: "RunnableSequence",+ type: "CHAIN",+ startMs: 6,+ durationMs: 228,+ children: [+ {+ name: "ChatPromptTemplate",+ type: "SPAN",+ startMs: 7,+ durationMs: 2,+ },+ {+ name: "ChatGroq",+ type: "GENERATION",+ startMs: 10,+ durationMs: 222,+ },+ ],+ },+ ],+ },+ {+ name: "writer",+ type: "CHAIN",+ startMs: 240,+ durationMs: 244,+ children: [+ {+ name: "RunnableSequence",+ type: "CHAIN",+ startMs: 242,+ durationMs: 241,+ children: [+ {+ name: "ChatGroq",+ type: "GENERATION",+ startMs: 243,+ durationMs: 238,+ },+ {+ name: "ChatPromptTemplate",+ type: "SPAN",+ startMs: 482,+ durationMs: 1,+ },+ ],+ },+ ],+ },+ ],+ },+ ]);++export const TIMELINE_SHAPES = {+ reporter: reporterTrace,+ single: singleSpan,+ three: threeSpans,+ deep: () => deepNesting(12),+ long: longTailTrace,+ instantaneous: allInstantaneous,+ missingEnd: missingEndTimes,+ zero: zeroDurationTrace,+ medium: () => manySpans(500),+ huge: () => manySpans(10_000),+} satisfies Record<string, () => LayoutNode[]>;++export type TimelineShapeKey = keyof typeof TIMELINE_SHAPES;diff --git a/web/src/features/traces/components/TraceTimelineV2/density.ts b/web/src/features/traces/components/TraceTimelineV2/density.tsnew file mode 100644index 0000000000..2b60d2b623--- /dev/null+++ b/web/src/features/traces/components/TraceTimelineV2/density.ts@@ -0,0 +1,68 @@+/**+ * Density is a resolved value, not a constant.+ *+ * It resolves from the input modality and how many text lines a row must hold:+ *+ * - `pointer: fine` (mouse) wants Finder-row density β a span as tall as a file+ * in a file listing, ~26px.+ * - `pointer: coarse` (touch) wants β₯44px, because zoom-and-tap instead of+ * hover makes the tap target load-bearing rather than cosmetic.+ *+ * Deliberately NOT a function of box height. An earlier revision grew rows into+ * the slack of a tall box (a 3-row trace got 34px rows in a 420px box); review+ * rejected it β density is the point, so the box decides how many rows are+ * visible, never how tall they are. Rows also stay uniform height, because+ * vertical virtualization depends on it.+ *+ * Production code, arriving one PR before its callers: the renderer beside it+ * (`TimelineV2.tsx`) is a Storybook harness and says so, this is not.+ */++export type PointerModality = "fine" | "coarse";++export const FINE_ROW_HEIGHT = 26;+export const COARSE_ROW_HEIGHT = 44;+/** A row that stacks a name over its bar needs two text lines' worth. */+export const TWO_LINE_MIN_HEIGHT = 38;++export type Density = {+ pointer: PointerModality;+ rowHeight: number;+ barHeight: number;+ labelFontPx: number;+ /** Horizontal padding for a label drawn inside its bar. */+ labelPaddingPx: number;+ /** Gap between a bar and a label drawn outside it. */+ labelGapPx: number;+ /** Zero-duration spans stay visible as a marker this wide. */+ minBarWidthPx: number;+};++export function resolveDensity(options: {+ pointer: PointerModality;+ /** 2 when the row stacks a name above its bar (no name gutter). */+ lines?: 1 | 2;+}): Density {+ const { pointer } = options;+ const lines = options.lines ?? 1;+ const rowHeight = Math.max(+ pointer === "coarse" ? COARSE_ROW_HEIGHT : FINE_ROW_HEIGHT,+ lines === 2 ? TWO_LINE_MIN_HEIGHT : 0,+ );++ return {+ pointer,+ rowHeight,+ barHeight: Math.max(8, Math.round(rowHeight * (lines === 2 ? 0.35 : 0.6))),+ labelFontPx: pointer === "coarse" ? 13 : 12,+ labelPaddingPx: 4,+ labelGapPx: 6,+ minBarWidthPx: pointer === "coarse" ? 6 : 4,+ };+}++/** Browser-only companion to `resolveDensity`; never called from `layout()`. */+export function detectPointerModality(): PointerModality {+ if (typeof window === "undefined" || !window.matchMedia) return "fine";+ return window.matchMedia("(pointer: coarse)").matches ? "coarse" : "fine";+}diff --git a/web/src/features/traces/components/TraceTimelineV2/layout.clienttest.ts b/web/src/features/traces/components/TraceTimelineV2/layout.clienttest.tsnew file mode 100644index 0000000000..4714e2652b--- /dev/null+++ b/web/src/features/traces/components/TraceTimelineV2/layout.clienttest.ts@@ -0,0 +1,306 @@+import { describe, expect, it } from "vitest";+import { resolveDensity } from "./density";+import {+ formatDurationMs,+ layout,+ prepareTimeline,+ type LayoutNode,+ type PositionedNode,+ type TimelineLayout,+} from "./layout";+import { PX_PER_LETTER, createTextMeasurerFrom } from "./textMeasurer";+import {+ MAX_ZOOM_PRECISION_MS,+ clampView,+ traceSpaceOf,+ zoomToSpan,+ zoomView,+} from "./viewTransform";+import {+ TIMELINE_SHAPES,+ longTailTrace,+ reporterTrace,+ singleSpan,+} from "./__tests__/timelineV2.fixtures";++// Explicit null context: the PX_PER_LETTER fallback, so widths are+// deterministic and jsdom is never asked for a canvas.+const measurer = createTextMeasurerFrom(null);++const BOXES = [+ { width: 320, height: 240 },+ { width: 480, height: 240 },+ { width: 768, height: 640 },+ { width: 1280, height: 640 },+ { width: 1920, height: 900 },+];++function run(+ roots: readonly LayoutNode[],+ box: { width: number; height: number },+ options: Partial<Parameters<typeof layout>[0]> = {},+): TimelineLayout {+ const prepared = prepareTimeline(roots, options.collapsed);+ return layout({+ roots,+ box,+ density: options.density ?? resolveDensity({ pointer: "fine" }),+ measurer,+ view: options.view ?? null,+ compress: options.compress ?? false,+ prepared,+ ...options,+ });+}++const numbersOf = (node: PositionedNode) => [+ node.x,+ node.width,+ node.y,+ node.height,+ node.labelX,+ node.labelWidth,+ node.startMs,+ node.endMs,+ node.firstTokenX ?? 0,+ node.durationMs ?? 0,+];++describe("layout", () => {+ it("scales to the measured box instead of a fixed canvas", () => {+ const roots = singleSpan();++ const narrow = run(roots, { width: 320, height: 240 });+ const wide = run(roots, { width: 1280, height: 240 });++ // Same trace, same fitted view; only the box differs.+ expect(narrow.nodes[0]!.width).toBeCloseTo(320, 0);+ expect(wide.nodes[0]!.width).toBeCloseTo(1280, 0);+ expect(narrow.view).toEqual(narrow.traceSpace);+ });++ it("keeps every bar and label inside the box for every shape and width", () => {+ for (const [shape, makeRoots] of Object.entries(TIMELINE_SHAPES)) {+ const roots = makeRoots();+ for (const box of BOXES) {+ const result = run(roots, box, { compress: true });+ for (const node of result.nodes) {+ const context = `${shape} @ ${box.width}px, node ${node.id}`;+ expect(node.x, context).toBeGreaterThanOrEqual(0);+ expect(node.x + node.width, context).toBeLessThanOrEqual(+ box.width + 0.001,+ );+ if (node.labelPlacement !== "hidden") {+ expect(node.labelX, context).toBeGreaterThanOrEqual(0);+ expect(node.labelX + node.labelWidth, context).toBeLessThanOrEqual(+ box.width + 0.001,+ );+ }+ }+ for (const tick of result.ticks) {+ expect(tick.x, `${shape} @ ${box.width}px tick`).toBeLessThanOrEqual(+ box.width + 0.001,+ );+ }+ }+ }+ });++ it("stays finite on degenerate shapes, degenerate boxes and compression", () => {+ const boxes = [+ ...BOXES,+ { width: 0, height: 0 },+ { width: 320, height: 0 },+ ];++ for (const [shape, makeRoots] of Object.entries(TIMELINE_SHAPES)) {+ const roots = makeRoots();+ for (const box of boxes) {+ for (const compress of [false, true]) {+ const result = run(roots, box, { compress });+ const context = `${shape} @ ${box.width}x${box.height} compress=${compress}`;++ expect(Number.isFinite(result.pxPerMs), context).toBe(true);+ expect(Number.isFinite(result.contentHeight), context).toBe(true);+ expect(Number.isFinite(result.traceSpace.duration), context).toBe(+ true,+ );+ expect(Number.isFinite(result.view.duration), context).toBe(true);++ for (const node of result.nodes) {+ for (const value of numbersOf(node)) {+ expect(Number.isFinite(value), `${context} ${node.id}`).toBe(+ true,+ );+ }+ }+ for (const tick of result.ticks) {+ expect(Number.isFinite(tick.x), context).toBe(true);+ }+ for (const gap of result.gaps) {+ expect(+ Number.isFinite(gap.x) && Number.isFinite(gap.width),+ context,+ ).toBe(true);+ }+ }+ }+ }++ // No roots at all is a shape too.+ const empty = run([], { width: 320, height: 240 });+ expect(empty.nodes).toEqual([]);+ expect(empty.contentHeight).toBe(0);+ });++ it("places the duration label inside a wide bar and outside a narrow one", () => {+ const wide = run(singleSpan(), { width: 1280, height: 240 }).nodes[0]!;+ expect(wide.labelPlacement).toBe("inside");+ expect(wide.labelX).toBeGreaterThan(wide.x);++ // The last span of the reporter trace is 1ms at the right edge: there is no+ // room inside the bar, and none after it either.+ const narrow = run(reporterTrace(), { width: 320, height: 240 });+ const lastSpan = narrow.nodes[narrow.nodes.length - 1]!;+ expect(lastSpan.width).toBeLessThan(8);+ expect(lastSpan.labelPlacement).toBe("before");+ });++ it("compression makes a long-tail trace legible and stays reversible", () => {+ const roots = longTailTrace();+ const box = { width: 320, height: 240 };++ const honest = run(roots, box, { compress: false });+ const compressed = run(roots, box, { compress: true });++ const leafWidth = (result: TimelineLayout) =>+ Math.max(...result.nodes.filter((n) => n.depth > 0).map((n) => n.width));++ // Fitted honestly, 40ms of work in a 36s trace is a sub-pixel sliver+ // pinned to the minimum bar width; compressed, it is a real bar.+ expect(leafWidth(honest)).toBe(4);+ expect(leafWidth(compressed)).toBeGreaterThan(20);+ expect(compressed.gaps.length).toBeGreaterThan(0);+ expect(compressed.compression.compressedDurationMs).toBeLessThan(+ compressed.realDurationMs,+ );++ // Round-trip: the axis labels read real time back out of compressed space.+ for (const realMs of [0, 40, 18_000, 36_020]) {+ expect(+ compressed.compression.toRealMs(+ compressed.compression.toCompressedMs(realMs),+ ),+ ).toBeCloseTo(realMs, 3);+ }+ });++ it("positions only the mounted row window", () => {+ const roots = TIMELINE_SHAPES.huge();+ const box = { width: 768, height: 640 };+ const windowed = run(roots, box, {+ rowRange: { startIndex: 100, endIndex: 139 },+ });++ expect(windowed.nodes).toHaveLength(40);+ expect(windowed.rowCount).toBe(10_000);+ expect(windowed.nodes[0]!.index).toBe(100);+ expect(windowed.nodes[0]!.y).toBe(100 * windowed.rowHeight);+ });+});++describe("view transform", () => {+ it("clamps the window inside trace space and floors the zoom", () => {+ const space = traceSpaceOf(1_000);++ expect(clampView({ start: -500, duration: 5_000 }, space)).toEqual({+ start: 0,+ duration: 1_000,+ });+ // Panning past the end holds the zoom level and pulls the start back.+ expect(clampView({ start: 900, duration: 400 }, space)).toEqual({+ start: 600,+ duration: 400,+ });+ expect(+ clampView({ start: 0, duration: 0.001 }, space).duration,+ ).toBeCloseTo(MAX_ZOOM_PRECISION_MS, 6);+ expect(clampView({ start: NaN, duration: NaN }, space)).toEqual({+ start: 0,+ duration: 1_000,+ });+ // A collapsed trace has nowhere to zoom to.+ expect(clampView({ start: 0, duration: 10 }, traceSpaceOf(0))).toEqual({+ start: 0,+ duration: 0,+ });+ });++ it("zooms about the anchor and zoom-to-span pads both sides", () => {+ const space = traceSpaceOf(1_000);+ const zoomed = zoomView({ start: 0, duration: 1_000 }, space, {+ factor: 2,+ anchorRatio: 0.5,+ });+ expect(zoomed).toEqual({ start: 250, duration: 500 });++ const fitted = zoomToSpan({ start: 400, duration: 100 }, space, 0.1);+ expect(fitted.start).toBeCloseTo(390, 6);+ expect(fitted.duration).toBeCloseTo(120, 6);+ });+});++describe("density", () => {+ it("resolves from the pointer modality and lines per row", () => {+ // Never a function of box height: a short trace in a tall box keeps+ // Finder-row density rather than growing into the slack.+ expect(resolveDensity({ pointer: "fine" }).rowHeight).toBe(26);+ expect(resolveDensity({ pointer: "coarse" }).rowHeight).toBe(44);+ // A stacked row (name above bar) needs two text lines' worth.+ expect(resolveDensity({ pointer: "fine", lines: 2 }).rowHeight).toBe(38);+ expect(resolveDensity({ pointer: "coarse", lines: 2 }).rowHeight).toBe(44);+ });+});++describe("textMeasurer", () => {+ // Every glyph 10px wide, so a measured width is countable by hand and the+ // per-letter fallback (6.5) is visible whenever one is used by mistake.+ const tenPerGlyph = {+ font: "",+ measureText: (text: string) => ({ width: text.length * 10 }),+ } as unknown as CanvasRenderingContext2D;++ it("measures every unit in a compound label, not just the last", () => {+ const measure = createTextMeasurerFrom(tenPerGlyph).measure;++ // `1m 35s` is six glyphs, so 60 β and it is only 60 if the leading `m` was+ // measured too. Matching a unit only as the whole remainder of the string+ // left it on the flat estimate, which is what every label above a minute is.+ expect(measure("1m 35s")).toBeCloseTo(60, 6);+ expect(measure("1h 30m")).toBeCloseTo(60, 6);+ expect(measure("486ms")).toBeCloseTo(50, 6);+ expect(measure("1.24s")).toBeCloseTo(50, 6);+ // Longest-first matching, so `min` is one unit rather than `m` plus letters.+ expect(measure("5min")).toBeCloseTo(40, 6);+ expect(measure("β 1.24s")).toBeCloseTo(70, 6);+ });++ it("falls back to a flat per-letter width with no canvas", () => {+ expect(createTextMeasurerFrom(null).measure("1m 35s")).toBeCloseTo(+ 6 * PX_PER_LETTER,+ 6,+ );+ });+});++describe("formatDurationMs", () => {+ it("keeps labels short at every magnitude", () => {+ expect(formatDurationMs(0)).toBe("0ms");+ expect(formatDurationMs(486)).toBe("486ms");+ expect(formatDurationMs(1_240)).toBe("1.24s");+ expect(formatDurationMs(36_020)).toBe("36.02s");+ expect(formatDurationMs(95_000)).toBe("1m 35s");+ expect(formatDurationMs(5_400_000)).toBe("1h 30m");+ expect(formatDurationMs(NaN)).toBe("0ms");+ });+});diff --git a/web/src/features/traces/components/TraceTimelineV2/layout.ts b/web/src/features/traces/components/TraceTimelineV2/layout.tsnew file mode 100644index 0000000000..df379a6272--- /dev/null+++ b/web/src/features/traces/components/TraceTimelineV2/layout.ts@@ -0,0 +1,556 @@+/**+ * `layout()` β the one pure function that owns every timeline coordinate.+ *+ * layout(tree, view, box, density) β PositionedNode[]+ *+ * Three properties it is built to hold, because the current renderer holds+ * none of them:+ *+ * 1. **`box` is required.** No default parameter, no fallback constant. A+ * missing box is a type error, not a silently-900px canvas.+ * 2. **Total.** Zero-duration traces, instantaneous spans and missing+ * `endTime`s produce finite coordinates, never `NaN`/`Infinity` β the+ * degenerate window yields `pxPerMs === 0` instead of a division by zero.+ * 3. **Everything inside the box.** Bars, labels, ticks and gap markers are+ * clamped into `[0, box.width]`, so no coordinate ever asks the container+ * for horizontal scroll. Off-view spans are reported as `offscreen`; the+ * way to reach them is to zoom or pan the view, never to scroll a canvas.+ *+ * Split for the per-frame path: `prepareTimeline` (tree walk β memoize on the+ * tree + collapsed set) and `timeCompressionFor` (memoize on the box width)+ * both stay out of the zoom/pan loop, which then only positions the rows the+ * virtualizer has mounted (`rowRange`).+ *+ * **This is production code, arriving one PR before its callers.** The renderer+ * beside it (`TimelineV2.tsx`) is a Storybook harness and says so; this file,+ * `viewTransform`, `timeCompression`, `textMeasurer` and `density` are not. They+ * move to `fns/timeline/` and the production timeline positions every bar,+ * label and tick through them β so a defect here reaches users, and the sibling's+ * "not production code" marker does not cover it.+ */++import type { Density } from "./density";+import type { TextMeasurer } from "./textMeasurer";+import {+ buildTimeCompression,+ identityCompression,+ type TimeCompression,+} from "./timeCompression";+import {+ clamp,+ clampView,+ createViewTransform,+ fitView,+ traceSpaceOf,+ type Box,+ type TimeSpan,+} from "./viewTransform";++/**+ * Structural input shape. `TreeNode` satisfies it, so Phase 2 can call+ * `layout()` on the real tree without an adapter.+ */+export type LayoutNode = {+ id: string;+ name: string;+ type?: string;+ startTime: Date;+ endTime?: Date | null;+ /** seconds β the only duration a synthetic root span has */+ latency?: number;+ completionStartTime?: Date | null;+ children: LayoutNode[];+};++export type TimelineRow = {+ node: LayoutNode;+ depth: number;+ treeLines: boolean[];+ isLastSibling: boolean;+ hasChildren: boolean;+ isCollapsed: boolean;+};++export type LabelPlacement = "inside" | "after" | "before" | "hidden";++export type PositionedNode = {+ id: string;+ name: string;+ type: string;+ index: number;+ depth: number;+ treeLines: boolean[];+ isLastSibling: boolean;+ hasChildren: boolean;+ isCollapsed: boolean;+ y: number;+ height: number;+ /** px from the lane's left edge β always within `[0, box.width]` */+ x: number;+ width: number;+ /** the span continues past this edge of the lane (zoomed in or panned) */+ clippedLeft: boolean;+ clippedRight: boolean;+ /** the span does not intersect the view at all */+ offscreen: boolean;+ /** real span duration; null when the span has no end and no latency */+ durationMs: number | null;+ /** time-to-first-token marker, null when absent or out of view */+ firstTokenX: number | null;+ label: string;+ labelWidth: number;+ labelPlacement: LabelPlacement;+ labelX: number;+ /** real ms offsets from the trace origin β what zoom-to-span needs */+ startMs: number;+ endMs: number;+};++export type Tick = { realMs: number; x: number; label: string };++export type GapMarker = {+ x: number;+ width: number;+ durationMs: number;+ label: string;+};++export type PreparedTimeline = {+ rows: TimelineRow[];+ originMs: number;+ durationMs: number;+ /** ms offsets of every non-root span β the compression input */+ spans: Array<[number, number]>;+};++export type TimelineLayout = {+ nodes: PositionedNode[];+ rowCount: number;+ rowHeight: number;+ contentHeight: number;+ /** compressed trace space β `[0, compressedDuration]` */+ traceSpace: TimeSpan;+ /** the visible window, clamped into trace space */+ view: TimeSpan;+ pxPerMs: number;+ realDurationMs: number;+ originMs: number;+ ticks: Tick[];+ gaps: GapMarker[];+ compression: TimeCompression;+};++export type LayoutInput = {+ roots: readonly LayoutNode[];+ /** measured β there is no fallback constant */+ box: Box;+ density: Density;+ measurer: TextMeasurer;+ /** null β fit the whole trace, which is the default view */+ view: TimeSpan | null;+ compress: boolean;+ collapsed?: ReadonlySet<string>;+ /** memoized tree walk; recomputed here when absent */+ prepared?: PreparedTimeline;+ /** memoized compression; recomputed here when absent */+ compression?: TimeCompression;+ /** position only these rows (the virtualizer's mounted window) */+ rowRange?: { startIndex: number; endIndex: number };+};++const EPSILON = 0.5;+const MAX_TICKS = 64;+const MIN_TICK_GAP_PX = 56;+const TICK_LABEL_PADDING_PX = 16;+/** Matches the renderer's label offset from its tick line. */+const TICK_LABEL_INSET_PX = 6;++// Nice tick steps in ms. Above a minute they land on time-nice boundaries so+// hour-scale traces get clean labels instead of "1500s".+const TICK_STEPS_MS = [+ 1, 2, 5, 10, 20, 25, 50, 100, 200, 250, 500, 1_000, 2_000, 5_000, 10_000,+ 15_000, 30_000, 60_000, 120_000, 300_000, 600_000, 900_000, 1_800_000,+ 3_600_000, 7_200_000, 10_800_000, 21_600_000, 43_200_000, 86_400_000,+];++const startOf = (node: LayoutNode) => node.startTime.getTime();++/** End of a span, falling back to `latency` and then to an instant. */+const endOf = (node: LayoutNode) => {+ if (node.endTime) return node.endTime.getTime();+ if (node.latency != null && Number.isFinite(node.latency)) {+ return startOf(node) + node.latency * 1000;+ }+ return startOf(node);+};++const hasDuration = (node: LayoutNode) =>+ Boolean(node.endTime) ||+ (node.latency != null && Number.isFinite(node.latency));++export function formatDurationMs(ms: number): string {+ if (!Number.isFinite(ms) || ms < 0) return "0ms";+ if (ms < 1_000) return `${Math.round(ms)}ms`;+ if (ms < 60_000) return `${(ms / 1_000).toFixed(2)}s`;+ const pad = (value: number) => String(value).padStart(2, "0");+ if (ms < 3_600_000) {+ return `${Math.floor(ms / 60_000)}m ${pad(Math.floor((ms % 60_000) / 1_000))}s`;+ }+ return `${Math.floor(ms / 3_600_000)}h ${pad(Math.floor((ms % 3_600_000) / 60_000))}m`;+}++/**+ * Tree walk: flatten to rows, find the origin and the total duration, and+ * collect the spans compression may keep. Iterative β deep traces must not+ * blow the stack.+ */+export function prepareTimeline(+ roots: readonly LayoutNode[],+ collapsed: ReadonlySet<string> = new Set(),+): PreparedTimeline {+ if (roots.length === 0) {+ return { rows: [], originMs: 0, durationMs: 0, spans: [] };+ }++ let originMs = Infinity;+ let latestEndMs = -Infinity;+ const all: LayoutNode[] = [];+ const boundsStack: LayoutNode[] = [...roots];+ while (boundsStack.length > 0) {+ const node = boundsStack.pop()!;+ all.push(node);+ originMs = Math.min(originMs, startOf(node));+ latestEndMs = Math.max(latestEndMs, endOf(node));+ for (const child of node.children) boundsStack.push(child);+ }++ if (!Number.isFinite(originMs) || !Number.isFinite(latestEndMs)) {+ return { rows: [], originMs: 0, durationMs: 0, spans: [] };+ }+ const durationMs = Math.max(latestEndMs - originMs, 0);++ // Roots are excluded: a root covers the whole trace by definition, so keeping+ // it would mean no stretch of the trace is ever idle.+ const rootIds = new Set(roots.map((root) => root.id));+ const spans: Array<[number, number]> = [];+ for (const node of all) {+ if (rootIds.has(node.id)) continue;+ spans.push([startOf(node) - originMs, endOf(node) - originMs]);+ }++ const byStart = (a: LayoutNode, b: LayoutNode) => startOf(a) - startOf(b);+ const rows: TimelineRow[] = [];+ const stack: Array<Omit<TimelineRow, "hasChildren" | "isCollapsed">> = [];+ const sortedRoots = [...roots].sort(byStart);+ for (let i = sortedRoots.length - 1; i >= 0; i--) {+ stack.push({+ node: sortedRoots[i]!,+ depth: 0,+ treeLines: [],+ isLastSibling: i === sortedRoots.length - 1,+ });+ }++ while (stack.length > 0) {+ const current = stack.pop()!;+ const hasChildren = current.node.children.length > 0;+ const isCollapsed = collapsed.has(current.node.id);+ rows.push({ ...current, hasChildren, isCollapsed });++ if (!hasChildren || isCollapsed) continue;+ const children = [...current.node.children].sort(byStart);+ for (let i = children.length - 1; i >= 0; i--) {+ stack.push({+ node: children[i]!,+ depth: current.depth + 1,+ treeLines: [...current.treeLines, i !== children.length - 1],+ isLastSibling: i === children.length - 1,+ });+ }+ }++ return { rows, originMs, durationMs, spans };+}++/** Memoize on `[prepared, box.width, compress]` β not on the view. */+export function timeCompressionFor(+ prepared: PreparedTimeline,+ box: Box,+ compress: boolean,+): TimeCompression {+ return compress+ ? buildTimeCompression({+ spans: prepared.spans,+ durationMs: prepared.durationMs,+ physicalWidth: box.width,+ enabled: true,+ })+ : identityCompression(prepared.durationMs);+}++export function layout(input: LayoutInput): TimelineLayout {+ const { box, density, measurer } = input;+ const laneWidth = Math.max(Number.isFinite(box.width) ? box.width : 0, 0);++ const prepared =+ input.prepared ?? prepareTimeline(input.roots, input.collapsed);+ const compression =+ input.compression ?? timeCompressionFor(prepared, box, input.compress);++ const traceSpace = traceSpaceOf(compression.compressedDurationMs);+ const view = clampView(input.view ?? fitView(traceSpace), traceSpace);+ const transform = createViewTransform(view, { ...box, width: laneWidth });++ const rowHeight = density.rowHeight;+ const from = Math.max(input.rowRange?.startIndex ?? 0, 0);+ const to = Math.min(+ input.rowRange?.endIndex ?? prepared.rows.length - 1,+ prepared.rows.length - 1,+ );++ const nodes: PositionedNode[] = [];+ for (let index = from; index <= to; index++) {+ const row = prepared.rows[index]!;+ nodes.push(+ positionRow(row, index, {+ originMs: prepared.originMs,+ compression,+ transform,+ laneWidth,+ rowHeight,+ density,+ measurer,+ }),+ );+ }++ return {+ nodes,+ rowCount: prepared.rows.length,+ rowHeight,+ contentHeight: prepared.rows.length * rowHeight,+ traceSpace,+ view,+ pxPerMs: transform.pxPerMs,+ realDurationMs: prepared.durationMs,+ originMs: prepared.originMs,+ ticks: buildTicks({ view, compression, transform, laneWidth, measurer }),+ gaps: buildGapMarkers({ compression, transform, laneWidth }),+ compression,+ };+}++function positionRow(+ row: TimelineRow,+ index: number,+ context: {+ originMs: number;+ compression: TimeCompression;+ transform: ReturnType<typeof createViewTransform>;+ laneWidth: number;+ rowHeight: number;+ density: Density;+ measurer: TextMeasurer;+ },+): PositionedNode {+ const {+ originMs,+ compression,+ transform,+ laneWidth,+ rowHeight,+ density,+ measurer,+ } = context;+ const node = row.node;++ const startMs = startOf(node) - originMs;+ const endMs = Math.max(endOf(node) - originMs, startMs);+ const left = transform.toPx(compression.toCompressedMs(startMs));+ const right = transform.toPx(compression.toCompressedMs(endMs));++ // Clamp into the lane, then keep the minimum-width marker inside it too:+ // a bar at the right edge shifts left rather than overflowing the box.+ const width = Math.min(+ Math.max(+ clamp(right, 0, laneWidth) - clamp(left, 0, laneWidth),+ density.minBarWidthPx,+ ),+ laneWidth,+ );+ const x = clamp(clamp(left, 0, laneWidth), 0, Math.max(laneWidth - width, 0));++ const durationMs = hasDuration(node) ? endMs - startMs : null;+ const label = durationMs == null ? "" : formatDurationMs(durationMs);+ const labelWidth = label ? measurer.measure(label) : 0;+ const { labelPlacement, labelX } = placeLabel({+ label,+ labelWidth,+ x,+ width,+ laneWidth,+ density,+ });++ const firstTokenMs = node.completionStartTime+ ? node.completionStartTime.getTime() - originMs+ : null;+ const firstTokenPx =+ firstTokenMs == null+ ? null+ : transform.toPx(compression.toCompressedMs(firstTokenMs));++ return {+ id: node.id,+ name: node.name,+ type: node.type ?? "SPAN",+ index,+ depth: row.depth,+ treeLines: row.treeLines,+ isLastSibling: row.isLastSibling,+ hasChildren: row.hasChildren,+ isCollapsed: row.isCollapsed,+ y: index * rowHeight,+ height: rowHeight,+ x,+ width,+ clippedLeft: left < -EPSILON,+ clippedRight: right > laneWidth + EPSILON,+ offscreen: right < -EPSILON || left > laneWidth + EPSILON,+ durationMs,+ firstTokenX:+ firstTokenPx == null || firstTokenPx < 0 || firstTokenPx > laneWidth+ ? null+ : firstTokenPx,+ label,+ labelWidth,+ labelPlacement,+ labelX,+ startMs,+ endMs,+ };+}++/**+ * The decision CSS flow gets wrong in a narrow lane: inside the bar if it fits,+ * else outside on whichever side has room, else not drawn at all.+ */+function placeLabel(args: {+ label: string;+ labelWidth: number;+ x: number;+ width: number;+ laneWidth: number;+ density: Density;+}): { labelPlacement: LabelPlacement; labelX: number } {+ const { label, labelWidth, x, width, laneWidth, density } = args;+ if (!label) return { labelPlacement: "hidden", labelX: x };++ if (labelWidth + density.labelPaddingPx * 2 <= width) {+ return { labelPlacement: "inside", labelX: x + density.labelPaddingPx };+ }+ const after = x + width + density.labelGapPx;+ if (after + labelWidth <= laneWidth) {+ return { labelPlacement: "after", labelX: after };+ }+ const before = x - density.labelGapPx - labelWidth;+ if (before >= 0) return { labelPlacement: "before", labelX: before };++ return { labelPlacement: "hidden", labelX: x };+}++function buildTicks(context: {+ view: TimeSpan;+ compression: TimeCompression;+ transform: ReturnType<typeof createViewTransform>;+ laneWidth: number;+ measurer: TextMeasurer;+}): Tick[] {+ const { view, compression, transform, laneWidth, measurer } = context;+ const realStart = compression.toRealMs(view.start);+ const realEnd = compression.toRealMs(view.start + view.duration);+ const realDuration = realEnd - realStart;++ if (laneWidth <= 0) return [];+ if (!(realDuration > 0)) {+ return [{ realMs: realStart, x: 0, label: formatDurationMs(realStart) }];+ }++ const minGapPx = Math.max(+ MIN_TICK_GAP_PX,+ measurer.measure(formatDurationMs(realEnd)) + TICK_LABEL_PADDING_PX,+ );+ const step =+ TICK_STEPS_MS.find(+ (candidate) => (candidate / realDuration) * laneWidth >= minGapPx,+ ) ?? TICK_STEPS_MS[TICK_STEPS_MS.length - 1]!;++ const insideCollapsedGap = (realMs: number) =>+ compression.gaps.some((gap) => realMs > gap.start && realMs < gap.end);++ const fits = (x: number, label: string) =>+ x >= -EPSILON &&+ x + TICK_LABEL_INSET_PX + measurer.measure(label) <= laneWidth;++ const ticks: Tick[] = [];+ const collides = (x: number) =>+ ticks.some((tick) => Math.abs(tick.x - x) < minGapPx);++ // The far side of every collapsed gap gets a tick first. Without them a+ // compressed axis loses every nice-step label into a gap and reads as a+ // single "0ms" β and the visible jump from 95ms to 18.00s across a 28px band+ // is what explains the band to the user.+ //+ // These are de-overlapped against EACH OTHER too, not only against the+ // nice-step ticks below: two gaps a few px apart β several near-instant spans+ // between collapsed idle, or the unbuffered fallback path where spans get no+ // label padding at all β would otherwise print their labels on top of one+ // another.+ for (const gap of compression.gaps) {+ const x = transform.toPx(gap.compressedEnd);+ const label = formatDurationMs(gap.end);+ if (fits(x, label) && !collides(x)) {+ ticks.push({ realMs: gap.end, x, label });+ }+ }++ const first = Math.ceil(realStart / step) * step;+ for (let realMs = first; realMs <= realEnd; realMs += step) {+ if (ticks.length >= MAX_TICKS) break;+ if (insideCollapsedGap(realMs)) continue;+ const x = transform.toPx(compression.toCompressedMs(realMs));+ // `toPx β toCompressedMs` is monotonic, so passing the right edge ends the+ // walk. Compression makes px spacing non-uniform, so labels are+ // de-overlapped against what is already placed, not assumed from the step.+ if (x > laneWidth + EPSILON) break;+ const label = formatDurationMs(realMs);+ if (!fits(x, label) || collides(x)) continue;+ ticks.push({ realMs, x, label });+ }++ return ticks.sort((a, b) => a.x - b.x);+}++function buildGapMarkers(context: {+ compression: TimeCompression;+ transform: ReturnType<typeof createViewTransform>;+ laneWidth: number;+}): GapMarker[] {+ const { compression, transform, laneWidth } = context;+ if (!compression.enabled) return [];++ const markers: GapMarker[] = [];+ for (const gap of compression.gaps) {+ const left = transform.toPx(gap.compressedStart);+ const right = transform.toPx(gap.compressedEnd);+ if (right < 0 || left > laneWidth) continue;+ const x = clamp(left, 0, laneWidth);+ markers.push({+ x,+ width: clamp(right, 0, laneWidth) - x,+ durationMs: gap.durationMs,+ label: formatDurationMs(gap.durationMs),+ });+ }+ return markers;+}diff --git a/web/src/features/traces/components/TraceTimelineV2/textMeasurer.ts b/web/src/features/traces/components/TraceTimelineV2/textMeasurer.tsnew file mode 100644index 0000000000..55cb430c7a--- /dev/null+++ b/web/src/features/traces/components/TraceTimelineV2/textMeasurer.ts@@ -0,0 +1,104 @@+/**+ * Duration-label text measurement β ported from Sentry's+ * `traceRenderers/traceTextMeasurer.tsx`.+ *+ * Measures each digit and unit string ONCE against a canvas, then sums cached+ * glyph widths per label. That is what lets `layout()` decide inside the pure+ * function whether a duration label fits in its bar or has to sit outside it β+ * a decision CSS flow currently makes, and makes wrong in a narrow lane.+ *+ * Production code, arriving one PR before its callers: the renderer beside it+ * (`TimelineV2.tsx`) is a Storybook harness and says so, this is not.+ */++/** Manual measurement average; used when no 2D context is available. */+export const PX_PER_LETTER = 6.5;++const UNITS = ["ns", "ms", "s", "m", "min", "h", "d", "β"] as const;++/**+ * Longest first, so "min" is never read as "m" followed by letters β and so a+ * COMPOUND label measures every unit in it. Matching a unit only when it is the+ * whole remainder of the string meant `1m 35s` and `1h 05m`, which is what+ * `formatDurationMs` emits above a minute, measured their leading unit at the+ * flat per-letter estimate and fed a slightly wrong width to the decision about+ * which side of a bar the label goes on.+ */+const UNITS_LONGEST_FIRST = [...UNITS].sort((a, b) => b.length - a.length);++const unitAt = (text: string, index: number): string | null => {+ for (const unit of UNITS_LONGEST_FIRST) {+ if (text.startsWith(unit, index)) return unit;+ }+ return null;+};++export type TextMeasurer = { measure: (text: string) => number };++export function createTextMeasurer(font = "12px ui-sans-serif"): TextMeasurer {+ let context: CanvasRenderingContext2D | null = null;+ try {+ context =+ typeof document === "undefined"+ ? null+ : document.createElement("canvas").getContext("2d");+ } catch {+ context = null;+ }+ return createTextMeasurerFrom(context, font);+}++/** Explicit-context entry point: `null` exercises the `PX_PER_LETTER` fallback. */+export function createTextMeasurerFrom(+ context: CanvasRenderingContext2D | null,+ font = "12px ui-sans-serif",+): TextMeasurer {+ const glyphs = new Map<string, number>();+ const units = new Map<string, number>();+ const cache = new Map<string, number>();++ if (context) {+ context.font = font;+ // One width for every digit keeps tabular labels stable as they tick.+ let digit = 0;+ for (let i = 0; i < 10; i++) {+ digit = Math.max(digit, context.measureText(String(i)).width);+ }+ for (let i = 0; i < 10; i++) glyphs.set(String(i), digit);+ for (const char of [".", ",", " "]) {+ glyphs.set(char, context.measureText(char).width);+ }+ for (const unit of UNITS) units.set(unit, context.measureText(unit).width);+ } else {+ for (const unit of UNITS) units.set(unit, unit.length * PX_PER_LETTER);+ }++ const computeWidth = (text: string) => {+ let width = 0;+ for (let i = 0; i < text.length; i++) {+ const glyph = glyphs.get(text[i]!);+ if (glyph !== undefined) {+ width += glyph;+ continue;+ }+ const unit = unitAt(text, i);+ if (unit !== null) {+ width += units.get(unit) ?? unit.length * PX_PER_LETTER;+ i += unit.length - 1;+ continue;+ }+ width += PX_PER_LETTER;+ }+ return width;+ };++ return {+ measure: (text) => {+ const cached = cache.get(text);+ if (cached !== undefined) return cached;+ const width = computeWidth(text);+ cache.set(text, width);+ return width;+ },+ };+}diff --git a/web/src/features/traces/components/TraceTimelineV2/timeCompression.ts b/web/src/features/traces/components/TraceTimelineV2/timeCompression.tsnew file mode 100644index 0000000000..a39bd00fc9--- /dev/null+++ b/web/src/features/traces/components/TraceTimelineV2/timeCompression.ts@@ -0,0 +1,240 @@+/**+ * Idle-gap time compression β ported from Sentry's+ * `traceRenderers/traceTimeCompression.tsx`.+ *+ * Fit-to-box is correct but not always legible: a 36s trace whose real work is+ * three 40ms spans fits honestly and reads as three invisible slivers. Gaps+ * where nothing happens, wider than 5% of the trace, collapse to a fixed ~28px+ * marker so the busy regions get the pixels.+ *+ * Compression is a coordinate remap applied BEFORE the view transform: the view+ * (zoom/pan) then works in compressed ms, so panning is linear on screen and+ * the collapsed gaps don't re-flow while the user zooms.+ *+ * It buys legibility by lying about proportion β the renderer must therefore+ * draw the gap markers, and tick labels must come back through `toRealMs`.+ *+ * Production code, arriving one PR before its callers: the renderer beside it+ * (`TimelineV2.tsx`) is a Storybook harness and says so, this is not.+ */++const COLLAPSE_THRESHOLD_RATIO = 0.05;+export const COLLAPSED_GAP_WIDTH_PX = 28;+/** Reserve room next to a bar for its duration label, so labels never land in a gap. */+const DURATION_LABEL_BUFFER_PX = 48;+const MARKER_PADDING_RATIO = 0.01;+const MARKER_PADDING_MAX_MS = 500;++type Interval = [start: number, end: number];++export type CompressedGap = {+ /** real ms offsets */+ start: number;+ end: number;+ durationMs: number;+ /** compressed ms offsets */+ compressedStart: number;+ compressedEnd: number;+};++export type TimeCompression = {+ enabled: boolean;+ /** ms, real */+ durationMs: number;+ /** ms, compressed β the width of compressed trace space */+ compressedDurationMs: number;+ gaps: readonly CompressedGap[];+ toCompressedMs: (realMs: number) => number;+ toRealMs: (compressedMs: number) => number;+};++export function identityCompression(durationMs: number): TimeCompression {+ const duration = Math.max(Number.isFinite(durationMs) ? durationMs : 0, 0);+ return {+ enabled: false,+ durationMs: duration,+ compressedDurationMs: duration,+ gaps: [],+ toCompressedMs: (realMs) => realMs,+ toRealMs: (compressedMs) => compressedMs,+ };+}++/**+ * @param spans ms offsets of every span that should keep its real width.+ * Roots must be excluded: a root covers the whole trace by definition, so+ * including it means no gap is ever idle.+ */+export function buildTimeCompression(options: {+ spans: readonly Interval[];+ durationMs: number;+ physicalWidth: number;+ enabled: boolean;+}): TimeCompression {+ const { spans, durationMs, physicalWidth } = options;++ if (+ !options.enabled ||+ !Number.isFinite(durationMs) ||+ durationMs <= 0 ||+ !Number.isFinite(physicalWidth) ||+ physicalWidth <= 0+ ) {+ return identityCompression(durationMs);+ }++ // The label buffer is px, so converting it to ms needs a px-per-ms β and+ // that is what compression is about to change, by up to 100Γ. Sentry+ // converts at the UNCOMPRESSED scale, which in a 320px lane reserves ~5.4s+ // around each span of a 36s trace and makes compression a no-op exactly+ // where it is needed most. One fixed-point step fixes it: compress with no+ // buffer, then re-compress with the buffer priced at the resulting scale.+ const unbuffered = compressOnce(spans, durationMs, physicalWidth, 0);+ if (!unbuffered) return identityCompression(durationMs);++ const labelBufferMs =+ (unbuffered.compressedDurationMs / physicalWidth) *+ DURATION_LABEL_BUFFER_PX;++ return (+ compressOnce(spans, durationMs, physicalWidth, labelBufferMs) ?? unbuffered+ );+}++function compressOnce(+ spans: readonly Interval[],+ durationMs: number,+ physicalWidth: number,+ labelBufferMs: number,+): TimeCompression | null {+ const merged = mergeIntervals(padIntervals(spans, durationMs, labelBufferMs));+ const collapsible = collectCollapsibleGaps(merged, durationMs);+ if (collapsible.length === 0) return null;++ const collapsedGapPx = Math.min(+ COLLAPSED_GAP_WIDTH_PX,+ physicalWidth / (collapsible.length + 1),+ );+ const gapWidthRatio = collapsedGapPx / physicalWidth;+ const collapsedDuration = collapsible.reduce(+ (sum, [start, end]) => sum + (end - start),+ 0,+ );+ const activeDuration = durationMs - collapsedDuration;+ const denominator = 1 - gapWidthRatio * collapsible.length;++ if (denominator <= 0 || activeDuration <= 0) return null;++ const compressedDurationMs = activeDuration / denominator;+ const retainedDuration = compressedDurationMs * gapWidthRatio;++ let removedBefore = 0;+ const gaps: CompressedGap[] = collapsible.map(([start, end]) => {+ const compressedStart = start - removedBefore;+ removedBefore += end - start - retainedDuration;+ return {+ start,+ end,+ durationMs: end - start,+ compressedStart,+ compressedEnd: compressedStart + retainedDuration,+ };+ });++ return {+ enabled: true,+ durationMs,+ compressedDurationMs,+ gaps,+ toCompressedMs: (realMs) => {+ let removed = 0;+ for (const gap of gaps) {+ if (realMs < gap.start) break;+ if (realMs <= gap.end) {+ const progress =+ gap.durationMs > 0 ? (realMs - gap.start) / gap.durationMs : 0;+ return gap.compressedStart + progress * retainedDuration;+ }+ removed += gap.durationMs - retainedDuration;+ }+ return realMs - removed;+ },+ toRealMs: (compressedMs) => {+ let restored = 0;+ for (const gap of gaps) {+ if (compressedMs < gap.compressedStart) break;+ if (compressedMs <= gap.compressedEnd) {+ const progress =+ retainedDuration > 0+ ? (compressedMs - gap.compressedStart) / retainedDuration+ : 0;+ return gap.start + progress * gap.durationMs;+ }+ restored += gap.durationMs - retainedDuration;+ }+ return compressedMs + restored;+ },+ };+}++function padIntervals(+ spans: readonly Interval[],+ durationMs: number,+ labelBufferMs: number,+): Interval[] {+ const markerPadding = Math.max(+ Math.min(durationMs * MARKER_PADDING_RATIO, MARKER_PADDING_MAX_MS),+ labelBufferMs,+ );+ const labelBuffer = labelBufferMs;+ const clampMs = (ms: number) => Math.min(Math.max(ms, 0), durationMs);++ return spans.flatMap(([start, end]) => {+ if (!Number.isFinite(start) || !Number.isFinite(end)) return [];+ const from = clampMs(start);+ const to = clampMs(end);+ return to > from+ ? ([+ [clampMs(from - labelBuffer), clampMs(to + labelBuffer)],+ ] as Interval[])+ : ([+ [clampMs(from - markerPadding), clampMs(from + markerPadding)],+ ] as Interval[]);+ });+}++function mergeIntervals(intervals: Interval[]): Interval[] {+ const sorted = intervals+ .filter(([start, end]) => end >= start)+ .sort((a, b) => a[0] - b[0]);++ const merged: Interval[] = [];+ for (const current of sorted) {+ const last = merged[merged.length - 1];+ if (last && current[0] <= last[1]) {+ last[1] = Math.max(last[1], current[1]);+ } else {+ merged.push([current[0], current[1]]);+ }+ }+ return merged;+}++function collectCollapsibleGaps(+ intervals: readonly Interval[],+ durationMs: number,+): Interval[] {+ const threshold = durationMs * COLLAPSE_THRESHOLD_RATIO;+ const gaps: Interval[] = [];+ let previousEnd = 0;++ for (const [start, end] of intervals) {+ if (start - previousEnd >= threshold) gaps.push([previousEnd, start]);+ previousEnd = Math.max(previousEnd, end);+ }+ if (durationMs - previousEnd >= threshold) {+ gaps.push([previousEnd, durationMs]);+ }++ return gaps;+}diff --git a/web/src/features/traces/components/TraceTimelineV2/viewTransform.ts b/web/src/features/traces/components/TraceTimelineV2/viewTransform.tsnew file mode 100644index 0000000000..09f539ff7e--- /dev/null+++ b/web/src/features/traces/components/TraceTimelineV2/viewTransform.ts@@ -0,0 +1,149 @@+/**+ * Four-space view model for the timeline.+ *+ * | space | meaning |+ * | ---------- | -------------------------------------------------------- |+ * | trace | the whole trace in time units β `[0, totalDuration]` |+ * | view | the visible window into trace space β this IS zoom/pan |+ * | physical | the measured pixel box of the chart lane |+ * | container | the measured pixel box of the whole timeline |+ *+ * Default `view === traceSpace` is what makes "the whole trace fits the box at+ * any size, with no horizontal scroll" true by construction rather than by+ * luck. Ported from Sentry's `traceRenderers/traceView.tsx` as scalars: the+ * mat3 composition buys nothing while both spaces are 1-dimensional in time.+ *+ * Total by construction: `pxPerMs` is 0 (never Infinity/NaN) for a degenerate+ * window, so every derived coordinate stays finite and collapses to the lane's+ * left edge instead of exploding.+ *+ * Production code, arriving one PR before its callers: the renderer beside it+ * (`TimelineV2.tsx`) is a Storybook harness and says so, this is not.+ */++export type TimeSpan = {+ /** ms offset from the trace origin */+ start: number;+ /** ms */+ duration: number;+};++export type Box = { width: number; height: number };++/** Zooming past 1ms per lane buys nothing and costs float precision. */+export const MAX_ZOOM_PRECISION_MS = 1;++export type ViewTransform = {+ /** ms in view space β px from the lane's left edge */+ toPx: (ms: number) => number;+ /** px from the lane's left edge β ms in view space */+ toMs: (px: number) => number;+ pxPerMs: number;+};++const finite = (value: number, fallback: number) =>+ Number.isFinite(value) ? value : fallback;++/** Shared with layout(), which clamps bars and labels into the same lane. */+export const clamp = (value: number, min: number, max: number) =>+ Math.min(Math.max(value, min), max);++export function traceSpaceOf(durationMs: number): TimeSpan {+ return { start: 0, duration: Math.max(finite(durationMs, 0), 0) };+}++export function fitView(space: TimeSpan): TimeSpan {+ return { start: space.start, duration: space.duration };+}++/**+ * The window can never leave trace space, nor invert, nor go non-finite.+ *+ * Deviates from Sentry deliberately: at the right edge we hold the zoom level+ * and pull `start` back, where they hold `x` and shrink the window. Holding the+ * zoom is what a pan gesture means β panning past the end should stop, not+ * silently zoom out.+ */+export function clampView(view: TimeSpan, space: TimeSpan): TimeSpan {+ const spaceDuration = Math.max(finite(space.duration, 0), 0);+ const duration = clamp(+ finite(view.duration, spaceDuration),+ Math.min(MAX_ZOOM_PRECISION_MS, spaceDuration),+ spaceDuration,+ );+ const start = clamp(+ finite(view.start, space.start),+ space.start,+ space.start + spaceDuration - duration,+ );+ return { start, duration };+}++export function createViewTransform(view: TimeSpan, box: Box): ViewTransform {+ const width = Math.max(finite(box.width, 0), 0);+ const duration = Math.max(finite(view.duration, 0), 0);+ const pxPerMs = duration > 0 && width > 0 ? width / duration : 0;++ return {+ pxPerMs,+ toPx: (ms) => (finite(ms, view.start) - view.start) * pxPerMs,+ toMs: (px) =>+ pxPerMs > 0 ? view.start + finite(px, 0) / pxPerMs : view.start,+ };+}++/**+ * Zoom about a fixed point in the lane (`anchorRatio` 0 = left edge, 1 = right).+ * `factor > 1` zooms in. The anchored time stays under the cursor/pinch centre.+ */+export function zoomView(+ view: TimeSpan,+ space: TimeSpan,+ options: { factor: number; anchorRatio: number },+): TimeSpan {+ const factor = finite(options.factor, 1);+ if (factor <= 0) return clampView(view, space);++ const anchorRatio = clamp(finite(options.anchorRatio, 0.5), 0, 1);+ const anchorMs = view.start + view.duration * anchorRatio;+ const duration = view.duration / factor;++ return clampView(+ { start: anchorMs - duration * anchorRatio, duration },+ space,+ );+}++export function panView(+ view: TimeSpan,+ space: TimeSpan,+ deltaMs: number,+): TimeSpan {+ return clampView(+ { start: view.start + finite(deltaMs, 0), duration: view.duration },+ space,+ );+}++/** Zoom-to-fit one span, with breathing room on both sides. */+export function zoomToSpan(+ target: TimeSpan,+ space: TimeSpan,+ paddingRatio = 0.1,+): TimeSpan {+ const targetDuration = Math.max(finite(target.duration, 0), 0);+ const padding = Math.max(+ targetDuration * clamp(finite(paddingRatio, 0), 0, 1),+ MAX_ZOOM_PRECISION_MS,+ );+ return clampView(+ {+ start: finite(target.start, space.start) - padding,+ duration: targetDuration + padding * 2,+ },+ space,+ );+}++export const isFitted = (view: TimeSpan, space: TimeSpan): boolean =>+ view.start <= space.start && view.duration >= space.duration;