🪢 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(trace): Auto-select root observation in v4 trace details (#18776)
Ben Bachem3613cb76dc77
diff --git a/web/src/features/trace-graph-view/components/TraceGraphView.tsx b/web/src/features/trace-graph-view/components/TraceGraphView.tsxindex b7228478e2..9716688bdc 100644--- a/web/src/features/trace-graph-view/components/TraceGraphView.tsx+++ b/web/src/features/trace-graph-view/components/TraceGraphView.tsx@@ -5,7 +5,6 @@ import React, {useCallback,useRef,} from "react";-import { StringParam, useQueryParam } from "use-query-params";import { ObservationType } from "@langfuse/shared";import { ElkGraphRenderer } from "./ElkGraphRenderer";@@ -32,6 +31,10 @@ import {type TraceGraphViewProps = {agentGraphData: AgentGraphDataResponse[];+ selectedObservationId: string | null;+ /** Selection the host resolves to when the explicit observation is cleared. */+ defaultObservationId: string | null;+ onSelectedObservationChange: (id: string | null) => void;/** How the graph is built (aggregated vs expanded) — see GraphViewMode. */viewMode?: GraphViewMode;/** When provided, the mode switch is rendered over the canvas. */@@ -58,24 +61,25 @@ type TraceGraphViewProps = {export const TraceGraphView: React.FC<TraceGraphViewProps> = ({agentGraphData,+ selectedObservationId: currentObservationId,+ defaultObservationId,+ onSelectedObservationChange: setCurrentObservationId,viewMode = "aggregated",onViewModeChange,onObservationSelect,search,}) => {const [selectedNodeName, setSelectedNodeName] = useState<string | null>(null);- const [currentObservationId, setCurrentObservationId] = useQueryParam(- "observation",- StringParam,- );const [currentObservationIndices, setCurrentObservationIndices] = useState<{[nodeName: string]: number;}>({});const [previousSelectedNode, setPreviousSelectedNode] = useState<string | null>(null);- // The observation id the last in-canvas click WROTE to the URL (undefined =- // no pending click write). Value-compared — a plain boolean flag gets stuck+ // The resolved observation id expected after the last in-canvas click+ // (undefined = no pending click write). Clearing the URL can resolve to the+ // host's implicit root, which is still a click echo, not an external selection.+ // Value-compared — a plain boolean flag gets stuck// when a click writes the same id the URL already has (the effect never// re-fires to clear it) and then swallows the NEXT genuine tree/timeline// selection, desyncing the graph highlight.@@ -259,7 +263,7 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({// For system nodes, don't set observation ID (they're synthetic)setPreviousSelectedNode(nodeName);setSelectedNodeName(nodeName);- clickWroteObservationIdRef.current = null;+ clickWroteObservationIdRef.current = defaultObservationId;setCurrentObservationId(null);return;}@@ -283,7 +287,7 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({setCurrentObservationId(observations[targetIndex]);onObservationSelect?.();} else {- clickWroteObservationIdRef.current = null;+ clickWroteObservationIdRef.current = defaultObservationId;setCurrentObservationId(null);}setPreviousSelectedNode(nodeName);@@ -297,6 +301,7 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({nodeToObservationsMap,currentObservationIndices,previousSelectedNode,+ defaultObservationId,setCurrentObservationId,onObservationSelect,],diff --git a/web/src/features/traces/components/Trace.tsx b/web/src/features/traces/components/Trace.tsxindex 9b84faf992..a7e0b66b64 100644--- a/web/src/features/traces/components/Trace.tsx+++ b/web/src/features/traces/components/Trace.tsx@@ -1,4 +1,5 @@-import { type TraceDomain, type ScoreDomain } from "@langfuse/shared";+import { type ScoreDomain } from "@langfuse/shared";+import { type buildTraceUiData } from "@/src/features/traces/fns/treeBuilding";import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";import {@@ -42,10 +43,7 @@ import { SkeletonGroup } from "@/src/components/ui/skeleton";export type TraceProps = {isLoading?: false;observations: Array<ObservationReturnTypeWithMetadata>;- trace: Omit<WithStringifiedMetadata<TraceDomain>, "input" | "output"> & {- input: string | null;- output: string | null;- };+ trace: Parameters<typeof buildTraceUiData>[0];scores: WithStringifiedMetadata<ScoreDomain>[];corrections: ScoreDomain[];projectId: string;@@ -94,10 +92,21 @@ export function Trace(props: TraceProps | TraceLoadingProps) {? "peek-observation-focused": traceContext;const desktopLayout = DESKTOP_LAYOUTS[desktopLayoutKey];+ const isMobile = useIsMobile();+ const trace = props.isLoading === true ? null : props.trace;+ const observations = props.isLoading === true ? null : props.observations;+ const defaultObservationId = useMemo(+ () => resolveDefaultObservationId(trace, observations),+ [trace, observations],+ );return (<ViewPreferencesProvider traceContext={traceContext}>- <SelectionProvider>+ <SelectionProvider+ defaultObservationId={defaultObservationId}+ isMobile={isMobile}+ expandDetailOnMount={desktopLayout.expandDetailOnMount}+ >{props.isLoading === true ? (<TraceLoading desktopLayout={desktopLayout} />) : (@@ -395,3 +404,21 @@ function MobileTraceContent({ shouldShowGraph }: { shouldShowGraph: boolean }) {/>);}++function resolveDefaultObservationId(+ trace: TraceProps["trace"] | null,+ observations: TraceProps["observations"] | null,+) {+ /** V4 defaults to observation details; v3 keeps the trace-level view. */+ if (!trace?.rootObservationType || !observations) return null;+ if (trace.rootObservationId) return trace.rootObservationId;++ let firstRoot: ObservationReturnTypeWithMetadata | undefined;+ for (const observation of observations) {+ if (observation.parentObservationId) continue;+ if (!firstRoot || observation.startTime < firstRoot.startTime) {+ firstRoot = observation;+ }+ }+ return firstRoot?.id ?? null;+}diff --git a/web/src/features/traces/components/TraceGraphView/TraceGraphView.tsx b/web/src/features/traces/components/TraceGraphView/TraceGraphView.tsxindex 5cf3ff653b..c7df675537 100644--- a/web/src/features/traces/components/TraceGraphView/TraceGraphView.tsx+++ b/web/src/features/traces/components/TraceGraphView/TraceGraphView.tsx@@ -16,9 +16,15 @@ import { useViewPreferences } from "@/src/features/traces/contexts/ViewPreferencimport { 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";+import { useSelection } from "../../contexts/SelectionContext";export function TraceGraphView() {+ const {+ defaultObservationId,+ selectedNodeId,+ setSelectedNodeId,+ selectNode,+ } = useSelection();const { agentGraphData, isLoading } = useTraceGraphData();const { graphViewMode, setGraphViewMode } = useViewPreferences();// The trace panel's search box, resolved by the same hook the Timeline reads.@@ -27,11 +33,6 @@ export function TraceGraphView() {const search = useTraceSearchMatches();const capture = usePostHogClientCapture();const analyticsDimensions = useTraceAnalyticsDimensions();- // Optional (null on desktop): jump to the Info tab when a canvas click selects- // an observation. The graph writes `?observation=` directly, so the tab effect- // already covers a genuine change; this also handles cycling a repeated node- // back to the same id, where the URL param wouldn't change.- const mobileLayout = useMobileLayoutContextOptional();// Analytics live here (not in the feature component) so the feature module// stays free of trace-view context dependencies.const handleObservationSelect = useCallback(() => {@@ -40,8 +41,7 @@ export function TraceGraphView() {graphViewMode,...analyticsDimensions,});- mobileLayout?.switchToInfoTab();- }, [capture, graphViewMode, analyticsDimensions, mobileLayout]);+ }, [capture, graphViewMode, analyticsDimensions]);const handleViewModeChange = useCallback((mode: GraphViewMode) => {// Clicking the already-active segment is a no-op — don't count it.@@ -55,6 +55,17 @@ export function TraceGraphView() {},[capture, graphViewMode, setGraphViewMode, analyticsDimensions],);+ const handleSelectedObservationChange = useCallback(+ (id: string | null) => {+ // Synthetic graph nodes clear selection without opening details.+ if (id === null) {+ setSelectedNodeId(null);+ return;+ }+ selectNode(id);+ },+ [setSelectedNodeId, selectNode],+ );if (isLoading) {return (@@ -70,6 +81,9 @@ export function TraceGraphView() {return (<TraceGraphViewComponent+ selectedObservationId={selectedNodeId}+ defaultObservationId={defaultObservationId}+ onSelectedObservationChange={handleSelectedObservationChange}agentGraphData={agentGraphData}viewMode={graphViewMode}onViewModeChange={handleViewModeChange}diff --git a/web/src/features/traces/components/TraceLayoutDesktop.tsx b/web/src/features/traces/components/TraceLayoutDesktop.tsxindex 62ddad86da..8c463aa6f9 100644--- a/web/src/features/traces/components/TraceLayoutDesktop.tsx+++ b/web/src/features/traces/components/TraceLayoutDesktop.tsx@@ -10,7 +10,6 @@ import {type PanelImperativeHandle,} from "react-resizable-panels";import {- useState,useEffect,useLayoutEffect,useRef,@@ -122,7 +121,7 @@ const COLLAPSED_LAYOUT_SHARE_MAX_PCT = collapsedShareMaxForWidth();// Used only to seed the collapse flags on mount so `bothPanelsOpen` (and thus// the min-width pin) matches the layout the library is about to restore,-// avoiding a one-frame scrollbar flash (see the useState initializers below).+// avoiding a one-frame scrollbar flash when restoring a saved layout.function isPanelCollapsedInLayout(layout: Record<string, number> | undefined,panelId: string,@@ -173,7 +172,6 @@ type TraceLayoutDesktopProps = {children: ReactNode;groupId: string;defaultNavigationCollapsed: boolean;- expandDetailOnMount: boolean;reviewOpen: boolean;reviewPanel: ReactNode;};@@ -204,17 +202,12 @@ function TraceNavigationDetailLayout({children,groupId,defaultNavigationCollapsed,- expandDetailOnMount,reviewOpen,reviewNavigationCollapsed,toggleReviewNavigation,}: Pick<TraceLayoutDesktopProps,- | "children"- | "groupId"- | "defaultNavigationCollapsed"- | "expandDetailOnMount"- | "reviewOpen"+ "children" | "groupId" | "defaultNavigationCollapsed" | "reviewOpen"> & {reviewNavigationCollapsed: boolean;toggleReviewNavigation: () => void;@@ -248,8 +241,8 @@ function TraceNavigationDetailLayout({// Restored layout for this group. Read before the collapse flags so we can// seed them from what the library is about to restore on mount — otherwise the- // first render derives `bothPanelsOpen` purely from the useState defaults- // (open), pins the group to 621px even when a persisted layout has a panel on+ // first render assumes both panels are open and pins the group to 621px+ // even when a persisted layout has a panel on// its 40px rail, and a narrow peek flashes a useless horizontal scrollbar// until the Panel's onResize corrects the flag a frame later.const { defaultLayout, onLayoutChanged } = useDefaultLayout({@@ -265,28 +258,38 @@ function TraceNavigationDetailLayout({? collapsedShareMaxForWidth(containerWidthPx): COLLAPSED_LAYOUT_SHARE_MAX_PCT;- const [isNavigationPanelCollapsed, setIsNavigationPanelCollapsed] = useState(- () =>- (defaultNavigationCollapsed && !defaultLayout) ||+ const {+ navigationPanelCollapsed,+ detailPanelCollapsed,+ setNavigationPanelCollapsed: setIsNavigationPanelCollapsed,+ setDetailPanelCollapsed: setIsDetailPanelCollapsed,+ pendingPanelExpand: pendingExpand,+ setPendingPanelExpand: setPendingExpand,+ openDetails,+ selectedTab,+ } = useSelection();+ const isNavigationPanelCollapsed =+ navigationPanelCollapsed ??+ ((defaultNavigationCollapsed && !defaultLayout) ||isPanelCollapsedInLayout(defaultLayout,RESIZABLE_PANEL_NAVIGATION_ID,collapseSeedMaxSharePct,- ),- );+ ));// Ref to programmatically control the panelconst panelRef = usePanelRef();- // Detail (info/preview) panel collapse state + control.+ // The parent owns collapse state; until sizes are restored, derive visibility+ // from the same saved layout the panel library will apply.const detailPanelRef = usePanelRef();- const [isDetailPanelCollapsed, setIsDetailPanelCollapsed] = useState(() =>+ const isDetailPanelCollapsed =+ detailPanelCollapsed ??isPanelCollapsedInLayout(defaultLayout,RESIZABLE_PANEL_PREVIEW_ID,collapseSeedMaxSharePct,- ),- );+ );// Group ref — drives the whole layout atomically (setLayout) when reopening a// collapsed panel, which is more robust than chaining the per-panel@@ -350,9 +353,6 @@ function TraceNavigationDetailLayout({// Without this, expanding while the peek is too narrow for both mins is a// silent no-op: the group stays at its current width and the solver refuses to// shrink the open panel below its min (the original LFE-10547 symptom).- const [pendingExpand, setPendingExpand] = useState<- "navigation" | "detail" | null- >(null);// Both panels open (neither collapsed) — drives the min-width pin on the group// so a too-narrow peek scrolls horizontally instead of force-collapsing one.@@ -386,6 +386,14 @@ function TraceNavigationDetailLayout({// mins + horizontal scroll); on a wide peek it's a true 50/50.useEffect(() => {if (!pendingExpand) return;+ const requestedPanel =+ pendingExpand === "navigation"+ ? panelRef.current+ : detailPanelRef.current;+ if (requestedPanel && !requestedPanel.isCollapsed()) {+ setPendingExpand(null);+ return;+ }if (reviewOpen) {setPendingExpand(null);return;@@ -459,22 +467,26 @@ function TraceNavigationDetailLayout({cancelAnimationFrame(outerRaf);cancelAnimationFrame(innerRaf);};- }, [pendingExpand, reviewOpen, groupRef, panelRef, detailPanelRef, groupId]);+ }, [+ pendingExpand,+ reviewOpen,+ groupRef,+ panelRef,+ detailPanelRef,+ groupId,+ setIsDetailPanelCollapsed,+ setIsNavigationPanelCollapsed,+ setPendingExpand,+ ]);// Guarded so it's a no-op (not a resize) when already open — safe to call on// every row click, which is how re-selecting the same node reopens it.const expandDetailPanel = () => {if (reviewOpen) return;if (!detailPanelRef.current?.isCollapsed()) return;- setPendingExpand("detail");+ openDetails();};- // Selecting another node (timeline/tree) while the detail panel is collapsed- // reopens it. Annotation items also reopen it on mount so a collapsed layout- // cannot hide the trace overview on the next trace-level queue item. Re-- // selecting the same node is handled at the row click via expandDetailPanel,- // since the URL param — and thus this effect — doesn't change on re-click.- const { selectedNodeId, selectedTab } = useSelection();const internalFeaturesEnabled = useInternalFeaturesEnabled();const { isV4 } = useReadPath();const showMessages =@@ -483,12 +495,6 @@ function TraceNavigationDetailLayout({if (!showMessages || reviewOpen) return;panelRef.current?.collapse();}, [showMessages, reviewOpen, panelRef]);- useEffect(() => {- // Guard on selectedNodeId so a deliberately-collapsed panel isn't reopened- // on mount/refresh when there's no selection (effects always run once).- if (selectedNodeId || expandDetailOnMount) expandDetailPanel();- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [selectedNodeId]);// Apply the caller's first-use default. A restored layout always wins.useEffect(() => {diff --git a/web/src/features/traces/components/TraceLayoutMobile.tsx b/web/src/features/traces/components/TraceLayoutMobile.tsxindex 977fba7ba9..f548ce6109 100644--- a/web/src/features/traces/components/TraceLayoutMobile.tsx+++ b/web/src/features/traces/components/TraceLayoutMobile.tsx@@ -8,7 +8,7 @@* selecting an observation in any of them jumps to the Info tab (which reuses* the shared detail panel). See MobileTraceContent in Trace.tsx for composition.*- * Mobile-only: this component (and its context) render solely under the mobile+ * Mobile-only: this component renders solely under the mobile* path. Desktop uses TraceLayoutDesktop and never mounts this.** Tab state lives in the `?mobileTab` URL param (shareable + back-able), never@@ -17,50 +17,16 @@* Tree.** Selection → Info wiring is purely imperative: all three navigators- * (Tree/Timeline/Graph) call `switchToInfoTab()` on select, so selecting a node- * jumps to Info. There is deliberately NO reactive selection→tab effect — see- * `switchToInfoTab` for why one would corrupt Back/Forward.+ * (Tree/Timeline/Graph) use the parent's select-and-open action. There is no+ * reactive selection→tab effect that could overwrite restored browser history.*/-import {- createContext,- useContext,- useCallback,- useMemo,- useState,- type ReactNode,-} from "react";-import { StringParam, useQueryParam } from "use-query-params";+import { type ReactNode } from "react";import { Tabs } from "@/src/components/design-system/Tabs/Tabs";-import { useSelection } from "@/src/features/traces/contexts/SelectionContext";+import { useSelection } from "../contexts/SelectionContext";import { TraceTruncationNotice } from "./TraceTruncationNotice";export type MobileTraceTab = "tree" | "timeline" | "graph" | "info";-const VALID_TABS: MobileTraceTab[] = ["tree", "timeline", "graph", "info"];--function isValidTab(value: string | null | undefined): value is MobileTraceTab {- return VALID_TABS.includes(value as MobileTraceTab);-}--// Mirror of TraceLayoutDesktop's layout context: exposes the imperative-// tab-switch so shared navigators can wire mobile behavior additively.-interface MobileLayoutContextValue {- switchToInfoTab: () => void;-}--const MobileLayoutContext = createContext<MobileLayoutContextValue | null>(- null,-);--/**- * Safe variant for components rendered in BOTH desktop and mobile layouts- * (desktop has no provider): returns null instead of throwing, so a `?.` call- * is a no-op on desktop and keeps the desktop path byte-identical.- */-export function useMobileLayoutContextOptional() {- return useContext(MobileLayoutContext);-}-export function TraceLayoutMobile({tree,timeline,@@ -78,84 +44,54 @@ export function TraceLayoutMobile({/** Skips the data-bound notice while the panels show placeholders. */isLoading?: boolean;}) {- const [tabParam, setTabParam] = useQueryParam("mobileTab", StringParam);- const { selectedNodeId } = useSelection();-- // Mount-time default only (captured once, never re-derived): a selection that- // was already present when the view opened lands on Info; otherwise Tree.- const [initialTab] = useState<MobileTraceTab>(() =>- selectedNodeId ? "info" : "tree",- );-- const requestedTab = isValidTab(tabParam) ? tabParam : initialTab;+ const { mobileTab, setMobileTab } = useSelection();// The Graph tab is conditionally rendered; if a stale/shared URL asks for it// while it's unavailable, fall back to Tree.const activeTab: MobileTraceTab =- requestedTab === "graph" && !showGraph ? "tree" : requestedTab;-- // Auto-switch to Info writes PUSH, not replace. Every navigator's select- // handler writes the `?observation=` param (pushIn) and calls this in the- // SAME tick, so with use-query-params batching (`enableBatching`, set in- // _app.tsx) both writes fold into ONE navigation whose updateType is taken- // from the LAST enqueued write — pushIn here keeps the combined selection+tab- // change as a single pushed history entry, so Back returns to the- // pre-selection view. (replaceIn would downgrade the whole batch to- // history.replaceState and drop that entry, so Back would leave the trace.)- //- // There is deliberately NO reactive selection→tab effect. All three- // navigators call this imperatively, so an effect keyed on `selectedNodeId`- // would be redundant on forward selections — and would BREAK Back/Forward: a- // POP that restores an older `{observation, mobileTab=tree}` entry changes- // `selectedNodeId`, which an effect cannot distinguish from a live tap, so it- // would immediately overwrite the just-restored tab back to Info and trap the- // user (LFE-11067). Letting the restored URL win outright is correct.- const switchToInfoTab = useCallback(() => {- setTabParam("info", "pushIn");- }, [setTabParam]);-- const contextValue = useMemo<MobileLayoutContextValue>(- () => ({ switchToInfoTab }),- [switchToInfoTab],- );+ mobileTab === "graph" && !showGraph ? "tree" : mobileTab;+ const handleTabChange = (value: string) => {+ if (+ value === "tree" ||+ value === "timeline" ||+ value === "graph" ||+ value === "info"+ ) {+ setMobileTab(value);+ }+ };return (- <MobileLayoutContext.Provider value={contextValue}>- <Tabs- value={activeTab}- onValueChange={(value) => setTabParam(value, "pushIn")}- layout="fill"- >- <Tabs.List variant="underline">- <Tabs.Trigger value="tree" label="Tree" />- <Tabs.Trigger value="timeline" label="Timeline" />- {showGraph && <Tabs.Trigger value="graph" label="Graph" />}- <Tabs.Trigger value="info" label="Data" />- </Tabs.List>+ <Tabs value={activeTab} onValueChange={handleTabChange} layout="fill">+ <Tabs.List variant="underline">+ <Tabs.Trigger value="tree" label="Tree" />+ <Tabs.Trigger value="timeline" label="Timeline" />+ {showGraph && <Tabs.Trigger value="graph" label="Graph" />}+ <Tabs.Trigger value="info" label="Data" />+ </Tabs.List>- {/* Above the tab bodies, not inside one: the truncation applies to every+ {/* Above the tab bodies, not inside one: the truncation applies to everytab, and the navigators own their own scroll containers. */}- {!isLoading && <TraceTruncationNotice />}+ {!isLoading && <TraceTruncationNotice />}- {/* Inactive tabs unmount (Radix default). On memory-constrained mobile+ {/* Inactive tabs unmount (Radix default). On memory-constrained mobilethat keeps a single heavy subtree live at a time (two virtualizers,the elk graph layout, and the detail JSON never all mount at once);the cost is that a navigator's scroll/zoom resets when revisited —an accepted v1 tradeoff (follow-up: preserve navigator state). */}- <Tabs.Content value="tree" layout="fill">- {tree}- </Tabs.Content>- <Tabs.Content value="timeline" layout="fill">- {timeline}- </Tabs.Content>- {showGraph && (- <Tabs.Content value="graph" layout="fill">- {graph}- </Tabs.Content>- )}- <Tabs.Content value="info" layout="fill">- {info}+ <Tabs.Content value="tree" layout="fill">+ {tree}+ </Tabs.Content>+ <Tabs.Content value="timeline" layout="fill">+ {timeline}+ </Tabs.Content>+ {showGraph && (+ <Tabs.Content value="graph" layout="fill">+ {graph}</Tabs.Content>- </Tabs>- </MobileLayoutContext.Provider>+ )}+ <Tabs.Content value="info" layout="fill">+ {info}+ </Tabs.Content>+ </Tabs>);}diff --git a/web/src/features/traces/components/TraceMessagesView/TraceMessagesView.tsx b/web/src/features/traces/components/TraceMessagesView/TraceMessagesView.tsxindex 6fabea4375..58de38a771 100644--- a/web/src/features/traces/components/TraceMessagesView/TraceMessagesView.tsx+++ b/web/src/features/traces/components/TraceMessagesView/TraceMessagesView.tsx@@ -19,7 +19,6 @@ import { useSelection } from "@/src/features/traces/contexts/SelectionContext";import { useTraceData } from "@/src/features/traces/contexts/TraceDataContext";import { toIOPreview } from "@/src/features/traces/parsers/toIOPreview";import { IO_SECTIONS_FLUSH_CLASS } from "@/src/features/traces/constants/ioSectionClasses";-import { useDesktopLayoutContextOptional } from "../TraceLayoutDesktop";type Transcript = NonNullable<RouterOutputs["events"]["transcriptByTraceId"]["transcript"]@@ -95,8 +94,7 @@ function ThreadBlock({projectId: string;traceId: string;}) {- const { setSelectedNodeId } = useSelection();- const layout = useDesktopLayoutContextOptional();+ const { selectNode } = useSelection();// History is context, not the point of the view; start folded.const [showHistory, setShowHistory] = useState(false);// Media of the emitting observations, so inline references resolve the way@@ -114,8 +112,7 @@ function ThreadBlock({const media = mediaQueries.flatMap((query) => query.data ?? []);const selectObservation = (id: string) => {- setSelectedNodeId(id);- layout?.expandDetailPanel();+ selectNode(id);};return (diff --git a/web/src/features/traces/components/TraceReviewPanel.tsx b/web/src/features/traces/components/TraceReviewPanel.tsxindex d9e79815e4..0cd30aa7da 100644--- a/web/src/features/traces/components/TraceReviewPanel.tsx+++ b/web/src/features/traces/components/TraceReviewPanel.tsx@@ -16,6 +16,7 @@ import { AnnotationPanelContent } from "@/src/features/scores/components/Annotatimport { hasBlockingOverlay } from "@/src/features/scores/lib/keyboardShortcuts";import { useTraceReviewPanel } from "../contexts/TraceReviewPanelContext";import { type TraceReviewPanelStore } from "../state/traceReviewPanelStore";+import { traceNodeId } from "../fns/treeBuilding";function closeReviewPanel(store: TraceReviewPanelStore, router: NextRouter) {store.getState().actions.close();@@ -129,7 +130,12 @@ function TraceAnnotationPanel() {const { isV4 } = useReadPath();const observation = observations.find((item) => item.id === selectedNodeId);const active = useRouter().query.annotation === "open";- if (selectedNodeId && selectedNodeId !== trace.id && !observation) {+ if (+ selectedNodeId &&+ selectedNodeId !== trace.id &&+ selectedNodeId !== traceNodeId(trace.id) &&+ !observation+ ) {return (<div className="p-4 text-sm" hidden={!active}>Loading annotation…diff --git a/web/src/features/traces/components/TraceSearchList.tsx b/web/src/features/traces/components/TraceSearchList.tsxindex 4b93b82330..c86bc16531 100644--- a/web/src/features/traces/components/TraceSearchList.tsx+++ b/web/src/features/traces/components/TraceSearchList.tsx@@ -11,7 +11,6 @@ import { useTraceData } from "@/src/features/traces/contexts/TraceDataContext";import { useSearch } from "@/src/features/traces/contexts/SearchContext";import { useSelection } from "@/src/features/traces/contexts/SelectionContext";import { useHandlePrefetchObservation } from "@/src/features/traces/hooks/useHandlePrefetchObservation";-import { 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";@@ -23,13 +22,10 @@ import { XIcon } from "lucide-react";export function TraceSearchList() {const { searchItems } = useTraceData();const { searchQuery, setSearchInputValue } = useSearch();- const { selectedNodeId, setSelectedNodeId } = useSelection();+ const { selectedNodeId, selectNode } = useSelection();const { handleHover } = useHandlePrefetchObservation();const capture = usePostHogClientCapture();const analyticsDimensions = useTraceAnalyticsDimensions();- // Optional (null on mobile): reopen the detail panel on select, including- // re-selecting the already-selected result.- const layout = useDesktopLayoutContextOptional();const handleSelectItem = (id: string | null) => {if (id) {capture("trace_detail:node_selected", {@@ -37,8 +33,7 @@ export function TraceSearchList() {...analyticsDimensions,});}- setSelectedNodeId(id);- layout?.expandDetailPanel();+ selectNode(id);};// Co-located filtering - only this component re-renders on search query change.diff --git a/web/src/features/traces/contexts/SelectionContext.tsx b/web/src/features/traces/contexts/SelectionContext.tsxindex c2d666af59..6c2cfefa74 100644--- a/web/src/features/traces/contexts/SelectionContext.tsx+++ b/web/src/features/traces/contexts/SelectionContext.tsx@@ -3,6 +3,7 @@** Purpose:* - Tracks selected node ID (synced to URL query param)+ * - Owns panel visibility and the mobile tab alongside selection* - Manages collapsed/expanded state for tree nodes* - Handles search query with debounced input* - Tracks selected detail tab - synced to URL query param `traceTab`@@ -22,6 +23,8 @@ import {createContext,useContext,useState,+ useEffect,+ useRef,useCallback,useMemo,type ReactNode,@@ -29,6 +32,7 @@ import {import { StringParam, useQueryParam } from "use-query-params";import { useDebounce } from "@/src/hooks/useDebounce";import { useViewPreferences } from "./ViewPreferencesContext";+import { type MobileTraceTab } from "../components/TraceLayoutMobile";import {isPrettyLikeJsonView,type JsonViewPreference,@@ -43,8 +47,20 @@ export type ViewPref = "formatted" | "json";const VALID_PREFS: ViewPref[] = ["formatted", "json"];interface SelectionContextValue {+ defaultObservationId: string | null;selectedNodeId: string | null;setSelectedNodeId: (id: string | null) => void;+ selectNode: (id: string | null) => void;+ openDetails: () => void;+ mobileTab: MobileTraceTab;+ setMobileTab: (tab: MobileTraceTab) => void;+ /** Null until the layout restores its saved sizes. */+ navigationPanelCollapsed: boolean | null;+ detailPanelCollapsed: boolean | null;+ setNavigationPanelCollapsed: (collapsed: boolean) => void;+ setDetailPanelCollapsed: (collapsed: boolean) => void;+ pendingPanelExpand: "navigation" | "detail" | null;+ setPendingPanelExpand: (panel: "navigation" | "detail" | null) => void;collapsedNodes: Set<string>;toggleCollapsed: (id: string) => void;expandAll: () => void;@@ -72,15 +88,105 @@ export function useSelection(): SelectionContextValue {interface SelectionProviderProps {children: ReactNode;+ defaultObservationId: string | null;+ isMobile: boolean;+ expandDetailOnMount: boolean;}-export function SelectionProvider({ children }: SelectionProviderProps) {+export function SelectionProvider({+ children,+ defaultObservationId,+ isMobile,+ expandDetailOnMount,+}: SelectionProviderProps) {const [currentObservationId, setCurrentObservationId] = useQueryParam("observation",StringParam,);+ const previousObservationId = useRef(currentObservationId ?? null);+ const pendingObservationId = useRef<string | null | undefined>(undefined);const [tabParam, setTabParam] = useQueryParam("traceTab", StringParam);const [prefParam, setPrefParam] = useQueryParam("pref", StringParam);+ const [mobileTabParam, setMobileTabParam] = useQueryParam(+ "mobileTab",+ StringParam,+ );+ // Opening intent is captured before the implicit root is applied. Later+ // default-root changes choose content without changing the user's layout.+ const [initialMobileTab] = useState<"tree" | "info">(+ currentObservationId ? "info" : "tree",+ );+ const mobileTab =+ mobileTabParam === "tree" ||+ mobileTabParam === "timeline" ||+ mobileTabParam === "graph" ||+ mobileTabParam === "info"+ ? mobileTabParam+ : initialMobileTab;+ const [navigationPanelCollapsed, setNavigationPanelCollapsed] = useState<+ boolean | null+ >(null);+ const [detailPanelCollapsed, setDetailPanelCollapsed] = useState<+ boolean | null+ >(null);+ const [pendingPanelExpand, setPendingPanelExpand] = useState<+ "navigation" | "detail" | null+ >(+ !isMobile && (currentObservationId || expandDetailOnMount)+ ? "detail"+ : null,+ );+ const setMobileTab = useCallback(+ (tab: SelectionContextValue["mobileTab"]) => {+ // Write last when selecting on mobile: batching keeps selection + tab in+ // one pushed history entry. Never infer a tab switch from selection changes,+ // which would overwrite the tab restored by Back/Forward (LFE-11067).+ setMobileTabParam(tab, "pushIn");+ },+ [setMobileTabParam],+ );+ const openDetails = useCallback(() => {+ if (isMobile) {+ setMobileTab("info");+ return;+ }+ if (detailPanelCollapsed !== false) setPendingPanelExpand("detail");+ }, [isMobile, setMobileTab, detailPanelCollapsed]);+ const selectNode = useCallback(+ (id: string | null) => {+ pendingObservationId.current = id;+ setCurrentObservationId(id);+ openDetails();+ },+ [setCurrentObservationId, openDetails],+ );+ const setSelectedNodeId = useCallback(+ (id: string | null) => {+ // Synthetic graph nodes intentionally change selection without opening details.+ pendingObservationId.current = id;+ setCurrentObservationId(id);+ },+ [setCurrentObservationId],+ );++ // History navigation bypasses selectNode. Watch only the explicit URL+ // selection so loading an implicit root never changes panel visibility.+ useEffect(() => {+ const observationId = currentObservationId ?? null;+ const changed = previousObservationId.current !== observationId;+ previousObservationId.current = observationId;++ if (!changed) return;++ // Query writes are batched; unrelated renders can happen before they land.+ // Consume the action's echo only once the URL selection actually changes.+ const pendingId = pendingObservationId.current;+ pendingObservationId.current = undefined;+ if (pendingId === observationId || isMobile) return;+ if (observationId === null) return;++ openDetails();+ }, [currentObservationId, isMobile, openDetails]);// Get localStorage default for view preferenceconst { jsonViewPreference, setJsonViewPreference } = useViewPreferences();@@ -166,17 +272,21 @@ export function SelectionProvider({ children }: SelectionProviderProps) {setCollapsedNodesArray(nodeIds);}, []);- const setSelectedNodeId = useCallback(- (id: string | null) => {- setCurrentObservationId(id);- },- [setCurrentObservationId],- );-const value = useMemo<SelectionContextValue>(() => ({- selectedNodeId: currentObservationId ?? null,+ defaultObservationId,+ selectedNodeId: currentObservationId ?? defaultObservationId,setSelectedNodeId,+ selectNode,+ openDetails,+ mobileTab,+ setMobileTab,+ navigationPanelCollapsed,+ detailPanelCollapsed,+ setNavigationPanelCollapsed,+ setDetailPanelCollapsed,+ pendingPanelExpand,+ setPendingPanelExpand,collapsedNodes,toggleCollapsed,expandAll,@@ -192,7 +302,15 @@ export function SelectionProvider({ children }: SelectionProviderProps) {}),[currentObservationId,+ defaultObservationId,setSelectedNodeId,+ selectNode,+ openDetails,+ mobileTab,+ setMobileTab,+ navigationPanelCollapsed,+ detailPanelCollapsed,+ pendingPanelExpand,collapsedNodes,toggleCollapsed,expandAll,diff --git a/web/src/features/traces/hooks/useSelectTraceNode.ts b/web/src/features/traces/hooks/useSelectTraceNode.tsindex ed3a5f5aea..9cde243c6f 100644--- a/web/src/features/traces/hooks/useSelectTraceNode.ts+++ b/web/src/features/traces/hooks/useSelectTraceNode.ts@@ -2,8 +2,6 @@ import { useCallback } from "react";import { useSelection } from "@/src/features/traces/contexts/SelectionContext";import { usePostHogClientCapture } from "@/src/features/posthog-analytics";import { useTraceAnalyticsDimensions } from "@/src/features/traces/hooks/useTraceAnalyticsDimensions";-import { useDesktopLayoutContextOptional } from "@/src/features/traces/components/TraceLayoutDesktop";-import { useMobileLayoutContextOptional } from "@/src/features/traces/components/TraceLayoutMobile";/** Which view is reporting the selection — the only thing that differs. */export type TraceNodeSelectionSource = "tree" | "timeline" | "timeline_compact";@@ -19,11 +17,9 @@ export type TraceNodeSelectionSource = "tree" | "timeline" | "timeline_compact";* bring the detail back after you collapsed it.*/export function useSelectTraceNode(source: TraceNodeSelectionSource) {- const { setSelectedNodeId } = useSelection();+ const { selectNode } = useSelection();const capture = usePostHogClientCapture();const analyticsDimensions = useTraceAnalyticsDimensions();- const layout = useDesktopLayoutContextOptional();- const mobileLayout = useMobileLayoutContextOptional();return useCallback((nodeId: string | null) => {@@ -33,17 +29,8 @@ export function useSelectTraceNode(source: TraceNodeSelectionSource) {...analyticsDimensions,});}- setSelectedNodeId(nodeId);- layout?.expandDetailPanel();- if (nodeId) mobileLayout?.switchToInfoTab();+ selectNode(nodeId);},- [- source,- capture,- analyticsDimensions,- setSelectedNodeId,- layout,- mobileLayout,- ],+ [source, capture, analyticsDimensions, selectNode],);}