🪢 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): compact timeline behind a feature preview (#16137)
Nikita Kabardin0833ad39e1b1
diff --git a/.agents/skills/seed-test-data/SKILL.md b/.agents/skills/seed-test-data/SKILL.mdindex c0c68f70a0..e6064e7eb8 100644--- a/.agents/skills/seed-test-data/SKILL.md+++ b/.agents/skills/seed-test-data/SKILL.md@@ -33,6 +33,8 @@ this.| Async parents whose subtree outlives their own span (subtree wall-clock duration badge) | add `--async-parents` to `trace-tree` (root + hub end immediately while children keep running) || 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 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) || A trace with MORE observations than the detail view loads (v4 caps the tree at 10k, `startTime ASC` — the chronological tail is missing) | `pnpm run seed -- trace-tree --observations 12000 --stride-ms 10 --v4` (`--stride-ms` starts each observation index × N ms in, so start times are unique and strictly increasing: observation index < 10000 loads, `-obs-10000` and up fall past the cap. Without it thousands of rows share one millisecond and the boundary is arbitrary. Re-runs that CHANGE timing flags need a fresh `--id-prefix`: `start_time` is an events ORDER BY key, so both versions persist in the same trace) |diff --git a/packages/shared/scripts/seeder/AGENTS.md b/packages/shared/scripts/seeder/AGENTS.mdindex 9796c362cb..a42884574a 100644--- a/packages/shared/scripts/seeder/AGENTS.md+++ b/packages/shared/scripts/seeder/AGENTS.md@@ -15,6 +15,9 @@ pnpm run seed -- trace-tree --observations 12000 --stride-ms 10 --v4 # more obspnpm run seed -- deep-chain --v4 # 1401 sequential generations in ONE parent chain (depth = count; LFE-10959 layout stress)pnpm run seed -- agent-timeline --turns 6 --v4 # realistic agent flow-with-loop over a timeline (graph view)pnpm run seed -- agent-graph --v4 # graph-DENSE trace: ~1,350 distinct node-pair connections from 350 observations (trace-graph layout stress)+pnpm 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 trace+pnpm 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 thempnpm 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/agent-timeline.ts b/packages/shared/scripts/seeder/scenarios/agent-timeline.tsindex cec0673a27..6677586631 100644--- a/packages/shared/scripts/seeder/scenarios/agent-timeline.ts+++ b/packages/shared/scripts/seeder/scenarios/agent-timeline.ts@@ -70,6 +70,7 @@ const run = async (): Promise<SeedSummary> => {const startedAt = Date.now();const turns = params["turns"] as number;+ const turnGapMs = params["turn-gap-ms"] as number;const withV4 = params["v4"] as boolean;// Default: attach langgraph metadata (the explicit-flow graph). --timing-only// omits it to exercise the pure timing-based graph fallback. (A boolean that@@ -83,6 +84,12 @@ const run = async ("pass a positive integer, e.g. --turns 6",);}+ if (turnGapMs < 0 || turnGapMs > 3_600_000) {+ throw new SeedError(+ `--turn-gap-ms must be between 0 and 3600000, got ${turnGapMs}`,+ "one hour of idle between turns is already an extreme trace",+ );+ }const rng = new Rng(ctx.seed);const traceId = `${ctx.idPrefix}-trace`;@@ -153,6 +160,15 @@ const run = async (cursor = nodeEnd + 20 + jitter(ctx.seed, step * 7 + 2, 60); // gap to next step}++ // A long-running agent spends most of its wall clock WAITING — on a queue, a+ // rate limit, a retry backoff, a human. Without that, a thousand-span trace+ // is a thousand spans inside four seconds, which is not what any real trace+ // looks like and makes every bar full-width. Jittered, because a fixed gap+ // reads as a metronome rather than as work arriving.+ if (turnGapMs > 0) {+ cursor += turnGapMs + jitter(ctx.seed, turn * 13 + 3, turnGapMs);+ }}if (ctx.dryRun) {@@ -395,6 +411,13 @@ export const agentTimelineScenario: ScenarioDefinition = {description:"refine-loop iterations (each is planner→retriever→generator→critic)",},+ {+ flag: "turn-gap-ms",+ type: "number",+ default: 0,+ description:+ "idle ms between turns (jittered up to 2x), so the run spreads over a real wall clock instead of packing every span into a few seconds — 120 turns at 60000 is a ~2.5h trace whose work is a few percent of it",+ },{flag: "timing-only",type: "boolean",diff --git a/packages/shared/scripts/seeder/scenarios/index.ts b/packages/shared/scripts/seeder/scenarios/index.tsindex 8e2a78b727..28c67196a7 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 { timelineShapesScenario } from "./timeline-shapes";import { traceTreeScenario } from "./trace-tree";import { ScenarioDefinition } from "./types";@@ -28,6 +29,7 @@ export const scenarios: Record<string, ScenarioDefinition> = {"annotation-queue": annotationQueueScenario,"custom-models": customModelsScenario,"support-agent": supportAgentScenario,+ "timeline-shapes": timelineShapesScenario,};export * from "./types";diff --git a/packages/shared/scripts/seeder/scenarios/payload.ts b/packages/shared/scripts/seeder/scenarios/payload.tsindex 68c456537a..f216a06864 100644--- a/packages/shared/scripts/seeder/scenarios/payload.ts+++ b/packages/shared/scripts/seeder/scenarios/payload.ts@@ -28,9 +28,17 @@ export const GEN_OUTPUT_PRICE = 6e-6;* the call site — the createObservation factory would otherwise fill* non-empty defaults.*/+/**+ * Usage and cost for one generation. The price pair is optional: a scenario that+ * models specific models passes its own, everything else takes the house rate.+ */export const generationUsageCost = (usageInput: number,usageOutput: number,+ prices: { input: number; output: number } = {+ input: GEN_INPUT_PRICE,+ output: GEN_OUTPUT_PRICE,+ },) => ({provided_usage_details: {input: usageInput,@@ -43,15 +51,15 @@ export const generationUsageCost = (total: usageInput + usageOutput,},provided_cost_details: {- input: usageInput * GEN_INPUT_PRICE,- output: usageOutput * GEN_OUTPUT_PRICE,+ input: usageInput * prices.input,+ output: usageOutput * prices.output,},cost_details: {- input: usageInput * GEN_INPUT_PRICE,- output: usageOutput * GEN_OUTPUT_PRICE,- total: usageInput * GEN_INPUT_PRICE + usageOutput * GEN_OUTPUT_PRICE,+ input: usageInput * prices.input,+ output: usageOutput * prices.output,+ total: usageInput * prices.input + usageOutput * prices.output,},- total_cost: usageInput * GEN_INPUT_PRICE + usageOutput * GEN_OUTPUT_PRICE,+ total_cost: usageInput * prices.input + usageOutput * prices.output,});const WORDS = [diff --git a/packages/shared/scripts/seeder/scenarios/timeline-shapes.ts b/packages/shared/scripts/seeder/scenarios/timeline-shapes.tsnew file mode 100644index 0000000000..48bdf2087d--- /dev/null+++ b/packages/shared/scripts/seeder/scenarios/timeline-shapes.ts@@ -0,0 +1,1095 @@+import {+ createTrace,+ createObservation,+ createTracesCh,+ createObservationsCh,+ createEventsCh,+ ObservationRecordInsertType,+ TraceRecordInsertType,+} from "../../../src/server";+import { ObservationType } from "../../../src/domain";+import { observationToEvent, traceToEvent } from "./event-mirror";+import { generationUsageCost } from "./payload";+import { utcDayStartMs } from "./rng";+import {+ chunk,+ ScenarioContext,+ ScenarioDefinition,+ SeedError,+ SeedSummary,+} from "./types";+import { countRows, traceLink } from "./verify";++/**+ * A dozen SMALL traces, each a different timeline morphology.+ *+ * The other scenarios generate one big shape with knobs, which answers "does it+ * survive 3000 spans" but not "does a timeline read". Real traces are mostly+ * small and they differ from each other in ways that are specifically about+ * TIME: a retry storm has widening gaps, an approval flow has one huge hole in+ * the middle, a fan-out is a column of overlapping bars, a slow tool is one bar+ * that dwarfs everything, a streaming answer has a time-to-first-token mark+ * inside it. None of that shows up in a scaled-up hub of a thousand siblings.+ *+ * So each shape here is hand-timed with plausible latencies — embeddings in tens+ * of ms, vector search in hundreds, LLM calls in seconds, humans in minutes —+ * and kept to 4-25 observations, because that is the size a trace usually is.+ * Deterministic: no rng at all, the offsets are written down.+ */++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 Span = {+ key: string;+ parent: string | null;+ type: ObservationType;+ name: string;+ /** ms from the trace start */+ start: number;+ /** ms from the trace start; null = still running (no end time at all) */+ end: number | null;+ model?: keyof typeof MODEL_PRICES;+ /** [input, output] tokens — generations only */+ usage?: [number, number];+ /** time to first token, ms after start — generations only */+ ttft?: number;+ level?: "DEFAULT" | "WARNING" | "ERROR";+ status?: string;+ input?: unknown;+ output?: unknown;+};++type Shape = {+ slug: string;+ /** Trace name, and what the shape is called in the catalog. */+ name: string;+ /** One line on what this shape teaches a timeline. */+ about: string;+ tags: string[];+ user: string;+ spans: Span[];+};++/** A sequence of same-shaped siblings, for the shapes that are a queue. */+const siblings = (+ count: number,+ from: number,+ each: number,+ gap: number,+ make: (index: number) => Omit<Span, "start" | "end" | "parent">,+): Span[] =>+ Array.from({ length: count }, (_, index) => ({+ parent: "root",+ start: from + index * (each + gap),+ end: from + index * (each + gap) + each,+ ...make(index),+ }));++const SHAPES: Shape[] = [+ {+ slug: "rag-answer",+ name: "rag.answer",+ about: "The everyday one: embed, search, rerank, answer. 2.4 seconds.",+ tags: ["shape:rag", "small"],+ user: "[email protected]",+ spans: [+ {+ key: "root",+ parent: null,+ type: "SPAN",+ name: "rag.answer",+ start: 0,+ end: 2380,+ input: { question: "Which plans include SSO?" },+ output: { answer: "Team and Enterprise include SSO." },+ },+ {+ key: "embed",+ parent: "root",+ type: "EMBEDDING",+ name: "embed-query",+ start: 30,+ end: 96,+ model: "text-embedding-4",+ usage: [12, 0],+ },+ {+ key: "search",+ parent: "root",+ type: "RETRIEVER",+ name: "vector-search",+ start: 105,+ end: 381,+ output: { hits: 8, top_score: 0.83 },+ },+ {+ key: "pg",+ parent: "search",+ type: "TOOL",+ name: "pgvector.query",+ start: 120,+ end: 360,+ },+ {+ key: "rerank",+ parent: "root",+ type: "SPAN",+ name: "rerank",+ start: 395,+ end: 612,+ },+ {+ key: "answer",+ parent: "root",+ type: "GENERATION",+ name: "answer-llm",+ start: 640,+ end: 2360,+ model: "gpt-5.4-mini",+ usage: [1840, 260],+ ttft: 420,+ },+ ],+ },+ {+ slug: "streaming-chat",+ name: "chat.turn",+ about:+ "One long streamed answer: the bar is split at time-to-first-token, so waiting and generating are different things.",+ tags: ["shape:streaming", "small"],+ user: "[email protected]",+ spans: [+ {+ key: "root",+ parent: null,+ type: "SPAN",+ name: "chat.turn",+ start: 0,+ end: 8180,+ },+ {+ key: "guard",+ parent: "root",+ type: "GUARDRAIL",+ name: "guardrail.input",+ start: 20,+ end: 74,+ output: { verdict: "pass" },+ },+ {+ key: "llm",+ parent: "root",+ type: "GENERATION",+ name: "chat-llm",+ start: 90,+ end: 8020,+ model: "gpt-5.4",+ usage: [520, 1480],+ ttft: 640,+ },+ {+ key: "persist",+ parent: "root",+ type: "SPAN",+ name: "persist-message",+ start: 8040,+ end: 8170,+ },+ ],+ },+ {+ slug: "parallel-fanout",+ name: "enrich.contact",+ about:+ "Eight tools launched at once and joined: a column of overlapping bars, which a tree cannot show you.",+ tags: ["shape:parallel", "small"],+ user: "[email protected]",+ spans: [+ {+ key: "root",+ parent: null,+ type: "AGENT",+ name: "enrich.contact",+ start: 0,+ end: 3080,+ },+ {+ key: "plan",+ parent: "root",+ type: "GENERATION",+ name: "plan-enrichment",+ start: 40,+ end: 760,+ model: "gpt-5.4-mini",+ usage: [340, 90],+ ttft: 210,+ },+ {+ key: "fan",+ parent: "root",+ type: "SPAN",+ name: "fan-out",+ start: 790,+ end: 2760,+ },+ // All eight start within 60ms of each other and finish whenever they finish.+ ...[+ ["clearbit.lookup", 1960],+ ["linkedin.profile", 2740],+ ["crm.contact", 1190],+ ["billing.account", 1420],+ ["tickets.recent", 2210],+ ["usage.rollup", 1640],+ ["notes.search", 980],+ ["email.threads", 2480],+ ].map(([name, end], index) => ({+ key: `tool-${index}`,+ parent: "fan",+ type: "TOOL" as ObservationType,+ name: name as string,+ start: 800 + index * 8,+ end: end as number,+ })),+ {+ key: "merge",+ parent: "root",+ type: "GENERATION",+ name: "merge-llm",+ start: 2790,+ end: 3060,+ model: "gpt-5.4-mini",+ usage: [1200, 180],+ ttft: 120,+ },+ ],+ },+ {+ slug: "retry-backoff",+ name: "sync.invoices",+ about:+ "A rate-limited API retried with exponential backoff: you can SEE 1s, 2s and 4s of waiting between the attempts.",+ tags: ["shape:retry", "small"],+ user: "[email protected]",+ spans: [+ {+ key: "root",+ parent: null,+ type: "SPAN",+ name: "sync.invoices",+ start: 0,+ end: 12520,+ },+ {+ key: "a1",+ parent: "root",+ type: "TOOL",+ name: "stripe.list (attempt 1)",+ start: 40,+ end: 1240,+ level: "ERROR",+ status: "429 rate_limited — retrying in 1s",+ },+ {+ key: "a2",+ parent: "root",+ type: "TOOL",+ name: "stripe.list (attempt 2)",+ start: 2260,+ end: 3480,+ level: "ERROR",+ status: "429 rate_limited — retrying in 2s",+ },+ {+ key: "a3",+ parent: "root",+ type: "TOOL",+ name: "stripe.list (attempt 3)",+ start: 5500,+ end: 6820,+ level: "ERROR",+ status: "429 rate_limited — retrying in 4s",+ },+ {+ key: "a4",+ parent: "root",+ type: "TOOL",+ name: "stripe.list (attempt 4)",+ start: 10840,+ end: 12240,+ output: { invoices: 34 },+ },+ {+ key: "persist",+ parent: "root",+ type: "SPAN",+ name: "persist-invoices",+ start: 12270,+ end: 12480,+ },+ ],+ },+ {+ slug: "waiting-on-approval",+ name: "refund.workflow",+ about:+ "13 minutes of the 13.5 are one human deciding: the hole in the middle IS the trace.",+ tags: ["shape:human-in-the-loop", "small"],+ user: "[email protected]",+ spans: [+ {+ key: "root",+ parent: null,+ type: "AGENT",+ name: "refund.workflow",+ start: 0,+ end: 811_000,+ },+ {+ key: "draft",+ parent: "root",+ type: "GENERATION",+ name: "draft-refund",+ start: 60,+ end: 1980,+ model: "gpt-5.4",+ usage: [880, 240],+ ttft: 300,+ },+ {+ key: "notify",+ parent: "root",+ type: "TOOL",+ name: "slack.request-approval",+ start: 2010,+ end: 2260,+ },+ {+ key: "wait",+ parent: "root",+ type: "EVENT",+ name: "awaiting-approval",+ start: 2300,+ end: 2300,+ },+ {+ key: "granted",+ parent: "root",+ type: "EVENT",+ name: "approval.granted",+ start: 795_000,+ end: 795_000,+ },+ {+ key: "refund",+ parent: "root",+ type: "TOOL",+ name: "stripe.create-refund",+ start: 795_200,+ end: 797_400,+ output: { refund_id: "re_8Fj2kQ" },+ },+ {+ key: "email",+ parent: "root",+ type: "SPAN",+ name: "confirm-email",+ start: 797_500,+ end: 810_900,+ },+ ],+ },+ {+ slug: "slow-tool",+ name: "report.build",+ about:+ "One 43-second warehouse query and five fast spans: the scale problem, where everything else is a sliver.",+ tags: ["shape:one-slow-span", "small"],+ user: "[email protected]",+ spans: [+ {+ key: "root",+ parent: null,+ type: "SPAN",+ name: "report.build",+ start: 0,+ end: 46_800,+ },+ {+ key: "cache",+ parent: "root",+ type: "EMBEDDING",+ name: "cache-key",+ start: 40,+ end: 80,+ model: "text-embedding-4",+ usage: [8, 0],+ },+ {+ key: "plan",+ parent: "root",+ type: "GENERATION",+ name: "plan-report",+ start: 110,+ end: 980,+ model: "gpt-5.4-mini",+ usage: [420, 140],+ ttft: 190,+ },+ {+ key: "warehouse",+ parent: "root",+ type: "TOOL",+ name: "warehouse.query",+ start: 1010,+ end: 44_200,+ output: { rows: 1_284_302 },+ },+ {+ key: "format",+ parent: "root",+ type: "SPAN",+ name: "format-tables",+ start: 44_230,+ end: 45_100,+ },+ {+ key: "summarize",+ parent: "root",+ type: "GENERATION",+ name: "summarize",+ start: 45_130,+ end: 46_700,+ model: "gpt-5.4",+ usage: [3200, 420],+ ttft: 380,+ },+ ],+ },+ {+ slug: "error-cascade",+ name: "assistant.turn",+ about:+ "A 503 on the primary model, a failover, and a warning on the output guard: three levels in one trace.",+ tags: ["shape:errors", "small"],+ user: "[email protected]",+ spans: [+ {+ key: "root",+ parent: null,+ type: "AGENT",+ name: "assistant.turn",+ start: 0,+ end: 6380,+ level: "WARNING",+ status: "answered on the fallback model",+ },+ {+ key: "guard-in",+ parent: "root",+ type: "GUARDRAIL",+ name: "guardrail.input",+ start: 25,+ end: 88,+ },+ {+ key: "primary",+ parent: "root",+ type: "GENERATION",+ name: "primary-llm",+ start: 110,+ end: 2400,+ model: "gpt-5.4",+ usage: [640, 0],+ level: "ERROR",+ status: "upstream 503 after 2 attempts",+ },+ {+ key: "failover",+ parent: "root",+ type: "EVENT",+ name: "failover",+ start: 2420,+ end: 2420,+ },+ {+ key: "fallback",+ parent: "root",+ type: "GENERATION",+ name: "fallback-llm",+ start: 2460,+ end: 5900,+ model: "gpt-5.4-mini",+ usage: [640, 720],+ ttft: 700,+ },+ {+ key: "guard-out",+ parent: "root",+ type: "GUARDRAIL",+ name: "guardrail.output",+ start: 5930,+ end: 6010,+ level: "WARNING",+ status: "1 pii redaction",+ },+ {+ key: "redact",+ parent: "root",+ type: "SPAN",+ name: "redact",+ start: 6030,+ end: 6180,+ },+ {+ key: "send",+ parent: "root",+ type: "SPAN",+ name: "send",+ start: 6200,+ end: 6360,+ },+ ],+ },+ {+ slug: "still-running",+ name: "batch.embed",+ about:+ "Three spans have no end time yet: the in-flight shape, which has no duration to label.",+ tags: ["shape:in-flight", "small"],+ user: "[email protected]",+ spans: [+ {+ key: "root",+ parent: null,+ type: "AGENT",+ name: "batch.embed",+ start: 0,+ end: null,+ },+ {+ key: "manifest",+ parent: "root",+ type: "SPAN",+ name: "load-manifest",+ start: 20,+ end: 340,+ },+ {+ key: "c1",+ parent: "root",+ type: "EMBEDDING",+ name: "embed-chunk-1",+ start: 360,+ end: 980,+ model: "text-embedding-4",+ usage: [8100, 0],+ },+ {+ key: "c2",+ parent: "root",+ type: "EMBEDDING",+ name: "embed-chunk-2",+ start: 1000,+ end: 1640,+ model: "text-embedding-4",+ usage: [7900, 0],+ },+ {+ key: "c3",+ parent: "root",+ type: "EMBEDDING",+ name: "embed-chunk-3",+ start: 1660,+ end: null,+ },+ {+ key: "upsert",+ parent: "root",+ type: "TOOL",+ name: "upsert-vectors",+ start: 1680,+ end: null,+ },+ ],+ },+ {+ slug: "checkpoint-marks",+ name: "pipeline.run",+ about:+ "Ten zero-duration checkpoints among three phases: instants have to stay visible without pretending to have width.",+ tags: ["shape:instants", "small"],+ user: "[email protected]",+ spans: [+ {+ key: "root",+ parent: null,+ type: "SPAN",+ name: "pipeline.run",+ start: 0,+ end: 4180,+ },+ {+ key: "ingest",+ parent: "root",+ type: "SPAN",+ name: "ingest",+ start: 40,+ end: 1380,+ },+ {+ key: "transform",+ parent: "root",+ type: "CHAIN",+ name: "transform",+ start: 1400,+ end: 3020,+ },+ {+ key: "load",+ parent: "root",+ type: "SPAN",+ name: "load",+ start: 3040,+ end: 4140,+ },+ ...[120, 460, 780, 1150, 1520, 1980, 2410, 2890, 3350, 3820].map(+ (at, index) => ({+ key: `mark-${index}`,+ parent:+ at < 1380 ? "ingest" : at < 3020 ? ("transform" as string) : "load",+ type: "EVENT" as ObservationType,+ name: `checkpoint-${index + 1}`,+ start: at,+ end: at,+ }),+ ),+ ],+ },+ {+ slug: "deep-ladder",+ name: "chain.refine",+ about:+ "Ten levels of nesting in ten spans: the staircase, small enough to read every step.",+ tags: ["shape:deep", "small"],+ user: "[email protected]",+ spans: Array.from({ length: 10 }, (_, level) => ({+ key: `level-${level}`,+ parent: level === 0 ? null : `level-${level - 1}`,+ type: (level % 3 === 2 ? "GENERATION" : "SPAN") as ObservationType,+ name: level === 0 ? "chain.refine" : `refine-step-${level}`,+ start: level * 420,+ end: 5600 - level * 90,+ ...(level % 3 === 2+ ? {+ model: "gpt-5.4-mini" as const,+ usage: [600 + level * 40, 120] as [number, number],+ ttft: 180,+ }+ : {}),+ })),+ },+ {+ slug: "flat-siblings",+ name: "queue.drain",+ about:+ "One root and 24 siblings back to back, no nesting at all: the flat list, where a timeline is just a ruler.",+ tags: ["shape:flat", "small"],+ user: "[email protected]",+ spans: [+ {+ key: "root",+ parent: null,+ type: "SPAN",+ name: "queue.drain",+ start: 0,+ end: 9000,+ },+ ...siblings(24, 40, 330, 40, (index) => ({+ key: `job-${index}`,+ type: (index % 4 === 3 ? "GENERATION" : "TOOL") as ObservationType,+ name: index % 4 === 3 ? "classify-job" : `handle-job-${index}`,+ ...(index % 4 === 3+ ? {+ model: "gpt-5.4-mini" as const,+ usage: [180, 40] as [number, number],+ ttft: 90,+ }+ : {}),+ })),+ ],+ },+ {+ slug: "mixed-loop",+ name: "agent.run",+ about:+ "A three-turn agent with think time between the turns: small, and shaped like a real loop rather than a hub.",+ tags: ["shape:agent-loop", "small"],+ user: "[email protected]",+ spans: [+ {+ key: "root",+ parent: null,+ type: "AGENT",+ name: "agent.run",+ start: 0,+ end: 23_800,+ },+ // turn 1+ {+ key: "plan-1",+ parent: "root",+ type: "AGENT",+ name: "plan",+ start: 40,+ end: 520,+ },+ {+ key: "search-1",+ parent: "root",+ type: "RETRIEVER",+ name: "search",+ start: 560,+ end: 900,+ },+ {+ key: "embed-1",+ parent: "search-1",+ type: "EMBEDDING",+ name: "embed-query",+ start: 570,+ end: 640,+ model: "text-embedding-4",+ usage: [14, 0],+ },+ {+ key: "vs-1",+ parent: "search-1",+ type: "TOOL",+ name: "vector-search",+ start: 650,+ end: 890,+ },+ {+ key: "gen-1",+ parent: "root",+ type: "GENERATION",+ name: "generate",+ start: 950,+ end: 4200,+ model: "gpt-5.4",+ usage: [2100, 380],+ ttft: 520,+ },+ {+ key: "critic-1",+ parent: "root",+ type: "EVALUATOR",+ name: "critic",+ start: 4240,+ end: 4900,+ output: { verdict: "revise", score: 0.61 },+ },+ // 2.5s of thinking, then turn 2+ {+ key: "plan-2",+ parent: "root",+ type: "AGENT",+ name: "plan",+ start: 7400,+ end: 7880,+ },+ {+ key: "gen-2",+ parent: "root",+ type: "GENERATION",+ name: "generate",+ start: 7920,+ end: 11_400,+ model: "gpt-5.4",+ usage: [2600, 440],+ ttft: 480,+ },+ {+ key: "critic-2",+ parent: "root",+ type: "EVALUATOR",+ name: "critic",+ start: 11_440,+ end: 12_100,+ output: { verdict: "revise", score: 0.78 },+ },+ // 4s gap, then the final turn+ {+ key: "gen-3",+ parent: "root",+ type: "GENERATION",+ name: "generate",+ start: 16_200,+ end: 23_300,+ model: "gpt-5.4",+ usage: [3100, 900],+ ttft: 610,+ },+ {+ key: "critic-3",+ parent: "root",+ type: "EVALUATOR",+ name: "critic",+ start: 23_340,+ end: 23_400,+ output: { verdict: "accept", score: 0.93 },+ },+ {+ key: "send",+ parent: "root",+ type: "SPAN",+ name: "send-answer",+ start: 23_430,+ end: 23_760,+ },+ ],+ },+];++const durationOf = (shape: Shape) =>+ Math.max(...shape.spans.map((s) => s.end ?? s.start));++const run = async (+ ctx: ScenarioContext,+ params: Record<string, string | number | boolean>,+): Promise<SeedSummary> => {+ const startedAt = Date.now();+ const withV4 = params["v4"] as boolean;+ const only = String(params["shape"]);++ const shapes =+ only === "all" ? SHAPES : SHAPES.filter((s) => s.slug === only);+ if (shapes.length === 0) {+ throw new SeedError(+ `unknown --shape "${only}"`,+ `one of: all, ${SHAPES.map((s) => s.slug).join(", ")}`,+ );+ }++ const traceTimestamp = utcDayStartMs();+ const traceIdOf = (shape: Shape) => `${ctx.idPrefix}-${shape.slug}`;++ if (ctx.dryRun) {+ return {+ scenario: "timeline-shapes",+ target: "clickhouse",+ params,+ projectId: ctx.projectId,+ environment: ctx.environment,+ traceIds: shapes.map(traceIdOf),+ sessionIds: [],+ counts: {+ traces: shapes.length,+ observations: shapes.reduce((n, s) => n + s.spans.length, 0),+ events: withV4 ? shapes.reduce((n, s) => n + s.spans.length + 1, 0) : 0,+ },+ verified: {},+ links: shapes.map((s) => traceLink(ctx, traceIdOf(s), traceTimestamp)),+ dryRun: true,+ durationMs: Date.now() - startedAt,+ };+ }++ const traces: TraceRecordInsertType[] = [];+ const observations: ObservationRecordInsertType[] = [];++ for (const shape of shapes) {+ const traceId = traceIdOf(shape);+ const root = shape.spans[0];+ const trace = createTrace({+ id: traceId,+ project_id: ctx.projectId,+ environment: ctx.environment,+ name: shape.name,+ timestamp: traceTimestamp,+ user_id: shape.user,+ session_id: null,+ release: "2026.08.14-1",+ version: "shapes-v1",+ tags: ["seed", "timeline-shapes", ...shape.tags],+ public: false,+ bookmarked: false,+ metadata: {+ scenario: "timeline-shapes",+ shape: shape.slug,+ about: shape.about,+ spans: String(shape.spans.length),+ wall_clock_ms: String(durationOf(shape)),+ },+ input: root.input !== undefined ? JSON.stringify(root.input) : null,+ output: root.output !== undefined ? JSON.stringify(root.output) : null,+ created_at: Date.now(),+ updated_at: Date.now(),+ event_ts: Date.now(),+ });+ traces.push(trace);++ const idOf = new Map(+ shape.spans.map((s, i) => [s.key, `${traceId}-obs-${i}`]),+ );++ for (const span of shape.spans) {+ const prices = span.model ? MODEL_PRICES[span.model] : null;+ const [usageIn, usageOut] = span.usage ?? [0, 0];++ observations.push(+ createObservation({+ id: idOf.get(span.key)!,+ 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+ ? traceTimestamp + span.start + span.ttft+ : null,+ level: span.level ?? "DEFAULT",+ status_message: span.status ?? null,+ version: null,+ input: span.input !== undefined ? JSON.stringify(span.input) : null,+ output:+ span.output !== undefined ? JSON.stringify(span.output) : null,+ metadata: { scenario: "timeline-shapes", shape: shape.slug },+ provided_model_name: span.model ?? null,+ internal_model_id: null,+ model_parameters: "{}",+ // Explicitly empty for non-generations: the factory would otherwise+ // fill in non-empty usage and cost defaults.+ ...(prices+ ? generationUsageCost(usageIn, usageOut, prices)+ : {+ provided_usage_details: {},+ usage_details: {},+ provided_cost_details: {},+ cost_details: {},+ total_cost: null,+ }),+ prompt_id: null,+ prompt_name: null,+ prompt_version: null,+ created_at: Date.now(),+ updated_at: Date.now(),+ event_ts: Date.now(),+ }),+ );+ }+ }++ const events = withV4+ ? [+ ...traces.map((t) => traceToEvent(t)),+ ...observations.map((o) => {+ const trace = traces.find((t) => t.id === o.trace_id)!;+ return observationToEvent(o, trace);+ }),+ ]+ : [];++ ctx.log(+ `writing ${traces.length} shapes, ${observations.length} observations${+ withV4 ? `, ${events.length} events` : ""+ }`,+ );+ await createTracesCh(traces);+ for (const batch of chunk(observations, 1000)) {+ await createObservationsCh(batch);+ }+ for (const batch of chunk(events, 500)) {+ await createEventsCh(batch);+ }++ const ids = traces.map((t) => t.id);+ const verified: Record<string, number> = {+ traces: await countRows(+ "traces",+ `project_id = {projectId: String} AND id IN {ids: Array(String)}`,+ { projectId: ctx.projectId, ids },+ "uniqExact(id)",+ ),+ observations: await countRows(+ "observations",+ `project_id = {projectId: String} AND trace_id IN {ids: Array(String)}`,+ { projectId: ctx.projectId, ids },+ "uniqExact(id)",+ ),+ };+ if (withV4) {+ // events_full has no `id` column — count rows.+ verified.events = await countRows(+ "events_full",+ `project_id = {projectId: String} AND trace_id IN {ids: Array(String)}`,+ { projectId: ctx.projectId, ids },+ );+ }++ if (verified.traces < traces.length) {+ throw new SeedError(+ `Readback mismatch: expected ${traces.length} traces, found ${verified.traces}`,+ );+ }+ if (verified.observations < observations.length) {+ throw new SeedError(+ `Readback mismatch: expected ${observations.length} observations, found ${verified.observations}`,+ );+ }+ if (withV4 && verified.events < events.length) {+ throw new SeedError(+ `Readback mismatch: expected ${events.length} events_full rows, found ${verified.events}`,+ );+ }++ return {+ scenario: "timeline-shapes",+ target: "clickhouse",+ params,+ projectId: ctx.projectId,+ environment: ctx.environment,+ traceIds: ids,+ sessionIds: [],+ counts: {+ traces: traces.length,+ observations: observations.length,+ events: events.length,+ },+ verified,+ links: shapes.map((s) => traceLink(ctx, traceIdOf(s), traceTimestamp)),+ dryRun: false,+ durationMs: Date.now() - startedAt,+ };+};++export const timelineShapesScenario: ScenarioDefinition = {+ name: "timeline-shapes",+ description:+ "A dozen SMALL traces (4-25 observations each), one per timeline morphology: rag answer, streamed chat, parallel 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, and a three-turn agent loop with think time. Hand-timed with plausible latencies rather than generated, because what differs between real traces is their TIME, and that does not come out of scaling one shape up.",+ supportsV4: true,+ flags: [+ {+ flag: "shape",+ type: "string",+ default: "all",+ description: `one shape or all: all, ${SHAPES.map((s) => s.slug).join(", ")}`,+ },+ {+ flag: "v4",+ type: "boolean",+ default: false,+ description: "also mirror into v4 events_full/events_core",+ },+ ],+ run,+};diff --git a/web/src/components/ItemBadge.stories.tsx b/web/src/components/ItemBadge.stories.tsxnew file mode 100644index 0000000000..b2b83a516e--- /dev/null+++ b/web/src/components/ItemBadge.stories.tsx@@ -0,0 +1,105 @@+import { expect } from "storybook/test";+import preview from "../../.storybook/preview";+import { ItemBadge, type LangfuseItemType } from "./ItemBadge";++const meta = preview.meta({+ component: ItemBadge,+});++const TYPES: LangfuseItemType[] = [+ "TRACE",+ "SPAN",+ "GENERATION",+ "AGENT",+ "TOOL",+ "CHAIN",+ "RETRIEVER",+ "EMBEDDING",+ "EVENT",+ "GUARDRAIL",+];++export const Default = meta.story({+ args: { type: "GENERATION" },+});++export const WithLabel = meta.story({+ args: { type: "GENERATION", showLabel: true },+});++export const Small = meta.story({+ args: { type: "GENERATION", isSmall: true },+});++/** Every type at both sizes, icon-only and labelled. */+export const VariantMatrix = meta.story({+ args: { type: "GENERATION" },+ render: () => (+ <div className="flex w-fit flex-col gap-3 text-sm">+ {(+ [+ ["icon only", false],+ ["with label", true],+ ] as const+ ).map(([caption, showLabel]) => (+ <div key={caption} className="flex flex-col gap-1">+ <span className="text-muted-foreground text-xs">{caption}</span>+ <div className="flex flex-wrap items-center gap-2">+ {TYPES.map((type) => (+ <ItemBadge key={type} type={type} showLabel={showLabel} />+ ))}+ </div>+ <div className="flex flex-wrap items-center gap-2">+ {TYPES.map((type) => (+ <ItemBadge key={type} type={type} showLabel={showLabel} isSmall />+ ))}+ </div>+ </div>+ ))}+ </div>+ ),+});++export const IconOnlyIsSquare = meta.story({+ name: "(Test) Icon Only Is Square",+ args: { type: "GENERATION" },+ render: () => (+ <div className="flex items-center gap-2">+ {TYPES.map((type) => (+ <span key={type} data-testid="icon-only">+ <ItemBadge type={type} />+ </span>+ ))}+ {TYPES.map((type) => (+ <span key={`${type}-small`} data-testid="icon-only-small">+ <ItemBadge type={type} isSmall />+ </span>+ ))}+ <span data-testid="labelled">+ <ItemBadge type="GENERATION" showLabel />+ </span>+ </div>+ ),+ play: async ({ canvasElement }) => {+ // The icon is square, so its box is too — a rectangle around it was just+ // horizontal padding with nothing to pad.+ for (const testId of ["icon-only", "icon-only-small"]) {+ const badges = canvasElement.querySelectorAll<HTMLElement>(+ `[data-testid="${testId}"] > *`,+ );+ await expect(badges.length).toBe(TYPES.length);+ for (const badge of badges) {+ const box = badge.getBoundingClientRect();+ await expect(box.width).toBeCloseTo(box.height, 0);+ await expect(box.width).toBeGreaterThan(0);+ }+ }++ // A labelled badge keeps its pill: there the padding separates icon from text.+ const labelled = canvasElement+ .querySelector<HTMLElement>('[data-testid="labelled"] > *')+ ?.getBoundingClientRect();+ if (!labelled) throw new Error("no labelled badge");+ await expect(labelled.width).toBeGreaterThan(labelled.height);+ },+});diff --git a/web/src/components/ItemBadge.tsx b/web/src/components/ItemBadge.tsxindex 262a977112..69cf6053a8 100644--- a/web/src/components/ItemBadge.tsx+++ b/web/src/components/ItemBadge.tsx@@ -133,8 +133,16 @@ export function ItemBadge({variant="outline"title={label}className={cn(- "bg-background flex max-w-fit items-center gap-1 overflow-hidden border-2 px-1 whitespace-nowrap",- isSmall && "h-4",+ "bg-background flex max-w-fit items-center gap-1 overflow-hidden border-2 whitespace-nowrap",+ // With a label the horizontal padding is what separates the icon from the+ // text. Without one there is nothing to separate, and the padding only+ // made a square icon sit in a rectangle. `max-w-none` is what lets it be+ // square: `max-w-fit` caps the width at the icon's own width, so a set+ // size would apply to the height alone.+ showLabel+ ? "px-1"+ : cn("max-w-none justify-center p-0", isSmall ? "size-4" : "size-6"),+ isSmall && showLabel && "h-4",)}><Icon className={iconClass} />diff --git a/web/src/features/feature-flags/available-flags.ts b/web/src/features/feature-flags/available-flags.tsindex 1162171a24..6f278c716c 100644--- a/web/src/features/feature-flags/available-flags.ts+++ b/web/src/features/feature-flags/available-flags.ts@@ -8,6 +8,7 @@ export const featurePreviewFlags = [// safe rollback; drop once the GA rollout is confirmed stable."searchBar","v4UpgradeUi",+ "compactTimeline",] as const;export type FeaturePreviewFlag = (typeof featurePreviewFlags)[number];@@ -32,6 +33,10 @@ export const isFeaturePreviewAvailable = (return true;}+ if (flag === "compactTimeline") {+ return true;+ }+return assertUnreachable(flag);};diff --git a/web/src/features/feature-flags/types.ts b/web/src/features/feature-flags/types.tsindex 464f94a4a0..567557680a 100644--- a/web/src/features/feature-flags/types.ts+++ b/web/src/features/feature-flags/types.ts@@ -2,9 +2,13 @@ import { type availableFlags } from "./available-flags";export type Flag = (typeof availableFlags)[number];export type Flags = {- [key in Exclude<Flag, "modernSession" | "v4UpgradeUi">]: boolean;+ [key in Exclude<+ Flag,+ "modernSession" | "v4UpgradeUi" | "compactTimeline"+ >]: boolean;} & {// Optional while older sessions and test fixtures roll across new flags.modernSession?: boolean;v4UpgradeUi?: boolean;+ compactTimeline?: boolean;};diff --git a/web/src/features/feature-flags/utils.clienttest.ts b/web/src/features/feature-flags/utils.clienttest.tsindex ee9723f55b..175dc163a1 100644--- a/web/src/features/feature-flags/utils.clienttest.ts+++ b/web/src/features/feature-flags/utils.clienttest.ts@@ -13,6 +13,7 @@ describe("parseFlags", () => {expect(flags.modernSession).toBe(true);expect(flags.searchBar).toBe(true);+ expect(flags.compactTimeline).toBe(true);});it("enables feature previews by default for ClickHouse team members", () => {@@ -23,6 +24,7 @@ describe("parseFlags", () => {expect(flags.modernSession).toBe(true);expect(flags.searchBar).toBe(true);+ expect(flags.compactTimeline).toBe(true);});it("does not enable feature previews by default for other users", () => {@@ -33,6 +35,7 @@ describe("parseFlags", () => {expect(flags.modernSession).toBe(false);expect(flags.searchBar).toBe(false);+ expect(flags.compactTimeline).toBe(false);});it("honors a Langfuse team member's explicit opt-out", () => {@@ -43,5 +46,7 @@ describe("parseFlags", () => {expect(flags.modernSession).toBe(false);expect(flags.searchBar).toBe(true);+ // Opting out of one preview leaves the others alone.+ expect(flags.compactTimeline).toBe(true);});});diff --git a/web/src/features/feature-previews/assets/compact-timeline-dark.svg b/web/src/features/feature-previews/assets/compact-timeline-dark.svgnew file mode 100644index 0000000000..8f3616d69e--- /dev/null+++ b/web/src/features/feature-previews/assets/compact-timeline-dark.svg@@ -0,0 +1,112 @@+<svg width="1200" height="700" viewBox="0 0 1200 700" fill="none" xmlns="http://www.w3.org/2000/svg">+ <rect width="1200" height="700" fill="#0A0A0A"/>+ <rect x="32" y="28" width="1136" height="644" rx="18" fill="#141414" stroke="#2A2A2A" stroke-width="2"/>+ <rect x="32" y="28" width="1136" height="60" rx="18" fill="#0A0A0A"/>+ <path d="M32 88H1168" stroke="#2A2A2A" stroke-width="2"/>+ <rect x="56" y="48" width="20" height="20" rx="4" fill="#2A2A2A"/>+ <rect x="88" y="52" width="20" height="12" rx="4" fill="#2A2A2A"/>+ <rect x="120" y="52" width="96" height="12" rx="6" fill="#2A2A2A"/>+ <path d="M32 128H1168" stroke="#2A2A2A" stroke-width="2"/>+ <rect x="252" y="100" width="52" height="10" rx="5" fill="#2A2A2A"/>+ <rect x="452" y="100" width="52" height="10" rx="5" fill="#2A2A2A"/>+ <rect x="652" y="100" width="52" height="10" rx="5" fill="#2A2A2A"/>+ <rect x="852" y="100" width="52" height="10" rx="5" fill="#2A2A2A"/>+ <path d="M250 128V664" stroke="#2A2A2A" stroke-width="2"/>+ <path d="M450 128V664" stroke="#2A2A2A" stroke-width="2"/>+ <path d="M650 128V664" stroke="#2A2A2A" stroke-width="2"/>+ <path d="M850 128V664" stroke="#2A2A2A" stroke-width="2"/>+ <path d="M1050 128V664" stroke="#2A2A2A" stroke-width="2"/>+ <rect x="60" y="128" width="1" height="536" fill="#2A2A2A"/>+ <rect x="250" y="150" width="800" height="6" rx="3" fill="#A78BFA"/>+ <rect x="70" y="150" width="6" height="6" rx="1" fill="#A78BFA"/>+ <rect x="271" y="161" width="783" height="6" rx="3" fill="#818CF8"/>+ <rect x="70" y="161" width="6" height="6" rx="1" fill="#818CF8"/>+ <rect x="280" y="172" width="774" height="6" rx="3" fill="#FB923C"/>+ <rect x="70" y="172" width="6" height="6" rx="1" fill="#FB923C"/>+ <rect x="284" y="183" width="750" height="6" rx="3" fill="#A3E635"/>+ <rect x="70" y="183" width="6" height="6" rx="1" fill="#A3E635"/>+ <rect x="292" y="194" width="727" height="6" rx="3" fill="#2DD4BF"/>+ <rect x="70" y="194" width="6" height="6" rx="1" fill="#2DD4BF"/>+ <rect x="303" y="205" width="707" height="6" rx="3" fill="#F9A8D4"/>+ <rect x="70" y="205" width="6" height="6" rx="1" fill="#F9A8D4"/>+ <rect x="328" y="216" width="686" height="6" rx="3" fill="#FBBF24"/>+ <rect x="70" y="216" width="6" height="6" rx="1" fill="#FBBF24"/>+ <rect x="343" y="227" width="656" height="6" rx="3" fill="#F472B6"/>+ <rect x="70" y="227" width="6" height="6" rx="1" fill="#F472B6"/>+ <rect x="350" y="238" width="644" height="6" rx="3" fill="#F87171"/>+ <rect x="70" y="238" width="6" height="6" rx="1" fill="#F87171"/>+ <rect x="374" y="249" width="615" height="6" rx="3" fill="#A78BFA"/>+ <rect x="70" y="249" width="6" height="6" rx="1" fill="#A78BFA"/>+ <rect x="382" y="260" width="602" height="6" rx="3" fill="#818CF8"/>+ <rect x="70" y="260" width="6" height="6" rx="1" fill="#818CF8"/>+ <rect x="401" y="271" width="569" height="6" rx="3" fill="#FB923C"/>+ <rect x="70" y="271" width="6" height="6" rx="1" fill="#FB923C"/>+ <rect x="408" y="282" width="537" height="6" rx="3" fill="#A3E635"/>+ <rect x="70" y="282" width="6" height="6" rx="1" fill="#A3E635"/>+ <rect x="431" y="293" width="513" height="6" rx="3" fill="#2DD4BF"/>+ <rect x="70" y="293" width="6" height="6" rx="1" fill="#2DD4BF"/>+ <rect x="443" y="304" width="502" height="6" rx="3" fill="#F9A8D4"/>+ <rect x="70" y="304" width="6" height="6" rx="1" fill="#F9A8D4"/>+ <rect x="446" y="315" width="469" height="6" rx="3" fill="#FBBF24"/>+ <rect x="70" y="315" width="6" height="6" rx="1" fill="#FBBF24"/>+ <rect x="454" y="326" width="443" height="6" rx="3" fill="#F472B6"/>+ <rect x="70" y="326" width="6" height="6" rx="1" fill="#F472B6"/>+ <rect x="462" y="337" width="413" height="6" rx="3" fill="#F87171"/>+ <rect x="70" y="337" width="6" height="6" rx="1" fill="#F87171"/>+ <rect x="478" y="348" width="398" height="6" rx="3" fill="#A78BFA"/>+ <rect x="70" y="348" width="6" height="6" rx="1" fill="#A78BFA"/>+ <rect x="485" y="359" width="371" height="6" rx="3" fill="#818CF8"/>+ <rect x="70" y="359" width="6" height="6" rx="1" fill="#818CF8"/>+ <rect x="488" y="370" width="357" height="6" rx="3" fill="#FB923C"/>+ <rect x="70" y="370" width="6" height="6" rx="1" fill="#FB923C"/>+ <rect x="504" y="381" width="327" height="6" rx="3" fill="#A3E635"/>+ <rect x="70" y="381" width="6" height="6" rx="1" fill="#A3E635"/>+ <rect x="520" y="392" width="312" height="6" rx="3" fill="#2DD4BF"/>+ <rect x="70" y="392" width="6" height="6" rx="1" fill="#2DD4BF"/>+ <rect x="544" y="403" width="298" height="6" rx="3" fill="#F9A8D4"/>+ <rect x="70" y="403" width="6" height="6" rx="1" fill="#F9A8D4"/>+ <rect x="547" y="414" width="283" height="6" rx="3" fill="#FBBF24"/>+ <rect x="70" y="414" width="6" height="6" rx="1" fill="#FBBF24"/>+ <rect x="560" y="425" width="274" height="6" rx="3" fill="#F472B6"/>+ <rect x="70" y="425" width="6" height="6" rx="1" fill="#F472B6"/>+ <rect x="566" y="436" width="256" height="6" rx="3" fill="#F87171"/>+ <rect x="70" y="436" width="6" height="6" rx="1" fill="#F87171"/>+ <rect x="582" y="447" width="245" height="6" rx="3" fill="#A78BFA"/>+ <rect x="70" y="447" width="6" height="6" rx="1" fill="#A78BFA"/>+ <rect x="592" y="458" width="214" height="6" rx="3" fill="#818CF8"/>+ <rect x="70" y="458" width="6" height="6" rx="1" fill="#818CF8"/>+ <rect x="618" y="469" width="188" height="6" rx="3" fill="#FB923C"/>+ <rect x="70" y="469" width="6" height="6" rx="1" fill="#FB923C"/>+ <rect x="636" y="480" width="165" height="6" rx="3" fill="#A3E635"/>+ <rect x="70" y="480" width="6" height="6" rx="1" fill="#A3E635"/>+ <rect x="642" y="491" width="156" height="6" rx="3" fill="#2DD4BF"/>+ <rect x="70" y="491" width="6" height="6" rx="1" fill="#2DD4BF"/>+ <rect x="644" y="502" width="125" height="6" rx="3" fill="#F9A8D4"/>+ <rect x="70" y="502" width="6" height="6" rx="1" fill="#F9A8D4"/>+ <rect x="663" y="513" width="92" height="6" rx="3" fill="#FBBF24"/>+ <rect x="70" y="513" width="6" height="6" rx="1" fill="#FBBF24"/>+ <rect x="665" y="524" width="67" height="6" rx="3" fill="#F472B6"/>+ <rect x="70" y="524" width="6" height="6" rx="1" fill="#F472B6"/>+ <rect x="679" y="535" width="40" height="6" rx="3" fill="#F87171"/>+ <rect x="70" y="535" width="6" height="6" rx="1" fill="#F87171"/>+ <rect x="689" y="546" width="28" height="6" rx="3" fill="#A78BFA"/>+ <rect x="70" y="546" width="6" height="6" rx="1" fill="#A78BFA"/>+ <rect x="693" y="557" width="28" height="6" rx="3" fill="#818CF8"/>+ <rect x="70" y="557" width="6" height="6" rx="1" fill="#818CF8"/>+ <rect x="712" y="568" width="28" height="6" rx="3" fill="#FB923C"/>+ <rect x="70" y="568" width="6" height="6" rx="1" fill="#FB923C"/>+ <rect x="732" y="579" width="28" height="6" rx="3" fill="#A3E635"/>+ <rect x="70" y="579" width="6" height="6" rx="1" fill="#A3E635"/>+ <rect x="753" y="590" width="28" height="6" rx="3" fill="#2DD4BF"/>+ <rect x="70" y="590" width="6" height="6" rx="1" fill="#2DD4BF"/>+ <rect x="763" y="601" width="28" height="6" rx="3" fill="#F9A8D4"/>+ <rect x="70" y="601" width="6" height="6" rx="1" fill="#F9A8D4"/>+ <rect x="787" y="612" width="28" height="6" rx="3" fill="#FBBF24"/>+ <rect x="70" y="612" width="6" height="6" rx="1" fill="#FBBF24"/>+ <rect x="799" y="623" width="28" height="6" rx="3" fill="#F472B6"/>+ <rect x="70" y="623" width="6" height="6" rx="1" fill="#F472B6"/>+ <rect x="822" y="634" width="28" height="6" rx="3" fill="#F87171"/>+ <rect x="70" y="634" width="6" height="6" rx="1" fill="#F87171"/>+ <rect x="839" y="645" width="28" height="6" rx="3" fill="#A78BFA"/>+ <rect x="70" y="645" width="6" height="6" rx="1" fill="#A78BFA"/>+</svg>diff --git a/web/src/features/feature-previews/assets/compact-timeline-light.svg b/web/src/features/feature-previews/assets/compact-timeline-light.svgnew file mode 100644index 0000000000..7a06b86e25--- /dev/null+++ b/web/src/features/feature-previews/assets/compact-timeline-light.svg@@ -0,0 +1,112 @@+<svg width="1200" height="700" viewBox="0 0 1200 700" fill="none" xmlns="http://www.w3.org/2000/svg">+ <rect width="1200" height="700" fill="#F8FAFC"/>+ <rect x="32" y="28" width="1136" height="644" rx="18" fill="#FFFFFF" stroke="#E2E8F0" stroke-width="2"/>+ <rect x="32" y="28" width="1136" height="60" rx="18" fill="#F8FAFC"/>+ <path d="M32 88H1168" stroke="#E2E8F0" stroke-width="2"/>+ <rect x="56" y="48" width="20" height="20" rx="4" fill="#E2E8F0"/>+ <rect x="88" y="52" width="20" height="12" rx="4" fill="#E2E8F0"/>+ <rect x="120" y="52" width="96" height="12" rx="6" fill="#E2E8F0"/>+ <path d="M32 128H1168" stroke="#E2E8F0" stroke-width="2"/>+ <rect x="252" y="100" width="52" height="10" rx="5" fill="#E2E8F0"/>+ <rect x="452" y="100" width="52" height="10" rx="5" fill="#E2E8F0"/>+ <rect x="652" y="100" width="52" height="10" rx="5" fill="#E2E8F0"/>+ <rect x="852" y="100" width="52" height="10" rx="5" fill="#E2E8F0"/>+ <path d="M250 128V664" stroke="#E2E8F0" stroke-width="2"/>+ <path d="M450 128V664" stroke="#E2E8F0" stroke-width="2"/>+ <path d="M650 128V664" stroke="#E2E8F0" stroke-width="2"/>+ <path d="M850 128V664" stroke="#E2E8F0" stroke-width="2"/>+ <path d="M1050 128V664" stroke="#E2E8F0" stroke-width="2"/>+ <rect x="60" y="128" width="1" height="536" fill="#E2E8F0"/>+ <rect x="250" y="150" width="800" height="6" rx="3" fill="#7C3AED"/>+ <rect x="70" y="150" width="6" height="6" rx="1" fill="#7C3AED"/>+ <rect x="263" y="161" width="777" height="6" rx="3" fill="#6467F2"/>+ <rect x="70" y="161" width="6" height="6" rx="1" fill="#6467F2"/>+ <rect x="287" y="172" width="757" height="6" rx="3" fill="#EA580C"/>+ <rect x="70" y="172" width="6" height="6" rx="1" fill="#EA580C"/>+ <rect x="301" y="183" width="734" height="6" rx="3" fill="#84CC16"/>+ <rect x="70" y="183" width="6" height="6" rx="1" fill="#84CC16"/>+ <rect x="308" y="194" width="713" height="6" rx="3" fill="#0D9488"/>+ <rect x="70" y="194" width="6" height="6" rx="1" fill="#0D9488"/>+ <rect x="325" y="205" width="684" height="6" rx="3" fill="#F76EB3"/>+ <rect x="70" y="205" width="6" height="6" rx="1" fill="#F76EB3"/>+ <rect x="329" y="216" width="668" height="6" rx="3" fill="#D97706"/>+ <rect x="70" y="216" width="6" height="6" rx="1" fill="#D97706"/>+ <rect x="333" y="227" width="639" height="6" rx="3" fill="#E11D63"/>+ <rect x="70" y="227" width="6" height="6" rx="1" fill="#E11D63"/>+ <rect x="352" y="238" width="630" height="6" rx="3" fill="#DC2626"/>+ <rect x="70" y="238" width="6" height="6" rx="1" fill="#DC2626"/>+ <rect x="377" y="249" width="597" height="6" rx="3" fill="#7C3AED"/>+ <rect x="70" y="249" width="6" height="6" rx="1" fill="#7C3AED"/>+ <rect x="395" y="260" width="573" height="6" rx="3" fill="#6467F2"/>+ <rect x="70" y="260" width="6" height="6" rx="1" fill="#6467F2"/>+ <rect x="401" y="271" width="565" height="6" rx="3" fill="#EA580C"/>+ <rect x="70" y="271" width="6" height="6" rx="1" fill="#EA580C"/>+ <rect x="416" y="282" width="555" height="6" rx="3" fill="#84CC16"/>+ <rect x="70" y="282" width="6" height="6" rx="1" fill="#84CC16"/>+ <rect x="422" y="293" width="541" height="6" rx="3" fill="#0D9488"/>+ <rect x="70" y="293" width="6" height="6" rx="1" fill="#0D9488"/>+ <rect x="425" y="304" width="521" height="6" rx="3" fill="#F76EB3"/>+ <rect x="70" y="304" width="6" height="6" rx="1" fill="#F76EB3"/>+ <rect x="437" y="315" width="491" height="6" rx="3" fill="#D97706"/>+ <rect x="70" y="315" width="6" height="6" rx="1" fill="#D97706"/>+ <rect x="452" y="326" width="466" height="6" rx="3" fill="#E11D63"/>+ <rect x="70" y="326" width="6" height="6" rx="1" fill="#E11D63"/>+ <rect x="466" y="337" width="441" height="6" rx="3" fill="#DC2626"/>+ <rect x="70" y="337" width="6" height="6" rx="1" fill="#DC2626"/>+ <rect x="479" y="348" width="426" height="6" rx="3" fill="#7C3AED"/>+ <rect x="70" y="348" width="6" height="6" rx="1" fill="#7C3AED"/>+ <rect x="505" y="359" width="392" height="6" rx="3" fill="#6467F2"/>+ <rect x="70" y="359" width="6" height="6" rx="1" fill="#6467F2"/>+ <rect x="527" y="370" width="365" height="6" rx="3" fill="#EA580C"/>+ <rect x="70" y="370" width="6" height="6" rx="1" fill="#EA580C"/>+ <rect x="537" y="381" width="351" height="6" rx="3" fill="#84CC16"/>+ <rect x="70" y="381" width="6" height="6" rx="1" fill="#84CC16"/>+ <rect x="545" y="392" width="342" height="6" rx="3" fill="#0D9488"/>+ <rect x="70" y="392" width="6" height="6" rx="1" fill="#0D9488"/>+ <rect x="566" y="403" width="323" height="6" rx="3" fill="#F76EB3"/>+ <rect x="70" y="403" width="6" height="6" rx="1" fill="#F76EB3"/>+ <rect x="588" y="414" width="305" height="6" rx="3" fill="#D97706"/>+ <rect x="70" y="414" width="6" height="6" rx="1" fill="#D97706"/>+ <rect x="613" y="425" width="275" height="6" rx="3" fill="#E11D63"/>+ <rect x="70" y="425" width="6" height="6" rx="1" fill="#E11D63"/>+ <rect x="615" y="436" width="262" height="6" rx="3" fill="#DC2626"/>+ <rect x="70" y="436" width="6" height="6" rx="1" fill="#DC2626"/>+ <rect x="639" y="447" width="241" height="6" rx="3" fill="#7C3AED"/>+ <rect x="70" y="447" width="6" height="6" rx="1" fill="#7C3AED"/>+ <rect x="665" y="458" width="223" height="6" rx="3" fill="#6467F2"/>+ <rect x="70" y="458" width="6" height="6" rx="1" fill="#6467F2"/>+ <rect x="668" y="469" width="199" height="6" rx="3" fill="#EA580C"/>+ <rect x="70" y="469" width="6" height="6" rx="1" fill="#EA580C"/>+ <rect x="689" y="480" width="184" height="6" rx="3" fill="#84CC16"/>+ <rect x="70" y="480" width="6" height="6" rx="1" fill="#84CC16"/>+ <rect x="693" y="491" width="167" height="6" rx="3" fill="#0D9488"/>+ <rect x="70" y="491" width="6" height="6" rx="1" fill="#0D9488"/>+ <rect x="718" y="502" width="139" height="6" rx="3" fill="#F76EB3"/>+ <rect x="70" y="502" width="6" height="6" rx="1" fill="#F76EB3"/>+ <rect x="723" y="513" width="125" height="6" rx="3" fill="#D97706"/>+ <rect x="70" y="513" width="6" height="6" rx="1" fill="#D97706"/>+ <rect x="727" y="524" width="115" height="6" rx="3" fill="#E11D63"/>+ <rect x="70" y="524" width="6" height="6" rx="1" fill="#E11D63"/>+ <rect x="749" y="535" width="103" height="6" rx="3" fill="#DC2626"/>+ <rect x="70" y="535" width="6" height="6" rx="1" fill="#DC2626"/>+ <rect x="764" y="546" width="83" height="6" rx="3" fill="#7C3AED"/>+ <rect x="70" y="546" width="6" height="6" rx="1" fill="#7C3AED"/>+ <rect x="771" y="557" width="56" height="6" rx="3" fill="#6467F2"/>+ <rect x="70" y="557" width="6" height="6" rx="1" fill="#6467F2"/>+ <rect x="776" y="568" width="31" height="6" rx="3" fill="#EA580C"/>+ <rect x="70" y="568" width="6" height="6" rx="1" fill="#EA580C"/>+ <rect x="781" y="579" width="28" height="6" rx="3" fill="#84CC16"/>+ <rect x="70" y="579" width="6" height="6" rx="1" fill="#84CC16"/>+ <rect x="788" y="590" width="28" height="6" rx="3" fill="#0D9488"/>+ <rect x="70" y="590" width="6" height="6" rx="1" fill="#0D9488"/>+ <rect x="813" y="601" width="28" height="6" rx="3" fill="#F76EB3"/>+ <rect x="70" y="601" width="6" height="6" rx="1" fill="#F76EB3"/>+ <rect x="822" y="612" width="28" height="6" rx="3" fill="#D97706"/>+ <rect x="70" y="612" width="6" height="6" rx="1" fill="#D97706"/>+ <rect x="829" y="623" width="28" height="6" rx="3" fill="#E11D63"/>+ <rect x="70" y="623" width="6" height="6" rx="1" fill="#E11D63"/>+ <rect x="852" y="634" width="28" height="6" rx="3" fill="#DC2626"/>+ <rect x="70" y="634" width="6" height="6" rx="1" fill="#DC2626"/>+ <rect x="856" y="645" width="28" height="6" rx="3" fill="#7C3AED"/>+ <rect x="70" y="645" width="6" height="6" rx="1" fill="#7C3AED"/>+</svg>diff --git a/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsx b/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsxindex 226b2b37f8..7421a144de 100644--- a/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsx+++ b/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsx@@ -21,6 +21,7 @@ const PREVIEW_LABEL: Record<PreviewFlag, string> = {modernSession: "Compact Session View",searchBar: "Filter Search Bar",v4UpgradeUi: "V4 Migration",+ compactTimeline: "Compact Timeline",};export function ControlledFeaturePreviewModal({@@ -74,6 +75,19 @@ export function ControlledFeaturePreviewModal({onToggle: onToggle("v4UpgradeUi"),isToggling: setFeaturePreviewEnabled.isPending,},+ compactTimeline: {+ enabled:+ authSession.data?.user?.featureFlags.compactTimeline === true ||+ authSession.data?.environment.enableExperimentalFeatures === true,+ disabled:+ authSession.data?.environment.enableExperimentalFeatures === true,+ warningReason:+ authSession.data?.environment.enableExperimentalFeatures === true+ ? "This preview is enabled by LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES, so a per-user opt-out does not disable it."+ : undefined,+ onToggle: onToggle("compactTimeline"),+ isToggling: setFeaturePreviewEnabled.isPending,+ },// The "Filter Search Bar" preview is retired — the bar is now generally// available on the v4 events tables for everyone (see useSearchBarEnabled),// so it no longer renders a tile here. The `searchBar` flag plumbingdiff --git a/web/src/features/feature-previews/components/FeaturePreviewModal.tsx b/web/src/features/feature-previews/components/FeaturePreviewModal.tsxindex ba4836b416..f7f453e872 100644--- a/web/src/features/feature-previews/components/FeaturePreviewModal.tsx+++ b/web/src/features/feature-previews/components/FeaturePreviewModal.tsx@@ -16,6 +16,8 @@ import type { FeaturePreviewFlag } from "@/src/features/feature-flags/available-import filterSearchBarDarkIllustration from "../assets/filter-search-bar-dark.svg";import filterSearchBarLightIllustration from "../assets/filter-search-bar-light.svg";+import compactTimelineDarkIllustration from "../assets/compact-timeline-dark.svg";+import compactTimelineLightIllustration from "../assets/compact-timeline-light.svg";import modernSessionDarkIllustration from "../assets/modern-session-dark.svg";import modernSessionLightIllustration from "../assets/modern-session-light.svg";@@ -72,6 +74,21 @@ const PREVIEW_REGISTRY: PreviewRegistryItem[] = [alt: "Compact Session View showing a trace minimap beside a continuous session conversation feed.",},},+ {+ flag: "compactTimeline",+ title: "Compact Timeline",+ sidebarLabel: "Compact Timeline",+ description:+ "See a whole trace at once — every observation a single dense line, coloured by type — then zoom and pan it like a map.",+ details:+ "The Compact Timeline replaces the trace panel's Timeline view. It fits the entire trace into the space available on both axes instead of scrolling: rows shrink to a single-pixel line, and colour carries the observation type where there is no room for a name. Scroll to pan, pinch to zoom both time and rows together, and double-click an observation to fly to it at a readable size — at which point the rows grow their names back and the tree gutter returns. Hovering the left edge peeks the names without moving the bars.",+ feedbackUrl: "https://github.com/orgs/langfuse/discussions",+ illustration: {+ light: compactTimelineLightIllustration,+ dark: compactTimelineDarkIllustration,+ alt: "A whole trace as dense coloured lines, one per observation, cascading across a time axis.",+ },+ },{flag: "v4UpgradeUi",title: "V4 Migration",diff --git a/web/src/features/traces/components/TracePanelNavigation.tsx b/web/src/features/traces/components/TracePanelNavigation.tsxindex c86121ec7b..b8a13a17d0 100644--- a/web/src/features/traces/components/TracePanelNavigation.tsx+++ b/web/src/features/traces/components/TracePanelNavigation.tsx@@ -3,6 +3,8 @@** Responsibility:* - Decide which navigation view to show (Tree/Timeline/Search)+ * - The Timeline is either the classic gantt or the Compact Timeline, depending+ * on that feature preview* - NO layout structure - just returns the content component** Hooks:@@ -20,12 +22,22 @@ import { useSearch } from "@/src/features/traces/contexts/SearchContext";import { TraceTree } from "./TraceTree";import { TraceSearchList } from "./TraceSearchList";import { TraceTimeline } from "./TraceTimeline/TraceTimeline";+import { TraceTimelineCompact } from "./TraceTimelineDense/TraceTimelineCompact";import { useMemo } from "react";+import useIsFeatureEnabled from "@/src/features/feature-flags/hooks/useIsFeatureEnabled";export function TracePanelNavigation() {const { searchQuery } = useSearch();const [viewMode] = useQueryParam("view", StringParam);+ // The Compact Timeline feature preview changes what the Timeline view IS,+ // rather than adding a third mode for the user to reason about. On by default+ // for the Langfuse team (see receivesFeaturePreviewsByDefault), opt-in for+ // everyone else. `enableForAdmins: false` so a self-hosted admin does not get+ // it silently — the preview toggle is the way in.+ const isCompactTimelineEnabled = useIsFeatureEnabled("compactTimeline", {+ enableForAdmins: false,+ });const hasQuery = searchQuery.trim().length > 0;const isTimelineView = viewMode === "timeline";@@ -36,10 +48,14 @@ export function TracePanelNavigation() {return <TraceSearchList />;}if (isTimelineView) {- return <TraceTimeline />;+ return isCompactTimelineEnabled ? (+ <TraceTimelineCompact />+ ) : (+ <TraceTimeline />+ );}return <TraceTree />;- }, [hasQuery, isTimelineView]);+ }, [hasQuery, isTimelineView, isCompactTimelineEnabled]);return content;}diff --git a/web/src/features/traces/components/TracePanelNavigationHeader/TracePanelNavigationHeader.tsx b/web/src/features/traces/components/TracePanelNavigationHeader/TracePanelNavigationHeader.tsxindex 867b21974f..caaf3da728 100644--- a/web/src/features/traces/components/TracePanelNavigationHeader/TracePanelNavigationHeader.tsx+++ b/web/src/features/traces/components/TracePanelNavigationHeader/TracePanelNavigationHeader.tsx@@ -344,6 +344,9 @@ function ViewModeSwitch({icon={ListTree}label="Tree"/>+ {/* One Timeline. What it IS depends on the Compact Timeline feature+ preview — see TracePanelNavigation — rather than on a third segment+ the user has to understand. */}<ViewModeSegmentactive={isTimelineView}onClick={() => onSelect(true)}diff --git a/web/src/features/traces/components/TraceTimeline/TraceTimeline.tsx b/web/src/features/traces/components/TraceTimeline/TraceTimeline.tsxindex 3bdd0cf580..a955afeae3 100644--- a/web/src/features/traces/components/TraceTimeline/TraceTimeline.tsx+++ b/web/src/features/traces/components/TraceTimeline/TraceTimeline.tsx@@ -40,8 +40,7 @@ import {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 { useSelectTraceNode } from "@/src/features/traces/hooks/useSelectTraceNode";import { computeSelectionScrollTarget } from "../../fns/timelineCalculations";import { formatIntervalSeconds } from "@/src/utils/dates";import {@@ -56,7 +55,6 @@ import {computeMaxVisualDepth,GUTTER_VISUAL_DEPTH,} from "../../fns/visualDepth";-import { useDesktopLayoutContextOptional } from "../TraceLayoutDesktop";import { useMobileLayoutContextOptional } from "../TraceLayoutMobile";import { type TreeNode } from "../../types/treeNode";import { cn } from "@/src/utils/tailwind";@@ -214,8 +212,7 @@ export function TraceTimeline() {comments,traceDuration,} = useTraceData();- const { collapsedNodes, toggleCollapsed, selectedNodeId, setSelectedNodeId } =- useSelection();+ const { collapsedNodes, toggleCollapsed, selectedNodeId } = useSelection();const {showDuration,showCostTokens,@@ -224,12 +221,9 @@ export function TraceTimeline() {colorCodeMetrics,} = useViewPreferences();const { handleHover } = useHandlePrefetchObservation();- const capture = usePostHogClientCapture();- const analyticsDimensions = useTraceAnalyticsDimensions();- // Optional (null in the mobile layout): reopen the detail panel on select.- const layout = useDesktopLayoutContextOptional();+ const handleSelectNode = useSelectTraceNode("timeline");// Optional (null on desktop): its presence also means the timeline is- // rendered inside a narrow mobile tab, and selecting jumps to the Info tab.+ // rendered inside a narrow mobile tab, which the gutter width follows.const mobileLayout = useMobileLayoutContextOptional();// The chart is the single vertical scroller; the gutter content is a one-way@@ -563,23 +557,9 @@ export function TraceTimeline() {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).- const handleSelectNode = useCallback(- (nodeId: string) => {- capture("trace_detail:node_selected", {- source: "timeline",- ...analyticsDimensions,- });- setSelectedNodeId(nodeId);- // Reopen the detail panel on any select — including re-clicking the- // already-selected row, where the URL param wouldn't fire an effect.- layout?.expandDetailPanel();- // Mobile: jump to the Info tab on the same re-click path (no-op on desktop).- mobileLayout?.switchToInfoTab();- },- [setSelectedNodeId, layout, mobileLayout, capture, analyticsDimensions],- );+ // Stable node-taking callback shared by every row shell (see TimelineRows.tsx+ // — stable references keep the memo boundary effective). Selecting itself is+ // useSelectTraceNode, above, which every view of a trace shares.const handleHoverNode = useCallback((node: TreeNode) => {setHoveredNodeId(node.id);diff --git a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.stories.tsx b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.stories.tsxindex 31c74f87a3..46b28268c8 100644--- a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.stories.tsx+++ b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.stories.tsx@@ -1,7 +1,9 @@-import { expect, waitFor } from "storybook/test";+import { useState } from "react";+import { expect, fn, userEvent, waitFor } from "storybook/test";import preview from "../../../../../.storybook/preview";-import { TimelineDense } from "./TimelineDense";+import { TimelineDense, type TimelineDenseProps } from "./TimelineDense";import {+ deepNesting,manySpans,reporterTrace,threeSpans,@@ -15,7 +17,7 @@ const meta = preview.meta({/*** A phone-shaped box: narrow and tall, which is the case this spike is for.* 658px leaves exactly 600px of surface once the frame, toolbar, axis and- * readout are taken — room for 150 rows at the 4px floor, so the "at the floor"+ * readout are taken — room for 600 rows at the 1px floor, so the "at the floor"* story really is at the floor.*/const PHONE = { width: 360, height: 658 };@@ -38,10 +40,14 @@ export const FiftySpansOnAPhone = meta.story({barColor: "neutral",compress: false,showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),},});-export const OneHundredFiftySpansExactlyAtTheFloor = meta.story({+/** Mid density: 4px a row, the bars still clearly individual things. */+export const OneHundredFiftySpansOnAPhone = meta.story({args: {roots: manySpans(150),box: PHONE,@@ -50,19 +56,45 @@ export const OneHundredFiftySpansExactlyAtTheFloor = meta.story({barColor: "neutral",compress: false,showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),},});-/** More rows than 4px each can show: the extra are panned to, maps-style. */-export const FiveHundredSpansPannable = meta.story({+/**+ * Exactly at the floor: 600 spans, one device pixel each, the whole trace on+ * screen with nothing to scroll to. This is the case that argued the floor down+ * from 4px — at 4px this trace was a window onto a quarter of itself.+ */+export const SixHundredSpansAtTheOnePixelFloor = meta.story({args: {- roots: manySpans(500),+ roots: manySpans(600),box: PHONE,gutter: "auto",pointer: "fine",- barColor: "neutral",+ barColor: "type",+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ },+});++/** Past even the 1px floor: the extra rows are panned to, maps-style. */+export const ThreeThousandSpansPannable = meta.story({+ args: {+ roots: manySpans(3000),+ box: PHONE,+ gutter: "auto",+ pointer: "fine",+ barColor: "type",compress: false,showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),},});@@ -75,6 +107,9 @@ export const TypeColouredBars = meta.story({barColor: "type",compress: false,showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),},});@@ -88,6 +123,9 @@ export const ShortTraceStaysReadable = meta.story({barColor: "neutral",compress: false,showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),},});@@ -100,6 +138,9 @@ export const ReporterShapeInAPeek = meta.story({barColor: "neutral",compress: false,showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),},});@@ -113,6 +154,9 @@ export const NamesExpanded = meta.story({barColor: "neutral",compress: false,showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),},});@@ -125,6 +169,9 @@ export const FullWidthDesktop = meta.story({barColor: "type",compress: false,showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),},});@@ -142,6 +189,9 @@ export const FullWidthWithNames = meta.story({barColor: "type",compress: false,showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),},});@@ -155,6 +205,9 @@ export const FullWidthManySpans = meta.story({barColor: "type",compress: false,showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),},});@@ -168,6 +221,9 @@ export const TouchTapToToggle = meta.story({barColor: "type",compress: false,showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),},});@@ -180,6 +236,9 @@ export const LongTailCompressed = meta.story({barColor: "type",compress: true,showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),},});@@ -193,6 +252,9 @@ export const NeitherAxisScrolls = meta.story({barColor: "neutral",compress: false,showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),},play: async ({ canvasElement }) => {const surface = canvasElement.querySelector<HTMLElement>(@@ -233,6 +295,9 @@ export const ScrollPansPinchZooms = meta.story({barColor: "neutral",compress: false,showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),},play: async ({ canvasElement }) => {const surface = canvasElement.querySelector<HTMLElement>(@@ -273,12 +338,256 @@ export const ScrollPansPinchZooms = meta.story({await waitFor(() => expect(rowWindow()).not.toBe(windowBefore));await expect(rowHeight()).toBe(heightBefore);+ // And a FAST flick is the same gesture. A trackpad sends deltas of well over+ // 100 when you flick, and classifying those as a discrete mouse notch made+ // them zoom out to the fitted view instead: scrolling down snapped the+ // timeline back to the top and kept it there.+ const windowAfterSlow = rowWindow();+ wheel({ deltaY: 240 });+ await waitFor(() => expect(rowWindow()).not.toBe(windowAfterSlow));+ await expect(rowHeight()).toBe(heightBefore);+ // Line-mode deltas (Firefox, classic wheels) pan too, and by a usable amount.+ const windowAfterFlick = rowWindow();+ wheel({ deltaY: 3, deltaMode: 1 });+ await waitFor(() => expect(rowWindow()).not.toBe(windowAfterFlick));+ await expect(rowHeight()).toBe(heightBefore);+// A pinch carries ctrlKey, and that zooms.wheel({ deltaY: -40, ctrlKey: true });await waitFor(() => expect(rowHeight()).not.toBe(heightBefore));},});+/**+ * Relative luminance of ANY css colour, via a painted pixel. Parsing the computed+ * string would not do: Chrome returns `oklch(...)` verbatim for the tokens+ * authored in it, and reading those numbers as R, G, B turns a mid-tone into+ * near-black — which is exactly the bug this test exists to catch.+ *+ * Deliberately NOT `luminanceOf` from `barContrast.ts`, which is the function the+ * component picks its tone with. A test that measures with the same function the+ * subject decides with cannot see that function being wrong: both sides would+ * move together and an unreadable label would pass. Keep this arm's length —+ * these are two implementations of a fixed published formula, on purpose.+ */+const luminance = (colour: string) => {+ const context = document.createElement("canvas").getContext("2d");+ if (!context) throw new Error("no 2d context to measure a colour with");+ context.fillStyle = colour;+ context.fillRect(0, 0, 1, 1);+ const [r = 0, g = 0, b = 0] = context.getImageData(0, 0, 1, 1).data;+ const channel = (value: number) => {+ const c = value / 255;+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;+ };+ return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);+};++export const LabelsStayReadableOnBars = meta.story({+ name: "(Test) Labels Stay Readable On Bars",+ args: {+ roots: threeSpans(),+ box: DESKTOP,+ gutter: "auto",+ pointer: "fine",+ barColor: "type",+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ },+ play: async ({ canvasElement }) => {+ const labels = [+ ...canvasElement.querySelectorAll<HTMLElement>(+ '[data-testid="timeline-dense-duration"][data-placement="inside"]',+ ),+ ];+ // A wide box makes the bars wide enough to hold their own labels, which is+ // the case that has to be legible: the type palette runs from pastels to+ // 600s, so no single text colour works on all of it.+ await expect(labels.length).toBeGreaterThan(0);++ for (const label of labels) {+ // The label draws straight on the bar — no chip of page-coloured ground,+ // which read as a hole punched in the bar.+ await expect(getComputedStyle(label).backgroundColor).toMatch(+ /rgba\(0, 0, 0, 0\)|transparent/,+ );++ // 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"]',+ );+ 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);+ // Light bar → dark text, dark bar → light text. Either way the two must+ // land on opposite sides of the crossover.+ if (barLuminance > 0.179) {+ await expect(textLuminance).toBeLessThan(barLuminance);+ } else {+ await expect(textLuminance).toBeGreaterThan(barLuminance);+ }+ }+ },+});++export const LabelsKeepTheirDistance = meta.story({+ name: "(Test) Labels Keep Their Distance",+ args: {+ // A long tail puts its real work hard against the right edge, which is the+ // only way a duration label ends up on the LEFT of its bar.+ roots: longTailTrace(),+ box: DESKTOP,+ gutter: "auto",+ pointer: "fine",+ barColor: "type",+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ },+ play: async ({ canvasElement }) => {+ const labels = [+ ...canvasElement.querySelectorAll<HTMLElement>(+ '[data-testid="timeline-dense-duration"]',+ ),+ ].filter((label) => label.dataset.placement !== "inside");+ await expect(labels.length).toBeGreaterThan(0);++ let sawBefore = false;+ for (const label of labels) {+ const bar = label.parentElement?.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-bar"]',+ );+ if (!bar) continue;+ const l = label.getBoundingClientRect();+ const b = bar.getBoundingClientRect();+ const before = label.dataset.placement === "before";+ sawBefore = sawBefore || before;+ // The SAME gap on either side. A `before` label positioned from its left+ // edge (`x - gap - measuredWidth`) spends any under-measure out of the gap+ // and ends up flush against the bar; anchored by its right edge it cannot.+ const gap = before ? b.left - l.right : l.left - b.right;+ await expect(gap).toBeCloseTo(6, 0);+ }+ // The fixture has to actually exercise the left side, or this guards nothing.+ await expect(sawBefore).toBe(true);+ },+});++export const TooltipShowsCostAndTokens = meta.story({+ name: "(Test) Tooltip Shows Cost And Tokens",+ args: {+ roots: manySpans(40),+ box: PHONE,+ gutter: "auto",+ pointer: "fine",+ barColor: "type",+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ factsOf: () => ["$0.006425", "2,100 → 380 (∑ 2,480)"],+ },+ play: async ({ canvasElement }) => {+ 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.7,+ clientY: rect.top + rect.height * 0.4,+ }),+ );++ const tooltip = () =>+ canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-tooltip"]',+ );+ await waitFor(() => expect(tooltip()).not.toBeNull());+ const box = tooltip()!;++ // 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.+ const name = box.querySelector<HTMLElement>("span[title]");+ if (!name) throw new Error("no name in the tooltip");+ await expect(name.getBoundingClientRect().width).toBeGreaterThan(20);+ await expect(name.innerText.length).toBeGreaterThan(0);++ // Still nothing to scroll: the tooltip is clamped to the space it has.+ await expect(surface.scrollWidth).toBeLessThanOrEqual(surface.clientWidth);+ await expect(surface.scrollHeight).toBeLessThanOrEqual(+ surface.clientHeight,+ );+ },+});++export const ZoomLandsOnContent = meta.story({+ name: "(Test) Zoom Lands On Content",+ args: {+ // A long tail: the spans are all in a sliver of the wall clock, so zooming+ // the middle of the box is exactly where the two axes come apart.+ roots: longTailTrace(),+ box: PHONE,+ gutter: "auto",+ pointer: "fine",+ barColor: "type",+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ },+ play: async ({ canvasElement }) => {+ const surface = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-surface"]',+ );+ if (!surface) throw new Error("dense surface not found");+ const bars = () =>+ canvasElement.querySelectorAll('[data-testid="timeline-dense-bar"]')+ .length;+ const readout = () =>+ canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-readout"]',+ )?.textContent ?? "";++ await expect(bars()).toBeGreaterThan(0);+ const rect = surface.getBoundingClientRect();+ // Zoom hard, about the middle of the box — the point most likely to be empty.+ for (let step = 0; step < 6; step++) {+ surface.dispatchEvent(+ new WheelEvent("wheel", {+ bubbles: true,+ cancelable: true,+ ctrlKey: true,+ deltaY: -40,+ clientX: rect.left + rect.width / 2,+ clientY: rect.top + rect.height / 2,+ }),+ );+ }+ await waitFor(() => expect(readout()).toContain("zoomed"));++ // Zooming in must never end up looking at nothing. The rows and the clock are+ // only correlated, so the window follows the rows when they part company.+ await expect(bars()).toBeGreaterThan(0);+ },+});+export const HoverPeeksTheNames = meta.story({name: "(Test) Hover Peeks The Names",args: {@@ -289,6 +598,9 @@ export const HoverPeeksTheNames = meta.story({barColor: "type",compress: false,showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),},play: async ({ canvasElement }) => {const surface = canvasElement.querySelector<HTMLElement>(@@ -350,6 +662,9 @@ export const DoubleClickFocusesBothAxes = meta.story({barColor: "neutral",compress: false,showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),},play: async ({ canvasElement }) => {const readout = () =>@@ -375,6 +690,710 @@ export const DoubleClickFocusesBothAxes = meta.story({},});+/** Pre-order DFS, the order `prepareTimeline` flattens rows in. */+const lastRowId = (roots: ReturnType<typeof manySpans>): string => {+ let last = "";+ const stack = [...roots].reverse();+ while (stack.length > 0) {+ const node = stack.pop();+ if (!node) break;+ last = node.id;+ stack.push(...[...node.children].reverse());+ }+ return last;+};++const DEEP_TRACE = manySpans(3000);++export const ExternalSelectionIsRevealed = meta.story({+ name: "(Test) External Selection Is Revealed",+ args: {+ roots: DEEP_TRACE,+ // The tree, a search hit or a deep link can select any row at all — here the+ // very last one, thousands of rows below the window this box can hold.+ selectedId: lastRowId(DEEP_TRACE),+ box: PHONE,+ gutter: "auto",+ pointer: "fine",+ barColor: "type",+ compress: false,+ showReadout: true,+ onSelect: fn(),+ onHover: fn(),+ },+ play: async ({ canvasElement }) => {+ const rows = () =>+ canvasElement.querySelector<HTMLElement>('[data-testid="dense-rows"]')+ ?.textContent ?? "";++ // A highlight you cannot see is not a highlight: the window has to come to+ // the selection, all the way down at row 2999 of 3000.+ await waitFor(() => expect(rows()).toContain("of 3000"));+ const window = /rows ([\d.]+)[–-]([\d.]+)/.exec(rows());+ if (!window) throw new Error(`no row window in "${rows()}"`);+ await expect(Number(window[1])).toBeGreaterThan(2_000);+ // Revealed by PANNING: 600 rows of window before and after, because bringing+ // a row into view is not a request to change how far in you are looking.+ await expect(Number(window[2]) - Number(window[1])).toBeCloseTo(600, 1);++ // And the selected row really is drawn, highlighted, inside the box.+ const selected = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-content"] > div.bg-primary-accent\\/20',+ );+ await expect(selected).not.toBeNull();+ const surface = canvasElement+ .querySelector('[data-testid="timeline-dense-surface"]')+ ?.getBoundingClientRect();+ const row = selected?.getBoundingClientRect();+ if (!surface || !row) throw new Error("no surface or selected row");+ await expect(row.top).toBeGreaterThanOrEqual(surface.top - 0.5);+ await expect(row.bottom).toBeLessThanOrEqual(surface.bottom + 0.5);+ },+});++export const ShiftDragZoomsToABox = meta.story({+ name: "(Test) Shift Drag Zooms To A Box",+ args: {+ roots: manySpans(3000),+ box: PHONE,+ gutter: "auto",+ pointer: "fine",+ barColor: "type",+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ },+ play: async ({ canvasElement }) => {+ const surface = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-surface"]',+ );+ if (!surface) throw new Error("dense surface not found");+ surface.setPointerCapture = () => undefined;+ surface.releasePointerCapture = () => undefined;+ const readout = () =>+ canvasElement.querySelector<HTMLElement>('[data-testid="dense-rows"]')+ ?.textContent ?? "";+ const marquee = () =>+ canvasElement.querySelector('[data-testid="timeline-dense-marquee"]');++ const rect = surface.getBoundingClientRect();+ const at = (fx: number, fy: number) => ({+ clientX: rect.left + rect.width * fx,+ clientY: rect.top + rect.height * fy,+ });+ const send = (type: string, point: ReturnType<typeof at>, shift = true) =>+ surface.dispatchEvent(+ new PointerEvent(type, {+ bubbles: true,+ cancelable: true,+ pointerId: 1,+ pointerType: "mouse",+ shiftKey: shift,+ ...point,+ }),+ );++ const before = readout();+ send("pointerdown", at(0.3, 0.3));+ send("pointermove", at(0.7, 0.5));+ // The box is visible while you draw it — a zoom you cannot aim is a guess.+ await waitFor(() => expect(marquee()).not.toBeNull());+ send("pointerup", at(0.7, 0.5));++ // Releasing flies to exactly that region: a fifth of the rows, and the rows+ // grow to match. Both axes come from the box, nothing is inferred.+ await waitFor(() => expect(marquee()).toBeNull());+ await waitFor(() => expect(readout()).not.toBe(before));+ // It FLIES there, so this is the landing rather than the first frame.+ const rowSpan = () => {+ const window = /rows ([\d.]+)[–-]([\d.]+)/.exec(readout());+ if (!window) throw new Error(`no row window in "${readout()}"`);+ return Number(window[2]) - Number(window[1]);+ };+ await waitFor(() => expect(rowSpan()).toBeCloseTo(120, 0));++ // A stray shift-click is not a zoom to a pinhole.+ const settled = readout();+ send("pointerdown", at(0.5, 0.5));+ send("pointermove", at(0.502, 0.502));+ send("pointerup", at(0.502, 0.502));+ await expect(readout()).toBe(settled);+ },+});++export const AGestureTakesOverFromAFlight = meta.story({+ name: "(Test) A Gesture Takes Over From A Flight",+ args: {+ roots: manySpans(150),+ box: PHONE,+ gutter: "auto",+ pointer: "fine",+ barColor: "type",+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ },+ play: async ({ canvasElement }) => {+ const readout = () =>+ canvasElement.querySelector<HTMLElement>(+ '[data-testid="dense-rowheight"]',+ )?.textContent ?? "";++ const row = canvasElement.querySelectorAll<HTMLElement>(+ '[data-testid="timeline-dense-content"] > div',+ )[40];+ if (!row) throw new Error("expected a row to double-click");++ // Start the 320ms focus flight, then immediately zoom out with the toolbar.+ row.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));+ const zoomOut = canvasElement.querySelector<HTMLElement>(+ 'button[aria-label="Zoom out"]',+ );+ if (!zoomOut) throw new Error("no zoom-out button");+ zoomOut.click();+ const afterGesture = readout();++ // The flight must not keep writing its own target over the gesture for the+ // rest of its 320ms: settle, then check nothing moved after the click.+ await new Promise((resolve) => setTimeout(resolve, 500));+ await expect(readout()).toBe(afterGesture);+ // And it did not land on the focus target (a human-height row).+ await expect(readout()).not.toContain("26.0px");+ },+});++/** Two fingers on the surface, as a touchscreen delivers them. */+const touch = (+ element: HTMLElement,+ type: string,+ pointerId: number,+ x: number,+ y: number,+) =>+ element.dispatchEvent(+ new PointerEvent(type, {+ bubbles: true,+ cancelable: true,+ pointerId,+ pointerType: "touch",+ isPrimary: pointerId === 1,+ // A live contact reports a pressed button; a release reports none. The+ // renderer uses that to drop pointers whose release never arrived.+ buttons: type === "pointerup" || type === "pointercancel" ? 0 : 1,+ clientX: x,+ clientY: y,+ }),+ );++export const PinchZoomsOnTouch = meta.story({+ name: "(Test) Pinch Zooms On Touch",+ args: {+ roots: manySpans(600),+ box: PHONE,+ gutter: "auto",+ pointer: "coarse",+ barColor: "type",+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ },+ play: async ({ canvasElement }) => {+ const surface = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-surface"]',+ );+ if (!surface) throw new Error("dense surface not found");+ surface.setPointerCapture = () => undefined;+ surface.releasePointerCapture = () => undefined;+ const rowHeight = () =>+ canvasElement.querySelector<HTMLElement>(+ '[data-testid="dense-rowheight"]',+ )?.textContent ?? "";+ const rowWindow = () =>+ canvasElement.querySelector<HTMLElement>('[data-testid="dense-rows"]')+ ?.textContent ?? "";++ const rect = surface.getBoundingClientRect();+ const midX = rect.left + rect.width / 2;+ const midY = rect.top + rect.height / 2;++ // A touchscreen pinch is two pointers — never a wheel — and `touch-action:+ // none` means the browser will not zoom the page either. With one-pointer+ // logic only, this did nothing at all.+ await expect(rowHeight()).toContain("1.0px");+ touch(surface, "pointerdown", 1, midX - 40, midY - 40);+ touch(surface, "pointerdown", 2, midX + 40, midY + 40);+ for (const spread of [60, 90, 120, 150]) {+ touch(surface, "pointermove", 1, midX - spread, midY - spread);+ touch(surface, "pointermove", 2, midX + spread, midY + spread);+ }+ await waitFor(() => expect(rowHeight()).not.toContain("1.0px"));++ // Fingers apart = zoomed in: taller rows AND a narrower row window.+ const zoomed = rowWindow();+ const span = /rows ([\d.]+)[–-]([\d.]+)/.exec(zoomed);+ if (!span) throw new Error(`no row window in "${zoomed}"`);+ await expect(Number(span[2]) - Number(span[1])).toBeLessThan(600);++ // Lifting one finger hands over to a one-finger pan from where THAT finger+ // is. Inheriting the departed finger's origin panned by the whole finger+ // separation on the survivor's next small move.+ touch(surface, "pointerup", 2, midX + 150, midY + 150);+ const settled = rowWindow();+ touch(surface, "pointermove", 1, midX - 149, midY - 149);+ await expect(rowWindow()).toBe(settled);+ touch(surface, "pointerup", 1, midX - 149, midY - 149);++ // And pinching back in returns to the floor rather than sticking.+ touch(surface, "pointerdown", 1, midX - 150, midY - 150);+ touch(surface, "pointerdown", 2, midX + 150, midY + 150);+ for (const spread of [110, 70, 40, 15]) {+ touch(surface, "pointermove", 1, midX - spread, midY - spread);+ touch(surface, "pointermove", 2, midX + spread, midY + spread);+ }+ await waitFor(() => expect(rowHeight()).toContain("1.0px"));+ },+});++export const DoubleTapFocusesOnTouch = meta.story({+ name: "(Test) Double Tap Focuses On Touch",+ args: {+ roots: manySpans(150),+ box: PHONE,+ gutter: "auto",+ pointer: "coarse",+ barColor: "type",+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ },+ play: async ({ canvasElement }) => {+ const surface = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-surface"]',+ );+ if (!surface) throw new Error("dense surface not found");+ surface.setPointerCapture = () => undefined;+ surface.releasePointerCapture = () => undefined;+ const readout = () =>+ canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-readout"]',+ )?.textContent ?? "";++ const rect = surface.getBoundingClientRect();+ const x = rect.left + rect.width * 0.6;+ const y = rect.top + 200;++ await expect(readout()).toContain("fitted");+ // `dblclick` is not dependable from touch — Safari does not synthesise it —+ // so two quick taps in the same place are detected here instead.+ for (const _ of [1, 2]) {+ touch(surface, "pointerdown", 1, x, y);+ touch(surface, "pointerup", 1, x, y);+ }+ await waitFor(() => expect(readout()).toContain("zoomed"));+ await waitFor(() => expect(readout()).toContain("26.0px rows"));+ },+});++/**+ * Opening and closing the names is two taps in the same place, inside the+ * double-tap window — and it used to also fly the viewport to whatever row the+ * second tap landed on, because the rail tap returned early without ever marking+ * itself as spent.+ */+export const RailTapsAreNotADoubleTap = meta.story({+ name: "(Test) Rail Taps Are Not A Double Tap",+ args: {+ // Tall enough rows that the rail exists to be tapped.+ roots: manySpans(40),+ box: PHONE,+ gutter: "auto",+ pointer: "coarse",+ barColor: "type",+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ },+ play: async ({ canvasElement }) => {+ const surface = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-surface"]',+ );+ if (!surface) throw new Error("dense surface not found");+ surface.setPointerCapture = () => undefined;+ surface.releasePointerCapture = () => undefined;+ const readout = () =>+ canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-readout"]',+ )?.textContent ?? "";+ const names = () =>+ canvasElement.querySelectorAll(+ '[data-testid="timeline-dense-peek"] span[title], [data-testid="timeline-dense-content"] > div span[title]',+ ).length;++ const rect = surface.getBoundingClientRect();+ const x = rect.left + 4;+ const y = rect.top + 200;+ await expect(readout()).toContain("fitted");++ // Open, then close — one frame apart, which is how a real pair arrives: far+ // enough for the toggle to see its own new state, far INSIDE the double-tap+ // window. Dispatching both in one microtask tests neither, because React has+ // not re-rendered and both taps read the same `isOpen`.+ const frame = () =>+ new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+ touch(surface, "pointerdown", 1, x, y);+ touch(surface, "pointerup", 1, x, y);+ await waitFor(() => expect(names()).toBeGreaterThan(0));+ await frame();+ touch(surface, "pointerdown", 1, x, y);+ touch(surface, "pointerup", 1, x, y);+ await waitFor(() => expect(names()).toBe(0));++ // Then a SINGLE tap in the chart, still inside the window. One tap is one+ // tap: it only looked like the second half of a double-tap because the rail's+ // release had recorded a tap it should never have recorded. This has to come+ // before the wait below, or the wait itself pushes it out of the window and+ // the sequence goes untested.+ await frame();+ touch(surface, "pointerdown", 1, rect.left + rect.width * 0.6, y);+ touch(surface, "pointerup", 1, rect.left + rect.width * 0.6, y);++ // "Nothing flew" has to outlast the flight, or it passes by being early — as+ // this assertion did at first, which made it green against the bug.+ let flew = false;+ try {+ await waitFor(() => expect(readout()).toContain("zoomed"), {+ timeout: 600,+ });+ flew = true;+ } catch {+ // Never zoomed inside a window longer than the 320ms flight: correct.+ }+ await expect(flew).toBe(false);+ },+});++export const TooltipFollowsTheContent = meta.story({+ name: "(Test) Tooltip Follows The Content",+ args: {+ roots: DEEP_TRACE,+ box: PHONE,+ gutter: "auto",+ pointer: "fine",+ barColor: "type",+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ },+ play: async ({ args, canvasElement }) => {+ const surface = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-surface"]',+ );+ if (!surface) throw new Error("dense surface not found");+ const tooltip = () =>+ canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-tooltip"]',+ )?.textContent ?? "";++ const rect = surface.getBoundingClientRect();+ surface.dispatchEvent(+ new PointerEvent("pointermove", {+ bubbles: true,+ pointerType: "mouse",+ clientX: rect.left + rect.width * 0.6,+ clientY: rect.top + 300,+ }),+ );+ await waitFor(() => expect(tooltip()).not.toBe(""));+ const named = tooltip();++ // Scrolling moves the rows under a pointer that has not moved. The tooltip+ // names whatever is under the pointer NOW — holding the row that used to be+ // there is how it ends up describing something else entirely.+ surface.dispatchEvent(+ new WheelEvent("wheel", {+ bubbles: true,+ cancelable: true,+ deltaY: 240,+ clientX: rect.left + rect.width * 0.6,+ clientY: rect.top + 300,+ }),+ );+ await waitFor(() => expect(tooltip()).not.toBe(named));+ await expect(tooltip()).not.toBe("");++ // The caller prefetches off `onHover`, so it has to hear about the row that+ // arrived under the still pointer. Firing only on pointermove meant the row+ // being read was the one row never fetched ahead: the tooltip renamed itself+ // and the callback went on naming the row that used to be there.+ const hovered = args.onHover as ReturnType<typeof fn>;+ const ids = hovered.mock.calls.map((call) => call[0] as string);+ await expect(ids.length).toBeGreaterThan(1);+ await expect(ids[ids.length - 1]).not.toBe(ids[0]);+ },+});++/** A playhead a story can drive by hand, standing in for the shared engine. */+function makeFakePlayhead() {+ let sec = 0;+ const listeners = new Set<(next: number) => void>();+ return {+ onSeek: fn(),+ playhead: {+ visible: true,+ getSec: () => sec,+ subscribe: (listener: (next: number) => void) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ onSeek: (next: number) => PLAYBACK.onSeek(next),+ },+ tick(next: number) {+ sec = next;+ for (const listener of listeners) listener(next);+ },+ };+}+const PLAYBACK = makeFakePlayhead();++export const PlaybackSweepsAndGlows = meta.story({+ name: "(Test) Playback Sweeps And Glows",+ args: {+ roots: manySpans(150),+ box: PHONE,+ gutter: "auto",+ pointer: "fine",+ barColor: "type",+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ // The root span of manySpans covers the whole trace, so it is "playing"+ // throughout — the simplest thing a glow can be asserted against.+ activeIds: new Set(["n0"]),+ playhead: PLAYBACK.playhead,+ },+ play: async ({ canvasElement }) => {+ const line = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-playhead"]',+ );+ if (!line) throw new Error("no playhead line");++ // It starts at the origin and is moved by the position feed, not by a+ // re-render: 600 rows must not re-render to move a 2px line.+ await expect(line.style.transform).toBe("translateX(0px)");+ PLAYBACK.tick(12);+ await waitFor(() =>+ expect(line.style.transform).not.toBe("translateX(0px)"),+ );++ // The rows the playhead is over glow up — never the others dimming down.+ const glowing = canvasElement.querySelectorAll(+ '[data-testid="timeline-dense-content"] > div.bg-primary\\/20',+ );+ await expect(glowing.length).toBe(1);++ // And the axis is the scrub track: press it to place the playhead.+ const axis = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-axis"]',+ );+ if (!axis) throw new Error("no axis");+ const axisRect = axis.getBoundingClientRect();+ axis.setPointerCapture = () => undefined;+ axis.dispatchEvent(+ new PointerEvent("pointerdown", {+ bubbles: true,+ pointerId: 1,+ clientX: axisRect.left + axisRect.width / 2,+ clientY: axisRect.top + 8,+ }),+ );+ await expect(PLAYBACK.onSeek).toHaveBeenCalled();+ },+});++/** A selection whose row arrives late, as a deep link's does. */+function WithLateRows(props: TimelineDenseProps) {+ const [roots, setRoots] = useState<TimelineDenseProps["roots"]>([]);+ return (+ <div className="flex flex-col items-start gap-1">+ <button type="button" onClick={() => setRoots(props.roots)}>+ load rows+ </button>+ <TimelineDense {...props} roots={roots} />+ </div>+ );+}++/**+ * The names floating over the chart are the SAME rows as the chart's. Where the+ * gutter is only a rail, peeking is the one way to read a name during playback —+ * and the peek kept its own copy of the row backgrounds, which knew about+ * selection and hover but had never heard of playback: the row that was playing+ * glowed in the chart and stayed plain in the names beside it.+ */+export const ThePeekGlowsWithThePlayingRow = meta.story({+ name: "(Test) The Peek Glows With The Playing Row",+ args: {+ // 40 rows in this box are 15px: too short to hold a name in flow, tall+ // enough that the rail exists to peek at. At the 1px floor there is no rail+ // by design, so there would be nothing to hover.+ roots: manySpans(40),+ box: PHONE,+ gutter: "auto",+ pointer: "fine",+ barColor: "type",+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ // The root covers the whole trace, so it plays throughout.+ activeIds: new Set(["n0"]),+ playhead: PLAYBACK.playhead,+ },+ play: async ({ canvasElement }) => {+ 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 + 4,+ // Well away from the playing row, so the hover wash cannot stand in for+ // the glow this is looking for.+ clientY: rect.top + 200,+ }),+ );+ const peek = await waitFor(() => {+ const el = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-peek"]',+ );+ if (!el) throw new Error("the rail did not peek");+ return el;+ });+ await expect(peek.querySelectorAll("div.bg-primary\\/20").length).toBe(1);+ },+});++export const ALateRowIsStillRevealed = meta.story({+ name: "(Test) A Late Row Is Still Revealed",+ args: {+ roots: DEEP_TRACE,+ selectedId: lastRowId(DEEP_TRACE),+ box: PHONE,+ gutter: "auto",+ pointer: "fine",+ barColor: "type",+ compress: false,+ showReadout: true,+ onSelect: fn(),+ onHover: fn(),+ },+ render: (args) => <WithLateRows {...args} />,+ play: async ({ canvasElement }) => {+ const rows = () =>+ canvasElement.querySelector<HTMLElement>('[data-testid="dense-rows"]')+ ?.textContent ?? "";++ // The selection is set before its row exists — a deep link naming an+ // observation fetched by id, or one past the load cap.+ await waitFor(() => expect(rows()).toContain("of 0"));+ const load = canvasElement.querySelector("button");+ if (!load) throw new Error("expected the load button");+ await userEvent.click(load);++ // Spending the one reveal on the absent row left the highlight off-screen+ // forever; un-advanced, the render that brings the rows retries.+ await waitFor(() => expect(rows()).toContain("of 3000"));+ await waitFor(() => {+ const window = /rows ([\d.]+)[–-]([\d.]+)/.exec(rows());+ if (!window) throw new Error(`no row window in "${rows()}"`);+ expect(Number(window[1])).toBeGreaterThan(2_000);+ });+ },+});++export const DoubleClickSelectsOnce = meta.story({+ name: "(Test) Double Click Selects Once",+ args: {+ roots: manySpans(150),+ box: PHONE,+ gutter: "auto",+ pointer: "fine",+ barColor: "neutral",+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ },+ play: async ({ canvasElement, args }) => {+ const row = canvasElement.querySelectorAll<HTMLElement>(+ '[data-testid="timeline-dense-content"] > div',+ )[40];+ if (!row) throw new Error("expected a row to double-click");++ // A double-click delivers two clicks and then dblclick. Selecting is not+ // free — it captures analytics and reopens the detail panel — so it must+ // happen exactly once, not three times.+ for (const detail of [1, 2]) {+ row.dispatchEvent(new MouseEvent("click", { bubbles: true, detail }));+ }+ row.dispatchEvent(new MouseEvent("dblclick", { bubbles: true, detail: 2 }));++ await expect(args.onSelect).toHaveBeenCalledTimes(1);+ },+});++export const TypeSquareStaysInsideTheRail = meta.story({+ name: "(Test) Type Square Stays Inside The Rail",+ args: {+ roots: deepNesting(12),+ box: PHONE,+ gutter: "auto",+ pointer: "fine",+ barColor: "type",+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ },+ play: async ({ canvasElement }) => {+ const squares = canvasElement.querySelectorAll<HTMLElement>(+ '[data-testid="timeline-dense-type-square"]',+ );+ // A closed rail has exactly one type indicator per row, so it cannot be the+ // part that gets clipped: at 10px wide, a depth-4 span's square hung most of+ // the way out of the rail's overflow-hidden box and showed as a sliver.+ await expect(squares.length).toBeGreaterThan(4);+ for (const square of squares) {+ const rail = square.parentElement?.getBoundingClientRect();+ const box = square.getBoundingClientRect();+ if (!rail) throw new Error("square without a rail");+ await expect(box.width).toBeGreaterThanOrEqual(2);+ await expect(box.left).toBeGreaterThanOrEqual(rail.left - 0.5);+ await expect(box.right).toBeLessThanOrEqual(rail.right + 0.5);+ }+ },+});+export const HoverOpensATooltip = meta.story({name: "(Test) Hover Opens A Tooltip",args: {@@ -385,6 +1404,9 @@ export const HoverOpensATooltip = meta.story({barColor: "neutral",compress: false,showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),},play: async ({ canvasElement }) => {const surface = canvasElement.querySelector<HTMLElement>(@@ -421,3 +1443,164 @@ export const HoverOpensATooltip = meta.story({);},});++/**+ * A tree's lines have to meet. The open gutter caps how deep it will indent — a+ * 1401-deep chain would otherwise push every name out of the box — and past that+ * cap a parent and its child flatten to the SAME indent. The connector was still+ * drawn one indent to the left of where the parent's spine actually descends, so+ * every generation past the cap hung off nothing.+ */+export const DeepConnectorsStillMeet = meta.story({+ name: "(Test) Deep Connectors Still Meet",+ args: {+ // Deeper than any gutter this narrow can indent, so the tail is flattened.+ roots: deepNesting(12),+ box: PHONE,+ gutter: "expanded",+ pointer: "fine",+ barColor: "type",+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ },+ play: async ({ canvasElement }) => {+ const rows = [+ ...canvasElement.querySelectorAll<HTMLElement>(+ '[data-testid="timeline-dense-content"] > div',+ ),+ ];+ await expect(rows.length).toBeGreaterThan(8);++ // A chain, so the row above is the parent: where a row's own spine descends+ // is exactly where its child's connector must rise to.+ const spineOf = (row: HTMLElement) =>+ row.querySelector<HTMLElement>('div[class*="bottom-0"][class*="w-px"]');+ const stubOf = (row: HTMLElement) =>+ row.querySelector<HTMLElement>('div[class*="top-0"][class*="w-px"]');++ let checked = 0;+ for (let index = 1; index < rows.length; index++) {+ const parentSpine = spineOf(rows[index - 1]!);+ const stub = stubOf(rows[index]!);+ if (!parentSpine || !stub) continue;+ await expect(stub.getBoundingClientRect().left).toBeCloseTo(+ parentSpine.getBoundingClientRect().left,+ 0,+ );+ checked++;+ }+ // Including the flattened tail, which is where this used to break.+ await expect(checked).toBeGreaterThan(6);+ },+});++/**+ * At hairline density the left side takes no width at all, so there is no rail to+ * tap — and a tap in the leftmost few px used to set the names override anyway.+ * Nothing happened, visibly: the override sat there until a double-tap zoomed the+ * rows tall enough to honour it, and then the names sprang open on their own.+ */+export const AHairlineTapDoesNotArmTheNames = meta.story({+ name: "(Test) A Hairline Tap Does Not Arm The Names",+ args: {+ roots: manySpans(600),+ box: PHONE,+ gutter: "auto",+ pointer: "coarse",+ barColor: "type",+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ },+ play: async ({ canvasElement }) => {+ const surface = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-surface"]',+ );+ if (!surface) throw new Error("dense surface not found");+ surface.setPointerCapture = () => undefined;+ surface.releasePointerCapture = () => undefined;+ const readout = () =>+ canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-readout"]',+ )?.textContent ?? "";+ const names = () =>+ canvasElement.querySelectorAll(+ '[data-testid="timeline-dense-peek"] span[title], [data-testid="timeline-dense-content"] > div span[title]',+ ).length;++ const rect = surface.getBoundingClientRect();+ // 600 rows in 600px: 1px each, no rail, nothing on the left to tap.+ await expect(readout()).toContain("1.0px rows");+ touch(surface, "pointerdown", 1, rect.left + 2, rect.top + 200);+ touch(surface, "pointerup", 1, rect.left + 2, rect.top + 200);+ await expect(names()).toBe(0);++ // Now zoom in far enough that rows COULD hold a name. Nothing asked for them.+ const x = rect.left + rect.width * 0.6;+ const y = rect.top + 200;+ for (const _ of [1, 2]) {+ touch(surface, "pointerdown", 1, x, y);+ touch(surface, "pointerup", 1, x, y);+ }+ await waitFor(() => expect(readout()).toContain("26.0px rows"));+ await expect(names()).toBe(0);+ },+});++/**+ * A double-tap to focus must select once, like a double-click does. `event.detail`+ * cannot tell: WebKit neither synthesises `dblclick` from taps nor counts them, so+ * both taps arrive as an ordinary first click and a detail-based guard sees+ * nothing. Selecting twice is not free — it captures an analytics event and+ * reopens the detail panel.+ */+export const ADoubleTapSelectsOnce = meta.story({+ name: "(Test) A Double Tap Selects Once",+ args: {+ roots: manySpans(40),+ box: PHONE,+ gutter: "auto",+ pointer: "coarse",+ barColor: "type",+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ },+ play: async ({ args, canvasElement }) => {+ const surface = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-surface"]',+ );+ if (!surface) throw new Error("dense surface not found");+ surface.setPointerCapture = () => undefined;+ surface.releasePointerCapture = () => undefined;+ const rect = surface.getBoundingClientRect();+ const x = rect.left + rect.width * 0.6;+ const y = rect.top + 200;+ const row = document.elementFromPoint(x, y)?.closest("div");+ if (!row) throw new Error("no row under the tap");++ for (const _ of [1, 2]) {+ touch(surface, "pointerdown", 1, x, y);+ touch(surface, "pointerup", 1, x, y);+ // The compatibility click a tap produces: first-click detail, every time.+ row.dispatchEvent(+ new MouseEvent("click", {+ bubbles: true,+ cancelable: true,+ detail: 1,+ clientX: x,+ clientY: y,+ }),+ );+ }+ const onSelect = args.onSelect as ReturnType<typeof fn>;+ await expect(onSelect.mock.calls.length).toBe(1);+ },+});diff --git a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsxindex 7d9ab647d4..5befcf8f50 100644--- a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx+++ b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx@@ -1,28 +1,40 @@/**- * Throwaway renderer for the extreme-density spike.+ * The Compact Timeline renderer, shipped behind the `compactTimeline` feature+ * preview: `TraceTimelineCompact` measures a box and renders this inside it, and+ * the trace panel's Timeline view is this whenever the preview is on — by+ * default for the team, opt-in for everyone else. Real users read traces through+ * it, so a bug here is a bug in the product.*- * The question it exists to answer: in a narrow, tall layout, does killing the- * names and the text and spending every pixel on shape make you FEEL the- * timeline — where a 26px row with a duration label next to a 4px bar reads as- * a list of numbers instead?+ * The question it started as a spike to answer, and still answers: in a narrow,+ * tall layout, does killing the names and the text and spending every pixel on+ * shape make you FEEL the timeline — where a 26px row with a duration label next+ * to a 4px bar reads as a list of numbers instead?** At rest: no name gutter, a 10px rail carrying type as a small square in the* type's own hue, rows shrunk to fit the box, and no text at all.** Then it is driven **like a map**, because that is what exploring a dense* surface wants:- * - The left side is adaptive: a bare colour rail by default, opening into the- * real tree gutter — the observation's own icon and name, indented by depth —- * as the rows grow past ~20px, and peekable earlier by hovering it (tapping it- * on touch). It cannot open below ~14px rows, because there is no name to show- * in a 4px row; the hover tooltip is what names a row at that density.- * Working in the chart hands the space straight back.- * - Two-finger scroll pans both axes; pinch (and a discrete mouse notch) zooms+ * - The left side follows one rule: if there is nothing to expand, it is not+ * shown. At bird's-eye density it takes no width at all — a 4px row cannot+ * hold a name, and a colour rail beside colour-coded bars is repetition. Once+ * the rows can hold a name it simply appears, if there is width for it; on a+ * phone or a peek panel, where there is not, the colour rail becomes the+ * affordance and a hover or a tap floats the names over the chart.+ * - Any wheel or two-finger scroll pans both axes; pinch and ⌘/ctrl + wheel zoom* BOTH axes about the cursor, so the time window narrows and the rows grow* together. Zoom is exponential in a zoom level and deltas accumulate per* frame, as in mapping libraries — see the rate constants below.- * - Drag pans both axes too. There are no scrollbars by design: a map has none,- * and the viewport clamps to the content so there is nowhere to get lost.+ * - Drag pans both axes too, and SHIFT-drag draws a box to zoom into — the one+ * gesture where the user has stated the window on both axes, so it goes+ * straight there. There are no scrollbars by design: a map has none, and the+ * viewport clamps to the content so there is nowhere to get lost.+ * - On a TOUCHSCREEN the same three gestures arrive as pointers rather than+ * wheels: two fingers pinch to zoom both axes about their midpoint and pan by+ * however far that midpoint travels, one finger pans, and a double-tap+ * focuses — `dblclick` is not dependable from touch. `touch-action: none`+ * stops the browser panning or zooming the page underneath, which also means+ * nothing else will handle a pinch: it is this component's job or nobody's.* - Double-click an element focuses it — the time window onto its own extent,* the rows at a height a human reads, the element centred.* - What a row shows follows from how tall it has become: the type square grows@@ -33,10 +45,9 @@* rest) is implemented and tested in fns/timeline/focusLens.ts and deliberately* NOT wired up: a fisheye needs an invertible transform to hit-test correctly,* and absolutely-positioned rows are the wrong substrate. That is the next spike.- *- * Not production code.*/+import { useTheme } from "next-themes";import {useCallback,useMemo,@@ -59,14 +70,17 @@ import {formatDurationMs,layout,prepareTimeline,+ spanOffsetsOf,timeCompressionFor,type LayoutNode,type PositionedNode,} from "../../fns/timeline/layout";import { createTextMeasurer } from "../../fns/timeline/textMeasurer";+import { resolveBarTones } from "../../fns/timeline/barContrast";import { traceSpaceOf, type Box } from "../../fns/timeline/viewTransform";import {HUMAN_ROW_HEIGHT,+ anchorTimeToRows,interpolateViewport,rowCountBounds,viewportsEqual,@@ -76,10 +90,13 @@ import {isViewportFitted,panViewport,presentationForRowHeight,+ revealViewport,rowHeightOf,rowIndexAtOffset,visibleRowRange,+ zoomToBox,zoomViewport,+ type RowExtent,type Viewport,} from "../../fns/timeline/viewport";@@ -97,12 +114,40 @@ const TYPE_COLOR: Record<string, string> = {GUARDRAIL: "bg-red-600",};const FALLBACK_COLOR = "bg-muted-gray";+/** Neutral mode's bar, and the accent a selected or hovered bar takes. */+const NEUTRAL_COLOR = "bg-muted-foreground/60";+const ACCENT_COLOR = "bg-primary-accent";+/** Every colour a bar can be — the set whose contrast has to be resolved. */+const BAR_COLORS = [+ ...Object.values(TYPE_COLOR),+ FALLBACK_COLOR,+ NEUTRAL_COLOR,+ ACCENT_COLOR,+];-const RAIL_WIDTH = 10;const RAIL_INDENT = 2;const RAIL_MAX_DEPTH = 4;+/** Biggest the closed rail's type square gets, however tall the row is. */+const RAIL_SQUARE_MAX = 5;+/**+ * Wide enough for the deepest indent plus the square, computed rather than+ * guessed: at 10px the square of a depth-4 span was mostly outside the rail's+ * overflow-hidden box, so the one type indicator a closed rail has left was+ * clipped to a sliver exactly on the deeply-nested spans.+ */+const RAIL_WIDTH = RAIL_MAX_DEPTH * RAIL_INDENT + RAIL_SQUARE_MAX + 2;/** Indent per level once the gutter is open, matching the production gutter. */-const GUTTER_INDENT = 10;+const GUTTER_INDENT = 14;+/** The ItemBadge box at `isSmall`, which is square. */+const GUTTER_ICON = 16;+/** A name needs at least this much to be worth indenting away from. */+const GUTTER_NAME_MIN = 48;+/**+ * Where a level's vertical rail sits: under the CENTRE of that level's icon, so+ * the spine reads as descending from the icon that owns it. Hugging the icon's+ * left edge instead left the elbow pointing at nothing in particular.+ */+const GUTTER_RAIL = GUTTER_ICON / 2;const TOOLBAR_HEIGHT = 22;const AXIS_HEIGHT = 16;const READOUT_HEIGHT = 18;@@ -117,17 +162,28 @@ const FRAME_BORDER = 1;* is why it felt like a lot of touching to get anywhere.*/const PINCH_ZOOM_RATE = 1 / 40;-const WHEEL_ZOOM_RATE = 1 / 160;-/** A deltaMode-0 event bigger than this is a mouse notch, not a trackpad. */-const WHEEL_DELTA_THRESHOLD = 40;+/** A line, for the browsers that report wheel deltas in lines rather than pixels. */+const WHEEL_LINE_PX = 16;/** Step for the toolbar buttons and the keyboard, in zoom levels. */const BUTTON_ZOOM_LEVELS = 0.6;const DRAG_THRESHOLD_PX = 3;const MAX_BAR_HEIGHT = 18;-/** Below this a row cannot hold a name, so the gutter stays a rail. */+/**+ * Below this a row cannot hold a name — and since a colour rail beside+ * colour-coded bars says nothing the bars have not already said, the whole left+ * side takes no width at all there. See `canShowNames` for the rule.+ */const NAME_MIN_ROW_HEIGHT = 14;-/** The chart never shrinks below this to make room for names. */+/** The chart never shrinks below this to make room for names, even if asked. */const MIN_LANE_WIDTH = 140;+/**+ * And it only VOLUNTEERS the gutter while the chart keeps this much. Two+ * thresholds, because "we opened it for you" and "you asked for it" deserve+ * different answers: on a phone, spending 136px of 360 on names by default+ * leaves the timeline too thin to read, so there the colour rail plus a tap is+ * the better trade.+ */+const AUTO_OPEN_MIN_LANE_WIDTH = 280;/*** A focus flies rather than teleports. An instant jump reads as "the bar I* clicked got bigger" — you cannot see that the window moved, especially when@@ -135,22 +191,24 @@ const MIN_LANE_WIDTH = 140;* same reason.*/const FOCUS_ANIMATION_MS = 320;-/** Slack around the rail so the peek zone is reachable at 10px wide. */+/** Slack around the rail so the peek zone is reachable at rail width. */const PEEK_MARGIN_PX = 6;+/** A collapsed-gap band narrower than this has no room to name itself. */+const GAP_LABEL_MIN_WIDTH = 14;+/** Below this in both axes a shift-drag was a stray click, not a box. */+const MARQUEE_MIN_PX = 6;+/** Two taps within this long, and this close, are one double-tap. */+const DOUBLE_TAP_MS = 320;+const DOUBLE_TAP_SLOP_PX = 24;-/**- * How wide the left side is once something has asked for it to open. The chart- * keeps priority: if opening would leave the lane below MIN_LANE_WIDTH it stays a- * rail, because the timeline is the point of the surface.- */-function resolveGutterWidth(input: {- open: boolean;- contentWidth: number;-}): number {- if (!input.open) return RAIL_WIDTH;- const wanted = Math.min(Math.max(input.contentWidth * 0.38, 96), 168);- return input.contentWidth - wanted >= MIN_LANE_WIDTH ? wanted : RAIL_WIDTH;-}+/** Anchor ratios are fractions of the box; a finger can leave it mid-gesture. */+const clampRatio = (value: number) =>+ Number.isFinite(value) ? Math.min(Math.max(value, 0), 1) : 0.5;++type MarqueeBox = {+ from: { x: number; y: number };+ to: { x: number; y: number };+};export type TimelineDenseProps = {roots: LayoutNode[];@@ -171,10 +229,67 @@ export type TimelineDenseProps = {barColor: "neutral" | "type";compress: boolean;showReadout: boolean;+ /**+ * Selection is CONTROLLED: the trace panel's other views select the same+ * observation, so this must not keep its own copy. See SelectionContext.+ */+ selectedId: string | null;+ onSelect: (nodeId: string) => void;+ /** Hover, for prefetching the observation the user is about to open. */+ onHover?: (nodeId: string) => void;+ /**+ * Ids playing at the playhead, glowed while playback runs. A crossing changes+ * the set, so this re-renders on boundaries only — never per frame.+ */+ activeIds?: ReadonlySet<string>;+ /**+ * Extra facts for the hover tooltip, already formatted — cost and token usage+ * live on the app's node, not on the layout contract, and their formatters+ * 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[];+ /**+ * 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+ * every size. Absent means there is no playback surface here.+ *+ * `subscribe` is the ~60fps position feed and drives the line imperatively —+ * a playhead that re-rendered 600 rows per frame would be a different kind of+ * broken.+ */+ playhead?: {+ visible: boolean;+ getSec: () => number;+ subscribe: (listener: (sec: number) => void) => () => void;+ /** Click or drag the axis to place it. */+ onSeek: (sec: number) => void;+ };};export type GutterMode = "auto" | "expanded" | "collapsed";+/**+ * What a row's background says about it. ONE decision, because two places draw a+ * row — the chart and the names floating over it — and a second copy is a second+ * chance to miss a state: the peek's copy only knew about selection and hover, so+ * during playback the row that was playing glowed in the chart and stayed plain+ * in the names right beside it.+ *+ * Playing rows glow UP rather than the others dimming down, which is the standing+ * rule for playback highlight here.+ */+function rowWashClass(state: {+ selected: boolean;+ focused: boolean;+ active: boolean;+}): string | false {+ if (state.selected) return "bg-primary-accent/20";+ if (state.focused) return "bg-primary-accent/15";+ // At 4px a tint is not enough to find yourself by, so these are full-width.+ return state.active && "bg-primary/20";+}+export function TimelineDense({roots,box,@@ -183,19 +298,55 @@ export function TimelineDense({barColor,compress,showReadout,+ selectedId,+ onSelect,+ onHover,+ activeIds,+ playhead,+ factsOf,}: TimelineDenseProps) {const [viewport, setViewport] = useState<Viewport | null>(null);- const [focusIndex, setFocusIndex] = useState<number | null>(null);const [pointerPos, setPointerPos] = useState<{ x: number; y: number } | null>(null,);- const [selectedIndex, setSelectedIndex] = useState<number | null>(null);const [dragging, setDragging] = useState(false);+ /**+ * Shift-drag box, in surface coordinates, while it is being drawn. The REF is+ * the authority and the state is only for drawing it: a gesture that read the+ * box back out of render scope would depend on React having re-rendered+ * between pointerdown and pointerup, which nothing guarantees.+ */+ const marqueeRef = useRef<MarqueeBox | null>(null);+ const [marquee, setMarquee] = useState<MarqueeBox | null>(null);+ const setMarqueeBox = (next: MarqueeBox | null) => {+ marqueeRef.current = next;+ setMarquee(next);+ };const prepared = useMemo(() => prepareTimeline(roots), [roots]);- // Rendered at 10px, so measured at 10px: layout() decides which side a label- // goes on, and that decision is only as good as the font it measured.- const measurer = useMemo(() => createTextMeasurer("10px ui-sans-serif"), []);+ // Measured in the font the labels ACTUALLY render in, read off a probe span+ // that carries their own size — `10px ui-sans-serif` is a guess, and the+ // canvas resolves it to a different face than the app's system stack, ~6px+ // narrow on a duration. layout() decides which side a label goes on, and that+ // decision is only as good as the font it measured.+ const [labelFont, setLabelFont] = useState<string | null>(null);+ const labelProbeRef = useCallback((element: HTMLSpanElement | null) => {+ if (!element) return;+ const style = getComputedStyle(element);+ const font = `${style.fontSize} ${style.fontFamily}`;+ setLabelFont((previous) => (previous === font ? previous : font));+ }, []);+ const measurer = useMemo(+ () => createTextMeasurer(labelFont ?? "10px ui-sans-serif"),+ [labelFont],+ );+ // Resolved per theme, because three of these colours flip lightness between+ // themes. `resolvedTheme` is the trigger; the probe is the answer.+ const { resolvedTheme } = useTheme();+ const barTones = useMemo(+ () => resolveBarTones(BAR_COLORS, { theme: resolvedTheme }),+ [resolvedTheme],+ );// A manual override lives until you touch the chart again, which is what// "expand to look, then get out of my way" means in practice.@@ -233,20 +384,38 @@ export function TimelineDense({// The left side is the key to the lines — the tree gutter, names and all. It// can only open when the rows are tall enough to hold a name: at 4px there is// no name to show, and the hover tooltip is what names a row at that density.+ /**+ * The left side follows one rule: **if there is nothing to expand, do not show+ * it.**+ *+ * At bird's-eye density a row cannot hold a name, so no amount of expanding+ * reveals anything — and the colour rail is pure repetition there, because the+ * bars already carry the type colour. So it takes no width at all and the whole+ * box is timeline.+ *+ * Once the rows CAN hold a name there are two cases. With width to spare, just+ * show the gutter — nothing is gained by making someone hover for something+ * that fits. Without it (a phone, a peek panel), keep the colour rail as the+ * affordance and let a hover or a tap float the names over the chart.+ */const canShowNames = liveRowHeight >= NAME_MIN_ROW_HEIGHT;+ const wantedGutter = Math.min(Math.max(contentWidth * 0.38, 96), 168);+ const asked = override === "expanded" || gutterMode === "expanded";+ const wantsOpen =+ override === "collapsed" ? false : asked || gutterMode === "auto";+ const gutterFits =+ contentWidth - wantedGutter >=+ (asked ? MIN_LANE_WIDTH : AUTO_OPEN_MIN_LANE_WIDTH);- // A COMMITTED open takes real space and re-lays out the chart, because you- // asked for it to stay. A PEEK must not: it floats over the timeline instead,- // so hovering the edge never shoves the bars sideways while you are reading- // them. Same content, different claim on the layout.- const committedOpen =- canShowNames &&- (override === "collapsed"- ? false- : override === "expanded" ||- gutterMode === "expanded" ||- (gutterMode === "auto" && liveRowHeight >= HUMAN_ROW_HEIGHT - 6));- const railWidth = resolveGutterWidth({ open: committedOpen, contentWidth });+ // A COMMITTED open takes real space and re-lays out the chart. A PEEK must+ // not: it floats over the timeline instead, so hovering the edge never shoves+ // the bars sideways while you are reading them.+ const committedOpen = canShowNames && gutterFits && wantsOpen;+ const railWidth = canShowNames+ ? committedOpen+ ? wantedGutter+ : RAIL_WIDTH+ : 0;const laneWidth = Math.max(contentWidth - railWidth, 0);const chartBox = useMemo(@@ -274,18 +443,71 @@ export function TimelineDense({[viewport, limits],);const rowHeight = rowHeightOf(current, surfaceHeight);- const isOpen = railWidth > RAIL_WIDTH;+ const isOpen = committedOpen;const namesVisible = isOpen;- // The overlay is not bound by MIN_LANE_WIDTH: it costs the chart no width.+ // The overlay is not bound by MIN_LANE_WIDTH: it costs the chart no width, so+ // an explicit ask still gets the names where they could not fit beside the+ // chart.const peekWidth =- !isOpen && canShowNames && peeking- ? Math.min(Math.max(contentWidth * 0.38, 96), 168)+ canShowNames && !committedOpen && (peeking || override === "expanded")+ ? wantedGutter: 0;const gutterWidth = Math.max(railWidth, peekWidth);const presentation = presentationForRowHeight(rowHeight);const fitted = isViewportFitted(current, limits);const barHeight = Math.max(Math.min(rowHeight - 1, MAX_BAR_HEIGHT), 1);+ /**+ * Which row the pointer is over — DERIVED from where the pointer is, never+ * stored. Storing it meant a gesture-scroll moved the rows under a pointer+ * that had not moved, and the tooltip went on naming the row that used to be+ * there. The pointer position is the only fact; the row under it follows from+ * that and the window, so it cannot go stale.+ */+ const focusIndex =+ pointerPos == null+ ? null+ : rowIndexAtOffset(+ current,+ pointerPos.y,+ rowHeight,+ prepared.rows.length,+ );+ /** Last id we told the caller about, so a prefetch fires once per row. */+ const hoveredRef = useRef<string | null>(null);+ const pointerPosRef = useRef(pointerPos);+ pointerPosRef.current = pointerPos;++ /**+ * Tell the caller which row is under the pointer, resolved from a VIEWPORT+ * rather than from the last pointermove: a zoom, a scroll, a zoom button and a+ * focus flight all slide a new row under a pointer that never moved. The+ * tooltip already follows that (`focusIndex` above re-derives every render),+ * but the callback did not, so the row the user is looking at was the one row+ * the caller never prefetched.+ */+ const notifyHover = (+ viewport: Viewport,+ at = pointerPosRef.current,+ ): void => {+ if (!at || !onHover) return;+ const live = layoutRef.current;+ const index = rowIndexAtOffset(+ viewport,+ at.y,+ live.rowHeight,+ live.rows.length,+ );+ const id = index == null ? null : live.rows[index]?.node.id;+ if (!id || id === hoveredRef.current) return;+ hoveredRef.current = id;+ onHover(id);+ };+ // Reached through a ref from the stable callbacks below, the same way they+ // reach the zoom pair: they attach once and must not close over this render.+ const notifyHoverRef = useRef(notifyHover);+ notifyHoverRef.current = notifyHover;+const density: Density = useMemo(() => ({pointer,@@ -312,34 +534,37 @@ export function TimelineDense({rowRange,});- const zoomBy = useCallback(- (factor: number, xRatio: number, yRatio: number) =>- setViewport((from) => {- const { limits: live } = layoutRef.current;- return zoomViewport(- from ? clampViewport(from, live) : fitViewport(live),- live,- { factor, xRatio, yRatio },- );- }),- [],- );-- const panBy = useCallback(- (dxPx: number, dyPx: number) =>- setViewport((from) => {- const { limits: live, laneWidth: width } = layoutRef.current;- return panViewport(- from ? clampViewport(from, live) : fitViewport(live),- live,- { dxPx, dyPx, boxWidth: width },- );- }),- [],+ // What each row occupies on the time axis, in the same compressed space the+ // window is expressed in — so a zoom can tell "nothing to see here" from "the+ // thing you were looking at is still here".+ const extentOf = useCallback(+ (rowIndex: number): RowExtent | null => {+ const row = prepared.rows[rowIndex];+ if (!row) return null;+ const offsets = spanOffsetsOf(row.node, prepared.originMs);+ return {+ startMs: compression.toCompressedMs(offsets.startMs),+ endMs: compression.toCompressedMs(offsets.endMs),+ };+ },+ [prepared, compression],);const surfaceRef = useRef<HTMLDivElement | null>(null);const gesture = useRef({ down: false, dragging: false, x: 0, y: 0 });+ /**+ * Every pointer currently down, and the pinch they describe.+ *+ * A touchscreen pinch is NOT a wheel event: it arrives as two pointers, and+ * `touch-action: none` (which this surface needs, so the browser does not pan+ * or zoom the page under the gesture) means nothing else handles it either. So+ * with one-pointer logic only, a two-finger pinch did nothing at all.+ */+ const touches = useRef({+ points: new Map<number, { x: number; y: number }>(),+ distance: 0,+ midpoint: { x: 0, y: 0 },+ });const tween = useRef(0);const cancelTween = useCallback(() => {@@ -359,8 +584,123 @@ export function TimelineDense({// in-flight focus animation at the exact moment the rows crossed the height// that opens the gutter. It also re-attached the wheel listener on every// layout change, for nothing.- const layoutRef = useRef({ limits, laneWidth, railWidth, peekWidth });- layoutRef.current = { limits, laneWidth, railWidth, peekWidth };+ const layoutRef = useRef({+ limits,+ laneWidth,+ railWidth,+ peekWidth,+ extentOf,+ rowHeight,+ rows: prepared.rows,+ });+ layoutRef.current = {+ limits,+ laneWidth,+ railWidth,+ peekWidth,+ extentOf,+ rowHeight,+ rows: prepared.rows,+ };++ /**+ * Zooming and re-anchoring are ONE operation, not two: `anchorTimeToRows`+ * exists precisely so a zoom cannot land on empty air, so every zoom entry+ * point owes it. Keeping the pair in one place is what stops a change to one+ * gesture from quietly not applying to the other.+ *+ * Plain functions, not `useCallback`: they are called from event handlers, so+ * their identity is nobody's dependency, and they read everything live from the+ * refs above.+ */+ const zoomAndAnchor = (+ from: Viewport | null,+ options: { factor: number; xRatio: number; yRatio: number },+ ) => {+ const { limits: live, extentOf: extent } = layoutRef.current;+ const zoomed = zoomViewport(+ from ? clampViewport(from, live) : fitViewport(live),+ live,+ options,+ );+ return anchorTimeToRows(zoomed, live, extent);+ };++ // The wheel path is a stable callback — the listener attaches once — so it+ // reaches the pair through a ref rather than closing over this render's copy.+ const zoomAndAnchorRef = useRef(zoomAndAnchor);+ zoomAndAnchorRef.current = zoomAndAnchor;++ /**+ * The one place a viewport lands from an event handler: the ref stays+ * authoritative for the next gesture frame, React renders it, and the row now+ * under the pointer is re-notified. (The reveal below writes ref + state+ * directly instead — it runs during render, where a callback must not fire.)+ */+ const commit = (next: Viewport) => {+ viewportRef.current = next;+ setViewport(next);+ notifyHover(next);+ };++ const zoomBy = (factor: number, xRatio: number, yRatio: number) => {+ // A gesture takes over from a flight in progress rather than fighting it.+ // Without this the tween's rAF loop kept writing its own interpolated target+ // over the user's zoom for the rest of the 320ms flight — press a zoom button+ // right after a double-click and the button did nothing.+ cancelTween();+ commit(zoomAndAnchor(viewportRef.current, { factor, xRatio, yRatio }));+ };++ const panBy = (dxPx: number, dyPx: number) => {+ cancelTween();+ const { limits: live, laneWidth: width } = layoutRef.current;+ commit(+ panViewport(clampViewport(viewportRef.current, live), live, {+ dxPx,+ dyPx,+ boxWidth: width,+ }),+ );+ };++ // Selection is not always ours to place. The tree, a search hit, a deep link+ // and playback all select rows, and a highlight you cannot see is not a+ // highlight — on a trace this dense the chosen row is usually outside the+ // window, and `layout()` does not even emit a node for it. So an EXTERNAL+ // change reveals its row: pan both axes just far enough, never zoom, because+ // "look at this one" is not a request to change how far in you are looking.+ // Adjusting state during render is React's own answer to "a prop changed and+ // some state must follow" — the superseded render never reaches the screen.+ // `undefined`, not `selectedId`: mounting with a selection already set IS the+ // deep-link case, and it has to be revealed like any other.+ const revealedRef = useRef<string | null | undefined>(undefined);+ if (selectedId !== revealedRef.current) {+ const index = selectedId+ ? prepared.rows.findIndex((row) => row.node.id === selectedId)+ : -1;+ const row = index >= 0 ? prepared.rows[index] : undefined;+ // Marked handled only once the row EXISTS. A deep link can name an+ // observation that is not in the rows yet — fetched by id, or past the+ // load cap — and advancing the ref regardless meant the one chance to reveal+ // it was spent on an absent row: the highlight then stayed off-screen until+ // the user panned. Left un-advanced, the next render with rows retries.+ if (!selectedId || row) revealedRef.current = selectedId;+ if (row) {+ const offsets = spanOffsetsOf(row.node, prepared.originMs);+ const revealed = revealViewport(current, limits, {+ rowIndex: index,+ startMs: compression.toCompressedMs(offsets.startMs),+ endMs: compression.toCompressedMs(offsets.endMs),+ });+ if (!viewportsEqual(revealed, current)) {+ // A flight in progress was aimed at the old selection.+ cancelTween();+ viewportRef.current = revealed;+ setViewport(revealed);+ }+ }+ }// Deltas accumulate and apply once per animation frame — the other half of// what makes map zoom feel immediate instead of laggy under a burst.@@ -384,7 +724,7 @@ export function TimelineDense({const { limits: live, laneWidth: width } = layoutRef.current;let next = viewportRef.current;if (queued.levels !== 0) {- next = zoomViewport(next, live, {+ next = zoomAndAnchorRef.current(next, {factor: 2 ** queued.levels,xRatio: queued.xRatio,yRatio: queued.yRatio,@@ -403,6 +743,7 @@ export function TimelineDense({if (viewportsEqual(next, viewportRef.current)) return;viewportRef.current = next;setViewport(next);+ notifyHoverRef.current(next);}, []);/** Ease-in-out, so the flight starts and lands softly. */@@ -418,6 +759,8 @@ export function TimelineDense({const next = interpolateViewport(from, target, eased);viewportRef.current = next;setViewport(next);+ // Per frame, but `hoveredRef` collapses it to one call per row crossed.+ notifyHoverRef.current(next);tween.current = linear < 1 ? requestAnimationFrame(step) : 0;};tween.current = requestAnimationFrame(step);@@ -449,9 +792,19 @@ export function TimelineDense({const rect = element.getBoundingClientRect();const queued = pending.current;const rail = layoutRef.current.railWidth;- // A macOS pinch is the ONLY wheel event that carries ctrlKey. A- // two-finger scroll is a plain wheel, so it must pan — treating it as- // zoom is what made scrolling around zoom the rows instead.+ // Deltas arrive in pixels, lines or pages depending on the browser and+ // the device, so normalize before anything reads them: a line-mode wheel+ // reports 3, and panning 3px per notch reads as stuck.+ const unit =+ event.deltaMode === 1+ ? WHEEL_LINE_PX+ : event.deltaMode === 2+ ? Math.max(rect.height, 1)+ : 1;+ const deltaX = event.deltaX * unit;+ const deltaY = event.deltaY * unit;+ // A macOS pinch is the ONLY wheel event that carries ctrlKey. Holding+ // ⌘/ctrl is the same intent by hand, and it is how you zoom with a mouse.const pinch = event.ctrlKey || event.metaKey;if (pinch) {@@ -462,34 +815,22 @@ export function TimelineDense({: 0.5;queued.yRatio =rect.height > 0 ? (event.clientY - rect.top) / rect.height : 0.5;- queued.levels += -event.deltaY * PINCH_ZOOM_RATE;+ queued.levels += -deltaY * PINCH_ZOOM_RATE;event.preventDefault();scheduleGesture();return;}- // A discrete mouse notch has no pan intent behind it, so it zooms, at- // its own much slower rate per unit of delta.- const isMouseNotch =- event.deltaMode !== 0 ||- Math.abs(event.deltaY) >= WHEEL_DELTA_THRESHOLD;- if (isMouseNotch && event.deltaX === 0 && !event.shiftKey) {- queued.xRatio =- rect.width > 0- ? (event.clientX - rect.left - rail) /- Math.max(rect.width - rail, 1)- : 0.5;- queued.yRatio =- rect.height > 0 ? (event.clientY - rect.top) / rect.height : 0.5;- queued.levels += -event.deltaY * WHEEL_ZOOM_RATE;- event.preventDefault();- scheduleGesture();- return;- }-- // Two-finger scroll: pan both axes. Shift maps a vertical wheel to time.- const dxPx = event.shiftKey ? -event.deltaY : -event.deltaX;- const dyPx = event.shiftKey ? 0 : -event.deltaY;+ // EVERY other wheel pans, whatever the device. Sniffing a "mouse notch"+ // out of a big delta and zooming on it was wrong twice over: a fast+ // two-finger flick on a Mac trackpad sends deltas far past any such+ // threshold, so a quick scroll down zoomed OUT to the fitted view and+ // the timeline looked like it kept snapping back to the top — and it+ // swallowed the event either way, so there was no scrolling down at all.+ // Zoom keeps the gestures that say zoom and nothing else: pinch,+ // ⌘/ctrl + wheel, the toolbar buttons, double-click to focus.+ const dxPx = event.shiftKey ? -deltaY : -deltaX;+ const dyPx = event.shiftKey ? 0 : -deltaY;const wouldMove = panViewport(viewportRef.current,layoutRef.current.limits,@@ -516,16 +857,78 @@ export function TimelineDense({);const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {- // Touch has no hover, so a tap on the rail is the toggle.+ // A click that never arrived (a drag, a tap outside a row) must not leave the+ // suppression armed for the next real one.+ focusedByTap.current = false;+ // Touch has no hover, so a tap on the rail is the toggle — but only a FIRST+ // finger. A pinch whose first finger happens to land near the left edge was+ // otherwise swallowed by this branch and never became a pinch at all.const offsetX =event.clientX - event.currentTarget.getBoundingClientRect().left;if (+ touches.current.points.size === 0 &&(pointer === "coarse" || event.pointerType === "touch") &&+ // There has to BE something to toggle. At hairline density the left side+ // takes no width, so this collapsed to "the leftmost 6px" and a tap there+ // set an override with nothing to show for it — which then sprang the names+ // open later, the moment a focus zoom grew the rows enough to honour it.+ canShowNames &&offsetX <= Math.max(railWidth, peekWidth) + PEEK_MARGIN_PX) {setOverride(isOpen ? "collapsed" : "expanded");+ // This tap is spent on the toggle, so it is not half of a double-tap:+ // opening and closing the names inside the double-tap window otherwise read+ // as one, and flew the viewport to whatever row the second tap landed on.+ // Forgetting the pending tap is enough — a tap NEAR the rail is a rail tap+ // and lands here too, and a tap far from it fails the proximity check.+ lastTap.current = { at: 0, x: 0, y: 0 };+ return;+ }+ // Shift+drag draws a box to zoom into, which is the one gesture where the+ // user states the window on BOTH axes — so it goes straight there rather+ // than picking a level for them. Plain drag keeps panning; a map's primary+ // gesture should not need a modifier.+ if (event.shiftKey) {+ const rect = event.currentTarget.getBoundingClientRect();+ const point = {+ x: event.clientX - rect.left,+ y: event.clientY - rect.top,+ };+ event.currentTarget.setPointerCapture(event.pointerId);+ setMarqueeBox({ from: point, to: point });return;}++ // A PRIMARY touch is the first contact of a new gesture, so anything left in+ // the map is stale by definition. Not every release arrives — lift two+ // fingers at once and a `pointerup` can go missing, or land outside the+ // element — and one phantom finger turns the next one-finger drag into a+ // pinch, which showed up as a pan that also zoomed a little.+ if (event.isPrimary && event.pointerType !== "mouse") {+ touches.current.points.clear();+ touches.current.distance = 0;+ }+ touches.current.points.set(event.pointerId, {+ x: event.clientX,+ y: event.clientY,+ });+ if (touches.current.points.size === 2) {+ // A second finger ends whatever the first one was doing and starts a+ // pinch from where the two currently are.+ gesture.current.down = false;+ gesture.current.dragging = false;+ setDragging(false);+ const [a, b] = [...touches.current.points.values()];+ if (a && b) {+ touches.current.distance = Math.hypot(b.x - a.x, b.y - a.y);+ touches.current.midpoint = {+ x: (a.x + b.x) / 2,+ y: (a.y + b.y) / 2,+ };+ }+ return;+ }+gesture.current = {down: true,dragging: false,@@ -535,6 +938,70 @@ export function TimelineDense({};const onPointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {+ // Two fingers: pinch to zoom BOTH axes about the midpoint, and pan by+ // however far that midpoint travelled — the two happen together on a map,+ // and separating them makes a pinch feel like it fights the drag. Both go+ // through the same per-frame accumulator the wheel uses, so they inherit its+ // zoom-then-reanchor and its cancelling of a focus flight.+ const active = touches.current;+ // Self-heal the other way too: no contact for this pointer means it is not+ // down, whatever we were told.+ if (event.buttons === 0 && active.points.has(event.pointerId)) {+ active.points.delete(event.pointerId);+ active.distance = 0;+ }+ if (active.points.has(event.pointerId) && active.points.size >= 2) {+ active.points.set(event.pointerId, {+ x: event.clientX,+ y: event.clientY,+ });+ const [a, b] = [...active.points.values()];+ if (!a || !b) return;+ const distance = Math.hypot(b.x - a.x, b.y - a.y);+ const midpoint = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };+ const rect = event.currentTarget.getBoundingClientRect();+ const queued = pending.current;++ if (active.distance > 0 && distance > 0) {+ // A ratio of distances is a ratio of scales, and the accumulator speaks+ // in zoom LEVELS — one level per doubling.+ queued.levels += Math.log2(distance / active.distance);+ const rail = layoutRef.current.railWidth;+ queued.xRatio =+ rect.width > rail+ ? clampRatio((midpoint.x - rect.left - rail) / (rect.width - rail))+ : 0.5;+ queued.yRatio =+ rect.height > 0+ ? clampRatio((midpoint.y - rect.top) / rect.height)+ : 0.5;+ }+ queued.dxPx += midpoint.x - active.midpoint.x;+ queued.dyPx += midpoint.y - active.midpoint.y;++ active.distance = distance;+ active.midpoint = midpoint;+ event.preventDefault();+ scheduleGesture();+ return;+ }+ if (active.points.has(event.pointerId)) {+ active.points.set(event.pointerId, {+ x: event.clientX,+ y: event.clientY,+ });+ }++ const drawing = marqueeRef.current;+ if (drawing) {+ const rect = event.currentTarget.getBoundingClientRect();+ setMarqueeBox({+ from: drawing.from,+ to: { x: event.clientX - rect.left, y: event.clientY - rect.top },+ });+ return;+ }+const state = gesture.current;if (state.down) {const dx = event.clientX - state.x;@@ -564,12 +1031,100 @@ export function TimelineDense({setPeeking(offsetX <= Math.max(railWidth, peekWidth) + PEEK_MARGIN_PX);}- setFocusIndex(- rowIndexAtOffset(current, offsetY, rowHeight, prepared.rows.length),- );+ notifyHover(current, { x: offsetX, y: offsetY });setPointerPos({ x: offsetX, y: offsetY });};+ /** Release of a shift-drag: fly to the box, if it is big enough to mean one. */+ const commitMarquee = () => {+ const box = marqueeRef.current;+ if (!box) return;+ setMarqueeBox(null);+ const width = Math.abs(box.to.x - box.from.x);+ const height = Math.abs(box.to.y - box.from.y);+ // A stray shift-click is not a zoom to a pinhole.+ if (width < MARQUEE_MIN_PX && height < MARQUEE_MIN_PX) return;+ const lane = Math.max(laneWidth, 1);+ const tall = Math.max(surfaceHeight, 1);+ flyTo(+ zoomToBox(current, limits, {+ xStartRatio: (box.from.x - railWidth) / lane,+ xEndRatio: (box.to.x - railWidth) / lane,+ yStartRatio: box.from.y / tall,+ yEndRatio: box.to.y / tall,+ }),+ );+ };++ /**+ * A pointer left. Lifting one finger of a pinch does NOT end the gesture — the+ * survivor becomes a one-finger pan — so its drag origin has to be re-anchored+ * on where that finger actually is. Inheriting the departed finger's origin+ * makes the survivor's next small move pan by the whole finger separation.+ */+ const releasePointer = (pointerId: number) => {+ const active = touches.current;+ active.points.delete(pointerId);+ if (active.points.size === 1) {+ const [survivor] = [...active.points.values()];+ if (survivor) {+ gesture.current = {+ down: true,+ dragging: false,+ x: survivor.x,+ y: survivor.y,+ };+ setDragging(false);+ return;+ }+ }+ if (active.points.size === 0) {+ active.distance = 0;+ gesture.current.down = false;+ gesture.current.dragging = false;+ setDragging(false);+ }+ };++ /**+ * Double-TAP focuses a row, because `dblclick` is not dependable from touch —+ * Safari in particular does not synthesise it. Detected here rather than+ * relied upon: two taps close in time and place, on the same row.+ */+ const lastTap = useRef({ at: 0, x: 0, y: 0 });+ /**+ * Set when a double-tap has just fired, so the tap's own click does not also+ * select. `event.detail` cannot carry this on touch: WebKit neither synthesises+ * `dblclick` from taps nor counts them, so both taps report `detail: 1` and a+ * detail-based guard only ever catches a mouse.+ */+ const focusedByTap = useRef(false);+ const maybeDoubleTap = (event: ReactPointerEvent<HTMLDivElement>) => {+ if (event.pointerType === "mouse") return; // the mouse has a real dblclick+ if (touches.current.points.size > 1 || gesture.current.dragging) return;+ const now = event.timeStamp;+ const previous = lastTap.current;+ const near =+ Math.hypot(event.clientX - previous.x, event.clientY - previous.y) <+ DOUBLE_TAP_SLOP_PX;+ if (now - previous.at < DOUBLE_TAP_MS && near) {+ lastTap.current = { at: 0, x: 0, y: 0 };+ const rect = event.currentTarget.getBoundingClientRect();+ const index = rowIndexAtOffset(+ current,+ event.clientY - rect.top,+ rowHeight,+ prepared.rows.length,+ );+ if (index != null) {+ focusedByTap.current = true;+ focusRow(index);+ }+ return;+ }+ lastTap.current = { at: now, x: event.clientX, y: event.clientY };+ };+const endGesture = useCallback(() => {gesture.current.down = false;gesture.current.dragging = false;@@ -577,8 +1132,8 @@ export function TimelineDense({}, []);const clearFocus = useCallback(() => {- setFocusIndex(null);setPointerPos(null);+ hoveredRef.current = null;setPeeking(false);endGesture();}, [endGesture]);@@ -586,8 +1141,12 @@ export function TimelineDense({/** Double-click an element: both axes move to put it on screen, readably. */const focusRow = (index: number) => {const positioned = result.nodes.find((node) => node.index === index);- if (!positioned) return;- setSelectedIndex(index);+ const row = prepared.rows[index];+ if (!positioned || !row) return;+ // The click that opened this double-click already selected the row, and this+ // flight is about to put it exactly where it should be — so the reveal below+ // must not also chase it and cancel the animation.+ revealedRef.current = row.node.id;const startMs = compression.toCompressedMs(positioned.startMs);flyTo(focusViewport(limits, {@@ -602,6 +1161,53 @@ export function TimelineDense({focusIndex == null? null: (result.nodes.find((node) => node.index === focusIndex) ?? null);+ // Seconds from the trace origin ↔ px in the lane, through the same+ // compression and window the bars went through — so the playhead cannot+ // disagree with what it is sweeping over.+ const secToX = (sec: number) =>+ (compression.toCompressedMs(Math.max(sec, 0) * 1000) - current.time.start) *+ result.pxPerMs;+ const xToSec = (px: number) =>+ result.pxPerMs > 0+ ? compression.toRealMs(current.time.start + px / result.pxPerMs) / 1000+ : 0;+ // The imperative feed reads the live mapping, so a pan or a zoom mid-playback+ // moves the line to the right place on its next tick rather than drifting.+ const mappingRef = useRef(secToX);+ mappingRef.current = secToX;++ const subscribePlayhead = playhead?.subscribe;+ const getPlayheadSec = playhead?.getSec;+ const attachPlayhead = useCallback(+ (element: HTMLDivElement | null) => {+ if (!element || !subscribePlayhead || !getPlayheadSec) return;+ const apply = (sec: number) => {+ element.style.transform = `translateX(${mappingRef.current(sec)}px)`;+ };+ apply(getPlayheadSec());+ return subscribePlayhead(apply);+ },+ [subscribePlayhead, getPlayheadSec],+ );++ const onSeek = playhead?.onSeek;+ const seekFromEvent = (event: ReactPointerEvent<HTMLDivElement>) => {+ if (!onSeek) return;+ const rect = event.currentTarget.getBoundingClientRect();+ onSeek(xToSec(event.clientX - rect.left - railWidth));+ };+ const onAxisPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {+ if (!onSeek) return;+ // Press to place it, drag to scrub — one gesture, as on the wide timeline.+ event.currentTarget.setPointerCapture(event.pointerId);+ seekFromEvent(event);+ };+ const onAxisPointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {+ if (!onSeek || !event.currentTarget.hasPointerCapture(event.pointerId)) {+ return;+ }+ seekFromEvent(event);+ };const windowLabel = formatDurationMs(compression.toRealMs(current.time.start + current.time.duration) -@@ -635,37 +1241,59 @@ export function TimelineDense({><Maximize2 className="h-3 w-3" /></ToolbarButton>- <ToolbarButton- label={isOpen ? "Collapse names" : "Show names"}- onClick={() => setOverride(isOpen ? "collapsed" : "expanded")}- >- {isOpen ? (- <PanelLeftClose className="h-3 w-3" />- ) : (- <PanelLeftOpen className="h-3 w-3" />- )}- </ToolbarButton>+ {/* Hidden when there is nothing to expand: a control that cannot do+ anything is worse than no control. */}+ {canShowNames ? (+ <ToolbarButton+ label={isOpen ? "Collapse names" : "Show names"}+ onClick={() => setOverride(isOpen ? "collapsed" : "expanded")}+ >+ {isOpen ? (+ <PanelLeftClose className="h-3 w-3" />+ ) : (+ <PanelLeftOpen className="h-3 w-3" />+ )}+ </ToolbarButton>+ ) : null}<spanclassName="text-muted-foreground truncate"style={{ fontSize: "10px" }}title={fitted- ? "scroll to pan · pinch to zoom · double-click to focus"+ ? "scroll to pan · pinch to zoom · shift-drag a box · double-click to focus": `${rowHeight.toFixed(1)}px rows · ${windowLabel} window`}>{fitted- ? "scroll to pan · pinch to zoom · double-click to focus"+ ? "scroll to pan · pinch to zoom · shift-drag a box · double-click to focus": `${rowHeight.toFixed(1)}px rows · ${windowLabel} window`}</span></div>+ {/* The axis doubles as the scrub track: press to place the playhead, drag+ to move it — the same gesture the wide timeline's scale has. */}<div- className="border-border relative shrink-0 border-b"- style={{ height: `${AXIS_HEIGHT}px` }}+ className={cn(+ "border-border relative shrink-0 border-b",+ onSeek && "cursor-ew-resize",+ )}+ style={{ height: `${AXIS_HEIGHT}px`, touchAction: "none" }}+ onPointerDown={onAxisPointerDown}+ 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. */}+ <span+ ref={labelProbeRef}+ aria-hidden+ className="invisible absolute"+ style={{ fontSize: "10px" }}+ >+ 0+ </span><div- className="absolute inset-y-0"+ className="absolute inset-y-0 overflow-hidden"style={{ left: `${railWidth}px`, width: `${laneWidth}px` }}>{result.ticks.map((tick) => (@@ -696,9 +1324,18 @@ export function TimelineDense({style={{ touchAction: "none" }}onPointerDown={onPointerDown}onPointerMove={onPointerMove}- onPointerUp={endGesture}+ onPointerUp={(event) => {+ commitMarquee();+ maybeDoubleTap(event);+ releasePointer(event.pointerId);+ event.currentTarget.releasePointerCapture?.(event.pointerId);+ }}onPointerLeave={clearFocus}- onPointerCancel={clearFocus}+ onPointerCancel={(event) => {+ setMarqueeBox(null);+ releasePointer(event.pointerId);+ clearFocus();+ }}data-testid="timeline-dense-surface">{/* The row layer clips its own rows. A row straddling the bottom edge@@ -719,13 +1356,26 @@ export function TimelineDense({style={{ left: `${tick.x}px` }}/>))}+ {/* A collapsed idle gap says how much time it swallowed IN the band,+ because it cannot say it on hover: the rows are painted over this+ layer and cover its full width, so a `title` here is never+ reachable by a pointer. Narrow bands stay silent and leave it to+ the axis ticks at their edges. */}{result.gaps.map((gap) => (<divkey={`${gap.x}-${gap.durationMs}`}- className="bg-muted border-border-contrast absolute inset-y-0 border-x border-dashed"+ className="bg-muted border-border-contrast absolute inset-y-0 flex items-center justify-center overflow-hidden border-x border-dashed"style={{ left: `${gap.x}px`, width: `${gap.width}px` }}- title={`${gap.label} of idle time, collapsed`}- />+ >+ {gap.width >= GAP_LABEL_MIN_WIDTH ? (+ <span+ className="text-muted-foreground rotate-90 whitespace-nowrap"+ style={{ fontSize: "9px" }}+ >+ {gap.label} idle+ </span>+ ) : null}+ </div>))}</div>@@ -734,21 +1384,40 @@ export function TimelineDense({if (y + rowHeight < 0 || y > surfaceHeight) return null;const isFocused = node.index === focusIndex;- const isSelected = node.index === selectedIndex;+ const isSelected = node.id === selectedId;+ const isActive = activeIds?.has(node.id) ?? false;const typeColor = TYPE_COLOR[node.type] ?? FALLBACK_COLOR;+ // One place decides the bar's colour, so the label can ask about the+ // exact class the bar got rather than guessing at it.+ const barClass =+ isFocused || isSelected+ ? ACCENT_COLOR+ : barColor === "type"+ ? typeColor+ : NEUTRAL_COLOR;return (<divkey={node.id}className={cn("absolute inset-x-0",- // At 4px a tint is not enough to find yourself by, so the- // hovered row takes a full-width accent wash.- isSelected && "bg-primary-accent/20",- isFocused && !isSelected && "bg-primary-accent/15",+ rowWashClass({+ selected: isSelected,+ focused: isFocused,+ active: isActive,+ }),)}style={{ top: `${y}px`, height: `${rowHeight}px` }}- onClick={() => setSelectedIndex(node.index)}+ // A double-click delivers TWO clicks, and selecting is not free:+ // it captures an analytics event and reopens the detail panel.+ // The first click of the pair already selected the row, so the+ // second one only focuses.+ onClick={(event) => {+ // A double-click delivers two clicks; a double-TAP delivers two+ // clicks that both look like the first one.+ if (event.detail > 1 || focusedByTap.current) return;+ onSelect(node.id);+ }}onDoubleClick={() => focusRow(node.index)}><GutterContent@@ -770,12 +1439,7 @@ export function TimelineDense({row itself stays for hover and selection. */}{node.offscreen ? (<div- className={cn(- "absolute w-[2px] opacity-40",- barColor === "type"- ? typeColor- : "bg-muted-foreground/60",- )}+ className={cn("absolute w-[2px] opacity-40", barClass)}style={{left: node.x <= 0 ? "0px" : undefined,right: node.x <= 0 ? undefined : "0px",@@ -787,13 +1451,7 @@ export function TimelineDense({/>) : (<div- className={cn(- "absolute rounded-[1px]",- barColor === "type"- ? typeColor- : "bg-muted-foreground/60",- (isFocused || isSelected) && "bg-primary-accent",- )}+ className={cn("absolute rounded-[1px]", barClass)}style={{left: `${node.x}px`,width: `${node.width}px`,@@ -813,14 +1471,38 @@ export function TimelineDense({node.labelPlacement !== "hidden" ? (<spanclassName={cn(- "absolute whitespace-nowrap",- node.labelPlacement === "inside"- ? "text-foreground"- : "text-muted-foreground",+ "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={{- left: `${node.labelX}px`,- maxWidth: `${Math.max(laneWidth - node.labelX, 0)}px`,+ // 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",}}@@ -832,6 +1514,40 @@ export function TimelineDense({</div>);})}++ {/* The box being drawn. Shown over everything so it reads as a+ selection rather than as part of the chart. */}+ {marquee ? (+ <div+ className="border-primary bg-primary/10 pointer-events-none absolute border border-dashed"+ style={{+ left: `${Math.min(marquee.from.x, marquee.to.x)}px`,+ top: `${Math.min(marquee.from.y, marquee.to.y)}px`,+ width: `${Math.abs(marquee.to.x - marquee.from.x)}px`,+ height: `${Math.abs(marquee.to.y - marquee.from.y)}px`,+ }}+ data-testid="timeline-dense-marquee"+ />+ ) : null}++ {/* The playhead sweeps in the lane, clipped by it, and is positioned+ imperatively off the position feed — 600 rows must not re-render to+ move a 2px line. */}+ {playhead?.visible ? (+ <div+ className="pointer-events-none absolute inset-y-0 overflow-hidden"+ style={{ left: `${railWidth}px`, width: `${laneWidth}px` }}+ >+ <div+ ref={attachPlayhead}+ className="bg-primary absolute inset-y-0 w-0.5"+ style={{+ transform: `translateX(${secToX(playhead.getSec())}px)`,+ }}+ data-testid="timeline-dense-playhead"+ />+ </div>+ ) : null}</div>{/* Peek: the same gutter content, floating OVER the chart. The bars keep@@ -851,10 +1567,11 @@ export function TimelineDense({key={node.id}className={cn("absolute inset-x-0",- node.index === selectedIndex && "bg-primary-accent/20",- node.index === focusIndex &&- node.index !== selectedIndex &&- "bg-primary-accent/15",+ rowWashClass({+ selected: node.id === selectedId,+ focused: node.index === focusIndex,+ active: Boolean(activeIds?.has(node.id)),+ }),)}style={{ top: `${y}px`, height: `${rowHeight}px` }}>@@ -874,16 +1591,25 @@ export function TimelineDense({{/* The tooltip is what names a row when the gutter cannot. */}{focused && pointerPos && !dragging && pointerPos.x > gutterWidth ? (<div- className="border-border bg-background text-foreground pointer-events-none absolute z-10 flex max-w-[90%] items-center gap-1 rounded border px-1.5 py-1 shadow-md"+ className="border-border bg-background text-foreground pointer-events-none absolute z-10 flex flex-col gap-0.5 overflow-hidden rounded border px-1.5 py-1 shadow-md"style={{left:- pointerPos.x > box.width * 0.55+ pointerPos.x > contentWidth * 0.55? undefined: `${Math.round(pointerPos.x + 12)}px`,right:- pointerPos.x > box.width * 0.55- ? `${Math.round(Math.max(box.width - pointerPos.x + 12, 4))}px`+ pointerPos.x > contentWidth * 0.55+ ? `${Math.round(Math.max(contentWidth - pointerPos.x + 12, 4))}px`: undefined,+ // Clamped to the space left, not a percentage guess: an unclamped+ // tooltip poked past the surface and put 5px of scrollWidth on a+ // box whose whole claim is that nothing scrolls.+ maxWidth: `${Math.max(+ pointerPos.x > contentWidth * 0.55+ ? pointerPos.x - 16+ : contentWidth - pointerPos.x - 16,+ 80,+ )}px`,top: `${Math.round(Math.min(Math.max(pointerPos.y + 12, 2),@@ -894,22 +1620,30 @@ export function TimelineDense({}}data-testid="timeline-dense-tooltip">- <span- className={cn(- "h-2 w-2 shrink-0 rounded-[1px]",- TYPE_COLOR[focused.type] ?? FALLBACK_COLOR,- )}- />- <span className="truncate" title={focused.name}>- {focused.name}- </span>- <span className="text-muted-foreground shrink-0">- {focused.durationMs == null- ? "—"- : formatDurationMs(focused.durationMs)}+ {/* Two rows, like a tree row: identity, then the metrics. One row+ made the NAME the only flexible item, so adding cost and tokens+ truncated it away — and the name is the thing you hovered for. */}+ <span className="flex items-center gap-1">+ <span+ className={cn(+ "h-2 w-2 shrink-0 rounded-[1px]",+ TYPE_COLOR[focused.type] ?? FALLBACK_COLOR,+ )}+ />+ <span className="truncate" title={focused.name}>+ {focused.name}+ </span></span>- <span className="text-muted-foreground shrink-0">- @{formatDurationMs(focused.startMs)}+ <span className="text-muted-foreground flex flex-wrap items-center gap-x-1.5 gap-y-0.5">+ <span>+ {focused.durationMs == null+ ? "—"+ : formatDurationMs(focused.durationMs)}+ </span>+ <span>@{formatDurationMs(focused.startMs)}</span>+ {factsOf?.(focused.id).map((fact) => (+ <span key={fact}>{fact}</span>+ ))}</span></div>) : null}@@ -959,10 +1693,41 @@ function GutterContent({barHeight: number;showName: boolean;}) {- const depth = Math.min(node.depth, RAIL_MAX_DEPTH);- const squareSize = Math.max(Math.min(barHeight, 6), 2);- const indent = showName ? depth * GUTTER_INDENT : depth * RAIL_INDENT + 1;+ // Nothing to show, so nothing to build: at bird's-eye density the rail has no+ // width, and a box of invisible squares is one DOM node per row of the trace.+ if (width <= 0) return null;++ // RAIL_MAX_DEPTH exists to keep a tiny square inside a 15px rail, and applying+ // it to the OPEN gutter flattened the tree: every node past depth 4 drew at the+ // same indent and the same connector column in a gutter up to 168px wide. The+ // open gutter caps on the width it actually has instead — deep traces still+ // need a cap (a 1401-deep chain would push every name out of the box), but it+ // is the one the gutter can afford, leaving room for the icon and a name.+ const depthCap = showName+ ? Math.max(+ Math.floor((width - GUTTER_ICON - GUTTER_NAME_MIN) / GUTTER_INDENT),+ 0,+ )+ : RAIL_MAX_DEPTH;+ const depth = Math.min(node.depth, depthCap);const typeColor = TYPE_COLOR[node.type] ?? FALLBACK_COLOR;+ // The square must end up INSIDE the rail, so its size and its indent are both+ // bounded by the width it has to live in — not by the row height alone.+ const squareSize = Math.max(+ Math.min(barHeight, RAIL_SQUARE_MAX, width - RAIL_INDENT),+ 2,+ );+ const indent = showName+ ? depth * GUTTER_INDENT+ : Math.min(depth * RAIL_INDENT + 1, Math.max(width - squareSize - 1, 0));+ /** x of this row's own rail, and of its parent's. */+ const railX = depth * GUTTER_INDENT + GUTTER_RAIL;+ // The PARENT's RENDERED depth, which is not always one less than this row's:+ // past the cap a parent and its child both flatten to the same indent, and an+ // elbow drawn an indent to the left of a spine that never went there is a tree+ // whose lines stop meeting — for the whole flattened tail of a deep trace.+ const parentRailX =+ Math.min(node.depth - 1, depthCap) * GUTTER_INDENT + GUTTER_RAIL;return (<div@@ -977,7 +1742,7 @@ function GutterContent({<divkey={level}className="bg-border-contrast absolute inset-y-0 w-px"- style={{ left: `${level * GUTTER_INDENT + 5}px` }}+ style={{ left: `${level * GUTTER_INDENT + GUTTER_RAIL}px` }}/>) : null,)@@ -989,22 +1754,29 @@ function GutterContent({"bg-border-contrast absolute top-0 w-px",node.isLastSibling ? "h-1/2" : "bottom-0",)}- style={{ left: `${(depth - 1) * GUTTER_INDENT + 5}px` }}+ style={{ left: `${parentRailX}px` }}/><divclassName="bg-border-contrast absolute top-1/2 h-px"style={{- left: `${(depth - 1) * GUTTER_INDENT + 5}px`,- width: `${GUTTER_INDENT}px`,+ left: `${parentRailX}px`,+ width: `${Math.max(indent - parentRailX, 0)}px`,}}/></>) : null}+ {/* This row's own spine, descending from its icon to its children. */}+ {showName && node.hasChildren && !node.isCollapsed ? (+ <div+ className="bg-border-contrast absolute top-1/2 bottom-0 w-px"+ style={{ left: `${railX}px` }}+ />+ ) : null}{showName ? (<divclassName="absolute flex items-center gap-1 overflow-hidden"style={{- left: `${indent + 6}px`,+ left: `${indent}px`,right: "2px",top: `${Math.max((rowHeight - 16) / 2, 0)}px`,height: "16px",@@ -1024,6 +1796,7 @@ function GutterContent({) : (<divclassName={cn("absolute rounded-[1px]", typeColor)}+ data-testid="timeline-dense-type-square"style={{left: `${indent}px`,top: `${Math.max((rowHeight - squareSize) / 2, 0)}px`,diff --git a/web/src/features/traces/components/TraceTimelineDense/TraceTimelineCompact.tsx b/web/src/features/traces/components/TraceTimelineDense/TraceTimelineCompact.tsxnew file mode 100644index 0000000000..d49702f3fb--- /dev/null+++ b/web/src/features/traces/components/TraceTimelineDense/TraceTimelineCompact.tsx@@ -0,0 +1,129 @@+/**+ * TraceTimelineCompact - the compact timeline, wired into the trace panel.+ *+ * This is the container half: it measures the box it has been given and hands+ * that to the renderer, and it connects the renderer's selection and hover to+ * the same contexts the Tree and Timeline views use, so all three select the+ * same observation and open the same detail panel.+ *+ * The renderer itself (TimelineDense) takes a measured box and nothing implicit,+ * which is what keeps it reviewable in Storybook across every size and shape.+ */++import { useCallback, useMemo, useState } from "react";+import { usdFormatter, formatTokenCounts } from "@/src/utils/numbers";+import { useTraceData } from "@/src/features/traces/contexts/TraceDataContext";+import { useSelection } from "@/src/features/traces/contexts/SelectionContext";+import {+ useActiveObservationIds,+ usePlayhead,+ useShowPlayhead,+} from "@/src/features/traces/contexts/PlayheadContext";+import { useHandlePrefetchObservation } from "@/src/features/traces/hooks/useHandlePrefetchObservation";+import { useSelectTraceNode } from "@/src/features/traces/hooks/useSelectTraceNode";+import { detectPointerModality } from "../../fns/timeline/density";+import { TimelineDense } from "./TimelineDense";++export function TraceTimelineCompact() {+ const { roots, nodeMap } = useTraceData();+ const { selectedNodeId } = useSelection();+ const { handleHover } = useHandlePrefetchObservation();+ const selectNode = useSelectTraceNode("timeline_compact");++ // Playback: the transport lives in the navigation header and drives the shared+ // engine, so this view owes the two things you WATCH — a line that sweeps and+ // the rows lighting up as it passes them. Both are handed to the renderer,+ // which stays context-free so Storybook can still mount it anywhere.+ const { seekToSec, getPlayheadSec, subscribePosition } = usePlayhead();+ const showPlayhead = useShowPlayhead();+ const activeIds = useActiveObservationIds();+ const playhead = useMemo(+ () => ({+ visible: showPlayhead,+ getSec: getPlayheadSec,+ subscribe: subscribePosition,+ onSeek: seekToSec,+ }),+ [showPlayhead, getPlayheadSec, subscribePosition, seekToSec],+ );++ const [pointerModality] = useState(detectPointerModality);+ const [box, setBox] = useState<{ width: number; height: number } | null>(+ null,+ );++ // Measure the box that actually holds the rows. Same rule as the timeline: the+ // element being measured is the one whose client box the renderer will fill,+ // because a border or a scrollbar the math never saw is how a lane ends up+ // wider than the space available.+ const measureRef = useCallback((element: HTMLDivElement | null) => {+ if (!element) return;+ const measure = () =>+ setBox((current) =>+ current?.width === element.clientWidth &&+ current?.height === element.clientHeight+ ? current+ : { width: element.clientWidth, height: element.clientHeight },+ );+ const observer = new ResizeObserver(measure);+ observer.observe(element);+ measure();+ return () => observer.disconnect();+ }, []);++ const handleHoverNode = useCallback(+ (nodeId: string) => {+ // The map the tree already builds, rather than a walk per hovered row —+ // and hover changes once per row at 1px rows.+ const node = nodeMap.get(nodeId);+ if (node) handleHover(node);+ },+ [nodeMap, handleHover],+ );++ // Cost and usage the way the tree row states them, so hovering a hairline row+ // tells you what reading a tree row would. Same formatters, same order.+ const factsOf = useCallback(+ (nodeId: string) => {+ const node = nodeMap.get(nodeId);+ if (!node) return [];+ const facts: string[] = [];+ if (node.totalCost) {+ const aggregated = node.children.length > 0 || node.type === "TRACE";+ facts.push(+ `${aggregated ? "∑ " : ""}${usdFormatter(node.totalCost.toNumber())}`,+ );+ }+ const tokens = formatTokenCounts(+ node.inputUsage,+ node.outputUsage,+ node.totalUsage,+ );+ if (tokens) facts.push(tokens);+ return facts;+ },+ [nodeMap],+ );++ return (+ <div ref={measureRef} className="h-full w-full overflow-hidden">+ {box && box.width > 0 && box.height > 0 ? (+ <TimelineDense+ roots={roots}+ box={box}+ gutter="auto"+ pointer={pointerModality}+ barColor="type"+ compress={false}+ showReadout={false}+ selectedId={selectedNodeId}+ onSelect={selectNode}+ onHover={handleHoverNode}+ activeIds={activeIds}+ playhead={playhead}+ factsOf={factsOf}+ />+ ) : null}+ </div>+ );+}diff --git a/web/src/features/traces/components/TraceTree.tsx b/web/src/features/traces/components/TraceTree.tsxindex 2b09bf7aef..58a892580d 100644--- a/web/src/features/traces/components/TraceTree.tsx+++ b/web/src/features/traces/components/TraceTree.tsx@@ -18,13 +18,10 @@ import { useTraceData } from "@/src/features/traces/contexts/TraceDataContext";import { useSelection } from "@/src/features/traces/contexts/SelectionContext";import { useIsObservationActive } from "@/src/features/traces/contexts/PlayheadContext";import { useHandlePrefetchObservation } from "@/src/features/traces/hooks/useHandlePrefetchObservation";-import { useDesktopLayoutContextOptional } from "./TraceLayoutDesktop";-import { useMobileLayoutContextOptional } from "./TraceLayoutMobile";+import { useSelectTraceNode } from "@/src/features/traces/hooks/useSelectTraceNode";import { type TreeNode } from "../types/treeNode";import { cn } from "@/src/utils/tailwind";import type Decimal from "decimal.js";-import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";-import { useTraceAnalyticsDimensions } from "@/src/features/traces/hooks/useTraceAnalyticsDimensions";/*** Feature-scoped row container: subscribes to the row's OWN playback-active@@ -89,29 +86,9 @@ const TraceTreeRow = memo(function TraceTreeRow({export function TraceTree() {const { roots, comments } = useTraceData();- const { selectedNodeId, setSelectedNodeId, collapsedNodes, toggleCollapsed } =- useSelection();+ const { selectedNodeId, collapsedNodes, toggleCollapsed } = useSelection();const { handleHover } = useHandlePrefetchObservation();- const capture = usePostHogClientCapture();- const analyticsDimensions = useTraceAnalyticsDimensions();- // Optional (null on mobile): reopen the detail panel on select, including- // re-selecting the already-selected node.- const layout = useDesktopLayoutContextOptional();- // Optional (null on desktop): jump to the Info tab on select, including- // re-selecting the already-selected node (URL param unchanged → the tab- // effect wouldn't fire).- const mobileLayout = useMobileLayoutContextOptional();- const handleSelectNode = (id: string | null) => {- if (id) {- capture("trace_detail:node_selected", {- source: "tree",- ...analyticsDimensions,- });- }- setSelectedNodeId(id);- layout?.expandDetailPanel();- if (id) mobileLayout?.switchToInfoTab();- };+ const handleSelectNode = useSelectTraceNode("tree");// TODO: Extract aggregation logic to shared utility - duplicated in tree-building.ts and TraceTimeline/index.tsx// Calculate aggregated totals across all roots for heatmap color scalingdiff --git a/web/src/features/traces/fns/timeline/barContrast.ts b/web/src/features/traces/fns/timeline/barContrast.tsnew file mode 100644index 0000000000..8eae839198--- /dev/null+++ b/web/src/features/traces/fns/timeline/barContrast.ts@@ -0,0 +1,103 @@+/**+ * Which text colour reads on a coloured bar — decided from the bar's own colour.+ *+ * A duration label drawn inside its bar has to contrast with the BAR, not with+ * the page, and no single colour can do that here: the type palette runs from+ * pastels to 600s. A hand-written table cannot either, because three of those+ * colours flip lightness between themes — the neutral grey goes from 91% to 16%+ * lightness, so a table right in light mode is wrong in dark mode.+ *+ * The browser is the only thing that knows what a class resolves to, so this asks+ * it: one hidden probe, one pass over the candidate classes, once per theme.+ *+ * Conversion goes through a canvas pixel rather than a regex over the computed+ * value. `getComputedStyle` hands back whatever colour space the token was+ * authored in — Chrome returns `oklch(59.6% 0.145 163)` verbatim for the palette+ * tokens that use it — and reading those three numbers as if they were R, G and B+ * turns a mid-tone into near-black, which then picks exactly the wrong text+ * colour. Painting the colour and reading the pixel is format-agnostic, and it+ * composites a translucent bar onto its surface for free.+ */++export type BarTextTone = "light" | "dark";++/**+ * WCAG's crossover. Below this relative luminance white text has the better+ * contrast ratio, above it black does — `1.05 / (L + 0.05)` against+ * `(L + 0.05) / 0.05`. Not 0.5: that over-picks white on mid-tones.+ */+const TONE_THRESHOLD = 0.179;++/** Relative luminance of an sRGB byte triple, per WCAG 2. */+export const luminanceOf = (r: number, g: number, b: number): number => {+ const channel = (value: number) => {+ const c = value / 255;+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;+ };+ return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);+};++/**+ * Memoized per theme, since that is the only thing that changes the answer —+ * every renderer on the page shares one probe per theme.+ */+const cache = new Map<string, Record<string, BarTextTone>>();++/**+ * Resolve each background class to the tone its text should take. Classes the+ * browser resolves to nothing are simply absent from the result, so a caller+ * falls back to its own default rather than to a wrong colour.+ *+ * `theme` is an input, not a decoration: it is what decides which colour a class+ * resolves to, and therefore what makes a previous answer stale.+ */+export function resolveBarTones(+ classNames: readonly string[],+ { theme = "", surfaceClassName = "bg-background" } = {},+): Record<string, BarTextTone> {+ const key = `${theme}|${surfaceClassName}|${classNames.join(",")}`;+ const cached = cache.get(key);+ if (cached) return cached;++ const tones: Record<string, BarTextTone> = {};+ if (typeof document === "undefined") return tones;++ const context = document.createElement("canvas").getContext("2d");+ const probe = document.createElement("div");+ probe.setAttribute("aria-hidden", "true");+ probe.style.cssText =+ "position:absolute;left:-9999px;top:0;width:1px;height:1px;pointer-events:none";+ document.body.appendChild(probe);++ try {+ if (!context) return tones;+ const colourOf = (className: string) => {+ probe.className = className;+ return getComputedStyle(probe).backgroundColor;+ };++ const surface = colourOf(surfaceClassName);+ for (const className of classNames) {+ const colour = colourOf(className);+ // Paint the surface, then the bar on top: one pixel of honest sRGB, with+ // any alpha already composited.+ context.clearRect(0, 0, 1, 1);+ context.fillStyle = surface;+ context.fillRect(0, 0, 1, 1);+ context.fillStyle = colour;+ context.fillRect(0, 0, 1, 1);+ const [r, g, b, a] = context.getImageData(0, 0, 1, 1).data;+ if (r == null || g == null || b == null || a === 0) continue;+ tones[className] =+ luminanceOf(r, g, b) > TONE_THRESHOLD ? "dark" : "light";+ }+ } finally {+ probe.remove();+ }++ cache.set(key, tones);+ return tones;+}++/** Test seam: the cache is keyed on the theme, which a test changes by hand. */+export const clearBarToneCache = () => cache.clear();diff --git a/web/src/features/traces/fns/timeline/layout.ts b/web/src/features/traces/fns/timeline/layout.tsindex 0848e53489..c655a5ece4 100644--- a/web/src/features/traces/fns/timeline/layout.ts+++ b/web/src/features/traces/fns/timeline/layout.ts@@ -213,6 +213,19 @@ const hasDuration = (node: LayoutNode) =>Boolean(node.endTime) ||(node.latency != null && Number.isFinite(node.latency));+/**+ * A span's offsets from the trace origin, with the same end-time fallbacks the+ * layout itself applies. Exported so a caller that needs an extent for a row the+ * layout has not positioned — one outside the visible window — cannot end up+ * disagreeing with the bar it will eventually draw.+ */+export function spanOffsetsOf(+ node: LayoutNode,+ originMs: number,+): { startMs: number; endMs: number } {+ return { startMs: startOf(node) - originMs, endMs: endOf(node) - originMs };+}+export function formatDurationMs(ms: number): string {if (!Number.isFinite(ms) || ms < 0) return "0ms";if (ms < 1_000) return `${Math.round(ms)}ms`;diff --git a/web/src/features/traces/fns/timeline/viewport.clienttest.ts b/web/src/features/traces/fns/timeline/viewport.clienttest.tsindex c5c5bdbcb9..c8cfce2c6b 100644--- a/web/src/features/traces/fns/timeline/viewport.clienttest.ts+++ b/web/src/features/traces/fns/timeline/viewport.clienttest.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";import { traceSpaceOf } from "./viewTransform";import {HUMAN_ROW_HEIGHT,+ anchorTimeToRows,MAX_ROW_HEIGHT,MIN_ROW_HEIGHT,clampViewport,@@ -9,18 +10,21 @@ import {focusViewport,isViewportFitted,panViewport,+ revealViewport,rowHeightOf,viewportsEqual,interpolateViewport,visibleRowRange,+ zoomToBox,zoomViewport,type Viewport,} from "./viewport";-// 600px of rows over a 24s trace, one row per span.+// 600px of rows over a 24s trace, one row per span. More spans than the box has+// pixels, so the floor and the panning both get exercised.const limits = {traceSpace: traceSpaceOf(24_000),- rowCount: 500,+ rowCount: 2_000,boxHeight: 600,};const BOX_WIDTH = 340;@@ -28,14 +32,14 @@ const BOX_WIDTH = 340;describe("viewport", () => {it("fits to the densest row window the height allows", () => {const fitted = fitViewport(limits);- // 600px at the 4px floor shows 150 of the 500 rows; the rest is panned to.+ // 600px at the 1px floor shows 600 of the 2000 rows; the rest is panned to.expect(fitted.rows.count).toBe(limits.boxHeight / MIN_ROW_HEIGHT);expect(fitted.rows.start).toBe(0);expect(rowHeightOf(fitted, limits.boxHeight)).toBe(MIN_ROW_HEIGHT);expect(fitted.time).toEqual(limits.traceSpace);expect(isViewportFitted(fitted, limits)).toBe(true);- // A trace that fits entirely shows every row and still floors at 4px.+ // A trace that fits entirely shows every row, floor or no floor.const forty = { ...limits, rowCount: 40 };expect(fitViewport(forty).rows.count).toBe(40);expect(rowHeightOf(fitViewport(forty), 600)).toBe(15);@@ -73,8 +77,8 @@ describe("viewport", () => {expect(zoomed.time.duration).toBeCloseTo(12_000, 6);expect(zoomed.time.start).toBeCloseTo(6_000, 6);// ...and so does the row window, so the rows get twice as tall.- expect(zoomed.rows.count).toBeCloseTo(75, 6);- expect(rowHeightOf(zoomed, limits.boxHeight)).toBeCloseTo(8, 6);+ expect(zoomed.rows.count).toBeCloseTo(300, 6);+ expect(rowHeightOf(zoomed, limits.boxHeight)).toBeCloseTo(2, 6);expect(isViewportFitted(zoomed, limits)).toBe(false);// The row under the anchor stays under the anchor.@@ -177,7 +181,7 @@ describe("viewport", () => {// Focusing the last row keeps the window inside the content.const last = focusViewport(limits, {- rowIndex: 499,+ rowIndex: limits.rowCount - 1,startMs: 23_000,durationMs: 100,});@@ -186,9 +190,165 @@ describe("viewport", () => {);});+ it("slides the clock to the rows when a zoom lands on empty air", () => {+ // The rows of this trace all live in its first third — a chain that finishes+ // early inside a trace whose duration one long root sets.+ const extentOf = (rowIndex: number) => ({+ startMs: rowIndex * 4,+ endMs: rowIndex * 4 + 3,+ });+ const zoomed = zoomViewport(fitViewport(limits), limits, {+ factor: 4,+ xRatio: 0.5,+ yRatio: 0,+ });+ // Rows 0-150ish, in a window centred on the middle of the trace: carets only.+ expect(zoomed.time.start).toBeGreaterThan(600 * 4);++ const anchored = anchorTimeToRows(zoomed, limits, extentOf);+ expect(anchored.time.duration).toBeCloseTo(zoomed.time.duration, 6);+ expect(anchored.rows).toEqual(zoomed.rows);+ // The window now covers the rows on screen.+ const range = visibleRowRange(anchored, limits.rowCount, 0);+ const first = extentOf(range.startIndex);+ const last = extentOf(range.endIndex);+ expect(anchored.time.start).toBeLessThanOrEqual(last.endMs);+ expect(anchored.time.start + anchored.time.duration).toBeGreaterThanOrEqual(+ first.startMs,+ );++ // Idempotent, and a no-op whenever there is anything to look at — it must+ // never move the ground under someone reading a span.+ expect(+ viewportsEqual(anchorTimeToRows(anchored, limits, extentOf), anchored),+ ).toBe(true);+ expect(anchorTimeToRows(fitViewport(limits), limits, extentOf)).toEqual(+ fitViewport(limits),+ );+ // No extents at all (an empty or unknown trace) leaves it untouched.+ expect(anchorTimeToRows(zoomed, limits, () => null)).toEqual(zoomed);+ });++ it("zooms to a drawn box on both axes", () => {+ const fitted = fitViewport(limits);+ // The right half of the width, the second quarter of the height.+ const boxed = zoomToBox(fitted, limits, {+ xStartRatio: 0.5,+ xEndRatio: 1,+ yStartRatio: 0.25,+ yEndRatio: 0.5,+ });+ expect(boxed.time.start).toBeCloseTo(12_000, 6);+ expect(boxed.time.duration).toBeCloseTo(12_000, 6);+ expect(boxed.rows.start).toBeCloseTo(150, 6);+ expect(boxed.rows.count).toBeCloseTo(150, 6);++ // Drawn right-to-left and bottom-to-top is the same box.+ expect(+ zoomToBox(fitted, limits, {+ xStartRatio: 1,+ xEndRatio: 0.5,+ yStartRatio: 0.5,+ yEndRatio: 0.25,+ }),+ ).toEqual(boxed);++ // A flat box keeps that axis rather than asking for an infinite zoom.+ const flat = zoomToBox(fitted, limits, {+ xStartRatio: 0.5,+ xEndRatio: 0.5,+ yStartRatio: 0.25,+ yEndRatio: 0.5,+ });+ expect(flat.time.duration).toBeCloseTo(fitted.time.duration, 6);+ expect(flat.rows.count).toBeCloseTo(150, 6);++ // And a pinhole box still cannot take the rows past the height ceiling.+ const tiny = zoomToBox(fitted, limits, {+ xStartRatio: 0.5,+ xEndRatio: 0.5001,+ yStartRatio: 0.5,+ yEndRatio: 0.5001,+ });+ expect(rowHeightOf(tiny, limits.boxHeight)).toBeCloseTo(MAX_ROW_HEIGHT, 6);+ expect(Number.isFinite(tiny.time.start)).toBe(true);++ for (const degenerate of [+ { xStartRatio: NaN, xEndRatio: NaN, yStartRatio: NaN, yEndRatio: NaN },+ { xStartRatio: -3, xEndRatio: 9, yStartRatio: -1, yEndRatio: 4 },+ ]) {+ const result = zoomToBox(fitted, limits, degenerate);+ expect(Number.isFinite(result.time.start)).toBe(true);+ expect(Number.isFinite(result.rows.count)).toBe(true);+ }+ });++ it("reveals a row without changing the zoom", () => {+ const zoomed = zoomViewport(fitViewport(limits), limits, {+ factor: 16,+ xRatio: 0,+ yRatio: 0,+ });+ expect(zoomed.rows.start).toBe(0);++ // A selection from the tree, a search or a deep link lands on row 900 —+ // nowhere near the window — and it has to become visible.+ const revealed = revealViewport(zoomed, limits, {+ rowIndex: 900,+ startMs: 18_000,+ endMs: 18_100,+ });+ expect(revealed.rows.start).toBeLessThanOrEqual(900);+ expect(revealed.rows.start + revealed.rows.count).toBeGreaterThan(900);+ expect(revealed.time.start).toBeLessThanOrEqual(18_000);+ expect(revealed.time.start + revealed.time.duration).toBeGreaterThanOrEqual(+ 18_100,+ );+ // But NOT by zooming: how far in you are looking is the user's business.+ expect(revealed.rows.count).toBeCloseTo(zoomed.rows.count, 6);+ expect(revealed.time.duration).toBeCloseTo(zoomed.time.duration, 6);++ // A row already comfortably inside the window is left exactly alone, which+ // is what keeps a click on a visible row from moving the ground under it.+ const inside = revealViewport(revealed, limits, {+ rowIndex: Math.round(revealed.rows.start + revealed.rows.count / 2),+ startMs: revealed.time.start + revealed.time.duration / 2,+ endMs: revealed.time.start + revealed.time.duration / 2 + 1,+ });+ expect(viewportsEqual(inside, revealed)).toBe(true);++ // A span wider than the window cannot be contained, so it is centred.+ const wide = revealViewport(zoomed, limits, {+ rowIndex: 10,+ startMs: 0,+ endMs: 24_000,+ });+ expect(wide.time.start + wide.time.duration / 2).toBeCloseTo(12_000, 6);++ for (const viewport of [+ revealViewport(zoomed, limits, {+ rowIndex: NaN,+ startMs: NaN,+ endMs: NaN,+ }),+ revealViewport(+ zoomed,+ { ...limits, rowCount: 0 },+ {+ rowIndex: 5,+ startMs: 0,+ endMs: 1,+ },+ ),+ ]) {+ expect(Number.isFinite(viewport.rows.start)).toBe(true);+ expect(Number.isFinite(viewport.time.start)).toBe(true);+ }+ });+it("windows the rows it renders", () => {const zoomed = zoomViewport(fitViewport(limits), limits, {- factor: 8,+ factor: 64,xRatio: 0.5,yRatio: 0.5,});diff --git a/web/src/features/traces/fns/timeline/viewport.ts b/web/src/features/traces/fns/timeline/viewport.tsindex a5a26ef7de..ae3a98c392 100644--- a/web/src/features/traces/fns/timeline/viewport.ts+++ b/web/src/features/traces/fns/timeline/viewport.ts@@ -19,8 +19,16 @@import { clampView, type TimeSpan } from "./viewTransform";-/** Rows never render thinner than this, so "everything visible" has a limit. */-export const MIN_ROW_HEIGHT = 4;+/**+ * One device pixel per span — the floor, and it is deliberately literal.+ *+ * A 4px floor still made a few thousand spans a scrolling job, which is the one+ * thing this layout exists to avoid: at 4px you are reading a window, at 1px you+ * are reading the trace. A 600px-tall box holds 600 rows, so most traces fit+ * whole and the shape arrives all at once; zoom is then how you get from the+ * shape to a span, rather than how you find out there is more below.+ */+export const MIN_ROW_HEIGHT = 1;/** Nor thicker than this, so zooming in cannot end at one giant row. */export const MAX_ROW_HEIGHT = 40;/** The row height a human reads comfortably — what double-click aims for. */@@ -168,6 +176,51 @@ export function zoomViewport();}+/**+ * Zoom to a box drawn on the surface — "show me exactly this region".+ *+ * Given as ratios of the box's own width and height, like `zoomViewport`'s+ * anchor, so this function never needs to know a pixel. Both axes come from the+ * rectangle and nothing is inferred: a marquee is the one gesture where the user+ * has stated the window on both axes, so the only thing left to do is clamp it+ * into the content and into the row-height limits.+ */+export function zoomToBox(+ viewport: Viewport,+ limits: ViewportLimits,+ box: {+ xStartRatio: number;+ xEndRatio: number;+ yStartRatio: number;+ yEndRatio: number;+ },+): Viewport {+ const from = clampViewport(viewport, limits);+ const x0 = clamp(finite(box.xStartRatio, 0), 0, 1);+ const x1 = clamp(finite(box.xEndRatio, 1), 0, 1);+ const y0 = clamp(finite(box.yStartRatio, 0), 0, 1);+ const y1 = clamp(finite(box.yEndRatio, 1), 0, 1);+ const left = Math.min(x0, x1);+ const right = Math.max(x0, x1);+ const top = Math.min(y0, y1);+ const bottom = Math.max(y0, y1);++ // A zero-width or zero-height box would ask for an infinite zoom; keep that+ // axis as it is rather than refusing the whole gesture.+ const duration =+ right > left ? from.time.duration * (right - left) : from.time.duration;+ const count =+ bottom > top ? from.rows.count * (bottom - top) : from.rows.count;++ return clampViewport(+ {+ time: { start: from.time.start + from.time.duration * left, duration },+ rows: { start: from.rows.start + from.rows.count * top, count },+ },+ limits,+ );+}+/** Pan by a pixel delta — the drag gesture, in both axes at once. */export function panViewport(viewport: Viewport,@@ -234,6 +287,100 @@ export function focusViewport();}+export type RowExtent = { startMs: number; endMs: number };++/**+ * Slide the clock to where the rows are, when a zoom has landed on empty air.+ *+ * The two axes are independent by design — one is time, the other is position in+ * the tree — and they are only ever CORRELATED, never proportional: a chain of+ * 600 spans can finish in the first third of a trace whose duration is set by one+ * long root. Zooming both axes about the same point therefore has a failure mode+ * with nothing wrong with it and nothing in it: forty rows whose spans all lie+ * outside the window, drawn as a column of edge carets.+ *+ * So after a zoom, if not one visible row has anything inside the window, the+ * window slides onto the rows that are there. It never resizes — the zoom the+ * user asked for is the zoom they get — and it does nothing at all whenever there+ * is something to see, so it cannot fight someone who is looking at a span.+ */+export function anchorTimeToRows(+ viewport: Viewport,+ limits: ViewportLimits,+ extentOf: (rowIndex: number) => RowExtent | null,+): Viewport {+ const range = visibleRowRange(viewport, limits.rowCount, 0);+ const windowStart = viewport.time.start;+ const windowEnd = windowStart + viewport.time.duration;+ let earliest = Infinity;+ let latest = -Infinity;++ for (let index = range.startIndex; index <= range.endIndex; index++) {+ const extent = extentOf(index);+ if (!extent) continue;+ // Anything at all inside the window means there is something to look at.+ if (extent.endMs >= windowStart && extent.startMs <= windowEnd) {+ return viewport;+ }+ earliest = Math.min(earliest, extent.startMs);+ latest = Math.max(latest, extent.endMs);+ }+ if (!Number.isFinite(earliest) || !Number.isFinite(latest)) return viewport;++ const centre = (earliest + latest) / 2;+ return clampViewport(+ {+ time: {+ start: centre - viewport.time.duration / 2,+ duration: viewport.time.duration,+ },+ rows: viewport.rows,+ },+ limits,+ );+}++/**+ * The smallest move that brings a row and its span inside the window —+ * scrollIntoView for a 2D viewport, and deliberately NOT a focus.+ *+ * Selection arrives from everywhere: the tree, a search hit, a deep link, a+ * playback cursor. All of those owe the user a visible highlight, but none of+ * them is a request to change how far in you are looking — so the zoom on both+ * axes is carried through untouched and only the offsets move. A span wider than+ * the current window is centred, since no offset can contain it.+ */+export function revealViewport(+ viewport: Viewport,+ limits: ViewportLimits,+ target: { rowIndex: number; startMs: number; endMs: number },+): Viewport {+ const from = clampViewport(viewport, limits);+ const rowIndex = Math.max(finite(target.rowIndex, 0), 0);++ // Keep a row of context around it where the window is big enough to spare it.+ const count = from.rows.count;+ const margin = Math.min(1, Math.max(count - 1, 0) / 2);+ let rowStart = from.rows.start;+ if (rowIndex < rowStart + margin) rowStart = rowIndex - margin;+ else if (rowIndex + 1 > rowStart + count - margin) {+ rowStart = rowIndex + 1 + margin - count;+ }++ const duration = from.time.duration;+ const startMs = finite(target.startMs, 0);+ const endMs = Math.max(finite(target.endMs, startMs), startMs);+ let timeStart = from.time.start;+ if (endMs - startMs >= duration) timeStart = (startMs + endMs - duration) / 2;+ else if (startMs < timeStart) timeStart = startMs;+ else if (endMs > timeStart + duration) timeStart = endMs - duration;++ return clampViewport(+ { time: { start: timeStart, duration }, rows: { start: rowStart, count } },+ limits,+ );+}+/*** Which row sits at a pixel offset in the box — the analytic inverse of the* render mapping `y = (index - rows.start) * rowHeight`. Exact by construction,diff --git a/web/src/features/traces/hooks/useSelectTraceNode.ts b/web/src/features/traces/hooks/useSelectTraceNode.tsnew file mode 100644index 0000000000..6b214cb4ce--- /dev/null+++ b/web/src/features/traces/hooks/useSelectTraceNode.ts@@ -0,0 +1,49 @@+import { useCallback } from "react";+import { useSelection } from "@/src/features/traces/contexts/SelectionContext";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { useTraceAnalyticsDimensions } from "@/src/features/traces/hooks/useTraceAnalyticsDimensions";+import { useDesktopLayoutContextOptional } from "@/src/features/traces/components/TraceLayoutDesktop";+import { useMobileLayoutContextOptional } from "@/src/features/traces/components/TraceLayoutMobile";++/** Which view is reporting the selection — the only thing that differs. */+export type TraceNodeSelectionSource = "tree" | "timeline" | "timeline_compact";++/**+ * Selecting an observation is four things at once: record it, point the app at+ * it, open the detail panel, and on mobile switch to the tab that shows it. Every+ * view of a trace owes all four, and each one that grew its own copy was a chance+ * for them to drift — so they share this.+ *+ * The panel reopens on EVERY select, including re-selecting the row that is+ * already selected: the URL parameter does not change then, so nothing else would+ * bring the detail back after you collapsed it.+ */+export function useSelectTraceNode(source: TraceNodeSelectionSource) {+ const { setSelectedNodeId } = useSelection();+ const capture = usePostHogClientCapture();+ const analyticsDimensions = useTraceAnalyticsDimensions();+ const layout = useDesktopLayoutContextOptional();+ const mobileLayout = useMobileLayoutContextOptional();++ return useCallback(+ (nodeId: string | null) => {+ if (nodeId) {+ capture("trace_detail:node_selected", {+ source,+ ...analyticsDimensions,+ });+ }+ setSelectedNodeId(nodeId);+ layout?.expandDetailPanel();+ if (nodeId) mobileLayout?.switchToInfoTab();+ },+ [+ source,+ capture,+ analyticsDimensions,+ setSelectedNodeId,+ layout,+ mobileLayout,+ ],+ );+}