πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(analytics): instrument peek / graph / timeline / tree view usage (LFE-10786) (#14947)
Nikita Kabardin69950bdcc770
diff --git a/web/src/components/table/peek.tsx b/web/src/components/table/peek.tsxindex 75f43f83f7..3e984dffda 100644--- a/web/src/components/table/peek.tsx+++ b/web/src/components/table/peek.tsx@@ -13,6 +13,8 @@ import { PeekTableStateProvider } from "@/src/components/table/peek/contexts/Peeimport { PeekHeader } from "@/src/components/table/peek/PeekHeader";import { usePeekPanelState } from "@/src/components/table/peek/usePeekPanelState";import { shouldIgnoreOutsideInteraction } from "@/src/utils/outside-interaction";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";// Peek view-mode URL param (also cleared by usePeekNavigation on close). When// `expanded`, the desktop peek widens to viewport β sidebar β shareable + back-able.@@ -142,6 +144,8 @@ export const shouldClosePeekAfterDelete = (function TablePeekViewComponent(props: TablePeekViewProps) {const { title, children } = props;const router = useRouter();+ const capture = usePostHogClientCapture();+ const { isBetaEnabled: isV4 } = useV4Beta();const itemId = router.query.peek as string | undefined;const isExpanded = router.query[PEEK_VIEW_PARAM] === PEEK_VIEW_EXPANDED;const isMobile = useIsMobile();@@ -158,6 +162,13 @@ function TablePeekViewComponent(props: TablePeekViewProps) {// No-op when the flag already matches: skip the redundant shallow// router.replace (and the re-render it would otherwise trigger).if (expanded === currentlyExpanded) return;+ // Header button, drag-past-threshold, and keyboard all commit through+ // here, so this (post no-op guard) fires once per real toggle.+ capture("peek:expand_toggle", {+ isExpanded: expanded,+ routePattern: router.pathname,+ isV4,+ });if (expanded) params.set(PEEK_VIEW_PARAM, PEEK_VIEW_EXPANDED);else params.delete(PEEK_VIEW_PARAM);router.replace(@@ -169,13 +180,25 @@ function TablePeekViewComponent(props: TablePeekViewProps) {{ shallow: true },);},- [router],+ [router, capture, isV4],);const panel = usePeekPanelState({isOpen: !!itemId,isExpanded,onExpandedChange: setExpanded,+ onResized: useCallback(+ (widthFraction: number, trigger: "drag" | "keyboard") => {+ capture("peek:resized", {+ // Bucketed viewport percentage β coarse metadata, not px.+ widthPercent: Math.round((widthFraction * 100) / 5) * 5,+ trigger,+ routePattern: router.pathname,+ isV4,+ });+ },+ [capture, router.pathname, isV4],+ ),});const ignoredSelectors = props.peekEventOptions?.ignoredSelectors ?? [];diff --git a/web/src/components/table/peek/actions/resizePeekPanel.ts b/web/src/components/table/peek/actions/resizePeekPanel.tsindex 858cc2030f..b21fdfdd1a 100644--- a/web/src/components/table/peek/actions/resizePeekPanel.ts+++ b/web/src/components/table/peek/actions/resizePeekPanel.ts@@ -36,6 +36,9 @@ export function beginPeekResize(// does (otherwise starting a drag while expanded snaps to the widget width// on pointer-down, a visible jump).startExpanded = false,+ // Notified once per drag gesture that commits a widget width (not on+ // expand-commits or cancelled drags) β the hook's analytics seam.+ onWidthCommit?: (fraction: number) => void,): () => void {// Only primary-button drags; the keyboard path handles the rest.if (event.button !== 0) return () => {};@@ -71,6 +74,7 @@ export function beginPeekResize(// Released on a widget width β persist it and ensure we're collapsed.actions.commitWidth(draftFraction);commitExpanded(false);+ onWidthCommit?.(draftFraction);}// The hook holds the committed expanded value (pendingExpanded) until the// URL catches up, so clearing the drag state here can't flash the old width.diff --git a/web/src/components/table/peek/hooks/usePeekNavigation.ts b/web/src/components/table/peek/hooks/usePeekNavigation.tsindex 2baee4fe3c..699d9840bd 100644--- a/web/src/components/table/peek/hooks/usePeekNavigation.ts+++ b/web/src/components/table/peek/hooks/usePeekNavigation.ts@@ -3,6 +3,8 @@ import { type ListEntry } from "@/src/features/navigate-detail-pages/context";import { useRouter } from "next/router";import { useCallback } from "react";import { urlSearchParamsToQuery } from "@/src/utils/navigation";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";const PEEK_PARAM = "peek";// View-mode param shared with the peek component (cleared whenever the peek closes).@@ -67,19 +69,38 @@ export function usePeekNavigation(export function usePeekNavigation(config?: PeekConfig): PeekNavigation;export function usePeekNavigation(config?: PeekConfig | PeekConfigWithExpand) {const router = useRouter();+ const capture = usePostHogClientCapture();+ const { isBetaEnabled: isV4 } = useV4Beta();+ // Every peek is opened/closed through this hook, so open/close/new-tab+ // analytics live here once instead of in each consuming table. Props are+ // metadata-only: `routePattern` is the Next.js route PATTERN+ // (`/project/[projectId]/traces`), never a concrete URL with ids.+ const routePattern = router.pathname;const openPeek = useCallback((id?: string, row?: any) => {const pathname = getPathnameWithoutBasePath();const url = new URL(window.location.href);const params = new URLSearchParams(url.search);+ const currentPeekId = params.get(PEEK_PARAM);if (!id) {// Close peek view - clear all peek-related params+ if (currentPeekId !== null) {+ capture("peek:closed", { routePattern, isV4 });+ }params.delete(PEEK_PARAM);params.delete(PEEK_VIEW_PARAM);config?.queryParams?.forEach((param) => params.delete(param));} else {+ // Re-clicking the already-peeked row is a no-op open β don't count it.+ if (id !== currentPeekId) {+ capture("peek:opened", {+ routePattern,+ wasOpen: currentPeekId !== null,+ isV4,+ });+ }// Clear all query params that are set in the configconfig?.queryParams?.forEach((param) => params.delete(param));@@ -109,7 +130,7 @@ export function usePeekNavigation(config?: PeekConfig | PeekConfigWithExpand) {{ shallow: true },);},- [router, config],+ [router, config, capture, routePattern, isV4],);const closePeek = useCallback(() => {@@ -117,6 +138,11 @@ export function usePeekNavigation(config?: PeekConfig | PeekConfigWithExpand) {const url = new URL(window.location.href);const params = new URLSearchParams(url.search);+ // Guarded so programmatic cleanup with no peek open emits nothing.+ if (params.get(PEEK_PARAM) !== null) {+ capture("peek:closed", { routePattern, isV4 });+ }+// Close peek view - clear all peek-related paramsparams.delete(PEEK_PARAM);params.delete(PEEK_VIEW_PARAM);@@ -130,7 +156,7 @@ export function usePeekNavigation(config?: PeekConfig | PeekConfigWithExpand) {undefined,{ shallow: true },);- }, [router, config]);+ }, [router, config, capture, routePattern, isV4]);const resolveDetailNavigationPath = useCallback((entry: ListEntry) => {@@ -184,13 +210,14 @@ export function usePeekNavigation(config?: PeekConfig | PeekConfigWithExpand) {const pathnameWithQuery = `${pathname}?${queryParams}`;if (openInNewTab) {+ capture("peek:open_in_new_tab", { routePattern, isV4 });const pathnameWithBasePath = `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}${pathnameWithQuery}`;window.open(pathnameWithBasePath, "_blank");} else {router.push(pathnameWithQuery);}},- [router, config],+ [router, config, capture, routePattern, isV4],);const baseNavigation = {diff --git a/web/src/components/table/peek/usePeekPanelState.ts b/web/src/components/table/peek/usePeekPanelState.tsindex 27b8e30e13..0889b48bf1 100644--- a/web/src/components/table/peek/usePeekPanelState.ts+++ b/web/src/components/table/peek/usePeekPanelState.ts@@ -18,6 +18,10 @@ import {} from "@/src/components/table/peek/store/peekPanelStore";import { beginPeekResize } from "@/src/components/table/peek/actions/resizePeekPanel";+// A burst of keyboard nudges is one resize action β trailing-debounce it into+// a single onResized notification.+const KEYBOARD_RESIZE_NOTIFY_DEBOUNCE_MS = 1000;+export type PeekPanelView = {/** Whether the panel is expanded to max width (viewport β sidebar). */isExpanded: boolean;@@ -66,10 +70,17 @@ export function usePeekPanelState({isOpen,isExpanded,onExpandedChange,+ onResized,}: {isOpen: boolean;isExpanded: boolean;onExpandedChange: (expanded: boolean) => void;+ /**+ * Notified once per user resize gesture that lands on a widget width β a+ * completed drag, or a burst of keyboard nudges (debounced). The host's+ * analytics seam; expand-commits and cancelled drags don't notify.+ */+ onResized?: (widthFraction: number, trigger: "drag" | "keyboard") => void;}): PeekPanelView {const [store] = useState(() => createPeekPanelStore());@@ -77,6 +88,26 @@ export function usePeekPanelState({const draftExpanded = useStore(store, selectDraftExpanded);const widgetWidth = useStore(store, selectWidgetWidth);+ // Keep the latest callback in a ref so drag/keyboard closures never go+ // stale and the memoized handlers don't churn on a new callback identity.+ const onResizedRef = useRef(onResized);+ useEffect(() => {+ onResizedRef.current = onResized;+ }, [onResized]);+ const keyboardResizeNotifyTimeoutRef = useRef<ReturnType<+ typeof setTimeout+ > | null>(null);+ // Cancelled whenever another gesture takes over (a drag starts) or the peek+ // closes β a pending keyboard notification must not fire with the new+ // gesture's width (mislabeled trigger) or after dismissal.+ const cancelKeyboardResizeNotify = useCallback(() => {+ if (keyboardResizeNotifyTimeoutRef.current) {+ clearTimeout(keyboardResizeNotifyTimeoutRef.current);+ keyboardResizeNotifyTimeoutRef.current = null;+ }+ }, []);+ useEffect(() => cancelKeyboardResizeNotify, [cancelKeyboardResizeNotify]);+// Locally-committed expanded value, held until the URL reflects it.const [pendingExpanded, setPendingExpanded] = useState<boolean | null>(null);useEffect(() => setPendingExpanded(null), [isExpanded]);@@ -143,12 +174,16 @@ export function usePeekPanelState({store.getState().actions.cancelResize();}, [store]);useEffect(() => {- if (!isOpen) endActiveDrag();- }, [isOpen, endActiveDrag]);+ if (!isOpen) {+ endActiveDrag();+ cancelKeyboardResizeNotify();+ }+ }, [isOpen, endActiveDrag, cancelKeyboardResizeNotify]);useEffect(() => endActiveDrag, [endActiveDrag]);const onPointerDown = useCallback((event: ReactPointerEvent) => {+ cancelKeyboardResizeNotify();// The drag flips to expanded at the sidebar edge (viewport β sidebar),// clamped to the widget bounds, so it can't overshoot onto the sidebar.const vw = typeof window === "undefined" ? 0 : window.innerWidth;@@ -165,9 +200,16 @@ export function usePeekPanelState({commitExpanded,expandAtFraction,effectiveExpanded,+ (fraction) => onResizedRef.current?.(fraction, "drag"),);},- [store, commitExpanded, sidebarOffset, effectiveExpanded],+ [+ store,+ commitExpanded,+ sidebarOffset,+ effectiveExpanded,+ cancelKeyboardResizeNotify,+ ],);const onKeyDown = useCallback(@@ -177,12 +219,20 @@ export function usePeekPanelState({if (event.key === "ArrowLeft" || event.key === "ArrowRight") {event.preventDefault();commitExpanded(false);+ const before = store.getState().widthFraction;store.getState().actions.nudgeWidth(event.key === "ArrowLeft" ? "grow" : "shrink");+ // Nudging against the min/max clamp changes nothing β notify nothing.+ if (store.getState().widthFraction === before) return;+ cancelKeyboardResizeNotify();+ keyboardResizeNotifyTimeoutRef.current = setTimeout(() => {+ keyboardResizeNotifyTimeoutRef.current = null;+ onResizedRef.current?.(store.getState().widthFraction, "keyboard");+ }, KEYBOARD_RESIZE_NOTIFY_DEBOUNCE_MS);}},- [store, commitExpanded],+ [store, commitExpanded, cancelKeyboardResizeNotify],);// Toggle relative to what the button currently SHOWS (effectiveExpanded),diff --git a/web/src/components/trace/components/TraceGraphView/TraceGraphView.tsx b/web/src/components/trace/components/TraceGraphView/TraceGraphView.tsxindex c1a71c00af..a99325fa83 100644--- a/web/src/components/trace/components/TraceGraphView/TraceGraphView.tsx+++ b/web/src/components/trace/components/TraceGraphView/TraceGraphView.tsx@@ -5,15 +5,43 @@* and uses data from GraphDataContext.*/+import { useCallback } from "react";import { TraceGraphView as TraceGraphViewComponent } from "@/src/features/trace-graph-view/components/TraceGraphView";+import { type GraphViewMode } from "@/src/features/trace-graph-view/types";import { useTraceGraphData } from "../../contexts/TraceGraphDataContext";import { useActiveObservationIds } from "../../contexts/PlayheadContext";import { useViewPreferences } from "../../contexts/ViewPreferencesContext";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { useTraceAnalyticsDimensions } from "../../hooks/useTraceAnalyticsDimensions";export function TraceGraphView() {const { agentGraphData, isLoading } = useTraceGraphData();const activeObservationIds = useActiveObservationIds();const { graphViewMode, setGraphViewMode } = useViewPreferences();+ const capture = usePostHogClientCapture();+ const analyticsDimensions = useTraceAnalyticsDimensions();+ // Analytics live here (not in the feature component) so the feature module+ // stays free of trace-view context dependencies.+ const handleObservationSelect = useCallback(() => {+ capture("trace_detail:node_selected", {+ source: "graph",+ graphViewMode,+ ...analyticsDimensions,+ });+ }, [capture, graphViewMode, analyticsDimensions]);+ const handleViewModeChange = useCallback(+ (mode: GraphViewMode) => {+ // Clicking the already-active segment is a no-op β don't count it.+ if (mode !== graphViewMode) {+ capture("trace_detail:graph_mode_switch", {+ graphViewMode: mode,+ ...analyticsDimensions,+ });+ }+ setGraphViewMode(mode);+ },+ [capture, graphViewMode, setGraphViewMode, analyticsDimensions],+ );if (isLoading) {return (@@ -32,7 +60,8 @@ export function TraceGraphView() {agentGraphData={agentGraphData}activeObservationIds={activeObservationIds}viewMode={graphViewMode}- onViewModeChange={setGraphViewMode}+ onViewModeChange={handleViewModeChange}+ onObservationSelect={handleObservationSelect}/>);}diff --git a/web/src/components/trace/components/TraceSearchList.tsx b/web/src/components/trace/components/TraceSearchList.tsxindex 007f813075..6015206a96 100644--- a/web/src/components/trace/components/TraceSearchList.tsx+++ b/web/src/components/trace/components/TraceSearchList.tsx@@ -12,6 +12,8 @@ import { useSearch } from "../contexts/SearchContext";import { useSelection } from "../contexts/SelectionContext";import { useHandlePrefetchObservation } from "../hooks/useHandlePrefetchObservation";import { useDesktopLayoutContextOptional } from "./_layout/TraceLayoutDesktop";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { useTraceAnalyticsDimensions } from "../hooks/useTraceAnalyticsDimensions";import { VirtualizedList } from "./_shared/VirtualizedList";import { TraceSearchListItem } from "./TraceSearchListItem";import { Button } from "@/src/components/ui/button";@@ -22,10 +24,18 @@ export function TraceSearchList() {const { searchQuery, setSearchInputValue } = useSearch();const { selectedNodeId, setSelectedNodeId } = 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", {+ source: "search",+ ...analyticsDimensions,+ });+ }setSelectedNodeId(id);layout?.expandDetailPanel();};diff --git a/web/src/components/trace/components/TraceSettingsDropdown.tsx b/web/src/components/trace/components/TraceSettingsDropdown.tsxindex 1204ba3ee8..3ef9d0d112 100644--- a/web/src/components/trace/components/TraceSettingsDropdown.tsx+++ b/web/src/components/trace/components/TraceSettingsDropdown.tsx@@ -30,6 +30,7 @@ import { Switch } from "@/src/components/design-system/Switch/Switch";import { cn } from "@/src/utils/tailwind";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { useViewPreferences } from "../contexts/ViewPreferencesContext";+import { useTraceAnalyticsDimensions } from "../hooks/useTraceAnalyticsDimensions";export interface TraceSettingsDropdownProps {isGraphViewAvailable: boolean;@@ -71,6 +72,7 @@ export function TraceViewOptionsMenuItems({isGraphViewAvailable,}: TraceSettingsDropdownProps) {const capture = usePostHogClientCapture();+ const analyticsDimensions = useTraceAnalyticsDimensions();// Get all preferences directly from contextconst {@@ -108,7 +110,13 @@ export function TraceViewOptionsMenuItems({<Switchsize="sm"checked={showGraph}- onCheckedChange={setShowGraph}+ onCheckedChange={(checked) => {+ capture("trace_detail:graph_view_toggle", {+ show: checked,+ ...analyticsDimensions,+ });+ setShowGraph(checked);+ }}/></div></DropdownMenuItem>@@ -144,6 +152,7 @@ export function TraceViewOptionsMenuItems({onCheckedChange={(checked) => {capture("trace_detail:observation_tree_toggle_scores", {show: checked,+ ...analyticsDimensions,});setShowScores(checked);}}diff --git a/web/src/components/trace/components/TraceTimeline/index.tsx b/web/src/components/trace/components/TraceTimeline/index.tsxindex 251b2d8147..005e6658ae 100644--- a/web/src/components/trace/components/TraceTimeline/index.tsx+++ b/web/src/components/trace/components/TraceTimeline/index.tsx@@ -39,6 +39,8 @@ import {useShowPlayhead,} from "../../contexts/PlayheadContext";import { useHandlePrefetchObservation } from "../../hooks/useHandlePrefetchObservation";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { useTraceAnalyticsDimensions } from "../../hooks/useTraceAnalyticsDimensions";import { flattenTreeWithTimelineMetrics } from "./timeline-flattening";import {calculateStepSize,@@ -237,6 +239,8 @@ export function TraceTimeline() {colorCodeMetrics,} = useViewPreferences();const { handleHover } = useHandlePrefetchObservation();+ const capture = usePostHogClientCapture();+ const analyticsDimensions = useTraceAnalyticsDimensions();// Optional (null in the mobile layout): reopen the detail panel on select.const layout = useDesktopLayoutContextOptional();@@ -501,12 +505,16 @@ export function TraceTimeline() {// TimelineRows.tsx β stable references keep the memo boundary effective).const handleSelectNode = useCallback((nodeId: string) => {+ capture("trace_detail:node_selected", {+ source: "timeline",+ ...analyticsDimensions,+ });setSelectedNodeId(nodeId);// Reopen the detail panel on any select β including re-clicking the// already-selected row, where the URL param wouldn't fire an effect.layout?.expandDetailPanel();},- [setSelectedNodeId, layout],+ [setSelectedNodeId, layout, capture, analyticsDimensions],);const handleHoverNode = useCallback((node: TreeNode) => {diff --git a/web/src/components/trace/components/TraceTree.tsx b/web/src/components/trace/components/TraceTree.tsxindex fabefd0a66..ba42284953 100644--- a/web/src/components/trace/components/TraceTree.tsx+++ b/web/src/components/trace/components/TraceTree.tsx@@ -22,6 +22,8 @@ import { useDesktopLayoutContextOptional } from "./_layout/TraceLayoutDesktop";import { type TreeNode } from "../lib/types";import { cn } from "@/src/utils/tailwind";import type Decimal from "decimal.js";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { useTraceAnalyticsDimensions } from "../hooks/useTraceAnalyticsDimensions";/*** Feature-scoped row container: subscribes to the row's OWN playback-active@@ -89,10 +91,18 @@ export function TraceTree() {const { selectedNodeId, setSelectedNodeId, collapsedNodes, toggleCollapsed } =useSelection();const { handleHover } = useHandlePrefetchObservation();+ const capture = usePostHogClientCapture();+ const analyticsDimensions = useTraceAnalyticsDimensions();// Optional (null on mobile): reopen the detail panel on select, including// re-selecting the already-selected node.const layout = useDesktopLayoutContextOptional();const handleSelectNode = (id: string | null) => {+ if (id) {+ capture("trace_detail:node_selected", {+ source: "tree",+ ...analyticsDimensions,+ });+ }setSelectedNodeId(id);layout?.expandDetailPanel();};diff --git a/web/src/components/trace/components/_layout/TracePanelNavigationButton.tsx b/web/src/components/trace/components/_layout/TracePanelNavigationButton.tsxindex da122ac5bd..dffe6b729f 100644--- a/web/src/components/trace/components/_layout/TracePanelNavigationButton.tsx+++ b/web/src/components/trace/components/_layout/TracePanelNavigationButton.tsx@@ -2,6 +2,7 @@ import { Button } from "@/src/components/ui/button";import { PanelLeftClose, PanelLeftOpen } from "lucide-react";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { useTraceAnalyticsDimensions } from "../../hooks/useTraceAnalyticsDimensions";interface TracePanelNavigationButtonProps {isPanelCollapsed: boolean;@@ -15,6 +16,7 @@ export function TracePanelNavigationButton({shouldPulseToggle = false,}: TracePanelNavigationButtonProps) {const capture = usePostHogClientCapture();+ const analyticsDimensions = useTraceAnalyticsDimensions();return (<div className="relative"><Button@@ -22,6 +24,7 @@ export function TracePanelNavigationButton({onTogglePanel();capture("trace_detail:tree_panel_toggle", {collapsed: !isPanelCollapsed,+ ...analyticsDimensions,});}}variant="ghost"diff --git a/web/src/components/trace/components/_layout/TracePanelNavigationHeader.tsx b/web/src/components/trace/components/_layout/TracePanelNavigationHeader.tsxindex 0b09664042..c962fcccf9 100644--- a/web/src/components/trace/components/_layout/TracePanelNavigationHeader.tsx+++ b/web/src/components/trace/components/_layout/TracePanelNavigationHeader.tsx@@ -47,6 +47,8 @@ import {import { TracePanelNavigationButton } from "./TracePanelNavigationButton";import { PlaybackControls } from "../PlaybackControls";import { useDesktopLayoutContextOptional } from "./TraceLayoutDesktop";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { useTraceAnalyticsDimensions } from "../../hooks/useTraceAnalyticsDimensions";import { toast } from "sonner";import { TRACE_DOWNLOAD_OMIT_LARGE_FIELDS_THRESHOLD } from "@/src/features/traces/shared/traceDownloadConfig";import { useWatchedPromiseCallback } from "@/src/hooks/useWatchedPromiseCallback";@@ -94,6 +96,8 @@ function TracePanelNavigationHeaderExpanded({const { isGraphViewAvailable } = useTraceGraphData();const { isBetaEnabled } = useV4Beta();const [viewMode, setViewMode] = useQueryParam("view", StringParam);+ const capture = usePostHogClientCapture();+ const analyticsDimensions = useTraceAnalyticsDimensions();// When the detail (info) panel is closed, the tree/timeline owns the whole// surface β so the left "collapse panel" toggle would only shrink the one@@ -124,15 +128,26 @@ function TracePanelNavigationHeaderExpanded({const handleToggleTreeNodes = useCallback(() => {if (isEverythingCollapsed) {+ capture("trace_detail:observation_tree_expand", analyticsDimensions);expandAll();} else {+ capture("trace_detail:observation_tree_collapse", analyticsDimensions);const allIds = roots.flatMap((root) => getAllNodeIds(root));collapseAll(allIds);}- }, [isEverythingCollapsed, expandAll, collapseAll, getAllNodeIds, roots]);+ }, [+ isEverythingCollapsed,+ expandAll,+ collapseAll,+ getAllNodeIds,+ roots,+ capture,+ analyticsDimensions,+ ]);const [handleDownload, isDownloading] =useWatchedPromiseCallback(async () => {+ capture("trace_detail:download_button_click", analyticsDimensions);try {if (!isBetaEnabled) {downloadLegacyTraceAsJson({@@ -159,7 +174,7 @@ function TracePanelNavigationHeaderExpanded({: "Failed to download trace JSON",);}- }, [isBetaEnabled, observations, trace]);+ }, [isBetaEnabled, observations, trace, capture, analyticsDimensions]);const isTimelineView = viewMode === "timeline";@@ -282,7 +297,16 @@ function TracePanelNavigationHeaderExpanded({the panel is narrow β see @container/navheader). */}<ViewModeSwitchisTimelineView={isTimelineView}- onSelect={(timeline) => setViewMode(timeline ? "timeline" : null)}+ onSelect={(timeline) => {+ // Clicking the already-active segment is a no-op β don't count it.+ if (timeline !== isTimelineView) {+ capture("trace_detail:view_mode_switch", {+ viewMode: timeline ? "timeline" : "tree",+ ...analyticsDimensions,+ });+ }+ setViewMode(timeline ? "timeline" : null);+ }}/>{/* When the detail panel is closed it shows its own collapsed railwith a "Show detail panel" button on the right edge (DetailPanel indiff --git a/web/src/components/trace/contexts/ViewPreferencesContext.tsx b/web/src/components/trace/contexts/ViewPreferencesContext.tsxindex 70548e5446..11abe1917a 100644--- a/web/src/components/trace/contexts/ViewPreferencesContext.tsx+++ b/web/src/components/trace/contexts/ViewPreferencesContext.tsx@@ -28,6 +28,9 @@ export type LogViewTreeStyle = "flat" | "indented";/** JSON view preference (formatted/pretty vs raw JSON vs advanced JSON beta) */export type JsonViewPreference = "pretty" | "json" | "json-beta";+/** Context in which trace is rendered - affects feature availability */+export type TraceRenderContext = "fullscreen" | "peek" | "annotation";+interface ViewPreferencesContextValue {showDuration: boolean;setShowDuration: (value: boolean) => void;@@ -46,6 +49,8 @@ interface ViewPreferencesContextValue {setGraphViewMode: (value: GraphViewMode) => void;minObservationLevel: ObservationLevelType;setMinObservationLevel: (value: ObservationLevelType) => void;+ /** Context in which trace is rendered (also an analytics dimension) */+ traceContext: TraceRenderContext;/** Whether trace is rendered in peek mode (e.g., table peek views) */isPeekMode: boolean;/** Whether trace is rendered in annotation mode (annotation queue processing) */@@ -80,7 +85,7 @@ export function useViewPreferences(): ViewPreferencesContextValue {interface ViewPreferencesProviderProps {children: ReactNode;/** Context in which trace is rendered - affects feature availability */- traceContext?: "fullscreen" | "peek" | "annotation";+ traceContext?: TraceRenderContext;}export function ViewPreferencesProvider({@@ -153,6 +158,7 @@ export function ViewPreferencesProvider({setGraphViewMode,minObservationLevel,setMinObservationLevel,+ traceContext,isPeekMode,isAnnotationMode,logViewMode,@@ -181,6 +187,7 @@ export function ViewPreferencesProvider({setGraphViewMode,minObservationLevel,setMinObservationLevel,+ traceContext,isPeekMode,isAnnotationMode,logViewMode,diff --git a/web/src/components/trace/hooks/useTraceAnalyticsDimensions.ts b/web/src/components/trace/hooks/useTraceAnalyticsDimensions.tsnew file mode 100644index 0000000000..6e3a5aa2ec--- /dev/null+++ b/web/src/components/trace/hooks/useTraceAnalyticsDimensions.ts@@ -0,0 +1,24 @@+import { useMemo } from "react";+import { useViewPreferences } from "@/src/components/trace/contexts/ViewPreferencesContext";+import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";++/**+ * Shared segmentation dimensions for every `trace_detail:*` analytics event:+ * - `isV4` β whether the trace view runs on the v4 (events/fast-mode) data+ * path at the moment of the action; the headline v3-vs-v4 slice.+ * - `traceContext` β where the trace view is rendered+ * (`fullscreen` | `peek` | `annotation`).+ *+ * Spread the result into every capture within the trace view so the+ * dimensions can never silently go missing on a new event. Must be used+ * within a ViewPreferencesProvider (i.e. inside <Trace/>).+ */+export function useTraceAnalyticsDimensions() {+ const { traceContext } = useViewPreferences();+ const { isBetaEnabled } = useV4Beta();++ return useMemo(+ () => ({ traceContext, isV4: isBetaEnabled }),+ [traceContext, isBetaEnabled],+ );+}diff --git a/web/src/features/datasets/components/DatasetAggregateTableCell.tsx b/web/src/features/datasets/components/DatasetAggregateTableCell.tsxindex d2cfd6cb6a..2c03881a9c 100644--- a/web/src/features/datasets/components/DatasetAggregateTableCell.tsx+++ b/web/src/features/datasets/components/DatasetAggregateTableCell.tsx@@ -23,6 +23,8 @@ import { type BaselineDiff } from "@/src/features/datasets/lib/calculateBaselineimport { DiffLabel } from "@/src/features/datasets/components/DiffLabel";import { useResourceMetricsDiff } from "@/src/features/datasets/hooks/useResourceMetricsDiff";import { NotFoundCard } from "@/src/features/datasets/components/NotFoundCard";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";const DatasetAggregateCellContent = ({projectId,@@ -40,6 +42,8 @@ const DatasetAggregateCellContent = ({baselineRunValue?: EnrichedDatasetRunItem;}) => {const router = useRouter();+ const capture = usePostHogClientCapture();+ const { isBetaEnabled: isV4 } = useV4Beta();const silentHttpCodes = [404];const { selectedFields } = useDatasetCompareFields();const { activeCell, setActiveCell } = useActiveCell();@@ -101,6 +105,18 @@ const DatasetAggregateCellContent = ({// Note that we implement custom handling for opening peek view from cellconst handleOpenPeek = () => {+ // Mirrors usePeekNavigation's peek:opened (this open bypasses the hook);+ // re-clicking the already-peeked cell is a no-op and emits nothing.+ if (+ router.query.peek !== value.trace.id ||+ router.query.observation !== value.observation?.id+ ) {+ capture("peek:opened", {+ routePattern: router.pathname,+ wasOpen: router.query.peek !== undefined,+ isV4,+ });+ }const newQuery: Record<string, string | string[] | undefined> = {...router.query,peek: value.trace.id,diff --git a/web/src/features/navigate-detail-pages/DetailPageNav.tsx b/web/src/features/navigate-detail-pages/DetailPageNav.tsxindex 9c024bd6a5..7817ccabbe 100644--- a/web/src/features/navigate-detail-pages/DetailPageNav.tsx+++ b/web/src/features/navigate-detail-pages/DetailPageNav.tsx@@ -11,6 +11,7 @@ import {useDetailPageLists,} from "@/src/features/navigate-detail-pages/context";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";import { cn } from "@/src/utils/tailwind";import { ArrowDown, ArrowUp } from "lucide-react";import { useRouter } from "next/router";@@ -43,6 +44,7 @@ export const DetailPageNav = (props: {);const capture = usePostHogClientCapture();+ const { isBetaEnabled: isV4 } = useV4Beta();const router = useRouter();const currentIndex = entries.findIndex((entry) => entry.id === currentId);const previousPageEntry =@@ -51,7 +53,22 @@ export const DetailPageNav = (props: {currentIndex < entries.length - 1 ? entries[currentIndex + 1] : undefined;const navigateToEntry = useCallback(- (entry: ListEntry) => {+ (+ entry: ListEntry,+ direction: "previous" | "next",+ method: "button" | "keyboard",+ ) => {+ // Single seam for both triggers so K/J navigation counts too (it+ // used to be button-only). `listKey` is a static list identifier and+ // `isPeek` distinguishes peek-header nav from full detail pages.+ capture("navigate_detail_pages:button_click_prev_or_next", {+ direction,+ method,+ listKey,+ isPeek: router.query.peek !== undefined,+ isV4,+ });+if (onNavigate) {onNavigate(entry);return;@@ -64,7 +81,7 @@ export const DetailPageNav = (props: {}),);},- [onNavigate, path, router],+ [onNavigate, path, router, capture, listKey, isV4],);const pulseShortcut = useCallback(@@ -109,10 +126,10 @@ export const DetailPageNav = (props: {if (event.key === "k" && previousPageEntry) {pulseShortcut("previous");- navigateToEntry(previousPageEntry);+ navigateToEntry(previousPageEntry, "previous", "keyboard");} else if (event.key === "j" && nextPageEntry) {pulseShortcut("next");- navigateToEntry(nextPageEntry);+ navigateToEntry(nextPageEntry, "next", "keyboard");}};window.addEventListener("keydown", handleKeyDown);@@ -138,8 +155,7 @@ export const DetailPageNav = (props: {disabled={!previousPageEntry}onClick={() => {if (previousPageEntry) {- capture("navigate_detail_pages:button_click_prev_or_next");- navigateToEntry(previousPageEntry);+ navigateToEntry(previousPageEntry, "previous", "button");}}}>@@ -163,8 +179,7 @@ export const DetailPageNav = (props: {disabled={!nextPageEntry}onClick={() => {if (nextPageEntry) {- capture("navigate_detail_pages:button_click_prev_or_next");- navigateToEntry(nextPageEntry);+ navigateToEntry(nextPageEntry, "next", "button");}}}>diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.tsindex b8c6163eee..9336a6e9b0 100644--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts@@ -1,5 +1,6 @@import { type CaptureResult, type CaptureOptions } from "posthog-js";import { usePostHog } from "posthog-js/react";+import { useCallback } from "react";export const V4_BETA_ENABLED_POSTHOG_PROPERTY = "v4BetaEnabled";@@ -34,7 +35,17 @@ export const events = {"download_button_click","view_mode_switch","tree_panel_toggle",+ "graph_view_toggle",+ // Aggregated vs expanded graph build mode (LFE-10676).+ "graph_mode_switch",+ // Fired from the tree, timeline, graph, and search-result click handlers;+ // `source` says which surface drove the navigation.+ "node_selected",],+ // The shared table peek panel (opened via the `peek` URL param). Props carry+ // `routePattern` (the Next.js route pattern, never a concrete URL) so opens+ // can be sliced by surface without leaking ids.+ peek: ["opened", "closed", "expand_toggle", "resized", "open_in_new_tab"],generations: ["export"],saved_views: ["create",@@ -274,14 +285,16 @@ type EventName = {export const usePostHogClientCapture = () => {const posthog = usePostHog();- // wrapped posthog.capture function that only allows events that are in the allowlist- function capture(- eventName: EventName,- properties?: Record<string, any> | null,- options?: CaptureOptions,- ): CaptureResult | void {- return posthog.capture(eventName, properties, options);- }-- return capture;+ // wrapped posthog.capture function that only allows events that are in the+ // allowlist; stable identity so it is safe in useCallback/useMemo deps+ return useCallback(+ function capture(+ eventName: EventName,+ properties?: Record<string, any> | null,+ options?: CaptureOptions,+ ): CaptureResult | void {+ return posthog.capture(eventName, properties, options);+ },+ [posthog],+ );};diff --git a/web/src/features/trace-graph-view/components/TraceGraphView.tsx b/web/src/features/trace-graph-view/components/TraceGraphView.tsxindex c646300d2d..beb9433e90 100644--- a/web/src/features/trace-graph-view/components/TraceGraphView.tsx+++ b/web/src/features/trace-graph-view/components/TraceGraphView.tsx@@ -35,6 +35,12 @@ type TraceGraphViewProps = {viewMode?: GraphViewMode;/** When provided, the mode switch is rendered over the canvas. */onViewModeChange?: (mode: GraphViewMode) => void;+ /**+ * Called when an in-canvas node click selects an observation (including+ * cycling a repeated node) β the host's analytics seam. Not called for+ * system start/end nodes or background deselects.+ */+ onObservationSelect?: () => void;};export const TraceGraphView: React.FC<TraceGraphViewProps> = ({@@ -42,6 +48,7 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({activeObservationIds,viewMode = "aggregated",onViewModeChange,+ onObservationSelect,}) => {const [selectedNodeName, setSelectedNodeName] = useState<string | null>(null);const [currentObservationId, setCurrentObservationId] = useQueryParam(@@ -291,6 +298,7 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({}));clickWroteObservationIdRef.current = observations[targetIndex];setCurrentObservationId(observations[targetIndex]);+ onObservationSelect?.();} else {clickWroteObservationIdRef.current = null;setCurrentObservationId(null);@@ -307,6 +315,7 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({currentObservationIndices,previousSelectedNode,setCurrentObservationId,+ onObservationSelect,],);