🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(trace-ui): keep expand/collapse state across trace peeks (#9598)
Nimar01e4c57a559b
diff --git a/web/src/components/trace/JsonExpansionContext.tsx b/web/src/components/trace/JsonExpansionContext.tsxindex d207c118c5..cb2d4eb97c 100644--- a/web/src/components/trace/JsonExpansionContext.tsx+++ b/web/src/components/trace/JsonExpansionContext.tsx@@ -1,4 +1,5 @@-import { createContext, useContext, useState, useCallback } from "react";+import { createContext, useContext, useCallback } from "react";+import useSessionStorage from "@/src/components/useSessionStorage";// Context Provider to store expanded/collapsed state of JSONs across different JSONs with similar structure// Used for traces (input/output/metadata) but can be reused at other places.@@ -14,6 +15,7 @@ type JsonExpansionState = {input: ExpandedState;output: ExpandedState;metadata: ExpandedState;+ log: ExpandedState; // for the Trace Log View};type JsonExpansionContextType = {@@ -25,7 +27,7 @@ type JsonExpansionContextType = {};const JsonExpansionContext = createContext<JsonExpansionContextType>({- expansionState: { input: {}, output: {}, metadata: {} },+ expansionState: { input: {}, output: {}, metadata: {}, log: {} },setFieldExpansion: () => {},});@@ -36,11 +38,13 @@ export function JsonExpansionProvider({}: {children: React.ReactNode;}) {- const [expansionState, setExpansionState] = useState<JsonExpansionState>({- input: {},- output: {},- metadata: {},- });+ const [expansionState, setExpansionState] =+ useSessionStorage<JsonExpansionState>("jsonExpansionState", {+ input: {},+ output: {},+ metadata: {},+ log: {},+ });const setFieldExpansion = useCallback((@@ -52,7 +56,7 @@ export function JsonExpansionProvider({[field]: expansion,}));},- [],+ [setExpansionState],);return (diff --git a/web/src/components/trace/TraceLogView.tsx b/web/src/components/trace/TraceLogView.tsxindex af0fd84c5a..a49957733e 100644--- a/web/src/components/trace/TraceLogView.tsx+++ b/web/src/components/trace/TraceLogView.tsx@@ -5,6 +5,80 @@ 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/trace/JsonExpansionContext";++// for Json Expansion Context State (keeps expanded/collapsed state across traces)++// Remove observation ID from keys for persistent expansion state and convert hyphens to dots (PrettyJsonView internal format)+// Example: "natural-language-filter (abc12345)" -> "natural.language.filter"+const normalizeKey = (key: string): string => {+ return key.replace(/-/g, ".").replace(/\s*\([a-f0-9]{8}\)/, "");+};++// Convert normalized expansion state to actual state with observation IDs+const 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)+ const normalizedToActual = new Map<string, string[]>();+ observationKeys.forEach((actualKey) => {+ const normalized = normalizeKey(actualKey);+ if (!normalizedToActual.has(normalized)) {+ normalizedToActual.set(normalized, []);+ }+ // store the normalized+ 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;+};++// for session storage, convert current expansion state to normalized state+const 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;+};export const TraceLogView = ({observations,@@ -20,6 +94,7 @@ export const TraceLogView = ({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 viewconst observationsWithIO = useQueries({@@ -127,6 +202,18 @@ export const TraceLogView = ({}}, [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],+ );+return (<div className="flex h-full w-full flex-col overflow-hidden pr-3"><div className="mb-2 flex max-h-full min-h-0 w-full flex-col gap-2 overflow-y-auto">@@ -137,6 +224,11 @@ export const TraceLogView = ({currentView={currentView}isLoading={isLoading}showNullValues={false}+ externalExpansionState={denormalizedState}+ onExternalExpansionChange={(expansion) =>+ setFieldExpansion("log", normalizeExpansionState(expansion))+ }+ stickyTopLevelKey={true}/></div></div>diff --git a/web/src/components/trace/TracePreview.tsx b/web/src/components/trace/TracePreview.tsxindex 2678a85283..9150446810 100644--- a/web/src/components/trace/TracePreview.tsx+++ b/web/src/components/trace/TracePreview.tsx@@ -277,7 +277,7 @@ export const TracePreview = ({<TooltipContent className="text-xs">{isLogViewDisabled? `Log View is disabled for traces with more than 50 observations (this trace has ${observations.length})`- : "Shows all observations concatenated. Great for quickly scanning through them"}+ : "Shows all observations concatenated. Great for quickly scanning through them. Nullish values are omitted."}</TooltipContent></Tooltip></TabsBarTrigger>diff --git a/web/src/components/trace/index.tsx b/web/src/components/trace/index.tsxindex 77f8f43d36..b949630ebc 100644--- a/web/src/components/trace/index.tsx+++ b/web/src/components/trace/index.tsx@@ -19,7 +19,7 @@ import {PanelLeftClose,PanelLeftOpen,} from "lucide-react";-import { useCallback, useState, useMemo, useRef } from "react";+import { useCallback, useState, useMemo, useRef, useEffect } from "react";import { usePanelState } from "./hooks/usePanelState";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { TraceTimelineView } from "@/src/components/trace/TraceTimelineView";@@ -110,6 +110,19 @@ export function Trace(props: {);const [collapsedNodes, setCollapsedNodes] = useState<string[]>([]);+ // TODO: remove, kinda hacky+ // when user clicks Log View, we want to show them that you can collapse the tree panel+ const [shouldPulseToggle, setShouldPulseToggle] = useState(false);+ useEffect(() => {+ if (viewTab === "log") {+ setShouldPulseToggle(true);+ const timeout = setTimeout(() => {+ setShouldPulseToggle(false);+ }, 2000); // Pulse for 2 seconds+ return () => clearTimeout(timeout);+ }+ }, [viewTab]);+// initial panel sizes for graph resizingconst [timelineGraphSizes, setTimelineGraphSizes] = useLocalStorage("trace-detail-timeline-graph-vertical",@@ -354,7 +367,10 @@ export function Trace(props: {});}}title="Show trace tree"- className="h-10 w-10"+ className={cn(+ "h-10 w-10",+ shouldPulseToggle && "animate-pulse",+ )}><PanelLeftOpen className="h-4 w-4" /></Button>@@ -646,6 +662,7 @@ export function Trace(props: {? "Show trace tree": "Hide trace tree"}+ className={cn(shouldPulseToggle && "animate-pulse")}>{isTreePanelCollapsed ? (<PanelLeftOpen className="h-4 w-4" />diff --git a/web/src/components/ui/PrettyJsonView.tsx b/web/src/components/ui/PrettyJsonView.tsxindex 14419225b8..e2446ac5d7 100644--- a/web/src/components/ui/PrettyJsonView.tsx+++ b/web/src/components/ui/PrettyJsonView.tsx@@ -51,6 +51,7 @@ import {ValueCell,getValueStringLength,} from "@/src/components/table/ValueCell";+import { ItemBadge, type LangfuseItemType } from "@/src/components/ItemBadge";// Constants for table layoutconst INDENTATION_PER_LEVEL = 16;@@ -346,6 +347,7 @@ function JsonPrettyTable({smartDefaultsLevel,expandedCells,toggleCellExpansion,+ stickyTopLevelKey = false,}: {data: JsonTableRow[];expandAllRef?: React.MutableRefObject<(() => void) | null>;@@ -360,7 +362,30 @@ function JsonPrettyTable({smartDefaultsLevel?: number | null;expandedCells: Set<string>;toggleCellExpansion: (cellId: string) => void;+ stickyTopLevelKey?: boolean;}) {+ const headerRef = useRef<HTMLTableRowElement>(null);+ const topLevelRowRef = useRef<HTMLTableRowElement>(null);+ const [stickyOffsets, setStickyOffsets] = useState({ header: 32, row: 32 });++ // calculate height of top row to calculate offsets for other headings to not go beneath sticky rows+ useEffect(() => {+ if (stickyTopLevelKey && headerRef.current) {+ const headerHeight = headerRef.current.offsetHeight;++ // get first top-level row height (if it exists)+ let rowHeight = 32; // default fallback+ if (topLevelRowRef.current) {+ rowHeight = topLevelRowRef.current.offsetHeight;+ }++ setStickyOffsets({+ header: headerHeight,+ row: rowHeight,+ });+ }+ }, [stickyTopLevelKey, data, expanded]);+const columns: LangfuseColumnDef<JsonTableRow, unknown>[] = [{accessorKey: "key",@@ -377,6 +402,17 @@ function JsonPrettyTable({const valueLength = getValueStringLength(row.original.value);const isLongValue = valueLength > MAX_CELL_DISPLAY_CHARS / 3; // already long if we don't truncate+ const itemBadgeType =+ row.original.level === 0 &&+ row.original.value &&+ typeof row.original.value === "object" &&+ !Array.isArray(row.original.value) &&+ "type" in row.original.value &&+ typeof (row.original.value as any).type === "string" &&+ (row.original.value as any).type+ ? ((row.original.value as any).type as LangfuseItemType)+ : null;+const content = (<div className="flex items-start break-words"><div@@ -410,16 +446,36 @@ function JsonPrettyTable({className={`ml-1 ${MONO_TEXT_CLASSES} font-medium`}style={{ maxWidth: availableTextWidth }}>+ {itemBadgeType && (+ <span className="mr-1 inline-block align-middle">+ <ItemBadge type={itemBadgeType} isSmall={true} />+ </span>+ )}{row.original.key}</span></div>);- return isLongValue ? (- <div className="sticky top-0 py-1">{content}</div>- ) : (- content- );+ if (isLongValue) {+ // calculate sticky position based on level and stickyTopLevelKey setting+ let topPosition = "0";+ if (stickyTopLevelKey) {+ // Level 0: position below header+ // Level > 0: position below header + one top-level row+ topPosition =+ row.original.level === 0+ ? `${stickyOffsets.header}px`+ : `${stickyOffsets.header + stickyOffsets.row}px`;+ }++ return (+ <div className="sticky z-[5] py-1" style={{ top: topPosition }}>+ {content}+ </div>+ );+ }++ return content;},},{@@ -551,12 +607,19 @@ function JsonPrettyTable({<div className={cn("w-full", !noBorder && "rounded-sm border")}><Table><TableHeader>- {table.getHeaderGroups().map((headerGroup) => (- <TableRow key={headerGroup.id}>+ {table.getHeaderGroups().map((headerGroup, index) => (+ <TableRow+ key={headerGroup.id}+ ref={index === 0 ? headerRef : undefined}+ className={stickyTopLevelKey ? "sticky top-0 z-20" : ""}+ >{headerGroup.headers.map((header) => (<TableHeadkey={header.id}- className="h-8 bg-transparent px-2 py-1"+ className={cn(+ "h-8 px-2 py-1",+ stickyTopLevelKey ? "bg-background" : "bg-transparent",+ )}style={{ width: `${header.column.columnDef.size}%` }}>{header.isPlaceholder@@ -571,9 +634,14 @@ function JsonPrettyTable({))}</TableHeader><TableBody>- {table.getRowModel().rows.map((row) => (+ {table.getRowModel().rows.map((row, rowIndex) => (<TableRowkey={row.id}+ ref={+ rowIndex === 0 && row.original.level === 0+ ? topLevelRowRef+ : undefined+ }data-observation-id={row.id}onClick={() =>handleRowExpansion(@@ -583,15 +651,23 @@ function JsonPrettyTable({toggleCellExpansion,)}- className={+ className={cn(row.original.hasChildren ||- (!row.original.hasChildren &&- row.original.type !== "array" &&- row.original.type !== "object" &&- getValueStringLength(row.original.value) >- MAX_CELL_DISPLAY_CHARS)+ (!row.original.hasChildren &&+ row.original.type !== "array" &&+ row.original.type !== "object" &&+ getValueStringLength(row.original.value) >+ MAX_CELL_DISPLAY_CHARS)? "cursor-pointer"- : ""+ : "",+ row.original.level === 0 && stickyTopLevelKey+ ? "sticky z-10 bg-background shadow-sm"+ : "",+ )}+ style={+ row.original.level === 0 && stickyTopLevelKey+ ? { top: `${stickyOffsets.header}px` }+ : undefined}>{row.getVisibleCells().map((cell) => (@@ -628,6 +704,7 @@ export function PrettyJsonView(props: {expansion: Record<string, boolean> | boolean,) => void;showNullValues?: boolean;+ stickyTopLevelKey?: boolean;}) {const jsonDependency = useMemo(() =>@@ -1016,6 +1093,7 @@ export function PrettyJsonView(props: {smartDefaultsLevel={null}expandedCells={expandedCells}toggleCellExpansion={toggleCellExpansion}+ stickyTopLevelKey={props.stickyTopLevelKey}/>)}</div>