πͺ’ 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): search highlights matching bars in the trace timeline (#17342)
Trang Nguyen815db2130e89
diff --git a/web/src/features/trace-graph-view/components/ElkGraphRenderer.tsx b/web/src/features/trace-graph-view/components/ElkGraphRenderer.tsxindex 33facaca18..8faecfe61b 100644--- a/web/src/features/trace-graph-view/components/ElkGraphRenderer.tsx+++ b/web/src/features/trace-graph-view/components/ElkGraphRenderer.tsx@@ -17,6 +17,7 @@ import { ZoomIn, ZoomOut, Maximize } from "lucide-react";import { Button } from "@/src/components/ui/button";import { reportError } from "@/src/utils/reportError";+import { cn } from "@/src/utils/tailwind";import { type GraphCanvasData, type GraphNodeData } from "../types";import {type GraphLayout,@@ -24,7 +25,7 @@ import {isElkCallStackOverflow,} from "../layout/elkLayout";import { requestGraphLayout } from "../layout/graphLayoutWorkerClient";-import { GraphNode } from "./GraphNode";+import { GraphNode, SEARCH_DIM_OPACITY } from "./GraphNode";type ElkGraphRendererProps = {graph: GraphCanvasData;@@ -38,6 +39,16 @@ type ElkGraphRendererProps = {* (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.+ *+ * Nodes and edges keep their hit targets while dimmed.+ */+ matchedNodeNames?: ReadonlySet<string> | null;/** Layer direction: DOWN (default) or RIGHT (long expanded chains). */layoutDirection?: GraphLayoutDirection;/**@@ -93,6 +104,7 @@ export const ElkGraphRenderer: React.FC<ElkGraphRendererProps> = ({nodeToObservationsMap = {},currentObservationIndices = {},activeNodeNames = null,+ matchedNodeNames = null,layoutDirection = "DOWN",onShowExpanded = null,}) => {@@ -495,15 +507,24 @@ export const ElkGraphRenderer: React.FC<ElkGraphRendererProps> = ({const active =focusNode != null &&(edge.source === focusNode || edge.target === focusNode);+ // An edge belongs to the matches when either end does β a hit's+ // connections are part of reading where it sits. An edge between+ // two misses is background and fades with them, which is what+ // keeps the matching path readable through a dense graph.+ const dimmed =+ matchedNodeNames != null &&+ !matchedNodeNames.has(edge.source) &&+ !matchedNodeNames.has(edge.target);return (<pathkey={edge.id}d={toPath(edge.points)}- className={+ className={cn(active? "stroke-primary fill-none"- : "stroke-muted-foreground/40 fill-none"- }+ : "stroke-muted-foreground/40 fill-none",+ dimmed && SEARCH_DIM_OPACITY,+ )}// 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.@@ -533,6 +554,9 @@ export const ElkGraphRenderer: React.FC<ElkGraphRendererProps> = ({counter={counters.get(node.id)}selected={node.id === selectedNodeName}active={activeNodeNames?.has(node.id) ?? false}+ dimmed={+ matchedNodeNames != null && !matchedNodeNames.has(node.id)+ }compact={compact}onSelect={handleSelect}onHover={setHoveredId}diff --git a/web/src/features/trace-graph-view/components/GraphNode.tsx b/web/src/features/trace-graph-view/components/GraphNode.tsxindex 3ea0d045bd..0dedc06263 100644--- a/web/src/features/trace-graph-view/components/GraphNode.tsx+++ b/web/src/features/trace-graph-view/components/GraphNode.tsx@@ -29,6 +29,12 @@ const TYPE_BORDER_CLASS: Record<string, string> = {};const DEFAULT_BORDER_CLASS = "border-muted-blue";+/**+ * How far a search miss drops β the same value the timeline dims its rows by,+ * so the two views answer one query with one visual language.+ */+export const SEARCH_DIM_OPACITY = "opacity-30";+const isStartNode = (id: string) =>id === LANGFUSE_START_NODE_NAME || id === LANGGRAPH_START_NODE_NAME;const isEndNode = (id: string) =>@@ -47,6 +53,13 @@ export type GraphNodeProps = {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,+ * and a hit means little without the nodes it sits between. Still clickable+ * and still keyboard-focusable β searching does not make the graph read-only.+ */+ dimmed?: boolean;/** Hide the text label (when zoomed out) β keeps the box, shows only the icon. */compact?: boolean;onSelect?: (id: string) => void;@@ -64,6 +77,7 @@ function GraphNodeComponent({counter,selected,active,+ dimmed,compact,onSelect,onHover,@@ -87,6 +101,10 @@ function GraphNodeComponent({(active? "ring-primary-accent ring-2 ring-offset-1": "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.+ dimmed && SEARCH_DIM_OPACITY,);// Real-HTML accessibility (the win over the old canvas renderer): selectablediff --git a/web/src/features/trace-graph-view/components/TraceGraphView.tsx b/web/src/features/trace-graph-view/components/TraceGraphView.tsxindex 0f4471170d..a481e27ac4 100644--- a/web/src/features/trace-graph-view/components/TraceGraphView.tsx+++ b/web/src/features/trace-graph-view/components/TraceGraphView.tsx@@ -24,6 +24,11 @@ import {transformLanggraphToGeneralized,} from "../buildGraphCanvasData";import { buildExpandedGraph } from "../buildExpandedGraph";+import {+ matchedGraphNodeNames,+ nearestGraphNodeName,+ type GraphNodeResolution,+} from "../graphNodeMatching";type TraceGraphViewProps = {agentGraphData: AgentGraphDataResponse[];@@ -42,6 +47,18 @@ type TraceGraphViewProps = {* system start/end nodes or background deselects.*/onObservationSelect?: () => void;+ /**+ * The active search, or absent when there is none. Handed in as OBSERVATION+ * ids because what counts as a match is the trace panel's one rule+ * (`matchesSearchQuery`) and this module stays free of the trace-view+ * contexts; projecting those ids onto graph nodes is the graph's own job and+ * depends on the view mode, so it happens here.+ */+ search?: {+ matchedObservationIds: ReadonlySet<string>;+ /** Quiet readout β the same "N matches" / "No matches" the timeline shows. */+ label: string;+ };};export const TraceGraphView: React.FC<TraceGraphViewProps> = ({@@ -50,6 +67,7 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({viewMode = "aggregated",onViewModeChange,onObservationSelect,+ search,}) => {const [selectedNodeName, setSelectedNodeName] = useState<string | null>(null);const [currentObservationId, setCurrentObservationId] = useQueryParam(@@ -141,6 +159,26 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({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+ * search projection, so a click and a query resolve an unmapped observation+ * to the same node.+ */+ const nodeResolution = useMemo<GraphNodeResolution>(+ () => ({+ isExpanded,+ observationsById: agentGraphById,+ graphNodeIds,+ nodeByObservationId: new Map(+ normalizedData.flatMap((o) =>+ o.id && o.node ? [[o.id, o.node] as [string, string]] : [],+ ),+ ),+ }),+ [isExpanded, agentGraphById, graphNodeIds, normalizedData],+ );+const activeNodeNames = useMemo(() => {if (!activeObservationIds || activeObservationIds.size === 0) return null;const names = new Set<string>();@@ -151,6 +189,20 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({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+ // nothing dims; an empty set means a query that hit nothing, and the whole+ // graph fades.+ const matchedNodeNames = useMemo(() => {+ if (!search) return null;+ return matchedGraphNodeNames({+ matchedObservationIds: search.matchedObservationIds,+ nodeToObservationsMap,+ resolution: nodeResolution,+ });+ }, [search, nodeToObservationsMap, nodeResolution]);+// Reset indices when graph data changes (new trace loaded)useEffect(() => {setCurrentObservationIndices({});@@ -191,49 +243,16 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({}}- // Fallback for observations not in the cycling map. Expanded modes: node- // ids are observation ids, so walk UP the parent chain to the nearest- // ancestor that has a node in the graph (covers observations filtered out- // of the graph, e.g. EVENTs and LangGraph child spans). Aggregated:- // 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 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.+ // Fallback for observations the cycling map does not register: resolve to+ // the nearest ancestor the graph kept. EVENTs, LangGraph child spans and+ // nested same-name calls all land here, and selecting one should keep its+ // enclosing node focused rather than clearing the selection. The search+ // highlight resolves them through the same function.if (!foundNodeName && currentObservationId) {- if (isExpanded) {- const seen = new Set<string>();- let cursor = agentGraphById.get(currentObservationId);- while (cursor && !seen.has(cursor.id)) {- seen.add(cursor.id);- if (graphNodeIds.has(cursor.id)) {- foundNodeName = cursor.id;- break;- }- cursor = cursor.parentObservationId- ? agentGraphById.get(cursor.parentObservationId)- : undefined;- }- } else {- 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;- }- }- }+ foundNodeName = nearestGraphNodeName(+ currentObservationId,+ nodeResolution,+ );}if (foundNodeName && graphNodeIds.has(foundNodeName)) {@@ -256,11 +275,9 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({}}, [currentObservationId,- agentGraphById,graphNodeIds,- isExpanded,nodeToObservationsMap,- normalizedData,+ nodeResolution,]);const onCanvasNodeNameChange = useCallback(@@ -335,6 +352,7 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({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.layoutDirection={isExpanded ? "RIGHT" : "DOWN"}@@ -348,11 +366,26 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({}/>)}- {onViewModeChange && (+ {(onViewModeChange || search) && (// Overlaid sibling of the canvas (top-left, opposite the zoom stack)// so canvas clicks/gestures underneath are untouched.- <div className="absolute top-2 left-2 z-10">- <GraphViewModeSwitch value={viewMode} onChange={onViewModeChange} />+ <div className="absolute top-2 left-2 z-10 flex items-center gap-2">+ {onViewModeChange && (+ <GraphViewModeSwitch value={viewMode} onChange={onViewModeChange} />+ )}+ {/* What the dimming means, said in words and in the same place the+ timeline says it. Without it, "nothing matched" and "the matches+ are off-canvas" look identical. Carries the switch's own+ background so it stays legible over nodes and edges. */}+ {search && (+ <span+ className="bg-background/80 text-muted-foreground truncate rounded-md border px-2 py-1 text-xs backdrop-blur"+ title={search.label}+ data-testid="graph-search-count"+ >+ {search.label}+ </span>+ )}</div>)}</div>diff --git a/web/src/features/trace-graph-view/graphNodeMatching.clienttest.ts b/web/src/features/trace-graph-view/graphNodeMatching.clienttest.tsnew file mode 100644index 0000000000..c7deea9636--- /dev/null+++ b/web/src/features/trace-graph-view/graphNodeMatching.clienttest.ts@@ -0,0 +1,109 @@+// @vitest-environment jsdom++import {+ matchedGraphNodeNames,+ nearestGraphNodeName,+ type GraphNodeResolution,+} from "./graphNodeMatching";++type Obs = {+ id: string;+ parentObservationId: string | null;+ node: string | null;+};++const observations = (rows: Obs[]) => new Map(rows.map((o) => [o.id, o]));++// classify (step "classify") -> obs-2 (same step, unregistered) -> obs-evt (an+// EVENT, dropped from the graph and carrying no step of its own).+const aggregated: GraphNodeResolution = {+ isExpanded: false,+ observationsById: observations([+ { id: "obs-1", parentObservationId: null, node: "classify" },+ { id: "obs-2", parentObservationId: "obs-1", node: "classify" },+ { id: "obs-evt", parentObservationId: "obs-2", node: null },+ { id: "obs-orphan", parentObservationId: null, node: null },+ ]),+ graphNodeIds: new Set(["classify", "respond", "__start__", "__end__"]),+ // Only what the normalized data registers: the EVENT has no step.+ nodeByObservationId: new Map([+ ["obs-1", "classify"],+ ["obs-2", "classify"],+ ]),+};++describe("nearestGraphNodeName", () => {+ it("walks up to the nearest ancestor carrying a step name", () => {+ // The EVENT itself is not in the graph; its enclosing step is.+ expect(nearestGraphNodeName("obs-evt", aggregated)).toBe("classify");+ });++ it("walks up to the nearest ancestor that IS a node, in expanded mode", () => {+ const expanded: GraphNodeResolution = {+ isExpanded: true,+ observationsById: observations([+ { id: "obs-1", parentObservationId: null, node: null },+ { id: "obs-evt", parentObservationId: "obs-1", node: null },+ ]),+ // EVENTs are excluded from the expanded graph, so only obs-1 is a node.+ graphNodeIds: new Set(["obs-1"]),+ nodeByObservationId: new Map(),+ };+ expect(nearestGraphNodeName("obs-evt", expanded)).toBe("obs-1");+ });++ it("returns null rather than looping when no ancestor is a node", () => {+ expect(nearestGraphNodeName("obs-orphan", aggregated)).toBeNull();+ expect(nearestGraphNodeName("not-an-observation", aggregated)).toBeNull();+ // Cyclic parent references are data, not an invariant.+ const cyclic: GraphNodeResolution = {+ ...aggregated,+ observationsById: observations([+ { id: "x", parentObservationId: "y", node: null },+ { id: "y", parentObservationId: "x", node: null },+ ]),+ nodeByObservationId: new Map(),+ };+ expect(nearestGraphNodeName("x", cyclic)).toBeNull();+ });+});++describe("matchedGraphNodeNames", () => {+ // What the graph registers for click-cycling: the top-most call per node.+ const nodeToObservationsMap: Record<string, string[]> = {+ classify: ["obs-1"],+ };++ it("lights the node that registers a match, and the enclosing node for one it does not", () => {+ // obs-1 is registered; obs-2 (a nested same-name call) and obs-evt (an+ // EVENT) are in no node's list and resolve to the step around them.+ expect(+ matchedGraphNodeNames({+ matchedObservationIds: new Set(["obs-1", "obs-2", "obs-evt"]),+ nodeToObservationsMap,+ resolution: aggregated,+ }),+ ).toEqual(new Set(["classify"]));+ });++ it("lights nothing when a live query hit nothing", () => {+ // An empty set, not "no search": the graph still dims everything.+ expect(+ matchedGraphNodeNames({+ matchedObservationIds: new Set(),+ nodeToObservationsMap,+ resolution: aggregated,+ }),+ ).toEqual(new Set());+ });++ it("drops a resolved name the graph never laid out", () => {+ expect(+ matchedGraphNodeNames({+ matchedObservationIds: new Set(["obs-evt"]),+ nodeToObservationsMap,+ resolution: { ...aggregated, graphNodeIds: new Set(["respond"]) },+ }),+ ).toEqual(new Set());+ });+});diff --git a/web/src/features/trace-graph-view/graphNodeMatching.ts b/web/src/features/trace-graph-view/graphNodeMatching.tsnew file mode 100644index 0000000000..df0a574ef6--- /dev/null+++ b/web/src/features/trace-graph-view/graphNodeMatching.ts@@ -0,0 +1,102 @@+/**+ * Which graph node an observation belongs to, and which nodes a search lights.+ *+ * A graph node is not an observation. In the aggregated view one node stands+ * for every call of a step; in either view the graph drops observations+ * entirely (EVENTs, LangGraph child spans, nested same-name calls), and+ * `nodeToObservationsMap` only registers the top-most of a same-name chain. So+ * "which node is this observation?" has a real answer for observations no node+ * claims β the nearest ANCESTOR that has one β and that answer has to be the+ * same whether the observation arrived from a click or from a search. One+ * resolver, used by both, is how that stays true.+ *+ * What counts as a matching observation is not decided here: that stays with+ * `matchesSearchQuery`, so the graph, the timeline and the flat result list+ * cannot disagree about the rule or the count.+ */++/** The lookups the ancestor walk needs, in whichever view mode is active. */+export type GraphNodeResolution = {+ /** Expanded: node ids ARE observation ids. Aggregated: node ids are step names. */+ isExpanded: boolean;+ /**+ * Observations by id, UNFILTERED β the chain to walk up. Filtered data would+ * break the walk at exactly the observations that need it.+ */+ observationsById: ReadonlyMap<+ string,+ {+ id: string;+ parentObservationId: string | null;+ node: string | null;+ }+ >;+ /** Node ids present in the laid-out graph. */+ graphNodeIds: ReadonlySet<string>;+ /** Observation id β its step name, from the normalized data (aggregated). */+ nodeByObservationId: ReadonlyMap<string, string>;+};++export function nearestGraphNodeName(+ observationId: string,+ {+ isExpanded,+ observationsById,+ graphNodeIds,+ nodeByObservationId,+ }: GraphNodeResolution,+): string | null {+ // Aggregated: the observation's own step name, when it has one.+ if (!isExpanded) {+ const own = nodeByObservationId.get(observationId);+ if (own) return own;+ }+ // Walk up to the nearest ancestor the graph DID keep. `seen` guards a cycle+ // in the parent references rather than trusting the data to be a tree.+ const seen = new Set<string>();+ let cursor = observationsById.get(observationId);+ while (cursor && !seen.has(cursor.id)) {+ seen.add(cursor.id);+ if (isExpanded ? graphNodeIds.has(cursor.id) : cursor.node) {+ return isExpanded ? cursor.id : cursor.node;+ }+ cursor = cursor.parentObservationId+ ? observationsById.get(cursor.parentObservationId)+ : undefined;+ }+ return null;+}++export function matchedGraphNodeNames({+ matchedObservationIds,+ nodeToObservationsMap,+ resolution,+}: {+ matchedObservationIds: ReadonlySet<string>;+ nodeToObservationsMap: Record<string, string[]>;+ resolution: GraphNodeResolution;+}): Set<string> {+ const lit = new Set<string>();+ // Nothing matched, so no node can be lit by association. An empty set, not+ // "no search": the caller's `search` prop says whether a query is live, and a+ // query with no hits must still dim everything.+ if (matchedObservationIds.size === 0) return lit;++ // One index over the map instead of a scan per hit.+ const claimedBy = new Map<string, string>();+ for (const [nodeName, observationIds] of Object.entries(+ nodeToObservationsMap,+ )) {+ for (const id of observationIds) {+ if (!claimedBy.has(id)) claimedBy.set(id, nodeName);+ }+ }++ for (const id of matchedObservationIds) {+ const nodeName = claimedBy.get(id) ?? nearestGraphNodeName(id, resolution);+ // A resolved name still has to be a node that was laid out β an ancestor+ // can carry a step name the graph never drew.+ if (nodeName && resolution.graphNodeIds.has(nodeName)) lit.add(nodeName);+ }+ return lit;+}diff --git a/web/src/features/traces/components/TraceGraphView/TraceGraphView.tsx b/web/src/features/traces/components/TraceGraphView/TraceGraphView.tsxindex 6d0854a5d6..aa1a12a3ce 100644--- a/web/src/features/traces/components/TraceGraphView/TraceGraphView.tsx+++ b/web/src/features/traces/components/TraceGraphView/TraceGraphView.tsx@@ -14,12 +14,17 @@ import { useActiveObservationIds } from "@/src/features/traces/contexts/Playheadimport { useViewPreferences } from "@/src/features/traces/contexts/ViewPreferencesContext";import { usePostHogClientCapture } from "@/src/features/posthog-analytics";import { useTraceAnalyticsDimensions } from "@/src/features/traces/hooks/useTraceAnalyticsDimensions";+import { useTraceSearchMatches } from "@/src/features/traces/hooks/useTraceSearchMatches";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+ // view-mode dependent and therefore its job, not this wrapper's.+ const search = useTraceSearchMatches();const capture = usePostHogClientCapture();const analyticsDimensions = useTraceAnalyticsDimensions();// Optional (null on desktop): jump to the Info tab when a canvas click selects@@ -70,6 +75,11 @@ export function TraceGraphView() {viewMode={graphViewMode}onViewModeChange={handleViewModeChange}onObservationSelect={handleObservationSelect}+ search={+ search+ ? { matchedObservationIds: search.matchedIds, label: search.label }+ : undefined+ }/>);}diff --git a/web/src/features/traces/components/TracePanelNavigation.tsx b/web/src/features/traces/components/TracePanelNavigation.tsxindex c9edf49f31..bc28496b12 100644--- a/web/src/features/traces/components/TracePanelNavigation.tsx+++ b/web/src/features/traces/components/TracePanelNavigation.tsx@@ -33,13 +33,20 @@ export function TracePanelNavigation() {// Memoize to prevent recreation when deps haven't changedconst content = useMemo(() => {- // Priority: Search > Timeline > Tree- if (hasQuery) {- return <TraceSearchList />;- }+ // The Timeline answers a query IN PLACE β matching bars keep their colour+ // and the rest dim β so it is not replaced by the flat result list. Losing+ // the chart was the thing that made searching in the Timeline feel like+ // leaving it: the one view whose whole point is where in time a span sits+ // gave that up the moment you typed.+ //+ // The Tree still hands a query to the flat list; highlighting it is its own+ // change.if (isTimelineView) {return <TraceTimelineCompact />;}+ if (hasQuery) {+ return <TraceSearchList />;+ }return <TraceTree />;}, [hasQuery, isTimelineView]);diff --git a/web/src/features/traces/components/TraceSearchList.tsx b/web/src/features/traces/components/TraceSearchList.tsxindex 03ad7f2b28..7a1ff86aae 100644--- a/web/src/features/traces/components/TraceSearchList.tsx+++ b/web/src/features/traces/components/TraceSearchList.tsx@@ -14,6 +14,7 @@ import { useHandlePrefetchObservation } from "@/src/features/traces/hooks/useHanimport { useDesktopLayoutContextOptional } from "./TraceLayoutDesktop";import { usePostHogClientCapture } from "@/src/features/posthog-analytics";import { useTraceAnalyticsDimensions } from "@/src/features/traces/hooks/useTraceAnalyticsDimensions";+import { matchesSearchQuery } from "@/src/features/traces/fns/matchesSearchQuery";import { VirtualizedList } from "./VirtualizedList";import { TraceSearchListItem } from "./TraceSearchListItem";import { Button } from "@/src/components/ui/button";@@ -40,20 +41,14 @@ export function TraceSearchList() {layout?.expandDetailPanel();};- // Co-located filtering - only this component re-renders on search query change- const searchResults = useMemo(() => {- if (!searchQuery.trim()) return [];-- const query = searchQuery.toLowerCase();- return searchItems.filter((item) => {- const node = item.node;- return (- node.type.toLowerCase().includes(query) ||- node.name.toLowerCase().includes(query) ||- node.id.toLowerCase().includes(query)- );- });- }, [searchItems, searchQuery]);+ // Co-located filtering - only this component re-renders on search query change.+ // What counts as a match lives in fns/matchesSearchQuery, because the Timeline+ // highlights with the same rule and states a count next to it.+ const searchResults = useMemo(+ () =>+ searchItems.filter((item) => matchesSearchQuery(item.node, searchQuery)),+ [searchItems, searchQuery],+ );// Empty stateif (searchResults.length === 0 && searchQuery.trim()) {diff --git a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsxindex 369f3d82d8..a6b0e98aa5 100644--- a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx+++ b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx@@ -77,6 +77,7 @@ import {type LayoutNode,type PositionedNode,} from "../../fns/timeline/layout";+import { collapsedForSearch } from "../../fns/timeline/searchMatches";import { createTextMeasurer } from "../../fns/timeline/textMeasurer";import { resolveBarTones } from "../../fns/timeline/barContrast";import { traceSpaceOf, type Box } from "../../fns/timeline/viewTransform";@@ -166,6 +167,14 @@ const GUTTER_NAME_MIN = 48;* left edge instead left the elbow pointing at nothing in particular.*/const GUTTER_RAIL = GUTTER_ICON / 2;+/** Stable empty set, so an absent `collapsed` prop does not break a memo. */+const EMPTY_COLLAPSED: ReadonlySet<string> = new Set<string>();+/**+ * How far a row that missed the search drops. Low enough that the hits read as+ * the only thing lit, high enough that a miss is still a bar you can aim at β+ * the rows stay clickable and hoverable while a query is live.+ */+const SEARCH_DIM_OPACITY = "opacity-30";const TOOLBAR_HEIGHT = 22;const AXIS_HEIGHT = 16;const READOUT_HEIGHT = 18;@@ -281,6 +290,33 @@ export type TimelineDenseProps = {metricsOf?: (nodeId: string) => RowMetrics;/** The view-options duration toggle; the tree honours the same one. */showDuration?: boolean;+ /**+ * An active search, or absent when there is none. The chart answers a query+ * by staying a chart: matching bars keep their hue and their label, the rest+ * drop to `SEARCH_DIM_OPACITY` β dimming the misses rather than recolouring+ * the hits, because hue here means observation type and nothing else.+ *+ * Dimmed rows keep their click and hover targets: a bar you can still see is+ * a bar you can still open, and searching should not make the trace read-only.+ */+ search?: {+ /**+ * The raw query string. Identity for "reveal the first hit ONCE per query":+ * retyping what is already in the box must not re-pan the chart.+ */+ query: string;+ /**+ * Matching OBSERVATION ids. A hit inside a collapsed subtree has no bar, so+ * the chart opens the rows above it for as long as the query is live (see+ * `collapsedForSearch`) β which is why the caller hands over ids rather than+ * rows: it does not know what this view has collapsed.+ */+ matchedIds: ReadonlySet<string>;+ /** The quiet toolbar readout β "3 matches" / "No matches". Supplied, so the+ * count is the wiring layer's to define (it counts matching observations+ * 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@@ -338,6 +374,7 @@ export function TimelineDense({playhead,metricsOf,showDuration = true,+ search,}: TimelineDenseProps) {const [viewport, setViewport] = useState<Viewport | null>(null);const [pointerPos, setPointerPos] = useState<{@@ -361,9 +398,26 @@ export function TimelineDense({setMarquee(next);};+ /**+ * The collapse state the rows are actually built with: the user's, plus the+ * paths to the search's hits opened, because a match with no row is a match+ * the count promises and the chart cannot show. Identical to `collapsed` when+ * there is no query or nothing is hidden.+ */+ const effectiveCollapsed = useMemo(+ () =>+ search+ ? collapsedForSearch({+ roots,+ collapsed: collapsed ?? EMPTY_COLLAPSED,+ matchedIds: search.matchedIds,+ })+ : collapsed,+ [search, roots, collapsed],+ );const prepared = useMemo(- () => prepareTimeline(roots, collapsed),- [roots, collapsed],+ () => prepareTimeline(roots, effectiveCollapsed),+ [roots, effectiveCollapsed],);// Measured in the font the labels ACTUALLY render in, read off a probe span// that carries their own size β `10px ui-sans-serif` is a guess, and the@@ -776,6 +830,45 @@ export function TimelineDense({}}+ // A new query reveals its first hit, for exactly the reason a new selection+ // reveals its row: on a trace this dense the first match is usually outside+ // the window, and a highlight you cannot see is not a highlight. Same pan,+ // never a zoom β "show me the matches" is not a request to change how far in+ // you are looking.+ //+ // Keyed on the QUERY, not on the hit's id: retyping what is already in the box+ // must not re-pan, and two different queries that happen to land on the same+ // row should each be revealed. Ordered after the selection reveal and built on+ // `viewportRef.current` rather than `current`, so when a click and a keystroke+ // land in the same render the newer intent wins instead of the two fighting.+ const revealedQueryRef = useRef<string | null>(null);+ const searchKey = search?.query ?? null;+ if (searchKey !== revealedQueryRef.current) {+ const index = searchKey+ ? prepared.rows.findIndex((row) => search?.matchedIds.has(row.node.id))+ : -1;+ const row = index >= 0 ? prepared.rows[index] : undefined;+ // Same lesson as the selection reveal: with no rows yet there is nothing to+ // reveal and nothing to conclude, so leave the query un-handled and let the+ // next render with rows retry. With rows, "no hit" is an answer.+ if (!searchKey || prepared.rows.length > 0)+ revealedQueryRef.current = searchKey;+ if (row) {+ const base = viewportRef.current;+ const offsets = spanOffsetsOf(row.node, prepared.originMs);+ const revealed = revealViewport(base, limits, {+ rowIndex: index,+ startMs: compression.toCompressedMs(offsets.startMs),+ endMs: compression.toCompressedMs(offsets.endMs),+ });+ if (!viewportsEqual(revealed, base)) {+ cancelTween();+ viewportRef.current = revealed;+ setViewport(revealed);+ }+ }+ }+// Deltas accumulate and apply once per animation frame β the other half of// what makes map zoom feel immediate instead of laggy under a burst.const pending = useRef({@@ -1395,6 +1488,17 @@ export function TimelineDense({<Scan className="h-3 w-3" /></ToolbarButton>)}+ {/* What the dimming means, said in words. Without it "nothing lit up"+ and "one hit, off to the left" look the same. */}+ {search ? (+ <span+ className="text-muted-foreground truncate text-xs"+ title={`${search.label} for β${search.query}β`}+ data-testid="timeline-dense-search-count"+ >+ {search.label}+ </span>+ ) : null}{/* Where you are, when you are somewhere β and nothing at all when thewhole trace is in view. */}{!offerShowLabels && !fitted ? (@@ -1530,6 +1634,10 @@ 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.+ const isDimmed = search != null && !search.matchedIds.has(node.id);const typeColor = TYPE_COLOR[node.type] ?? FALLBACK_COLOR;// One place decides the bar's colour, so the label can ask about the// exact class the bar got rather than guessing at it.@@ -1563,10 +1671,19 @@ export function TimelineDense({rowHeight={rowHeight}barHeight={barHeight}showName={namesVisible}+ dimmed={isDimmed}/>+ {/* Dimming sits on the lane, so the bar, the caret and the+ label all fade together β a full-strength duration beside a+ ghost bar reads as two rows. The row's own wash is outside+ it, so the selected row stays findable while a query is+ live. */}<div- className="absolute inset-y-0 overflow-hidden"+ className={cn(+ "absolute inset-y-0 overflow-hidden",+ isDimmed && SEARCH_DIM_OPACITY,+ )}style={{ left: `${railWidth}px`, width: `${laneWidth}px` }}>{/* A span outside the time window is clamped to the lane edge@@ -1713,6 +1830,7 @@ export function TimelineDense({rowHeight={rowHeight}barHeight={barHeight}showName+ dimmed={search != null && !search.matchedIds.has(node.id)}/></div>);@@ -1833,12 +1951,19 @@ function GutterContent({rowHeight,barHeight,showName,+ dimmed = false,}: {node: PositionedNode;width: number;rowHeight: number;barHeight: number;showName: boolean;+ /**+ * This row missed the active search. The name and the type square fade with+ * the bar beside them β a full-strength name next to a ghost bar is the row+ * shouting and whispering at once.+ */+ dimmed?: boolean;}) {// Nothing to show, so nothing to build: at bird's-eye density the rail has no// width, and a box of invisible squares is one DOM node per row of the trace.@@ -1919,9 +2044,16 @@ function GutterContent({style={{ left: `${railX}px` }}/>) : null}+ {/* The connector rails above deliberately do NOT dim: each row draws only+ its own slice of a shared vertical spine, so per-row opacity would+ turn one continuous line into a dashed one wherever the matches fall.+ The row's IDENTITY β its icon and its name β is what fades. */}{showName ? (<div- className="absolute flex items-center gap-1 overflow-hidden"+ className={cn(+ "absolute flex items-center gap-1 overflow-hidden",+ dimmed && SEARCH_DIM_OPACITY,+ )}style={{left: `${indent}px`,right: "2px",@@ -1942,7 +2074,11 @@ function GutterContent({</div>) : (<div- className={cn("absolute rounded-[1px]", typeColor)}+ className={cn(+ "absolute rounded-[1px]",+ typeColor,+ dimmed && SEARCH_DIM_OPACITY,+ )}data-testid="timeline-dense-type-square"style={{left: `${indent}px`,diff --git a/web/src/features/traces/components/TraceTimelineDense/TraceTimelineCompact.tsx b/web/src/features/traces/components/TraceTimelineDense/TraceTimelineCompact.tsxindex 020fd67939..90236dc484 100644--- a/web/src/features/traces/components/TraceTimelineDense/TraceTimelineCompact.tsx+++ b/web/src/features/traces/components/TraceTimelineDense/TraceTimelineCompact.tsx@@ -16,6 +16,7 @@ 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,@@ -53,6 +54,15 @@ export function TraceTimelineCompact() {[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+ * the first hit and states the count, which is all a chart can do with a+ * query. The Graph reads the same hook, so the two cannot state different+ * counts for one query.+ */+ const search = useTraceSearchMatches();+const [pointerModality] = useState(detectPointerModality);const [box, setBox] = useState<{ width: number; height: number } | null>(null,@@ -125,6 +135,7 @@ export function TraceTimelineCompact() {playhead={playhead}metricsOf={metricsOf}showDuration={showDuration}+ search={search}/>) : null}</div>diff --git a/web/src/features/traces/fns/matchesSearchQuery.clienttest.ts b/web/src/features/traces/fns/matchesSearchQuery.clienttest.tsnew file mode 100644index 0000000000..c8e6414681--- /dev/null+++ b/web/src/features/traces/fns/matchesSearchQuery.clienttest.ts@@ -0,0 +1,29 @@+// @vitest-environment jsdom++import { matchesSearchQuery, type SearchableNode } from "./matchesSearchQuery";++const node: SearchableNode = {+ id: "obs-a1b2",+ name: "classify intent",+ type: "GENERATION",+};++describe("matchesSearchQuery", () => {+ it("matches a case-insensitive substring of type, name or id", () => {+ expect(matchesSearchQuery(node, "CLASSIFY")).toBe(true);+ expect(matchesSearchQuery(node, "generation")).toBe(true);+ expect(matchesSearchQuery(node, "a1b2")).toBe(true);+ expect(matchesSearchQuery(node, "zzz")).toBe(false);+ });++ it("treats a blank query as no search at all", () => {+ // Not match-everything: the callers show their unfiltered view instead.+ expect(matchesSearchQuery(node, "")).toBe(false);+ expect(matchesSearchQuery(node, " ")).toBe(false);+ });++ it("ignores padding around a real query", () => {+ // A trailing space is a keystroke on the way to the next word.+ expect(matchesSearchQuery(node, " classify ")).toBe(true);+ });+});diff --git a/web/src/features/traces/fns/matchesSearchQuery.ts b/web/src/features/traces/fns/matchesSearchQuery.tsnew file mode 100644index 0000000000..3a9603efec--- /dev/null+++ b/web/src/features/traces/fns/matchesSearchQuery.ts@@ -0,0 +1,38 @@+/**+ * Does an observation answer the trace panel's search box?+ *+ * ONE definition, because two views read it now: the Tree's flat result list+ * (TraceSearchList) and the Timeline, which keeps its bars and dims the ones+ * that miss. A second copy is a second chance for the two to disagree about+ * what a match is β and the Timeline states a count, so a disagreement would be+ * visible as a number that does not match the list beside it.+ *+ * The rule is the one the result list has always used: a case-insensitive+ * substring of the observation's type, name or id. Nothing is searched that the+ * trace panel does not already show.+ */++export type SearchableNode = {+ id: string;+ name: string;+ type: string;+};++export function matchesSearchQuery(+ node: SearchableNode,+ query: string,+): boolean {+ // Trimmed, because a trailing space is a keystroke on the way to the next+ // word and not a thing anybody means to search for. The result list already+ // treated an all-whitespace query as empty; this extends the same reading to+ // the padding around a real one.+ const needle = query.trim().toLowerCase();+ // An empty query is not a match-everything β it is no search at all, and the+ // callers decide what to show instead.+ if (!needle) return false;+ return (+ node.type.toLowerCase().includes(needle) ||+ node.name.toLowerCase().includes(needle) ||+ node.id.toLowerCase().includes(needle)+ );+}diff --git a/web/src/features/traces/fns/timeline/searchMatches.clienttest.ts b/web/src/features/traces/fns/timeline/searchMatches.clienttest.tsnew file mode 100644index 0000000000..1c21f0db7d--- /dev/null+++ b/web/src/features/traces/fns/timeline/searchMatches.clienttest.ts@@ -0,0 +1,67 @@+// @vitest-environment jsdom++import { collapsedForSearch } from "./searchMatches";+import { type LayoutNode } from "./layout";++const node = (id: string, children: LayoutNode[] = []): LayoutNode => ({+ id,+ name: id,+ startTime: new Date("2026-01-01T00:00:00Z"),+ latency: 1,+ children,+});++// root+// |- a+// | |- a1+// | `- a2+// | `- a2x+// `- b+const tree = [+ node("root", [node("a", [node("a1"), node("a2", [node("a2x")])]), node("b")]),+];++describe("collapsedForSearch", () => {+ it("opens the whole collapsed chain above a hit, and nothing else", () => {+ // "a" and "a2" both hide a2x, so both have to open or it still has no row.+ // "b" hides nothing that matched and stays as the user left it.+ expect(+ collapsedForSearch({+ roots: tree,+ collapsed: new Set(["a", "a2", "b"]),+ matchedIds: new Set(["a2x"]),+ }),+ ).toEqual(new Set(["b"]));+ });++ it("leaves a matched row's own subtree collapsed", () => {+ // "a" already has a row of its own; the query said nothing about its+ // children.+ expect(+ collapsedForSearch({+ roots: tree,+ collapsed: new Set(["a"]),+ matchedIds: new Set(["a"]),+ }),+ ).toEqual(new Set(["a"]));+ });++ it("returns the same set when no hit is hidden", () => {+ // Reference equality, not just contents: the row layout memoizes on it.+ const collapsed = new Set(["b"]);+ expect(+ collapsedForSearch({+ roots: tree,+ collapsed,+ matchedIds: new Set(["a1"]),+ }),+ ).toBe(collapsed);+ });++ it("returns the same set for a query that hit nothing", () => {+ const collapsed = new Set(["a"]);+ expect(+ collapsedForSearch({ roots: tree, collapsed, matchedIds: new Set() }),+ ).toBe(collapsed);+ });+});diff --git a/web/src/features/traces/fns/timeline/searchMatches.ts b/web/src/features/traces/fns/timeline/searchMatches.tsnew file mode 100644index 0000000000..a5f13fb0ea--- /dev/null+++ b/web/src/features/traces/fns/timeline/searchMatches.ts@@ -0,0 +1,65 @@+/**+ * What a live search does to the timeline's collapse state.+ *+ * A match is an observation, but the timeline draws rows, and a collapsed row+ * hides its whole subtree. A hit inside one therefore has no bar to light: the+ * toolbar says "3 matches" while a single stand-in parent is lit, and the+ * reveal-first-hit pan has nowhere to scroll.+ *+ * So the timeline draws those rows. While a query is live the collapsed rows+ * between a hit and the surface are treated as OPEN, which makes the count and+ * the lit bars the same fact: every match has a bar of its own. Only the+ * ANCESTORS open β a matched row that is itself collapsed already has a bar, and+ * the query said nothing about its children.+ *+ * Derived per render rather than written back to the shared collapse state:+ * clearing the search box restores exactly the shape the user had, and the tree+ * beside it does not reshuffle under a keystroke. The trade is that a live query+ * PINS the paths to its hits open β re-collapsing one while still searching does+ * not hold.+ */+import { type LayoutNode } from "./layout";++export function collapsedForSearch({+ roots,+ collapsed,+ matchedIds,+}: {+ roots: readonly LayoutNode[];+ /** The user's own collapse state β what the rows would be built with. */+ collapsed: ReadonlySet<string>;+ matchedIds: ReadonlySet<string>;+}): ReadonlySet<string> {+ // Same reference when nothing has to open, so the row layout downstream keeps+ // its memo instead of rebuilding on every keystroke.+ if (collapsed.size === 0 || matchedIds.size === 0) return collapsed;++ // Collapsed rows standing between a hit and a row of its own. Walks the full+ // tree, not the rendered rows β the hits that need a row are exactly the ones+ // no row exists for.+ const hiding = new Set<string>();+ // Explicit stack, not recursion: traces can nest thousands of levels deep+ // and the timeline must not blow the call stack on a keystroke.+ const stack: Array<{+ node: LayoutNode;+ collapsedAncestors: readonly string[];+ }> = roots.map((node) => ({ node, collapsedAncestors: [] }));+ while (stack.length > 0) {+ const { node, collapsedAncestors } = stack.pop()!;+ // The whole chain opens: an inner collapsed row is no use while an outer one+ // still hides it.+ if (collapsedAncestors.length > 0 && matchedIds.has(node.id)) {+ for (const id of collapsedAncestors) hiding.add(id);+ }+ if (node.children.length === 0) continue;+ const below = collapsed.has(node.id)+ ? [...collapsedAncestors, node.id]+ : collapsedAncestors;+ for (const child of node.children) {+ stack.push({ node: child, collapsedAncestors: below });+ }+ }++ if (hiding.size === 0) return collapsed;+ return new Set([...collapsed].filter((id) => !hiding.has(id)));+}diff --git a/web/src/features/traces/hooks/useTraceSearchMatches.ts b/web/src/features/traces/hooks/useTraceSearchMatches.tsnew file mode 100644index 0000000000..1f5477dbdf--- /dev/null+++ b/web/src/features/traces/hooks/useTraceSearchMatches.ts@@ -0,0 +1,55 @@+/**+ * The active search in the trace panel, resolved once for every view that+ * highlights it in place β the Timeline's bars and the Graph's nodes.+ *+ * There is one of these rather than a copy per view because both views state a+ * COUNT. Two independent filters over the same observations would eventually+ * disagree about a number the user can read off two surfaces at once, and the+ * cheapest way for that never to happen is for there to be one filter.+ *+ * `undefined` means no query: the views show their resting state, nothing dims.+ * A query with no hits is NOT undefined β it is an empty `matchedIds` with a+ * "No matches" label, and dims everything.+ */+import { useMemo } from "react";++import { useSearch } from "@/src/features/traces/contexts/SearchContext";+import { useTraceData } from "@/src/features/traces/contexts/TraceDataContext";+import { matchesSearchQuery } from "@/src/features/traces/fns/matchesSearchQuery";++export type TraceSearchMatches = {+ /**+ * The raw query. Views key "reveal the first hit once per query" on it, so+ * retyping what is already in the box does not move the view.+ */+ query: string;+ /** Observation ids that answer the query. */+ matchedIds: ReadonlySet<string>;+ /** The quiet readout β "3 matches" / "1 match" / "No matches". */+ label: string;+};++export function useTraceSearchMatches(): TraceSearchMatches | undefined {+ const { searchQuery } = useSearch();+ const { searchItems } = useTraceData();++ return useMemo(() => {+ if (!searchQuery.trim()) return undefined;+ const matchedIds = new Set(+ searchItems+ .filter((item) => matchesSearchQuery(item.node, searchQuery))+ .map((item) => item.node.id),+ );+ return {+ query: searchQuery,+ matchedIds,+ // Counted over the whole trace, not over the rows or nodes a view happens+ // to be showing: the number has to be the number the flat result list+ // would give for the same query.+ label:+ matchedIds.size === 0+ ? "No matches"+ : `${matchedIds.size} ${matchedIds.size === 1 ? "match" : "matches"}`,+ };+ }, [searchItems, searchQuery]);+}