🪢 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
refactor(trace2): improve maintainability and error handling in LogView (#10846)
Michael Fröhlich97f78871e457
diff --git a/web/src/components/trace2/api/usePrefetchObservation.ts b/web/src/components/trace2/api/usePrefetchObservation.tsindex e0ec8924e1..c8c8cf34af 100644--- a/web/src/components/trace2/api/usePrefetchObservation.ts+++ b/web/src/components/trace2/api/usePrefetchObservation.ts@@ -4,17 +4,31 @@ export type UsePrefetchObservationParams = {projectId: string;};+/**+ * Hook to prefetch observation data on hover.+ * Matches the old trace component's prefetch behavior with 5-minute staleTime.+ */export function usePrefetchObservation({projectId,}: UsePrefetchObservationParams) {const utils = api.useUtils();- const prefetch = (observationId: string, traceId: string) => {- void utils.observations.byId.prefetch({- observationId,- traceId,- projectId,- });+ const prefetch = (+ observationId: string,+ traceId: string,+ startTime?: Date,+ ) => {+ void utils.observations.byId.prefetch(+ {+ observationId,+ traceId,+ projectId,+ startTime,+ },+ {+ staleTime: 5 * 60 * 1000, // 5 minutes - matches old trace behavior+ },+ );};return { prefetch };diff --git a/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx b/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsxindex 2f287cbec1..87d94bec6f 100644--- a/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx+++ b/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx@@ -32,7 +32,6 @@ import {TabsBarTrigger,} from "@/src/components/ui/tabs-bar";import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";-import useLocalStorage from "@/src/components/useLocalStorage";import { useMemo, useState } from "react";import {LatencyBadge,@@ -51,6 +50,7 @@ import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";import { api } from "@/src/utils/api";import { useJsonExpansion } from "@/src/components/trace2/contexts/JsonExpansionContext";import { useMedia } from "@/src/components/trace2/api/useMedia";+import { useSelection } from "@/src/components/trace2/contexts/SelectionContext";// Header action componentsimport { CopyIdsPopover } from "@/src/components/trace2/components/_shared/CopyIdsPopover";@@ -72,13 +72,27 @@ export function ObservationDetailView({projectId,traceId,}: ObservationDetailViewProps) {- const [selectedTab, setSelectedTab] = useState<"preview" | "scores">(- "preview",- );- const [currentView, setCurrentView] = useLocalStorage<"pretty" | "json">(- "jsonViewPreference",- "pretty",- );+ // Tab and view state from URL (via SelectionContext)+ // For observations, "log" tab doesn't apply - map to "preview"+ const {+ selectedTab: globalSelectedTab,+ setSelectedTab: setGlobalSelectedTab,+ viewPref,+ setViewPref,+ } = useSelection();++ // Map global tab to observation-specific tabs (preview, scores)+ // "log" tab doesn't exist for observations, so fall back to "preview"+ const selectedTab =+ globalSelectedTab === "scores" ? "scores" : ("preview" as const);++ const setSelectedTab = (tab: "preview" | "scores") => {+ setGlobalSelectedTab(tab);+ };++ // Map viewPref to currentView format expected by child components+ const currentView = viewPref === "json" ? "json" : "pretty";+const [isPrettyViewAvailable, setIsPrettyViewAvailable] = useState(true);// Get comments, scores, and expansion state from contexts@@ -131,7 +145,7 @@ export function ObservationDetailView({return (<div className="flex h-full flex-col overflow-hidden">{/* Header section */}- <div className="flex-shrink-0 space-y-2 border-b p-4 @container">+ <div className="flex-shrink-0 space-y-2 border-b p-4">{/* Title row with actions */}<div className="grid w-full grid-cols-1 items-start gap-2 @2xl:grid-cols-[auto,auto] @2xl:justify-between"><div className="flex w-full flex-row items-start gap-1">@@ -264,7 +278,7 @@ export function ObservationDetailView({className="ml-auto mr-1 h-fit px-2 py-0.5"value={currentView}onValueChange={(value) => {- setCurrentView(value as "pretty" | "json");+ setViewPref(value === "json" ? "json" : "formatted");}}><TabsList className="h-fit py-0.5">@@ -284,7 +298,7 @@ export function ObservationDetailView({value="preview"className="mt-0 flex max-h-full min-h-0 w-full flex-1">- <div className="flex w-full flex-col gap-2 overflow-y-auto p-4">+ <div className="flex w-full flex-col gap-2 overflow-y-auto"><IOPreviewkey={observation.id}observationName={observation.name ?? undefined}diff --git a/web/src/components/trace2/components/ObservationDetailView/ObservationMetadataBadgeModel.tsx b/web/src/components/trace2/components/ObservationDetailView/ObservationMetadataBadgeModel.tsxindex 7019d59f95..ee8f6ea588 100644--- a/web/src/components/trace2/components/ObservationDetailView/ObservationMetadataBadgeModel.tsx+++ b/web/src/components/trace2/components/ObservationDetailView/ObservationMetadataBadgeModel.tsx@@ -37,7 +37,7 @@ export function ModelBadge({);}- // Unlinked model - show create form drawer+ // Unlinked model - show create form dialogreturn (<UpsertModelFormDialogaction="create"diff --git a/web/src/components/trace2/components/SpanContent.tsx b/web/src/components/trace2/components/SpanContent.tsxindex 263c04f62b..ac9b2e0f42 100644--- a/web/src/components/trace2/components/SpanContent.tsx+++ b/web/src/components/trace2/components/SpanContent.tsx@@ -35,6 +35,7 @@ interface SpanContentProps {parentTotalDuration?: number;commentCount?: number;onSelect?: () => void;+ onHover?: () => void;className?: string;}@@ -44,6 +45,7 @@ export function SpanContent({parentTotalDuration,commentCount,onSelect,+ onHover,className,}: SpanContentProps) {const { scores } = useTraceData();@@ -89,6 +91,7 @@ export function SpanContent({e.stopPropagation();onSelect?.();}}+ onMouseEnter={onHover}title={node.name}className={cn("peer relative flex min-w-0 flex-1 items-start rounded-md py-0.5 pl-1 pr-2 text-left",diff --git a/web/src/components/trace2/components/TraceDetailView/TraceDetailView.tsx b/web/src/components/trace2/components/TraceDetailView/TraceDetailView.tsxindex 9528dc315b..aced50acd4 100644--- a/web/src/components/trace2/components/TraceDetailView/TraceDetailView.tsx+++ b/web/src/components/trace2/components/TraceDetailView/TraceDetailView.tsx@@ -12,14 +12,18 @@ import {TabsBarTrigger,} from "@/src/components/ui/tabs-bar";import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";-import useLocalStorage from "@/src/components/useLocalStorage";-import { useEffect, useMemo, useState } from "react";+import { useMemo, useState } from "react";import {Tooltip,TooltipContent,TooltipProvider,TooltipTrigger,} from "@/src/components/ui/tooltip";+import {+ HoverCard,+ HoverCardContent,+ HoverCardTrigger,+} from "@/src/components/ui/hover-card";// Preview tab componentsimport { IOPreview } from "@/src/components/trace2/components/IOPreview/IOPreview";@@ -31,16 +35,12 @@ import { useMedia } from "@/src/components/trace2/api/useMedia";// Contexts and hooksimport { useTraceData } from "@/src/components/trace2/contexts/TraceDataContext";import { useViewPreferences } from "@/src/components/trace2/contexts/ViewPreferencesContext";+import { useSelection } from "@/src/components/trace2/contexts/SelectionContext";import { useIsAuthenticatedAndProjectMember } from "@/src/features/auth/hooks";-import {- useLogViewConfirmation,- LOG_VIEW_DISABLED_THRESHOLD,-} from "@/src/components/trace2/components/TraceLogView/useLogViewConfirmation";-// Extracted componentsimport { TraceDetailViewHeader } from "./TraceDetailViewHeader";-import { TraceLogViewConfirmationDialog } from "../TraceLogView/TraceLogViewConfirmationDialog";import { TraceLogView } from "../TraceLogView/TraceLogView";+import { TRACE_VIEW_CONFIG } from "@/src/components/trace2/config/trace-view-config";import ScoresTable from "@/src/components/table/use-cases/scores";export interface TraceDetailViewProps {@@ -60,16 +60,13 @@ export function TraceDetailView({scores,projectId,}: TraceDetailViewProps) {- // Tab and view state- const [selectedTab, setSelectedTab] = useState<"preview" | "log" | "scores">(- "preview",- );- const [currentView, setCurrentView] = useLocalStorage<"pretty" | "json">(- "jsonViewPreference",- "pretty",- );+ // Tab and view state from URL (via SelectionContext)+ const { selectedTab, setSelectedTab, viewPref, setViewPref } = useSelection();const [isPrettyViewAvailable, setIsPrettyViewAvailable] = useState(true);+ // Map viewPref to currentView format expected by child components+ const currentView = viewPref === "json" ? "json" : "pretty";+// Context hooksconst { comments } = useTraceData();const { expansionState, setFieldExpansion } = useJsonExpansion();@@ -83,23 +80,11 @@ export function TraceDetailView({[scores],);- // Log view confirmation logic- const logViewConfirmation = useLogViewConfirmation({- observationCount: observations.length,- traceId: trace.id,- });-const showLogViewTab = observations.length > 0;- // Auto-redirect from invalid tab state- useEffect(() => {- if (- (logViewConfirmation.isDisabled || !showLogViewTab) &&- selectedTab === "log"- ) {- setSelectedTab("preview");- }- }, [logViewConfirmation.isDisabled, showLogViewTab, selectedTab]);+ // Check if log view will be virtualized (affects JSON tab availability)+ const isLogViewVirtualized =+ observations.length >= TRACE_VIEW_CONFIG.logView.virtualizationThreshold;// Scores tab visibility: hide for public trace viewers and in peek mode (annotation queues)const { isPeekMode } = useViewPreferences();@@ -107,21 +92,11 @@ export function TraceDetailView({useIsAuthenticatedAndProjectMember(projectId);const showScoresTab = isAuthenticatedAndProjectMember && !isPeekMode;- // Handle tab change with log view confirmation+ // Handle tab changeconst handleTabChange = (value: string) => {- if (value === "log") {- const canProceed = logViewConfirmation.attemptLogView();- if (!canProceed) return;- }setSelectedTab(value as "preview" | "log" | "scores");};- // Handle log view confirmation- const handleLogViewConfirm = () => {- logViewConfirmation.confirmLogView();- setSelectedTab("log");- };-return (<div className="flex h-full flex-col overflow-hidden">{/* Header section (extracted component) */}@@ -142,20 +117,15 @@ export function TraceDetailView({<TabsBarList><TabsBarTrigger value="preview">Preview</TabsBarTrigger>{showLogViewTab && (- <TabsBarTrigger- value="log"- disabled={logViewConfirmation.isDisabled}- >+ <TabsBarTrigger value="log"><Tooltip><TooltipTrigger asChild><span>Log View</span></TooltipTrigger><TooltipContent className="text-xs">- {logViewConfirmation.isDisabled- ? `Log View is disabled for traces with more than ${LOG_VIEW_DISABLED_THRESHOLD} observations (this trace has ${observations.length})`- : logViewConfirmation.requiresConfirmation- ? `Log View may be slow with ${observations.length} observations. Click to confirm.`- : "Shows all observations concatenated. Great for quickly scanning through them. Nullish values are omitted."}+ {isLogViewVirtualized+ ? `Shows all ${observations.length} observations with virtualization enabled.`+ : "Shows all observations concatenated. Great for quickly scanning through them."}</TooltipContent></Tooltip></TabsBarTrigger>@@ -165,22 +135,61 @@ export function TraceDetailView({)}{/* View toggle (Formatted/JSON) - show for preview and log tabs when pretty view available */}+ {/* JSON is disabled for virtualized log view (large traces) */}{(selectedTab === "log" ||(selectedTab === "preview" && isPrettyViewAvailable)) && (<TabsclassName="ml-auto mr-1 h-fit px-2 py-0.5"- value={currentView}+ value={+ selectedTab === "log" && isLogViewVirtualized+ ? "pretty"+ : currentView+ }onValueChange={(value) => {- setCurrentView(value as "pretty" | "json");+ // Don't allow JSON for virtualized log view+ if (+ selectedTab === "log" &&+ isLogViewVirtualized &&+ value === "json"+ ) {+ return;+ }+ setViewPref(value === "json" ? "json" : "formatted");}}><TabsList className="h-fit py-0.5"><TabsTrigger value="pretty" className="h-fit px-1 text-xs">Formatted</TabsTrigger>- <TabsTrigger value="json" className="h-fit px-1 text-xs">- JSON- </TabsTrigger>+ {selectedTab === "log" && isLogViewVirtualized ? (+ <HoverCard openDelay={200}>+ <HoverCardTrigger asChild>+ <TabsTrigger+ value="json"+ className="h-fit px-1 text-xs"+ disabled+ >+ JSON+ </TabsTrigger>+ </HoverCardTrigger>+ <HoverCardContent+ align="end"+ className="w-64 text-sm"+ sideOffset={8}+ >+ <p className="font-medium">JSON view unavailable</p>+ <p className="mt-1 text-muted-foreground">+ Disabled for traces with{" "}+ {TRACE_VIEW_CONFIG.logView.virtualizationThreshold}++ observations to maintain performance.+ </p>+ </HoverCardContent>+ </HoverCard>+ ) : (+ <TabsTrigger value="json" className="h-fit px-1 text-xs">+ JSON+ </TabsTrigger>+ )}</TabsList></Tabs>)}@@ -192,7 +201,7 @@ export function TraceDetailView({value="preview"className="mt-0 flex max-h-full min-h-0 w-full flex-1">- <div className="flex w-full flex-col gap-2 overflow-y-auto p-4">+ <div className="flex w-full flex-col gap-2 overflow-y-auto">{/* I/O Preview */}<IOPreviewkey={trace.id + "-io"}@@ -240,11 +249,9 @@ export function TraceDetailView({className="mt-0 flex max-h-full min-h-0 w-full flex-1"><TraceLogView- observations={observations}traceId={trace.id}projectId={projectId}- currentView={currentView}- trace={trace}+ currentView={isLogViewVirtualized ? "pretty" : currentView}/></TabsBarContent>@@ -266,14 +273,6 @@ export function TraceDetailView({</TabsBarContent>)}</TabsBar>-- {/* Confirmation dialog for log view with many observations (extracted component) */}- <TraceLogViewConfirmationDialog- open={logViewConfirmation.showDialog}- onOpenChange={logViewConfirmation.setShowDialog}- observationCount={observations.length}- onConfirm={handleLogViewConfirm}- /></div>);}diff --git a/web/src/components/trace2/components/TraceLogView/LogViewExpandedContent.tsx b/web/src/components/trace2/components/TraceLogView/LogViewExpandedContent.tsxnew file mode 100644index 0000000000..43380186b6--- /dev/null+++ b/web/src/components/trace2/components/TraceLogView/LogViewExpandedContent.tsx@@ -0,0 +1,105 @@+/**+ * LogViewExpandedContent - Content shown when a log view row is expanded.+ *+ * Only renders the I/O data (PrettyJsonView), not the header row.+ * The header row is handled by JSONTableView.+ */++import { memo, useMemo } from "react";+import { Loader2 } from "lucide-react";+import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";+import { type TreeNode } from "@/src/components/trace2/lib/types";+import { useLogViewObservationIO } from "./useLogViewObservationIO";++export interface LogViewExpandedContentProps {+ node: TreeNode;+ traceId: string;+ projectId: string;+ currentView?: "pretty" | "json";+ /** Optional external expansion state for JSON tree (non-virtualized mode) */+ externalExpansionState?: Record<string, boolean> | boolean;+ /** Callback when expansion state changes (non-virtualized mode) */+ onExternalExpansionChange?: (+ expansion: Record<string, boolean> | boolean,+ ) => void;+}++/**+ * Expanded content with full observation data as JSON.+ * Fetches observation data lazily when mounted.+ */+export const LogViewExpandedContent = memo(function LogViewExpandedContent({+ node,+ traceId,+ projectId,+ currentView = "pretty",+ externalExpansionState,+ onExternalExpansionChange,+}: LogViewExpandedContentProps) {+ // Fetch I/O data lazily+ const { data, isLoading, isError } = useLogViewObservationIO({+ observationId: node.id,+ traceId,+ projectId,+ startTime: node.startTime,+ enabled: true, // Always enabled when mounted (row is expanded)+ });++ // Build JSON object with all observation properties+ const jsonData = useMemo(() => {+ if (!data) return null;++ // Filter out null/undefined values for cleaner display+ const result: Record<string, unknown> = {};++ if (data.input !== null && data.input !== undefined) {+ result.input = data.input;+ }+ if (data.output !== null && data.output !== undefined) {+ result.output = data.output;+ }+ if (data.metadata !== null && data.metadata !== undefined) {+ result.metadata = data.metadata;+ }++ return Object.keys(result).length > 0 ? result : null;+ }, [data]);++ return (+ <div className="w-full">+ {isLoading && (+ <div className="flex items-center justify-center py-4">+ <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />+ <span className="ml-2 text-xs text-muted-foreground">Loading...</span>+ </div>+ )}++ {isError && (+ <div className="flex h-full w-full items-center bg-destructive/10 px-6 py-2 text-xs text-destructive">+ Failed to load data+ </div>+ )}++ {jsonData && !isLoading && (+ <PrettyJsonView+ json={jsonData}+ currentView={currentView}+ isLoading={false}+ showNullValues={false}+ stickyTopLevelKey={false}+ showObservationTypeBadge={true}+ scrollable={true}+ externalExpansionState={externalExpansionState}+ onExternalExpansionChange={onExternalExpansionChange}+ className="w-full [&_.border]:border-0 [&_.io-message-content]:p-0 [&_.rounded-sm]:rounded-none [&_td:first-child]:pl-6 [&_th:first-child]:pl-6 [&_th]:h-6 [&_th]:text-xs"+ />+ )}++ {!jsonData && !isLoading && !isError && (+ <div className="py-2 pl-6 text-xs text-muted-foreground">+ No input/output/metadata+ </div>+ )}+ </div>+ );+});diff --git a/web/src/components/trace2/components/TraceLogView/LogViewJsonMode.tsx b/web/src/components/trace2/components/TraceLogView/LogViewJsonMode.tsxnew file mode 100644index 0000000000..2b0bc34a20--- /dev/null+++ b/web/src/components/trace2/components/TraceLogView/LogViewJsonMode.tsx@@ -0,0 +1,96 @@+/**+ * LogViewJsonMode - Renders all observations as a single JSON view.+ *+ * Used when currentView="json" to display all observation data+ * as one concatenated JSON object instead of the table view.+ *+ * Reuses the existing JSONView component from CodeJsonViewer.tsx.+ */++import { memo, useEffect } from "react";+import { Loader2 } from "lucide-react";+import { JSONView } from "@/src/components/ui/CodeJsonViewer";+import { type FlatLogItem } from "./log-view-types";+import { useLogViewAllObservationsIO } from "./useLogViewAllObservationsIO";++export interface LogViewJsonModeProps {+ items: FlatLogItem[];+ traceId: string;+ projectId: string;+ /** Whether JSON view is collapsed */+ isCollapsed: boolean;+ /** Callback to toggle collapse state */+ onToggleCollapse: () => void;+}++/**+ * Renders all observations as a single JSON object.+ * Fetches all observation I/O data and combines into one view.+ */+export const LogViewJsonMode = memo(function LogViewJsonMode({+ items,+ traceId,+ projectId,+ isCollapsed,+ onToggleCollapse,+}: LogViewJsonModeProps) {+ const { data, isLoading, isError, loadAllData, totalCount } =+ useLogViewAllObservationsIO({+ items,+ traceId,+ projectId,+ });++ // Auto-load data when JSON mode is rendered+ useEffect(() => {+ if (!data && !isLoading && !isError) {+ void loadAllData();+ }+ }, [data, isLoading, isError, loadAllData]);++ return (+ <div className="flex h-full w-full flex-col overflow-hidden">+ {/* Loading state */}+ {isLoading && (+ <div className="flex flex-1 items-center justify-center">+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />+ <span className="ml-2 text-sm text-muted-foreground">+ Loading observations (0/{totalCount})...+ </span>+ </div>+ )}++ {/* Error state */}+ {isError && !isLoading && (+ <div className="flex flex-1 items-center justify-center">+ <div className="rounded border border-destructive/50 bg-destructive/10 p-4 text-sm text-destructive">+ Failed to load observation data+ </div>+ </div>+ )}++ {/* JSON view */}+ {data && !isLoading && (+ <div className="flex-1 overflow-y-auto">+ <JSONView+ json={data}+ scrollable={false}+ externalJsonCollapsed={isCollapsed}+ onToggleCollapse={onToggleCollapse}+ className="h-full [&_.io-message-content]:border-none"+ codeClassName="min-h-full"+ />+ </div>+ )}++ {/* Empty state */}+ {!data && !isLoading && !isError && (+ <div className="flex flex-1 items-center justify-center">+ <div className="text-sm text-muted-foreground">+ No observation data available+ </div>+ </div>+ )}+ </div>+ );+});diff --git a/web/src/components/trace2/components/TraceLogView/LogViewObservationCell.tsx b/web/src/components/trace2/components/TraceLogView/LogViewObservationCell.tsxnew file mode 100644index 0000000000..820e3eed89--- /dev/null+++ b/web/src/components/trace2/components/TraceLogView/LogViewObservationCell.tsx@@ -0,0 +1,99 @@+/**+ * LogViewObservationCell - Cell component for the observation column.+ *+ * Handles viewport-based prefetching with debounce to load observation+ * data before user expands the row.+ */++import { memo, useRef, useEffect } from "react";+import { ItemBadge } from "@/src/components/ItemBadge";+import { usePrefetchObservation } from "@/src/components/trace2/api/usePrefetchObservation";+import { TRACE_VIEW_CONFIG } from "@/src/components/trace2/config/trace-view-config";+import { type FlatLogItem } from "./log-view-types";+import { formatDisplayName } from "./log-view-formatters";++// Constants for prefetching behavior+const {+ prefetch: {+ rootMargin: PREFETCH_ROOT_MARGIN,+ debounceMs: PREFETCH_DEBOUNCE_MS,+ },+ indentPx: INDENT_PX,+} = TRACE_VIEW_CONFIG.logView;++export interface LogViewObservationCellProps {+ item: FlatLogItem;+ indentEnabled: boolean;+ projectId: string;+ traceId: string;+}++/**+ * Cell component that prefetches observation data when entering viewport.+ */+export const LogViewObservationCell = memo(function LogViewObservationCell({+ item,+ indentEnabled,+ projectId,+ traceId,+}: LogViewObservationCellProps) {+ const ref = useRef<HTMLDivElement>(null);+ const { prefetch } = usePrefetchObservation({ projectId });+ const hasPrefetched = useRef(false);+ const timeoutRef = useRef<NodeJS.Timeout | null>(null);++ useEffect(() => {+ const element = ref.current;+ if (!element || item.node.type === "TRACE") return;++ // Reset prefetch flag when item changes to ensure we prefetch new data+ hasPrefetched.current = false;++ const observer = new IntersectionObserver(+ (entries) => {+ const entry = entries[0];+ if (entry?.isIntersecting && !hasPrefetched.current) {+ // Debounce: wait before prefetching to avoid firing+ // many requests during fast scrolling+ timeoutRef.current = setTimeout(() => {+ hasPrefetched.current = true;+ prefetch(item.node.id, traceId, item.node.startTime);+ }, PREFETCH_DEBOUNCE_MS);+ } else if (!entry?.isIntersecting && timeoutRef.current) {+ // Cancel pending prefetch if element leaves viewport+ clearTimeout(timeoutRef.current);+ timeoutRef.current = null;+ }+ },+ { rootMargin: PREFETCH_ROOT_MARGIN },+ );++ observer.observe(element);+ return () => {+ observer.disconnect();+ if (timeoutRef.current) {+ clearTimeout(timeoutRef.current);+ }+ };+ }, [item.node.id, item.node.type, item.node.startTime, traceId, prefetch]);++ const displayName = formatDisplayName(item.node);+ const childrenCount = item.node.children?.length ?? 0;+ const indent = indentEnabled ? item.node.depth * INDENT_PX : 0;++ return (+ <div+ ref={ref}+ className="flex h-5 min-w-0 items-center gap-2"+ style={{ paddingLeft: indent }}+ >+ <ItemBadge type={item.node.type} isSmall />+ <span className="truncate">{displayName}</span>+ {childrenCount > 0 && (+ <span className="flex-shrink-0 text-xs text-muted-foreground">+ {childrenCount} {childrenCount === 1 ? "item" : "items"}+ </span>+ )}+ </div>+ );+});diff --git a/web/src/components/trace2/components/TraceLogView/LogViewToolbar.tsx b/web/src/components/trace2/components/TraceLogView/LogViewToolbar.tsxnew file mode 100644index 0000000000..48df697f73--- /dev/null+++ b/web/src/components/trace2/components/TraceLogView/LogViewToolbar.tsx@@ -0,0 +1,337 @@+/**+ * LogViewToolbar - Controls for log view search and actions.+ *+ * Provides:+ * - Search input for filtering observations (hidden in JSON view)+ * - Action buttons: expand/collapse all, copy JSON, download JSON+ * - Large Trace indicator for virtualized mode+ */++import { memo, useState } from "react";+import {+ FoldVertical,+ UnfoldVertical,+ Copy,+ Download,+ Check,+ IndentIncrease,+ Timer,+ Loader2,+} from "lucide-react";+import { Button } from "@/src/components/ui/button";+import { Command, CommandInput } from "@/src/components/ui/command";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/src/components/ui/tooltip";+import {+ HoverCard,+ HoverCardContent,+ HoverCardTrigger,+} from "@/src/components/ui/hover-card";+import { cn } from "@/src/utils/tailwind";++export interface LogViewToolbarProps {+ /** Current search query */+ searchQuery: string;+ /** Callback when search query changes */+ onSearchChange: (query: string) => void;+ /** Whether virtualization is active (for large traces) */+ isVirtualized?: boolean;+ /** Total number of observations (shown in Large Trace indicator) */+ observationCount?: number;+ /** Number of observations with loaded I/O data (for cache-only mode) */+ loadedObservationCount?: number;+ /** Callback to toggle expand/collapse all (non-virtualized only) */+ onToggleExpandAll?: () => void;+ /** Whether all rows are expanded */+ allRowsExpanded?: boolean;+ /** Callback to copy JSON */+ onCopyJson?: () => void;+ /** Callback to download JSON */+ onDownloadJson?: () => void;+ /** Whether download/copy uses cached I/O only (doesn't load all) */+ isDownloadCacheOnly?: boolean;+ /** Current view type (pretty/json) */+ currentView?: "pretty" | "json";+ /** Whether indent visualization is enabled */+ indentEnabled?: boolean;+ /** Whether indent toggle is disabled (tree too deep) */+ indentDisabled?: boolean;+ /** Callback to toggle indent visualization */+ onToggleIndent?: () => void;+ /** Whether milliseconds are shown in time values */+ showMilliseconds?: boolean;+ /** Callback to toggle milliseconds display */+ onToggleMilliseconds?: () => void;+ /** Whether download/copy is currently loading */+ isDownloadLoading?: boolean;+}++/**+ * Toolbar for log view controls.+ */+export const LogViewToolbar = memo(function LogViewToolbar({+ searchQuery,+ onSearchChange,+ isVirtualized = true,+ observationCount,+ loadedObservationCount,+ onToggleExpandAll,+ allRowsExpanded,+ onCopyJson,+ onDownloadJson,+ isDownloadCacheOnly = false,+ currentView = "pretty",+ indentEnabled = false,+ indentDisabled = false,+ onToggleIndent,+ showMilliseconds = false,+ onToggleMilliseconds,+ isDownloadLoading = false,+}: LogViewToolbarProps) {+ const [isCopied, setIsCopied] = useState(false);++ const handleCopyClick = () => {+ setIsCopied(true);+ onCopyJson?.();+ setTimeout(() => setIsCopied(false), 1000);+ };++ return (+ <div className="flex h-9 flex-shrink-0 items-center gap-1.5 border-b bg-background px-2">+ {/* Large Trace indicator - only shown for virtualized mode */}+ {isVirtualized && (+ <HoverCard openDelay={200}>+ <HoverCardTrigger asChild>+ <span className="cursor-help rounded bg-yellow-100 px-1.5 py-0.5 text-xs font-medium text-yellow-700 dark:bg-yellow-900 dark:text-yellow-300">+ Large Trace+ </span>+ </HoverCardTrigger>+ <HoverCardContent+ align="start"+ className="w-72 text-sm"+ sideOffset={8}+ >+ <p className="font-medium">Optimized for performance</p>+ <p className="mt-1.5 text-muted-foreground">+ This trace has {observationCount?.toLocaleString() ?? "many"}{" "}+ observations. To keep things smooth:+ </p>+ <ul className="mt-1.5 list-inside list-disc space-y-0.5 text-muted-foreground">+ <li>Content loads as you scroll</li>+ <li>JSON view is disabled</li>+ <li>Download/copy includes I/O for cached observations only</li>+ </ul>+ </HoverCardContent>+ </HoverCard>+ )}++ {/* Search input or spacer (hidden in JSON view) */}+ {currentView === "json" ? (+ <div className="flex-1" />+ ) : (+ <Command className="flex-1 rounded-none border-0 bg-transparent">+ <CommandInput+ showBorder={false}+ placeholder="Search observations..."+ className="h-7 border-0 focus:ring-0"+ value={searchQuery}+ onValueChange={onSearchChange}+ />+ </Command>+ )}++ {/* Action buttons */}+ <div className="flex items-center gap-0.5">+ {/* Indent Toggle - only in formatted view */}+ {currentView === "pretty" && onToggleIndent && (+ <HoverCard openDelay={200}>+ <HoverCardTrigger asChild>+ <Button+ variant={indentEnabled ? "default" : "ghost"}+ size="icon"+ className={cn(+ "h-7 w-7",+ indentEnabled && "bg-primary text-primary-foreground",+ indentDisabled && "cursor-not-allowed opacity-50",+ )}+ onClick={indentDisabled ? undefined : onToggleIndent}+ disabled={indentDisabled}+ title={+ indentDisabled+ ? undefined+ : indentEnabled+ ? "Hide indentation"+ : "Show indentation"+ }+ >+ <IndentIncrease className="h-3.5 w-3.5" />+ </Button>+ </HoverCardTrigger>+ {indentDisabled && (+ <HoverCardContent className="w-56 text-sm" sideOffset={8}>+ <p className="font-medium">Indentation unavailable</p>+ <p className="mt-1 text-muted-foreground">+ Disabled for deeply nested trees to maintain readability.+ </p>+ </HoverCardContent>+ )}+ </HoverCard>+ )}++ {/* Milliseconds Toggle - only in formatted view */}+ {currentView === "pretty" && onToggleMilliseconds && (+ <Button+ variant={showMilliseconds ? "default" : "ghost"}+ size="icon"+ className={cn(+ "h-7 w-7",+ showMilliseconds && "bg-primary text-primary-foreground",+ )}+ onClick={onToggleMilliseconds}+ title={showMilliseconds ? "Hide milliseconds" : "Show milliseconds"}+ >+ <Timer className="h-3.5 w-3.5" />+ </Button>+ )}++ {/* Expand/Collapse All - show disabled with tooltip when virtualized */}+ {currentView === "pretty" && onToggleExpandAll && (+ <Tooltip>+ <TooltipTrigger asChild>+ <span>+ <Button+ variant="ghost"+ size="icon"+ className={cn(+ "h-7 w-7",+ isVirtualized && "cursor-not-allowed opacity-50",+ )}+ onClick={isVirtualized ? undefined : onToggleExpandAll}+ disabled={isVirtualized}+ >+ {allRowsExpanded && !isVirtualized ? (+ <FoldVertical className="h-3.5 w-3.5" />+ ) : (+ <UnfoldVertical className="h-3.5 w-3.5" />+ )}+ </Button>+ </span>+ </TooltipTrigger>+ <TooltipContent>+ {isVirtualized+ ? "Disabled for large traces"+ : allRowsExpanded+ ? "Collapse all"+ : "Expand all"}+ </TooltipContent>+ </Tooltip>+ )}++ {/* Copy JSON */}+ {onCopyJson && (+ <HoverCard openDelay={200}>+ <HoverCardTrigger asChild>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ size="icon"+ className="h-7 w-7"+ onClick={isDownloadLoading ? undefined : handleCopyClick}+ disabled={isDownloadLoading}+ >+ {isDownloadLoading ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : isCopied ? (+ <Check className="h-3.5 w-3.5" />+ ) : (+ <Copy className="h-3.5 w-3.5" />+ )}+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ {isDownloadLoading+ ? "Loading data..."+ : isDownloadCacheOnly+ ? "Copy as JSON (cache only)"+ : "Copy as JSON"}+ </TooltipContent>+ </Tooltip>+ </HoverCardTrigger>+ {isDownloadCacheOnly && !isDownloadLoading && (+ <HoverCardContent className="w-64 text-sm" sideOffset={8}>+ <p className="font-medium">Cache-only mode</p>+ <p className="mt-1 text-muted-foreground">+ For large traces, only expanded observations include full I/O+ data.+ </p>+ {loadedObservationCount !== undefined &&+ observationCount !== undefined && (+ <p className="mt-1.5 text-muted-foreground">+ <span className="font-medium">+ {loadedObservationCount} of {observationCount}+ </span>{" "}+ observations loaded+ </p>+ )}+ </HoverCardContent>+ )}+ </HoverCard>+ )}++ {/* Download JSON */}+ {onDownloadJson && (+ <HoverCard openDelay={200}>+ <HoverCardTrigger asChild>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ size="icon"+ className="h-7 w-7"+ onClick={isDownloadLoading ? undefined : onDownloadJson}+ disabled={isDownloadLoading}+ >+ {isDownloadLoading ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Download className="h-3.5 w-3.5" />+ )}+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ {isDownloadLoading+ ? "Loading data..."+ : isDownloadCacheOnly+ ? "Download as JSON (cache only)"+ : "Download as JSON"}+ </TooltipContent>+ </Tooltip>+ </HoverCardTrigger>+ {isDownloadCacheOnly && !isDownloadLoading && (+ <HoverCardContent className="w-64 text-sm" sideOffset={8}>+ <p className="font-medium">Cache-only mode</p>+ <p className="mt-1 text-muted-foreground">+ For large traces, only expanded observations include full I/O+ data.+ </p>+ {loadedObservationCount !== undefined &&+ observationCount !== undefined && (+ <p className="mt-1.5 text-muted-foreground">+ <span className="font-medium">+ {loadedObservationCount} of {observationCount}+ </span>{" "}+ observations loaded+ </p>+ )}+ </HoverCardContent>+ )}+ </HoverCard>+ )}+ </div>+ </div>+ );+});diff --git a/web/src/components/trace2/components/TraceLogView/LogViewTreeIndent.tsx b/web/src/components/trace2/components/TraceLogView/LogViewTreeIndent.tsxnew file mode 100644index 0000000000..fd4c053a3a--- /dev/null+++ b/web/src/components/trace2/components/TraceLogView/LogViewTreeIndent.tsx@@ -0,0 +1,51 @@+/**+ * LogViewTreeIndent - Tree indentation lines for log view rows.+ *+ * Renders visual tree lines connecting parent-child relationships.+ */++import { memo } from "react";+import { cn } from "@/src/utils/tailwind";++export interface LogViewTreeIndentProps {+ /** Array indicating which ancestor levels should show vertical lines */+ treeLines: boolean[];+ /** Whether this node is the last sibling at its level */+ isLastSibling: boolean;+ /** Current depth level */+ depth: number;+}++/**+ * Tree indentation with connecting lines.+ */+export const LogViewTreeIndent = memo(function LogViewTreeIndent({+ treeLines,+ isLastSibling,+ depth,+}: LogViewTreeIndentProps) {+ if (depth <= 0) return null;++ return (+ <div className="flex flex-shrink-0">+ {/* Vertical lines for each ancestor level */}+ {treeLines.map((hasLine, index) => (+ <div key={index} className="relative w-3">+ {hasLine && (+ <div className="absolute bottom-0 left-1.5 top-0 w-px bg-border" />+ )}+ </div>+ ))}+ {/* Current level connector */}+ <div className="relative w-3">+ <div+ className={cn(+ "absolute left-1.5 top-0 w-px bg-border",+ isLastSibling ? "h-1/2" : "h-full",+ )}+ />+ <div className="absolute left-1.5 top-1/2 h-px w-1.5 bg-border" />+ </div>+ </div>+ );+});diff --git a/web/src/components/trace2/components/TraceLogView/TraceLogView.tsx b/web/src/components/trace2/components/TraceLogView/TraceLogView.tsxindex ee11c19724..412b57e467 100644--- a/web/src/components/trace2/components/TraceLogView/TraceLogView.tsx+++ b/web/src/components/trace2/components/TraceLogView/TraceLogView.tsx@@ -1,224 +1,328 @@-import { useMemo, useEffect, useCallback } from "react";-import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";-import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";-import { api } from "@/src/utils/api";-import { StringParam, useQueryParam } from "use-query-params";-import { useQueries } from "@tanstack/react-query";-import { type JsonNested } from "@langfuse/shared";+/**+ * TraceLogView - Log view of trace observations with conditional virtualization.+ *+ * Features:+ * - Conditional virtualization based on observation count threshold+ * - Non-virtualized (< 350 obs): All rows in DOM, full features+ * - Virtualized (>= 350 obs): Only visible rows rendered+ * - Lazy I/O loading (data fetched only when row is expanded)+ * - Two view modes: chronological (by time) and tree-order (DFS hierarchy)+ * - Search filtering by name, type, or ID+ * - Expandable rows with full I/O preview+ * - Copy/Download JSON functionality+ *+ * Uses JSONTableView for table rendering with domain-specific column definitions.+ *+ * **IMPORTANT: Context Dependencies**+ * This component MUST be rendered within the following context providers:+ * - `TraceDataProvider` - Provides tree, observations, and scores data+ * - `ViewPreferencesProvider` - Provides logViewMode, logViewTreeStyle preferences+ * - `JsonExpansionProvider` - Manages expansion state persistence+ *+ * Example usage:+ * ```tsx+ * <TraceDataProvider trace={trace} observations={observations}>+ * <ViewPreferencesProvider>+ * <JsonExpansionProvider>+ * <TraceLogView traceId={id} projectId={pid} currentView="pretty" />+ * </JsonExpansionProvider>+ * </ViewPreferencesProvider>+ * </TraceDataProvider>+ * ```+ */++import { useState, useMemo, useCallback } from "react";+import { TRACE_VIEW_CONFIG } from "@/src/components/trace2/config/trace-view-config";+import { useTraceData } from "@/src/components/trace2/contexts/TraceDataContext";+import { useViewPreferences } from "@/src/components/trace2/contexts/ViewPreferencesContext";import { useJsonExpansion } from "@/src/components/trace2/contexts/JsonExpansionContext";+import { JSONTableView } from "@/src/components/trace2/components/_shared/JSONTableView";import {- normalizeExpansionState,- denormalizeExpansionState,-} from "@/src/components/trace2/contexts/json-expansion-utils";-import { Download } from "lucide-react";-import { Button } from "@/src/components/ui/button";-import { downloadTraceAsJson as downloadTraceUtil } from "@/src/components/trace2/lib/download-trace";+ flattenChronological,+ flattenTreeOrder,+ filterBySearch,+} from "./log-view-flattening";+import { type FlatLogItem } from "./log-view-types";+import { LogViewToolbar } from "./LogViewToolbar";+import { LogViewExpandedContent } from "./LogViewExpandedContent";+import { LogViewTreeIndent } from "./LogViewTreeIndent";+import { LogViewJsonMode } from "./LogViewJsonMode";+import { useLogViewAllObservationsIO } from "./useLogViewAllObservationsIO";+import { useObservationIOLoadedCount } from "./useLogViewObservationIO";+import { useLogViewPreferences } from "./useLogViewPreferences";+import { useLogViewDownload } from "./useLogViewDownload";+import { useLogViewColumns } from "./useLogViewColumns";export interface TraceLogViewProps {- observations: ObservationReturnTypeWithMetadata[];traceId: string;projectId: string;- currentView: "pretty" | "json";- trace: {- id: string;- [key: string]: unknown;- };+ currentView?: "pretty" | "json";}+// Import configuration constants+const {+ virtualizationThreshold: LOG_VIEW_VIRTUALIZATION_THRESHOLD,+ downloadThreshold: LOG_VIEW_DOWNLOAD_THRESHOLD,+ rowHeight: { collapsed: COLLAPSED_ROW_HEIGHT, expanded: EXPANDED_ROW_HEIGHT },+ maxIndentDepth: INDENT_DEPTH_THRESHOLD,+} = TRACE_VIEW_CONFIG.logView;++// Re-export thresholds for use in parent components+export { LOG_VIEW_VIRTUALIZATION_THRESHOLD };+export const TraceLogView = ({- observations,traceId,projectId,- currentView,- trace,+ currentView = "pretty",}: TraceLogViewProps) => {- const [currentObservationId] = useQueryParam("observation", StringParam);- const [selectedTab] = useQueryParam("view", StringParam);- const utils = api.useUtils();+ const { tree, observations } = useTraceData();+ const { logViewMode, logViewTreeStyle } = useViewPreferences();const { expansionState, setFieldExpansion } = useJsonExpansion();- // Load all observations with their input/output for the log view- const observationsWithIO = useQueries({- queries: observations.map((obs) =>- utils.observations.byId.queryOptions({- observationId: obs.id,- startTime: obs.startTime,- traceId: traceId,- projectId: projectId,- }),- ),- });+ // Determine if we should virtualize based on observation count+ const isVirtualized =+ observations.length >= LOG_VIEW_VIRTUALIZATION_THRESHOLD;- const logData = useMemo(() => {- // Sort observations by start time- const sortedObservations = [...observations].sort(- (a, b) => a.startTime.getTime() - b.startTime.getTime(),- );+ // Determine if download/copy should use cached I/O only (vs loading all)+ const isDownloadCacheOnly =+ observations.length >= LOG_VIEW_DOWNLOAD_THRESHOLD;++ // Get expanded keys from context (persisted in sessionStorage)+ // Uses dynamic key format: logViewRows:${traceId}+ const expandedRowsKey = `logViewRows:${traceId}`;- const allObsData: Record<+ const expandedKeys = useMemo(() => {+ const expandedRowsState = (expansionState[expandedRowsKey] ?? {}) as Record<string,- {- id: string;- type: string;- name: string | null;- startTime: string;- endTime: string | null;- latency: number | null;- level: string;- parentObservationId: string | null;- model: string | null;- modelParameters:- | string- | number- | boolean- | JsonNested[]- | { [key: string]: JsonNested }- | null;- promptName: string | null;- promptVersion: number | null;- input: unknown;- output: unknown;- metadata: unknown;- statusMessage: string | null;- inputUsage: number;- outputUsage: number;- totalUsage: number;- totalCost: number | null;- }- > = {};-- const idToDisplayName = new Map<string, string>();-- sortedObservations.forEach((obs) => {- const index = observations.findIndex((o) => o.id === obs.id);- const obsWithIO = observationsWithIO[index]?.data;-- const displayName = `${obs.name || obs.type} (${obs.id.substring(0, 8)})`;- idToDisplayName.set(obs.id, displayName);-- allObsData[displayName] = {- id: obs.id,- type: obs.type,- name: obs.name,- startTime: obs.startTime.toISOString(),- endTime: obs.endTime?.toISOString() || null,- latency: obs.latency,- level: obs.level,- parentObservationId: obs.parentObservationId,- model: obs.model,- modelParameters: obs.modelParameters,- promptName: obs.promptName,- promptVersion: obs.promptVersion,- input: obsWithIO?.input,- output: obsWithIO?.output,- metadata: obsWithIO?.metadata,- statusMessage: obs.statusMessage,- inputUsage: obs.inputUsage,- outputUsage: obs.outputUsage,- totalUsage: obs.totalUsage,- totalCost: obs.totalCost,- };- });+ boolean+ >;+ return new Set(+ Object.entries(expandedRowsState)+ .filter(([, isExpanded]) => isExpanded)+ .map(([id]) => id),+ );+ }, [expansionState, expandedRowsKey]);- return { data: allObsData, idToDisplayName };- }, [observations, observationsWithIO]);-- // Check if any data is still loading- const isLoading = observationsWithIO.some((query) => query.isPending);-- // Scroll to observation when clicked in trace tree- useEffect(() => {- if (currentObservationId && selectedTab === "log") {- const displayName = logData.idToDisplayName.get(currentObservationId);- if (displayName) {- // Convert display name format: hyphens to dots to match convertRowIdToKeyPath- const keyPathFormat = displayName.replace(/-/g, ".");- const element = document.querySelector(- `[data-observation-id="${keyPathFormat}"]`,- );- if (element) {- element.scrollIntoView({ behavior: "smooth", block: "start" });- }- }- }- }, [currentObservationId, selectedTab, logData]);+ // Update expanded keys in context+ const setExpandedKeys = useCallback(+ (keysOrUpdater: Set<string> | ((prev: Set<string>) => Set<string>)) => {+ const newKeys =+ typeof keysOrUpdater === "function"+ ? keysOrUpdater(expandedKeys)+ : keysOrUpdater;++ // Convert Set to Record<string, boolean>+ const newState: Record<string, boolean> = {};+ newKeys.forEach((id) => {+ newState[id] = true;+ });- // Get top-level observation keys for denormalization- const observationKeys = useMemo(- () => Object.keys(logData.data),- [logData.data],+ setFieldExpansion(expandedRowsKey, newState);+ },+ [expandedKeys, setFieldExpansion, expandedRowsKey],);- // Convert normalized state from context to actual state with observation IDs- const denormalizedState = useMemo(- () => denormalizeExpansionState(expansionState.log, observationKeys),- [expansionState.log, observationKeys],+ // Local state for search+ const [searchQuery, setSearchQuery] = useState("");++ // State for JSON view collapse+ const [jsonViewCollapsed, setJsonViewCollapsed] = useState(false);++ // Preferences from localStorage+ const {+ indentEnabled: indentEnabledPref,+ setIndentEnabled,+ showMilliseconds,+ setShowMilliseconds,+ } = useLogViewPreferences();++ // Disable indent when tree is too deep+ const indentDisabled = tree.childrenDepth > INDENT_DEPTH_THRESHOLD;+ const indentEnabled = indentEnabledPref && !indentDisabled;++ // Flatten tree based on mode+ const allItems = useMemo(() => {+ return logViewMode === "chronological"+ ? flattenChronological(tree)+ : flattenTreeOrder(tree);+ }, [tree, logViewMode]);++ // Apply search filter+ const flatItems = useMemo(() => {+ return filterBySearch(allItems, searchQuery);+ }, [allItems, searchQuery]);++ // Tree style: flat for chronological, use preference for tree-order+ const treeStyle = logViewMode === "chronological" ? "flat" : logViewTreeStyle;++ // Column definitions+ const columns = useLogViewColumns({+ indentEnabled,+ showMilliseconds,+ projectId,+ traceId,+ });++ // Render tree indentation for indented mode+ const renderRowPrefix = useCallback(+ (item: FlatLogItem) => {+ if (treeStyle !== "indented" || item.node.depth <= 0) return null;++ return (+ <LogViewTreeIndent+ treeLines={item.treeLines}+ isLastSibling={item.isLastSibling}+ depth={item.node.depth}+ />+ );+ },+ [treeStyle],);- // download includes trace + observations with full I/O- const downloadLogAsJson = useCallback(() => {- const observationsWithFullData = observations.map((obs, index) => {- const obsWithIO = observationsWithIO[index]?.data;- return {- ...obs,- input: obsWithIO?.input,- output: obsWithIO?.output,- metadata: obsWithIO?.metadata,- };- });+ // Render expanded content with JSON expansion context integration+ // Always persist expansion state regardless of virtualization mode+ const renderExpanded = useCallback(+ (item: FlatLogItem) => {+ const observationExpansionKey = `log:${item.node.id}`;- downloadTraceUtil({- trace,- observations: observationsWithFullData,- filename: `trace-with-observations-${traceId}.json`,+ return (+ <LogViewExpandedContent+ node={item.node}+ traceId={traceId}+ projectId={projectId}+ currentView={currentView}+ externalExpansionState={expansionState[observationExpansionKey]}+ onExternalExpansionChange={(exp) =>+ setFieldExpansion(observationExpansionKey, exp)+ }+ />+ );+ },+ [traceId, projectId, currentView, expansionState, setFieldExpansion],+ );++ // Track if all rows are expanded (for non-virtualized mode)+ const allRowsExpanded = useMemo(() => {+ if (flatItems.length === 0) return false;+ return flatItems.every((item) => expandedKeys.has(item.node.id));+ }, [flatItems, expandedKeys]);++ // Toggle expand/collapse all (non-virtualized mode only)+ const handleToggleExpandAll = useCallback(() => {+ if (allRowsExpanded) {+ // Collapse all+ setExpandedKeys(new Set());+ } else {+ // Expand all+ const allKeys = new Set(flatItems.map((item) => item.node.id));+ setExpandedKeys(allKeys);+ }+ }, [allRowsExpanded, flatItems, setExpandedKeys]);++ // On-demand loading hook for observation I/O data+ // Does NOT auto-fetch - call loadAllData() or buildDataFromCache() when needed+ const allObservationsIO = useLogViewAllObservationsIO({+ items: flatItems,+ traceId,+ projectId,+ });++ // Track loaded observation count for cache-only mode UX+ const { loaded: loadedObservationCount } = useObservationIOLoadedCount({+ items: flatItems,+ traceId,+ projectId,+ });++ // Download and copy handlers+ const { handleCopyJson, handleDownloadJson, isDownloadOrCopyLoading } =+ useLogViewDownload({+ traceId,+ isDownloadCacheOnly,+ allObservationsData: allObservationsIO.data,+ isLoadingAllData: allObservationsIO.isLoading,+ failedObservationIds: allObservationsIO.failedObservationIds,+ loadAllData: allObservationsIO.loadAllData,+ buildDataFromCache: allObservationsIO.buildDataFromCache,});- }, [trace, observations, observationsWithIO, traceId]);-- // Only render the actual log view when all data is loaded- // prevents partial rendering and improves performance- if (isLoading) {- return (- <div className="flex h-full w-full flex-col overflow-hidden px-2">- <div className="mb-2 flex max-h-full min-h-0 w-full flex-col gap-2 overflow-y-auto">- <div className="rounded-md border p-4">- <div className="text-sm text-muted-foreground">- Loading {observations.length} observations...- </div>++ // Toggle JSON view collapse+ const handleToggleJsonCollapse = useCallback(() => {+ setJsonViewCollapsed((prev) => !prev);+ }, []);++ // Check if there are any observations at all+ const hasNoObservations = allItems.length === 0;+ const hasNoSearchResults = !hasNoObservations && flatItems.length === 0;++ return (+ <div className="flex h-full w-full flex-col overflow-hidden">+ {/* Toolbar with search and actions */}+ <LogViewToolbar+ searchQuery={searchQuery}+ onSearchChange={setSearchQuery}+ isVirtualized={isVirtualized}+ observationCount={observations.length}+ loadedObservationCount={loadedObservationCount}+ onToggleExpandAll={handleToggleExpandAll}+ allRowsExpanded={allRowsExpanded}+ onCopyJson={handleCopyJson}+ onDownloadJson={handleDownloadJson}+ isDownloadCacheOnly={isDownloadCacheOnly}+ isDownloadLoading={isDownloadOrCopyLoading}+ currentView={currentView}+ indentEnabled={indentEnabled}+ indentDisabled={indentDisabled}+ onToggleIndent={() => setIndentEnabled(!indentEnabledPref)}+ showMilliseconds={showMilliseconds}+ onToggleMilliseconds={() => setShowMilliseconds(!showMilliseconds)}+ />++ {/* Empty states */}+ {hasNoObservations && (+ <div className="flex flex-1 items-center justify-center">+ <div className="text-sm text-muted-foreground">+ No observations in this trace</div></div>- </div>- );- }+ )}- return (- <div className="flex h-full w-full flex-col overflow-hidden pr-2">- <div className="mb-2 flex max-h-full min-h-0 w-full flex-col gap-2 overflow-y-auto px-2">- <PrettyJsonView- key="trace-log-view"- title="Concatenated Observation Log"- json={logData.data}- currentView={currentView}- isLoading={false}- showNullValues={false}- externalExpansionState={denormalizedState}- onExternalExpansionChange={(expansion) =>- setFieldExpansion("log", normalizeExpansionState(expansion))- }- stickyTopLevelKey={true}- showObservationTypeBadge={true}- controlButtons={- <Button- variant="ghost"- size="sm"- onClick={downloadLogAsJson}- title="Download trace log as JSON"- className="-mr-2"- >- <Download className="h-3 w-3" />- </Button>- }+ {hasNoSearchResults && (+ <div className="flex flex-1 items-center justify-center">+ <div className="text-sm text-muted-foreground">+ No observations match "{searchQuery}"+ </div>+ </div>+ )}++ {/* JSON view mode - only available for non-virtualized traces */}+ {flatItems.length > 0 && currentView === "json" && !isVirtualized && (+ <LogViewJsonMode+ items={flatItems}+ traceId={traceId}+ projectId={projectId}+ isCollapsed={jsonViewCollapsed}+ onToggleCollapse={handleToggleJsonCollapse}+ />+ )}++ {/* Table view mode - render as expandable table */}+ {flatItems.length > 0 && currentView === "pretty" && (+ <JSONTableView+ items={flatItems}+ columns={columns}+ getItemKey={(item) => item.node.id}+ expandable+ renderExpanded={renderExpanded}+ expandedKeys={expandedKeys}+ onExpandedKeysChange={setExpandedKeys}+ virtualized={isVirtualized}+ overscan={100}+ collapsedRowHeight={COLLAPSED_ROW_HEIGHT}+ expandedRowHeight={EXPANDED_ROW_HEIGHT}+ renderRowPrefix={renderRowPrefix}/>- </div>+ )}</div>);};diff --git a/web/src/components/trace2/components/TraceLogView/TraceLogViewConfirmationDialog.tsx b/web/src/components/trace2/components/TraceLogView/TraceLogViewConfirmationDialog.tsxdeleted file mode 100644index 7b38e5f16e..0000000000--- a/web/src/components/trace2/components/TraceLogView/TraceLogViewConfirmationDialog.tsx+++ /dev/null@@ -1,53 +0,0 @@-/**- * LogViewConfirmationDialog - Confirmation dialog for viewing traces with many observations- *- * Warns users about potential performance issues when viewing log view- * for traces with a large number of observations.- */--import {- AlertDialog,- AlertDialogAction,- AlertDialogCancel,- AlertDialogContent,- AlertDialogDescription,- AlertDialogFooter,- AlertDialogHeader,- AlertDialogTitle,-} from "@/src/components/ui/alert-dialog";--interface TraceLogViewConfirmationDialogProps {- open: boolean;- onOpenChange: (open: boolean) => void;- observationCount: number;- onConfirm: () => void;-}--export function TraceLogViewConfirmationDialog({- open,- onOpenChange,- observationCount,- onConfirm,-}: TraceLogViewConfirmationDialogProps) {- return (- <AlertDialog open={open} onOpenChange={onOpenChange}>- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle>Sluggish Performance Warning</AlertDialogTitle>- <AlertDialogDescription>- This trace has {observationCount} observations. The log view may be- slow to load and interact with. Do you want to continue?- </AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel onClick={() => onOpenChange(false)}>- Cancel- </AlertDialogCancel>- <AlertDialogAction onClick={onConfirm}>- Show Log View- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>- );-}diff --git a/web/src/components/trace2/components/TraceLogView/log-view-flattening.clienttest.ts b/web/src/components/trace2/components/TraceLogView/log-view-flattening.clienttest.tsnew file mode 100644index 0000000000..ecd562fffd--- /dev/null+++ b/web/src/components/trace2/components/TraceLogView/log-view-flattening.clienttest.ts@@ -0,0 +1,450 @@+/**+ * Tests for log-view-flattening.ts+ *+ * @jest-environment jsdom+ */++import {+ flattenChronological,+ flattenTreeOrder,+ filterBySearch,+} from "./log-view-flattening";+import { type TreeNode } from "@/src/components/trace2/lib/types";++// Helper to create a minimal TreeNode for testing+function createNode(+ overrides: Partial<TreeNode> & { id: string; type: TreeNode["type"] },+): TreeNode {+ return {+ name: overrides.name ?? overrides.id,+ startTime: overrides.startTime ?? new Date("2024-01-01T00:00:00Z"),+ endTime: overrides.endTime ?? null,+ children: overrides.children ?? [],+ startTimeSinceTrace: overrides.startTimeSinceTrace ?? 0,+ startTimeSinceParentStart: overrides.startTimeSinceParentStart ?? null,+ depth: overrides.depth ?? 0,+ childrenDepth: overrides.childrenDepth ?? 0,+ ...overrides,+ };+}++// Helper to create a TRACE root node+function createTraceRoot(children: TreeNode[]): TreeNode {+ return createNode({+ id: "trace-root",+ type: "TRACE",+ name: "Test Trace",+ startTime: new Date("2024-01-01T00:00:00Z"),+ children,+ depth: -1,+ startTimeSinceTrace: 0,+ startTimeSinceParentStart: null,+ });+}++describe("log-view-flattening", () => {+ describe("flattenChronological", () => {+ it("should return empty array for trace with no observations", () => {+ const root = createTraceRoot([]);+ const result = flattenChronological(root);+ expect(result).toHaveLength(0);+ });++ it("should sort observations by startTime", () => {+ const obs1 = createNode({+ id: "obs-1",+ type: "GENERATION",+ name: "first",+ startTime: new Date("2024-01-01T00:00:03Z"),+ depth: 0,+ });+ const obs2 = createNode({+ id: "obs-2",+ type: "SPAN",+ name: "second",+ startTime: new Date("2024-01-01T00:00:01Z"),+ depth: 0,+ });+ const obs3 = createNode({+ id: "obs-3",+ type: "EVENT",+ name: "third",+ startTime: new Date("2024-01-01T00:00:02Z"),+ depth: 0,+ });+ const root = createTraceRoot([obs1, obs2, obs3]);++ const result = flattenChronological(root);++ expect(result).toHaveLength(3);+ expect(result[0].node.id).toBe("obs-2"); // earliest+ expect(result[1].node.id).toBe("obs-3");+ expect(result[2].node.id).toBe("obs-1"); // latest+ });++ it("should flatten nested children chronologically", () => {+ const child = createNode({+ id: "child",+ type: "GENERATION",+ name: "child",+ startTime: new Date("2024-01-01T00:00:01Z"),+ depth: 1,+ });+ const parent = createNode({+ id: "parent",+ type: "SPAN",+ name: "parent",+ startTime: new Date("2024-01-01T00:00:02Z"),+ children: [child],+ depth: 0,+ });+ const root = createTraceRoot([parent]);++ const result = flattenChronological(root);++ expect(result).toHaveLength(2);+ // Child started before parent, so comes first chronologically+ expect(result[0].node.id).toBe("child");+ expect(result[1].node.id).toBe("parent");+ });++ it("should have no treeLines in chronological mode", () => {+ const child = createNode({+ id: "child",+ type: "GENERATION",+ startTime: new Date("2024-01-01T00:00:02Z"),+ depth: 1,+ });+ const parent = createNode({+ id: "parent",+ type: "SPAN",+ startTime: new Date("2024-01-01T00:00:01Z"),+ children: [child],+ depth: 0,+ });+ const root = createTraceRoot([parent]);++ const result = flattenChronological(root);++ // All items should have empty treeLines (flat view)+ result.forEach((item) => {+ expect(item.treeLines).toEqual([]);+ });+ });+ });++ describe("flattenTreeOrder", () => {+ it("should return empty array for trace with no observations", () => {+ const root = createTraceRoot([]);+ const result = flattenTreeOrder(root);+ expect(result).toHaveLength(0);+ });++ it("should preserve parent-child order (DFS)", () => {+ const grandchild = createNode({+ id: "grandchild",+ type: "EVENT",+ startTime: new Date("2024-01-01T00:00:03Z"),+ depth: 2,+ });+ const child = createNode({+ id: "child",+ type: "GENERATION",+ startTime: new Date("2024-01-01T00:00:02Z"),+ children: [grandchild],+ depth: 1,+ });+ const parent = createNode({+ id: "parent",+ type: "SPAN",+ startTime: new Date("2024-01-01T00:00:01Z"),+ children: [child],+ depth: 0,+ });+ const root = createTraceRoot([parent]);++ const result = flattenTreeOrder(root);++ expect(result).toHaveLength(3);+ expect(result[0].node.id).toBe("parent");+ expect(result[1].node.id).toBe("child");+ expect(result[2].node.id).toBe("grandchild");+ });++ it("should sort siblings by startTime", () => {+ const child1 = createNode({+ id: "child-1",+ type: "GENERATION",+ startTime: new Date("2024-01-01T00:00:03Z"),+ depth: 1,+ });+ const child2 = createNode({+ id: "child-2",+ type: "SPAN",+ startTime: new Date("2024-01-01T00:00:01Z"),+ depth: 1,+ });+ const parent = createNode({+ id: "parent",+ type: "SPAN",+ startTime: new Date("2024-01-01T00:00:00Z"),+ children: [child1, child2],+ depth: 0,+ });+ const root = createTraceRoot([parent]);++ const result = flattenTreeOrder(root);++ expect(result).toHaveLength(3);+ expect(result[0].node.id).toBe("parent");+ expect(result[1].node.id).toBe("child-2"); // earlier startTime+ expect(result[2].node.id).toBe("child-1"); // later startTime+ });++ it("should calculate treeLines correctly", () => {+ const child1 = createNode({+ id: "child-1",+ type: "GENERATION",+ startTime: new Date("2024-01-01T00:00:01Z"),+ depth: 1,+ });+ const child2 = createNode({+ id: "child-2",+ type: "SPAN",+ startTime: new Date("2024-01-01T00:00:02Z"),+ depth: 1,+ });+ const parent = createNode({+ id: "parent",+ type: "SPAN",+ startTime: new Date("2024-01-01T00:00:00Z"),+ children: [child1, child2],+ depth: 0,+ });+ const root = createTraceRoot([parent]);++ const result = flattenTreeOrder(root);++ expect(result[0].treeLines).toEqual([]); // parent - no ancestors+ expect(result[0].isLastSibling).toBe(true); // only root child++ expect(result[1].treeLines).toEqual([false]); // child-1: parent is last sibling, so no line+ expect(result[1].isLastSibling).toBe(false); // not last child++ expect(result[2].treeLines).toEqual([false]); // child-2: parent is last sibling+ expect(result[2].isLastSibling).toBe(true); // last child+ });++ it("should handle multiple root observations", () => {+ const obs1 = createNode({+ id: "obs-1",+ type: "GENERATION",+ startTime: new Date("2024-01-01T00:00:02Z"),+ depth: 0,+ });+ const obs2 = createNode({+ id: "obs-2",+ type: "SPAN",+ startTime: new Date("2024-01-01T00:00:01Z"),+ depth: 0,+ });+ const root = createTraceRoot([obs1, obs2]);++ const result = flattenTreeOrder(root);++ expect(result).toHaveLength(2);+ expect(result[0].node.id).toBe("obs-2"); // earlier+ expect(result[0].isLastSibling).toBe(false);+ expect(result[1].node.id).toBe("obs-1"); // later+ expect(result[1].isLastSibling).toBe(true);+ });++ it("should handle deeply nested structure", () => {+ // Create a chain: level0 -> level1 -> level2 -> level3+ const level3 = createNode({+ id: "level-3",+ type: "EVENT",+ depth: 3,+ });+ const level2 = createNode({+ id: "level-2",+ type: "GENERATION",+ children: [level3],+ depth: 2,+ });+ const level1 = createNode({+ id: "level-1",+ type: "SPAN",+ children: [level2],+ depth: 1,+ });+ const level0 = createNode({+ id: "level-0",+ type: "SPAN",+ children: [level1],+ depth: 0,+ });+ const root = createTraceRoot([level0]);++ const result = flattenTreeOrder(root);++ expect(result).toHaveLength(4);+ expect(result.map((r) => r.node.id)).toEqual([+ "level-0",+ "level-1",+ "level-2",+ "level-3",+ ]);++ // All are only children, so all are last siblings+ result.forEach((item) => {+ expect(item.isLastSibling).toBe(true);+ });+ });+ });++ describe("filterBySearch", () => {+ const createTestItems = (): ReturnType<typeof flattenChronological> => {+ const obs1 = createNode({+ id: "gen-123",+ type: "GENERATION",+ name: "chat-completion",+ depth: 0,+ });+ const obs2 = createNode({+ id: "span-456",+ type: "SPAN",+ name: "process-request",+ depth: 0,+ });+ const obs3 = createNode({+ id: "event-789",+ type: "EVENT",+ name: "user-click",+ depth: 0,+ });+ const root = createTraceRoot([obs1, obs2, obs3]);+ return flattenChronological(root);+ };++ it("should return all items for empty query", () => {+ const items = createTestItems();+ const result = filterBySearch(items, "");+ expect(result).toHaveLength(3);+ });++ it("should return all items for whitespace query", () => {+ const items = createTestItems();+ const result = filterBySearch(items, " ");+ expect(result).toHaveLength(3);+ });++ it("should filter by name (case-insensitive)", () => {+ const items = createTestItems();++ const result1 = filterBySearch(items, "chat");+ expect(result1).toHaveLength(1);+ expect(result1[0].node.name).toBe("chat-completion");++ const result2 = filterBySearch(items, "CHAT");+ expect(result2).toHaveLength(1);+ expect(result2[0].node.name).toBe("chat-completion");+ });++ it("should filter by type", () => {+ const items = createTestItems();++ const result = filterBySearch(items, "generation");+ expect(result).toHaveLength(1);+ expect(result[0].node.type).toBe("GENERATION");+ });++ it("should filter by id", () => {+ const items = createTestItems();++ const result = filterBySearch(items, "456");+ expect(result).toHaveLength(1);+ expect(result[0].node.id).toBe("span-456");+ });++ it("should match partial strings", () => {+ const items = createTestItems();++ const result = filterBySearch(items, "request");+ expect(result).toHaveLength(1);+ expect(result[0].node.name).toBe("process-request");+ });++ it("should return empty array when no matches", () => {+ const items = createTestItems();+ const result = filterBySearch(items, "nonexistent");+ expect(result).toHaveLength(0);+ });++ it("should match multiple items", () => {+ const items = createTestItems();++ // Both "span" type and observation names contain hyphen-separated words+ const result = filterBySearch(items, "-");+ expect(result).toHaveLength(3); // all have hyphens in name or id+ });++ it("should handle null name gracefully", () => {+ const obs = createNode({+ id: "obs-1",+ type: "GENERATION",+ name: undefined as unknown as string,+ depth: 0,+ });+ const root = createTraceRoot([obs]);+ const items = flattenChronological(root);++ // Should not throw+ const result = filterBySearch(items, "GENERATION");+ expect(result).toHaveLength(1);+ });+ });++ describe.skip("performance", () => {+ it("should handle 1000 observations efficiently", () => {+ const observations: TreeNode[] = [];+ for (let i = 0; i < 1000; i++) {+ observations.push(+ createNode({+ id: `obs-${i}`,+ type: "GENERATION",+ name: `observation-${i}`,+ startTime: new Date(Date.now() + i * 1000),+ depth: 0,+ }),+ );+ }+ const root = createTraceRoot(observations);++ const start = performance.now();+ const result = flattenChronological(root);+ const duration = performance.now() - start;++ expect(result).toHaveLength(1000);+ expect(duration).toBeLessThan(100); // Should complete in < 100ms+ });++ it("should handle deeply nested tree (100 levels) without stack overflow", () => {+ // Build a chain of 100 nested nodes+ let current: TreeNode | null = null;+ for (let i = 99; i >= 0; i--) {+ current = createNode({+ id: `level-${i}`,+ type: "SPAN",+ children: current ? [current] : [],+ depth: i,+ });+ }+ const root = createTraceRoot([current!]);++ // Should not throw (stack overflow)+ const result = flattenTreeOrder(root);+ expect(result).toHaveLength(100);+ });+ });+});diff --git a/web/src/components/trace2/components/TraceLogView/log-view-flattening.ts b/web/src/components/trace2/components/TraceLogView/log-view-flattening.tsnew file mode 100644index 0000000000..6693084d9b--- /dev/null+++ b/web/src/components/trace2/components/TraceLogView/log-view-flattening.ts@@ -0,0 +1,162 @@+/**+ * Log view flattening utilities for virtualized rendering.+ *+ * Provides two flattening modes:+ * - Chronological: Sorted by startTime (execution order)+ * - Tree-order: DFS traversal preserving parent-child relationships+ *+ * Also provides search filtering functionality.+ */++import { type TreeNode } from "@/src/components/trace2/lib/types";+import { type FlatLogItem } from "./log-view-types";++/**+ * Collects all observation nodes from a tree (excludes TRACE root).+ * Used internally by both flattening functions.+ */+function collectObservations(root: TreeNode): TreeNode[] {+ const observations: TreeNode[] = [];+ const stack: TreeNode[] = [root];++ while (stack.length > 0) {+ const node = stack.pop()!;++ // Only include observations, not the TRACE root+ if (node.type !== "TRACE") {+ observations.push(node);+ }++ // Add children to stack (reverse order for correct DFS)+ for (let i = node.children.length - 1; i >= 0; i--) {+ stack.push(node.children[i]);+ }+ }++ return observations;+}++/**+ * Flattens tree into chronological order (sorted by startTime).+ * All observations are at the same visual level (no indentation).+ *+ * @param root - Root TreeNode (typically the TRACE node)+ * @returns Flat list of observations sorted by startTime+ */+export function flattenChronological(root: TreeNode): FlatLogItem[] {+ const observations = collectObservations(root);++ // Sort by startTime+ observations.sort((a, b) => a.startTime.getTime() - b.startTime.getTime());++ // Convert to FlatLogItem with no tree structure (chronological = flat)+ return observations.map((node, index) => ({+ node,+ treeLines: [],+ isLastSibling: index === observations.length - 1,+ }));+}++/**+ * Flattens tree in DFS order (parent → children → siblings).+ * Preserves tree structure with treeLines for visual indentation.+ *+ * Uses iterative approach to avoid stack overflow with deep trees.+ *+ * @param root - Root TreeNode (typically the TRACE node)+ * @returns Flat list of observations in DFS order with tree metadata+ */+export function flattenTreeOrder(root: TreeNode): FlatLogItem[] {+ const flatList: FlatLogItem[] = [];++ // Stack entry type for iterative DFS+ interface StackEntry {+ node: TreeNode;+ depth: number;+ treeLines: boolean[];+ isLastSibling: boolean;+ }++ // Start with root's children (skip TRACE node itself)+ const stack: StackEntry[] = [];++ // Sort root children by startTime and push in reverse order+ const sortedRootChildren = [...root.children].sort(+ (a, b) => a.startTime.getTime() - b.startTime.getTime(),+ );++ for (let i = sortedRootChildren.length - 1; i >= 0; i--) {+ stack.push({+ node: sortedRootChildren[i],+ depth: 0,+ treeLines: [],+ isLastSibling: i === sortedRootChildren.length - 1,+ });+ }++ // Process stack (LIFO - depth-first traversal)+ while (stack.length > 0) {+ const current = stack.pop()!;++ // Add current node to result+ flatList.push({+ node: current.node,+ treeLines: current.treeLines,+ isLastSibling: current.isLastSibling,+ });++ // If node has children, add them to stack+ if (current.node.children.length > 0) {+ // Sort children by startTime+ const sortedChildren = [...current.node.children].sort(+ (a, b) => a.startTime.getTime() - b.startTime.getTime(),+ );++ // Push children in REVERSE order for correct DFS traversal+ for (let i = sortedChildren.length - 1; i >= 0; i--) {+ const child = sortedChildren[i];+ const isChildLast = i === sortedChildren.length - 1;++ stack.push({+ node: child,+ depth: current.depth + 1,+ treeLines: [...current.treeLines, !current.isLastSibling],+ isLastSibling: isChildLast,+ });+ }+ }+ }++ return flatList;+}++/**+ * Filters log items by search query.+ * Matches against observation name and type (case-insensitive).+ *+ * @param items - List of FlatLogItem to filter+ * @param query - Search query string+ * @returns Filtered list of items matching the query+ */+export function filterBySearch(+ items: FlatLogItem[],+ query: string,+): FlatLogItem[] {+ if (!query.trim()) {+ return items;+ }++ const lowerQuery = query.toLowerCase().trim();++ return items.filter((item) => {+ const name = item.node.name?.toLowerCase() ?? "";+ const type = item.node.type.toLowerCase();+ const id = item.node.id.toLowerCase();++ return (+ name.includes(lowerQuery) ||+ type.includes(lowerQuery) ||+ id.includes(lowerQuery)+ );+ });+}diff --git a/web/src/components/trace2/components/TraceLogView/log-view-formatters.ts b/web/src/components/trace2/components/TraceLogView/log-view-formatters.tsnew file mode 100644index 0000000000..8074747505--- /dev/null+++ b/web/src/components/trace2/components/TraceLogView/log-view-formatters.ts@@ -0,0 +1,112 @@+/**+ * Pure formatting utilities for LogView display.+ *+ * These functions handle presentation logic, keeping it separate from+ * data transformation and component rendering.+ */++import { type TreeNode } from "@/src/components/trace2/lib/types";++/**+ * Formats a node's display name for the log view.+ *+ * Format: "{name or type} ({first 8 chars of id})"+ * Example: "chat-completion (abc12345)"+ *+ * @param node - TreeNode to format+ * @returns Formatted display name+ */+export function formatDisplayName(node: TreeNode): string {+ const name = node.name || node.type;+ const shortId = node.id.substring(0, 8);+ return `${name} (${shortId})`;+}++/**+ * Formats milliseconds as a time string in mm:ss or mm:ss.mmm format.+ *+ * Examples (showMs = false):+ * - 0 → "0:00"+ * - 500 → "0:00"+ * - 1500 → "0:01"+ * - 65000 → "1:05"+ * - 3665000 → "61:05"+ *+ * Examples (showMs = true):+ * - 0 → "0:00.000"+ * - 500 → "0:00.500"+ * - 1500 → "0:01.500"+ * - 65123 → "1:05.123"+ *+ * @param ms - Milliseconds since trace start+ * @param showMs - Whether to display milliseconds+ * @returns Formatted time string in mm:ss or mm:ss.mmm format+ */+export function formatRelativeTime(ms: number, showMs = false): string {+ if (ms < 0) {+ return "-" + formatRelativeTime(-ms, showMs);+ }++ const totalSeconds = Math.floor(ms / 1000);+ const minutes = Math.floor(totalSeconds / 60);+ const seconds = totalSeconds % 60;+ const milliseconds = ms % 1000;++ if (showMs) {+ return `${minutes}:${seconds.toString().padStart(2, "0")}.${milliseconds.toString().padStart(3, "0")}`;+ }++ return `${minutes}:${seconds.toString().padStart(2, "0")}`;+}++/**+ * Formats depth as a visual indicator.+ *+ * @param depth - Tree depth (0 for root observations)+ * @returns Formatted depth string or empty for depth 0+ */+export function formatDepthIndicator(depth: number): string {+ if (depth <= 0) {+ return "";+ }+ return `L${depth}`;+}++/**+ * Formats duration in milliseconds to a human-readable string.+ *+ * Examples:+ * - 0 → "0ms"+ * - 50 → "50ms"+ * - 1500 → "1.5s"+ * - 65000 → "1:05"+ *+ * @param startTime - Start time+ * @param endTime - End time (optional)+ * @returns Formatted duration string or "-" if no end time+ */+export function formatDuration(startTime: Date, endTime?: Date | null): string {+ if (!endTime) {+ return "-";+ }++ const ms = endTime.getTime() - startTime.getTime();++ if (ms < 0) {+ return "-";+ }++ if (ms < 1000) {+ return `${Math.round(ms)}ms`;+ }++ if (ms < 60000) {+ return `${(ms / 1000).toFixed(1)}s`;+ }++ // Use mm:ss format for longer durations+ const totalSeconds = Math.floor(ms / 1000);+ const minutes = Math.floor(totalSeconds / 60);+ const seconds = totalSeconds % 60;+ return `${minutes}:${seconds.toString().padStart(2, "0")}`;+}diff --git a/web/src/components/trace2/components/TraceLogView/log-view-types.ts b/web/src/components/trace2/components/TraceLogView/log-view-types.tsnew file mode 100644index 0000000000..60a6e969ea--- /dev/null+++ b/web/src/components/trace2/components/TraceLogView/log-view-types.ts@@ -0,0 +1,31 @@+/**+ * Types for LogView virtualized rendering.+ *+ * FlatLogItem represents a single row in the log view,+ * containing the TreeNode and metadata for visual rendering.+ */++import { type TreeNode } from "@/src/components/trace2/lib/types";++/**+ * Flattened log item for virtualized rendering.+ * Contains raw data - formatting happens in components.+ */+export interface FlatLogItem {+ /** The tree node containing observation data */+ node: TreeNode;+ /** Visual tree lines for indented tree-order style */+ treeLines: boolean[];+ /** Whether this node is the last sibling at its level */+ isLastSibling: boolean;+}++/**+ * View mode for log view display.+ */+export type LogViewMode = "chronological" | "tree-order";++/**+ * Tree style for tree-order view.+ */+export type LogViewTreeStyle = "flat" | "indented";diff --git a/web/src/components/trace2/components/TraceLogView/useLogViewAllObservationsIO.ts b/web/src/components/trace2/components/TraceLogView/useLogViewAllObservationsIO.tsnew file mode 100644index 0000000000..77936a13bd--- /dev/null+++ b/web/src/components/trace2/components/TraceLogView/useLogViewAllObservationsIO.ts@@ -0,0 +1,280 @@+/**+ * Hook for on-demand batch-loading all observation I/O data.+ *+ * IMPORTANT: This hook does NOT fetch data automatically.+ * Call `loadAllData()` to trigger fetching when needed (e.g., download button click).+ *+ * This avoids creating 10k+ queries on mount which would freeze the browser.+ */++import { useState, useCallback } from "react";+import { useQueryClient } from "@tanstack/react-query";+import { chunk } from "lodash";+import { api } from "@/src/utils/api";+import { TRACE_VIEW_CONFIG } from "@/src/components/trace2/config/trace-view-config";+import { type FlatLogItem } from "./log-view-types";+import { formatDisplayName } from "./log-view-formatters";++// Max concurrent requests when loading all observation data+const FETCH_CONCURRENCY = TRACE_VIEW_CONFIG.logView.batchFetch.concurrency;++export interface UseLogViewAllObservationsIOParams {+ items: FlatLogItem[];+ traceId: string;+ projectId: string;+}++export interface ObservationIOData {+ id: string;+ type: string;+ name: string;+ startTime: Date;+ endTime?: Date | null;+ depth: number;+ input?: unknown;+ output?: unknown;+ metadata?: unknown;+}++/**+ * Build the tRPC query key for an observation.+ * Must match the format used by api.observations.byId.useQuery+ */+export function getObservationQueryKey(+ observationId: string,+ traceId: string,+ projectId: string,+ startTime: Date,+) {+ return [+ ["observations", "byId"],+ {+ input: { observationId, traceId, projectId, startTime },+ type: "query",+ },+ ];+}++/**+ * Hook for on-demand loading of all observation I/O data.+ *+ * Does NOT auto-fetch. Call `loadAllData()` to trigger.+ *+ * @param params - Items array, traceId, projectId+ * @returns loadAllData function, loading state, data, and error state+ */+export function useLogViewAllObservationsIO({+ items,+ traceId,+ projectId,+}: UseLogViewAllObservationsIOParams) {+ const utils = api.useUtils();+ const queryClient = useQueryClient();++ const [isLoading, setIsLoading] = useState(false);+ const [isError, setIsError] = useState(false);+ const [data, setData] = useState<ObservationIOData[] | null>(null);+ const [failedObservationIds, setFailedObservationIds] = useState<string[]>(+ [],+ );++ /**+ * Build download data from tree structure + any cached observation I/O.+ * This is synchronous and doesn't fetch new data - only uses what's cached.+ */+ const buildDataFromCache = useCallback((): ObservationIOData[] => {+ return items+ .filter((item) => item.node.type !== "TRACE")+ .map((item) => {+ const baseData: ObservationIOData = {+ id: item.node.id,+ type: item.node.type,+ name: formatDisplayName(item.node),+ startTime: item.node.startTime,+ endTime: item.node.endTime,+ depth: item.node.depth,+ };++ // Check if we have cached I/O data for this observation+ const queryKey = getObservationQueryKey(+ item.node.id,+ traceId,+ projectId,+ item.node.startTime,+ );+ const cachedData = queryClient.getQueryData(queryKey) as+ | { input?: unknown; output?: unknown; metadata?: unknown }+ | undefined;++ if (cachedData) {+ if (cachedData.input !== null && cachedData.input !== undefined) {+ baseData.input = cachedData.input;+ }+ if (cachedData.output !== null && cachedData.output !== undefined) {+ baseData.output = cachedData.output;+ }+ if (+ cachedData.metadata !== null &&+ cachedData.metadata !== undefined+ ) {+ baseData.metadata = cachedData.metadata;+ }+ }++ return baseData;+ });+ }, [items, traceId, projectId, queryClient]);++ /**+ * Load all observation I/O data, using cache where available.+ * Only fetches observations not already in React Query cache.+ * Returns the combined data once all fetches complete.+ * Tracks failures and continues downloading remaining observations.+ */+ const loadAllData = useCallback(async (): Promise<ObservationIOData[]> => {+ setIsLoading(true);+ setIsError(false);+ setFailedObservationIds([]);++ try {+ const observationItems = items.filter(+ (item) => item.node.type !== "TRACE",+ );++ // Separate cached vs uncached items+ const cachedResults: ObservationIOData[] = [];+ const uncachedItems: FlatLogItem[] = [];++ for (const item of observationItems) {+ const queryKey = getObservationQueryKey(+ item.node.id,+ traceId,+ projectId,+ item.node.startTime,+ );+ const cachedData = queryClient.getQueryData(queryKey) as+ | { input?: unknown; output?: unknown; metadata?: unknown }+ | undefined;++ if (cachedData) {+ // Build data from cache+ const baseData: ObservationIOData = {+ id: item.node.id,+ type: item.node.type,+ name: formatDisplayName(item.node),+ startTime: item.node.startTime,+ endTime: item.node.endTime,+ depth: item.node.depth,+ };+ if (cachedData.input !== null && cachedData.input !== undefined) {+ baseData.input = cachedData.input;+ }+ if (cachedData.output !== null && cachedData.output !== undefined) {+ baseData.output = cachedData.output;+ }+ if (+ cachedData.metadata !== null &&+ cachedData.metadata !== undefined+ ) {+ baseData.metadata = cachedData.metadata;+ }+ cachedResults.push(baseData);+ } else {+ uncachedItems.push(item);+ }+ }++ // Track failed observation IDs+ const failures: string[] = [];++ // Fetch uncached items in batches to avoid rate limiting+ const itemChunks = chunk(uncachedItems, FETCH_CONCURRENCY);+ const fetchedResults: ObservationIOData[] = [];++ for (const itemChunk of itemChunks) {+ const chunkResults = await Promise.all(+ itemChunk.map(async (item) => {+ try {+ const result = await utils.observations.byId.fetch({+ observationId: item.node.id,+ traceId,+ projectId,+ startTime: item.node.startTime,+ });++ const baseData: ObservationIOData = {+ id: item.node.id,+ type: item.node.type,+ name: formatDisplayName(item.node),+ startTime: item.node.startTime,+ endTime: item.node.endTime,+ depth: item.node.depth,+ };++ if (result.input !== null && result.input !== undefined) {+ baseData.input = result.input;+ }+ if (result.output !== null && result.output !== undefined) {+ baseData.output = result.output;+ }+ if (result.metadata !== null && result.metadata !== undefined) {+ baseData.metadata = result.metadata;+ }++ return baseData;+ } catch {+ // Track failure and return base data without I/O+ failures.push(item.node.id);+ return {+ id: item.node.id,+ type: item.node.type,+ name: formatDisplayName(item.node),+ startTime: item.node.startTime,+ endTime: item.node.endTime,+ depth: item.node.depth,+ } as ObservationIOData;+ }+ }),+ );+ fetchedResults.push(...chunkResults);+ }++ // Combine cached and fetched results+ const allResults = [...cachedResults, ...fetchedResults];++ // Sort to maintain original item order+ const idOrder = new Map(+ observationItems.map((item, i) => [item.node.id, i]),+ );+ allResults.sort(+ (a, b) => (idOrder.get(a.id) ?? 0) - (idOrder.get(b.id) ?? 0),+ );++ setData(allResults);+ setFailedObservationIds(failures);+ setIsLoading(false);+ return allResults;+ } catch {+ setIsError(true);+ setIsLoading(false);+ throw new Error("Failed to load observation data");+ }+ }, [items, traceId, projectId, utils, queryClient]);++ return {+ /** Cached/loaded data (null if not yet loaded) */+ data,+ /** Whether data is currently being loaded */+ isLoading,+ /** Whether an error occurred during loading */+ isError,+ /** IDs of observations that failed to load */+ failedObservationIds,+ /** Trigger loading all observation I/O data */+ loadAllData,+ /** Build data from tree + cache without fetching (for virtualized mode) */+ buildDataFromCache,+ /** Total number of observations */+ totalCount: items.filter((item) => item.node.type !== "TRACE").length,+ };+}diff --git a/web/src/components/trace2/components/TraceLogView/useLogViewColumns.tsx b/web/src/components/trace2/components/TraceLogView/useLogViewColumns.tsxnew file mode 100644index 0000000000..0b033ef71e--- /dev/null+++ b/web/src/components/trace2/components/TraceLogView/useLogViewColumns.tsx@@ -0,0 +1,87 @@+/**+ * Hook for defining log view table columns.+ *+ * Extracts column configuration from TraceLogView for cleaner separation+ * of concerns. Columns include observation name, depth, start time, and duration.+ */++import { useMemo } from "react";+import { type JSONTableViewColumn } from "@/src/components/trace2/components/_shared/JSONTableView";+import { type FlatLogItem } from "./log-view-types";+import { LogViewObservationCell } from "./LogViewObservationCell";+import { formatRelativeTime, formatDuration } from "./log-view-formatters";++export interface UseLogViewColumnsParams {+ /** Whether indent visualization is enabled */+ indentEnabled: boolean;+ /** Whether milliseconds are shown in time values */+ showMilliseconds: boolean;+ /** Project ID for data fetching */+ projectId: string;+ /** Trace ID for data fetching */+ traceId: string;+}++/**+ * Hook for defining log view table columns.+ */+export function useLogViewColumns({+ indentEnabled,+ showMilliseconds,+ projectId,+ traceId,+}: UseLogViewColumnsParams): JSONTableViewColumn<FlatLogItem>[] {+ return useMemo((): JSONTableViewColumn<FlatLogItem>[] => {+ return [+ {+ key: "observation",+ header: "Observation",+ width: "flex-1",+ render: (item) => (+ <LogViewObservationCell+ item={item}+ indentEnabled={indentEnabled}+ projectId={projectId}+ traceId={traceId}+ />+ ),+ },+ {+ key: "depth",+ header: "Depth",+ width: "w-12",+ align: "right" as const,+ render: (item) => (+ <span className="text-xs text-muted-foreground">+ {item.node.depth >= 0 ? `L${item.node.depth}` : "-"}+ </span>+ ),+ },+ {+ key: "start",+ header: "Start",+ width: showMilliseconds ? "w-20" : "w-12",+ align: "right" as const,+ render: (item) => (+ <span className="text-xs text-muted-foreground">+ {formatRelativeTime(+ item.node.startTimeSinceTrace,+ showMilliseconds,+ )}+ </span>+ ),+ },+ {+ key: "duration",+ header: "Duration",+ width: "w-16",+ align: "right" as const,+ render: (item) => (+ <span className="text-xs text-muted-foreground">+ {formatDuration(item.node.startTime, item.node.endTime)}+ </span>+ ),+ },+ ];+ }, [indentEnabled, showMilliseconds, projectId, traceId]);+}diff --git a/web/src/components/trace2/components/TraceLogView/useLogViewConfirmation.ts b/web/src/components/trace2/components/TraceLogView/useLogViewConfirmation.tsdeleted file mode 100644index 0e9457b962..0000000000--- a/web/src/components/trace2/components/TraceLogView/useLogViewConfirmation.ts+++ /dev/null@@ -1,80 +0,0 @@-/**- * useLogViewConfirmation - Hook for managing log view confirmation dialog state- *- * Handles the threshold-based confirmation logic for viewing traces with many observations.- * Consolidates related state (hasConfirmed, showDialog) and derived values (isDisabled, requiresConfirmation).- *- * Thresholds:- * - >150 observations: Show confirmation dialog before viewing- * - >350 observations: Disable log view entirely (performance concern)- */--import { useState, useEffect, useCallback } from "react";--export const LOG_VIEW_CONFIRMATION_THRESHOLD = 150;-export const LOG_VIEW_DISABLED_THRESHOLD = 350;--interface UseLogViewConfirmationParams {- observationCount: number;- traceId: string;-}--interface UseLogViewConfirmationReturn {- /** Whether log view is completely disabled (too many observations) */- isDisabled: boolean;- /** Whether confirmation is required before viewing */- requiresConfirmation: boolean;- /** Whether the confirmation dialog is open */- showDialog: boolean;- /** Set dialog open state */- setShowDialog: (show: boolean) => void;- /** Number of observations (for display in dialog) */- observationCount: number;- /**- * Attempt to switch to log tab. Returns true if allowed, false if confirmation needed.- * If confirmation is needed, opens the dialog automatically.- */- attemptLogView: () => boolean;- /** Confirm and allow log view (call after user confirms in dialog) */- confirmLogView: () => void;-}--export function useLogViewConfirmation({- observationCount,- traceId,-}: UseLogViewConfirmationParams): UseLogViewConfirmationReturn {- const [hasConfirmed, setHasConfirmed] = useState(false);- const [showDialog, setShowDialog] = useState(false);-- const isDisabled = observationCount > LOG_VIEW_DISABLED_THRESHOLD;- const requiresConfirmation =- observationCount > LOG_VIEW_CONFIRMATION_THRESHOLD && !isDisabled;-- // Reset confirmation state when trace changes- useEffect(() => {- setHasConfirmed(false);- }, [traceId]);-- const attemptLogView = useCallback(() => {- if (requiresConfirmation && !hasConfirmed) {- setShowDialog(true);- return false;- }- return true;- }, [requiresConfirmation, hasConfirmed]);-- const confirmLogView = useCallback(() => {- setHasConfirmed(true);- setShowDialog(false);- }, []);-- return {- isDisabled,- requiresConfirmation,- showDialog,- setShowDialog,- observationCount,- attemptLogView,- confirmLogView,- };-}diff --git a/web/src/components/trace2/components/TraceLogView/useLogViewDownload.ts b/web/src/components/trace2/components/TraceLogView/useLogViewDownload.tsnew file mode 100644index 0000000000..b376c615b7--- /dev/null+++ b/web/src/components/trace2/components/TraceLogView/useLogViewDownload.ts@@ -0,0 +1,180 @@+/**+ * Hook for download and copy JSON functionality in LogView.+ *+ * Handles:+ * - Copy to clipboard (non-virtualized mode)+ * - Download as JSON file (both modes)+ * - Loading state management+ */++import { useState, useCallback } from "react";+import { toast } from "sonner";+import { copyTextToClipboard } from "@/src/utils/clipboard";+import { type ObservationIOData } from "./useLogViewAllObservationsIO";++export interface UseLogViewDownloadParams {+ /** Trace ID for filename */+ traceId: string;+ /** Whether to use cached I/O only (vs loading all data) */+ isDownloadCacheOnly: boolean;+ /** Already loaded observation data (null if not loaded) */+ allObservationsData: ObservationIOData[] | null;+ /** Whether data is being loaded by useLogViewAllObservationsIO */+ isLoadingAllData: boolean;+ /** IDs of observations that failed to load */+ failedObservationIds: string[];+ /** Load all observation data (uses cache where available) */+ loadAllData: () => Promise<ObservationIOData[]>;+ /** Build data from tree + cache without fetching (for cache-only mode) */+ buildDataFromCache: () => ObservationIOData[];+}++export interface UseLogViewDownloadReturn {+ /** Copy JSON to clipboard handler */+ handleCopyJson: () => Promise<void>;+ /** Download JSON file handler */+ handleDownloadJson: () => Promise<void>;+ /** Whether download/copy operation is in progress */+ isDownloadOrCopyLoading: boolean;+}++/**+ * Hook for managing download and copy JSON functionality.+ */+export function useLogViewDownload({+ traceId,+ isDownloadCacheOnly,+ allObservationsData,+ isLoadingAllData,+ failedObservationIds,+ loadAllData,+ buildDataFromCache,+}: UseLogViewDownloadParams): UseLogViewDownloadReturn {+ // Track if we're actively loading for download+ const [isDownloadLoading, setIsDownloadLoading] = useState(false);++ // Helper to download JSON data+ const downloadJsonData = useCallback(+ (data: unknown) => {+ const blob = new Blob([JSON.stringify(data, null, 2)], {+ type: "application/json",+ });+ const url = URL.createObjectURL(blob);+ const a = document.createElement("a");+ a.href = url;+ a.download = `trace-${traceId}.json`;+ a.click();+ URL.revokeObjectURL(url);+ },+ [traceId],+ );++ // Copy JSON handler - uses cache only or loads all based on threshold+ const handleCopyJson = useCallback(async () => {+ if (isDownloadCacheOnly) {+ // Cache-only mode: build from tree + cache (no fetching)+ setIsDownloadLoading(true);+ setTimeout(() => {+ const data = buildDataFromCache();+ void copyTextToClipboard(JSON.stringify(data, null, 2));+ toast.success("Copied to clipboard (cache only)");+ setIsDownloadLoading(false);+ }, 0);+ } else {+ // Load all mode: fetch all data if needed+ if (allObservationsData) {+ void copyTextToClipboard(JSON.stringify(allObservationsData, null, 2));+ // Show warning if some observations failed to load+ if (failedObservationIds.length > 0) {+ toast.warning(+ `Copied to clipboard. ${failedObservationIds.length} observation${failedObservationIds.length === 1 ? "" : "s"} failed to load and ${failedObservationIds.length === 1 ? "is" : "are"} missing I/O data.`,+ );+ } else {+ toast.success("Copied to clipboard");+ }+ } else {+ setIsDownloadLoading(true);+ try {+ const data = await loadAllData();+ void copyTextToClipboard(JSON.stringify(data, null, 2));+ // Check for failures after loading+ if (failedObservationIds.length > 0) {+ toast.warning(+ `Copied to clipboard. ${failedObservationIds.length} observation${failedObservationIds.length === 1 ? "" : "s"} failed to load and ${failedObservationIds.length === 1 ? "is" : "are"} missing I/O data.`,+ );+ } else {+ toast.success("Copied to clipboard");+ }+ } finally {+ setIsDownloadLoading(false);+ }+ }+ }+ }, [+ isDownloadCacheOnly,+ allObservationsData,+ loadAllData,+ buildDataFromCache,+ failedObservationIds,+ ]);++ // Download JSON handler - uses cache only or loads all based on threshold+ const handleDownloadJson = useCallback(async () => {+ if (isDownloadCacheOnly) {+ // Cache-only mode: build from tree + cache (no fetching)+ setIsDownloadLoading(true);+ // Use setTimeout to allow spinner to render before potentially heavy operation+ setTimeout(() => {+ const data = buildDataFromCache();+ downloadJsonData(data);+ toast.success("Downloaded trace data (cache only)");+ setIsDownloadLoading(false);+ }, 0);+ } else {+ // Load all mode: fetch all data if needed+ if (allObservationsData) {+ downloadJsonData(allObservationsData);+ // Show warning if some observations failed to load+ if (failedObservationIds.length > 0) {+ toast.warning(+ `Downloaded trace data. ${failedObservationIds.length} observation${failedObservationIds.length === 1 ? "" : "s"} failed to load and ${failedObservationIds.length === 1 ? "is" : "are"} missing I/O data.`,+ );+ } else {+ toast.success("Downloaded trace data");+ }+ } else {+ setIsDownloadLoading(true);+ try {+ const data = await loadAllData();+ downloadJsonData(data);+ // Check for failures after loading+ if (failedObservationIds.length > 0) {+ toast.warning(+ `Downloaded trace data. ${failedObservationIds.length} observation${failedObservationIds.length === 1 ? "" : "s"} failed to load and ${failedObservationIds.length === 1 ? "is" : "are"} missing I/O data.`,+ );+ } else {+ toast.success("Downloaded trace data");+ }+ } finally {+ setIsDownloadLoading(false);+ }+ }+ }+ }, [+ isDownloadCacheOnly,+ allObservationsData,+ loadAllData,+ buildDataFromCache,+ downloadJsonData,+ failedObservationIds,+ ]);++ // Loading state for download button+ const isDownloadOrCopyLoading = isDownloadLoading || isLoadingAllData;++ return {+ handleCopyJson,+ handleDownloadJson,+ isDownloadOrCopyLoading,+ };+}diff --git a/web/src/components/trace2/components/TraceLogView/useLogViewObservationIO.ts b/web/src/components/trace2/components/TraceLogView/useLogViewObservationIO.tsnew file mode 100644index 0000000000..78b4d61e6d--- /dev/null+++ b/web/src/components/trace2/components/TraceLogView/useLogViewObservationIO.ts@@ -0,0 +1,96 @@+/**+ * Hook for lazy-loading observation I/O data.+ *+ * Only fetches when `enabled` is true (row is expanded).+ * Uses staleTime: Infinity to cache results indefinitely within the session.+ */++import { useMemo } from "react";+import { useQueryClient } from "@tanstack/react-query";+import { api } from "@/src/utils/api";+import { type FlatLogItem } from "./log-view-types";++export interface UseLogViewObservationIOParams {+ observationId: string;+ traceId: string;+ projectId: string;+ startTime: Date;+ /** Only fetch when true (row is expanded) */+ enabled: boolean;+}++/**+ * Fetches observation I/O data (input, output, metadata) lazily.+ *+ * @param params - Parameters including observationId, traceId, projectId, startTime, and enabled flag+ * @returns Query result with observation data, loading state, and error state+ */+export function useLogViewObservationIO({+ observationId,+ traceId,+ projectId,+ startTime,+ enabled,+}: UseLogViewObservationIOParams) {+ return api.observations.byId.useQuery(+ {+ observationId,+ traceId,+ projectId,+ startTime,+ },+ {+ enabled,+ // Cache indefinitely within session - data doesn't change+ staleTime: Infinity,+ // Don't refetch on window focus+ refetchOnWindowFocus: false,+ },+ );+}++/**+ * Hook to count how many observations have their I/O data loaded in the cache.+ * Useful for showing progress indicator in virtualized mode.+ */+export function useObservationIOLoadedCount({+ items,+ traceId,+ projectId,+}: {+ items: FlatLogItem[];+ traceId: string;+ projectId: string;+}): { loaded: number; total: number } {+ const queryClient = useQueryClient();++ return useMemo(() => {+ // Filter out TRACE type (which doesn't have observation I/O)+ const observationItems = items.filter((item) => item.node.type !== "TRACE");+ const total = observationItems.length;++ let loaded = 0;+ for (const item of observationItems) {+ // Build the same query key that tRPC uses+ const queryKey = [+ ["observations", "byId"],+ {+ input: {+ observationId: item.node.id,+ traceId,+ projectId,+ startTime: item.node.startTime,+ },+ type: "query",+ },+ ];++ const state = queryClient.getQueryState(queryKey);+ if (state?.status === "success") {+ loaded++;+ }+ }++ return { loaded, total };+ }, [items, traceId, projectId, queryClient]);+}diff --git a/web/src/components/trace2/components/TraceLogView/useLogViewPreferences.ts b/web/src/components/trace2/components/TraceLogView/useLogViewPreferences.tsnew file mode 100644index 0000000000..81dc84890b--- /dev/null+++ b/web/src/components/trace2/components/TraceLogView/useLogViewPreferences.ts@@ -0,0 +1,27 @@+/**+ * Hook for persisting LogView display preferences to localStorage.+ *+ * Preferences:+ * - indentEnabled: Show tree depth via visual indentation+ * - showMilliseconds: Display milliseconds in time values+ */++import useLocalStorage from "@/src/components/useLocalStorage";++export function useLogViewPreferences() {+ const [indentEnabled, setIndentEnabled] = useLocalStorage(+ "logView-indentEnabled",+ false,+ );+ const [showMilliseconds, setShowMilliseconds] = useLocalStorage(+ "logView-showMilliseconds",+ false,+ );++ return {+ indentEnabled,+ setIndentEnabled,+ showMilliseconds,+ setShowMilliseconds,+ };+}diff --git a/web/src/components/trace2/components/TraceSearchList.tsx b/web/src/components/trace2/components/TraceSearchList.tsxindex 49d6e24322..8d903aa3b1 100644--- a/web/src/components/trace2/components/TraceSearchList.tsx+++ b/web/src/components/trace2/components/TraceSearchList.tsx@@ -10,6 +10,7 @@ import { useMemo } from "react";import { useTraceData } from "../contexts/TraceDataContext";import { useSearch } from "../contexts/SearchContext";import { useSelection } from "../contexts/SelectionContext";+import { useHandlePrefetchObservation } from "../hooks/useHandlePrefetchObservation";import { VirtualizedList } from "./_shared/VirtualizedList";import { TraceSearchListItem } from "./TraceSearchListItem";import { Button } from "@/src/components/ui/button";@@ -19,6 +20,7 @@ export function TraceSearchList() {const { searchItems } = useTraceData();const { searchQuery, setSearchInputValue } = useSearch();const { selectedNodeId, setSelectedNodeId } = useSelection();+ const { handleHover } = useHandlePrefetchObservation();// Co-located filtering - only this component re-renders on search query changeconst searchResults = useMemo(() => {@@ -70,6 +72,7 @@ export function TraceSearchList() {item={item}isSelected={isSelected}onSelect={onSelect}+ onHover={() => handleHover(item.node)}/>)}/>diff --git a/web/src/components/trace2/components/TraceSearchListItem.tsx b/web/src/components/trace2/components/TraceSearchListItem.tsxindex 9d7754c16b..cae01a550b 100644--- a/web/src/components/trace2/components/TraceSearchListItem.tsx+++ b/web/src/components/trace2/components/TraceSearchListItem.tsx@@ -17,12 +17,14 @@ interface TraceSearchListItemProps {item: TraceSearchListItem;isSelected: boolean;onSelect: () => void;+ onHover?: () => void;}export function TraceSearchListItem({item,isSelected,onSelect,+ onHover,}: TraceSearchListItemProps) {const { node, parentTotalCost, parentTotalDuration } = item;const { comments } = useTraceData();@@ -39,6 +41,7 @@ export function TraceSearchListItem({return (<divonClick={onSelect}+ onMouseEnter={onHover}className={cn("flex cursor-pointer items-start gap-2 px-2 py-1.5 transition-colors hover:bg-muted/50",isSelected && "bg-muted",diff --git a/web/src/components/trace2/components/TraceTimeline/TimelineBar.tsx b/web/src/components/trace2/components/TraceTimeline/TimelineBar.tsxindex d03ae16dce..04e42ce7ac 100644--- a/web/src/components/trace2/components/TraceTimeline/TimelineBar.tsx+++ b/web/src/components/trace2/components/TraceTimeline/TimelineBar.tsx@@ -18,6 +18,7 @@ export function TimelineBar({metrics,isSelected,onSelect,+ onHover,showDuration,showCostTokens,showScores,@@ -41,6 +42,7 @@ export function TimelineBar({<divclassName="group my-0.5 flex w-full min-w-fit cursor-pointer flex-row items-center"onClick={onSelect}+ onMouseEnter={onHover}><divclassName={cn(@@ -125,6 +127,7 @@ export function TimelineBar({<divclassName="group my-0.5 flex w-full min-w-fit cursor-pointer flex-row items-center"onClick={onSelect}+ onMouseEnter={onHover}><div className="relative" style={{ marginLeft: `${startOffset}px` }}><divdiff --git a/web/src/components/trace2/components/TraceTimeline/TimelineRow.tsx b/web/src/components/trace2/components/TraceTimeline/TimelineRow.tsxindex d62ad30926..e0d6d88308 100644--- a/web/src/components/trace2/components/TraceTimeline/TimelineRow.tsx+++ b/web/src/components/trace2/components/TraceTimeline/TimelineRow.tsx@@ -14,6 +14,7 @@ export function TimelineRow({item,isSelected,onSelect,+ onHover,onToggleCollapse,hasChildren,isCollapsed,@@ -95,6 +96,7 @@ export function TimelineRow({metrics={metrics}isSelected={isSelected}onSelect={onSelect}+ onHover={onHover}showDuration={showDuration}showCostTokens={showCostTokens}showScores={showScores}diff --git a/web/src/components/trace2/components/TraceTimeline/index.tsx b/web/src/components/trace2/components/TraceTimeline/index.tsxindex f2619a0c73..a0f3568f9f 100644--- a/web/src/components/trace2/components/TraceTimeline/index.tsx+++ b/web/src/components/trace2/components/TraceTimeline/index.tsx@@ -8,6 +8,7 @@ import { useVirtualizer } from "@tanstack/react-virtual";import { useTraceData } from "../../contexts/TraceDataContext";import { useSelection } from "../../contexts/SelectionContext";import { useViewPreferences } from "../../contexts/ViewPreferencesContext";+import { useHandlePrefetchObservation } from "../../hooks/useHandlePrefetchObservation";import { flattenTreeWithTimelineMetrics } from "./timeline-flattening";import { calculateStepSize, SCALE_WIDTH } from "./timeline-calculations";import { TimelineScale } from "./TimelineScale";@@ -24,6 +25,7 @@ export function TraceTimeline() {showComments,colorCodeMetrics,} = useViewPreferences();+ const { handleHover } = useHandlePrefetchObservation();const timeIndexRef = useRef<HTMLDivElement>(null);const contentRef = useRef<HTMLDivElement>(null);@@ -187,6 +189,7 @@ export function TraceTimeline() {item={item}isSelected={isSelected}onSelect={() => setSelectedNodeId(nodeId)}+ onHover={() => handleHover(item.node)}onToggleCollapse={() => toggleCollapsed(nodeId)}hasChildren={hasChildren}isCollapsed={isCollapsed}diff --git a/web/src/components/trace2/components/TraceTimeline/types.ts b/web/src/components/trace2/components/TraceTimeline/types.tsindex a132ef8b84..131017c276 100644--- a/web/src/components/trace2/components/TraceTimeline/types.ts+++ b/web/src/components/trace2/components/TraceTimeline/types.ts@@ -31,6 +31,7 @@ export interface TimelineBarProps {metrics: TimelineMetrics;isSelected: boolean;onSelect: () => void;+ onHover?: () => void;// View preferencesshowDuration: boolean;showCostTokens: boolean;@@ -67,6 +68,7 @@ export interface TimelineRowProps {item: FlatTimelineItem;isSelected: boolean;onSelect: () => void;+ onHover?: () => void;onToggleCollapse: () => void;hasChildren: boolean;isCollapsed: boolean;diff --git a/web/src/components/trace2/components/TraceTree.tsx b/web/src/components/trace2/components/TraceTree.tsxindex 9437df78e6..b8d7b87c3c 100644--- a/web/src/components/trace2/components/TraceTree.tsx+++ b/web/src/components/trace2/components/TraceTree.tsx@@ -14,12 +14,14 @@ import { VirtualizedTreeNodeWrapper } from "./_shared/VirtualizedTreeNodeWrapperimport { SpanContent } from "./SpanContent";import { useTraceData } from "../contexts/TraceDataContext";import { useSelection } from "../contexts/SelectionContext";+import { useHandlePrefetchObservation } from "../hooks/useHandlePrefetchObservation";import { type TreeNode } from "../lib/types";export function TraceTree() {const { tree, comments } = useTraceData();const { selectedNodeId, setSelectedNodeId, collapsedNodes, toggleCollapsed } =useSelection();+ const { handleHover } = useHandlePrefetchObservation();// Calculate root totals for heatmap color scaling// These values are used as the "max" reference for all nodes@@ -60,6 +62,7 @@ export function TraceTree() {parentTotalDuration={rootTotalDuration}commentCount={comments.get(typedNode.id)}onSelect={onSelect}+ onHover={() => handleHover(typedNode)}/></VirtualizedTreeNodeWrapper>);diff --git a/web/src/components/trace2/components/_shared/JSONTableView/JSONTableView.tsx b/web/src/components/trace2/components/_shared/JSONTableView/JSONTableView.tsxnew file mode 100644index 0000000000..378d2505f7--- /dev/null+++ b/web/src/components/trace2/components/_shared/JSONTableView/JSONTableView.tsx@@ -0,0 +1,259 @@+/**+ * JSONTableView - Generic virtualized table with customizable columns.+ *+ * Features:+ * - Conditional virtualization based on `virtualized` prop+ * - Customizable columns with render functions+ * - Expandable rows (controlled/uncontrolled)+ * - Sticky header support+ * - Row prefix support (for tree indentation)+ */++import { useState, useMemo, useRef, useCallback, useEffect } from "react";+import { useVirtualizer } from "@tanstack/react-virtual";+import { cn } from "@/src/utils/tailwind";+import { type JSONTableViewProps } from "./json-table-view-types";+import { JSONTableViewHeader } from "./JSONTableViewHeader";+import { JSONTableViewRow } from "./JSONTableViewRow";++// Default row heights for virtualization+const DEFAULT_COLLAPSED_ROW_HEIGHT = 28;+const DEFAULT_EXPANDED_ROW_HEIGHT = 150;++/**+ * Generic virtualized table component.+ */+export function JSONTableView<T>({+ items,+ columns,+ getItemKey,+ expandable = false,+ renderExpanded,+ expandedKeys: controlledExpandedKeys,+ onExpandedKeysChange,+ virtualized = false,+ collapsedRowHeight = DEFAULT_COLLAPSED_ROW_HEIGHT,+ expandedRowHeight = DEFAULT_EXPANDED_ROW_HEIGHT,+ stickyHeaderContent,+ onVisibleItemsChange,+ renderRowPrefix,+ overscan = 100,+ className,+}: JSONTableViewProps<T>) {+ // Internal expand state (uncontrolled mode)+ const [internalExpandedKeys, setInternalExpandedKeys] = useState<Set<string>>(+ new Set(),+ );++ // Determine if controlled or uncontrolled+ const isControlled = controlledExpandedKeys !== undefined;+ const expandedKeys = isControlled+ ? controlledExpandedKeys+ : internalExpandedKeys;++ // Refs for scroll containers+ const parentRef = useRef<HTMLDivElement>(null);+ const scrollContainerRef = useRef<HTMLDivElement>(null);++ // Track scroll position for non-virtualized sticky header+ const [scrollTopIndex, setScrollTopIndex] = useState(0);++ // Toggle expand/collapse for a row+ const handleToggle = useCallback(+ (key: string) => {+ const updateKeys = (prev: Set<string>) => {+ const next = new Set(prev);+ if (next.has(key)) {+ next.delete(key);+ } else {+ next.add(key);+ }+ return next;+ };++ if (isControlled) {+ onExpandedKeysChange?.(updateKeys(expandedKeys));+ } else {+ setInternalExpandedKeys(updateKeys);+ }+ },+ [isControlled, expandedKeys, onExpandedKeysChange],+ );++ // Estimate row size based on expand state+ const estimateSize = useCallback(+ (index: number) => {+ const item = items[index];+ if (!item) return collapsedRowHeight;+ const key = getItemKey(item);+ return expandedKeys.has(key) ? expandedRowHeight : collapsedRowHeight;+ },+ [items, getItemKey, expandedKeys, collapsedRowHeight, expandedRowHeight],+ );++ // Set up virtualizer (only used when virtualized is true)+ const rowVirtualizer = useVirtualizer({+ count: virtualized ? items.length : 0,+ getScrollElement: () => parentRef.current,+ estimateSize,+ overscan: overscan,+ measureElement:+ typeof window !== "undefined"+ ? (element) => element.getBoundingClientRect().height+ : undefined,+ enabled: virtualized,+ });++ // Track topmost visible item for sticky header (virtualized mode)+ const virtualizedTopmostIndex = useMemo(() => {+ if (!virtualized) return 0;+ const virtualItems = rowVirtualizer.getVirtualItems();+ return virtualItems[0]?.index ?? 0;+ }, [virtualized, rowVirtualizer]);++ // Track scroll position for non-virtualized sticky header+ useEffect(() => {+ if (virtualized || !scrollContainerRef.current) return;++ const container = scrollContainerRef.current;+ const handleScroll = () => {+ const rows = container.querySelectorAll("[data-row-index]");++ for (const row of rows) {+ const rect = row.getBoundingClientRect();+ const containerRect = container.getBoundingClientRect();+ const relativeTop = rect.top - containerRect.top;++ if (relativeTop >= -rect.height / 2) {+ const index = parseInt(row.getAttribute("data-row-index") ?? "0", 10);+ setScrollTopIndex(index);+ break;+ }+ }+ };++ container.addEventListener("scroll", handleScroll);+ return () => container.removeEventListener("scroll", handleScroll);+ }, [virtualized]);++ // Compute topmost item and index+ const topmostIndex = virtualized ? virtualizedTopmostIndex : scrollTopIndex;+ const topmostItem = items[topmostIndex] ?? null;++ // Notify about visible items changes (for viewport-based prefetching)+ useEffect(() => {+ if (!virtualized || !onVisibleItemsChange) return;++ const virtualItems = rowVirtualizer.getVirtualItems();+ const visibleItems = virtualItems+ .map((vi) => items[vi.index])+ .filter((item): item is T => item !== undefined);++ if (visibleItems.length > 0) {+ onVisibleItemsChange(visibleItems);+ }+ }, [virtualized, rowVirtualizer, items, onVisibleItemsChange]);++ // Check if we have items+ const hasItems = items.length > 0;+ const hasExpandIcon = expandable;++ return (+ <div+ className={cn("flex h-full w-full flex-col overflow-hidden", className)}+ >+ {/* Sticky header showing topmost visible item */}+ {hasItems && stickyHeaderContent && (+ <div className="flex-shrink-0">+ {stickyHeaderContent(topmostItem, topmostIndex)}+ </div>+ )}++ {/* Table header with column labels */}+ {hasItems && (+ <JSONTableViewHeader columns={columns} hasExpandIcon={hasExpandIcon} />+ )}++ {/* Virtualized list */}+ {hasItems && virtualized && (+ <div ref={parentRef} className="flex-1 overflow-y-scroll">+ <div+ style={{+ height: `${rowVirtualizer.getTotalSize()}px`,+ width: "100%",+ position: "relative",+ }}+ >+ {rowVirtualizer.getVirtualItems().map((virtualRow) => {+ const item = items[virtualRow.index];+ if (!item) return null;++ const key = getItemKey(item);+ const isExpanded = expandedKeys.has(key);++ return (+ <div+ key={key}+ data-index={virtualRow.index}+ ref={rowVirtualizer.measureElement}+ style={{+ position: "absolute",+ top: 0,+ left: 0,+ width: "100%",+ transform: `translateY(${virtualRow.start}px)`,+ }}+ >+ <JSONTableViewRow+ item={item}+ itemKey={key}+ index={virtualRow.index}+ columns={columns}+ isExpanded={isExpanded}+ expandable={expandable}+ onToggle={() => handleToggle(key)}+ renderExpanded={renderExpanded}+ renderRowPrefix={renderRowPrefix}+ />+ </div>+ );+ })}+ </div>+ </div>+ )}++ {/* Non-virtualized list */}+ {hasItems && !virtualized && (+ <div ref={scrollContainerRef} className="flex-1 overflow-y-auto">+ {items.map((item, index) => {+ const key = getItemKey(item);+ const isExpanded = expandedKeys.has(key);++ return (+ <div key={key} data-row-index={index}>+ <JSONTableViewRow+ item={item}+ itemKey={key}+ index={index}+ columns={columns}+ isExpanded={isExpanded}+ expandable={expandable}+ onToggle={() => handleToggle(key)}+ renderExpanded={renderExpanded}+ renderRowPrefix={renderRowPrefix}+ />+ </div>+ );+ })}+ </div>+ )}++ {/* Empty state */}+ {!hasItems && (+ <div className="flex flex-1 items-center justify-center">+ <div className="text-sm text-muted-foreground">No items</div>+ </div>+ )}+ </div>+ );+}diff --git a/web/src/components/trace2/components/_shared/JSONTableView/JSONTableViewHeader.tsx b/web/src/components/trace2/components/_shared/JSONTableView/JSONTableViewHeader.tsxnew file mode 100644index 0000000000..16ded898c1--- /dev/null+++ b/web/src/components/trace2/components/_shared/JSONTableView/JSONTableViewHeader.tsx@@ -0,0 +1,42 @@+/**+ * JSONTableViewHeader - Table header generated from column definitions.+ *+ * Renders column headers with proper alignment and spacing.+ */++import { memo } from "react";+import { cn } from "@/src/utils/tailwind";+import { type JSONTableViewHeaderProps } from "./json-table-view-types";++/**+ * Table header component that renders column labels.+ */+function JSONTableViewHeaderInner<T>({+ columns,+ hasExpandIcon,+}: JSONTableViewHeaderProps<T>) {+ return (+ <div className="flex min-h-6 items-center gap-2 border-b border-border bg-muted/50 px-3 py-0.5 text-xs font-medium text-muted-foreground">+ {/* Spacer for expand icon (aligns with chevron in rows) */}+ {hasExpandIcon && <div className="w-4" />}++ {/* Column headers */}+ {columns.map((column) => (+ <div+ key={column.key}+ className={cn(+ "flex-shrink-0",+ column.width ?? "flex-1",+ column.align === "right" && "text-right",+ )}+ >+ {column.header}+ </div>+ ))}+ </div>+ );+}++export const JSONTableViewHeader = memo(+ JSONTableViewHeaderInner,+) as typeof JSONTableViewHeaderInner;diff --git a/web/src/components/trace2/components/_shared/JSONTableView/JSONTableViewRow.tsx b/web/src/components/trace2/components/_shared/JSONTableView/JSONTableViewRow.tsxnew file mode 100644index 0000000000..1cbd6c05e8--- /dev/null+++ b/web/src/components/trace2/components/_shared/JSONTableView/JSONTableViewRow.tsx@@ -0,0 +1,98 @@+/**+ * JSONTableViewRow - Row component for JSONTableView.+ *+ * Renders a single row with columns and handles expand/collapse.+ */++import { memo } from "react";+import { ChevronRight, ChevronDown } from "lucide-react";+import { cn } from "@/src/utils/tailwind";+import { useClickWithoutSelection } from "@/src/hooks/useClickWithoutSelection";+import { type JSONTableViewRowProps } from "./json-table-view-types";++/**+ * Row component that renders column cells and handles expand/collapse.+ */+function JSONTableViewRowInner<T>({+ item,+ itemKey,+ index,+ columns,+ isExpanded,+ expandable,+ onToggle,+ renderExpanded,+ renderRowPrefix,+}: JSONTableViewRowProps<T>) {+ // Use click-without-selection to allow text selection while still supporting expand+ const { props: clickProps } = useClickWithoutSelection({+ onClick: onToggle,+ enabled: expandable,+ });++ const ChevronIcon = isExpanded ? ChevronDown : ChevronRight;+ const expandedContentId = `expanded-content-${itemKey}`;++ return (+ <div className="border-b border-border bg-background">+ {/* Preview row - always visible */}+ <div+ className={cn(+ "flex min-h-6 items-center gap-2 px-3 py-0.5",+ expandable && "cursor-pointer hover:bg-muted/50",+ isExpanded && "border-b border-border/50 bg-muted/30",+ )}+ {...(expandable ? clickProps : {})}+ role={expandable ? "button" : undefined}+ tabIndex={expandable ? 0 : undefined}+ aria-expanded={expandable ? isExpanded : undefined}+ aria-controls={expandable ? expandedContentId : undefined}+ onKeyDown={+ expandable+ ? (e) => {+ if (e.key === "Enter" || e.key === " ") {+ e.preventDefault();+ onToggle();+ }+ }+ : undefined+ }+ >+ {/* Prefix content (e.g., tree indentation) */}+ {renderRowPrefix && renderRowPrefix(item, isExpanded)}++ {/* Expand icon */}+ {expandable && (+ <ChevronIcon className="h-3.5 w-3.5 flex-shrink-0 text-muted-foreground" />+ )}++ {/* Column cells */}+ {columns.map((column) => (+ <div+ key={column.key}+ className={cn(+ "flex-shrink-0 text-sm",+ column.width ?? "min-w-0 flex-1",+ column.align === "right" && "text-right",+ // Truncate flex-1 columns+ column.width === "flex-1" && "truncate",+ )}+ >+ {column.render(item, index)}+ </div>+ ))}+ </div>++ {/* Expanded content */}+ {isExpanded && renderExpanded && (+ <div id={expandedContentId} className="w-full">+ {renderExpanded(item)}+ </div>+ )}+ </div>+ );+}++export const JSONTableViewRow = memo(+ JSONTableViewRowInner,+) as typeof JSONTableViewRowInner;diff --git a/web/src/components/trace2/components/_shared/JSONTableView/index.ts b/web/src/components/trace2/components/_shared/JSONTableView/index.tsnew file mode 100644index 0000000000..f63e0196db--- /dev/null+++ b/web/src/components/trace2/components/_shared/JSONTableView/index.ts@@ -0,0 +1,28 @@+/**+ * JSONTableView - Generic virtualized table with customizable columns.+ *+ * @example+ * ```tsx+ * <JSONTableView+ * items={data}+ * getItemKey={(item) => item.id}+ * columns={[+ * { key: "name", header: "Name", width: "flex-1", render: (item) => item.name },+ * { key: "value", header: "Value", width: "w-20", align: "right", render: (item) => item.value },+ * ]}+ * expandable+ * renderExpanded={(item) => <ExpandedContent item={item} />}+ * virtualized={data.length > 100}+ * />+ * ```+ */++export { JSONTableView } from "./JSONTableView";+export { JSONTableViewHeader } from "./JSONTableViewHeader";+export { JSONTableViewRow } from "./JSONTableViewRow";+export type {+ JSONTableViewProps,+ JSONTableViewColumn,+ JSONTableViewRowProps,+ JSONTableViewHeaderProps,+} from "./json-table-view-types";diff --git a/web/src/components/trace2/components/_shared/JSONTableView/json-table-view-types.ts b/web/src/components/trace2/components/_shared/JSONTableView/json-table-view-types.tsnew file mode 100644index 0000000000..01d7d31793--- /dev/null+++ b/web/src/components/trace2/components/_shared/JSONTableView/json-table-view-types.ts@@ -0,0 +1,98 @@+/**+ * JSONTableView Types+ *+ * Generic types for the JSONTableView component - a domain-agnostic+ * virtualized table with customizable columns.+ */++import { type ReactNode } from "react";++/**+ * Column definition for JSONTableView.+ * @template T - The type of items in the table+ */+export interface JSONTableViewColumn<T> {+ /** Unique key for the column */+ key: string;+ /** Header content - string or ReactNode */+ header: string | ReactNode;+ /** Tailwind width class (e.g., "w-20", "flex-1", "w-16") */+ width?: string;+ /** Text alignment - defaults to "left" */+ align?: "left" | "right";+ /** Render function for cell content */+ render: (item: T, index: number) => ReactNode;+}++/**+ * Props for JSONTableView component.+ * @template T - The type of items in the table+ */+export interface JSONTableViewProps<T> {+ /** Array of items to display */+ items: T[];+ /** Column definitions */+ columns: JSONTableViewColumn<T>[];+ /** Function to get unique key for each item */+ getItemKey: (item: T) => string;++ // Expandable rows (controlled/uncontrolled pattern)+ /** Enable expand/collapse functionality */+ expandable?: boolean;+ /** Render function for expanded content */+ renderExpanded?: (item: T) => ReactNode;+ /** Controlled mode: set of expanded item keys */+ expandedKeys?: Set<string>;+ /** Controlled mode: callback when expanded keys change */+ onExpandedKeysChange?: (keys: Set<string>) => void;++ // Virtualization+ /** Enable virtualization for large lists */+ virtualized?: boolean;+ /** Row height when collapsed (for virtualization estimates) */+ collapsedRowHeight?: number;+ /** Row height when expanded (for virtualization estimates) */+ expandedRowHeight?: number;+ /** Number of rows to render above and below the visible area */+ overscan?: number;++ // Sticky header+ /** Render function for sticky header showing current visible item */+ stickyHeaderContent?: (topmostItem: T | null, index: number) => ReactNode;++ // Callbacks+ /** Called when visible items change (for viewport-based prefetching) */+ onVisibleItemsChange?: (items: T[]) => void;++ // Custom row rendering+ /** Render content before columns (e.g., tree indentation) */+ renderRowPrefix?: (item: T, isExpanded: boolean) => ReactNode;++ // Styling+ /** Additional class name for the container */+ className?: string;+}++/**+ * Internal props for JSONTableViewRow component.+ */+export interface JSONTableViewRowProps<T> {+ item: T;+ /** Unique key for the item (used for ARIA attributes) */+ itemKey: string;+ index: number;+ columns: JSONTableViewColumn<T>[];+ isExpanded: boolean;+ expandable: boolean;+ onToggle: () => void;+ renderExpanded?: (item: T) => ReactNode;+ renderRowPrefix?: (item: T, isExpanded: boolean) => ReactNode;+}++/**+ * Internal props for JSONTableViewHeader component.+ */+export interface JSONTableViewHeaderProps<T> {+ columns: JSONTableViewColumn<T>[];+ hasExpandIcon: boolean;+}diff --git a/web/src/components/trace2/config/trace-view-config.ts b/web/src/components/trace2/config/trace-view-config.tsnew file mode 100644index 0000000000..73c0f9b411--- /dev/null+++ b/web/src/components/trace2/config/trace-view-config.ts@@ -0,0 +1,71 @@+/**+ * Configuration constants for trace2 views.+ *+ * Centralizes thresholds, dimensions, and behavior settings+ * for easier tuning and maintenance.+ */++export const TRACE_VIEW_CONFIG = {+ /**+ * Log View configuration+ */+ logView: {+ /**+ * Number of observations above which virtualization is enabled.+ * Virtualization renders only visible rows for better performance.+ */+ virtualizationThreshold: 350,++ /**+ * Number of observations above which download uses cached I/O only.+ * Above this threshold, only expanded observations include full I/O data.+ */+ downloadThreshold: 350,++ /**+ * Row heights for virtualization calculations+ */+ rowHeight: {+ collapsed: 28,+ expanded: 150,+ },++ /**+ * Maximum tree depth for indent visualization.+ * Deeper trees disable indent to prevent excessive horizontal space.+ */+ maxIndentDepth: 5,++ /**+ * Indent size per level (in pixels)+ */+ indentPx: 12,++ /**+ * Prefetching behavior for viewport-based observation loading+ */+ prefetch: {+ /**+ * Margin around viewport for triggering prefetch (e.g., "100px")+ * Observations within this margin will be prefetched.+ */+ rootMargin: "100px",++ /**+ * Debounce delay in milliseconds before triggering prefetch.+ * Prevents request storms during fast scrolling.+ */+ debounceMs: 250,+ },++ /**+ * Batch fetching configuration for loading all observations+ */+ batchFetch: {+ /**+ * Maximum number of concurrent observation fetch requests+ */+ concurrency: 10,+ },+ },+} as const;diff --git a/web/src/components/trace2/contexts/JsonExpansionContext.tsx b/web/src/components/trace2/contexts/JsonExpansionContext.tsxindex 46237a5ff7..aa05546218 100644--- a/web/src/components/trace2/contexts/JsonExpansionContext.tsx+++ b/web/src/components/trace2/contexts/JsonExpansionContext.tsx@@ -22,14 +22,13 @@ type JsonExpansionState = {output: ExpandedState;metadata: ExpandedState;log: ExpandedState;+ // Dynamic keys for per-observation log view expansion (e.g., "log:observationId")+ [key: string]: ExpandedState;};interface JsonExpansionContextValue {expansionState: JsonExpansionState;- setFieldExpansion: (- field: keyof JsonExpansionState,- expansion: ExpandedState,- ) => void;+ setFieldExpansion: (field: string, expansion: ExpandedState) => void;}const JsonExpansionContext = createContext<JsonExpansionContextValue>({@@ -49,7 +48,7 @@ export function JsonExpansionProvider({ children }: { children: ReactNode }) {});const setFieldExpansion = useCallback(- (field: keyof JsonExpansionState, expansion: ExpandedState) => {+ (field: string, expansion: ExpandedState) => {setExpansionState((prev) => ({...prev,[field]: expansion,@@ -60,7 +59,10 @@ export function JsonExpansionProvider({ children }: { children: ReactNode }) {return (<JsonExpansionContext.Provider- value={{ expansionState, setFieldExpansion }}+ value={{+ expansionState,+ setFieldExpansion,+ }}>{children}</JsonExpansionContext.Provider>diff --git a/web/src/components/trace2/contexts/SelectionContext.tsx b/web/src/components/trace2/contexts/SelectionContext.tsxindex 9c531a8833..adc62ee761 100644--- a/web/src/components/trace2/contexts/SelectionContext.tsx+++ b/web/src/components/trace2/contexts/SelectionContext.tsx@@ -5,10 +5,17 @@* - Tracks selected node ID (synced to URL query param)* - Manages collapsed/expanded state for tree nodes* - Handles search query with debounced input+ * - Tracks selected tab (preview/log/scores) - synced to URL query param+ * - Tracks view preference (formatted/json) - synced to URL query param AND localStorage+ *+ * View Preference Behavior:+ * - Uses localStorage as global default (via ViewPreferencesContext)+ * - URL param overrides default when present (for shareable URLs)+ * - Changes update BOTH URL and localStorage for consistency** Not responsible for:* - Trace data or tree structure - see TraceDataContext- * - Display preferences - see ViewPreferencesContext+ * - Display preferences (other than view pref) - see ViewPreferencesContext*/import {@@ -21,6 +28,19 @@ import {} from "react";import { StringParam, useQueryParam } from "use-query-params";import { useDebounce } from "@/src/hooks/useDebounce";+import {+ useViewPreferences,+ type JsonViewPreference,+} from "./ViewPreferencesContext";++// Valid tab values for detail view+export type DetailTab = "preview" | "log" | "scores";+const VALID_TABS: DetailTab[] = ["preview", "log", "scores"];+const DEFAULT_TAB: DetailTab = "preview";++// Valid view preference values+export type ViewPref = "formatted" | "json";+const VALID_PREFS: ViewPref[] = ["formatted", "json"];interface SelectionContextValue {selectedNodeId: string | null;@@ -33,6 +53,11 @@ interface SelectionContextValue {searchInputValue: string;setSearchInputValue: (value: string) => void;setSearchQueryImmediate: (value: string) => void;+ // Tab and view preference (URL-synced)+ selectedTab: DetailTab;+ setSelectedTab: (tab: DetailTab) => void;+ viewPref: ViewPref;+ setViewPref: (pref: ViewPref) => void;}const SelectionContext = createContext<SelectionContextValue | null>(null);@@ -54,10 +79,53 @@ export function SelectionProvider({ children }: SelectionProviderProps) {"observation",StringParam,);+ const [tabParam, setTabParam] = useQueryParam("tab", StringParam);+ const [prefParam, setPrefParam] = useQueryParam("pref", StringParam);++ // Get localStorage default for view preference+ const { jsonViewPreference, setJsonViewPreference } = useViewPreferences();+const [collapsedNodesArray, setCollapsedNodesArray] = useState<string[]>([]);const [searchInputValue, setSearchInputValue] = useState("");const [searchQuery, setSearchQuery] = useState("");+ // Validate and provide defaults for tab+ const selectedTab: DetailTab = VALID_TABS.includes(tabParam as DetailTab)+ ? (tabParam as DetailTab)+ : DEFAULT_TAB;++ // Map localStorage JsonViewPreference to ViewPref format+ const localStorageViewPref: ViewPref =+ jsonViewPreference === "json" ? "json" : "formatted";++ // View preference: URL param overrides localStorage default+ const viewPref: ViewPref = VALID_PREFS.includes(prefParam as ViewPref)+ ? (prefParam as ViewPref)+ : localStorageViewPref;++ const setSelectedTab = useCallback(+ (tab: DetailTab) => {+ setTabParam(tab === DEFAULT_TAB ? null : tab);+ },+ [setTabParam],+ );++ const setViewPref = useCallback(+ (pref: ViewPref) => {+ // Map ViewPref back to JsonViewPreference format+ const jsonPref: JsonViewPreference = pref === "json" ? "json" : "pretty";++ // Update localStorage+ setJsonViewPreference(jsonPref);++ // Update URL param (clear if it matches the new localStorage default)+ const newLocalStorageViewPref: ViewPref =+ jsonPref === "json" ? "json" : "formatted";+ setPrefParam(pref === newLocalStorageViewPref ? null : pref);+ },+ [setJsonViewPreference, setPrefParam],+ );+// Debounce search query updates by 500ms for smooth typingconst debouncedSetSearchQuery = useDebounce(setSearchQuery, 500, false);@@ -114,6 +182,10 @@ export function SelectionProvider({ children }: SelectionProviderProps) {searchInputValue,setSearchInputValue: handleSearchInputChange,setSearchQueryImmediate,+ selectedTab,+ setSelectedTab,+ viewPref,+ setViewPref,}),[currentObservationId,@@ -126,6 +198,10 @@ export function SelectionProvider({ children }: SelectionProviderProps) {searchInputValue,handleSearchInputChange,setSearchQueryImmediate,+ selectedTab,+ setSelectedTab,+ viewPref,+ setViewPref,],);diff --git a/web/src/components/trace2/contexts/TraceGraphDataContext.tsx b/web/src/components/trace2/contexts/TraceGraphDataContext.tsxindex 1ba1d129a6..0c77bda27d 100644--- a/web/src/components/trace2/contexts/TraceGraphDataContext.tsx+++ b/web/src/components/trace2/contexts/TraceGraphDataContext.tsx@@ -49,24 +49,43 @@ export function TraceGraphDataProvider({traceId,observations,}: TraceGraphDataProviderProps) {- // Calculate time bounds from observations- const observationStartTimes = observations.map((o) => o.startTime.getTime());- const minStartTime = new Date(- Math.min(...observationStartTimes, Date.now()),- ).toISOString();- const maxStartTime = new Date(- Math.max(...observationStartTimes, 0),- ).toISOString();+ // Skip graph data entirely for large traces to avoid performance issues+ const exceedsThreshold = observations.length >= MAX_NODES_FOR_GRAPH_UI;++ // Calculate time bounds using loop to avoid stack overflow from spread operator+ // Math.min(...array) with 10k+ elements can exceed JavaScript call stack limit+ const { minStartTime, maxStartTime } = useMemo(() => {+ if (exceedsThreshold || observations.length === 0) {+ return { minStartTime: null, maxStartTime: null };+ }++ let minTime = Infinity;+ let maxTime = 0;+ for (const obs of observations) {+ const t = obs.startTime.getTime();+ if (t < minTime) minTime = t;+ if (t > maxTime) maxTime = t;+ }++ return {+ minStartTime: new Date(minTime).toISOString(),+ maxStartTime: new Date(maxTime).toISOString(),+ };+ }, [observations, exceedsThreshold]);const query = api.traces.getAgentGraphData.useQuery({projectId,traceId,- minStartTime,- maxStartTime,+ minStartTime: minStartTime ?? "",+ maxStartTime: maxStartTime ?? "",},{- enabled: observations.length > 0,+ enabled:+ !exceedsThreshold &&+ observations.length > 0 &&+ minStartTime !== null &&+ maxStartTime !== null,refetchOnWindowFocus: false,refetchOnMount: false,refetchOnReconnect: false,diff --git a/web/src/components/trace2/contexts/ViewPreferencesContext.tsx b/web/src/components/trace2/contexts/ViewPreferencesContext.tsxindex 7e0211f31f..2584ac642b 100644--- a/web/src/components/trace2/contexts/ViewPreferencesContext.tsx+++ b/web/src/components/trace2/contexts/ViewPreferencesContext.tsx@@ -15,6 +15,15 @@ import { createContext, useContext, useMemo, type ReactNode } from "react";import { type ObservationLevelType, ObservationLevel } from "@langfuse/shared";import useLocalStorage from "@/src/components/useLocalStorage";+/** Log view ordering mode */+export type LogViewMode = "chronological" | "tree-order";++/** Log view tree visualization style (only applies in tree-order mode) */+export type LogViewTreeStyle = "flat" | "indented";++/** JSON view preference (formatted/pretty vs raw JSON) */+export type JsonViewPreference = "pretty" | "json";+interface ViewPreferencesContextValue {showDuration: boolean;setShowDuration: (value: boolean) => void;@@ -32,6 +41,15 @@ interface ViewPreferencesContextValue {setMinObservationLevel: (value: ObservationLevelType) => void;/** Whether trace is rendered in peek mode (e.g., annotation queues) */isPeekMode: boolean;+ /** Log view ordering mode (chronological or tree-order) */+ logViewMode: LogViewMode;+ setLogViewMode: (value: LogViewMode) => void;+ /** Log view tree style (flat or indented, only applies in tree-order mode) */+ logViewTreeStyle: LogViewTreeStyle;+ setLogViewTreeStyle: (value: LogViewTreeStyle) => void;+ /** JSON view preference (pretty/formatted or raw JSON) */+ jsonViewPreference: JsonViewPreference;+ setJsonViewPreference: (value: JsonViewPreference) => void;}const ViewPreferencesContext =@@ -81,6 +99,14 @@ export function ViewPreferencesProvider({"minObservationLevel",ObservationLevel.DEFAULT,);+ const [logViewMode, setLogViewMode] = useLocalStorage<LogViewMode>(+ "logViewMode",+ "chronological",+ );+ const [logViewTreeStyle, setLogViewTreeStyle] =+ useLocalStorage<LogViewTreeStyle>("logViewTreeStyle", "flat");+ const [jsonViewPreference, setJsonViewPreference] =+ useLocalStorage<JsonViewPreference>("jsonViewPreference", "pretty");const value = useMemo<ViewPreferencesContextValue>(() => ({@@ -99,6 +125,12 @@ export function ViewPreferencesProvider({minObservationLevel,setMinObservationLevel,isPeekMode,+ logViewMode,+ setLogViewMode,+ logViewTreeStyle,+ setLogViewTreeStyle,+ jsonViewPreference,+ setJsonViewPreference,}),[showDuration,@@ -116,6 +148,12 @@ export function ViewPreferencesProvider({minObservationLevel,setMinObservationLevel,isPeekMode,+ logViewMode,+ setLogViewMode,+ logViewTreeStyle,+ setLogViewTreeStyle,+ jsonViewPreference,+ setJsonViewPreference,],);diff --git a/web/src/components/trace2/hooks/useHandlePrefetchObservation.ts b/web/src/components/trace2/hooks/useHandlePrefetchObservation.tsnew file mode 100644index 0000000000..bef66bf7c4--- /dev/null+++ b/web/src/components/trace2/hooks/useHandlePrefetchObservation.ts@@ -0,0 +1,32 @@+/**+ * Hook to prefetch observation data on hover in navigation panels.+ *+ * Combines TraceDataContext (for trace/project IDs) with usePrefetchObservation+ * to provide a simple callback for hover events.+ */++import { useCallback } from "react";+import { useTraceData } from "../contexts/TraceDataContext";+import { usePrefetchObservation } from "../api/usePrefetchObservation";+import { type TreeNode } from "../lib/types";++/**+ * Returns a callback to prefetch observation data when hovering over nodes.+ * Skips prefetch for TRACE type (root node).+ */+export function useHandlePrefetchObservation() {+ const { trace } = useTraceData();+ const { prefetch } = usePrefetchObservation({ projectId: trace.projectId });++ const handleHover = useCallback(+ (node: TreeNode) => {+ // Don't prefetch for TRACE type (only observations)+ if (node.type !== "TRACE") {+ prefetch(node.id, trace.id, node.startTime);+ }+ },+ [prefetch, trace.id],+ );++ return { handleHover };+}diff --git a/web/src/components/trace2/lib/helpers.ts b/web/src/components/trace2/lib/helpers.tsindex 963bfd7969..d35badf2b5 100644--- a/web/src/components/trace2/lib/helpers.ts+++ b/web/src/components/trace2/lib/helpers.ts@@ -289,36 +289,47 @@ function buildTraceTree(traceStartTime: Date,parentStartTime: Date | null,depth: number,- ): TreeNode => ({- id: obs.id,- type: obs.type,- name: obs.name ?? "",- startTime: obs.startTime,- endTime: obs.endTime,- level: obs.level,- children: obs.children.map((child) =>+ ): TreeNode => {+ const children = obs.children.map((child) =>convertObservationToTreeNode(child,traceStartTime,obs.startTime,depth + 1,),- ),- inputUsage: obs.inputUsage,- outputUsage: obs.outputUsage,- totalUsage: obs.totalUsage,- calculatedInputCost: obs.inputCost,- calculatedOutputCost: obs.outputCost,- calculatedTotalCost: obs.totalCost,- parentObservationId: obs.parentObservationId,- traceId: obs.traceId,- startTimeSinceTrace: obs.startTime.getTime() - traceStartTime.getTime(),- startTimeSinceParentStart:- parentStartTime !== null- ? obs.startTime.getTime() - parentStartTime.getTime()- : null,- depth,- });+ );++ // Calculate childrenDepth (max depth of subtree rooted at this node)+ const childrenDepth =+ children.length > 0+ ? Math.max(...children.map((c) => c.childrenDepth)) + 1+ : 0;++ return {+ id: obs.id,+ type: obs.type,+ name: obs.name ?? "",+ startTime: obs.startTime,+ endTime: obs.endTime,+ level: obs.level,+ children,+ inputUsage: obs.inputUsage,+ outputUsage: obs.outputUsage,+ totalUsage: obs.totalUsage,+ calculatedInputCost: obs.inputCost,+ calculatedOutputCost: obs.outputCost,+ calculatedTotalCost: obs.totalCost,+ parentObservationId: obs.parentObservationId,+ traceId: obs.traceId,+ startTimeSinceTrace: obs.startTime.getTime() - traceStartTime.getTime(),+ startTimeSinceParentStart:+ parentStartTime !== null+ ? obs.startTime.getTime() - parentStartTime.getTime()+ : null,+ depth,+ childrenDepth,+ };+ };// Convert and enrich children with pre-computed costs and populate nodeMapconst enrichedChildren = nestedObservations@@ -334,6 +345,12 @@ function buildTraceTree(undefined,);+ // Calculate childrenDepth for trace root+ const traceChildrenDepth =+ enrichedChildren.length > 0+ ? Math.max(...enrichedChildren.map((c) => c.childrenDepth)) + 1+ : 0;+// Create the root tree node (trace)// Use a unique ID for the trace root to avoid conflicts with observations that might have the same IDconst tree: TreeNode = {@@ -348,6 +365,7 @@ function buildTraceTree(startTimeSinceTrace: 0,startTimeSinceParentStart: null,depth: -1,+ childrenDepth: traceChildrenDepth,};// Add trace root to nodeMap as welldiff --git a/web/src/components/trace2/lib/tree-building.clienttest.ts b/web/src/components/trace2/lib/tree-building.clienttest.tsindex d26fb85de9..2c82b35eaa 100644--- a/web/src/components/trace2/lib/tree-building.clienttest.ts+++ b/web/src/components/trace2/lib/tree-building.clienttest.ts@@ -1088,6 +1088,194 @@ describe("buildTraceUiData", () => {});});+ describe("Children Depth Calculation", () => {+ it("assigns childrenDepth 0 to leaf nodes", () => {+ const trace = createMockTrace({ id: "trace-1" });+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "leaf-1",+ parentObservationId: null,+ }),+ createMockObservation({+ id: "leaf-2",+ parentObservationId: null,+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ expect(result.nodeMap.get("leaf-1")?.childrenDepth).toBe(0);+ expect(result.nodeMap.get("leaf-2")?.childrenDepth).toBe(0);+ });++ it("calculates childrenDepth for linear chain (A → B → C)", () => {+ const trace = createMockTrace({ id: "trace-1" });+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "A",+ parentObservationId: null,+ }),+ createMockObservation({+ id: "B",+ parentObservationId: "A",+ }),+ createMockObservation({+ id: "C",+ parentObservationId: "B",+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ // C is leaf: childrenDepth = 0+ expect(result.nodeMap.get("C")?.childrenDepth).toBe(0);+ // B has one child (C): childrenDepth = 1+ expect(result.nodeMap.get("B")?.childrenDepth).toBe(1);+ // A has chain of depth 2: childrenDepth = 2+ expect(result.nodeMap.get("A")?.childrenDepth).toBe(2);+ // Trace root has chain of depth 3: childrenDepth = 3+ expect(result.tree.childrenDepth).toBe(3);+ });++ it("calculates childrenDepth for wide tree (parent with 3 children)", () => {+ const trace = createMockTrace({ id: "trace-1" });+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "parent",+ parentObservationId: null,+ }),+ createMockObservation({+ id: "child-1",+ parentObservationId: "parent",+ }),+ createMockObservation({+ id: "child-2",+ parentObservationId: "parent",+ }),+ createMockObservation({+ id: "child-3",+ parentObservationId: "parent",+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ // All children are leaves: childrenDepth = 0+ expect(result.nodeMap.get("child-1")?.childrenDepth).toBe(0);+ expect(result.nodeMap.get("child-2")?.childrenDepth).toBe(0);+ expect(result.nodeMap.get("child-3")?.childrenDepth).toBe(0);+ // Parent has children at depth 1: childrenDepth = 1+ expect(result.nodeMap.get("parent")?.childrenDepth).toBe(1);+ // Trace root: childrenDepth = 2+ expect(result.tree.childrenDepth).toBe(2);+ });++ it("takes max childrenDepth when branches have different depths", () => {+ const trace = createMockTrace({ id: "trace-1" });+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "root",+ parentObservationId: null,+ }),+ // Branch 1: depth 2 (root → branch1 → deep)+ createMockObservation({+ id: "branch1",+ parentObservationId: "root",+ }),+ createMockObservation({+ id: "deep",+ parentObservationId: "branch1",+ }),+ // Branch 2: depth 1 (root → branch2)+ createMockObservation({+ id: "branch2",+ parentObservationId: "root",+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ // deep is leaf: childrenDepth = 0+ expect(result.nodeMap.get("deep")?.childrenDepth).toBe(0);+ // branch1 has one child: childrenDepth = 1+ expect(result.nodeMap.get("branch1")?.childrenDepth).toBe(1);+ // branch2 is leaf: childrenDepth = 0+ expect(result.nodeMap.get("branch2")?.childrenDepth).toBe(0);+ // root takes max(1, 0) + 1 = 2+ expect(result.nodeMap.get("root")?.childrenDepth).toBe(2);+ // Trace root: childrenDepth = 3+ expect(result.tree.childrenDepth).toBe(3);+ });++ it("calculates childrenDepth 0 for empty trace", () => {+ const trace = createMockTrace({ id: "trace-1" });+ const observations: ObservationReturnType[] = [];++ const result = buildTraceUiData(trace, observations);++ expect(result.tree.childrenDepth).toBe(0);+ });++ it("calculates correct childrenDepth for deep nesting (5+ levels)", () => {+ const trace = createMockTrace({ id: "trace-1" });+ const observations: ObservationReturnType[] = [+ createMockObservation({ id: "L0", parentObservationId: null }),+ createMockObservation({ id: "L1", parentObservationId: "L0" }),+ createMockObservation({ id: "L2", parentObservationId: "L1" }),+ createMockObservation({ id: "L3", parentObservationId: "L2" }),+ createMockObservation({ id: "L4", parentObservationId: "L3" }),+ createMockObservation({ id: "L5", parentObservationId: "L4" }),+ createMockObservation({ id: "L6", parentObservationId: "L5" }),+ ];++ const result = buildTraceUiData(trace, observations);++ // Bottom-up childrenDepth+ expect(result.nodeMap.get("L6")?.childrenDepth).toBe(0);+ expect(result.nodeMap.get("L5")?.childrenDepth).toBe(1);+ expect(result.nodeMap.get("L4")?.childrenDepth).toBe(2);+ expect(result.nodeMap.get("L3")?.childrenDepth).toBe(3);+ expect(result.nodeMap.get("L2")?.childrenDepth).toBe(4);+ expect(result.nodeMap.get("L1")?.childrenDepth).toBe(5);+ expect(result.nodeMap.get("L0")?.childrenDepth).toBe(6);+ // Trace root: 7 levels deep+ expect(result.tree.childrenDepth).toBe(7);+ });++ it("calculates childrenDepth with multiple root observations", () => {+ const trace = createMockTrace({ id: "trace-1" });+ const observations: ObservationReturnType[] = [+ // First root with depth 2+ createMockObservation({ id: "root1", parentObservationId: null }),+ createMockObservation({+ id: "root1-child",+ parentObservationId: "root1",+ }),+ createMockObservation({+ id: "root1-grandchild",+ parentObservationId: "root1-child",+ }),+ // Second root with depth 1+ createMockObservation({ id: "root2", parentObservationId: null }),+ createMockObservation({+ id: "root2-child",+ parentObservationId: "root2",+ }),+ // Third root is leaf+ createMockObservation({ id: "root3", parentObservationId: null }),+ ];++ const result = buildTraceUiData(trace, observations);++ // root1 has depth 2, root2 has depth 1, root3 has depth 0+ expect(result.nodeMap.get("root1")?.childrenDepth).toBe(2);+ expect(result.nodeMap.get("root2")?.childrenDepth).toBe(1);+ expect(result.nodeMap.get("root3")?.childrenDepth).toBe(0);+ // Trace root takes max(2, 1, 0) + 1 = 3+ expect(result.tree.childrenDepth).toBe(3);+ });+ });+describe("Edge Cases", () => {it("handles observation starting at same time as parent", () => {const trace = createMockTrace({diff --git a/web/src/components/trace2/lib/tree-building.ts b/web/src/components/trace2/lib/tree-building.tsindex 0dfc1a1535..d9bf3f7984 100644--- a/web/src/components/trace2/lib/tree-building.ts+++ b/web/src/components/trace2/lib/tree-building.ts@@ -265,6 +265,14 @@ function buildTreeNodesBottomUp(// Use pre-calculated depth from ProcessingNodeconst depth = currentNode.depth;+ // Calculate childrenDepth (max depth of subtree rooted at this node)+ // Leaf nodes have childrenDepth = 0+ // Parent nodes have childrenDepth = max(children.childrenDepth) + 1+ const childrenDepth =+ childTreeNodes.length > 0+ ? Math.max(...childTreeNodes.map((c) => c.childrenDepth)) + 1+ : 0;+// Create TreeNodeconst treeNode: TreeNode = {id: obs.id,@@ -286,6 +294,7 @@ function buildTreeNodesBottomUp(startTimeSinceTrace,startTimeSinceParentStart,depth,+ childrenDepth,};// Store in registry and nodeMap@@ -342,6 +351,7 @@ function buildTraceTree(startTimeSinceTrace: 0,startTimeSinceParentStart: null,depth: -1,+ childrenDepth: 0,};const nodeMap = new Map<string, TreeNode>();nodeMap.set(emptyTree.id, emptyTree);@@ -378,6 +388,12 @@ function buildTraceTree(undefined,);+ // Calculate trace root childrenDepth+ const traceChildrenDepth =+ rootTreeNodes.length > 0+ ? Math.max(...rootTreeNodes.map((c) => c.childrenDepth)) + 1+ : 0;+// Create trace root nodeconst tree: TreeNode = {id: `trace-${trace.id}`,@@ -391,6 +407,7 @@ function buildTraceTree(startTimeSinceTrace: 0,startTimeSinceParentStart: null,depth: -1,+ childrenDepth: traceChildrenDepth,};nodeMap.set(tree.id, tree);diff --git a/web/src/components/trace2/lib/types.ts b/web/src/components/trace2/lib/types.tsindex 429a70c18a..8654cd426e 100644--- a/web/src/components/trace2/lib/types.ts+++ b/web/src/components/trace2/lib/types.ts@@ -43,6 +43,8 @@ export type TreeNode = {startTimeSinceParentStart: number | null;/** Tree depth: -1 for trace root, 0 for root observations, increases with nesting */depth: number;+ /** Maximum depth of subtree rooted at this node (0 for leaf nodes) */+ childrenDepth: number;};/**