πͺ’ 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): fit the timeline to its measured lane (#16131)
Nikita Kabardin8a1aa87c69cf
diff --git a/web/src/components/grouped-score-badge.tsx b/web/src/components/grouped-score-badge.tsxindex 53f69fb57e..4224386224 100644--- a/web/src/components/grouped-score-badge.tsx+++ b/web/src/components/grouped-score-badge.tsx@@ -18,6 +18,23 @@ import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";import { ScoreTag, scoreLevelFromScore } from "@/src/components/score-tag";+/**+ * Bucket scores by name, the way the badges group them. Exported so a caller that+ * has to RESERVE room for these badges buckets them identically β two copies of+ * the grouping rule are two chances to price a chip that never renders.+ */+export const groupScoresByName = <+ T extends WithStringifiedMetadata<ScoreDomain> | LastUserScore,+>(+ scores: T[],+): Record<string, T[]> =>+ scores.reduce<Record<string, T[]>>((groups, score) => {+ const bucket = groups[score.name];+ if (!bucket || !Array.isArray(bucket)) groups[score.name] = [score];+ else bucket.push(score);+ return groups;+ }, {});+const partitionScores = <T extends WithStringifiedMetadata<ScoreDomain> | LastUserScore,>(@@ -150,20 +167,22 @@ export const GroupedScoreBadges = <maxVisible,compact,badgeClassName,+ expandable = true,}: {scores: T[];maxVisible?: number;compact?: boolean;badgeClassName?: string;+ /**+ * Whether "+N" expands the hidden chips IN PLACE. A caller that has measured a+ * box for exactly `maxVisible` chips has to say no: expanding is unbounded by+ * construction, so inside a clipping box it does not reveal the hidden scores,+ * it cuts the visible ones. The hover preview stays either way, which is the+ * part that actually shows them.+ */+ expandable?: boolean;}) => {- const groupedScores = scores.reduce<Record<string, T[]>>((acc, score) => {- if (!acc[score.name] || !Array.isArray(acc[score.name])) {- acc[score.name] = [score];- } else {- acc[score.name].push(score);- }- return acc;- }, {});+ const groupedScores = groupScoresByName(scores);// Level tags only when this selection MIXES levels (LFE-10596): a row whose// scores all share one level (the common case β e.g. a span's own@@ -181,12 +200,12 @@ export const GroupedScoreBadges = <const { visibleScores, hiddenScores } = partitionScores(groupedScores,- expanded ? undefined : maxVisible,+ expanded && expandable ? undefined : maxVisible,);const overflowButtonClassName = cn(badgeVariants({ variant: "tertiary" }),- "cursor-pointer",+ expandable ? "cursor-pointer" : "cursor-default",compact ? "px-0.5 py-0 leading-tight" : "px-1","text-xs font-bold",badgeClassName,@@ -213,10 +232,12 @@ export const GroupedScoreBadges = <// the hover-card preview.aria-label={`Show ${hiddenScores.length} more score${hiddenScores.length === 1 ? "" : "s"}`}// Chips render inside clickable rows (tree nodes, table rows) β- // expanding must not also select/navigate the row.+ // expanding must not also select/navigate the row. Still swallowed+ // when expansion is off, or the row would react to a click aimed at+ // the preview.onClick={(event) => {event.stopPropagation();- setExpanded(true);+ if (expandable) setExpanded(true);}}className={overflowButtonClassName}>diff --git a/web/src/features/comments/CommentCountIcon.stories.tsx b/web/src/features/comments/CommentCountIcon.stories.tsxnew file mode 100644index 0000000000..46daacf084--- /dev/null+++ b/web/src/features/comments/CommentCountIcon.stories.tsx@@ -0,0 +1,43 @@+import { expect } from "storybook/test";+import preview from "../../../.storybook/preview";+import { CommentCountIcon } from "./CommentCountIcon";++const meta = preview.meta({+ component: CommentCountIcon,+ args: { count: 3 },+});++export const Single = meta.story({ args: { count: 1 } });+export const TwoDigits = meta.story({ args: { count: 42 } });+export const Capped = meta.story({ args: { count: 1234 } });++/**+ * The count badge overlaps the bubble's corner, and it has to do that from INSIDE+ * the icon's own box. Positioned absolutely it hung outside, so it overlapped+ * whatever followed it in a flow layout, and a clipping ancestor β the trace+ * timeline's metric cluster β cut it mid-glyph at exactly two digits.+ */+export const TheCountStaysInsideTheIconsBox = meta.story({+ name: "(Test) The Count Stays Inside The Icon's Box",+ args: { count: 1234 },+ play: async ({ canvasElement }) => {+ // By testid, not by text: the icon's own wrapper has the same textContent,+ // and a `find` over every span picks the wrapper β which measures nothing.+ const badge = canvasElement.querySelector<HTMLElement>(+ "[data-testid='comment-count']",+ );+ if (!badge) throw new Error("no capped count badge");+ const icon = badge.parentElement!;+ const box = icon.getBoundingClientRect();+ const drawn = badge.getBoundingClientRect();+ // Fully inside, on every side: the timeline's metric cluster clips both axes,+ // so an overhang out of the top is cut just as an overhang out of the right is.+ await expect(drawn.right).toBeLessThanOrEqual(box.right + 0.5);+ await expect(drawn.left).toBeGreaterThanOrEqual(box.left - 0.5);+ await expect(drawn.top).toBeGreaterThanOrEqual(box.top - 0.5);+ await expect(drawn.bottom).toBeLessThanOrEqual(box.bottom + 0.5);+ // And it still overlaps the bubble rather than sitting beside it.+ const bubble = icon.querySelector("svg")!.getBoundingClientRect();+ await expect(drawn.left).toBeLessThan(bubble.right);+ },+});diff --git a/web/src/features/comments/CommentCountIcon.tsx b/web/src/features/comments/CommentCountIcon.tsxindex 6323c1f532..b430b7bb96 100644--- a/web/src/features/comments/CommentCountIcon.tsx+++ b/web/src/features/comments/CommentCountIcon.tsx@@ -6,9 +6,17 @@ export function CommentCountIcon({ count }: { count?: number }) {if (!count) return null;return (- <span className="relative mr-1 text-xs">- <MessageSquareMore className="h-4 w-4" />- <span className="border-muted-foreground bg-muted-foreground text-muted dark:bg-muted dark:text-muted-foreground absolute -top-0.5 left-2.5 flex max-h-[0.8rem] min-w-[0.8rem] items-center justify-center rounded-sm border px-[0.2rem] text-[8px] shadow-xs">+ // The count overlaps the bubble's corner by a negative margin rather than by+ // `absolute`: positioned absolutely it sat OUTSIDE this span's own box, so it+ // overlapped whatever followed in a flow layout, and a clipping ancestor β+ // the trace timeline's metric cluster β cut a two-digit count mid-glyph.+ // In flow, the overhang is part of the footprint and everything reserves it.+ <span className="mr-1 inline-flex items-start text-xs">+ <MessageSquareMore className="h-4 w-4 shrink-0" />+ <span+ data-testid="comment-count"+ className="border-muted-foreground bg-muted-foreground text-muted dark:bg-muted dark:text-muted-foreground -ml-2 flex max-h-[0.8rem] min-w-[0.8rem] shrink-0 items-center justify-center rounded-sm border px-[0.2rem] text-[8px] shadow-xs"+ >{count > 99 ? "99+" : count}</span></span>diff --git a/web/src/features/traces/components/TraceTimeline/TimelineBar.stories.tsx b/web/src/features/traces/components/TraceTimeline/TimelineBar.stories.tsxindex ab418ded1d..7bcbc47587 100644--- a/web/src/features/traces/components/TraceTimeline/TimelineBar.stories.tsx+++ b/web/src/features/traces/components/TraceTimeline/TimelineBar.stories.tsx@@ -1,12 +1,33 @@+import { expect, userEvent, waitFor } from "storybook/test";import preview from "../../../../../.storybook/preview";-import { TimelineBar } from "./TimelineBar";-import { makeTreeNode, makeMetrics, cost } from "./__tests__/timeline.fixtures";+import {+ MAX_SCORE_GROUPS,+ SCORE_GROUP_GAP_PX,+ TimelineBar,+ overflowButtonWidth,+ scoreBadgesWidth,+} from "./TimelineBar";+import {+ createTextMeasurer,+ createTextMeasurerFrom,+} from "../../fns/timeline/textMeasurer";+import { resolveDensity } from "../../fns/timeline/density";+import {+ makeRow,+ makeTreeNode,+ cost,+ score,+} from "./__tests__/timeline.fixtures";const meta = preview.meta({component: TimelineBar,args: {- node: makeTreeNode(),- metrics: makeMetrics(),+ row: makeRow(),+ laneWidth: 640,+ measurer: createTextMeasurer(),+ // The same density layout() positions with β the cluster's gap and inset+ // come from it, so a story that omitted it would measure a different bar.+ density: resolveDensity({ pointer: "fine" }),isSelected: false,showDuration: true,showCostTokens: false,@@ -33,32 +54,484 @@ export const Selected = meta.story({export const ZeroDuration = meta.story({args: {- node: makeTreeNode({- endTime: new Date("2024-01-01T00:00:00.000Z"),- latency: 0,+ row: makeRow({+ node: makeTreeNode({+ endTime: new Date("2024-01-01T00:00:00.000Z"),+ latency: 0,+ }),+ width: 4,+ durationMs: 0,+ label: "0.00s",+ labelX: 70,}),- metrics: makeMetrics({ itemWidth: 0, latency: 0 }),},});export const Streaming = meta.story({args: {- metrics: makeMetrics({- startOffset: 60,- itemWidth: 260,- firstTokenTimeOffset: 150,+ row: makeRow({ width: 260, firstTokenX: 150, labelX: 326 }),+ },+});++/** No room on either side of the bar, so nothing in the cluster fits. */+export const LabelHidden = meta.story({+ args: {+ row: makeRow({ x: 636, width: 4, labelPlacement: "hidden" }),+ },+});++/**+ * An in-flight span has no duration to label, but it can still have a comment,+ * a cost or a score β and room in the lane to show them.+ */+export const InFlightWithComments = meta.story({+ name: "(Test) In Flight Span Keeps Its Icons",+ args: {+ showComments: true,+ commentCount: 2,+ row: makeRow({+ node: makeTreeNode({ endTime: null, latency: undefined }),+ width: 40,+ durationMs: null,+ label: "",+ labelWidth: 0,+ labelPlacement: "hidden",}),},+ play: async ({ canvasElement }) => {+ // `hidden` is layout()'s verdict on the duration LABEL. Reading it as a+ // verdict on the whole cluster hid every icon on every in-flight span.+ await waitFor(() =>+ expect(canvasElement.querySelector("svg")).not.toBeNull(),+ );+ await expect(canvasElement.textContent).toContain("2");+ },+});++/**+ * A leftover budget that fits either the comment icon or the score badges, but+ * not both. They are charged to one running budget, so the cluster still ends up+ * narrower than the space it was given.+ */+export const CrowdedCluster = meta.story({+ name: "(Test) Crowded Cluster Never Clips",+ args: {+ showComments: true,+ showScores: true,+ commentCount: 3,+ scores: [score("quality", 0.92), score("helpfulness", 0.71)],+ // 90px of room after the bar: enough for the duration and then EITHER the+ // comment icon (22px) or the score badges (48px), never both.+ row: makeRow({ x: 60, width: 484, labelX: 550 }),+ },+ play: async ({ canvasElement }) => {+ const cluster = canvasElement.querySelector<HTMLElement>(+ "div[style*='max-width']",+ );+ if (!cluster) throw new Error("metric cluster not found");++ // Admitting the icon and the badges against the SAME leftover let both in,+ // and their combined width was then clipped by the cluster's overflow box β+ // the mid-content clipping this whole layout exists to remove. Charged to one+ // running budget, the badges are dropped rather than half-drawn.+ await expect(cluster.textContent).toContain("2.00s");+ await expect(cluster.textContent).not.toContain("quality");+ await expect(cluster.scrollWidth).toBeLessThanOrEqual(+ cluster.clientWidth + 0.5,+ );+ // What was dropped stays reachable, counts and all: a narrow row used not to+ // mention that a comment or a score existed at all.+ await expect(cluster.title).toContain("3 comments");+ await expect(cluster.title).toContain("2 scores");+ },+});++/**+ * Two real scores render 100-300px, not the 48px a flat reservation assumed. A+ * lane with room for the duration and *almost* room for the badges is where that+ * gap used to clip them mid-glyph.+ */+export const ScoreBadgesArePricedFromTheirContent = meta.story({+ name: "(Test) Score Badges Are Priced From Their Content",+ args: {+ showScores: true,+ scores: [+ score("helpfulness-of-the-answer", 0.71),+ score("factual-accuracy", 0.92),+ ],+ row: makeRow({ x: 60, width: 420, labelX: 486 }),+ },+ play: async ({ canvasElement }) => {+ const cluster = canvasElement.querySelector<HTMLElement>(+ "div[style*='max-width']",+ );+ if (!cluster) throw new Error("metric cluster not found");+ await expect(cluster.scrollWidth).toBeLessThanOrEqual(+ cluster.clientWidth + 0.5,+ );+ // Either the badges fit whole, or they are not drawn β never half-drawn.+ const showsBadges = cluster.textContent?.includes("factual-accuracy");+ if (showsBadges) {+ await expect(cluster.textContent).toContain("helpfulness");+ } else {+ await expect(cluster.title).toContain("2 scores");+ }+ },+});++/**+ * A bar hard against the right edge: the duration fits on neither side, but the+ * space BEFORE it is wide open. The cluster belongs there, not in the 0px after.+ */+/**+ * The widest a chip gets: a row that MIXES score levels grows a spelled-out pill+ * per chip ("Observation", not a dot), and a value carrying both a comment and+ * metadata grows two icons. Under-price any of those and the badges are admitted+ * and then clipped β the one direction that must not happen.+ */+export const AnnotatedMixedLevelScoresAreNeverClipped = meta.story({+ name: "(Test) Annotated Mixed-Level Scores Are Never Clipped",+ args: {+ showScores: true,+ scores: [+ score("quality", 0.92, {+ level: "observation",+ comment: "looks right",+ metadata: '{"model":"gpt-5.4"}',+ }),+ score("quality", 0.71, { level: "trace" }),+ ],+ row: makeRow({ x: 60, width: 300, labelX: 366 }),+ },+ play: async ({ canvasElement }) => {+ const cluster = canvasElement.querySelector<HTMLElement>(+ "div[style*='max-width']",+ );+ if (!cluster) throw new Error("metric cluster not found");+ // Whole or absent, never half-drawn.+ await expect(cluster.scrollWidth).toBeLessThanOrEqual(+ cluster.clientWidth + 0.5,+ );+ if (cluster.textContent?.includes("quality")) {+ // If it was admitted, everything it brings has to fit: the level pill too.+ await expect(cluster.innerText).toMatch(/Observation|Trace/);+ } else {+ await expect(cluster.title).toContain("2 scores");+ }+ },+});++/**+ * The invariant behind all of the above, asserted directly: what the cluster+ * RESERVES for the badges is never less than what they render at.+ *+ * The two stories above can only catch a mispricing that changes the admit/drop+ * decision at their one lane width, so three rounds of under-reservation+ * (a flat 48px, a flat level pill, one gap instead of one per child) passed+ * them. This one prices the same scores the bar prices, measures the DOM the+ * badges actually produced, and compares the two numbers.+ */+/**+ * A measurer seeded from what the DOM is ACTUALLY setting the chips in, the way+ * the app seeds one from a tick-label probe. Pricing text against a font nothing+ * renders in would make a band assertion pass for the wrong reason.+ */+const measurerFor = (element: HTMLElement) => {+ const style = getComputedStyle(element);+ return createTextMeasurerFrom(+ document.createElement("canvas").getContext("2d"),+ `${style.fontSize} ${style.fontFamily}`,+ );+};++// Every width-bearing feature at once: two levels in one group (two pills), two+// values under one name (comma + separator), a value carrying BOTH a comment and+// metadata (two icons), and a name at the truncation limit.+const PRICED_SCORES = [+ score("quality", 0.92, {+ level: "observation",+ comment: "looks right",+ metadata: '{"model":"gpt-5.4"}',+ }),+ score("quality", 0.71, { level: "trace" }),+ score("helpfulness-of-the-answer", 0.68, { level: "trace" }),+];++export const ScorePricingNeverUnderReserves = meta.story({+ name: "(Test) Score Pricing Never Under-Reserves",+ args: {+ showScores: true,+ scores: PRICED_SCORES,+ laneWidth: 900,+ row: makeRow({ x: 0, width: 120, labelX: 126 }),+ },+ play: async ({ canvasElement }) => {+ const rendered = await waitFor(() => {+ const el = canvasElement.querySelector<HTMLElement>(+ "[data-testid='timeline-bar-scores']",+ );+ if (!el) throw new Error("the badges were not admitted at all");+ return el;+ });+ const priced = scoreBadgesWidth(+ PRICED_SCORES,+ measurerFor(rendered),+ MAX_SCORE_GROUPS,+ );+ // Under a clipping ancestor the box would report the SMALLER of natural and+ // available, which would make any under-price look safe. Compare against a+ // width that is actually the badges' own.+ await expect(rendered.scrollWidth).toBeLessThanOrEqual(+ rendered.clientWidth,+ );+ const actual = rendered.getBoundingClientRect().width;++ // Never below: the cluster's overflow box cuts whatever it over-admits.+ await expect(priced).toBeGreaterThanOrEqual(actual);+ // And within a few px above, which is what makes the line above bite: with+ // loose slack anywhere in the sum, a whole missing term still "passes". The+ // budget here is 2 chips' measurement margin plus the icons' rounding.+ await expect(priced - actual).toBeLessThan(12);+ },+});++// Thirteen distinct names, all the same shape, so the three admitted chips are+// interchangeable and the only variable left is the "+10" button. Categorical, so+// every chip is measured exactly and the band below is tight enough to be about+// the button rather than about the slack in three numeric values.+const MANY_SCORES = Array.from({ length: 13 }, (_, index) =>+ score(`score-${String.fromCharCode(97 + index)}`, 0, {+ stringValue: "good",+ }),+);++/**+ * The same invariant with the overflow button in play. A flat reservation for+ * "+N" was fine until a node carried ten hidden groups and the button grew a+ * second digit β which the cluster then clipped, having priced one.+ */+export const OverflowButtonIsPricedFromItsDigits = meta.story({+ name: "(Test) Overflow Button Is Priced From Its Digits",+ args: {+ showScores: true,+ scores: MANY_SCORES,+ row: makeRow({ x: 0, width: 120, labelX: 126 }),+ },+ play: async ({ canvasElement }) => {+ const rendered = await waitFor(() => {+ const el = canvasElement.querySelector<HTMLElement>(+ "[data-testid='timeline-bar-scores']",+ );+ if (!el) throw new Error("the badges were not admitted at all");+ return el;+ });+ // Ten hidden groups, so the button is two digits wide β the case a flat+ // reservation got wrong.+ await expect(rendered.textContent).toContain("+10");+ await expect(rendered.scrollWidth).toBeLessThanOrEqual(+ rendered.clientWidth,+ );+ const priced = scoreBadgesWidth(+ MANY_SCORES,+ measurerFor(rendered),+ MAX_SCORE_GROUPS,+ );+ const actual = rendered.getBoundingClientRect().width;+ await expect(priced).toBeGreaterThanOrEqual(actual);++ // And the button against ITS own box, which is the sharp version: a+ // cluster-wide band cannot isolate this term, because pricing deliberately+ // charges the WIDEST groups while the DOM renders the alphabetically first+ // ones, and that difference is bigger than a digit.+ const button = rendered.querySelector<HTMLElement>("button");+ if (!button) throw new Error("no overflow button");+ const charged =+ overflowButtonWidth(10, measurerFor(rendered)) - SCORE_GROUP_GAP_PX;+ const drawn = button.getBoundingClientRect().width;+ await expect(charged).toBeGreaterThanOrEqual(drawn);+ // A wider ceiling than the chips get: this term carries an explicit margin,+ // because its measurement is the one that moved between font stacks.+ await expect(charged - drawn).toBeLessThan(8);+ // Bold is what it renders in, so bold is what it must be priced at β the+ // regular weight is short, and short is the direction that clips.+ const regular = measurerFor(rendered).measure("+10");+ await expect(measurerFor(rendered).measureBold("+10")).toBeGreaterThan(+ regular,+ );+ },+});++/**+ * A comment count is a badge hanging off the corner of its bubble. It used to+ * hang outside the icon's own box, so the cluster's clip cut it β and only ever+ * for a 2-digit count, which is why it survived the single-digit stories.+ */+export const CommentCountIsNeverClipped = meta.story({+ name: "(Test) Comment Count Is Never Clipped",+ args: {+ showComments: true,+ commentCount: 42,+ showDuration: false,+ // Room to spare, so the icon is certainly drawn and this is about its shape.+ row: makeRow({ x: 0, width: 500, labelPlacement: "hidden" }),+ },+ play: async ({ canvasElement }) => {+ const cluster = canvasElement.querySelector<HTMLElement>(+ "div[style*='max-width']",+ );+ if (!cluster) throw new Error("metric cluster not found");+ if (!cluster.textContent?.includes("42")) {+ // Dropped rather than clipped is the other acceptable outcome, and then+ // the row still has to say the comments exist.+ await expect(cluster.title).toContain("42 comments");+ return;+ }+ // Admitted: the count has to be whole, inside the icon's box and inside the+ // cluster's.+ const badge = cluster.querySelector<HTMLElement>(+ "[data-testid='comment-count']",+ );+ if (!badge) throw new Error("no count badge");+ const icon = badge.parentElement!.getBoundingClientRect();+ await expect(badge.getBoundingClientRect().right).toBeLessThanOrEqual(+ icon.right + 0.5,+ );+ await expect(cluster.scrollWidth).toBeLessThanOrEqual(+ cluster.clientWidth + 0.5,+ );+ },+});++/**+ * And the same count against a budget that leaves room for the bubble but not for+ * its badge. Whichever way it goes β drawn whole or refused β the cluster must not+ * end up holding half a number, which is what a flat "an icon is 22px" produced+ * once the badge became part of the icon's footprint.+ */+export const CommentCountIsPricedFromItsDigits = meta.story({+ name: "(Test) Comment Count Is Priced From Its Digits",+ args: {+ showComments: true,+ commentCount: 42,+ showDuration: false,+ // 24px of lane left after the bar: a two-digit count needs a little more.+ row: makeRow({ x: 0, width: 610, labelPlacement: "hidden" }),+ },+ play: async ({ canvasElement }) => {+ const cluster = canvasElement.querySelector<HTMLElement>(+ "div[style*='max-width']",+ );+ if (cluster) {+ // Admitted: whole, or not at all β never a half-drawn number.+ await expect(cluster.scrollWidth).toBeLessThanOrEqual(+ cluster.clientWidth + 0.5,+ );+ if (!cluster.textContent?.includes("42")) {+ await expect(cluster.title).toContain("42 comments");+ }+ return;+ }+ // Refused, which is the correct outcome at this width β and then the bar+ // itself has to say the comments exist, since there is no cluster left to.+ const bar = canvasElement.querySelector<HTMLElement>("div[title]");+ if (!bar) throw new Error("nothing on the row mentions the comments");+ await expect(bar.title).toContain("42 comments");+ },+});++/**+ * "+N" cannot expand in place here. The cluster was measured for three chips, so+ * an unbounded expansion inside its clip does not reveal the hidden scores β it+ * cuts the ones already on screen.+ */+export const ExpandingOverflowCannotClipTheCluster = meta.story({+ name: "(Test) Expanding Overflow Cannot Clip The Cluster",+ args: {+ showScores: true,+ scores: MANY_SCORES,+ row: makeRow({ x: 0, width: 120, labelX: 126 }),+ },+ play: async ({ canvasElement }) => {+ const cluster = canvasElement.querySelector<HTMLElement>(+ "div[style*='max-width']",+ );+ if (!cluster) throw new Error("metric cluster not found");+ const button = canvasElement.querySelector<HTMLElement>(+ "button[aria-label*='more score']",+ );+ if (!button) throw new Error("no overflow button");+ const before = cluster.textContent;+ await userEvent.click(button);+ // Nothing expanded, and nothing was cut.+ await expect(cluster.textContent).toBe(before);+ await expect(cluster.scrollWidth).toBeLessThanOrEqual(+ cluster.clientWidth + 0.5,+ );+ },+});++/**+ * A streaming bar is two phases in one bar, told apart by shade. The frame must+ * not paint the ground: a translucent wait over an opaque frame of the same+ * colour composites back to that colour, and the split disappears.+ */+export const StreamingPhasesReadAsTwoShades = meta.story({+ name: "(Test) Streaming Phases Read As Two Shades",+ args: {+ row: makeRow({ x: 40, width: 400, firstTokenX: 160, labelX: 446 }),+ },+ play: async ({ canvasElement }) => {+ const waiting = canvasElement.querySelector<HTMLElement>(+ "div[title='Time to first token']",+ );+ if (!waiting) throw new Error("no first-token segment");+ const completion = waiting.nextElementSibling as HTMLElement | null;+ if (!completion) throw new Error("no completion segment");+ // Same hue, different shade β and the difference has to survive whatever the+ // frame paints behind them.+ const frame = waiting.parentElement!;+ await expect(getComputedStyle(frame).backgroundColor).toMatch(+ /rgba\(0, 0, 0, 0\)|transparent/,+ );+ await expect(Number(getComputedStyle(waiting).opacity)).toBeLessThan(+ Number(getComputedStyle(completion).opacity),+ );+ },+});++export const HiddenLabelUsesTheRoomierSide = meta.story({+ name: "(Test) Hidden Label Uses The Roomier Side",+ args: {+ showComments: true,+ commentCount: 4,+ row: makeRow({ x: 600, width: 38, labelPlacement: "hidden" }),+ },+ play: async ({ canvasElement }) => {+ const cluster = canvasElement.querySelector<HTMLElement>(+ "div[style*='max-width']",+ );+ if (!cluster) throw new Error("the cluster went nowhere at all");+ const box = cluster.getBoundingClientRect();+ const bar = canvasElement+ .querySelector<HTMLElement>("div[style*='left: 600px']")+ ?.getBoundingClientRect();+ if (!bar) throw new Error("no bar");+ // Left of the bar, and inside the lane.+ await expect(box.right).toBeLessThanOrEqual(bar.left + 0.5);+ await expect(box.width).toBeGreaterThan(0);+ },});export const WithCostAndTokens = meta.story({args: {showCostTokens: true,- node: makeTreeNode({- totalCost: cost(0.0021),- inputUsage: 320,- outputUsage: 140,- totalUsage: 460,+ row: makeRow({+ node: makeTreeNode({+ totalCost: cost(0.0021),+ inputUsage: 320,+ outputUsage: 140,+ totalUsage: 460,+ }),}),},});diff --git a/web/src/features/traces/components/TraceTimeline/TimelineBar.tsx b/web/src/features/traces/components/TraceTimeline/TimelineBar.tsxindex 0e794b3893..16fb3a4e07 100644--- a/web/src/features/traces/components/TraceTimeline/TimelineBar.tsx+++ b/web/src/features/traces/components/TraceTimeline/TimelineBar.tsx@@ -5,12 +5,25 @@* start offset, followed by a trailing metric label. Identity (badge, name) and* hierarchy (tree connectors) live in the gutter (TimelineGutterRow) β not here β so* the bar can sit at its true time position without dragging the tree with it.+ *+ * Every coordinate arrives already computed from `layout()`, including WHICH SIDE+ * of the bar the metric cluster goes on. That decision used to belong to CSS+ * flow, which cannot see the lane's width and so pushed the cluster off-screen+ * in a narrow lane; the lane no longer scrolls horizontally, so off-screen means+ * gone. See fns/timeline/layout.ts.*/import { type TimelineBarProps } from "./types";import { cn } from "@/src/utils/tailwind";import { CommentCountIcon } from "@/src/features/comments/CommentCountIcon";-import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";+import {+ GroupedScoreBadges,+ groupScoresByName,+} from "@/src/components/grouped-score-badge";+import {+ SCORE_LEVEL_LABELS,+ scoreLevelFromScore,+} from "@/src/components/score-tag";import { formatIntervalSeconds } from "@/src/utils/dates";import { usdFormatter } from "@/src/utils/numbers";import { getSubtreeDurationOverflowMs } from "@/src/features/traces/fns/getSubtreeDurationOverflowMs";@@ -20,12 +33,187 @@ import { isPresent } from "@langfuse/shared";const SUBTREE_DURATION_TITLE ="Subtree wall-clock duration (first start β last end)";-// Keep zero/near-zero-duration spans visible as a small marker.-const MIN_BAR_WIDTH = 4;+/**+ * The cluster's own `gap-2`. The budget has to reserve the gap the cluster+ * actually renders with, not a smaller one: five admitted items multiply a 2px+ * under-reservation into a clipped last item.+ */+const CLUSTER_ITEM_GAP_PX = 8;+/** The speech bubble of a comment icon, plus its own `mr-1`. */+const ICON_GLYPH_PX = 20;+/** Its count badge overlaps the bubble by `-ml-2`, so only the rest is width. */+const ICON_BADGE_OVERLAP_PX = 7;+/** `px-[0.2rem]` both sides plus the badge's 1px border. */+const ICON_BADGE_CHROME_PX = 8;+/** `min-w-[0.8rem]` floors a single digit. */+const ICON_BADGE_MIN_PX = 12;++/**+ * A comment icon is its bubble plus a count badge, and the badge grows with the+ * count β 99 comments is wider than 9, and "99+" wider again. A flat number for+ * "an icon" under-reserved every 2-digit count, which is the direction that+ * clips: the badge is in the flow now, so what it takes is what it takes.+ *+ * The digits are measured at the cluster's own font, a little larger than the+ * badge's `text-[8px]`, which over-reserves by a px or two and never under.+ */+function commentIconWidth(+ count: number,+ measurer: TimelineBarProps["measurer"],+): number {+ const label = count > 99 ? "99+" : String(count);+ const badge = Math.max(+ measurer.measure(label) + ICON_BADGE_CHROME_PX,+ ICON_BADGE_MIN_PX,+ );+ return ICON_GLYPH_PX - ICON_BADGE_OVERLAP_PX + badge;+}+/** `px-2.5` both sides plus the 1px border of a score chip. */+const SCORE_CHIP_CHROME_PX = 22;+/** `max-w-20` truncates a score's name. */+const SCORE_NAME_MAX_PX = 80;+/** `gap-1`, which a score chip applies between EVERY one of its flex children. */+const SCORE_GAP_PX = 4;+/** `gap-1` plus the value span's own `ml-1`, between two values of one name. */+const SCORE_VALUE_SEPARATOR_PX = 8;+/**+ * One `size-3` icon plus its gap, rounded up (the app's root font scale makes a+ * `size-3` 10.8px). A value can carry BOTH a comment and metadata, and they+ * render as two separate icons.+ */+const SCORE_VALUE_ICON_PX = 16;+/** `px-1` both sides of a ScoreTag level pill; the label itself is measured. */+const SCORE_PILL_CHROME_PX = 8;+/** `px-1` both sides of the "+N" button for groups past `maxVisible`, and its border. */+const SCORE_OVERFLOW_CHROME_PX = 10;+/** `gap-1` on the score-badges wrapper β not the cluster's own `gap-2`. */+export const SCORE_GROUP_GAP_PX = 4;+/**+ * A canvas measurement and the browser's own layout of the same string agree to+ * a fraction of a px, not exactly β enough that a chip priced to the last tenth+ * came out 0.09px short on another font stack. One px a chip, in the direction+ * that does not clip.+ */+const MEASURE_MARGIN_PX = 1;++/**+ * The trailing "+N" button, plus the `gap-1` before it. Its digits are measured+ * because a flat number for it under-priced every count past 9 β a node can+ * carry a dozen distinct score names, and "+10" is wider than "+9".+ */+export function overflowButtonWidth(+ hidden: number,+ measurer: TimelineBarProps["measurer"],+): number {+ // Bold, and measured as bold: at the regular weight this came out ~4% short,+ // which fitted on one font stack and clipped on another. Two px of margin on+ // top, because this is the one item whose own measurement was observed to+ // disagree with layout by more than a rounding error, and it is admitted last+ // β over-reserving it can only drop badges in a lane that was borderline+ // anyway, while under-reserving it cuts a digit off.+ return (+ measurer.measureBold(`+${hidden}`) ++ SCORE_OVERFLOW_CHROME_PX ++ SCORE_GROUP_GAP_PX ++ MEASURE_MARGIN_PX * 2+ );+}++/**+ * What `GroupedScoreBadges` will actually take, measured rather than guessed.+ *+ * A flat 48px reservation was the bug: two real scores render 100-300px, so a+ * leftover budget anywhere in between admitted the badges and then let the+ * cluster's overflow box cut them mid-glyph β exactly the clipping this layout+ * exists to remove, in exactly the narrow lanes it targets. The widest groups are+ * priced, because over-reserving drops a badge (recoverable, and the title says+ * so) while under-reserving clips one (not recoverable).+ *+ * Every term here is one the DOM actually charges, and the gap between this sum+ * and the rendered width is pinned in Storybook β three rounds of missing terms+ * (a flat 48px, a flat level pill, one gap instead of one per child) all passed+ * stories that could only see the admit-or-drop decision at one lane width.+ */+export function scoreBadgesWidth(+ scores: NonNullable<TimelineBarProps["scores"]>,+ measurer: TimelineBarProps["measurer"],+ maxVisible: number,+): number {+ // Bucketed by the badges' own grouping rule, so this cannot price a chip that+ // never renders β or miss one that does.+ const groups = Object.entries(groupScoresByName(scores));+ // Level pills appear only when the row MIXES levels; a row whose scores share+ // one level needs no per-chip disambiguation. Same rule the badges use.+ const mixesLevels =+ new Set(scores.map((score) => scoreLevelFromScore(score))).size > 1;++ const comma = measurer.measure(",");++ const widths = groups+ .map(([name, group]) => {+ // Each value is its own flex span: the text, one icon per comment and per+ // metadata (a value carrying both grows two), and a comma on all but the+ // last. Two spans are separated by the box's `gap-1` AND the span's `ml-1`.+ const values = group.reduce((total, score, index) => {+ const text = score.stringValue ?? score.value?.toFixed(2) ?? "";+ const icons = (score.comment ? 1 : 0) + (score.metadata ? 1 : 0);+ const separator =+ index === group.length - 1+ ? 0+ : SCORE_GAP_PX + comma + SCORE_VALUE_SEPARATOR_PX;+ return (+ total ++ measurer.measure(text) ++ icons * SCORE_VALUE_ICON_PX ++ separator+ );+ }, 0);+ // The pill spells its level out ("Observation" is not "Trace"), so it is+ // measured rather than assumed.+ const levels = mixesLevels+ ? [...new Set(group.map((score) => scoreLevelFromScore(score)))]+ : [];+ const pills = levels.reduce(+ (total, level) =>+ total ++ measurer.measure(SCORE_LEVEL_LABELS[level]) ++ SCORE_PILL_CHROME_PX,+ 0,+ );+ // The chip is one `gap-1` flex row whose direct children are every level+ // pill, the name, and the values box β so N pills mean N + 1 gaps. Pricing+ // the name-to-values gap alone under-reserved a mixed-level chip by 4px+ // per extra pill, and the cluster's overflow box cuts what it admits.+ const gaps = (levels.length + 1) * SCORE_GAP_PX;+ return (+ Math.min(measurer.measure(`${name}:`), SCORE_NAME_MAX_PX) ++ values ++ pills ++ gaps ++ SCORE_CHIP_CHROME_PX ++ MEASURE_MARGIN_PX+ );+ })+ .sort((a, b) => b - a)+ .slice(0, maxVisible);++ // Groups past the cap collapse into a "+N" button, which is also width.+ const hidden = groups.length - maxVisible;+ const overflow = hidden > 0 ? overflowButtonWidth(hidden, measurer) : 0;+ return widths.reduce(+ (total, width, index) =>+ total + width + (index > 0 ? SCORE_GROUP_GAP_PX : 0),+ overflow,+ );+}++/** How many score groups the cluster shows before the rest are hidden. */+export const MAX_SCORE_GROUPS = 3;export function TimelineBar({- node,- metrics,+ row,+ laneWidth,+ measurer,isSelected,isHovered,showDuration,@@ -37,16 +225,21 @@ export function TimelineBar({parentTotalDuration,commentCount,scores,+ density,}: TimelineBarProps) {- const { startOffset, itemWidth, firstTokenTimeOffset, latency } = metrics;- const duration = latency ? latency * 1000 : undefined;-- // Own-span basis mirrors SpanContent: fall back to node.latency when there's- // no endTime (e.g. the synthetic v4 trace-root span) so tree and timeline- // agree. Wall-clock subtree duration is surfaced only when async descendants- // outlive this node's own span (LFE-10475).- const ownDurationMs =- duration ?? (node.latency ? node.latency * 1000 : undefined);+ // Room between the bar and a metric cluster outside it, and the inset of one+ // sitting inside: `density`'s own values, threaded in rather than copied. These+ // are the exact numbers `placeLabel()` measured the placement with, so a local+ // copy would be a silent desync waiting for the first change to density.+ const CLUSTER_GAP_PX = density.labelGapPx;+ const CLUSTER_INSET_PX = density.labelPaddingPx;+ const node = row.node;++ // `layout()` already applies the latency fallback (`hasDuration` covers it), so+ // a second one here could only ever run when latency is absent too. Wall-clock+ // subtree duration is surfaced only when async descendants outlive this node's+ // own span.+ const ownDurationMs = row.durationMs ?? undefined;const subtreeWallClockOverflowMs = showDuration? getSubtreeDurationOverflowMs(ownDurationMs,@@ -62,105 +255,223 @@ export function TimelineBar({? "ring-tertiary ring-2": "";- // Trailing label: rides just after the bar so metrics stay readable no matter- // how thin the bar is. Respects the same view toggles as the tree.- const label = (- <div className="text-muted-foreground flex items-center gap-2 text-xs whitespace-nowrap">- {showComments && commentCount ? (- <CommentCountIcon count={commentCount} />- ) : null}- {showDuration && isPresent(ownDurationMs) && (- <span- className={cn(- parentTotalDuration &&- colorCodeMetrics &&- heatMapTextColor({- max: parentTotalDuration,- value: ownDurationMs,- }),- )}- >- {formatIntervalSeconds(ownDurationMs / 1000)}- </span>- )}- {isPresent(ownDurationMs) && subtreeWallClockOverflowMs != null && (- <span title={SUBTREE_DURATION_TITLE}>- {"β "}- {formatIntervalSeconds(subtreeWallClockOverflowMs / 1000)}- </span>- )}- {showCostTokens && node.totalCost && (- <span- className={cn(- parentTotalCost &&- colorCodeMetrics &&- heatMapTextColor({- max: parentTotalCost,- value: node.totalCost,- }),- )}- >- {usdFormatter(node.totalCost.toNumber())}- </span>- )}- {showScores && scores && scores.length > 0 && (- <div className="flex max-h-5 gap-1">- <GroupedScoreBadges scores={scores} maxVisible={3} />- </div>- )}- </div>+ // Which side the metric cluster lands on is layout()'s call, made against the+ // measured lane; we only turn it into a position. `hidden` means neither side+ // had room, so nothing is drawn rather than something drawn off the lane.+ // `hidden` means the DURATION LABEL fitted on neither side β not that neither+ // side has room. The cluster's other items are much narrower, so it goes to+ // whichever side is actually roomier instead of always falling in with+ // `after`, which in a lane like 137px is often the side with nothing left.+ const spaceBefore = Math.max(row.x - CLUSTER_GAP_PX, 0);+ const spaceAfter = Math.max(+ laneWidth - (row.x + row.width + CLUSTER_GAP_PX),+ 0,);+ const placement =+ row.labelPlacement === "hidden" && spaceBefore > spaceAfter+ ? "before"+ : row.labelPlacement;- // Split bar for streaming LLMs (first token time): waiting segment + completion.- if (firstTokenTimeOffset) {- const firstTokenWidth = Math.max(firstTokenTimeOffset - startOffset, 0);- const completionWidth = Math.max(- itemWidth - firstTokenWidth,- MIN_BAR_WIDTH,- );+ const clusterStyle =+ placement === "before"+ ? {+ right: `${Math.max(laneWidth - row.x + CLUSTER_GAP_PX, 0)}px`,+ maxWidth: `${Math.max(row.x - CLUSTER_GAP_PX, 0)}px`,+ }+ : placement === "inside"+ ? {+ left: `${row.x + CLUSTER_INSET_PX}px`,+ maxWidth: `${Math.max(row.width - CLUSTER_INSET_PX * 2, 0)}px`,+ }+ : {+ left: `${row.x + row.width + CLUSTER_GAP_PX}px`,+ maxWidth: `${Math.max(+ laneWidth - (row.x + row.width + CLUSTER_GAP_PX),+ 0,+ )}px`,+ };++ // layout() measures the duration; the optional metrics are this component's+ // own content, so it fits them here with the SAME measurer rather than+ // letting them clip mid-glyph at the lane edge. Highest priority first: a+ // duration always beats a cost you cannot finish reading.+ const budgetPx = Number.parseFloat(clusterStyle.maxWidth);+ let spentPx = 0;+ /**+ * Admit a piece of the cluster, or refuse it β and charge it if admitted. The+ * flex gap sits BETWEEN children, so the first item is charged none: billing it+ * for a gap it does not have rejected content that renders perfectly well+ * alone (a 32px duration against a 39px budget).+ */+ const fitsWidth = (widthPx: number) => {+ const next = spentPx + widthPx + (spentPx > 0 ? CLUSTER_ITEM_GAP_PX : 0);+ if (next > budgetPx) return false;+ spentPx = next;+ return true;+ };+ const fitsCluster = (text: string) => fitsWidth(measurer.measure(text));++ // The layout measured this exact string, which is why the bar renders it+ // rather than formatting the duration a second time: two formatters disagree+ // above an hour, and the side layout() chose was chosen for the shorter one.+ const durationText = showDuration && row.label ? row.label : null;+ const subtreeText =+ isPresent(ownDurationMs) && subtreeWallClockOverflowMs != null+ ? `β ${formatIntervalSeconds(subtreeWallClockOverflowMs / 1000)}`+ : null;+ const costText =+ showCostTokens && node.totalCost+ ? usdFormatter(node.totalCost.toNumber())+ : null;++ // `hidden` is layout()'s verdict on the DURATION LABEL β neither side of the+ // bar had room for it, or there is no duration to show yet. It is not a verdict+ // on the icons, which are much narrower and may well fit.+ const showDurationText =+ durationText != null &&+ row.labelPlacement !== "hidden" &&+ fitsCluster(durationText);+ const showSubtreeText = subtreeText != null && fitsCluster(subtreeText);+ const showCostText = costText != null && fitsCluster(costText);+ // Both are charged through the SAME running budget. Checking each against one+ // leftover let a comment icon and score badges both be admitted on the same+ // 48px, and their combined width then clipped the badges inside the cluster's+ // overflow box.+ const showCommentIcon =+ showComments &&+ Boolean(commentCount) &&+ fitsWidth(commentIconWidth(commentCount!, measurer));+ const showScoreBadges =+ showScores &&+ Boolean(scores?.length) &&+ fitsWidth(scoreBadgesWidth(scores!, measurer, MAX_SCORE_GROUPS));- return (+ // Everything the row HAS stays reachable on hover when anything had to be+ // dropped β the icon and the badges included. They are admitted last, against+ // the smallest remaining budget, so they are the likeliest to go; without this+ // a narrow row simply did not mention that a comment or a score existed.+ const plural = (count: number, noun: string) =>+ `${count} ${noun}${count === 1 ? "" : "s"}`;+ const commentText =+ showComments && commentCount ? plural(commentCount, "comment") : null;+ const scoreText =+ showScores && scores?.length ? plural(scores.length, "score") : null;+ const droppedSomething =+ (durationText != null && !showDurationText) ||+ (subtreeText != null && !showSubtreeText) ||+ (costText != null && !showCostText) ||+ (commentText != null && !showCommentIcon) ||+ (scoreText != null && !showScoreBadges);+ const clusterTitle = droppedSomething+ ? [durationText, subtreeText, costText, commentText, scoreText]+ .filter(Boolean)+ .join(" ")+ : undefined;++ // Draw the cluster when it has something in it. Gating it on the duration+ // label's placement hid the comment icon, the cost and the scores of every+ // in-flight span β which never has a duration label β however much room the+ // lane had for them.+ const cluster =+ !showDurationText &&+ !showSubtreeText &&+ !showCostText &&+ !showCommentIcon &&+ !showScoreBadges ? null : (<div- className="absolute top-1/2 flex -translate-y-1/2 items-center gap-2"- style={{ left: `${startOffset}px` }}+ className="text-muted-foreground absolute top-1/2 flex -translate-y-1/2 items-center gap-2 overflow-hidden text-xs whitespace-nowrap"+ style={clusterStyle}+ title={clusterTitle}>- <div- className={cn(- "border-border flex h-4 overflow-hidden rounded-sm border",- // Dashed when in-flight (no width yet), matching the non-streaming bar.- itemWidth ? "" : "border-dashed",- ringClass,- )}- >- <div- className="bg-muted h-full border-r border-gray-400 opacity-60"- style={{ width: `${firstTokenWidth}px` }}- title="Time to first token"- />- <div- className="bg-muted h-full"- style={{ width: `${completionWidth}px` }}- />- </div>- {label}+ {showCommentIcon ? <CommentCountIcon count={commentCount!} /> : null}+ {showDurationText && (+ <span+ className={cn(+ parentTotalDuration &&+ colorCodeMetrics &&+ heatMapTextColor({+ max: parentTotalDuration,+ value: ownDurationMs!,+ }),+ )}+ >+ {durationText}+ </span>+ )}+ {showSubtreeText && (+ <span title={SUBTREE_DURATION_TITLE}>{subtreeText}</span>+ )}+ {showCostText && (+ <span+ className={cn(+ parentTotalCost &&+ colorCodeMetrics &&+ heatMapTextColor({+ max: parentTotalCost,+ value: node.totalCost!,+ }),+ )}+ >+ {costText}+ </span>+ )}+ {showScoreBadges && (+ <div className="flex max-h-5 gap-1" data-testid="timeline-bar-scores">+ {/* Not expandable here: the cluster's width was measured for exactly+ `MAX_SCORE_GROUPS` chips, so expanding in place would clip the+ chips already on screen instead of revealing the hidden ones. The+ hover preview shows them, and the row's title lists them. */}+ <GroupedScoreBadges+ scores={scores!}+ maxVisible={MAX_SCORE_GROUPS}+ expandable={false}+ />+ </div>+ )}</div>);- }++ // Streaming LLMs (first token time) split the bar: waiting segment, then+ // completion. firstTokenX is null when the marker falls outside the lane.+ const firstTokenWidth =+ row.firstTokenX == null+ ? null+ : Math.min(Math.max(row.firstTokenX - row.x, 0), row.width);return (- <div- className="absolute top-1/2 flex -translate-y-1/2 items-center gap-2"- style={{ left: `${startOffset}px` }}- >+ <><div+ // When the lane is too narrow for even one item, the cluster is not drawn+ // at all β and the title listing what was dropped went with it, so the+ // narrowest rows were the ones that never mentioned their own comments or+ // scores. The bar is always there, so it carries the fallback.+ title={cluster ? undefined : clusterTitle}className={cn(- "border-border bg-muted h-4 rounded-sm border",- itemWidth ? "" : "border-dashed",+ "border-border absolute top-1/2 flex h-4 -translate-y-1/2 overflow-hidden rounded-sm border",+ // Dashed when in-flight (no measurable duration yet).+ row.durationMs == null && "border-dashed",+ // A clipped edge loses its rounding, so the bar reads as continuing.+ row.clippedLeft && "rounded-l-none",+ row.clippedRight && "rounded-r-none",ringClass,)}- style={{ width: `${Math.max(itemWidth, MIN_BAR_WIDTH)}px` }}- />- {label}- </div>+ style={{ left: `${row.x}px`, width: `${row.width}px` }}+ >+ {/* Two SEGMENTS, and the ground belongs to them rather than to the+ frame: a translucent waiting segment over an opaque frame of the same+ colour composites straight back to that colour, so the wait and the+ completion read identically and only the divider says there was a+ split at all. */}+ {firstTokenWidth == null ? null : (+ <div+ className="bg-muted h-full border-r border-gray-400 opacity-60"+ style={{ width: `${firstTokenWidth}px` }}+ title="Time to first token"+ />+ )}+ <div className="bg-muted h-full flex-1" />+ </div>+ {cluster}+ </>);}diff --git a/web/src/features/traces/components/TraceTimeline/TimelineGutterRow.stories.tsx b/web/src/features/traces/components/TraceTimeline/TimelineGutterRow.stories.tsxindex b491bf8630..330552e108 100644--- a/web/src/features/traces/components/TraceTimeline/TimelineGutterRow.stories.tsx+++ b/web/src/features/traces/components/TraceTimeline/TimelineGutterRow.stories.tsx@@ -1,8 +1,8 @@import { fn } from "storybook/test";import preview from "../../../../../.storybook/preview";import { TimelineGutterRow } from "./TimelineGutterRow";-import { flattenTreeWithTimelineMetrics } from "./timeline-flattening";-import { makeItem, makeTreeNode } from "./__tests__/timeline.fixtures";+import { prepareTimeline } from "../../fns/timeline/layout";+import { makeRow, makeTreeNode } from "./__tests__/timeline.fixtures";const ROW_BOX ="bg-background relative h-[26px] w-[320px] overflow-hidden rounded border";@@ -14,7 +14,7 @@ const PANEL_BOX = "bg-background w-[320px] overflow-hidden rounded border";const meta = preview.meta({component: TimelineGutterRow,args: {- item: makeItem({+ row: makeRow({depth: 1,treeLines: [false],isLastSibling: true,@@ -41,7 +41,7 @@ export const Default = meta.story({export const RootWithChildren = meta.story({args: {- item: makeItem({+ row: makeRow({depth: 0,treeLines: [],isLastSibling: true,@@ -60,7 +60,7 @@ export const RootWithChildren = meta.story({export const NestedWithSiblingBelow = meta.story({args: {- item: makeItem({+ row: makeRow({depth: 2,treeLines: [true, true],isLastSibling: false,@@ -79,7 +79,7 @@ export const NestedWithSiblingBelow = meta.story({export const NestedLastChild = meta.story({args: {- item: makeItem({+ row: makeRow({depth: 2,treeLines: [true, false],isLastSibling: true,@@ -108,7 +108,7 @@ export const Selected = meta.story({export const Collapsed = meta.story({args: {- item: makeItem({+ row: makeRow({depth: 1,treeLines: [false],isLastSibling: true,@@ -198,25 +198,22 @@ export const TreeShowcase = meta.story({],});- const items = flattenTreeWithTimelineMetrics(- [tree],- new Set(),- tree.startTime,- 8,- 900,- );+ // The real tree walk, so connectors connect parentβchild across rows+ // exactly as in the app. Only depth/treeLines matter here; the gutter takes+ // no geometry.+ const rows = prepareTimeline([tree]).rows;return (<>- {items.map((item) => (- <div key={item.node.id} className="h-[26px]">+ {rows.map((row) => (+ <div key={row.node.id} className="h-[26px]"><TimelineGutterRow- item={item}+ row={row}isSelected={false}onSelect={args.onSelect}onHover={args.onHover}onToggleCollapse={args.onToggleCollapse}- hasChildren={item.node.children.length > 0}+ hasChildren={row.hasChildren}isCollapsed={false}/></div>diff --git a/web/src/features/traces/components/TraceTimeline/TimelineGutterRow.tsx b/web/src/features/traces/components/TraceTimeline/TimelineGutterRow.tsxindex b3e20bd120..35e756aaa2 100644--- a/web/src/features/traces/components/TraceTimeline/TimelineGutterRow.tsx+++ b/web/src/features/traces/components/TraceTimeline/TimelineGutterRow.tsx@@ -22,7 +22,7 @@ const RAIL = 7; // x of a level's vertical rail within its indent stepconst ICON_GAP = 6; // gap from a node's rail to its iconexport function TimelineGutterRow({- item,+ row,isSelected,isHovered,onSelect,@@ -32,7 +32,7 @@ export function TimelineGutterRow({isCollapsed,maxVisualDepth = Infinity,}: TimelineGutterRowProps) {- const { node, depth, treeLines, isLastSibling } = item;+ const { node, depth, treeLines, isLastSibling } = row;// Visual depth: real depth capped to the gutter width (see visual-depth.ts)// so extremely deep traces keep names readable β rows past the cap renderdiff --git a/web/src/features/traces/components/TraceTimeline/TimelineRows.tsx b/web/src/features/traces/components/TraceTimeline/TimelineRows.tsxindex 2c6ef8d32d..5dab141488 100644--- a/web/src/features/traces/components/TraceTimeline/TimelineRows.tsx+++ b/web/src/features/traces/components/TraceTimeline/TimelineRows.tsx@@ -16,14 +16,16 @@ import type Decimal from "decimal.js";import { type ScoreDomain } from "@langfuse/shared";import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";import { type TreeNode } from "../../types/treeNode";-import { type FlatTimelineItem } from "./types";+import { type TimelineRowNode } from "./types";+import { type TextMeasurer } from "../../fns/timeline/textMeasurer";+import { type Density } from "../../fns/timeline/density";import { TimelineGutterRow } from "./TimelineGutterRow";import { TimelineBar } from "./TimelineBar";import { useIsObservationActive } from "@/src/features/traces/contexts/PlayheadContext";import { cn } from "@/src/utils/tailwind";interface RowShellSharedProps {- item: FlatTimelineItem;+ row: TimelineRowNode;/** Virtual row offset/extent β primitives so the memo can bail on scroll. */top: number;height: number;@@ -43,7 +45,7 @@ type GutterRowShellProps = RowShellSharedProps & {};function TimelineGutterRowShellComponent({- item,+ row,top,height,isSelected,@@ -55,7 +57,7 @@ function TimelineGutterRowShellComponent({onHover,onToggleCollapse,}: GutterRowShellProps) {- const nodeId = item.node.id;+ const nodeId = row.node.id;// Playhead glow: rows "playing" at the current time light UP (accent tint).const isActive = useIsObservationActive(nodeId);@@ -75,11 +77,11 @@ function TimelineGutterRowShellComponent({)}><TimelineGutterRow- item={item}+ row={row}isSelected={isSelected}isHovered={isHovered}onSelect={() => onSelect(nodeId)}- onHover={() => onHover(item.node)}+ onHover={() => onHover(row.node)}onToggleCollapse={() => onToggleCollapse(nodeId)}hasChildren={hasChildren}isCollapsed={isCollapsed}@@ -102,10 +104,12 @@ type ChartRowShellProps = RowShellSharedProps & {parentTotalDuration?: number;commentCount: number;nodeScores: WithStringifiedMetadata<ScoreDomain>[];+ measurer: TextMeasurer;+ density: Density;};function TimelineChartRowShellComponent({- item,+ row,top,height,width,@@ -120,10 +124,12 @@ function TimelineChartRowShellComponent({parentTotalDuration,commentCount,nodeScores,+ measurer,+ density,onSelect,onHover,}: ChartRowShellProps) {- const nodeId = item.node.id;+ const nodeId = row.node.id;const isActive = useIsObservationActive(nodeId);return (@@ -150,11 +156,13 @@ function TimelineChartRowShellComponent({: "",)}onClick={() => onSelect(nodeId)}- onMouseEnter={() => onHover(item.node)}+ onMouseEnter={() => onHover(row.node)}><TimelineBar- node={item.node}- metrics={item.metrics}+ row={row}+ laneWidth={width}+ measurer={measurer}+ density={density}isSelected={isSelected}isHovered={isHovered}showDuration={showDuration}diff --git a/web/src/features/traces/components/TraceTimeline/TimelineScale.stories.tsx b/web/src/features/traces/components/TraceTimeline/TimelineScale.stories.tsxindex caf3a743ca..05a244833e 100644--- a/web/src/features/traces/components/TraceTimeline/TimelineScale.stories.tsx+++ b/web/src/features/traces/components/TraceTimeline/TimelineScale.stories.tsx@@ -1,25 +1,63 @@+import { expect } from "storybook/test";import preview from "../../../../../.storybook/preview";import { TimelineScale } from "./TimelineScale";+import { TICK_LABEL_INSET_PX } from "../../fns/timeline/layout";const meta = preview.meta({component: TimelineScale,- args: { traceDuration: 8, scaleWidth: 900, stepSize: 1 },- // The scale is wider than most viewports; host it in a scrollable box.- decorators: [- (Story) => (- <div className="bg-background w-[700px] overflow-x-auto rounded border p-2">- <Story />- </div>- ),- ],});-export const Default = meta.story({});+/** Ticks arrive already placed and labelled by layout(); see fns/timeline. */+const ticks = (stepMs: number, count: number, laneWidth: number) =>+ Array.from({ length: count }, (_, i) => ({+ realMs: i * stepMs,+ x: (i / count) * laneWidth,+ label:+ stepMs >= 1000+ ? `${((i * stepMs) / 1000).toFixed(2)}s`+ : `${i * stepMs}ms`,+ }));++export const Default = meta.story({+ args: { ticks: ticks(1000, 8, 700), laneWidth: 700 },+});export const SubSecond = meta.story({- args: { traceDuration: 0.8, stepSize: 0.1 },+ args: { ticks: ticks(100, 8, 700), laneWidth: 700 },});-export const LongTrace = meta.story({- args: { traceDuration: 300, stepSize: 50 },+export const NarrowLane = meta.story({+ args: { ticks: ticks(1000, 3, 240), laneWidth: 240 },+});++/**+ * The axis renders a label at the same distance from its tick line that `layout()`+ * reserves for it. There were three numbers for that one distance β a constant+ * here, a Tailwind class in the renderer, and a literal in the label's clamp β so+ * `fits()` was quietly stricter than the render and dropped ticks that would have+ * been whole. One number, asserted against what the DOM did with it.+ */+export const TheLabelSitsWhereLayoutReservedIt = meta.story({+ name: "(Test) The Label Sits Where Layout Reserved It",+ args: { ticks: ticks(1000, 6, 700), laneWidth: 700 },+ play: async ({ canvasElement }) => {+ const lane = canvasElement.querySelector<HTMLElement>(+ "div[style*='width']",+ );+ if (!lane) throw new Error("no lane");+ const labels = [...canvasElement.querySelectorAll<HTMLElement>("span")];+ await expect(labels.length).toBeGreaterThan(1);++ const laneBox = lane.getBoundingClientRect();+ for (const label of labels) {+ const line = label.parentElement!.getBoundingClientRect();+ const drawn = label.getBoundingClientRect();+ // Exactly the reserved inset from its own tick line...+ await expect(drawn.left - line.left).toBeCloseTo(TICK_LABEL_INSET_PX, 0);+ // ...and never past the lane, whatever the label says.+ await expect(drawn.right).toBeLessThanOrEqual(laneBox.right + 0.5);+ }+ // And the axis itself does not scroll β the same rule as everything else.+ await expect(lane.scrollWidth).toBeLessThanOrEqual(lane.clientWidth);+ },});diff --git a/web/src/features/traces/components/TraceTimeline/TimelineScale.tsx b/web/src/features/traces/components/TraceTimeline/TimelineScale.tsxindex a7ac9fa4a9..11403409ca 100644--- a/web/src/features/traces/components/TraceTimeline/TimelineScale.tsx+++ b/web/src/features/traces/components/TraceTimeline/TimelineScale.tsx@@ -1,90 +1,61 @@/**- * TimelineScale - Renders the time axis at the top of the timeline- * Shows time markers with step intervals based on trace duration+ * TimelineScale - Renders the time axis at the top of the timeline.*- * Ticks are positioned in BAR coordinates ((time / traceDuration) *- * scaleWidth) β the same mapping the gantt bars, the playhead, and- * click-to-seek use β so a tick labeled "5.00s" sits exactly where a seek- * lands at 5.00s. Positioning ticks on a fixed pixel grid instead- * (index * STEP_SIZE) silently diverges whenever the rounded-up stepSize- * doesn't equal traceDuration / (scaleWidth / STEP_SIZE), which is almost- * every real trace.+ * Draws ticks, nothing more: which times get a tick, where they land and how+ * they are labelled all come from `layout()`, in the same coordinate space as+ * the bars and the playhead. That is what keeps a tick labelled "5.00s" exactly+ * above the bar that starts at 5.00s β the axis and the bars used to derive+ * their positions separately and disagree whenever the rounded step size did+ * not divide the trace duration evenly.+ *+ * Ticks whose label would not fit inside the measured lane are dropped by the+ * layout rather than clipped here, so the axis obeys the same+ * everything-inside-the-box rule as everything else.*/+import {+ TICK_LABEL_GAP_PX,+ TICK_LABEL_INSET_PX,+} from "../../fns/timeline/layout";import { type TimelineScaleProps } from "./types";-import { formatIntervalSeconds } from "@/src/utils/dates";--/**- * Sub-minute ticks keep the precise "5.00s" form; minute-scale and larger- * ticks read as durations ("25m 00s", "1h 30m 00s") β raw "1500.00s" labels- * are unreadable on hour-scale traces (LFE-10959).- */-const formatTickLabel = (timeValue: number): string =>- timeValue >= 60- ? formatIntervalSeconds(timeValue)- : `${timeValue.toFixed(2)}s`;--export function TimelineScale({- traceDuration,- scaleWidth,- stepSize,-}: TimelineScaleProps) {- // Guard against non-finite / absurd inputs ever reaching here:- // Array.from({ length }) throws "RangeError: Invalid array length" for- // Infinity and OOMs for an enormous finite length, so clamp to a finite,- // sane upper bound. calculateStepSize keeps the real count at ~10.- const safeScaleWidth = Number.isFinite(scaleWidth)- ? Math.max(0, scaleWidth)- : 0;- const numMarkers =- traceDuration > 0 && stepSize > 0 && Number.isFinite(traceDuration)- ? Math.min(Math.floor(traceDuration / stepSize) + 1, 10_000)- : 1;-- const tickLeft = (timeValue: number) =>- traceDuration > 0 ? (timeValue / traceDuration) * safeScaleWidth : 0;+export function TimelineScale({ ticks, laneWidth }: TimelineScaleProps) {return (- // No left margin: the 0s tick must sit exactly at the track origin so the- // ticks line up with the bars (which start at startOffset = 0 there).<div className="mb-2">- <div className="relative h-8" style={{ width: `${scaleWidth}px` }}>- {Array.from({ length: numMarkers }).map((_, index) => {- const timeValue = stepSize * index;-- return (- <div- key={index}- className="border-border-contrast absolute h-full border-l text-xs"- style={{ left: `${tickLeft(timeValue)}px` }}+ <div+ className="relative h-8 overflow-hidden"+ style={{ width: `${laneWidth}px` }}+ >+ {ticks.map((tick) => (+ <div+ key={tick.realMs}+ className="border-border-contrast absolute h-full border-l text-xs"+ style={{ left: `${tick.x}px` }}+ >+ {/* maxWidth is the structural guarantee: layout() already drops a+ tick whose label would not fit, but it predicts the width from+ measured glyphs, and a prediction must not be the only thing+ keeping the axis inside the box.++ The offset and the clamp both come from the constant layout()+ reserves with, so the prediction and the render cannot drift. */}+ <span+ className="text-muted-foreground absolute overflow-hidden text-xs whitespace-nowrap"+ style={{+ // Inside the tick's border, so the gap β while the clamp pays for+ // the border too, which is what layout() reserved.+ left: `${TICK_LABEL_GAP_PX}px`,+ maxWidth: `${Math.max(+ laneWidth - tick.x - TICK_LABEL_INSET_PX,+ 0,+ )}px`,+ }}+ title={tick.label}>- <span- className="text-muted-foreground absolute left-2 text-xs whitespace-nowrap"- title={formatTickLabel(timeValue)}- >- {formatTickLabel(timeValue)}- </span>- </div>- );- })}-- {/* Grid lines for visual alignment */}- <div className="pointer-events-none absolute inset-0">- {Array.from({ length: numMarkers }).map((_, index) => {- if (index === 0) {- return null;- }- const timeValue = stepSize * index;-- return (- <div- key={`grid-${index}`}- className="border-border/30 absolute h-full border-l"- style={{ left: `${tickLeft(timeValue)}px` }}- />- );- })}- </div>+ {tick.label}+ </span>+ </div>+ ))}</div></div>);diff --git a/web/src/features/traces/components/TraceTimeline/TraceTimeline.tsx b/web/src/features/traces/components/TraceTimeline/TraceTimeline.tsxindex ba7e0ad029..3bdd0cf580 100644--- a/web/src/features/traces/components/TraceTimeline/TraceTimeline.tsx+++ b/web/src/features/traces/components/TraceTimeline/TraceTimeline.tsx@@ -6,12 +6,15 @@* itself β its content is a one-way translateY projection of the chart's* vertical scroll, so the two panes can't drift; wheeling or touch-dragging* over it drives the chart.- * - Chart pane (flex-1): the gantt bars. Owns the only scrollbars (horizontal- * and vertical) and is the virtualizer's scroll element.+ * - Chart pane (flex-1): the gantt bars. Owns the only (vertical) scrollbar and+ * is the virtualizer's scroll element.*- * The time scale sits in an overflow-hidden header strip whose inner is- * transform-synced to the chart's horizontal scroll, so the scale stays aligned- * with the bars without a scrollbar of its own.+ * The chart NEVER scrolls horizontally. Its measured client width is the scale+ * basis, so the whole trace is fitted into the lane the user actually has, at+ * any size β every coordinate comes from the pure layout() in fns/timeline,+ * which clamps bars, labels and ticks inside that lane. The previous design+ * scaled against a hard-coded 900px canvas and let the container scroll, which+ * put part of the trace off-screen in any narrower lane.** Playback: the engine (RAF loop, transport) lives in the shared playhead* store (contexts/playheadStore.ts); the transport buttons live in the@@ -27,7 +30,6 @@ import {useRef,useState,useLayoutEffect,- type RefObject,} from "react";import { useVirtualizer } from "@tanstack/react-virtual";import { useTraceData } from "@/src/features/traces/contexts/TraceDataContext";@@ -35,20 +37,19 @@ import { useSelection } from "@/src/features/traces/contexts/SelectionContext";import { useViewPreferences } from "@/src/features/traces/contexts/ViewPreferencesContext";import {usePlayhead,- usePlayheadStore,useShowPlayhead,} from "@/src/features/traces/contexts/PlayheadContext";import { useHandlePrefetchObservation } from "@/src/features/traces/hooks/useHandlePrefetchObservation";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { useTraceAnalyticsDimensions } from "@/src/features/traces/hooks/useTraceAnalyticsDimensions";-import { flattenTreeWithTimelineMetrics } from "./timeline-flattening";+import { computeSelectionScrollTarget } from "../../fns/timelineCalculations";+import { formatIntervalSeconds } from "@/src/utils/dates";import {- calculateStepSize,- computeSelectionScrollTarget,- REVEAL_LEFT_FRACTION,- REVEAL_MARGIN_PX,- SCALE_WIDTH,-} from "../../fns/timelineCalculations";+ layout as computeTimelineLayout,+ prepareTimeline,+} from "../../fns/timeline/layout";+import { resolveDensity } from "../../fns/timeline/density";+import { createTextMeasurer } from "../../fns/timeline/textMeasurer";import { TimelineScale } from "./TimelineScale";import { TimelineChartRowShell, TimelineGutterRowShell } from "./TimelineRows";import {@@ -66,12 +67,18 @@ const GUTTER_WIDTH_DEFAULT = 200;const GUTTER_WIDTH_MIN = 160;const GUTTER_WIDTH_MAX = 560;// Dense waterfall rows (LFE-10539): the 16px bar / 16px name chip sit centered-// with ~5px of breathing room. Drives both the virtualizer estimate and the-// rendered row height, so the two never drift.-const ROW_HEIGHT = 26;+// with ~5px of breathing room. Resolved once here so the virtualizer estimate+// and the rendered row height cannot drift. Touch density is Phase 4's job, so+// this pins the fine-pointer value.+const DENSITY = resolveDensity({ pointer: "fine" });+const ROW_HEIGHT = DENSITY.rowHeight;const EMPTY_SCORES: never[] = [];+/** The timeline's own duration copy, and therefore what layout() measures. */+const formatRowDuration = (durationMs: number) =>+ formatIntervalSeconds(durationMs / 1000);+/*** Wire a window-level drag gesture: move events flow to `onMove` until* pointerup β and pointercancel (OS gesture, contextmenu, touch interruption),@@ -99,12 +106,15 @@ function startWindowDrag(onMove: (ev: PointerEvent) => void) {*/function useTimelinePlayhead({traceDuration,- chartRef,+ secToX,+ xToSec,}: {traceDuration: number;- chartRef: RefObject<HTMLDivElement | null>;+ /** Seconds from the trace origin β px in the chart lane. */+ secToX: (sec: number) => number;+ /** px in the chart lane β seconds from the trace origin. */+ xToSec: (px: number) => number;}) {- const store = usePlayheadStore();const { seekToSec, pause, getPlayheadSec, subscribePosition } = usePlayhead();const showPlayhead = useShowPlayhead();@@ -112,13 +122,6 @@ function useTimelinePlayhead({const playheadLineRef = useRef<HTMLDivElement>(null);const playheadHandleRef = useRef<HTMLDivElement>(null);- // Map a playhead time (seconds from origin) to an x within the gantt content.- const secToX = useCallback(- (sec: number) =>- traceDuration > 0 ? (sec / traceDuration) * SCALE_WIDTH : 0,- [traceDuration],- );-// Position the line + handle imperatively off the engine's position feed (no// re-render). They only exist while showPlayhead; re-subscribe when the// scale (secToX) changes so the mapping stays correct.@@ -134,46 +137,23 @@ function useTimelinePlayhead({handle.setAttribute("aria-valuenow", sec.toFixed(2));handle.setAttribute("aria-valuetext", `${sec.toFixed(2)} seconds`);}- // Follow the playhead while PLAYING so the sweep never exits the- // viewport β but never during manual scrubbing or while paused, so we- // don't hijack the user's horizontal scroll. Instant (runs per frame).- const chart = chartRef.current;- if (chart && store.getState().isPlaying) {- const x = secToX(sec);- if (- x < chart.scrollLeft + REVEAL_MARGIN_PX ||- x > chart.scrollLeft + chart.clientWidth - REVEAL_MARGIN_PX- ) {- chart.scrollLeft = Math.max(- 0,- x - chart.clientWidth * REVEAL_LEFT_FRACTION,- );- }- }+ // No follow-scroll: the whole trace is fitted into the lane, so the+ // playhead cannot sweep out of view.};apply(getPlayheadSec());return subscribePosition(apply);- }, [- showPlayhead,- secToX,- getPlayheadSec,- subscribePosition,- chartRef,- store,- ]);+ }, [showPlayhead, secToX, getPlayheadSec, subscribePosition]);// Translate a pointer x on the scale into a seek (places/moves the playhead).+ // The scale shares the chart lane's coordinate space and neither scrolls, so+ // the offset from the strip's left edge IS the lane x.const seekFromClientX = useCallback((clientX: number) => {const outer = scaleOuterRef.current;if (!outer || traceDuration <= 0) return;- const contentX =- clientX -- outer.getBoundingClientRect().left +- (chartRef.current?.scrollLeft ?? 0);- seekToSec((contentX / SCALE_WIDTH) * traceDuration);+ seekToSec(xToSec(clientX - outer.getBoundingClientRect().left));},- [traceDuration, seekToSec, chartRef],+ [traceDuration, seekToSec, xToSec],);const handleScalePointerDown = useCallback(@@ -232,7 +212,6 @@ export function TraceTimeline() {serverScores: scores,traceLevelScoreOwnerIds,comments,- traceStartTime,traceDuration,} = useTraceData();const { collapsedNodes, toggleCollapsed, selectedNodeId, setSelectedNodeId } =@@ -257,7 +236,6 @@ export function TraceTimeline() {// transform projection of it (gutterInnerRef), so the two panes can't drift.const gutterInnerRef = useRef<HTMLDivElement>(null);const chartRef = useRef<HTMLDivElement>(null);- const scaleInnerRef = useRef<HTMLDivElement>(null);// Hovered row, lifted to shared state so hovering either pane highlights the// whole row (caption + chart), which CSS :hover can't do across two panes.@@ -286,10 +264,6 @@ export function TraceTimeline() {[gutterWidth],);- const stepSize = useMemo(() => {- return calculateStepSize(traceDuration, SCALE_WIDTH);- }, [traceDuration]);-// Cap gutter indentation to the gutter width so extremely deep traces (a// reported one chained ~1400 levels) keep names readable instead of// clipping into nothing (LFE-10959).@@ -298,29 +272,30 @@ export function TraceTimeline() {GUTTER_VISUAL_DEPTH,);- const flattenedItems = useMemo(() => {- return flattenTreeWithTimelineMetrics(- roots,- collapsedNodes,- traceStartTime,- traceDuration,- SCALE_WIDTH,- );- }, [roots, collapsedNodes, traceStartTime, traceDuration]);-- // Width of the chart content (gantt area). Padding leaves room for the- // trailing metric label that rides after each bar.- const chartContentWidth = useMemo(() => {- if (flattenedItems.length === 0) return SCALE_WIDTH;-- const maxEnd = Math.max(- ...flattenedItems.map(- (item) => item.metrics.startOffset + item.metrics.itemWidth,- ),- );+ // Tree walk, memoized on the tree + collapsed set: it is the one expensive+ // part and it must stay out of the resize/render path.+ const prepared = useMemo(+ () => prepareTimeline(roots, collapsedNodes),+ [roots, collapsedNodes],+ );- return Math.max(SCALE_WIDTH, maxEnd + 300);- }, [flattenedItems]);+ // Canvas glyph widths so layout() can decide whether a duration label fits+ // inside its bar β measured in the font the labels ACTUALLY render in, read+ // off a probe span carrying the label's own classes. Guessing the font gets+ // the decision wrong: a `12px ui-sans-serif` guess resolves to a different+ // face than the app's 11.2px system stack and underestimated an axis label by+ // 5px, which is exactly enough to push it past the lane edge.+ const [labelFont, setLabelFont] = useState<string | null>(null);+ const labelProbeRef = useCallback((el: HTMLSpanElement | null) => {+ if (!el) return;+ const style = getComputedStyle(el);+ const font = `${style.fontSize} ${style.fontFamily}`;+ setLabelFont((prev) => (prev === font ? prev : font));+ }, []);+ const measurer = useMemo(+ () => createTextMeasurer(labelFont ?? undefined),+ [labelFont],+ );// Virtualizer drives off the chart pane; the gutter mirrors its vertical scroll.// overscan is a ROW COUNT (not px): keep it small so a long trace re-renders@@ -328,10 +303,13 @@ export function TraceTimeline() {// px-vs-items mix-up β made big traces stutter). ~16 rows β half a viewport of// headroom, enough to avoid blank rows on a normal scroll.const rowVirtualizer = useVirtualizer({- count: flattenedItems.length,+ count: prepared.rows.length,getScrollElement: () => chartRef.current,estimateSize: () => ROW_HEIGHT,overscan: 16,+ // Key by node id: an index-keyed measurement cache and an id-keyed DOM+ // drift apart the moment a collapse changes what index a row holds.+ getItemKey: (index) => prepared.rows[index]?.node.id ?? index,});// Scroll the selected row into view whenever the selection changes β so@@ -347,12 +325,12 @@ export function TraceTimeline() {return;}- const index = flattenedItems.findIndex(- (item) => item.node.id === selectedNodeId,+ const index = prepared.rows.findIndex(+ (row) => row.node.id === selectedNodeId,);// Keep the scroll PENDING when the row is missing (collapsed subtree,// level filter) β the ref stays un-advanced, so this retries when- // flattenedItems changes and the row appears.+ // prepared.rows changes and the row appears.if (index === -1) return;const chart = chartRef.current;if (!chart) return;@@ -360,33 +338,29 @@ export function TraceTimeline() {const isInitial = prevSelectedIdRef.current === undefined;prevSelectedIdRef.current = selectedNodeId;- const { top, left } = computeSelectionScrollTarget({+ // Vertical only: the whole trace is fitted into the lane, so a selected bar+ // is never off to the side. Reaching detail is zoom's job (Phase 3).+ const { top } = computeSelectionScrollTarget({index,rowHeight: ROW_HEIGHT,scrollTop: chart.scrollTop,- scrollLeft: chart.scrollLeft,clientHeight: chart.clientHeight,- clientWidth: chart.clientWidth,- barStart: flattenedItems[index]?.metrics.startOffset ?? null,isInitial,});- chart.scrollTo({ top, left, behavior: isInitial ? "auto" : "smooth" });- }, [selectedNodeId, flattenedItems]);+ chart.scrollTo({ top, behavior: isInitial ? "auto" : "smooth" });+ }, [selectedNodeId, prepared]);- // The chart owns the only vertical scroll. The gutter and the time scale are- // one-way projections of it (translateY / translateX) updated in the same- // scroll frame β no second scroll container to fight the chart's momentum,- // which is what made the two panes drift apart.+ // The chart owns the only scroll. The gutter is a one-way projection of it+ // (translateY) updated in the same scroll frame β no second scroll container+ // to fight the chart's momentum, which is what made the two panes drift+ // apart. The scale needs no projection: nothing scrolls horizontally.const handleChartScroll = useCallback(() => {const chart = chartRef.current;if (!chart) return;if (gutterInnerRef.current) {gutterInnerRef.current.style.transform = `translateY(${-chart.scrollTop}px)`;}- if (scaleInnerRef.current) {- scaleInnerRef.current.style.transform = `translateX(${-chart.scrollLeft}px)`;- }}, []);// The gutter doesn't scroll itself; wheeling over it drives the chart, which@@ -488,43 +462,106 @@ export function TraceTimeline() {const totalSize = rowVirtualizer.getTotalSize();const virtualItems = rowVirtualizer.getVirtualItems();- const {- scaleOuterRef,- playheadLineRef,- playheadHandleRef,- showPlayhead,- secToX,- getPlayheadSec,- handleScalePointerDown,- handleHandlePointerDown,- handleHandleKeyDown,- } = useTimelinePlayhead({ traceDuration, chartRef });-- // Classic scrollbars (Windows/Linux) on the chart pane consume client area- // the gutter/scale don't: its horizontal scrollbar eats ~15px of height, its- // vertical scrollbar ~15px of width. We reserve the matching amount on the- // gutter (bottom) and the scale strip (right) so the three panes share the- // same scrollable extent β otherwise mirrored scroll clamps at the bottom and- // a right-edge tick floats over the chart's scrollbar. Both are 0 with macOS- // overlay bars.- const [chartScrollbar, setChartScrollbar] = useState({ x: 0, y: 0 });+ // THE measurement. The chart pane's own client box is the scale basis, and it+ // must be the box of the element that SCROLLS: its border and its vertical+ // scrollbar (~15px on Windows/Linux, 0 with macOS overlay bars) both take+ // width that an arithmetic guess from the container would miss, and any such+ // miss is a lane wider than the space available β which is horizontal scroll,+ // the thing this design removes. `scrollbarWidth` is reported separately so+ // the scale strip, which has no scrollbar of its own, can reserve the same+ // gutter and stay aligned with the bars.+ const [chartBox, setChartBox] = useState({+ width: 0,+ height: 0,+ scrollbarWidth: 0,+ });useLayoutEffect(() => {const el = chartRef.current;if (!el) return;const measure = () => {- const x = el.offsetWidth - el.clientWidth;- const y = el.offsetHeight - el.clientHeight;+ const next = {+ width: el.clientWidth,+ height: el.clientHeight,+ scrollbarWidth: el.offsetWidth - el.clientWidth,+ };// Only re-render when the measurement actually changes β the observer- // fires on every content resize, but the scrollbar size rarely moves.- setChartScrollbar((prev) =>- prev.x === x && prev.y === y ? prev : { x, y },+ // fires on every content resize, but the box rarely moves.+ setChartBox((prev) =>+ prev.width === next.width &&+ prev.height === next.height &&+ prev.scrollbarWidth === next.scrollbarWidth+ ? prev+ : next,);};measure();const ro = new ResizeObserver(measure);ro.observe(el);return () => ro.disconnect();- }, [chartContentWidth, totalSize, gutterWidth]);+ }, [totalSize, gutterWidth]);++ // One pure call owns every coordinate on screen, for the mounted rows only.+ // The view is the whole trace: zoom/pan is Phase 3, and until then+ // "fit to the measured box" is the only view there is.+ //+ // Memoized because it allocates a fresh PositionedNode per mounted row, and+ // the row shells are React.memo precisely so a hover or a selection re-renders+ // the two rows that changed. Recomputing this on every render handed all of+ // them a new `row` object and re-rendered every one, which is the memo+ // boundary TimelineRows.tsx documents doing nothing at all.+ // Keyed on the two indices rather than on the items array, so the range is+ // only a new object when the mounted window really moved.+ const firstIndex = virtualItems.length ? virtualItems[0]!.index : -1;+ const lastIndex = virtualItems.length+ ? virtualItems[virtualItems.length - 1]!.index+ : -1;+ const rowRange = useMemo(+ () =>+ firstIndex < 0+ ? // Before the virtualizer has measured its scroll element, fill the box.+ {+ startIndex: 0,+ endIndex: Math.ceil(chartBox.height / ROW_HEIGHT) + 1,+ }+ : { startIndex: firstIndex, endIndex: lastIndex },+ [firstIndex, lastIndex, chartBox.height],+ );+ const chartLayout = useMemo(+ () =>+ computeTimelineLayout({+ roots,+ box: { width: chartBox.width, height: chartBox.height },+ density: DENSITY,+ measurer,+ view: null,+ compress: false,+ prepared,+ rowRange,+ // The bar renders `label`, so the layout has to measure the string the+ // bar will draw β see the formatLabel contract in fns/timeline/layout.ts.+ formatLabel: formatRowDuration,+ }),+ [roots, chartBox.width, chartBox.height, measurer, prepared, rowRange],+ );++ // Playhead β lane mapping, in the same space as the bars and the ticks.+ const { pxPerMs } = chartLayout;+ const secToX = useCallback((sec: number) => sec * 1000 * pxPerMs, [pxPerMs]);+ const xToSec = useCallback(+ (px: number) => (pxPerMs > 0 ? px / pxPerMs / 1000 : 0),+ [pxPerMs],+ );++ const {+ scaleOuterRef,+ playheadLineRef,+ playheadHandleRef,+ showPlayhead,+ getPlayheadSec,+ handleScalePointerDown,+ handleHandlePointerDown,+ handleHandleKeyDown,+ } = useTimelinePlayhead({ traceDuration, secToX, xToSec });// Stable id/node-taking callbacks shared by every row shell (see// TimelineRows.tsx β stable references keep the memo boundary effective).@@ -553,8 +590,10 @@ export function TraceTimeline() {return (<div className="flex h-full w-full flex-col overflow-hidden">- {/* Header: name label + time scale (transform-synced). Transport controls- live in the shared navigation header (see PlaybackControls). */}+ {/* Header: name label + time scale. The scale shares the chart lane's+ coordinate space and neither scrolls, so no transform sync is needed β+ it only reserves the width the chart's scrollbar takes. Transport+ controls live in the shared navigation header (see PlaybackControls). */}<div className="flex shrink-0"><divclassName="bg-background text-muted-foreground flex shrink-0 items-center pl-2 text-xs font-bold"@@ -569,17 +608,21 @@ export function TraceTimeline() {ref={scaleOuterRef}onPointerDown={handleScalePointerDown}className="flex-1 cursor-pointer overflow-hidden select-none"- style={{ marginRight: `${chartScrollbar.x}px` }}+ style={{ marginRight: `${chartBox.scrollbarWidth}px` }}>- <div- ref={scaleInnerRef}- className="relative"- style={{ width: `${chartContentWidth}px` }}- >+ <div className="relative">+ {/* Font probe for the text measurer: same classes as a tick label,+ invisible and out of flow so it costs no layout. */}+ <span+ ref={labelProbeRef}+ aria-hidden+ className="text-muted-foreground invisible absolute text-xs"+ >+ 0+ </span><TimelineScale- traceDuration={traceDuration}- scaleWidth={SCALE_WIDTH}- stepSize={stepSize}+ ticks={chartLayout.ticks}+ laneWidth={chartBox.width}/>{showPlayhead && (<div@@ -629,29 +672,26 @@ export function TraceTimeline() {<divref={gutterInnerRef}style={{- // Match the chart's scrollable extent, including the height its- // horizontal scrollbar steals on classic (Windows/Linux) bars, so- // the projected rows line up to the very bottom (0 on macOS overlay- // bars).- height: `${totalSize + chartScrollbar.y}px`,+ // Match the chart's scrollable extent. The chart no longer scrolls+ // horizontally, so there is no horizontal scrollbar height to+ // reserve for any more.+ height: `${totalSize}px`,position: "relative",willChange: "transform",}}>- {virtualItems.map((vr) => {- const item = flattenedItems[vr.index];- if (!item) return null;- const nodeId = item.node.id;+ {chartLayout.nodes.map((row) => {+ const nodeId = row.node.id;return (<TimelineGutterRowShellkey={nodeId}- item={item}- top={vr.start}- height={vr.size}+ row={row}+ top={row.y}+ height={row.height}isSelected={selectedNodeId === nodeId}isHovered={hoveredNodeId === nodeId}- hasChildren={item.node.children.length > 0}- isCollapsed={collapsedNodes.has(nodeId)}+ hasChildren={row.hasChildren}+ isCollapsed={row.isCollapsed}maxVisualDepth={gutterMaxVisualDepth}onSelect={handleSelectNode}onHover={handleHoverNode}@@ -676,30 +716,31 @@ export function TraceTimeline() {/></div>- {/* Chart pane β the only horizontal scrollbar lives here. */}+ {/* Chart pane β vertical scroll only. overflow-x is hidden rather than+ auto so a stray sub-pixel can never reintroduce a horizontal+ scrollbar; the content is exactly the measured lane wide. */}<divref={chartRef}onScroll={handleChartScroll}- className="flex-1 overflow-auto"+ className="flex-1 overflow-x-hidden overflow-y-auto"><divstyle={{height: `${totalSize}px`,- width: `${chartContentWidth}px`,+ width: `${chartBox.width}px`,position: "relative",}}>- {virtualItems.map((vr) => {- const item = flattenedItems[vr.index];- if (!item) return null;- const nodeId = item.node.id;+ {chartLayout.nodes.map((row) => {+ const nodeId = row.node.id;return (<TimelineChartRowShellkey={nodeId}- item={item}- top={vr.start}- height={vr.size}- width={chartContentWidth}+ row={row}+ top={row.y}+ height={row.height}+ width={chartBox.width}+ density={DENSITY}isSelected={selectedNodeId === nodeId}isHovered={hoveredNodeId === nodeId}showDuration={showDuration}@@ -711,6 +752,7 @@ export function TraceTimeline() {parentTotalDuration={parentTotalDuration}commentCount={comments.get(nodeId) ?? 0}nodeScores={scoresByNodeId.get(nodeId) ?? EMPTY_SCORES}+ measurer={measurer}onSelect={handleSelectNode}onHover={handleHoverNode}/>diff --git a/web/src/features/traces/components/TraceTimeline/__tests__/timeline.fixtures.ts b/web/src/features/traces/components/TraceTimeline/__tests__/timeline.fixtures.tsindex ec2866f097..d3949607d7 100644--- a/web/src/features/traces/components/TraceTimeline/__tests__/timeline.fixtures.ts+++ b/web/src/features/traces/components/TraceTimeline/__tests__/timeline.fixtures.ts@@ -7,8 +7,8 @@import Decimal from "decimal.js";import { type TreeNode } from "@/src/features/traces/types/treeNode";import {- type FlatTimelineItem,- type TimelineMetrics,+ type TimelineBarProps,+ type TimelineRowNode,} from "@/src/features/traces/components/TraceTimeline/types";const BASE_START = new Date("2024-01-01T00:00:00.000Z");@@ -31,23 +31,93 @@ export function makeTreeNode(overrides: Partial<TreeNode> = {}): TreeNode {};}-export function makeMetrics(- overrides: Partial<TimelineMetrics> = {},-): TimelineMetrics {- return { startOffset: 60, itemWidth: 220, latency: 2, ...overrides };-}--export function makeItem(- overrides: Partial<FlatTimelineItem> = {},-): FlatTimelineItem {+/**+ * A row as `layout()` returns it. Geometry is passed in directly rather than+ * computed so a story can pin the exact placement it wants to show.+ */+export function makeRow(+ overrides: Partial<TimelineRowNode> = {},+): TimelineRowNode {+ const node = overrides.node ?? makeTreeNode();return {- node: overrides.node ?? makeTreeNode(),+ node,+ id: node.id,+ name: node.name,+ type: node.type,+ index: 0,depth: 0,treeLines: [],isLastSibling: true,- metrics: overrides.metrics ?? makeMetrics(),+ hasChildren: node.children.length > 0,+ isCollapsed: false,+ y: 0,+ height: 26,+ x: 60,+ width: 220,+ clippedLeft: false,+ clippedRight: false,+ offscreen: false,+ durationMs: 2000,+ firstTokenX: null,+ label: "2.00s",+ labelWidth: 32,+ labelPlacement: "after",+ labelX: 286,+ startMs: 0,+ endMs: 2000,...overrides,};}export const cost = (value: number) => new Decimal(value);++/**+ * A numeric score, as the timeline receives them: metadata already stringified.+ *+ * `level` and the annotation flags matter for WIDTH: a row that mixes levels+ * grows a spelled-out pill per chip, and a value carrying a comment and metadata+ * grows two icons β all three are things the cluster has to reserve room for.+ */+export function score(+ name: string,+ value: number,+ extras: {+ level?: "trace" | "observation";+ comment?: string;+ metadata?: string;+ /**+ * A categorical score's own label. Worth setting when a test needs its width+ * to be EXACT: the measurer prices every digit at the widest digit's width,+ * on purpose (a ticking duration must not jitter), so a numeric value is+ * reserved a couple of px over β enough slack to hide a small mispricing+ * elsewhere in the same sum.+ */+ stringValue?: string;+ } = {},+): NonNullable<TimelineBarProps["scores"]>[number] {+ return {+ id: `score-${name}`,+ projectId: "project",+ environment: "default",+ name,+ value,+ stringValue: extras.stringValue ?? null,+ dataType: extras.stringValue ? "CATEGORICAL" : "NUMERIC",+ source: "API",+ authorUserId: null,+ comment: extras.comment ?? null,+ metadata: extras.metadata ?? null,+ configId: null,+ queueId: null,+ executionTraceId: null,+ createdAt: BASE_START,+ updatedAt: BASE_START,+ timestamp: BASE_START,+ traceId: "trace",+ sessionId: null,+ datasetRunId: null,+ // A trace-level score has no observation; that is what makes a row "mixed".+ observationId: extras.level === "trace" ? null : "node",+ longStringValue: "",+ };+}diff --git a/web/src/features/traces/components/TraceTimeline/timeline-flattening.ts b/web/src/features/traces/components/TraceTimeline/timeline-flattening.tsdeleted file mode 100644index ece9dfe1c6..0000000000--- a/web/src/features/traces/components/TraceTimeline/timeline-flattening.ts+++ /dev/null@@ -1,139 +0,0 @@-/**- * Timeline-specific tree flattening with pre-computed metrics.- * Extends base tree flattening to include timeline positioning calculations.- */--import { type TreeNode } from "../../types/treeNode";-import { type FlatTimelineItem, type TimelineMetrics } from "./types";-import {- calculateTimelineOffset,- calculateTimelineWidth,- SCALE_WIDTH,-} from "../../fns/timelineCalculations";--/**- * Flattens tree into list for timeline virtualized rendering.- * Pre-computes timeline metrics (offset, width) during flattening for performance.- *- * Uses iterative approach to avoid stack overflow with deep trees.- *- * @param roots - Root nodes to flatten (supports multiple roots)- * @param collapsedNodes - Set of node IDs that are collapsed- * @param traceStartTime - When the trace started (for offset calculation)- * @param totalScaleSpan - Total duration of the trace in seconds- * @param scaleWidth - Width of the timeline scale in pixels (default: SCALE_WIDTH)- * @returns Flat list of nodes with timeline metrics- */-export function flattenTreeWithTimelineMetrics(- roots: TreeNode[],- collapsedNodes: Set<string>,- traceStartTime: Date,- totalScaleSpan: number,- scaleWidth: number = SCALE_WIDTH,-): FlatTimelineItem[] {- if (roots.length === 0) return [];-- const flatList: FlatTimelineItem[] = [];-- // Sort roots by startTime- const sortedRoots = [...roots].sort(- (a, b) => a.startTime.getTime() - b.startTime.getTime(),- );-- // Initialize stack with all roots at depth 0 (in reverse order for correct DFS)- const stack: Array<{- node: TreeNode;- depth: number;- treeLines: boolean[];- isLastSibling: boolean;- }> = [];-- for (let i = sortedRoots.length - 1; i >= 0; i--) {- stack.push({- node: sortedRoots[i]!,- depth: 0,- treeLines: [],- isLastSibling: i === sortedRoots.length - 1,- });- }-- // Process stack (LIFO - depth-first traversal)- while (stack.length > 0) {- const current = stack.pop()!;- const currentNode = current.node;-- // Pre-compute timeline metrics ONCE during flattening- const latency = currentNode.endTime- ? (currentNode.endTime.getTime() - currentNode.startTime.getTime()) / 1000- : undefined;-- const startOffset = calculateTimelineOffset(- currentNode.startTime,- traceStartTime,- totalScaleSpan,- scaleWidth,- );-- const itemWidth = calculateTimelineWidth(- latency ?? 0,- totalScaleSpan,- scaleWidth,- );-- // Handle first token time for streaming LLMs (completionStartTime)- // This is stored on observations that have streaming responses- const firstTokenTimeOffset =- "completionStartTime" in currentNode &&- currentNode.completionStartTime instanceof Date- ? calculateTimelineOffset(- currentNode.completionStartTime,- traceStartTime,- totalScaleSpan,- scaleWidth,- )- : undefined;-- const metrics: TimelineMetrics = {- startOffset,- itemWidth,- firstTokenTimeOffset,- latency,- };-- // Add current node to result- flatList.push({- node: currentNode,- depth: current.depth,- treeLines: current.treeLines,- isLastSibling: current.isLastSibling,- metrics,- });-- // If node has children and is not collapsed, add children to stack- if (- currentNode.children.length > 0 &&- !collapsedNodes.has(currentNode.id)- ) {- // Sort children by startTime (chronological order)- const sortedChildren = [...currentNode.children].sort(- (a, b) => a.startTime.getTime() - b.startTime.getTime(),- );-- // Push children in REVERSE order to maintain left-to-right DFS traversal- // (stack is LIFO, so last pushed = first popped)- for (let i = sortedChildren.length - 1; i >= 0; i--) {- const child = sortedChildren[i];- const isChildLast = i === sortedChildren.length - 1;-- stack.push({- node: child,- depth: current.depth + 1,- treeLines: [...current.treeLines, !isChildLast], // Add line if not last child- isLastSibling: isChildLast,- });- }- }- }-- return flatList;-}diff --git a/web/src/features/traces/components/TraceTimeline/types.ts b/web/src/features/traces/components/TraceTimeline/types.tsindex 84042e9e3c..58883273b0 100644--- a/web/src/features/traces/components/TraceTimeline/types.ts+++ b/web/src/features/traces/components/TraceTimeline/types.ts@@ -1,26 +1,21 @@/*** Timeline-specific types for trace visualization+ *+ * Geometry is not here: every coordinate comes from `PositionedNode`, produced+ * by the pure `layout()` in fns/timeline. These types only describe what the+ * row components need on top of it.*/import type { TreeNode } from "../../types/treeNode";+import type { PositionedNode, Tick } from "../../fns/timeline/layout";+import type { TextMeasurer } from "../../fns/timeline/textMeasurer";+import type { Density } from "../../fns/timeline/density";import type Decimal from "decimal.js";import type { ScoreDomain } from "@langfuse/shared";import type { WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";-/**- * Pre-computed timeline metrics for efficient rendering- * Calculated once during tree flattening to avoid per-frame calculations- */-export interface TimelineMetrics {- /** Horizontal offset from trace start (in pixels) */- startOffset: number;- /** Width of the timeline bar (in pixels) */- itemWidth: number;- /** Offset for first token time marker (for streaming LLMs, in pixels) */- firstTokenTimeOffset?: number;- /** Duration in seconds */- latency?: number;-}+/** A row of the timeline, positioned against the measured lane. */+export type TimelineRowNode = PositionedNode<TreeNode>;/*** Props for TimelineBar component@@ -29,8 +24,19 @@ export interface TimelineMetrics {* gutter (TimelineGutterRow), not here.*/export interface TimelineBarProps {- node: TreeNode;- metrics: TimelineMetrics;+ row: TimelineRowNode;+ /** Measured width of the chart lane; the cluster may not cross it. */+ laneWidth: number;+ /** Same measurer layout() used, so the bar can fit its own optional badges. */+ measurer: TextMeasurer;+ /**+ * Same density layout() used. The cluster's gap and inset ARE+ * `labelGapPx`/`labelPaddingPx` β the values `placeLabel()` measured the+ * placement with β so they have to come from the same place, or a change to+ * density silently desyncs the rendered cluster from the decision made about+ * where it goes.+ */+ density: Density;isSelected: boolean;/** Row is hovered (driven by shared state so the whole row highlights). */isHovered?: boolean;@@ -49,26 +55,13 @@ export interface TimelineBarProps {scores?: WithStringifiedMetadata<ScoreDomain>[];}-/**- * Flattened timeline item for virtualized rendering- * Extends TreeNode with timeline positioning data and tree structure metadata- */-export interface FlatTimelineItem {- node: TreeNode;- depth: number;- treeLines: boolean[];- isLastSibling: boolean;- // Pre-computed timeline metrics- metrics: TimelineMetrics;-}-/*** Props for TimelineGutterRow component* Renders the left gutter: tree connectors + icon + name (the depth coordinate).* Identity only β time/metrics live on the bar (TimelineBar) in the chart pane.*/export interface TimelineGutterRowProps {- item: FlatTimelineItem;+ row: Pick<TimelineRowNode, "node" | "depth" | "treeLines" | "isLastSibling">;isSelected: boolean;/** Row is hovered (shared state so the gutter + chart highlight together). */isHovered?: boolean;@@ -87,13 +80,10 @@ export interface TimelineGutterRowProps {/*** Props for TimelineScale component- * Renders time axis with markers+ * Renders the time axis from ticks the layout already placed and labelled.*/export interface TimelineScaleProps {- /** Total trace duration in seconds */- traceDuration: number;- /** Width of the timeline scale in pixels */- scaleWidth: number;- /** Step size between time markers in seconds */- stepSize: number;+ ticks: readonly Tick[];+ /** Measured width of the chart lane. */+ laneWidth: number;}diff --git a/web/src/features/traces/components/TraceTimelineV2/TimelineV2.stories.tsx b/web/src/features/traces/components/TraceTimelineV2/TimelineV2.stories.tsxindex 9b36dc904d..cf41e61bc5 100644--- a/web/src/features/traces/components/TraceTimelineV2/TimelineV2.stories.tsx+++ b/web/src/features/traces/components/TraceTimelineV2/TimelineV2.stories.tsx@@ -13,7 +13,7 @@ import {singleSpan,threeSpans,zeroDurationTrace,-} from "./__tests__/timelineV2.fixtures";+} from "../../fns/timeline/__tests__/timelineV2.fixtures";const meta = preview.meta({component: TimelineV2,diff --git a/web/src/features/traces/components/TraceTimelineV2/TimelineV2.tsx b/web/src/features/traces/components/TraceTimelineV2/TimelineV2.tsxindex f6a2a3f6ce..301ad3bf1d 100644--- a/web/src/features/traces/components/TraceTimelineV2/TimelineV2.tsx+++ b/web/src/features/traces/components/TraceTimelineV2/TimelineV2.tsx@@ -27,7 +27,7 @@ import {detectPointerModality,resolveDensity,type PointerModality,-} from "./density";+} from "../../fns/timeline/density";import {formatDurationMs,layout,@@ -35,8 +35,8 @@ import {timeCompressionFor,type LayoutNode,type PositionedNode,-} from "./layout";-import { createTextMeasurer } from "./textMeasurer";+} from "../../fns/timeline/layout";+import { createTextMeasurer } from "../../fns/timeline/textMeasurer";import {fitView,isFitted,@@ -46,7 +46,7 @@ import {zoomView,type Box,type TimeSpan,-} from "./viewTransform";+} from "../../fns/timeline/viewTransform";/*** The four takes on "what happens to the name gutter below ~480px", so thediff --git a/web/src/features/traces/components/TraceTimelineV2/TimelineV2Compression.stories.tsx b/web/src/features/traces/components/TraceTimelineV2/TimelineV2Compression.stories.tsxindex 1d2c828742..78c1681557 100644--- a/web/src/features/traces/components/TraceTimelineV2/TimelineV2Compression.stories.tsx+++ b/web/src/features/traces/components/TraceTimelineV2/TimelineV2Compression.stories.tsx@@ -1,6 +1,9 @@import preview from "../../../../../.storybook/preview";import { TimelineV2 } from "./TimelineV2";-import { longTailTrace, manySpans } from "./__tests__/timelineV2.fixtures";+import {+ longTailTrace,+ manySpans,+} from "../../fns/timeline/__tests__/timelineV2.fixtures";const meta = preview.meta({component: TimelineV2,diff --git a/web/src/features/traces/components/TraceTimelineV2/TimelineV2Mobile.stories.tsx b/web/src/features/traces/components/TraceTimelineV2/TimelineV2Mobile.stories.tsxindex 435630c59e..19c31e07a6 100644--- a/web/src/features/traces/components/TraceTimelineV2/TimelineV2Mobile.stories.tsx+++ b/web/src/features/traces/components/TraceTimelineV2/TimelineV2Mobile.stories.tsx@@ -1,6 +1,6 @@import preview from "../../../../../.storybook/preview";import { TimelineV2, type TimelineComposition } from "./TimelineV2";-import { reporterTrace } from "./__tests__/timelineV2.fixtures";+import { reporterTrace } from "../../fns/timeline/__tests__/timelineV2.fixtures";const meta = preview.meta({component: TimelineV2,diff --git a/web/src/features/traces/components/TraceTimelineV2/TimelineV2Sizes.stories.tsx b/web/src/features/traces/components/TraceTimelineV2/TimelineV2Sizes.stories.tsxindex 78ddd2bb4f..c62c808c40 100644--- a/web/src/features/traces/components/TraceTimelineV2/TimelineV2Sizes.stories.tsx+++ b/web/src/features/traces/components/TraceTimelineV2/TimelineV2Sizes.stories.tsx@@ -1,6 +1,6 @@import preview from "../../../../../.storybook/preview";import { TimelineV2 } from "./TimelineV2";-import { reporterTrace } from "./__tests__/timelineV2.fixtures";+import { reporterTrace } from "../../fns/timeline/__tests__/timelineV2.fixtures";const meta = preview.meta({component: TimelineV2,diff --git a/web/src/features/traces/components/TraceTimelineV2/__tests__/timelineV2.fixtures.ts b/web/src/features/traces/fns/timeline/__tests__/timelineV2.fixtures.tssimilarity index 98%rename from web/src/features/traces/components/TraceTimelineV2/__tests__/timelineV2.fixtures.tsrename to web/src/features/traces/fns/timeline/__tests__/timelineV2.fixtures.tsindex ed66c69bea..f5f69d2b4b 100644--- a/web/src/features/traces/components/TraceTimelineV2/__tests__/timelineV2.fixtures.ts+++ b/web/src/features/traces/fns/timeline/__tests__/timelineV2.fixtures.ts@@ -4,7 +4,7 @@* the tests look at the same pixels.*/-import type { LayoutNode } from "@/src/features/traces/components/TraceTimelineV2/layout";+import type { LayoutNode } from "@/src/features/traces/fns/timeline/layout";const BASE_START = new Date("2024-01-01T00:00:00.000Z").getTime();diff --git a/web/src/features/traces/components/TraceTimelineV2/density.ts b/web/src/features/traces/fns/timeline/density.tssimilarity index 100%rename from web/src/features/traces/components/TraceTimelineV2/density.tsrename to web/src/features/traces/fns/timeline/density.tsdiff --git a/web/src/features/traces/components/TraceTimelineV2/layout.clienttest.ts b/web/src/features/traces/fns/timeline/layout.clienttest.tssimilarity index 90%rename from web/src/features/traces/components/TraceTimelineV2/layout.clienttest.tsrename to web/src/features/traces/fns/timeline/layout.clienttest.tsindex 4714e2652b..c3ff64d28c 100644--- a/web/src/features/traces/components/TraceTimelineV2/layout.clienttest.ts+++ b/web/src/features/traces/fns/timeline/layout.clienttest.ts@@ -285,6 +285,34 @@ describe("textMeasurer", () => {expect(measure("β 1.24s")).toBeCloseTo(70, 6);});+ it("measures bold wider than regular, and neither twin sets the other's font", () => {+ // Width follows the FONT this context was last given, so an interleaved call+ // that forgot to set it reads as the other weight β which is the bug: both+ // twins share one canvas, and the run measurement happens lazily at measure+ // time rather than when the twin was built.+ const byWeight: {+ font: string;+ measureText: (text: string) => TextMetrics;+ } = {+ font: "",+ measureText: (text: string) =>+ ({+ width: text.length * (byWeight.font.startsWith("700") ? 20 : 10),+ }) as TextMetrics,+ };+ const measurer = createTextMeasurerFrom(+ byWeight as unknown as CanvasRenderingContext2D,+ "12px test",+ );++ expect(measurer.measure("abc")).toBeCloseTo(30, 6);+ expect(measurer.measureBold("abc")).toBeCloseTo(60, 6);+ // Interleaved, and each still its own weight.+ expect(measurer.measure("abcd")).toBeCloseTo(40, 6);+ expect(measurer.measureBold("abcd")).toBeCloseTo(80, 6);+ expect(measurer.measure("ab")).toBeCloseTo(20, 6);+ });+it("falls back to a flat per-letter width with no canvas", () => {expect(createTextMeasurerFrom(null).measure("1m 35s")).toBeCloseTo(6 * PX_PER_LETTER,diff --git a/web/src/features/traces/components/TraceTimelineV2/layout.ts b/web/src/features/traces/fns/timeline/layout.tssimilarity index 84%rename from web/src/features/traces/components/TraceTimelineV2/layout.tsrename to web/src/features/traces/fns/timeline/layout.tsindex df379a6272..0848e53489 100644--- a/web/src/features/traces/components/TraceTimelineV2/layout.ts+++ b/web/src/features/traces/fns/timeline/layout.ts@@ -62,8 +62,8 @@ export type LayoutNode = {children: LayoutNode[];};-export type TimelineRow = {- node: LayoutNode;+export type TimelineRow<TNode extends LayoutNode = LayoutNode> = {+ node: TNode;depth: number;treeLines: boolean[];isLastSibling: boolean;@@ -73,7 +73,9 @@ export type TimelineRow = {export type LabelPlacement = "inside" | "after" | "before" | "hidden";-export type PositionedNode = {+export type PositionedNode<TNode extends LayoutNode = LayoutNode> = {+ /** The input node, carried through so callers keep their own richer type. */+ node: TNode;id: string;name: string;type: string;@@ -115,16 +117,16 @@ export type GapMarker = {label: string;};-export type PreparedTimeline = {- rows: TimelineRow[];+export type PreparedTimeline<TNode extends LayoutNode = LayoutNode> = {+ rows: Array<TimelineRow<TNode>>;originMs: number;durationMs: number;/** ms offsets of every non-root span β the compression input */spans: Array<[number, number]>;};-export type TimelineLayout = {- nodes: PositionedNode[];+export type TimelineLayout<TNode extends LayoutNode = LayoutNode> = {+ nodes: Array<PositionedNode<TNode>>;rowCount: number;rowHeight: number;contentHeight: number;@@ -140,8 +142,8 @@ export type TimelineLayout = {compression: TimeCompression;};-export type LayoutInput = {- roots: readonly LayoutNode[];+export type LayoutInput<TNode extends LayoutNode = LayoutNode> = {+ roots: readonly TNode[];/** measured β there is no fallback constant */box: Box;density: Density;@@ -151,19 +153,42 @@ export type LayoutInput = {compress: boolean;collapsed?: ReadonlySet<string>;/** memoized tree walk; recomputed here when absent */- prepared?: PreparedTimeline;+ prepared?: PreparedTimeline<TNode>;/** memoized compression; recomputed here when absent */compression?: TimeCompression;/** position only these rows (the virtualizer's mounted window) */rowRange?: { startIndex: number; endIndex: number };+ /**+ * How a row's duration reads. The layout MEASURES the text it places, so the+ * caller that RENDERS the text has to be the one that formats it: a caller+ * drawing `1h 05m 00s` where the layout measured `1h 05m` picks the side from+ * the wrong width, and then its own fit check drops a label that would have+ * fitted on the other one. Callers render `label`.+ */+ formatLabel?: (durationMs: number) => string;};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;+/** The tick line itself β a `border-l`, which the label is positioned inside of. */+export const TICK_LINE_PX = 1;+/** The gap between that line and its label. */+export const TICK_LABEL_GAP_PX = 4;+/**+ * What a label costs to the right of its tick's `x`: the line, then the gap.+ * Derived rather than written down, and exported, because the renderer positions+ * with the same two facts.+ *+ * There were three numbers for this one distance β 6 here, a `left-1` in the CSS+ * and a literal 4 in the label's own clamp β and every one of them was wrong: the+ * label sits inside the tick's 1px border, so its offset from `x` is 5. 6 dropped+ * a tick that would have rendered whole; 4 would have admitted one whose label+ * then gets truncated by its clamp. A reservation that does not match the render+ * is wrong even when it errs safely, because nothing says which way it errs next.+ */+export const TICK_LABEL_INSET_PX = TICK_LINE_PX + TICK_LABEL_GAP_PX;// Nice tick steps in ms. Above a minute they land on time-nice boundaries so// hour-scale traces get clean labels instead of "1500s".@@ -204,24 +229,24 @@ export function formatDurationMs(ms: number): string {* collect the spans compression may keep. Iterative β deep traces must not* blow the stack.*/-export function prepareTimeline(- roots: readonly LayoutNode[],+export function prepareTimeline<TNode extends LayoutNode>(+ roots: readonly TNode[],collapsed: ReadonlySet<string> = new Set(),-): PreparedTimeline {+): PreparedTimeline<TNode> {if (roots.length === 0) {return { rows: [], originMs: 0, durationMs: 0, spans: [] };}let originMs = Infinity;let latestEndMs = -Infinity;- const all: LayoutNode[] = [];- const boundsStack: LayoutNode[] = [...roots];+ const all: TNode[] = [];+ const boundsStack: TNode[] = [...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);+ for (const child of node.children) boundsStack.push(child as TNode);}if (!Number.isFinite(originMs) || !Number.isFinite(latestEndMs)) {@@ -238,9 +263,10 @@ export function prepareTimeline(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 byStart = (a: TNode, b: TNode) => startOf(a) - startOf(b);+ const rows: Array<TimelineRow<TNode>> = [];+ const stack: Array<Omit<TimelineRow<TNode>, "hasChildren" | "isCollapsed">> =+ [];const sortedRoots = [...roots].sort(byStart);for (let i = sortedRoots.length - 1; i >= 0; i--) {stack.push({@@ -258,7 +284,7 @@ export function prepareTimeline(rows.push({ ...current, hasChildren, isCollapsed });if (!hasChildren || isCollapsed) continue;- const children = [...current.node.children].sort(byStart);+ const children = [...(current.node.children as TNode[])].sort(byStart);for (let i = children.length - 1; i >= 0; i--) {stack.push({node: children[i]!,@@ -274,7 +300,7 @@ export function prepareTimeline(/** Memoize on `[prepared, box.width, compress]` β not on the view. */export function timeCompressionFor(- prepared: PreparedTimeline,+ prepared: PreparedTimeline<LayoutNode>,box: Box,compress: boolean,): TimeCompression {@@ -288,7 +314,9 @@ export function timeCompressionFor(: identityCompression(prepared.durationMs);}-export function layout(input: LayoutInput): TimelineLayout {+export function layout<TNode extends LayoutNode>(+ input: LayoutInput<TNode>,+): TimelineLayout<TNode> {const { box, density, measurer } = input;const laneWidth = Math.max(Number.isFinite(box.width) ? box.width : 0, 0);@@ -308,7 +336,7 @@ export function layout(input: LayoutInput): TimelineLayout {prepared.rows.length - 1,);- const nodes: PositionedNode[] = [];+ const nodes: Array<PositionedNode<TNode>> = [];for (let index = from; index <= to; index++) {const row = prepared.rows[index]!;nodes.push(@@ -320,6 +348,7 @@ export function layout(input: LayoutInput): TimelineLayout {rowHeight,density,measurer,+ formatLabel: input.formatLabel ?? formatDurationMs,}),);}@@ -340,8 +369,8 @@ export function layout(input: LayoutInput): TimelineLayout {};}-function positionRow(- row: TimelineRow,+function positionRow<TNode extends LayoutNode>(+ row: TimelineRow<TNode>,index: number,context: {originMs: number;@@ -351,8 +380,9 @@ function positionRow(rowHeight: number;density: Density;measurer: TextMeasurer;+ formatLabel: (durationMs: number) => string;},-): PositionedNode {+): PositionedNode<TNode> {const {originMs,compression,@@ -361,6 +391,7 @@ function positionRow(rowHeight,density,measurer,+ formatLabel,} = context;const node = row.node;@@ -381,7 +412,7 @@ function positionRow(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 label = durationMs == null ? "" : formatLabel(durationMs);const labelWidth = label ? measurer.measure(label) : 0;const { labelPlacement, labelX } = placeLabel({label,@@ -401,6 +432,7 @@ function positionRow(: transform.toPx(compression.toCompressedMs(firstTokenMs));return {+ node,id: node.id,name: node.name,type: node.type ?? "SPAN",diff --git a/web/src/features/traces/components/TraceTimelineV2/textMeasurer.ts b/web/src/features/traces/fns/timeline/textMeasurer.tssimilarity index 64%rename from web/src/features/traces/components/TraceTimelineV2/textMeasurer.tsrename to web/src/features/traces/fns/timeline/textMeasurer.tsindex 55cb430c7a..108bbc2a2e 100644--- a/web/src/features/traces/components/TraceTimelineV2/textMeasurer.ts+++ b/web/src/features/traces/fns/timeline/textMeasurer.ts@@ -33,7 +33,16 @@ const unitAt = (text: string, index: number): string | null => {return null;};-export type TextMeasurer = { measure: (text: string) => number };+export type TextMeasurer = {+ measure: (text: string) => number;+ /**+ * The same text as the browser will set it in BOLD. Callers that reserve room+ * for bold content need this: measuring it at the regular weight came out+ * ~4% short on one font stack and fitted on another, which is a reservation+ * that clips only on some machines.+ */+ measureBold: (text: string) => number;+};export function createTextMeasurer(font = "12px ui-sans-serif"): TextMeasurer {let context: CanvasRenderingContext2D | null = null;@@ -53,6 +62,18 @@ export function createTextMeasurerFrom(context: CanvasRenderingContext2D | null,font = "12px ui-sans-serif",): TextMeasurer {+ return {+ measure: measurerFor(context, font),+ // A CSS font shorthand takes the weight first, and the callers here build+ // theirs from a probe's `font-size` + `font-family`.+ measureBold: measurerFor(context, `700 ${font}`),+ };+}++function measurerFor(+ context: CanvasRenderingContext2D | null,+ font: string,+): (text: string) => number {const glyphs = new Map<string, number>();const units = new Map<string, number>();const cache = new Map<string, number>();@@ -75,30 +96,49 @@ export function createTextMeasurerFrom(const computeWidth = (text: string) => {let width = 0;+ // Anything that is neither a digit nor a duration unit is measured as a run,+ // not estimated per letter: callers now price arbitrary text with this+ // (a score's name, a level label), and at 6.5px a letter `quality:` came out+ // 13px wider than it renders β slack that hides a real under-reservation+ // somewhere else in the same sum.+ let run = "";+ const flush = () => {+ if (!run) return;+ if (context) {+ // Set every time: the bold twin shares this context, and whichever+ // measured last would otherwise decide the font for both.+ context.font = font;+ width += context.measureText(run).width;+ } else {+ width += run.length * PX_PER_LETTER;+ }+ run = "";+ };for (let i = 0; i < text.length; i++) {const glyph = glyphs.get(text[i]!);if (glyph !== undefined) {+ flush();width += glyph;continue;}const unit = unitAt(text, i);if (unit !== null) {+ flush();width += units.get(unit) ?? unit.length * PX_PER_LETTER;i += unit.length - 1;continue;}- width += PX_PER_LETTER;+ run += text[i]!;}+ flush();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;- },+ return (text: string) => {+ 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/fns/timeline/timeCompression.tssimilarity index 100%rename from web/src/features/traces/components/TraceTimelineV2/timeCompression.tsrename to web/src/features/traces/fns/timeline/timeCompression.tsdiff --git a/web/src/features/traces/components/TraceTimelineV2/viewTransform.ts b/web/src/features/traces/fns/timeline/viewTransform.tssimilarity index 100%rename from web/src/features/traces/components/TraceTimelineV2/viewTransform.tsrename to web/src/features/traces/fns/timeline/viewTransform.tsdiff --git a/web/src/features/traces/fns/timelineCalculations.clienttest.ts b/web/src/features/traces/fns/timelineCalculations.clienttest.tsindex 3c91d82a0d..2ef91ecf85 100644--- a/web/src/features/traces/fns/timelineCalculations.clienttest.ts+++ b/web/src/features/traces/fns/timelineCalculations.clienttest.ts@@ -1,17 +1,9 @@// @vitest-environment jsdomimport {- calculateTimelineOffset,- calculateTimelineWidth,- calculateStepSize,calculateTraceDuration,computeSelectionScrollTarget,findEarliestStartTime,- getPredefinedStepSizes,- REVEAL_LEFT_FRACTION,- REVEAL_MARGIN_PX,- SCALE_WIDTH,- PREDEFINED_STEP_SIZES,} from "./timelineCalculations";import { type TreeNode } from "@/src/features/traces/types/treeNode";@@ -43,271 +35,6 @@ function makeNode(}describe("timeline-calculations", () => {- describe("calculateTimelineOffset", () => {- it("should return 0 for node starting at trace start", () => {- const traceStart = new Date("2024-01-01T00:00:00Z");- const nodeStart = new Date("2024-01-01T00:00:00Z");- const totalDuration = 10; // 10 seconds-- const offset = calculateTimelineOffset(- nodeStart,- traceStart,- totalDuration,- );-- expect(offset).toBe(0);- });-- it("should return SCALE_WIDTH for node starting at trace end", () => {- const traceStart = new Date("2024-01-01T00:00:00Z");- const nodeStart = new Date("2024-01-01T00:00:10Z"); // 10 seconds later- const totalDuration = 10;-- const offset = calculateTimelineOffset(- nodeStart,- traceStart,- totalDuration,- );-- expect(offset).toBe(SCALE_WIDTH);- });-- it("should return half SCALE_WIDTH for node starting at trace midpoint", () => {- const traceStart = new Date("2024-01-01T00:00:00Z");- const nodeStart = new Date("2024-01-01T00:00:05Z"); // 5 seconds later- const totalDuration = 10;-- const offset = calculateTimelineOffset(- nodeStart,- traceStart,- totalDuration,- );-- expect(offset).toBe(SCALE_WIDTH / 2);- });-- it("should handle custom scale width", () => {- const traceStart = new Date("2024-01-01T00:00:00Z");- const nodeStart = new Date("2024-01-01T00:00:05Z");- const totalDuration = 10;- const customWidth = 1800;-- const offset = calculateTimelineOffset(- nodeStart,- traceStart,- totalDuration,- customWidth,- );-- expect(offset).toBe(customWidth / 2);- });-- it("should handle fractional seconds", () => {- const traceStart = new Date("2024-01-01T00:00:00Z");- const nodeStart = new Date("2024-01-01T00:00:00.500Z"); // 0.5 seconds later- const totalDuration = 1;-- const offset = calculateTimelineOffset(- nodeStart,- traceStart,- totalDuration,- );-- expect(offset).toBe(SCALE_WIDTH / 2);- });- });-- describe("calculateTimelineWidth", () => {- it("should return 0 for zero duration", () => {- const width = calculateTimelineWidth(0, 10);- expect(width).toBe(0);- });-- it("should return SCALE_WIDTH for duration equal to total span", () => {- const width = calculateTimelineWidth(10, 10);- expect(width).toBe(SCALE_WIDTH);- });-- it("should return half SCALE_WIDTH for duration half of total span", () => {- const width = calculateTimelineWidth(5, 10);- expect(width).toBe(SCALE_WIDTH / 2);- });-- it("should handle custom scale width", () => {- const customWidth = 1800;- const width = calculateTimelineWidth(5, 10, customWidth);- expect(width).toBe(customWidth / 2);- });-- it("should handle fractional durations", () => {- const width = calculateTimelineWidth(0.5, 1);- expect(width).toBe(SCALE_WIDTH / 2);- });-- it("should handle very small durations", () => {- const width = calculateTimelineWidth(0.001, 10);- expect(width).toBe(SCALE_WIDTH * 0.0001);- });- });-- describe("calculateStepSize", () => {- it("should select appropriate step size for short traces", () => {- // 1 second trace should use small step size- const stepSize = calculateStepSize(1);- expect(stepSize).toBeLessThanOrEqual(1);- expect(PREDEFINED_STEP_SIZES).toContain(stepSize);- });-- it("should select appropriate step size for medium traces", () => {- // 50 second trace- const stepSize = calculateStepSize(50);- expect(stepSize).toBeGreaterThan(1);- expect(stepSize).toBeLessThanOrEqual(50);- expect(PREDEFINED_STEP_SIZES).toContain(stepSize);- });-- it("should select appropriate step size for long traces", () => {- // 500 second trace- const stepSize = calculateStepSize(500);- expect(stepSize).toBeGreaterThan(10);- expect(PREDEFINED_STEP_SIZES).toContain(stepSize);- });-- it("should keep tick spacing readable for very long traces (LFE-10959)", () => {- // A ~2.8h trace (the reported deep-chain trace) previously clamped to- // the 500s max step -> ~21 ticks ~45px apart with overlapping labels.- // Ticks must never be denser than the STEP_SIZE (100px) design grid.- for (const duration of [- 10_000, 10_061, 40_000, 86_400, 100_000, 500_000, 1_000_000,- ]) {- const stepSize = calculateStepSize(duration);- const tickSpacingPx = (stepSize / duration) * SCALE_WIDTH;- expect(tickSpacingPx).toBeGreaterThanOrEqual(100);- }- });-- it("should pick time-nice steps for hour-scale traces", () => {- // ~2.8h trace: step lands on a clean 20m boundary, not a raw 500s clamp- expect(calculateStepSize(10_061)).toBe(1200);- });-- it("should return smallest applicable step size", () => {- // For a 2 second trace, should select a step size >= calculated- const stepSize = calculateStepSize(2);- const calculatedStepSize = 2 / (SCALE_WIDTH / 100);- expect(stepSize).toBeGreaterThanOrEqual(calculatedStepSize);- });-- it("should handle custom scale width", () => {- const customWidth = 1800;- const stepSize = calculateStepSize(50, customWidth);- expect(PREDEFINED_STEP_SIZES).toContain(stepSize);- });-- it("should be consistent for same input", () => {- const duration = 25;- const stepSize1 = calculateStepSize(duration);- const stepSize2 = calculateStepSize(duration);- expect(stepSize1).toBe(stepSize2);- });- });-- describe("getPredefinedStepSizes", () => {- it("should return array of step sizes", () => {- const stepSizes = getPredefinedStepSizes();- expect(Array.isArray(stepSizes)).toBe(true);- expect(stepSizes.length).toBeGreaterThan(0);- });-- it("should return a copy (not mutate original)", () => {- const stepSizes = getPredefinedStepSizes();- const originalLength = stepSizes.length;- stepSizes.push(999);-- const stepSizes2 = getPredefinedStepSizes();- expect(stepSizes2.length).toBe(originalLength);- expect(stepSizes2).not.toContain(999);- });-- it("should be in ascending order", () => {- const stepSizes = getPredefinedStepSizes();- for (let i = 1; i < stepSizes.length; i++) {- expect(stepSizes[i]).toBeGreaterThan(stepSizes[i - 1]);- }- });-- it("should contain expected range of values", () => {- const stepSizes = getPredefinedStepSizes();- expect(stepSizes[0]).toBeLessThanOrEqual(1); // Has sub-second steps- expect(stepSizes[stepSizes.length - 1]).toBeGreaterThanOrEqual(100); // Has large steps- });- });-- describe("Integration: offset + width should fit within trace", () => {- it("should place a mid-trace observation correctly", () => {- const traceStart = new Date("2024-01-01T00:00:00Z");- const nodeStart = new Date("2024-01-01T00:00:03Z"); // starts at 3s- const duration = 2; // lasts 2 seconds- const totalDuration = 10;-- const offset = calculateTimelineOffset(- nodeStart,- traceStart,- totalDuration,- );- const width = calculateTimelineWidth(duration, totalDuration);-- // Should start at 30% of scale width- expect(offset).toBe(SCALE_WIDTH * 0.3);- // Should be 20% of scale width- expect(width).toBe(SCALE_WIDTH * 0.2);- // Should end at 50% of scale width- expect(offset + width).toBe(SCALE_WIDTH * 0.5);- });-- it("should handle observation at trace boundary", () => {- const traceStart = new Date("2024-01-01T00:00:00Z");- const nodeStart = new Date("2024-01-01T00:00:00Z");- const duration = 10;- const totalDuration = 10;-- const offset = calculateTimelineOffset(- nodeStart,- traceStart,- totalDuration,- );- const width = calculateTimelineWidth(duration, totalDuration);-- expect(offset).toBe(0);- expect(width).toBe(SCALE_WIDTH);- expect(offset + width).toBe(SCALE_WIDTH);- });- });-- describe("Edge cases", () => {- it("calculateTimelineOffset should handle zero duration trace", () => {- const traceStart = new Date("2024-01-01T00:00:00Z");- const nodeStart = new Date("2024-01-01T00:00:00Z");- const totalDuration = 0;-- // Should not throw, but result is undefined (division by zero)- expect(() => {- calculateTimelineOffset(nodeStart, traceStart, totalDuration);- }).not.toThrow();- });-- it("calculateStepSize should handle very small durations", () => {- const stepSize = calculateStepSize(0.1);- expect(stepSize).toBe(PREDEFINED_STEP_SIZES[0]); // Should use smallest step- });-- it("calculateTimelineWidth should handle duration larger than total span", () => {- // This shouldn't happen in practice, but handle gracefully- const width = calculateTimelineWidth(20, 10);- expect(width).toBe(SCALE_WIDTH * 2); // Just calculates proportionally- });- });-describe("findEarliestStartTime (timeline origin)", () => {it("returns null for an empty tree", () => {expect(findEarliestStartTime([])).toBeNull();@@ -334,15 +61,6 @@ describe("timeline-calculations", () => {const origin = findEarliestStartTime([root]);expect(origin?.toISOString()).toBe("2024-01-01T00:00:01.000Z");-- // And the offset of that early child against the corrected origin is 0,- // not negative as it would be when anchoring to the root.- const offset = calculateTimelineOffset(- new Date("2024-01-01T00:00:01Z"),- origin!,- 10,- );- expect(offset).toBe(0);});it("descends into deeply nested children to find the minimum", () => {@@ -420,15 +138,7 @@ describe("timeline-calculations", () => {children: [makeNode("early-child", "2024-01-01T00:00:00Z")],});- const span = calculateTraceDuration([root], origin);- expect(span).toBe(13);-- // The root bar (offset from origin + width) fits exactly within the axis- // (modulo floating-point rounding). With the pre-fix scale of 10 it would- // have reached 1.3 * SCALE_WIDTH and overrun the last tick.- const offset = calculateTimelineOffset(root.startTime, origin, span);- const width = calculateTimelineWidth(root.latency!, span);- expect(offset + width).toBeCloseTo(SCALE_WIDTH, 6);+ expect(calculateTraceDuration([root], origin)).toBe(13);});it("uses the larger of end-based span and offset-aware latency", () => {@@ -449,15 +159,12 @@ describe("timeline-calculations", () => {});describe("computeSelectionScrollTarget", () => {- // A 10-row viewport (260px at 26px rows), 400px wide, scrolled to (0, 0).+ // A 10-row viewport (260px at 26px rows), scrolled to the top.const base = {index: 0,rowHeight: 26,scrollTop: 0,- scrollLeft: 0,clientHeight: 260,- clientWidth: 400,- barStart: null,isInitial: false,};@@ -504,39 +211,4 @@ describe("computeSelectionScrollTarget", () => {});expect(top).toBe(0);});-- it("keeps scrollLeft while the bar start sits inside the comfort band", () => {- const { left } = computeSelectionScrollTarget({- ...base,- scrollLeft: 100,- barStart: 100 + REVEAL_MARGIN_PX, // exactly at the band edge β visible- });- expect(left).toBe(100);- });-- it("reveals an off-screen-right bar a fraction from the left edge", () => {- const { left } = computeSelectionScrollTarget({- ...base,- barStart: 900, // beyond viewRight 400- });- expect(left).toBe(900 - 400 * REVEAL_LEFT_FRACTION);- });-- it("clamps an off-screen-left reveal at 0", () => {- const { left } = computeSelectionScrollTarget({- ...base,- scrollLeft: 600,- barStart: 10, // far left of the viewport- });- expect(left).toBe(0);- });-- it("keeps scrollLeft when there is no bar (barStart null)", () => {- const { left } = computeSelectionScrollTarget({- ...base,- scrollLeft: 250,- barStart: null,- });- expect(left).toBe(250);- });});diff --git a/web/src/features/traces/fns/timelineCalculations.ts b/web/src/features/traces/fns/timelineCalculations.tsindex f6481d512e..e2c837f147 100644--- a/web/src/features/traces/fns/timelineCalculations.ts+++ b/web/src/features/traces/fns/timelineCalculations.ts@@ -1,14 +1,15 @@/**- * Pure functions for timeline calculations- * These functions handle all timeline positioning and sizing logic+ * Trace-level time bounds, shared by every trace view.+ *+ * Positioning is NOT here: bar, label and tick coordinates come from the pure+ * `layout()` in ./timeline, which takes the measured pixel box. This module used+ * to own a `SCALE_WIDTH = 900` constant passed as a DEFAULT PARAMETER to four+ * positioning helpers, so the measured box never reached the math and any lane+ * narrower than 900px pushed part of the trace off-screen.*/import { type TreeNode } from "@/src/features/traces/types/treeNode";-// Fixed widths for timeline styling-export const SCALE_WIDTH = 900;-export const STEP_SIZE = 100;-/*** Find the earliest start time across the whole tree (roots + all descendants).*@@ -91,125 +92,24 @@ export function calculateTraceDuration(return Math.max(spanFromEnds, maxRootLatencySpan);}-// Predefined step sizes for time axis (in seconds). Above 500s the steps land-// on time-nice boundaries (10m, 15m, 20m, 30m, 45m, 1h, 1.5h, 2h, 3h, 4h, 6h,-// 12h, 24h) so hour-scale traces get clean tick labels β without the upper-// entries, multi-hour traces clamped to 500s and rendered ~2Γ the intended-// tick density with overlapping labels (LFE-10959).-export const PREDEFINED_STEP_SIZES = [- 0.25, 0.5, 0.75, 1, 1.25, 1.5, 2, 2.5, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25,- 35, 40, 45, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 600, 900, 1200,- 1800, 2700, 3600, 5400, 7200, 10800, 14400, 21600, 43200, 86400,-];--/**- * Calculate the horizontal offset from the trace start time- * @param nodeStartTime - When the observation started- * @param traceStartTime - When the trace started- * @param totalScaleSpan - Total duration of the trace in seconds- * @param scaleWidth - Width of the timeline scale in pixels- * @returns Horizontal offset in pixels- */-export function calculateTimelineOffset(- nodeStartTime: Date,- traceStartTime: Date,- totalScaleSpan: number,- scaleWidth: number = SCALE_WIDTH,-): number {- const timeFromStart =- (nodeStartTime.getTime() - traceStartTime.getTime()) / 1000;- return (timeFromStart / totalScaleSpan) * scaleWidth;-}--/**- * Calculate the width of a timeline bar from duration- * @param duration - Duration in seconds- * @param totalScaleSpan - Total duration of the trace in seconds- * @param scaleWidth - Width of the timeline scale in pixels- * @returns Width of the bar in pixels- */-export function calculateTimelineWidth(- duration: number,- totalScaleSpan: number,- scaleWidth: number = SCALE_WIDTH,-): number {- return (duration / totalScaleSpan) * scaleWidth;-}--/**- * Calculate appropriate step size for the time axis- * Selects from predefined step sizes to ensure readable time markers- * @param traceDuration - Total trace duration in seconds- * @param scaleWidth - Width of the timeline scale in pixels- * @returns Step size in seconds- */-export function calculateStepSize(- traceDuration: number,- scaleWidth: number = SCALE_WIDTH,-): number {- const calculatedStepSize = traceDuration / (scaleWidth / STEP_SIZE);- const predefined = PREDEFINED_STEP_SIZES.find(- (step) => step >= calculatedStepSize,- );- if (predefined !== undefined) return predefined;- if (!Number.isFinite(calculatedStepSize)) {- return PREDEFINED_STEP_SIZES[PREDEFINED_STEP_SIZES.length - 1];- }- // Beyond the largest predefined step (multi-day traces): whole days keep the- // marker count bounded (never clamp to a smaller step β that multiplies the- // tick count and the labels overlap, LFE-10959).- const DAY = 86_400;- return Math.ceil(calculatedStepSize / DAY) * DAY;-}--/**- * Get all predefined step sizes- * Useful for testing and validation- * @returns Array of predefined step sizes in seconds- */-export function getPredefinedStepSizes(): number[] {- return [...PREDEFINED_STEP_SIZES];-}--// Horizontal reveal on selection: a bar counts as visible only if it sits at-// least this far inside the viewport; when revealed, it lands this fraction-// from the left edge.-export const REVEAL_MARGIN_PX = 16;-export const REVEAL_LEFT_FRACTION = 0.2;-/**- * Scroll target that brings a selected row fully into view on BOTH axes with a- * single scrollTo (two competing smooth animations on one element clobber each- * other β the vertical one re-fires as it settles and resets the horizontal).+ * Scroll target that brings a selected row into view.*- * Vertical: initial load centers the row; later selections scroll the minimum- * (above the fold β align top, below β align bottom, visible β unchanged).- * Horizontal: no-op while the bar start sits comfortably in view, else land it- * REVEAL_LEFT_FRACTION from the left edge.+ * Initial load centers the row; later selections scroll the minimum (above the+ * fold β align top, below β align bottom, visible β unchanged).*- * Pure β see timeline-calculations.clienttest.ts.+ * Vertical only: the timeline fits the whole trace into its measured lane, so a+ * selected bar is never off to the side and there is nothing to reveal+ * horizontally. Pure β see timelineCalculations.clienttest.ts.*/export function computeSelectionScrollTarget(args: {index: number;rowHeight: number;scrollTop: number;- scrollLeft: number;clientHeight: number;- clientWidth: number;- /** Bar start offset in content px; null = no horizontal component. */- barStart: number | null;isInitial: boolean;-}): { top: number; left: number } {- const {- index,- rowHeight,- scrollTop,- scrollLeft,- clientHeight,- clientWidth,- barStart,- isInitial,- } = args;+}): { top: number } {+ const { index, rowHeight, scrollTop, clientHeight, isInitial } = args;const rowTop = index * rowHeight;let top = scrollTop;@@ -221,16 +121,5 @@ export function computeSelectionScrollTarget(args: {top = rowTop - clientHeight + rowHeight; // below β align to bottom}- let left = scrollLeft;- if (barStart != null) {- const viewRight = scrollLeft + clientWidth;- if (- barStart < scrollLeft + REVEAL_MARGIN_PX ||- barStart > viewRight - REVEAL_MARGIN_PX- ) {- left = Math.max(0, barStart - clientWidth * REVEAL_LEFT_FRACTION);- }- }-- return { top: Math.max(0, top), left };+ return { top: Math.max(0, top) };}