Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(ui): sessions view gets into infinite rerendering loop while translated with google translate (#14036)

Nikita Kabardincfcdc838c092
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 5ec2767ebc..e191454f85 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -794,6 +794,9 @@ importers:
zod:
specifier: 4.3.6
version: 4.3.6
+ zustand:
+ specifier: ^5.0.14
devDependencies:
'@jedmao/location':
specifier: ^3.0.0
@@ -11550,6 +11553,24 @@ packages:
resolution: {integrity: sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==}
+ resolution: {integrity: sha512-/8tAspM5LMPr28b3fwLYrtdj77ECpfZviaP75CMTnwO8ISyaE4GDIG/9rDDYq/cH9D2Xw2A2RXglLInmVBQB/g==}
+ engines: {node: '>=12.20.0'}
+ peerDependencies:
+ '@types/react': '>=18.0.0'
+ immer: '>=9.0.6'
+ react: '>=18.0.0'
+ use-sync-external-store: '>=1.2.0'
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ immer:
+ optional: true
+ react:
+ optional: true
+ use-sync-external-store:
+ optional: true
+
resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}
@@ -23908,4 +23929,11 @@ snapshots:
+ optionalDependencies:
+ '@types/react': 19.2.14
+ immer: 11.1.4
+ react: 19.2.4
+ use-sync-external-store: 1.6.0([email protected])
+
diff --git a/web/package.json b/web/package.json
index 0e117b0bb9..a52afdf66a 100644
--- a/web/package.json
+++ b/web/package.json
@@ -172,7 +172,8 @@
"uuid": "^14.0.0",
"vaul": "^1.1.2",
"vis-network": "^9.1.13",
- "zod": "^4.3.6"
+ "zod": "^4.3.6",
+ "zustand": "^5.0.14"
},
"devDependencies": {
"@jedmao/location": "^3.0.0",
diff --git a/web/src/components/session/LazySessionTraceEventsRow.tsx b/web/src/components/session/LazySessionTraceEventsRow.tsx
new file mode 100644
index 0000000000..c7b7af4331
--- /dev/null
+++ b/web/src/components/session/LazySessionTraceEventsRow.tsx
@@ -0,0 +1,87 @@
+import React from "react";
+import {
+ TraceEventsRow,
+ TraceEventsSkeleton,
+} from "@/src/components/session/TraceEventsRow";
+import { useSessionDetailStore } from "@/src/components/session/SessionDetailStoreProvider";
+import { type RouterOutputs } from "@/src/utils/api";
+import { type FilterState } from "@langfuse/shared";
+
+type LazySessionTraceEventsRowProps = {
+ trace: RouterOutputs["sessions"]["tracesFromEvents"][number];
+ projectId: string;
+ sessionId: string;
+ openPeek: (id: string, row: any) => void;
+ index: number;
+ traceCommentCounts: Map<string, number> | undefined;
+ filterState: FilterState;
+ hideTracePanel?: boolean;
+};
+
+const LazySessionTraceEventsRowInner = (
+ props: LazySessionTraceEventsRowProps,
+) => {
+ const { index, ...rowProps } = props;
+ const shouldLoad = useSessionDetailStore((state) =>
+ Boolean(state.loadedTraceIds[props.trace.id]),
+ );
+ const showCorrections = useSessionDetailStore(
+ (state) => state.showCorrections,
+ );
+ const markTraceLoaded = useSessionDetailStore(
+ (state) => state.actions.markTraceLoaded,
+ );
+ const internalRef = React.useRef<HTMLDivElement>(null);
+
+ React.useEffect(() => {
+ if (!internalRef.current || shouldLoad) return;
+ return observe(internalRef.current, () => markTraceLoaded(props.trace.id));
+ }, [markTraceLoaded, shouldLoad, props.trace.id]);
+
+ const setRowRef = React.useCallback((node: HTMLDivElement | null) => {
+ internalRef.current = node;
+ }, []);
+
+ return (
+ <div ref={setRowRef} className="pb-3" data-session-row-index={index}>
+ {shouldLoad ? (
+ <TraceEventsRow {...rowProps} showCorrections={showCorrections} />
+ ) : (
+ <TraceEventsSkeleton />
+ )}
+ </div>
+ );
+};
+
+LazySessionTraceEventsRowInner.displayName = "LazySessionTraceEventsRowInner";
+export const LazySessionTraceEventsRow = React.memo(
+ LazySessionTraceEventsRowInner,
+);
+LazySessionTraceEventsRow.displayName = "LazySessionTraceEventsRow";
+
+const listeners = new Map<Element, () => void>();
+let sharedObserver: IntersectionObserver;
+
+function observe(element: Element, callback: () => void) {
+ if (!sharedObserver) {
+ sharedObserver = new IntersectionObserver(
+ (entries) => {
+ entries.forEach((entry) => {
+ if (entry.isIntersecting) {
+ const cb = listeners.get(entry.target);
+ cb?.();
+ }
+ });
+ },
+ { rootMargin: "400px" },
+ );
+ }
+
+ listeners.set(element, callback);
+ sharedObserver.observe(element);
+
+ return () => {
+ listeners.delete(element);
+ sharedObserver.unobserve(element);
+ };
+}
diff --git a/web/src/components/session/SessionDetailStoreProvider.tsx b/web/src/components/session/SessionDetailStoreProvider.tsx
new file mode 100644
index 0000000000..add81f02ab
--- /dev/null
+++ b/web/src/components/session/SessionDetailStoreProvider.tsx
@@ -0,0 +1,38 @@
+import { createContext, useContext, type ReactNode } from "react";
+import { useStore } from "zustand";
+import {
+ type SessionDetailStore,
+ type SessionDetailStoreState,
+} from "@/src/components/session/sessionDetailStore";
+
+const SessionDetailStoreContext = createContext<SessionDetailStore | null>(
+ null,
+);
+
+export function SessionDetailStoreProvider({
+ children,
+ store,
+}: {
+ children: ReactNode;
+ store: SessionDetailStore;
+}) {
+ return (
+ <SessionDetailStoreContext.Provider value={store}>
+ {children}
+ </SessionDetailStoreContext.Provider>
+ );
+}
+
+export function useSessionDetailStore<TValue>(
+ selector: (state: SessionDetailStoreState) => TValue,
+): TValue {
+ const store = useContext(SessionDetailStoreContext);
+
+ if (!store) {
+ throw new Error(
+ "useSessionDetailStore must be used within SessionDetailStoreProvider",
+ );
+ }
+
+ return useStore(store, selector);
+}
diff --git a/web/src/components/session/SessionVirtualizedRow.tsx b/web/src/components/session/SessionVirtualizedRow.tsx
new file mode 100644
index 0000000000..24a21d9108
--- /dev/null
+++ b/web/src/components/session/SessionVirtualizedRow.tsx
@@ -0,0 +1,43 @@
+import { type ReactNode } from "react";
+import { type VirtualItem, type Virtualizer } from "@tanstack/react-virtual";
+import { useStableVirtualRowMeasurement } from "@/src/components/session/useStableVirtualRowMeasurement";
+
+export function SessionVirtualizedRow({
+ children,
+ itemKey,
+ measurementKey = itemKey,
+ source,
+ virtualItem,
+ virtualizer,
+}: {
+ children: ReactNode;
+ itemKey: string | number;
+ measurementKey?: string | number;
+ source: "legacy" | "events";
+ virtualItem: VirtualItem;
+ virtualizer: Virtualizer<HTMLDivElement, Element>;
+}) {
+ const measurementRef = useStableVirtualRowMeasurement({
+ index: virtualItem.index,
+ itemKey: measurementKey,
+ isScrolling: Boolean(virtualizer.isScrolling),
+ virtualizer,
+ });
+
+ return (
+ <div
+ ref={measurementRef}
+ data-index={virtualItem.index}
+ data-session-virtualizer-row={source}
+ style={{
+ position: "absolute",
+ top: 0,
+ left: 0,
+ width: "100%",
+ transform: `translateY(${virtualItem.start}px)`,
+ }}
+ >
+ {children}
+ </div>
+ );
+}
diff --git a/web/src/components/session/TraceEventsRow.tsx b/web/src/components/session/TraceEventsRow.tsx
index a17d5a34e8..3dade37077 100644
--- a/web/src/components/session/TraceEventsRow.tsx
+++ b/web/src/components/session/TraceEventsRow.tsx
@@ -9,12 +9,12 @@ import { AnnotateDrawer } from "@/src/features/scores/components/AnnotateDrawer"
import { CommentDrawerButton } from "@/src/features/comments/CommentDrawerButton";
import { ItemBadge } from "@/src/components/ItemBadge";
import { NewDatasetItemFromTraceId } from "@/src/components/session/NewDatasetItemFromTrace";
-import { AnnotationQueueObjectType, type FilterState } from "@langfuse/shared";
+import { type FilterState } from "@langfuse/shared";
import { CreateNewAnnotationQueueItem } from "@/src/features/annotation-queues/components/CreateNewAnnotationQueueItem";
import { IOPreview } from "@/src/components/trace/components/IOPreview/IOPreview";
import { api } from "@/src/utils/api";
-const TraceSkeleton = () => {
+export const TraceEventsSkeleton = () => {
return (
<Card className="border-border shadow-none">
<div className="flex h-64 items-center justify-center p-4">
@@ -24,6 +24,32 @@ const TraceSkeleton = () => {
);
};
+type LazyTraceEventsRowProps = {
+ trace: RouterOutputs["sessions"]["tracesFromEvents"][number];
+ projectId: string;
+ sessionId: string;
+ openPeek: (id: string, row: any) => void;
+ index: number;
+ traceCommentCounts: Map<string, number> | undefined;
+ showCorrections: boolean;
+ filterState: FilterState;
+ hideTracePanel?: boolean;
+};
+
+const areLazyTraceEventsRowPropsEqual = (
+ previous: LazyTraceEventsRowProps,
+ next: LazyTraceEventsRowProps,
+) =>
+ previous.trace === next.trace &&
+ previous.projectId === next.projectId &&
+ previous.sessionId === next.sessionId &&
+ previous.openPeek === next.openPeek &&
+ previous.index === next.index &&
+ previous.traceCommentCounts === next.traceCommentCounts &&
+ previous.showCorrections === next.showCorrections &&
+ previous.filterState === next.filterState &&
+ previous.hideTracePanel === next.hideTracePanel;
+
export const TraceEventsRow = React.memo(
({
trace,
@@ -176,7 +202,7 @@ export const TraceEventsRow = React.memo(
<CreateNewAnnotationQueueItem
projectId={projectId}
objectId={trace.id}
- objectType={AnnotationQueueObjectType.TRACE}
+ objectType="TRACE"
variant="outline"
/>
</div>
@@ -206,22 +232,8 @@ export const TraceEventsRow = React.memo(
TraceEventsRow.displayName = "TraceEventsRow";
-export const LazyTraceEventsRow = React.forwardRef<
- HTMLDivElement,
- {
- trace: RouterOutputs["sessions"]["tracesFromEvents"][number];
- projectId: string;
- sessionId: string;
- openPeek: (id: string, row: any) => void;
- index: number;
- traceCommentCounts: Map<string, number> | undefined;
- showCorrections: boolean;
- filterState: FilterState;
- hideTracePanel?: boolean;
- onLoad?: (index: number) => void;
- }
->((props, measureRef) => {
- const { index, onLoad: onLoad, ...cardProps } = props;
+const LazyTraceEventsRowInner = (props: LazyTraceEventsRowProps) => {
+ const { index, ...cardProps } = props;
const [shouldLoad, setShouldLoad] = React.useState(false);
const internalRef = React.useRef<HTMLDivElement>(null);
@@ -230,28 +242,22 @@ export const LazyTraceEventsRow = React.forwardRef<
return observe(internalRef.current, () => setShouldLoad(true));
}, [shouldLoad]);
- React.useLayoutEffect(() => {
- if (shouldLoad && onLoad) {
- onLoad(index);
- }
- }, [shouldLoad, onLoad, index]);
-
- const combinedRef = React.useCallback(
- (node: HTMLDivElement | null) => {
- internalRef.current = node;
- if (typeof measureRef === "function") measureRef(node);
- else if (measureRef) measureRef.current = node;
- },
- [measureRef],
- );
+ const setRowRef = React.useCallback((node: HTMLDivElement | null) => {
+ internalRef.current = node;
+ }, []);
return (
- <div ref={combinedRef} className="pb-3" data-index={index}>
- {shouldLoad ? <TraceEventsRow {...cardProps} /> : <TraceSkeleton />}
+ <div ref={setRowRef} className="pb-3" data-session-row-index={index}>
+ {shouldLoad ? <TraceEventsRow {...cardProps} /> : <TraceEventsSkeleton />}
</div>
);
-});
+};
+LazyTraceEventsRowInner.displayName = "LazyTraceEventsRowInner";
+export const LazyTraceEventsRow = React.memo(
+ LazyTraceEventsRowInner,
+ areLazyTraceEventsRowPropsEqual,
+);
LazyTraceEventsRow.displayName = "LazyTraceEventsRow";
const listeners = new Map<Element, () => void>();
diff --git a/web/src/components/session/TraceRow.tsx b/web/src/components/session/TraceRow.tsx
index 26fc4fc132..4d1a62d7eb 100644
--- a/web/src/components/session/TraceRow.tsx
+++ b/web/src/components/session/TraceRow.tsx
@@ -5,21 +5,14 @@ import { Card } from "@/src/components/ui/card";
import { type RouterOutputs } from "@/src/utils/api";
import { getNumberFromMap } from "@/src/utils/map-utils";
import Link from "next/link";
-import React, {
- useEffect,
- useState,
- useCallback,
- useRef,
- useLayoutEffect,
-} from "react";
+import React, { useEffect, useCallback, useRef } from "react";
import { AnnotateDrawer } from "@/src/features/scores/components/AnnotateDrawer";
import { CommentDrawerButton } from "@/src/features/comments/CommentDrawerButton";
import { ItemBadge } from "@/src/components/ItemBadge";
import { NewDatasetItemFromTraceId } from "@/src/components/session/NewDatasetItemFromTrace";
-import { AnnotationQueueObjectType } from "@langfuse/shared";
import { CreateNewAnnotationQueueItem } from "@/src/features/annotation-queues/components/CreateNewAnnotationQueueItem";
+import { useSessionDetailStore } from "@/src/components/session/SessionDetailStoreProvider";
-// Skeleton placeholder for trace cards
const TraceSkeleton = () => {
return (
<Card className="border-border shadow-none">
@@ -30,7 +23,24 @@ const TraceSkeleton = () => {
);
};
-// Trace card with all the heavy content (memoized to prevent unnecessary re-renders)
+type LazyTraceRowProps = {
+ trace: RouterOutputs["sessions"]["byIdWithScores"]["traces"][number];
+ projectId: string;
+ openPeek: (id: string, row: any) => void;
+ index: number;
+ traceCommentCounts: Map<string, number> | undefined;
+};
+
+const areLazyTraceRowPropsEqual = (
+ previous: LazyTraceRowProps,
+ next: LazyTraceRowProps,
+) =>
+ previous.trace === next.trace &&
+ previous.projectId === next.projectId &&
+ previous.openPeek === next.openPeek &&
+ previous.index === next.index &&
+ previous.traceCommentCounts === next.traceCommentCounts;
+
const TraceRow = React.memo(
({
trace,
@@ -53,6 +63,7 @@ const TraceRow = React.memo(
traceId={trace.id}
projectId={projectId}
timestamp={new Date(trace.timestamp)}
+ environment={trace.environment}
showCorrections={showCorrections}
/>
</div>
@@ -108,7 +119,7 @@ const TraceRow = React.memo(
<CreateNewAnnotationQueueItem
projectId={projectId}
objectId={trace.id}
- objectType={AnnotationQueueObjectType.TRACE}
+ objectType="TRACE"
variant="outline"
/>
</div>
@@ -135,24 +146,17 @@ const TraceRow = React.memo(
);
TraceRow.displayName = "TraceRow";
-/**
- * Progressive hydration wrapper for trace rows in virtualized lists.
- * Renders a cheap skeleton initially, then swaps to the full TraceRow when scrolled into view.
- * This prevents layout thrashing by decoupling virtualization (positioning) from heavy content rendering.
- * The virtualizer measures the skeleton first, then remeasures once after loading completes.
- */
const listeners = new Map<Element, () => void>();
let sharedObserver: IntersectionObserver;
function observe(element: Element, callback: () => void) {
- // Lazy-init the observer only once
if (!sharedObserver) {
sharedObserver = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const cb = listeners.get(entry.target);
- cb?.(); // Run the callback
+ cb?.();
}
});
},
@@ -163,53 +167,36 @@ function observe(element: Element, callback: () => void) {
listeners.set(element, callback);
sharedObserver.observe(element);
- // Return simple cleanup function
return () => {
listeners.delete(element);
sharedObserver.unobserve(element);
};
}
-export const LazyTraceRow = React.forwardRef<
- HTMLDivElement,
- {
- trace: RouterOutputs["sessions"]["byIdWithScores"]["traces"][number];
- projectId: string;
- openPeek: (id: string, row: any) => void;
- index: number;
- traceCommentCounts: Map<string, number> | undefined;
- showCorrections: boolean;
- onLoad?: (index: number) => void;
- }
->((props, measureRef) => {
- const { index, onLoad: onLoad, showCorrections, ...cardProps } = props;
- const [shouldLoad, setShouldLoad] = useState(false);
+const LazyTraceRowInner = (props: LazyTraceRowProps) => {
+ const { index, ...cardProps } = props;
+ const shouldLoad = useSessionDetailStore((state) =>
+ Boolean(state.loadedTraceIds[props.trace.id]),
+ );
+ const showCorrections = useSessionDetailStore(
+ (state) => state.showCorrections,
+ );
+ const markTraceLoaded = useSessionDetailStore(
+ (state) => state.actions.markTraceLoaded,
+ );
const internalRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!internalRef.current || shouldLoad) return;
- return observe(internalRef.current, () => setShouldLoad(true));
- }, [shouldLoad]);
+ return observe(internalRef.current, () => markTraceLoaded(props.trace.id));
+ }, [markTraceLoaded, shouldLoad, props.trace.id]);
- // Notify virtualizer when content changes (fixes height)
- useLayoutEffect(() => {
- if (shouldLoad && onLoad) {
- onLoad(index);
- }
- }, [shouldLoad, onLoad, index]);
-
- // Merge refs (Virtualizer + Local)
- const combinedRef = useCallback(
- (node: HTMLDivElement | null) => {
- internalRef.current = node;
- if (typeof measureRef === "function") measureRef(node);
- else if (measureRef) measureRef.current = node;
- },
- [measureRef],
- );
+ const setRowRef = useCallback((node: HTMLDivElement | null) => {
+ internalRef.current = node;
+ }, []);
return (
- <div ref={combinedRef} className="pb-3">
+ <div ref={setRowRef} className="pb-3" data-session-row-index={index}>
{shouldLoad ? (
<TraceRow showCorrections={showCorrections} {...cardProps} />
) : (
@@ -217,6 +204,11 @@ export const LazyTraceRow = React.forwardRef<
)}
</div>
);
-});
+};
+LazyTraceRowInner.displayName = "LazyTraceRowInner";
+export const LazyTraceRow = React.memo(
+ LazyTraceRowInner,
+ areLazyTraceRowPropsEqual,
+);
LazyTraceRow.displayName = "LazyTraceRow";
diff --git a/web/src/components/session/actions/downloadSessionAsJson.ts b/web/src/components/session/actions/downloadSessionAsJson.ts
new file mode 100644
index 0000000000..0c9e4b0998
--- /dev/null
+++ b/web/src/components/session/actions/downloadSessionAsJson.ts
@@ -0,0 +1,102 @@
+import { type RouterOutputs } from "@/src/utils/api";
+
+type SessionData = RouterOutputs["sessions"]["byIdWithScores"];
+type SessionTrace = NonNullable<SessionData>["traces"][number];
+type SessionComments = RouterOutputs["comments"]["getByObjectId"];
+type TraceCommentsByTraceId =
+ RouterOutputs["comments"]["getTraceCommentsBySessionId"];
+
+type RefetchSessionComments = () => Promise<{
+ data?: SessionComments;
+}>;
+
+type FetchTraceComments = (input: {
+ projectId: string;
+ sessionId: string;
+}) => Promise<TraceCommentsByTraceId>;
+
+type CaptureSessionEvent = (
+ eventName: "session_detail:download_button_click",
+) => void;
+
+export function buildSessionExportData({
+ session,
+ sessionComments,
+ traceCommentsByTraceId,
+}: {
+ session: SessionData | undefined;
+ sessionComments: SessionComments | undefined;
+ traceCommentsByTraceId: TraceCommentsByTraceId;
+}) {
+ if (!session) {
+ return {
+ comments: sessionComments ?? [],
+ };
+ }
+
+ return {
+ ...session,
+ traces: session.traces.map((trace: SessionTrace) => ({
+ ...trace,
+ comments: traceCommentsByTraceId[trace.id] ?? [],
+ })),
+ comments: sessionComments ?? [],
+ };
+}
+
+function downloadJsonFile({
+ data,
+ fileName,
+}: {
+ data: unknown;
+ fileName: string;
+}) {
+ const jsonString = JSON.stringify(data, null, 2);
+ const blob = new Blob([jsonString], {
+ type: "application/json; charset=utf-8",
+ });
+ const url = URL.createObjectURL(blob);
+
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = fileName;
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ URL.revokeObjectURL(url);
+}
+
+export async function downloadSessionAsJson({
+ capture,
+ fetchTraceComments,
+ projectId,
+ refetchSessionComments,
+ session,
+ sessionId,
+}: {
+ capture: CaptureSessionEvent;
+ fetchTraceComments: FetchTraceComments;
+ projectId: string;
+ refetchSessionComments: RefetchSessionComments;
+ session: SessionData | undefined;
+ sessionId: string;
+}) {
+ const [sessionCommentsData, traceCommentsByTraceId] = await Promise.all([
+ refetchSessionComments(),
+ fetchTraceComments({
+ projectId,
+ sessionId,
+ }),
+ ]);
+
+ downloadJsonFile({
+ data: buildSessionExportData({
+ session,
+ sessionComments: sessionCommentsData.data,
+ traceCommentsByTraceId,
+ }),
+ fileName: `session-${sessionId}.json`,
+ });
+
+ capture("session_detail:download_button_click");
+}
diff --git a/web/src/components/session/index.tsx b/web/src/components/session/index.tsx
index 91d288b29d..d1562c7052 100644
--- a/web/src/components/session/index.tsx
+++ b/web/src/components/session/index.tsx
@@ -6,10 +6,7 @@ import { IOPreview } from "@/src/components/trace/components/IOPreview/IOPreview
import { JsonSkeleton } from "@/src/components/ui/CodeJsonViewer";
import { Badge } from "@/src/components/ui/badge";
import { DetailPageNav } from "@/src/features/navigate-detail-pages/DetailPageNav";
-import {
- type ListEntry,
- useDetailPageLists,
-} from "@/src/features/navigate-detail-pages/context";
+import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";
import { api } from "@/src/utils/api";
import { usdFormatter } from "@/src/utils/numbers";
import { getNumberFromMap } from "@/src/utils/map-utils";
@@ -32,7 +29,6 @@ import {
import { ScrollArea } from "@/src/components/ui/scroll-area";
import { Label } from "@/src/components/ui/label";
import {
- AnnotationQueueObjectType,
type ColumnDefinition,
type FilterState,
type ScoreDomain,
@@ -46,7 +42,7 @@ import { LazyTraceRow } from "@/src/components/session/TraceRow";
import { useParsedTrace } from "@/src/hooks/useParsedTrace";
import useLocalStorage from "@/src/components/useLocalStorage";
import { Switch } from "@/src/components/ui/switch";
-import { LazyTraceEventsRow } from "@/src/components/session/TraceEventsRow";
+import { LazySessionTraceEventsRow } from "@/src/components/session/LazySessionTraceEventsRow";
import { observationEventsFilterConfig } from "@/src/features/events/config/filter-config";
import { useEventsFilterOptions } from "@/src/features/events/hooks/useEventsFilterOptions";
import { normalizeLegacySessionPositionInTraceFilters } from "@/src/components/session/session-position-in-trace";
@@ -72,24 +68,25 @@ import {
type SessionDetailSystemPreset,
getSessionDetailPresetToApply,
} from "@/src/components/session/session-detail-presets";
+import { downloadSessionAsJson } from "@/src/components/session/actions/downloadSessionAsJson";
+import { SessionDetailStoreProvider } from "@/src/components/session/SessionDetailStoreProvider";
+import { SessionVirtualizedRow } from "@/src/components/session/SessionVirtualizedRow";
+import { createSessionDetailStore } from "@/src/components/session/sessionDetailStore";
+import {
+ areDetailPageListsEqual,
+ asCommentCounts,
+ getStringFilterOptions,
+ isMultiValueOptionRecord,
+ type EventFilterOptions,
+ type EventSessionTrace,
+ type LegacySessionTrace,
+} from "@/src/components/session/sessionDetailPageTypes";
// some projects have thousands of users in a session, paginate to avoid rendering all at once
const INITIAL_USERS_DISPLAY_COUNT = 10;
const USERS_PER_PAGE_IN_POPOVER = 50;
-
-const areDetailPageListsEqual = (
- left: ListEntry[] | undefined,
- right: ListEntry[] | undefined,
-) => {
- if (left === right) return true;
- if (!left || !right || left.length !== right.length) return false;
- return left.every((entry, index) => {
- const other = right[index];
- if (entry.id !== other?.id) return false;
- if (!entry.params && !other?.params) return true;
- return JSON.stringify(entry.params) === JSON.stringify(other?.params);
- });
-};
+// Keep this near TanStack's default to avoid waking too many lazy row loaders.
+const SESSION_VIRTUALIZER_OVERSCAN = 5;
export function SessionUsers({
projectId,
@@ -229,6 +226,30 @@ export const SessionPage: React.FC<{
"showCorrections",
false,
);
+ const [sessionDetailStore] = useState(() =>
+ createSessionDetailStore({
+ initialSessionId: sessionId,
+ initialShowCorrections: showCorrections,
+ }),
+ );
+
+ useEffect(() => {
+ sessionDetailStore.getState().actions.resetForSession(sessionId);
+ }, [sessionDetailStore, sessionId]);
+
+ useEffect(() => {
+ sessionDetailStore.getState().actions.setShowCorrections(showCorrections);
+ }, [sessionDetailStore, showCorrections]);
+
+ const setShowCorrectionsForSession = useCallback(
+ (nextShowCorrections: boolean) => {
+ setShowCorrections(nextShowCorrections);
+ sessionDetailStore
+ .getState()
+ .actions.setShowCorrections(nextShowCorrections);
+ },
+ [sessionDetailStore, setShowCorrections],
+ );
const sessionComments = api.comments.getByObjectId.useQuery({
projectId,
@@ -236,64 +257,35 @@ export const SessionPage: React.FC<{
objectType: "SESSION",
});
- const downloadSessionAsJson = useCallback(async () => {
- // Fetch fresh session and trace comments data
- const [sessionCommentsData, traceCommentsData] = await Promise.all([
- sessionComments.refetch(),
- utils.comments.getTraceCommentsBySessionId.fetch({
- projectId,
- sessionId,
- }),
- ]);
-
- // Add comments to each trace
- const sessionWithTraceComments = session.data
- ? {
- ...session.data,
- traces: session.data.traces.map((trace) => ({
- ...trace,
- comments: traceCommentsData[trace.id] ?? [],
- })),
- }
- : session.data;
-
- const exportData = {
- ...sessionWithTraceComments,
- comments: sessionCommentsData.data ?? [],
- };
-
- const jsonString = JSON.stringify(exportData, null, 2);
- const blob = new Blob([jsonString], {
- type: "application/json; charset=utf-8",
+ const onDownloadSessionAsJson = useCallback(async () => {
+ await downloadSessionAsJson({
+ capture,
+ fetchTraceComments: utils.comments.getTraceCommentsBySessionId.fetch,
+ projectId,
+ refetchSessionComments: sessionComments.refetch,
+ session: session.data,
+ sessionId,
});
- const url = URL.createObjectURL(blob);
-
- const link = document.createElement("a");
- link.href = url;
- link.download = `session-${sessionId}.json`;
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- URL.revokeObjectURL(url);
-
- capture("session_detail:download_button_click");
}, [session.data, sessionId, projectId, capture, sessionComments, utils]);
- const { openPeek, closePeek, resolveDetailNavigationPath, expandPeek } =
- usePeekNavigation({
+ const peekNavigationConfig = React.useMemo(
+ () => ({
expandConfig: {
- // Expand peeked traces to the trace detail route; sessions list traces
basePath: `/project/${projectId}/traces`,
},
queryParams: ["observation", "display", "timestamp"],
extractParamsValuesFromRow: (row: any) => ({
timestamp: row.timestamp.toISOString(),
}),
- });
+ }),
+ [projectId],
+ );
+ const { openPeek, closePeek, resolveDetailNavigationPath, expandPeek } =
+ usePeekNavigation(peekNavigationConfig);
useEffect(() => {
if (!session.isSuccess) return;
- const nextList = session.data.traces.map((t) => ({
+ const nextList = session.data.traces.map((t: LegacySessionTrace) => ({
id: t.id,
params: { timestamp: t.timestamp.toISOString() },
}));
@@ -320,18 +312,14 @@ export const SessionPage: React.FC<{
{ enabled: session.isSuccess && userSession.status === "authenticated" },
);
- // Virtualizer measures cheap skeleton, then updates once when hydrated
const virtualizer = useVirtualizer({
count: session.data?.traces.length ?? 0,
getScrollElement: () => parentRef.current,
estimateSize: () => 300,
- overscan: 1, // Render 1 item above/below viewport
+ overscan: SESSION_VIRTUALIZER_OVERSCAN,
getItemKey: (index) => session.data?.traces[index]?.id ?? index,
- measureElement:
- typeof window !== "undefined"
- ? (element) => element.getBoundingClientRect().height
- : undefined,
});
+ const virtualItems = virtualizer.getVirtualItems();
if (session.error?.data?.code === "UNAUTHORIZED")
return <ErrorPage message="You do not have access to this session." />;
@@ -349,168 +337,159 @@ export const SessionPage: React.FC<{
);
return (
- <Page
- headerProps={{
- title: sessionId,
- itemType: "SESSION",
- breadcrumb: [
- {
- name: "Sessions",
- href: `/project/${projectId}/sessions`,
- },
- ],
- actionButtonsLeft: (
- <div className="flex items-center gap-0">
- <StarSessionToggle
- key="star"
- projectId={projectId}
- sessionId={sessionId}
- value={session.data?.bookmarked ?? false}
- size="icon-xs"
- />
- <PublishSessionSwitch
- projectId={projectId}
- sessionId={sessionId}
- isPublic={session.data?.public ?? false}
- key="publish"
- size="icon-xs"
- />
- </div>
- ),
- actionButtonsRight: (
- <>
- {!router.query.peek && (
- <DetailPageNav
- key="nav"
- currentId={encodeURIComponent(sessionId)}
- path={(entry) =>
- `/project/${projectId}/sessions/${encodeURIComponent(entry.id)}`
- }
- listKey="sessions"
- />
- )}
- <Button
- variant="outline"
- size="icon"
- onClick={downloadSessionAsJson}
- title="Download session as JSON"
- >
- <Download className="h-4 w-4" />
- </Button>
- <CommentDrawerButton
- key="comment"
- variant="outline"
- projectId={projectId}
- objectId={sessionId}
- objectType="SESSION"
- count={getNumberFromMap(sessionCommentCounts.data, sessionId)}
- />
- <div className="flex items-start">
- <AnnotateDrawer
+ <SessionDetailStoreProvider store={sessionDetailStore}>
+ <Page
+ headerProps={{
+ title: sessionId,
+ itemType: "SESSION",
+ breadcrumb: [
+ {
+ name: "Sessions",
+ href: `/project/${projectId}/sessions`,
+ },
+ ],
+ actionButtonsLeft: (
+ <div className="flex items-center gap-0">
+ <StarSessionToggle
+ key="star"
projectId={projectId}
- scoreTarget={{
- type: "session",
- sessionId,
- }}
- scores={session.data?.scores ?? []}
- scoreMetadata={{
- projectId: projectId,
- environment: session.data?.environment,
- }}
- buttonVariant="outline"
+ sessionId={sessionId}
+ value={session.data?.bookmarked ?? false}
+ size="icon-xs"
/>
- <CreateNewAnnotationQueueItem
+ <PublishSessionSwitch
projectId={projectId}
- objectId={sessionId}
- objectType={AnnotationQueueObjectType.SESSION}
- variant="outline"
+ sessionId={sessionId}
+ isPublic={session.data?.public ?? false}
+ key="publish"
+ size="icon-xs"
/>
</div>
- <div className="flex items-center">
- <Switch
- checked={showCorrections}
- onCheckedChange={setShowCorrections}
- className="scale-75"
+ ),
+ actionButtonsRight: (
+ <>
+ {!router.query.peek && (
+ <DetailPageNav
+ key="nav"
+ currentId={encodeURIComponent(sessionId)}
+ path={(entry) =>
+ `/project/${projectId}/sessions/${encodeURIComponent(entry.id)}`
+ }
+ listKey="sessions"
+ />
+ )}
+ <Button
+ variant="outline"
+ size="icon"
+ onClick={onDownloadSessionAsJson}
+ title="Download session as JSON"
+ >
+ <Download className="h-4 w-4" />
+ </Button>
+ <CommentDrawerButton
+ key="comment"
+ variant="outline"
+ projectId={projectId}
+ objectId={sessionId}
+ objectType="SESSION"
+ count={getNumberFromMap(sessionCommentCounts.data, sessionId)}
/>
- <span className="text-muted-foreground text-xs">
- Show corrections
- </span>
- </div>
- </>
- ),
- }}
- >
- <div className="flex h-full flex-col overflow-auto">
- <div className="bg-background sticky top-0 z-40 flex flex-wrap gap-2 border-b p-4">
- {session.data?.users?.length ? (
- <SessionUsers projectId={projectId} users={session.data.users} />
- ) : null}
- <Badge variant="outline">
- Total traces: {session.data?.traces.length}
- </Badge>
- {session.data && (
+ <div className="flex items-start">
+ <AnnotateDrawer
+ projectId={projectId}
+ scoreTarget={{
+ type: "session",
+ sessionId,
+ }}
+ scores={session.data?.scores ?? []}
+ scoreMetadata={{
+ projectId: projectId,
+ environment: session.data?.environment,
+ }}
+ buttonVariant="outline"
+ />
+ <CreateNewAnnotationQueueItem
+ projectId={projectId}
+ objectId={sessionId}
+ objectType="SESSION"
+ variant="outline"
+ />
+ </div>
+ <div className="flex items-center">
+ <Switch
+ checked={showCorrections}
+ onCheckedChange={setShowCorrectionsForSession}
+ className="scale-75"
+ />
+ <span className="text-muted-foreground text-xs">
+ Show corrections
+ </span>
+ </div>
+ </>
+ ),
+ }}
+ >
+ <div className="flex h-full flex-col overflow-auto">
+ <div className="bg-background sticky top-0 z-40 flex flex-wrap gap-2 border-b p-4">
+ {session.data?.users?.length ? (
+ <SessionUsers projectId={projectId} users={session.data.users} />
+ ) : null}
<Badge variant="outline">
- Total cost: {usdFormatter(session.data.totalCost, 2)}
+ Total traces: {session.data?.traces.length}
</Badge>
- )}
- <SessionScores scores={session.data?.scores ?? []} />
- </div>
- <div ref={parentRef} className="flex-1 overflow-auto p-4">
- <div
- style={{
- height: `${virtualizer.getTotalSize()}px`,
- width: "100%",
- position: "relative",
- }}
- >
- {virtualizer.getVirtualItems().map((virtualItem) => {
- const trace = session.data?.traces[virtualItem.index];
- if (!trace) return null;
-
- return (
- <div
- key={virtualItem.key}
- data-index={virtualItem.index}
- style={{
- position: "absolute",
- top: 0,
- left: 0,
- width: "100%",
- transform: `translateY(${virtualItem.start}px)`,
- }}
- >
- <LazyTraceRow
- ref={virtualizer.measureElement}
- trace={trace}
- projectId={projectId}
- openPeek={openPeek}
- traceCommentCounts={traceCommentCounts.data}
- index={virtualItem.index}
- showCorrections={showCorrections}
- onLoad={() => {
- // Force virtualizer to remeasure this specific item
- virtualizer.measureElement(
- document.querySelector(
- `[data-index="${virtualItem.index}"]`,
- ) as HTMLElement,
- );
- }}
- />
- </div>
- );
- })}
+ {session.data && (
+ <Badge variant="outline">
+ Total cost: {usdFormatter(session.data.totalCost, 2)}
+ </Badge>
+ )}
+ <SessionScores scores={session.data?.scores ?? []} />
+ </div>
+ <div ref={parentRef} className="flex-1 overflow-auto p-4">
+ <div
+ style={{
+ height: `${virtualizer.getTotalSize()}px`,
+ width: "100%",
+ position: "relative",
+ }}
+ >
+ {virtualItems.map((virtualItem) => {
+ const trace = session.data?.traces[virtualItem.index];
+ if (!trace) return null;
+
+ return (
+ <SessionVirtualizedRow
+ key={virtualItem.key}
+ itemKey={String(virtualItem.key)}
+ measurementKey={`${String(virtualItem.key)}:${showCorrections}`}
+ source="legacy"
+ virtualItem={virtualItem}
+ virtualizer={virtualizer}
+ >
+ <LazyTraceRow
+ trace={trace}
+ projectId={projectId}
+ openPeek={openPeek}
+ traceCommentCounts={asCommentCounts(
+ traceCommentCounts.data,
+ )}
+ index={virtualItem.index}
+ />
+ </SessionVirtualizedRow>
+ );
+ })}
+ </div>
</div>
</div>
- </div>
- <TablePeekViewTraceDetail
- itemType="TRACE"
- detailNavigationKey="traces"
- closePeek={closePeek}
- expandPeek={expandPeek}
- resolveDetailNavigationPath={resolveDetailNavigationPath}
- projectId={projectId}
- />
- </Page>
+ <TablePeekViewTraceDetail
+ itemType="TRACE"
+ detailNavigationKey="traces"
+ closePeek={closePeek}
+ expandPeek={expandPeek}
+ resolveDetailNavigationPath={resolveDetailNavigationPath}
+ projectId={projectId}
+ />
+ </Page>
+ </SessionDetailStoreProvider>
);
};
@@ -550,6 +529,30 @@ export const SessionEventsPage: React.FC<{
"showCorrections",
false,
);
+ const [sessionDetailStore] = useState(() =>
+ createSessionDetailStore({
+ initialSessionId: sessionId,
+ initialShowCorrections: showCorrections,
+ }),
+ );
+
+ useEffect(() => {
+ sessionDetailStore.getState().actions.resetForSession(sessionId);
+ }, [sessionDetailStore, sessionId]);
+
+ useEffect(() => {
+ sessionDetailStore.getState().actions.setShowCorrections(showCorrections);
+ }, [sessionDetailStore, showCorrections]);
+
+ const setShowCorrectionsForSession = useCallback(
+ (nextShowCorrections: boolean) => {
+ setShowCorrections(nextShowCorrections);
+ sessionDetailStore
+ .getState()
+ .actions.setShowCorrections(nextShowCorrections);
+ },
+ [sessionDetailStore, setShowCorrections],
+ );
const sessionCommentCounts = api.comments.getCountByObjectId.useQuery(
{
@@ -584,8 +587,8 @@ export const SessionEventsPage: React.FC<{
},
);
- const { openPeek, closePeek, resolveDetailNavigationPath, expandPeek } =
- usePeekNavigation({
+ const peekNavigationConfig = React.useMemo(
+ () => ({
expandConfig: {
basePath: `/project/${projectId}/traces`,
},
@@ -593,11 +596,15 @@ export const SessionEventsPage: React.FC<{
extractParamsValuesFromRow: (row: any) => ({
timestamp: row.timestamp.toISOString(),
}),
- });
+ }),
+ [projectId],
+ );
+ const { openPeek, closePeek, resolveDetailNavigationPath, expandPeek } =
+ usePeekNavigation(peekNavigationConfig);
useEffect(() => {
if (!tracesQuery.isSuccess) return;
- const nextList = tracesQuery.data.map((t) => ({
+ const nextList = tracesQuery.data.map((t: EventSessionTrace) => ({
id: t.id,
params: { timestamp: t.timestamp.toISOString() },
}));
@@ -669,14 +676,21 @@ export const SessionEventsPage: React.FC<{
projectId,
oldFilterState: timeFiltersForOptions,
});
+ const typedFilterOptions = filterOptions as EventFilterOptions;
const filterColumns = React.useMemo<ColumnDefinition[]>(() => {
- const scoreCategoryOptions = filterOptions.score_categories
- ? Object.entries(filterOptions.score_categories).map(
- ([label, values]) => ({
- label,
- values,
- }),
+ const scoreCategoryOptions = isMultiValueOptionRecord(
+ typedFilterOptions.score_categories,
+ )
+ ? Object.entries(typedFilterOptions.score_categories).map(
+ ([label, values]) => ({ label, values }),
+ )
+ : [];
+ const traceScoreCategoryOptions = isMultiValueOptionRecord(
+ typedFilterOptions.trace_score_categories,
+ )
+ ? Object.entries(typedFilterOptions.trace_score_categories).map(
+ ([label, values]) => ({ label, values }),
)
: [];
@@ -695,16 +709,32 @@ export const SessionEventsPage: React.FC<{
.map((column) => {
if (column.type === "stringOptions" || column.type === "arrayOptions") {
const optionMap: Record<string, typeof column.options | undefined> = {
- type: filterOptions.type,
- name: filterOptions.name,
- level: filterOptions.level,
- providedModelName: filterOptions.providedModelName,
- modelId: filterOptions.modelId,
- promptName: filterOptions.promptName,
- version: filterOptions.version,
- experimentDatasetId: filterOptions.experimentDatasetId,
- experimentId: filterOptions.experimentId,
- experimentName: filterOptions.experimentName,
+ type: typedFilterOptions.type as typeof column.options | undefined,
+ name: typedFilterOptions.name as typeof column.options | undefined,
+ level: typedFilterOptions.level as
+ | typeof column.options
+ | undefined,
+ providedModelName: typedFilterOptions.providedModelName as
+ | typeof column.options
+ | undefined,
+ modelId: typedFilterOptions.modelId as
+ | typeof column.options
+ | undefined,
+ promptName: typedFilterOptions.promptName as
+ | typeof column.options
+ | undefined,
+ version: typedFilterOptions.version as
+ | typeof column.options
+ | undefined,
+ experimentDatasetId: typedFilterOptions.experimentDatasetId as
+ | typeof column.options
+ | undefined,
+ experimentId: typedFilterOptions.experimentId as
+ | typeof column.options
+ | undefined,
+ experimentName: typedFilterOptions.experimentName as
+ | typeof column.options
+ | undefined,
};
const options = optionMap[column.id];
@@ -718,15 +748,35 @@ export const SessionEventsPage: React.FC<{
return { ...column, options: scoreCategoryOptions };
}
+ if (
+ column.type === "categoryOptions" &&
+ column.id === "trace_score_categories"
+ ) {
+ return { ...column, options: traceScoreCategoryOptions };
+ }
+
if (column.type === "numberObject" && column.id === "scores_avg") {
- return filterOptions.scores_avg
- ? { ...column, keyOptions: filterOptions.scores_avg }
- : column;
+ const keyOptions = getStringFilterOptions(
+ typedFilterOptions.scores_avg,
+ );
+
+ return keyOptions ? { ...column, keyOptions } : column;
+ }
+
+ if (
+ column.type === "numberObject" &&
+ column.id === "trace_scores_avg"
+ ) {
+ const keyOptions = getStringFilterOptions(
+ typedFilterOptions.trace_scores_avg,
+ );
+
+ return keyOptions ? { ...column, keyOptions } : column;
}
return column;
});
- }, [filterOptions, sessionEventsFilterConfig.columnDefinitions]);
+ }, [typedFilterOptions, sessionEventsFilterConfig.columnDefinitions]);
const filterColumnsWithCustomSelect = React.useMemo(
() =>
@@ -741,7 +791,7 @@ export const SessionEventsPage: React.FC<{
const queryFilter = useSidebarFilterState(
sessionEventsFilterConfig,
- filterOptions,
+ typedFilterOptions,
{
loading: isFilterOptionsPending,
stateLocation: "urlAndSessionStorage",
@@ -767,6 +817,10 @@ export const SessionEventsPage: React.FC<{
),
[queryFilter.filterState],
);
+ const visibleFilterMeasurementKey = React.useMemo(
+ () => JSON.stringify(visibleFilterState),
+ [visibleFilterState],
+ );
// Stub state for Saved Views (no actual table columns in this view)
const [columnOrder, setColumnOrder] = useState<ColumnOrderState>([]);
@@ -833,13 +887,10 @@ export const SessionEventsPage: React.FC<{
count: tracesQuery.data?.length ?? 0,
getScrollElement: () => parentRef.current,
estimateSize: () => 320,
- overscan: 1,
+ overscan: SESSION_VIRTUALIZER_OVERSCAN,
getItemKey: (index) => tracesQuery.data?.[index]?.id ?? index,
- measureElement:
- typeof window !== "undefined"
- ? (element) => element.getBoundingClientRect().height
- : undefined,
});
+ const virtualItems = virtualizer.getVirtualItems();
if (session.error?.data?.code === "UNAUTHORIZED")
return <ErrorPage message="You do not have access to this session." />;
@@ -857,194 +908,186 @@ export const SessionEventsPage: React.FC<{
);
return (
- <Page
- headerProps={{
- title: sessionId,
- itemType: "SESSION",
- breadcrumb: [
- {
- name: "Sessions",
- href: `/project/${projectId}/sessions`,
- },
- ],
- actionButtonsLeft: (
- <div className="flex items-center gap-0">
- <StarSessionToggle
- key="star"
- projectId={projectId}
- sessionId={sessionId}
- value={session.data?.bookmarked ?? false}
- size="icon-xs"
- />
- <PublishSessionSwitch
- projectId={projectId}
- sessionId={sessionId}
- isPublic={session.data?.public ?? false}
- key="publish"
- size="icon-xs"
- />
- </div>
- ),
- actionButtonsRight: (
- <>
- {!router.query.peek && (
- <DetailPageNav
- key="nav"
- currentId={encodeURIComponent(sessionId)}
- path={(entry) =>
- `/project/${projectId}/sessions/${encodeURIComponent(entry.id)}`
- }
- listKey="sessions"
- />
- )}
- <CommentDrawerButton
- key="comment"
- variant="outline"
- projectId={projectId}
- objectId={sessionId}
- objectType="SESSION"
- count={getNumberFromMap(sessionCommentCounts.data, sessionId)}
- />
- <div className="flex items-start">
- <AnnotateDrawer
+ <SessionDetailStoreProvider store={sessionDetailStore}>
+ <Page
+ headerProps={{
+ title: sessionId,
+ itemType: "SESSION",
+ breadcrumb: [
+ {
+ name: "Sessions",
+ href: `/project/${projectId}/sessions`,
+ },
+ ],
+ actionButtonsLeft: (
+ <div className="flex items-center gap-0">
+ <StarSessionToggle
+ key="star"
projectId={projectId}
- scoreTarget={{
- type: "session",
- sessionId,
- }}
- scores={session.data?.scores ?? []}
- scoreMetadata={{
- projectId: projectId,
- environment: session.data?.environment,
- }}
- buttonVariant="outline"
+ sessionId={sessionId}
+ value={session.data?.bookmarked ?? false}
+ size="icon-xs"
/>
- <CreateNewAnnotationQueueItem
+ <PublishSessionSwitch
projectId={projectId}
- objectId={sessionId}
- objectType={AnnotationQueueObjectType.SESSION}
- variant="outline"
+ sessionId={sessionId}
+ isPublic={session.data?.public ?? false}
+ key="publish"
+ size="icon-xs"
/>
</div>
- <div className="flex items-center">
- <Switch
- checked={showCorrections}
- onCheckedChange={setShowCorrections}
- className="scale-75"
+ ),
+ actionButtonsRight: (
+ <>
+ {!router.query.peek && (
+ <DetailPageNav
+ key="nav"
+ currentId={encodeURIComponent(sessionId)}
+ path={(entry) =>
+ `/project/${projectId}/sessions/${encodeURIComponent(entry.id)}`
+ }
+ listKey="sessions"
+ />
+ )}
+ <CommentDrawerButton
+ key="comment"
+ variant="outline"
+ projectId={projectId}
+ objectId={sessionId}
+ objectType="SESSION"
+ count={getNumberFromMap(sessionCommentCounts.data, sessionId)}
/>
- <span className="text-muted-foreground text-xs">
- Show corrections
- </span>
- </div>
- </>
- ),
- }}
- >
- <div className="flex h-full flex-col overflow-auto">
- <div className="bg-background sticky top-0 z-40 flex flex-wrap items-center gap-2 border-b p-4">
- {/* Saved Views */}
- <TableViewPresetsDrawer
- viewConfig={{
- tableName: TableViewPresetTableName.SessionDetail,
- projectId,
- controllers: viewControllers,
- }}
- currentState={{
- orderBy: null,
- filters: queryFilter.filterState,
- columnOrder,
- columnVisibility,
- searchQuery: "",
- }}
- systemFilterPresets={SESSION_DETAIL_SYSTEM_PRESETS}
- />
-
- {/* Filter Builder */}
- <PopoverFilterBuilder
- columns={filterColumns}
- filterState={visibleFilterState}
- onChange={queryFilter.setFilterState}
- columnsWithCustomSelect={filterColumnsWithCustomSelect}
- />
-
- {/* Separator */}
- <Separator orientation="vertical" className="h-6" />
-
- {/* Stats */}
- <Badge variant="outline">
- Total traces: {session.data?.countTraces ?? 0}
- </Badge>
- {session.data && (
+ <div className="flex items-start">
+ <AnnotateDrawer
+ projectId={projectId}
+ scoreTarget={{
+ type: "session",
+ sessionId,
+ }}
+ scores={session.data?.scores ?? []}
+ scoreMetadata={{
+ projectId: projectId,
+ environment: session.data?.environment,
+ }}
+ buttonVariant="outline"
+ />
+ <CreateNewAnnotationQueueItem
+ projectId={projectId}
+ objectId={sessionId}
+ objectType="SESSION"
+ variant="outline"
+ />
+ </div>
+ <div className="flex items-center">
+ <Switch
+ checked={showCorrections}
+ onCheckedChange={setShowCorrectionsForSession}
+ className="scale-75"
+ />
+ <span className="text-muted-foreground text-xs">
+ Show corrections
+ </span>
+ </div>
+ </>
+ ),
+ }}
+ >
+ <div className="flex h-full flex-col overflow-auto">
+ <div className="bg-background sticky top-0 z-40 flex flex-wrap items-center gap-2 border-b p-4">
+ {/* Saved Views */}
+ <TableViewPresetsDrawer
+ viewConfig={{
+ tableName: TableViewPresetTableName.SessionDetail,
+ projectId,
+ controllers: viewControllers,
+ }}
+ currentState={{
+ orderBy: null,
+ filters: queryFilter.filterState,
+ columnOrder,
+ columnVisibility,
+ searchQuery: "",
+ }}
+ systemFilterPresets={SESSION_DETAIL_SYSTEM_PRESETS}
+ />
+
+ {/* Filter Builder */}
+ <PopoverFilterBuilder
+ columns={filterColumns}
+ filterState={visibleFilterState}
+ onChange={queryFilter.setFilterState}
+ columnsWithCustomSelect={filterColumnsWithCustomSelect}
+ />
+
+ {/* Separator */}
+ <Separator orientation="vertical" className="h-6" />
+
+ {/* Stats */}
<Badge variant="outline">
- Total cost: {usdFormatter(session.data.totalCost ?? 0, 2)}
+ Total traces: {session.data?.countTraces ?? 0}
</Badge>
- )}
+ {session.data && (
+ <Badge variant="outline">
+ Total cost: {usdFormatter(session.data.totalCost ?? 0, 2)}
+ </Badge>
+ )}
- {/* Users */}
- {session.data?.users?.length ? (
- <SessionUsers projectId={projectId} users={session.data.users} />
- ) : null}
+ {/* Users */}
+ {session.data?.users?.length ? (
+ <SessionUsers projectId={projectId} users={session.data.users} />
+ ) : null}
- {/* Scores */}
- <SessionScores scores={session.data?.scores ?? []} />
- </div>
- <div ref={parentRef} className="flex-1 overflow-auto p-4">
- <div
- style={{
- height: `${virtualizer.getTotalSize()}px`,
- width: "100%",
- position: "relative",
- }}
- >
- {virtualizer.getVirtualItems().map((virtualItem) => {
- const trace = tracesQuery.data?.[virtualItem.index];
- if (!trace) return null;
-
- return (
- <div
- key={virtualItem.key}
- data-index={virtualItem.index}
- style={{
- position: "absolute",
- top: 0,
- left: 0,
- width: "100%",
- transform: `translateY(${virtualItem.start}px)`,
- }}
- >
- <LazyTraceEventsRow
- ref={virtualizer.measureElement}
- trace={trace}
- projectId={projectId}
- sessionId={sessionId}
- openPeek={openPeek}
- traceCommentCounts={traceCommentCounts.data}
- index={virtualItem.index}
- showCorrections={showCorrections}
- filterState={visibleFilterState}
- onLoad={() => {
- virtualizer.measureElement(
- document.querySelector(
- `[data-index="${virtualItem.index}"]`,
- ) as HTMLElement,
- );
- }}
- />
- </div>
- );
- })}
+ {/* Scores */}
+ <SessionScores scores={session.data?.scores ?? []} />
+ </div>
+ <div ref={parentRef} className="flex-1 overflow-auto p-4">
+ <div
+ style={{
+ height: `${virtualizer.getTotalSize()}px`,
+ width: "100%",
+ position: "relative",
+ }}
+ >
+ {virtualItems.map((virtualItem) => {
+ const trace = tracesQuery.data?.[virtualItem.index];
+ if (!trace) return null;
+
+ return (
+ <SessionVirtualizedRow
+ key={virtualItem.key}
+ itemKey={String(virtualItem.key)}
+ measurementKey={`${String(virtualItem.key)}:${showCorrections}:${visibleFilterMeasurementKey}`}
+ source="events"
+ virtualItem={virtualItem}
+ virtualizer={virtualizer}
+ >
+ <LazySessionTraceEventsRow
+ trace={trace}
+ projectId={projectId}
+ sessionId={sessionId}
+ openPeek={openPeek}
+ traceCommentCounts={asCommentCounts(
+ traceCommentCounts.data,
+ )}
+ index={virtualItem.index}
+ filterState={visibleFilterState}
+ />
+ </SessionVirtualizedRow>
+ );
+ })}
+ </div>
</div>
</div>
- </div>
- <TablePeekViewTraceDetail
- itemType="TRACE"
- detailNavigationKey="traces"
- closePeek={closePeek}
- expandPeek={expandPeek}
- resolveDetailNavigationPath={resolveDetailNavigationPath}
- projectId={projectId}
- />
- </Page>
+ <TablePeekViewTraceDetail
+ itemType="TRACE"
+ detailNavigationKey="traces"
+ closePeek={closePeek}
+ expandPeek={expandPeek}
+ resolveDetailNavigationPath={resolveDetailNavigationPath}
+ projectId={projectId}
+ />
+ </Page>
+ </SessionDetailStoreProvider>
);
};
@@ -1052,11 +1095,13 @@ export const SessionIO = ({
traceId,
projectId,
timestamp,
+ environment,
showCorrections,
}: {
traceId: string;
projectId: string;
timestamp: Date;
+ environment?: string | null;
showCorrections: boolean;
}) => {
const trace = api.traces.byId.useQuery(
@@ -1079,6 +1124,8 @@ export const SessionIO = ({
output: trace.data?.output,
metadata: undefined,
});
+ const previewEnvironment =
+ environment ?? trace.data?.environment ?? undefined;
return (
<div className="flex w-full flex-col gap-2 overflow-hidden p-0">
@@ -1098,7 +1145,7 @@ export const SessionIO = ({
hideIfNull
projectId={projectId}
traceId={traceId}
- environment={trace.data.environment}
+ environment={previewEnvironment}
showCorrections={showCorrections}
/>
) : (
diff --git a/web/src/components/session/sessionDetailPageTypes.ts b/web/src/components/session/sessionDetailPageTypes.ts
new file mode 100644
index 0000000000..eff5f17cf8
--- /dev/null
+++ b/web/src/components/session/sessionDetailPageTypes.ts
@@ -0,0 +1,45 @@
+import { type ListEntry } from "@/src/features/navigate-detail-pages/context";
+import { type RouterOutputs } from "@/src/utils/api";
+import { type SingleValueOption } from "@langfuse/shared";
+
+export type LegacySessionTrace =
+ RouterOutputs["sessions"]["byIdWithScores"]["traces"][number];
+export type EventSessionTrace =
+ RouterOutputs["sessions"]["tracesFromEvents"][number];
+export type CommentCounts = Map<string, number>;
+export type EventFilterOptions = Record<
+ string,
+ (string | SingleValueOption)[] | Record<string, string[]> | undefined
+>;
+
+export const asCommentCounts = (
+ commentCounts: Map<unknown, unknown> | undefined,
+): CommentCounts | undefined => commentCounts as CommentCounts | undefined;
+
+export const isMultiValueOptionRecord = (
+ value: (string | SingleValueOption)[] | Record<string, string[]> | undefined,
+): value is Record<string, string[]> => Boolean(value) && !Array.isArray(value);
+
+export const getStringFilterOptions = (
+ value: (string | SingleValueOption)[] | Record<string, string[]> | undefined,
+) => {
+ if (!Array.isArray(value)) return undefined;
+
+ return value.map((option) =>
+ typeof option === "string" ? option : option.value,
+ );
+};
+
+export const areDetailPageListsEqual = (
+ left: ListEntry[] | undefined,
+ right: ListEntry[] | undefined,
+) => {
+ if (left === right) return true;
+ if (!left || !right || left.length !== right.length) return false;
+ return left.every((entry, index) => {
+ const other = right[index];
+ if (entry.id !== other?.id) return false;
+ if (!entry.params && !other?.params) return true;
+ return JSON.stringify(entry.params) === JSON.stringify(other?.params);
+ });
+};
diff --git a/web/src/components/session/sessionDetailStore.clienttest.ts b/web/src/components/session/sessionDetailStore.clienttest.ts
new file mode 100644
index 0000000000..4cb816997f
--- /dev/null
+++ b/web/src/components/session/sessionDetailStore.clienttest.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from "vitest";
+import { createSessionDetailStore } from "@/src/components/session/sessionDetailStore";
+
+describe("createSessionDetailStore", () => {
+ it("marks loaded traces idempotently", () => {
+ const store = createSessionDetailStore({
+ initialSessionId: "session-a",
+ initialShowCorrections: false,
+ });
+
+ store.getState().actions.markTraceLoaded("trace-1");
+ const firstLoadedTraceIds = store.getState().loadedTraceIds;
+
+ store.getState().actions.markTraceLoaded("trace-1");
+
+ expect(store.getState().loadedTraceIds).toBe(firstLoadedTraceIds);
+ expect(store.getState().loadedTraceIds).toEqual({ "trace-1": true });
+ });
+
+ it("resets loaded row state when the session changes", () => {
+ const store = createSessionDetailStore({
+ initialSessionId: "session-a",
+ initialShowCorrections: false,
+ });
+
+ store.getState().actions.markTraceLoaded("trace-1");
+ store.getState().actions.resetForSession("session-b");
+
+ expect(store.getState().sessionId).toBe("session-b");
+ expect(store.getState().loadedTraceIds).toEqual({});
+ });
+
+ it("updates correction visibility without changing loaded rows", () => {
+ const store = createSessionDetailStore({
+ initialSessionId: "session-a",
+ initialShowCorrections: false,
+ });
+
+ store.getState().actions.markTraceLoaded("trace-1");
+ const loadedTraceIds = store.getState().loadedTraceIds;
+
+ store.getState().actions.setShowCorrections(true);
+
+ expect(store.getState().showCorrections).toBe(true);
+ expect(store.getState().loadedTraceIds).toBe(loadedTraceIds);
+ });
+});
diff --git a/web/src/components/session/sessionDetailStore.ts b/web/src/components/session/sessionDetailStore.ts
new file mode 100644
index 0000000000..9b5ac753ba
--- /dev/null
+++ b/web/src/components/session/sessionDetailStore.ts
@@ -0,0 +1,53 @@
+import { createStore, type StoreApi } from "zustand/vanilla";
+
+export type LoadedTraceIds = Record<string, true>;
+
+export interface SessionDetailStoreState {
+ loadedTraceIds: LoadedTraceIds;
+ showCorrections: boolean;
+ sessionId: string;
+ actions: {
+ markTraceLoaded: (traceId: string) => void;
+ setShowCorrections: (showCorrections: boolean) => void;
+ resetForSession: (sessionId: string) => void;
+ };
+}
+
+export type SessionDetailStore = StoreApi<SessionDetailStoreState>;
+
+export function createSessionDetailStore({
+ initialSessionId,
+ initialShowCorrections,
+}: {
+ initialSessionId: string;
+ initialShowCorrections: boolean;
+}): SessionDetailStore {
+ return createStore<SessionDetailStoreState>((set, get) => ({
+ loadedTraceIds: {},
+ showCorrections: initialShowCorrections,
+ sessionId: initialSessionId,
+ actions: {
+ markTraceLoaded: (traceId: string) => {
+ if (get().loadedTraceIds[traceId]) return;
+
+ set((state) => ({
+ loadedTraceIds: {
+ ...state.loadedTraceIds,
+ [traceId]: true,
+ },
+ }));
+ },
+ setShowCorrections: (showCorrections: boolean) => {
+ if (showCorrections === get().showCorrections) return;
+ set({ showCorrections });
+ },
+ resetForSession: (sessionId: string) => {
+ if (sessionId === get().sessionId) return;
+ set({
+ loadedTraceIds: {},
+ sessionId,
+ });
+ },
+ },
+ }));
+}
diff --git a/web/src/components/session/stableVirtualRowMeasurementState.clienttest.ts b/web/src/components/session/stableVirtualRowMeasurementState.clienttest.ts
new file mode 100644
index 0000000000..9fe6d2f2fb
--- /dev/null
+++ b/web/src/components/session/stableVirtualRowMeasurementState.clienttest.ts
@@ -0,0 +1,204 @@
+import { describe, expect, it, vi } from "vitest";
+import { createStableVirtualRowMeasurementState } from "@/src/components/session/stableVirtualRowMeasurementState";
+
+describe("createStableVirtualRowMeasurementState", () => {
+ it("clears stale pending height when a direct commit lands", () => {
+ const measurement = createStableVirtualRowMeasurementState();
+
+ expect(measurement.commitHeight(300, 0)).toBe(300);
+ measurement.setPendingHeight(350);
+
+ expect(measurement.commitHeight(320, 10)).toBe(320);
+ expect(measurement.getSnapshot().pendingHeight).toBeNull();
+ expect(measurement.commitPendingHeight(20)).toBeNull();
+ expect(measurement.getSnapshot().committedHeight).toBe(320);
+ });
+
+ it("commits a deferred pending height only when pending height is consumed", () => {
+ const measurement = createStableVirtualRowMeasurementState();
+
+ measurement.setPendingHeight(350);
+
+ expect(measurement.getSnapshot().committedHeight).toBeNull();
+ expect(measurement.commitPendingHeight(0)).toBe(350);
+ expect(measurement.getSnapshot().pendingHeight).toBeNull();
+ expect(measurement.getSnapshot().committedHeight).toBe(350);
+ });
+
+ it("clears committed, pending, oscillation, and freeze state on reset", () => {
+ const measurement = createStableVirtualRowMeasurementState();
+
+ expect(measurement.commitHeight(100, 0)).toBe(100);
+ expect(measurement.commitHeight(200, 100)).toBe(200);
+ measurement.setPendingHeight(150);
+ measurement.reset();
+
+ expect(measurement.getSnapshot()).toEqual({
+ committedHeight: null,
+ pendingHeight: null,
+ previousObservedHeight: null,
+ oscillationPair: null,
+ oscillationCount: 0,
+ oscillationWindowStartedAt: 0,
+ lastObservationAt: 0,
+ frozenMinHeight: null,
+ });
+ });
+
+ it("ignores rounded no-op height changes", () => {
+ const measurement = createStableVirtualRowMeasurementState();
+
+ expect(measurement.commitHeight(100.2, 0)).toBe(101);
+ expect(measurement.commitHeight(100.8, 10)).toBeNull();
+ expect(measurement.getSnapshot().committedHeight).toBe(101);
+ });
+
+ it("clamps the observation that triggers repeated-height oscillation", () => {
+ const measurement = createStableVirtualRowMeasurementState();
+
+ expect(measurement.commitHeight(100, 0)).toBe(100);
+ expect(measurement.commitHeight(200, 100)).toBe(200);
+ expect(measurement.commitHeight(100, 200)).toBe(100);
+ expect(measurement.commitHeight(200, 300)).toBe(200);
+
+ expect(measurement.commitHeight(100, 400)).toBeNull();
+ expect(measurement.getSnapshot()).toMatchObject({
+ committedHeight: 200,
+ frozenMinHeight: 200,
+ oscillationCount: 4,
+ });
+ });
+
+ it("allows legitimate growth after oscillation has been clamped", () => {
+ const measurement = createStableVirtualRowMeasurementState();
+
+ measurement.commitHeight(100, 0);
+ measurement.commitHeight(200, 100);
+ measurement.commitHeight(100, 200);
+ measurement.commitHeight(200, 300);
+ measurement.commitHeight(100, 400);
+
+ expect(measurement.commitHeight(260, 500)).toBe(260);
+ expect(measurement.getSnapshot().committedHeight).toBe(260);
+ });
+
+ it("keeps a frozen shrink clamped while the oscillation window is active", () => {
+ const measurement = createStableVirtualRowMeasurementState();
+
+ measurement.commitHeight(100, 0);
+ measurement.commitHeight(200, 100);
+ measurement.commitHeight(100, 200);
+ measurement.commitHeight(200, 300);
+ measurement.commitHeight(100, 400);
+
+ expect(measurement.commitHeight(100, 500)).toBeNull();
+ expect(measurement.getSnapshot()).toMatchObject({
+ committedHeight: 200,
+ frozenMinHeight: 200,
+ });
+ });
+
+ it("keeps sustained oscillation clamped across the rolling window", () => {
+ const measurement = createStableVirtualRowMeasurementState();
+
+ expect(measurement.commitHeight(100, 0)).toBe(100);
+ expect(measurement.commitHeight(200, 16)).toBe(200);
+ expect(measurement.commitHeight(100, 32)).toBe(100);
+ expect(measurement.commitHeight(200, 48)).toBe(200);
+ expect(measurement.commitHeight(100, 64)).toBeNull();
+
+ for (let now = 80; now <= 2_000; now += 16) {
+ const height = now % 32 === 0 ? 100 : 200;
+
+ expect(measurement.commitHeight(height, now)).toBeNull();
+ }
+
+ expect(measurement.getSnapshot()).toMatchObject({
+ committedHeight: 200,
+ frozenMinHeight: 200,
+ });
+ });
+
+ it("keeps scroll-deferred oscillation clamped after the rolling window", () => {
+ const measurement = createStableVirtualRowMeasurementState();
+
+ expect(measurement.commitHeight(100, 0)).toBe(100);
+ expect(measurement.commitHeight(200, 100)).toBe(200);
+ expect(measurement.commitHeight(100, 200)).toBe(100);
+ expect(measurement.commitHeight(200, 300)).toBe(200);
+ expect(measurement.commitHeight(100, 400)).toBeNull();
+
+ vi.useFakeTimers();
+ try {
+ vi.setSystemTime(1_300);
+ measurement.setPendingHeight(200);
+ vi.setSystemTime(1_400);
+ measurement.setPendingHeight(100);
+
+ expect(measurement.commitPendingHeight(1_410)).toBeNull();
+ expect(measurement.getSnapshot()).toMatchObject({
+ committedHeight: 200,
+ frozenMinHeight: 200,
+ });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("releases a frozen shrink after the oscillation window expires", () => {
+ const measurement = createStableVirtualRowMeasurementState();
+
+ measurement.commitHeight(100, 0);
+ measurement.commitHeight(200, 100);
+ measurement.commitHeight(100, 200);
+ measurement.commitHeight(200, 300);
+ measurement.commitHeight(100, 400);
+
+ expect(measurement.commitHeight(100, 1_500)).toBe(100);
+ expect(measurement.getSnapshot()).toMatchObject({
+ committedHeight: 100,
+ frozenMinHeight: null,
+ oscillationPair: null,
+ oscillationCount: 0,
+ oscillationWindowStartedAt: 0,
+ });
+ });
+
+ it("clears stale frozen state after the oscillation window expires", () => {
+ const measurement = createStableVirtualRowMeasurementState();
+
+ measurement.commitHeight(100, 0);
+ measurement.commitHeight(200, 100);
+ measurement.commitHeight(100, 200);
+ measurement.commitHeight(200, 300);
+ measurement.commitHeight(100, 400);
+
+ expect(measurement.commitHeight(200, 1_500)).toBeNull();
+ expect(measurement.getSnapshot()).toMatchObject({
+ committedHeight: 200,
+ frozenMinHeight: null,
+ oscillationPair: null,
+ oscillationCount: 0,
+ oscillationWindowStartedAt: 0,
+ });
+ });
+
+ it("clears stale frozen state after later legitimate growth", () => {
+ const measurement = createStableVirtualRowMeasurementState();
+
+ measurement.commitHeight(100, 0);
+ measurement.commitHeight(200, 100);
+ measurement.commitHeight(100, 200);
+ measurement.commitHeight(200, 300);
+ measurement.commitHeight(100, 400);
+
+ expect(measurement.commitHeight(260, 1_500)).toBe(260);
+ expect(measurement.getSnapshot()).toMatchObject({
+ committedHeight: 260,
+ frozenMinHeight: null,
+ oscillationPair: null,
+ oscillationCount: 0,
+ oscillationWindowStartedAt: 0,
+ });
+ });
+});
diff --git a/web/src/components/session/stableVirtualRowMeasurementState.ts b/web/src/components/session/stableVirtualRowMeasurementState.ts
new file mode 100644
index 0000000000..16af127248
--- /dev/null
+++ b/web/src/components/session/stableVirtualRowMeasurementState.ts
@@ -0,0 +1,150 @@
+export type StableVirtualRowMeasurementConfig = {
+ scrollIdleMs: number;
+ oscillationWindowMs: number;
+ maxOscillationCount: number;
+};
+
+export const STABLE_VIRTUAL_ROW_MEASUREMENT_CONFIG: StableVirtualRowMeasurementConfig =
+ {
+ scrollIdleMs: 150,
+ oscillationWindowMs: 1_000,
+ maxOscillationCount: 4,
+ };
+
+type OscillationPair = [number, number];
+
+type StableVirtualRowMeasurementState = {
+ committedHeight: number | null;
+ pendingHeight: number | null;
+ previousObservedHeight: number | null;
+ oscillationPair: OscillationPair | null;
+ oscillationCount: number;
+ oscillationWindowStartedAt: number;
+ lastObservationAt: number;
+ frozenMinHeight: number | null;
+};
+
+export type StableVirtualRowMeasurementSnapshot =
+ StableVirtualRowMeasurementState;
+
+const createInitialState = (): StableVirtualRowMeasurementState => ({
+ committedHeight: null,
+ pendingHeight: null,
+ previousObservedHeight: null,
+ oscillationPair: null,
+ oscillationCount: 0,
+ oscillationWindowStartedAt: 0,
+ lastObservationAt: 0,
+ frozenMinHeight: null,
+});
+
+export function createStableVirtualRowMeasurementState(
+ config: StableVirtualRowMeasurementConfig = STABLE_VIRTUAL_ROW_MEASUREMENT_CONFIG,
+) {
+ let state = createInitialState();
+
+ const commitObservedHeight = (
+ rawHeight: number,
+ now = Date.now(),
+ ): number | null => {
+ const roundedHeight = Math.ceil(rawHeight);
+ if (roundedHeight <= 0) return null;
+
+ if (
+ state.frozenMinHeight !== null &&
+ now - state.lastObservationAt > config.oscillationWindowMs
+ ) {
+ state.frozenMinHeight = null;
+ state.oscillationPair = null;
+ state.oscillationCount = 0;
+ state.oscillationWindowStartedAt = 0;
+ state.previousObservedHeight = null;
+ }
+ state.lastObservationAt = now;
+
+ const previousObservedHeight = state.previousObservedHeight;
+ if (
+ previousObservedHeight !== null &&
+ previousObservedHeight !== roundedHeight
+ ) {
+ const nextPair: OscillationPair = [
+ Math.min(previousObservedHeight, roundedHeight),
+ Math.max(previousObservedHeight, roundedHeight),
+ ];
+ const previousPair = state.oscillationPair;
+
+ if (
+ now - state.oscillationWindowStartedAt > config.oscillationWindowMs ||
+ !previousPair ||
+ previousPair[0] !== nextPair[0] ||
+ previousPair[1] !== nextPair[1]
+ ) {
+ state.oscillationWindowStartedAt = now;
+ state.oscillationPair = nextPair;
+ state.oscillationCount = 1;
+ } else {
+ state.oscillationWindowStartedAt = now;
+ state.oscillationCount += 1;
+ }
+ }
+
+ state.previousObservedHeight = roundedHeight;
+
+ const committedHeight = state.committedHeight;
+ if (
+ state.oscillationCount >= config.maxOscillationCount &&
+ committedHeight !== null
+ ) {
+ state.frozenMinHeight = Math.max(committedHeight, roundedHeight);
+ }
+
+ const nextHeight =
+ state.frozenMinHeight === null
+ ? roundedHeight
+ : Math.max(state.frozenMinHeight, roundedHeight);
+
+ if (
+ committedHeight !== null &&
+ Math.abs(committedHeight - nextHeight) < 1
+ ) {
+ return null;
+ }
+
+ state.committedHeight = nextHeight;
+ return nextHeight;
+ };
+
+ return {
+ reset() {
+ state = createInitialState();
+ },
+ setPendingHeight(height: number, now = Date.now()) {
+ state.pendingHeight = height;
+ if (Math.ceil(height) > 0) {
+ state.lastObservationAt = now;
+ }
+ },
+ hasPendingHeight() {
+ return state.pendingHeight !== null;
+ },
+ commitHeight(height: number, now?: number) {
+ state.pendingHeight = null;
+ return commitObservedHeight(height, now);
+ },
+ commitPendingHeight(now?: number) {
+ const pendingHeight = state.pendingHeight;
+ state.pendingHeight = null;
+ return pendingHeight === null
+ ? null
+ : commitObservedHeight(pendingHeight, now);
+ },
+ getSnapshot(): StableVirtualRowMeasurementSnapshot {
+ return {
+ ...state,
+ oscillationPair: state.oscillationPair
+ ? [...state.oscillationPair]
+ : null,
+ };
+ },
+ };
+}
diff --git a/web/src/components/session/useStableVirtualRowMeasurement.ts b/web/src/components/session/useStableVirtualRowMeasurement.ts
new file mode 100644
index 0000000000..28c4bcd874
--- /dev/null
+++ b/web/src/components/session/useStableVirtualRowMeasurement.ts
@@ -0,0 +1,165 @@
+import { useCallback, useEffect, useRef } from "react";
+import { type Virtualizer } from "@tanstack/react-virtual";
+import {
+ createStableVirtualRowMeasurementState,
+ STABLE_VIRTUAL_ROW_MEASUREMENT_CONFIG,
+} from "@/src/components/session/stableVirtualRowMeasurementState";
+
+type StableVirtualRowMeasurementOptions = {
+ index: number;
+ itemKey: string | number;
+ isScrolling: boolean;
+ virtualizer: Virtualizer<HTMLDivElement, Element>;
+};
+
+type StableVirtualRowMeasurementStateApi = ReturnType<
+ typeof createStableVirtualRowMeasurementState
+>;
+
+/**
+ * Controlled row measurement for session detail virtualization.
+ *
+ * Use this instead of live `virtualizer.measureElement` for dynamic,
+ * text-heavy rows where browser translation or async content can repeatedly
+ * mutate DOM height while scrolling. It observes the row shell, defers commits
+ * during active scroll, and clamps short-lived height oscillation before calling
+ * `virtualizer.resizeItem`.
+ *
+ * Keep this session-local until another virtualized surface has the same
+ * symptoms: dynamic row height, scroll jumps, or measurement churn. If that
+ * happens, extract a shared hook with generic HTMLElement support, injectable
+ * config, explicit unmount cleanup tests, and callsite-specific browser checks.
+ */
+export function useStableVirtualRowMeasurement({
+ index,
+ itemKey,
+ isScrolling,
+ virtualizer,
+}: StableVirtualRowMeasurementOptions) {
+ const observerRef = useRef<ResizeObserver | null>(null);
+ const frameRef = useRef<number | null>(null);
+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const nodeRef = useRef<HTMLDivElement | null>(null);
+ const latestIndexRef = useRef(index);
+ const latestIsScrollingRef = useRef(isScrolling);
+ const itemKeyRef = useRef(itemKey);
+ const measurementStateRef =
+ useRef<StableVirtualRowMeasurementStateApi | null>(null);
+
+ if (measurementStateRef.current === null) {
+ measurementStateRef.current = createStableVirtualRowMeasurementState();
+ }
+
+ const measurementState = measurementStateRef.current;
+
+ latestIndexRef.current = index;
+ latestIsScrollingRef.current = isScrolling;
+
+ const cancelFrame = useCallback(() => {
+ if (frameRef.current === null) return;
+ cancelAnimationFrame(frameRef.current);
+ frameRef.current = null;
+ }, []);
+
+ const cancelTimer = useCallback(() => {
+ if (timerRef.current === null) return;
+ clearTimeout(timerRef.current);
+ timerRef.current = null;
+ }, []);
+
+ const cancelScheduledWork = useCallback(() => {
+ cancelFrame();
+ cancelTimer();
+ }, [cancelFrame, cancelTimer]);
+
+ const resizeCommittedHeight = useCallback(
+ (height: number | null) => {
+ if (height === null) return;
+ virtualizer.resizeItem(latestIndexRef.current, height);
+ },
+ [virtualizer],
+ );
+
+ const commitPendingHeight = useCallback(() => {
+ resizeCommittedHeight(measurementState.commitPendingHeight());
+ }, [measurementState, resizeCommittedHeight]);
+
+ const scheduleHeightCommit = useCallback(
+ (height: number) => {
+ cancelScheduledWork();
+
+ frameRef.current = requestAnimationFrame(() => {
+ frameRef.current = null;
+
+ if (latestIsScrollingRef.current) {
+ measurementState.setPendingHeight(height);
+ return;
+ }
+
+ resizeCommittedHeight(measurementState.commitHeight(height));
+ });
+ },
+ [cancelScheduledWork, measurementState, resizeCommittedHeight],
+ );
+
+ useEffect(() => {
+ const itemKeyChanged = itemKeyRef.current !== itemKey;
+
+ if (itemKeyChanged) {
+ itemKeyRef.current = itemKey;
+ cancelScheduledWork();
+ measurementState.reset();
+
+ if (nodeRef.current) {
+ scheduleHeightCommit(nodeRef.current.getBoundingClientRect().height);
+ }
+
+ return;
+ }
+
+ if (isScrolling || !measurementState.hasPendingHeight()) {
+ return;
+ }
+
+ cancelTimer();
+ timerRef.current = setTimeout(() => {
+ timerRef.current = null;
+
+ if (latestIsScrollingRef.current) return;
+
+ commitPendingHeight();
+ }, STABLE_VIRTUAL_ROW_MEASUREMENT_CONFIG.scrollIdleMs);
+
+ return cancelTimer;
+ }, [
+ cancelScheduledWork,
+ cancelTimer,
+ commitPendingHeight,
+ isScrolling,
+ itemKey,
+ measurementState,
+ scheduleHeightCommit,
+ ]);
+
+ return useCallback(
+ (node: HTMLDivElement | null) => {
+ observerRef.current?.disconnect();
+ observerRef.current = null;
+ nodeRef.current = node;
+ cancelScheduledWork();
+
+ if (!node || typeof ResizeObserver === "undefined") return;
+
+ observerRef.current = new ResizeObserver((entries) => {
+ const entry = entries[0];
+ const blockSize = entry.borderBoxSize?.[0]?.blockSize;
+
+ scheduleHeightCommit(blockSize ?? entry.contentRect.height);
+ });
+
+ observerRef.current.observe(node);
+ scheduleHeightCommit(node.getBoundingClientRect().height);
+ },
+ [cancelScheduledWork, scheduleHeightCommit],
+ );
+}
diff --git a/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx b/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx
index 975b4b11e0..5edc32feb6 100644
--- a/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx
+++ b/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx
@@ -6,6 +6,7 @@ import { AnnotationDrawerSection } from "../shared/AnnotationDrawerSection";
import { AnnotationProcessingLayout } from "../shared/AnnotationProcessingLayout";
import { SessionIO } from "@/src/components/session";
import { LazyTraceEventsRow } from "@/src/components/session/TraceEventsRow";
+import { asCommentCounts } from "@/src/components/session/sessionDetailPageTypes";
import { useState, useMemo, useCallback } from "react";
import { Button } from "@/src/components/ui/button";
import { ItemBadge } from "@/src/components/ItemBadge";
@@ -18,11 +19,13 @@ import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";
import { api } from "@/src/utils/api";
import { JsonSkeleton } from "@/src/components/ui/CodeJsonViewer";
+type SessionAnnotationQueueItem = AnnotationQueueItem & {
+ parentTraceId?: string | null;
+ lockedByUser: { name: string | null | undefined } | null;
+};
+
interface SessionAnnotationProcessorProps {
- item: AnnotationQueueItem & {
- parentTraceId?: string | null;
- lockedByUser: { name: string | null | undefined } | null;
- };
+ item: SessionAnnotationQueueItem;
data: any; // // Session data with scores
configs: ScoreConfigDomain[];
projectId: string;
@@ -162,7 +165,7 @@ export const SessionAnnotationProcessor: React.FC<
projectId={projectId}
sessionId={item.objectId}
openPeek={openPeek}
- traceCommentCounts={traceCommentCounts.data ?? undefined}
+ traceCommentCounts={asCommentCounts(traceCommentCounts.data)}
showCorrections
filterState={EMPTY_FILTER_STATE}
hideTracePanel
@@ -191,6 +194,7 @@ export const SessionAnnotationProcessor: React.FC<
traceId={trace.id}
projectId={projectId}
timestamp={trace.timestamp}
+ environment={trace.environment}
showCorrections
/>
</Card>