🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(trace2): new trace viewer UI for parallel testing (#10762)
Michael Fröhlich4783d11e4e35
diff --git a/.gitignore b/.gitignoreindex f4f56d73d2..4c5883377d 100644--- a/.gitignore+++ b/.gitignore@@ -73,4 +73,8 @@ web/test-results/*# local config files*.local.*+# claude meta files.claude/tsc-cache++# Refactoring planning files (local only)+**/.refactor/diff --git a/web/src/components/layouts/app-layout/utils/pathClassification.ts b/web/src/components/layouts/app-layout/utils/pathClassification.tsindex 23a2ec972b..e7e8b1d8ca 100644--- a/web/src/components/layouts/app-layout/utils/pathClassification.ts+++ b/web/src/components/layouts/app-layout/utils/pathClassification.ts@@ -15,6 +15,7 @@ export const PATH_CONSTANTS = {publishable: ["/project/[projectId]/sessions/[sessionId]","/project/[projectId]/traces/[traceId]",+ "/project/[projectId]/traces2/[traceId]","/auth/reset-password",] as const,};diff --git a/web/src/components/trace2/Trace.tsx b/web/src/components/trace2/Trace.tsxnew file mode 100644index 0000000000..b011f3e5e7--- /dev/null+++ b/web/src/components/trace2/Trace.tsx@@ -0,0 +1,173 @@+import { type TraceDomain } from "@langfuse/shared";+import { type UrlUpdateType } from "use-query-params";+import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";+import { type ScoreDomain } from "@langfuse/shared";+import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";+import { TraceDataProvider } from "./contexts/TraceDataContext";+import { ViewPreferencesProvider } from "./contexts/ViewPreferencesContext";+import { SelectionProvider } from "./contexts/SelectionContext";+import { SearchProvider } from "./contexts/SearchContext";+import { JsonExpansionProvider } from "./contexts/JsonExpansionContext";+import { TraceGraphDataProvider } from "./contexts/TraceGraphDataContext";+import { TraceLayoutMobile } from "./components/_layout/TraceLayoutMobile";+import { TraceLayoutDesktop } from "./components/_layout/TraceLayoutDesktop";+import { TracePanelNavigation } from "./components/_layout/TracePanelNavigation";+import { TracePanelDetail } from "./components/_layout/TracePanelDetail";+import { TracePanelNavigationLayoutDesktop } from "./components/_layout/TracePanelNavigationLayoutDesktop";+import { TracePanelNavigationLayoutMobile } from "./components/_layout/TracePanelNavigationLayoutMobile";+import { useIsMobile } from "@/src/hooks/use-mobile";+import { useTraceComments } from "./api/useTraceComments";+import { useViewPreferences } from "./contexts/ViewPreferencesContext";+import { useTraceGraphData } from "./contexts/TraceGraphDataContext";+import { TraceGraphView } from "./components/TraceGraphView/TraceGraphView";++import { useMemo } from "react";++export type TraceProps = {+ observations: Array<ObservationReturnTypeWithMetadata>;+ trace: Omit<WithStringifiedMetadata<TraceDomain>, "input" | "output"> & {+ input: string | null;+ output: string | null;+ };+ scores: WithStringifiedMetadata<ScoreDomain>[];+ projectId: string;+ viewType?: "detailed" | "focused";+ context?: "peek" | "fullscreen";+ isValidObservationId?: boolean;+ selectedTab?: string;+ setSelectedTab?: (+ newValue?: string | null,+ updateType?: UrlUpdateType,+ ) => void;+};++export function Trace({+ trace,+ observations,+ scores,+ projectId,+ context,+}: TraceProps) {+ // Fetch comment counts using existing hook+ const { observationCommentCounts, traceCommentCount } = useTraceComments({+ projectId,+ traceId: trace.id,+ });++ // Merge observation + trace comments into single Map for TraceDataContext+ const commentsMap = useMemo(() => {+ const map = new Map(observationCommentCounts);+ if (traceCommentCount > 0) {+ map.set(trace.id, traceCommentCount);+ }+ return map;+ }, [observationCommentCounts, traceCommentCount, trace.id]);++ return (+ <ViewPreferencesProvider traceContext={context}>+ <TraceDataProvider+ trace={trace}+ observations={observations}+ scores={scores}+ comments={commentsMap}+ >+ <TraceGraphDataProvider+ projectId={trace.projectId}+ traceId={trace.id}+ observations={observations}+ >+ <SelectionProvider>+ <SearchProvider>+ <JsonExpansionProvider>+ <TraceContent />+ </JsonExpansionProvider>+ </SearchProvider>+ </SelectionProvider>+ </TraceGraphDataProvider>+ </TraceDataProvider>+ </ViewPreferencesProvider>+ );+}++/**+ * TraceContent - Platform detection and routing component+ *+ * Purpose:+ * - Detects mobile vs desktop viewport+ * - Routes to appropriate platform-specific implementation+ * - Manages shared graph visibility logic+ *+ * Hooks:+ * - useIsMobile() - for responsive platform detection+ * - useViewPreferences() - for graph toggle state+ * - useTraceGraphData() - for graph availability+ */+function TraceContent() {+ const isMobile = useIsMobile();+ const { showGraph } = useViewPreferences();+ const { isGraphViewAvailable } = useTraceGraphData();+ const shouldShowGraph = showGraph && isGraphViewAvailable;++ return isMobile ? (+ <MobileTraceContent shouldShowGraph={shouldShowGraph} />+ ) : (+ <DesktopTraceContent shouldShowGraph={shouldShowGraph} />+ );+}++/**+ * DesktopTraceContent - Desktop layout composition+ *+ * Purpose:+ * - Composes desktop-specific layout structure+ * - Horizontal resizable panels with collapse functionality+ * - Navigation panel (left) + Detail panel (right)+ */+function DesktopTraceContent({+ shouldShowGraph,+}: {+ shouldShowGraph: boolean;+}) {+ return (+ <TraceLayoutDesktop>+ <TraceLayoutDesktop.NavigationPanel>+ <TracePanelNavigationLayoutDesktop+ secondaryContent={shouldShowGraph ? <TraceGraphView /> : undefined}+ >+ <TracePanelNavigation />+ </TracePanelNavigationLayoutDesktop>+ </TraceLayoutDesktop.NavigationPanel>+ <TraceLayoutDesktop.ResizeHandle />+ <TraceLayoutDesktop.DetailPanel>+ <TracePanelDetail />+ </TraceLayoutDesktop.DetailPanel>+ </TraceLayoutDesktop>+ );+}++/**+ * MobileTraceContent - Mobile layout composition+ *+ * Purpose:+ * - Composes mobile-specific layout structure+ * - Vertical accordion-style panels+ * - Navigation panel (top, collapsible) + Detail panel (bottom)+ */+function MobileTraceContent({ shouldShowGraph }: { shouldShowGraph: boolean }) {+ return (+ <div className="h-full w-full">+ <TraceLayoutMobile>+ <TraceLayoutMobile.NavigationPanel>+ <TracePanelNavigationLayoutMobile+ secondaryContent={shouldShowGraph ? <TraceGraphView /> : undefined}+ >+ <TracePanelNavigation />+ </TracePanelNavigationLayoutMobile>+ </TraceLayoutMobile.NavigationPanel>+ <TraceLayoutMobile.DetailPanel>+ <TracePanelDetail />+ </TraceLayoutMobile.DetailPanel>+ </TraceLayoutMobile>+ </div>+ );+}diff --git a/web/src/components/trace2/TracePage.tsx b/web/src/components/trace2/TracePage.tsxnew file mode 100644index 0000000000..77bb99f805--- /dev/null+++ b/web/src/components/trace2/TracePage.tsx@@ -0,0 +1,143 @@+import { StringParam, useQueryParam, withDefault } from "use-query-params";+import { PublishTraceSwitch } from "@/src/components/publish-object-switch";+import { DetailPageNav } from "@/src/features/navigate-detail-pages/DetailPageNav";+import { useRouter } from "next/router";+import { api } from "@/src/utils/api";+import { StarTraceDetailsToggle } from "@/src/components/star-toggle";+import { ErrorPage } from "@/src/components/error-page";+import { DeleteTraceButton } from "@/src/components/deleteButton";+import Page from "@/src/components/layouts/page";+import { Trace } from "@/src/components/trace2/Trace";++export function TracePage({+ traceId,+ timestamp,+}: {+ traceId: string;+ timestamp?: Date;+}) {+ const router = useRouter();++ const trace = api.traces.byIdWithObservationsAndScores.useQuery(+ {+ traceId,+ timestamp,+ projectId: router.query.projectId as string,+ },+ {+ retry(failureCount, error) {+ if (+ error.data?.code === "UNAUTHORIZED" ||+ error.data?.code === "NOT_FOUND"+ )+ return false;+ return failureCount < 3;+ },+ },+ );++ const [selectedTab, setSelectedTab] = useQueryParam(+ "display",+ withDefault(StringParam, "details"),+ );++ if (trace.error?.data?.code === "UNAUTHORIZED")+ return <ErrorPage message="You do not have access to this trace." />;++ if (trace.error?.data?.code === "NOT_FOUND")+ return (+ <ErrorPage+ title="Trace not found"+ message="The trace is either still being processed or has been deleted."+ additionalButton={{+ label: "Retry",+ onClick: () => void window.location.reload(),+ }}+ />+ );++ if (!trace.data) return <div className="p-3">Loading...</div>;++ return (+ <Page+ headerProps={{+ title: trace.data.name+ ? `${trace.data.name}: ${trace.data.id}`+ : trace.data.id,+ itemType: "TRACE",+ breadcrumb: [+ {+ name: "Traces",+ href: `/project/${router.query.projectId as string}/traces`,+ },+ ],+ actionButtonsLeft: (+ <div className="ml-1 flex items-center gap-1">+ <div className="flex items-center gap-0">+ <StarTraceDetailsToggle+ traceId={trace.data.id}+ projectId={trace.data.projectId}+ value={trace.data.bookmarked}+ size="icon-xs"+ />+ <PublishTraceSwitch+ traceId={trace.data.id}+ projectId={trace.data.projectId}+ isPublic={trace.data.public}+ size="icon-xs"+ />+ </div>+ </div>+ ),+ actionButtonsRight: (+ <>+ <DetailPageNav+ currentId={traceId}+ path={(entry) => {+ const { view, display, projectId } = router.query;+ const queryParams = new URLSearchParams({+ ...(typeof view === "string" ? { view } : {}),+ ...(typeof display === "string" ? { display } : {}),+ });+ const timestamp =+ entry.params && entry.params.timestamp+ ? encodeURIComponent(entry.params.timestamp)+ : undefined;++ if (timestamp) {+ queryParams.set("timestamp", timestamp);+ }++ const finalQueryString = queryParams.size+ ? `?${queryParams.toString()}`+ : "";++ return `/project/${projectId as string}/traces2/${entry.id}${finalQueryString}`;+ }}+ listKey="traces"+ />+ <DeleteTraceButton+ itemId={traceId}+ projectId={trace.data.projectId}+ redirectUrl={`/project/${router.query.projectId as string}/traces`}+ deleteConfirmation={trace.data.name ?? ""}+ icon+ />+ </>+ ),+ }}+ >+ <div className="flex max-h-full min-h-0 flex-1 overflow-hidden">+ <Trace+ trace={trace.data}+ scores={trace.data.scores}+ projectId={trace.data.projectId}+ observations={trace.data.observations}+ selectedTab={selectedTab}+ setSelectedTab={setSelectedTab}+ context={router.query.peek !== undefined ? "peek" : "fullscreen"}+ />+ </div>+ </Page>+ );+}diff --git a/web/src/components/trace2/api/useAgentGraphData.ts b/web/src/components/trace2/api/useAgentGraphData.tsnew file mode 100644index 0000000000..0bb1144a77--- /dev/null+++ b/web/src/components/trace2/api/useAgentGraphData.ts@@ -0,0 +1,96 @@+import { useMemo } from "react";+import { api } from "@/src/utils/api";+import { type AgentGraphDataResponse } from "@/src/features/trace-graph-view/types";++export type UseAgentGraphDataParams = {+ projectId: string;+ traceId: string;+ observations: Array<{ startTime: Date }>;+ enabled?: boolean;+};++/**+ * Hook to fetch agent graph data for visualization.+ * Calculates time bounds from observations and fetches graph data.+ *+ * @param projectId - Project ID+ * @param traceId - Trace ID+ * @param observations - Array of observations with startTime+ * @param enabled - Whether to enable the query (default: true)+ */+export function useAgentGraphData({+ projectId,+ traceId,+ observations,+ enabled = true,+}: UseAgentGraphDataParams) {+ // 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();++ const query = api.traces.getAgentGraphData.useQuery(+ {+ projectId,+ traceId,+ minStartTime,+ maxStartTime,+ },+ {+ enabled: enabled && observations.length > 0,+ refetchOnWindowFocus: false,+ refetchOnMount: false,+ refetchOnReconnect: false,+ staleTime: 50 * 60 * 1000, // 50 minutes+ },+ );++ const data = useMemo(() => query.data ?? [], [query.data]);++ return {+ data,+ isLoading: query.isLoading,+ isError: query.isError,+ error: query.error,+ };+}++const MAX_NODES_FOR_GRAPH_UI = 5000;++/**+ * Determines if graph view should be available based on observation data.+ */+export function useIsGraphViewAvailable(+ agentGraphData: AgentGraphDataResponse[],+): boolean {+ return useMemo(() => {+ if (agentGraphData.length === 0) {+ return false;+ }++ // Don't show graph UI for extremely large traces+ if (agentGraphData.length >= MAX_NODES_FOR_GRAPH_UI) {+ return false;+ }++ // Check if there are observations that would be included in the graph+ // (not SPAN, EVENT, or GENERATION)+ const hasGraphableObservations = agentGraphData.some(+ (obs) =>+ obs.observationType !== "SPAN" &&+ obs.observationType !== "EVENT" &&+ obs.observationType !== "GENERATION",+ );++ // Check for LangGraph data (has step != 0)+ const hasLangGraphData = agentGraphData.some(+ (obs) => obs.step != null && obs.step !== 0,+ );++ return hasGraphableObservations || hasLangGraphData;+ }, [agentGraphData]);+}diff --git a/web/src/components/trace2/api/useMedia.ts b/web/src/components/trace2/api/useMedia.tsnew file mode 100644index 0000000000..d12a90b681--- /dev/null+++ b/web/src/components/trace2/api/useMedia.ts@@ -0,0 +1,34 @@+import { api } from "@/src/utils/api";++export type UseMediaParams = {+ projectId: string;+ traceId: string;+ observationId?: string;+};++/**+ * Hook to fetch media attachments for a trace or observation.+ *+ * @param projectId - Project ID+ * @param traceId - Trace ID (required)+ * @param observationId - Observation ID (optional, for observation-level media)+ */+export function useMedia({+ projectId,+ traceId,+ observationId,+}: UseMediaParams) {+ return api.media.getByTraceOrObservationId.useQuery(+ {+ projectId,+ traceId,+ observationId,+ },+ {+ refetchOnWindowFocus: false,+ refetchOnMount: false,+ refetchOnReconnect: false,+ staleTime: 50 * 60 * 1000, // 50 minutes+ },+ );+}diff --git a/web/src/components/trace2/api/usePrefetchObservation.ts b/web/src/components/trace2/api/usePrefetchObservation.tsnew file mode 100644index 0000000000..e0ec8924e1--- /dev/null+++ b/web/src/components/trace2/api/usePrefetchObservation.ts@@ -0,0 +1,21 @@+import { api } from "@/src/utils/api";++export type UsePrefetchObservationParams = {+ projectId: string;+};++export function usePrefetchObservation({+ projectId,+}: UsePrefetchObservationParams) {+ const utils = api.useUtils();++ const prefetch = (observationId: string, traceId: string) => {+ void utils.observations.byId.prefetch({+ observationId,+ traceId,+ projectId,+ });+ };++ return { prefetch };+}diff --git a/web/src/components/trace2/api/useTraceComments.ts b/web/src/components/trace2/api/useTraceComments.tsnew file mode 100644index 0000000000..840951d77b--- /dev/null+++ b/web/src/components/trace2/api/useTraceComments.ts@@ -0,0 +1,54 @@+import { api } from "@/src/utils/api";+import { useIsAuthenticatedAndProjectMember } from "@/src/features/auth/hooks";+import { castToNumberMap } from "@/src/utils/map-utils";++export type UseTraceCommentsParams = {+ projectId: string;+ traceId: string;+};++export function useTraceComments({+ projectId,+ traceId,+}: UseTraceCommentsParams) {+ const isAuthenticatedAndProjectMember =+ useIsAuthenticatedAndProjectMember(projectId);++ const observationCommentCounts = api.comments.getCountByObjectType.useQuery(+ {+ projectId,+ objectType: "OBSERVATION",+ },+ {+ refetchOnMount: false,+ enabled: isAuthenticatedAndProjectMember,+ },+ );++ const traceCommentCounts = api.comments.getCountByObjectId.useQuery(+ {+ projectId,+ objectId: traceId,+ objectType: "TRACE",+ },+ {+ refetchOnMount: false,+ enabled: isAuthenticatedAndProjectMember,+ },+ );++ // Extract trace comment count from the Map response+ const traceCommentCountMap = traceCommentCounts.data+ ? castToNumberMap(traceCommentCounts.data)+ : undefined;+ const traceCount = traceCommentCountMap?.get(traceId) ?? 0;++ return {+ observationCommentCounts: observationCommentCounts.data+ ? castToNumberMap(observationCommentCounts.data)+ : new Map<string, number>(),+ traceCommentCount: traceCount,+ isLoading:+ observationCommentCounts.isLoading || traceCommentCounts.isLoading,+ };+}diff --git a/web/src/components/trace2/api/useTraceData.ts b/web/src/components/trace2/api/useTraceData.tsnew file mode 100644index 0000000000..e19f59d962--- /dev/null+++ b/web/src/components/trace2/api/useTraceData.ts@@ -0,0 +1,40 @@+import { api } from "@/src/utils/api";++export type UseTraceDataParams = {+ traceId: string;+ projectId: string;+ timestamp?: Date;+};++export function useTraceData({+ traceId,+ projectId,+ timestamp,+}: UseTraceDataParams) {+ const query = api.traces.byIdWithObservationsAndScores.useQuery(+ {+ traceId,+ timestamp,+ projectId,+ },+ {+ retry(failureCount, error) {+ if (+ error.data?.code === "UNAUTHORIZED" ||+ error.data?.code === "NOT_FOUND"+ )+ return false;+ return failureCount < 3;+ },+ },+ );++ return {+ trace: query.data,+ observations: query.data?.observations ?? [],+ scores: query.data?.scores ?? [],+ isLoading: query.isLoading,+ error: query.error,+ refetch: query.refetch,+ };+}diff --git a/web/src/components/trace2/components/IOPreview/IOPreview.tsx b/web/src/components/trace2/components/IOPreview/IOPreview.tsxnew file mode 100644index 0000000000..eb24da27f5--- /dev/null+++ b/web/src/components/trace2/components/IOPreview/IOPreview.tsx@@ -0,0 +1,251 @@+import { useEffect, useMemo } from "react";+import { type Prisma, deepParseJson } from "@langfuse/shared";+import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import useLocalStorage from "@/src/components/useLocalStorage";+import usePreserveRelativeScroll from "@/src/hooks/usePreserveRelativeScroll";+import { MARKDOWN_RENDER_CHARACTER_LIMIT } from "@/src/utils/constants";+import { type MediaReturnType } from "@/src/features/media/validation";++import { useChatMLParser } from "./hooks/useChatMLParser";+import { ChatMessageList } from "./components/ChatMessageList";+import { SectionToolDefinitions } from "./components/SectionToolDefinitions";+import { ViewModeToggle, type ViewMode } from "./components/ViewModeToggle";++export type { ViewMode };++export interface ExpansionStateProps {+ inputExpansionState?: Record<string, boolean> | boolean;+ outputExpansionState?: Record<string, boolean> | boolean;+ onInputExpansionChange?: (+ expansion: Record<string, boolean> | boolean,+ ) => void;+ onOutputExpansionChange?: (+ expansion: Record<string, boolean> | boolean,+ ) => void;+}++export interface IOPreviewProps extends ExpansionStateProps {+ input?: Prisma.JsonValue;+ output?: Prisma.JsonValue;+ metadata?: Prisma.JsonValue;+ observationName?: string;+ isLoading?: boolean;+ hideIfNull?: boolean;+ media?: MediaReturnType[];+ hideOutput?: boolean;+ hideInput?: boolean;+ currentView?: ViewMode;+ setIsPrettyViewAvailable?: (value: boolean) => void;+}++interface JsonInputOutputViewProps {+ parsedInput: unknown;+ parsedOutput: unknown;+ isLoading: boolean;+ media?: MediaReturnType[];+ selectedView: ViewMode;+ hideIfNull: boolean;+ hideInput: boolean;+ hideOutput: boolean;+ inputExpansionState?: Record<string, boolean> | boolean;+ outputExpansionState?: Record<string, boolean> | boolean;+ onInputExpansionChange?: (+ expansion: Record<string, boolean> | boolean,+ ) => void;+ onOutputExpansionChange?: (+ expansion: Record<string, boolean> | boolean,+ ) => void;+}++function JsonInputOutputView({+ parsedInput,+ parsedOutput,+ isLoading,+ media,+ selectedView,+ hideIfNull,+ hideInput,+ hideOutput,+ inputExpansionState,+ outputExpansionState,+ onInputExpansionChange,+ onOutputExpansionChange,+}: JsonInputOutputViewProps) {+ const showInput = !hideInput && !(hideIfNull && !parsedInput);+ const showOutput = !hideOutput && !(hideIfNull && !parsedOutput);++ return (+ <div className="[&_.io-message-content]:px-2 [&_.io-message-header]:px-2">+ {showInput && (+ <PrettyJsonView+ title="Input"+ json={parsedInput ?? null}+ isLoading={isLoading}+ media={media?.filter((m) => m.field === "input") ?? []}+ currentView={selectedView}+ externalExpansionState={inputExpansionState}+ onExternalExpansionChange={onInputExpansionChange}+ />+ )}+ {showOutput && (+ <PrettyJsonView+ title="Output"+ json={parsedOutput}+ isLoading={isLoading}+ media={media?.filter((m) => m.field === "output") ?? []}+ currentView={selectedView}+ externalExpansionState={outputExpansionState}+ onExternalExpansionChange={onOutputExpansionChange}+ />+ )}+ </div>+ );+}++/**+ * IOPreview renders input/output data from LLM observations.+ *+ * Features:+ * - ChatML message format detection and rendering+ * - Tool definitions and invocations display+ * - Pretty/JSON view toggle+ * - Media attachments support+ * - Large content safety (markdown rendering limit)+ */+export function IOPreview({+ input,+ output,+ metadata,+ observationName,+ isLoading = false,+ hideIfNull = false,+ hideOutput = false,+ hideInput = false,+ media,+ currentView,+ inputExpansionState,+ outputExpansionState,+ onInputExpansionChange,+ onOutputExpansionChange,+ setIsPrettyViewAvailable,+}: IOPreviewProps) {+ const capture = usePostHogClientCapture();++ // View state management+ const [localCurrentView, setLocalCurrentView] = useLocalStorage<ViewMode>(+ "jsonViewPreference",+ "pretty",+ );+ const selectedView = currentView ?? localCurrentView;+ const showViewToggle = currentView === undefined;++ const [compensateScrollRef, startPreserveScroll] =+ usePreserveRelativeScroll<HTMLDivElement>([selectedView]);++ // Parse input/output+ const parsedInput = deepParseJson(input);+ const parsedOutput = deepParseJson(output);++ // Parse ChatML format+ const {+ canDisplayAsChat,+ allMessages,+ additionalInput,+ allTools,+ toolCallCounts,+ messageToToolCallNumbers,+ toolNameToDefinitionNumber,+ } = useChatMLParser(input, output, metadata, observationName);++ // Notify parent about pretty view availability+ // Always true - we always show the toggle and let components decide rendering+ useEffect(() => {+ setIsPrettyViewAvailable?.(true);+ }, [setIsPrettyViewAvailable]);++ // Determine if markdown is safe to render (content size check)+ const shouldRenderMarkdown = useMemo(() => {+ const inputSize = JSON.stringify(parsedInput || {}).length;+ const outputSize = JSON.stringify(parsedOutput || {}).length;+ const messagesSize = JSON.stringify(allMessages).length;+ return (+ inputSize + outputSize + messagesSize <= MARKDOWN_RENDER_CHARACTER_LIMIT+ );+ }, [parsedInput, parsedOutput, allMessages]);++ // Handle view change with analytics+ const handleViewChange = (view: ViewMode) => {+ startPreserveScroll();+ capture("trace_detail:io_mode_switch", { view });+ setLocalCurrentView(view);+ };++ // Prepare additional input (only if non-empty)+ const additionalInputToShow = useMemo(() => {+ if (!additionalInput || Object.keys(additionalInput).length === 0) {+ return undefined;+ }+ return additionalInput;+ }, [additionalInput]);++ // Shared props for JsonInputOutputView+ const jsonViewProps = {+ parsedInput,+ parsedOutput,+ isLoading,+ media,+ selectedView,+ hideIfNull,+ hideInput,+ hideOutput,+ inputExpansionState,+ outputExpansionState,+ onInputExpansionChange,+ onOutputExpansionChange,+ };++ return (+ <>+ <SectionToolDefinitions+ tools={allTools}+ toolCallCounts={toolCallCounts}+ toolNameToDefinitionNumber={toolNameToDefinitionNumber}+ />++ {showViewToggle && (+ <ViewModeToggle+ selectedView={selectedView}+ onViewChange={handleViewChange}+ compensateScrollRef={compensateScrollRef}+ />+ )}++ {/*+ * Content views - BOTH are rendered but one is hidden via CSS.+ * This preserves component state (scroll position, expansion state, etc.)+ * when toggling between views, avoiding re-mount and data loss.+ */}+ <div style={{ display: selectedView === "pretty" ? "block" : "none" }}>+ {canDisplayAsChat ? (+ <div className="[&_.io-message-content]:px-2 [&_.io-message-header]:px-2">+ <ChatMessageList+ messages={allMessages}+ shouldRenderMarkdown={shouldRenderMarkdown}+ additionalInput={additionalInputToShow}+ media={media ?? []}+ currentView={selectedView}+ messageToToolCallNumbers={messageToToolCallNumbers}+ />+ </div>+ ) : (+ <JsonInputOutputView {...jsonViewProps} />+ )}+ </div>++ <div style={{ display: selectedView === "json" ? "block" : "none" }}>+ <JsonInputOutputView {...jsonViewProps} />+ </div>+ </>+ );+}diff --git a/web/src/components/trace2/components/IOPreview/components/ChatMessage.tsx b/web/src/components/trace2/components/IOPreview/components/ChatMessage.tsxnew file mode 100644index 0000000000..bfbb4b0808--- /dev/null+++ b/web/src/components/trace2/components/IOPreview/components/ChatMessage.tsx@@ -0,0 +1,212 @@+import { useState } from "react";+import { cn } from "@/src/utils/tailwind";+import { Button } from "@/src/components/ui/button";+import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";+import {+ MarkdownJsonView,+ MarkdownJsonViewHeader,+} from "@/src/components/ui/MarkdownJsonView";+import { ToolCallInvocationsView } from "@/src/components/trace2/components/ToolCallInvocationsView";+import { ListChevronsDownUp, ListChevronsUpDown } from "lucide-react";+import { copyTextToClipboard } from "@/src/utils/clipboard";+import {+ type ChatMlMessage,+ getMessageTitle,+ hasRenderableContent,+ hasAdditionalData,+ hasPassthroughJson,+ isPlaceholderMessage,+ isOnlyJsonMessage,+ parseToolCallsFromMessage,+} from "./chat-message-utils";++// View mode for pretty/json toggle+export type ViewMode = "pretty" | "json";++// ChatMessage props+export interface ChatMessageProps {+ message: ChatMlMessage;+ shouldRenderMarkdown: boolean;+ currentView: ViewMode;+ toolCallNumbers?: number[];+ projectIdForPromptButtons?: string;+}++/**+ * ChatMessage renders a single ChatML message with appropriate view.+ *+ * Handles different message types:+ * - Placeholder messages+ * - JSON-only messages (non-ChatML objects)+ * - Content messages with optional tool calls+ * - Tool-call-only messages (no content)+ */+export function ChatMessage({+ message,+ shouldRenderMarkdown,+ currentView,+ toolCallNumbers,+ projectIdForPromptButtons,+}: ChatMessageProps) {+ const [showTableView, setShowTableView] = useState(false);++ const title = getMessageTitle(message);+ const toolCalls = parseToolCallsFromMessage(message);+ const hasContent = hasRenderableContent(message);++ // Toggle button for passthrough JSON+ const passthroughToggleButton = hasPassthroughJson(message) ? (+ <Button+ variant="ghost"+ size="icon-xs"+ onClick={() => setShowTableView((v) => !v)}+ title={+ showTableView ? "Show formatted view" : "Show passthrough JSON data"+ }+ className="-mr-2 hover:bg-border"+ >+ {showTableView ? (+ <ListChevronsDownUp className="h-3 w-3 text-primary" />+ ) : (+ <ListChevronsUpDown className="h-3 w-3" />+ )}+ </Button>+ ) : undefined;++ // Placeholder message+ if (isPlaceholderMessage(message)) {+ return (+ <div className={cn("transition-colors hover:bg-muted")}>+ <div style={{ display: shouldRenderMarkdown ? "block" : "none" }}>+ <MarkdownJsonView+ title="Placeholder"+ content={message.name || "Unnamed placeholder"}+ customCodeHeaderClassName={cn("bg-primary-foreground")}+ />+ </div>+ <div style={{ display: shouldRenderMarkdown ? "none" : "block" }}>+ <PrettyJsonView+ title="Placeholder"+ json={message.name || "Unnamed placeholder"}+ projectIdForPromptButtons={projectIdForPromptButtons}+ currentView={currentView}+ />+ </div>+ </div>+ );+ }++ // JSON-only message (non-ChatML object)+ if (isOnlyJsonMessage(message)) {+ return (+ <div className={cn("transition-colors hover:bg-muted")}>+ <PrettyJsonView+ title={title || "Output"}+ json={message.json}+ projectIdForPromptButtons={projectIdForPromptButtons}+ currentView={currentView}+ />+ </div>+ );+ }++ // User toggled to show passthrough JSON+ if (showTableView) {+ return (+ <div className={cn("transition-colors hover:bg-muted")}>+ <PrettyJsonView+ title={title}+ json={message.json}+ projectIdForPromptButtons={projectIdForPromptButtons}+ currentView="pretty"+ controlButtons={passthroughToggleButton}+ />+ </div>+ );+ }++ // Tool-call-only message (no content)+ if (!hasContent && toolCalls.length > 0) {+ return (+ <div className={cn("transition-colors hover:bg-muted")}>+ <MarkdownJsonViewHeader+ title={title}+ handleOnValueChange={() => {}}+ handleOnCopy={() => {+ const rawText = JSON.stringify(message, null, 2);+ void copyTextToClipboard(rawText);+ }}+ controlButtons={passthroughToggleButton}+ />+ <ToolCallInvocationsView+ message={message}+ toolCallNumbers={toolCallNumbers}+ />+ </div>+ );+ }++ // Content message (with optional tool calls)+ if (hasContent) {+ return (+ <div className={cn("transition-colors hover:bg-muted")}>+ {/* Markdown view */}+ <div style={{ display: shouldRenderMarkdown ? "block" : "none" }}>+ <MarkdownJsonView+ title={title}+ content={message.content || '""'}+ customCodeHeaderClassName={cn(+ message.role === "assistant" && "bg-secondary",+ message.role === "system" && "bg-primary-foreground",+ )}+ audio={message.audio}+ controlButtons={passthroughToggleButton}+ />+ {toolCalls.length > 0 && (+ <div className="mt-2">+ <ToolCallInvocationsView+ message={message}+ toolCallNumbers={toolCallNumbers}+ />+ </div>+ )}+ </div>++ {/* JSON view */}+ <div style={{ display: shouldRenderMarkdown ? "none" : "block" }}>+ <PrettyJsonView+ title={title}+ json={message.content}+ projectIdForPromptButtons={projectIdForPromptButtons}+ currentView={currentView}+ controlButtons={passthroughToggleButton}+ />+ {toolCalls.length > 0 && (+ <div className="mt-2">+ <ToolCallInvocationsView+ message={message}+ toolCallNumbers={toolCallNumbers}+ />+ </div>+ )}+ </div>+ </div>+ );+ }++ // Fallback: message with additional data but no content+ if (hasAdditionalData(message)) {+ return (+ <div className={cn("transition-colors hover:bg-muted")}>+ <PrettyJsonView+ title={title || "Message"}+ json={message}+ projectIdForPromptButtons={projectIdForPromptButtons}+ currentView={currentView}+ />+ </div>+ );+ }++ return null;+}diff --git a/web/src/components/trace2/components/IOPreview/components/ChatMessageList.tsx b/web/src/components/trace2/components/IOPreview/components/ChatMessageList.tsxnew file mode 100644index 0000000000..e209c1ef1b--- /dev/null+++ b/web/src/components/trace2/components/IOPreview/components/ChatMessageList.tsx@@ -0,0 +1,116 @@+import { Fragment, useMemo, useState } from "react";+import { Button } from "@/src/components/ui/button";+import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";+import { ChatMessage, type ViewMode } from "./ChatMessage";+import { SectionMedia } from "./SectionMedia";+import { type ChatMlMessage, shouldRenderMessage } from "./chat-message-utils";+import { type MediaReturnType } from "@/src/features/media/validation";++const COLLAPSE_THRESHOLD = 3;++// ChatMessageList props+export interface ChatMessageListProps {+ messages: ChatMlMessage[];+ shouldRenderMarkdown: boolean;+ media?: MediaReturnType[];+ additionalInput?: Record<string, unknown>;+ currentView: ViewMode;+ messageToToolCallNumbers: Map<number, number[]>;+ collapseLongHistory?: boolean;+ projectIdForPromptButtons?: string;+}++/**+ * ChatMessageList renders a list of ChatML messages with collapse/expand.+ *+ * Features:+ * - Filters out empty messages+ * - Collapses long history (shows first + last N messages)+ * - Renders additional input section+ * - Renders media section+ */+export function ChatMessageList({+ messages,+ shouldRenderMarkdown,+ media,+ additionalInput,+ currentView,+ messageToToolCallNumbers,+ collapseLongHistory = true,+ projectIdForPromptButtons,+}: ChatMessageListProps) {+ // Filter messages to only those with renderable content+ const messagesToRender = useMemo(+ () => messages.filter(shouldRenderMessage),+ [messages],+ );++ // Initialize collapsed state based on message count+ const [isCollapsed, setCollapsed] = useState<boolean | null>(+ collapseLongHistory && messagesToRender.length > COLLAPSE_THRESHOLD+ ? true+ : null,+ );++ return (+ <div className="flex max-h-full min-h-0 flex-col gap-2">+ <div className="flex max-h-full min-h-0 flex-col gap-2">+ <div className="flex flex-col gap-2">+ {messagesToRender+ .map((message, originalIndex) => ({ message, originalIndex }))+ .filter(+ ({ originalIndex }) =>+ // Show all if not collapsed or null+ // Show first and last N if collapsed+ !isCollapsed ||+ originalIndex === 0 ||+ originalIndex > messagesToRender.length - COLLAPSE_THRESHOLD,+ )+ .map(({ message, originalIndex }) => (+ <Fragment key={originalIndex}>+ <ChatMessage+ message={message}+ shouldRenderMarkdown={shouldRenderMarkdown}+ currentView={currentView}+ toolCallNumbers={messageToToolCallNumbers.get(originalIndex)}+ projectIdForPromptButtons={projectIdForPromptButtons}+ />+ {/* Show collapse/expand button after first message */}+ {isCollapsed !== null && originalIndex === 0 && (+ <Button+ variant="ghost"+ size="xs"+ onClick={() => setCollapsed((v) => !v)}+ className="underline"+ >+ {isCollapsed+ ? `Show ${messagesToRender.length - COLLAPSE_THRESHOLD} more ...`+ : "Hide history"}+ </Button>+ )}+ </Fragment>+ ))}+ </div>++ {/* Additional input section */}+ {additionalInput && (+ <PrettyJsonView+ title="Additional Input"+ json={additionalInput}+ projectIdForPromptButtons={projectIdForPromptButtons}+ currentView={shouldRenderMarkdown ? "pretty" : "json"}+ />+ )}++ {/* Media section */}+ {media && media.length > 0 && <SectionMedia media={media} />}+ </div>+ </div>+ );+}++/**+ * OpenAiMessageView - Alias for backwards compatibility.+ * @deprecated Use ChatMessageList instead.+ */+export const OpenAiMessageView = ChatMessageList;diff --git a/web/src/components/trace2/components/IOPreview/components/SectionMedia.tsx b/web/src/components/trace2/components/IOPreview/components/SectionMedia.tsxnew file mode 100644index 0000000000..d5f55611fc--- /dev/null+++ b/web/src/components/trace2/components/IOPreview/components/SectionMedia.tsx@@ -0,0 +1,33 @@+import { LangfuseMediaView } from "@/src/components/ui/LangfuseMediaView";+import { type MediaReturnType } from "@/src/features/media/validation";++// SectionMedia props+export interface SectionMediaProps {+ media: MediaReturnType[];+}++/**+ * SectionMedia renders media attachments at the bottom of the message list.+ */+export function SectionMedia({ media }: SectionMediaProps) {+ if (media.length === 0) {+ return null;+ }++ return (+ <>+ <div className="mx-3 border-t px-2 py-1 text-xs text-muted-foreground">+ Media+ </div>+ <div className="flex flex-wrap gap-2 p-4 pt-1">+ {media.map((m) => (+ <LangfuseMediaView+ mediaAPIReturnValue={m}+ asFileIcon={true}+ key={m.mediaId}+ />+ ))}+ </div>+ </>+ );+}diff --git a/web/src/components/trace2/components/IOPreview/components/SectionToolDefinitions.tsx b/web/src/components/trace2/components/IOPreview/components/SectionToolDefinitions.tsxnew file mode 100644index 0000000000..ffc60e17f2--- /dev/null+++ b/web/src/components/trace2/components/IOPreview/components/SectionToolDefinitions.tsx@@ -0,0 +1,42 @@+import {+ ToolCallDefinitionCard,+ type ToolDefinition,+} from "./ToolCallDefinitionCard";++// SectionToolDefinitions props+export interface SectionToolDefinitionsProps {+ tools: ToolDefinition[];+ toolCallCounts: Map<string, number>;+ toolNameToDefinitionNumber: Map<string, number>;+}++/**+ * SectionToolDefinitions renders tool definition cards at the top of IOPreview.+ *+ * Shows available tools with their call counts and definition numbers.+ */+export function SectionToolDefinitions({+ tools,+ toolCallCounts,+ toolNameToDefinitionNumber,+}: SectionToolDefinitionsProps) {+ if (tools.length === 0) {+ return null;+ }++ return (+ <div className="[&_.io-message-content]:px-2 [&_.io-message-header]:px-2">+ <div className="mb-4 border-b border-border pb-4">+ <div className="io-message-header px-1 py-1 text-sm font-medium capitalize">+ Tools+ </div>+ <ToolCallDefinitionCard+ tools={tools}+ toolCallCounts={toolCallCounts}+ toolNameToDefinitionNumber={toolNameToDefinitionNumber}+ className="px-2"+ />+ </div>+ </div>+ );+}diff --git a/web/src/components/trace2/components/IOPreview/components/ToolCallDefinitionCard.tsx b/web/src/components/trace2/components/IOPreview/components/ToolCallDefinitionCard.tsxnew file mode 100644index 0000000000..d76959ed2a--- /dev/null+++ b/web/src/components/trace2/components/IOPreview/components/ToolCallDefinitionCard.tsx@@ -0,0 +1,187 @@+import { ChevronRight, ChevronDown, Wrench } from "lucide-react";+import { Badge } from "@/src/components/ui/badge";+import { cn } from "@/src/utils/tailwind";+import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";+import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";+import useLocalStorage from "@/src/components/useLocalStorage";+import { useState } from "react";++// Tool definition extracted from messages+export interface ToolDefinition {+ name: string;+ description?: string;+ parameters?: Record<string, unknown>;+}++// ToolCallDefinitionCard props+export interface ToolCallDefinitionCardProps {+ tools: ToolDefinition[];+ toolCallCounts: Map<string, number>;+ toolNameToDefinitionNumber?: Map<string, number>;+ className?: string;+}++/**+ * ToolCallDefinitionCard renders expandable cards for tool definitions.+ *+ * Features:+ * - Accordion-style expansion (one tool at a time)+ * - Status badges showing call count+ * - Formatted/JSON view toggle for parameters+ * - Definition numbers for reference+ */+export function ToolCallDefinitionCard({+ tools,+ toolCallCounts,+ toolNameToDefinitionNumber,+ className,+}: ToolCallDefinitionCardProps) {+ const [expandedIndex, setExpandedIndex] = useState<number | null>(null);+ const [currentView, setCurrentView] = useLocalStorage<"formatted" | "json">(+ "toolCallPillViewPreference",+ "formatted",+ );++ if (!tools || tools.length === 0) {+ return null;+ }++ return (+ <div className={cn("flex flex-col gap-2", className)}>+ {tools.map((tool, index) => {+ const isExpanded = expandedIndex === index;+ const callCount = toolCallCounts.get(tool.name) || 0;+ const isCalled = callCount > 0;+ const toolDefinitionNumber = toolNameToDefinitionNumber?.get(tool.name);+ const statusText =+ callCount === 0+ ? "not called"+ : callCount === 1+ ? "called"+ : `called ${callCount}x`;++ return (+ <div+ key={`${tool.name}-${index}`}+ className="w-full overflow-hidden rounded-sm border"+ >+ {/* Card header */}+ <div+ className="flex w-full cursor-pointer items-center justify-between gap-2 px-3 py-1.5 hover:bg-muted/20"+ onClick={() => {+ setExpandedIndex(isExpanded ? null : index);+ }}+ >+ {/* Left: Tool icon + definition number + name */}+ <div className="flex items-center gap-2">+ <Wrench className="h-3.5 w-3.5 text-muted-foreground" />+ <span className="font-mono text-xs font-medium text-foreground">+ {toolDefinitionNumber !== undefined && (+ <span className="mr-1">{toolDefinitionNumber}.</span>+ )}+ {tool.name}+ </span>+ </div>++ {/* Right: Status badge + chevron indicator */}+ <div className="flex items-center gap-1.5">+ <Badge+ variant={isCalled ? undefined : "secondary"}+ className={cn(+ "text-xs font-medium",+ isCalled &&+ "select-none border-transparent bg-light-green text-dark-green hover:bg-light-green",+ )}+ >+ {statusText}+ </Badge>++ {/* Chevron indicator */}+ {isExpanded ? (+ <ChevronDown className="h-3.5 w-3.5 text-muted-foreground" />+ ) : (+ <ChevronRight className="h-3.5 w-3.5 text-muted-foreground" />+ )}+ </div>+ </div>++ {/* Expanded details view */}+ {isExpanded && (+ <div className="relative border-t border-border bg-muted/30 px-4 py-3">+ {/* View toggle tabs - positioned top right */}+ <div className="absolute right-4 top-1">+ <Tabs+ className="h-fit py-0.5"+ value={currentView}+ onValueChange={(value) =>+ setCurrentView(value as "formatted" | "json")+ }+ >+ <TabsList className="h-fit p-0.5">+ <TabsTrigger+ value="formatted"+ className="h-fit px-1 text-xs"+ >+ Formatted+ </TabsTrigger>+ <TabsTrigger value="json" className="h-fit px-1 text-xs">+ JSON+ </TabsTrigger>+ </TabsList>+ </Tabs>+ </div>++ {/* Formatted view */}+ {currentView === "formatted" && (+ <div className="space-y-4">+ {/* Description */}+ {tool.description && (+ <div>+ <div className="mb-1.5 text-xs font-medium text-muted-foreground">+ Description+ </div>+ <div className="text-sm text-foreground">+ {tool.description}+ </div>+ </div>+ )}++ {/* Parameters */}+ {tool.parameters && (+ <div>+ <div className="mb-1.5 text-xs font-medium text-muted-foreground">+ Parameters+ </div>+ <PrettyJsonView+ json={tool.parameters}+ currentView="pretty"+ codeClassName="text-xs"+ />+ </div>+ )}++ {/* Show message if no additional details */}+ {!tool.description && !tool.parameters && (+ <div className="text-sm text-muted-foreground">+ No additional details available+ </div>+ )}+ </div>+ )}++ {/* JSON view - full tool object */}+ {currentView === "json" && (+ <PrettyJsonView+ json={tool}+ currentView="json"+ codeClassName="text-xs"+ />+ )}+ </div>+ )}+ </div>+ );+ })}+ </div>+ );+}diff --git a/web/src/components/trace2/components/IOPreview/components/ViewModeToggle.tsx b/web/src/components/trace2/components/IOPreview/components/ViewModeToggle.tsxnew file mode 100644index 0000000000..dce08cd119--- /dev/null+++ b/web/src/components/trace2/components/IOPreview/components/ViewModeToggle.tsx@@ -0,0 +1,35 @@+import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";++export type ViewMode = "pretty" | "json";++export interface ViewModeToggleProps {+ selectedView: ViewMode;+ onViewChange: (view: ViewMode) => void;+ compensateScrollRef: React.RefObject<HTMLDivElement | null>;+}++export function ViewModeToggle({+ selectedView,+ onViewChange,+ compensateScrollRef,+}: ViewModeToggleProps) {+ return (+ <div className="flex w-full flex-row justify-start">+ <Tabs+ ref={compensateScrollRef}+ className="h-fit py-0.5"+ value={selectedView}+ onValueChange={(value) => onViewChange(value as ViewMode)}+ >+ <TabsList className="h-fit p-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>+ </TabsList>+ </Tabs>+ </div>+ );+}diff --git a/web/src/components/trace2/components/IOPreview/components/chat-message-utils.clienttest.ts b/web/src/components/trace2/components/IOPreview/components/chat-message-utils.clienttest.tsnew file mode 100644index 0000000000..43a0e135bf--- /dev/null+++ b/web/src/components/trace2/components/IOPreview/components/chat-message-utils.clienttest.ts@@ -0,0 +1,316 @@+import { type ChatMlMessage } from "./chat-message-utils";+import {+ getMessageTitle,+ hasRenderableContent,+ hasAdditionalData,+ hasPassthroughJson,+ isPlaceholderMessage,+ isOnlyJsonMessage,+ shouldRenderMessage,+ parseToolCallsFromMessage,+} from "./chat-message-utils";++// Helper to create test messages - only includes fields that are explicitly passed+// This is important because hasAdditionalData checks Object.keys()+const createMessage = (fields: Partial<ChatMlMessage>): ChatMlMessage =>+ fields as ChatMlMessage;++describe("chat-message-utils", () => {+ describe("getMessageTitle", () => {+ it("returns name when present", () => {+ expect(+ getMessageTitle(createMessage({ role: "user", name: "John" })),+ ).toBe("John");+ });++ it("returns role when name is not present", () => {+ expect(getMessageTitle(createMessage({ role: "assistant" }))).toBe(+ "assistant",+ );+ });++ it("returns empty string when neither name nor role present", () => {+ expect(+ getMessageTitle(createMessage({ role: undefined, name: undefined })),+ ).toBe("");+ });+ });++ describe("hasRenderableContent", () => {+ it("returns true when content is non-empty string", () => {+ expect(+ hasRenderableContent(createMessage({ role: "user", content: "Hello" })),+ ).toBe(true);+ });++ it("returns false when content is empty string", () => {+ expect(+ hasRenderableContent(createMessage({ role: "user", content: "" })),+ ).toBe(false);+ });++ it("returns false when content is null", () => {+ expect(+ hasRenderableContent(createMessage({ role: "user", content: null })),+ ).toBe(false);+ });++ it("returns true when audio is present", () => {+ expect(+ hasRenderableContent(+ createMessage({+ role: "user",+ content: "",+ audio: {+ data: {+ type: "base64",+ id: "1",+ source: "",+ referenceString: "",+ },+ },+ }),+ ),+ ).toBe(true);+ });+ });++ describe("hasAdditionalData", () => {+ it("returns false when only role and content present", () => {+ expect(+ hasAdditionalData(createMessage({ role: "user", content: "Hello" })),+ ).toBe(false);+ });++ it("returns true when tool_calls present", () => {+ expect(+ hasAdditionalData(+ createMessage({+ role: "assistant",+ content: "",+ tool_calls: [{ id: "1", name: "test", arguments: "{}" }],+ }),+ ),+ ).toBe(true);+ });++ it("returns true when json present", () => {+ expect(+ hasAdditionalData(+ createMessage({+ role: "user",+ content: "",+ json: { extra: "data" },+ }),+ ),+ ).toBe(true);+ });+ });++ describe("hasPassthroughJson", () => {+ it("returns true when json field is present", () => {+ expect(+ hasPassthroughJson(+ createMessage({+ role: "user",+ content: "",+ json: { data: "test" },+ }),+ ),+ ).toBe(true);+ });++ it("returns false when json field is not present", () => {+ expect(+ hasPassthroughJson(createMessage({ role: "user", content: "" })),+ ).toBe(false);+ });++ it("returns false when json is null", () => {+ expect(+ hasPassthroughJson(+ createMessage({ role: "user", content: "", json: null as any }),+ ),+ ).toBe(false);+ });+ });++ describe("isPlaceholderMessage", () => {+ it("returns true for placeholder type", () => {+ expect(+ isPlaceholderMessage(+ createMessage({+ role: "user",+ content: "",+ type: "placeholder",+ }),+ ),+ ).toBe(true);+ });++ it("returns false for non-placeholder", () => {+ expect(+ isPlaceholderMessage(createMessage({ role: "user", content: "" })),+ ).toBe(false);+ });+ });++ describe("isOnlyJsonMessage", () => {+ it("returns true when only json field present (no content, tool_calls, or audio)", () => {+ expect(+ isOnlyJsonMessage(+ createMessage({+ role: "assistant",+ content: undefined,+ json: { data: "test" },+ }),+ ),+ ).toBe(true);+ });++ it("returns false when content is present", () => {+ expect(+ isOnlyJsonMessage(+ createMessage({+ role: "assistant",+ content: "Hello",+ json: { data: "test" },+ }),+ ),+ ).toBe(false);+ });++ it("returns false when tool_calls present", () => {+ expect(+ isOnlyJsonMessage(+ createMessage({+ role: "assistant",+ tool_calls: [{ id: "1", name: "test", arguments: "{}" }],+ json: { data: "test" },+ }),+ ),+ ).toBe(false);+ });++ it("returns false when audio present", () => {+ expect(+ isOnlyJsonMessage(+ createMessage({+ role: "assistant",+ audio: {+ data: {+ type: "base64",+ id: "1",+ source: "",+ referenceString: "",+ },+ },+ json: { data: "test" },+ }),+ ),+ ).toBe(false);+ });++ it("returns false when no json present", () => {+ expect(+ isOnlyJsonMessage(+ createMessage({+ role: "assistant",+ }),+ ),+ ).toBe(false);+ });+ });++ describe("shouldRenderMessage", () => {+ it("returns true for message with content", () => {+ expect(+ shouldRenderMessage(createMessage({ role: "user", content: "Hello" })),+ ).toBe(true);+ });++ it("returns true for placeholder message", () => {+ expect(+ shouldRenderMessage(+ createMessage({+ role: "user",+ content: "",+ type: "placeholder",+ }),+ ),+ ).toBe(true);+ });++ it("returns true for message with additional data", () => {+ expect(+ shouldRenderMessage(+ createMessage({+ role: "assistant",+ content: "",+ tool_calls: [{ id: "1", name: "test", arguments: "{}" }],+ }),+ ),+ ).toBe(true);+ });++ it("returns false for empty message", () => {+ expect(+ shouldRenderMessage(createMessage({ role: "user", content: "" })),+ ).toBe(false);+ });+ });++ describe("parseToolCallsFromMessage", () => {+ it("returns tool_calls array when present", () => {+ const toolCalls = [{ id: "1", name: "test", arguments: "{}" }];+ expect(+ parseToolCallsFromMessage(+ createMessage({+ role: "assistant",+ content: "",+ tool_calls: toolCalls,+ }),+ ),+ ).toEqual(toolCalls);+ });++ it("returns json.tool_calls when tool_calls not present", () => {+ const toolCalls = [{ id: "2", name: "other" }];+ expect(+ parseToolCallsFromMessage(+ createMessage({+ role: "assistant",+ content: "",+ json: { tool_calls: toolCalls },+ }),+ ),+ ).toEqual(toolCalls);+ });++ it("returns empty array when no tool_calls", () => {+ expect(+ parseToolCallsFromMessage(+ createMessage({+ role: "assistant",+ content: "Hello",+ }),+ ),+ ).toEqual([]);+ });++ it("prefers direct tool_calls over json.tool_calls", () => {+ const directToolCalls = [{ id: "1", name: "direct", arguments: "{}" }];+ const jsonToolCalls = [{ id: "2", name: "json" }];+ expect(+ parseToolCallsFromMessage(+ createMessage({+ role: "assistant",+ content: "",+ tool_calls: directToolCalls,+ json: { tool_calls: jsonToolCalls },+ }),+ ),+ ).toEqual(directToolCalls);+ });+ });+});diff --git a/web/src/components/trace2/components/IOPreview/components/chat-message-utils.ts b/web/src/components/trace2/components/IOPreview/components/chat-message-utils.tsnew file mode 100644index 0000000000..947cdb6f83--- /dev/null+++ b/web/src/components/trace2/components/IOPreview/components/chat-message-utils.ts@@ -0,0 +1,82 @@+import type { z } from "zod/v4";+import type { ChatMlMessageSchema } from "@/src/components/schemas/ChatMlSchema";+import type { combineInputOutputMessages } from "@/src/utils/chatml";++export type ChatMlMessage = z.infer<typeof ChatMlMessageSchema>;++/**+ * Get display title for a message based on name or role.+ */+export function getMessageTitle(message: ChatMlMessage): string {+ return message.name ?? message.role ?? "";+}++/**+ * Check if message has renderable content (text or audio).+ */+export function hasRenderableContent(message: ChatMlMessage): boolean {+ const hasContent = message.content != null && message.content !== "";+ return hasContent || !!message.audio;+}++/**+ * Check if message has additional data beyond role and content.+ */+export function hasAdditionalData(message: ChatMlMessage): boolean {+ const messageKeys = Object.keys(message).filter(+ (key) => key !== "role" && key !== "content",+ );+ return messageKeys.length > 0;+}++/**+ * Check if message has passthrough JSON data.+ */+export function hasPassthroughJson(message: ChatMlMessage): boolean {+ return message.json != null;+}++/**+ * Check if message is a placeholder type.+ */+export function isPlaceholderMessage(message: ChatMlMessage): boolean {+ return message.type === "placeholder";+}++/**+ * Check if message only has JSON (no valid ChatML content).+ * Message parsed as ChatML but only has json field (non-ChatML object).+ * Valid ChatML needs content OR tool_calls OR audio (role alone is insufficient).+ */+export function isOnlyJsonMessage(message: ChatMlMessage): boolean {+ const hasValidChatMlContent =+ message.content != null ||+ message.tool_calls != null ||+ message.audio != null;+ return !hasValidChatMlContent && message.json != null;+}++/**+ * Check if message should be rendered (has content, audio, additional data, or is placeholder).+ */+export function shouldRenderMessage(message: ChatMlMessage): boolean {+ return (+ hasRenderableContent(message) ||+ hasAdditionalData(message) ||+ isPlaceholderMessage(message)+ );+}++/**+ * Parse tool calls from a ChatML message.+ * Handles both standard tool_calls array and passthrough json.tool_calls.+ */+export function parseToolCallsFromMessage(+ message: ReturnType<typeof combineInputOutputMessages>[0],+): unknown[] {+ return message.tool_calls && Array.isArray(message.tool_calls)+ ? message.tool_calls+ : message.json?.tool_calls && Array.isArray(message.json?.tool_calls)+ ? message.json.tool_calls+ : [];+}diff --git a/web/src/components/trace2/components/IOPreview/hooks/useChatMLParser.ts b/web/src/components/trace2/components/IOPreview/hooks/useChatMLParser.tsnew file mode 100644index 0000000000..95ba55d5bc--- /dev/null+++ b/web/src/components/trace2/components/IOPreview/hooks/useChatMLParser.ts@@ -0,0 +1,164 @@+import { useMemo } from "react";+import type { z } from "zod/v4";+import { type Prisma, deepParseJson } from "@langfuse/shared";+import {+ normalizeInput,+ normalizeOutput,+ combineInputOutputMessages,+ cleanLegacyOutput,+ extractAdditionalInput,+} from "@/src/utils/chatml";+import type { ChatMlMessageSchema } from "@/src/components/schemas/ChatMlSchema";++// ChatML message type from schema+export type ChatMlMessage = z.infer<typeof ChatMlMessageSchema>;++// Tool definition extracted from messages+export interface ToolDefinition {+ name: string;+ description?: string;+ parameters?: Record<string, unknown>;+}++// Result from ChatML parsing hook+export interface ChatMLParserResult {+ canDisplayAsChat: boolean;+ allMessages: ChatMlMessage[];+ additionalInput: Record<string, unknown> | undefined;+ allTools: ToolDefinition[];+ toolCallCounts: Map<string, number>;+ messageToToolCallNumbers: Map<number, number[]>;+ toolNameToDefinitionNumber: Map<string, number>;+}++/**+ * Parse tool calls from a ChatML message.+ * Handles both standard tool_calls array and passthrough json.tool_calls.+ */+function parseToolCallsFromMessage(+ message: ReturnType<typeof combineInputOutputMessages>[0],+) {+ return message.tool_calls && Array.isArray(message.tool_calls)+ ? message.tool_calls+ : message.json?.tool_calls && Array.isArray(message.json?.tool_calls)+ ? message.json.tool_calls+ : [];+}++/**+ * Hook to parse input/output into ChatML format and extract tool information.+ *+ * Handles:+ * - ChatML message normalization from various input formats+ * - Tool definition extraction from messages+ * - Tool call counting and numbering (output messages only)+ * - Additional non-message input extraction+ */+export function useChatMLParser(+ input: Prisma.JsonValue | undefined,+ output: Prisma.JsonValue | undefined,+ metadata: Prisma.JsonValue | undefined,+ observationName: string | undefined,+): ChatMLParserResult {+ const parsedInput = deepParseJson(input);+ const parsedOutput = deepParseJson(output);+ const parsedMetadata = deepParseJson(metadata);++ return useMemo(() => {+ const ctx = { metadata: parsedMetadata, observationName };+ const inResult = normalizeInput(parsedInput, ctx);+ const outResult = normalizeOutput(parsedOutput, ctx);+ const outputClean = cleanLegacyOutput(parsedOutput, parsedOutput);+ const messages = combineInputOutputMessages(+ inResult,+ outResult,+ outputClean,+ );++ // Extract all unique tools from messages (no numbering yet)+ const toolsMap = new Map<string, ToolDefinition>();++ for (const message of messages) {+ if (message.tools && Array.isArray(message.tools)) {+ for (const tool of message.tools) {+ if (!toolsMap.has(tool.name)) {+ toolsMap.set(tool.name, tool);+ }+ }+ }+ }++ // Count tool call invocations+ // Only number tool calls from OUTPUT messages (current invocation), not input (history)+ const inputMessageCount = inResult.success ? inResult.data.length : 0;+ let toolCallCounter = 0;+ const messageToToolCallNumbers = new Map<number, number[]>();+ const toolCallCounts = new Map<string, number>();++ for (let i = 0; i < messages.length; i++) {+ const message = messages[i];+ const isOutputMessage = i >= inputMessageCount;++ const toolCallList = parseToolCallsFromMessage(message);++ if (toolCallList.length > 0) {+ const messageToolNumbers: number[] = [];++ for (const toolCall of toolCallList) {+ const calledToolName =+ toolCall.name && typeof toolCall.name === "string"+ ? toolCall.name+ : // AI SDK has 'toolName'+ toolCall.toolName && typeof toolCall.toolName === "string"+ ? toolCall.toolName+ : undefined;++ if (calledToolName) {+ // Count tool calls from OUTPUT messages only+ if (isOutputMessage) {+ toolCallCounts.set(+ calledToolName,+ (toolCallCounts.get(calledToolName) || 0) + 1,+ );+ toolCallCounter++;+ messageToolNumbers.push(toolCallCounter);+ }+ }+ }++ if (messageToolNumbers.length > 0) {+ messageToToolCallNumbers.set(i, messageToolNumbers);+ }+ }+ }++ // Sort tools by display order (called first, then by call count)+ const sortedTools = Array.from(toolsMap.values()).sort((a, b) => {+ const callCountA = toolCallCounts.get(a.name) || 0;+ const callCountB = toolCallCounts.get(b.name) || 0;+ if (callCountA > 0 && callCountB === 0) return -1;+ if (callCountA === 0 && callCountB > 0) return 1;+ return callCountB - callCountA;+ });++ // Assign definition numbers based on sorted display order+ const toolNameToDefinitionNumber = new Map<string, number>();+ sortedTools.forEach((tool, index) => {+ toolNameToDefinitionNumber.set(tool.name, index + 1);+ });++ return {+ canDisplayAsChat:+ (inResult.success || outResult.success) && messages.length > 0,+ allMessages: messages as ChatMlMessage[],+ additionalInput: extractAdditionalInput(parsedInput),+ allTools: sortedTools,+ toolCallCounts,+ messageToToolCallNumbers,+ toolNameToDefinitionNumber,+ };+ }, [parsedInput, parsedOutput, parsedMetadata, observationName]);+}++// Re-export for use in ChatMessage+export { parseToolCallsFromMessage };diff --git a/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx b/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsxnew file mode 100644index 0000000000..2f287cbec1--- /dev/null+++ b/web/src/components/trace2/components/ObservationDetailView/ObservationDetailView.tsx@@ -0,0 +1,349 @@+/**+ * ObservationDetailView - Shows observation-level details when an observation is selected+ *+ * Responsibility:+ * - Display observation metadata (type, timestamp, model, environment, etc.)+ * - Show cost and token usage with tooltips+ * - Provide tabbed interface (Preview, Scores)+ * - Support Formatted/JSON toggle for preview content+ *+ * Hooks:+ * - useLocalStorage() - for JSON view preference+ * - useState() - for tab selection+ *+ * Re-renders when:+ * - Observation prop changes (new observation selected)+ * - Tab selection changes+ * - View mode toggle changes+ */++import {+ type ObservationType,+ AnnotationQueueObjectType,+ isGenerationLike,+} from "@langfuse/shared";+import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";+import { ItemBadge } from "@/src/components/ItemBadge";+import { LocalIsoDate } from "@/src/components/LocalIsoDate";+import {+ TabsBar,+ TabsBarContent,+ TabsBarList,+ 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,+ TimeToFirstTokenBadge,+ EnvironmentBadge,+ VersionBadge,+ LevelBadge,+ StatusMessageBadge,+} from "./ObservationMetadataBadgesSimple";+import { CostBadge, UsageBadge } from "./ObservationMetadataBadgesTooltip";+import { ModelBadge } from "./ObservationMetadataBadgeModel";+import { ModelParametersBadges } from "./ObservationMetadataBadgeModelParameters";+import ScoresTable from "@/src/components/table/use-cases/scores";+import { IOPreview } from "@/src/components/trace2/components/IOPreview/IOPreview";+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";++// Header action components+import { CopyIdsPopover } from "@/src/components/trace2/components/_shared/CopyIdsPopover";+import { NewDatasetItemFromExistingObject } from "@/src/features/datasets/components/NewDatasetItemFromExistingObject";+import { AnnotateDrawer } from "@/src/features/scores/components/AnnotateDrawer";+import { CreateNewAnnotationQueueItem } from "@/src/features/annotation-queues/components/CreateNewAnnotationQueueItem";+import { CommentDrawerButton } from "@/src/features/comments/CommentDrawerButton";+import { JumpToPlaygroundButton } from "@/src/features/playground/page/components/JumpToPlaygroundButton";+import { useTraceData } from "@/src/components/trace2/contexts/TraceDataContext";++export interface ObservationDetailViewProps {+ observation: ObservationReturnTypeWithMetadata;+ projectId: string;+ traceId: string;+}++export function ObservationDetailView({+ observation,+ projectId,+ traceId,+}: ObservationDetailViewProps) {+ const [selectedTab, setSelectedTab] = useState<"preview" | "scores">(+ "preview",+ );+ const [currentView, setCurrentView] = useLocalStorage<"pretty" | "json">(+ "jsonViewPreference",+ "pretty",+ );+ const [isPrettyViewAvailable, setIsPrettyViewAvailable] = useState(true);++ // Get comments, scores, and expansion state from contexts+ const { comments, scores } = useTraceData();+ const { expansionState, setFieldExpansion } = useJsonExpansion();+ const observationScores = useMemo(+ () => scores.filter((s) => s.observationId === observation.id),+ [scores, observation.id],+ );++ // Fetch observation input/output (not included in ObservationReturnTypeWithMetadata)+ const observationWithIO = api.observations.byId.useQuery(+ {+ observationId: observation.id,+ traceId: traceId,+ projectId: projectId,+ startTime: observation.startTime,+ },+ {+ staleTime: 5 * 60 * 1000, // 5 minutes+ },+ );++ // Fetch media for this observation+ const observationMedia = useMedia({+ projectId,+ traceId,+ observationId: observation.id,+ });++ // Calculate latency in seconds if not provided+ const latencySeconds = useMemo(() => {+ if (observation.latency) {+ return observation.latency;+ }+ if (observation.startTime && observation.endTime) {+ return (+ (observation.endTime.getTime() - observation.startTime.getTime()) / 1000+ );+ }+ return null;+ }, [observation.latency, observation.startTime, observation.endTime]);++ // Format cost and usage values+ const totalCost = observation.totalCost;+ const totalUsage = observation.totalUsage;+ const inputUsage = observation.inputUsage;+ const outputUsage = observation.outputUsage;++ 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">+ {/* 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">+ <div className="mt-1.5">+ <ItemBadge type={observation.type as ObservationType} isSmall />+ </div>+ <span className="mb-0 ml-1 line-clamp-2 min-w-0 break-all font-medium md:break-normal md:break-words">+ {observation.name || observation.id}+ </span>+ <CopyIdsPopover+ idItems={[+ { id: traceId, name: "Trace ID" },+ { id: observation.id, name: "Observation ID" },+ ]}+ />+ </div>+ {/* Action buttons */}+ <div className="flex h-full flex-wrap content-start items-start justify-start gap-0.5 @2xl:mr-1 @2xl:justify-end">+ {observationWithIO.data && (+ <NewDatasetItemFromExistingObject+ traceId={traceId}+ observationId={observation.id}+ projectId={projectId}+ input={observationWithIO.data.input}+ output={observationWithIO.data.output}+ metadata={observationWithIO.data.metadata}+ key={observation.id}+ size="sm"+ />+ )}+ <div className="flex items-start">+ <AnnotateDrawer+ key={"annotation-drawer-" + observation.id}+ projectId={projectId}+ scoreTarget={{+ type: "trace",+ traceId: traceId,+ observationId: observation.id,+ }}+ scores={observationScores}+ scoreMetadata={{+ projectId: projectId,+ environment: observation.environment,+ }}+ size="sm"+ />+ <CreateNewAnnotationQueueItem+ projectId={projectId}+ objectId={observation.id}+ objectType={AnnotationQueueObjectType.OBSERVATION}+ size="sm"+ />+ </div>+ {observationWithIO.data &&+ isGenerationLike(observationWithIO.data.type) && (+ <JumpToPlaygroundButton+ source="generation"+ generation={observationWithIO.data}+ analyticsEventName="trace_detail:test_in_playground_button_click"+ size="sm"+ />+ )}+ <CommentDrawerButton+ projectId={projectId}+ objectId={observation.id}+ objectType="OBSERVATION"+ count={comments.get(observation.id)}+ size="sm"+ />+ </div>+ </div>++ {/* Metadata badges */}+ <div className="flex flex-col gap-1">+ {/* Timestamp on its own row */}+ <div className="flex items-center">+ <LocalIsoDate+ date={observation.startTime}+ accuracy="millisecond"+ className="text-xs"+ />+ </div>+ {/* Other badges on second row */}+ <div className="flex flex-wrap items-center gap-1">+ <LatencyBadge latencySeconds={latencySeconds} />+ <TimeToFirstTokenBadge+ timeToFirstToken={observation.timeToFirstToken}+ />+ <EnvironmentBadge environment={observation.environment} />+ <CostBadge+ totalCost={totalCost}+ costDetails={observation.costDetails}+ />+ <UsageBadge+ type={observation.type}+ inputUsage={inputUsage}+ outputUsage={outputUsage}+ totalUsage={totalUsage}+ usageDetails={observation.usageDetails}+ />+ <VersionBadge version={observation.version} />+ <ModelBadge+ model={observation.model}+ internalModelId={observation.internalModelId}+ projectId={projectId}+ usageDetails={observation.usageDetails}+ />+ <ModelParametersBadges+ modelParameters={observation.modelParameters}+ />+ <LevelBadge level={observation.level} />+ <StatusMessageBadge statusMessage={observation.statusMessage} />+ </div>+ </div>+ </div>++ {/* Tabs section */}+ <TabsBar+ value={selectedTab}+ className="flex min-h-0 flex-1 flex-col overflow-hidden"+ onValueChange={(value) => setSelectedTab(value as "preview" | "scores")}+ >+ <TabsBarList>+ <TabsBarTrigger value="preview">Preview</TabsBarTrigger>+ <TabsBarTrigger value="scores">Scores</TabsBarTrigger>++ {/* View toggle (Formatted/JSON) - show for preview tab when pretty view is available */}+ {selectedTab === "preview" && isPrettyViewAvailable && (+ <Tabs+ className="ml-auto mr-1 h-fit px-2 py-0.5"+ value={currentView}+ onValueChange={(value) => {+ setCurrentView(value as "pretty" | "json");+ }}+ >+ <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>+ </TabsList>+ </Tabs>+ )}+ </TabsBarList>++ {/* Preview tab content */}+ <TabsBarContent+ 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">+ <IOPreview+ key={observation.id}+ observationName={observation.name ?? undefined}+ input={observationWithIO.data?.input ?? undefined}+ output={observationWithIO.data?.output ?? undefined}+ metadata={observationWithIO.data?.metadata ?? undefined}+ isLoading={observationWithIO.isLoading}+ media={observationMedia.data}+ currentView={currentView}+ setIsPrettyViewAvailable={setIsPrettyViewAvailable}+ inputExpansionState={expansionState.input}+ outputExpansionState={expansionState.output}+ onInputExpansionChange={(exp) => setFieldExpansion("input", exp)}+ onOutputExpansionChange={(exp) =>+ setFieldExpansion("output", exp)+ }+ />+ {observationWithIO.data?.metadata && (+ <div className="px-2">+ <PrettyJsonView+ key={observationWithIO.data.id + "-metadata"}+ title="Metadata"+ json={observationWithIO.data.metadata}+ media={observationMedia.data?.filter(+ (m) => m.field === "metadata",+ )}+ currentView={currentView}+ externalExpansionState={expansionState.metadata}+ onExternalExpansionChange={(exp) =>+ setFieldExpansion("metadata", exp)+ }+ />+ </div>+ )}+ </div>+ </TabsBarContent>++ {/* Scores tab content */}+ <TabsBarContent+ value="scores"+ className="mb-2 mr-4 mt-0 flex h-full min-h-0 flex-1 overflow-hidden"+ >+ <div className="flex h-full min-h-0 w-full flex-1 flex-col overflow-hidden">+ <ScoresTable+ projectId={projectId}+ traceId={traceId}+ observationId={observation.id}+ hiddenColumns={[+ "traceId",+ "observationId",+ "traceName",+ "jobConfigurationId",+ "userId",+ ]}+ localStorageSuffix="ObservationPreview"+ />+ </div>+ </TabsBarContent>+ </TabsBar>+ </div>+ );+}diff --git a/web/src/components/trace2/components/ObservationDetailView/ObservationMetadataBadgeModel.tsx b/web/src/components/trace2/components/ObservationDetailView/ObservationMetadataBadgeModel.tsxnew file mode 100644index 0000000000..7019d59f95--- /dev/null+++ b/web/src/components/trace2/components/ObservationDetailView/ObservationMetadataBadgeModel.tsx@@ -0,0 +1,68 @@+/**+ * Model badge for ObservationDetailView+ * Handles linked models (with external link) and unlinked models (with create form)+ */++import { Badge } from "@/src/components/ui/badge";+import { ExternalLinkIcon, PlusCircle } from "lucide-react";+import Link from "next/link";+import { UpsertModelFormDialog } from "@/src/features/models/components/UpsertModelFormDialog";++export function ModelBadge({+ model,+ internalModelId,+ projectId,+ usageDetails,+}: {+ model: string | null;+ internalModelId: string | null;+ projectId: string;+ usageDetails: Record<string, number> | undefined;+}) {+ if (!model) return null;++ // Linked model - show link to model settings+ if (internalModelId) {+ return (+ <Badge>+ <Link+ href={`/project/${projectId}/settings/models/${internalModelId}`}+ className="flex items-center"+ title="View model details"+ >+ <span className="truncate">{model}</span>+ <ExternalLinkIcon className="ml-1 h-3 w-3" />+ </Link>+ </Badge>+ );+ }++ // Unlinked model - show create form drawer+ return (+ <UpsertModelFormDialog+ action="create"+ projectId={projectId}+ prefilledModelData={{+ modelName: model,+ prices:+ usageDetails && Object.keys(usageDetails).length > 0+ ? Object.keys(usageDetails)+ .filter((key) => key !== "total")+ .reduce(+ (acc, key) => {+ acc[key] = 0.000001;+ return acc;+ },+ {} as Record<string, number>,+ )+ : undefined,+ }}+ className="cursor-pointer"+ >+ <Badge variant="tertiary" className="flex items-center gap-1">+ <span>{model}</span>+ <PlusCircle className="h-3 w-3" />+ </Badge>+ </UpsertModelFormDialog>+ );+}diff --git a/web/src/components/trace2/components/ObservationDetailView/ObservationMetadataBadgeModelParameters.tsx b/web/src/components/trace2/components/ObservationDetailView/ObservationMetadataBadgeModelParameters.tsxnew file mode 100644index 0000000000..34ed5315dc--- /dev/null+++ b/web/src/components/trace2/components/ObservationDetailView/ObservationMetadataBadgeModelParameters.tsx@@ -0,0 +1,50 @@+/**+ * Model parameters badges for ObservationDetailView+ * Renders dynamic badges for each model parameter with truncation+ */++import { type JsonNested } from "@langfuse/shared";+import { Badge } from "@/src/components/ui/badge";++export function ModelParametersBadges({+ modelParameters,+}: {+ modelParameters: JsonNested | null | undefined;+}) {+ // Only render if modelParameters is an object (not array, primitive, or null)+ if (+ !modelParameters ||+ typeof modelParameters !== "object" ||+ Array.isArray(modelParameters)+ ) {+ return null;+ }++ const entries = Object.entries(modelParameters).filter(+ ([_, value]) => value !== null,+ );++ if (entries.length === 0) return null;++ return (+ <>+ {entries.map(([key, value]) => {+ const valueString =+ Object.prototype.toString.call(value) === "[object Object]"+ ? JSON.stringify(value)+ : value?.toString();++ return (+ <Badge variant="tertiary" key={key} className="max-w-md">+ <span+ className="overflow-hidden text-ellipsis whitespace-nowrap"+ title={valueString}+ >+ {key}: {valueString}+ </span>+ </Badge>+ );+ })}+ </>+ );+}diff --git a/web/src/components/trace2/components/ObservationDetailView/ObservationMetadataBadgesSimple.tsx b/web/src/components/trace2/components/ObservationDetailView/ObservationMetadataBadgesSimple.tsxnew file mode 100644index 0000000000..1e45f8a9ff--- /dev/null+++ b/web/src/components/trace2/components/ObservationDetailView/ObservationMetadataBadgesSimple.tsx@@ -0,0 +1,83 @@+/**+ * Simple metadata badges for ObservationDetailView+ * Each badge handles its own null checks and returns null when data is unavailable+ */++import { Badge } from "@/src/components/ui/badge";+import { formatIntervalSeconds } from "@/src/utils/dates";++export function LatencyBadge({+ latencySeconds,+}: {+ latencySeconds: number | null;+}) {+ if (latencySeconds == null) return null;++ return (+ <Badge variant="tertiary">+ Latency: {formatIntervalSeconds(latencySeconds)}+ </Badge>+ );+}++export function TimeToFirstTokenBadge({+ timeToFirstToken,+}: {+ timeToFirstToken: number | null | undefined;+}) {+ if (timeToFirstToken == null) return null;++ return (+ <Badge variant="tertiary">+ Time to first token: {formatIntervalSeconds(timeToFirstToken)}+ </Badge>+ );+}++export function EnvironmentBadge({+ environment,+}: {+ environment: string | null | undefined;+}) {+ if (!environment) return null;++ return <Badge variant="tertiary">Env: {environment}</Badge>;+}++export function VersionBadge({+ version,+}: {+ version: string | null | undefined;+}) {+ if (!version) return null;++ return <Badge variant="tertiary">Version: {version}</Badge>;+}++export function LevelBadge({ level }: { level: string | null | undefined }) {+ if (!level || level === "DEFAULT") return null;++ return (+ <Badge+ variant={+ level === "ERROR"+ ? "destructive"+ : level === "WARNING"+ ? "warning"+ : "tertiary"+ }+ >+ {level}+ </Badge>+ );+}++export function StatusMessageBadge({+ statusMessage,+}: {+ statusMessage: string | null | undefined;+}) {+ if (!statusMessage) return null;++ return <Badge variant="tertiary">{statusMessage}</Badge>;+}diff --git a/web/src/components/trace2/components/ObservationDetailView/ObservationMetadataBadgesTooltip.tsx b/web/src/components/trace2/components/ObservationDetailView/ObservationMetadataBadgesTooltip.tsxnew file mode 100644index 0000000000..dc252ce50f--- /dev/null+++ b/web/src/components/trace2/components/ObservationDetailView/ObservationMetadataBadgesTooltip.tsx@@ -0,0 +1,67 @@+/**+ * Tooltip-based metadata badges for ObservationDetailView+ * These badges use BreakdownTooltip to show detailed cost/usage information+ */++import { type ObservationType, isGenerationLike } from "@langfuse/shared";+import { Badge } from "@/src/components/ui/badge";+import { BreakdownTooltip } from "@/src/components/trace2/components/_shared/BreakdownToolTip";+import { usdFormatter, formatTokenCounts } from "@/src/utils/numbers";+import { InfoIcon } from "lucide-react";++export function CostBadge({+ totalCost,+ costDetails,+}: {+ totalCost: number | null;+ costDetails: Record<string, number> | undefined;+}) {+ // Don't show if no cost data or cost is 0+ if (totalCost == null || totalCost === 0 || !costDetails) return null;++ return (+ <BreakdownTooltip details={costDetails} isCost={true}>+ <Badge variant="tertiary" className="flex items-center gap-1">+ <span>{usdFormatter(totalCost)}</span>+ <InfoIcon className="h-3 w-3" />+ </Badge>+ </BreakdownTooltip>+ );+}++export function UsageBadge({+ type,+ inputUsage,+ outputUsage,+ totalUsage,+ usageDetails,+}: {+ type: ObservationType;+ inputUsage: number;+ outputUsage: number;+ totalUsage: number;+ usageDetails: Record<string, number> | undefined;+}) {+ // Only show for generation-like observations+ if (!isGenerationLike(type) || !usageDetails) return null;++ const tokenText = formatTokenCounts(+ inputUsage,+ outputUsage,+ totalUsage,+ true,+ );+ const hasText = tokenText.length > 0;++ return (+ <BreakdownTooltip details={usageDetails} isCost={false}>+ <Badge+ variant="tertiary"+ className={`flex items-center gap-1 ${!hasText ? "h-6 pl-2" : ""}`}+ >+ {hasText && <span>{tokenText}</span>}+ <InfoIcon className="h-3 w-3" />+ </Badge>+ </BreakdownTooltip>+ );+}diff --git a/web/src/components/trace2/components/SpanContent.tsx b/web/src/components/trace2/components/SpanContent.tsxnew file mode 100644index 0000000000..263c04f62b--- /dev/null+++ b/web/src/components/trace2/components/SpanContent.tsx@@ -0,0 +1,204 @@+/**+ * SpanContent - Pure span/observation content renderer.+ *+ * Responsibilities:+ * - Render span-specific data (name, metrics, badges, scores)+ * - Apply view preferences (show/hide features)+ * - Format and display metrics with color coding+ *+ * Does NOT know about:+ * - Tree structure (indents, lines, collapse buttons)+ * - How it's being displayed (tree, list, timeline, etc.)+ *+ * This component can be reused in ANY context that needs to display span content:+ * - Tree view (wrapped in TreeNodeWrapper)+ * - Search results (standalone)+ * - Timeline view (custom layout)+ * - Preview cards (modal/panel)+ */++import { type TreeNode } from "../lib/types";+import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";+import { LevelColors } from "@/src/components/level-colors";+import { CommentCountIcon } from "@/src/features/comments/CommentCountIcon";+import { cn } from "@/src/utils/tailwind";+import { formatIntervalSeconds } from "@/src/utils/dates";+import { usdFormatter, formatTokenCounts } from "@/src/utils/numbers";+import { heatMapTextColor } from "@/src/components/trace2/lib/helpers";+import { useViewPreferences } from "../contexts/ViewPreferencesContext";+import { useTraceData } from "../contexts/TraceDataContext";+import type Decimal from "decimal.js";++interface SpanContentProps {+ node: TreeNode;+ parentTotalCost?: Decimal;+ parentTotalDuration?: number;+ commentCount?: number;+ onSelect?: () => void;+ className?: string;+}++export function SpanContent({+ node,+ parentTotalCost,+ parentTotalDuration,+ commentCount,+ onSelect,+ className,+}: SpanContentProps) {+ const { scores } = useTraceData();+ const {+ showDuration,+ showCostTokens,+ showScores,+ colorCodeMetrics,+ showComments,+ } = useViewPreferences();++ // Use pre-computed cost from the TreeNode+ const totalCost = node.totalCost;++ const duration =+ node.endTime && node.startTime+ ? node.endTime.getTime() - node.startTime.getTime()+ : node.latency+ ? node.latency * 1000+ : undefined;++ const shouldRenderDuration =+ showDuration && Boolean(duration || node.latency);++ const shouldRenderCostTokens =+ showCostTokens &&+ Boolean(+ node.inputUsage || node.outputUsage || node.totalUsage || totalCost,+ );++ const shouldRenderAnyMetrics = shouldRenderDuration || shouldRenderCostTokens;++ // Filter scores for this node+ const nodeScores =+ node.type === "TRACE"+ ? scores.filter((s) => s.observationId === null)+ : scores.filter((s) => s.observationId === node.id);++ return (+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ onSelect?.();+ }}+ 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",+ className,+ )}+ >+ <div className="flex min-w-0 flex-col">+ {/* Name and badges row */}+ <div className="flex min-w-0 items-center gap-2 overflow-hidden">+ <span className="flex-shrink truncate text-xs">+ {node.name || `Unnamed ${node.type.toLowerCase()}`}+ </span>++ <div className="flex items-center gap-x-2">+ {/* Comment count */}+ {showComments && commentCount !== undefined && (+ <CommentCountIcon count={commentCount} />+ )}++ {/* Level badge */}+ {node.type !== "TRACE" &&+ node.level &&+ node.level !== "DEFAULT" && (+ <div className="flex">+ <span+ className={cn(+ "rounded-sm p-0.5 text-xs",+ LevelColors[node.level as keyof typeof LevelColors]?.bg,+ LevelColors[node.level as keyof typeof LevelColors]?.text,+ )}+ >+ {node.level}+ </span>+ </div>+ )}+ </div>+ </div>++ {/* Metrics row */}+ {shouldRenderAnyMetrics && (+ <div className="flex flex-wrap gap-x-2">+ {/* Duration */}+ {shouldRenderDuration && (duration || node.latency) ? (+ <span+ title={+ node.children.length > 0 || node.type === "TRACE"+ ? "Aggregated duration of all child observations"+ : undefined+ }+ className={cn(+ "text-xs text-muted-foreground",+ parentTotalDuration &&+ colorCodeMetrics &&+ heatMapTextColor({+ max: parentTotalDuration,+ value:+ duration || (node.latency ? node.latency * 1000 : 0),+ }),+ )}+ >+ {formatIntervalSeconds(+ (duration || (node.latency ? node.latency * 1000 : 0)) / 1000,+ )}+ </span>+ ) : null}++ {/* Token counts */}+ {shouldRenderCostTokens &&+ (node.inputUsage || node.outputUsage || node.totalUsage) ? (+ <span className="text-xs text-muted-foreground">+ {formatTokenCounts(+ node.inputUsage,+ node.outputUsage,+ node.totalUsage,+ )}+ </span>+ ) : null}++ {/* Cost */}+ {shouldRenderCostTokens && totalCost ? (+ <span+ title={+ node.children.length > 0 || node.type === "TRACE"+ ? "Aggregated cost of all child observations"+ : undefined+ }+ className={cn(+ "text-xs text-muted-foreground",+ parentTotalCost &&+ colorCodeMetrics &&+ heatMapTextColor({+ max: parentTotalCost,+ value: totalCost,+ }),+ )}+ >+ {node.children.length > 0 || node.type === "TRACE" ? "∑ " : ""}+ {usdFormatter(totalCost.toNumber())}+ </span>+ ) : null}+ </div>+ )}++ {/* Scores row */}+ {showScores && nodeScores.length > 0 && (+ <div className="flex flex-wrap gap-1">+ <GroupedScoreBadges compact scores={nodeScores} />+ </div>+ )}+ </div>+ </button>+ );+}diff --git a/web/src/components/trace2/components/ToolCallInvocationsView.tsx b/web/src/components/trace2/components/ToolCallInvocationsView.tsxnew file mode 100644index 0000000000..11e8114319--- /dev/null+++ b/web/src/components/trace2/components/ToolCallInvocationsView.tsx@@ -0,0 +1,87 @@+import { Wrench } from "lucide-react";+import { cn } from "@/src/utils/tailwind";+import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";+import type { z } from "zod/v4";+import type { ChatMlMessageSchema } from "@/src/components/schemas/ChatMlSchema";++interface ToolCallInvocationsViewProps {+ message: z.infer<typeof ChatMlMessageSchema>;+ toolCallNumbers?: number[];+ className?: string;+}++export function ToolCallInvocationsView({+ message,+ toolCallNumbers,+ className,+}: ToolCallInvocationsViewProps) {+ const toolCalls = message.tool_calls;++ if (!toolCalls || !Array.isArray(toolCalls) || toolCalls.length === 0) {+ return null;+ }++ return (+ <div className={cn("flex flex-col gap-2", className)}>+ {toolCalls.map((toolCall, index) => {+ const invocationNumber = toolCallNumbers?.[index];+ // Parse arguments if they're a JSON string+ let parsedArguments = toolCall.arguments;+ if (typeof toolCall.arguments === "string") {+ try {+ parsedArguments = JSON.parse(toolCall.arguments);+ } catch {+ // Keep as string if parsing fails+ parsedArguments = toolCall.arguments;+ }+ }++ return (+ <div+ key={`${toolCall.id}-${index}`}+ className={cn(+ "w-full border-t px-2 py-2",+ (message.role === "assistant" ||+ message.name === "Output" ||+ message.name === "Model") &&+ "bg-accent-light-green",+ )}+ >+ {/* Card header */}+ <div className="flex w-full items-center justify-between gap-2 py-1">+ {/* Left: Tool icon + number + name */}+ <div className="flex items-center gap-2">+ <Wrench className="h-3.5 w-3.5 text-muted-foreground" />+ <span className="font-mono text-xs font-medium text-foreground">+ {invocationNumber !== undefined && (+ <span className="mr-1">{invocationNumber}.</span>+ )}+ {toolCall.name}+ </span>+ </div>++ {/* Right: Call ID if available */}+ {toolCall.id && (+ <span className="font-mono text-xs text-muted-foreground">+ {toolCall.id}+ </span>+ )}+ </div>++ {/* Arguments view */}+ <div className="py-2 [&_.io-message-content]:px-0">+ <div className="mb-1.5 text-xs font-medium text-muted-foreground">+ Arguments+ </div>+ <PrettyJsonView+ json={parsedArguments}+ currentView="pretty"+ codeClassName="text-xs"+ />+ </div>+ </div>+ );+ })}+ </div>+ );+}diff --git a/web/src/components/trace2/components/TraceDetailView/TraceDetailView.tsx b/web/src/components/trace2/components/TraceDetailView/TraceDetailView.tsxnew file mode 100644index 0000000000..9528dc315b--- /dev/null+++ b/web/src/components/trace2/components/TraceDetailView/TraceDetailView.tsx@@ -0,0 +1,279 @@+/**+ * TraceDetailView - Shows trace-level details when no observation is selected+ */++import { type TraceDomain, type ScoreDomain } from "@langfuse/shared";+import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";+import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";+import {+ TabsBar,+ TabsBarContent,+ TabsBarList,+ 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 {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@/src/components/ui/tooltip";++// Preview tab components+import { IOPreview } from "@/src/components/trace2/components/IOPreview/IOPreview";+import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";+import TagList from "@/src/features/tag/components/TagList";+import { useJsonExpansion } from "@/src/components/trace2/contexts/JsonExpansionContext";+import { useMedia } from "@/src/components/trace2/api/useMedia";++// Contexts and hooks+import { useTraceData } from "@/src/components/trace2/contexts/TraceDataContext";+import { useViewPreferences } from "@/src/components/trace2/contexts/ViewPreferencesContext";+import { useIsAuthenticatedAndProjectMember } from "@/src/features/auth/hooks";+import {+ useLogViewConfirmation,+ LOG_VIEW_DISABLED_THRESHOLD,+} from "@/src/components/trace2/components/TraceLogView/useLogViewConfirmation";++// Extracted components+import { TraceDetailViewHeader } from "./TraceDetailViewHeader";+import { TraceLogViewConfirmationDialog } from "../TraceLogView/TraceLogViewConfirmationDialog";+import { TraceLogView } from "../TraceLogView/TraceLogView";+import ScoresTable from "@/src/components/table/use-cases/scores";++export interface TraceDetailViewProps {+ trace: Omit<WithStringifiedMetadata<TraceDomain>, "input" | "output"> & {+ latency?: number;+ input: string | null;+ output: string | null;+ };+ observations: ObservationReturnTypeWithMetadata[];+ scores: WithStringifiedMetadata<ScoreDomain>[];+ projectId: string;+}++export function TraceDetailView({+ trace,+ observations,+ scores,+ projectId,+}: TraceDetailViewProps) {+ // Tab and view state+ const [selectedTab, setSelectedTab] = useState<"preview" | "log" | "scores">(+ "preview",+ );+ const [currentView, setCurrentView] = useLocalStorage<"pretty" | "json">(+ "jsonViewPreference",+ "pretty",+ );+ const [isPrettyViewAvailable, setIsPrettyViewAvailable] = useState(true);++ // Context hooks+ const { comments } = useTraceData();+ const { expansionState, setFieldExpansion } = useJsonExpansion();++ // Data fetching+ const traceMedia = useMedia({ projectId, traceId: trace.id });++ // Derived state+ const traceScores = useMemo(+ () => scores.filter((s) => !s.observationId),+ [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]);++ // Scores tab visibility: hide for public trace viewers and in peek mode (annotation queues)+ const { isPeekMode } = useViewPreferences();+ const isAuthenticatedAndProjectMember =+ useIsAuthenticatedAndProjectMember(projectId);+ const showScoresTab = isAuthenticatedAndProjectMember && !isPeekMode;++ // Handle tab change with log view confirmation+ const 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) */}+ <TraceDetailViewHeader+ trace={trace}+ projectId={projectId}+ traceScores={traceScores}+ commentCount={comments.get(trace.id)}+ />++ {/* Tabs section */}+ <TabsBar+ value={selectedTab}+ className="flex min-h-0 flex-1 flex-col overflow-hidden"+ onValueChange={handleTabChange}+ >+ <TooltipProvider>+ <TabsBarList>+ <TabsBarTrigger value="preview">Preview</TabsBarTrigger>+ {showLogViewTab && (+ <TabsBarTrigger+ value="log"+ disabled={logViewConfirmation.isDisabled}+ >+ <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."}+ </TooltipContent>+ </Tooltip>+ </TabsBarTrigger>+ )}+ {showScoresTab && (+ <TabsBarTrigger value="scores">Scores</TabsBarTrigger>+ )}++ {/* View toggle (Formatted/JSON) - show for preview and log tabs when pretty view available */}+ {(selectedTab === "log" ||+ (selectedTab === "preview" && isPrettyViewAvailable)) && (+ <Tabs+ className="ml-auto mr-1 h-fit px-2 py-0.5"+ value={currentView}+ onValueChange={(value) => {+ setCurrentView(value as "pretty" | "json");+ }}+ >+ <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>+ </TabsList>+ </Tabs>+ )}+ </TabsBarList>+ </TooltipProvider>++ {/* Preview tab content */}+ <TabsBarContent+ 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">+ {/* I/O Preview */}+ <IOPreview+ key={trace.id + "-io"}+ input={trace.input ?? undefined}+ output={trace.output ?? undefined}+ media={traceMedia.data}+ currentView={currentView}+ setIsPrettyViewAvailable={setIsPrettyViewAvailable}+ inputExpansionState={expansionState.input}+ outputExpansionState={expansionState.output}+ onInputExpansionChange={(exp) => setFieldExpansion("input", exp)}+ onOutputExpansionChange={(exp) =>+ setFieldExpansion("output", exp)+ }+ />++ {/* Tags Section */}+ <div className="px-2 text-sm font-medium">Tags</div>+ <div className="flex flex-wrap gap-x-1 gap-y-1 px-2">+ <TagList selectedTags={trace.tags} isLoading={false} />+ </div>++ {/* Metadata Section */}+ {trace.metadata && (+ <div className="px-2">+ <PrettyJsonView+ key={trace.id + "-metadata"}+ title="Metadata"+ json={trace.metadata}+ media={traceMedia.data?.filter((m) => m.field === "metadata")}+ currentView={currentView}+ externalExpansionState={expansionState.metadata}+ onExternalExpansionChange={(exp) =>+ setFieldExpansion("metadata", exp)+ }+ />+ </div>+ )}+ </div>+ </TabsBarContent>++ {/* Log View tab content */}+ <TabsBarContent+ value="log"+ 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}+ />+ </TabsBarContent>++ {/* Scores tab content */}+ {showScoresTab && (+ <TabsBarContent+ value="scores"+ className="mt-0 flex max-h-full min-h-0 w-full flex-1 overflow-hidden"+ >+ <div className="flex h-full min-h-0 w-full flex-col overflow-hidden pr-3">+ <ScoresTable+ projectId={projectId}+ omittedFilter={["Trace ID"]}+ traceId={trace.id}+ hiddenColumns={["traceName", "jobConfigurationId", "userId"]}+ localStorageSuffix="TracePreview"+ />+ </div>+ </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/TraceDetailView/TraceDetailViewHeader.tsx b/web/src/components/trace2/components/TraceDetailView/TraceDetailViewHeader.tsxnew file mode 100644index 0000000000..79f349fad6--- /dev/null+++ b/web/src/components/trace2/components/TraceDetailView/TraceDetailViewHeader.tsx@@ -0,0 +1,129 @@+/**+ * TraceDetailViewHeader - Extracted header component for TraceDetailView+ *+ * Contains:+ * - Title row with ItemBadge, trace name, CopyIdsPopover+ * - Action buttons (Dataset, Annotate, Queue, Comments)+ * - Metadata badges (timestamp, session, user, environment, release, version)+ *+ * Memoized to prevent unnecessary re-renders when tab state changes.+ */++import { memo } from "react";+import {+ type TraceDomain,+ type ScoreDomain,+ AnnotationQueueObjectType,+} from "@langfuse/shared";+import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";+import { ItemBadge } from "@/src/components/ItemBadge";+import { LocalIsoDate } from "@/src/components/LocalIsoDate";+import { CopyIdsPopover } from "@/src/components/trace2/components/_shared/CopyIdsPopover";+import { NewDatasetItemFromExistingObject } from "@/src/features/datasets/components/NewDatasetItemFromExistingObject";+import { AnnotateDrawer } from "@/src/features/scores/components/AnnotateDrawer";+import { CreateNewAnnotationQueueItem } from "@/src/features/annotation-queues/components/CreateNewAnnotationQueueItem";+import { CommentDrawerButton } from "@/src/features/comments/CommentDrawerButton";+import {+ SessionBadge,+ UserIdBadge,+ EnvironmentBadge,+ ReleaseBadge,+ VersionBadge,+} from "./TraceMetadataBadges";++export interface TraceDetailViewHeaderProps {+ trace: Omit<WithStringifiedMetadata<TraceDomain>, "input" | "output"> & {+ latency?: number;+ input: string | null;+ output: string | null;+ };+ projectId: string;+ traceScores: WithStringifiedMetadata<ScoreDomain>[];+ commentCount: number | undefined;+}++export const TraceDetailViewHeader = memo(function TraceDetailViewHeader({+ trace,+ projectId,+ traceScores,+ commentCount,+}: TraceDetailViewHeaderProps) {+ return (+ <div className="flex-shrink-0 space-y-2 border-b p-4 @container">+ {/* 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">+ <div className="mt-1.5">+ <ItemBadge type="TRACE" isSmall />+ </div>+ <span className="mb-0 ml-1 line-clamp-2 min-w-0 break-all font-medium md:break-normal md:break-words">+ {trace.name || trace.id}+ </span>+ <CopyIdsPopover idItems={[{ id: trace.id, name: "Trace ID" }]} />+ </div>+ {/* Action buttons */}+ <div className="flex h-full flex-wrap content-start items-start justify-start gap-0.5 @2xl:mr-1 @2xl:justify-end">+ <NewDatasetItemFromExistingObject+ traceId={trace.id}+ projectId={projectId}+ input={trace.input}+ output={trace.output}+ metadata={trace.metadata}+ key={trace.id}+ size="sm"+ />+ <div className="flex items-start">+ <AnnotateDrawer+ key={"annotation-drawer-" + trace.id}+ projectId={projectId}+ scoreTarget={{+ type: "trace",+ traceId: trace.id,+ }}+ scores={traceScores}+ scoreMetadata={{+ projectId: projectId,+ environment: trace.environment,+ }}+ size="sm"+ />+ <CreateNewAnnotationQueueItem+ projectId={projectId}+ objectId={trace.id}+ objectType={AnnotationQueueObjectType.TRACE}+ size="sm"+ />+ </div>+ <CommentDrawerButton+ projectId={projectId}+ objectId={trace.id}+ objectType="TRACE"+ count={commentCount}+ size="sm"+ />+ </div>+ </div>++ {/* Metadata badges */}+ <div className="flex flex-col gap-2">+ {/* Timestamp */}+ <div className="flex flex-wrap items-center gap-1">+ <LocalIsoDate+ date={trace.timestamp}+ accuracy="millisecond"+ className="text-sm"+ />+ </div>++ {/* Other badges */}+ <div className="flex flex-wrap items-center gap-1">+ <SessionBadge sessionId={trace.sessionId} projectId={projectId} />+ <UserIdBadge userId={trace.userId} projectId={projectId} />+ <EnvironmentBadge environment={trace.environment} />+ <ReleaseBadge release={trace.release} />+ <VersionBadge version={trace.version} />+ </div>+ </div>+ </div>+ );+});diff --git a/web/src/components/trace2/components/TraceDetailView/TraceMetadataBadges.tsx b/web/src/components/trace2/components/TraceDetailView/TraceMetadataBadges.tsxnew file mode 100644index 0000000000..bd9c55ddc5--- /dev/null+++ b/web/src/components/trace2/components/TraceDetailView/TraceMetadataBadges.tsx@@ -0,0 +1,71 @@+/**+ * TraceMetadataBadges - Extracted badge components for trace metadata+ *+ * Following the pattern from ObservationDetailView/ObservationMetadataBadgesSimple.tsx+ * Each badge handles its own null check and returns null when data is unavailable.+ */++import Link from "next/link";+import { ExternalLinkIcon } from "lucide-react";+import { Badge } from "@/src/components/ui/badge";++export function SessionBadge({+ sessionId,+ projectId,+}: {+ sessionId: string | null;+ projectId: string;+}) {+ if (!sessionId) return null;+ return (+ <Link+ href={`/project/${projectId}/sessions/${encodeURIComponent(sessionId)}`}+ className="inline-flex"+ >+ <Badge>+ <span className="truncate">Session: {sessionId}</span>+ <ExternalLinkIcon className="ml-1 h-3 w-3" />+ </Badge>+ </Link>+ );+}++export function UserIdBadge({+ userId,+ projectId,+}: {+ userId: string | null;+ projectId: string;+}) {+ if (!userId) return null;+ return (+ <Link+ href={`/project/${projectId}/users/${encodeURIComponent(userId)}`}+ className="inline-flex"+ >+ <Badge>+ <span className="truncate">User ID: {userId}</span>+ <ExternalLinkIcon className="ml-1 h-3 w-3" />+ </Badge>+ </Link>+ );+}++export function EnvironmentBadge({+ environment,+}: {+ environment: string | null;+}) {+ if (!environment) return null;+ return <Badge variant="tertiary">Env: {environment}</Badge>;+}++export function ReleaseBadge({ release }: { release: string | null }) {+ if (!release) return null;+ return <Badge variant="tertiary">Release: {release}</Badge>;+}++export function VersionBadge({ version }: { version: string | null }) {+ if (!version) return null;+ return <Badge variant="tertiary">Version: {version}</Badge>;+}diff --git a/web/src/components/trace2/components/TraceGraphView/TraceGraphView.tsx b/web/src/components/trace2/components/TraceGraphView/TraceGraphView.tsxnew file mode 100644index 0000000000..b4bb5a3bc0--- /dev/null+++ b/web/src/components/trace2/components/TraceGraphView/TraceGraphView.tsx@@ -0,0 +1,27 @@+/**+ * TraceGraphView wrapper for trace2+ *+ * This component wraps the TraceGraphView from features/trace-graph-view/+ * and uses data from GraphDataContext.+ */++import { TraceGraphView as TraceGraphViewComponent } from "@/src/features/trace-graph-view/components/TraceGraphView";+import { useTraceGraphData } from "../../contexts/TraceGraphDataContext";++export function TraceGraphView() {+ const { agentGraphData, isLoading } = useTraceGraphData();++ if (isLoading) {+ return (+ <div className="flex h-full w-full items-center justify-center">+ <span className="text-sm text-muted-foreground">Loading graph...</span>+ </div>+ );+ }++ if (agentGraphData.length === 0) {+ return null;+ }++ return <TraceGraphViewComponent agentGraphData={agentGraphData} />;+}diff --git a/web/src/components/trace2/components/TraceLogView/TraceLogView.tsx b/web/src/components/trace2/components/TraceLogView/TraceLogView.tsxnew file mode 100644index 0000000000..ee11c19724--- /dev/null+++ b/web/src/components/trace2/components/TraceLogView/TraceLogView.tsx@@ -0,0 +1,224 @@+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";+import { useJsonExpansion } from "@/src/components/trace2/contexts/JsonExpansionContext";+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";++export interface TraceLogViewProps {+ observations: ObservationReturnTypeWithMetadata[];+ traceId: string;+ projectId: string;+ currentView: "pretty" | "json";+ trace: {+ id: string;+ [key: string]: unknown;+ };+}++export const TraceLogView = ({+ observations,+ traceId,+ projectId,+ currentView,+ trace,+}: TraceLogViewProps) => {+ const [currentObservationId] = useQueryParam("observation", StringParam);+ const [selectedTab] = useQueryParam("view", StringParam);+ const utils = api.useUtils();+ 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,+ }),+ ),+ });++ const logData = useMemo(() => {+ // Sort observations by start time+ const sortedObservations = [...observations].sort(+ (a, b) => a.startTime.getTime() - b.startTime.getTime(),+ );++ const allObsData: 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,+ };+ });++ 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]);++ // Get top-level observation keys for denormalization+ const observationKeys = useMemo(+ () => Object.keys(logData.data),+ [logData.data],+ );++ // Convert normalized state from context to actual state with observation IDs+ const denormalizedState = useMemo(+ () => denormalizeExpansionState(expansionState.log, observationKeys),+ [expansionState.log, observationKeys],+ );++ // 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,+ };+ });++ downloadTraceUtil({+ trace,+ observations: observationsWithFullData,+ filename: `trace-with-observations-${traceId}.json`,+ });+ }, [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>+ </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>+ }+ />+ </div>+ </div>+ );+};diff --git a/web/src/components/trace2/components/TraceLogView/TraceLogViewConfirmationDialog.tsx b/web/src/components/trace2/components/TraceLogView/TraceLogViewConfirmationDialog.tsxnew file mode 100644index 0000000000..7b38e5f16e--- /dev/null+++ b/web/src/components/trace2/components/TraceLogView/TraceLogViewConfirmationDialog.tsx@@ -0,0 +1,53 @@+/**+ * 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/useLogViewConfirmation.ts b/web/src/components/trace2/components/TraceLogView/useLogViewConfirmation.tsnew file mode 100644index 0000000000..0e9457b962--- /dev/null+++ b/web/src/components/trace2/components/TraceLogView/useLogViewConfirmation.ts@@ -0,0 +1,80 @@+/**+ * 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/TraceSearchList.tsx b/web/src/components/trace2/components/TraceSearchList.tsxnew file mode 100644index 0000000000..49d6e24322--- /dev/null+++ b/web/src/components/trace2/components/TraceSearchList.tsx@@ -0,0 +1,77 @@+/**+ * TraceSearchList - Search results view+ *+ * Displays filtered list of observations based on search query.+ * Uses VirtualizedList for performance with large result sets.+ * Filtering is co-located to avoid unnecessary re-renders.+ */++import { useMemo } from "react";+import { useTraceData } from "../contexts/TraceDataContext";+import { useSearch } from "../contexts/SearchContext";+import { useSelection } from "../contexts/SelectionContext";+import { VirtualizedList } from "./_shared/VirtualizedList";+import { TraceSearchListItem } from "./TraceSearchListItem";+import { Button } from "@/src/components/ui/button";+import { XIcon } from "lucide-react";++export function TraceSearchList() {+ const { searchItems } = useTraceData();+ const { searchQuery, setSearchInputValue } = useSearch();+ const { selectedNodeId, setSelectedNodeId } = useSelection();++ // Co-located filtering - only this component re-renders on search query change+ const searchResults = useMemo(() => {+ if (!searchQuery.trim()) return [];++ const query = searchQuery.toLowerCase();+ return searchItems.filter((item) => {+ const node = item.node;+ return (+ node.type.toLowerCase().includes(query) ||+ node.name.toLowerCase().includes(query) ||+ node.id.toLowerCase().includes(query)+ );+ });+ }, [searchItems, searchQuery]);++ // Empty state+ if (searchResults.length === 0 && searchQuery.trim()) {+ return (+ <div className="flex h-full flex-col items-center justify-center p-8 text-center">+ <div className="space-y-4">+ <p className="text-muted-foreground">No results found</p>+ <p className="text-sm text-muted-foreground">+ Try searching by type, title, or id+ </p>+ <Button+ variant="outline"+ size="sm"+ onClick={() => setSearchInputValue("")}+ >+ <XIcon className="mr-2 h-4 w-4" />+ Clear search+ </Button>+ </div>+ </div>+ );+ }++ return (+ <VirtualizedList+ items={searchResults}+ selectedItemId={selectedNodeId}+ onSelectItem={setSelectedNodeId}+ getItemId={(item) => item.node.id}+ estimatedItemSize={48}+ overscan={500}+ renderItem={({ item, isSelected, onSelect }) => (+ <TraceSearchListItem+ item={item}+ isSelected={isSelected}+ onSelect={onSelect}+ />+ )}+ />+ );+}diff --git a/web/src/components/trace2/components/TraceSearchListItem.tsx b/web/src/components/trace2/components/TraceSearchListItem.tsxnew file mode 100644index 0000000000..9d7754c16b--- /dev/null+++ b/web/src/components/trace2/components/TraceSearchListItem.tsx@@ -0,0 +1,67 @@+/**+ * SearchListItem - Individual search result row+ *+ * Renders a single search result using ItemBadge + SpanContent.+ * Reuses SpanContent from tree view for consistency.+ * Displays relative timestamps to show temporal context within the trace.+ */++import { type TraceSearchListItem } from "../lib/types";+import { ItemBadge } from "@/src/components/ItemBadge";+import { SpanContent } from "./SpanContent";+import { cn } from "@/src/utils/tailwind";+import { useTraceData } from "../contexts/TraceDataContext";+import { formatIntervalSeconds } from "@/src/utils/dates";++interface TraceSearchListItemProps {+ item: TraceSearchListItem;+ isSelected: boolean;+ onSelect: () => void;+}++export function TraceSearchListItem({+ item,+ isSelected,+ onSelect,+}: TraceSearchListItemProps) {+ const { node, parentTotalCost, parentTotalDuration } = item;+ const { comments } = useTraceData();++ // Format relative timestamps+ const traceRelativeTime = formatIntervalSeconds(+ node.startTimeSinceTrace / 1000,+ );+ const parentRelativeTime =+ node.startTimeSinceParentStart !== null+ ? formatIntervalSeconds(node.startTimeSinceParentStart / 1000)+ : null;++ return (+ <div+ onClick={onSelect}+ className={cn(+ "flex cursor-pointer items-start gap-2 px-2 py-1.5 transition-colors hover:bg-muted/50",+ isSelected && "bg-muted",+ )}+ >+ <ItemBadge type={node.type} />+ <div className="min-w-0 flex-1 space-y-0.5">+ <SpanContent+ node={node}+ parentTotalCost={parentTotalCost}+ parentTotalDuration={parentTotalDuration}+ commentCount={comments.get(node.id)}+ onSelect={onSelect}+ />+ {/* Temporal and depth context - only show for observations (not TRACE root) */}+ {node.type !== "TRACE" && (+ <div className="text-xs text-muted-foreground/70">+ depth {node.depth} • +{traceRelativeTime}+ {parentRelativeTime !== null &&+ ` • +${parentRelativeTime} from parent`}+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/web/src/components/trace2/components/TraceSettingsDropdown.tsx b/web/src/components/trace2/components/TraceSettingsDropdown.tsxnew file mode 100644index 0000000000..740a4c378b--- /dev/null+++ b/web/src/components/trace2/components/TraceSettingsDropdown.tsx@@ -0,0 +1,234 @@+/**+ * TraceSettingsDropdown - View preferences dropdown component+ *+ * Provides toggles for:+ * - Show Comments+ * - Show Scores+ * - Show Duration+ * - Show Cost/Tokens+ * - Color Code Metrics (dependent on duration or cost being enabled)+ * - Minimum Observation Level filter+ * - Show Graph (hidden when graph view not available)+ *+ * All preferences are managed via ViewPreferencesContext and persisted to localStorage.+ */++import { ObservationLevel } from "@langfuse/shared";+import { Settings2 } from "lucide-react";+import { Button } from "@/src/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ DropdownMenuSeparator,+ DropdownMenuSub,+ DropdownMenuSubTrigger,+ DropdownMenuSubContent,+ DropdownMenuLabel,+} from "@/src/components/ui/dropdown-menu";+import { Switch } from "@/src/components/ui/switch";+import { cn } from "@/src/utils/tailwind";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { useViewPreferences } from "../contexts/ViewPreferencesContext";++export interface TraceSettingsDropdownProps {+ isGraphViewAvailable: boolean;+}++export function TraceSettingsDropdown({+ isGraphViewAvailable,+}: TraceSettingsDropdownProps) {+ const capture = usePostHogClientCapture();++ // Get all preferences directly from context+ const {+ showGraph,+ setShowGraph,+ showComments,+ setShowComments,+ showScores,+ setShowScores,+ showDuration,+ setShowDuration,+ showCostTokens,+ setShowCostTokens,+ colorCodeMetrics,+ setColorCodeMetrics,+ minObservationLevel,+ setMinObservationLevel,+ } = useViewPreferences();++ // Color coding is only available when duration or cost metrics are shown+ const isColorCodeEnabled = showDuration || showCostTokens;++ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ size="icon"+ title="View Options"+ className="h-7 w-7"+ >+ <Settings2 className="h-3.5 w-3.5" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="end"+ className="w-64 space-x-0 space-y-0 p-0 px-0"+ >+ <DropdownMenuLabel>View Options</DropdownMenuLabel>+ <DropdownMenuSeparator />++ <div className="space-y-0 p-0 py-1">+ {/* Show Graph Toggle (only when available) */}+ {isGraphViewAvailable && (+ <DropdownMenuItem+ asChild+ onSelect={(e) => e.preventDefault()}+ className="space-y-0 px-2 py-1"+ >+ <div className="flex w-full items-center justify-between">+ <span className="mr-2">Show Graph</span>+ <Switch+ size="sm"+ checked={showGraph}+ onCheckedChange={setShowGraph}+ />+ </div>+ </DropdownMenuItem>+ )}++ {/* Show Comments Toggle */}+ <DropdownMenuItem+ asChild+ onSelect={(e) => e.preventDefault()}+ className="px-2 py-1"+ >+ <div className="flex w-full items-center justify-between">+ <span className="mr-2">Show Comments</span>+ <Switch+ size="sm"+ checked={showComments}+ onCheckedChange={setShowComments}+ />+ </div>+ </DropdownMenuItem>++ {/* Show Scores Toggle */}+ <DropdownMenuItem+ asChild+ onSelect={(e) => e.preventDefault()}+ className="px-2 py-1"+ >+ <div className="flex w-full items-center justify-between">+ <span className="mr-2">Show Scores</span>+ <Switch+ size="sm"+ checked={showScores}+ onCheckedChange={(checked) => {+ capture("trace_detail:observation_tree_toggle_scores", {+ show: checked,+ });+ setShowScores(checked);+ }}+ />+ </div>+ </DropdownMenuItem>++ {/* Show Duration Toggle */}+ <DropdownMenuItem+ asChild+ onSelect={(e) => e.preventDefault()}+ className="px-2 py-1"+ >+ <div className="flex w-full items-center justify-between">+ <span className="mr-2">Show Duration</span>+ <Switch+ size="sm"+ checked={showDuration}+ onCheckedChange={setShowDuration}+ />+ </div>+ </DropdownMenuItem>++ {/* Show Cost/Tokens Toggle */}+ <DropdownMenuItem+ asChild+ onSelect={(e) => e.preventDefault()}+ className="px-2 py-1"+ >+ <div className="flex w-full items-center justify-between">+ <span className="mr-2">Show Cost/Tokens</span>+ <Switch+ size="sm"+ checked={showCostTokens}+ onCheckedChange={setShowCostTokens}+ />+ </div>+ </DropdownMenuItem>++ {/* Color Code Metrics Toggle (disabled when no metrics shown) */}+ <DropdownMenuItem+ asChild+ onSelect={(e) => e.preventDefault()}+ disabled={!isColorCodeEnabled}+ className={cn([+ "px-2 py-1",+ isColorCodeEnabled ? "" : "cursor-not-allowed",+ ])}+ >+ <div+ className={cn(+ "flex w-full items-center justify-between",+ !isColorCodeEnabled && "cursor-not-allowed",+ )}+ >+ <span+ className={cn(+ "mr-2",+ !isColorCodeEnabled && "cursor-not-allowed",+ )}+ >+ Show Color Code Metrics+ </span>+ <Switch+ size="sm"+ checked={colorCodeMetrics}+ onCheckedChange={setColorCodeMetrics}+ disabled={!isColorCodeEnabled}+ className={cn(!isColorCodeEnabled && "cursor-not-allowed")}+ />+ </div>+ </DropdownMenuItem>+ </div>++ {/* Minimum Observation Level Submenu */}+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <span className="flex items-center">+ Min Level: {minObservationLevel}+ </span>+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent>+ <DropdownMenuLabel className="font-semibold">+ Minimum Level+ </DropdownMenuLabel>+ {Object.values(ObservationLevel).map((level) => (+ <DropdownMenuItem+ key={level}+ onSelect={(e) => {+ e.preventDefault();+ setMinObservationLevel(level);+ }}+ >+ {level}+ </DropdownMenuItem>+ ))}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/web/src/components/trace2/components/TraceTimeline/TimelineBar.tsx b/web/src/components/trace2/components/TraceTimeline/TimelineBar.tsxnew file mode 100644index 0000000000..d03ae16dce--- /dev/null+++ b/web/src/components/trace2/components/TraceTimeline/TimelineBar.tsx@@ -0,0 +1,194 @@+/**+ * TimelineBar - Renders individual Gantt bar for a node+ * Shows duration visually with colored box, displays name, badges, and metrics+ */++import { type TimelineBarProps } from "./types";+import { cn } from "@/src/utils/tailwind";+import { ItemBadge } from "@/src/components/ItemBadge";+import { CommentCountIcon } from "@/src/features/comments/CommentCountIcon";+import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";+import { formatIntervalSeconds } from "@/src/utils/dates";+import { usdFormatter } from "@/src/utils/numbers";+import { heatMapTextColor } from "@/src/components/trace2/lib/helpers";+import { isPresent } from "@langfuse/shared";++export function TimelineBar({+ node,+ metrics,+ isSelected,+ onSelect,+ showDuration,+ showCostTokens,+ showScores,+ showComments,+ colorCodeMetrics,+ parentTotalCost,+ parentTotalDuration,+ commentCount,+ scores,+}: TimelineBarProps) {+ const { startOffset, itemWidth, firstTokenTimeOffset, latency } = metrics;+ const duration = latency ? latency * 1000 : undefined;+ const hasChildren = node.children.length > 0;++ // Render split bar for streaming LLMs (first token time)+ if (firstTokenTimeOffset) {+ const firstTokenWidth = firstTokenTimeOffset - startOffset;+ const completionWidth = itemWidth - firstTokenWidth;++ return (+ <div+ className="group my-0.5 flex w-full min-w-fit cursor-pointer flex-row items-center"+ onClick={onSelect}+ >+ <div+ className={cn(+ "flex rounded-sm border border-border",+ isSelected+ ? "ring ring-primary-accent"+ : "group-hover:ring group-hover:ring-tertiary",+ )}+ style={{ marginLeft: `${startOffset}px` }}+ >+ {/* First token time bar (waiting period) */}+ <div+ className={cn(+ "flex h-8 items-center justify-start rounded-l-sm border-r border-gray-400 bg-muted opacity-60",+ itemWidth ? "" : "border border-dashed",+ )}+ style={{ width: `${firstTokenWidth}px` }}+ />++ {/* Completion time bar */}+ <div+ className={cn(+ "flex h-8 items-center justify-start rounded-r-sm bg-muted",+ itemWidth ? "" : "border border-dashed",+ )}+ style={{ width: `${completionWidth}px` }}+ >+ <div className="-ml-8 flex flex-row items-center justify-start gap-2 text-xs text-muted-foreground">+ <span className="text-xxs text-primary">First token</span>+ <ItemBadge type={node.type} isSmall />+ <span className="whitespace-nowrap text-sm font-medium text-primary">+ {node.name}+ </span>+ {showComments && commentCount ? (+ <CommentCountIcon count={commentCount} />+ ) : null}+ {showDuration && isPresent(latency) && (+ <span+ className={cn(+ "text-xs text-muted-foreground",+ parentTotalDuration &&+ colorCodeMetrics &&+ duration &&+ heatMapTextColor({+ max: parentTotalDuration,+ value: duration,+ }),+ )}+ >+ {formatIntervalSeconds(latency)}+ </span>+ )}+ {showCostTokens && node.totalCost && (+ <span+ className={cn(+ "text-xs text-muted-foreground",+ parentTotalCost &&+ colorCodeMetrics &&+ heatMapTextColor({+ max: parentTotalCost,+ value: node.totalCost,+ }),+ )}+ >+ {usdFormatter(node.totalCost.toNumber())}+ </span>+ )}+ {showScores && scores && scores.length > 0 && (+ <div className="flex max-h-8 gap-1">+ <GroupedScoreBadges scores={scores} maxVisible={3} />+ </div>+ )}+ </div>+ </div>+ </div>+ </div>+ );+ }++ // Regular bar (no first token time)+ return (+ <div+ className="group my-0.5 flex w-full min-w-fit cursor-pointer flex-row items-center"+ onClick={onSelect}+ >+ <div className="relative" style={{ marginLeft: `${startOffset}px` }}>+ <div+ className={cn(+ "flex h-8 items-center justify-start rounded-sm border border-border bg-muted",+ itemWidth ? "" : "border-dashed",+ isSelected+ ? "ring ring-primary-accent"+ : "group-hover:ring group-hover:ring-tertiary",+ )}+ style={{ width: `${itemWidth || 10}px` }}+ >+ <div+ className={cn(+ "flex flex-row items-center justify-start gap-2 text-xs text-muted-foreground",+ hasChildren ? "ml-6" : "ml-1",+ )}+ >+ <ItemBadge type={node.type} isSmall />+ <span className="whitespace-nowrap text-sm font-medium text-primary">+ {node.name}+ </span>+ {showComments && commentCount ? (+ <CommentCountIcon count={commentCount} />+ ) : null}+ {showDuration && isPresent(latency) && (+ <span+ className={cn(+ "text-xs text-muted-foreground",+ parentTotalDuration &&+ colorCodeMetrics &&+ duration &&+ heatMapTextColor({+ max: parentTotalDuration,+ value: duration,+ }),+ )}+ >+ {formatIntervalSeconds(latency)}+ </span>+ )}+ {showCostTokens && node.totalCost && (+ <span+ className={cn(+ "text-xs text-muted-foreground",+ parentTotalCost &&+ colorCodeMetrics &&+ heatMapTextColor({+ max: parentTotalCost,+ value: node.totalCost,+ }),+ )}+ >+ {usdFormatter(node.totalCost.toNumber())}+ </span>+ )}+ {showScores && scores && scores.length > 0 && (+ <div className="flex max-h-8 gap-1">+ <GroupedScoreBadges scores={scores} maxVisible={3} />+ </div>+ )}+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/web/src/components/trace2/components/TraceTimeline/TimelineRow.tsx b/web/src/components/trace2/components/TraceTimeline/TimelineRow.tsxnew file mode 100644index 0000000000..d62ad30926--- /dev/null+++ b/web/src/components/trace2/components/TraceTimeline/TimelineRow.tsx@@ -0,0 +1,110 @@+/**+ * TimelineRow - Combines tree structure with timeline bar+ * Renders tree lines, expand button, and timeline bar positioned horizontally by time+ */++import { type TimelineRowProps } from "./types";+import { TimelineBar } from "./TimelineBar";+import { ChevronRight } from "lucide-react";+import { cn } from "@/src/utils/tailwind";++const TREE_INDENTATION = 12; // pixels per depth level++export function TimelineRow({+ item,+ isSelected,+ onSelect,+ onToggleCollapse,+ hasChildren,+ isCollapsed,+ showDuration,+ showCostTokens,+ showScores,+ showComments,+ colorCodeMetrics,+ parentTotalCost,+ parentTotalDuration,+ commentCount,+ scores,+}: TimelineRowProps) {+ const { node, depth, treeLines, isLastSibling, metrics } = item;++ return (+ <div className="group my-0.5 flex w-full min-w-fit cursor-pointer flex-row items-center">+ {/* Tree lines for ancestor levels (depth - 1) */}+ {depth > 0 && (+ <div className="flex flex-shrink-0">+ {Array.from({ length: depth - 1 }, (_, i) => (+ <div+ key={i}+ className="relative"+ style={{ width: `${TREE_INDENTATION}px` }}+ >+ {treeLines[i] && (+ <div className="absolute bottom-0 left-1.5 top-0 w-px bg-border" />+ )}+ </div>+ ))}+ </div>+ )}++ {/* Current level tree connector */}+ {depth > 0 && (+ <div+ className="relative flex-shrink-0"+ style={{ width: `${TREE_INDENTATION}px` }}+ >+ {/* Vertical line up */}+ <div+ className={cn(+ "absolute left-1.5 top-0 w-px bg-border",+ isLastSibling ? "h-3" : "bottom-0",+ )}+ />+ {/* Horizontal line to content */}+ <div className="absolute left-1.5 top-3 h-px w-2 bg-border" />+ </div>+ )}++ {/* Expand/collapse button (if has children) */}+ {hasChildren && (+ <button+ onClick={(e) => {+ e.stopPropagation();+ onToggleCollapse();+ }}+ className="absolute z-10 rounded hover:bg-muted"+ style={{+ left: `${depth * TREE_INDENTATION + (metrics.startOffset > 0 ? metrics.startOffset + 4 : 4)}px`,+ top: "50%",+ transform: "translateY(-50%)",+ }}+ >+ <ChevronRight+ className={cn(+ "h-4 w-4 transition-transform duration-200",+ !isCollapsed && "rotate-90",+ )}+ />+ </button>+ )}++ {/* Timeline bar */}+ <TimelineBar+ node={node}+ metrics={metrics}+ isSelected={isSelected}+ onSelect={onSelect}+ showDuration={showDuration}+ showCostTokens={showCostTokens}+ showScores={showScores}+ showComments={showComments}+ colorCodeMetrics={colorCodeMetrics}+ parentTotalCost={parentTotalCost}+ parentTotalDuration={parentTotalDuration}+ commentCount={commentCount}+ scores={scores}+ />+ </div>+ );+}diff --git a/web/src/components/trace2/components/TraceTimeline/TimelineScale.tsx b/web/src/components/trace2/components/TraceTimeline/TimelineScale.tsxnew file mode 100644index 0000000000..548d2b31fd--- /dev/null+++ b/web/src/components/trace2/components/TraceTimeline/TimelineScale.tsx@@ -0,0 +1,64 @@+/**+ * TimelineScale - Renders the time axis at the top of the timeline+ * Shows time markers with step intervals based on trace duration+ */++import { type TimelineScaleProps } from "./types";+import { STEP_SIZE } from "./timeline-calculations";++export function TimelineScale({+ traceDuration,+ scaleWidth,+ stepSize,+}: TimelineScaleProps) {+ // Calculate how many markers to show+ const numMarkers = Math.ceil(scaleWidth / STEP_SIZE) + 1;++ return (+ <div className="mb-2 ml-2">+ <div className="relative mr-2 h-8" style={{ width: `${scaleWidth}px` }}>+ {Array.from({ length: numMarkers }).map((_, index) => {+ const timeValue = stepSize * index;++ // Only show markers that are within the trace duration+ if (timeValue > traceDuration) {+ return null;+ }++ return (+ <div+ key={index}+ className="absolute h-full border-l text-xs"+ style={{ left: `${index * STEP_SIZE}px` }}+ >+ <span+ className="absolute left-2 text-xs text-muted-foreground"+ title={`${timeValue.toFixed(2)}s`}+ >+ {timeValue.toFixed(2)}s+ </span>+ </div>+ );+ })}++ {/* Grid lines for visual alignment */}+ <div className="pointer-events-none absolute inset-0">+ {Array.from({ length: numMarkers }).map((_, index) => {+ const timeValue = stepSize * index;+ if (timeValue > traceDuration || index === 0) {+ return null;+ }++ return (+ <div+ key={`grid-${index}`}+ className="absolute h-full border-l border-border/30"+ style={{ left: `${index * STEP_SIZE}px` }}+ />+ );+ })}+ </div>+ </div>+ </div>+ );+}diff --git a/web/src/components/trace2/components/TraceTimeline/index.tsx b/web/src/components/trace2/components/TraceTimeline/index.tsxnew file mode 100644index 0000000000..f2619a0c73--- /dev/null+++ b/web/src/components/trace2/components/TraceTimeline/index.tsx@@ -0,0 +1,210 @@+/**+ * TraceTimeline - Main timeline view component+ * Renders Gantt chart visualization with virtualized rows+ */++import { useMemo, useRef, useLayoutEffect } from "react";+import { useVirtualizer } from "@tanstack/react-virtual";+import { useTraceData } from "../../contexts/TraceDataContext";+import { useSelection } from "../../contexts/SelectionContext";+import { useViewPreferences } from "../../contexts/ViewPreferencesContext";+import { flattenTreeWithTimelineMetrics } from "./timeline-flattening";+import { calculateStepSize, SCALE_WIDTH } from "./timeline-calculations";+import { TimelineScale } from "./TimelineScale";+import { TimelineRow } from "./TimelineRow";++export function TraceTimeline() {+ const { tree, scores, comments } = useTraceData();+ const { collapsedNodes, toggleCollapsed, selectedNodeId, setSelectedNodeId } =+ useSelection();+ const {+ showDuration,+ showCostTokens,+ showScores,+ showComments,+ colorCodeMetrics,+ } = useViewPreferences();++ const timeIndexRef = useRef<HTMLDivElement>(null);+ const contentRef = useRef<HTMLDivElement>(null);++ // Calculate trace duration from tree root+ const traceDuration = useMemo(() => {+ // Use tree's latency (already calculated in buildTraceUiData)+ return tree.latency ?? 0;+ }, [tree.latency]);++ const traceStartTime = useMemo(() => {+ return tree.startTime;+ }, [tree.startTime]);++ // Calculate step size for time axis+ const stepSize = useMemo(() => {+ return calculateStepSize(traceDuration, SCALE_WIDTH);+ }, [traceDuration]);++ // Flatten tree with pre-computed timeline metrics+ const flattenedItems = useMemo(() => {+ return flattenTreeWithTimelineMetrics(+ tree,+ collapsedNodes,+ traceStartTime,+ traceDuration,+ SCALE_WIDTH,+ );+ }, [tree, collapsedNodes, traceStartTime, traceDuration]);++ // Calculate content width (max offset + max width)+ const contentWidth = useMemo(() => {+ if (flattenedItems.length === 0) return SCALE_WIDTH;++ const maxEnd = Math.max(+ ...flattenedItems.map(+ (item) => item.metrics.startOffset + item.metrics.itemWidth,+ ),+ );++ return Math.max(SCALE_WIDTH, maxEnd + 50); // Add padding+ }, [flattenedItems]);++ // Set up virtualizer for rows+ const rowVirtualizer = useVirtualizer({+ count: flattenedItems.length,+ getScrollElement: () => contentRef.current,+ estimateSize: () => 42, // Row height in pixels+ overscan: 500, // Large overscan for smooth scrolling with complex items+ });++ // Auto-scroll to selected node on initial load (URL-based navigation only)+ const initialNodeIdRef = useRef(selectedNodeId);+ const hasScrolledRef = useRef(false);++ useLayoutEffect(() => {+ if (+ selectedNodeId &&+ !hasScrolledRef.current &&+ selectedNodeId === initialNodeIdRef.current+ ) {+ const index = flattenedItems.findIndex(+ (item) => item.node.id === selectedNodeId,+ );++ if (index !== -1) {+ // Use behavior: "auto" for instant scroll on initial load to prevent+ // visible scroll animation after page render. The synchronous scroll+ // completes within useLayoutEffect, before browser paint.+ rowVirtualizer.scrollToIndex(index, {+ align: "center",+ behavior: "auto",+ });+ hasScrolledRef.current = true;+ }+ }+ }, [selectedNodeId, flattenedItems, rowVirtualizer]);++ // Scroll sync handlers+ const handleTimeIndexScroll = (e: React.UIEvent<HTMLDivElement>) => {+ if (contentRef.current) {+ contentRef.current.scrollLeft = e.currentTarget.scrollLeft;+ }+ };++ const handleContentScroll = (e: React.UIEvent<HTMLDivElement>) => {+ if (timeIndexRef.current) {+ timeIndexRef.current.scrollLeft = e.currentTarget.scrollLeft;+ }+ };++ // Get parent totals for heatmap coloring+ const parentTotalCost = tree.totalCost;+ const parentTotalDuration = traceDuration;++ return (+ <div className="flex h-full w-full flex-col overflow-hidden">+ {/* Sticky time scale header */}+ <div+ ref={timeIndexRef}+ className="overflow-x-auto overflow-y-hidden"+ onScroll={handleTimeIndexScroll}+ >+ <div style={{ width: `${contentWidth}px` }}>+ <TimelineScale+ traceDuration={traceDuration}+ scaleWidth={SCALE_WIDTH}+ stepSize={stepSize}+ />+ </div>+ </div>++ {/* Main scrollable content with virtualized rows */}+ <div+ ref={contentRef}+ className="flex-1 overflow-auto"+ onScroll={handleContentScroll}+ >+ <div+ style={{+ height: `${rowVirtualizer.getTotalSize()}px`,+ width: `${contentWidth}px`,+ position: "relative",+ }}+ >+ {rowVirtualizer.getVirtualItems().map((virtualRow) => {+ const item = flattenedItems[virtualRow.index];+ if (!item) return null;++ const nodeId = item.node.id;+ const isSelected = selectedNodeId === nodeId;+ const hasChildren = item.node.children.length > 0;+ const isCollapsed = collapsedNodes.has(nodeId);++ // Get scores for this node+ const nodeScores = scores.filter((score) => {+ // Match based on observation ID or trace ID+ if (item.node.type === "TRACE") {+ return score.traceId === item.node.id;+ } else {+ return score.observationId === item.node.id;+ }+ });++ // Get comment count for this node+ const commentCount = comments.get(nodeId) ?? 0;++ return (+ <div+ key={nodeId}+ style={{+ position: "absolute",+ top: 0,+ left: 0,+ width: "100%",+ height: `${virtualRow.size}px`,+ transform: `translateY(${virtualRow.start}px)`,+ }}+ >+ <TimelineRow+ item={item}+ isSelected={isSelected}+ onSelect={() => setSelectedNodeId(nodeId)}+ onToggleCollapse={() => toggleCollapsed(nodeId)}+ hasChildren={hasChildren}+ isCollapsed={isCollapsed}+ showDuration={showDuration}+ showCostTokens={showCostTokens}+ showScores={showScores}+ showComments={showComments}+ colorCodeMetrics={colorCodeMetrics}+ parentTotalCost={parentTotalCost}+ parentTotalDuration={parentTotalDuration}+ commentCount={commentCount}+ scores={nodeScores}+ />+ </div>+ );+ })}+ </div>+ </div>+ </div>+ );+}diff --git a/web/src/components/trace2/components/TraceTimeline/timeline-calculations.clienttest.ts b/web/src/components/trace2/components/TraceTimeline/timeline-calculations.clienttest.tsnew file mode 100644index 0000000000..f7b3e47584--- /dev/null+++ b/web/src/components/trace2/components/TraceTimeline/timeline-calculations.clienttest.ts@@ -0,0 +1,269 @@+/**+ * @jest-environment jsdom+ */++import {+ calculateTimelineOffset,+ calculateTimelineWidth,+ calculateStepSize,+ getPredefinedStepSizes,+ SCALE_WIDTH,+ PREDEFINED_STEP_SIZES,+} from "./timeline-calculations";++describe("timeline-calculations", () => {+ describe("calculateTimelineOffset", () => {+ it("should return 0 for node starting at trace start", () => {+ const traceStart = new Date("2024-01-01T00:00:00Z");+ const nodeStart = new Date("2024-01-01T00:00:00Z");+ const totalDuration = 10; // 10 seconds++ const offset = calculateTimelineOffset(+ nodeStart,+ traceStart,+ totalDuration,+ );++ expect(offset).toBe(0);+ });++ it("should return SCALE_WIDTH for node starting at trace end", () => {+ const traceStart = new Date("2024-01-01T00:00:00Z");+ const nodeStart = new Date("2024-01-01T00:00:10Z"); // 10 seconds later+ const totalDuration = 10;++ const offset = calculateTimelineOffset(+ nodeStart,+ traceStart,+ totalDuration,+ );++ expect(offset).toBe(SCALE_WIDTH);+ });++ it("should return half SCALE_WIDTH for node starting at trace midpoint", () => {+ const traceStart = new Date("2024-01-01T00:00:00Z");+ const nodeStart = new Date("2024-01-01T00:00:05Z"); // 5 seconds later+ const totalDuration = 10;++ const offset = calculateTimelineOffset(+ nodeStart,+ traceStart,+ totalDuration,+ );++ expect(offset).toBe(SCALE_WIDTH / 2);+ });++ it("should handle custom scale width", () => {+ const traceStart = new Date("2024-01-01T00:00:00Z");+ const nodeStart = new Date("2024-01-01T00:00:05Z");+ const totalDuration = 10;+ const customWidth = 1800;++ const offset = calculateTimelineOffset(+ nodeStart,+ traceStart,+ totalDuration,+ customWidth,+ );++ expect(offset).toBe(customWidth / 2);+ });++ it("should handle fractional seconds", () => {+ const traceStart = new Date("2024-01-01T00:00:00Z");+ const nodeStart = new Date("2024-01-01T00:00:00.500Z"); // 0.5 seconds later+ const totalDuration = 1;++ const offset = calculateTimelineOffset(+ nodeStart,+ traceStart,+ totalDuration,+ );++ expect(offset).toBe(SCALE_WIDTH / 2);+ });+ });++ describe("calculateTimelineWidth", () => {+ it("should return 0 for zero duration", () => {+ const width = calculateTimelineWidth(0, 10);+ expect(width).toBe(0);+ });++ it("should return SCALE_WIDTH for duration equal to total span", () => {+ const width = calculateTimelineWidth(10, 10);+ expect(width).toBe(SCALE_WIDTH);+ });++ it("should return half SCALE_WIDTH for duration half of total span", () => {+ const width = calculateTimelineWidth(5, 10);+ expect(width).toBe(SCALE_WIDTH / 2);+ });++ it("should handle custom scale width", () => {+ const customWidth = 1800;+ const width = calculateTimelineWidth(5, 10, customWidth);+ expect(width).toBe(customWidth / 2);+ });++ it("should handle fractional durations", () => {+ const width = calculateTimelineWidth(0.5, 1);+ expect(width).toBe(SCALE_WIDTH / 2);+ });++ it("should handle very small durations", () => {+ const width = calculateTimelineWidth(0.001, 10);+ expect(width).toBe(SCALE_WIDTH * 0.0001);+ });+ });++ describe("calculateStepSize", () => {+ it("should select appropriate step size for short traces", () => {+ // 1 second trace should use small step size+ const stepSize = calculateStepSize(1);+ expect(stepSize).toBeLessThanOrEqual(1);+ expect(PREDEFINED_STEP_SIZES).toContain(stepSize);+ });++ it("should select appropriate step size for medium traces", () => {+ // 50 second trace+ const stepSize = calculateStepSize(50);+ expect(stepSize).toBeGreaterThan(1);+ expect(stepSize).toBeLessThanOrEqual(50);+ expect(PREDEFINED_STEP_SIZES).toContain(stepSize);+ });++ it("should select appropriate step size for long traces", () => {+ // 500 second trace+ const stepSize = calculateStepSize(500);+ expect(stepSize).toBeGreaterThan(10);+ expect(PREDEFINED_STEP_SIZES).toContain(stepSize);+ });++ it("should return largest step size for very long traces", () => {+ // 10000 second trace+ const stepSize = calculateStepSize(10000);+ expect(stepSize).toBe(+ PREDEFINED_STEP_SIZES[PREDEFINED_STEP_SIZES.length - 1],+ );+ });++ it("should return smallest applicable step size", () => {+ // For a 2 second trace, should select a step size >= calculated+ const stepSize = calculateStepSize(2);+ const calculatedStepSize = 2 / (SCALE_WIDTH / 100);+ expect(stepSize).toBeGreaterThanOrEqual(calculatedStepSize);+ });++ it("should handle custom scale width", () => {+ const customWidth = 1800;+ const stepSize = calculateStepSize(50, customWidth);+ expect(PREDEFINED_STEP_SIZES).toContain(stepSize);+ });++ it("should be consistent for same input", () => {+ const duration = 25;+ const stepSize1 = calculateStepSize(duration);+ const stepSize2 = calculateStepSize(duration);+ expect(stepSize1).toBe(stepSize2);+ });+ });++ describe("getPredefinedStepSizes", () => {+ it("should return array of step sizes", () => {+ const stepSizes = getPredefinedStepSizes();+ expect(Array.isArray(stepSizes)).toBe(true);+ expect(stepSizes.length).toBeGreaterThan(0);+ });++ it("should return a copy (not mutate original)", () => {+ const stepSizes = getPredefinedStepSizes();+ const originalLength = stepSizes.length;+ stepSizes.push(999);++ const stepSizes2 = getPredefinedStepSizes();+ expect(stepSizes2.length).toBe(originalLength);+ expect(stepSizes2).not.toContain(999);+ });++ it("should be in ascending order", () => {+ const stepSizes = getPredefinedStepSizes();+ for (let i = 1; i < stepSizes.length; i++) {+ expect(stepSizes[i]).toBeGreaterThan(stepSizes[i - 1]);+ }+ });++ it("should contain expected range of values", () => {+ const stepSizes = getPredefinedStepSizes();+ expect(stepSizes[0]).toBeLessThanOrEqual(1); // Has sub-second steps+ expect(stepSizes[stepSizes.length - 1]).toBeGreaterThanOrEqual(100); // Has large steps+ });+ });++ describe("Integration: offset + width should fit within trace", () => {+ it("should place a mid-trace observation correctly", () => {+ const traceStart = new Date("2024-01-01T00:00:00Z");+ const nodeStart = new Date("2024-01-01T00:00:03Z"); // starts at 3s+ const duration = 2; // lasts 2 seconds+ const totalDuration = 10;++ const offset = calculateTimelineOffset(+ nodeStart,+ traceStart,+ totalDuration,+ );+ const width = calculateTimelineWidth(duration, totalDuration);++ // Should start at 30% of scale width+ expect(offset).toBe(SCALE_WIDTH * 0.3);+ // Should be 20% of scale width+ expect(width).toBe(SCALE_WIDTH * 0.2);+ // Should end at 50% of scale width+ expect(offset + width).toBe(SCALE_WIDTH * 0.5);+ });++ it("should handle observation at trace boundary", () => {+ const traceStart = new Date("2024-01-01T00:00:00Z");+ const nodeStart = new Date("2024-01-01T00:00:00Z");+ const duration = 10;+ const totalDuration = 10;++ const offset = calculateTimelineOffset(+ nodeStart,+ traceStart,+ totalDuration,+ );+ const width = calculateTimelineWidth(duration, totalDuration);++ expect(offset).toBe(0);+ expect(width).toBe(SCALE_WIDTH);+ expect(offset + width).toBe(SCALE_WIDTH);+ });+ });++ describe("Edge cases", () => {+ it("calculateTimelineOffset should handle zero duration trace", () => {+ const traceStart = new Date("2024-01-01T00:00:00Z");+ const nodeStart = new Date("2024-01-01T00:00:00Z");+ const totalDuration = 0;++ // Should not throw, but result is undefined (division by zero)+ expect(() => {+ calculateTimelineOffset(nodeStart, traceStart, totalDuration);+ }).not.toThrow();+ });++ it("calculateStepSize should handle very small durations", () => {+ const stepSize = calculateStepSize(0.1);+ expect(stepSize).toBe(PREDEFINED_STEP_SIZES[0]); // Should use smallest step+ });++ it("calculateTimelineWidth should handle duration larger than total span", () => {+ // This shouldn't happen in practice, but handle gracefully+ const width = calculateTimelineWidth(20, 10);+ expect(width).toBe(SCALE_WIDTH * 2); // Just calculates proportionally+ });+ });+});diff --git a/web/src/components/trace2/components/TraceTimeline/timeline-calculations.ts b/web/src/components/trace2/components/TraceTimeline/timeline-calculations.tsnew file mode 100644index 0000000000..75066ca3a7--- /dev/null+++ b/web/src/components/trace2/components/TraceTimeline/timeline-calculations.ts@@ -0,0 +1,75 @@+/**+ * Pure functions for timeline calculations+ * These functions handle all timeline positioning and sizing logic+ */++// Fixed widths for timeline styling+export const SCALE_WIDTH = 900;+export const STEP_SIZE = 100;++// Predefined step sizes for time axis (in seconds)+export const PREDEFINED_STEP_SIZES = [+ 0.25, 0.5, 0.75, 1, 1.25, 1.5, 2, 2.5, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25,+ 35, 40, 45, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500,+];++/**+ * Calculate the horizontal offset from the trace start time+ * @param nodeStartTime - When the observation started+ * @param traceStartTime - When the trace started+ * @param totalScaleSpan - Total duration of the trace in seconds+ * @param scaleWidth - Width of the timeline scale in pixels+ * @returns Horizontal offset in pixels+ */+export function calculateTimelineOffset(+ nodeStartTime: Date,+ traceStartTime: Date,+ totalScaleSpan: number,+ scaleWidth: number = SCALE_WIDTH,+): number {+ const timeFromStart =+ (nodeStartTime.getTime() - traceStartTime.getTime()) / 1000;+ return (timeFromStart / totalScaleSpan) * scaleWidth;+}++/**+ * Calculate the width of a timeline bar from duration+ * @param duration - Duration in seconds+ * @param totalScaleSpan - Total duration of the trace in seconds+ * @param scaleWidth - Width of the timeline scale in pixels+ * @returns Width of the bar in pixels+ */+export function calculateTimelineWidth(+ duration: number,+ totalScaleSpan: number,+ scaleWidth: number = SCALE_WIDTH,+): number {+ return (duration / totalScaleSpan) * scaleWidth;+}++/**+ * Calculate appropriate step size for the time axis+ * Selects from predefined step sizes to ensure readable time markers+ * @param traceDuration - Total trace duration in seconds+ * @param scaleWidth - Width of the timeline scale in pixels+ * @returns Step size in seconds+ */+export function calculateStepSize(+ traceDuration: number,+ scaleWidth: number = SCALE_WIDTH,+): number {+ const calculatedStepSize = traceDuration / (scaleWidth / STEP_SIZE);+ return (+ PREDEFINED_STEP_SIZES.find((step) => step >= calculatedStepSize) ||+ PREDEFINED_STEP_SIZES[PREDEFINED_STEP_SIZES.length - 1]+ );+}++/**+ * Get all predefined step sizes+ * Useful for testing and validation+ * @returns Array of predefined step sizes in seconds+ */+export function getPredefinedStepSizes(): number[] {+ return [...PREDEFINED_STEP_SIZES];+}diff --git a/web/src/components/trace2/components/TraceTimeline/timeline-flattening.ts b/web/src/components/trace2/components/TraceTimeline/timeline-flattening.tsnew file mode 100644index 0000000000..f9b2124c12--- /dev/null+++ b/web/src/components/trace2/components/TraceTimeline/timeline-flattening.ts@@ -0,0 +1,129 @@+/**+ * Timeline-specific tree flattening with pre-computed metrics.+ * Extends base tree flattening to include timeline positioning calculations.+ */++import { type TreeNode } from "../../lib/types";+import { type FlatTimelineItem, type TimelineMetrics } from "./types";+import {+ calculateTimelineOffset,+ calculateTimelineWidth,+ SCALE_WIDTH,+} from "./timeline-calculations";++/**+ * Flattens tree into list for timeline virtualized rendering.+ * Pre-computes timeline metrics (offset, width) during flattening for performance.+ *+ * Uses iterative approach to avoid stack overflow with deep trees.+ *+ * @param node - Root node to flatten+ * @param collapsedNodes - Set of node IDs that are collapsed+ * @param traceStartTime - When the trace started (for offset calculation)+ * @param totalScaleSpan - Total duration of the trace in seconds+ * @param scaleWidth - Width of the timeline scale in pixels (default: SCALE_WIDTH)+ * @param depth - Current depth (0 for root)+ * @param treeLines - Which ancestor levels have vertical lines+ * @param isLastSibling - Whether this node is the last child of its parent+ * @returns Flat list of nodes with timeline metrics+ */+export function flattenTreeWithTimelineMetrics(+ node: TreeNode,+ collapsedNodes: Set<string>,+ traceStartTime: Date,+ totalScaleSpan: number,+ scaleWidth: number = SCALE_WIDTH,+ depth = 0,+ treeLines: boolean[] = [],+ isLastSibling = true,+): FlatTimelineItem[] {+ const flatList: FlatTimelineItem[] = [];++ // Initialize stack with root node+ const stack: Array<{+ node: TreeNode;+ depth: number;+ treeLines: boolean[];+ isLastSibling: boolean;+ }> = [{ node, depth, treeLines, isLastSibling }];++ // Process stack (LIFO - depth-first traversal)+ while (stack.length > 0) {+ const current = stack.pop()!;+ const currentNode = current.node;++ // Pre-compute timeline metrics ONCE during flattening+ const latency = currentNode.endTime+ ? (currentNode.endTime.getTime() - currentNode.startTime.getTime()) / 1000+ : undefined;++ const startOffset = calculateTimelineOffset(+ currentNode.startTime,+ traceStartTime,+ totalScaleSpan,+ scaleWidth,+ );++ const itemWidth = calculateTimelineWidth(+ latency ?? 0,+ totalScaleSpan,+ scaleWidth,+ );++ // Handle first token time for streaming LLMs (completionStartTime)+ // This is stored on observations that have streaming responses+ const firstTokenTimeOffset =+ "completionStartTime" in currentNode &&+ currentNode.completionStartTime instanceof Date+ ? calculateTimelineOffset(+ currentNode.completionStartTime,+ traceStartTime,+ totalScaleSpan,+ scaleWidth,+ )+ : undefined;++ const metrics: TimelineMetrics = {+ startOffset,+ itemWidth,+ firstTokenTimeOffset,+ latency,+ };++ // Add current node to result+ flatList.push({+ node: currentNode,+ depth: current.depth,+ treeLines: current.treeLines,+ isLastSibling: current.isLastSibling,+ metrics,+ });++ // If node has children and is not collapsed, add children to stack+ if (+ currentNode.children.length > 0 &&+ !collapsedNodes.has(currentNode.id)+ ) {+ // Sort children by startTime (chronological order)+ const sortedChildren = [...currentNode.children].sort(+ (a, b) => a.startTime.getTime() - b.startTime.getTime(),+ );++ // Push children in REVERSE order to maintain left-to-right DFS traversal+ // (stack is LIFO, so last pushed = first popped)+ 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, !isChildLast], // Add line if not last child+ isLastSibling: isChildLast,+ });+ }+ }+ }++ return flatList;+}diff --git a/web/src/components/trace2/components/TraceTimeline/types.ts b/web/src/components/trace2/components/TraceTimeline/types.tsnew file mode 100644index 0000000000..a132ef8b84--- /dev/null+++ b/web/src/components/trace2/components/TraceTimeline/types.ts@@ -0,0 +1,98 @@+/**+ * Timeline-specific types for trace visualization+ */++import type { TreeNode } from "../../lib/types";+import type Decimal from "decimal.js";+import type { ScoreDomain } from "@langfuse/shared";+import type { WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";++/**+ * Pre-computed timeline metrics for efficient rendering+ * Calculated once during tree flattening to avoid per-frame calculations+ */+export interface TimelineMetrics {+ /** Horizontal offset from trace start (in pixels) */+ startOffset: number;+ /** Width of the timeline bar (in pixels) */+ itemWidth: number;+ /** Offset for first token time marker (for streaming LLMs, in pixels) */+ firstTokenTimeOffset?: number;+ /** Duration in seconds */+ latency?: number;+}++/**+ * Props for TimelineBar component+ * Renders individual Gantt bar with metrics and badges+ */+export interface TimelineBarProps {+ node: TreeNode;+ metrics: TimelineMetrics;+ isSelected: boolean;+ onSelect: () => void;+ // View preferences+ showDuration: boolean;+ showCostTokens: boolean;+ showScores: boolean;+ showComments: boolean;+ colorCodeMetrics: boolean;+ // Heatmap context for color coding+ parentTotalCost?: Decimal;+ parentTotalDuration?: number;+ // Comment count (optional)+ commentCount?: number;+ // Scores for badges+ scores?: WithStringifiedMetadata<ScoreDomain>[];+}++/**+ * Flattened timeline item for virtualized rendering+ * Extends TreeNode with timeline positioning data and tree structure metadata+ */+export interface FlatTimelineItem {+ node: TreeNode;+ depth: number;+ treeLines: boolean[];+ isLastSibling: boolean;+ // Pre-computed timeline metrics+ metrics: TimelineMetrics;+}++/**+ * Props for TimelineRow component+ * Renders tree structure + timeline bar+ */+export interface TimelineRowProps {+ item: FlatTimelineItem;+ isSelected: boolean;+ onSelect: () => void;+ onToggleCollapse: () => void;+ hasChildren: boolean;+ isCollapsed: boolean;+ // View preferences+ showDuration: boolean;+ showCostTokens: boolean;+ showScores: boolean;+ showComments: boolean;+ colorCodeMetrics: boolean;+ // Heatmap context+ parentTotalCost?: Decimal;+ parentTotalDuration?: number;+ // Optional data+ commentCount?: number;+ scores?: WithStringifiedMetadata<ScoreDomain>[];+}++/**+ * Props for TimelineScale component+ * Renders time axis with markers+ */+export interface TimelineScaleProps {+ /** Total trace duration in seconds */+ traceDuration: number;+ /** Width of the timeline scale in pixels */+ scaleWidth: number;+ /** Step size between time markers in seconds */+ stepSize: number;+}diff --git a/web/src/components/trace2/components/TraceTree.tsx b/web/src/components/trace2/components/TraceTree.tsxnew file mode 100644index 0000000000..9437df78e6--- /dev/null+++ b/web/src/components/trace2/components/TraceTree.tsx@@ -0,0 +1,69 @@+/**+ * TraceTree - Composition of VirtualizedTree + TreeNodeWrapper + SpanContent.+ *+ * Connects three layers:+ * - VirtualizedTree (virtualization)+ * - TreeNodeWrapper (tree structure rendering)+ * - SpanContent (span-specific content)+ *+ * This composition pattern allows each component to have a single responsibility.+ */++import { VirtualizedTree } from "./_shared/VirtualizedTree";+import { VirtualizedTreeNodeWrapper } from "./_shared/VirtualizedTreeNodeWrapper";+import { SpanContent } from "./SpanContent";+import { useTraceData } from "../contexts/TraceDataContext";+import { useSelection } from "../contexts/SelectionContext";+import { type TreeNode } from "../lib/types";++export function TraceTree() {+ const { tree, comments } = useTraceData();+ const { selectedNodeId, setSelectedNodeId, collapsedNodes, toggleCollapsed } =+ useSelection();++ // Calculate root totals for heatmap color scaling+ // These values are used as the "max" reference for all nodes+ const rootTotalCost = tree.totalCost;+ const rootTotalDuration =+ tree.latency != null ? tree.latency * 1000 : undefined;++ return (+ <VirtualizedTree+ tree={tree}+ collapsedNodes={collapsedNodes}+ selectedNodeId={selectedNodeId}+ onToggleCollapse={toggleCollapsed}+ onSelectNode={setSelectedNodeId}+ renderNode={({+ node,+ treeMetadata,+ isSelected,+ isCollapsed,+ onToggleCollapse,+ onSelect,+ }) => {+ const typedNode = node as TreeNode;++ return (+ <VirtualizedTreeNodeWrapper+ metadata={treeMetadata}+ nodeType={typedNode.type}+ hasChildren={typedNode.children.length > 0}+ isCollapsed={isCollapsed}+ onToggleCollapse={onToggleCollapse}+ isSelected={isSelected}+ onSelect={onSelect}+ >+ <SpanContent+ node={typedNode}+ parentTotalCost={rootTotalCost}+ parentTotalDuration={rootTotalDuration}+ commentCount={comments.get(typedNode.id)}+ onSelect={onSelect}+ />+ </VirtualizedTreeNodeWrapper>+ );+ }}+ />+ );+}diff --git a/web/src/components/trace2/components/_layout/TraceLayoutDesktop.tsx b/web/src/components/trace2/components/_layout/TraceLayoutDesktop.tsxnew file mode 100644index 0000000000..691ab7dd03--- /dev/null+++ b/web/src/components/trace2/components/_layout/TraceLayoutDesktop.tsx@@ -0,0 +1,230 @@+import { StringParam, useQueryParam } from "use-query-params";+import {+ PanelGroup,+ PanelResizeHandle,+ Panel,+ type ImperativePanelHandle,+} from "react-resizable-panels";+import {+ useRef,+ useState,+ useEffect,+ useLayoutEffect,+ createContext,+ useContext,+ type ReactNode,+} from "react";++const RESIZABLE_PANEL_GROUP_ID = "trace-layout";+const RESIZABLE_PANEL_HANDLE_ID = "trace-layout-handle";+const RESIZABLE_PANEL_NAVIGATION_ID = "trace-layout-panel-navigation";+const RESIZABLE_PANEL_PREVIEW_ID = "trace-layout-panel-preview";++const NAVIGATION_PANEL_DEFAULT_SIZE_IN_PIXELS = 450;+const NAVIGATION_PANEL_MIN_SIZE_IN_PIXELS = 360;+const NAVIGATION_PANEL_COLLAPSED_SIZE_IN_PIXELS = 40;++// Context for sharing panel state with compound components+interface TraceLayoutDesktopContext {+ navigationPanelMinSize: number;+ navigationPanelCollapsedSize: number;+ isNavigationPanelCollapsed: boolean;+ setIsNavigationPanelCollapsed: (collapsed: boolean) => void;+ panelRef: React.RefObject<ImperativePanelHandle | null>;+ handleTogglePanel: () => void;+ shouldPulseToggle: boolean;+}++const LayoutContext = createContext<TraceLayoutDesktopContext | null>(null);++function useLayoutContext() {+ const context = useContext(LayoutContext);+ if (!context) {+ throw new Error(+ "TraceLayoutDesktop compound components must be used within TraceLayoutDesktop",+ );+ }+ return context;+}++// Export hook for use in Trace.tsx+export function useDesktopLayoutContext() {+ return useLayoutContext();+}++export function TraceLayoutDesktop({ children }: { children: ReactNode }) {+ // Get current view mode from URL+ const [viewMode] = useQueryParam("view", StringParam);+ const isTimelineView = viewMode === "timeline";++ // react-resizable-panels requires percentage values+ const [navigationPanelDefaultSize, setNavigationPanelDefaultSize] =+ useState(10);+ const [navigationPanelMinSize, setNavigationPanelMinSize] = useState(10);+ const [navigationPanelCollapsedSize, setNavigationPanelCollapsedSize] =+ useState(5);+ const [isNavigationPanelCollapsed, setIsNavigationPanelCollapsed] =+ useState(false);++ // Remember the last size before collapse to restore it when expanding+ const [lastNavigationPanelSize, setLastNavigationPanelSize] = useState<+ number | null+ >(null);++ // Ref to programmatically control the panel+ const panelRef = useRef<ImperativePanelHandle>(null);++ useLayoutEffect(() => {+ // Note: react-resizable-panels does not support pixel-based values+ // this is a workaround to get the correct values+ const panelGroup = document.querySelector(+ `#${RESIZABLE_PANEL_GROUP_ID}`,+ ) as HTMLElement;+ const resizeHandles = document.querySelectorAll(+ `#${RESIZABLE_PANEL_HANDLE_ID}`,+ ) as NodeListOf<HTMLElement>;++ if (!panelGroup || !resizeHandles) {+ return;+ }++ const observer = new ResizeObserver(() => {+ // For horizontal panels, we need to use width, not height+ let width = panelGroup.offsetWidth;++ // Subtract the width of resize handles+ resizeHandles.forEach((resizeHandle) => {+ width -= resizeHandle.offsetWidth;+ });++ // Convert pixel values to percentages based on available width+ const defaultSizePercentage =+ (NAVIGATION_PANEL_DEFAULT_SIZE_IN_PIXELS / width) * 100;+ const minSizePercentage =+ (NAVIGATION_PANEL_MIN_SIZE_IN_PIXELS / width) * 100;+ const collapsedSizePercentage =+ (NAVIGATION_PANEL_COLLAPSED_SIZE_IN_PIXELS / width) * 100;++ setNavigationPanelDefaultSize(defaultSizePercentage);+ setNavigationPanelMinSize(minSizePercentage);+ setNavigationPanelCollapsedSize(collapsedSizePercentage);+ });+ observer.observe(panelGroup);++ resizeHandles.forEach((resizeHandle) => {+ observer.observe(resizeHandle);+ });++ return () => {+ observer.disconnect();+ };+ }, []);++ const handleTogglePanel = () => {+ if (!panelRef.current) return;++ // Programmatically collapse or expand the panel+ if (isNavigationPanelCollapsed) {+ // Expanding: restore to last size or use defaultSize as fallback+ const targetSize = lastNavigationPanelSize ?? navigationPanelDefaultSize;+ panelRef.current.resize(targetSize);+ setIsNavigationPanelCollapsed(false);+ } else {+ // Collapsing: save current size before collapsing+ const currentSize = panelRef.current.getSize();+ setLastNavigationPanelSize(currentSize);+ setIsNavigationPanelCollapsed(true);+ panelRef.current.resize(navigationPanelCollapsedSize);+ }+ };++ // Pulse animation: hint to user that panel can be collapsed when switching to timeline+ const [shouldPulseToggle, setShouldPulseToggle] = useState(false);++ useEffect(() => {+ if (isTimelineView) {+ setShouldPulseToggle(true);+ const timeout = setTimeout(() => {+ setShouldPulseToggle(false);+ }, 12000); // Stop pulse after 12 seconds+ return () => clearTimeout(timeout);+ } else {+ // Reset pulse when leaving timeline view+ setShouldPulseToggle(false);+ }+ }, [isTimelineView]);++ const contextValue: TraceLayoutDesktopContext = {+ navigationPanelMinSize,+ navigationPanelCollapsedSize,+ isNavigationPanelCollapsed,+ setIsNavigationPanelCollapsed,+ panelRef,+ handleTogglePanel,+ shouldPulseToggle,+ };++ return (+ <LayoutContext.Provider value={contextValue}>+ <div className="h-full w-full">+ <PanelGroup direction="horizontal" id={RESIZABLE_PANEL_GROUP_ID}>+ {children}+ </PanelGroup>+ </div>+ </LayoutContext.Provider>+ );+}++// Compound component: Navigation panel+TraceLayoutDesktop.NavigationPanel = function Navigation({+ children,+}: {+ children: ReactNode;+}) {+ const {+ navigationPanelMinSize,+ navigationPanelCollapsedSize,+ setIsNavigationPanelCollapsed,+ panelRef,+ } = useLayoutContext();++ return (+ <Panel+ id={RESIZABLE_PANEL_NAVIGATION_ID}+ ref={panelRef}+ collapsible={true}+ collapsedSize={navigationPanelCollapsedSize}+ minSize={navigationPanelMinSize}+ onCollapse={() => setIsNavigationPanelCollapsed(true)}+ onExpand={() => setIsNavigationPanelCollapsed(false)}+ >+ {children}+ </Panel>+ );+};++// Compound component: Resize handle+TraceLayoutDesktop.ResizeHandle = function ResizeHandle() {+ const { handleTogglePanel } = useLayoutContext();++ return (+ <PanelResizeHandle+ id={RESIZABLE_PANEL_HANDLE_ID}+ className="relative w-px bg-border transition-colors duration-200 after:absolute after:inset-y-0 after:left-0 after:w-1 after:bg-blue-200 after:opacity-0 after:transition-opacity after:duration-200 hover:after:opacity-100 data-[resize-handle-state='drag']:after:opacity-100"+ onDoubleClick={handleTogglePanel}+ />+ );+};++// Compound component: Detail panel+TraceLayoutDesktop.DetailPanel = function Detail({+ children,+}: {+ children: ReactNode;+}) {+ return (+ <Panel id={RESIZABLE_PANEL_PREVIEW_ID} defaultSize={70} minSize={50}>+ {children}+ </Panel>+ );+};diff --git a/web/src/components/trace2/components/_layout/TraceLayoutMobile.tsx b/web/src/components/trace2/components/_layout/TraceLayoutMobile.tsxnew file mode 100644index 0000000000..2a4e2f277f--- /dev/null+++ b/web/src/components/trace2/components/_layout/TraceLayoutMobile.tsx@@ -0,0 +1,96 @@+/**+ * TraceLayoutMobile - Touch-friendly vertical layout for mobile devices+ *+ * Purpose:+ * - Provide mobile-optimized UI without resizable panels+ * - Vertical stack: navigation at top, detail below+ * - No drag handles (confusing on touch devices)+ *+ * Layout:+ * - Navigation is collapsible (accordion-style)+ * - Detail takes remaining space+ * - All content scrollable within sections+ */++import { useState, createContext, useContext, type ReactNode } from "react";+import { Button } from "@/src/components/ui/button";+import { ChevronDown, ChevronUp } from "lucide-react";++// Context for sharing accordion state with compound components+interface TraceLayoutMobileContext {+ isNavigationExpanded: boolean;+ setIsNavigationExpanded: (expanded: boolean) => void;+}++const LayoutContext = createContext<TraceLayoutMobileContext | null>(null);++function useLayoutContext() {+ const context = useContext(LayoutContext);+ if (!context) {+ throw new Error(+ "TraceLayoutMobile compound components must be used within TraceLayoutMobile",+ );+ }+ return context;+}++// Export hook for use in TracePanelNavigationLayoutMobile+export function useMobileLayoutContext() {+ return useLayoutContext();+}++export function TraceLayoutMobile({ children }: { children: ReactNode }) {+ const [isNavigationExpanded, setIsNavigationExpanded] = useState(true);++ const contextValue: TraceLayoutMobileContext = {+ isNavigationExpanded,+ setIsNavigationExpanded,+ };++ return (+ <LayoutContext.Provider value={contextValue}>+ <div className="flex h-full w-full flex-col">{children}</div>+ </LayoutContext.Provider>+ );+}++// Compound component: Navigation section with accordion+TraceLayoutMobile.NavigationPanel = function Navigation({+ children,+}: {+ children: ReactNode;+}) {+ const { isNavigationExpanded, setIsNavigationExpanded } = useLayoutContext();++ return (+ <div className="flex flex-shrink-0 flex-col border-b">+ {/* Accordion Header */}+ <Button+ variant="ghost"+ className="flex w-full justify-between rounded-none px-4 py-3 text-left"+ onClick={() => setIsNavigationExpanded(!isNavigationExpanded)}+ >+ <span className="font-medium">Navigation</span>+ {isNavigationExpanded ? (+ <ChevronUp className="h-4 w-4" />+ ) : (+ <ChevronDown className="h-4 w-4" />+ )}+ </Button>++ {/* Navigation Content - Collapsible */}+ {isNavigationExpanded && (+ <div className="max-h-96 overflow-y-auto">{children}</div>+ )}+ </div>+ );+};++// Compound component: Detail section+TraceLayoutMobile.DetailPanel = function Detail({+ children,+}: {+ children: ReactNode;+}) {+ return <div className="flex-1 overflow-y-auto">{children}</div>;+};diff --git a/web/src/components/trace2/components/_layout/TracePanelDetail.tsx b/web/src/components/trace2/components/_layout/TracePanelDetail.tsxnew file mode 100644index 0000000000..98704bd36e--- /dev/null+++ b/web/src/components/trace2/components/_layout/TracePanelDetail.tsx@@ -0,0 +1,72 @@+/**+ * TracePanelDetail - Pure content component for detail panel+ *+ * Responsibility:+ * - Decide which detail view to show (Trace/Observation)+ * - Minimal wrapper (scrollable container) for layout consistency+ *+ * Hooks:+ * - useSelection() - for selected node state+ * - useTraceData() - for trace, nodeMap, observations, scores+ *+ * Re-renders when:+ * - Selection changes (clicking nodes)+ * - Trace data changes (rare)+ * - Does NOT re-render when search changes (isolated)+ */++import { useSelection } from "../../contexts/SelectionContext";+import { useTraceData } from "../../contexts/TraceDataContext";+import { TraceDetailView } from "../TraceDetailView/TraceDetailView";+import { ObservationDetailView } from "../ObservationDetailView/ObservationDetailView";+import { useMemo } from "react";++export function TracePanelDetail() {+ const { selectedNodeId } = useSelection();+ const { trace, nodeMap, observations, scores } = useTraceData();++ // Memoize to prevent recreation when deps haven't changed+ const content = useMemo(() => {+ const selectedNode = selectedNodeId ? nodeMap.get(selectedNodeId) : null;+ const isObservationSelected =+ selectedNodeId !== null && selectedNode?.type !== "TRACE";++ if (isObservationSelected && selectedNode) {+ // Find the full observation data from observations array+ const observationData = observations.find(+ (obs) => obs.id === selectedNode.id,+ );++ if (!observationData) {+ return (+ <div className="flex h-full w-full items-center justify-center p-4">+ <p className="text-sm text-muted-foreground">+ Observation not found+ </p>+ </div>+ );+ }++ return (+ <ObservationDetailView+ observation={observationData}+ projectId={trace.projectId}+ traceId={trace.id}+ />+ );+ }++ return (+ <TraceDetailView+ trace={trace}+ observations={observations}+ scores={scores}+ projectId={trace.projectId}+ />+ );+ }, [selectedNodeId, nodeMap, trace, observations, scores]);++ return (+ <div className="h-full w-full overflow-y-auto bg-background">{content}</div>+ );+}diff --git a/web/src/components/trace2/components/_layout/TracePanelNavigation.tsx b/web/src/components/trace2/components/_layout/TracePanelNavigation.tsxnew file mode 100644index 0000000000..f28cb8dfd0--- /dev/null+++ b/web/src/components/trace2/components/_layout/TracePanelNavigation.tsx@@ -0,0 +1,45 @@+/**+ * TracePanelNavigation - Pure content component for navigation panel+ *+ * Responsibility:+ * - Decide which navigation view to show (Tree/Timeline/Search)+ * - NO layout structure - just returns the content component+ *+ * Hooks:+ * - useSearch() - for search query state+ * - useQueryParam() - for timeline view mode+ *+ * Re-renders when:+ * - Search query changes+ * - View mode changes (timeline toggle)+ * - Does NOT re-render when selection changes (isolated)+ */++import { StringParam, useQueryParam } from "use-query-params";+import { useSearch } from "../../contexts/SearchContext";+import { TraceTree } from "../TraceTree";+import { TraceSearchList } from "../TraceSearchList";+import { TraceTimeline } from "../TraceTimeline";+import { useMemo } from "react";++export function TracePanelNavigation() {+ const { searchQuery } = useSearch();+ const [viewMode] = useQueryParam("view", StringParam);++ const hasQuery = searchQuery.trim().length > 0;+ const isTimelineView = viewMode === "timeline";++ // Memoize to prevent recreation when deps haven't changed+ const content = useMemo(() => {+ // Priority: Search > Timeline > Tree+ if (hasQuery) {+ return <TraceSearchList />;+ }+ if (isTimelineView) {+ return <TraceTimeline />;+ }+ return <TraceTree />;+ }, [hasQuery, isTimelineView]);++ return content;+}diff --git a/web/src/components/trace2/components/_layout/TracePanelNavigationButton.tsx b/web/src/components/trace2/components/_layout/TracePanelNavigationButton.tsxnew file mode 100644index 0000000000..933b406198--- /dev/null+++ b/web/src/components/trace2/components/_layout/TracePanelNavigationButton.tsx@@ -0,0 +1,48 @@+import { Button } from "@/src/components/ui/button";+import { PanelLeftClose, PanelLeftOpen } from "lucide-react";++import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";++interface TracePanelNavigationButtonProps {+ isPanelCollapsed: boolean;+ onTogglePanel: () => void;+ shouldPulseToggle?: boolean;+}++export function TracePanelNavigationButton({+ isPanelCollapsed,+ onTogglePanel,+ shouldPulseToggle = false,+}: TracePanelNavigationButtonProps) {+ const capture = usePostHogClientCapture();+ return (+ <div className="relative">+ <Button+ onClick={() => {+ onTogglePanel();+ capture("trace_detail:tree_panel_toggle", {+ collapsed: !isPanelCollapsed,+ });+ }}+ variant="ghost"+ size="icon"+ title={isPanelCollapsed ? "Expand panel" : "Collapse panel"}+ className="h-7 w-7 shrink-0"+ >+ {isPanelCollapsed ? (+ <PanelLeftOpen className="h-3.5 w-3.5" />+ ) : (+ <PanelLeftClose className="h-3.5 w-3.5" />+ )}+ </Button>++ {/* Pulsing status indicator */}+ {shouldPulseToggle && (+ <span className="pointer-events-none absolute right-0.5 top-0.5 flex h-2.5 w-2.5">+ <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-blue-400 opacity-75" />+ <span className="relative inline-flex h-2.5 w-2.5 rounded-full bg-blue-500" />+ </span>+ )}+ </div>+ );+}diff --git a/web/src/components/trace2/components/_layout/TracePanelNavigationHeader.tsx b/web/src/components/trace2/components/_layout/TracePanelNavigationHeader.tsxnew file mode 100644index 0000000000..4c19924ad9--- /dev/null+++ b/web/src/components/trace2/components/_layout/TracePanelNavigationHeader.tsx@@ -0,0 +1,174 @@+/**+ * NavigationHeader - Fixed-height search bar for navigation panel+ *+ * Responsibilities:+ * - Render search input+ * - Render toolbar buttons (expand/collapse, settings, download, timeline)+ * - Manage search input state via SearchContext+ *+ * This component has a fixed height and uses flex-shrink-0 to maintain size.+ */++import { useSearch } from "../../contexts/SearchContext";+import { useSelection } from "../../contexts/SelectionContext";+import { useTraceData } from "../../contexts/TraceDataContext";+import { useTraceGraphData } from "../../contexts/TraceGraphDataContext";+import { Command, CommandInput } from "@/src/components/ui/command";+import { Button } from "@/src/components/ui/button";+import { FoldVertical, UnfoldVertical, Download } from "lucide-react";+import { StringParam, useQueryParam } from "use-query-params";+import { cn } from "@/src/utils/tailwind";+import { useCallback } from "react";+import { TraceSettingsDropdown } from "../TraceSettingsDropdown";+import { downloadTraceAsJson } from "../../lib/download-trace";+import { TracePanelNavigationButton } from "./TracePanelNavigationButton";++interface TracePanelNavigationHeaderProps {+ isPanelCollapsed: boolean;+ onTogglePanel: () => void;+ shouldPulseToggle?: boolean;+}++export function TracePanelNavigationHeader(+ props: TracePanelNavigationHeaderProps,+) {+ if (props.isPanelCollapsed) {+ return <TracePanelNavigationHeaderCollapsed {...props} />;+ }+ return <TracePanelNavigationHeaderExpanded {...props} />;+}++function TracePanelNavigationHeaderCollapsed({+ isPanelCollapsed,+ onTogglePanel,+ shouldPulseToggle = false,+}: TracePanelNavigationHeaderProps) {+ return (+ <div className="flex w-full flex-row items-center justify-center p-2">+ <TracePanelNavigationButton+ isPanelCollapsed={isPanelCollapsed}+ onTogglePanel={onTogglePanel}+ shouldPulseToggle={shouldPulseToggle}+ />+ </div>+ );+}++function TracePanelNavigationHeaderExpanded({+ isPanelCollapsed,+ onTogglePanel,+ shouldPulseToggle = false,+}: TracePanelNavigationHeaderProps) {+ const { searchInputValue, setSearchInputValue, setSearchQueryImmediate } =+ useSearch();+ const { expandAll, collapseAll, collapsedNodes } = useSelection();+ const { tree, trace, observations } = useTraceData();+ const { isGraphViewAvailable } = useTraceGraphData();+ const [viewMode, setViewMode] = useQueryParam("view", StringParam);++ const handleSearchKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {+ if (e.key === "Enter") {+ // Skip debouncing and search immediately+ setSearchQueryImmediate(searchInputValue);+ }+ };++ // Check if everything is collapsed+ const isEverythingCollapsed = collapsedNodes.has(tree.id);++ // Collect all node IDs for collapse all+ const getAllNodeIds = useCallback((node: typeof tree): string[] => {+ const ids = [node.id];+ node.children.forEach((child) => {+ ids.push(...getAllNodeIds(child));+ });+ return ids;+ }, []);++ const handleToggleTreeNodes = useCallback(() => {+ if (isEverythingCollapsed) {+ expandAll();+ } else {+ const allIds = getAllNodeIds(tree);+ collapseAll(allIds);+ }+ }, [isEverythingCollapsed, expandAll, collapseAll, getAllNodeIds, tree]);++ const handleDownload = useCallback(() => {+ downloadTraceAsJson({+ trace,+ observations,+ });+ }, [trace, observations]);++ const isTimelineView = viewMode === "timeline";++ return (+ <Command className="mt-1 flex h-auto flex-shrink-0 flex-col gap-1 overflow-hidden rounded-none border-b">+ <div className="flex flex-row justify-between pl-1 pr-2">+ {/* Panel Toggle Button; special p-0.5 offset to pixel align with closed version */}+ <div className="flex flex-row items-center p-0.5">+ <TracePanelNavigationButton+ isPanelCollapsed={isPanelCollapsed}+ onTogglePanel={onTogglePanel}+ shouldPulseToggle={shouldPulseToggle}+ />+ </div>+ {/* Search Input */}+ <div className="relative flex-1">+ <CommandInput+ showBorder={false}+ placeholder="Search"+ className="h-7 min-w-20 border-0 pr-0 focus:ring-0"+ value={searchInputValue}+ onValueChange={setSearchInputValue}+ onKeyDown={handleSearchKeyDown}+ />+ </div>+ <div className="flex flex-row items-center gap-0.5">+ {/* Expand/Collapse All Button */}+ <Button+ onClick={handleToggleTreeNodes}+ variant="ghost"+ size="icon"+ title={isEverythingCollapsed ? "Expand all" : "Collapse all"}+ className="h-7 w-7"+ >+ {isEverythingCollapsed ? (+ <UnfoldVertical className="h-3.5 w-3.5" />+ ) : (+ <FoldVertical className="h-3.5 w-3.5" />+ )}+ </Button>++ {/* Settings Dropdown */}+ <TraceSettingsDropdown isGraphViewAvailable={isGraphViewAvailable} />++ {/* Download Button */}+ <Button+ variant="ghost"+ size="icon"+ onClick={handleDownload}+ title="Download trace as JSON"+ className="h-7 w-7"+ >+ <Download className="h-3.5 w-3.5" />+ </Button>++ {/* Timeline Toggle Button */}+ <Button+ variant={isTimelineView ? "default" : "ghost"}+ size="sm"+ onClick={() => setViewMode(isTimelineView ? null : "timeline")}+ className={cn(+ "h-7 px-2 text-xs",+ isTimelineView && "bg-primary text-primary-foreground",+ )}+ >+ <span className="text-xs">Timeline</span>+ </Button>+ </div>+ </div>+ </Command>+ );+}diff --git a/web/src/components/trace2/components/_layout/TracePanelNavigationHiddenNotice.tsx b/web/src/components/trace2/components/_layout/TracePanelNavigationHiddenNotice.tsxnew file mode 100644index 0000000000..3062fb322e--- /dev/null+++ b/web/src/components/trace2/components/_layout/TracePanelNavigationHiddenNotice.tsx@@ -0,0 +1,53 @@+/**+ * HiddenObservationsNotice - Shows notification when observations are filtered by minimum level+ *+ * Displays:+ * - Count of hidden observations+ * - Current minimum observation level+ * - "Show all" link to reset filter to DEBUG level+ *+ * Only renders when hiddenObservationsCount > 0+ * Fixed height component placed below NavigationHeader+ */++import { ObservationLevel } from "@langfuse/shared";+import { useTraceData } from "../../contexts/TraceDataContext";+import { useViewPreferences } from "../../contexts/ViewPreferencesContext";++export function TracePanelNavigationHiddenNotice() {+ const { hiddenObservationsCount } = useTraceData();+ const { minObservationLevel, setMinObservationLevel } = useViewPreferences();++ const handleShowAll = () => {+ setMinObservationLevel(ObservationLevel.DEBUG);+ };++ // Only show when observations are hidden+ if (hiddenObservationsCount === 0) {+ return null;+ }++ return (+ <div className="flex flex-shrink-0 items-center justify-end gap-1 border-b px-4 py-1">+ <span className="flex flex-col gap-1 text-xs text-muted-foreground sm:flex-row">+ <p>+ {hiddenObservationsCount} hidden observations below{" "}+ {minObservationLevel} level.+ </p>+ <p+ className="cursor-pointer underline"+ onClick={handleShowAll}+ role="button"+ tabIndex={0}+ onKeyDown={(e) => {+ if (e.key === "Enter" || e.key === " ") {+ handleShowAll();+ }+ }}+ >+ Show all+ </p>+ </span>+ </div>+ );+}diff --git a/web/src/components/trace2/components/_layout/TracePanelNavigationLayoutDesktop.tsx b/web/src/components/trace2/components/_layout/TracePanelNavigationLayoutDesktop.tsxnew file mode 100644index 0000000000..7c614fa776--- /dev/null+++ b/web/src/components/trace2/components/_layout/TracePanelNavigationLayoutDesktop.tsx@@ -0,0 +1,71 @@+/**+ * TracePanelNavigationLayoutDesktop - Desktop-specific layout wrapper for navigation panel+ *+ * Responsibility:+ * - Wrap navigation content with header and collapsible layout structure+ * - Handle panel collapse/expand state for desktop+ * - Position TracePanelNavigationHiddenNotice above content+ * - Render graph view panel below tree/timeline when enabled+ *+ * Hooks:+ * - useDesktopLayoutContext() - for panel collapse state+ * - useViewPreferences() - for showGraph preference+ * - useGraphData() - for isGraphViewAvailable+ *+ * Re-renders when:+ * - Panel collapse/expand state changes+ * - showGraph or isGraphViewAvailable changes+ * - Does NOT re-render when search/selection changes (isolated)+ */++import { type ReactNode } from "react";+import {+ ResizablePanel,+ ResizablePanelGroup,+ ResizableHandle,+} from "@/src/components/ui/resizable";+import { useDesktopLayoutContext } from "./TraceLayoutDesktop";+import { TracePanelNavigationHeader } from "./TracePanelNavigationHeader";+import { TracePanelNavigationHiddenNotice } from "./TracePanelNavigationHiddenNotice";++export function TracePanelNavigationLayoutDesktop({+ children,+ secondaryContent,+}: {+ children: ReactNode;+ secondaryContent?: ReactNode;+}) {+ const { isNavigationPanelCollapsed, handleTogglePanel, shouldPulseToggle } =+ useDesktopLayoutContext();++ return (+ <div className="flex h-full flex-col border-r">+ <TracePanelNavigationHeader+ isPanelCollapsed={isNavigationPanelCollapsed}+ onTogglePanel={handleTogglePanel}+ shouldPulseToggle={shouldPulseToggle}+ />+ {!isNavigationPanelCollapsed && (+ <>+ <TracePanelNavigationHiddenNotice />+ {secondaryContent ? (+ <ResizablePanelGroup+ direction="vertical"+ className="flex-1 overflow-hidden"+ >+ <ResizablePanel defaultSize={60} minSize={20}>+ <div className="h-full overflow-hidden">{children}</div>+ </ResizablePanel>+ <ResizableHandle className="h-px bg-border" />+ <ResizablePanel defaultSize={40} minSize={20}>+ <div className="h-full overflow-hidden">{secondaryContent}</div>+ </ResizablePanel>+ </ResizablePanelGroup>+ ) : (+ <div className="flex-1 overflow-hidden">{children}</div>+ )}+ </>+ )}+ </div>+ );+}diff --git a/web/src/components/trace2/components/_layout/TracePanelNavigationLayoutMobile.tsx b/web/src/components/trace2/components/_layout/TracePanelNavigationLayoutMobile.tsxnew file mode 100644index 0000000000..a351faa5f1--- /dev/null+++ b/web/src/components/trace2/components/_layout/TracePanelNavigationLayoutMobile.tsx@@ -0,0 +1,61 @@+/**+ * TracePanelNavigationLayoutMobile - Mobile-specific layout wrapper for navigation panel+ *+ * Responsibility:+ * - Wrap navigation content with mobile-optimized layout structure+ * - Position TracePanelNavigationHiddenNotice above content+ * - Provide scrollable container for navigation content+ * - Render graph view below tree/timeline when enabled (collapsible)+ *+ * Hooks:+ * - None (pure layout component)+ * - useViewPreferences() - for showGraph preference+ * - useTraceGraphData() - for isGraphViewAvailable+ *+ * Re-renders when:+ * - Children change (TracePanelNavigation content)+ * - showGraph or isGraphViewAvailable changes+ * - Does NOT re-render when selection changes (isolated to detail panel)+ */++import { type ReactNode, useState } from "react";+import { ChevronDown, ChevronUp } from "lucide-react";+import { Button } from "@/src/components/ui/button";+import { TracePanelNavigationHiddenNotice } from "./TracePanelNavigationHiddenNotice";++export function TracePanelNavigationLayoutMobile({+ children,+ secondaryContent,+}: {+ children: ReactNode;+ secondaryContent?: ReactNode;+}) {+ const [isGraphExpanded, setIsGraphExpanded] = useState(false);++ return (+ <div className="flex h-full flex-col">+ <TracePanelNavigationHiddenNotice />+ <div className="flex-1 overflow-hidden">{children}</div>+ {secondaryContent && (+ <div className="border-t">+ <Button+ variant="ghost"+ size="sm"+ onClick={() => setIsGraphExpanded(!isGraphExpanded)}+ className="flex w-full items-center justify-between px-2 py-1"+ >+ <span className="text-xs font-medium">Graph View</span>+ {isGraphExpanded ? (+ <ChevronUp className="h-3.5 w-3.5" />+ ) : (+ <ChevronDown className="h-3.5 w-3.5" />+ )}+ </Button>+ {isGraphExpanded && (+ <div className="h-64 overflow-hidden">{secondaryContent}</div>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/web/src/components/trace2/components/_shared/BreakdownToolTip.tsx b/web/src/components/trace2/components/_shared/BreakdownToolTip.tsxnew file mode 100644index 0000000000..8de1c32cbb--- /dev/null+++ b/web/src/components/trace2/components/_shared/BreakdownToolTip.tsx@@ -0,0 +1,201 @@+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@/src/components/ui/tooltip";+import { useState } from "react";+import Decimal from "decimal.js";+import { getMaxDecimals } from "@/src/features/models/utils";++interface Details {+ [key: string]: number | undefined;+}++interface BreakdownTooltipProps {+ details: Details | Details[];+ children: React.ReactNode;+ isCost?: boolean;+}++export const BreakdownTooltip = ({+ details,+ children,+ isCost = false,+}: BreakdownTooltipProps) => {+ const [isOpen, setIsOpen] = useState(false);++ // Aggregate details if array is provided+ const aggregatedDetails = Array.isArray(details)+ ? details.reduce<Details>((acc, curr) => {+ Object.entries(curr).forEach(([key, value]) => {+ acc[key] = new Decimal(acc[key] || 0)+ .plus(new Decimal(value || 0))+ .toNumber();+ });+ return acc;+ }, {})+ : details;++ const formatValueWithPadding = (value: number, maxDecimals: number) => {+ return !value+ ? "0"+ : isCost+ ? `$${value.toFixed(maxDecimals)}`+ : value.toLocaleString();+ };++ const maxDecimals = isCost+ ? Math.max(+ ...Object.values(aggregatedDetails).map((v) => getMaxDecimals(v)),+ )+ : 0;++ return (+ <TooltipProvider>+ <Tooltip open={isOpen} onOpenChange={setIsOpen}>+ <TooltipTrigger+ className="flex cursor-pointer"+ onClick={() => setIsOpen(!isOpen)}+ >+ {children}+ </TooltipTrigger>+ <TooltipContent className="w-64 p-4">+ <div className="flex flex-col gap-4">+ <div className="flex flex-col gap-1">+ <span className="font-semibold">+ {isCost ? "Cost breakdown" : "Usage breakdown"}+ </span>+ {Array.isArray(details) && details.length > 0 && (+ <span className="text-xs italic text-muted-foreground">+ Aggregate across {details.length}{" "}+ {details.length === 1 ? "generation" : "generations"}+ </span>+ )}+ </div>++ {/* Input Section */}+ <Section+ title={isCost ? "Input cost" : "Input usage"}+ details={aggregatedDetails}+ filterFn={(key) => key.includes("input")}+ formatValue={(v) => formatValueWithPadding(v, maxDecimals)}+ />++ {/* Output Section */}+ <Section+ title={isCost ? "Output cost" : "Output usage"}+ details={aggregatedDetails}+ filterFn={(key) => key.includes("output")}+ formatValue={(v) => formatValueWithPadding(v, maxDecimals)}+ />++ {/* Other Section */}+ <OtherSection+ details={aggregatedDetails}+ isCost={isCost}+ formatValue={(v) => formatValueWithPadding(v, maxDecimals)}+ />++ {/* Total */}+ <div className="flex justify-between border-b-4 border-t border-double py-1">+ <span className="text-xs font-semibold">+ {isCost ? "Total cost" : "Total usage"}+ </span>+ <span className="font-mono text-xs font-semibold">+ {formatValueWithPadding(+ aggregatedDetails.total ?? 0,+ maxDecimals,+ )}+ </span>+ </div>+ </div>+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ );+};++interface SectionProps {+ title: string;+ details: Details;+ filterFn: (key: string) => boolean;+ formatValue: (value: number) => string;+}++const Section = ({ title, details, filterFn, formatValue }: SectionProps) => {+ const filteredEntries = Object.entries(details)+ .filter(([key]) => filterFn(key))+ .sort(([, a], [, b]) => (b ?? 0) - (a ?? 0));++ const sectionTotal = filteredEntries.reduce(+ (sum, [_, value]) =>+ new Decimal(sum).plus(new Decimal(value ?? 0)).toNumber(),+ 0,+ );++ return (+ <div className="flex flex-col gap-2">+ <div className="flex justify-between border-b pb-1">+ <span className="text-xs font-semibold">{title}</span>+ <span className="text-right font-mono text-xs font-semibold">+ {formatValue(sectionTotal)}+ </span>+ </div>+ {filteredEntries.map(([key, value]) => (+ <div+ key={key}+ className="flex justify-between text-xs text-muted-foreground"+ >+ <span className="mr-4">{key}</span>+ <span className="font-mono">{formatValue(value ?? 0)}</span>+ </div>+ ))}+ </div>+ );+};++interface OtherSectionProps {+ details: Details;+ isCost: boolean;+ formatValue: (value: number) => string;+}++const OtherSection = ({ details, isCost, formatValue }: OtherSectionProps) => {+ const otherEntries = Object.entries(details)+ .filter(+ ([key]) =>+ !key.includes("input") && !key.includes("output") && key !== "total",+ )+ .sort(([, a], [, b]) => (b ?? 0) - (a ?? 0));++ if (otherEntries.length === 0) return null;++ const otherTotal = otherEntries.reduce((acc, val) => {+ if (typeof val[1] !== "number") return acc;++ return acc + (val[1] ?? 0);+ }, 0);++ return (+ <div className="flex flex-col gap-2">+ <div className="flex justify-between border-b pb-2">+ <span className="text-xs font-medium">+ {isCost ? "Other cost" : "Other usage"}+ </span>+ <span className="text-right font-mono text-xs font-medium">+ {formatValue(otherTotal)}+ </span>+ </div>+ {otherEntries.map(([key, value]) => (+ <div+ key={key}+ className="flex justify-between text-xs text-muted-foreground"+ >+ <span className="mr-4">{key}</span>+ <span className="font-mono">{formatValue(value ?? 0)}</span>+ </div>+ ))}+ </div>+ );+};diff --git a/web/src/components/trace2/components/_shared/CopyIdsPopover.tsx b/web/src/components/trace2/components/_shared/CopyIdsPopover.tsxnew file mode 100644index 0000000000..a82b7a1a00--- /dev/null+++ b/web/src/components/trace2/components/_shared/CopyIdsPopover.tsx@@ -0,0 +1,102 @@+import { Button } from "@/src/components/ui/button";+import { CopyIcon, CheckIcon } from "lucide-react";+import { useState } from "react";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/src/components/ui/popover";+import { cn } from "@/src/utils/tailwind";+import { copyTextToClipboard } from "@/src/utils/clipboard";++interface IdItem {+ name: string;+ id: string;+}++export const CopyIdsPopover = ({+ idItems,+ className,+}: {+ idItems: IdItem[];+ className?: string;+}) => {+ const [copiedId, setCopiedId] = useState<string | null>(null);++ const handleCopy = (textToCopy: string) => {+ copyTextToClipboard(textToCopy);+ setCopiedId(textToCopy);+ setTimeout(() => setCopiedId(null), 1500);+ };++ // If only one idItem provided, use simple button with only one ID+ if (idItems.length === 1) {+ return (+ <Button+ variant="ghost"+ title="Copy ID"+ className={cn("h-fit p-1", className)}+ onClick={() => handleCopy(idItems[0].id)}+ >+ {copiedId === idItems[0].id ? (+ <CheckIcon className="h-3 w-3 text-muted-green" />+ ) : (+ <CopyIcon className="h-3 w-3" />+ )}+ <span className="ml-1 text-xs">ID</span>+ </Button>+ );+ }++ return (+ <Popover>+ <PopoverTrigger asChild>+ <Button+ variant="ghost"+ title="Copy ID"+ className={cn("h-fit px-1", className)}+ >+ <CopyIcon className="h-3 w-3" />+ <span className="ml-1 text-xs">ID</span>+ </Button>+ </PopoverTrigger>+ <PopoverContent+ className="max-h-[50vh] w-auto min-w-[280px] overflow-y-auto p-1"+ align="start"+ >+ <div className="flex flex-col gap-0.5">+ {idItems.map((item) => (+ <div+ key={item.id}+ className="group flex items-center justify-between gap-2 rounded-sm px-2 py-1.5 transition-colors hover:bg-muted/50"+ >+ <div className="flex min-w-0 flex-col gap-0.5">+ <span className="text-xs font-medium text-muted-foreground">+ {item.name}+ </span>+ <span+ className="max-w-[220px] truncate font-mono text-xs"+ title={item.id}+ >+ {item.id}+ </span>+ </div>+ <Button+ variant="ghost"+ size="icon"+ className="h-6 w-6 shrink-0 opacity-70 transition-opacity group-hover:opacity-100"+ onClick={() => handleCopy(item.id)}+ >+ {copiedId === item.id ? (+ <CheckIcon className="h-3 w-3 text-muted-green" />+ ) : (+ <CopyIcon className="h-3 w-3" />+ )}+ </Button>+ </div>+ ))}+ </div>+ </PopoverContent>+ </Popover>+ );+};diff --git a/web/src/components/trace2/components/_shared/VirtualizedList.tsx b/web/src/components/trace2/components/_shared/VirtualizedList.tsxnew file mode 100644index 0000000000..2d5f9d8647--- /dev/null+++ b/web/src/components/trace2/components/_shared/VirtualizedList.tsx@@ -0,0 +1,85 @@+/**+ * VirtualizedList - Generic virtualized list component+ *+ * Simpler than VirtualizedTree - no tree structure, just flat list virtualization.+ * Uses @tanstack/react-virtual for efficient rendering of large lists.+ */++import { useVirtualizer } from "@tanstack/react-virtual";+import { useRef, type ReactNode } from "react";++interface VirtualizedListProps<T> {+ items: T[];+ renderItem: (params: {+ item: T;+ index: number;+ isSelected: boolean;+ onSelect: () => void;+ }) => ReactNode;+ selectedItemId?: string | null;+ onSelectItem: (id: string) => void;+ getItemId: (item: T) => string;+ estimatedItemSize?: number;+ overscan?: number;+}++export function VirtualizedList<T>({+ items,+ renderItem,+ selectedItemId,+ onSelectItem,+ getItemId,+ estimatedItemSize = 48,+ overscan = 500,+}: VirtualizedListProps<T>) {+ const parentRef = useRef<HTMLDivElement>(null);++ const virtualizer = useVirtualizer({+ count: items.length,+ getScrollElement: () => parentRef.current,+ estimateSize: () => estimatedItemSize,+ overscan,+ });++ const virtualItems = virtualizer.getVirtualItems();++ return (+ <div ref={parentRef} className="h-full overflow-auto">+ <div+ style={{+ height: `${virtualizer.getTotalSize()}px`,+ width: "100%",+ position: "relative",+ }}+ >+ {virtualItems.map((virtualRow) => {+ const item = items[virtualRow.index];+ const itemId = getItemId(item);+ const isSelected = selectedItemId === itemId;++ return (+ <div+ key={itemId}+ data-index={virtualRow.index}+ ref={virtualizer.measureElement}+ style={{+ position: "absolute",+ top: 0,+ left: 0,+ width: "100%",+ transform: `translateY(${virtualRow.start}px)`,+ }}+ >+ {renderItem({+ item,+ index: virtualRow.index,+ isSelected,+ onSelect: () => onSelectItem(itemId),+ })}+ </div>+ );+ })}+ </div>+ </div>+ );+}diff --git a/web/src/components/trace2/components/_shared/VirtualizedTree.tsx b/web/src/components/trace2/components/_shared/VirtualizedTree.tsxnew file mode 100644index 0000000000..24809afe89--- /dev/null+++ b/web/src/components/trace2/components/_shared/VirtualizedTree.tsx@@ -0,0 +1,140 @@+/**+ * Generic virtualized tree component using @tanstack/react-virtual.+ *+ * Renders large trees efficiently with dynamic row heights.+ * Uses render prop pattern for node customization.+ */++import { useRef, useLayoutEffect, useMemo, type ReactNode } from "react";+import { useVirtualizer } from "@tanstack/react-virtual";+import { flattenTree } from "./tree-flattening";+import { cn } from "@/src/utils/tailwind";+import { type TreeNodeMetadata } from "./VirtualizedTreeNodeWrapper";++interface VirtualizedTreeProps<T extends { id: string; children: T[] }> {+ tree: T;+ collapsedNodes: Set<string>;+ selectedNodeId: string | null;+ renderNode: (params: {+ node: T;+ treeMetadata: TreeNodeMetadata;+ isSelected: boolean;+ isCollapsed: boolean;+ onToggleCollapse: () => void;+ onSelect: () => void;+ }) => ReactNode;+ onToggleCollapse: (nodeId: string) => void;+ onSelectNode: (nodeId: string | null) => void;+ estimateSize?: (node: T, index: number) => number;+ overscan?: number;+ defaultRowHeight?: number;+ className?: string;+}++export function VirtualizedTree<T extends { id: string; children: T[] }>({+ tree,+ collapsedNodes,+ selectedNodeId,+ renderNode,+ onToggleCollapse,+ onSelectNode,+ estimateSize,+ overscan = 500,+ defaultRowHeight = 37,+ className,+}: VirtualizedTreeProps<T>) {+ const parentRef = useRef<HTMLDivElement>(null);++ const flattenedItems = useMemo(+ () => flattenTree(tree, collapsedNodes, 0, [], true),+ [tree, collapsedNodes],+ );++ const defaultEstimateSize = () => defaultRowHeight;++ const rowVirtualizer = useVirtualizer({+ count: flattenedItems.length,+ getScrollElement: () => parentRef.current,+ estimateSize: estimateSize+ ? (index) => estimateSize(flattenedItems[index]!.node, index)+ : defaultEstimateSize,+ overscan,+ measureElement:+ typeof window !== "undefined"+ ? (element) => element.getBoundingClientRect().height+ : undefined,+ });++ // Auto-scroll to selected node on initial load (URL-based navigation only)+ const initialNodeIdRef = useRef(selectedNodeId);+ const hasScrolledRef = useRef(false);++ useLayoutEffect(() => {+ if (+ selectedNodeId &&+ !hasScrolledRef.current &&+ selectedNodeId === initialNodeIdRef.current+ ) {+ const index = flattenedItems.findIndex(+ (item) => item.node.id === selectedNodeId,+ );++ if (index !== -1) {+ // Use behavior: "auto" for instant scroll on initial load to prevent+ // visible scroll animation after page render. The synchronous scroll+ // completes within useLayoutEffect, before browser paint.+ rowVirtualizer.scrollToIndex(index, {+ align: "center",+ behavior: "auto",+ });+ hasScrolledRef.current = true;+ }+ }+ }, [selectedNodeId, flattenedItems, rowVirtualizer]);++ return (+ <div ref={parentRef} className={cn("h-full overflow-y-auto", className)}>+ <div+ style={{+ height: `${rowVirtualizer.getTotalSize()}px`,+ width: "100%",+ position: "relative",+ }}+ >+ {rowVirtualizer.getVirtualItems().map((virtualRow) => {+ const item = flattenedItems[virtualRow.index]!;+ const isSelected = item.node.id === selectedNodeId;+ const isCollapsed = collapsedNodes.has(item.node.id);++ return (+ <div+ key={item.node.id}+ data-index={virtualRow.index}+ ref={rowVirtualizer.measureElement}+ style={{+ position: "absolute",+ top: 0,+ left: 0,+ width: "100%",+ transform: `translateY(${virtualRow.start}px)`,+ }}+ >+ {renderNode({+ node: item.node,+ treeMetadata: {+ depth: item.depth,+ treeLines: item.treeLines,+ isLastSibling: item.isLastSibling,+ },+ isSelected,+ isCollapsed,+ onToggleCollapse: () => onToggleCollapse(item.node.id),+ onSelect: () => onSelectNode(item.node.id),+ })}+ </div>+ );+ })}+ </div>+ </div>+ );+}diff --git a/web/src/components/trace2/components/_shared/VirtualizedTreeNodeWrapper.tsx b/web/src/components/trace2/components/_shared/VirtualizedTreeNodeWrapper.tsxnew file mode 100644index 0000000000..50edcc76da--- /dev/null+++ b/web/src/components/trace2/components/_shared/VirtualizedTreeNodeWrapper.tsx@@ -0,0 +1,158 @@+/**+ * TreeNodeWrapper - Generic tree structure renderer.+ *+ * Responsibilities:+ * - Render tree visual structure (indents, connector lines)+ * - Render collapse/expand button+ * - Handle selection state and click events+ *+ * Does NOT know about:+ * - Domain-specific content (that's passed as children)+ * - What kind of data is being displayed+ *+ * This component wraps arbitrary content, making it reusable for any tree view.+ */++import { type ReactNode } from "react";+import { Button } from "@/src/components/ui/button";+import { ItemBadge, type LangfuseItemType } from "@/src/components/ItemBadge";+import { ChevronRight } from "lucide-react";+import { cn } from "@/src/utils/tailwind";++export interface TreeNodeMetadata {+ depth: number;+ treeLines: boolean[];+ isLastSibling: boolean;+}++interface TreeNodeWrapperProps {+ // Tree structure data+ metadata: TreeNodeMetadata;+ nodeType: LangfuseItemType; // For the icon badge (e.g., "SPAN", "GENERATION", "TRACE")+ hasChildren: boolean;+ isCollapsed: boolean;+ onToggleCollapse: () => void;++ // Selection/interaction+ isSelected: boolean;+ onSelect: () => void;++ // Content to render (fully decoupled from tree structure)+ children: ReactNode;++ // Optional customization+ className?: string;+}++export function VirtualizedTreeNodeWrapper({+ metadata,+ nodeType,+ hasChildren,+ isCollapsed,+ onToggleCollapse,+ isSelected,+ onSelect,+ children,+ className,+}: TreeNodeWrapperProps) {+ const { depth, treeLines, isLastSibling } = metadata;++ return (+ <div+ className={cn(+ "relative flex w-full cursor-pointer px-0",+ isSelected ? "bg-muted" : "hover:bg-muted/50",+ className,+ )}+ style={{+ paddingTop: 0,+ paddingBottom: 0,+ }}+ onClick={(e) => {+ if (!e.currentTarget?.closest("[data-expand-button]")) {+ onSelect();+ }+ }}+ >+ <div className="flex w-full pl-2">+ {/* 1. Indents: ancestor level indicators */}+ {depth > 0 && (+ <div className="flex flex-shrink-0">+ {Array.from({ length: depth - 1 }, (_, i) => (+ <div key={i} className="relative w-5">+ {treeLines[i] && (+ <div className="absolute bottom-0 left-3 top-0 w-px bg-border" />+ )}+ </div>+ ))}+ </div>+ )}++ {/* 2. Current element bars: up/down/horizontal connectors */}+ {depth > 0 && (+ <div className="relative w-5 flex-shrink-0">+ <>+ {/* Vertical bar connecting upwards */}+ <div+ className={cn(+ "absolute left-3 top-0 w-px bg-border",+ isLastSibling ? "h-3" : "bottom-3",+ )}+ />+ {/* Vertical bar connecting downwards if not last sibling */}+ {!isLastSibling && (+ <div className="absolute bottom-0 left-3 top-3 w-px bg-border" />+ )}+ {/* Horizontal bar connecting to icon */}+ <div className="absolute left-3 top-3 h-px w-2 bg-border" />+ </>+ </div>+ )}++ {/* 3. Icon + child connector: fixed width container */}+ <div className="relative flex w-6 flex-shrink-0 flex-col py-1.5">+ <div className="relative z-10 flex h-4 items-center justify-center">+ <ItemBadge type={nodeType} isSmall className="!size-3" />+ </div>+ {/* Vertical bar downwards if there are expanded children */}+ {hasChildren && !isCollapsed && (+ <div className="absolute bottom-0 left-1/2 top-3 w-px bg-border" />+ )}+ {/* Root node downward connector */}+ {depth === 0 && hasChildren && !isCollapsed && (+ <div className="absolute bottom-0 left-1/2 top-3 w-px bg-border" />+ )}+ </div>++ {/* 4. Content area (passed as children - completely decoupled) */}+ <div className="flex min-w-0 flex-1">{children}</div>++ {/* 5. Expand/Collapse button */}+ {hasChildren && (+ <div className="flex items-center justify-end py-1 pr-1">+ <Button+ aria-expanded={!isCollapsed}+ data-expand-button+ size="icon"+ variant="ghost"+ onClick={(ev) => {+ ev.stopPropagation();+ onToggleCollapse();+ }}+ className="h-6 w-6 flex-shrink-0 hover:bg-primary/10"+ >+ <span+ className={cn(+ "inline-block h-4 w-4 transform transition-transform duration-200 ease-in-out",+ isCollapsed ? "rotate-0" : "rotate-90",+ )}+ >+ <ChevronRight className="h-4 w-4" />+ </span>+ </Button>+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/web/src/components/trace2/components/_shared/tree-flattening.clienttest.ts b/web/src/components/trace2/components/_shared/tree-flattening.clienttest.tsnew file mode 100644index 0000000000..a0383ed1bf--- /dev/null+++ b/web/src/components/trace2/components/_shared/tree-flattening.clienttest.ts@@ -0,0 +1,785 @@+/**+ * Tests for tree-flattening utilities.+ *+ * Tests the flattenTree function which converts hierarchical tree structures+ * into flat lists for virtualized rendering.+ *+ * Run with: pnpm test-client --testPathPattern="tree-flattening"+ */++import { flattenTree } from "./tree-flattening";++// Test node type+interface TestNode {+ id: string;+ name: string;+ children: TestNode[];+ startTime?: Date;+}++describe("flattenTree", () => {+ describe("basic flattening", () => {+ it("should flatten single node with no children", () => {+ const tree: TestNode = {+ id: "root",+ name: "Root",+ children: [],+ };++ const result = flattenTree(tree, new Set());++ expect(result).toEqual([+ {+ node: tree,+ depth: 0,+ treeLines: [],+ isLastSibling: true,+ },+ ]);+ });++ it("should flatten node with single child", () => {+ const child: TestNode = { id: "child", name: "Child", children: [] };+ const tree: TestNode = {+ id: "root",+ name: "Root",+ children: [child],+ };++ const result = flattenTree(tree, new Set());++ expect(result).toHaveLength(2);+ expect(result[0]).toEqual({+ node: tree,+ depth: 0,+ treeLines: [],+ isLastSibling: true,+ });+ expect(result[1]).toEqual({+ node: child,+ depth: 1,+ treeLines: [false], // Last sibling gets false in treeLines+ isLastSibling: true,+ });+ });++ it("should flatten node with multiple children", () => {+ const child1: TestNode = { id: "child1", name: "Child 1", children: [] };+ const child2: TestNode = { id: "child2", name: "Child 2", children: [] };+ const child3: TestNode = { id: "child3", name: "Child 3", children: [] };+ const tree: TestNode = {+ id: "root",+ name: "Root",+ children: [child1, child2, child3],+ };++ const result = flattenTree(tree, new Set());++ expect(result).toHaveLength(4);++ // Root+ expect(result[0]?.node.id).toBe("root");+ expect(result[0]?.depth).toBe(0);+ expect(result[0]?.isLastSibling).toBe(true);++ // First child - not last sibling+ expect(result[1]?.node.id).toBe("child1");+ expect(result[1]?.depth).toBe(1);+ expect(result[1]?.isLastSibling).toBe(false);+ expect(result[1]?.treeLines).toEqual([true]); // Has line for siblings below++ // Second child - not last sibling+ expect(result[2]?.node.id).toBe("child2");+ expect(result[2]?.depth).toBe(1);+ expect(result[2]?.isLastSibling).toBe(false);+ expect(result[2]?.treeLines).toEqual([true]); // Has line for siblings below++ // Third child - last sibling+ expect(result[3]?.node.id).toBe("child3");+ expect(result[3]?.depth).toBe(1);+ expect(result[3]?.isLastSibling).toBe(true);+ expect(result[3]?.treeLines).toEqual([false]); // Last sibling gets false+ });++ it("should flatten deeply nested tree", () => {+ const grandchild: TestNode = {+ id: "grandchild",+ name: "Grandchild",+ children: [],+ };+ const child: TestNode = {+ id: "child",+ name: "Child",+ children: [grandchild],+ };+ const tree: TestNode = {+ id: "root",+ name: "Root",+ children: [child],+ };++ const result = flattenTree(tree, new Set());++ expect(result).toHaveLength(3);++ // Root+ expect(result[0]?.node.id).toBe("root");+ expect(result[0]?.depth).toBe(0);++ // Child+ expect(result[1]?.node.id).toBe("child");+ expect(result[1]?.depth).toBe(1);++ // Grandchild+ expect(result[2]?.node.id).toBe("grandchild");+ expect(result[2]?.depth).toBe(2);+ });+ });++ describe("collapsed nodes", () => {+ it("should not include children of collapsed node", () => {+ const child1: TestNode = { id: "child1", name: "Child 1", children: [] };+ const child2: TestNode = { id: "child2", name: "Child 2", children: [] };+ const tree: TestNode = {+ id: "root",+ name: "Root",+ children: [child1, child2],+ };++ const collapsed = new Set(["root"]);+ const result = flattenTree(tree, collapsed);++ // Only root should be in the result, children hidden+ expect(result).toHaveLength(1);+ expect(result[0]?.node.id).toBe("root");+ });++ it("should not include grandchildren of collapsed node", () => {+ const grandchild: TestNode = {+ id: "grandchild",+ name: "Grandchild",+ children: [],+ };+ const child: TestNode = {+ id: "child",+ name: "Child",+ children: [grandchild],+ };+ const tree: TestNode = {+ id: "root",+ name: "Root",+ children: [child],+ };++ const collapsed = new Set(["child"]);+ const result = flattenTree(tree, collapsed);++ // Root and child, but not grandchild+ expect(result).toHaveLength(2);+ expect(result[0]?.node.id).toBe("root");+ expect(result[1]?.node.id).toBe("child");+ });++ it("should handle multiple collapsed nodes", () => {+ const grandchild1: TestNode = {+ id: "grandchild1",+ name: "Grandchild 1",+ children: [],+ };+ const grandchild2: TestNode = {+ id: "grandchild2",+ name: "Grandchild 2",+ children: [],+ };+ const child1: TestNode = {+ id: "child1",+ name: "Child 1",+ children: [grandchild1],+ };+ const child2: TestNode = {+ id: "child2",+ name: "Child 2",+ children: [grandchild2],+ };+ const tree: TestNode = {+ id: "root",+ name: "Root",+ children: [child1, child2],+ };++ const collapsed = new Set(["child1", "child2"]);+ const result = flattenTree(tree, collapsed);++ // Root and two children, no grandchildren+ expect(result).toHaveLength(3);+ expect(result[0]?.node.id).toBe("root");+ expect(result[1]?.node.id).toBe("child1");+ expect(result[2]?.node.id).toBe("child2");+ });+ });++ describe("tree lines calculation", () => {+ it("should calculate tree lines for complex structure", () => {+ // root+ // / \+ // child1 child2 (last)+ // |+ // grandchild (last)++ const grandchild: TestNode = {+ id: "grandchild",+ name: "Grandchild",+ children: [],+ };+ const child1: TestNode = {+ id: "child1",+ name: "Child 1",+ children: [grandchild],+ };+ const child2: TestNode = {+ id: "child2",+ name: "Child 2",+ children: [],+ };+ const tree: TestNode = {+ id: "root",+ name: "Root",+ children: [child1, child2],+ };++ const result = flattenTree(tree, new Set());++ // child1 should have tree line (not last sibling)+ const child1Result = result.find((n) => n.node.id === "child1");+ expect(child1Result?.treeLines).toEqual([true]);++ // child2 should have false tree line (last sibling)+ const child2Result = result.find((n) => n.node.id === "child2");+ expect(child2Result?.treeLines).toEqual([false]);++ // grandchild should have tree line at depth 1 (parent is not last)+ // and is itself last at depth 2+ const grandchildResult = result.find((n) => n.node.id === "grandchild");+ expect(grandchildResult?.treeLines).toEqual([true, false]);+ expect(grandchildResult?.isLastSibling).toBe(true);+ });++ it("should calculate tree lines for deep nesting with siblings", () => {+ // root+ // / \+ // child1 child2 (last)+ // |+ // gc1+ // |+ // ggc1 (last)++ const ggc1: TestNode = {+ id: "ggc1",+ name: "Great-grandchild 1",+ children: [],+ };+ const gc1: TestNode = {+ id: "gc1",+ name: "Grandchild 1",+ children: [ggc1],+ };+ const child1: TestNode = {+ id: "child1",+ name: "Child 1",+ children: [gc1],+ };+ const child2: TestNode = {+ id: "child2",+ name: "Child 2",+ children: [],+ };+ const tree: TestNode = {+ id: "root",+ name: "Root",+ children: [child1, child2],+ };++ const result = flattenTree(tree, new Set());++ // ggc1 should have tree lines showing:+ // - depth 0: true (child1 is not last at level 1)+ // - depth 1: false (gc1 IS last at level 2)+ // - depth 2: false (ggc1 IS last at level 3)+ const ggc1Result = result.find((n) => n.node.id === "ggc1");+ expect(ggc1Result?.depth).toBe(3);+ expect(ggc1Result?.treeLines).toEqual([true, false, false]); // Mixed lines based on ancestry+ });+ });++ describe("sorting by startTime", () => {+ it("should sort children by startTime", () => {+ const child1: TestNode = {+ id: "child1",+ name: "Child 1",+ children: [],+ startTime: new Date("2024-01-01T10:00:00Z"),+ };+ const child2: TestNode = {+ id: "child2",+ name: "Child 2",+ children: [],+ startTime: new Date("2024-01-01T09:00:00Z"), // Earlier+ };+ const child3: TestNode = {+ id: "child3",+ name: "Child 3",+ children: [],+ startTime: new Date("2024-01-01T11:00:00Z"), // Latest+ };+ const tree: TestNode = {+ id: "root",+ name: "Root",+ children: [child1, child2, child3], // Unsorted+ };++ const result = flattenTree(tree, new Set());++ // Should be sorted by startTime+ expect(result[1]?.node.id).toBe("child2"); // 09:00+ expect(result[2]?.node.id).toBe("child1"); // 10:00+ expect(result[3]?.node.id).toBe("child3"); // 11:00+ });++ it("should handle nodes without startTime", () => {+ const child1: TestNode = {+ id: "child1",+ name: "Child 1",+ children: [],+ };+ const child2: TestNode = {+ id: "child2",+ name: "Child 2",+ children: [],+ startTime: new Date("2024-01-01T10:00:00Z"),+ };+ const tree: TestNode = {+ id: "root",+ name: "Root",+ children: [child1, child2],+ };++ const result = flattenTree(tree, new Set());++ // Should not throw, nodes without startTime get 0+ expect(result).toHaveLength(3);+ expect(result[1]?.node.id).toBe("child1"); // No startTime (0)+ expect(result[2]?.node.id).toBe("child2"); // Has startTime+ });+ });++ describe("edge cases", () => {+ it("should handle empty children array", () => {+ const tree: TestNode = {+ id: "root",+ name: "Root",+ children: [],+ };++ const result = flattenTree(tree, new Set());++ expect(result).toHaveLength(1);+ expect(result[0]?.node.id).toBe("root");+ });++ it("should handle very deep nesting", () => {+ // Create a chain of 10 nodes+ let current: TestNode = {+ id: "node9",+ name: "Node 9",+ children: [],+ };++ for (let i = 8; i >= 0; i--) {+ current = {+ id: `node${i}`,+ name: `Node ${i}`,+ children: [current],+ };+ }++ const result = flattenTree(current, new Set());++ expect(result).toHaveLength(10);+ expect(result[0]?.depth).toBe(0);+ expect(result[9]?.depth).toBe(9);+ });++ it("should preserve original tree structure (immutability)", () => {+ const child: TestNode = { id: "child", name: "Child", children: [] };+ const tree: TestNode = {+ id: "root",+ name: "Root",+ children: [child],+ };++ const originalChildren = tree.children;+ flattenTree(tree, new Set());++ // Original tree should not be modified+ expect(tree.children).toBe(originalChildren);+ expect(tree.children).toHaveLength(1);+ });+ });++ describe("complex real-world scenarios", () => {+ it("should handle mixed collapsed and expanded nodes", () => {+ // root+ // / \+ // child1 child2+ // / \ |+ // gc1 gc2 gc3+ //+ // Collapse child1, keep child2 expanded++ const gc1: TestNode = { id: "gc1", name: "GC1", children: [] };+ const gc2: TestNode = { id: "gc2", name: "GC2", children: [] };+ const gc3: TestNode = { id: "gc3", name: "GC3", children: [] };+ const child1: TestNode = {+ id: "child1",+ name: "Child 1",+ children: [gc1, gc2],+ };+ const child2: TestNode = {+ id: "child2",+ name: "Child 2",+ children: [gc3],+ };+ const tree: TestNode = {+ id: "root",+ name: "Root",+ children: [child1, child2],+ };++ const collapsed = new Set(["child1"]);+ const result = flattenTree(tree, collapsed);++ // root, child1 (collapsed), child2, gc3+ expect(result).toHaveLength(4);+ expect(result.map((n) => n.node.id)).toEqual([+ "root",+ "child1",+ "child2",+ "gc3",+ ]);+ });++ it("should handle wide tree (many siblings)", () => {+ const children = Array.from({ length: 100 }, (_, i) => ({+ id: `child${i}`,+ name: `Child ${i}`,+ children: [],+ }));++ const tree: TestNode = {+ id: "root",+ name: "Root",+ children,+ };++ const result = flattenTree(tree, new Set());++ expect(result).toHaveLength(101); // root + 100 children++ // First child should not be last+ expect(result[1]?.isLastSibling).toBe(false);+ expect(result[1]?.treeLines).toEqual([true]);++ // Last child should be last+ expect(result[100]?.isLastSibling).toBe(true);+ expect(result[100]?.treeLines).toEqual([false]); // Last sibling gets false+ });+ });++ describe("Performance Tests", () => {+ // Helper to generate tree structures at scale+ const generateTree = (+ count: number,+ structure: "flat" | "deep" | "balanced" | "realistic",+ ): TestNode => {+ if (structure === "flat") {+ // All nodes at root level+ const children: TestNode[] = [];+ for (let i = 0; i < count; i++) {+ children.push({+ id: `node-${i}`,+ name: `Node ${i}`,+ children: [],+ startTime: new Date(`2024-01-01T00:00:${i % 60}.${i % 1000}Z`),+ });+ }+ return {+ id: "root",+ name: "Root",+ children,+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ };+ } else if (structure === "deep") {+ // Single linear chain (worst case)+ let current: TestNode = {+ id: `node-${count - 1}`,+ name: `Node ${count - 1}`,+ children: [],+ startTime: new Date(+ `2024-01-01T00:00:${(count - 1) % 60}.${(count - 1) % 1000}Z`,+ ),+ };++ for (let i = count - 2; i >= 0; i--) {+ current = {+ id: `node-${i}`,+ name: `Node ${i}`,+ children: [current],+ startTime: new Date(`2024-01-01T00:00:${i % 60}.${i % 1000}Z`),+ };+ }++ return current;+ } else if (structure === "balanced") {+ // Binary tree structure+ const nodes: TestNode[] = [];++ // Create all nodes first+ for (let i = 0; i < count; i++) {+ nodes.push({+ id: `node-${i}`,+ name: `Node ${i}`,+ children: [],+ startTime: new Date(`2024-01-01T00:00:${i % 60}.${i % 1000}Z`),+ });+ }++ // Build tree structure (parent at i, children at 2i+1 and 2i+2)+ for (let i = 0; i < count; i++) {+ const leftChildIndex = 2 * i + 1;+ const rightChildIndex = 2 * i + 2;++ if (leftChildIndex < count) {+ nodes[i].children.push(nodes[leftChildIndex]);+ }+ if (rightChildIndex < count) {+ nodes[i].children.push(nodes[rightChildIndex]);+ }+ }++ return nodes[0];+ } else {+ // Realistic: ~20% intermediate nodes, ~80% leaf nodes, max depth ~5+ const intermediateNodeCount = Math.floor(count * 0.2);+ const leafNodeCount = count - intermediateNodeCount;++ const allNodes: TestNode[] = [];++ // Create all nodes first+ for (let i = 0; i < count; i++) {+ allNodes.push({+ id: `node-${i}`,+ name: `Node ${i}`,+ children: [],+ startTime: new Date(`2024-01-01T00:00:${i % 60}.${i % 1000}Z`),+ });+ }++ // Build realistic hierarchy+ // Root nodes (10% of intermediate nodes)+ const rootCount = Math.max(1, Math.floor(intermediateNodeCount * 0.1));+ const roots: TestNode[] = allNodes.slice(0, rootCount);++ // Remaining intermediate nodes attach to previous nodes+ for (let i = rootCount; i < intermediateNodeCount; i++) {+ const parentIndex = Math.floor(Math.random() * i);+ allNodes[parentIndex].children.push(allNodes[i]);+ }++ // Leaf nodes attach to any intermediate node+ for (let i = 0; i < leafNodeCount; i++) {+ const nodeIndex = intermediateNodeCount + i;+ const parentIndex = Math.floor(Math.random() * intermediateNodeCount);+ allNodes[parentIndex].children.push(allNodes[nodeIndex]);+ }++ // Create root with all root-level nodes as children+ return {+ id: "root",+ name: "Root",+ children: roots,+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ };+ }+ };++ const runPerformanceTest = (+ scale: number,+ structure: "flat" | "deep" | "balanced" | "realistic",+ collapsedPercent: number,+ threshold: number,+ ) => {+ const tree = generateTree(scale, structure);++ // Collapse a percentage of nodes+ const collapsedNodes = new Set<string>();+ if (collapsedPercent > 0) {+ // Collect all node IDs via flattening first+ const allFlattened = flattenTree(tree, new Set());+ const collapseCount = Math.floor(+ allFlattened.length * (collapsedPercent / 100),+ );+ for (let i = 0; i < collapseCount; i++) {+ const nodeIndex = Math.floor(Math.random() * allFlattened.length);+ collapsedNodes.add(allFlattened[nodeIndex].node.id);+ }+ }++ const start = Date.now();+ const result = flattenTree(tree, collapsedNodes);+ const duration = Date.now() - start;++ // Verify result is valid+ expect(result.length).toBeGreaterThan(0);+ expect(result[0].node.id).toBeDefined();++ // Log performance metrics+ const collapsedSuffix =+ collapsedPercent > 0 ? `, ${collapsedPercent}% collapsed` : "";+ console.log(+ `${scale.toLocaleString()} nodes (${structure}${collapsedSuffix}): ${duration}ms`,+ );++ // Assert threshold+ expect(duration).toBeLessThan(threshold);++ return duration;+ };++ describe("1k nodes", () => {+ const scale = 1_000;+ const threshold = 100; // 100ms++ it("flattens flat structure", () => {+ runPerformanceTest(scale, "flat", 0, threshold);+ });++ it("flattens deep chain", () => {+ runPerformanceTest(scale, "deep", 0, threshold);+ });++ it("flattens balanced tree", () => {+ runPerformanceTest(scale, "balanced", 0, threshold);+ });++ it("flattens realistic structure", () => {+ runPerformanceTest(scale, "realistic", 0, threshold);+ });++ it("flattens with 30% collapsed nodes", () => {+ runPerformanceTest(scale, "realistic", 30, threshold);+ });+ });++ describe("10k nodes", () => {+ const scale = 10_000;+ const threshold = 750; // 750ms++ it("flattens flat structure", () => {+ runPerformanceTest(scale, "flat", 0, threshold);+ });++ it("flattens deep chain", () => {+ runPerformanceTest(scale, "deep", 0, threshold);+ });++ it("flattens balanced tree", () => {+ runPerformanceTest(scale, "balanced", 0, threshold);+ });++ it("flattens realistic structure", () => {+ runPerformanceTest(scale, "realistic", 0, threshold);+ });++ it("flattens with 30% collapsed nodes", () => {+ runPerformanceTest(scale, "realistic", 30, threshold);+ });+ });++ describe("25k nodes", () => {+ const scale = 25_000;+ const threshold = 2_000; // 2s++ it("flattens flat structure", () => {+ runPerformanceTest(scale, "flat", 0, threshold);+ });++ it("flattens realistic structure", () => {+ runPerformanceTest(scale, "realistic", 0, threshold);+ });++ it("flattens with 30% collapsed nodes", () => {+ runPerformanceTest(scale, "realistic", 30, threshold);+ });+ });++ describe("50k nodes", () => {+ const scale = 50_000;+ const threshold = 5_000; // 5s++ it("flattens flat structure", () => {+ runPerformanceTest(scale, "flat", 0, threshold);+ });++ it("flattens realistic structure", () => {+ runPerformanceTest(scale, "realistic", 0, threshold);+ });++ it("flattens with 30% collapsed nodes", () => {+ runPerformanceTest(scale, "realistic", 30, threshold);+ });+ });++ describe("100k nodes", () => {+ const scale = 100_000;+ const threshold = 15_000; // 15s++ it("flattens flat structure", () => {+ runPerformanceTest(scale, "flat", 0, threshold);+ });++ it("flattens realistic structure", () => {+ runPerformanceTest(scale, "realistic", 0, threshold);+ });++ it("flattens with 30% collapsed nodes", () => {+ runPerformanceTest(scale, "realistic", 30, threshold);+ });+ });++ describe("500k nodes (extreme - manual only)", () => {+ const scale = 500_000;+ const threshold = 60_000; // 60s++ it("flattens realistic structure", () => {+ runPerformanceTest(scale, "realistic", 0, threshold);+ });++ it("flattens with 30% collapsed nodes", () => {+ runPerformanceTest(scale, "realistic", 30, threshold);+ });+ });++ describe("1M nodes (extreme - manual only)", () => {+ const scale = 1_000_000;+ const threshold = 180_000; // 3 minutes++ it("flattens realistic structure", () => {+ runPerformanceTest(scale, "realistic", 0, threshold);+ });++ it("flattens with 30% collapsed nodes", () => {+ runPerformanceTest(scale, "realistic", 30, threshold);+ });+ });+ });+});diff --git a/web/src/components/trace2/components/_shared/tree-flattening.ts b/web/src/components/trace2/components/_shared/tree-flattening.tsnew file mode 100644index 0000000000..e3af8a4d4d--- /dev/null+++ b/web/src/components/trace2/components/_shared/tree-flattening.ts@@ -0,0 +1,88 @@+/**+ * Tree flattening utilities for virtualized rendering.+ *+ * Converts hierarchical tree structure into flat list for virtualization,+ * while tracking depth, tree lines, and sibling relationships for visual rendering.+ */++export interface FlatNode<T> {+ node: T;+ depth: number;+ treeLines: boolean[]; // Which ancestor levels have vertical lines+ isLastSibling: boolean;+}++/**+ * Flattens tree into list for virtualized rendering using iterative approach.+ * Respects collapsed state - collapsed nodes don't include children.+ *+ * Uses an explicit stack instead of recursion to avoid stack overflow+ * with deeply nested trees (10k+ levels).+ *+ * @param node - Root node to flatten+ * @param collapsedNodes - Set of node IDs that are collapsed+ * @param depth - Current depth (0 for root)+ * @param treeLines - Which ancestor levels have vertical lines+ * @param isLastSibling - Whether this node is the last child of its parent+ * @returns Flat list of nodes with rendering metadata+ */+export function flattenTree<T extends { id: string; children: T[] }>(+ node: T,+ collapsedNodes: Set<string>,+ depth = 0,+ treeLines: boolean[] = [],+ isLastSibling = true,+): FlatNode<T>[] {+ const flatList: FlatNode<T>[] = [];++ // Initialize stack with root node+ const stack: Array<{+ node: T;+ depth: number;+ treeLines: boolean[];+ isLastSibling: boolean;+ }> = [{ node, depth, treeLines, isLastSibling }];++ // Process stack (LIFO - depth-first traversal)+ while (stack.length > 0) {+ const current = stack.pop()!;++ // Add current node to result+ flatList.push({+ node: current.node,+ depth: current.depth,+ treeLines: current.treeLines,+ isLastSibling: current.isLastSibling,+ });++ // If node has children and is not collapsed, add children to stack+ if (+ current.node.children.length > 0 &&+ !collapsedNodes.has(current.node.id)+ ) {+ // Sort children by startTime if available (assumes TreeNode structure)+ const sortedChildren = [...current.node.children].sort((a, b) => {+ // Safe type assertion - TreeNode has startTime+ const aStart = (a as any).startTime?.getTime?.() ?? 0;+ const bStart = (b as any).startTime?.getTime?.() ?? 0;+ return aStart - bStart;+ });++ // Push children in REVERSE order to maintain left-to-right DFS traversal+ // (stack is LIFO, so last pushed = first popped)+ 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, !isChildLast], // Add line if not last child+ isLastSibling: isChildLast,+ });+ }+ }+ }++ return flatList;+}diff --git a/web/src/components/trace2/contexts/JsonExpansionContext.tsx b/web/src/components/trace2/contexts/JsonExpansionContext.tsxnew file mode 100644index 0000000000..46237a5ff7--- /dev/null+++ b/web/src/components/trace2/contexts/JsonExpansionContext.tsx@@ -0,0 +1,68 @@+/**+ * JsonExpansionContext - Persists JSON expand/collapse state across observations+ *+ * Purpose:+ * - Store which JSON paths are expanded/collapsed (e.g., "response.data.items": true)+ * - Persist state in sessionStorage (per-tab, clears on tab close)+ * - Share expansion state between observations with similar JSON structure+ *+ * Usage:+ * - Components receive externalExpansionState and onExternalExpansionChange props+ * - When user expands a path, it persists across observation switches+ * - Separate from TraceDataContext to avoid unnecessary re-renders+ */++import { createContext, useContext, useCallback, type ReactNode } from "react";+import useSessionStorage from "@/src/components/useSessionStorage";++type ExpandedState = Record<string, boolean> | boolean;++type JsonExpansionState = {+ input: ExpandedState;+ output: ExpandedState;+ metadata: ExpandedState;+ log: ExpandedState;+};++interface JsonExpansionContextValue {+ expansionState: JsonExpansionState;+ setFieldExpansion: (+ field: keyof JsonExpansionState,+ expansion: ExpandedState,+ ) => void;+}++const JsonExpansionContext = createContext<JsonExpansionContextValue>({+ expansionState: { input: {}, output: {}, metadata: {}, log: {} },+ setFieldExpansion: () => {},+});++export const useJsonExpansion = () => useContext(JsonExpansionContext);++export function JsonExpansionProvider({ children }: { children: ReactNode }) {+ const [expansionState, setExpansionState] =+ useSessionStorage<JsonExpansionState>("trace2-jsonExpansionState", {+ input: {},+ output: {},+ metadata: {},+ log: {},+ });++ const setFieldExpansion = useCallback(+ (field: keyof JsonExpansionState, expansion: ExpandedState) => {+ setExpansionState((prev) => ({+ ...prev,+ [field]: expansion,+ }));+ },+ [setExpansionState],+ );++ return (+ <JsonExpansionContext.Provider+ value={{ expansionState, setFieldExpansion }}+ >+ {children}+ </JsonExpansionContext.Provider>+ );+}diff --git a/web/src/components/trace2/contexts/SearchContext.tsx b/web/src/components/trace2/contexts/SearchContext.tsxnew file mode 100644index 0000000000..aea4883d1a--- /dev/null+++ b/web/src/components/trace2/contexts/SearchContext.tsx@@ -0,0 +1,69 @@+/**+ * SearchContext - Isolated search state management+ *+ * Manages search input and query with debouncing, separate from selection/tree UI state+ * to avoid unnecessary re-renders of unrelated components.+ */++import {+ createContext,+ useContext,+ useState,+ useEffect,+ useCallback,+ type ReactNode,+} from "react";++interface SearchContextValue {+ searchQuery: string;+ searchInputValue: string;+ setSearchInputValue: (value: string) => void;+ setSearchQueryImmediate: (value: string) => void;+}++const SearchContext = createContext<SearchContextValue | null>(null);++interface SearchProviderProps {+ children: ReactNode;+}++export function SearchProvider({ children }: SearchProviderProps) {+ const [searchInputValue, setSearchInputValue] = useState("");+ const [searchQuery, setSearchQuery] = useState("");++ // Debounced update - wait 500ms after user stops typing+ useEffect(() => {+ const timeout = setTimeout(() => {+ setSearchQuery(searchInputValue);+ }, 500);++ return () => clearTimeout(timeout);+ }, [searchInputValue]);++ // Immediate update - for Enter key or programmatic updates+ const setSearchQueryImmediate = useCallback((value: string) => {+ setSearchInputValue(value);+ setSearchQuery(value);+ }, []);++ return (+ <SearchContext.Provider+ value={{+ searchQuery,+ searchInputValue,+ setSearchInputValue,+ setSearchQueryImmediate,+ }}+ >+ {children}+ </SearchContext.Provider>+ );+}++export function useSearch() {+ const context = useContext(SearchContext);+ if (!context) {+ throw new Error("useSearch must be used within SearchProvider");+ }+ return context;+}diff --git a/web/src/components/trace2/contexts/SelectionContext.tsx b/web/src/components/trace2/contexts/SelectionContext.tsxnew file mode 100644index 0000000000..9c531a8833--- /dev/null+++ b/web/src/components/trace2/contexts/SelectionContext.tsx@@ -0,0 +1,137 @@+/**+ * SelectionContext - Manages UI navigation and interaction state.+ *+ * Purpose:+ * - Tracks selected node ID (synced to URL query param)+ * - Manages collapsed/expanded state for tree nodes+ * - Handles search query with debounced input+ *+ * Not responsible for:+ * - Trace data or tree structure - see TraceDataContext+ * - Display preferences - see ViewPreferencesContext+ */++import {+ createContext,+ useContext,+ useState,+ useCallback,+ useMemo,+ type ReactNode,+} from "react";+import { StringParam, useQueryParam } from "use-query-params";+import { useDebounce } from "@/src/hooks/useDebounce";++interface SelectionContextValue {+ selectedNodeId: string | null;+ setSelectedNodeId: (id: string | null) => void;+ collapsedNodes: Set<string>;+ toggleCollapsed: (id: string) => void;+ expandAll: () => void;+ collapseAll: (nodeIds: string[]) => void;+ searchQuery: string;+ searchInputValue: string;+ setSearchInputValue: (value: string) => void;+ setSearchQueryImmediate: (value: string) => void;+}++const SelectionContext = createContext<SelectionContextValue | null>(null);++export function useSelection(): SelectionContextValue {+ const context = useContext(SelectionContext);+ if (!context) {+ throw new Error("useSelection must be used within a SelectionProvider");+ }+ return context;+}++interface SelectionProviderProps {+ children: ReactNode;+}++export function SelectionProvider({ children }: SelectionProviderProps) {+ const [currentObservationId, setCurrentObservationId] = useQueryParam(+ "observation",+ StringParam,+ );+ const [collapsedNodesArray, setCollapsedNodesArray] = useState<string[]>([]);+ const [searchInputValue, setSearchInputValue] = useState("");+ const [searchQuery, setSearchQuery] = useState("");++ // Debounce search query updates by 500ms for smooth typing+ const debouncedSetSearchQuery = useDebounce(setSearchQuery, 500, false);++ const handleSearchInputChange = useCallback(+ (value: string) => {+ setSearchInputValue(value);+ debouncedSetSearchQuery(value);+ },+ [debouncedSetSearchQuery],+ );++ const setSearchQueryImmediate = useCallback((value: string) => {+ setSearchInputValue(value);+ setSearchQuery(value);+ }, []);++ const collapsedNodes = useMemo(+ () => new Set(collapsedNodesArray),+ [collapsedNodesArray],+ );++ const toggleCollapsed = useCallback((id: string) => {+ setCollapsedNodesArray((prev) =>+ prev.includes(id)+ ? prev.filter((nodeId) => nodeId !== id)+ : [...prev, id],+ );+ }, []);++ const expandAll = useCallback(() => {+ setCollapsedNodesArray([]);+ }, []);++ const collapseAll = useCallback((nodeIds: string[]) => {+ setCollapsedNodesArray(nodeIds);+ }, []);++ const setSelectedNodeId = useCallback(+ (id: string | null) => {+ setCurrentObservationId(id);+ },+ [setCurrentObservationId],+ );++ const value = useMemo<SelectionContextValue>(+ () => ({+ selectedNodeId: currentObservationId ?? null,+ setSelectedNodeId,+ collapsedNodes,+ toggleCollapsed,+ expandAll,+ collapseAll,+ searchQuery,+ searchInputValue,+ setSearchInputValue: handleSearchInputChange,+ setSearchQueryImmediate,+ }),+ [+ currentObservationId,+ setSelectedNodeId,+ collapsedNodes,+ toggleCollapsed,+ expandAll,+ collapseAll,+ searchQuery,+ searchInputValue,+ handleSearchInputChange,+ setSearchQueryImmediate,+ ],+ );++ return (+ <SelectionContext.Provider value={value}>+ {children}+ </SelectionContext.Provider>+ );+}diff --git a/web/src/components/trace2/contexts/TraceDataContext.tsx b/web/src/components/trace2/contexts/TraceDataContext.tsxnew file mode 100644index 0000000000..cc00cd0774--- /dev/null+++ b/web/src/components/trace2/contexts/TraceDataContext.tsx@@ -0,0 +1,95 @@+/**+ * TraceDataContext - Provides read-only trace data and derived structures.+ *+ * Purpose:+ * - Provides trace, observations, scores from props+ * - Computes and memoizes tree structure, nodeMap, and searchItems+ *+ * Not responsible for:+ * - Data fetching (done by parent via API hooks)+ * - UI state (selection, collapsed nodes) - see SelectionContext+ * - Display preferences - see ViewPreferencesContext+ */++import { createContext, useContext, useMemo, type ReactNode } from "react";+import { type TraceDomain, type ScoreDomain } from "@langfuse/shared";+import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";+import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";+import { type TreeNode, type TraceSearchListItem } from "../lib/types";+import { buildTraceUiData } from "../lib/tree-building";+import { useViewPreferences } from "./ViewPreferencesContext";++type TraceType = Omit<+ WithStringifiedMetadata<TraceDomain>,+ "input" | "output"+> & {+ input: string | null;+ output: string | null;+};++interface TraceDataContextValue {+ trace: TraceType;+ observations: ObservationReturnTypeWithMetadata[];+ scores: WithStringifiedMetadata<ScoreDomain>[];+ tree: TreeNode;+ nodeMap: Map<string, TreeNode>;+ searchItems: TraceSearchListItem[];+ hiddenObservationsCount: number;+ comments: Map<string, number>;+}++const TraceDataContext = createContext<TraceDataContextValue | null>(null);++export function useTraceData(): TraceDataContextValue {+ const context = useContext(TraceDataContext);+ if (!context) {+ throw new Error("useTraceData must be used within a TraceDataProvider");+ }+ return context;+}++interface TraceDataProviderProps {+ trace: TraceType;+ observations: ObservationReturnTypeWithMetadata[];+ scores: WithStringifiedMetadata<ScoreDomain>[];+ comments: Map<string, number>;+ children: ReactNode;+}++/**+ * TraceDataProvider must be rendered within ViewPreferencesProvider.+ * It consumes minObservationLevel directly from ViewPreferencesContext.+ */+export function TraceDataProvider({+ trace,+ observations,+ scores,+ comments,+ children,+}: TraceDataProviderProps) {+ const { minObservationLevel } = useViewPreferences();++ const uiData = useMemo(() => {+ return buildTraceUiData(trace, observations, minObservationLevel);+ }, [trace, observations, minObservationLevel]);++ const value = useMemo<TraceDataContextValue>(+ () => ({+ trace,+ observations,+ scores,+ tree: uiData.tree,+ nodeMap: uiData.nodeMap,+ searchItems: uiData.searchItems,+ hiddenObservationsCount: uiData.hiddenObservationsCount,+ comments,+ }),+ [trace, observations, scores, uiData, comments],+ );++ return (+ <TraceDataContext.Provider value={value}>+ {children}+ </TraceDataContext.Provider>+ );+}diff --git a/web/src/components/trace2/contexts/TraceGraphDataContext.tsx b/web/src/components/trace2/contexts/TraceGraphDataContext.tsxnew file mode 100644index 0000000000..1ba1d129a6--- /dev/null+++ b/web/src/components/trace2/contexts/TraceGraphDataContext.tsx@@ -0,0 +1,120 @@+/**+ * TraceGraphDataContext - Provides agent graph data for visualization.+ *+ * Purpose:+ * - Fetches agent graph data once and shares across components+ * - Computes isGraphViewAvailable for UI conditionals+ * - Avoids duplicate fetches in header and graph components+ */++import { createContext, useContext, useMemo, type ReactNode } from "react";+import { api } from "@/src/utils/api";+import { type AgentGraphDataResponse } from "@/src/features/trace-graph-view/types";++const MAX_NODES_FOR_GRAPH_UI = 5000;++interface TraceGraphDataContextValue {+ /** Agent graph data for visualization */+ agentGraphData: AgentGraphDataResponse[];+ /** Whether graph view is available (has graphable data, not too large) */+ isGraphViewAvailable: boolean;+ /** Whether data is currently loading */+ isLoading: boolean;+}++const TraceGraphDataContext = createContext<TraceGraphDataContextValue | null>(+ null,+);++export function useTraceGraphData(): TraceGraphDataContextValue {+ const context = useContext(TraceGraphDataContext);+ if (!context) {+ throw new Error(+ "useTraceGraphData must be used within a TraceGraphDataProvider",+ );+ }+ return context;+}++interface TraceGraphDataProviderProps {+ children: ReactNode;+ projectId: string;+ traceId: string;+ observations: Array<{ startTime: Date }>;+}++export function TraceGraphDataProvider({+ children,+ projectId,+ 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();++ const query = api.traces.getAgentGraphData.useQuery(+ {+ projectId,+ traceId,+ minStartTime,+ maxStartTime,+ },+ {+ enabled: observations.length > 0,+ refetchOnWindowFocus: false,+ refetchOnMount: false,+ refetchOnReconnect: false,+ staleTime: 50 * 60 * 1000, // 50 minutes+ },+ );++ const agentGraphData = useMemo(() => query.data ?? [], [query.data]);++ const isGraphViewAvailable = useMemo(() => {+ if (agentGraphData.length === 0) {+ return false;+ }++ // Don't show graph UI for extremely large traces+ if (agentGraphData.length >= MAX_NODES_FOR_GRAPH_UI) {+ return false;+ }++ // Check if there are observations that would be included in the graph+ // (not SPAN, EVENT, or GENERATION)+ const hasGraphableObservations = agentGraphData.some(+ (obs) =>+ obs.observationType !== "SPAN" &&+ obs.observationType !== "EVENT" &&+ obs.observationType !== "GENERATION",+ );++ // Check for LangGraph data (has step != 0)+ const hasLangGraphData = agentGraphData.some(+ (obs) => obs.step != null && obs.step !== 0,+ );++ return hasGraphableObservations || hasLangGraphData;+ }, [agentGraphData]);++ const value = useMemo<TraceGraphDataContextValue>(+ () => ({+ agentGraphData,+ isGraphViewAvailable,+ isLoading: query.isLoading,+ }),+ [agentGraphData, isGraphViewAvailable, query.isLoading],+ );++ return (+ <TraceGraphDataContext.Provider value={value}>+ {children}+ </TraceGraphDataContext.Provider>+ );+}diff --git a/web/src/components/trace2/contexts/ViewPreferencesContext.tsx b/web/src/components/trace2/contexts/ViewPreferencesContext.tsxnew file mode 100644index 0000000000..7e0211f31f--- /dev/null+++ b/web/src/components/trace2/contexts/ViewPreferencesContext.tsx@@ -0,0 +1,127 @@+/**+ * ViewPreferencesContext - Manages user display preferences persisted to localStorage.+ *+ * Purpose:+ * - Stores toggle states for tree item display (duration, cost, scores, comments)+ * - Manages minimum observation level filter+ * - Persists preferences across sessions via localStorage+ *+ * Not responsible for:+ * - Trace data - see TraceDataContext+ * - Selection/navigation state - see SelectionContext+ */++import { createContext, useContext, useMemo, type ReactNode } from "react";+import { type ObservationLevelType, ObservationLevel } from "@langfuse/shared";+import useLocalStorage from "@/src/components/useLocalStorage";++interface ViewPreferencesContextValue {+ showDuration: boolean;+ setShowDuration: (value: boolean) => void;+ showCostTokens: boolean;+ setShowCostTokens: (value: boolean) => void;+ showScores: boolean;+ setShowScores: (value: boolean) => void;+ colorCodeMetrics: boolean;+ setColorCodeMetrics: (value: boolean) => void;+ showComments: boolean;+ setShowComments: (value: boolean) => void;+ showGraph: boolean;+ setShowGraph: (value: boolean) => void;+ minObservationLevel: ObservationLevelType;+ setMinObservationLevel: (value: ObservationLevelType) => void;+ /** Whether trace is rendered in peek mode (e.g., annotation queues) */+ isPeekMode: boolean;+}++const ViewPreferencesContext =+ createContext<ViewPreferencesContextValue | null>(null);++export function useViewPreferences(): ViewPreferencesContextValue {+ const context = useContext(ViewPreferencesContext);+ if (!context) {+ throw new Error(+ "useViewPreferences must be used within a ViewPreferencesProvider",+ );+ }+ return context;+}++interface ViewPreferencesProviderProps {+ children: ReactNode;+ /** Context in which trace is rendered - affects feature availability */+ traceContext?: "peek" | "fullscreen";+}++export function ViewPreferencesProvider({+ children,+ traceContext = "fullscreen",+}: ViewPreferencesProviderProps) {+ const isPeekMode = traceContext === "peek";+ const [showDuration, setShowDuration] = useLocalStorage(+ "durationOnObservationTree",+ true,+ );+ const [showCostTokens, setShowCostTokens] = useLocalStorage(+ "costTokensOnObservationTree",+ true,+ );+ const [showScores, setShowScores] = useLocalStorage(+ "scoresOnObservationTree",+ true,+ );+ const [colorCodeMetrics, setColorCodeMetrics] = useLocalStorage(+ "colorCodeMetricsOnObservationTree",+ true,+ );+ const [showComments, setShowComments] = useLocalStorage("showComments", true);+ const [showGraph, setShowGraph] = useLocalStorage("showGraph", true);+ const [minObservationLevel, setMinObservationLevel] =+ useLocalStorage<ObservationLevelType>(+ "minObservationLevel",+ ObservationLevel.DEFAULT,+ );++ const value = useMemo<ViewPreferencesContextValue>(+ () => ({+ showDuration,+ setShowDuration,+ showCostTokens,+ setShowCostTokens,+ showScores,+ setShowScores,+ colorCodeMetrics,+ setColorCodeMetrics,+ showComments,+ setShowComments,+ showGraph,+ setShowGraph,+ minObservationLevel,+ setMinObservationLevel,+ isPeekMode,+ }),+ [+ showDuration,+ setShowDuration,+ showCostTokens,+ setShowCostTokens,+ showScores,+ setShowScores,+ colorCodeMetrics,+ setColorCodeMetrics,+ showComments,+ setShowComments,+ showGraph,+ setShowGraph,+ minObservationLevel,+ setMinObservationLevel,+ isPeekMode,+ ],+ );++ return (+ <ViewPreferencesContext.Provider value={value}>+ {children}+ </ViewPreferencesContext.Provider>+ );+}diff --git a/web/src/components/trace2/contexts/json-expansion-utils.clienttest.ts b/web/src/components/trace2/contexts/json-expansion-utils.clienttest.tsnew file mode 100644index 0000000000..2859f66272--- /dev/null+++ b/web/src/components/trace2/contexts/json-expansion-utils.clienttest.ts@@ -0,0 +1,500 @@+/**+ * Tests for JSON expansion state normalization utilities.+ *+ * These functions handle translation between actual observation keys and+ * normalized keys for persistent storage across different traces.+ *+ * Run with: pnpm test-client --testPathPattern="json-expansion-utils"+ */++import {+ normalizeKey,+ normalizeExpansionState,+ denormalizeExpansionState,+} from "./json-expansion-utils";++describe("json-expansion-utils", () => {+ describe("normalizeKey", () => {+ it("converts hyphens to dots", () => {+ expect(normalizeKey("natural-language")).toBe("natural.language");+ expect(normalizeKey("deeply-nested-path")).toBe("deeply.nested.path");+ });++ it("removes observation ID suffix (8-char hex in parentheses)", () => {+ expect(normalizeKey("filter (abc12345)")).toBe("filter");+ expect(normalizeKey("my-span (deadbeef)")).toBe("my.span");+ });++ it("handles combined hyphen conversion and ID removal", () => {+ expect(normalizeKey("natural-language-filter (abc12345)")).toBe(+ "natural.language.filter",+ );+ });++ it("leaves simple keys unchanged", () => {+ expect(normalizeKey("simple")).toBe("simple");+ expect(normalizeKey("already.dotted")).toBe("already.dotted");+ });++ it("handles keys with dots and hyphens", () => {+ expect(normalizeKey("deeply-nested-path.sub.item")).toBe(+ "deeply.nested.path.sub.item",+ );+ });++ it("only removes valid 8-char hex IDs", () => {+ // Should not remove non-hex or wrong length+ expect(normalizeKey("filter (notahex1)")).toBe("filter (notahex1)");+ expect(normalizeKey("filter (abc123)")).toBe("filter (abc123)"); // 6 chars+ expect(normalizeKey("filter (abc123456)")).toBe("filter (abc123456)"); // 9 chars+ });+ });++ describe("normalizeExpansionState", () => {+ it("passes through boolean true", () => {+ expect(normalizeExpansionState(true)).toBe(true);+ });++ it("passes through boolean false", () => {+ expect(normalizeExpansionState(false)).toBe(false);+ });++ it("returns empty object for empty input", () => {+ expect(normalizeExpansionState({})).toEqual({});+ });++ it("normalizes object keys", () => {+ const input = {+ "my-span (abc12345)": true,+ "another-span (def67890)": false,+ };+ expect(normalizeExpansionState(input)).toEqual({+ "my.span": true,+ "another.span": false,+ });+ });++ it("normalizes nested paths", () => {+ const input = {+ "my-span (abc12345).input": true,+ "my-span (abc12345).output.nested": false,+ };+ expect(normalizeExpansionState(input)).toEqual({+ "my.span.input": true,+ "my.span.output.nested": false,+ });+ });++ it("merges keys that normalize to the same value (last wins)", () => {+ const input = {+ "span (abc12345)": true,+ "span (def67890)": false, // Same normalized key, different value+ };+ const result = normalizeExpansionState(input);+ // Last value wins due to iteration order+ expect(result).toHaveProperty("span");+ });+ });++ describe("denormalizeExpansionState", () => {+ it("passes through boolean true", () => {+ expect(denormalizeExpansionState(true, [])).toBe(true);+ });++ it("passes through boolean false", () => {+ expect(denormalizeExpansionState(false, [])).toBe(false);+ });++ it("returns empty object when no matching observation keys", () => {+ const normalizedState = { "non.existent": true };+ const observationKeys: string[] = ["other (abc12345)"];+ expect(+ denormalizeExpansionState(normalizedState, observationKeys),+ ).toEqual({});+ });++ it("maps top-level normalized key to actual observation key", () => {+ const normalizedState = { filter: true };+ const observationKeys = ["filter (abc12345)"];++ expect(+ denormalizeExpansionState(normalizedState, observationKeys),+ ).toEqual({+ "filter (abc12345)": true,+ });+ });++ it("handles nested paths within observations", () => {+ const normalizedState = {+ "filter.input": true,+ "filter.output.nested": false,+ };+ const observationKeys = ["filter (abc12345)"];++ expect(+ denormalizeExpansionState(normalizedState, observationKeys),+ ).toEqual({+ "filter (abc12345).input": true,+ "filter (abc12345).output.nested": false,+ });+ });++ it("applies state to multiple observations with same normalized name", () => {+ const normalizedState = { filter: true };+ const observationKeys = ["filter (abc12345)", "filter (def67890)"];++ expect(+ denormalizeExpansionState(normalizedState, observationKeys),+ ).toEqual({+ "filter (abc12345)": true,+ "filter (def67890)": true,+ });+ });++ it("handles hyphenated observation names correctly", () => {+ const normalizedState = { "my.span": true };+ const observationKeys = ["my-span (abc12345)"];++ // Observation key gets hyphens converted to dots in output+ expect(+ denormalizeExpansionState(normalizedState, observationKeys),+ ).toEqual({+ "my.span (abc12345)": true,+ });+ });++ it("handles complex nested paths with multiple observations", () => {+ // Note: This tests single-word observation names (no hyphens).+ // Observation names with hyphens (e.g., "llm-call") become dotted after+ // normalization ("llm.call"), which makes nested path matching ambiguous.+ const normalizedState = {+ "generation.input.messages": true,+ "generation.output": false,+ };+ const observationKeys = [+ "generation (abc12345)",+ "generation (def67890)",+ ];++ expect(+ denormalizeExpansionState(normalizedState, observationKeys),+ ).toEqual({+ "generation (abc12345).input.messages": true,+ "generation (def67890).input.messages": true,+ "generation (abc12345).output": false,+ "generation (def67890).output": false,+ });+ });++ it("ignores normalized keys that don't match any observation", () => {+ const normalizedState = {+ filter: true,+ "non.existent": false,+ };+ const observationKeys = ["filter (abc12345)"];++ expect(+ denormalizeExpansionState(normalizedState, observationKeys),+ ).toEqual({+ "filter (abc12345)": true,+ // "non.existent" is not in output+ });+ });+ });++ describe("Performance Tests", () => {+ // Helper to generate random 8-char hex ID+ const generateHexId = (): string => {+ return Math.random().toString(16).slice(2, 10).padEnd(8, "0");+ };++ // Helper to generate observation keys at scale+ const generateObservationKeys = (count: number): string[] => {+ const keys: string[] = [];+ const names = [+ "filter",+ "llm-call",+ "retriever",+ "agent-step",+ "embedding",+ "tool-call",+ "chain",+ "prompt",+ "output-parser",+ "memory-lookup",+ ];++ for (let i = 0; i < count; i++) {+ const name = names[i % names.length];+ const hexId = generateHexId();+ keys.push(`${name} (${hexId})`);+ }+ return keys;+ };++ // Helper to generate expansion state from observation keys+ const generateExpansionState = (+ observationKeys: string[],+ nestedPathsPerKey: number = 0,+ ): Record<string, boolean> => {+ const state: Record<string, boolean> = {};+ const nestedPaths = ["input", "output", "metadata", "messages", "config"];++ observationKeys.forEach((key, i) => {+ // Top-level expansion+ state[key] = i % 2 === 0;++ // Add nested paths+ for (let j = 0; j < nestedPathsPerKey; j++) {+ const nestedPath = nestedPaths[j % nestedPaths.length];+ state[`${key}.${nestedPath}`] = (i + j) % 2 === 0;+ }+ });++ return state;+ };++ // Helper to generate normalized state for denormalization tests+ const generateNormalizedState = (+ count: number,+ nestedPathsPerKey: number = 0,+ ): Record<string, boolean> => {+ const state: Record<string, boolean> = {};+ const names = [+ "filter",+ "llm.call",+ "retriever",+ "agent.step",+ "embedding",+ "tool.call",+ "chain",+ "prompt",+ "output.parser",+ "memory.lookup",+ ];+ const nestedPaths = ["input", "output", "metadata", "messages", "config"];++ for (let i = 0; i < count; i++) {+ const name = names[i % names.length];+ state[name] = i % 2 === 0;++ for (let j = 0; j < nestedPathsPerKey; j++) {+ const nestedPath = nestedPaths[j % nestedPaths.length];+ state[`${name}.${nestedPath}`] = (i + j) % 2 === 0;+ }+ }++ return state;+ };++ const runNormalizeKeyTest = (count: number, threshold: number) => {+ const keys = generateObservationKeys(count);++ const start = Date.now();+ keys.forEach((key) => normalizeKey(key));+ const duration = Date.now() - start;++ console.log(`normalizeKey x${count.toLocaleString()}: ${duration}ms`);+ expect(duration).toBeLessThan(threshold);+ return duration;+ };++ const runNormalizeStateTest = (+ keyCount: number,+ nestedPaths: number,+ threshold: number,+ ) => {+ const observationKeys = generateObservationKeys(keyCount);+ const state = generateExpansionState(observationKeys, nestedPaths);+ const totalKeys = Object.keys(state).length;++ const start = Date.now();+ const result = normalizeExpansionState(state);+ const duration = Date.now() - start;++ expect(typeof result).toBe("object");+ console.log(+ `normalizeExpansionState (${totalKeys.toLocaleString()} keys): ${duration}ms`,+ );+ expect(duration).toBeLessThan(threshold);+ return duration;+ };++ const runDenormalizeStateTest = (+ keyCount: number,+ observationCount: number,+ nestedPaths: number,+ threshold: number,+ ) => {+ const normalizedState = generateNormalizedState(keyCount, nestedPaths);+ const observationKeys = generateObservationKeys(observationCount);+ const totalNormalizedKeys = Object.keys(normalizedState).length;++ const start = Date.now();+ const result = denormalizeExpansionState(+ normalizedState,+ observationKeys,+ );+ const duration = Date.now() - start;++ expect(typeof result).toBe("object");+ console.log(+ `denormalizeExpansionState (${totalNormalizedKeys.toLocaleString()} normalized keys, ${observationCount.toLocaleString()} observations): ${duration}ms`,+ );+ expect(duration).toBeLessThan(threshold);+ return duration;+ };++ describe("1k scale", () => {+ const scale = 1_000;+ const threshold = 50; // 50ms++ it("normalizes 1k keys", () => {+ runNormalizeKeyTest(scale, threshold);+ });++ it("normalizes expansion state with 1k keys", () => {+ runNormalizeStateTest(scale, 0, threshold);+ });++ it("normalizes expansion state with 1k keys and nested paths", () => {+ runNormalizeStateTest(scale, 3, threshold);+ });++ it("denormalizes state with 1k observations", () => {+ runDenormalizeStateTest(100, scale, 0, threshold);+ });++ it("denormalizes state with 1k observations and nested paths", () => {+ runDenormalizeStateTest(100, scale, 3, threshold);+ });+ });++ describe("10k scale", () => {+ const scale = 10_000;+ const threshold = 200; // 200ms++ it("normalizes 10k keys", () => {+ runNormalizeKeyTest(scale, threshold);+ });++ it("normalizes expansion state with 10k keys", () => {+ runNormalizeStateTest(scale, 0, threshold);+ });++ it("normalizes expansion state with 10k keys and nested paths", () => {+ runNormalizeStateTest(scale, 3, threshold);+ });++ it("denormalizes state with 10k observations", () => {+ runDenormalizeStateTest(100, scale, 0, threshold);+ });++ it("denormalizes state with 10k observations and nested paths", () => {+ runDenormalizeStateTest(100, scale, 3, threshold);+ });+ });++ describe("25k scale", () => {+ const scale = 25_000;+ const threshold = 500; // 500ms++ it("normalizes 25k keys", () => {+ runNormalizeKeyTest(scale, threshold);+ });++ it("normalizes expansion state with 25k keys", () => {+ runNormalizeStateTest(scale, 0, threshold);+ });++ it("denormalizes state with 25k observations", () => {+ runDenormalizeStateTest(100, scale, 0, threshold);+ });+ });++ describe("50k scale", () => {+ const scale = 50_000;+ const threshold = 1_000; // 1s++ it("normalizes 50k keys", () => {+ runNormalizeKeyTest(scale, threshold);+ });++ it("normalizes expansion state with 50k keys", () => {+ runNormalizeStateTest(scale, 0, threshold);+ });++ it("denormalizes state with 50k observations", () => {+ runDenormalizeStateTest(100, scale, 0, threshold);+ });+ });++ describe("100k scale", () => {+ const scale = 100_000;+ const threshold = 2_000; // 2s++ it("normalizes 100k keys", () => {+ runNormalizeKeyTest(scale, threshold);+ });++ it("normalizes expansion state with 100k keys", () => {+ runNormalizeStateTest(scale, 0, threshold);+ });++ it("denormalizes state with 100k observations", () => {+ runDenormalizeStateTest(100, scale, 0, threshold);+ });+ });++ describe("500k scale", () => {+ const scale = 500_000;+ const threshold = 10_000; // 10s++ it("normalizes 500k keys", () => {+ runNormalizeKeyTest(scale, threshold);+ });++ it("normalizes expansion state with 500k keys", () => {+ runNormalizeStateTest(scale, 0, threshold);+ });++ it("denormalizes state with 500k observations", () => {+ runDenormalizeStateTest(100, scale, 0, threshold);+ });+ });++ describe("1M scale", () => {+ const scale = 1_000_000;+ const threshold = 30_000; // 30s++ it("normalizes 1M keys", () => {+ runNormalizeKeyTest(scale, threshold);+ });++ it("normalizes expansion state with 1M keys", () => {+ runNormalizeStateTest(scale, 0, threshold);+ });++ it("denormalizes state with 1M observations", () => {+ runDenormalizeStateTest(100, scale, 0, threshold);+ });+ });++ describe("5M scale", () => {+ const scale = 5_000_000;+ const threshold = 120_000; // 2 minutes++ it("normalizes 5M keys", () => {+ runNormalizeKeyTest(scale, threshold);+ });++ it("normalizes expansion state with 5M keys", () => {+ runNormalizeStateTest(scale, 0, threshold);+ });++ it("denormalizes state with 5M observations", () => {+ runDenormalizeStateTest(100, scale, 0, threshold);+ });+ });+ });+});diff --git a/web/src/components/trace2/contexts/json-expansion-utils.ts b/web/src/components/trace2/contexts/json-expansion-utils.tsnew file mode 100644index 0000000000..32f85ece09--- /dev/null+++ b/web/src/components/trace2/contexts/json-expansion-utils.ts@@ -0,0 +1,108 @@+/**+ * Utility functions for JSON expansion state normalization.+ *+ * These functions handle the translation between:+ * - Actual observation keys (e.g., "natural-language-filter (abc12345)")+ * - Normalized keys for persistent storage (e.g., "natural.language.filter")+ *+ * This normalization allows expansion state to persist across different traces+ * that have similarly-named observations, regardless of their specific IDs.+ */++/**+ * Normalizes an observation key for persistent storage.+ *+ * Transforms:+ * 1. Hyphens to dots (PrettyJsonView internal format)+ * 2. Removes observation ID suffix (8-char hex in parentheses)+ *+ * @example+ * normalizeKey("natural-language-filter (abc12345)") // "natural.language.filter"+ * normalizeKey("simple") // "simple"+ */+export function normalizeKey(key: string): string {+ return key.replace(/-/g, ".").replace(/\s*\([a-f0-9]{8}\)/, "");+}++/**+ * Converts actual expansion state to normalized form for persistent storage.+ *+ * @param actualState - The current expansion state with actual observation keys+ * @returns Normalized state suitable for storage, or boolean if input is boolean+ */+export function normalizeExpansionState(+ actualState: Record<string, boolean> | boolean,+): Record<string, boolean> | boolean {+ if (typeof actualState === "boolean") return actualState;++ const normalized: Record<string, boolean> = {};++ Object.entries(actualState).forEach(([key, value]) => {+ const normalizedKey = normalizeKey(key);+ normalized[normalizedKey] = value;+ });++ return normalized;+}++/**+ * Converts normalized expansion state back to actual state with observation IDs.+ *+ * This function maps normalized keys back to their actual observation keys,+ * handling:+ * - Top-level observation keys+ * - Nested paths within observations+ * - Multiple observations that normalize to the same key+ *+ * @param normalizedState - The stored normalized expansion state+ * @param observationKeys - Array of actual observation keys (e.g., ["filter (abc12345)", "filter (def67890)"])+ * @returns Denormalized state with actual observation keys, or boolean if input is boolean+ */+export function denormalizeExpansionState(+ normalizedState: Record<string, boolean> | boolean,+ observationKeys: string[],+): Record<string, boolean> | boolean {+ if (typeof normalizedState === "boolean") return normalizedState;++ // Build mapping: normalized observation name -> actual observation name(s)+ // Note: Multiple observations can normalize to the same key+ const normalizedToActual = new Map<string, string[]>();+ observationKeys.forEach((actualKey) => {+ const normalized = normalizeKey(actualKey);+ if (!normalizedToActual.has(normalized)) {+ normalizedToActual.set(normalized, []);+ }+ // Store with hyphens converted to dots (PrettyJsonView format)+ normalizedToActual.get(normalized)!.push(actualKey.replace(/-/g, "."));+ });++ const denormalized: Record<string, boolean> = {};++ Object.entries(normalizedState).forEach(([normalizedKey, value]) => {+ // First check if this is a top-level observation key (no nested path)+ if (normalizedToActual.has(normalizedKey)) {+ const actualKeys = normalizedToActual.get(normalizedKey)!;+ actualKeys.forEach((actualKey) => {+ denormalized[actualKey] = value;+ });+ return;+ }++ // Otherwise split key into top-level observation and nested path+ const parts = normalizedKey.split(".");+ const topLevelNormalized = parts[0];+ const restOfPath = parts.slice(1).join(".");++ // Find all actual observation keys that match this normalized key+ const actualTopLevelKeys = normalizedToActual.get(topLevelNormalized) || [];++ actualTopLevelKeys.forEach((actualTopLevel) => {+ const actualKey = restOfPath+ ? `${actualTopLevel}.${restOfPath}`+ : actualTopLevel;+ denormalized[actualKey] = value;+ });+ });++ return denormalized;+}diff --git a/web/src/components/trace2/lib/download-trace.ts b/web/src/components/trace2/lib/download-trace.tsnew file mode 100644index 0000000000..b4392f5d2a--- /dev/null+++ b/web/src/components/trace2/lib/download-trace.ts@@ -0,0 +1,41 @@+/**+ * Helper function for downloading trace data as JSON+ */++export interface DownloadTraceAsJsonParams {+ trace: {+ id: string;+ [key: string]: unknown;+ };+ observations: unknown[];+ filename?: string;+}++/**+ * Download trace data with observations as JSON file+ *+ * @param params - Configuration object+ * @param params.trace - Trace object to download+ * @param params.observations - Array of observations (can be basic or with full I/O data)+ * @param params.filename - Optional custom filename (defaults to trace-{traceId}.json)+ */+export function downloadTraceAsJson(params: DownloadTraceAsJsonParams): void {+ const { trace, observations, filename } = params;++ const exportData = {+ trace,+ observations,+ };++ const jsonString = JSON.stringify(exportData, null, 2);+ const blob = new Blob([jsonString], { type: "application/json" });+ const url = URL.createObjectURL(blob);++ const link = document.createElement("a");+ link.href = url;+ link.download = filename || `trace-${trace.id}.json`;+ document.body.appendChild(link);+ link.click();+ document.body.removeChild(link);+ URL.revokeObjectURL(url);+}diff --git a/web/src/components/trace2/lib/helpers.ts b/web/src/components/trace2/lib/helpers.tsnew file mode 100644index 0000000000..963bfd7969--- /dev/null+++ b/web/src/components/trace2/lib/helpers.ts@@ -0,0 +1,487 @@+import { type NestedObservation } from "@/src/utils/types";+import { type TreeNode, type TraceSearchListItem } from "./types";+import { type ObservationReturnType } from "@/src/server/api/routers/traces";+import Decimal from "decimal.js";+import {+ type ObservationLevelType,+ ObservationLevel,+ type TraceDomain,+} from "@langfuse/shared";+import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";++export function nestObservations(+ list: ObservationReturnType[],+ minLevel?: ObservationLevelType,+): {+ nestedObservations: NestedObservation[];+ hiddenObservationsCount: number;+} {+ if (list.length === 0)+ return { nestedObservations: [], hiddenObservationsCount: 0 };++ // Data prep:+ // - Filter for observations with minimum level+ // - Remove parentObservationId attribute from observations if the id does not exist in the list of observations+ const mutableList = list.filter((o) =>+ getObservationLevels(minLevel).includes(o.level),+ );+ const hiddenObservationsCount = list.length - mutableList.length;++ // Build a Set of all observation IDs for O(1) lookup instead of O(n) find+ const observationIds = new Set(list.map((o) => o.id));++ mutableList.forEach((observation) => {+ if (+ observation.parentObservationId &&+ !observationIds.has(observation.parentObservationId)+ ) {+ observation.parentObservationId = null;+ }+ });++ // Step 0: Sort the list by start time to ensure observations are in right order+ const sortedObservations = mutableList.sort(+ (a, b) => a.startTime.getTime() - b.startTime.getTime(),+ );++ // Step 1: Create a map where the keys are object IDs, and the values are+ // the corresponding objects with an added 'children' property.+ const map = new Map<string, NestedObservation>();+ for (const obj of sortedObservations) {+ map.set(obj.id, { ...obj, children: [] });+ }++ // Step 2: Create another map for the roots of all trees.+ const roots = new Map<string, NestedObservation>();++ // Step 3: Populate the 'children' arrays and root map.+ for (const obj of map.values()) {+ if (obj.parentObservationId) {+ const parent = map.get(obj.parentObservationId);+ if (parent) {+ parent.children.push(obj);+ }+ } else {+ roots.set(obj.id, obj);+ }+ }++ // Step 4: Sort children by start time for each parent+ for (const obj of map.values()) {+ obj.children.sort((a, b) => a.startTime.getTime() - b.startTime.getTime());+ }++ // Step 5: Return the roots.+ return {+ nestedObservations: Array.from(roots.values()),+ hiddenObservationsCount,+ };+}++export function calculateDisplayTotalCost(p: {+ allObservations: ObservationReturnType[];+ rootObservationId?: string;+}): Decimal | undefined {+ // if parentObservationId is provided, only calculate cost for children of that observation+ // need to be checked recursively for all children and children of children+ // loop until no more children to be added+ let observations = p.allObservations;++ if (p.rootObservationId) {+ observations = observations.filter(+ (o) =>+ o.parentObservationId === p.rootObservationId ||+ o.id === p.rootObservationId,+ );++ while (true) {+ const childrenToAdd = p.allObservations.filter(+ (o) =>+ o.parentObservationId &&+ !observations.map((o2) => o2.id).includes(o.id) &&+ observations.map((o2) => o2.id).includes(o.parentObservationId),+ );+ if (childrenToAdd.length === 0) break;+ observations = [...observations, ...childrenToAdd];+ }+ }++ const totalCost = observations.reduce<Decimal | undefined>(+ (prev: Decimal | undefined, curr: ObservationReturnType) => {+ // if we don't have any calculated costs, we can't do anything+ if (!curr.totalCost && !curr.inputCost && !curr.outputCost) return prev;++ // if we have either input or output cost, but not total cost, we can use that+ if (!curr.totalCost && (curr.inputCost || curr.outputCost)) {+ const inputCost =+ curr.inputCost != null ? new Decimal(curr.inputCost) : new Decimal(0);++ const outputCost =+ curr.outputCost != null+ ? new Decimal(curr.outputCost)+ : new Decimal(0);++ const combinedCost = inputCost.plus(outputCost);++ return prev+ ? prev.plus(combinedCost)+ : combinedCost.isZero()+ ? undefined+ : combinedCost;+ }++ if (!curr.totalCost) return prev;++ // if we have total cost, we can use that+ return prev ? prev.plus(curr.totalCost) : new Decimal(curr.totalCost);+ },+ undefined,+ );++ return totalCost;+}++function getObservationLevels(minLevel: ObservationLevelType | undefined) {+ const ascendingLevels = [+ ObservationLevel.DEBUG,+ ObservationLevel.DEFAULT,+ ObservationLevel.WARNING,+ ObservationLevel.ERROR,+ ];++ if (!minLevel) return ascendingLevels;++ const minLevelIndex = ascendingLevels.indexOf(minLevel);++ return ascendingLevels.slice(minLevelIndex);+}++export const heatMapTextColor = (p: {+ min?: Decimal | number;+ max: Decimal | number;+ value: Decimal | number;+}) => {+ const { min, max, value } = p;+ const minDecimal = min ? new Decimal(min) : new Decimal(0);+ const maxDecimal = new Decimal(max);+ const valueDecimal = new Decimal(value);++ const cutOffs: [number, string][] = [+ [0.75, "text-dark-red"], // 75%+ [0.5, "text-dark-yellow"], // 50%+ ];+ const standardizedValueOnStartEndScale = valueDecimal+ .sub(minDecimal)+ .div(maxDecimal.sub(minDecimal));+ const ratio = standardizedValueOnStartEndScale.toNumber();++ // pick based on ratio if threshold is exceeded+ for (const [threshold, color] of cutOffs) {+ if (ratio >= threshold) {+ return color;+ }+ }+ return "";+};++// Helper function to unnest observations for cost calculation+export const unnestObservation = (nestedObservation: NestedObservation) => {+ const unnestedObservations = [];+ const { children, ...observation } = nestedObservation;+ unnestedObservations.push(observation);+ children.forEach((child) => {+ unnestedObservations.push(...unnestObservation(child));+ });+ return unnestedObservations;+};++// Transform trace + observations into unified tree structure+// Helper function to compute and enrich tree nodes with pre-computed costs+// This is done bottom-up: compute children first, then sum up to parent+// Also populates the nodeMap for O(1) lookup by ID+function enrichTreeNodeWithCosts(+ node: TreeNode,+ nodeMap: Map<string, TreeNode>,+): TreeNode {+ // First, recursively enrich all children+ const enrichedChildren = node.children.map((child) =>+ enrichTreeNodeWithCosts(child, nodeMap),+ );++ // Calculate this node's own cost+ let nodeCost: Decimal | undefined;++ if (node.calculatedTotalCost != null) {+ const cost = new Decimal(node.calculatedTotalCost);+ if (!cost.isZero()) {+ nodeCost = cost;+ }+ } else if (+ node.calculatedInputCost != null ||+ node.calculatedOutputCost != null+ ) {+ const inputCost =+ node.calculatedInputCost != null+ ? new Decimal(node.calculatedInputCost)+ : new Decimal(0);+ const outputCost =+ node.calculatedOutputCost != null+ ? new Decimal(node.calculatedOutputCost)+ : new Decimal(0);+ const combinedCost = inputCost.plus(outputCost);+ if (!combinedCost.isZero()) {+ nodeCost = combinedCost;+ }+ }++ // Sum up all children's total costs+ const childrenTotalCost = enrichedChildren.reduce<Decimal | undefined>(+ (acc, child) => {+ if (!child.totalCost) return acc;+ return acc ? acc.plus(child.totalCost) : child.totalCost;+ },+ undefined,+ );++ // Total cost = this node's cost + all children's costs+ const totalCost =+ nodeCost && childrenTotalCost+ ? nodeCost.plus(childrenTotalCost)+ : nodeCost || childrenTotalCost;++ const enrichedNode = {+ ...node,+ children: enrichedChildren,+ totalCost,+ };++ nodeMap.set(enrichedNode.id, enrichedNode);++ return enrichedNode;+}++// This function is only used internally by buildTraceUiData+function buildTraceTree(+ trace: Omit<WithStringifiedMetadata<TraceDomain>, "input" | "output"> & {+ input: string | null;+ output: string | null;+ latency?: number;+ },+ observations: ObservationReturnType[],+ minLevel?: ObservationLevelType,+): {+ tree: TreeNode;+ hiddenObservationsCount: number;+ nodeMap: Map<string, TreeNode>;+} {+ // First, nest the observations as before+ const { nestedObservations, hiddenObservationsCount } = nestObservations(+ observations,+ minLevel,+ );++ // Create nodeMap for O(1) lookup by ID+ const nodeMap = new Map<string, TreeNode>();++ // Convert observations to TreeNodes with temporal and depth properties+ const convertObservationToTreeNode = (+ obs: NestedObservation,+ 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) =>+ 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,+ });++ // Convert and enrich children with pre-computed costs and populate nodeMap+ const enrichedChildren = nestedObservations+ .map((obs) => convertObservationToTreeNode(obs, trace.timestamp, null, 0))+ .map((node) => enrichTreeNodeWithCosts(node, nodeMap));++ // Calculate total cost for trace root (sum of all top-level children)+ const traceTotalCost = enrichedChildren.reduce<Decimal | undefined>(+ (acc, child) => {+ if (!child.totalCost) return acc;+ return acc ? acc.plus(child.totalCost) : child.totalCost;+ },+ undefined,+ );++ // Create the root tree node (trace)+ // Use a unique ID for the trace root to avoid conflicts with observations that might have the same ID+ const tree: TreeNode = {+ id: `trace-${trace.id}`,+ type: "TRACE",+ name: trace.name ?? "",+ startTime: trace.timestamp,+ endTime: null, // traces don't have explicit end times+ children: enrichedChildren,+ latency: trace.latency,+ totalCost: traceTotalCost,+ startTimeSinceTrace: 0,+ startTimeSinceParentStart: null,+ depth: -1,+ };++ // Add trace root to nodeMap as well+ nodeMap.set(tree.id, tree);++ return { tree, hiddenObservationsCount, nodeMap };+}++// UI helper: build flat search items with per-node aggregated totals and root-level parent totals for heatmap scaling++export function buildTraceUiData(+ trace: Omit<WithStringifiedMetadata<TraceDomain>, "input" | "output"> & {+ input: string | null;+ output: string | null;+ latency?: number;+ },+ observations: ObservationReturnType[],+ minLevel?: ObservationLevelType,+): {+ tree: TreeNode;+ hiddenObservationsCount: number;+ searchItems: TraceSearchListItem[];+ nodeMap: Map<string, TreeNode>;+} {+ const { tree, hiddenObservationsCount, nodeMap } = buildTraceTree(+ trace,+ observations,+ minLevel,+ );++ // Calculate total cost directly from TreeNode structure+ // This avoids unnecessary type conversions and is more straightforward+ const calculateTreeNodeTotalCost = (node: TreeNode): Decimal | undefined => {+ // Check if this node has cost data+ let nodeCost: Decimal | undefined;++ if (node.calculatedTotalCost != null) {+ const cost = new Decimal(node.calculatedTotalCost);+ if (!cost.isZero()) {+ nodeCost = cost;+ }+ } else if (+ node.calculatedInputCost != null ||+ node.calculatedOutputCost != null+ ) {+ const inputCost =+ node.calculatedInputCost != null+ ? new Decimal(node.calculatedInputCost)+ : new Decimal(0);+ const outputCost =+ node.calculatedOutputCost != null+ ? new Decimal(node.calculatedOutputCost)+ : new Decimal(0);+ const combinedCost = inputCost.plus(outputCost);+ if (!combinedCost.isZero()) {+ nodeCost = combinedCost;+ }+ }++ // Calculate total from all children+ const childrenCost = node.children.reduce<Decimal | undefined>(+ (acc, child) => {+ const childCost = calculateTreeNodeTotalCost(child);+ if (!childCost) return acc;+ return acc ? acc.plus(childCost) : childCost;+ },+ undefined,+ );++ // Return the sum of node cost and children cost+ if (nodeCost && childrenCost) {+ return nodeCost.plus(childrenCost);+ }+ return nodeCost || childrenCost;+ };++ const rootTotalCost =+ tree.type === "TRACE"+ ? tree.children.reduce<Decimal | undefined>((acc, child) => {+ const childCost = calculateTreeNodeTotalCost(child);+ if (!childCost) return acc;+ return acc ? acc.plus(childCost) : childCost;+ }, undefined)+ : calculateTreeNodeTotalCost(tree);+ const rootDuration = tree.latency ? tree.latency * 1000 : undefined;++ const out: TraceSearchListItem[] = [];+ const visit = (node: TreeNode) => {+ // push node; SpanItem will compute its own displayed metrics, we only need parent totals for heatmap+ out.push({+ node,+ parentTotalCost: rootTotalCost,+ parentTotalDuration: rootDuration,+ // For TRACE nodes, observationId should be undefined (shows trace overview)+ // For actual observations, use the node ID (which is the real observation ID)+ observationId: node.type === "TRACE" ? undefined : node.id,+ });+ node.children.forEach(visit);+ };+ visit(tree);++ return { tree, hiddenObservationsCount, searchItems: out, nodeMap };+}++/**+ * Download trace data with optionally observations as JSON file+ * @param trace - Trace object to download+ * @param observations - Array of observations (can be basic or with full I/O data)+ * @param filename - Optional custom filename (defaults to trace-{traceId}.json)+ */+export function downloadTraceAsJson(params: {+ trace: {+ id: string;+ [key: string]: unknown;+ };+ observations: unknown[];+ filename?: string;+}) {+ const { trace, observations, filename } = params;++ const exportData = {+ trace,+ observations,+ };++ const jsonString = JSON.stringify(exportData, null, 2);+ const blob = new Blob([jsonString], { type: "application/json" });+ const url = URL.createObjectURL(blob);++ const link = document.createElement("a");+ link.href = url;+ link.download = filename || `trace-${trace.id}.json`;+ document.body.appendChild(link);+ link.click();+ document.body.removeChild(link);+ URL.revokeObjectURL(url);+}diff --git a/web/src/components/trace2/lib/tree-building.clienttest.ts b/web/src/components/trace2/lib/tree-building.clienttest.tsnew file mode 100644index 0000000000..d26fb85de9--- /dev/null+++ b/web/src/components/trace2/lib/tree-building.clienttest.ts@@ -0,0 +1,1358 @@+/**+ * Tests for tree-building utilities.+ *+ * Run with: pnpm test-client --testPathPattern="tree-building"+ */++import { buildTraceUiData } from "./tree-building";+import { type ObservationReturnType } from "@/src/server/api/routers/traces";+import Decimal from "decimal.js";++// Helper to create mock observations+const createMockObservation = (+ overrides: Partial<ObservationReturnType> = {},+): ObservationReturnType => ({+ id: "mock-id",+ name: "Mock Observation",+ type: "SPAN",+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ endTime: new Date("2024-01-01T00:00:01.000Z"),+ parentObservationId: null,+ traceId: "mock-trace-id",+ projectId: "mock-project-id",+ environment: "production",+ createdAt: new Date("2024-01-01T00:00:00.000Z"),+ updatedAt: new Date("2024-01-01T00:00:00.000Z"),+ level: "DEFAULT",+ statusMessage: null,+ version: null,+ model: null,+ internalModelId: null,+ modelParameters: null,+ inputCost: null,+ outputCost: null,+ totalCost: null,+ completionStartTime: null,+ timeToFirstToken: null,+ promptId: null,+ promptName: null,+ promptVersion: null,+ inputUsage: 0,+ outputUsage: 0,+ totalUsage: 0,+ usageDetails: {},+ costDetails: {},+ providedCostDetails: {},+ latency: null,+ usagePricingTierId: null,+ usagePricingTierName: null,+ ...overrides,+});++// Helper to create mock trace+const createMockTrace = (overrides: Record<string, unknown> = {}) => ({+ id: "mock-trace-id",+ name: "Mock Trace",+ timestamp: new Date("2024-01-01T00:00:00.000Z"),+ projectId: "mock-project-id",+ createdAt: new Date("2024-01-01T00:00:00.000Z"),+ updatedAt: new Date("2024-01-01T00:00:00.000Z"),+ public: false,+ bookmarked: false,+ metadata: "{}",+ release: null,+ version: null,+ userId: null,+ sessionId: null,+ input: null,+ output: null,+ tags: [],+ environment: "default",+ latency: 1.5,+ ...overrides,+});++describe("buildTraceUiData", () => {+ it("creates tree with trace as root and observations as children", () => {+ const trace = createMockTrace({ id: "trace-1", name: "Test Trace" });+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "obs-1",+ name: "Observation 1",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.100Z"),+ }),+ createMockObservation({+ id: "obs-2",+ name: "Observation 2",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.200Z"),+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ // Tree root should be the trace+ expect(result.tree.id).toBe("trace-trace-1");+ expect(result.tree.type).toBe("TRACE");+ expect(result.tree.name).toBe("Test Trace");++ // Should have 2 child observations+ expect(result.tree.children).toHaveLength(2);+ expect(result.tree.children[0].id).toBe("obs-1");+ expect(result.tree.children[1].id).toBe("obs-2");+ });++ it("nests child observations under parent observations", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "parent",+ name: "Parent",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ }),+ createMockObservation({+ id: "child-1",+ name: "Child 1",+ parentObservationId: "parent",+ startTime: new Date("2024-01-01T00:00:01.000Z"),+ }),+ createMockObservation({+ id: "child-2",+ name: "Child 2",+ parentObservationId: "parent",+ startTime: new Date("2024-01-01T00:00:02.000Z"),+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ // Should have 1 root observation under trace+ expect(result.tree.children).toHaveLength(1);+ const parent = result.tree.children[0];+ expect(parent.id).toBe("parent");++ // Parent should have 2 children+ expect(parent.children).toHaveLength(2);+ expect(parent.children[0].id).toBe("child-1");+ expect(parent.children[1].id).toBe("child-2");+ });++ it("populates nodeMap for O(1) lookup", () => {+ const trace = createMockTrace({ id: "trace-1" });+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "obs-1",+ parentObservationId: null,+ }),+ createMockObservation({+ id: "obs-2",+ parentObservationId: "obs-1",+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ // nodeMap should contain trace and both observations+ expect(result.nodeMap.size).toBe(3);+ expect(result.nodeMap.has("trace-trace-1")).toBe(true);+ expect(result.nodeMap.has("obs-1")).toBe(true);+ expect(result.nodeMap.has("obs-2")).toBe(true);++ // Should be able to get nodes by ID+ const obs1 = result.nodeMap.get("obs-1");+ expect(obs1?.name).toBe("Mock Observation");+ });++ it("generates searchItems list with all nodes", () => {+ const trace = createMockTrace({ id: "trace-1", latency: 2.0 });+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "obs-1",+ parentObservationId: null,+ }),+ createMockObservation({+ id: "obs-2",+ parentObservationId: "obs-1",+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ // searchItems should contain trace + all observations (flattened)+ expect(result.searchItems).toHaveLength(3);++ // First item should be trace (undefined observationId)+ expect(result.searchItems[0].node.type).toBe("TRACE");+ expect(result.searchItems[0].observationId).toBeUndefined();++ // Other items should have observationId set+ expect(result.searchItems[1].observationId).toBe("obs-1");+ expect(result.searchItems[2].observationId).toBe("obs-2");++ // All items should have parent duration for heatmap+ expect(result.searchItems[0].parentTotalDuration).toBe(2000); // 2s * 1000ms+ });++ it("returns empty children for trace with no observations", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [];++ const result = buildTraceUiData(trace, observations);++ expect(result.tree.children).toHaveLength(0);+ expect(result.searchItems).toHaveLength(1); // Just the trace+ expect(result.hiddenObservationsCount).toBe(0);+ });++ it("sorts children by startTime", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "obs-late",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:02.000Z"),+ }),+ createMockObservation({+ id: "obs-early",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ }),+ createMockObservation({+ id: "obs-middle",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:01.000Z"),+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ // Children should be sorted by startTime+ expect(result.tree.children[0].id).toBe("obs-early");+ expect(result.tree.children[1].id).toBe("obs-middle");+ expect(result.tree.children[2].id).toBe("obs-late");+ });++ describe("Cost Aggregation - Fundamentals", () => {+ it("treats null costs as undefined (not zero)", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "obs-1",+ inputCost: null,+ outputCost: null,+ totalCost: null,+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ const obs = result.nodeMap.get("obs-1");+ expect(obs?.totalCost).toBeUndefined();+ expect(result.tree.totalCost).toBeUndefined();+ });++ it("treats zero costs as undefined", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "obs-1",+ totalCost: 0,+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ const obs = result.nodeMap.get("obs-1");+ expect(obs?.totalCost).toBeUndefined();+ });++ it("treats zero input + output as undefined", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "obs-1",+ inputCost: 0,+ outputCost: 0,+ totalCost: null,+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ const obs = result.nodeMap.get("obs-1");+ expect(obs?.totalCost).toBeUndefined();+ });++ it("uses inputCost when only input is set", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "obs-1",+ inputCost: 0.5,+ outputCost: null,+ totalCost: null,+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ const obs = result.nodeMap.get("obs-1");+ expect(obs?.totalCost).toBeDefined();+ expect(obs?.totalCost?.equals(new Decimal(0.5))).toBe(true);+ });++ it("uses outputCost when only output is set", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "obs-1",+ inputCost: null,+ outputCost: 0.3,+ totalCost: null,+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ const obs = result.nodeMap.get("obs-1");+ expect(obs?.totalCost).toBeDefined();+ expect(obs?.totalCost?.equals(new Decimal(0.3))).toBe(true);+ });++ it("sums input + output when both are set", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "obs-1",+ inputCost: 0.5,+ outputCost: 0.3,+ totalCost: null,+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ const obs = result.nodeMap.get("obs-1");+ expect(obs?.totalCost).toBeDefined();+ expect(obs?.totalCost?.equals(new Decimal(0.8))).toBe(true);+ });++ it("prefers totalCost over input + output", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "obs-1",+ inputCost: 0.5,+ outputCost: 0.3,+ totalCost: 0.9, // Different from sum+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ const obs = result.nodeMap.get("obs-1");+ expect(obs?.totalCost).toBeDefined();+ expect(obs?.totalCost?.equals(new Decimal(0.9))).toBe(true);+ });++ it("treats zero totalCost as undefined (does not fall back to input+output)", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "obs-1",+ inputCost: 0.5,+ outputCost: 0.3,+ totalCost: 0, // Zero means "no cost"+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ const obs = result.nodeMap.get("obs-1");+ // Zero totalCost is treated as undefined (explicit "no cost")+ // Does NOT fall back to input+output+ expect(obs?.totalCost).toBeUndefined();+ });+ });++ describe("Cost Aggregation - Hierarchical", () => {+ it("sums parent and children costs when both have costs", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "parent",+ parentObservationId: null,+ totalCost: 0.5,+ }),+ createMockObservation({+ id: "child-1",+ parentObservationId: "parent",+ totalCost: 0.3,+ }),+ createMockObservation({+ id: "child-2",+ parentObservationId: "parent",+ totalCost: 0.2,+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ const parent = result.nodeMap.get("parent");+ expect(parent?.totalCost).toBeDefined();+ expect(parent?.totalCost?.equals(new Decimal(1.0))).toBe(true);+ });++ it("bubbles up children costs when parent has no cost", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "parent",+ parentObservationId: null,+ totalCost: null,+ }),+ createMockObservation({+ id: "child-1",+ parentObservationId: "parent",+ totalCost: 0.3,+ }),+ createMockObservation({+ id: "child-2",+ parentObservationId: "parent",+ totalCost: 0.2,+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ const parent = result.nodeMap.get("parent");+ expect(parent?.totalCost).toBeDefined();+ expect(parent?.totalCost?.equals(new Decimal(0.5))).toBe(true);+ });++ it("uses only parent cost when children have no costs", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "parent",+ parentObservationId: null,+ totalCost: 0.5,+ }),+ createMockObservation({+ id: "child-1",+ parentObservationId: "parent",+ totalCost: null,+ }),+ createMockObservation({+ id: "child-2",+ parentObservationId: "parent",+ totalCost: null,+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ const parent = result.nodeMap.get("parent");+ expect(parent?.totalCost).toBeDefined();+ expect(parent?.totalCost?.equals(new Decimal(0.5))).toBe(true);+ });++ it("aggregates costs through deep nesting (3 levels)", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "grandparent",+ parentObservationId: null,+ totalCost: 0.1,+ }),+ createMockObservation({+ id: "parent",+ parentObservationId: "grandparent",+ totalCost: 0.2,+ }),+ createMockObservation({+ id: "child",+ parentObservationId: "parent",+ totalCost: 0.3,+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ const grandparent = result.nodeMap.get("grandparent");+ const parent = result.nodeMap.get("parent");+ const child = result.nodeMap.get("child");++ expect(child?.totalCost?.equals(new Decimal(0.3))).toBe(true);+ expect(parent?.totalCost?.equals(new Decimal(0.5))).toBe(true); // 0.2 + 0.3+ expect(grandparent?.totalCost?.equals(new Decimal(0.6))).toBe(true); // 0.1 + 0.5+ });++ it("handles gaps in cost hierarchy (parent has no cost)", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "grandparent",+ parentObservationId: null,+ totalCost: 0.1,+ }),+ createMockObservation({+ id: "parent",+ parentObservationId: "grandparent",+ totalCost: null, // Gap here+ }),+ createMockObservation({+ id: "child",+ parentObservationId: "parent",+ totalCost: 0.3,+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ const grandparent = result.nodeMap.get("grandparent");+ const parent = result.nodeMap.get("parent");++ expect(parent?.totalCost?.equals(new Decimal(0.3))).toBe(true); // Just child's cost+ expect(grandparent?.totalCost?.equals(new Decimal(0.4))).toBe(true); // 0.1 + 0.3+ });++ it("handles mixed cost types among siblings", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "parent",+ parentObservationId: null,+ totalCost: null,+ }),+ createMockObservation({+ id: "child-1",+ parentObservationId: "parent",+ totalCost: 0.5, // Uses totalCost+ }),+ createMockObservation({+ id: "child-2",+ parentObservationId: "parent",+ inputCost: 0.2,+ outputCost: 0.1,+ totalCost: null, // Uses input+output+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ const parent = result.nodeMap.get("parent");+ expect(parent?.totalCost).toBeDefined();+ expect(parent?.totalCost?.equals(new Decimal(0.8))).toBe(true); // 0.5 + 0.3+ });+ });++ describe("Cost Aggregation - Edge Cases", () => {+ it("does not double-count costs (parent with input/output + child)", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "parent",+ parentObservationId: null,+ inputCost: 0.5,+ outputCost: 0.3,+ totalCost: null,+ }),+ createMockObservation({+ id: "child",+ parentObservationId: "parent",+ totalCost: 0.2,+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ const parent = result.nodeMap.get("parent");+ // Should be 0.8 (parent's 0.5+0.3) + 0.2 (child) = 1.0+ // NOT 0.5 + 0.3 + 0.8 (double-counting parent)+ expect(parent?.totalCost?.equals(new Decimal(1.0))).toBe(true);+ });++ it("aggregates costs at trace root level", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "obs-1",+ parentObservationId: null,+ totalCost: 0.5,+ }),+ createMockObservation({+ id: "obs-2",+ parentObservationId: null,+ totalCost: 0.3,+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ // Trace root should sum all top-level observations+ expect(result.tree.totalCost).toBeDefined();+ expect(result.tree.totalCost?.equals(new Decimal(0.8))).toBe(true);+ });++ it("propagates trace totalCost to all searchItems as parentTotalCost", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "obs-1",+ parentObservationId: null,+ totalCost: 0.5,+ }),+ createMockObservation({+ id: "obs-2",+ parentObservationId: null,+ totalCost: 0.3,+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ // All searchItems should have the trace's total cost as parentTotalCost+ const traceTotalCost = result.tree.totalCost;+ expect(traceTotalCost).toBeDefined();++ result.searchItems.forEach((item) => {+ expect(item.parentTotalCost).toBeDefined();+ expect(item.parentTotalCost?.equals(traceTotalCost!)).toBe(true);+ });+ });++ it("handles zero costs correctly in hierarchy (should not propagate)", () => {+ const trace = createMockTrace();+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "parent",+ parentObservationId: null,+ totalCost: 0, // Zero cost+ }),+ createMockObservation({+ id: "child",+ parentObservationId: "parent",+ totalCost: 0, // Zero cost+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ const parent = result.nodeMap.get("parent");+ const child = result.nodeMap.get("child");++ // Both should have undefined totalCost (zero is treated as undefined)+ expect(child?.totalCost).toBeUndefined();+ expect(parent?.totalCost).toBeUndefined();+ expect(result.tree.totalCost).toBeUndefined();+ });+ });++ describe("Performance Tests", () => {+ // Helper to generate observations at scale+ const generateObservations = (+ count: number,+ structure: "flat" | "deep" | "balanced" | "realistic",+ withCosts: boolean,+ ): ObservationReturnType[] => {+ const observations: ObservationReturnType[] = [];+ const baseCost = withCosts ? 0.001 : null;++ if (structure === "flat") {+ // All observations at root level+ for (let i = 0; i < count; i++) {+ observations.push(+ createMockObservation({+ id: `obs-${i}`,+ parentObservationId: null,+ totalCost: baseCost,+ startTime: new Date(`2024-01-01T00:00:${i % 60}.${i % 1000}Z`),+ }),+ );+ }+ } else if (structure === "deep") {+ // Single linear chain (worst case for recursion)+ for (let i = 0; i < count; i++) {+ observations.push(+ createMockObservation({+ id: `obs-${i}`,+ parentObservationId: i === 0 ? null : `obs-${i - 1}`,+ totalCost: baseCost,+ startTime: new Date(`2024-01-01T00:00:${i % 60}.${i % 1000}Z`),+ }),+ );+ }+ } else if (structure === "balanced") {+ // Binary tree structure+ for (let i = 0; i < count; i++) {+ const parentIndex = i === 0 ? null : Math.floor((i - 1) / 2);+ observations.push(+ createMockObservation({+ id: `obs-${i}`,+ parentObservationId:+ parentIndex === null ? null : `obs-${parentIndex}`,+ totalCost: baseCost,+ startTime: new Date(`2024-01-01T00:00:${i % 60}.${i % 1000}Z`),+ }),+ );+ }+ } else {+ // Realistic: ~20% intermediate nodes, ~80% leaf nodes, max depth ~5+ const intermediateNodeCount = Math.floor(count * 0.2);+ const leafNodeCount = count - intermediateNodeCount;++ // Create root nodes (no parent) - 10% of intermediate nodes+ const rootCount = Math.max(1, Math.floor(intermediateNodeCount * 0.1));+ for (let i = 0; i < rootCount; i++) {+ observations.push(+ createMockObservation({+ id: `obs-${i}`,+ parentObservationId: null,+ totalCost: baseCost,+ startTime: new Date(`2024-01-01T00:00:${i % 60}.${i % 1000}Z`),+ }),+ );+ }++ // Create remaining intermediate nodes - attach to previous nodes+ for (let i = rootCount; i < intermediateNodeCount; i++) {+ const parentIndex = Math.floor(Math.random() * i);+ observations.push(+ createMockObservation({+ id: `obs-${i}`,+ parentObservationId: `obs-${parentIndex}`,+ totalCost: baseCost,+ startTime: new Date(`2024-01-01T00:00:${i % 60}.${i % 1000}Z`),+ }),+ );+ }++ // Create leaf nodes - attach to any intermediate node+ for (let i = 0; i < leafNodeCount; i++) {+ const obsId = intermediateNodeCount + i;+ const parentIndex =+ intermediateNodeCount === 0+ ? null+ : Math.floor(Math.random() * intermediateNodeCount);+ observations.push(+ createMockObservation({+ id: `obs-${obsId}`,+ parentObservationId:+ parentIndex === null ? null : `obs-${parentIndex}`,+ totalCost: baseCost,+ startTime: new Date(+ `2024-01-01T00:00:${obsId % 60}.${obsId % 1000}Z`,+ ),+ }),+ );+ }+ }++ return observations;+ };++ const runPerformanceTest = (+ scale: number,+ structure: "flat" | "deep" | "balanced" | "realistic",+ withCosts: boolean,+ threshold: number,+ ) => {+ const trace = createMockTrace();+ const observations = generateObservations(scale, structure, withCosts);++ const start = Date.now();+ const result = buildTraceUiData(trace, observations);+ const duration = Date.now() - start;++ // Verify correct structure was built+ expect(result.nodeMap.size).toBe(scale + 1); // +1 for trace root+ expect(result.searchItems.length).toBe(scale + 1);++ // Log performance metrics+ console.log(+ `${scale.toLocaleString()} observations (${structure}, ${withCosts ? "with costs" : "no costs"}): ${duration}ms`,+ );++ // Assert threshold (generous to avoid flakiness)+ expect(duration).toBeLessThan(threshold);++ return duration;+ };++ describe("1k observations", () => {+ const scale = 1_000;+ const threshold = 100; // 100ms++ it("builds flat structure", () => {+ runPerformanceTest(scale, "flat", false, threshold);+ });++ it("builds deep chain", () => {+ runPerformanceTest(scale, "deep", false, threshold);+ });++ it("builds balanced tree", () => {+ runPerformanceTest(scale, "balanced", false, threshold);+ });++ it("builds realistic structure", () => {+ runPerformanceTest(scale, "realistic", false, threshold);+ });++ it("builds with cost aggregation", () => {+ runPerformanceTest(scale, "realistic", true, threshold);+ });+ });++ describe("10k observations", () => {+ const scale = 10_000;+ const threshold = 500; // 500ms++ it("builds flat structure", () => {+ runPerformanceTest(scale, "flat", false, threshold);+ });++ // Deep chain skipped - causes stack overflow at this scale+ it("builds deep chain", () => {+ runPerformanceTest(scale, "deep", false, threshold);+ });++ it("builds balanced tree", () => {+ runPerformanceTest(scale, "balanced", false, threshold);+ });++ it("builds realistic structure", () => {+ runPerformanceTest(scale, "realistic", false, threshold);+ });++ it("builds with cost aggregation", () => {+ runPerformanceTest(scale, "realistic", true, threshold);+ });+ });++ describe("25k observations", () => {+ const scale = 25_000;+ const threshold = 2_000; // 2s++ it("builds flat structure", () => {+ runPerformanceTest(scale, "flat", false, threshold);+ });++ it("builds realistic structure", () => {+ runPerformanceTest(scale, "realistic", false, threshold);+ });++ it("builds with cost aggregation", () => {+ runPerformanceTest(scale, "realistic", true, threshold);+ });+ });++ describe("50k observations", () => {+ const scale = 50_000;+ const threshold = 5_000; // 5s++ it("builds flat structure", () => {+ runPerformanceTest(scale, "flat", false, threshold);+ });++ it("builds realistic structure", () => {+ runPerformanceTest(scale, "realistic", false, threshold);+ });++ it("builds with cost aggregation", () => {+ runPerformanceTest(scale, "realistic", true, threshold);+ });+ });++ describe("100k observations", () => {+ const scale = 100_000;+ const threshold = 15_000; // 15s++ it("builds flat structure", () => {+ runPerformanceTest(scale, "flat", false, threshold);+ });++ it("builds realistic structure", () => {+ runPerformanceTest(scale, "realistic", false, threshold);+ });++ it("builds with cost aggregation", () => {+ runPerformanceTest(scale, "realistic", true, threshold);+ });+ });++ describe("500k observations (extreme - manual only)", () => {+ const scale = 500_000;+ const threshold = 60_000; // 60s++ it("builds realistic structure", () => {+ runPerformanceTest(scale, "realistic", false, threshold);+ });++ it("builds with cost aggregation", () => {+ runPerformanceTest(scale, "realistic", true, threshold);+ });+ });++ describe("1M observations (extreme - manual only)", () => {+ const scale = 1_000_000;+ const threshold = 180_000; // 3 minutes++ it("builds realistic structure", () => {+ runPerformanceTest(scale, "realistic", false, threshold);+ });++ it("builds with cost aggregation", () => {+ runPerformanceTest(scale, "realistic", true, threshold);+ });+ });+ });++ describe("Temporal and Depth Properties", () => {+ describe("Basic Calculations", () => {+ it("calculates startTimeSinceTrace for single observation", () => {+ const trace = createMockTrace({+ id: "trace-1",+ timestamp: new Date("2024-01-01T00:00:00.000Z"),+ });+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "obs-1",+ name: "Observation 1",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:02.500Z"), // 2500ms after trace+ }),+ ];++ const result = buildTraceUiData(trace, observations);+ const obs1 = result.nodeMap.get("obs-1");++ expect(obs1?.startTimeSinceTrace).toBe(2500);+ });++ it("calculates startTimeSinceParentStart for parent-child pair", () => {+ const trace = createMockTrace({+ id: "trace-1",+ timestamp: new Date("2024-01-01T00:00:00.000Z"),+ });+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "parent",+ name: "Parent",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:01.000Z"), // +1000ms+ }),+ createMockObservation({+ id: "child",+ name: "Child",+ parentObservationId: "parent",+ startTime: new Date("2024-01-01T00:00:01.300Z"), // +300ms from parent+ }),+ ];++ const result = buildTraceUiData(trace, observations);+ const parent = result.nodeMap.get("parent");+ const child = result.nodeMap.get("child");++ expect(parent?.startTimeSinceTrace).toBe(1000);+ expect(parent?.startTimeSinceParentStart).toBeNull();++ expect(child?.startTimeSinceTrace).toBe(1300);+ expect(child?.startTimeSinceParentStart).toBe(300);+ });++ it("sets startTimeSinceParentStart to null for root observations", () => {+ const trace = createMockTrace({+ id: "trace-1",+ timestamp: new Date("2024-01-01T00:00:00.000Z"),+ });+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "root-1",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:01.000Z"),+ }),+ createMockObservation({+ id: "root-2",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:02.000Z"),+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ expect(+ result.nodeMap.get("root-1")?.startTimeSinceParentStart,+ ).toBeNull();+ expect(+ result.nodeMap.get("root-2")?.startTimeSinceParentStart,+ ).toBeNull();+ });++ it("handles TRACE root node properties correctly", () => {+ const trace = createMockTrace({+ id: "trace-1",+ timestamp: new Date("2024-01-01T00:00:00.000Z"),+ });+ const observations: ObservationReturnType[] = [];++ const result = buildTraceUiData(trace, observations);++ expect(result.tree.startTimeSinceTrace).toBe(0);+ expect(result.tree.startTimeSinceParentStart).toBeNull();+ expect(result.tree.depth).toBe(-1);+ });+ });++ describe("Depth Calculation", () => {+ it("assigns depth 0 to root observations", () => {+ const trace = createMockTrace({ id: "trace-1" });+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "root-1",+ parentObservationId: null,+ }),+ createMockObservation({+ id: "root-2",+ parentObservationId: null,+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ expect(result.nodeMap.get("root-1")?.depth).toBe(0);+ expect(result.nodeMap.get("root-2")?.depth).toBe(0);+ });++ it("increments depth for nested observations", () => {+ const trace = createMockTrace({ id: "trace-1" });+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "level-0",+ parentObservationId: null,+ }),+ createMockObservation({+ id: "level-1",+ parentObservationId: "level-0",+ }),+ createMockObservation({+ id: "level-2",+ parentObservationId: "level-1",+ }),+ createMockObservation({+ id: "level-3",+ parentObservationId: "level-2",+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ expect(result.nodeMap.get("level-0")?.depth).toBe(0);+ expect(result.nodeMap.get("level-1")?.depth).toBe(1);+ expect(result.nodeMap.get("level-2")?.depth).toBe(2);+ expect(result.nodeMap.get("level-3")?.depth).toBe(3);+ });++ it("handles multiple branches with different depths", () => {+ const trace = createMockTrace({ id: "trace-1" });+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "root",+ parentObservationId: null,+ }),+ // Branch 1: depth 1 → 2+ createMockObservation({+ id: "branch1-level1",+ parentObservationId: "root",+ }),+ createMockObservation({+ id: "branch1-level2",+ parentObservationId: "branch1-level1",+ }),+ // Branch 2: depth 1 only+ createMockObservation({+ id: "branch2-level1",+ parentObservationId: "root",+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ expect(result.nodeMap.get("root")?.depth).toBe(0);+ expect(result.nodeMap.get("branch1-level1")?.depth).toBe(1);+ expect(result.nodeMap.get("branch1-level2")?.depth).toBe(2);+ expect(result.nodeMap.get("branch2-level1")?.depth).toBe(1);+ });+ });++ describe("Edge Cases", () => {+ it("handles observation starting at same time as parent", () => {+ const trace = createMockTrace({+ timestamp: new Date("2024-01-01T00:00:00.000Z"),+ });+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "parent",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:01.000Z"),+ }),+ createMockObservation({+ id: "child",+ parentObservationId: "parent",+ startTime: new Date("2024-01-01T00:00:01.000Z"), // Same as parent+ }),+ ];++ const result = buildTraceUiData(trace, observations);+ const child = result.nodeMap.get("child");++ expect(child?.startTimeSinceParentStart).toBe(0);+ });++ it("handles observation starting before trace (clock skew)", () => {+ const trace = createMockTrace({+ timestamp: new Date("2024-01-01T00:00:01.000Z"),+ });+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "obs-1",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.500Z"), // 500ms before trace+ }),+ ];++ const result = buildTraceUiData(trace, observations);+ const obs1 = result.nodeMap.get("obs-1");++ expect(obs1?.startTimeSinceTrace).toBe(-500);+ });++ it("handles multiple root observations with different start times", () => {+ const trace = createMockTrace({+ timestamp: new Date("2024-01-01T00:00:00.000Z"),+ });+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "root-1",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:01.000Z"),+ }),+ createMockObservation({+ id: "root-2",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:05.000Z"),+ }),+ createMockObservation({+ id: "root-3",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:03.500Z"),+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ expect(result.nodeMap.get("root-1")?.startTimeSinceTrace).toBe(1000);+ expect(result.nodeMap.get("root-2")?.startTimeSinceTrace).toBe(5000);+ expect(result.nodeMap.get("root-3")?.startTimeSinceTrace).toBe(3500);++ // All should have null parent-relative time+ expect(+ result.nodeMap.get("root-1")?.startTimeSinceParentStart,+ ).toBeNull();+ expect(+ result.nodeMap.get("root-2")?.startTimeSinceParentStart,+ ).toBeNull();+ expect(+ result.nodeMap.get("root-3")?.startTimeSinceParentStart,+ ).toBeNull();+ });++ it("handles deep nesting without stack overflow", () => {+ const trace = createMockTrace({+ timestamp: new Date("2024-01-01T00:00:00.000Z"),+ });+ const depth = 1000;+ const observations: ObservationReturnType[] = [];++ // Create deep chain: obs-0 → obs-1 → obs-2 → ... → obs-999+ for (let i = 0; i < depth; i++) {+ observations.push(+ createMockObservation({+ id: `obs-${i}`,+ parentObservationId: i === 0 ? null : `obs-${i - 1}`,+ startTime: new Date(+ `2024-01-01T00:00:${String(i).padStart(2, "0")}.000Z`,+ ),+ }),+ );+ }++ const result = buildTraceUiData(trace, observations);++ // Verify first, middle, and last nodes+ expect(result.nodeMap.get("obs-0")?.depth).toBe(0);+ expect(result.nodeMap.get("obs-500")?.depth).toBe(500);+ expect(result.nodeMap.get("obs-999")?.depth).toBe(999);++ // Verify temporal calculations still work+ expect(result.nodeMap.get("obs-0")?.startTimeSinceTrace).toBe(0);+ expect(+ result.nodeMap.get("obs-0")?.startTimeSinceParentStart,+ ).toBeNull();+ expect(result.nodeMap.get("obs-1")?.startTimeSinceParentStart).toBe(+ 1000,+ );+ });+ });++ describe("Real-World Scenarios", () => {+ it("identifies sequential execution pattern", () => {+ const trace = createMockTrace({+ timestamp: new Date("2024-01-01T00:00:00.000Z"),+ });+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "parent",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ }),+ // Sequential children with large delays+ createMockObservation({+ id: "step-1",+ parentObservationId: "parent",+ startTime: new Date("2024-01-01T00:00:01.000Z"), // +1s+ }),+ createMockObservation({+ id: "step-2",+ parentObservationId: "parent",+ startTime: new Date("2024-01-01T00:00:03.000Z"), // +3s+ }),+ createMockObservation({+ id: "step-3",+ parentObservationId: "parent",+ startTime: new Date("2024-01-01T00:00:06.000Z"), // +6s+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ // Sequential pattern: large, increasing parent-relative times+ expect(result.nodeMap.get("step-1")?.startTimeSinceParentStart).toBe(+ 1000,+ );+ expect(result.nodeMap.get("step-2")?.startTimeSinceParentStart).toBe(+ 3000,+ );+ expect(result.nodeMap.get("step-3")?.startTimeSinceParentStart).toBe(+ 6000,+ );+ });++ it("identifies parallel execution pattern", () => {+ const trace = createMockTrace({+ timestamp: new Date("2024-01-01T00:00:00.000Z"),+ });+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "parent",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ }),+ // Parallel children with small, similar delays+ createMockObservation({+ id: "parallel-1",+ parentObservationId: "parent",+ startTime: new Date("2024-01-01T00:00:00.050Z"), // +50ms+ }),+ createMockObservation({+ id: "parallel-2",+ parentObservationId: "parent",+ startTime: new Date("2024-01-01T00:00:00.055Z"), // +55ms+ }),+ createMockObservation({+ id: "parallel-3",+ parentObservationId: "parent",+ startTime: new Date("2024-01-01T00:00:00.060Z"), // +60ms+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ // Parallel pattern: small, similar parent-relative times+ expect(+ result.nodeMap.get("parallel-1")?.startTimeSinceParentStart,+ ).toBe(50);+ expect(+ result.nodeMap.get("parallel-2")?.startTimeSinceParentStart,+ ).toBe(55);+ expect(+ result.nodeMap.get("parallel-3")?.startTimeSinceParentStart,+ ).toBe(60);+ });++ it("handles mixed execution patterns", () => {+ const trace = createMockTrace({+ timestamp: new Date("2024-01-01T00:00:00.000Z"),+ });+ const observations: ObservationReturnType[] = [+ createMockObservation({+ id: "root",+ parentObservationId: null,+ startTime: new Date("2024-01-01T00:00:00.000Z"),+ }),+ // First child starts immediately+ createMockObservation({+ id: "immediate",+ parentObservationId: "root",+ startTime: new Date("2024-01-01T00:00:00.010Z"), // +10ms+ }),+ // Second child delayed+ createMockObservation({+ id: "delayed",+ parentObservationId: "root",+ startTime: new Date("2024-01-01T00:00:02.000Z"), // +2s+ }),+ // Nested children under "immediate" - parallel pattern+ createMockObservation({+ id: "nested-1",+ parentObservationId: "immediate",+ startTime: new Date("2024-01-01T00:00:00.100Z"), // +90ms from parent+ }),+ createMockObservation({+ id: "nested-2",+ parentObservationId: "immediate",+ startTime: new Date("2024-01-01T00:00:00.105Z"), // +95ms from parent+ }),+ ];++ const result = buildTraceUiData(trace, observations);++ // Immediate execution+ expect(result.nodeMap.get("immediate")?.startTimeSinceParentStart).toBe(+ 10,+ );+ // Delayed execution+ expect(result.nodeMap.get("delayed")?.startTimeSinceParentStart).toBe(+ 2000,+ );+ // Nested parallel execution+ expect(result.nodeMap.get("nested-1")?.startTimeSinceParentStart).toBe(+ 90,+ );+ expect(result.nodeMap.get("nested-2")?.startTimeSinceParentStart).toBe(+ 95,+ );++ // Verify depths+ expect(result.nodeMap.get("root")?.depth).toBe(0);+ expect(result.nodeMap.get("immediate")?.depth).toBe(1);+ expect(result.nodeMap.get("delayed")?.depth).toBe(1);+ expect(result.nodeMap.get("nested-1")?.depth).toBe(2);+ expect(result.nodeMap.get("nested-2")?.depth).toBe(2);+ });+ });+ });+});diff --git a/web/src/components/trace2/lib/tree-building.ts b/web/src/components/trace2/lib/tree-building.tsnew file mode 100644index 0000000000..0dfc1a1535--- /dev/null+++ b/web/src/components/trace2/lib/tree-building.ts@@ -0,0 +1,449 @@+/**+ * Tree building utilities for trace component.+ *+ * IMPLEMENTATION APPROACH:+ * Uses fully iterative algorithms (no recursion) to avoid stack overflow on deep trees (10k+ depth).+ *+ * Algorithm Overview:+ * 1. Filter observations by level threshold and sort by startTime+ * 2. Build dependency graph: Map-based parent-child relationships (O(N))+ * 3. Topological sort: Process nodes bottom-up (leaves first) using queue with index-based traversal+ * 4. Cost aggregation: Compute bottom-up during tree construction (children before parents)+ * 5. Flatten to searchItems: Iterative pre-order traversal using explicit stack+ *+ * Complexity: O(N) time, O(N) space - handles unlimited depth without stack overflow.+ *+ * Main export: buildTraceUiData() - builds tree, nodeMap, and searchItems from trace + observations.+ */++import { type TreeNode, type TraceSearchListItem } from "./types";+import { type ObservationReturnType } from "@/src/server/api/routers/traces";+import Decimal from "decimal.js";+import {+ type ObservationLevelType,+ ObservationLevel,+ type TraceDomain,+} from "@langfuse/shared";+import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";++type TraceType = Omit<+ WithStringifiedMetadata<TraceDomain>,+ "input" | "output"+> & {+ input: string | null;+ output: string | null;+ latency?: number;+};++/**+ * Processing node for iterative tree building.+ * Tracks parent-child relationships and processing state for bottom-up traversal.+ */+interface ProcessingNode {+ observation: ObservationReturnType;+ childrenIds: string[];+ inDegree: number; // Number of unprocessed children (for topological sort)+ depth: number; // Tree depth (calculated during graph building)+ treeNode?: TreeNode; // Set when node is processed+}++/**+ * Returns observation levels at or above the minimum level.+ */+function getObservationLevels(minLevel: ObservationLevelType | undefined) {+ const ascendingLevels = [+ ObservationLevel.DEBUG,+ ObservationLevel.DEFAULT,+ ObservationLevel.WARNING,+ ObservationLevel.ERROR,+ ];++ if (!minLevel) return ascendingLevels;++ const minLevelIndex = ascendingLevels.indexOf(minLevel);+ return ascendingLevels.slice(minLevelIndex);+}++/**+ * Filters and prepares observations for tree building.+ * Filters by minimum observation level, cleans orphaned parents, and sorts by startTime.+ * Returns flat array (nesting happens in buildDependencyGraph).+ */+function filterAndPrepareObservations(+ list: ObservationReturnType[],+ minLevel?: ObservationLevelType,+): {+ sortedObservations: ObservationReturnType[];+ hiddenObservationsCount: number;+} {+ if (list.length === 0)+ return { sortedObservations: [], hiddenObservationsCount: 0 };++ // Filter for observations with minimum level+ const mutableList = list.filter((o) =>+ getObservationLevels(minLevel).includes(o.level),+ );+ const hiddenObservationsCount = list.length - mutableList.length;++ // Build a Set of all observation IDs for O(1) lookup+ const observationIds = new Set(list.map((o) => o.id));++ // Remove parentObservationId if parent doesn't exist+ mutableList.forEach((observation) => {+ if (+ observation.parentObservationId &&+ !observationIds.has(observation.parentObservationId)+ ) {+ observation.parentObservationId = null;+ }+ });++ // Sort by start time+ const sortedObservations = mutableList.sort(+ (a, b) => a.startTime.getTime() - b.startTime.getTime(),+ );++ return {+ sortedObservations,+ hiddenObservationsCount,+ };+}++/**+ * Phase 2: Builds dependency graph for bottom-up tree construction.+ * Creates ProcessingNodes with parent-child relationships via IDs.+ * Calculates in-degrees for topological sort (children count per node).+ * Calculates depth for each node based on parent relationships.+ */+function buildDependencyGraph(sortedObservations: ObservationReturnType[]): {+ nodeRegistry: Map<string, ProcessingNode>;+ leafIds: string[];+} {+ const nodeRegistry = new Map<string, ProcessingNode>();++ // First pass: create all ProcessingNodes with initial depth+ for (const obs of sortedObservations) {+ nodeRegistry.set(obs.id, {+ observation: obs,+ childrenIds: [],+ inDegree: 0,+ depth: 0, // Will be calculated in third pass+ treeNode: undefined,+ });+ }++ // Second pass: build parent-child relationships+ for (const obs of sortedObservations) {+ if (obs.parentObservationId) {+ const parent = nodeRegistry.get(obs.parentObservationId);+ if (parent) {+ parent.childrenIds.push(obs.id);+ }+ }+ }++ // Third pass: calculate depth top-down using BFS+ const rootIds: string[] = [];+ for (const [id, node] of nodeRegistry) {+ if (!node.observation.parentObservationId) {+ rootIds.push(id);+ node.depth = 0;+ }+ }++ // BFS to propagate depth down the tree+ const queue = [...rootIds];+ let queueIndex = 0;+ while (queueIndex < queue.length) {+ const currentId = queue[queueIndex++];+ const currentNode = nodeRegistry.get(currentId)!;++ for (const childId of currentNode.childrenIds) {+ const childNode = nodeRegistry.get(childId)!;+ childNode.depth = currentNode.depth + 1;+ queue.push(childId);+ }+ }++ // Fourth pass: calculate in-degrees and identify leaf nodes+ // Note: Children are already in correct order because observations are pre-sorted+ // by startTime in filterAndPrepareObservations, and children are added in iteration order.+ const leafIds: string[] = [];+ for (const [id, node] of nodeRegistry) {+ // Set in-degree to children count (for topological sort)+ node.inDegree = node.childrenIds.length;++ // Track leaf nodes (no children = ready to process first)+ if (node.childrenIds.length === 0) {+ leafIds.push(id);+ }+ }++ return { nodeRegistry, leafIds };+}++/**+ * Phase 3: Builds TreeNodes bottom-up using topological sort.+ * Processes leaf nodes first, then parents once all children are processed.+ * Calculates costs bottom-up: node cost + aggregated children costs.+ * Also calculates temporal properties (startTimeSinceTrace, startTimeSinceParentStart) and depth.+ */+function buildTreeNodesBottomUp(+ nodeRegistry: Map<string, ProcessingNode>,+ leafIds: string[],+ nodeMap: Map<string, TreeNode>,+ traceStartTime: Date,+): string[] {+ // Queue starts with all leaf nodes (inDegree === 0)+ // Use index-based traversal instead of shift() for O(1) dequeue (shift is O(N))+ const queue = [...leafIds];+ let queueIndex = 0;+ const rootIds: string[] = [];++ while (queueIndex < queue.length) {+ const currentId = queue[queueIndex++];+ const currentNode = nodeRegistry.get(currentId)!;+ const obs = currentNode.observation;++ // Get child TreeNodes (already processed)+ const childTreeNodes: TreeNode[] = [];+ for (const childId of currentNode.childrenIds) {+ const childNode = nodeRegistry.get(childId)!;+ if (childNode.treeNode) {+ childTreeNodes.push(childNode.treeNode);+ }+ }++ // Calculate this node's own cost+ let nodeCost: Decimal | undefined;++ if (obs.totalCost != null) {+ const cost = new Decimal(obs.totalCost);+ if (!cost.isZero()) {+ nodeCost = cost;+ }+ } else if (obs.inputCost != null || obs.outputCost != null) {+ const inputCost =+ obs.inputCost != null ? new Decimal(obs.inputCost) : new Decimal(0);+ const outputCost =+ obs.outputCost != null ? new Decimal(obs.outputCost) : new Decimal(0);+ const combinedCost = inputCost.plus(outputCost);+ if (!combinedCost.isZero()) {+ nodeCost = combinedCost;+ }+ }++ // Sum children's total costs (already computed bottom-up)+ const childrenTotalCost = childTreeNodes.reduce<Decimal | undefined>(+ (acc, child) => {+ if (!child.totalCost) return acc;+ return acc ? acc.plus(child.totalCost) : child.totalCost;+ },+ undefined,+ );++ // Total = node cost + children costs+ const totalCost =+ nodeCost && childrenTotalCost+ ? nodeCost.plus(childrenTotalCost)+ : nodeCost || childrenTotalCost;++ // Calculate temporal and structural properties+ const startTimeSinceTrace =+ obs.startTime.getTime() - traceStartTime.getTime();++ let startTimeSinceParentStart: number | null = null;++ if (obs.parentObservationId) {+ const parentNode = nodeRegistry.get(obs.parentObservationId);+ if (parentNode) {+ startTimeSinceParentStart =+ obs.startTime.getTime() - parentNode.observation.startTime.getTime();+ }+ }++ // Use pre-calculated depth from ProcessingNode+ const depth = currentNode.depth;++ // Create TreeNode+ const treeNode: TreeNode = {+ id: obs.id,+ type: obs.type,+ name: obs.name ?? "",+ startTime: obs.startTime,+ endTime: obs.endTime,+ level: obs.level,+ children: childTreeNodes,+ inputUsage: obs.inputUsage,+ outputUsage: obs.outputUsage,+ totalUsage: obs.totalUsage,+ calculatedInputCost: obs.inputCost,+ calculatedOutputCost: obs.outputCost,+ calculatedTotalCost: obs.totalCost,+ parentObservationId: obs.parentObservationId,+ traceId: obs.traceId,+ totalCost,+ startTimeSinceTrace,+ startTimeSinceParentStart,+ depth,+ };++ // Store in registry and nodeMap+ currentNode.treeNode = treeNode;+ nodeMap.set(currentId, treeNode);++ // Decrement parent's in-degree and queue if ready+ if (obs.parentObservationId) {+ const parent = nodeRegistry.get(obs.parentObservationId);+ if (parent) {+ parent.inDegree--;+ if (parent.inDegree === 0) {+ queue.push(obs.parentObservationId);+ }+ }+ } else {+ // No parent = root observation+ rootIds.push(currentId);+ }+ }++ return rootIds;+}++/**+ * Builds hierarchical tree from trace and observations (ITERATIVE - optimal).+ * Uses topological sort for bottom-up cost aggregation.+ * Handles unlimited tree depth without stack overflow.+ */+function buildTraceTree(+ trace: TraceType,+ observations: ObservationReturnType[],+ minLevel?: ObservationLevelType,+): {+ tree: TreeNode;+ hiddenObservationsCount: number;+ nodeMap: Map<string, TreeNode>;+} {+ // Phase 1: Filter and prepare observations+ const { sortedObservations, hiddenObservationsCount } =+ filterAndPrepareObservations(observations, minLevel);++ // Handle empty case+ if (sortedObservations.length === 0) {+ const emptyTree: TreeNode = {+ id: `trace-${trace.id}`,+ type: "TRACE",+ name: trace.name ?? "",+ startTime: trace.timestamp,+ endTime: null,+ children: [],+ latency: trace.latency,+ totalCost: undefined,+ startTimeSinceTrace: 0,+ startTimeSinceParentStart: null,+ depth: -1,+ };+ const nodeMap = new Map<string, TreeNode>();+ nodeMap.set(emptyTree.id, emptyTree);+ return { tree: emptyTree, hiddenObservationsCount, nodeMap };+ }++ // Phase 2: Build dependency graph+ const { nodeRegistry, leafIds } = buildDependencyGraph(sortedObservations);++ // Phase 3: Build TreeNodes bottom-up with cost aggregation+ const nodeMap = new Map<string, TreeNode>();+ const rootIds = buildTreeNodesBottomUp(+ nodeRegistry,+ leafIds,+ nodeMap,+ trace.timestamp,+ );++ // Phase 4: Build trace root+ const rootTreeNodes: TreeNode[] = [];+ for (const rootId of rootIds) {+ const rootNode = nodeRegistry.get(rootId)!;+ if (rootNode.treeNode) {+ rootTreeNodes.push(rootNode.treeNode);+ }+ }++ // Calculate trace root total cost+ const traceTotalCost = rootTreeNodes.reduce<Decimal | undefined>(+ (acc, child) => {+ if (!child.totalCost) return acc;+ return acc ? acc.plus(child.totalCost) : child.totalCost;+ },+ undefined,+ );++ // Create trace root node+ const tree: TreeNode = {+ id: `trace-${trace.id}`,+ type: "TRACE",+ name: trace.name ?? "",+ startTime: trace.timestamp,+ endTime: null,+ children: rootTreeNodes,+ latency: trace.latency,+ totalCost: traceTotalCost,+ startTimeSinceTrace: 0,+ startTimeSinceParentStart: null,+ depth: -1,+ };++ nodeMap.set(tree.id, tree);++ return { tree, hiddenObservationsCount, nodeMap };+}++/**+ * Main entry point: builds complete UI data from trace and observations.+ *+ * Returns:+ * - tree: Hierarchical TreeNode structure with trace as root+ * - nodeMap: Map<id, TreeNode> for O(1) lookup+ * - searchItems: Flattened list for search/virtualized rendering+ * - hiddenObservationsCount: Number filtered by minLevel+ */+export function buildTraceUiData(+ trace: TraceType,+ observations: ObservationReturnType[],+ minLevel?: ObservationLevelType,+): {+ tree: TreeNode;+ hiddenObservationsCount: number;+ searchItems: TraceSearchListItem[];+ nodeMap: Map<string, TreeNode>;+} {+ const { tree, hiddenObservationsCount, nodeMap } = buildTraceTree(+ trace,+ observations,+ minLevel,+ );++ // Use pre-computed totals for heatmap scaling (computed in buildTreeNodesBottomUp)+ const rootTotalCost = tree.totalCost;+ const rootDuration = tree.latency ? tree.latency * 1000 : undefined;++ // Build flat search items list (iterative to avoid stack overflow on deep trees)+ const searchItems: TraceSearchListItem[] = [];+ const stack: TreeNode[] = [tree];++ while (stack.length > 0) {+ const node = stack.pop()!;+ searchItems.push({+ node,+ parentTotalCost: rootTotalCost,+ parentTotalDuration: rootDuration,+ observationId: node.type === "TRACE" ? undefined : node.id,+ });+ // Push children in reverse order to maintain depth-first left-to-right traversal+ for (let i = node.children.length - 1; i >= 0; i--) {+ stack.push(node.children[i]!);+ }+ }++ return { tree, hiddenObservationsCount, searchItems, nodeMap };+}diff --git a/web/src/components/trace2/lib/types.ts b/web/src/components/trace2/lib/types.tsnew file mode 100644index 0000000000..429a70c18a--- /dev/null+++ b/web/src/components/trace2/lib/types.ts@@ -0,0 +1,60 @@+/**+ * Core types for trace component tree structure.+ *+ * TreeNode: Unified node type representing both traces and observations in a hierarchical tree.+ * TraceSearchListItem: Flattened representation of tree nodes for search/list views.+ */++import { type ObservationType } from "@langfuse/shared";+import type Decimal from "decimal.js";++/**+ * Unified tree node type for trace tree component.+ * Represents both TRACE root nodes and OBSERVATION child nodes.+ */+export type TreeNode = {+ id: string;+ type: "TRACE" | ObservationType;+ name: string;+ startTime: Date;+ endTime?: Date | null;+ level?: string;+ children: TreeNode[];+ // Token usage+ inputUsage?: number | null;+ outputUsage?: number | null;+ totalUsage?: number | null;+ // Per-node cost from API+ calculatedInputCost?: number | null;+ calculatedOutputCost?: number | null;+ calculatedTotalCost?: number | null;+ // Pre-computed cost for this node + all descendants+ // Calculated bottom-up during tree construction for O(1) access+ totalCost?: Decimal;+ // Trace-specific properties (when type === 'TRACE')+ latency?: number;+ // Observation-specific properties (when type !== 'TRACE')+ parentObservationId?: string | null;+ traceId?: string;+ // Temporal and structural properties+ /** Milliseconds from trace start to this node's start time */+ startTimeSinceTrace: number;+ /** Milliseconds from parent's start to this node's start (null for root observations or trace root) */+ startTimeSinceParentStart: number | null;+ /** Tree depth: -1 for trace root, 0 for root observations, increases with nesting */+ depth: number;+};++/**+ * Flattened tree node for search list and virtualized rendering.+ * Contains parent-level totals for heatmap color scaling.+ */+export interface TraceSearchListItem {+ node: TreeNode;+ /** Root-level total cost for heatmap scaling */+ parentTotalCost?: Decimal;+ /** Root-level total duration for heatmap scaling */+ parentTotalDuration?: number;+ /** Observation ID for navigation (undefined for TRACE nodes) */+ observationId?: string;+}diff --git a/web/src/components/ui/switch.tsx b/web/src/components/ui/switch.tsxindex 04573776d4..2633e76d9f 100644--- a/web/src/components/ui/switch.tsx+++ b/web/src/components/ui/switch.tsx@@ -2,26 +2,54 @@import * as React from "react";import * as SwitchPrimitives from "@radix-ui/react-switch";+import { cva, type VariantProps } from "class-variance-authority";import { cn } from "@/src/utils/tailwind";+const switchVariants = cva(+ "peer inline-flex shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input dark:data-[state=unchecked]:bg-muted-foreground",+ {+ variants: {+ size: {+ default: "h-5 w-9",+ sm: "h-4 w-7",+ },+ },+ defaultVariants: {+ size: "default",+ },+ },+);++const switchThumbVariants = cva(+ "pointer-events-none block rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=unchecked]:translate-x-0",+ {+ variants: {+ size: {+ default: "h-4 w-4 data-[state=checked]:translate-x-4",+ sm: "h-3 w-3 data-[state=checked]:translate-x-3",+ },+ },+ defaultVariants: {+ size: "default",+ },+ },+);++interface SwitchProps+ extends React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>,+ VariantProps<typeof switchVariants> {}+const Switch = React.forwardRef<React.ElementRef<typeof SwitchPrimitives.Root>,- React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>->(({ className, ...props }, ref) => (+ SwitchProps+>(({ className, size, ...props }, ref) => (<SwitchPrimitives.Root- className={cn(- "peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input dark:data-[state=unchecked]:bg-muted-foreground",- className,- )}+ className={cn(switchVariants({ size, className }))}{...props}ref={ref}>- <SwitchPrimitives.Thumb- className={cn(- "pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0",- )}- />+ <SwitchPrimitives.Thumb className={cn(switchThumbVariants({ size }))} /></SwitchPrimitives.Root>));Switch.displayName = SwitchPrimitives.Root.displayName;diff --git a/web/src/pages/project/[projectId]/traces2/[traceId].tsx b/web/src/pages/project/[projectId]/traces2/[traceId].tsxnew file mode 100644index 0000000000..bfa4f298db--- /dev/null+++ b/web/src/pages/project/[projectId]/traces2/[traceId].tsx@@ -0,0 +1,14 @@+import { TracePage } from "@/src/components/trace2/TracePage";+import { useRouter } from "next/router";++export default function Trace() {+ const router = useRouter();+ const traceId = router.query.traceId as string;++ const timestamp =+ router.query.timestamp && typeof router.query.timestamp === "string"+ ? new Date(decodeURIComponent(router.query.timestamp))+ : undefined;++ return <TracePage traceId={traceId} timestamp={timestamp} />;+}diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.tsindex 67538a0c19..5cb3a15d55 100644--- a/web/src/server/api/routers/traces.ts+++ b/web/src/server/api/routers/traces.ts@@ -609,6 +609,9 @@ export const traceRouter = createTRPCRouter({traceId: z.string(),minStartTime: z.string(),maxStartTime: z.string(),+ // Optional fields for enforceTraceAccess middleware (supports public traces)+ timestamp: z.date().nullish(),+ fromTimestamp: z.date().nullish(),}),).query(async ({ input }): Promise<Required<AgentGraphDataResponse>[]> => {