πͺ’ 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
fix(web): remove the trace playback feature (#17927)
Trang Nguyen2daf6c353f62
diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.tsindex 9eeb9c3173..78c17d5a98 100644--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts@@ -42,13 +42,6 @@ const events = {// Fired from the tree, timeline, graph, and search-result click handlers;// `source` says which surface drove the navigation."node_selected",- // Trace playhead transport in the navigation header (and the overflow- // menu on a narrow panel). Distinguishes play vs pause vs stop; `viewMode`- // is tree vs timeline at click time; `observationCount` is the loaded- // trace size. Metadata only β never a trace/observation id.- "playback_play",- "playback_pause",- "playback_stop",// Download from the large-string IO fallback (LFE-10991): a top-level// string over the render limit is shown as a bounded preview + download// instead of the full Pretty/JSON viewer. Measures how often users hit it.diff --git a/web/src/features/trace-graph-view/README.md b/web/src/features/trace-graph-view/README.mdindex 3eb212b4b7..5b978b31f0 100644--- a/web/src/features/trace-graph-view/README.md+++ b/web/src/features/trace-graph-view/README.md@@ -45,10 +45,6 @@ downstream is mode-agnostic. The selected mode is a trace view preference`components/TraceGraphView.tsx` (click-cycling through a node's observations,URLβnode sync with a parent-walk fallback for descendants without their owngraph 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`). `elkLayout.ts` stays free of worker plumbing so itruns unchanged on either thread; `graphLayoutWorkerClient.ts` owns the workerdiff --git a/web/src/features/trace-graph-view/components/ElkGraphRenderer.tsx b/web/src/features/trace-graph-view/components/ElkGraphRenderer.tsxindex 8faecfe61b..f5552e177d 100644--- a/web/src/features/trace-graph-view/components/ElkGraphRenderer.tsx+++ b/web/src/features/trace-graph-view/components/ElkGraphRenderer.tsx@@ -33,18 +33,11 @@ type ElkGraphRendererProps = {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;/*** Node names that answer the active search, or `null`/absent when there is no- * query. The inverse of `activeNodeNames`: playback glows the few UP and- * leaves the rest alone, a search fades everything that missed DOWN β with- * a query live, "not in this set" is a statement and has to look like one,- * including the empty set, which dims the whole graph.+ * query. A search fades everything that missed β with a query live, "not in+ * this set" is a statement and has to look like one, including the empty+ * set, which dims the whole graph.** Nodes and edges keep their hit targets while dimmed.*/@@ -103,7 +96,6 @@ export const ElkGraphRenderer: React.FC<ElkGraphRendererProps> = ({onCanvasNodeNameChange,nodeToObservationsMap = {},currentObservationIndices = {},- activeNodeNames = null,matchedNodeNames = null,layoutDirection = "DOWN",onShowExpanded = null,@@ -553,7 +545,6 @@ export const ElkGraphRenderer: React.FC<ElkGraphRendererProps> = ({height={node.height}counter={counters.get(node.id)}selected={node.id === selectedNodeName}- active={activeNodeNames?.has(node.id) ?? false}dimmed={matchedNodeNames != null && !matchedNodeNames.has(node.id)}diff --git a/web/src/features/trace-graph-view/components/GraphNode.tsx b/web/src/features/trace-graph-view/components/GraphNode.tsxindex a2b88abb2a..b7df3a70a9 100644--- a/web/src/features/trace-graph-view/components/GraphNode.tsx+++ b/web/src/features/trace-graph-view/components/GraphNode.tsx@@ -51,8 +51,6 @@ export type GraphNodeProps = {/** 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;/*** None of this node's observations answer the active search. It fades rather* than disappearing: the shape of the run is the reason to look at a graph,@@ -76,7 +74,6 @@ function GraphNodeComponent({height,counter,selected,- active,dimmed,compact,onSelect,@@ -91,16 +88,7 @@ function GraphNodeComponent({"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"),+ selected && "ring-ring ring-2 ring-offset-1",// A search miss. Last, so it fades whatever the node ended up wearing β// and it is the misses that dim rather than the hits that recolour,// because border hue here means observation type and nothing else.diff --git a/web/src/features/trace-graph-view/components/TraceGraphView.tsx b/web/src/features/trace-graph-view/components/TraceGraphView.tsxindex a481e27ac4..b7228478e2 100644--- a/web/src/features/trace-graph-view/components/TraceGraphView.tsx+++ b/web/src/features/trace-graph-view/components/TraceGraphView.tsx@@ -32,11 +32,6 @@ import {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>;/** How the graph is built (aggregated vs expanded) β see GraphViewMode. */viewMode?: GraphViewMode;/** When provided, the mode switch is rendered over the canvas. */@@ -63,7 +58,6 @@ type TraceGraphViewProps = {export const TraceGraphView: React.FC<TraceGraphViewProps> = ({agentGraphData,- activeObservationIds,viewMode = "aggregated",onViewModeChange,onObservationSelect,@@ -140,25 +134,6 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({[agentGraphData],);- // observation id β its node id, so the playhead's active-observation set can- // be projected onto graph nodes. Aggregated: id β node NAME from the full- // data (nodeToObservationsMap only holds the top-most of a same-name chain).- // Expanded: node ids ARE observation ids β the projection is identity over- // the unfiltered data (ids that aren't graph nodes simply never match).- const observationToNodeName = useMemo(() => {- const map = new Map<string, string>();- if (isExpanded) {- for (const o of agentGraphData) {- if (o.id) map.set(o.id, o.id);- }- } else {- for (const o of normalizedData) {- if (o.id && o.node) map.set(o.id, o.node);- }- }- return map;- }, [normalizedData, agentGraphData, isExpanded]);-/*** Everything the "which node is this observation?" walk needs, in the active* view mode. Built once and shared by the selection fallback below and the@@ -179,16 +154,6 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({[isExpanded, agentGraphById, graphNodeIds, 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]);-// A node stands for every call of its step, so it keeps its colour when ANY// observation behind it matched β including the ones no node registers, which// resolve to the nearest ancestor the graph kept. `null` means no query and@@ -351,7 +316,6 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({onCanvasNodeNameChange={onCanvasNodeNameChange}nodeToObservationsMap={nodeToObservationsMap}currentObservationIndices={currentObservationIndices}- activeNodeNames={activeNodeNames}matchedNodeNames={matchedNodeNames}// Expanded runs are long chains β leftβright reads like a// timeline and fits the wide graph panel far better than top-down.diff --git a/web/src/features/traces/components/PlaybackControls.clienttest.tsx b/web/src/features/traces/components/PlaybackControls.clienttest.tsxdeleted file mode 100644index c04dc3e085..0000000000--- a/web/src/features/traces/components/PlaybackControls.clienttest.tsx+++ /dev/null@@ -1,175 +0,0 @@-import { fireEvent, render, screen } from "@testing-library/react";-import { beforeEach, describe, expect, it, vi } from "vitest";-import { PlaybackControls } from "./PlaybackControls";--const h = vi.hoisted(() => ({- capture: vi.fn(),- play: vi.fn(),- pause: vi.fn(),- stop: vi.fn(),- isPlaying: false,- showPlayhead: false,- viewMode: null as string | null,- observationCount: 42,- dimensions: {- isV4: true,- traceContext: "fullscreen" as "fullscreen" | "peek" | "annotation",- },-}));--vi.mock("@/src/features/posthog-analytics/usePostHogClientCapture", () => ({- usePostHogClientCapture: () => h.capture,-}));--vi.mock("@/src/features/traces/hooks/useTraceAnalyticsDimensions", () => ({- useTraceAnalyticsDimensions: () => h.dimensions,-}));--vi.mock("use-query-params", async () => {- const actual = await vi.importActual("use-query-params");- return {- ...actual,- useQueryParam: () => [h.viewMode, vi.fn()] as const,- };-});--vi.mock("@/src/features/traces/contexts/TraceDataContext", () => ({- useTraceData: () => ({- traceDuration: 10,- observations: Array.from({ length: h.observationCount }, (_, i) => ({- id: `obs-${i}`,- })),- }),-}));--vi.mock("@/src/features/traces/contexts/TraceGraphDataContext", () => ({- useTraceGraphData: () => ({- isGraphViewAvailable: true,- isLoading: false,- }),-}));--vi.mock("@/src/features/traces/contexts/SearchContext", () => ({- useSearch: () => ({ searchQuery: "" }),-}));--vi.mock("@/src/features/traces/contexts/PlayheadContext", () => ({- usePlayhead: () => ({- play: h.play,- pause: h.pause,- stop: h.stop,- getPlayheadSec: () => 0,- subscribePosition: () => () => {},- }),- useIsPlaying: () => h.isPlaying,- useShowPlayhead: () => h.showPlayhead,-}));--const payloadKeys = (call: unknown[]) =>- call[1] && typeof call[1] === "object" ? Object.keys(call[1] as object) : [];--describe("PlaybackControls analytics", () => {- beforeEach(() => {- h.capture.mockClear();- h.play.mockClear();- h.pause.mockClear();- h.stop.mockClear();- h.isPlaying = false;- h.showPlayhead = false;- h.viewMode = null;- h.observationCount = 42;- h.dimensions = { isV4: true, traceContext: "fullscreen" };- });-- it("captures play from tree with observation count, once", () => {- render(<PlaybackControls />);-- fireEvent.click(- screen.getByRole("button", { name: "Play trace over time" }),- );-- expect(h.play).toHaveBeenCalledTimes(1);- expect(h.capture).toHaveBeenCalledTimes(1);- expect(h.capture).toHaveBeenCalledWith("trace_detail:playback_play", {- viewMode: "tree",- observationCount: 42,- isV4: true,- traceContext: "fullscreen",- });- expect(payloadKeys(h.capture.mock.calls[0])).toEqual([- "viewMode",- "observationCount",- "isV4",- "traceContext",- ]);- });-- it("captures play from timeline, not tree", () => {- h.viewMode = "timeline";- h.observationCount = 7;- h.dimensions = { isV4: false, traceContext: "peek" };- render(<PlaybackControls />);-- fireEvent.click(- screen.getByRole("button", { name: "Play trace over time" }),- );-- expect(h.capture).toHaveBeenCalledWith("trace_detail:playback_play", {- viewMode: "timeline",- observationCount: 7,- isV4: false,- traceContext: "peek",- });- });-- it("captures pause (not play) when the transport is already running", () => {- h.isPlaying = true;- render(<PlaybackControls />);-- fireEvent.click(screen.getByRole("button", { name: "Pause playback" }));-- expect(h.pause).toHaveBeenCalledTimes(1);- expect(h.play).not.toHaveBeenCalled();- expect(h.capture).toHaveBeenCalledTimes(1);- expect(h.capture).toHaveBeenCalledWith("trace_detail:playback_pause", {- viewMode: "tree",- observationCount: 42,- isV4: true,- traceContext: "fullscreen",- });- });-- it("captures stop with the same dimensions as play", () => {- h.viewMode = "timeline";- h.showPlayhead = true;- render(<PlaybackControls />);-- fireEvent.click(screen.getByRole("button", { name: "Stop playback" }));-- expect(h.stop).toHaveBeenCalledTimes(1);- expect(h.capture).toHaveBeenCalledTimes(1);- expect(h.capture).toHaveBeenCalledWith("trace_detail:playback_stop", {- viewMode: "timeline",- observationCount: 42,- isV4: true,- traceContext: "fullscreen",- });- });-- it("does not capture stop before a playhead is placed", () => {- render(<PlaybackControls />);-- const stopButton = screen.getByRole("button", { name: "Stop playback" });- expect(stopButton).toBeDisabled();- fireEvent.click(stopButton);-- expect(h.stop).not.toHaveBeenCalled();- expect(h.capture).not.toHaveBeenCalled();- });-- it("does not capture when the store pauses without a click", () => {- render(<PlaybackControls />);- h.pause();- expect(h.capture).not.toHaveBeenCalled();- });-});diff --git a/web/src/features/traces/components/PlaybackControls.tsx b/web/src/features/traces/components/PlaybackControls.tsxdeleted file mode 100644index 803eaf5bda..0000000000--- a/web/src/features/traces/components/PlaybackControls.tsx+++ /dev/null@@ -1,238 +0,0 @@-/* eslint-disable no-nested-ternary */-/* eslint-disable @repo/no-null-render */-/**- * PlaybackControls - transport for the trace playhead, in the navigation- * header. 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.- *- * Shown only when there is something to WATCH play: the timeline view (the- * sweeping playhead) or a visible graph panel (the node glow). In the default- * tree view without a graph the transport is hidden β the row glow alone- * isn't a playback surface β but it never disappears while a playhead is- * actively placed, so an in-flight playback keeps its controls across view- * switches.- *- * 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 { DropdownMenuItem } from "@/src/components/ui/dropdown-menu";-import { StringParam, useQueryParam } from "use-query-params";-import { Button } from "@/src/components/ui/button";-import {- usePlayhead,- useIsPlaying,- useShowPlayhead,-} from "@/src/features/traces/contexts/PlayheadContext";-import { useTraceData } from "@/src/features/traces/contexts/TraceDataContext";-import { useTraceGraphData } from "@/src/features/traces/contexts/TraceGraphDataContext";-import { useSearch } from "@/src/features/traces/contexts/SearchContext";-import { usePostHogClientCapture } from "@/src/features/posthog-analytics";-import { useTraceAnalyticsDimensions } from "@/src/features/traces/hooks/useTraceAnalyticsDimensions";--// 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;--/**- * Whether a playback surface exists to drive.- *- * Shared, because the transport has two homes now: inline in the header, and- * folded into its overflow menu when the panel is too narrow for it. One rule for- * both β a second copy would drift the moment either home changed.- *- * A playback surface exists in the timeline view (unless a search query has- * replaced it with the search list) or when the graph panel renders β a- * COLLAPSED panel still counts (the surface is one click away; hiding the- * transport when the user collapses the panel would make it undiscoverable), and- * a pending graph query counts too, so graph-eligible traces don't get a- * transport pop-in after first load. An actively-placed playhead keeps its- * controls regardless.- */-function useHasPlayback(): boolean {- const { traceDuration } = useTraceData();- const { isGraphViewAvailable, isLoading: isGraphDataLoading } =- useTraceGraphData();- const { searchQuery } = useSearch();- const [viewMode] = useQueryParam("view", StringParam);- const showPlayhead = useShowPlayhead();-- const isSearching = searchQuery.trim().length > 0;- const hasPlaybackSurface =- (viewMode === "timeline" && !isSearching) ||- isGraphViewAvailable ||- isGraphDataLoading;- return traceDuration > 0 && (hasPlaybackSurface || showPlayhead);-}--/**- * Shared play/pause/stop handlers for the header buttons and the overflow- * menu. Capture at this click seam (not the store's play/pause/stop): auto-pause- * at end-of-trace must not look like a user stop, and a programmatic reset- * must not inflate usage.- */-function usePlaybackClickHandlers() {- const capture = usePostHogClientCapture();- const analyticsDimensions = useTraceAnalyticsDimensions();- const { observations } = useTraceData();- const [viewMode] = useQueryParam("view", StringParam);- const { play, pause, stop } = usePlayhead();- const isPlaying = useIsPlaying();- const showPlayhead = useShowPlayhead();-- // Tree is stored as a null query param; an unrecognised value reads as tree.- const props = {- viewMode:- viewMode === "timeline"- ? ("timeline" as const)- : viewMode === "graph"- ? ("graph" as const)- : ("tree" as const),- observationCount: observations.length,- ...analyticsDimensions,- };-- return {- isPlaying,- showPlayhead,- handlePlayPause: () => {- if (isPlaying) {- capture("trace_detail:playback_pause", props);- pause();- } else {- capture("trace_detail:playback_play", props);- play();- }- },- handleStop: () => {- // Menu already disables Stop until a playhead exists; the header- // button must do the same or idle clicks inflate playback_stop.- if (!showPlayhead) return;- capture("trace_detail:playback_stop", props);- stop();- },- };-}--export function PlaybackControls() {- const { traceDuration } = useTraceData();- const { getPlayheadSec, subscribePosition } = usePlayhead();- const hasPlayback = useHasPlayback();- const { isPlaying, showPlayhead, handlePlayPause, handleStop } =- usePlaybackClickHandlers();- 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 (!hasPlayback) 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={handlePlayPause}- 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={handleStop}- disabled={!showPlayhead}- title="Stop playback"- aria-label="Stop playback"- className="h-7 w-7"- >- <Square className="h-2.5 w-2.5" />- </Button>- </div>- );-}--/**- * The transport as menu items, for the overflow menu the header folds into below- * ~360px. Two 28px buttons plus their ring are what tipped that row over: the- * search input collapsed to "Se" and the segmented switch clipped. Play is a- * verb, so it reads fine as a menu entry β and unlike hiding it, the transport- * stays reachable while a playhead is placed.- */-export function PlaybackMenuItems() {- const hasPlayback = useHasPlayback();- const { isPlaying, showPlayhead, handlePlayPause, handleStop } =- usePlaybackClickHandlers();-- if (!hasPlayback) return null;-- return (- <>- <DropdownMenuItem onSelect={handlePlayPause}>- {isPlaying ? (- <Pause className="mr-2 h-3.5 w-3.5" />- ) : (- <Play className="mr-2 h-3.5 w-3.5" />- )}- {isPlaying ? "Pause playback" : "Play trace over time"}- </DropdownMenuItem>- <DropdownMenuItem onSelect={handleStop} disabled={!showPlayhead}>- <Square className="mr-2 h-3 w-3" />- Stop playback- </DropdownMenuItem>- </>- );-}diff --git a/web/src/features/traces/components/Trace.tsx b/web/src/features/traces/components/Trace.tsxindex 2c8f1166af..57dfbeecbe 100644--- a/web/src/features/traces/components/Trace.tsx+++ b/web/src/features/traces/components/Trace.tsx@@ -13,7 +13,6 @@ import {import { useSelectedObservation } from "@/src/features/traces/hooks/useSelectedObservation";import { SearchProvider } from "@/src/features/traces/contexts/SearchContext";import { JsonExpansionProvider } from "@/src/features/traces/contexts/JsonExpansionContext";-import { PlayheadProvider } from "@/src/features/traces/contexts/PlayheadContext";import {TraceGraphDataProvider,useTraceGraphData,@@ -180,9 +179,7 @@ function TraceWithSelection({><SearchProvider><JsonExpansionProvider>- <PlayheadProvider>- <TraceContent desktopLayout={desktopLayout} />- </PlayheadProvider>+ <TraceContent desktopLayout={desktopLayout} /></JsonExpansionProvider></SearchProvider></TraceGraphDataProvider>diff --git a/web/src/features/traces/components/TraceGraphView/TraceGraphView.tsx b/web/src/features/traces/components/TraceGraphView/TraceGraphView.tsxindex 0447e84e3d..5cf3ff653b 100644--- a/web/src/features/traces/components/TraceGraphView/TraceGraphView.tsx+++ b/web/src/features/traces/components/TraceGraphView/TraceGraphView.tsx@@ -12,7 +12,6 @@ import {type GraphViewMode,} from "@/src/features/trace-graph-view";import { useTraceGraphData } from "@/src/features/traces/contexts/TraceGraphDataContext";-import { useActiveObservationIds } from "@/src/features/traces/contexts/PlayheadContext";import { useViewPreferences } from "@/src/features/traces/contexts/ViewPreferencesContext";import { usePostHogClientCapture } from "@/src/features/posthog-analytics";import { useTraceAnalyticsDimensions } from "@/src/features/traces/hooks/useTraceAnalyticsDimensions";@@ -21,7 +20,6 @@ import { useMobileLayoutContextOptional } from "../TraceLayoutMobile";export function TraceGraphView() {const { agentGraphData, isLoading } = useTraceGraphData();- const activeObservationIds = useActiveObservationIds();const { graphViewMode, setGraphViewMode } = useViewPreferences();// The trace panel's search box, resolved by the same hook the Timeline reads.// The graph projects these observation ids onto its own nodes, which is@@ -73,7 +71,6 @@ export function TraceGraphView() {return (<TraceGraphViewComponentagentGraphData={agentGraphData}- activeObservationIds={activeObservationIds}viewMode={graphViewMode}onViewModeChange={handleViewModeChange}onObservationSelect={handleObservationSelect}diff --git a/web/src/features/traces/components/TracePanelNavigationHeader/TracePanelNavigationHeader.tsx b/web/src/features/traces/components/TracePanelNavigationHeader/TracePanelNavigationHeader.tsxindex 9e97dd166a..b4c8d95e34 100644--- a/web/src/features/traces/components/TracePanelNavigationHeader/TracePanelNavigationHeader.tsx+++ b/web/src/features/traces/components/TracePanelNavigationHeader/TracePanelNavigationHeader.tsx@@ -54,7 +54,6 @@ import {downloadServerTraceAsJson,} from "../../fns/downloadTrace";import { TracePanelNavigationButton } from "./components/TracePanelNavigationButton";-import { PlaybackControls, PlaybackMenuItems } from "../PlaybackControls";import { useDesktopLayoutContextOptional } from "../TraceLayoutDesktop";import { usePostHogClientCapture } from "@/src/features/posthog-analytics";import { useTraceAnalyticsDimensions } from "@/src/features/traces/hooks/useTraceAnalyticsDimensions";@@ -231,7 +230,6 @@ function TracePanelNavigationHeaderExpanded({<Download className="mr-2 h-3.5 w-3.5" />Download trace as JSON</DropdownMenuItem>- <PlaybackMenuItems /><DropdownMenuSeparator /><TraceViewOptionsMenuItems /></>@@ -337,13 +335,6 @@ function TracePanelNavigationHeaderExpanded({</DropdownMenu></div>- {/* Playback transport + circular time-progress ring. View-agnostic:- shown in both Tree and Timeline views (see PlaybackControls) β and- folded into the overflow menu on a narrow panel, like the tools. */}- <div className="hidden flex-row items-center @min-[510px]/navheader:flex">- <PlaybackControls />- </div>-<div className="ml-2 hidden @min-[330px]/navheader:block"><ViewModeSwitchactiveView={activeView}diff --git a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.stories.tsx b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.stories.tsxindex 8cb61a2210..5ecc50161e 100644--- a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.stories.tsx+++ b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.stories.tsx@@ -1199,86 +1199,6 @@ export const TooltipFollowsTheContent = meta.story({},});-/** A playhead a story can drive by hand, standing in for the shared engine. */-function makeFakePlayhead() {- let sec = 0;- const listeners = new Set<(next: number) => void>();- return {- onSeek: fn(),- playhead: {- visible: true,- getSec: () => sec,- subscribe: (listener: (next: number) => void) => {- listeners.add(listener);- return () => listeners.delete(listener);- },- onSeek: (next: number) => PLAYBACK.onSeek(next),- },- tick(next: number) {- sec = next;- for (const listener of listeners) listener(next);- },- };-}-const PLAYBACK = makeFakePlayhead();--export const PlaybackSweepsAndGlows = meta.story({- name: "(Test) Playback Sweeps And Glows",- args: {- roots: manySpans(150),- box: PHONE,- gutter: "auto",- pointer: "fine",- barColor: "type",- compress: false,- showReadout: true,- selectedId: null,- onSelect: fn(),- onHover: fn(),- // The root span of manySpans covers the whole trace, so it is "playing"- // throughout β the simplest thing a glow can be asserted against.- activeIds: new Set(["n0"]),- playhead: PLAYBACK.playhead,- },- play: async ({ canvasElement }) => {- const line = canvasElement.querySelector<HTMLElement>(- '[data-testid="timeline-dense-playhead"]',- );- if (!line) throw new Error("no playhead line");-- // It starts at the origin and is moved by the position feed, not by a- // re-render: 600 rows must not re-render to move a 2px line.- await expect(line.style.transform).toBe("translateX(0px)");- PLAYBACK.tick(12);- await waitFor(() =>- expect(line.style.transform).not.toBe("translateX(0px)"),- );-- // The rows the playhead is over glow up β never the others dimming down.- const glowing = canvasElement.querySelectorAll(- '[data-testid="timeline-dense-content"] > div.bg-primary\\/20',- );- await expect(glowing.length).toBe(1);-- // And the axis is the scrub track: press it to place the playhead.- const axis = canvasElement.querySelector<HTMLElement>(- '[data-testid="timeline-dense-axis"]',- );- if (!axis) throw new Error("no axis");- const axisRect = axis.getBoundingClientRect();- axis.setPointerCapture = () => undefined;- axis.dispatchEvent(- new PointerEvent("pointerdown", {- bubbles: true,- pointerId: 1,- clientX: axisRect.left + axisRect.width / 2,- clientY: axisRect.top + 8,- }),- );- await expect(PLAYBACK.onSeek).toHaveBeenCalled();- },-});-/** A selection whose row arrives late, as a deep link's does. */function WithLateRows(props: TimelineDenseProps) {const [roots, setRoots] = useState<TimelineDenseProps["roots"]>([]);@@ -1292,60 +1212,6 @@ function WithLateRows(props: TimelineDenseProps) {);}-/**- * The names floating over the chart are the SAME rows as the chart's. Where the- * gutter is only a rail, peeking is the one way to read a name during playback β- * and the peek kept its own copy of the row backgrounds, which knew about- * selection and hover but had never heard of playback: the row that was playing- * glowed in the chart and stayed plain in the names beside it.- */-export const ThePeekGlowsWithThePlayingRow = meta.story({- name: "(Test) The Peek Glows With The Playing Row",- args: {- // 40 rows in this box are 15px: too short to hold a name in flow, tall- // enough that the rail exists to peek at. At the 1px floor there is no rail- // by design, so there would be nothing to hover.- roots: manySpans(40),- box: PHONE,- gutter: "auto",- pointer: "fine",- barColor: "type",- compress: false,- showReadout: true,- selectedId: null,- onSelect: fn(),- onHover: fn(),- // The root covers the whole trace, so it plays throughout.- activeIds: new Set(["n0"]),- playhead: PLAYBACK.playhead,- },- play: async ({ canvasElement }) => {- const surface = canvasElement.querySelector<HTMLElement>(- '[data-testid="timeline-dense-surface"]',- );- if (!surface) throw new Error("dense surface not found");- const rect = surface.getBoundingClientRect();- surface.dispatchEvent(- new PointerEvent("pointermove", {- bubbles: true,- pointerType: "mouse",- clientX: rect.left + 4,- // Well away from the playing row, so the hover wash cannot stand in for- // the glow this is looking for.- clientY: rect.top + 200,- }),- );- const peek = await waitFor(() => {- const el = canvasElement.querySelector<HTMLElement>(- '[data-testid="timeline-dense-peek"]',- );- if (!el) throw new Error("the rail did not peek");- return el;- });- await expect(peek.querySelectorAll("div.bg-primary\\/20").length).toBe(1);- },-});-export const ALateRowIsStillRevealed = meta.story({name: "(Test) A Late Row Is Still Revealed",args: {diff --git a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsxindex 88c2d13b5a..7ff293caf8 100644--- a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx+++ b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx@@ -276,11 +276,6 @@ export type TimelineDenseProps = {onSelect: (nodeId: string) => void;/** Hover, for prefetching the observation the user is about to open. */onHover?: (nodeId: string) => void;- /**- * Ids playing at the playhead, glowed while playback runs. A crossing changes- * the set, so this re-renders on boundaries only β never per frame.- */- activeIds?: ReadonlySet<string>;/*** Extra facts for the hover tooltip, already formatted β cost and token usage* live on the app's node, not on the layout contract, and their formatters@@ -322,22 +317,6 @@ export type TimelineDenseProps = {* over the whole trace, which is every bar this chart lights). */label: string;};- /**- * The trace playhead, handed in rather than read from context: this renderer- * takes data and nothing implicit, which is what lets Storybook mount it at- * every size. Absent means there is no playback surface here.- *- * `subscribe` is the ~60fps position feed and drives the line imperatively β- * a playhead that re-rendered 600 rows per frame would be a different kind of- * broken.- */- playhead?: {- visible: boolean;- getSec: () => number;- subscribe: (listener: (sec: number) => void) => () => void;- /** Click or drag the axis to place it. */- onSeek: (sec: number) => void;- };};export type GutterMode = "auto" | "expanded" | "collapsed";@@ -345,22 +324,15 @@ export type GutterMode = "auto" | "expanded" | "collapsed";/*** What a row's background says about it. ONE decision, because two places draw a* row β the chart and the names floating over it β and a second copy is a second- * chance to miss a state: the peek's copy only knew about selection and hover, so- * during playback the row that was playing glowed in the chart and stayed plain- * in the names right beside it.- *- * Playing rows glow UP rather than the others dimming down, which is the standing- * rule for playback highlight here.+ * chance to miss a state.*/function rowWashClass(state: {selected: boolean;focused: boolean;- active: boolean;}): string | false {if (state.selected) return "bg-primary-accent/20";- if (state.focused) return "bg-primary-accent/15";// At 4px a tint is not enough to find yourself by, so these are full-width.- return state.active && "bg-primary/20";+ return state.focused && "bg-primary-accent/15";}export function TimelineDense({@@ -375,8 +347,6 @@ export function TimelineDense({selectedId,onSelect,onHover,- activeIds,- playhead,metricsOf,showDuration = true,search,@@ -797,12 +767,12 @@ export function TimelineDense({);};- // Selection is not always ours to place. The tree, a search hit, a deep link- // and playback all select rows, and a highlight you cannot see is not a- // highlight β on a trace this dense the chosen row is usually outside the- // window, and `layout()` does not even emit a node for it. So an EXTERNAL- // change reveals its row: pan both axes just far enough, never zoom, because- // "look at this one" is not a request to change how far in you are looking.+ // Selection is not always ours to place. The tree, a search hit and a deep+ // link all select rows, and a highlight you cannot see is not a highlight β+ // on a trace this dense the chosen row is usually outside the window, and+ // `layout()` does not even emit a node for it. So an EXTERNAL change reveals+ // its row: pan both axes just far enough, never zoom, because "look at this+ // one" is not a request to change how far in you are looking.// Adjusting state during render is React's own answer to "a prop changed and// some state must follow" β the superseded render never reaches the screen.// `undefined`, not `selectedId`: mounting with a selection already set IS the@@ -1390,54 +1360,6 @@ export function TimelineDense({focusIndex == null? null: (result.nodes.find((node) => node.index === focusIndex) ?? null);- // Seconds from the trace origin β px in the lane, through the same- // compression and window the bars went through β so the playhead cannot- // disagree with what it is sweeping over.- const secToX = (sec: number) =>- (compression.toCompressedMs(Math.max(sec, 0) * 1000) - current.time.start) *- result.pxPerMs;- const xToSec = (px: number) =>- result.pxPerMs > 0- ? compression.toRealMs(current.time.start + px / result.pxPerMs) / 1000- : 0;- // The imperative feed reads the live mapping, so a pan or a zoom mid-playback- // moves the line to the right place on its next tick rather than drifting.- const mappingRef = useRef(secToX);- mappingRef.current = secToX;-- const subscribePlayhead = playhead?.subscribe;- const getPlayheadSec = playhead?.getSec;- const attachPlayhead = useCallback(- (element: HTMLDivElement | null) => {- if (!element || !subscribePlayhead || !getPlayheadSec) return;- const apply = (sec: number) => {- element.style.transform = `translateX(${mappingRef.current(sec)}px)`;- };- apply(getPlayheadSec());- return subscribePlayhead(apply);- },- [subscribePlayhead, getPlayheadSec],- );-- const onSeek = playhead?.onSeek;- const seekFromEvent = (event: ReactPointerEvent<HTMLDivElement>) => {- if (!onSeek) return;- const rect = event.currentTarget.getBoundingClientRect();- onSeek(xToSec(event.clientX - rect.left - railWidth));- };- const onAxisPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {- if (!onSeek) return;- // Press to place it, drag to scrub β one gesture, as on the wide timeline.- event.currentTarget.setPointerCapture(event.pointerId);- seekFromEvent(event);- };- const onAxisPointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {- if (!onSeek || !event.currentTarget.hasPointerCapture(event.pointerId)) {- return;- }- seekFromEvent(event);- };-const windowLabel = formatDurationMs(compression.toRealMs(current.time.start + current.time.duration) -compression.toRealMs(current.time.start),@@ -1517,16 +1439,9 @@ export function TimelineDense({) : null}</div>- {/* The axis doubles as the scrub track: press to place the playhead, drag- to move it β the same gesture the wide timeline's scale has. */}<div- className={cn(- "border-border relative shrink-0 border-b",- onSeek && "cursor-ew-resize",- )}+ className="border-border relative shrink-0 border-b"style={{ height: `${AXIS_HEIGHT}px`, touchAction: "none" }}- onPointerDown={onAxisPointerDown}- onPointerMove={onAxisPointerMove}data-testid="timeline-dense-axis">{/* Font probe for the measurer, at the size a label ACTUALLY renders in β@@ -1638,7 +1553,6 @@ export function TimelineDense({const isFocused = node.index === focusIndex;const isSelected = node.id === selectedId;- const isActive = activeIds?.has(node.id) ?? false;// A miss under a live query. Not "hidden": the row keeps its place// on the clock, its click target and its hover, so the matches read// in the context of everything they sit between.@@ -1662,7 +1576,6 @@ export function TimelineDense({rowWashClass({selected: isSelected,focused: isFocused,- active: isActive,}),)}style={{ top: `${y}px`, height: `${rowHeight}px` }}@@ -1780,25 +1693,6 @@ export function TimelineDense({data-testid="timeline-dense-marquee"/>) : null}-- {/* The playhead sweeps in the lane, clipped by it, and is positioned- imperatively off the position feed β 600 rows must not re-render to- move a 2px line. */}- {playhead?.visible ? (- <div- className="pointer-events-none absolute inset-y-0 overflow-hidden"- style={{ left: `${railWidth}px`, width: `${laneWidth}px` }}- >- <div- ref={attachPlayhead}- className="bg-primary absolute inset-y-0 w-0.5"- style={{- transform: `translateX(${secToX(playhead.getSec())}px)`,- }}- data-testid="timeline-dense-playhead"- />- </div>- ) : null}</div>{/* Peek: the same gutter content, floating OVER the chart. The bars keep@@ -1821,7 +1715,6 @@ export function TimelineDense({rowWashClass({selected: node.id === selectedId,focused: node.index === focusIndex,- active: Boolean(activeIds?.has(node.id)),}),)}style={{ top: `${y}px`, height: `${rowHeight}px` }}diff --git a/web/src/features/traces/components/TraceTimelineDense/TraceTimelineCompact.tsx b/web/src/features/traces/components/TraceTimelineDense/TraceTimelineCompact.tsxindex 76bc1fcba7..747ee66d44 100644--- a/web/src/features/traces/components/TraceTimelineDense/TraceTimelineCompact.tsx+++ b/web/src/features/traces/components/TraceTimelineDense/TraceTimelineCompact.tsx@@ -10,18 +10,13 @@* which is what keeps it reviewable in Storybook across every size and shape.*/-import { useCallback, useMemo, useState } from "react";+import { useCallback, useState } from "react";import { useViewPreferences } from "@/src/features/traces/contexts/ViewPreferencesContext";import { type RowMetrics } from "./TimelineRowMetrics";import { usdFormatter } from "@/src/utils/numbers";import { useTraceData } from "@/src/features/traces/contexts/TraceDataContext";import { useSelection } from "@/src/features/traces/contexts/SelectionContext";import { useTraceSearchMatches } from "@/src/features/traces/hooks/useTraceSearchMatches";-import {- useActiveObservationIds,- usePlayhead,- useShowPlayhead,-} from "@/src/features/traces/contexts/PlayheadContext";import { useHandlePrefetchObservation } from "@/src/features/traces/hooks/useHandlePrefetchObservation";import { useSelectTraceNode } from "@/src/features/traces/hooks/useSelectTraceNode";import { detectPointerModality } from "../../fns/timeline/density";@@ -37,23 +32,6 @@ export function TraceTimelineCompact() {const { handleHover } = useHandlePrefetchObservation();const selectNode = useSelectTraceNode("timeline_compact");- // Playback: the transport lives in the navigation header and drives the shared- // engine, so this view owes the two things you WATCH β a line that sweeps and- // the rows lighting up as it passes them. Both are handed to the renderer,- // which stays context-free so Storybook can still mount it anywhere.- const { seekToSec, getPlayheadSec, subscribePosition } = usePlayhead();- const showPlayhead = useShowPlayhead();- const activeIds = useActiveObservationIds();- const playhead = useMemo(- () => ({- visible: showPlayhead,- getSec: getPlayheadSec,- subscribe: subscribePosition,- onSeek: seekToSec,- }),- [showPlayhead, getPlayheadSec, subscribePosition, seekToSec],- );-/*** The search box, answered in place. The renderer takes the SET of ids that* keep their colour and nothing about searching β it dims the rest, reveals@@ -128,8 +106,6 @@ export function TraceTimelineCompact() {selectedId={selectedNodeId}onSelect={selectNode}onHover={handleHoverNode}- activeIds={activeIds}- playhead={playhead}metricsOf={metricsOf}showDuration={showDuration}search={search}diff --git a/web/src/features/traces/components/TraceTree.tsx b/web/src/features/traces/components/TraceTree.tsxindex 6b12839bcc..c1a8322d9f 100644--- a/web/src/features/traces/components/TraceTree.tsx+++ b/web/src/features/traces/components/TraceTree.tsx@@ -9,82 +9,15 @@* This composition pattern allows each component to have a single responsibility.*/-import { memo } from "react";import { VirtualizedTree } from "./VirtualizedTree";-import {- VirtualizedTreeNodeWrapper,- type TreeNodeMetadata,-} from "./VirtualizedTreeNodeWrapper";+import { VirtualizedTreeNodeWrapper } from "./VirtualizedTreeNodeWrapper";import { SpanContent } from "./SpanContent";import { useTraceData } from "@/src/features/traces/contexts/TraceDataContext";import { useSelection } from "@/src/features/traces/contexts/SelectionContext";-import { useIsObservationActive } from "@/src/features/traces/contexts/PlayheadContext";import { useHandlePrefetchObservation } from "@/src/features/traces/hooks/useHandlePrefetchObservation";import { useSelectTraceNode } from "@/src/features/traces/hooks/useSelectTraceNode";import { type TreeNode } from "../types/treeNode";-import { cn } from "@/src/utils/tailwind";-import {- metricEmphasisFor,- type MetricEmphasisContext,-} from "@/src/features/traces/fns/metricEmphasis";--/**- * 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,- emphasis,- commentCount,- onHover,-}: {- node: TreeNode;- treeMetadata: TreeNodeMetadata;- isSelected: boolean;- isCollapsed: boolean;- onToggleCollapse: () => void;- onSelect: () => void;- emphasis?: MetricEmphasisContext;- 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}- emphasis={emphasis}- commentCount={commentCount}- onSelect={onSelect}- onHover={() => onHover(node)}- />- </VirtualizedTreeNodeWrapper>- </div>- );-});+import { metricEmphasisFor } from "@/src/features/traces/fns/metricEmphasis";export function TraceTree() {const { roots, comments, metricEmphasis } = useTraceData();@@ -106,19 +39,29 @@ export function TraceTree() {isCollapsed,onToggleCollapse,onSelect,- }) => (- <TraceTreeRow- node={node as TreeNode}- treeMetadata={treeMetadata}- isSelected={isSelected}- isCollapsed={isCollapsed}- onToggleCollapse={onToggleCollapse}- onSelect={onSelect}- emphasis={metricEmphasisFor(node as TreeNode, metricEmphasis)}- commentCount={comments.get(node.id)}- onHover={handleHover}- />- )}+ }) => {+ 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}+ emphasis={metricEmphasisFor(typedNode, metricEmphasis)}+ commentCount={comments.get(typedNode.id)}+ onSelect={onSelect}+ onHover={() => handleHover(typedNode)}+ />+ </VirtualizedTreeNodeWrapper>+ );+ }}/>);}diff --git a/web/src/features/traces/contexts/PlayheadContext.tsx b/web/src/features/traces/contexts/PlayheadContext.tsxdeleted file mode 100644index 9df14b2605..0000000000--- a/web/src/features/traces/contexts/PlayheadContext.tsx+++ /dev/null@@ -1,137 +0,0 @@-/**- * 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 "../stores/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>- );-}--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/features/traces/contexts/TraceDataContext.tsx b/web/src/features/traces/contexts/TraceDataContext.tsxindex a92990e6c8..acbd05a028 100644--- a/web/src/features/traces/contexts/TraceDataContext.tsx+++ b/web/src/features/traces/contexts/TraceDataContext.tsx@@ -27,10 +27,6 @@ import {getObservationLevels,removeHiddenNodes,} from "../fns/treeBuilding";-import {- calculateTraceDuration,- findEarliestStartTime,-} from "@/src/features/traces/fns/timelineCalculations";import { type TraceMetricEmphasis } from "@/src/features/traces/fns/metricEmphasis";import { useViewPreferences } from "./ViewPreferencesContext";import { useMergedScores } from "@/src/features/scores";@@ -82,12 +78,6 @@ interface TraceDataContextValue {/** Observation cap this trace was loaded under, when it hit it. */truncatedAtObservations?: 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);@@ -174,17 +164,6 @@ 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],- );-const traceLevelScoreOwnerIdSet = useMemo(() =>traceLevelScoreOwnerIds(@@ -223,8 +202,6 @@ export function TraceDataProvider({detachedObservationIsMisplaced,truncatedAtObservations,comments,- traceStartTime,- traceDuration,}),[trace,@@ -242,8 +219,6 @@ export function TraceDataProvider({uiData.nodeMap,uiData.metricEmphasis,comments,- traceStartTime,- traceDuration,],);diff --git a/web/src/features/traces/fns/timeline/viewport.ts b/web/src/features/traces/fns/timeline/viewport.tsindex 22062b99e0..4e2f5bf582 100644--- a/web/src/features/traces/fns/timeline/viewport.ts+++ b/web/src/features/traces/fns/timeline/viewport.ts@@ -446,11 +446,11 @@ export function anchorTimeToRows(* The smallest move that brings a row and its span inside the window β* scrollIntoView for a 2D viewport, and deliberately NOT a focus.*- * Selection arrives from everywhere: the tree, a search hit, a deep link, a- * playback cursor. All of those owe the user a visible highlight, but none of- * them is a request to change how far in you are looking β so the zoom on both- * axes is carried through untouched and only the offsets move. A span wider than- * the current window is centred, since no offset can contain it.+ * Selection arrives from everywhere: the tree, a search hit, a deep link. All of+ * those owe the user a visible highlight, but none of them is a request to+ * change how far in you are looking β so the zoom on both axes is carried+ * through untouched and only the offsets move. A span wider than the current+ * window is centred, since no offset can contain it.*/export function revealViewport(viewport: Viewport,diff --git a/web/src/features/traces/stores/playheadStore.clienttest.ts b/web/src/features/traces/stores/playheadStore.clienttest.tsdeleted file mode 100644index 10e8011c65..0000000000--- a/web/src/features/traces/stores/playheadStore.clienttest.ts+++ /dev/null@@ -1,199 +0,0 @@-// @vitest-environment jsdom--import {- buildNodeWindows,- computeActiveIds,- createPlayheadStore,- padActivationWindows,- playbackRate,- PLAYBACK_MAX_SECONDS,- type NodeWindow,-} from "./playheadStore";-import { type TreeNode } from "../types/treeNode";--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/features/traces/stores/playheadStore.ts b/web/src/features/traces/stores/playheadStore.tsdeleted file mode 100644index a3781899ed..0000000000--- a/web/src/features/traces/stores/playheadStore.ts+++ /dev/null@@ -1,265 +0,0 @@-/**- * 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 "../types/treeNode";--/** Activation window of one observation, in seconds from the timeline origin. */-export type NodeWindow = { id: string; startSec: number; endSec: number };--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;--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);- },- },- };- });-}