🪢 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): custom graph renderer + trace playback (LFE-10577) (#14659)
Nikita Kabardinc128cd998e3d
diff --git a/.agents/skills/seed-test-data/SKILL.md b/.agents/skills/seed-test-data/SKILL.mdindex 0b7e3acc96..70d720a783 100644--- a/.agents/skills/seed-test-data/SKILL.md+++ b/.agents/skills/seed-test-data/SKILL.md@@ -34,6 +34,7 @@ this.| A very complex observation tree (v3) | `pnpm run seed -- trace-tree --observations 5000 --depth 12 --breadth 500` || The same tree readable in the v4 events UI | add `--v4` (writes `events_full`; `events_core` fills via MV) || 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 super tough session (v3 legacy session view) | `pnpm run seed -- long-session --traces 300 --observations-per-trace 8` || Many traces for list/filter performance | `pnpm run seed -- many-traces --count 100000 --days 14` || Scores with spaces in the name (filter/grammar testing) | `pnpm run seed -- scored-traces --traces 24 --v4` |diff --git a/packages/shared/scripts/seeder/AGENTS.md b/packages/shared/scripts/seeder/AGENTS.mdindex 4771dc4a5a..fa24131d25 100644--- a/packages/shared/scripts/seeder/AGENTS.md+++ b/packages/shared/scripts/seeder/AGENTS.md@@ -9,6 +9,7 @@ verification, and deep links.pnpm run seed -- doctor # check the stack; prints the fix per failurepnpm run seed -- list # scenarios and flags (--json for machines)pnpm run seed -- trace-tree --observations 5000 --breadth 500 --v4+pnpm run seed -- agent-timeline --turns 6 --v4 # realistic agent flow-with-loop over a timeline (graph view)pnpm run seed -- long-session --traces 300 --observations-per-trace 8pnpm run seed -- many-traces --count 100000 --days 14pnpm run seed -- scored-traces --traces 24 --v4 # scores w/ spaces in the namediff --git a/packages/shared/scripts/seeder/scenarios/agent-timeline.ts b/packages/shared/scripts/seeder/scenarios/agent-timeline.tsnew file mode 100644index 0000000000..ec02b9681a--- /dev/null+++ b/packages/shared/scripts/seeder/scenarios/agent-timeline.ts@@ -0,0 +1,413 @@+import {+ createTrace,+ createObservation,+ createTracesCh,+ createObservationsCh,+ createEventsCh,+ ObservationRecordInsertType,+} from "../../../src/server";+import { ObservationType } from "../../../src/domain";+import { observationToEvent, traceToEvent } from "./event-mirror";+import { buildPayload, generationUsageCost } from "./payload";+import { jitter, Rng, utcDayStartMs } from "./rng";+import {+ chunk,+ ScenarioContext,+ ScenarioDefinition,+ SeedError,+ SeedSummary,+} from "./types";+import { countRows, sessionLink, traceLink } from "./verify";++/**+ * A realistic agent run over a *timeline*: a LangGraph-style refine loop+ * (planner → retriever → generator → critic → back to planner …), unrolled for+ * N turns. Unlike trace-tree (which piles many children under one hub at the+ * same instant), each step here starts after the previous one finishes, so the+ * observations spread across a real ~20-30s timeline with a little parallelism.+ *+ * Node observations carry `langgraph_node` + `langgraph_step` metadata, so the+ * graph view uses its explicit-step model and renders a real flow with a loop+ * (the repeated node names collapse to one vertex each, critic → planner is the+ * refine back-edge). Their LLM/tool children have no langgraph metadata, so they+ * enrich the timeline without becoming graph nodes.+ */++const LANGGRAPH_NODE_TAG = "langgraph_node";+const LANGGRAPH_STEP_TAG = "langgraph_step";++// One turn of the loop: four nodes, each its own super-step.+const LOOP_NODES: { node: string; type: ObservationType }[] = [+ { node: "planner", type: "AGENT" },+ { node: "retriever", type: "RETRIEVER" },+ { node: "generator", type: "GENERATION" },+ { node: "critic", type: "EVALUATOR" },+];++// Rough per-node own-duration windows (ms), min + jitter range.+const DURATION: Record<string, [number, number]> = {+ planner: [350, 500],+ retriever: [150, 300],+ generator: [1200, 2600],+ critic: [500, 700],+};++type PlannedObs = {+ index: number;+ parentIndex: number | null;+ type: ObservationType;+ name: string;+ node: string | null; // langgraph_node (null for child spans)+ step: number | null; // langgraph_step+ startOffset: number;+ endOffset: number;+ isGeneration: boolean;+};++const run = async (+ ctx: ScenarioContext,+ params: Record<string, string | number | boolean>,+): Promise<SeedSummary> => {+ const startedAt = Date.now();+ const turns = params["turns"] 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+ // defaults true can't be unset via the CLI's presence-only flags, so this is+ // phrased as an opt-in.)+ const withMetadata = !(params["timing-only"] as boolean);++ if (turns < 1) {+ throw new SeedError(+ `--turns must be >= 1, got ${turns}`,+ "pass a positive integer, e.g. --turns 6",+ );+ }++ const rng = new Rng(ctx.seed);+ const traceId = `${ctx.idPrefix}-trace`;+ const sessionId = `${ctx.idPrefix}-session`;+ const traceTimestamp = utcDayStartMs();++ // Plan the observations along a single moving timeline cursor. `cursor` is the+ // ms offset from the trace timestamp; each node step advances it so nothing+ // overlaps across steps (children may overlap within a step = parallelism).+ const planned: PlannedObs[] = [];+ let cursor = 40; // small lead-in before the first node+ let step = 0;++ for (let turn = 0; turn < turns; turn++) {+ for (const { node, type } of LOOP_NODES) {+ step += 1;+ const nodeIndex = planned.length;+ const [dmin, drange] = DURATION[node];+ const ownDuration = dmin + jitter(ctx.seed, step * 7 + 1, drange);+ const nodeStart = cursor;+ const nodeEnd = nodeStart + ownDuration;++ planned.push({+ index: nodeIndex,+ parentIndex: null, // top-level node span under the trace+ type,+ name: node,+ node,+ step,+ startOffset: nodeStart,+ endOffset: nodeEnd,+ isGeneration: type === "GENERATION",+ });++ // Child work inside this node's window (no langgraph metadata → timeline+ // detail, not graph nodes). Some run in parallel to show a busy slice.+ const childSpecs: { type: ObservationType; name: string }[] =+ node === "planner"+ ? [{ type: "GENERATION", name: "plan-llm" }]+ : node === "retriever"+ ? [+ { type: "EMBEDDING", name: "query-embedding" },+ { type: "TOOL", name: "vector-search" },+ ]+ : node === "critic"+ ? [{ type: "GENERATION", name: "critique-llm" }]+ : []; // generator IS the LLM call — no child++ childSpecs.forEach((child, ci) => {+ // stagger children a touch; retriever's two run in parallel (same start)+ const childStart = nodeStart + 5 + (node === "retriever" ? 0 : ci * 20);+ const childEnd = Math.min(+ nodeEnd - 5,+ childStart + Math.max(20, Math.floor(ownDuration * 0.7)),+ );+ planned.push({+ index: planned.length,+ parentIndex: nodeIndex,+ type: child.type,+ name: child.name,+ node: null,+ step: null,+ startOffset: childStart,+ endOffset: Math.max(childStart + 10, childEnd),+ isGeneration: child.type === "GENERATION",+ });+ });++ cursor = nodeEnd + 20 + jitter(ctx.seed, step * 7 + 2, 60); // gap to next step+ }+ }++ if (ctx.dryRun) {+ return {+ scenario: "agent-timeline",+ target: "clickhouse",+ params,+ projectId: ctx.projectId,+ environment: ctx.environment,+ traceIds: [traceId],+ sessionIds: [sessionId],+ counts: {+ traces: 1,+ observations: planned.length,+ events: withV4 ? planned.length + 1 : 0,+ },+ verified: {},+ links: [+ traceLink(ctx, traceId, traceTimestamp),+ sessionLink(ctx, sessionId),+ ],+ dryRun: true,+ durationMs: Date.now() - startedAt,+ };+ }++ const rootInput = JSON.stringify({+ question: "How do I get a refund for a duplicate charge on my invoice?",+ });+ const rootOutput = JSON.stringify({+ answer:+ "I found the duplicate charge and issued a refund; it should appear in 3-5 business days.",+ turns,+ });++ const trace = createTrace({+ id: traceId,+ project_id: ctx.projectId,+ environment: ctx.environment,+ name: `seed-agent-timeline (${turns} turns)`,+ timestamp: traceTimestamp,+ user_id: `user-${ctx.idPrefix}`,+ session_id: sessionId,+ release: "seed-1.0.0",+ version: "seed-agent-v1",+ tags: ["seed", "agent-timeline"],+ public: false,+ bookmarked: false,+ metadata: { scenario: "agent-timeline", seed: String(ctx.seed) },+ input: rootInput,+ output: rootOutput,+ created_at: Date.now(),+ updated_at: Date.now(),+ event_ts: Date.now(),+ });++ const observations: ObservationRecordInsertType[] = planned.map((p) => {+ const start = traceTimestamp + p.startOffset;+ const end = traceTimestamp + p.endOffset;+ const durationMs = p.endOffset - p.startOffset;+ const usageInput = rng.int(200, 3000);+ const usageOutput = rng.int(50, 1200);+ const metadata: Record<string, string> = {+ scenario: "agent-timeline",+ };+ if (withMetadata && p.node !== null && p.step !== null) {+ metadata[LANGGRAPH_NODE_TAG] = p.node;+ metadata[LANGGRAPH_STEP_TAG] = String(p.step);+ }++ return createObservation({+ id: `${ctx.idPrefix}-obs-${p.index}`,+ trace_id: traceId,+ project_id: ctx.projectId,+ environment: ctx.environment,+ type: p.type,+ parent_observation_id:+ p.parentIndex === null ? null : `${ctx.idPrefix}-obs-${p.parentIndex}`,+ name: p.name,+ start_time: start,+ end_time: end,+ // Clamp the time-to-first-token into the observation's own window so+ // completion_start_time never lands after end_time (short generations).+ // Exactly one rng.int draw either way — the rng stream is unchanged.+ completion_start_time: p.isGeneration+ ? start + Math.min(rng.int(60, 300), Math.max(10, durationMs - 10))+ : null,+ level: "DEFAULT",+ status_message: null,+ version: null,+ input: p.isGeneration+ ? JSON.stringify({+ messages: [+ { role: "system", content: "You are a helpful support agent." },+ {+ role: "user",+ content: buildPayload("text", rng.int(200, 800), rng),+ },+ ],+ })+ : p.node+ ? JSON.stringify({ node: p.node, step: p.step })+ : null,+ output: p.isGeneration+ ? buildPayload("text", rng.int(150, 700), rng)+ : null,+ metadata,+ provided_model_name: p.isGeneration ? "gpt-4o" : null,+ internal_model_id: null,+ model_parameters: p.isGeneration+ ? JSON.stringify({ temperature: 0.2, max_tokens: 1024 })+ : "{}",+ // Empty fields stay explicit for non-generations: the createObservation+ // factory would otherwise fill non-empty usage/cost defaults.+ ...(p.isGeneration+ ? generationUsageCost(usageInput, usageOutput)+ : {+ 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+ ? [+ traceToEvent(trace),+ ...observations.map((o) => observationToEvent(o, trace)),+ ]+ : [];++ const counts: Record<string, number> = {+ traces: 1,+ observations: observations.length,+ events: events.length,+ };++ ctx.log(+ `writing 1 trace (${turns} turns), ${observations.length} observations${withV4 ? `, ${events.length} events` : ""}`,+ );+ await createTracesCh([trace]);+ for (const batch of chunk(observations, 1000)) {+ await createObservationsCh(batch);+ }+ for (const batch of chunk(events, 500)) {+ await createEventsCh(batch);+ }++ const verified: Record<string, number> = {+ traces: await countRows(+ "traces",+ `project_id = {projectId: String} AND id = {traceId: String}`,+ { projectId: ctx.projectId, traceId },+ "uniqExact(id)",+ ),+ observations: await countRows(+ "observations",+ `project_id = {projectId: String} AND trace_id = {traceId: String}`,+ { projectId: ctx.projectId, traceId },+ "uniqExact(id)",+ ),+ };+ if (withMetadata) {+ // The langgraph metadata is what this scenario exists to seed (the graph+ // view's explicit-step model) — verify it landed, not just the row counts.+ verified.langgraphNodes = await countRows(+ "observations",+ `project_id = {projectId: String} AND trace_id = {traceId: String} AND metadata[{nodeTag: String}] != ''`,+ { projectId: ctx.projectId, traceId, nodeTag: LANGGRAPH_NODE_TAG },+ `uniqExact(metadata[{nodeTag: String}])`,+ );+ }+ if (withV4) {+ verified.events = await countRows(+ "events_full",+ `project_id = {projectId: String} AND trace_id = {traceId: String}`,+ { projectId: ctx.projectId, traceId },+ "uniqExact(span_id)",+ );+ }++ if (verified.traces < 1) {+ throw new SeedError(+ `Readback mismatch: trace ${traceId} not found after insert`,+ );+ }+ if (verified.observations < observations.length) {+ throw new SeedError(+ `Readback mismatch: expected ${observations.length} observations, found ${verified.observations}`,+ );+ }+ if (withMetadata && verified.langgraphNodes < LOOP_NODES.length) {+ throw new SeedError(+ `Readback mismatch: expected ${LOOP_NODES.length} distinct langgraph_node metadata values, found ${verified.langgraphNodes}`,+ );+ }+ if (withV4 && verified.events < events.length) {+ throw new SeedError(+ `Readback mismatch: expected ${events.length} events_full rows, found ${verified.events}`,+ );+ }++ return {+ scenario: "agent-timeline",+ target: "clickhouse",+ params,+ projectId: ctx.projectId,+ environment: ctx.environment,+ traceIds: [traceId],+ sessionIds: [sessionId],+ counts,+ verified,+ links: [+ traceLink(ctx, traceId, traceTimestamp),+ sessionLink(ctx, sessionId),+ ],+ dryRun: false,+ durationMs: Date.now() - startedAt,+ };+};++export const agentTimelineScenario: ScenarioDefinition = {+ name: "agent-timeline",+ description:+ "One trace: a realistic LangGraph-style refine-loop agent (planner → retriever → generator → critic → loop) unrolled over N turns, with observations staggered across a real timeline and langgraph_node/step metadata. Exercises the graph's real-flow-with-loop rendering and a scrubbable timeline (vs. trace-tree's all-at-once hub).",+ supportsV4: true,+ flags: [+ {+ flag: "turns",+ type: "number",+ default: 6,+ description:+ "refine-loop iterations (each is planner→retriever→generator→critic)",+ },+ {+ flag: "timing-only",+ type: "boolean",+ default: false,+ description:+ "omit langgraph_node/langgraph_step metadata, so the graph is built from the pure timing-based fallback (every observation becomes a node)",+ },+ {+ flag: "v4",+ type: "boolean",+ default: false,+ description: "also mirror into v4 events_full/events_core",+ },+ ],+ run,+};diff --git a/packages/shared/scripts/seeder/scenarios/index.ts b/packages/shared/scripts/seeder/scenarios/index.tsindex 6498a54922..0f6df41901 100644--- a/packages/shared/scripts/seeder/scenarios/index.ts+++ b/packages/shared/scripts/seeder/scenarios/index.ts@@ -1,3 +1,4 @@+import { agentTimelineScenario } from "./agent-timeline";import { annotationQueueScenario } from "./annotation-queue";import { longSessionScenario } from "./long-session";import { manyTracesScenario } from "./many-traces";@@ -10,6 +11,7 @@ import { ScenarioDefinition } from "./types";*/export const scenarios: Record<string, ScenarioDefinition> = {"trace-tree": traceTreeScenario,+ "agent-timeline": agentTimelineScenario,"long-session": longSessionScenario,"many-traces": manyTracesScenario,"scored-traces": scoredTracesScenario,diff --git a/packages/shared/scripts/seeder/scenarios/long-session.ts b/packages/shared/scripts/seeder/scenarios/long-session.tsindex c807dbc019..a040475c82 100644--- a/packages/shared/scripts/seeder/scenarios/long-session.ts+++ b/packages/shared/scripts/seeder/scenarios/long-session.ts@@ -14,7 +14,7 @@ import {TraceRecordInsertType,} from "../../../src/server";import { observationToEvent, traceToEvent } from "./event-mirror";-import { buildPayload, PayloadStyle } from "./payload";+import { buildPayload, generationUsageCost, PayloadStyle } from "./payload";import { jitter, Rng, utcDayStartMs } from "./rng";import {chunk,@@ -233,33 +233,18 @@ const run = async (model_parameters: isGeneration? JSON.stringify({ temperature: 0.7 }): "{}",- provided_usage_details: isGeneration- ? {- input: usageInput,- output: usageOutput,- total: usageInput + usageOutput,- }- : {},- usage_details: isGeneration- ? {- input: usageInput,- output: usageOutput,- total: usageInput + usageOutput,- }- : {},- provided_cost_details: isGeneration- ? { input: usageInput * 2e-6, output: usageOutput * 6e-6 }- : {},- cost_details: isGeneration- ? {- input: usageInput * 2e-6,- output: usageOutput * 6e-6,- total: usageInput * 2e-6 + usageOutput * 6e-6,- }- : {},- total_cost: isGeneration- ? usageInput * 2e-6 + usageOutput * 6e-6- : null,+ // Empty fields stay explicit for non-generations: the+ // createObservation factory would otherwise fill non-empty+ // usage/cost defaults.+ ...(isGeneration+ ? generationUsageCost(usageInput, usageOutput)+ : {+ provided_usage_details: {},+ usage_details: {},+ provided_cost_details: {},+ cost_details: {},+ total_cost: null,+ }),prompt_id: null,prompt_name: null,prompt_version: null,diff --git a/packages/shared/scripts/seeder/scenarios/payload.ts b/packages/shared/scripts/seeder/scenarios/payload.tsindex 7476b0103d..caede9c73d 100644--- a/packages/shared/scripts/seeder/scenarios/payload.ts+++ b/packages/shared/scripts/seeder/scenarios/payload.ts@@ -10,6 +10,43 @@ export const PAYLOAD_STYLES: PayloadStyle[] = ["bignum",];+export const GEN_INPUT_PRICE = 2e-6;+export const GEN_OUTPUT_PRICE = 6e-6;++/**+ * The usage/cost field block every scenario attaches to GENERATION+ * observations. Token counts stay caller-computed (usually from the rng+ * stream) so extracting this shared shape cannot shift any scenario's rng+ * consumption. Non-generations must keep their explicit empty `{}` fields at+ * the call site — the createObservation factory would otherwise fill+ * non-empty defaults.+ */+export const generationUsageCost = (+ usageInput: number,+ usageOutput: number,+) => ({+ provided_usage_details: {+ input: usageInput,+ output: usageOutput,+ total: usageInput + usageOutput,+ },+ usage_details: {+ input: usageInput,+ output: usageOutput,+ total: usageInput + usageOutput,+ },+ provided_cost_details: {+ input: usageInput * GEN_INPUT_PRICE,+ output: usageOutput * GEN_OUTPUT_PRICE,+ },+ cost_details: {+ input: usageInput * GEN_INPUT_PRICE,+ output: usageOutput * GEN_OUTPUT_PRICE,+ total: usageInput * GEN_INPUT_PRICE + usageOutput * GEN_OUTPUT_PRICE,+ },+ total_cost: usageInput * GEN_INPUT_PRICE + usageOutput * GEN_OUTPUT_PRICE,+});+const WORDS = ["retrieval","latency",diff --git a/packages/shared/scripts/seeder/scenarios/trace-tree.ts b/packages/shared/scripts/seeder/scenarios/trace-tree.tsindex d84413e0c6..216df59f6e 100644--- a/packages/shared/scripts/seeder/scenarios/trace-tree.ts+++ b/packages/shared/scripts/seeder/scenarios/trace-tree.ts@@ -11,7 +11,12 @@ import {} from "../../../src/server";import { ObservationType } from "../../../src/domain";import { observationToEvent, traceToEvent } from "./event-mirror";-import { buildPayload, PayloadStyle, PAYLOAD_STYLES } from "./payload";+import {+ buildPayload,+ generationUsageCost,+ PayloadStyle,+ PAYLOAD_STYLES,+} from "./payload";import { jitter, Rng, utcDayStartMs } from "./rng";import {chunk,@@ -389,31 +394,17 @@ const run = async (model_parameters: isGeneration? JSON.stringify({ temperature: 0.2, max_tokens: 1024 }): "{}",- provided_usage_details: isGeneration- ? {- input: usageInput,- output: usageOutput,- total: usageInput + usageOutput,- }- : {},- usage_details: isGeneration- ? {- input: usageInput,- output: usageOutput,- total: usageInput + usageOutput,- }- : {},- provided_cost_details: isGeneration- ? { input: usageInput * 2e-6, output: usageOutput * 6e-6 }- : {},- cost_details: isGeneration- ? {- input: usageInput * 2e-6,- output: usageOutput * 6e-6,- total: usageInput * 2e-6 + usageOutput * 6e-6,- }- : {},- total_cost: isGeneration ? usageInput * 2e-6 + usageOutput * 6e-6 : null,+ // Empty fields stay explicit for non-generations: the createObservation+ // factory would otherwise fill non-empty usage/cost defaults.+ ...(isGeneration+ ? generationUsageCost(usageInput, usageOutput)+ : {+ provided_usage_details: {},+ usage_details: {},+ provided_cost_details: {},+ cost_details: {},+ total_cost: null,+ }),prompt_id: null,prompt_name: null,prompt_version: null,diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 34afa7c0f4..831a387a0b 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -650,6 +650,12 @@ importers:csv-parse:specifier: ^5.6.0version: 5.6.0+ d3-selection:+ specifier: ^3.0.0+ version: 3.0.0+ d3-zoom:+ specifier: ^3.0.0+ version: 3.0.0date-fns:specifier: ^3.6.0version: 3.6.0@@ -665,6 +671,9 @@ importers:dompurify:specifier: ^3.4.11version: 3.4.11+ elkjs:+ specifier: ^0.11.1+ version: 0.11.1fastest-levenshtein:specifier: ^1.0.16version: 1.0.16@@ -800,9 +809,6 @@ importers:vaul:specifier: ^1.1.2version: 1.1.2(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- vis-network:- specifier: ^9.1.13- version: 9.1.13(@egjs/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected])([email protected](@egjs/[email protected])([email protected])))([email protected](@egjs/[email protected])([email protected]))yaml:specifier: ^2.9.0version: 2.9.0@@ -861,6 +867,12 @@ importers:'@types/cors':specifier: ^2.8.19version: 2.8.19+ '@types/d3-selection':+ specifier: ^3.0.11+ version: 3.0.11+ '@types/d3-zoom':+ specifier: ^3.0.8+ version: 3.0.8'@types/eslint':specifier: ^9.6.1version: 9.6.1@@ -1915,10 +1927,6 @@ packages:peerDependencies:react: '>=16.8.0'- '@egjs/[email protected]':- resolution: {integrity: sha512-XQsZgjm2EcVUiZQf11UBJQfmZeEmOW8DpI1gsFeln6w0ae0ii4dMQEQ0kjl6DspdWX1aGY1/loyXnP0JS06e/A==}- engines: {node: '>=0.8.0'}-'@emnapi/[email protected]':resolution: {integrity: sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==}@@ -5735,9 +5743,6 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==}- '@types/[email protected]':- resolution: {integrity: sha512-ynRvcq6wvqexJ9brDMS4BnBLzmr0e14d6ZJTEShTBWKymQiHwlAyGu0ZPEFI2Fh1U53F7tN9ufClWM5KvqkKOw==}-'@types/[email protected]':resolution: {integrity: sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==}@@ -6849,9 +6854,6 @@ packages:resolution: {integrity: sha512-4hm4VPpIecmlg59CHXnRDnqGplJFrbLG4aFEl5vl6cK1u76ws3LLvX7ikFnTDl5vo39sjWD6AaDPYodJp/NNHg==}- resolution: {integrity: sha512-T0+barUSQRTUQASh8bx02dl+DhF54GtIDY13Y3m9oWTklKbb3Wv974meRpeZ3lp1JpLVECWWNHC4vaG2XHXouQ==}-resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==}@@ -7383,6 +7385,9 @@ packages:resolution: {integrity: sha512-IbxXrsTlD3hRodkLnbxAPP4OuJYdWCeM3IOdT+CpcMoIwIoDfCmRpEtSPfwBXxVkg9xmBeY7Lz2Eo2TDn/HC3Q==}+ resolution: {integrity: sha512-zxxR9k+rx5ktMwT/FwyLdPCrq7xN6e4VGGHH8hA01vVYKjTFik7nHOxBnAYtrgYUB1RpAiLvA1/U2YraWxyKKg==}+resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==}@@ -8757,9 +8762,6 @@ packages:resolution: {integrity: sha512-pQpZbdBu7wCTmQUh7ufPmLr0pFoObnGUoL/yhtwJDgmmQpbkg/0HSVti25Fu4rmd1oCR6NGWe9vqTWuWv3GcNA==}hasBin: true- resolution: {integrity: sha512-TyQTtsabOVv3MeOpR92sIKk/br9wxS+zGj4BG7CR8YbK4jM3tyIBaF0zhzeBUMx36/Q/iQLOKKOT+3jOQtemRQ==}-resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==}@@ -11437,29 +11439,6 @@ packages:resolution: {integrity: sha512-SbPDPdDBYp+5MJHhBCAyI7wKM3d5ivekigc2Dk2s7pgbZ9wIgIBYGVw4zGHBml/qTFbexrofXW6Gu4noGxrOwQ==}- resolution: {integrity: sha512-COQsxlVrmcRIbZMMTYwD+C2bxYCFDNQ2EHESklPiInbD/Pk3JZ6qNL84Bp9wWjYjAzXfSlsNaFtRk+hO9yBPWA==}- peerDependencies:- uuid: ^3.4.0 || ^7.0.0 || ^8.0.0 || ^9.0.0- vis-util: ^5.0.1-- resolution: {integrity: sha512-HLeHd5KZS92qzO1kC59qMh1/FWAZxMUEwUWBwDMoj6RKj/Ajkrgy/heEYo0Zc8SZNQ2J+u6omvK2+a28GX1QuQ==}- peerDependencies:- '@egjs/hammerjs': ^2.0.0- component-emitter: ^1.3.0 || ^2.0.0- keycharm: ^0.2.0 || ^0.3.0 || ^0.4.0- uuid: ^3.4.0 || ^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0- vis-data: ^6.3.0 || ^7.0.0- vis-util: ^5.0.1-- resolution: {integrity: sha512-E3L03G3+trvc/X4LXvBfih3YIHcKS2WrP0XTdZefr6W6Qi/2nNCqZfe4JFfJU6DcQLm6Gxqj2Pfl+02859oL5A==}- engines: {node: '>=8'}- peerDependencies:- '@egjs/hammerjs': ^2.0.0- component-emitter: ^1.3.0 || ^2.0.0-resolution: {integrity: sha512-shFOJpGQsWDS1FLm8BR8b6FIQC65pFZ5a0IUFGLiBHAX1eRz0N8TOhUJN4p708zfPBLDXqWzj++ocECe8gSoMg==}peerDependencies:@@ -13330,10 +13309,6 @@ snapshots:react: 19.2.4tslib: 2.8.1- '@egjs/[email protected]':- dependencies:- '@types/hammerjs': 2.0.46-'@emnapi/[email protected]':dependencies:'@emnapi/wasi-threads': 1.2.1@@ -17099,8 +17074,6 @@ snapshots:'@types/[email protected]': {}- '@types/[email protected]': {}-'@types/[email protected]':dependencies:'@types/unist': 3.0.3@@ -18371,8 +18344,6 @@ snapshots:- [email protected]: {}-@@ -18887,6 +18858,8 @@ snapshots:+ [email protected]: {}+@@ -20627,8 +20600,6 @@ snapshots:dependencies:commander: 8.3.0- [email protected]: {}-dependencies:json-buffer: 3.0.1@@ -23774,25 +23745,6 @@ snapshots:d3-time: 3.1.0d3-timer: 3.0.1- [email protected]([email protected])([email protected](@egjs/[email protected])([email protected])):- dependencies:- uuid: 14.0.0- vis-util: 5.0.7(@egjs/[email protected])([email protected])-- [email protected](@egjs/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected])([email protected](@egjs/[email protected])([email protected])))([email protected](@egjs/[email protected])([email protected])):- dependencies:- '@egjs/hammerjs': 2.0.17- component-emitter: 1.3.1- keycharm: 0.4.0- uuid: 14.0.0- vis-util: 5.0.7(@egjs/[email protected])([email protected])-- dependencies:- '@egjs/hammerjs': 2.0.17- component-emitter: 1.3.1-[email protected]([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected](@testing-library/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:'@next/env': 16.0.0diff --git a/web/next.config.mjs b/web/next.config.mjsindex 2f93d92437..b2f06828c5 100644--- a/web/next.config.mjs+++ b/web/next.config.mjs@@ -73,7 +73,7 @@ const nextConfig = {// Agent/browser tooling often targets 127.0.0.1 instead of localhost in dev.allowedDevOrigins: ["127.0.0.1"],staticPageGenerationTimeout: 500, // default is 60. Required for build process for amd- transpilePackages: ["@langfuse/shared", "vis-network/standalone"],+ transpilePackages: ["@langfuse/shared"],reactStrictMode: true,serverExternalPackages: ["dd-trace",diff --git a/web/package.json b/web/package.jsonindex e6fed89715..543c549dbd 100644--- a/web/package.json+++ b/web/package.json@@ -123,11 +123,14 @@"core-js": "^3.38.1","cors": "^2.8.6","csv-parse": "^5.6.0",+ "d3-selection": "^3.0.0",+ "d3-zoom": "^3.0.0","date-fns": "^3.6.0","dd-trace": "5.109.0","decimal.js": "^10.4.3","diff": "^8.0.4","dompurify": "^3.4.11",+ "elkjs": "^0.11.1","fastest-levenshtein": "^1.0.16","https-proxy-agent": "^7.0.6","ioredis": "^5.10.1",@@ -173,7 +176,6 @@"use-query-params": "^2.2.2","uuid": "^14.0.0","vaul": "^1.1.2",- "vis-network": "^9.1.13","yaml": "^2.9.0","zod": "^4.3.6","zustand": "^5.0.14"@@ -195,6 +197,8 @@"@types/bcryptjs": "^2.4.6","@types/chroma-js": "^3.1.2","@types/cors": "^2.8.19",+ "@types/d3-selection": "^3.0.11",+ "@types/d3-zoom": "^3.0.8","@types/eslint": "^9.6.1","@types/lodash": "^4.17.24","@types/node": "24.3.0",diff --git a/web/src/__tests__/buildStepData.clienttest.ts b/web/src/__tests__/buildStepData.clienttest.tsindex 79ee590dbe..be2c24bb48 100644--- a/web/src/__tests__/buildStepData.clienttest.ts+++ b/web/src/__tests__/buildStepData.clienttest.ts@@ -478,6 +478,52 @@ describe("buildStepData", () => {expect(parent!.step!).toBeLessThan(child!.step!);});+ it(+ "should terminate when parent pointers form a cycle and still assign steps to well-formed nodes",+ { timeout: 2000 },+ () => {+ // o1 and o2 name each other as parent (malformed data): without the+ // ancestor-walk cycle guard in assignGlobalTimingSteps this walk would+ // loop forever; the MAX_ITERATIONS bound caps the unsatisfiable+ // constraint loop the cycle creates.+ const observations: AgentGraphDataResponse[] = [+ createMockObservation({+ id: "o1",+ name: "cycle-first",+ startTime: "2025-08-21 18:53:25.000",+ endTime: "2025-08-21 18:53:25.100",+ parentObservationId: "o2",+ }),+ createMockObservation({+ id: "o2",+ name: "cycle-second",+ startTime: "2025-08-21 18:53:25.050",+ endTime: "2025-08-21 18:53:25.150",+ parentObservationId: "o1",+ }),+ createMockObservation({+ id: "root",+ name: "well-formed-root",+ startTime: "2025-08-21 18:53:25.020",+ endTime: "2025-08-21 18:53:25.120",+ parentObservationId: null,+ }),+ ];++ const result = buildStepData(observations);++ const userObservations = result.filter(+ (obs) => !obs.name.includes("__"),+ );+ expect(userObservations).toHaveLength(3);++ const root = userObservations.find(+ (obs) => obs.name === "well-formed-root",+ );+ expect(root?.step).toEqual(expect.any(Number));+ },+ );+it("should handle empty array", () => {const result = buildStepData([]);// Should only have system nodes (__start__, __end__)diff --git a/web/src/components/trace/Trace.tsx b/web/src/components/trace/Trace.tsxindex ef3d72cd8b..fc85ad98fb 100644--- a/web/src/components/trace/Trace.tsx+++ b/web/src/components/trace/Trace.tsx@@ -7,6 +7,7 @@ import { ViewPreferencesProvider } from "./contexts/ViewPreferencesContext";import { SelectionProvider } from "./contexts/SelectionContext";import { SearchProvider } from "./contexts/SearchContext";import { JsonExpansionProvider } from "./contexts/JsonExpansionContext";+import { PlayheadProvider } from "./contexts/PlayheadContext";import { TraceGraphDataProvider } from "./contexts/TraceGraphDataContext";import { TraceLayoutMobile } from "./components/_layout/TraceLayoutMobile";import { TraceLayoutDesktop } from "./components/_layout/TraceLayoutDesktop";@@ -74,7 +75,9 @@ export function Trace({<SelectionProvider><SearchProvider><JsonExpansionProvider>- <TraceContent />+ <PlayheadProvider>+ <TraceContent />+ </PlayheadProvider></JsonExpansionProvider></SearchProvider></SelectionProvider>diff --git a/web/src/components/trace/components/PlaybackControls.tsx b/web/src/components/trace/components/PlaybackControls.tsxnew file mode 100644index 0000000000..3e8214cccc--- /dev/null+++ b/web/src/components/trace/components/PlaybackControls.tsx@@ -0,0 +1,107 @@+/**+ * PlaybackControls - view-agnostic transport for the trace playhead.+ *+ * Lives in the navigation header (shown in Tree AND Timeline views). The+ * play/pause button is wrapped in a circular progress ring that fills as the+ * playhead sweeps the trace's total time — a compact "where are we in the+ * trace" indicator that isn't tied to the gantt. Stop resets it.+ *+ * The ring is driven imperatively off the playhead position feed, so it+ * animates at 60fps without re-rendering (only the play/pause icon flips, via+ * the isPlaying selector).+ */++import { useEffect, useRef } from "react";+import { Pause, Play, Square } from "lucide-react";+import { Button } from "@/src/components/ui/button";+import { usePlayhead, useIsPlaying } from "../contexts/PlayheadContext";+import { useTraceData } from "../contexts/TraceDataContext";++// A 22px ring around the ~28px (h-7) button; 2px stroke reads at this size.+const RING_SIZE = 22;+const RING_STROKE = 2;+const RING_R = (RING_SIZE - RING_STROKE) / 2;+const RING_C = 2 * Math.PI * RING_R;++export function PlaybackControls() {+ const { traceDuration } = useTraceData();+ const { play, pause, stop, getPlayheadSec, subscribePosition } =+ usePlayhead();+ const isPlaying = useIsPlaying();+ const ringRef = useRef<SVGCircleElement>(null);++ // Fill the ring to the current playhead fraction; update imperatively as the+ // playhead moves (no re-render). dashoffset goes C → 0 as progress 0 → 1.+ useEffect(() => {+ const apply = (sec: number) => {+ const frac = traceDuration > 0 ? Math.min(1, sec / traceDuration) : 0;+ if (ringRef.current) {+ ringRef.current.style.strokeDashoffset = String(RING_C * (1 - frac));+ }+ };+ apply(getPlayheadSec());+ return subscribePosition(apply);+ }, [traceDuration, getPlayheadSec, subscribePosition]);++ if (traceDuration <= 0) return null;++ return (+ <div className="ml-1 flex shrink-0 flex-row items-center gap-0.5">+ <Button+ type="button"+ variant="ghost"+ size="icon"+ onClick={isPlaying ? pause : play}+ title={isPlaying ? "Pause playback" : "Play trace over time"}+ aria-label={isPlaying ? "Pause playback" : "Play trace over time"}+ className="relative h-7 w-7"+ >+ <svg+ className="pointer-events-none absolute inset-0 m-auto"+ width={RING_SIZE}+ height={RING_SIZE}+ viewBox={`0 0 ${RING_SIZE} ${RING_SIZE}`}+ aria-hidden="true"+ >+ <circle+ cx={RING_SIZE / 2}+ cy={RING_SIZE / 2}+ r={RING_R}+ fill="none"+ strokeWidth={RING_STROKE}+ className="stroke-muted-foreground/25"+ />+ <circle+ ref={ringRef}+ cx={RING_SIZE / 2}+ cy={RING_SIZE / 2}+ r={RING_R}+ fill="none"+ strokeWidth={RING_STROKE}+ strokeLinecap="round"+ strokeDasharray={RING_C}+ strokeDashoffset={RING_C}+ transform={`rotate(-90 ${RING_SIZE / 2} ${RING_SIZE / 2})`}+ className="stroke-primary-accent"+ />+ </svg>+ {isPlaying ? (+ <Pause className="h-3 w-3" />+ ) : (+ <Play className="h-3 w-3 translate-x-px" />+ )}+ </Button>+ <Button+ type="button"+ variant="ghost"+ size="icon"+ onClick={stop}+ title="Stop playback"+ aria-label="Stop playback"+ className="h-7 w-7"+ >+ <Square className="h-2.5 w-2.5" />+ </Button>+ </div>+ );+}diff --git a/web/src/components/trace/components/TraceGraphView/TraceGraphView.tsx b/web/src/components/trace/components/TraceGraphView/TraceGraphView.tsxindex f423acf288..b388f86dbb 100644--- a/web/src/components/trace/components/TraceGraphView/TraceGraphView.tsx+++ b/web/src/components/trace/components/TraceGraphView/TraceGraphView.tsx@@ -7,9 +7,11 @@import { TraceGraphView as TraceGraphViewComponent } from "@/src/features/trace-graph-view/components/TraceGraphView";import { useTraceGraphData } from "../../contexts/TraceGraphDataContext";+import { useActiveObservationIds } from "../../contexts/PlayheadContext";export function TraceGraphView() {const { agentGraphData, isLoading } = useTraceGraphData();+ const activeObservationIds = useActiveObservationIds();if (isLoading) {return (@@ -23,5 +25,10 @@ export function TraceGraphView() {return null;}- return <TraceGraphViewComponent agentGraphData={agentGraphData} />;+ return (+ <TraceGraphViewComponent+ agentGraphData={agentGraphData}+ activeObservationIds={activeObservationIds}+ />+ );}diff --git a/web/src/components/trace/components/TraceTimeline/TimelineRows.tsx b/web/src/components/trace/components/TraceTimeline/TimelineRows.tsxnew file mode 100644index 0000000000..ee4377f214--- /dev/null+++ b/web/src/components/trace/components/TraceTimeline/TimelineRows.tsx@@ -0,0 +1,170 @@+/**+ * Memoized virtual-row shells for the timeline.+ *+ * These are the render boundary that keeps playback and hover cheap: each+ * shell subscribes to its OWN row's playhead-active flag+ * (useIsObservationActive — a primitive selector), so a playback boundary+ * crossing re-renders only the rows whose glow flipped, never the whole+ * virtualized list. Every other prop is a primitive or a reference the parent+ * keeps stable (the flattenedItems memo, useCallback handlers, the+ * scores-by-node map), so scroll/hover/selection reconciliation bails out here+ * for unaffected rows.+ */++import { memo } from "react";+import type Decimal from "decimal.js";+import { type ScoreDomain } from "@langfuse/shared";+import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";+import { type TreeNode } from "../../lib/types";+import { type FlatTimelineItem } from "./types";+import { TimelineGutterRow } from "./TimelineGutterRow";+import { TimelineBar } from "./TimelineBar";+import { useIsObservationActive } from "../../contexts/PlayheadContext";+import { cn } from "@/src/utils/tailwind";++interface RowShellSharedProps {+ item: FlatTimelineItem;+ /** Virtual row offset/extent — primitives so the memo can bail on scroll. */+ top: number;+ height: number;+ isSelected: boolean;+ isHovered: boolean;+ /** Stable id/node-taking callbacks created once in the parent. */+ onSelect: (nodeId: string) => void;+ onHover: (node: TreeNode) => void;+}++type GutterRowShellProps = RowShellSharedProps & {+ hasChildren: boolean;+ isCollapsed: boolean;+ onToggleCollapse: (nodeId: string) => void;+};++function TimelineGutterRowShellComponent({+ item,+ top,+ height,+ isSelected,+ isHovered,+ hasChildren,+ isCollapsed,+ onSelect,+ onHover,+ onToggleCollapse,+}: GutterRowShellProps) {+ const nodeId = item.node.id;+ // Playhead glow: rows "playing" at the current time light UP (accent tint).+ const isActive = useIsObservationActive(nodeId);++ return (+ <div+ style={{+ position: "absolute",+ top: 0,+ left: 0,+ width: "100%",+ height: `${height}px`,+ transform: `translateY(${top}px)`,+ }}+ className={cn(+ "transition-colors duration-150",+ isActive && "bg-primary-accent/15",+ )}+ >+ <TimelineGutterRow+ item={item}+ isSelected={isSelected}+ isHovered={isHovered}+ onSelect={() => onSelect(nodeId)}+ onHover={() => onHover(item.node)}+ onToggleCollapse={() => onToggleCollapse(nodeId)}+ hasChildren={hasChildren}+ isCollapsed={isCollapsed}+ />+ </div>+ );+}++export const TimelineGutterRowShell = memo(TimelineGutterRowShellComponent);++type ChartRowShellProps = RowShellSharedProps & {+ width: number;+ showDuration: boolean;+ showCostTokens: boolean;+ showScores: boolean;+ showComments: boolean;+ colorCodeMetrics: boolean;+ parentTotalCost?: Decimal;+ parentTotalDuration?: number;+ commentCount: number;+ nodeScores: WithStringifiedMetadata<ScoreDomain>[];+};++function TimelineChartRowShellComponent({+ item,+ top,+ height,+ width,+ isSelected,+ isHovered,+ showDuration,+ showCostTokens,+ showScores,+ showComments,+ colorCodeMetrics,+ parentTotalCost,+ parentTotalDuration,+ commentCount,+ nodeScores,+ onSelect,+ onHover,+}: ChartRowShellProps) {+ const nodeId = item.node.id;+ const isActive = useIsObservationActive(nodeId);++ return (+ <div+ style={{+ position: "absolute",+ top: 0,+ left: 0,+ width: `${width}px`,+ height: `${height}px`,+ transform: `translateY(${top}px)`,+ }}+ className={cn(+ "cursor-pointer transition-colors duration-150",+ // Selected = accent tint so the neutral bar (bg-muted) stays visible+ // against the row; a playhead-active row glows with the same accent;+ // hover stays neutral.+ isSelected+ ? "bg-primary-accent/10"+ : isActive+ ? "bg-primary-accent/15"+ : isHovered+ ? "bg-muted"+ : "",+ )}+ onClick={() => onSelect(nodeId)}+ onMouseEnter={() => onHover(item.node)}+ >+ <TimelineBar+ node={item.node}+ metrics={item.metrics}+ isSelected={isSelected}+ isHovered={isHovered}+ showDuration={showDuration}+ showCostTokens={showCostTokens}+ showScores={showScores}+ showComments={showComments}+ colorCodeMetrics={colorCodeMetrics}+ parentTotalCost={parentTotalCost}+ parentTotalDuration={parentTotalDuration}+ commentCount={commentCount}+ scores={nodeScores}+ />+ </div>+ );+}++export const TimelineChartRowShell = memo(TimelineChartRowShellComponent);diff --git a/web/src/components/trace/components/TraceTimeline/TimelineScale.tsx b/web/src/components/trace/components/TraceTimeline/TimelineScale.tsxindex 7984365745..2aac7383d3 100644--- a/web/src/components/trace/components/TraceTimeline/TimelineScale.tsx+++ b/web/src/components/trace/components/TraceTimeline/TimelineScale.tsx@@ -1,28 +1,37 @@/*** TimelineScale - Renders the time axis at the top of the timeline* Shows time markers with step intervals based on trace duration+ *+ * Ticks are positioned in BAR coordinates ((time / traceDuration) *+ * scaleWidth) — the same mapping the gantt bars, the playhead, and+ * click-to-seek use — so a tick labeled "5.00s" sits exactly where a seek+ * lands at 5.00s. Positioning ticks on a fixed pixel grid instead+ * (index * STEP_SIZE) silently diverges whenever the rounded-up stepSize+ * doesn't equal traceDuration / (scaleWidth / STEP_SIZE), which is almost+ * every real trace.*/import { type TimelineScaleProps } from "./types";-import { STEP_SIZE } from "./timeline-calculations";export function TimelineScale({traceDuration,scaleWidth,stepSize,}: TimelineScaleProps) {- // Calculate how many markers to show. scaleWidth is expected to be the finite- // SCALE_WIDTH constant, but guard against a non-finite / absurd value ever- // reaching here: Array.from({ length }) throws "RangeError: Invalid array- // length" for Infinity and OOMs for an enormous finite length, so clamp to a- // finite, sane upper bound.+ // Guard against non-finite / absurd inputs ever reaching here:+ // Array.from({ length }) throws "RangeError: Invalid array length" for+ // Infinity and OOMs for an enormous finite length, so clamp to a finite,+ // sane upper bound. calculateStepSize keeps the real count at ~10.const safeScaleWidth = Number.isFinite(scaleWidth)? Math.max(0, scaleWidth): 0;- const numMarkers = Math.min(- Math.ceil(safeScaleWidth / STEP_SIZE) + 1,- 10_000,- );+ const numMarkers =+ traceDuration > 0 && stepSize > 0 && Number.isFinite(traceDuration)+ ? Math.min(Math.floor(traceDuration / stepSize) + 1, 10_000)+ : 1;++ const tickLeft = (timeValue: number) =>+ traceDuration > 0 ? (timeValue / traceDuration) * safeScaleWidth : 0;return (// No left margin: the 0s tick must sit exactly at the track origin so the@@ -32,16 +41,11 @@ export function TimelineScale({{Array.from({ length: numMarkers }).map((_, index) => {const timeValue = stepSize * index;- // Only show markers that are within the trace duration- if (timeValue > traceDuration) {- return null;- }-return (<divkey={index}className="absolute h-full border-l text-xs"- style={{ left: `${index * STEP_SIZE}px` }}+ style={{ left: `${tickLeft(timeValue)}px` }}><spanclassName="text-muted-foreground absolute left-2 text-xs"@@ -56,16 +60,16 @@ export function TimelineScale({{/* Grid lines for visual alignment */}<div className="pointer-events-none absolute inset-0">{Array.from({ length: numMarkers }).map((_, index) => {- const timeValue = stepSize * index;- if (timeValue > traceDuration || index === 0) {+ if (index === 0) {return null;}+ const timeValue = stepSize * index;return (<divkey={`grid-${index}`}className="border-border/30 absolute h-full border-l"- style={{ left: `${index * STEP_SIZE}px` }}+ style={{ left: `${tickLeft(timeValue)}px` }}/>);})}diff --git a/web/src/components/trace/components/TraceTimeline/index.tsx b/web/src/components/trace/components/TraceTimeline/index.tsxindex 3f05791143..9133dde677 100644--- a/web/src/components/trace/components/TraceTimeline/index.tsx+++ b/web/src/components/trace/components/TraceTimeline/index.tsx@@ -12,25 +12,45 @@* The time scale sits in an overflow-hidden header strip whose inner is* transform-synced to the chart's horizontal scroll, so the scale stays aligned* with the bars without a scrollbar of its own.+ *+ * Playback: the engine (RAF loop, transport) lives in the shared playhead+ * store (contexts/playheadStore.ts); the transport buttons live in the+ * navigation header (PlaybackControls). This file only draws the vertical+ * playhead line + scrub handle (useTimelinePlayhead) and glows the active rows+ * (each row shell subscribes to its own flag — see TimelineRows.tsx).*/-import { useCallback, useMemo, useRef, useState, useLayoutEffect } from "react";+import {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+ useLayoutEffect,+ type RefObject,+} from "react";import { useVirtualizer } from "@tanstack/react-virtual";import { useTraceData } from "../../contexts/TraceDataContext";import { useSelection } from "../../contexts/SelectionContext";import { useViewPreferences } from "../../contexts/ViewPreferencesContext";+import {+ usePlayhead,+ usePlayheadStore,+ useShowPlayhead,+} from "../../contexts/PlayheadContext";import { useHandlePrefetchObservation } from "../../hooks/useHandlePrefetchObservation";import { flattenTreeWithTimelineMetrics } from "./timeline-flattening";import {calculateStepSize,- calculateTraceDuration,- findEarliestStartTime,+ computeSelectionScrollTarget,+ REVEAL_LEFT_FRACTION,+ REVEAL_MARGIN_PX,SCALE_WIDTH,} from "./timeline-calculations";import { TimelineScale } from "./TimelineScale";-import { TimelineGutterRow } from "./TimelineGutterRow";-import { TimelineBar } from "./TimelineBar";+import { TimelineChartRowShell, TimelineGutterRowShell } from "./TimelineRows";import { useDesktopLayoutContextOptional } from "../_layout/TraceLayoutDesktop";+import { type TreeNode } from "../../lib/types";import { cn } from "@/src/utils/tailwind";// Width of the left name gutter. Resizable; these bound it. Kept slim so the@@ -43,8 +63,170 @@ const GUTTER_WIDTH_MAX = 560;// rendered row height, so the two never drift.const ROW_HEIGHT = 26;+const EMPTY_SCORES: never[] = [];++/**+ * Wire a window-level drag gesture: move events flow to `onMove` until+ * pointerup — and pointercancel (OS gesture, contextmenu, touch interruption),+ * which must also tear down the listener, else the drag ghosts on afterwards.+ * One helper for all three drag sites (gutter resize, scale scrub, handle+ * scrub) so future fixes land once.+ */+function startWindowDrag(onMove: (ev: PointerEvent) => void) {+ const onUp = () => {+ window.removeEventListener("pointermove", onMove);+ window.removeEventListener("pointerup", onUp);+ window.removeEventListener("pointercancel", onUp);+ };+ window.addEventListener("pointermove", onMove);+ window.addEventListener("pointerup", onUp);+ window.addEventListener("pointercancel", onUp);+}++/**+ * The timeline's playhead surface: maps the shared engine onto gantt+ * coordinates. Owns the line/handle refs, the imperative position feed+ * (transforms + slider ARIA + follow-scroll while playing — no React state at+ * 60fps), and the scrub gestures (scale click-drag, handle drag, handle+ * keyboard).+ */+function useTimelinePlayhead({+ traceDuration,+ chartRef,+}: {+ traceDuration: number;+ chartRef: RefObject<HTMLDivElement | null>;+}) {+ const store = usePlayheadStore();+ const { seekToSec, pause, getPlayheadSec, subscribePosition } = usePlayhead();+ const showPlayhead = useShowPlayhead();++ const scaleOuterRef = useRef<HTMLDivElement>(null);+ const playheadLineRef = useRef<HTMLDivElement>(null);+ const playheadHandleRef = useRef<HTMLDivElement>(null);++ // Map a playhead time (seconds from origin) to an x within the gantt content.+ const secToX = useCallback(+ (sec: number) =>+ traceDuration > 0 ? (sec / traceDuration) * SCALE_WIDTH : 0,+ [traceDuration],+ );++ // Position the line + handle imperatively off the engine's position feed (no+ // re-render). They only exist while showPlayhead; re-subscribe when the+ // scale (secToX) changes so the mapping stays correct.+ useEffect(() => {+ if (!showPlayhead) return;+ const apply = (sec: number) => {+ const t = `translateX(${secToX(sec)}px)`;+ if (playheadLineRef.current) playheadLineRef.current.style.transform = t;+ const handle = playheadHandleRef.current;+ if (handle) {+ handle.style.transform = t;+ // Slider semantics for assistive tech, updated on the same feed.+ handle.setAttribute("aria-valuenow", sec.toFixed(2));+ handle.setAttribute("aria-valuetext", `${sec.toFixed(2)} seconds`);+ }+ // Follow the playhead while PLAYING so the sweep never exits the+ // viewport — but never during manual scrubbing or while paused, so we+ // don't hijack the user's horizontal scroll. Instant (runs per frame).+ const chart = chartRef.current;+ if (chart && store.getState().isPlaying) {+ const x = secToX(sec);+ if (+ x < chart.scrollLeft + REVEAL_MARGIN_PX ||+ x > chart.scrollLeft + chart.clientWidth - REVEAL_MARGIN_PX+ ) {+ chart.scrollLeft = Math.max(+ 0,+ x - chart.clientWidth * REVEAL_LEFT_FRACTION,+ );+ }+ }+ };+ apply(getPlayheadSec());+ return subscribePosition(apply);+ }, [+ showPlayhead,+ secToX,+ getPlayheadSec,+ subscribePosition,+ chartRef,+ store,+ ]);++ // Translate a pointer x on the scale into a seek (places/moves the playhead).+ const seekFromClientX = useCallback(+ (clientX: number) => {+ const outer = scaleOuterRef.current;+ if (!outer || traceDuration <= 0) return;+ const contentX =+ clientX -+ outer.getBoundingClientRect().left ++ (chartRef.current?.scrollLeft ?? 0);+ seekToSec((contentX / SCALE_WIDTH) * traceDuration);+ },+ [traceDuration, seekToSec, chartRef],+ );++ const handleScalePointerDown = useCallback(+ (e: React.PointerEvent) => {+ e.preventDefault(); // don't start a text selection on the scale labels+ seekFromClientX(e.clientX); // seekToSec pauses + shows the playhead+ // Click-and-drag on the scale scrubs in one gesture.+ startWindowDrag((ev) => seekFromClientX(ev.clientX));+ },+ [seekFromClientX],+ );++ const handleHandlePointerDown = useCallback(+ (e: React.PointerEvent) => {+ // Grab the handle to scrub without re-seeking to the click x.+ e.preventDefault();+ e.stopPropagation();+ pause();+ startWindowDrag((ev) => seekFromClientX(ev.clientX));+ },+ [pause, seekFromClientX],+ );++ // Keyboard seek on the handle: ←/→ nudge by 1% of the trace, Home/End jump.+ const handleHandleKeyDown = useCallback(+ (e: React.KeyboardEvent) => {+ let next: number | null = null;+ if (e.key === "ArrowLeft") next = getPlayheadSec() - traceDuration / 100;+ else if (e.key === "ArrowRight")+ next = getPlayheadSec() + traceDuration / 100;+ else if (e.key === "Home") next = 0;+ else if (e.key === "End") next = traceDuration;+ if (next == null) return;+ e.preventDefault();+ seekToSec(next);+ },+ [traceDuration, getPlayheadSec, seekToSec],+ );++ return {+ scaleOuterRef,+ playheadLineRef,+ playheadHandleRef,+ showPlayhead,+ secToX,+ getPlayheadSec,+ handleScalePointerDown,+ handleHandlePointerDown,+ handleHandleKeyDown,+ };+}+export function TraceTimeline() {- const { roots, serverScores: scores, comments } = useTraceData();+ const {+ roots,+ serverScores: scores,+ comments,+ traceStartTime,+ traceDuration,+ } = useTraceData();const { collapsedNodes, toggleCollapsed, selectedNodeId, setSelectedNodeId } =useSelection();const {@@ -75,39 +257,16 @@ export function TraceTimeline() {e.preventDefault();const startX = e.clientX;const startWidth = gutterWidth;- const onMove = (ev: PointerEvent) => {+ startWindowDrag((ev) => {const next = startWidth + (ev.clientX - startX);setGutterWidth(Math.min(GUTTER_WIDTH_MAX, Math.max(GUTTER_WIDTH_MIN, next)),);- };- const onUp = () => {- window.removeEventListener("pointermove", onMove);- window.removeEventListener("pointerup", onUp);- window.removeEventListener("pointercancel", onUp);- };- window.addEventListener("pointermove", onMove);- window.addEventListener("pointerup", onUp);- // pointercancel (OS gesture, contextmenu, touch interruption) must also- // tear down the move listener, else the gutter ghost-resizes afterwards.- window.addEventListener("pointercancel", onUp);+ });},[gutterWidth],);- // Timeline origin (the 0s mark): the earliest start time across the WHOLE- // tree, not just the roots. See findEarliestStartTime.- const traceStartTime = useMemo(() => {- return findEarliestStartTime(roots) ?? new Date();- }, [roots]);-- // TODO: Extract aggregation logic to shared utility - duplicated in tree-building.ts and TraceTree.tsx- // Total span of the scale, in seconds, from origin to latest end. See- // calculateTraceDuration.- const traceDuration = useMemo(() => {- return calculateTraceDuration(roots, traceStartTime);- }, [roots, traceStartTime]);-const stepSize = useMemo(() => {return calculateStepSize(traceDuration, SCALE_WIDTH);}, [traceDuration]);@@ -148,29 +307,45 @@ export function TraceTimeline() {overscan: 16,});- // Auto-scroll to selected node on initial load (URL-based navigation only).- const initialNodeIdRef = useRef(selectedNodeId);- const hasScrolledRef = useRef(false);+ // Scroll the selected row into view whenever the selection changes — so+ // selecting a node elsewhere (e.g. clicking it in the graph view) brings the+ // matching timeline row into view. Math lives in computeSelectionScrollTarget+ // (pure, tested); both axes go through ONE scrollTo (two competing smooth+ // animations on the same element clobber each other).+ const prevSelectedIdRef = useRef<string | null | undefined>(undefined);useLayoutEffect(() => {- if (- selectedNodeId &&- !hasScrolledRef.current &&- selectedNodeId === initialNodeIdRef.current- ) {- const index = flattenedItems.findIndex(- (item) => item.node.id === selectedNodeId,- );-- if (index !== -1) {- rowVirtualizer.scrollToIndex(index, {- align: "center",- behavior: "auto",- });- hasScrolledRef.current = true;- }+ if (!selectedNodeId || selectedNodeId === prevSelectedIdRef.current) {+ prevSelectedIdRef.current = selectedNodeId;+ return;}- }, [selectedNodeId, flattenedItems, rowVirtualizer]);++ const index = flattenedItems.findIndex(+ (item) => item.node.id === selectedNodeId,+ );+ // Keep the scroll PENDING when the row is missing (collapsed subtree,+ // level filter) — the ref stays un-advanced, so this retries when+ // flattenedItems changes and the row appears.+ if (index === -1) return;+ const chart = chartRef.current;+ if (!chart) return;++ const isInitial = prevSelectedIdRef.current === undefined;+ prevSelectedIdRef.current = selectedNodeId;++ const { top, left } = computeSelectionScrollTarget({+ index,+ rowHeight: ROW_HEIGHT,+ scrollTop: chart.scrollTop,+ scrollLeft: chart.scrollLeft,+ clientHeight: chart.clientHeight,+ clientWidth: chart.clientWidth,+ barStart: flattenedItems[index]?.metrics.startOffset ?? null,+ isInitial,+ });++ chart.scrollTo({ top, left, behavior: isInitial ? "auto" : "smooth" });+ }, [selectedNodeId, flattenedItems]);// The chart owns the only vertical scroll. The gutter and the time scale are// one-way projections of it (translateY / translateX) updated in the same@@ -254,11 +429,48 @@ export function TraceTimeline() {undefined as (typeof roots)[0]["totalCost"],);}, [roots]);- const parentTotalDuration = traceDuration;+ // MILLISECONDS: TimelineBar heat-maps ownDurationMs against this max, and+ // the tree path (TraceTree rootTotalDuration) is ms too. traceDuration is+ // seconds — passing it raw inflated the heat ratio ×1000, painting every+ // duration label dark red.+ const parentTotalDuration = traceDuration * 1000;++ // Score lookup: one pass over the scores instead of an O(scores) filter per+ // row per render. Two maps preserve the exact TRACE-vs-observation keying:+ // trace rows show every score of the trace, observation rows only their own.+ const { scoresByObservationId, scoresByTraceId } = useMemo(() => {+ const byObservation = new Map<string, typeof scores>();+ const byTrace = new Map<string, typeof scores>();+ for (const score of scores) {+ if (score.observationId) {+ const arr = byObservation.get(score.observationId);+ if (arr) arr.push(score);+ else byObservation.set(score.observationId, [score]);+ }+ if (score.traceId) {+ const arr = byTrace.get(score.traceId);+ if (arr) arr.push(score);+ else byTrace.set(score.traceId, [score]);+ }+ }+ return { scoresByObservationId: byObservation, scoresByTraceId: byTrace };+ }, [scores]);const totalSize = rowVirtualizer.getTotalSize();const virtualItems = rowVirtualizer.getVirtualItems();+ const {+ scaleOuterRef,+ playheadLineRef,+ playheadHandleRef,+ showPlayhead,+ secToX,+ getPlayheadSec,+ handleScalePointerDown,+ handleHandlePointerDown,+ handleHandleKeyDown,+ } = useTimelinePlayhead({ traceDuration, chartRef });+// Classic scrollbars (Windows/Linux) on the chart pane consume client area// the gutter/scale don't: its horizontal scrollbar eats ~15px of height, its// vertical scrollbar ~15px of width. We reserve the matching amount on the@@ -285,115 +497,77 @@ export function TraceTimeline() {return () => ro.disconnect();}, [chartContentWidth, totalSize, gutterWidth]);- const renderRow = (- virtualRow: (typeof virtualItems)[number],- pane: "gutter" | "chart",- ) => {- const item = flattenedItems[virtualRow.index];- if (!item) return null;-- const nodeId = item.node.id;- const isSelected = selectedNodeId === nodeId;- const isHovered = hoveredNodeId === nodeId;- const hasChildren = item.node.children.length > 0;- const isCollapsed = collapsedNodes.has(nodeId);-- const onEnter = () => {- setHoveredNodeId(nodeId);- handleHover(item.node);- };- // Reopen the detail panel on any select — including re-clicking the- // already-selected row, where the URL param (and the effect) wouldn't fire.- const onSelectNode = () => {+ // 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) => {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();- };-- const baseStyle = {- position: "absolute" as const,- top: 0,- left: 0,- height: `${virtualRow.size}px`,- transform: `translateY(${virtualRow.start}px)`,- };-- if (pane === "gutter") {- return (- <div key={nodeId} style={{ ...baseStyle, width: "100%" }}>- <TimelineGutterRow- item={item}- isSelected={isSelected}- isHovered={isHovered}- onSelect={onSelectNode}- onHover={onEnter}- onToggleCollapse={() => toggleCollapsed(nodeId)}- hasChildren={hasChildren}- isCollapsed={isCollapsed}- />- </div>- );- }-- const nodeScores = scores.filter((score) =>- item.node.type === "TRACE"- ? score.traceId === item.node.id- : score.observationId === item.node.id,- );- const commentCount = comments.get(nodeId) ?? 0;-- return (- <div- key={nodeId}- style={{ ...baseStyle, width: `${chartContentWidth}px` }}- className={cn(- "cursor-pointer",- // Selected = accent tint so the neutral bar (bg-muted) stays visible- // against the row; hover stays neutral.- isSelected ? "bg-primary-accent/10" : isHovered ? "bg-muted" : "",- )}- onClick={onSelectNode}- onMouseEnter={onEnter}- >- <TimelineBar- node={item.node}- metrics={item.metrics}- isSelected={isSelected}- isHovered={isHovered}- showDuration={showDuration}- showCostTokens={showCostTokens}- showScores={showScores}- showComments={showComments}- colorCodeMetrics={colorCodeMetrics}- parentTotalCost={parentTotalCost}- parentTotalDuration={parentTotalDuration}- commentCount={commentCount}- scores={nodeScores}- />- </div>- );- };+ },+ [setSelectedNodeId, layout],+ );+ const handleHoverNode = useCallback(+ (node: TreeNode) => {+ setHoveredNodeId(node.id);+ handleHover(node);+ },+ [handleHover],+ );return (<div className="flex h-full w-full flex-col overflow-hidden">- {/* Header: name label + time scale (scale transform-synced, no scrollbar). */}+ {/* Header: name label + time scale (transform-synced). Transport controls+ live in the shared navigation header (see PlaybackControls). */}<div className="flex shrink-0"><div- className="bg-background text-muted-foreground flex shrink-0 items-start pt-0.5 pl-2 text-xs font-medium"+ className="bg-background text-muted-foreground flex shrink-0 items-center pl-2 text-xs font-medium"style={{ width: `${gutterWidth}px` }}>- Name+ <span className="truncate" title="Name">+ Name+ </span></div><div className="bg-border/60 w-px shrink-0" /><div- className="flex-1 overflow-hidden"+ ref={scaleOuterRef}+ onPointerDown={handleScalePointerDown}+ className="flex-1 cursor-pointer overflow-hidden select-none"style={{ marginRight: `${chartScrollbar.x}px` }}>- <div ref={scaleInnerRef} style={{ width: `${chartContentWidth}px` }}>+ <div+ ref={scaleInnerRef}+ className="relative"+ style={{ width: `${chartContentWidth}px` }}+ ><TimelineScaletraceDuration={traceDuration}scaleWidth={SCALE_WIDTH}stepSize={stepSize}/>+ {showPlayhead && (+ <div+ ref={playheadHandleRef}+ role="slider"+ tabIndex={0}+ aria-label="Playhead position"+ aria-valuemin={0}+ aria-valuemax={Number(traceDuration.toFixed(2))}+ aria-valuenow={Number(getPlayheadSec().toFixed(2))}+ onPointerDown={handleHandlePointerDown}+ onKeyDown={handleHandleKeyDown}+ className={cn(+ "absolute top-0 bottom-0 z-30 -ml-1.5 w-3 cursor-ew-resize select-none",+ "focus-visible:ring-ring rounded focus-visible:ring-2 focus-visible:outline-none",+ )}+ style={{+ transform: `translateX(${secToX(getPlayheadSec())}px)`,+ }}+ >+ <div className="bg-primary mx-auto h-2 w-2 rotate-45" />+ </div>+ )}</div></div></div>@@ -429,7 +603,26 @@ export function TraceTimeline() {willChange: "transform",}}>- {virtualItems.map((vr) => renderRow(vr, "gutter"))}+ {virtualItems.map((vr) => {+ const item = flattenedItems[vr.index];+ if (!item) return null;+ const nodeId = item.node.id;+ return (+ <TimelineGutterRowShell+ key={nodeId}+ item={item}+ top={vr.start}+ height={vr.size}+ isSelected={selectedNodeId === nodeId}+ isHovered={hoveredNodeId === nodeId}+ hasChildren={item.node.children.length > 0}+ isCollapsed={collapsedNodes.has(nodeId)}+ onSelect={handleSelectNode}+ onHover={handleHoverNode}+ onToggleCollapse={toggleCollapsed}+ />+ );+ })}</div></div>@@ -460,7 +653,48 @@ export function TraceTimeline() {position: "relative",}}>- {virtualItems.map((vr) => renderRow(vr, "chart"))}+ {virtualItems.map((vr) => {+ const item = flattenedItems[vr.index];+ if (!item) return null;+ const nodeId = item.node.id;+ return (+ <TimelineChartRowShell+ key={nodeId}+ item={item}+ top={vr.start}+ height={vr.size}+ width={chartContentWidth}+ isSelected={selectedNodeId === nodeId}+ isHovered={hoveredNodeId === nodeId}+ showDuration={showDuration}+ showCostTokens={showCostTokens}+ showScores={showScores}+ showComments={showComments}+ colorCodeMetrics={colorCodeMetrics}+ parentTotalCost={parentTotalCost}+ parentTotalDuration={parentTotalDuration}+ commentCount={comments.get(nodeId) ?? 0}+ nodeScores={+ (item.node.type === "TRACE"+ ? scoresByTraceId.get(nodeId)+ : scoresByObservationId.get(nodeId)) ?? EMPTY_SCORES+ }+ onSelect={handleSelectNode}+ onHover={handleHoverNode}+ />+ );+ })}+ {showPlayhead && (+ <div+ ref={playheadLineRef}+ className="bg-primary pointer-events-none absolute top-0 z-20 w-0.5"+ style={{+ left: 0,+ height: `${totalSize}px`,+ transform: `translateX(${secToX(getPlayheadSec())}px)`,+ }}+ />+ )}</div></div></div>diff --git a/web/src/components/trace/components/TraceTimeline/timeline-calculations.clienttest.ts b/web/src/components/trace/components/TraceTimeline/timeline-calculations.clienttest.tsindex 7212ec5bf7..8dba85c906 100644--- a/web/src/components/trace/components/TraceTimeline/timeline-calculations.clienttest.ts+++ b/web/src/components/trace/components/TraceTimeline/timeline-calculations.clienttest.ts@@ -5,8 +5,11 @@ import {calculateTimelineWidth,calculateStepSize,calculateTraceDuration,+ computeSelectionScrollTarget,findEarliestStartTime,getPredefinedStepSizes,+ REVEAL_LEFT_FRACTION,+ REVEAL_MARGIN_PX,SCALE_WIDTH,PREDEFINED_STEP_SIZES,} from "./timeline-calculations";@@ -434,3 +437,96 @@ describe("timeline-calculations", () => {});});});++describe("computeSelectionScrollTarget", () => {+ // A 10-row viewport (260px at 26px rows), 400px wide, scrolled to (0, 0).+ const base = {+ index: 0,+ rowHeight: 26,+ scrollTop: 0,+ scrollLeft: 0,+ clientHeight: 260,+ clientWidth: 400,+ barStart: null,+ isInitial: false,+ };++ it("centers the row on initial load", () => {+ const { top } = computeSelectionScrollTarget({+ ...base,+ index: 100,+ isInitial: true,+ });+ // rowTop 2600, centered: 2600 - (260 - 26) / 2 = 2483+ expect(top).toBe(2483);+ });++ it("clamps the initial center to 0 for rows near the top", () => {+ const { top } = computeSelectionScrollTarget({+ ...base,+ index: 1,+ isInitial: true,+ });+ expect(top).toBe(0);+ });++ it("aligns a row above the fold to the top", () => {+ const { top } = computeSelectionScrollTarget({+ ...base,+ index: 2, // rowTop 52+ scrollTop: 500,+ });+ expect(top).toBe(52);+ });++ it("aligns a row below the fold to the bottom", () => {+ const { top } = computeSelectionScrollTarget({+ ...base,+ index: 50, // rowTop 1300, viewport [0, 260)+ });+ expect(top).toBe(1300 - 260 + 26);+ });++ it("keeps scrollTop for an already-visible row", () => {+ const { top } = computeSelectionScrollTarget({+ ...base,+ index: 5, // rowTop 130, fully inside [0, 260)+ });+ expect(top).toBe(0);+ });++ it("keeps scrollLeft while the bar start sits inside the comfort band", () => {+ const { left } = computeSelectionScrollTarget({+ ...base,+ scrollLeft: 100,+ barStart: 100 + REVEAL_MARGIN_PX, // exactly at the band edge → visible+ });+ expect(left).toBe(100);+ });++ it("reveals an off-screen-right bar a fraction from the left edge", () => {+ const { left } = computeSelectionScrollTarget({+ ...base,+ barStart: 900, // beyond viewRight 400+ });+ expect(left).toBe(900 - 400 * REVEAL_LEFT_FRACTION);+ });++ it("clamps an off-screen-left reveal at 0", () => {+ const { left } = computeSelectionScrollTarget({+ ...base,+ scrollLeft: 600,+ barStart: 10, // far left of the viewport+ });+ expect(left).toBe(0);+ });++ it("keeps scrollLeft when there is no bar (barStart null)", () => {+ const { left } = computeSelectionScrollTarget({+ ...base,+ scrollLeft: 250,+ barStart: null,+ });+ expect(left).toBe(250);+ });+});diff --git a/web/src/components/trace/components/TraceTimeline/timeline-calculations.ts b/web/src/components/trace/components/TraceTimeline/timeline-calculations.tsindex 5ff332c460..911689f55a 100644--- a/web/src/components/trace/components/TraceTimeline/timeline-calculations.ts+++ b/web/src/components/trace/components/TraceTimeline/timeline-calculations.ts@@ -157,3 +157,67 @@ export function calculateStepSize(export function getPredefinedStepSizes(): number[] {return [...PREDEFINED_STEP_SIZES];}++// Horizontal reveal on selection: a bar counts as visible only if it sits at+// least this far inside the viewport; when revealed, it lands this fraction+// from the left edge.+export const REVEAL_MARGIN_PX = 16;+export const REVEAL_LEFT_FRACTION = 0.2;++/**+ * Scroll target that brings a selected row fully into view on BOTH axes with a+ * single scrollTo (two competing smooth animations on one element clobber each+ * other — the vertical one re-fires as it settles and resets the horizontal).+ *+ * Vertical: initial load centers the row; later selections scroll the minimum+ * (above the fold → align top, below → align bottom, visible → unchanged).+ * Horizontal: no-op while the bar start sits comfortably in view, else land it+ * REVEAL_LEFT_FRACTION from the left edge.+ *+ * Pure — see timeline-calculations.clienttest.ts.+ */+export function computeSelectionScrollTarget(args: {+ index: number;+ rowHeight: number;+ scrollTop: number;+ scrollLeft: number;+ clientHeight: number;+ clientWidth: number;+ /** Bar start offset in content px; null = no horizontal component. */+ barStart: number | null;+ isInitial: boolean;+}): { top: number; left: number } {+ const {+ index,+ rowHeight,+ scrollTop,+ scrollLeft,+ clientHeight,+ clientWidth,+ barStart,+ isInitial,+ } = args;++ const rowTop = index * rowHeight;+ let top = scrollTop;+ if (isInitial) {+ top = rowTop - (clientHeight - rowHeight) / 2; // center on load+ } else if (rowTop < scrollTop) {+ top = rowTop; // above the fold → align to top+ } else if (rowTop + rowHeight > scrollTop + clientHeight) {+ top = rowTop - clientHeight + rowHeight; // below → align to bottom+ }++ let left = scrollLeft;+ if (barStart != null) {+ const viewRight = scrollLeft + clientWidth;+ if (+ barStart < scrollLeft + REVEAL_MARGIN_PX ||+ barStart > viewRight - REVEAL_MARGIN_PX+ ) {+ left = Math.max(0, barStart - clientWidth * REVEAL_LEFT_FRACTION);+ }+ }++ return { top: Math.max(0, top), left };+}diff --git a/web/src/components/trace/components/TraceTree.tsx b/web/src/components/trace/components/TraceTree.tsxindex 0f0fa46ca1..fabefd0a66 100644--- a/web/src/components/trace/components/TraceTree.tsx+++ b/web/src/components/trace/components/TraceTree.tsx@@ -9,14 +9,80 @@* This composition pattern allows each component to have a single responsibility.*/+import { memo } from "react";import { VirtualizedTree } from "./_shared/VirtualizedTree";import { VirtualizedTreeNodeWrapper } from "./_shared/VirtualizedTreeNodeWrapper";+import { type TreeNodeMetadata } from "./_shared/VirtualizedTreeNodeWrapper";import { SpanContent } from "./SpanContent";import { useTraceData } from "../contexts/TraceDataContext";import { useSelection } from "../contexts/SelectionContext";+import { useIsObservationActive } from "../contexts/PlayheadContext";import { useHandlePrefetchObservation } from "../hooks/useHandlePrefetchObservation";import { useDesktopLayoutContextOptional } from "./_layout/TraceLayoutDesktop";import { type TreeNode } from "../lib/types";+import { cn } from "@/src/utils/tailwind";+import type Decimal from "decimal.js";++/**+ * Feature-scoped row container: subscribes to the row's OWN playback-active+ * flag so the playhead glow lights tree rows up exactly like timeline rows —+ * and a boundary crossing re-renders only the rows whose flag flipped. Lives+ * here (not in the shared VirtualizedTree) so the shared component stays+ * context-free.+ */+const TraceTreeRow = memo(function TraceTreeRow({+ node,+ treeMetadata,+ isSelected,+ isCollapsed,+ onToggleCollapse,+ onSelect,+ rootTotalCost,+ rootTotalDuration,+ commentCount,+ onHover,+}: {+ node: TreeNode;+ treeMetadata: TreeNodeMetadata;+ isSelected: boolean;+ isCollapsed: boolean;+ onToggleCollapse: () => void;+ onSelect: () => void;+ rootTotalCost?: Decimal;+ rootTotalDuration?: number;+ commentCount?: number;+ onHover: (node: TreeNode) => void;+}) {+ const isActive = useIsObservationActive(node.id);++ return (+ <div+ className={cn(+ "transition-colors duration-150",+ isActive && "bg-primary-accent/15",+ )}+ >+ <VirtualizedTreeNodeWrapper+ metadata={treeMetadata}+ nodeType={node.type}+ hasChildren={node.children.length > 0}+ isCollapsed={isCollapsed}+ onToggleCollapse={onToggleCollapse}+ isSelected={isSelected}+ onSelect={onSelect}+ >+ <SpanContent+ node={node}+ parentTotalCost={rootTotalCost}+ parentTotalDuration={rootTotalDuration}+ commentCount={commentCount}+ onSelect={onSelect}+ onHover={() => onHover(node)}+ />+ </VirtualizedTreeNodeWrapper>+ </div>+ );+});export function TraceTree() {const { roots, comments } = useTraceData();@@ -62,30 +128,20 @@ export function TraceTree() {isCollapsed,onToggleCollapse,onSelect,- }) => {- const typedNode = node as TreeNode;-- return (- <VirtualizedTreeNodeWrapper- metadata={treeMetadata}- nodeType={typedNode.type}- hasChildren={typedNode.children.length > 0}- isCollapsed={isCollapsed}- onToggleCollapse={onToggleCollapse}- isSelected={isSelected}- onSelect={onSelect}- >- <SpanContent- node={typedNode}- parentTotalCost={rootTotalCost}- parentTotalDuration={rootTotalDuration}- commentCount={comments.get(typedNode.id)}- onSelect={onSelect}- onHover={() => handleHover(typedNode)}- />- </VirtualizedTreeNodeWrapper>- );- }}+ }) => (+ <TraceTreeRow+ node={node as TreeNode}+ treeMetadata={treeMetadata}+ isSelected={isSelected}+ isCollapsed={isCollapsed}+ onToggleCollapse={onToggleCollapse}+ onSelect={onSelect}+ rootTotalCost={rootTotalCost}+ rootTotalDuration={rootTotalDuration}+ commentCount={comments.get(node.id)}+ onHover={handleHover}+ />+ )}/>);}diff --git a/web/src/components/trace/components/_layout/TracePanelNavigationHeader.tsx b/web/src/components/trace/components/_layout/TracePanelNavigationHeader.tsxindex cc69aca2fe..d4b9626b58 100644--- a/web/src/components/trace/components/_layout/TracePanelNavigationHeader.tsx+++ b/web/src/components/trace/components/_layout/TracePanelNavigationHeader.tsx@@ -45,6 +45,7 @@ import {downloadServerTraceAsJson,} from "../../lib/download-trace";import { TracePanelNavigationButton } from "./TracePanelNavigationButton";+import { PlaybackControls } from "../PlaybackControls";import { useDesktopLayoutContextOptional } from "./TraceLayoutDesktop";import { toast } from "sonner";import { TRACE_DOWNLOAD_OMIT_LARGE_FIELDS_THRESHOLD } from "@/src/features/traces/shared/traceDownloadConfig";@@ -263,6 +264,10 @@ function TracePanelNavigationHeaderExpanded({</DropdownMenuContent></DropdownMenu>+ {/* Playback transport + circular time-progress ring. View-agnostic:+ shown in both Tree and Timeline views (see PlaybackControls). */}+ <PlaybackControls />+{/* Tree / Timeline segmented switch (labels collapse to icons whenthe panel is narrow — see @container/navheader). */}<ViewModeSwitchdiff --git a/web/src/components/trace/components/_shared/VirtualizedTree.tsx b/web/src/components/trace/components/_shared/VirtualizedTree.tsxindex 6243b40fb4..73a28a8f79 100644--- a/web/src/components/trace/components/_shared/VirtualizedTree.tsx+++ b/web/src/components/trace/components/_shared/VirtualizedTree.tsx@@ -78,31 +78,36 @@ export function VirtualizedTree<T extends { id: string; children: T[] }>({: undefined,});- // Auto-scroll to selected node on initial load (URL-based navigation only)- const initialNodeIdRef = useRef(selectedNodeId);- const hasScrolledRef = useRef(false);+ // Scroll the selected node into view whenever the selection changes — so+ // selecting a node elsewhere (e.g. clicking it in the graph view) brings the+ // matching tree row into view. `align: "auto"` scrolls the minimum needed and+ // is a no-op when the row is already visible, so clicking a visible row never+ // jumps the list.+ const prevSelectedIdRef = useRef<string | null | undefined>(undefined);useLayoutEffect(() => {- if (- selectedNodeId &&- !hasScrolledRef.current &&- selectedNodeId === initialNodeIdRef.current- ) {- const index = flattenedItems.findIndex(- (item) => item.node.id === selectedNodeId,- );-- if (index !== -1) {- // Use behavior: "auto" for instant scroll on initial load to prevent- // visible scroll animation after page render. The synchronous scroll- // completes within useLayoutEffect, before browser paint.- rowVirtualizer.scrollToIndex(index, {- align: "center",- behavior: "auto",- });- hasScrolledRef.current = true;- }+ if (!selectedNodeId || selectedNodeId === prevSelectedIdRef.current) {+ prevSelectedIdRef.current = selectedNodeId;+ return;}++ const index = flattenedItems.findIndex(+ (item) => item.node.id === selectedNodeId,+ );+ // Keep the scroll PENDING when the row is missing (collapsed subtree,+ // level filter) — the ref stays un-advanced, so this retries when+ // flattenedItems changes and the row appears.+ if (index === -1) return;++ const isInitial = prevSelectedIdRef.current === undefined;+ prevSelectedIdRef.current = selectedNodeId;++ // Initial load: center it instantly (no post-paint animation). Later+ // selection changes: minimal, smooth scroll only if it's off-screen.+ rowVirtualizer.scrollToIndex(index, {+ align: isInitial ? "center" : "auto",+ behavior: isInitial ? "auto" : "smooth",+ });}, [selectedNodeId, flattenedItems, rowVirtualizer]);return (diff --git a/web/src/components/trace/contexts/PlayheadContext.tsx b/web/src/components/trace/contexts/PlayheadContext.tsxnew file mode 100644index 0000000000..ed426666c7--- /dev/null+++ b/web/src/components/trace/contexts/PlayheadContext.tsx@@ -0,0 +1,137 @@+/**+ * PlayheadContext - provides the per-mount trace playback store.+ *+ * The engine itself (state, actions, RAF loop) lives in playheadStore.ts as a+ * vanilla Zustand store; this file is only the integration boundary:+ * - creates one store instance per mounted trace view (lazy useState),+ * - syncs trace-derived inputs (duration, activation windows) into the store+ * via a named action whenever the trace or its geometry changes,+ * - exposes narrow hooks so each consumer re-renders only for its slice.+ *+ * The ~60fps playhead position is consumed imperatively via subscribePosition+ * (store.subscribe → write the DOM directly); only discrete flags and the+ * boundary-crossing active Set go through React.+ */++import {+ createContext,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState,+ type ReactNode,+} from "react";+import { useStore } from "zustand";+import { useTraceData } from "./TraceDataContext";+import {+ buildNodeWindows,+ createPlayheadStore,+ type PlayheadStore,+} from "./playheadStore";++const PlayheadStoreContext = createContext<PlayheadStore | null>(null);++export function PlayheadProvider({ children }: { children: ReactNode }) {+ const { trace, roots, traceStartTime, traceDuration } = useTraceData();++ const nodeWindows = useMemo(+ () => buildNodeWindows(roots, traceStartTime),+ [roots, traceStartTime],+ );++ // One engine instance per mounted trace view, seeded synchronously so the+ // first render already sees the real duration (no "controls flash in" frame).+ const [store] = useState(() => {+ const created = createPlayheadStore();+ created.getState().actions.syncTrace({+ traceDuration,+ nodeWindows,+ hard: true,+ });+ return created;+ });++ // Integration boundary: push geometry changes into the store. A different+ // trace id is a hard reset (playback cleared); same-trace churn (level+ // filter, refetch) is a soft sync that re-clamps and keeps playing.+ const syncedTraceIdRef = useRef(trace.id);+ const firstSyncRef = useRef(true);+ useEffect(() => {+ if (firstSyncRef.current) {+ // The lazy initializer above already synced this exact geometry.+ firstSyncRef.current = false;+ return;+ }+ const hard = syncedTraceIdRef.current !== trace.id;+ syncedTraceIdRef.current = trace.id;+ store.getState().actions.syncTrace({ traceDuration, nodeWindows, hard });+ }, [store, trace.id, traceDuration, nodeWindows]);++ // Halt the RAF loop when the trace view unmounts.+ useEffect(() => () => store.getState().actions.pause(), [store]);++ return (+ <PlayheadStoreContext.Provider value={store}>+ {children}+ </PlayheadStoreContext.Provider>+ );+}++export function usePlayheadStore(): PlayheadStore {+ const store = useContext(PlayheadStoreContext);+ if (!store) {+ throw new Error("usePlayheadStore must be used within a PlayheadProvider");+ }+ return store;+}++/**+ * Transport surface: stable actions plus the imperative position feed for+ * ~60fps consumers (the progress ring, the timeline playhead line/handle).+ */+export function usePlayhead() {+ const store = usePlayheadStore();+ return useMemo(+ () => ({+ ...store.getState().actions,+ getPlayheadSec: () => store.getState().playheadSec,+ /** High-frequency position updates — write the DOM, don't setState. */+ subscribePosition: (listener: (sec: number) => void) =>+ store.subscribe((state, prev) => {+ if (state.playheadSec !== prev.playheadSec) {+ listener(state.playheadSec);+ }+ }),+ }),+ [store],+ );+}++/** Whether playback is currently running (re-renders only on play/pause). */+export function useIsPlaying(): boolean {+ return useStore(usePlayheadStore(), (s) => s.isPlaying);+}++/** Whether a playhead has been placed (re-renders only when it toggles). */+export function useShowPlayhead(): boolean {+ return useStore(usePlayheadStore(), (s) => s.showPlayhead);+}++/**+ * The set of observation ids "playing" at the playhead. Re-renders on+ * boundary crossings only. Drives the timeline row glow and (mapped to node+ * names) the graph glow, so both stay in sync.+ */+export function useActiveObservationIds(): ReadonlySet<string> {+ return useStore(usePlayheadStore(), (s) => s.activeIds);+}++/**+ * Per-row glow subscription: re-renders ONLY the row whose membership flipped+ * (a primitive selector), so a boundary crossing never re-renders the whole+ * virtualized list.+ */+export function useIsObservationActive(id: string): boolean {+ return useStore(usePlayheadStore(), (s) => s.activeIds.has(id));+}diff --git a/web/src/components/trace/contexts/TraceDataContext.tsx b/web/src/components/trace/contexts/TraceDataContext.tsxindex c35f3c8c34..ecb3ab612f 100644--- a/web/src/components/trace/contexts/TraceDataContext.tsx+++ b/web/src/components/trace/contexts/TraceDataContext.tsx@@ -26,6 +26,10 @@ import {getObservationLevels,removeHiddenNodes,} from "../lib/tree-building";+import {+ calculateTraceDuration,+ findEarliestStartTime,+} from "../components/TraceTimeline/timeline-calculations";import { useViewPreferences } from "./ViewPreferencesContext";import { useMergedScores } from "@/src/features/scores/lib/useMergedScores";@@ -48,6 +52,12 @@ interface TraceDataContextValue {searchItems: TraceSearchListItem[];hiddenObservationsCount: number;comments: Map<string, number>;+ /** Timeline origin (the 0s mark): earliest start across the whole tree. The+ * single owner of the temporal frame — timeline, playhead, and graph all+ * consume these two instead of re-deriving them. */+ traceStartTime: Date;+ /** Total trace span in seconds, origin → latest end (0 for empty traces). */+ traceDuration: number;}const TraceDataContext = createContext<TraceDataContextValue | null>(null);@@ -128,6 +138,17 @@ export function TraceDataProvider({return { filteredRoots, filteredSearchItems, hiddenObservationsCount };}, [uiData, minObservationLevel]);+ // Temporal frame, derived once from the filtered roots (single source of+ // truth for the timeline scale, the playback engine, and scroll math).+ const traceStartTime = useMemo(+ () => findEarliestStartTime(filteredRoots) ?? new Date(),+ [filteredRoots],+ );+ const traceDuration = useMemo(+ () => calculateTraceDuration(filteredRoots, traceStartTime),+ [filteredRoots, traceStartTime],+ );+// Merge scores with optimistic cacheconst mergedScores = useMergedScores(serverScores,@@ -150,6 +171,8 @@ export function TraceDataProvider({searchItems: filteredSearchItems,hiddenObservationsCount,comments,+ traceStartTime,+ traceDuration,}),[trace,@@ -162,6 +185,8 @@ export function TraceDataProvider({hiddenObservationsCount,uiData.nodeMap,comments,+ traceStartTime,+ traceDuration,],);diff --git a/web/src/components/trace/contexts/playheadStore.clienttest.ts b/web/src/components/trace/contexts/playheadStore.clienttest.tsnew file mode 100644index 0000000000..dd6dfeb7a3--- /dev/null+++ b/web/src/components/trace/contexts/playheadStore.clienttest.ts@@ -0,0 +1,199 @@+// @vitest-environment jsdom++import {+ buildNodeWindows,+ computeActiveIds,+ createPlayheadStore,+ padActivationWindows,+ playbackRate,+ PLAYBACK_MAX_SECONDS,+ type NodeWindow,+} from "./playheadStore";+import { type TreeNode } from "../lib/types";++function makeNode(+ id: string,+ startMs: number,+ endMs: number | null,+ children: TreeNode[] = [],+): TreeNode {+ return {+ id,+ type: "SPAN",+ name: id,+ startTime: new Date(startMs),+ endTime: endMs != null ? new Date(endMs) : null,+ children,+ startTimeSinceTrace: 0,+ startTimeSinceParentStart: null,+ depth: 0,+ childrenDepth: 0,+ } as TreeNode;+}++const ORIGIN = new Date(0);++describe("playbackRate", () => {+ it("plays short traces in real time", () => {+ expect(playbackRate(3)).toBe(1);+ expect(playbackRate(PLAYBACK_MAX_SECONDS)).toBe(1);+ });++ it("compresses long traces to exactly the playback window", () => {+ expect(playbackRate(40)).toBe(40 / PLAYBACK_MAX_SECONDS);+ });+});++describe("buildNodeWindows", () => {+ it("flattens the whole tree into seconds-from-origin windows", () => {+ const roots = [+ makeNode("root", 0, 10_000, [makeNode("child", 2_000, 4_000)]),+ ];+ const windows = buildNodeWindows(roots, ORIGIN);+ const byId = new Map(windows.map((w) => [w.id, w]));+ expect(byId.get("root")).toEqual({ id: "root", startSec: 0, endSec: 10 });+ expect(byId.get("child")).toEqual({ id: "child", startSec: 2, endSec: 4 });+ });++ it("treats a missing endTime as a zero-length window", () => {+ const windows = buildNodeWindows([makeNode("n", 5_000, null)], ORIGIN);+ expect(windows[0]).toEqual({ id: "n", startSec: 5, endSec: 5 });+ });++ it("skips the synthetic TRACE wrapper but keeps its descendants", () => {+ // v3 traces wrap observations in a TRACE root (endTime null) — it must not+ // get an activation window, else padding makes the trace-name row glow+ // briefly at playback start.+ const traceRoot = {+ ...makeNode("trace-t1", 0, null, [makeNode("obs", 1_000, 2_000)]),+ type: "TRACE",+ } as TreeNode;+ const windows = buildNodeWindows([traceRoot], ORIGIN);+ expect(windows.map((w) => w.id)).toEqual(["obs"]);+ });+});++describe("padActivationWindows", () => {+ it("pads zero/short windows to the minimum glow span", () => {+ const windows: NodeWindow[] = [{ id: "n", startSec: 5, endSec: 5 }];+ const [padded] = padActivationWindows(windows, 5); // real-time: rate 1+ expect(padded!.endSec).toBeCloseTo(5.2); // MIN_GLOW_WALL_SECONDS+ });++ it("scales the pad by the compression rate for long traces", () => {+ const windows: NodeWindow[] = [{ id: "n", startSec: 0, endSec: 0 }];+ const [padded] = padActivationWindows(windows, 100); // rate 10+ expect(padded!.endSec).toBeCloseTo(2); // 0.2 wall-clock sec × rate 10+ });++ it("leaves already-long windows untouched (same reference)", () => {+ const w: NodeWindow = { id: "n", startSec: 0, endSec: 9 };+ const [padded] = padActivationWindows([w], 10);+ expect(padded).toBe(w);+ });+});++describe("computeActiveIds", () => {+ const windows: NodeWindow[] = [+ { id: "a", startSec: 0, endSec: 2 },+ { id: "b", startSec: 3, endSec: 3.1 },+ { id: "c", startSec: 5, endSec: 9 },+ ];++ it("point-samples when lo === hi", () => {+ expect([...computeActiveIds(windows, 1, 1)]).toEqual(["a"]);+ expect(computeActiveIds(windows, 4, 4).size).toBe(0);+ });++ it("sweeps the whole interval so short windows can't be skipped", () => {+ // A dropped frame jumping 2.5 → 4.5 still catches b's 100ms window.+ expect([...computeActiveIds(windows, 2.5, 4.5)]).toEqual(["b"]);+ });++ it("includes boundary touches", () => {+ expect(computeActiveIds(windows, 2, 3).has("a")).toBe(true);+ expect(computeActiveIds(windows, 2, 3).has("b")).toBe(true);+ });+});++describe("createPlayheadStore actions", () => {+ const windows: NodeWindow[] = [+ { id: "a", startSec: 0, endSec: 4 },+ { id: "b", startSec: 6, endSec: 10 },+ ];++ function seededStore() {+ const store = createPlayheadStore();+ store.getState().actions.syncTrace({+ traceDuration: 10,+ nodeWindows: windows,+ hard: true,+ });+ return store;+ }++ it("seekToSec clamps, shows the playhead, pauses, and computes the glow", () => {+ const store = seededStore();+ store.getState().actions.seekToSec(99);+ const s = store.getState();+ expect(s.playheadSec).toBe(10);+ expect(s.showPlayhead).toBe(true);+ expect(s.isPlaying).toBe(false);+ expect([...s.activeIds]).toEqual(["b"]);+ });++ it("keeps the activeIds reference stable when the set is unchanged", () => {+ const store = seededStore();+ store.getState().actions.seekToSec(1);+ const first = store.getState().activeIds;+ store.getState().actions.seekToSec(2); // still only "a"+ expect(store.getState().activeIds).toBe(first);+ });++ it("stop clears position, glow, and visibility", () => {+ const store = seededStore();+ store.getState().actions.seekToSec(7);+ store.getState().actions.stop();+ const s = store.getState();+ expect(s.playheadSec).toBe(0);+ expect(s.showPlayhead).toBe(false);+ expect(s.activeIds.size).toBe(0);+ });++ it("hard syncTrace resets playback for a new trace", () => {+ const store = seededStore();+ store.getState().actions.seekToSec(7);+ store.getState().actions.syncTrace({+ traceDuration: 5,+ nodeWindows: [{ id: "x", startSec: 0, endSec: 5 }],+ hard: true,+ });+ const s = store.getState();+ expect(s.traceDuration).toBe(5);+ expect(s.playheadSec).toBe(0);+ expect(s.showPlayhead).toBe(false);+ expect(s.activeIds.size).toBe(0);+ });++ it("soft syncTrace re-clamps the visible playhead against the new duration", () => {+ const store = seededStore();+ store.getState().actions.seekToSec(9);+ store.getState().actions.syncTrace({+ traceDuration: 6,+ nodeWindows: windows,+ hard: false,+ });+ const s = store.getState();+ expect(s.showPlayhead).toBe(true); // playhead survives same-trace churn+ expect(s.playheadSec).toBe(6); // re-clamped to the new duration+ });++ it("play is a no-op without a timeline", () => {+ const store = createPlayheadStore();+ store+ .getState()+ .actions.syncTrace({ traceDuration: 0, nodeWindows: [], hard: true });+ store.getState().actions.play();+ expect(store.getState().isPlaying).toBe(false);+ });+});diff --git a/web/src/components/trace/contexts/playheadStore.ts b/web/src/components/trace/contexts/playheadStore.tsnew file mode 100644index 0000000000..9cf87cb95b--- /dev/null+++ b/web/src/components/trace/contexts/playheadStore.ts@@ -0,0 +1,265 @@+/**+ * playheadStore - the trace playback engine as a per-mount vanilla Zustand store.+ *+ * One store instance per mounted trace view (created by PlayheadProvider with a+ * lazy useState, per the frontend-large-feature-architecture skill). All+ * playback state lives here; all mutations are named store actions. The RAF+ * loop is owned by the store closure and reads live state via get() each tick,+ * so a trace/data change mid-playback can never leave a stale rate or duration+ * running.+ *+ * Consumption model (re-render discipline):+ * - Discrete flags (isPlaying, showPlayhead) and the active-observation Set are+ * read via `useStore(store, selector)` — subscribers re-render only when+ * their slice changes (the active Set changes on boundary crossings, a+ * handful of times per second, never per frame).+ * - The ~60fps playhead position is consumed imperatively: subscribe to the+ * store and write the DOM directly (see subscribePosition in+ * PlayheadContext). playheadSec IS in store state, but nothing subscribes to+ * it through React.+ */++import { createStore, type StoreApi } from "zustand/vanilla";+import { type TreeNode } from "../lib/types";++/** Activation window of one observation, in seconds from the timeline origin. */+export type NodeWindow = { id: string; startSec: number; endSec: number };++export const EMPTY_ACTIVE_IDS: ReadonlySet<string> = new Set();++// Playback compresses to at most this many wall-clock seconds: traces shorter+// than this play in real time; anything longer scales so the whole trace always+// plays in exactly this window (no manual speed control).+export const PLAYBACK_MAX_SECONDS = 10;+// RAF suspends in hidden tabs; cap the resumed delta so playback sweeps+// instead of teleporting to the end after a background-tab or GC stall.+const MAX_FRAME_SECONDS = 0.25;+// End-of-trace epsilon: at/after this close to the end, "play" restarts from 0.+const END_EPSILON_SECONDS = 0.05;+// Every observation glows for at least this many WALL-CLOCK seconds during+// playback, however short it is in trace time (windows are padded by this+// span × the playback rate).+const MIN_GLOW_WALL_SECONDS = 0.2;++export interface PlayheadState {+ /** Total trace span in seconds (0 = no timeline to play). */+ traceDuration: number;+ /** Padded activation windows for every node in the tree. */+ nodeWindows: NodeWindow[];+ /** Playhead time in seconds from the timeline origin. Updated ~60fps during+ * playback — consume imperatively (store.subscribe), not via useStore. */+ playheadSec: number;+ isPlaying: boolean;+ showPlayhead: boolean;+ /** Observations "playing" at the playhead — drives the timeline/graph glow. */+ activeIds: ReadonlySet<string>;+ actions: {+ play: () => void;+ pause: () => void;+ /** Clear the playhead entirely (position, glow, visibility). */+ stop: () => void;+ /** Move the playhead to an absolute time (seconds from origin) and pause. */+ seekToSec: (sec: number) => void;+ /**+ * Integration seam: sync trace-derived inputs into the store.+ * `hard` (a different trace loaded) also resets playback; a soft sync+ * (same trace, roots churn — level filter, refetch) re-clamps the playhead+ * against the new geometry and keeps playback running.+ */+ syncTrace: (input: {+ traceDuration: number;+ nodeWindows: NodeWindow[];+ hard: boolean;+ }) => void;+ };+}++export type PlayheadStore = StoreApi<PlayheadState>;++/** Playback rate in trace-seconds per wall-clock second. */+export function playbackRate(traceDuration: number): number {+ return traceDuration > PLAYBACK_MAX_SECONDS+ ? traceDuration / PLAYBACK_MAX_SECONDS+ : 1;+}++/**+ * Flatten the trace tree into activation windows (seconds from origin).+ * The synthetic TRACE wrapper (v3 traces) gets no window: it isn't an+ * observation, and its zero-width window (endTime null) would otherwise be+ * padded into a brief bogus glow of the trace-name row at playback start.+ * Iterative to avoid stack overflow on deep trees. Pure — unit-testable.+ */+export function buildNodeWindows(+ roots: TreeNode[],+ traceStartTime: Date,+): NodeWindow[] {+ const originMs = traceStartTime.getTime();+ const out: NodeWindow[] = [];+ const stack: TreeNode[] = [...roots];+ while (stack.length > 0) {+ const node = stack.pop()!;+ for (const child of node.children) stack.push(child);+ if (node.type === "TRACE") continue;+ const startSec = (node.startTime.getTime() - originMs) / 1000;+ const endSec =+ ((node.endTime ?? node.startTime).getTime() - originMs) / 1000;+ out.push({ id: node.id, startSec, endSec });+ }+ return out;+}++/**+ * Pad windows so every observation stays active for at least+ * MIN_GLOW_WALL_SECONDS of wall-clock playback — otherwise zero/short-duration+ * observations (events, fast tool calls) would never light up: the playhead+ * samples at frame granularity and playback compresses long traces, so a 5ms+ * span inside a compressed 10s sweep is far narrower than one frame.+ * Activation-only: rendered bar geometry does NOT use these windows. Pure.+ */+export function padActivationWindows(+ windows: NodeWindow[],+ traceDuration: number,+): NodeWindow[] {+ const minSpanSec = MIN_GLOW_WALL_SECONDS * playbackRate(traceDuration);+ return windows.map((w) =>+ w.endSec - w.startSec >= minSpanSec+ ? w+ : { ...w, endSec: w.startSec + minSpanSec },+ );+}++/**+ * The ids active anywhere in the swept interval [lo, hi]. Sweep semantics (not+ * point sampling) so a dropped/throttled frame cannot skip over a short+ * observation without it ever glowing. Pure.+ */+export function computeActiveIds(+ windows: NodeWindow[],+ lo: number,+ hi: number,+): Set<string> {+ const next = new Set<string>();+ for (const w of windows) {+ if (w.startSec <= hi && w.endSec >= lo) next.add(w.id);+ }+ return next;+}++function setsEqual(a: ReadonlySet<string>, b: ReadonlySet<string>): boolean {+ if (a.size !== b.size) return false;+ for (const id of b) if (!a.has(id)) return false;+ return true;+}++function clamp(value: number, min: number, max: number): number {+ return Math.max(min, Math.min(max, value));+}++export function createPlayheadStore(): PlayheadStore {+ // RAF handle + frame clock are per-instance (a trace peek and the full trace+ // page can mount two providers) — they live in this closure, not module scope.+ let raf: number | null = null;+ let lastTs = 0;++ return createStore<PlayheadState>()((set, get) => {+ const cancelRaf = () => {+ if (raf != null) cancelAnimationFrame(raf);+ raf = null;+ };++ // Move the playhead across [prevSec, sec]: clamp, recompute the active set+ // over the swept interval, and commit the Set only when it changed (a+ // boundary crossing) so React subscribers don't wake every frame.+ const positionPlayhead = (sec: number, prevSec = sec) => {+ const { traceDuration, nodeWindows, activeIds } = get();+ const clamped = clamp(sec, 0, traceDuration);+ const lo = Math.min(clamped, clamp(prevSec, 0, traceDuration));+ const next = computeActiveIds(nodeWindows, lo, clamped);+ if (setsEqual(activeIds, next)) {+ set({ playheadSec: clamped });+ } else {+ set({ playheadSec: clamped, activeIds: next });+ }+ };++ const pause = () => {+ cancelRaf();+ set({ isPlaying: false });+ };++ return {+ traceDuration: 0,+ nodeWindows: [],+ playheadSec: 0,+ isPlaying: false,+ showPlayhead: false,+ activeIds: EMPTY_ACTIVE_IDS,+ actions: {+ play: () => {+ if (get().traceDuration <= 0) return;+ cancelRaf();+ set({ showPlayhead: true, isPlaying: true });+ // Restart from the beginning if the playhead is at (or past) the end.+ if (get().playheadSec >= get().traceDuration - END_EPSILON_SECONDS) {+ positionPlayhead(0);+ }+ lastTs = 0;+ const step = (ts: number) => {+ if (!lastTs) lastTs = ts;+ const dt = Math.min((ts - lastTs) / 1000, MAX_FRAME_SECONDS);+ lastTs = ts;+ // Live reads each tick — duration/rate stay correct across+ // same-trace data changes mid-playback.+ const { traceDuration, playheadSec } = get();+ const nextSec = playheadSec + dt * playbackRate(traceDuration);+ if (nextSec >= traceDuration) {+ positionPlayhead(traceDuration, playheadSec);+ pause();+ return;+ }+ positionPlayhead(nextSec, playheadSec);+ raf = requestAnimationFrame(step);+ };+ raf = requestAnimationFrame(step);+ },+ pause,+ stop: () => {+ cancelRaf();+ set({+ playheadSec: 0,+ isPlaying: false,+ showPlayhead: false,+ activeIds: EMPTY_ACTIVE_IDS,+ });+ },+ seekToSec: (sec) => {+ cancelRaf();+ set({ isPlaying: false, showPlayhead: true });+ positionPlayhead(sec);+ },+ syncTrace: ({ traceDuration, nodeWindows, hard }) => {+ const padded = padActivationWindows(nodeWindows, traceDuration);+ if (hard) {+ // A different trace loaded — reset playback entirely.+ cancelRaf();+ set({+ traceDuration,+ nodeWindows: padded,+ playheadSec: 0,+ isPlaying: false,+ showPlayhead: false,+ activeIds: EMPTY_ACTIVE_IDS,+ });+ return;+ }+ // Same trace, new geometry (level filter, refetch): re-clamp the+ // playhead and recompute the glow; playback (live-reading get())+ // continues seamlessly at the new rate.+ set({ traceDuration, nodeWindows: padded });+ if (get().showPlayhead) positionPlayhead(get().playheadSec);+ },+ },+ };+ });+}diff --git a/web/src/features/trace-graph-view/README.md b/web/src/features/trace-graph-view/README.mdnew file mode 100644index 0000000000..aba0fc5e5a--- /dev/null+++ b/web/src/features/trace-graph-view/README.md@@ -0,0 +1,42 @@+# trace-graph-view++Read-only agent-graph renderer for the trace detail view: ELK computes the+layout, we draw HTML nodes over an SVG edge layer, d3-zoom owns the viewport.+Deliberately NOT React Flow / vis-network — the view is read-only and the+custom renderer keeps it virtualization-ready.++## Data flow (one way)++```+agentGraphData (tRPC getAgentGraphData)+ → buildStepData timing-based step inference (cycle-guarded)+ / transformLanggraphToGeneralized when langgraph metadata exists+ → buildGraphCanvasData nodes/edges + node→observations cycling map+ → layout/elkLayout.computeGraphLayout async ELK (lazy import);+ layout/measureNode estimates node boxes (labels, counter reserve)+ → components/ElkGraphRenderer draws + gestures+ components/GraphNode view-only node (memo)+```++## Ownership++- **Viewport**: the d3-zoom transform is the single source of truth. Per-frame+ pan/zoom writes the world div's CSS transform (and the edge+ stroke-compensation var) imperatively — React state holds only the discrete+ derivations (`compact` label threshold, `fitted` reveal, layout/error).+- **Selection**: the `?observation=` URL param, wired in+ `components/TraceGraphView.tsx` (click-cycling through a node's observations,+ URL→node sync with a parent-walk fallback for descendants without their own+ graph node).+- **Playback glow**: the active-observation set comes from+ `web/src/components/trace/contexts/PlayheadContext.tsx` (the engine); THIS+ folder owns only the projection observation-ids → node names+ (`components/TraceGraphView.tsx`) and the glow rendering (`GraphNode`).+- **Pure layout math**: `layout/*` has no React imports and is unit-tested+ (`layout/*.clienttest.ts`).++## Next migration slices++- Move ELK layout into a Web Worker (seam: `layout/elkLayout.ts#getElk`).+- Node virtualization for very large graphs (only render nodes intersecting+ the viewport — the renderer's world/viewport split is already shaped for it).diff --git a/web/src/features/trace-graph-view/buildStepData.ts b/web/src/features/trace-graph-view/buildStepData.tsindex 38617865e7..cedf30530c 100644--- a/web/src/features/trace-graph-view/buildStepData.ts+++ b/web/src/features/trace-graph-view/buildStepData.ts@@ -146,8 +146,12 @@ function assignGlobalTimingSteps(const ancestors = new Set<string>();let current = obsMap.get(obsId);while (current?.parentObservationId) {- ancestors.add(current.parentObservationId);- current = obsMap.get(current.parentObservationId);+ const parentId = current.parentObservationId;+ // Cycle guard: parent pointers are acyclic by DB schema, but a malformed+ // chain (parent already seen) would otherwise loop this walk forever.+ if (ancestors.has(parentId)) break;+ ancestors.add(parentId);+ current = obsMap.get(parentId);}return ancestors;};diff --git a/web/src/features/trace-graph-view/components/ElkGraphRenderer.tsx b/web/src/features/trace-graph-view/components/ElkGraphRenderer.tsxnew file mode 100644index 0000000000..5f9534d413--- /dev/null+++ b/web/src/features/trace-graph-view/components/ElkGraphRenderer.tsx@@ -0,0 +1,521 @@+import React, {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import { select, type Selection } from "d3-selection";+import {+ zoom as createZoom,+ zoomIdentity,+ zoomTransform,+ type D3ZoomEvent,+ type ZoomBehavior,+} from "d3-zoom";+import { ZoomIn, ZoomOut, Maximize } from "lucide-react";++import { Button } from "@/src/components/ui/button";+import { type GraphCanvasData, type GraphNodeData } from "../types";+import { computeGraphLayout, type GraphLayout } from "../layout/elkLayout";+import { GraphNode } from "./GraphNode";++type ElkGraphRendererProps = {+ graph: GraphCanvasData;+ selectedNodeName?: string | null;+ onCanvasNodeNameChange?: (nodeName: string | null) => void;+ nodeToObservationsMap?: Record<string, string[]>;+ currentObservationIndices?: Record<string, number>;+ /**+ * Node names "playing" at the timeline playhead. Nodes in the set glow so the+ * active run stands out as the playhead sweeps. `null`/empty = nothing glows+ * (resting state stays fully visible — no dimming).+ */+ activeNodeNames?: ReadonlySet<string> | null;+};++type Transform = { x: number; y: number; k: number };++const FIT_PADDING = 24;+const SCALE_MIN = 0.05;+const SCALE_MAX = 2;+const MAX_FIT_SCALE = 1.2;+const ZOOM_STEP = 1.4;+// Below this scale labels are unreadable noise — show only node shape + icon.+const LABEL_HIDE_SCALE = 0.5;+// One consistent scale to reveal a selection from a zoomed-out overview, so+// navigating between nodes pans rather than re-zooms (no "zoom jumping").+const SELECTION_REVEAL_SCALE = 0.9;+const CLICK_MOVE_THRESHOLD = 4; // px; beyond this a pointerup is a drag, not a click++function toPath(points: { x: number; y: number }[]): string {+ return points.map((p, i) => `${i === 0 ? "M" : "L"} ${p.x} ${p.y}`).join(" ");+}++function toCss({ x, y, k }: Transform): string {+ return `translate(${x}px, ${y}px) scale(${k})`;+}++/** Edge strokes scale with the world's CSS transform (the SVG is inside the+ * transformed div, so vector-effect can't help) — compensate so they keep a+ * constant on-screen width when zoomed OUT and never vanish. */+function strokeCompensation(k: number): number {+ return Math.max(1, 1 / k);+}++/**+ * Custom read-only graph renderer: ELK lays out the DAG, we draw HTML nodes over+ * an SVG edge layer inside a single transformed "world" container. d3-zoom owns+ * the pan/zoom transform (one source of truth → no view-state drift), and gives+ * us drag-pan, wheel + pinch zoom, and programmatic fit/focus for free.+ *+ * Per-frame gestures stay out of React: the zoom handler writes the world+ * transform (and the edge stroke compensation CSS var) straight to the DOM.+ * React state holds only the discrete derivations — `compact` (labels hidden+ * below a zoom threshold) and `fitted` (first framing applied).+ */+export const ElkGraphRenderer: React.FC<ElkGraphRendererProps> = ({+ graph,+ selectedNodeName = null,+ onCanvasNodeNameChange,+ nodeToObservationsMap = {},+ currentObservationIndices = {},+ activeNodeNames = null,+}) => {+ const containerRef = useRef<HTMLDivElement>(null);+ const worldRef = useRef<HTMLDivElement>(null);+ const transformRef = useRef<Transform>({ x: 0, y: 0, k: 1 });+ const zoomRef = useRef<ZoomBehavior<HTMLDivElement, unknown> | null>(null);+ const selectionRef = useRef<Selection<+ HTMLDivElement,+ unknown,+ null,+ undefined+ > | null>(null);+ // Once the user pans/zooms, stop auto-fitting on resize.+ const userControlledRef = useRef(false);+ // The node id (or null for an empty click) of the last in-canvas selection, so+ // the focus effect re-frames only for selections from the tree/timeline.+ const lastCanvasClickRef = useRef<string | null | undefined>(undefined);+ // The selection last reflected by the focus effect, so a resize (which also+ // re-fires that effect) doesn't re-frame a still-selected node.+ const prevSelectedRef = useRef<string | null>(null);+ const pointerDownPos = useRef<{ x: number; y: number } | null>(null);++ const [layout, setLayout] = useState<GraphLayout | null>(null);+ const [layoutError, setLayoutError] = useState(false);+ const [layoutAttempt, setLayoutAttempt] = useState(0);+ const [size, setSize] = useState({ width: 0, height: 0 });+ // Discrete zoom derivation: labels hide below LABEL_HIDE_SCALE.+ const [compact, setCompact] = useState(false);+ const [hoveredId, setHoveredId] = useState<string | null>(null);+ // Keep the world hidden until the first fit is applied, so we never flash one+ // frame of the unfitted (scale-1, top-left) graph after layout resolves.+ const [fitted, setFitted] = useState(false);++ const nodeMeta = useMemo(() => {+ const map = new Map<string, GraphNodeData>();+ graph.nodes.forEach((node) => map.set(node.id, node));+ return map;+ }, [graph.nodes]);++ // Highlighted node: hover takes precedence over the sticky selection.+ const focusNode = hoveredId ?? selectedNodeName;++ // Observation-cycling counter per node, e.g. " (2/3)".+ const counters = useMemo(() => {+ const map = new Map<string, string>();+ for (const [node, observations] of Object.entries(nodeToObservationsMap)) {+ if (observations.length > 1) {+ const index = currentObservationIndices[node] ?? 0;+ map.set(+ node,+ ` (${observations.length - index}/${observations.length})`,+ );+ }+ }+ return map;+ }, [nodeToObservationsMap, currentObservationIndices]);++ // Compute layout via ELK whenever the graph changes (or a retry is asked).+ useEffect(() => {+ let cancelled = false;+ setLayout(null);+ setLayoutError(false);+ setFitted(false);+ userControlledRef.current = false;+ // Also clear cross-graph view state so a graph change re-focuses the+ // selected node on the new instance and drops stale hover highlighting.+ prevSelectedRef.current = null;+ setHoveredId(null);+ computeGraphLayout(graph, nodeToObservationsMap)+ .then((result) => {+ if (!cancelled) setLayout(result);+ })+ .catch((error) => {+ console.error("Graph layout failed:", error);+ // Guarded so a superseded effect's rejection can't stomp newer state.+ if (!cancelled) setLayoutError(true);+ });+ return () => {+ cancelled = true;+ };+ }, [graph, nodeToObservationsMap, layoutAttempt]);++ // Track container size.+ useEffect(() => {+ const el = containerRef.current;+ if (!el) return;+ const observer = new ResizeObserver(() => {+ setSize({ width: el.clientWidth, height: el.clientHeight });+ });+ observer.observe(el);+ return () => observer.disconnect();+ }, []);++ // Wire up d3-zoom once (drag-pan + wheel/pinch zoom). Per-frame transform+ // updates are written imperatively to the world div — pan/zoom frames commit+ // ZERO React renders (compact/fitted bail on unchanged values).+ useEffect(() => {+ const el = containerRef.current;+ if (!el) return;+ const selection = select(el);+ const zoomBehavior = createZoom<HTMLDivElement, unknown>()+ .scaleExtent([SCALE_MIN, SCALE_MAX])+ .on("zoom", (event: D3ZoomEvent<HTMLDivElement, unknown>) => {+ if (event.sourceEvent) userControlledRef.current = true;+ const { x, y, k } = event.transform;+ transformRef.current = { x, y, k };+ const world = worldRef.current;+ if (world) {+ world.style.transform = toCss(transformRef.current);+ world.style.setProperty(+ "--graph-stroke-comp",+ String(strokeCompensation(k)),+ );+ }+ setCompact(k < LABEL_HIDE_SCALE);+ // First transform (auto-fit or focus) means the graph is framed — reveal it.+ setFitted(true);+ });+ selection.call(zoomBehavior);+ selection.on("dblclick.zoom", null); // don't zoom on double-click+ zoomRef.current = zoomBehavior;+ selectionRef.current = selection;+ return () => {+ selection.on(".zoom", null);+ zoomRef.current = null;+ selectionRef.current = null;+ };+ }, []);++ // Bound panning to a generous frame around the laid-out graph so a drag can+ // never strand the user on a blank canvas (d3-zoom's default translate+ // extent is infinite).+ useEffect(() => {+ const zoomBehavior = zoomRef.current;+ if (!zoomBehavior || !layout) return;+ zoomBehavior.translateExtent([+ [-layout.width, -layout.height],+ [layout.width * 2, layout.height * 2],+ ]);+ }, [layout]);++ // Drive all transform changes through d3-zoom so its internal state stays in+ // sync with what's displayed (otherwise the next gesture jumps).+ const applyTransform = useCallback((next: Transform) => {+ const selection = selectionRef.current;+ const zoomBehavior = zoomRef.current;+ if (!selection || !zoomBehavior) return;+ zoomBehavior.transform(+ selection,+ zoomIdentity.translate(next.x, next.y).scale(next.k),+ );+ }, []);++ const computeFit = useCallback((): Transform | null => {+ if (+ !layout ||+ layout.width === 0 ||+ layout.height === 0 ||+ size.width === 0+ )+ return null;+ // Clamp within d3-zoom's scaleExtent — below SCALE_MIN, applyTransform+ // would write a scale d3 then snaps back on the first gesture (a jump).+ const k = Math.max(+ SCALE_MIN,+ Math.min(+ (size.width - FIT_PADDING * 2) / layout.width,+ (size.height - FIT_PADDING * 2) / layout.height,+ MAX_FIT_SCALE,+ ),+ );+ return {+ k,+ x: (size.width - layout.width * k) / 2,+ y: (size.height - layout.height * k) / 2,+ };+ }, [layout, size]);++ // Auto-fit on layout/size until the user takes control.+ useEffect(() => {+ if (userControlledRef.current) return;+ const fit = computeFit();+ if (fit) applyTransform(fit);+ }, [computeFit, applyTransform]);++ // Reflect external selection (tree/timeline): bring the node into view at the+ // current zoom (or one reveal scale when zoomed out). In-canvas clicks don't+ // move the view; selecting the root/empty returns to the full-graph overview.+ useEffect(() => {+ const cameFromClick = lastCanvasClickRef.current === selectedNodeName;+ lastCanvasClickRef.current = undefined;+ // Only react to an actual selection change. This effect also depends on+ // `size`/`computeFit`, so without this guard a resize / panel-drag would+ // re-frame (and yank) a still-selected node.+ if (prevSelectedRef.current === selectedNodeName) return;+ // Wait for layout/size before acting — and don't mark the selection as+ // reflected yet, so we retry once they're ready (e.g. a deep link with a+ // preselected observation that arrives before the graph lays out).+ if (!layout || size.width === 0) return;+ prevSelectedRef.current = selectedNodeName;+ // In-canvas clicks already selected the node; don't move the view.+ if (cameFromClick) return;++ if (!selectedNodeName) {+ userControlledRef.current = false;+ const fit = computeFit();+ if (fit) applyTransform(fit);+ return;+ }++ const node = layout.nodes.find((n) => n.id === selectedNodeName);+ if (!node) return;+ userControlledRef.current = true;+ // Read d3-zoom's synchronously-updated scale (set by applyTransform before+ // React re-renders), not a state mirror that's stale in the same commit.+ const current = containerRef.current+ ? zoomTransform(containerRef.current).k+ : 1;+ const k = current >= LABEL_HIDE_SCALE ? current : SELECTION_REVEAL_SCALE;+ const cx = node.x + node.width / 2;+ const cy = node.y + node.height / 2;+ applyTransform({+ k,+ x: size.width / 2 - cx * k,+ y: size.height / 2 - cy * k,+ });+ }, [selectedNodeName, layout, size, computeFit, applyTransform]);++ const handleSelect = useCallback(+ (id: string) => {+ lastCanvasClickRef.current = id;+ onCanvasNodeNameChange?.(id);+ },+ [onCanvasNodeNameChange],+ );++ const handleBackgroundClick = (event: React.MouseEvent) => {+ // Ignore the click that ends a drag-pan.+ const down = pointerDownPos.current;+ if (+ down &&+ Math.hypot(event.clientX - down.x, event.clientY - down.y) >+ CLICK_MOVE_THRESHOLD+ ) {+ return;+ }+ lastCanvasClickRef.current = null;+ onCanvasNodeNameChange?.(null);+ };++ const zoomBy = (factor: number) => {+ const selection = selectionRef.current;+ const zoomBehavior = zoomRef.current;+ if (!selection || !zoomBehavior) return;+ userControlledRef.current = true;+ zoomBehavior.scaleBy(selection, factor);+ };++ const handleFit = () => {+ userControlledRef.current = false;+ const fit = computeFit();+ if (fit) applyTransform(fit);+ };++ if (!graph.nodes.length) {+ return (+ <div className="text-muted-foreground flex h-full items-center justify-center text-sm">+ No graph data available+ </div>+ );+ }++ return (+ <div+ ref={containerRef}+ role="group"+ aria-label="Trace agent graph"+ className="bg-background/50 relative h-full w-full cursor-grab overflow-hidden active:cursor-grabbing"+ onPointerDown={(e) =>+ (pointerDownPos.current = { x: e.clientX, y: e.clientY })+ }+ onClick={handleBackgroundClick}+ >+ {!layout && !layoutError && (+ <div className="text-muted-foreground absolute inset-0 flex items-center justify-center text-sm">+ Laying out graph…+ </div>+ )}+ {layoutError && (+ <div className="text-muted-foreground absolute inset-0 flex flex-col items-center justify-center gap-2 text-sm">+ <span>Could not lay out the graph.</span>+ <Button+ variant="outline"+ size="sm"+ onClick={(e) => {+ e.stopPropagation(); // don't treat the retry as a canvas deselect+ setLayoutAttempt((n) => n + 1);+ }}+ >+ Retry+ </Button>+ </div>+ )}++ {layout && (+ <div+ ref={worldRef}+ className="absolute top-0 left-0 origin-top-left"+ style={{+ width: layout.width,+ height: layout.height,+ // Seed from the last known transform so a layout-change remount+ // paints in place instead of at identity; the zoom handler owns+ // every subsequent update imperatively.+ transform: toCss(transformRef.current),+ ["--graph-stroke-comp" as string]: String(+ strokeCompensation(transformRef.current.k),+ ),+ opacity: fitted ? 1 : 0,+ }}+ >+ <svg+ width={layout.width}+ height={layout.height}+ className="pointer-events-none absolute top-0 left-0 overflow-visible"+ >+ <defs>+ <marker+ id="graph-arrow"+ markerUnits="userSpaceOnUse"+ markerWidth="8"+ markerHeight="8"+ refX="7"+ refY="4"+ orient="auto"+ >+ <path+ d="M0,0 L8,4 L0,8 Z"+ className="fill-muted-foreground/50"+ />+ </marker>+ <marker+ id="graph-arrow-active"+ markerUnits="userSpaceOnUse"+ markerWidth="8"+ markerHeight="8"+ refX="7"+ refY="4"+ orient="auto"+ >+ <path d="M0,0 L8,4 L0,8 Z" className="fill-primary" />+ </marker>+ </defs>+ {layout.edges.map((edge) => {+ const active =+ focusNode != null &&+ (edge.source === focusNode || edge.target === focusNode);+ return (+ <path+ key={edge.id}+ d={toPath(edge.points)}+ className={+ active+ ? "stroke-primary fill-none"+ : "stroke-muted-foreground/40 fill-none"+ }+ // Strokes scale with the world transform (vector-effect can't+ // reach across the HTML ancestor) — the CSS var, written by+ // the zoom handler, keeps them visible when zoomed out.+ style={{+ strokeWidth: `calc(${active ? 2 : 1.5}px * var(--graph-stroke-comp, 1))`,+ }}+ markerEnd={+ active ? "url(#graph-arrow-active)" : "url(#graph-arrow)"+ }+ />+ );+ })}+ </svg>+ {layout.nodes.map((node) => {+ const meta = nodeMeta.get(node.id);+ if (!meta) return null;+ return (+ <GraphNode+ key={node.id}+ id={node.id}+ label={meta.label}+ type={meta.type}+ x={node.x}+ y={node.y}+ width={node.width}+ height={node.height}+ counter={counters.get(node.id)}+ selected={node.id === selectedNodeName}+ active={activeNodeNames?.has(node.id) ?? false}+ compact={compact}+ onSelect={handleSelect}+ onHover={setHoveredId}+ />+ );+ })}+ </div>+ )}++ <div+ className="absolute top-2 right-2 z-10 flex flex-col gap-1"+ onClick={(e) => e.stopPropagation()} // controls shouldn't deselect+ >+ <Button+ onClick={() => zoomBy(ZOOM_STEP)}+ variant="outline"+ size="icon"+ className="bg-background/80 h-7 w-7 backdrop-blur"+ title="Zoom in"+ >+ <ZoomIn className="h-4 w-4" />+ </Button>+ <Button+ onClick={() => zoomBy(1 / ZOOM_STEP)}+ variant="outline"+ size="icon"+ className="bg-background/80 h-7 w-7 backdrop-blur"+ title="Zoom out"+ >+ <ZoomOut className="h-4 w-4" />+ </Button>+ <Button+ onClick={handleFit}+ variant="outline"+ size="icon"+ className="bg-background/80 h-7 w-7 backdrop-blur"+ title="Fit to view"+ >+ <Maximize className="h-4 w-4" />+ </Button>+ </div>+ </div>+ );+};diff --git a/web/src/features/trace-graph-view/components/GraphNode.tsx b/web/src/features/trace-graph-view/components/GraphNode.tsxnew file mode 100644index 0000000000..ea8375562a--- /dev/null+++ b/web/src/features/trace-graph-view/components/GraphNode.tsx@@ -0,0 +1,175 @@+import React from "react";++import { renderFilterIcon } from "@/src/components/ItemBadge";+import { cn } from "@/src/utils/tailwind";+import { truncateLabel } from "../layout/measureNode";+import {+ LANGFUSE_START_NODE_NAME,+ LANGFUSE_END_NODE_NAME,+ LANGGRAPH_START_NODE_NAME,+ LANGGRAPH_END_NODE_NAME,+} from "../types";++/**+ * Per-type border accent, matching `ItemBadge`'s icon palette exactly (same+ * shade, same theme-aware muted-* vars) so a node's border, its icon, and the+ * type's badge in the tree/timeline all read as one color across light/dark.+ */+const TYPE_BORDER_CLASS: Record<string, string> = {+ AGENT: "border-purple-600",+ TOOL: "border-orange-600",+ GENERATION: "border-muted-magenta",+ SPAN: "border-muted-blue",+ CHAIN: "border-pink-600",+ RETRIEVER: "border-teal-600",+ EVALUATOR: "border-primary-accent",+ EVENT: "border-muted-green",+ EMBEDDING: "border-amber-600",+ GUARDRAIL: "border-red-600",+};+const DEFAULT_BORDER_CLASS = "border-muted-blue";++const isStartNode = (id: string) =>+ id === LANGFUSE_START_NODE_NAME || id === LANGGRAPH_START_NODE_NAME;+const isEndNode = (id: string) =>+ id === LANGFUSE_END_NODE_NAME || id === LANGGRAPH_END_NODE_NAME;++export type GraphNodeProps = {+ id: string;+ label: string;+ type: string;+ x: number;+ y: number;+ width: number;+ height: number;+ /** Suffix appended after the label, e.g. " (2/3)" for observation cycling. */+ counter?: string;+ selected?: boolean;+ /** "Playing" at the timeline playhead — glows to stand out during playback. */+ active?: boolean;+ /** Hide the text label (when zoomed out) — keeps the box, shows only the icon. */+ compact?: boolean;+ onSelect?: (id: string) => void;+ onHover?: (id: string | null) => void;+};++function GraphNodeComponent({+ id,+ label,+ type,+ x,+ y,+ width,+ height,+ counter,+ selected,+ active,+ compact,+ onSelect,+ onHover,+}: GraphNodeProps) {+ const display = truncateLabel(label);+ const style: React.CSSProperties = { left: x, top: y, width, height };++ const shared = cn(+ "absolute flex select-none items-center justify-center gap-1.5 overflow-hidden rounded-md px-2 text-xs font-medium transition-[box-shadow]",+ onSelect && [+ "cursor-pointer hover:ring-2 hover:ring-ring/40",+ "focus-visible:ring-ring focus-visible:ring-2 focus-visible:outline-none",+ ],+ // Playhead glow ("playing at the playhead"): lift + soft accent halo. Ring+ // colors live in exactly one branch each so tailwind-merge never has to+ // arbitrate: selected+active shares the accent ring (the two signals+ // reinforce), selected-only keeps the neutral selection ring.+ active && "z-10 shadow-[0_0_16px_2px_hsl(var(--primary-accent)/0.65)]",+ active && !selected && "ring-primary-accent ring-2",+ selected &&+ (active+ ? "ring-primary-accent ring-2 ring-offset-1"+ : "ring-ring ring-2 ring-offset-1"),+ );++ // Real-HTML accessibility (the win over the old canvas renderer): selectable+ // nodes are keyboard-focusable buttons announced with their type + label.+ const handlers = onSelect+ ? {+ role: "button" as const,+ tabIndex: 0,+ "aria-label": `${type} ${label}${counter ?? ""}`,+ "aria-pressed": !!selected,+ onClick: (event: React.MouseEvent) => {+ event.stopPropagation(); // don't trigger the canvas background deselect+ onSelect(id);+ },+ onKeyDown: (event: React.KeyboardEvent) => {+ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ event.stopPropagation();+ onSelect(id);+ }+ },+ onMouseEnter: onHover ? () => onHover(id) : undefined,+ onMouseLeave: onHover ? () => onHover(null) : undefined,+ }+ : {+ onMouseEnter: onHover ? () => onHover(id) : undefined,+ onMouseLeave: onHover ? () => onHover(null) : undefined,+ };++ // Tooltip only when the label is hidden (compact) — otherwise the label+ // span's own title covers truncation (both estimator and CSS ellipsis).+ const containerTitle = compact ? label : undefined;++ if (isStartNode(id) || isEndNode(id)) {+ const isStart = isStartNode(id);+ return (+ <div+ style={style}+ title={containerTitle}+ className={cn(+ shared,+ "border-2 text-white",+ isStart+ ? "border-green-700 bg-green-600"+ : "border-red-700 bg-red-600",+ )}+ {...handlers}+ >+ {!compact && (+ <span className="min-w-0 truncate" title={label}>+ {display}+ </span>+ )}+ </div>+ );+ }++ return (+ <div+ style={style}+ title={containerTitle}+ className={cn(+ shared,+ "bg-background text-foreground border-2",+ TYPE_BORDER_CLASS[type] ?? DEFAULT_BORDER_CLASS,+ )}+ {...handlers}+ >+ {renderFilterIcon(type)}+ {!compact && (+ <>+ <span className="min-w-0 truncate" title={label}>+ {display}+ </span>+ {counter && (+ <span className="text-muted-foreground shrink-0 tabular-nums">+ {counter}+ </span>+ )}+ </>+ )}+ </div>+ );+}++export const GraphNode = React.memo(GraphNodeComponent);diff --git a/web/src/features/trace-graph-view/components/TraceGraphCanvas.tsx b/web/src/features/trace-graph-view/components/TraceGraphCanvas.tsxdeleted file mode 100644index 3fb1d51f69..0000000000--- a/web/src/features/trace-graph-view/components/TraceGraphCanvas.tsx+++ /dev/null@@ -1,485 +0,0 @@-import React, { useEffect, useRef, useMemo, useState } from "react";-import { Network, DataSet } from "vis-network/standalone";-import { ZoomIn, ZoomOut, RotateCcw } from "lucide-react";--import type { GraphCanvasData } from "../types";-import {- LANGFUSE_START_NODE_NAME,- LANGFUSE_END_NODE_NAME,- LANGGRAPH_START_NODE_NAME,- LANGGRAPH_END_NODE_NAME,-} from "../types";-import { Button } from "@/src/components/ui/button";--type TraceGraphCanvasProps = {- graph: GraphCanvasData;- selectedNodeName: string | null;- onCanvasNodeNameChange: (nodeName: string | null) => void;- disablePhysics?: boolean;- nodeToObservationsMap?: Record<string, string[]>;- currentObservationIndices?: Record<string, number>;-};--export const TraceGraphCanvas: React.FC<TraceGraphCanvasProps> = (props) => {- const {- graph: graphData,- selectedNodeName,- onCanvasNodeNameChange,- disablePhysics = false,- nodeToObservationsMap = {},- currentObservationIndices = {},- } = props;- const [isHovering, setIsHovering] = useState(false);-- const containerRef = useRef<HTMLDivElement>(null);- const networkRef = useRef<Network | null>(null);- const nodesDataSetRef = useRef<DataSet<any> | null>(null);- const onCanvasNodeNameChangeRef = useRef(onCanvasNodeNameChange);-- // Keep ref up to date without triggering Network recreation- useEffect(() => {- onCanvasNodeNameChangeRef.current = onCanvasNodeNameChange;- }, [onCanvasNodeNameChange]);-- const getNodeStyle = (nodeType: string) => {- switch (nodeType) {- case "AGENT":- return {- border: "#c4b5fd", // purple-300 (former background)- background: "#f3f4f6", // gray-100- highlight: { border: "#a78bfa", background: "#e5e7eb" }, // gray-200- };- case "TOOL":- return {- border: "#fed7aa", // orange-300 (former background)- background: "#f3f4f6", // gray-100- highlight: { border: "#fdba74", background: "#e5e7eb" }, // gray-200- };- case "GENERATION":- return {- border: "#f0abfc", // fuchsia-300 (former background)- background: "#f3f4f6", // gray-100- highlight: { border: "#e879f9", background: "#e5e7eb" }, // gray-200- };- case "SPAN":- return {- border: "#93c5fd", // blue-300 (former background)- background: "#f3f4f6", // gray-100- highlight: { border: "#60a5fa", background: "#e5e7eb" }, // gray-200- };- case "CHAIN":- return {- border: "#f9a8d4", // pink-300 (former background)- background: "#f3f4f6", // gray-100- highlight: { border: "#f472b6", background: "#e5e7eb" }, // gray-200- };- case "RETRIEVER":- return {- border: "#5eead4", // teal-300 (former background)- background: "#f3f4f6", // gray-100- highlight: { border: "#2dd4bf", background: "#e5e7eb" }, // gray-200- };- case "EVENT":- return {- border: "#6ee7b7", // green-300 (former background)- background: "#f3f4f6", // gray-100- highlight: { border: "#34d399", background: "#e5e7eb" }, // gray-200- };- case "EMBEDDING":- return {- border: "#fbbf24", // amber-300 (former background)- background: "#f3f4f6", // gray-100- highlight: { border: "#f59e0b", background: "#e5e7eb" }, // gray-200- };- case "GUARDRAIL":- return {- border: "#fca5a5", // red-300 (former background)- background: "#f3f4f6", // gray-100- highlight: { border: "#f87171", background: "#e5e7eb" }, // gray-200- };- case "LANGGRAPH_SYSTEM":- return {- border: "#d1d5db", // gray (former background)- background: "#f3f4f6", // gray-100- highlight: { border: "#9ca3af", background: "#e5e7eb" }, // gray-200- };- default:- return {- border: "#93c5fd", // blue-300 (former background)- background: "#f3f4f6", // gray-100- highlight: { border: "#60a5fa", background: "#e5e7eb" }, // gray-200- };- }- };-- const nodes = useMemo(- () =>- graphData.nodes.map((node) => {- const nodeData = {- id: node.id,- label: node.label,- color: getNodeStyle(node.type),- };-- // Special positioning and colors for system nodes- if (- node.id === LANGFUSE_START_NODE_NAME ||- node.id === LANGGRAPH_START_NODE_NAME- ) {- return {- ...nodeData,- x: -200,- y: 0,- color: {- border: "#166534", // green- background: "#86efac",- highlight: {- border: "#15803d",- background: "#4ade80",- },- },- };- }- if (- node.id === LANGFUSE_END_NODE_NAME ||- node.id === LANGGRAPH_END_NODE_NAME- ) {- return {- ...nodeData,- x: 200,- y: 0,- color: {- border: "#7f1d1d", // red- background: "#fecaca",- highlight: {- border: "#991b1b",- background: "#fca5a5",- },- },- };- }- return nodeData;- }),- [graphData.nodes],- );-- const options = useMemo(- () => ({- autoResize: true,- layout: {- hierarchical: {- enabled: true,- direction: "UD", // Up-Down (top to bottom)- levelSeparation: 60,- nodeSpacing: 175,- sortMethod: "hubsize",- shakeTowards: "roots",- },- randomSeed: 1,- },- physics: {- enabled: !disablePhysics,- stabilization: {- iterations: disablePhysics ? 0 : 500,- },- },- interaction: {- zoomView: false,- },- nodes: {- shape: "box",- margin: {- top: 10,- right: 10,- bottom: 10,- left: 10,- },- borderWidth: 2,- font: {- size: 14,- color: "#000000",- },- shadow: {- enabled: true,- color: "rgba(0,0,0,0.2)",- size: 3,- x: 3,- y: 3,- },- scaling: {- label: {- enabled: true,- min: 14,- max: 16,- },- },- },- edges: {- arrows: {- to: { enabled: true, scaleFactor: 0.5 },- },- width: 1.5,- color: {- color: "#64748b",- },- selectionWidth: 0,- chosen: false,- },- }),- [disablePhysics],- );-- const handleZoomIn = () => {- if (networkRef.current) {- const currentScale = networkRef.current.getScale();- networkRef.current.moveTo({- scale: currentScale * 1.2,- });- }- };-- const handleZoomOut = () => {- if (networkRef.current) {- const currentScale = networkRef.current.getScale();- networkRef.current.moveTo({- scale: currentScale / 1.2,- });- }- };-- const handleReset = () => {- if (networkRef.current) {- networkRef.current.fit({- animation: {- duration: 300,- easingFunction: "easeInOutQuad",- },- });- }- };-- useEffect(() => {- if (!containerRef.current) {- return;- }-- const nodesDataSet = new DataSet(nodes);- nodesDataSetRef.current = nodesDataSet;-- // Create the network- const network = new Network(- containerRef.current,- { ...graphData, nodes: nodesDataSet },- options,- );- networkRef.current = network;-- // Use click event instead of selectNode/deselectNode to handle cycling properly- network.on("click", (params) => {- if (params.nodes.length > 0) {- // Node was clicked- onCanvasNodeNameChangeRef.current(params.nodes[0]);- } else {- // Empty area was clicked- onCanvasNodeNameChangeRef.current(null);- network.unselectAll();- }- });-- // Prevent dragging the view completely out of bounds- // this resets the graph position so that always a little bit is visible- const constrainView = () => {- const position = network.getViewPosition();- const scale = network.getScale();- const container = containerRef.current;-- if (!container) return;- const containerRect = container.getBoundingClientRect();-- const nodePositions = network.getPositions();- const nodeIds = Object.keys(nodePositions);-- if (nodeIds.length === 0) {- return;- }-- let minX = Infinity,- maxX = -Infinity,- minY = Infinity,- maxY = -Infinity;-- nodeIds.forEach((nodeId) => {- const pos = nodePositions[nodeId];- minX = Math.min(minX, pos.x);- maxX = Math.max(maxX, pos.x);- minY = Math.min(minY, pos.y);- maxY = Math.max(maxY, pos.y);- });-- // Add some padding for node sizes (approximate node width/height)- const nodePadding = 100;- const graphWidth = (maxX - minX + nodePadding * 2) * scale;- const graphHeight = (maxY - minY + nodePadding * 2) * scale;-- // max amount that a graph can be dragged on respective axis- const maxDragX = (containerRect.width / 2 + graphWidth * 0.35) / scale;- const maxDragY = (containerRect.height / 2 + graphHeight * 0.35) / scale;-- // Clamp position within bounds- const constrainedX = Math.max(-maxDragX, Math.min(maxDragX, position.x));- const constrainedY = Math.max(-maxDragY, Math.min(maxDragY, position.y));-- if (constrainedX !== position.x || constrainedY !== position.y) {- network.moveTo({- position: { x: constrainedX, y: constrainedY },- scale: scale,- animation: false,- });- }- };-- // Apply constraints after drag ends- network.on("dragEnd", (params) => {- // only if dragging graph not nodes- if (params.nodes.length === 0) {- constrainView();- }- });-- network.on("zoom", () => {- constrainView();- });-- // force redraw on resetting view- const handleResize = () => {- if (network) {- network.redraw();- network.fit();- }- };-- window.addEventListener("resize", handleResize);-- return () => {- window.removeEventListener("resize", handleResize);- networkRef.current = null;- nodesDataSetRef.current = null;- network.destroy();- };- }, [graphData, nodes, options]);-- // Update node labels when observation indices change, without recreating network- useEffect(() => {- const nodesDataSet = nodesDataSetRef.current;- if (!nodesDataSet) return;-- try {- const updates: { id: string; label: string }[] = [];-- graphData.nodes.forEach((node) => {- const isSystemNode =- node.id === LANGFUSE_START_NODE_NAME ||- node.id === LANGFUSE_END_NODE_NAME ||- node.id === LANGGRAPH_START_NODE_NAME ||- node.id === LANGGRAPH_END_NODE_NAME;-- if (isSystemNode) return;-- const observations = nodeToObservationsMap[node.id] || [];- const currentIndex = currentObservationIndices[node.id] || 0;- const counter =- observations.length > 1- ? ` (${observations.length - currentIndex}/${observations.length})`- : "";-- const newLabel = `${node.label}${counter}`;- updates.push({ id: node.id, label: newLabel });- });-- if (updates.length > 0) {- nodesDataSet.update(updates);- }- } catch (error) {- console.error("Error updating node labels:", error);- }- }, [graphData.nodes, nodeToObservationsMap, currentObservationIndices]);-- useEffect(() => {- const network = networkRef.current;- if (!network) return;-- if (selectedNodeName) {- // Validate that the node exists before trying to select it- const nodeExists = graphData.nodes.some(- (node) => node.id === selectedNodeName,- );-- if (nodeExists) {- try {- network.selectNodes([selectedNodeName]);- } catch (error) {- console.error("Error selecting node:", selectedNodeName, error);- // Fallback to clearing selection- network.unselectAll();- }- } else {- console.warn(- "Cannot select node that doesn't exist:",- selectedNodeName,- );- network.unselectAll();- }- } else {- network.unselectAll();- }- }, [selectedNodeName, graphData.nodes]);-- if (!graphData.nodes.length) {- return (- <div className="flex h-full items-center justify-center">- No graph data available- </div>- );- }-- return (- <div- className="relative h-full min-h-[50dvh] w-full pb-2"- onMouseEnter={() => setIsHovering(true)}- onMouseLeave={() => setIsHovering(false)}- >- {isHovering && (- <div className="absolute top-2 right-2 z-10 flex flex-col gap-1">- <Button- onClick={handleZoomIn}- variant="ghost"- size="icon"- className="dark:shadow-border p-1.5 shadow-md"- title="Zoom in"- >- <ZoomIn className="h-4 w-4" />- </Button>- <Button- onClick={handleZoomOut}- variant="ghost"- size="icon"- className="dark:shadow-border p-1.5 shadow-md"- title="Zoom out"- >- <ZoomOut className="h-4 w-4" />- </Button>- <Button- onClick={handleReset}- variant="ghost"- size="icon"- className="dark:shadow-border p-1.5 shadow-md"- title="Reset view"- >- <RotateCcw className="h-4 w-4" />- </Button>- </div>- )}- <div ref={containerRef} className="h-full w-full" />- </div>- );-};diff --git a/web/src/features/trace-graph-view/components/TraceGraphView.tsx b/web/src/features/trace-graph-view/components/TraceGraphView.tsxindex 1a3e5abfa8..45f82dc402 100644--- a/web/src/features/trace-graph-view/components/TraceGraphView.tsx+++ b/web/src/features/trace-graph-view/components/TraceGraphView.tsx@@ -7,7 +7,7 @@ import React, {} from "react";import { StringParam, useQueryParam } from "use-query-params";-import { TraceGraphCanvas } from "./TraceGraphCanvas";+import { ElkGraphRenderer } from "./ElkGraphRenderer";import { type AgentGraphDataResponse } from "../types";import { buildStepData } from "../buildStepData";import {@@ -21,14 +21,18 @@ import {LANGGRAPH_END_NODE_NAME,} from "../types";-const MAX_NODE_NUMBER_FOR_PHYSICS = 500;-type TraceGraphViewProps = {agentGraphData: AgentGraphDataResponse[];+ /**+ * Observation ids "playing" at the timeline playhead (from PlayheadContext).+ * Mapped to their node names here so the graph glows in sync with the timeline.+ */+ activeObservationIds?: ReadonlySet<string>;};export const TraceGraphView: React.FC<TraceGraphViewProps> = ({agentGraphData,+ activeObservationIds,}) => {const [selectedNodeName, setSelectedNodeName] = useState<string | null>(null);const [currentObservationId, setCurrentObservationId] = useQueryParam(@@ -41,7 +45,14 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({const [previousSelectedNode, setPreviousSelectedNode] = useState<string | null>(null);- const isClickNavigationRef = useRef(false);+ // The observation id the last in-canvas click WROTE to the URL (undefined =+ // no pending click write). Value-compared — a plain boolean flag gets stuck+ // when a click writes the same id the URL already has (the effect never+ // re-fires to clear it) and then swallows the NEXT genuine tree/timeline+ // selection, desyncing the graph highlight.+ const clickWroteObservationIdRef = useRef<string | null | undefined>(+ undefined,+ );const normalizedData = useMemo(() => {const hasStepData = agentGraphData.some(@@ -65,8 +76,33 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({return buildGraphFromStepData(normalizedData);}, [normalizedData]);- const shouldDisablePhysics =- agentGraphData.length >= MAX_NODE_NUMBER_FOR_PHYSICS;+ // Unfiltered observation lookup for the parent-walk fallback below (child+ // observations without a langgraph node are absent from normalizedData).+ const agentGraphById = useMemo(+ () => new Map(agentGraphData.map((o) => [o.id, o])),+ [agentGraphData],+ );++ // observation id → its node name, so the playhead's active-observation set can+ // be projected onto graph nodes (nodeToObservationsMap only holds the top-most+ // of a same-name chain, so build the reverse map from the full data instead).+ const observationToNodeName = useMemo(() => {+ const map = new Map<string, string>();+ for (const o of normalizedData) {+ if (o.id && o.node) map.set(o.id, o.node);+ }+ return map;+ }, [normalizedData]);++ const activeNodeNames = useMemo(() => {+ if (!activeObservationIds || activeObservationIds.size === 0) return null;+ const names = new Set<string>();+ for (const id of activeObservationIds) {+ const name = observationToNodeName.get(id);+ if (name) names.add(name);+ }+ return names;+ }, [activeObservationIds, observationToNodeName]);// Reset indices when graph data changes (new trace loaded)useEffect(() => {@@ -74,15 +110,18 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({}, [normalizedData]);useEffect(() => {- // if this observation ID change came from a click -> skip- if (isClickNavigationRef.current) {- isClickNavigationRef.current = false;- return;+ // Skip genuine echoes of an in-canvas click (the click already selected the+ // node); a stale entry from a no-op write is cleared and IGNORED when a+ // genuinely different observation arrives, so the graph re-syncs.+ if (clickWroteObservationIdRef.current !== undefined) {+ const wrote = clickWroteObservationIdRef.current;+ clickWroteObservationIdRef.current = undefined;+ if (wrote === (currentObservationId ?? null)) return;}- // Find which node and index corresponds to currentObservationId- let foundNodeName = null;- let foundIndex = 0;+ // Find which node and index corresponds to currentObservationId.+ let foundNodeName: string | null = null;+ let foundIndex: number | null = null;for (const [nodeName, observations] of Object.entries(nodeToObservationsMap,@@ -97,15 +136,49 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({}}+ // Fallback for observations not in the cycling map: nested/repeated+ // same-name observations (only the top-most of a same-name chain is+ // registered) map to their own node; descendants WITHOUT a node of their+ // own (e.g. LangGraph child spans, which are filtered out of+ // normalizedData) resolve by walking UP the parent chain in the unfiltered+ // data until an ancestor carries one — so selecting any descendant keeps+ // its enclosing node focused instead of clearing the selection.+ if (!foundNodeName && currentObservationId) {+ const own = normalizedData.find((o) => o.id === currentObservationId);+ if (own?.node) {+ foundNodeName = own.node;+ } else {+ const seen = new Set<string>();+ let cursor = agentGraphById.get(currentObservationId);+ while (cursor && !seen.has(cursor.id)) {+ seen.add(cursor.id);+ if (cursor.node) {+ foundNodeName = cursor.node;+ break;+ }+ cursor = cursor.parentObservationId+ ? agentGraphById.get(cursor.parentObservationId)+ : undefined;+ }+ }+ }+if (foundNodeName &&graph.nodes.some((node) => node.id === foundNodeName)) {setSelectedNodeName(foundNodeName);- setCurrentObservationIndices((prev) => ({- ...prev,- [foundNodeName]: foundIndex,- }));+ // Only sync the cycling index when the id was actually found in the+ // cycling map — fallback-resolved observations must not rewind the+ // node's "(x/N)" counter and next-click cycle position to 0.+ if (foundIndex !== null) {+ const nodeKey = foundNodeName;+ const index = foundIndex;+ setCurrentObservationIndices((prev) => ({+ ...prev,+ [nodeKey]: index,+ }));+ }setPreviousSelectedNode(foundNodeName);} else {setSelectedNodeName(null);@@ -113,9 +186,10 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({}}, [currentObservationId,- agentGraphData,+ agentGraphById,graph.nodes,nodeToObservationsMap,+ normalizedData,]);const onCanvasNodeNameChange = useCallback(@@ -132,7 +206,7 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({// For system nodes, don't set observation ID (they're synthetic)setPreviousSelectedNode(nodeName);setSelectedNodeName(nodeName);- isClickNavigationRef.current = true;+ clickWroteObservationIdRef.current = null;setCurrentObservationId(null);return;}@@ -152,10 +226,10 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({...prev,[nodeName]: targetIndex,}));- isClickNavigationRef.current = true;+ clickWroteObservationIdRef.current = observations[targetIndex];setCurrentObservationId(observations[targetIndex]);} else {- isClickNavigationRef.current = true;+ clickWroteObservationIdRef.current = null;setCurrentObservationId(null);}setPreviousSelectedNode(nodeName);@@ -174,14 +248,14 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({);return (- <div className="grid h-full w-full gap-4">- <TraceGraphCanvas+ <div className="h-full w-full">+ <ElkGraphRenderergraph={graph}selectedNodeName={selectedNodeName}onCanvasNodeNameChange={onCanvasNodeNameChange}- disablePhysics={shouldDisablePhysics}nodeToObservationsMap={nodeToObservationsMap}currentObservationIndices={currentObservationIndices}+ activeNodeNames={activeNodeNames}/></div>);diff --git a/web/src/features/trace-graph-view/layout/elkLayout.clienttest.ts b/web/src/features/trace-graph-view/layout/elkLayout.clienttest.tsnew file mode 100644index 0000000000..21ccb31273--- /dev/null+++ b/web/src/features/trace-graph-view/layout/elkLayout.clienttest.ts@@ -0,0 +1,76 @@+import { type GraphCanvasData, type GraphNodeData } from "../types";+import { computeGraphLayout } from "./elkLayout";++const node = (id: string): GraphNodeData => ({ id, label: id, type: "AGENT" });++describe("computeGraphLayout", () => {+ it("dedupes duplicate edges into a single positioned edge", async () => {+ const graph: GraphCanvasData = {+ nodes: [node("a"), node("b")],+ edges: [+ { from: "a", to: "b" },+ { from: "a", to: "b" },+ ],+ };++ const layout = await computeGraphLayout(graph);++ expect(layout.edges).toHaveLength(1);+ expect(layout.edges[0]).toMatchObject({ source: "a", target: "b" });+ });++ it("keeps distinct edges whose dedupe keys would collide when space-joined", async () => {+ // Node ids are SDK-supplied names that may contain spaces: a naive+ // space-joined key would collapse ("a b" → "c") and ("a" → "b c").+ const graph: GraphCanvasData = {+ nodes: [node("a b"), node("c"), node("a"), node("b c")],+ edges: [+ { from: "a b", to: "c" },+ { from: "a", to: "b c" },+ ],+ };++ const layout = await computeGraphLayout(graph);++ expect(layout.edges).toHaveLength(2);+ const pairs = layout.edges.map((edge) => [edge.source, edge.target]);+ expect(pairs).toContainEqual(["a b", "c"]);+ expect(pairs).toContainEqual(["a", "b c"]);+ });++ it("drops self-loops but still lays out the node", async () => {+ const graph: GraphCanvasData = {+ nodes: [node("x")],+ edges: [{ from: "x", to: "x" }],+ };++ const layout = await computeGraphLayout(graph);++ expect(layout.edges).toHaveLength(0);+ expect(layout.nodes).toHaveLength(1);+ expect(layout.nodes[0].id).toBe("x");+ expect(layout.nodes[0].width).toBeGreaterThan(0);+ });++ it("reserves extra node width for the observation counter", async () => {+ const graph: GraphCanvasData = {+ nodes: [node("important-node")],+ edges: [],+ };++ const single = await computeGraphLayout(graph, {+ "important-node": ["obs-1"],+ });+ const multi = await computeGraphLayout(graph, {+ "important-node": ["obs-1", "obs-2", "obs-3"],+ });++ const singleWidth = single.nodes.find(+ (n) => n.id === "important-node",+ )!.width;+ const multiWidth = multi.nodes.find(+ (n) => n.id === "important-node",+ )!.width;+ expect(multiWidth).toBeGreaterThan(singleWidth);+ });+});diff --git a/web/src/features/trace-graph-view/layout/elkLayout.ts b/web/src/features/trace-graph-view/layout/elkLayout.tsnew file mode 100644index 0000000000..13d89f1de3--- /dev/null+++ b/web/src/features/trace-graph-view/layout/elkLayout.ts@@ -0,0 +1,171 @@+import type { ELK, ElkNode } from "elkjs";++import { type GraphCanvasData } from "../types";+import { measureNode } from "./measureNode";++export interface PositionedNode {+ id: string;+ x: number;+ y: number;+ width: number;+ height: number;+}++export interface PositionedEdge {+ id: string;+ source: string;+ target: string;+ /** Polyline points (start → bend points → end) in layout coordinates. */+ points: { x: number; y: number }[];+}++export interface GraphLayout {+ nodes: PositionedNode[];+ edges: PositionedEdge[];+ /** Bounding size of the laid-out graph. */+ width: number;+ height: number;+}++/**+ * ELK "layered" options for a top-down, deterministic DAG. Orthogonal routing ++ * merged edges keep dense traces from turning into a hairball.+ * @see https://eclipse.dev/elk/reference/algorithms/org-eclipse-elk-layered.html+ */+const LAYOUT_OPTIONS: Record<string, string> = {+ "elk.algorithm": "org.eclipse.elk.layered",+ "elk.direction": "DOWN",+ "elk.edgeRouting": "ORTHOGONAL",+ "elk.layered.mergeEdges": "true",+ "elk.layered.spacing.nodeNodeBetweenLayers": "52",+ "elk.spacing.nodeNode": "32",+ "elk.spacing.edgeNode": "20",+ "elk.layered.nodePlacement.strategy": "NETWORK_SIMPLEX",+ "elk.layered.cycleBreaking.strategy": "DEPTH_FIRST",+};++/** Map our {nodes, edges} into an ELK graph, deduping edges and dropping self-loops. */+function buildElkGraph(+ graph: GraphCanvasData,+ counterReserve: Map<string, number>,+): ElkNode {+ const children = graph.nodes.map((node) => {+ const { width, height } = measureNode(+ node,+ counterReserve.get(node.id) ?? 0,+ );+ return { id: node.id, width, height };+ });++ const seen = new Set<string>();+ const edges = graph.edges+ .filter((edge) => {+ if (edge.from === edge.to) return false; // self-loop+ // JSON key, not a space-joined one: node ids are SDK-supplied names that+ // commonly contain spaces, so two distinct edges must not collide.+ const key = JSON.stringify([edge.from, edge.to]);+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ })+ .map((edge, index) => ({+ id: `edge-${index}`,+ sources: [edge.from],+ targets: [edge.to],+ }));++ return {+ id: "root",+ layoutOptions: LAYOUT_OPTIONS,+ children,+ edges,+ };+}++let elkInstance: Promise<ELK> | null = null;++/**+ * Lazy-load ELK (~1MB) only when a graph is rendered, and reuse the instance.+ * Runs on the main thread for now; this is the seam to move into a Web Worker+ * for very large graphs without touching callers.+ */+function getElk(): Promise<ELK> {+ if (!elkInstance) {+ elkInstance = import("elkjs/lib/elk.bundled.js").then(+ (mod) => new (mod.default as unknown as { new (): ELK })(),+ );+ // Don't permanently cache a rejected import (transient fetch failure, stale+ // chunk after a deploy) — clear it so the next call retries.+ elkInstance.catch(() => {+ elkInstance = null;+ });+ }+ return elkInstance;+}++/**+ * Reserve extra node width for the observation counter (e.g. " (2/3)") so the+ * suffix isn't ellipsized at render time. Width is based on the stable "(N/N)"+ * form (max digits), not the live index, so cycling never re-runs layout.+ */+function buildCounterReserve(+ nodeToObservationsMap: Record<string, string[]>,+): Map<string, number> {+ const reserve = new Map<string, number>();+ for (const [id, observations] of Object.entries(nodeToObservationsMap)) {+ if (observations.length > 1) {+ reserve.set(+ id,+ ` (${observations.length}/${observations.length})`.length,+ );+ }+ }+ return reserve;+}++/** Compute a deterministic hierarchical layout for the graph via ELK. */+export async function computeGraphLayout(+ graph: GraphCanvasData,+ nodeToObservationsMap: Record<string, string[]> = {},+): Promise<GraphLayout> {+ if (graph.nodes.length === 0) {+ return { nodes: [], edges: [], width: 0, height: 0 };+ }++ const elk = await getElk();+ const counterReserve = buildCounterReserve(nodeToObservationsMap);+ const result = await elk.layout(buildElkGraph(graph, counterReserve));++ const nodes: PositionedNode[] = (result.children ?? []).map((child) => ({+ id: child.id,+ x: child.x ?? 0,+ y: child.y ?? 0,+ width: child.width ?? 0,+ height: child.height ?? 0,+ }));++ const edges: PositionedEdge[] = (result.edges ?? []).flatMap((edge) => {+ const section = edge.sections?.[0];+ if (!section) return [];+ const points = [+ section.startPoint,+ ...(section.bendPoints ?? []),+ section.endPoint,+ ];+ return [+ {+ id: edge.id,+ source: edge.sources?.[0] ?? "",+ target: edge.targets?.[0] ?? "",+ points,+ },+ ];+ });++ return {+ nodes,+ edges,+ width: result.width ?? 0,+ height: result.height ?? 0,+ };+}diff --git a/web/src/features/trace-graph-view/layout/measureNode.clienttest.ts b/web/src/features/trace-graph-view/layout/measureNode.clienttest.tsnew file mode 100644index 0000000000..eca64037a8--- /dev/null+++ b/web/src/features/trace-graph-view/layout/measureNode.clienttest.ts@@ -0,0 +1,56 @@+import {+ APPROX_CHAR_WIDTH,+ MAX_LABEL_LENGTH,+ MAX_WIDTH,+ MIN_WIDTH,+ NODE_HEIGHT,+ measureNode,+ truncateLabel,+} from "./measureNode";++describe("truncateLabel", () => {+ it("keeps a label exactly at MAX_LABEL_LENGTH unchanged", () => {+ const label = "x".repeat(MAX_LABEL_LENGTH);+ expect(truncateLabel(label)).toBe(label);+ });++ it("truncates labels beyond MAX_LABEL_LENGTH with an ellipsis", () => {+ const label = "x".repeat(MAX_LABEL_LENGTH + 5);+ const truncated = truncateLabel(label);+ expect(truncated).toBe(`${"x".repeat(MAX_LABEL_LENGTH - 1)}…`);+ expect(truncated.length).toBeLessThanOrEqual(MAX_LABEL_LENGTH);+ });++ it("does not leave a trailing space before the ellipsis", () => {+ // The character at the cut position is a space, which a plain slice would+ // keep as "xxx …" — trimEnd must remove it before the ellipsis.+ const label = `${"x".repeat(MAX_LABEL_LENGTH - 2)} ${"y".repeat(10)}`;+ const truncated = truncateLabel(label);+ expect(truncated).toBe(`${"x".repeat(MAX_LABEL_LENGTH - 2)}…`);+ expect(truncated).not.toMatch(/\s…$/);+ });+});++describe("measureNode", () => {+ it("floors short labels at MIN_WIDTH and uses the fixed NODE_HEIGHT", () => {+ const { width, height } = measureNode({ label: "ab" });+ expect(width).toBe(MIN_WIDTH);+ expect(height).toBe(NODE_HEIGHT);+ });++ it("bounds very long labels with a counter reserve at the widened cap", () => {+ const counterChars = " (12/12)".length;+ const wide = measureNode({ label: "x".repeat(500) }, counterChars);+ const wider = measureNode({ label: "x".repeat(5000) }, counterChars);++ // Truncation makes the width independent of the raw label length…+ expect(wider.width).toBe(wide.width);+ // …and it never exceeds the cap widened by the counter reserve.+ expect(wide.width).toBeLessThanOrEqual(+ Math.round(MAX_WIDTH + counterChars * APPROX_CHAR_WIDTH),+ );+ // The reserve itself widens the node vs. the same label without one.+ const noReserve = measureNode({ label: "x".repeat(500) });+ expect(wide.width).toBeGreaterThan(noReserve.width);+ });+});diff --git a/web/src/features/trace-graph-view/layout/measureNode.ts b/web/src/features/trace-graph-view/layout/measureNode.tsnew file mode 100644index 0000000000..80e74156de--- /dev/null+++ b/web/src/features/trace-graph-view/layout/measureNode.ts@@ -0,0 +1,44 @@+import { type GraphNodeData } from "../types";++/**+ * Deterministic node sizing. ELK needs each node's width/height up front (it+ * lays out abstract boxes and never sees our HTML), so we estimate the box from+ * the (truncated) label rather than measuring the DOM. Estimating keeps layout+ * pure and synchronous to feed; the small inaccuracy vs. real text metrics is+ * absorbed by node padding.+ */+export const NODE_HEIGHT = 34;+export const MAX_LABEL_LENGTH = 28;++export const APPROX_CHAR_WIDTH = 6.6; // px per char at the ~13px label font+const ICON_SLOT = 22; // type icon + gap+const PADDING_X = 22; // left + right padding+export const MIN_WIDTH = 96;+export const MAX_WIDTH = 240;++/** Truncate a label to keep nodes compact; full name is shown on hover. */+export function truncateLabel(label: string): string {+ return label.length > MAX_LABEL_LENGTH+ ? `${label.slice(0, MAX_LABEL_LENGTH - 1).trimEnd()}…`+ : label;+}++export function measureNode(+ node: Pick<GraphNodeData, "label">,+ // Extra characters to reserve for the observation counter (e.g. " (2/3)"), so+ // it isn't ellipsized at render time.+ counterChars = 0,+): {+ width: number;+ height: number;+} {+ const label = truncateLabel(node.label);+ const width = Math.min(+ MAX_WIDTH + counterChars * APPROX_CHAR_WIDTH,+ Math.max(+ MIN_WIDTH,+ (label.length + counterChars) * APPROX_CHAR_WIDTH + ICON_SLOT + PADDING_X,+ ),+ );+ return { width: Math.round(width), height: NODE_HEIGHT };+}