πͺ’ 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): ready the compact timeline to be the only one (#16561)
Nikita Kabardina3994e93f938
diff --git a/.agents/skills/seed-test-data/SKILL.md b/.agents/skills/seed-test-data/SKILL.mdindex e6064e7eb8..7fb0d45f89 100644--- a/.agents/skills/seed-test-data/SKILL.md+++ b/.agents/skills/seed-test-data/SKILL.md@@ -34,6 +34,7 @@ this.| A realistic agent flow over a timeline (graph view + scrubbable timeline) | `pnpm run seed -- agent-timeline --turns 6 --v4` (LangGraph refine loop plannerβretrieverβgeneratorβcriticβloop, staggered in time; add `--timing-only` for the pure timing fallback) || A trace that is large as a GRAPH (many distinct node names + connections, the trace-graph layout stress) | `pnpm run seed -- agent-graph --v4` (~1,350 distinct connections from 350 observations; `--nodes 120 --steps 100 --parallel 8` crosses the layout ceiling, `--nodes 80 --steps 30 --parallel 4` is small-but-dense) || A dozen SMALL traces, each a different timeline shape (the everyday case, not a stress test) | `pnpm run seed -- timeline-shapes --v4` (12 hand-timed traces of 4-25 observations: rag answer, streamed chat with a TTFT split, 8-way fan-out, retry backoff with widening gaps, a 13-minute wait on a human, one slow tool dwarfing everything, an error cascade with failover, in-flight spans with no end time, zero-duration checkpoints, a ten-level ladder, 24 flat siblings, a three-turn agent loop with think time; `--shape <slug>` for one) |+| A row carrying every annotation at once, to judge whether the timeline is overloaded | `pnpm run seed -- timeline-annotated --v4` (ONE trace, 12 observations: one/two/four scores β the last collapsing into `+1` β one and twelve comments, a streaming first-token mark, costs and durations spread so the heat map paints some rows, plain rows beside them for contrast, and all three label placements on screen together) || A multi-HOUR agent run (wall clock dominated by waiting, as production ones are) | `pnpm run seed -- agent-timeline --turns 120 --turn-gap-ms 60000 --v4` (~2.5h; the gap is jittered up to 2x, so the work lands at a few percent of the trace instead of packing every span into a few seconds) || A demo-grade, real-looking agent trace (videos, screenshots, docs) | `pnpm run seed -- support-agent --v4 --id-prefix <hex>` (one fixed, fully handcrafted support-copilot refund run: guardrails, parallel context fan-out, 3-turn ReAct loop with real payloads/costs; deterministic β reseed with a FRESH prefix for a clean take; the prefix is the trace id, so a hex prefix reads like production) || A plain trace with no agentic types (collapsed-by-default graph panel) | add `--plain` to `trace-tree` (SPAN/GENERATION/EVENT only) |diff --git a/packages/shared/scripts/seeder/AGENTS.md b/packages/shared/scripts/seeder/AGENTS.mdindex a42884574a..921ec031b8 100644--- a/packages/shared/scripts/seeder/AGENTS.md+++ b/packages/shared/scripts/seeder/AGENTS.md@@ -18,6 +18,7 @@ pnpm run seed -- agent-graph --v4 # graph-DENSE trace: ~1,350 distinct node-paipnpm run seed -- agent-timeline --turns 120 --turn-gap-ms 60000 --v4 # ~2.5h wall clock: idle between turns, so the work is a few percent of the tracepnpm run seed -- timeline-shapes --v4 # a dozen SMALL traces, one per timeline morphology (retry backoff, human wait, fan-out, slow tool, in-flight, instants, ...)pnpm run seed -- timeline-shapes --shape retry-backoff --v4 # just one of them+pnpm run seed -- timeline-annotated --v4 # ONE trace with every row annotation at once (scores incl. +N overflow, 1 and 12 comments, costs, heat map, first-token mark) β for judging visual loadpnpm run seed -- support-agent --v4 --id-prefix <hex> # demo-grade handcrafted support-copilot run (videos/screenshots)pnpm run seed -- long-session --traces 300 --observations-per-trace 8pnpm run seed -- session-shapes --shape all # chat / coding-agent / mixed / media v4 sessionsdiff --git a/packages/shared/scripts/seeder/scenarios/index.ts b/packages/shared/scripts/seeder/scenarios/index.tsindex 28c67196a7..98e8562f92 100644--- a/packages/shared/scripts/seeder/scenarios/index.ts+++ b/packages/shared/scripts/seeder/scenarios/index.ts@@ -9,6 +9,7 @@ import { outlierTrafficScenario } from "./outlier-traffic";import { scoredTracesScenario } from "./scored-traces";import { sessionShapesScenario } from "./session-shapes";import { supportAgentScenario } from "./support-agent";+import { timelineAnnotatedScenario } from "./timeline-annotated";import { timelineShapesScenario } from "./timeline-shapes";import { traceTreeScenario } from "./trace-tree";import { ScenarioDefinition } from "./types";@@ -29,6 +30,7 @@ export const scenarios: Record<string, ScenarioDefinition> = {"annotation-queue": annotationQueueScenario,"custom-models": customModelsScenario,"support-agent": supportAgentScenario,+ "timeline-annotated": timelineAnnotatedScenario,"timeline-shapes": timelineShapesScenario,};diff --git a/packages/shared/scripts/seeder/scenarios/timeline-annotated.ts b/packages/shared/scripts/seeder/scenarios/timeline-annotated.tsnew file mode 100644index 0000000000..6aa220f6c0--- /dev/null+++ b/packages/shared/scripts/seeder/scenarios/timeline-annotated.ts@@ -0,0 +1,458 @@+import { prisma } from "../../../src/db";+import {+ createTrace,+ createObservation,+ createTraceScore,+ createTracesCh,+ createObservationsCh,+ createScoresCh,+ createEventsCh,+ ObservationRecordInsertType,+ ScoreRecordInsertType,+ TraceRecordInsertType,+} from "../../../src/server";+import { ObservationType } from "../../../src/domain";+import { observationToEvent, traceToEvent } from "./event-mirror";+import { generationUsageCost } from "./payload";+import { utcDayStartMs } from "./rng";+import {+ ScenarioContext,+ ScenarioDefinition,+ SeedError,+ SeedSummary,+} from "./types";+import { countRows, traceLink } from "./verify";++/**+ * ONE trace carrying every annotation a timeline row can show, on purpose, all+ * at once β a worst case for visual load rather than a realistic trace.+ *+ * `timeline-shapes` answers "does a timeline read at this shape". This answers a+ * different question: with scores, comments, costs, a heat map and a+ * first-token mark on the same rows, is the row still legible or is it a wall?+ * You cannot judge that from a trace where each row has one thing.+ *+ * So the rows are laid out to put each addition next to a plain one:+ * - a row with no annotations at all, for contrast+ * - one score, two scores, and four (which collapses into "+1")+ * - one comment, and twelve (a two-digit badge)+ * - one row carrying comment AND scores AND cost together+ * - a streaming answer with a time-to-first-token mark inside its bar+ * - the widest bar (label sits INSIDE), a mid-lane sliver (label AFTER), and a+ * span hard against the right edge (label BEFORE), so all three placements+ * are on screen at once+ * - costs and durations spread wide enough that the heat map paints some rows+ * and leaves others alone+ *+ * Hand-timed, no rng: the same trace every run.+ */++const MODEL_PRICES: Record<string, { input: number; output: number }> = {+ "gpt-5.4": { input: 1.25e-6, output: 1e-5 },+ "gpt-5.4-mini": { input: 2.5e-7, output: 2e-6 },+ "text-embedding-4": { input: 2e-8, output: 0 },+};++type Annotated = {+ key: string;+ parent: string | null;+ type: ObservationType;+ name: string;+ /** ms from the trace start */+ start: number;+ /** ms from the trace start; null = still running */+ end: number | null;+ model?: keyof typeof MODEL_PRICES;+ usage?: [number, number];+ /** time to first token, ms after start */+ ttft?: number;+ /** [name, value] per score, observation-level */+ scores?: Array<[string, number]>;+ /** how many comments hang off this observation */+ comments?: number;+ /** what this row is here to demonstrate */+ demonstrates: string;+};++const SPANS: Annotated[] = [+ {+ key: "root",+ parent: null,+ type: "SPAN",+ name: "handle-request",+ start: 0,+ end: 19_800,+ demonstrates:+ "the whole trace β 100% of the duration, so the heat map reddens it",+ },+ {+ key: "guard-in",+ parent: "root",+ type: "GUARDRAIL",+ name: "guardrail.input",+ start: 40,+ end: 180,+ demonstrates: "a plain row with nothing on it, for contrast",+ },+ {+ key: "classify",+ parent: "root",+ type: "GENERATION",+ name: "classify-intent",+ start: 200,+ end: 900,+ model: "gpt-5.4-mini",+ usage: [900, 40],+ scores: [["helpfulness", 0.92]],+ demonstrates: "one score",+ },+ {+ key: "retrieve",+ parent: "root",+ type: "RETRIEVER",+ name: "vector-search",+ start: 950,+ end: 2_100,+ scores: [+ ["relevance", 0.71],+ ["coverage", 0.44],+ ],+ demonstrates: "two scores",+ },+ {+ key: "embed",+ parent: "retrieve",+ type: "EMBEDDING",+ name: "embed-query",+ start: 960,+ end: 1_010,+ model: "text-embedding-4",+ usage: [18, 0],+ demonstrates: "a sliver mid-lane β its label goes AFTER the bar",+ },+ {+ key: "answer",+ parent: "root",+ type: "GENERATION",+ name: "compose-answer",+ start: 2_200,+ end: 12_000,+ model: "gpt-5.4",+ usage: [12_000, 1_800],+ ttft: 1_400,+ scores: [+ ["helpfulness", 0.88],+ ["faithfulness", 0.95],+ ["tone", 0.62],+ ["verbosity", 0.31],+ ],+ demonstrates:+ "the loaded generation: first-token mark, the biggest cost, and four scores collapsing to +1",+ },+ {+ key: "refund",+ parent: "root",+ type: "TOOL",+ name: "stripe.refund",+ start: 12_100,+ end: 13_000,+ comments: 12,+ demonstrates: "a two-digit comment count",+ },+ {+ key: "email",+ parent: "root",+ type: "TOOL",+ name: "email.send",+ start: 13_100,+ end: 13_400,+ model: "gpt-5.4-mini",+ usage: [300, 90],+ comments: 1,+ scores: [+ ["tone", 0.77],+ ["length", 0.5],+ ],+ demonstrates:+ "everything on one row: comment, cost and two scores together",+ },+ {+ key: "verify",+ parent: "root",+ type: "GENERATION",+ name: "verify-answer",+ start: 13_500,+ end: 15_000,+ model: "gpt-5.4-mini",+ usage: [700, 120],+ demonstrates: "a cost with no annotations β the baseline for comparison",+ },+ {+ key: "guard-out",+ parent: "root",+ type: "GUARDRAIL",+ name: "guardrail.output",+ start: 15_100,+ end: 15_300,+ demonstrates: "another plain row",+ },+ {+ key: "persist",+ parent: "root",+ type: "SPAN",+ name: "persist-conversation",+ start: 19_500,+ end: 19_800,+ scores: [["durability", 1]],+ comments: 2,+ demonstrates:+ "hard against the right edge β nothing fits after it, so the cluster goes BEFORE the bar",+ },+ {+ key: "audit",+ parent: "root",+ type: "EVENT",+ name: "audit.logged",+ start: 19_700,+ end: 19_700,+ demonstrates: "a zero-duration checkpoint",+ },+];++const COMMENT_TEXTS = [+ "Confirmed with the customer, refund approved.",+ "This is the second attempt β the first timed out.",+ "Numbers match the invoice.",+ "Flagging for the weekly review.",+ "Latency here is expected: the provider throttles us at this hour.",+];++const run = async (+ ctx: ScenarioContext,+ params: Record<string, string | number | boolean>,+): Promise<SeedSummary> => {+ const startedAt = Date.now();+ const withV4 = params["v4"] as boolean;+ const traceTimestamp = utcDayStartMs();+ const traceId = `${ctx.idPrefix}-annotated`;+ const idOf = new Map(+ SPANS.map((span, index) => [span.key, `${traceId}-obs-${index}`]),+ );+ const commentCount = SPANS.reduce((n, s) => n + (s.comments ?? 0), 0);+ const scoreCount = SPANS.reduce((n, s) => n + (s.scores?.length ?? 0), 0);++ if (ctx.dryRun) {+ return {+ scenario: "timeline-annotated",+ target: "clickhouse",+ params,+ projectId: ctx.projectId,+ environment: ctx.environment,+ traceIds: [traceId],+ sessionIds: [],+ counts: {+ traces: 1,+ observations: SPANS.length,+ scores: scoreCount,+ comments: commentCount,+ events: withV4 ? SPANS.length + 1 : 0,+ },+ verified: {},+ links: [traceLink(ctx, traceId, traceTimestamp)],+ dryRun: true,+ durationMs: Date.now() - startedAt,+ };+ }++ const trace: TraceRecordInsertType = createTrace({+ id: traceId,+ project_id: ctx.projectId,+ environment: ctx.environment,+ name: "annotated-request",+ timestamp: traceTimestamp,+ user_id: "[email protected]",+ session_id: null,+ release: "2026.08.26-1",+ version: "annotated-v1",+ tags: ["seed", "timeline-annotated", "design-review"],+ public: false,+ bookmarked: false,+ metadata: {+ scenario: "timeline-annotated",+ about:+ "Every row annotation at once β for judging visual load, not realism.",+ spans: String(SPANS.length),+ scores: String(scoreCount),+ comments: String(commentCount),+ },+ input: JSON.stringify({ question: "Why was I charged twice?" }),+ output: JSON.stringify({ answer: "You were not β one was a hold." }),+ created_at: Date.now(),+ updated_at: Date.now(),+ event_ts: Date.now(),+ });++ const observations: ObservationRecordInsertType[] = [];+ const scores: ScoreRecordInsertType[] = [];++ for (const span of SPANS) {+ const obsId = idOf.get(span.key)!;+ const prices = span.model ? MODEL_PRICES[span.model] : null;+ const [usageIn, usageOut] = span.usage ?? [0, 0];++ observations.push(+ createObservation({+ id: obsId,+ trace_id: traceId,+ project_id: ctx.projectId,+ environment: ctx.environment,+ type: span.type,+ parent_observation_id:+ span.parent === null ? null : (idOf.get(span.parent) ?? null),+ name: span.name,+ start_time: traceTimestamp + span.start,+ end_time: span.end === null ? null : traceTimestamp + span.end,+ completion_start_time:+ span.ttft === undefined+ ? null+ : traceTimestamp + span.start + span.ttft,+ level: "DEFAULT",+ status_message: null,+ version: null,+ input: null,+ output: null,+ metadata: {+ scenario: "timeline-annotated",+ demonstrates: span.demonstrates,+ },+ provided_model_name: span.model ?? null,+ internal_model_id: null,+ model_parameters: "{}",+ ...(prices+ ? generationUsageCost(usageIn, usageOut, prices)+ : {+ usage_details: {},+ provided_usage_details: {},+ cost_details: {},+ provided_cost_details: {},+ total_cost: 0,+ }),+ created_at: Date.now(),+ updated_at: Date.now(),+ event_ts: Date.now(),+ }),+ );++ for (const [name, value] of span.scores ?? []) {+ scores.push(+ createTraceScore({+ id: `${obsId}-score-${name}`,+ project_id: ctx.projectId,+ trace_id: traceId,+ observation_id: obsId,+ environment: ctx.environment,+ name,+ value,+ data_type: "NUMERIC",+ source: "EVAL",+ comment: null,+ metadata: {},+ timestamp: traceTimestamp + span.start,+ }),+ );+ }+ }++ await createTracesCh([trace]);+ await createObservationsCh(observations);+ await createScoresCh(scores);+ if (withV4) {+ await createEventsCh([+ traceToEvent(trace),+ ...observations.map((observation) =>+ observationToEvent(observation, trace),+ ),+ ]);+ }++ // Comments live in Postgres, not ClickHouse β the timeline reads a count per+ // observation, so what matters here is how MANY hang off a row.+ const comments = SPANS.flatMap((span) =>+ Array.from({ length: span.comments ?? 0 }, (_, index) => ({+ id: `${idOf.get(span.key)!}-comment-${index}`,+ projectId: ctx.projectId,+ objectType: "OBSERVATION" as const,+ objectId: idOf.get(span.key)!,+ content: COMMENT_TEXTS[index % COMMENT_TEXTS.length]!,+ authorUserId: null,+ })),+ );+ if (comments.length > 0) {+ await prisma.comment.createMany({ data: comments, skipDuplicates: true });+ }++ const byTrace = `project_id = {projectId: String} AND trace_id = {traceId: String}`;+ const args = { projectId: ctx.projectId, traceId };+ const verified: Record<string, number> = {+ traces: await countRows(+ "traces",+ `project_id = {projectId: String} AND id = {traceId: String}`,+ args,+ "uniqExact(id)",+ ),+ observations: await countRows(+ "observations",+ byTrace,+ args,+ "uniqExact(id)",+ ),+ scores: await countRows("scores", byTrace, args, "uniqExact(id)"),+ };+ if (withV4) {+ // events_full has no `id` column β count rows.+ verified.events = await countRows("events_full", byTrace, args);+ }+ if (verified.observations < observations.length) {+ throw new SeedError(+ `wrote ${observations.length} observations, read back ${verified.observations}`,+ "re-run; if it persists, check the ClickHouse the CLI is pointed at",+ );+ }++ return {+ scenario: "timeline-annotated",+ target: "clickhouse",+ params,+ projectId: ctx.projectId,+ environment: ctx.environment,+ traceIds: [traceId],+ sessionIds: [],+ counts: {+ traces: 1,+ observations: observations.length,+ scores: scores.length,+ comments: comments.length,+ events: withV4 ? observations.length + 1 : 0,+ },+ verified,+ links: [traceLink(ctx, traceId, traceTimestamp)],+ dryRun: false,+ durationMs: Date.now() - startedAt,+ };+};++export const timelineAnnotatedScenario: ScenarioDefinition = {+ name: "timeline-annotated",+ description:+ "ONE trace carrying every row annotation at once β scores (one, two, and four collapsing to +1), comments (one and twelve), costs, the duration and cost heat maps, and a streaming first-token mark β with plain rows beside them for contrast, and all three label placements on screen together. A worst case for visual load rather than a realistic trace: for judging whether an annotated row is still legible.",+ supportsV4: true,+ flags: [+ {+ flag: "v4",+ type: "boolean",+ default: false,+ description: "also mirror into v4 events_full/events_core",+ },+ ],+ run,+};diff --git a/web/src/features/traces/components/TraceTimeline/TimelineBar.stories.tsx b/web/src/features/traces/components/TraceTimeline/TimelineBar.stories.tsxindex 7bcbc47587..2b64455e9a 100644--- a/web/src/features/traces/components/TraceTimeline/TimelineBar.stories.tsx+++ b/web/src/features/traces/components/TraceTimeline/TimelineBar.stories.tsx@@ -1,12 +1,12 @@import { expect, userEvent, waitFor } from "storybook/test";import preview from "../../../../../.storybook/preview";+import { TimelineBar } from "./TimelineBar";import {MAX_SCORE_GROUPS,SCORE_GROUP_GAP_PX,- TimelineBar,overflowButtonWidth,scoreBadgesWidth,-} from "./TimelineBar";+} from "../../fns/timeline/metricCluster";import {createTextMeasurer,createTextMeasurerFrom,diff --git a/web/src/features/traces/components/TraceTimeline/TimelineBar.tsx b/web/src/features/traces/components/TraceTimeline/TimelineBar.tsxindex 16fb3a4e07..a1fb1e6363 100644--- a/web/src/features/traces/components/TraceTimeline/TimelineBar.tsx+++ b/web/src/features/traces/components/TraceTimeline/TimelineBar.tsx@@ -16,200 +16,23 @@import { type TimelineBarProps } from "./types";import { cn } from "@/src/utils/tailwind";import { CommentCountIcon } from "@/src/features/comments/CommentCountIcon";-import {- GroupedScoreBadges,- groupScoresByName,-} from "@/src/components/grouped-score-badge";-import {- SCORE_LEVEL_LABELS,- scoreLevelFromScore,-} from "@/src/components/score-tag";+import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";import { formatIntervalSeconds } from "@/src/utils/dates";import { usdFormatter } from "@/src/utils/numbers";import { getSubtreeDurationOverflowMs } from "@/src/features/traces/fns/getSubtreeDurationOverflowMs";import { heatMapTextColor } from "@/src/features/traces/fns/heatMapTextColor";import { isPresent } from "@langfuse/shared";+import {+ CLUSTER_ITEM_GAP_PX,+ MAX_SCORE_GROUPS,+ commentIconWidth,+ createClusterFitter,+ scoreBadgesWidth,+} from "../../fns/timeline/metricCluster";const SUBTREE_DURATION_TITLE ="Subtree wall-clock duration (first start β last end)";-/**- * 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({row,laneWidth,@@ -296,19 +119,7 @@ export function TimelineBar({// 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 fitsWidth = createClusterFitter(budgetPx, CLUSTER_ITEM_GAP_PX);const fitsCluster = (text: string) => fitsWidth(measurer.measure(text));// The layout measured this exact string, which is why the bar renders itdiff --git a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.stories.tsx b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.stories.tsxindex da6e6543c4..31432ad3d0 100644--- a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.stories.tsx+++ b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.stories.tsx@@ -4,6 +4,7 @@ import preview from "../../../../../.storybook/preview";import { TimelineDense, type TimelineDenseProps } from "./TimelineDense";import {deepNesting,+ streamingSpan,manySpans,reporterTrace,threeSpans,@@ -417,9 +418,11 @@ export const LabelsStayReadableOnBars = meta.story({// And its colour is the one that contrasts with THIS bar: the bar is the// label's own row, so ask that bar what colour it resolved to.- const bar = label.parentElement?.querySelector<HTMLElement>(- '[data-testid="timeline-dense-bar"]',- );+ // From the ROW, not the label's parent: the label lives in the metric+ // cluster now, and the bar is its sibling rather than its uncle.+ const bar = label+ .closest('[data-testid="timeline-dense-row"]')+ ?.querySelector<HTMLElement>('[data-testid="timeline-dense-bar"]');if (!bar) throw new Error("a label with no bar to sit on");const barLuminance = luminance(getComputedStyle(bar).backgroundColor);const textLuminance = luminance(getComputedStyle(label).color);@@ -460,9 +463,9 @@ export const LabelsKeepTheirDistance = meta.story({let sawBefore = false;for (const label of labels) {- const bar = label.parentElement?.querySelector<HTMLElement>(- '[data-testid="timeline-dense-bar"]',- );+ const bar = label+ .closest('[data-testid="timeline-dense-row"]')+ ?.querySelector<HTMLElement>('[data-testid="timeline-dense-bar"]');if (!bar) continue;const l = label.getBoundingClientRect();const b = bar.getBoundingClientRect();@@ -479,8 +482,8 @@ export const LabelsKeepTheirDistance = meta.story({},});-export const TooltipShowsCostAndTokens = meta.story({- name: "(Test) Tooltip Shows Cost And Tokens",+export const TooltipShowsTheCost = meta.story({+ name: "(Test) Tooltip Shows The Cost",args: {roots: manySpans(40),box: PHONE,@@ -492,7 +495,7 @@ export const TooltipShowsCostAndTokens = meta.story({selectedId: null,onSelect: fn(),onHover: fn(),- factsOf: () => ["$0.006425", "2,100 β 380 (β 2,480)"],+ metricsOf: () => ({ costText: "$0.006425" }),},play: async ({ canvasElement }) => {const surface = canvasElement.querySelector<HTMLElement>(@@ -521,7 +524,6 @@ export const TooltipShowsCostAndTokens = meta.story({// At this density hover IS how a row is read, so it says what a tree row// says: identity, then the metrics.await expect(box.innerText).toContain("$0.006425");- await expect(box.innerText).toContain("2,100 β 380");// And the NAME survives the extra facts. One flex row made the name the only// flexible item, so cost and tokens truncated it to nothing β the one thing// the hover was for.@@ -1627,7 +1629,7 @@ export const TheTooltipEscapesTheSurface = meta.story({selectedId: null,onSelect: fn(),onHover: fn(),- factsOf: () => ["$0.006425", "2,100 β 380 (β 2,480)"],+ metricsOf: () => ({ costText: "$0.006425" }),},play: async ({ canvasElement }) => {const surface = canvasElement.querySelector<HTMLElement>(@@ -2129,3 +2131,151 @@ export const APinchAbandonsAnUnfinishedBox = meta.story({await expect(flew).toBe(false);},});++/**+ * A streaming call spends part of its bar waiting for the first token. The wide+ * timeline says so with a second shade; here it is a divider, because a shade+ * needs a bar tall enough to read one and these are a single pixel at the floor.+ */+export const TheFirstTokenHasItsMark = meta.story({+ name: "(Test) The First Token Has Its Mark",+ args: {+ roots: streamingSpan(),+ box: DESKTOP,+ gutter: "expanded" as const,+ pointer: "fine" as const,+ barColor: "type" as const,+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ },+ play: async ({ canvasElement }) => {+ const bar = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-bar"]',+ );+ if (!bar) throw new Error("no bar");+ const mark = bar.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-first-token"]',+ );+ if (!mark) throw new Error("the streaming split is not drawn");++ // A quarter of the way along, whatever the scale happens to be.+ const barBox = bar.getBoundingClientRect();+ const markBox = mark.getBoundingClientRect();+ const fraction = (markBox.left - barBox.left) / barBox.width;+ await expect(fraction).toBeGreaterThan(0.2);+ await expect(fraction).toBeLessThan(0.3);+ // And inside its own bar, not over the lane.+ await expect(markBox.right).toBeLessThanOrEqual(barBox.right + 0.5);+ },+});++/**+ * The cluster stays inside its box, and it moves to the side that has room. It+ * used to inherit the side `layout()` chose by measuring the duration alone,+ * which is why annotations vanished mid-zoom: growing a bar turned the budget+ * from "the rest of the lane" into "this bar".+ */+export const TheClusterTakesTheRoomierSide = meta.story({+ name: "(Test) The Cluster Takes The Roomier Side",+ args: {+ roots: threeSpans(),+ box: DESKTOP,+ gutter: "expanded" as const,+ pointer: "fine" as const,+ barColor: "type" as const,+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ metricsOf: () => ({ costText: "$0.0021" }),+ },+ play: async ({ canvasElement }) => {+ const clusters = [+ ...canvasElement.querySelectorAll<HTMLElement>(+ '[data-testid="timeline-dense-metrics"]',+ ),+ ];+ await expect(clusters.length).toBeGreaterThan(0);++ for (const cluster of clusters) {+ const row = cluster.closest('[data-testid="timeline-dense-row"]');+ const bar = row?.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-bar"]',+ );+ if (!bar) continue;+ const barBox = bar.getBoundingClientRect();+ const lane = cluster.parentElement!.getBoundingClientRect();+ // Whichever side it picked, it must be the one with the most room.+ const after = lane.right - barBox.right;+ const before = barBox.left - lane.left;+ if (cluster.dataset.placement === "after") {+ await expect(after).toBeGreaterThanOrEqual(before - 0.5);+ }+ // And it never spills: the cluster clips, so what it admits has to fit.+ await expect(cluster.scrollWidth).toBeLessThanOrEqual(+ cluster.clientWidth + 0.5,+ );+ await expect(cluster.innerText).toContain("$0.0021");+ }+ },+});++/**+ * When the lane is too narrow for even one metric, the row draws none β and the+ * tooltip is what keeps it from going silent. It states the same duration and+ * cost for every row at every density, which is why the cluster does not need a+ * title on a box of zero width.+ */+export const ARowTooTightForMetricsStillSaysThem = meta.story({+ name: "(Test) A Row Too Tight For Metrics Still Says Them",+ args: {+ // 600 rows in this box are 1px each: no room for a metric anywhere.+ roots: manySpans(600),+ box: PHONE,+ gutter: "auto" as const,+ pointer: "fine" as const,+ barColor: "type" as const,+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ metricsOf: () => ({ costText: "$0.0021" }),+ },+ play: async ({ canvasElement }) => {+ // Nothing is drawn beside a 1px bar.+ await expect(+ canvasElement.querySelectorAll('[data-testid="timeline-dense-metrics"]')+ .length,+ ).toBe(0);++ const surface = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-surface"]',+ );+ if (!surface) throw new Error("dense surface not found");+ const rect = surface.getBoundingClientRect();+ surface.dispatchEvent(+ new PointerEvent("pointermove", {+ bubbles: true,+ pointerType: "mouse",+ clientX: rect.left + rect.width * 0.6,+ clientY: rect.top + 200,+ }),+ );++ const tooltip = await waitFor(() => {+ const el = document.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-tooltip"]',+ );+ if (!el) throw new Error("no tooltip");+ return el;+ });+ // The duration and the cost, on a row that had no room to print either.+ await expect(tooltip.innerText).toMatch(/\d/);+ await expect(tooltip.innerText).toContain("$0.0021");+ },+});diff --git a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsxindex 65fb77daf8..fda703d5c8 100644--- a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx+++ b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx@@ -64,6 +64,7 @@ import {type TooltipPlacement,} from "../../fns/timeline/tooltipPlacement";import { Layer } from "@/src/components/ui/layer";+import { TimelineRowMetrics, type RowMetrics } from "./TimelineRowMetrics";import { cn } from "@/src/utils/tailwind";import { type Density, type PointerModality } from "../../fns/timeline/density";import {@@ -269,7 +270,14 @@ export type TimelineDenseProps = {* live with the app. At this density hover is how a row is read at all, so it* should say what a tree row says.*/- factsOf?: (nodeId: string) => string[];+ /**+ * What a row has to say about itself β cost, scores, comments, and the+ * heat-map classes for its metrics. Supplied rather than derived, so this+ * renderer keeps deciding only what FITS.+ */+ metricsOf?: (nodeId: string) => RowMetrics;+ /** The view-options duration toggle; the tree honours the same one. */+ showDuration?: boolean;/*** The trace playhead, handed in rather than read from context: this renderer* takes data and nothing implicit, which is what lets Storybook mount it at@@ -325,7 +333,8 @@ export function TimelineDense({onHover,activeIds,playhead,- factsOf,+ metricsOf,+ showDuration = true,}: TimelineDenseProps) {const [viewport, setViewport] = useState<Viewport | null>(null);const [pointerPos, setPointerPos] = useState<{@@ -1338,13 +1347,16 @@ export function TimelineDense({onPointerMove={onAxisPointerMove}data-testid="timeline-dense-axis">- {/* Font probe for the measurer: a label's own size, invisible and out of- flow so it costs no layout. */}+ {/* Font probe for the measurer, at the size a label ACTUALLY renders in β+ `density.labelFontPx`, the same value the metrics set themselves in.+ Probing one size and rendering another under-prices every string by+ the difference, which is the direction that clips. Invisible and out+ of flow, so it costs no layout. */}<spanref={labelProbeRef}aria-hiddenclassName="invisible absolute"- style={{ fontSize: "10px" }}+ style={{ fontSize: `${density.labelFontPx}px` }}>0</span>@@ -1527,56 +1539,41 @@ export function TimelineDense({height: `${barHeight}px`,}}data-testid="timeline-dense-bar"- />+ >+ {/* Where the first token arrived: a divider rather than the+ wide timeline's second shade, because a shade needs a+ bar tall enough to read one and these are 1px at the+ floor. It also keeps the label's contrast decision on a+ single colour. */}+ {node.firstTokenX == null ? null : (+ <div+ className="bg-background/70 absolute inset-y-0 w-px"+ style={{+ left: `${Math.min(Math.max(node.firstTokenX - node.x, 0), node.width)}px`,+ }}+ data-testid="timeline-dense-first-token"+ />+ )}+ </div>)}{/* Text comes back on its own as the rows grow β and it goeson whichever side layout() measured room for, rather thanalways after the bar, which clipped a full-width bar'slabel at the lane edge. */}- {presentation === "labelled" &&- node.label &&- !node.offscreen &&- node.labelPlacement !== "hidden" ? (- <span- className={cn(- "absolute overflow-hidden whitespace-nowrap",- // A label drawn ON the bar contrasts with the BAR, not- // with the page, so it takes white or black from that- // bar's own luminance β see fns/timeline/barContrast.ts.- // A chip of page-coloured ground read as a hole punched- // in the bar; this reads as a label on it.- node.labelPlacement !== "inside"- ? "text-muted-foreground"- : barTones[barClass] === "dark"- ? "text-black/85"- : "text-white/95",- )}- data-testid="timeline-dense-duration"- data-placement={node.labelPlacement}- style={{- // A `before` label is anchored by its RIGHT edge, so its- // gap from the bar is exact no matter what the measurer- // thought the text was worth. Positioning it from the- // left needs `left = x - gap - measuredWidth`, and any- // under-measure is subtracted straight out of the gap:- // measured 6px narrow and the label sat flush against- // the bar. `after` never had the bug β it grows away- // from its anchor rather than toward it.- ...(node.labelPlacement === "before"- ? {- right: `${Math.max(laneWidth - node.labelX - node.labelWidth, 0)}px`,- maxWidth: `${Math.max(node.labelX + node.labelWidth, 0)}px`,- }- : {- left: `${node.labelX}px`,- maxWidth: `${Math.max(laneWidth - node.labelX, 0)}px`,- }),- top: `${Math.max((rowHeight - 12) / 2, 0)}px`,- fontSize: "10px",- }}- >- {node.label}- </span>+ {presentation === "labelled" && !node.offscreen ? (+ <TimelineRowMetrics+ row={node}+ laneWidth={laneWidth}+ measurer={measurer}+ density={density}+ metrics={metricsOf?.(node.id) ?? {}}+ showDuration={showDuration}+ toneClass={+ barTones[barClass] === "dark"+ ? "text-black/85"+ : "text-white/95"+ }+ />) : null}</div></div>@@ -1712,9 +1709,9 @@ export function TimelineDense({? "β": formatDurationMs(focused.durationMs)}</span>- {factsOf?.(focused.id).map((fact) => (- <span key={fact}>{fact}</span>- ))}+ {metricsOf?.(focused.id)?.costText ? (+ <span>{metricsOf(focused.id).costText}</span>+ ) : null}</span></div></Layer>diff --git a/web/src/features/traces/components/TraceTimelineDense/TimelineRowMetrics.stories.tsx b/web/src/features/traces/components/TraceTimelineDense/TimelineRowMetrics.stories.tsxnew file mode 100644index 0000000000..9d67a1bc0a--- /dev/null+++ b/web/src/features/traces/components/TraceTimelineDense/TimelineRowMetrics.stories.tsx@@ -0,0 +1,111 @@+import { expect } from "storybook/test";+import preview from "../../../../../.storybook/preview";+import { TimelineRowMetrics } from "./TimelineRowMetrics";+import { createTextMeasurer } from "../../fns/timeline/textMeasurer";+import { resolveDensity } from "../../fns/timeline/density";+import { type PositionedNode } from "../../fns/timeline/layout";++const LANE = 640;++/** A positioned row, as `layout()` hands one over. */+function row(overrides: Partial<PositionedNode> = {}): PositionedNode {+ const node = {+ id: "n0",+ name: "llm.chat",+ type: "GENERATION",+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ endTime: new Date("2024-01-01T00:00:02.000Z"),+ children: [],+ };+ return {+ node,+ id: node.id,+ name: node.name,+ type: node.type,+ index: 0,+ depth: 0,+ treeLines: [],+ isLastSibling: true,+ hasChildren: false,+ 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,+ } as PositionedNode;+}++const meta = preview.meta({+ component: TimelineRowMetrics,+ args: {+ row: row(),+ laneWidth: LANE,+ // A generic family, and the SAME one the decorator renders in: a canvas+ // resolves `ui-sans-serif` to a face ~19% narrower than the DOM does, so a+ // measurer seeded with the app's stack prices text nobody renders. The app+ // avoids this by seeding from a probe; a story has to state both sides.+ measurer: createTextMeasurer("12px sans-serif"),+ density: resolveDensity({ pointer: "fine" }),+ metrics: {},+ showDuration: true,+ toneClass: "text-white/95",+ },+ decorators: [+ (Story) => (+ <div+ className="bg-background relative h-[26px] w-[640px] rounded border"+ style={{ fontFamily: "sans-serif" }}+ >+ <Story />+ </div>+ ),+ ],+});++export const DurationOnly = meta.story({});++/**+ * A bar can be wide enough to hold the duration and still be the WORST place to+ * put the cluster. `layout()` picks a side by measuring the duration alone, so+ * inheriting its choice confined the cluster to a 142px bar while 424px of lane+ * sat free beside it β which is what made annotations vanish as you zoomed in:+ * growing a bar shrank the budget.+ */+export const TheRoomierSideWins = meta.story({+ name: "(Test) The Roomier Side Wins",+ args: {+ // 150px bar in a 640px lane: `layout()` says the duration fits inside it.+ row: row({ x: 60, width: 150, labelPlacement: "inside", labelX: 66 }),+ metrics: { costText: "$0.0021" },+ },+ play: async ({ canvasElement }) => {+ const cluster = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-metrics"]',+ );+ if (!cluster) throw new Error("no cluster");++ // It went where the room is, not where the duration happened to fit.+ await expect(cluster.dataset.placement).toBe("after");+ await expect(Number.parseFloat(cluster.style.maxWidth)).toBeGreaterThan(+ 150,+ );+ // Both items survive, which they would not have in a 142px box.+ await expect(cluster.innerText).toContain("2.00s");+ await expect(cluster.innerText).toContain("$0.0021");+ await expect(cluster.scrollWidth).toBeLessThanOrEqual(+ cluster.clientWidth + 0.5,+ );+ },+});diff --git a/web/src/features/traces/components/TraceTimelineDense/TimelineRowMetrics.tsx b/web/src/features/traces/components/TraceTimelineDense/TimelineRowMetrics.tsxnew file mode 100644index 0000000000..74e685b564--- /dev/null+++ b/web/src/features/traces/components/TraceTimelineDense/TimelineRowMetrics.tsx@@ -0,0 +1,153 @@+/**+ * The metrics beside a bar: how long it took, what it cost, whether anyone+ * commented on it, and how it scored.+ *+ * Placement comes from `layout()`, which already measured which side of the bar+ * the duration fits on. Everything after the duration is this component's own+ * content, so it prices each item with the same measurer and admits them in+ * priority order β a duration always beats a cost you cannot finish reading.+ * Whatever does not fit is listed in the row's title instead, because a row that+ * silently omits a score reads as a row without one.+ *+ * The box clips. That is deliberate: a reservation that comes out under what the+ * DOM renders would push content over the lane edge, and a lane that overflows+ * is the one thing this timeline promises never to do.+ */++import {+ CLUSTER_ITEM_GAP_PX,+ createClusterFitter,+} from "../../fns/timeline/metricCluster";+import { type Density } from "../../fns/timeline/density";+import { type TextMeasurer } from "../../fns/timeline/textMeasurer";+import { type PositionedNode } from "../../fns/timeline/layout";++/**+ * What a row has to say about itself, formatted by whoever owns the trace data.+ * The renderer stays presentational: it decides what FITS, never what a cost+ * looks like.+ *+ * Deliberately just the cost. Scores, comment counts and heat-map colouring were+ * all tried here and all removed for the same reason: a row beside a bar cannot+ * hold them CONSISTENTLY. Whether they fit depends on where the bar happens to+ * sit and how far you have zoomed, so identical rows showed different things β+ * and the heat map put a second meaning on colour that already means observation+ * type, painting dark red text on a blue bar whose label had already been given+ * white for contrast. They belong somewhere that does not move: the tree, the+ * detail panel, or a fixed column of their own.+ */+export type RowMetrics = {+ /** Already formatted, e.g. `β $0.02`. */+ costText?: string | null;+};++export function TimelineRowMetrics({+ row,+ laneWidth,+ measurer,+ density,+ metrics,+ showDuration: durationEnabled,+ toneClass,+}: {+ row: PositionedNode;+ laneWidth: number;+ measurer: TextMeasurer;+ density: Density;+ metrics: RowMetrics;+ showDuration: boolean;+ /** Text colour for a label drawn ON the bar, from that bar's own luminance. */+ toneClass: string;+}) {+ const gapPx = density.labelGapPx;+ const insetPx = density.labelPaddingPx;++ // `layout()` chooses a side by measuring the DURATION alone. The cluster is+ // wider than that, so it chooses its own β by room, not by inheritance.+ //+ // Inheriting was the bug behind "they disappear when I zoom in": zooming grows+ // the bar until the duration fits inside it, at which point the budget stops+ // being "the rest of the lane" and becomes "this bar", so a cluster that fit a+ // moment ago no longer does. More space for the bar meant less for the label.+ // Inside is now the LAST resort, taken only when neither flank has room.+ const spaceBefore = Math.max(row.x - gapPx, 0);+ const spaceAfter = Math.max(laneWidth - (row.x + row.width + gapPx), 0);+ const spaceInside = Math.max(row.width - insetPx * 2, 0);+ const placement =+ spaceAfter >= spaceBefore && spaceAfter >= spaceInside+ ? "after"+ : spaceBefore >= spaceInside+ ? "before"+ : "inside";++ const style =+ placement === "before"+ ? {+ right: `${Math.max(laneWidth - row.x + gapPx, 0)}px`,+ maxWidth: `${spaceBefore}px`,+ }+ : placement === "inside"+ ? {+ left: `${row.x + insetPx}px`,+ maxWidth: `${Math.max(row.width - insetPx * 2, 0)}px`,+ }+ : {+ left: `${row.x + row.width + gapPx}px`,+ maxWidth: `${spaceAfter}px`,+ };++ const fits = createClusterFitter(+ Number.parseFloat(style.maxWidth),+ CLUSTER_ITEM_GAP_PX,+ );+ const fitsText = (text: string) => fits(measurer.measure(text));++ const durationText =+ durationEnabled && row.label && row.labelPlacement !== "hidden"+ ? row.label+ : null;+ const showDuration = durationText != null && fitsText(durationText);+ const showCost = Boolean(metrics.costText) && fitsText(metrics.costText!);+ // Nothing fitted: draw nothing. The row is not silent β hovering it names it+ // and states the same duration and cost, for every row at every density,+ // which is a better fallback than a title on a box of zero width.+ if (!showDuration && !showCost) return null;++ // What did not fit stays reachable on hover: a row that silently omits its+ // cost reads as a row without one.+ const dropped = [+ durationText != null && !showDuration ? durationText : null,+ metrics.costText && !showCost ? metrics.costText : null,+ ].filter(Boolean);++ return (+ <div+ className="absolute top-1/2 flex -translate-y-1/2 items-center gap-2 overflow-hidden whitespace-nowrap"+ style={{ ...style, fontSize: `${density.labelFontPx}px` }}+ title={dropped.length > 0 ? dropped.join(" ") : undefined}+ data-testid="timeline-dense-metrics"+ data-placement={placement}+ >+ {showDuration ? (+ <span+ className={+ placement === "inside" ? toneClass : "text-muted-foreground"+ }+ data-testid="timeline-dense-duration"+ data-placement={placement}+ >+ {durationText}+ </span>+ ) : null}+ {showCost ? (+ <span+ className={+ placement === "inside" ? toneClass : "text-muted-foreground"+ }+ >+ {metrics.costText}+ </span>+ ) : null}+ </div>+ );+}diff --git a/web/src/features/traces/components/TraceTimelineDense/TraceTimelineCompact.tsx b/web/src/features/traces/components/TraceTimelineDense/TraceTimelineCompact.tsxindex 4cbd3561cd..020fd67939 100644--- a/web/src/features/traces/components/TraceTimelineDense/TraceTimelineCompact.tsx+++ b/web/src/features/traces/components/TraceTimelineDense/TraceTimelineCompact.tsx@@ -11,6 +11,8 @@*/import { useCallback, useMemo, useState } from "react";+import { useViewPreferences } from "@/src/features/traces/contexts/ViewPreferencesContext";+import { type RowMetrics } from "./TimelineRowMetrics";import { usdFormatter } from "@/src/utils/numbers";import { useTraceData } from "@/src/features/traces/contexts/TraceDataContext";import { useSelection } from "@/src/features/traces/contexts/SelectionContext";@@ -27,6 +29,10 @@ import { TimelineDense } from "./TimelineDense";export function TraceTimelineCompact() {const { roots, nodeMap } = useTraceData();const { selectedNodeId, collapsedNodes } = useSelection();+ // The same five switches the tree honours. They live in one place because a+ // toggle that works in one view and silently does nothing in the other is+ // worse than no toggle.+ const { showDuration, showCostTokens } = useViewPreferences();const { handleHover } = useHandlePrefetchObservation();const selectNode = useSelectTraceNode("timeline_compact");@@ -82,22 +88,22 @@ export function TraceTimelineCompact() {);/**- * Cost, and only cost. Tokens used to come too, which put six numbers in a- * hover β and only on the spans that HAVE usage, so the tooltip changed shape- * from row to row. Cost is the one figure that means the same thing on every- * kind of span; the token split is a click away in the detail panel. Same- * formatter and the same `β` for a subtotal as the tree row uses.+ * What a row says about itself: its cost, formatted the way a tree row states+ * it. Scores, comment counts and heat-map colouring were tried here and taken+ * back out β a row beside a bar cannot carry them consistently, and colour+ * already means observation type. `showScores` and `showComments` mean what+ * their storage keys have always said: the observation tree.*/- const factsOf = useCallback(- (nodeId: string) => {+ const metricsOf = useCallback(+ (nodeId: string): RowMetrics => {const node = nodeMap.get(nodeId);- if (!node?.totalCost) return [];+ if (!node?.totalCost || !showCostTokens) return {};const aggregated = node.children.length > 0 || node.type === "TRACE";- return [- `${aggregated ? "β " : ""}${usdFormatter(node.totalCost.toNumber())}`,- ];+ return {+ costText: `${aggregated ? "β " : ""}${usdFormatter(node.totalCost.toNumber())}`,+ };},- [nodeMap],+ [nodeMap, showCostTokens],);return (@@ -117,7 +123,8 @@ export function TraceTimelineCompact() {onHover={handleHoverNode}activeIds={activeIds}playhead={playhead}- factsOf={factsOf}+ metricsOf={metricsOf}+ showDuration={showDuration}/>) : null}</div>diff --git a/web/src/features/traces/fns/timeline/__tests__/timelineV2.fixtures.ts b/web/src/features/traces/fns/timeline/__tests__/timelineV2.fixtures.tsindex 343cdeb2fc..09da4ea405 100644--- a/web/src/features/traces/fns/timeline/__tests__/timelineV2.fixtures.ts+++ b/web/src/features/traces/fns/timeline/__tests__/timelineV2.fixtures.ts@@ -17,6 +17,8 @@ type SpanSpec = {durationMs: number | null;children?: SpanSpec[];latency?: number;+ /** ms after the trace origin; the moment a streaming model produced its first token */+ firstTokenMs?: number;};function toNode(spec: SpanSpec, path: string): LayoutNode {@@ -31,6 +33,10 @@ function toNode(spec: SpanSpec, path: string): LayoutNode {? null: new Date(BASE_START + spec.startMs + spec.durationMs),latency: spec.latency,+ completionStartTime:+ spec.firstTokenMs == null+ ? null+ : new Date(BASE_START + spec.firstTokenMs),children: (spec.children ?? []).map((child, index) =>toNode(child, `${path}.${index}`),),@@ -310,3 +316,23 @@ export const TIMELINE_SHAPES = {} satisfies Record<string, () => LayoutNode[]>;export type TimelineShapeKey = keyof typeof TIMELINE_SHAPES;++/**+ * One streaming model call: a quarter of its time waiting for the first token,+ * the rest producing. The wide timeline splits such a bar into two shades; this+ * is the shape that has to keep saying where the split is.+ */+export const streamingSpan = (): LayoutNode[] =>+ build([+ {+ name: "chat.completion",+ type: "GENERATION",+ startMs: 0,+ durationMs: 1000,+ firstTokenMs: 250,+ children: [+ { name: "tokenize", startMs: 10, durationMs: 40 },+ { name: "post-process", startMs: 900, durationMs: 80 },+ ],+ },+ ]);diff --git a/web/src/features/traces/fns/timeline/layout.clienttest.ts b/web/src/features/traces/fns/timeline/layout.clienttest.tsindex 23e6445932..6896d49e19 100644--- a/web/src/features/traces/fns/timeline/layout.clienttest.ts+++ b/web/src/features/traces/fns/timeline/layout.clienttest.ts@@ -286,6 +286,46 @@ describe("textMeasurer", () => {expect(measure("β 1.24s")).toBeCloseTo(70, 6);});+ it("corrects for a canvas that refused the font it was given", () => {+ // A real canvas keeps `10px sans-serif` when it rejects a font string, and+ // then measures 10px glyphs for a 12px label β 20% short, silently.+ const stubborn: { font: string; measureText: (t: string) => TextMetrics } =+ {+ font: "10px sans-serif",+ measureText: (text: string) =>+ ({ width: text.length * 10 }) as TextMetrics,+ };+ Object.defineProperty(stubborn, "font", {+ get: () => "10px sans-serif",+ set: () => undefined,+ });+ const measure = createTextMeasurerFrom(+ stubborn as unknown as CanvasRenderingContext2D,+ "20px test",+ ).measure;+ // Asked for 20px, measured at 10px: every width doubles back to the truth.+ expect(measure("abc")).toBeCloseTo(60, 6);+ });++ it("reads the SIZE out of a weighted font, not the weight", () => {+ // The bold twin asks for `700 20px β¦`. Reading the leading number takes 700,+ // which against a context reporting 10px scales every width by seventy.+ const stubborn = {+ measureText: (text: string) =>+ ({ width: text.length * 10 }) as TextMetrics,+ };+ Object.defineProperty(stubborn, "font", {+ get: () => "10px sans-serif",+ set: () => undefined,+ });+ const measurer = createTextMeasurerFrom(+ stubborn as unknown as CanvasRenderingContext2D,+ "20px test",+ );+ // Bold asks for the same 20px, so it corrects by two β never by seventy.+ expect(measurer.measureBold("abc")).toBeCloseTo(60, 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: bothdiff --git a/web/src/features/traces/fns/timeline/metricCluster.ts b/web/src/features/traces/fns/timeline/metricCluster.tsnew file mode 100644index 0000000000..d966bba0ca--- /dev/null+++ b/web/src/features/traces/fns/timeline/metricCluster.ts@@ -0,0 +1,219 @@+/**+ * What a row's metric cluster COSTS, in px, measured rather than guessed.+ *+ * A cluster is the duration, the subtree total, the cost, a comment icon and the+ * score badges, laid beside a bar in whatever room the lane has left. The box it+ * lives in clips, so a reservation that comes out under what the DOM renders+ * cuts the last item mid-glyph β which is why every number here is measured from+ * the thing it is paying for, and why the widest candidates are priced rather+ * than the likeliest: over-reserving drops a badge and says so in the row's+ * title, under-reserving clips one and says nothing.+ *+ * Pure and shared, because two renderers place this cluster and a second copy of+ * the arithmetic is a second chance to get it wrong.+ */++import { groupScoresByName } from "@/src/components/grouped-score-badge";+import {+ SCORE_LEVEL_LABELS,+ scoreLevelFromScore,+} from "@/src/components/score-tag";+import { type TextMeasurer } from "./textMeasurer";+import type { ScoreDomain } from "@langfuse/shared";+import type { WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";++/** The score shape the badges render, and therefore the one this prices. */+type ClusterScore = WithStringifiedMetadata<ScoreDomain>;++/**+ * 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.+ */+export 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.+ */+export function commentIconWidth(+ count: number,+ measurer: TextMeasurer,+): 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: TextMeasurer,+): 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: ClusterScore[],+ measurer: TextMeasurer,+ 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 a cluster shows before the rest collapse into "+N". */+export const MAX_SCORE_GROUPS = 3;++/**+ * Admit items into the room the lane has left, in priority order, charging each+ * the gap the cluster actually renders with. 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.+ */+export function createClusterFitter(budgetPx: number, gapPx: number) {+ let spentPx = 0;+ return (widthPx: number): boolean => {+ const next = spentPx + widthPx + (spentPx > 0 ? gapPx : 0);+ if (next > budgetPx) return false;+ spentPx = next;+ return true;+ };+}diff --git a/web/src/features/traces/fns/timeline/textMeasurer.ts b/web/src/features/traces/fns/timeline/textMeasurer.tsindex 108bbc2a2e..ec582b0ba4 100644--- a/web/src/features/traces/fns/timeline/textMeasurer.ts+++ b/web/src/features/traces/fns/timeline/textMeasurer.ts@@ -70,6 +70,17 @@ export function createTextMeasurerFrom(};}+/**+ * The px size out of a CSS font shorthand β the SIZE, not the first number in+ * the string. A bold twin's font is `700 11px β¦`, so reading the leading number+ * takes the weight: paired with a canvas that refused the font and reports+ * `10px sans-serif`, that scales every width by seventy rather than by one.+ */+function pxSizeOf(font: string): number {+ const match = /(\d*\.?\d+)px/.exec(font);+ return match ? Number.parseFloat(match[1]!) : NaN;+}+function measurerFor(context: CanvasRenderingContext2D | null,font: string,@@ -78,18 +89,36 @@ function measurerFor(const units = new Map<string, number>();const cache = new Map<string, number>();+ // A canvas can REFUSE a font string and say nothing: `context.font` keeps its+ // previous value β `10px sans-serif` on a fresh context β and every width+ // afterwards is short by the size ratio. That is invisible, and it is the+ // direction that clips: a caller pricing a 12px label against 10px metrics+ // admits content that does not fit. So the size is read back and any+ // difference is corrected rather than trusted.+ const scale = (() => {+ if (!context) return 1;+ context.font = font;+ const asked = pxSizeOf(font);+ const got = pxSizeOf(context.font);+ return Number.isFinite(asked) && Number.isFinite(got) && got > 0+ ? asked / got+ : 1;+ })();+if (context) {context.font = font;// One width for every digit keeps tabular labels stable as they tick.let digit = 0;for (let i = 0; i < 10; i++) {- digit = Math.max(digit, context.measureText(String(i)).width);+ digit = Math.max(digit, context.measureText(String(i)).width * scale);}for (let i = 0; i < 10; i++) glyphs.set(String(i), digit);for (const char of [".", ",", " "]) {- glyphs.set(char, context.measureText(char).width);+ glyphs.set(char, context.measureText(char).width * scale);+ }+ for (const unit of UNITS) {+ units.set(unit, context.measureText(unit).width * scale);}- for (const unit of UNITS) units.set(unit, context.measureText(unit).width);} else {for (const unit of UNITS) units.set(unit, unit.length * PX_PER_LETTER);}@@ -108,7 +137,7 @@ function measurerFor(// 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;+ width += context.measureText(run).width * scale;} else {width += run.length * PX_PER_LETTER;}