🪢 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(sessions): Add span list to modern sidebar (#15586)
Ben Bachem96fbf4a85735
diff --git a/packages/shared/src/server/services/sessions-ui-table-events-service.ts b/packages/shared/src/server/services/sessions-ui-table-events-service.tsindex 664beccea9..0a8960272a 100644--- a/packages/shared/src/server/services/sessions-ui-table-events-service.ts+++ b/packages/shared/src/server/services/sessions-ui-table-events-service.ts@@ -53,6 +53,7 @@ export type SessionTraceFromEvents = {environment: string | null;userId: string | null;observationCount: number;+ latencyMs: number | null;};export const getSessionTracesFromEvents = async (props: {@@ -90,6 +91,7 @@ export const getSessionTracesFromEvents = async (props: {environment: string | null;user_id: string | null;observation_count: number | string;+ latency_milliseconds: number | string | null;}>({query,params: input.params,@@ -104,6 +106,10 @@ export const getSessionTracesFromEvents = async (props: {environment: row.environment,userId: row.user_id,observationCount: Number(row.observation_count),+ latencyMs:+ row.latency_milliseconds === null+ ? null+ : Number(row.latency_milliseconds),}));};diff --git a/web/src/components/session/LazySessionTraceEventsRow.tsx b/web/src/components/session/LazySessionTraceEventsRow.tsxindex 640f1aa01b..317ed170ce 100644--- a/web/src/components/session/LazySessionTraceEventsRow.tsx+++ b/web/src/components/session/LazySessionTraceEventsRow.tsx@@ -22,7 +22,6 @@ type LazySessionTraceEventsRowProps = {surface?: TraceEventsSurface;contentMode?: IOPreviewContentMode;showSystemPrompt?: boolean;- isActive?: boolean;};const LazySessionTraceEventsRowInner = (diff --git a/web/src/components/session/ModernSession.tsx b/web/src/components/session/ModernSession.tsxindex 6964b1a4c2..82720d07a7 100644--- a/web/src/components/session/ModernSession.tsx+++ b/web/src/components/session/ModernSession.tsx@@ -1,227 +1,326 @@-import React, { useCallback, useRef, useState } from "react";+import React, { useEffect, useRef, useState } from "react";import { useVirtualizer } from "@tanstack/react-virtual";import { type FilterState } from "@langfuse/shared";-import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";-import { ItemBadge } from "@/src/components/ItemBadge";import { LazySessionTraceEventsRow } from "@/src/components/session/LazySessionTraceEventsRow";import { SessionVirtualizedRow } from "@/src/components/session/SessionVirtualizedRow";-import { SessionTraceActionButtons } from "@/src/components/session/SessionTraceActionButtons";import { type EventSessionTrace } from "@/src/components/session/sessionDetailPageTypes";-import { cn } from "@/src/utils/tailwind";-import { usdFormatter } from "@/src/utils/numbers";+import { computeIdleGapSeconds } from "@/src/components/session/sessionIdleGap";+import { useElementSize } from "@/src/hooks/useElementSize";+import { useDebounce } from "@/src/hooks/useDebounce";+import { useVirtualizedScrollSpy } from "@/src/hooks/useVirtualizedScrollSpy";+import {+ ModernSessionSidebar,+ type ModernSessionSidebarFilterControls,+ type ModernSessionSidebarTrace,+} from "@/src/components/session/ModernSessionSidebar";+import { api } from "@/src/utils/api";const MODERN_SESSION_OVERSCAN = 5;+const SIDEBAR_TRACE_CHUNK_SIZE = 20;+const SIDEBAR_OBSERVATION_PAGE_SIZE = 100;+const EMPTY_TRACES: EventSessionTrace[] = [];-type OpenPeek = (id: string, row: any) => void;+type OpenPeek = (id: string, row: EventSessionTrace) => void;type ModernSessionProps = {- traces: EventSessionTrace[];+ tracesState:+ | { type: "loading" }+ | { type: "loaded"; traces: EventSessionTrace[] };projectId: string;sessionId: string;+ sessionMinTimestamp: Date;+ sessionMaxTimestamp: Date;openPeek: OpenPeek;traceCommentCounts: Map<string, number> | undefined;filterState: FilterState;filterMeasurementKey: string;viewLabel: string | null;- totalCost: number;showInlineToolCalls: boolean;showSystemPrompt: boolean;+ sidebarFilterControls: ModernSessionSidebarFilterControls;+ onExcludeObservation: (name: string) => void;};-const ModernSessionMinimapItem = React.memo(- ({- trace,- index,- isActive,- projectId,- traceCommentCounts,- openPeek,- onSelect,- }: {- trace: EventSessionTrace;- index: number;- isActive: boolean;- projectId: string;- traceCommentCounts: Map<string, number> | undefined;- openPeek: OpenPeek;- onSelect: (index: number) => void;- }) => {- const observationCount = trace.observationCount ?? 0;- const observationLabel = `${observationCount} observation${observationCount === 1 ? "" : "s"}`;-- return (- <div- className={cn(- "group relative border-b border-l-2 transition-colors",- isActive- ? "border-l-primary bg-accent/60"- : "hover:bg-muted/60 border-l-transparent",- )}- data-modern-session-minimap-active={isActive}- >- <button- type="button"- className="flex w-full min-w-0 flex-col gap-1.5 px-3 py-3 text-left"- onClick={() =>- isActive ? openPeek(trace.id, trace) : onSelect(index)- }- aria-current={isActive ? "true" : undefined}- >- <span className="flex min-w-0 items-center gap-1.5">- <ItemBadge type="TRACE" isSmall />- <span- className="min-w-0 flex-1 truncate text-xs font-bold"- title={trace.name ?? "Trace"}- >- {trace.name ?? "Trace"}- </span>- </span>- <time className="text-muted-foreground text-xs">- {trace.timestamp.toLocaleString()}- </time>- <span- className="text-muted-foreground truncate font-mono text-[11px]"- title={trace.id}- >- {trace.id}- </span>- <span className="text-muted-foreground flex flex-wrap items-center gap-1 text-xs">- <span>{observationLabel}</span>- <span>·</span>- {trace.scores.length > 0 ? (- <span>{trace.scores.length} scores</span>- ) : (- <span>no scores</span>- )}- </span>- {isActive && trace.scores.length > 0 ? (- <span className="flex max-h-10 flex-wrap gap-1 overflow-hidden">- <GroupedScoreBadges scores={trace.scores} />- </span>- ) : null}- </button>-- {isActive ? (- <div- className="px-3 pb-2"- onClick={(event) => event.stopPropagation()}- >- <SessionTraceActionButtons- projectId={projectId}- traceId={trace.id}- timestamp={trace.timestamp}- environment={trace.environment}- scores={trace.scores}- traceCommentCounts={traceCommentCounts}- density="compact"- className="gap-1"- />- </div>- ) : null}- </div>- );- },-);-ModernSessionMinimapItem.displayName = "ModernSessionMinimapItem";--const ModernSessionMinimap = React.memo(- ({- traces,- activeTraceId,- projectId,- traceCommentCounts,- openPeek,- onSelect,- totalCost,- }: {- traces: EventSessionTrace[];- activeTraceId: string | undefined;- projectId: string;- traceCommentCounts: Map<string, number> | undefined;- openPeek: OpenPeek;- onSelect: (index: number) => void;- totalCost: number;- }) => {- const minimapRef = useRef<HTMLDivElement>(null);- const virtualizer = useVirtualizer({- count: traces.length,- getScrollElement: () => minimapRef.current,- estimateSize: () => 105,- overscan: MODERN_SESSION_OVERSCAN,- getItemKey: (index) => traces[index]?.id ?? index,- });-- return (- <div- ref={minimapRef}- role="complementary"- aria-label="Session traces"- className="bg-muted/10 min-h-0 overflow-y-auto border-r"- >- <div className="bg-background sticky top-0 z-10 flex items-center justify-between gap-2 border-b px-3 py-2">- <span className="text-muted-foreground text-xs font-bold tracking-wide uppercase">- Traces · {traces.length}- </span>- <span className="text-muted-foreground text-xs font-bold">- Total cost · {usdFormatter(totalCost, 2)}- </span>- </div>- <div- style={{- height: `${virtualizer.getTotalSize()}px`,- position: "relative",- width: "100%",- }}- >- {virtualizer.getVirtualItems().map((virtualItem) => {- const trace = traces[virtualItem.index];- if (!trace) return null;- const isActive = trace.id === activeTraceId;-- return (- <SessionVirtualizedRow- key={virtualItem.key}- itemKey={String(virtualItem.key)}- measurementKey={`${String(virtualItem.key)}:${isActive}`}- source="modern"- virtualItem={virtualItem}- virtualizer={virtualizer}- >- <ModernSessionMinimapItem- trace={trace}- index={virtualItem.index}- isActive={isActive}- projectId={projectId}- traceCommentCounts={traceCommentCounts}- openPeek={openPeek}- onSelect={onSelect}- />- </SessionVirtualizedRow>- );- })}- </div>- </div>- );- },-);-ModernSessionMinimap.displayName = "ModernSessionMinimap";-export function ModernSession({- traces,+ tracesState,projectId,sessionId,+ sessionMinTimestamp,+ sessionMaxTimestamp,openPeek,traceCommentCounts,filterState,filterMeasurementKey,viewLabel,- totalCost,showInlineToolCalls,showSystemPrompt,+ sidebarFilterControls,+ onExcludeObservation,}: ModernSessionProps) {- const feedRef = useRef<HTMLDivElement>(null);- const [selectedTraceId, setSelectedTraceId] = useState<string>();+ const traces =+ tracesState.type === "loaded" ? tracesState.traces : EMPTY_TRACES;+ const [search, setSearch] = useState("");+ const [searchQuery, setSearchQuery] = useState("");+ const debouncedSetSearchQuery = useDebounce(setSearchQuery, 500, false);+ const isSearchPending = search.trim() !== searchQuery;+ const [collapsedTraceIds, setCollapsedTraceIds] = useState<Set<string>>(+ new Set(),+ );+ const [visibleTraceIds, setVisibleTraceIds] = useState<string[]>([]);+ const [pageCounts, setPageCounts] = useState<Record<string, number>>({});+ const expandedTraceIds = new Set(+ traces+ .filter((trace) => !collapsedTraceIds.has(trace.id))+ .map((trace) => trace.id),+ );++ const baseFilters: FilterState = [+ ...filterState,+ {+ column: "sessionId",+ type: "string",+ operator: "=",+ value: sessionId,+ },+ {+ column: "startTime",+ type: "datetime",+ operator: ">=",+ value: sessionMinTimestamp,+ },+ {+ column: "startTime",+ type: "datetime",+ operator: "<=",+ value: sessionMaxTimestamp,+ },+ ];+ const filtersRequireIO = filterState.some(+ (filter) =>+ (filter.column === "hasInput" || filter.column === "hasOutput") &&+ filter.type === "boolean" &&+ filter.operator === "=" &&+ filter.value,+ );++ const traceIndexById = new Map(+ traces.map((trace, index) => [trace.id, index] as const),+ );+ const activeChunkIndices = new Set<number>();+ if (!searchQuery) {+ for (const traceId of visibleTraceIds) {+ if (!expandedTraceIds.has(traceId)) continue;+ const traceIndex = traceIndexById.get(traceId);+ if (traceIndex === undefined) continue;+ activeChunkIndices.add(Math.floor(traceIndex / SIDEBAR_TRACE_CHUNK_SIZE));+ }+ }++ const queryDescriptors: Array<{+ key: string;+ page: number;+ traceIds: string[] | undefined;+ }> = [];+ if (searchQuery) {+ const key = `search:${filterMeasurementKey}:${searchQuery}`;+ const pageCount = pageCounts[key] ?? 1;+ for (let page = 1; page <= pageCount; page++) {+ queryDescriptors.push({ key, page, traceIds: undefined });+ }+ } else {+ for (const chunkIndex of activeChunkIndices) {+ const key = `browse:${filterMeasurementKey}:${chunkIndex}`;+ const pageCount = pageCounts[key] ?? 1;+ const startIndex = chunkIndex * SIDEBAR_TRACE_CHUNK_SIZE;+ const traceIds = traces+ .slice(startIndex, startIndex + SIDEBAR_TRACE_CHUNK_SIZE)+ .map((trace) => trace.id);+ for (let page = 1; page <= pageCount; page++) {+ queryDescriptors.push({ key, page, traceIds });+ }+ }+ }++ const observationQueries = api.useQueries((t) =>+ queryDescriptors.map((descriptor) =>+ t.events.all(+ {+ projectId,+ filter: descriptor.traceIds+ ? [+ ...baseFilters,+ {+ column: "traceId",+ type: "stringOptions",+ operator: "any of",+ value: descriptor.traceIds,+ },+ ]+ : baseFilters,+ searchQuery: searchQuery || null,+ searchType: searchQuery ? ["id"] : [],+ page: descriptor.page,+ limit: SIDEBAR_OBSERVATION_PAGE_SIZE,+ orderBy: { column: "startTime", order: "ASC" },+ },+ {+ staleTime: 60 * 1000,+ refetchOnWindowFocus: false,+ },+ ),+ ),+ );++ const observationsByTraceId = new Map<+ string,+ NonNullable<ModernSessionSidebarTrace["observations"]>+ >();+ const observationIdsByTraceId = new Map<string, Set<string>>();+ const traceIdsWithMatchingTraceLevelIO = new Set<string>();+ for (const query of observationQueries) {+ for (const observation of query.data?.observations ?? []) {+ if (!observation.traceId) {+ continue;+ }+ if (observation.id === `t-${observation.traceId}`) {+ traceIdsWithMatchingTraceLevelIO.add(observation.traceId);+ continue;+ }+ const observationIds = observationIdsByTraceId.get(observation.traceId);+ if (observationIds?.has(observation.id)) {+ continue;+ }+ if (observationIds) observationIds.add(observation.id);+ else {+ observationIdsByTraceId.set(+ observation.traceId,+ new Set([observation.id]),+ );+ }+ const observations = observationsByTraceId.get(observation.traceId);+ const row = {+ id: observation.id,+ name: observation.name,+ type: observation.type,+ latency: observation.latency,+ };+ if (observations) observations.push(row);+ else observationsByTraceId.set(observation.traceId, [row]);+ }+ }++ const sidebarTraces: ModernSessionSidebarTrace[] = [];+ for (const [index, trace] of traces.entries()) {+ const chunkIndex = Math.floor(index / SIDEBAR_TRACE_CHUNK_SIZE);+ const chunkKey = `browse:${filterMeasurementKey}:${chunkIndex}`;+ const relevantQueryIndices = queryDescriptors.flatMap(+ (descriptor, queryIndex) =>+ descriptor.key ===+ (searchQuery+ ? `search:${filterMeasurementKey}:${searchQuery}`+ : chunkKey)+ ? [queryIndex]+ : [],+ );+ const hasLoadedObservations = observationsByTraceId.has(trace.id);+ const isPending =+ relevantQueryIndices.length === 0 ||+ relevantQueryIndices.every(+ (queryIndex) => observationQueries[queryIndex]?.isPending,+ );+ const isError = relevantQueryIndices.some(+ (queryIndex) => observationQueries[queryIndex]?.isError,+ );+ const lastRelevantQuery =+ observationQueries[relevantQueryIndices.at(-1) ?? -1];+ const mayHaveMoreObservations = Boolean(+ lastRelevantQuery?.isPending || lastRelevantQuery?.data?.hasMore,+ );+ const observations =+ isPending && !hasLoadedObservations+ ? undefined+ : isError+ ? null+ : mayHaveMoreObservations && !hasLoadedObservations+ ? undefined+ : (observationsByTraceId.get(trace.id) ?? []);++ if (+ searchQuery &&+ !observationsByTraceId.has(trace.id) &&+ !traceIdsWithMatchingTraceLevelIO.has(trace.id)+ ) {+ continue;+ }++ sidebarTraces.push({+ trace,+ turnNumber: index + 1,+ idleGapSeconds:+ index === 0 ? null : computeIdleGapSeconds(traces[index - 1]!, trace),+ observations,+ hasMatchingTraceLevelIO:+ filtersRequireIO && traceIdsWithMatchingTraceLevelIO.has(trace.id),+ });+ }++ const lastQueryByKey = new Map<string, number>();+ queryDescriptors.forEach((descriptor, queryIndex) => {+ lastQueryByKey.set(descriptor.key, queryIndex);+ });+ const hasMoreObservations = Array.from(lastQueryByKey.values()).some(+ (queryIndex) => observationQueries[queryIndex]?.data?.hasMore,+ );+ const isLoadingMoreObservations = Array.from(lastQueryByKey.values()).some(+ (queryIndex) => observationQueries[queryIndex]?.isFetching,+ );+ const observationLoadError = observationQueries.some(+ (query) => query.isError,+ );++ const loadMoreObservations = () => {+ setPageCounts((current) => {+ let next = current;+ for (const [key, queryIndex] of lastQueryByKey) {+ const query = observationQueries[queryIndex];+ const descriptor = queryDescriptors[queryIndex];+ if (!query?.data?.hasMore || query.isFetching || !descriptor) {+ continue;+ }+ if (next === current) next = { ...current };+ next[key] = Math.max(current[key] ?? 1, descriptor.page + 1);+ }+ return next;+ });+ };++ const handleVisibleTraceIdsChange = (nextTraceIds: string[]) => {+ setVisibleTraceIds((current) => {+ if (+ current.length === nextTraceIds.length &&+ current.every((traceId, index) => traceId === nextTraceIds[index])+ ) {+ return current;+ }+ return nextTraceIds;+ });+ };++ const handleSearchChange = (nextSearch: string) => {+ setSearch(nextSearch);+ debouncedSetSearchQuery(nextSearch.trim());+ };++ const toggleTraceExpanded = (traceId: string) => {+ setCollapsedTraceIds((current) => {+ const next = new Set(current);+ if (next.has(traceId)) next.delete(traceId);+ else next.add(traceId);+ return next;+ });+ };+ const [feedRef, feedSize] = useElementSize<HTMLDivElement>();const virtualizer = useVirtualizer({count: traces.length,getScrollElement: () => feedRef.current,@@ -229,81 +328,114 @@ export function ModernSession({overscan: MODERN_SESSION_OVERSCAN,getItemKey: (index) => traces[index]?.id ?? index,});- const virtualItems = virtualizer.getVirtualItems();- const scrollOffset = virtualizer.scrollOffset ?? 0;- const activeVirtualItem =- virtualItems.find(- (item) => item.start <= scrollOffset + 1 && item.end > scrollOffset + 1,- ) ?? virtualItems.find((item) => item.start > scrollOffset);- const scrollSpyTraceId =- traces[activeVirtualItem?.index ?? 0]?.id ?? traces[0]?.id;- const activeTraceId = selectedTraceId ?? scrollSpyTraceId;+ const {+ activeItemId: activeTraceId,+ virtualItems,+ selectItem: selectTrace,+ } = useVirtualizedScrollSpy({+ items: traces,+ virtualizer,+ scrollElementRef: feedRef,+ viewportHeight: feedSize?.height ?? 0,+ endTransitionRatio: 0.2,+ });+ const observationScrollCleanupRef = useRef<(() => void) | null>(null);+ useEffect(() => () => observationScrollCleanupRef.current?.(), []);+ const handleSelect = (index: number, observationId?: string) => {+ observationScrollCleanupRef.current?.();+ observationScrollCleanupRef.current = null;+ selectTrace(index);+ if (!observationId) return;- const scrollToTrace = useCallback(- (index: number) => {- const feed = feedRef.current;- const offset = virtualizer.getOffsetForIndex(index, "start")?.[0];- if (!feed || offset === undefined) return;- // TanStack retries smooth scrolls against dynamic row measurements and- // can stop one row early. Native scrolling uses its measured target once- // and preserves the requested smooth minimap navigation.- feed.scrollTo({ top: offset, behavior: "smooth" });- },- [virtualizer],- );+ const feed = feedRef.current;+ if (!feed) return;- const selectTrace = useCallback(- (index: number) => {- const trace = traces[index];- if (!trace) return;- setSelectedTraceId(trace.id);- scrollToTrace(index);- },- [scrollToTrace, traces],- );+ const scrollToObservation = () => {+ const observation = Array.from(+ feed.querySelectorAll<HTMLElement>("[data-session-observation-id]"),+ ).find(+ (element) => element.dataset.sessionObservationId === observationId,+ );+ if (!observation) return false;- const restoreScrollSpy = () => setSelectedTraceId(undefined);+ const top =+ feed.scrollTop ++ observation.getBoundingClientRect().top -+ feed.getBoundingClientRect().top -+ Math.max(0, (feed.clientHeight - observation.clientHeight) / 2);+ feed.scrollTo({ top, behavior: "smooth" });+ return true;+ };++ if (scrollToObservation()) return;++ let timeout: number;+ const cleanup = () => {+ observer.disconnect();+ window.clearTimeout(timeout);+ };+ const observer = new MutationObserver(() => {+ if (!scrollToObservation()) return;+ cleanup();+ if (observationScrollCleanupRef.current === cleanup) {+ observationScrollCleanupRef.current = null;+ }+ });+ observer.observe(feed, { childList: true, subtree: true });+ timeout = window.setTimeout(() => {+ cleanup();+ if (observationScrollCleanupRef.current === cleanup) {+ observationScrollCleanupRef.current = null;+ }+ }, 5_000);+ observationScrollCleanupRef.current = cleanup;+ };return (- <div className="grid min-h-0 flex-1 grid-rows-[minmax(10rem,13rem)_minmax(0,1fr)] overflow-hidden lg:grid-cols-[300px_minmax(0,1fr)] lg:grid-rows-1">- <ModernSessionMinimap- traces={traces}- activeTraceId={activeTraceId}- projectId={projectId}- traceCommentCounts={traceCommentCounts}- openPeek={openPeek}- onSelect={selectTrace}- totalCost={totalCost}- />- <div- ref={feedRef}- className="min-h-0 overflow-y-auto scroll-smooth"- onWheel={restoreScrollSpy}- onTouchMove={restoreScrollSpy}- onPointerDown={(event) => {- if (event.target === event.currentTarget) restoreScrollSpy();- }}- >+ <div className="bg-background relative grid min-h-0 flex-1 grid-rows-[minmax(10rem,13rem)_minmax(0,1fr)] gap-x-4 overflow-hidden lg:grid-cols-[clamp(200px,24vw,296px)_minmax(0,1fr)] lg:grid-rows-1">+ {tracesState.type === "loading" ? (+ <ModernSessionSidebar state="loading" />+ ) : (+ <ModernSessionSidebar+ state="loaded"+ traces={isSearchPending ? [] : sidebarTraces}+ activeTraceId={activeTraceId}+ filterControls={sidebarFilterControls}+ search={search}+ onSearchChange={handleSearchChange}+ expandedTraceIds={expandedTraceIds}+ onToggleTraceExpanded={toggleTraceExpanded}+ onExcludeObservation={onExcludeObservation}+ onSelect={handleSelect}+ onVisibleTraceIdsChange={handleVisibleTraceIdsChange}+ hasMoreObservations={hasMoreObservations}+ isLoadingMoreObservations={+ isSearchPending || isLoadingMoreObservations+ }+ observationLoadError={observationLoadError}+ onLoadMoreObservations={loadMoreObservations}+ onViewportUnderfilled={+ searchQuery && !isSearchPending ? loadMoreObservations : undefined+ }+ />+ )}+ <div className="bg-card dark:bg-background relative min-h-0 min-w-[320px]"><div- style={{- height: `${virtualizer.getTotalSize()}px`,- width: "100%",- position: "relative",- }}+ ref={feedRef}+ className="h-full min-h-0 overflow-y-auto scroll-smooth">- {virtualItems.map((virtualItem) => {- const trace = traces[virtualItem.index];- if (!trace) return null;+ <div+ style={{+ height: `${virtualizer.getTotalSize()}px`,+ width: "100%",+ position: "relative",+ }}+ >+ {virtualItems.map((virtualItem) => {+ const trace = traces[virtualItem.index];+ if (!trace) return null;- return (- <SessionVirtualizedRow- key={virtualItem.key}- itemKey={String(virtualItem.key)}- measurementKey={`${String(virtualItem.key)}:${showInlineToolCalls}:${showSystemPrompt}:${filterMeasurementKey}`}- source="modern"- virtualItem={virtualItem}- virtualizer={virtualizer}- >+ const content = (<LazySessionTraceEventsRowtrace={trace}projectId={projectId}@@ -316,11 +448,23 @@ export function ModernSession({surface="modern"contentMode={showInlineToolCalls ? "all" : "conversation"}showSystemPrompt={showSystemPrompt}- isActive={trace.id === activeTraceId}/>- </SessionVirtualizedRow>- );- })}+ );++ return (+ <SessionVirtualizedRow+ key={virtualItem.key}+ itemKey={String(virtualItem.key)}+ measurementKey={`${String(virtualItem.key)}:${showInlineToolCalls}:${showSystemPrompt}:${filterMeasurementKey}`}+ source="modern"+ virtualItem={virtualItem}+ virtualizer={virtualizer}+ >+ {content}+ </SessionVirtualizedRow>+ );+ })}+ </div></div></div></div>diff --git a/web/src/components/session/ModernSessionFilterControls.tsx b/web/src/components/session/ModernSessionFilterControls.tsxnew file mode 100644index 0000000000..29ee962e4d--- /dev/null+++ b/web/src/components/session/ModernSessionFilterControls.tsx@@ -0,0 +1,343 @@+import { type ReactNode, useState } from "react";+import {+ type ColumnDefinition,+ type FilterState,+ type TableViewPresetState,+ TableViewPresetTableName,+} from "@langfuse/shared";+import {+ type ColumnOrderState,+ type VisibilityState,+} from "@tanstack/react-table";+import isEqual from "lodash/isEqual";++import {+ ModernSessionFilterDialogContent,+ type ModernSessionFilterDialogViewActions,+} from "@/src/components/session/ModernSessionFilterDialogContent";+import { ModernSessionSaveViewDialogContent } from "@/src/components/session/ModernSessionSaveViewDialogContent";+import { SESSION_DETAIL_SYSTEM_PRESETS } from "@/src/components/session/session-detail-presets";+import { type ModernSessionSidebarFilterControls } from "@/src/components/session/ModernSessionSidebar";+import {+ TableViewPresetsDrawerContent,+ TableViewPresetsDrawerRoot,+} from "@/src/components/table/table-view-presets/components/data-table-view-presets-drawer";+import { useViewData } from "@/src/components/table/table-view-presets/hooks/useViewData";+import { useViewMutations } from "@/src/components/table/table-view-presets/hooks/useViewMutations";+import { Dialog } from "@/src/components/ui/dialog";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";++type ViewControllers = {+ selectedViewId: string | null;+ appliedViewId: string | null;+ handleSetViewId: (viewId: string | null) => void;+ applyViewState: (+ viewData: TableViewPresetState,+ meta?: {+ trigger: "select" | "permalink" | "default" | "system_preset";+ viewId?: string | null;+ },+ ) => void;+};++type ModernSessionFilterControlsProps = {+ projectId: string;+ filterState: FilterState;+ filterColumns: ColumnDefinition[];+ filterColumnsWithCustomSelect: string[];+ onChange: (filters: FilterState) => void;+ viewControllers: ViewControllers;+ currentViewState: {+ orderBy: null;+ filters: FilterState;+ columnOrder: ColumnOrderState;+ columnVisibility: VisibilityState;+ searchQuery: string;+ };+ children: (controls: ModernSessionSidebarFilterControls) => ReactNode;+};++const normalizeFilters = (filters: FilterState) =>+ filters.map((filter) =>+ Object.fromEntries(+ Object.entries(filter).filter(([, value]) => value !== undefined),+ ),+ );++export function ModernSessionFilterControls({+ projectId,+ filterState,+ filterColumns,+ filterColumnsWithCustomSelect,+ onChange,+ viewControllers,+ currentViewState,+ children,+}: ModernSessionFilterControlsProps) {+ const capture = usePostHogClientCapture();+ const [filterDialogOpen, setFilterDialogOpen] = useState(false);+ const [saveViewDialogOpen, setSaveViewDialogOpen] = useState(false);+ const [manageViewsOpen, setManageViewsOpen] = useState(false);+ const [filtersToSave, setFiltersToSave] = useState<FilterState>([]);+ const activeFilterCount = filterState.length;+ const { TableViewPresetsList } = useViewData({+ tableName: TableViewPresetTableName.SessionDetail,+ projectId,+ });+ const hasWriteAccess = useHasProjectAccess({+ projectId,+ scope: "TableViewPresets:CUD",+ });+ const { createMutation, updateConfigMutation } = useViewMutations({+ handleSetViewId: viewControllers.handleSetViewId,+ applyViewState: viewControllers.applyViewState,+ });++ const matchingSystemPreset = SESSION_DETAIL_SYSTEM_PRESETS.find(+ (preset) =>+ preset.id === viewControllers.selectedViewId &&+ isEqual(normalizeFilters(preset.filters), normalizeFilters(filterState)),+ );+ const matchingSavedView = TableViewPresetsList?.find(+ (view) =>+ view.id === viewControllers.selectedViewId &&+ isEqual(normalizeFilters(view.filters), normalizeFilters(filterState)),+ );+ const matchingUserView = matchingSavedView?.isSystem+ ? undefined+ : matchingSavedView;+ const activeViewName = matchingSystemPreset?.name ?? matchingSavedView?.name;++ const openFilterDialog = () => {+ setFilterDialogOpen(true);+ capture("table:filter_builder_open", {+ tableName: "session-detail",+ isV4: true,+ });+ };++ const applyFilters = (nextFilters: FilterState) => {+ if (isEqual(normalizeFilters(nextFilters), normalizeFilters(filterState))) {+ setFilterDialogOpen(false);+ return;+ }++ onChange(nextFilters);+ const appliedFilter = nextFilters[nextFilters.length - 1];+ if (appliedFilter) {+ capture("filters:applied", {+ surface: "filter_builder",+ tableName: "session-detail",+ column: appliedFilter.column,+ filterType: appliedFilter.type,+ operator: appliedFilter.operator,+ ...("key" in appliedFilter && appliedFilter.key+ ? { key: appliedFilter.key }+ : {}),+ valueCount: Array.isArray(appliedFilter.value)+ ? appliedFilter.value.length+ : 1,+ conditionCount: nextFilters.length,+ columnConditionCount: nextFilters.filter(+ (filter) => filter.column === appliedFilter.column,+ ).length,+ isV4: true,+ });+ } else if (filterState.length > 0) {+ capture("filters:cleared", {+ surface: "filter_builder",+ tableName: "session-detail",+ clearedCount: filterState.length,+ isV4: true,+ });+ }+ setFilterDialogOpen(false);+ };++ const saveView = (name: string) => {+ capture("saved_views:create", {+ tableName: TableViewPresetTableName.SessionDetail,+ });+ createMutation.mutate({+ name,+ tableName: TableViewPresetTableName.SessionDetail,+ projectId,+ orderBy: null,+ filters: filtersToSave,+ columnOrder: currentViewState.columnOrder,+ columnVisibility: currentViewState.columnVisibility,+ searchQuery: "",+ });+ setSaveViewDialogOpen(false);+ };++ const updateCurrentView = (filters: FilterState) => {+ if (!matchingUserView) return;++ capture("saved_views:update_config", {+ tableName: TableViewPresetTableName.SessionDetail,+ viewId: matchingUserView.id,+ name: matchingUserView.name,+ });++ const viewWasApplied =+ viewControllers.appliedViewId === matchingUserView.id;+ updateConfigMutation.mutate(+ {+ projectId,+ name: matchingUserView.name,+ id: matchingUserView.id,+ tableName: TableViewPresetTableName.SessionDetail,+ orderBy: null,+ filters,+ columnOrder: viewWasApplied+ ? currentViewState.columnOrder+ : matchingUserView.columnOrder,+ columnVisibility: viewWasApplied+ ? currentViewState.columnVisibility+ : matchingUserView.columnVisibility,+ searchQuery: "",+ },+ {+ onSuccess: () => {+ onChange(filters);+ setFilterDialogOpen(false);+ },+ },+ );+ };++ const openSaveViewDialog = (filters: FilterState) => {+ setFiltersToSave(filters);+ setFilterDialogOpen(false);+ setSaveViewDialogOpen(true);+ };++ const applyPreset = (+ preset: (typeof SESSION_DETAIL_SYSTEM_PRESETS)[number],+ ) => {+ capture("saved_views:system_preset_selected", {+ tableName: TableViewPresetTableName.SessionDetail,+ presetId: preset.id,+ });+ viewControllers.handleSetViewId(preset.id);+ viewControllers.applyViewState(+ {+ filters: preset.filters,+ columnOrder: [],+ columnVisibility: {},+ orderBy: null,+ searchQuery: "",+ },+ { trigger: "system_preset", viewId: preset.id },+ );+ };++ const applySavedView = (+ view: TableViewPresetState & { id: string; name: string },+ ) => {+ capture("saved_views:view_selected", {+ tableName: TableViewPresetTableName.SessionDetail,+ viewId: view.id,+ });+ viewControllers.handleSetViewId(view.id);+ viewControllers.applyViewState(view, {+ trigger: "select",+ viewId: view.id,+ });+ };++ const clearFilters = () => {+ onChange([]);+ viewControllers.handleSetViewId(null);+ capture("filters:cleared", {+ surface: "filter_builder",+ tableName: "session-detail",+ clearedCount: activeFilterCount,+ isV4: true,+ });+ };++ let filterDialogViewActions: ModernSessionFilterDialogViewActions = {+ type: "none",+ };+ if (hasWriteAccess && matchingUserView) {+ filterDialogViewActions = {+ type: "update",+ viewName: matchingUserView.name,+ isUpdating: updateConfigMutation.isPending,+ onCreate: openSaveViewDialog,+ onUpdate: updateCurrentView,+ };+ } else if (hasWriteAccess) {+ filterDialogViewActions = {+ type: "create",+ onCreate: openSaveViewDialog,+ };+ }++ return (+ <>+ {children({+ activeFilterCount,+ activeFilters: filterState,+ activeViewName,+ selectedViewId: viewControllers.selectedViewId,+ matchingSystemPresetId: matchingSystemPreset?.id,+ matchingSavedViewId: matchingSavedView?.id,+ savedViews:+ TableViewPresetsList?.filter((view) => !view.isSystem) ?? [],+ onApplyPreset: applyPreset,+ onApplySavedView: applySavedView,+ onManageViews: () =>+ window.requestAnimationFrame(() => setManageViewsOpen(true)),+ onOpenFilterDialog: () =>+ window.requestAnimationFrame(openFilterDialog),+ onClearFilters: clearFilters,+ })}++ <Dialog open={filterDialogOpen} onOpenChange={setFilterDialogOpen}>+ {filterDialogOpen ? (+ <ModernSessionFilterDialogContent+ initialFilters={filterState}+ filterColumns={filterColumns}+ filterColumnsWithCustomSelect={filterColumnsWithCustomSelect}+ viewActions={filterDialogViewActions}+ onCancel={() => setFilterDialogOpen(false)}+ onApplyFilters={applyFilters}+ />+ ) : null}+ </Dialog>++ <Dialog open={saveViewDialogOpen} onOpenChange={setSaveViewDialogOpen}>+ {saveViewDialogOpen ? (+ <ModernSessionSaveViewDialogContent+ isSaving={createMutation.isPending}+ onCancel={() => {+ setSaveViewDialogOpen(false);+ setFilterDialogOpen(true);+ }}+ onSave={saveView}+ />+ ) : null}+ </Dialog>++ <TableViewPresetsDrawerRoot+ tableName={TableViewPresetTableName.SessionDetail}+ open={manageViewsOpen}+ onOpenChange={setManageViewsOpen}+ >+ <TableViewPresetsDrawerContent+ viewConfig={{+ tableName: TableViewPresetTableName.SessionDetail,+ projectId,+ controllers: viewControllers,+ }}+ currentState={currentViewState}+ systemFilterPresets={SESSION_DETAIL_SYSTEM_PRESETS}+ />+ </TableViewPresetsDrawerRoot>+ </>+ );+}diff --git a/web/src/components/session/ModernSessionFilterDialogContent.stories.tsx b/web/src/components/session/ModernSessionFilterDialogContent.stories.tsxnew file mode 100644index 0000000000..47952577c6--- /dev/null+++ b/web/src/components/session/ModernSessionFilterDialogContent.stories.tsx@@ -0,0 +1,89 @@+import { type ColumnDefinition, type FilterState } from "@langfuse/shared";+import { type ComponentProps } from "react";+import { fn } from "storybook/test";++import preview from "../../../.storybook/preview";+import { ModernSessionFilterDialogContent } from "@/src/components/session/ModernSessionFilterDialogContent";+import { Dialog } from "@/src/components/ui/dialog";++const filterColumns = [+ {+ name: "Name",+ id: "name",+ type: "stringOptions",+ internal: "name",+ options: [{ value: "generate-response" }, { value: "retrieve-context" }],+ },+ {+ name: "Type",+ id: "type",+ type: "stringOptions",+ internal: "type",+ options: [{ value: "GENERATION" }, { value: "SPAN" }],+ },+] satisfies ColumnDefinition[];++const filters = [+ {+ column: "type",+ type: "stringOptions",+ operator: "any of",+ value: ["GENERATION"],+ },+] satisfies FilterState;++const defaultArgs = {+ initialFilters: [],+ filterColumns,+ filterColumnsWithCustomSelect: [],+ viewActions: { type: "none" },+ onCancel: fn(),+ onApplyFilters: fn(),+} satisfies ComponentProps<typeof ModernSessionFilterDialogContent>;++const meta = preview.meta({+ component: ModernSessionFilterDialogContent,+ decorators: [+ (Story) => (+ <Dialog open onOpenChange={fn()}>+ <Story />+ </Dialog>+ ),+ ],+ parameters: { layout: "fullscreen" },+});++export default meta;++export const Default = meta.story({+ args: defaultArgs,+});++export const WithFilters = meta.story({+ args: {+ ...defaultArgs,+ initialFilters: filters,+ },+});++export const CanSaveView = meta.story({+ args: {+ ...defaultArgs,+ initialFilters: filters,+ viewActions: { type: "create", onCreate: fn() },+ },+});++export const CanUpdateSelectedView = meta.story({+ args: {+ ...defaultArgs,+ initialFilters: filters,+ viewActions: {+ type: "update",+ viewName: "Generations",+ isUpdating: false,+ onCreate: fn(),+ onUpdate: fn(),+ },+ },+});diff --git a/web/src/components/session/ModernSessionFilterDialogContent.tsx b/web/src/components/session/ModernSessionFilterDialogContent.tsxnew file mode 100644index 0000000000..597576b983--- /dev/null+++ b/web/src/components/session/ModernSessionFilterDialogContent.tsx@@ -0,0 +1,85 @@+import { type ColumnDefinition, type FilterState } from "@langfuse/shared";+import { useState } from "react";++import { Button } from "@/src/components/ui/button";+import {+ DialogBody,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/src/components/ui/dialog";+import { InlineFilterBuilder } from "@/src/features/filters/components/filter-builder";++export type ModernSessionFilterDialogViewActions =+ | { type: "none" }+ | {+ type: "create";+ onCreate: (filters: FilterState) => void;+ }+ | {+ type: "update";+ viewName: string;+ isUpdating: boolean;+ onCreate: (filters: FilterState) => void;+ onUpdate: (filters: FilterState) => void;+ };++type ModernSessionFilterDialogContentProps = {+ initialFilters: FilterState;+ filterColumns: ColumnDefinition[];+ filterColumnsWithCustomSelect: string[];+ viewActions: ModernSessionFilterDialogViewActions;+ onCancel: () => void;+ onApplyFilters: (filters: FilterState) => void;+};++export function ModernSessionFilterDialogContent({+ initialFilters,+ filterColumns,+ filterColumnsWithCustomSelect,+ viewActions,+ onCancel,+ onApplyFilters,+}: ModernSessionFilterDialogContentProps) {+ const [filters, setFilters] = useState(initialFilters);++ return (+ <DialogContent size="lg">+ <DialogHeader>+ <DialogTitle>Filter observations</DialogTitle>+ </DialogHeader>+ <DialogBody className="overflow-y-auto">+ <InlineFilterBuilder+ columns={filterColumns}+ filterState={filters}+ onChange={setFilters}+ columnsWithCustomSelect={filterColumnsWithCustomSelect}+ />+ </DialogBody>+ <DialogFooter>+ <Button variant="outline" onClick={onCancel}>+ Cancel+ </Button>+ {viewActions.type !== "none" ? (+ <Button+ variant="outline"+ onClick={() => viewActions.onCreate(filters)}+ >+ Save as new view+ </Button>+ ) : null}+ {viewActions.type === "update" ? (+ <Button+ variant="outline"+ loading={viewActions.isUpdating}+ onClick={() => viewActions.onUpdate(filters)}+ >+ Update "{viewActions.viewName}"+ </Button>+ ) : null}+ <Button onClick={() => onApplyFilters(filters)}>Apply filters</Button>+ </DialogFooter>+ </DialogContent>+ );+}diff --git a/web/src/components/session/ModernSessionSaveViewDialogContent.stories.tsx b/web/src/components/session/ModernSessionSaveViewDialogContent.stories.tsxnew file mode 100644index 0000000000..dfdffa64db--- /dev/null+++ b/web/src/components/session/ModernSessionSaveViewDialogContent.stories.tsx@@ -0,0 +1,37 @@+import { type ComponentProps } from "react";+import { fn } from "storybook/test";++import preview from "../../../.storybook/preview";+import { ModernSessionSaveViewDialogContent } from "@/src/components/session/ModernSessionSaveViewDialogContent";+import { Dialog } from "@/src/components/ui/dialog";++const defaultArgs = {+ isSaving: false,+ onCancel: fn(),+ onSave: fn(),+} satisfies ComponentProps<typeof ModernSessionSaveViewDialogContent>;++const meta = preview.meta({+ component: ModernSessionSaveViewDialogContent,+ decorators: [+ (Story) => (+ <Dialog open onOpenChange={fn()}>+ <Story />+ </Dialog>+ ),+ ],+ parameters: { layout: "fullscreen" },+});++export default meta;++export const Default = meta.story({+ args: defaultArgs,+});++export const Saving = meta.story({+ args: {+ ...defaultArgs,+ isSaving: true,+ },+});diff --git a/web/src/components/session/ModernSessionSaveViewDialogContent.tsx b/web/src/components/session/ModernSessionSaveViewDialogContent.tsxnew file mode 100644index 0000000000..a094ae95b8--- /dev/null+++ b/web/src/components/session/ModernSessionSaveViewDialogContent.tsx@@ -0,0 +1,67 @@+import { Button } from "@/src/components/ui/button";+import { useState } from "react";+import {+ DialogBody,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/src/components/ui/dialog";+import { Input } from "@/src/components/ui/input";++type ModernSessionSaveViewDialogContentProps = {+ isSaving: boolean;+ onCancel: () => void;+ onSave: (viewName: string) => void;+};++export function ModernSessionSaveViewDialogContent({+ isSaving,+ onCancel,+ onSave,+}: ModernSessionSaveViewDialogContentProps) {+ const [viewName, setViewName] = useState("");+ const saveView = () => onSave(viewName.trim());++ return (+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Save as new view</DialogTitle>+ </DialogHeader>+ <DialogBody>+ <div>+ <label+ htmlFor="modern-session-view-name"+ className="mb-2 block text-sm font-bold"+ >+ View name+ </label>+ <Input+ id="modern-session-view-name"+ value={viewName}+ onChange={(event) => setViewName(event.target.value)}+ placeholder="Name this view"+ autoFocus+ onKeyDown={(event) => {+ if (event.key === "Enter" && viewName.trim() && !isSaving) {+ saveView();+ }+ }}+ />+ </div>+ </DialogBody>+ <DialogFooter>+ <Button variant="outline" onClick={onCancel}>+ Cancel+ </Button>+ <Button+ loading={isSaving}+ disabled={!viewName.trim()}+ onClick={saveView}+ >+ Save view+ </Button>+ </DialogFooter>+ </DialogContent>+ );+}diff --git a/web/src/components/session/ModernSessionSidebar.stories.tsx b/web/src/components/session/ModernSessionSidebar.stories.tsxnew file mode 100644index 0000000000..90c151e05a--- /dev/null+++ b/web/src/components/session/ModernSessionSidebar.stories.tsx@@ -0,0 +1,604 @@+import preview from "../../../.storybook/preview";+import { expect, fn, userEvent, waitFor, within } from "storybook/test";+import { type ComponentProps, useState } from "react";++import {+ ModernSessionSidebar,+ type ModernSessionSidebarTrace,+} from "@/src/components/session/ModernSessionSidebar";+import { type EventSessionTrace } from "@/src/components/session/sessionDetailPageTypes";+import { computeIdleGapSeconds } from "@/src/components/session/sessionIdleGap";+import { type FilterState } from "@langfuse/shared";++const traces = [+ {+ id: "turn-1",+ name: "Answer product question",+ timestamp: new Date("2026-01-01T12:00:00.000Z"),+ environment: "production",+ userId: "user-1",+ observationCount: 2,+ latencyMs: 60_000,+ scores: [],+ },+ {+ id: "turn-2",+ name: "Resolve follow-up",+ timestamp: new Date("2026-01-01T12:02:00.000Z"),+ environment: "production",+ userId: "user-1",+ observationCount: 2,+ latencyMs: 60_000,+ scores: [],+ },+ {+ id: "turn-3",+ name: "Summarize findings",+ timestamp: new Date("2026-01-01T12:08:00.000Z"),+ environment: "production",+ userId: "user-1",+ observationCount: 1,+ latencyMs: 30_000,+ scores: [],+ },+] satisfies EventSessionTrace[];++const observationsByTraceId: Record<+ string,+ Array<{ id: string; name: string; type: string; latency: number | null }>+> = {+ "turn-1": [+ {+ id: "span-1",+ name: "Retrieve documentation",+ type: "SPAN",+ latency: 0.42,+ },+ {+ id: "generation-1",+ name: "Compose response",+ type: "GENERATION",+ latency: 1.8,+ },+ ],+ "turn-2": [+ { id: "tool-1", name: "Search knowledge base", type: "TOOL", latency: 0.7 },+ {+ id: "generation-2",+ name: "Write follow-up",+ type: "GENERATION",+ latency: 1.2,+ },+ ],+ "turn-3": [+ {+ id: "event-1",+ name: "Conversation closed",+ type: "EVENT",+ latency: null,+ },+ ],+};++const LARGE_SESSION_TURN_COUNT = 200;+const largeSessionTurnTopics = [+ "Troubleshoot API timeout",+ "Compare model performance",+ "Explain usage costs",+ "Debug missing traces",+ "Configure prompt versioning",+ "Review evaluation results",+ "Investigate ingestion delay",+ "Set up dataset testing",+];+const largeSessionData = Array.from(+ { length: LARGE_SESSION_TURN_COUNT },+ (_, index) => {+ const turnNumber = index + 1;+ const traceId = `large-turn-${turnNumber}`;+ const observations = [+ {+ id: `${traceId}-receive-message`,+ name: "Receive user message",+ type: "EVENT",+ latency: 0.01,+ },+ {+ id: `${traceId}-load-history`,+ name: "Load conversation history",+ type: "SPAN",+ latency: 0.08,+ },+ ...(turnNumber % 2 === 0+ ? [+ {+ id: `${traceId}-search-docs`,+ name: "Search product documentation",+ type: "TOOL",+ latency: 0.42,+ },+ ]+ : []),+ ...(turnNumber % 5 === 0+ ? [+ {+ id: `${traceId}-fetch-account`,+ name: "Fetch account context",+ type: "TOOL",+ latency: 0.27,+ },+ ]+ : []),+ {+ id: `${traceId}-generate-response`,+ name: "Generate assistant response",+ type: "GENERATION",+ latency: 0.9 + (turnNumber % 7) * 0.13,+ },+ {+ id: `${traceId}-validate-response`,+ name: "Validate response against policy",+ type: "SPAN",+ latency: 0.06,+ },+ {+ id: `${traceId}-persist-response`,+ name: "Persist assistant message",+ type: "EVENT",+ latency: 0.02,+ },+ ];++ return {+ trace: {+ id: traceId,+ name:+ largeSessionTurnTopics[index % largeSessionTurnTopics.length] ??+ "Continue conversation",+ timestamp: new Date(+ new Date("2026-01-01T12:00:00.000Z").getTime() + index * 90_000,+ ),+ environment: "production",+ userId: "large-session-user",+ observationCount: observations.length,+ latencyMs: Math.round(+ observations.reduce(+ (total, observation) => total + observation.latency,+ 0,+ ) * 1_000,+ ),+ scores: [],+ } satisfies EventSessionTrace,+ observations,+ };+ },+);+const largeSessionTraces = largeSessionData.map(({ trace }) => trace);+const largeSessionObservationsByTraceId = Object.fromEntries(+ largeSessionData.map(({ trace, observations }) => [trace.id, observations]),+);+const onExcludeObservation = fn();++const toSidebarTraces = (+ sourceTraces: EventSessionTrace[],+ observations: Record<+ string,+ Array<{ id: string; name: string; type: string; latency: number | null }>+ >,+): ModernSessionSidebarTrace[] =>+ sourceTraces.map((trace, index) => ({+ trace,+ turnNumber: index + 1,+ idleGapSeconds:+ index === 0+ ? null+ : computeIdleGapSeconds(sourceTraces[index - 1]!, trace),+ observations: observations[trace.id] ?? [],+ hasMatchingTraceLevelIO: false,+ }));++const sidebarTraces = toSidebarTraces(traces, observationsByTraceId);+const largeSessionSidebarTraces = toSidebarTraces(+ largeSessionTraces,+ largeSessionObservationsByTraceId,+);++const activeFilters = [+ {+ column: "type",+ type: "stringOptions",+ operator: "any of",+ value: ["GENERATION", "SPAN"],+ },+ {+ column: "environment",+ type: "stringOptions",+ operator: "any of",+ value: ["production"],+ },+] satisfies FilterState;++const loadedArgs = {+ state: "loaded",+ traces: sidebarTraces,+ activeTraceId: "turn-2",+ filterControls: {+ activeFilterCount: 0,+ activeFilters: [],+ activeViewName: undefined,+ selectedViewId: null,+ matchingSystemPresetId: undefined,+ matchingSavedViewId: undefined,+ savedViews: [],+ onApplyPreset: fn(),+ onApplySavedView: fn(),+ onManageViews: fn(),+ onOpenFilterDialog: fn(),+ onClearFilters: fn(),+ },+ search: "",+ onSearchChange: fn(),+ expandedTraceIds: new Set(traces.map((trace) => trace.id)),+ onToggleTraceExpanded: fn(),+ onExcludeObservation,+ onSelect: fn(),+ onVisibleTraceIdsChange: fn(),+ hasMoreObservations: false,+ isLoadingMoreObservations: false,+ observationLoadError: false,+ onLoadMoreObservations: fn(),+} satisfies Extract<+ ComponentProps<typeof ModernSessionSidebar>,+ { state: "loaded" }+>;++function assertLoadedArgs(+ args: ComponentProps<typeof ModernSessionSidebar>,+): asserts args is Extract<+ ComponentProps<typeof ModernSessionSidebar>,+ { state: "loaded" }+> {+ if (args.state !== "loaded") {+ throw new Error("Expected loaded sidebar args");+ }+}++function ModernSessionSidebarStory(+ args: ComponentProps<typeof ModernSessionSidebar>,+) {+ const [search, setSearch] = useState(+ args.state === "loaded" ? args.search : "",+ );+ const [expandedTraceIds, setExpandedTraceIds] = useState(+ args.state === "loaded" ? args.expandedTraceIds : new Set<string>(),+ );++ if (args.state === "loading") {+ return (+ <div className="h-screen w-[296px]">+ <ModernSessionSidebar state="loading" />+ </div>+ );+ }++ const normalizedSearch = search.trim().toLowerCase();+ const visibleTraces = normalizedSearch+ ? args.traces.flatMap((sidebarTrace) => {+ const matchingObservations = sidebarTrace.observations?.filter(+ (observation) =>+ (observation.name ?? "").toLowerCase().includes(normalizedSearch),+ );+ const traceMatches = (sidebarTrace.trace.name ?? "")+ .toLowerCase()+ .includes(normalizedSearch);+ if (!traceMatches && matchingObservations?.length === 0) return [];+ return [{ ...sidebarTrace, observations: matchingObservations }];+ })+ : args.traces;++ return (+ <div className="h-screen w-[296px]">+ <ModernSessionSidebar+ {...args}+ traces={visibleTraces}+ search={search}+ onSearchChange={(nextSearch) => {+ setSearch(nextSearch);+ args.onSearchChange(nextSearch);+ }}+ expandedTraceIds={expandedTraceIds}+ onToggleTraceExpanded={(traceId) => {+ setExpandedTraceIds((current) => {+ const next = new Set(current);+ if (next.has(traceId)) next.delete(traceId);+ else next.add(traceId);+ return next;+ });+ args.onToggleTraceExpanded(traceId);+ }}+ />+ </div>+ );+}++const meta = preview.meta({+ component: ModernSessionSidebar,+ parameters: { layout: "fullscreen", a11y: { test: "error" } },+ render: (args) => <ModernSessionSidebarStory {...args} />,+});++export default meta;++export const Default = meta.story({ args: loadedArgs });++export const DarkMode = meta.story({+ args: {+ ...loadedArgs,+ traces: [+ sidebarTraces[0]!,+ {+ ...sidebarTraces[1]!,+ observations: [],+ hasMatchingTraceLevelIO: true,+ },+ { ...sidebarTraces[2]!, observations: [] },+ ],+ activeTraceId: "turn-1",+ filterControls: {+ ...loadedArgs.filterControls,+ activeFilterCount: 2,+ activeFilters: [+ {+ column: "hasInput",+ type: "boolean",+ operator: "=",+ value: true,+ },+ {+ column: "hasOutput",+ type: "boolean",+ operator: "=",+ value: true,+ },+ ],+ activeViewName: "All observations with I/O",+ selectedViewId: "__langfuse_with_io__",+ matchingSystemPresetId: "__langfuse_with_io__",+ },+ },+ globals: { theme: "dark" },+});++export const ActiveFilters = meta.story({+ args: {+ ...loadedArgs,+ filterControls: {+ ...loadedArgs.filterControls,+ activeFilterCount: 2,+ activeFilters,+ },+ },+});++export const ActiveView = meta.story({+ args: {+ ...loadedArgs,+ filterControls: {+ ...loadedArgs.filterControls,+ activeFilterCount: 2,+ activeFilters,+ activeViewName: "All observations with I/O",+ selectedViewId: "__langfuse_with_io__",+ matchingSystemPresetId: "__langfuse_with_io__",+ },+ },+});++export const TraceLevelIOOnly = meta.story({+ args: {+ ...loadedArgs,+ traces: [+ {+ ...sidebarTraces[0]!,+ observations: [],+ hasMatchingTraceLevelIO: true,+ },+ ],+ activeTraceId: "turn-1",+ expandedTraceIds: new Set(["turn-1"]),+ filterControls: {+ ...loadedArgs.filterControls,+ activeFilterCount: 2,+ activeFilters: [+ {+ column: "hasInput",+ type: "boolean",+ operator: "=",+ value: true,+ },+ {+ column: "hasOutput",+ type: "boolean",+ operator: "=",+ value: true,+ },+ ],+ activeViewName: "All observations with I/O",+ selectedViewId: "__langfuse_with_io__",+ matchingSystemPresetId: "__langfuse_with_io__",+ },+ },+});++export const LargeSession = meta.story({+ args: {+ ...loadedArgs,+ traces: largeSessionSidebarTraces,+ activeTraceId: "large-turn-1",+ expandedTraceIds: new Set(largeSessionTraces.map((trace) => trace.id)),+ },+});++export const LoadingTurns = meta.story({+ args: {+ state: "loading",+ },+});++export const LoadingObservations = meta.story({+ args: {+ ...loadedArgs,+ traces: sidebarTraces.map((sidebarTrace) => ({+ ...sidebarTrace,+ observations: undefined,+ })),+ },+});++export const ObservationLoadError = meta.story({+ args: {+ ...loadedArgs,+ traces: [],+ activeTraceId: undefined,+ search: "missing",+ expandedTraceIds: new Set(),+ observationLoadError: true,+ },+});++export const TestSelectsFilteredTurnByStableNumber = meta.story({+ name: "(Test) Selects filtered turn by stable number",+ args: {+ ...loadedArgs,+ traces: [+ {+ ...sidebarTraces[2]!,+ turnNumber: 3,+ observations: [+ {+ id: "observation-3",+ name: "Matching observation",+ type: "SPAN",+ latency: 0.5,+ },+ ],+ },+ ],+ activeTraceId: "turn-3",+ search: "matching",+ expandedTraceIds: new Set(["turn-3"]),+ onSelect: fn(),+ },+ play: async ({ args, canvasElement }) => {+ assertLoadedArgs(args);+ const canvas = within(canvasElement);+ await expect(canvas.getByText("3")).toBeInTheDocument();+ await expect(canvas.getByText("Matching observation")).toBeInTheDocument();++ await userEvent.click(+ canvas.getByRole("button", { name: /Summarize findings/i }),+ );+ await expect(args.onSelect).toHaveBeenCalledWith(2);+ },+});++export const TestSelectsObservation = meta.story({+ name: "(Test) Selects observation",+ args: {+ ...loadedArgs,+ onSelect: fn(),+ },+ play: async ({ args, canvasElement }) => {+ assertLoadedArgs(args);+ const canvas = within(canvasElement);++ await userEvent.click(+ canvas.getByRole("button", { name: /^Search knowledge base 0.70s$/i }),+ );+ await expect(args.onSelect).toHaveBeenCalledWith(1, "tool-1");+ },+});++export const TestLoadsUnderfilledSearchResults = meta.story({+ name: "(Test) Loads underfilled search results",+ args: {+ ...loadedArgs,+ traces: [sidebarTraces[0]!],+ activeTraceId: "turn-1",+ search: "retrieve",+ expandedTraceIds: new Set(["turn-1"]),+ hasMoreObservations: true,+ onVisibleTraceIdsChange: fn(),+ onViewportUnderfilled: fn(),+ },+ play: async ({ args }) => {+ assertLoadedArgs(args);+ await waitFor(() => {+ expect(args.onVisibleTraceIdsChange).toHaveBeenCalledWith(["turn-1"]);+ expect(args.onViewportUnderfilled).toHaveBeenCalled();+ });+ },+});++export const TestLoadsNearListEnd = meta.story({+ name: "(Test) Loads near list end",+ args: {+ ...loadedArgs,+ traces: largeSessionSidebarTraces,+ activeTraceId: "large-turn-1",+ expandedTraceIds: new Set(largeSessionTraces.map((trace) => trace.id)),+ hasMoreObservations: true,+ onLoadMoreObservations: fn(),+ },+ play: async ({ args, canvasElement }) => {+ assertLoadedArgs(args);+ const canvas = within(canvasElement);+ const region = canvas.getByRole("region", { name: "Session turns" });++ await waitFor(() => {+ expect(region.scrollHeight).toBeGreaterThan(region.clientHeight);+ });+ region.scrollTop = region.scrollHeight;+ region.dispatchEvent(new Event("scroll", { bubbles: true }));++ await waitFor(() => {+ expect(args.onLoadMoreObservations).toHaveBeenCalled();+ });+ },+});++export const TestDistinguishesTraceLevelIO = meta.story({+ name: "(Test) Distinguishes trace-level I/O",+ args: {+ ...loadedArgs,+ traces: [+ {+ ...sidebarTraces[0]!,+ observations: [],+ hasMatchingTraceLevelIO: true,+ },+ {+ ...sidebarTraces[1]!,+ observations: [],+ },+ ],+ activeTraceId: "turn-1",+ expandedTraceIds: new Set(["turn-1", "turn-2"]),+ filterControls: {+ ...loadedArgs.filterControls,+ activeFilterCount: 1,+ },+ onSelect: fn(),+ },+ play: async ({ args, canvasElement }) => {+ assertLoadedArgs(args);+ const canvas = within(canvasElement);+ await expect(canvas.getByText("Trace-level I/O only")).toBeInTheDocument();+ await expect(+ canvas.getByText("No matching child observations"),+ ).toBeInTheDocument();++ await userEvent.click(canvas.getByText("Trace-level I/O only"));+ await expect(args.onSelect).toHaveBeenCalledWith(0);+ },+});diff --git a/web/src/components/session/ModernSessionSidebar.tsx b/web/src/components/session/ModernSessionSidebar.tsxnew file mode 100644index 0000000000..0fc6af3d87--- /dev/null+++ b/web/src/components/session/ModernSessionSidebar.tsx@@ -0,0 +1,669 @@+import React, { useCallback, useRef } from "react";+import { useVirtualizer } from "@tanstack/react-virtual";+import {+ ChevronDown,+ ListFilter,+ MoreHorizontal,+ Pencil,+ Save,+ Search,+ X,+} from "lucide-react";+import { type FilterState } from "@langfuse/shared";++import { renderFilterIcon } from "@/src/components/ItemBadge";+import { SessionVirtualizedRow } from "@/src/components/session/SessionVirtualizedRow";+import { type EventSessionTrace } from "@/src/components/session/sessionDetailPageTypes";+import {+ ModernSessionViewDropdownMenu,+ type ModernSessionViewDropdownMenuControls,+} from "@/src/components/session/ModernSessionViewDropdownMenu";+import { SESSION_DETAIL_VIEW_TRIGGER_ID } from "@/src/components/session/session-detail-presets";+import {+ formatIdleGap,+ IDLE_GAP_THRESHOLD_SECONDS,+} from "@/src/components/session/sessionIdleGap";+import { Input } from "@/src/components/ui/input";+import { Button } from "@/src/components/ui/button";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/src/components/ui/dropdown-menu";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/src/components/ui/tooltip";+import { InlineFilterState } from "@/src/features/filters/components/filter-builder";+import { ComposerTokens } from "@/src/features/search-bar/components/ComposerTokens";+import { filterStateToQueryText } from "@/src/features/search-bar/lib/filter-state-to-query";+import { formatIntervalSeconds } from "@/src/utils/dates";+import { cn } from "@/src/utils/tailwind";++const OBSERVATION_LIST_OVERSCAN = 5;+const SIDEBAR_AUTO_FOLLOW_IDLE_MS = 750;++type ObservationListRow = {+ id: string;+ name: string | null;+ type: string;+ latency: number | null;+};++type ObservationListRowsState =+ | { type: "loading" }+ | { type: "error" }+ | { type: "trace-io-only" }+ | { type: "empty"; hasFilters: boolean }+ | { type: "loaded"; rows: ObservationListRow[] };++export type ModernSessionSidebarTrace = {+ trace: EventSessionTrace;+ turnNumber: number;+ idleGapSeconds: number | null;+ observations: ObservationListRow[] | null | undefined;+ hasMatchingTraceLevelIO: boolean;+};++const EMPTY_TRACES: ModernSessionSidebarTrace[] = [];++export type ModernSessionSidebarFilterControls =+ ModernSessionViewDropdownMenuControls & {+ activeFilterCount: number;+ activeFilters: FilterState;+ activeViewName: string | undefined;+ selectedViewId: string | null;+ onClearFilters: () => void;+ };++function ObservationListRows({+ state,+ onSelectObservation,+ onExcludeObservation,+}:+ | {+ state: Extract<+ ObservationListRowsState,+ { type: "loading" | "error" | "trace-io-only" | "empty" }+ >;+ onSelectObservation?: never;+ onExcludeObservation?: never;+ }+ | {+ state: Extract<ObservationListRowsState, { type: "loaded" }>;+ onSelectObservation: (observationId: string) => void;+ onExcludeObservation?: (name: string) => void;+ }) {+ if (state.type === "loading") {+ return (+ <div className="-mx-1 flex flex-col gap-1 px-1 py-2">+ <div className="bg-muted h-3 w-3/4 animate-pulse rounded-sm" />+ <div className="bg-muted h-3 w-1/2 animate-pulse rounded-sm" />+ </div>+ );+ }++ if (state.type === "empty") {+ return (+ <p className="text-muted-foreground -mx-1 px-1 py-2 text-xs">+ {state.hasFilters+ ? "No matching child observations"+ : "No child observations"}+ </p>+ );+ }++ if (state.type === "trace-io-only") {+ return (+ <div className="border-border bg-border/40 text-foreground -mx-1 mt-2 rounded-sm border px-2 py-1.5 text-xs">+ Trace-level I/O only+ </div>+ );+ }++ if (state.type === "error") {+ return (+ <p className="text-muted-foreground -mx-1 px-1 py-2 text-xs">+ Failed to load observations+ </p>+ );+ }++ if (!onSelectObservation) {+ throw new Error("Loaded observation rows require a selection handler");+ }++ return (+ <div className="mt-2 flex flex-col">+ {state.rows.map((observation) => (+ <div+ key={observation.id}+ className="hover:bg-foreground/10 -mr-2 -ml-1 flex items-center rounded-sm transition-colors duration-150"+ >+ <button+ type="button"+ onClick={() => onSelectObservation(observation.id)}+ className="flex min-w-0 flex-1 items-center gap-2 px-1 py-1 text-left"+ >+ {renderFilterIcon(observation.type)}+ <span+ className="text-muted-foreground min-w-0 flex-1 truncate text-[13px]"+ title={observation.name ?? observation.id}+ >+ {observation.name ?? observation.id}+ </span>+ {observation.latency !== null && observation.type !== "EVENT" ? (+ <span className="text-muted-foreground shrink-0 font-mono text-[11px]">+ {formatIntervalSeconds(observation.latency)}+ </span>+ ) : null}+ </button>+ {observation.name && onExcludeObservation ? (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ size="icon"+ className="text-muted-foreground hover:text-muted-foreground -my-1 -mr-0.5 h-8 w-8 shrink-0 hover:bg-transparent"+ aria-label={`Actions for ${observation.name}`}+ >+ <MoreHorizontal className="h-3.5 w-3.5" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" sideOffset={0}>+ <DropdownMenuItem+ onSelect={() =>+ onExcludeObservation(observation.name as string)+ }+ >+ Exclude similar observations+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ ) : null}+ </div>+ ))}+ </div>+ );+}++const TurnCard = React.memo(+ ({+ sidebarTrace,+ selectIndex,+ isActive,+ isCollapsed,+ onToggleCollapse,+ onSelect,+ hasFilters,+ onExcludeObservation,+ }: {+ sidebarTrace: ModernSessionSidebarTrace;+ selectIndex: number;+ isActive: boolean;+ isCollapsed: boolean;+ onToggleCollapse: (traceId: string) => void;+ onSelect: (index: number, observationId?: string) => void;+ hasFilters: boolean;+ onExcludeObservation: (name: string) => void;+ }) => {+ const { trace, turnNumber, observations, hasMatchingTraceLevelIO } =+ sidebarTrace;+ const isTraceLevelIOOnly =+ hasMatchingTraceLevelIO && observations?.length === 0;++ return (+ <div+ onClick={(event) => {+ if (!isTraceLevelIOOnly) return;+ if ((event.target as Element).closest("button, [role='button']")) {+ return;+ }+ onSelect(selectIndex);+ }}+ className={cn(+ "group hover:bg-muted/60 rounded-sm border border-transparent p-2 transition-colors duration-150",+ isActive && "border-primary-accent/50 bg-background dark:bg-muted",+ isTraceLevelIOOnly && "cursor-pointer",+ )}+ data-observation-list-active={isActive}+ >+ <div className="flex w-full items-center gap-2">+ <button+ type="button"+ onClick={() => onSelect(selectIndex)}+ className="flex min-w-0 flex-1 items-center gap-2 text-left"+ aria-current={isActive ? "true" : undefined}+ >+ <span className="border-border bg-tertiary text-foreground flex h-4 w-4 shrink-0 items-center justify-center rounded-sm border font-mono text-[10px]">+ {turnNumber}+ </span>+ <span+ className="min-w-0 flex-1 truncate text-[13px] font-bold"+ title={trace.name ?? "Trace"}+ >+ {trace.name ?? "Trace"}+ </span>+ </button>+ <button+ type="button"+ aria-label={isCollapsed ? "Expand turn" : "Collapse turn"}+ onClick={() => onToggleCollapse(trace.id)}+ className="text-muted-foreground -my-2 -mr-2.5 -ml-2 flex h-8 w-8 shrink-0 items-center justify-center"+ >+ <ChevronDown+ className={cn(+ "h-3 w-3 transition-transform duration-150",+ isCollapsed ? "-rotate-90" : "rotate-0",+ )}+ strokeWidth={1.6}+ />+ </button>+ </div>+ {!isCollapsed ? (+ observations === undefined ? (+ <ObservationListRows state={{ type: "loading" }} />+ ) : observations === null ? (+ <ObservationListRows state={{ type: "error" }} />+ ) : observations.length === 0 ? (+ <ObservationListRows+ state={+ isTraceLevelIOOnly+ ? { type: "trace-io-only" }+ : { type: "empty", hasFilters }+ }+ />+ ) : (+ <ObservationListRows+ state={{ type: "loaded", rows: observations }}+ onSelectObservation={(observationId) =>+ onSelect(selectIndex, observationId)+ }+ onExcludeObservation={onExcludeObservation}+ />+ )+ ) : null}+ </div>+ );+ },+);+TurnCard.displayName = "TurnCard";++export function ModernSessionSidebar(+ props:+ | { state: "loading" }+ | {+ state: "loaded";+ traces: ModernSessionSidebarTrace[];+ activeTraceId: string | undefined;+ filterControls: ModernSessionSidebarFilterControls;+ search: string;+ onSearchChange: (search: string) => void;+ expandedTraceIds: ReadonlySet<string>;+ onToggleTraceExpanded: (traceId: string) => void;+ onExcludeObservation: (name: string) => void;+ onSelect: (index: number, observationId?: string) => void;+ onVisibleTraceIdsChange: (traceIds: string[]) => void;+ hasMoreObservations: boolean;+ isLoadingMoreObservations: boolean;+ observationLoadError: boolean;+ onLoadMoreObservations: () => void;+ onViewportUnderfilled?: () => void;+ },+) {+ const traces = props.state === "loaded" ? props.traces : EMPTY_TRACES;+ const activeTraceId =+ props.state === "loaded" ? props.activeTraceId : undefined;+ const listRef = useRef<HTMLDivElement>(null);+ const isSidebarPointerDownRef = useRef(false);+ const autoFollowPausedUntilRef = useRef(0);++ const virtualizer = useVirtualizer({+ count: traces.length,+ getScrollElement: () => listRef.current,+ estimateSize: () => 160,+ overscan: OBSERVATION_LIST_OVERSCAN,+ getItemKey: (index) => traces[index]?.trace.id ?? index,+ onChange: (instance) => {+ if (props.state !== "loaded") return;++ props.onVisibleTraceIdsChange(+ instance.getVirtualItems().flatMap((virtualItem) => {+ const traceId = traces[virtualItem.index]?.trace.id;+ return traceId ? [traceId] : [];+ }),+ );++ const scrollElement = instance.scrollElement;+ if (+ props.onViewportUnderfilled &&+ props.hasMoreObservations &&+ !props.isLoadingMoreObservations &&+ scrollElement &&+ instance.getTotalSize() <= scrollElement.clientHeight+ ) {+ props.onViewportUnderfilled();+ }+ },+ });+ const activeTraceIndex = activeTraceId+ ? traces.findIndex(({ trace }) => trace.id === activeTraceId)+ : -1;+ const virtualItems = virtualizer.getVirtualItems();+ const setListElement = useCallback(+ (element: HTMLDivElement | null) => {+ listRef.current = element;+ if (+ !element ||+ activeTraceIndex === -1 ||+ isSidebarPointerDownRef.current ||+ Date.now() < autoFollowPausedUntilRef.current+ ) {+ return;+ }++ // `auto` moves the minimum distance and does nothing while the row is visible.+ virtualizer.scrollToIndex(activeTraceIndex, { align: "auto" });+ },+ [activeTraceIndex, virtualizer],+ );++ const handleTransientSidebarScroll = () => {+ autoFollowPausedUntilRef.current = Date.now() + SIDEBAR_AUTO_FOLLOW_IDLE_MS;+ };++ const handleSidebarScroll = (event: React.UIEvent<HTMLDivElement>) => {+ const { clientHeight, scrollTop } = event.currentTarget;+ const viewportBottom = scrollTop + clientHeight;+ const visibleTurn = virtualItems.findLast(+ (virtualItem) => virtualItem.start < viewportBottom,+ );+ const loadMoreThreshold = visibleTurn+ ? Math.min(240, visibleTurn.size / 4)+ : 0;+ if (+ props.state === "loaded" &&+ props.hasMoreObservations &&+ !props.isLoadingMoreObservations &&+ visibleTurn &&+ viewportBottom >= visibleTurn.end - loadMoreThreshold+ ) {+ props.onLoadMoreObservations();+ }+ };++ const handleSidebarPointerDown = () => {+ isSidebarPointerDownRef.current = true;+ };++ const handleSidebarPointerEnd = () => {+ isSidebarPointerDownRef.current = false;+ handleTransientSidebarScroll();+ };++ if (props.state === "loading") {+ return (+ <div+ role="complementary"+ aria-label="Session observations"+ aria-busy="true"+ className="bg-background relative flex h-full min-h-0 flex-col border-r"+ >+ <div className="flex shrink-0 items-center border-b px-2 py-2.5">+ <div className="bg-muted h-7 flex-1 animate-pulse rounded-sm" />+ </div>+ <div className="flex min-h-0 flex-1 flex-col gap-2 px-1 pt-0.5 pb-4">+ {[0, 1, 2].map((index) => (+ <div+ key={index}+ className="flex flex-col gap-2 rounded-sm border border-transparent p-2"+ >+ <div className="flex items-center gap-2">+ <div className="bg-muted h-4 w-4 animate-pulse rounded-sm" />+ <div className="bg-muted h-3 flex-1 animate-pulse rounded-sm" />+ <div className="bg-muted h-4 w-4 animate-pulse rounded-sm" />+ </div>+ <div className="bg-muted h-2.5 w-3/4 animate-pulse rounded-sm" />+ <div className="bg-muted h-2.5 w-1/2 animate-pulse rounded-sm" />+ </div>+ ))}+ </div>+ </div>+ );+ }++ const {+ filterControls,+ search,+ onSearchChange,+ expandedTraceIds,+ onToggleTraceExpanded,+ onExcludeObservation,+ onSelect,+ } = props;+ const handleSearchChange = (nextSearch: string) => {+ virtualizer.scrollToOffset(0);+ onSearchChange(nextSearch);+ };+ const showFilterSummary = Boolean(+ filterControls.activeFilterCount > 0 ||+ filterControls.activeViewName ||+ filterControls.selectedViewId,+ );+ const filterSummaryLabel = filterControls.activeViewName+ ? `View: ${filterControls.activeViewName}`+ : `${filterControls.activeFilterCount} active filter${filterControls.activeFilterCount === 1 ? "" : "s"}`;+ const activeFilterQuery = filterStateToQueryText(+ filterControls.activeFilters,+ );+ const hasFilterRepresentation = Boolean(+ activeFilterQuery.text || activeFilterQuery.skippedFilters.length > 0,+ );++ return (+ <div+ role="complementary"+ aria-label="Session observations"+ className="bg-background relative flex h-full min-h-0 flex-col border-r"+ >+ <div className="shrink-0 border-b">+ <div className="flex items-center gap-1 px-2 py-2.5">+ <div className="relative min-w-0 flex-1">+ <Search+ className="text-foreground-tertiary absolute top-1/2 left-2 h-3.5 w-3.5 -translate-y-1/2"+ strokeWidth={1.6}+ />+ <Input+ value={search}+ onChange={(event) => handleSearchChange(event.target.value)}+ aria-label="Search turns and observations"+ placeholder="Search turns and observations"+ className="h-7 rounded-sm bg-transparent pl-7 font-mono text-xs"+ />+ </div>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ id={SESSION_DETAIL_VIEW_TRIGGER_ID}+ type="button"+ variant="outline"+ size="icon"+ className="relative h-7 w-7 shrink-0 rounded-sm"+ aria-label="Filter observations"+ >+ <ListFilter className="h-3.5 w-3.5" />+ </Button>+ </DropdownMenuTrigger>+ <ModernSessionViewDropdownMenu controls={filterControls} />+ </DropdownMenu>+ </div>+ {showFilterSummary ? (+ <div className="border-t px-2 py-2.5">+ <div className="border-border/80 bg-muted/30 grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-x-1.5 rounded-md border py-2 pr-1 pl-2.5">+ <Tooltip>+ <TooltipTrigger asChild>+ <span+ className="text-muted-foreground min-w-0 overflow-hidden font-mono text-[10px] text-ellipsis whitespace-nowrap"+ tabIndex={0}+ >+ {filterSummaryLabel}+ </span>+ </TooltipTrigger>+ <TooltipContent side="bottom" className="max-w-80 p-2">+ {hasFilterRepresentation ? (+ <div className="flex flex-wrap gap-1">+ {activeFilterQuery.text ? (+ <span className="min-w-0 font-mono text-xs leading-6">+ <ComposerTokens+ draft={activeFilterQuery.text}+ showDiagnostics={false}+ />+ </span>+ ) : null}+ <InlineFilterState+ filterState={activeFilterQuery.skippedFilters}+ className="m-0"+ />+ </div>+ ) : (+ <span className="text-muted-foreground text-xs">+ No filters+ </span>+ )}+ </TooltipContent>+ </Tooltip>+ <div className="flex shrink-0 items-center">+ {!filterControls.activeViewName ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ className="text-muted-foreground hover:text-foreground h-5 w-5"+ aria-label="Save filters as view"+ onClick={filterControls.onOpenFilterDialog}+ >+ <Save className="h-3 w-3" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>Save as view</TooltipContent>+ </Tooltip>+ ) : null}+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ className="text-muted-foreground hover:text-foreground h-5 w-5"+ aria-label="Edit filters"+ onClick={filterControls.onOpenFilterDialog}+ >+ <Pencil className="h-3 w-3" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>Edit filters</TooltipContent>+ </Tooltip>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ className="text-muted-foreground hover:text-foreground h-5 w-5"+ aria-label="Clear filters"+ onClick={filterControls.onClearFilters}+ >+ <X className="h-3 w-3" />+ </Button>+ </TooltipTrigger>+ <TooltipContent>Clear filters</TooltipContent>+ </Tooltip>+ </div>+ </div>+ </div>+ ) : null}+ </div>+ <div+ ref={setListElement}+ role="region"+ aria-label="Session turns"+ className="min-h-0 flex-1 overflow-y-auto pt-0.5 pb-4"+ onWheel={handleTransientSidebarScroll}+ onTouchMove={handleTransientSidebarScroll}+ onScroll={handleSidebarScroll}+ onPointerDown={handleSidebarPointerDown}+ onPointerUp={handleSidebarPointerEnd}+ onPointerCancel={handleSidebarPointerEnd}+ onPointerLeave={handleSidebarPointerEnd}+ >+ {traces.length === 0 ? (+ <div className="text-muted-foreground px-3 py-6 text-center text-xs">+ {props.isLoadingMoreObservations+ ? "Loading observations..."+ : props.observationLoadError+ ? "Failed to load observations"+ : search+ ? "No matching turns"+ : "No turns"}+ </div>+ ) : (+ <div+ style={{+ height: `${virtualizer.getTotalSize()}px`,+ position: "relative",+ width: "100%",+ }}+ >+ {virtualItems.map((virtualItem) => {+ const sidebarTrace = traces[virtualItem.index];+ if (!sidebarTrace) return null;+ const { trace } = sidebarTrace;+ const isCollapsed = !expandedTraceIds.has(trace.id);+ const gap = sidebarTrace.idleGapSeconds;+ return (+ <SessionVirtualizedRow+ key={virtualItem.key}+ itemKey={String(virtualItem.key)}+ measurementKey={`${String(virtualItem.key)}:${isCollapsed}:${search}`}+ source="modern"+ virtualItem={virtualItem}+ virtualizer={virtualizer}+ >+ {gap !== null &&+ gap !== undefined &&+ gap >= IDLE_GAP_THRESHOLD_SECONDS ? (+ <div className="my-0.5 mb-2 flex items-center bg-[repeating-linear-gradient(315deg,hsl(var(--foreground)/0.07)_0_1px,transparent_1px_5px)] px-3 py-[5px]">+ <span className="text-muted-foreground font-mono text-[11px] whitespace-nowrap">+ +{formatIdleGap(gap)} idle+ </span>+ </div>+ ) : null}+ <div className="px-1 pb-2">+ <TurnCard+ sidebarTrace={sidebarTrace}+ selectIndex={sidebarTrace.turnNumber - 1}+ isActive={trace.id === activeTraceId}+ isCollapsed={isCollapsed}+ onToggleCollapse={onToggleTraceExpanded}+ onSelect={onSelect}+ hasFilters={+ search.trim() !== "" ||+ filterControls.activeFilterCount > 0+ }+ onExcludeObservation={onExcludeObservation}+ />+ </div>+ </SessionVirtualizedRow>+ );+ })}+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/web/src/components/session/ModernSessionViewDropdownMenu.stories.tsx b/web/src/components/session/ModernSessionViewDropdownMenu.stories.tsxnew file mode 100644index 0000000000..08a6b11476--- /dev/null+++ b/web/src/components/session/ModernSessionViewDropdownMenu.stories.tsx@@ -0,0 +1,68 @@+import { fn } from "storybook/test";++import preview from "../../../.storybook/preview";+import {+ ModernSessionViewDropdownMenu,+ type ModernSessionViewDropdownMenuControls,+} from "@/src/components/session/ModernSessionViewDropdownMenu";+import {+ DropdownMenu,+ DropdownMenuTrigger,+} from "@/src/components/ui/dropdown-menu";++const savedViews = [+ {+ id: "view-agent-steps",+ name: "Agent steps",+ filters: [],+ columnOrder: [],+ columnVisibility: {},+ orderBy: null,+ searchQuery: "",+ },+ {+ id: "view-generations",+ name: "Generations only",+ filters: [],+ columnOrder: [],+ columnVisibility: {},+ orderBy: null,+ searchQuery: "",+ },+] satisfies ModernSessionViewDropdownMenuControls["savedViews"];++const controls = {+ matchingSystemPresetId: "__langfuse_with_io__",+ matchingSavedViewId: undefined,+ savedViews,+ onApplyPreset: fn(),+ onApplySavedView: fn(),+ onManageViews: fn(),+ onOpenFilterDialog: fn(),+} satisfies ModernSessionViewDropdownMenuControls;++const meta = preview.meta({+ component: ModernSessionViewDropdownMenu,+ render: (args) => (+ <DropdownMenu defaultOpen>+ <DropdownMenuTrigger>Trigger</DropdownMenuTrigger>+ <ModernSessionViewDropdownMenu {...args} />+ </DropdownMenu>+ ),+});++export default meta;++export const Default = meta.story({+ args: { controls },+});++export const WithoutSavedViews = meta.story({+ args: {+ controls: {+ ...controls,+ matchingSystemPresetId: undefined,+ savedViews: [],+ },+ },+});diff --git a/web/src/components/session/ModernSessionViewDropdownMenu.tsx b/web/src/components/session/ModernSessionViewDropdownMenu.tsxnew file mode 100644index 0000000000..bd3d199ec1--- /dev/null+++ b/web/src/components/session/ModernSessionViewDropdownMenu.tsx@@ -0,0 +1,89 @@+import { type TableViewPresetState } from "@langfuse/shared";+import { Check, Filter, Settings2 } from "lucide-react";++import { SESSION_DETAIL_SYSTEM_PRESETS } from "@/src/components/session/session-detail-presets";+import {+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuItemWithSecondaryAction,+ DropdownMenuLabel,+ DropdownMenuSeparator,+} from "@/src/components/ui/dropdown-menu";++export type ModernSessionViewDropdownMenuControls = {+ matchingSystemPresetId: string | undefined;+ matchingSavedViewId: string | undefined;+ savedViews: Array<TableViewPresetState & { id: string; name: string }>;+ onApplyPreset: (+ preset: (typeof SESSION_DETAIL_SYSTEM_PRESETS)[number],+ ) => void;+ onApplySavedView: (+ view: TableViewPresetState & { id: string; name: string },+ ) => void;+ onManageViews: () => void;+ onOpenFilterDialog: () => void;+};++export function ModernSessionViewDropdownMenu({+ controls,+}: {+ controls: ModernSessionViewDropdownMenuControls;+}) {+ return (+ <DropdownMenuContent align="end" className="w-72">+ <DropdownMenuLabel>System Presets</DropdownMenuLabel>+ {SESSION_DETAIL_SYSTEM_PRESETS.filter(+ (preset) => preset.filters.length > 0,+ ).map((preset) => (+ <DropdownMenuItemWithSecondaryAction+ key={preset.id}+ title={preset.name}+ onClick={() => controls.onApplyPreset(preset)}+ // TODO: We are abusing the `secondaryAction` prop here to show a checkmark for the selected preset. This is not ideal, but it works for now. We should consider adding a `selected` prop to `DropdownMenuItemWithSecondaryAction` in the future.+ secondaryAction={+ controls.matchingSystemPresetId === preset.id+ ? {+ icon: Check,+ ariaLabel: `${preset.name} selected`,+ onClick: () => controls.onApplyPreset(preset),+ }+ : undefined+ }+ />+ ))}+ <DropdownMenuSeparator />+ <DropdownMenuLabel>Saved Views</DropdownMenuLabel>+ {controls.savedViews.map((view) => (+ <DropdownMenuItemWithSecondaryAction+ key={view.id}+ title={view.name}+ onClick={() => controls.onApplySavedView(view)}+ secondaryAction={+ controls.matchingSavedViewId === view.id+ ? {+ icon: Check,+ ariaLabel: `${view.name} selected`,+ onClick: () => controls.onApplySavedView(view),+ }+ : undefined+ }+ />+ ))}+ {controls.savedViews.length === 0 ? (+ <DropdownMenuItem disabled>No saved views</DropdownMenuItem>+ ) : null}+ <DropdownMenuSeparator />+ <DropdownMenuItemWithSecondaryAction+ title="Manage Views"+ icon={Settings2}+ onClick={controls.onManageViews}+ />+ <DropdownMenuSeparator />+ <DropdownMenuItemWithSecondaryAction+ title="Apply custom filter"+ icon={Filter}+ onClick={controls.onOpenFilterDialog}+ />+ </DropdownMenuContent>+ );+}diff --git a/web/src/components/session/README.md b/web/src/components/session/README.mddeleted file mode 100644index 6add63212e..0000000000--- a/web/src/components/session/README.md+++ /dev/null@@ -1,34 +0,0 @@-# Session detail ownership--`index.tsx` owns session queries, header actions, filters, saved views, and the-feature-flagged choice between the existing card layout and Modern Session.--## Render boundaries--- `TraceRow.tsx`: legacy trace card and lazy-load boundary.-- `TraceEventsRow.tsx`: events-backed trace content for card and Modern Session- feed surfaces.-- `ModernSession.tsx`: minimap, scroll-spy derivation, smooth navigation, and- the continuous virtualized feed.-- `SessionVirtualizedRow.tsx` + `useStableVirtualRowMeasurement.ts`: translated- DOM-safe dynamic row measurement.-- `SessionObservationIO.tsx`: bounded observation payload rendering and the- bridge into `IOPreview` full/conversation modes.--Modern Session prepares each events-backed observation once inside its narrow-row container and passes the parsed I/O plus ChatML result through `IOPreview`.-The existing card surface keeps its lazy parser path.--## State--`sessionDetailStore.ts` is a per-page store. It owns loaded trace IDs,-correction visibility, inline-tool visibility, and system-prompt visibility so-virtual row remounts do not reset view state. On the events-backed session-page, `modernSession` is a user Feature Preview flag; disabled users retain the-card layout without a page-level layout control. The preview toggle is disabled-unless the V4 Preview toggle selects this events-backed page.--Server/query state remains in tRPC and React Query. Active Modern Session state-is derived from TanStack Virtual's current scroll offset unless the user-explicitly selects a minimap item that cannot reach the feed's top edge. User-scrolling restores scroll-spy ownership; no effect mirrors either state.diff --git a/web/src/components/session/TraceEventsRow.tsx b/web/src/components/session/TraceEventsRow.tsxindex fb6c04e3d9..b919149312 100644--- a/web/src/components/session/TraceEventsRow.tsx+++ b/web/src/components/session/TraceEventsRow.tsx@@ -96,6 +96,7 @@ const ModernSessionObservation = ({return (<div+ data-session-observation-id={observation.id}className={isConversation? "flex flex-col gap-2"@@ -212,7 +213,6 @@ type LazyTraceEventsRowProps = {surface?: TraceEventsSurface;contentMode?: IOPreviewContentMode;showSystemPrompt?: boolean;- isActive?: boolean;};const areLazyTraceEventsRowPropsEqual = (@@ -231,8 +231,7 @@ const areLazyTraceEventsRowPropsEqual = (previous.hideTracePanel === next.hideTracePanel &&previous.surface === next.surface &&previous.contentMode === next.contentMode &&- previous.showSystemPrompt === next.showSystemPrompt &&- previous.isActive === next.isActive;+ previous.showSystemPrompt === next.showSystemPrompt;export const TraceEventsRow = React.memo(({@@ -248,7 +247,6 @@ export const TraceEventsRow = React.memo(surface = "card",contentMode = "all",showSystemPrompt,- isActive = false,}: {trace: RouterOutputs["sessions"]["tracesFromEvents"][number];projectId: string;@@ -262,7 +260,6 @@ export const TraceEventsRow = React.memo(surface?: TraceEventsSurface;contentMode?: IOPreviewContentMode;showSystemPrompt?: boolean;- isActive?: boolean;}) => {const observationsQuery =api.sessions.observationsForTraceFromEvents.useQuery(@@ -381,13 +378,8 @@ export const TraceEventsRow = React.memo(return (<FrameclassName={- surface === "card"- ? "border-border shadow-none"- : isActive- ? "bg-background border-l-primary border-l-2"- : "bg-background border-l-2 border-l-transparent"+ surface === "card" ? "border-border shadow-none" : "bg-background"}- data-modern-session-active={surface === "modern" && isActive}><divclassName={diff --git a/web/src/components/session/index.tsx b/web/src/components/session/index.tsxindex c5ba418908..4aa77cc938 100644--- a/web/src/components/session/index.tsx+++ b/web/src/components/session/index.tsx@@ -32,7 +32,6 @@ import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePosimport Page from "@/src/components/layouts/page";import {Popover,- PopoverClose,PopoverContent,PopoverTrigger,} from "@/src/components/ui/popover";@@ -75,7 +74,6 @@ import {type ColumnOrderState,} from "@tanstack/react-table";import {- SESSION_DETAIL_LLM_CALL_PRESETS,SESSION_DETAIL_SYSTEM_PRESETS,type SessionDetailSystemPreset,getSessionDetailPresetToApply,@@ -87,6 +85,7 @@ import { SessionDetailStoreProvider } from "@/src/components/session/SessionDetaimport { SessionVirtualizedRow } from "@/src/components/session/SessionVirtualizedRow";import { createSessionDetailStore } from "@/src/components/session/sessionDetailStore";import { ModernSession } from "@/src/components/session/ModernSession";+import { ModernSessionFilterControls } from "@/src/components/session/ModernSessionFilterControls";import useIsFeatureEnabled from "@/src/features/feature-flags/hooks/useIsFeatureEnabled";import { useIsMobile } from "@/src/hooks/use-mobile";import { useStore } from "zustand";@@ -844,12 +843,7 @@ const LoadedSessionEventsPage: React.FC<{});const isMobile = useIsMobile();const parentRef = useRef<HTMLDivElement>(null);- const defaultPresetAppliedRef = useRef(false);-- // Reset default preset flag when session changes (e.g., navigating between sessions)- useEffect(() => {- defaultPresetAppliedRef.current = false;- }, [sessionId]);+ const defaultPresetResolvedSessionRef = useRef<string | null>(null);const [showCorrections, setShowCorrections] = useLocalStorage("showCorrections",@@ -1244,7 +1238,7 @@ const LoadedSessionEventsPage: React.FC<{// useRef initializer wouldn't re-run, leaving a stale viewId that blocks the// default-view effect on the new session. Re-read the URL during render (not// an effect, which would race the view manager's strip on reload) whenever the- // sessionId changes, mirroring the defaultPresetAppliedRef reset above.+ // sessionId changes, mirroring the per-session default-preset decision above.const initialViewIdSessionRef = useRef(sessionId);if (initialViewIdSessionRef.current !== sessionId) {initialViewIdSessionRef.current = sessionId;@@ -1267,28 +1261,50 @@ const LoadedSessionEventsPage: React.FC<{? filterMatchedView: null;const viewLabel = matchedView?.name ?? null;- const isLlmCallPresetActive = SESSION_DETAIL_LLM_CALL_PRESETS.some(- (preset) => matchedView?.id === preset.id,+ const hasSessionControls =+ !isModernSessionEnabled ||+ Boolean(session.users?.length || session.scores.length);+ const excludeObservationsByName = useCallback(+ (name: string) => {+ const existingFilter = queryFilter.filterState.find(+ (+ filter,+ ): filter is Extract<FilterState[number], { type: "stringOptions" }> =>+ filter.column === "name" &&+ filter.type === "stringOptions" &&+ filter.operator === "none of",+ );+ if (existingFilter?.value.includes(name)) return;++ const nextFilters = existingFilter+ ? queryFilter.filterState.map((filter) =>+ filter === existingFilter+ ? { ...existingFilter, value: [...existingFilter.value, name] }+ : filter,+ )+ : queryFilter.filterState.concat({+ column: "name",+ type: "stringOptions",+ operator: "none of",+ value: [name],+ });++ queryFilter.setFilterState(nextFilters);+ capture("filters:applied", {+ surface: "filter_builder",+ tableName: "session-detail",+ column: "name",+ filterType: "stringOptions",+ operator: "none of",+ valueCount: 1,+ conditionCount: nextFilters.length,+ columnConditionCount: 1,+ isV4: true,+ });+ },+ [capture, queryFilter],);- const applyLlmCallPreset = (preset: SessionDetailSystemPreset) => {- capture("saved_views:system_preset_selected", {- tableName: TableViewPresetTableName.SessionDetail,- presetId: preset.id,- });- viewControllers.handleSetViewId(preset.id);- viewControllers.applyViewState(- {- filters: preset.filters,- columnOrder: [],- columnVisibility: {},- orderBy: null,- searchQuery: "",- },- { trigger: "system_preset", viewId: preset.id },- );- };-// Recover the system-preset viewId the view manager strips from the URL on// reload/shared-link (frontend presets aren't backend-fetchable). Idempotent// (no one-shot guard) so it runs *after* the async strip, not before. Recovers@@ -1320,7 +1336,11 @@ const LoadedSessionEventsPage: React.FC<{// prev/next session navigation re-decides, mirroring initialViewIdRef.const arrivedOnVisitedHistoryEntry = useHistoryEntryRevisit(sessionId);- // Fresh load with nothing in the URL → apply the default view. Skipped on+ // On each session's first resolved view state, apply the default view when+ // nothing else is selected. The decision is consumed even when existing+ // filters make us skip it, so clearing those filters later remains a user+ // clear action instead of unexpectedly applying the default preset.+ // Skipped on// reload/shared-link (a viewId was in the URL) so the recovery effect above,// not the default, decides the view — otherwise "All observations" would be// silently replaced by the default on every reload. Also skipped when the@@ -1329,8 +1349,9 @@ const LoadedSessionEventsPage: React.FC<{// default would overwrite what the user deliberately left there// (LFE-10715).useEffect(() => {- if (defaultPresetAppliedRef.current) return;+ if (defaultPresetResolvedSessionRef.current === sessionId) return;if (isViewLoading) return; // Wait for view manager to initialize+ defaultPresetResolvedSessionRef.current = sessionId;if (selectedViewId) return;if (initialViewIdRef.current) return;if (arrivedOnVisitedHistoryEntry) return;@@ -1339,13 +1360,13 @@ const LoadedSessionEventsPage: React.FC<{hasFilters: visibleFilterState.length > 0,});if (!presetToApply) return;- defaultPresetAppliedRef.current = true;applySystemPreset(presetToApply);}, [applySystemPreset,arrivedOnVisitedHistoryEntry,isViewLoading,selectedViewId,+ sessionId,visibleFilterState,]);@@ -1599,133 +1620,90 @@ const LoadedSessionEventsPage: React.FC<{: "flex h-full flex-col overflow-auto"}>- <SessionControlsBar- isMobile={isMobile && !isModernSessionEnabled}- desktopClassName="bg-background sticky top-0 z-40 flex flex-wrap items-center gap-2 border-b p-4"- summary={- <>- <span className="text-sm font-bold">Session controls</span>- <span- className="text-muted-foreground min-w-0 truncate text-xs"- title={`${session.countTraces} traces · ${usdFormatter(- session.totalCost ?? 0,- 2,- )}`}- >- {session.countTraces} traces ·{" "}- {usdFormatter(session.totalCost ?? 0, 2)}- </span>- </>- }- >- {isModernSessionEnabled ? (- <Popover>- <PopoverTrigger asChild>- <Button- type="button"- variant="outline"- aria-pressed={isLlmCallPresetActive}- className={- isLlmCallPresetActive ? "bg-primary/5" : undefined- }+ {hasSessionControls ? (+ <SessionControlsBar+ isMobile={isMobile && !isModernSessionEnabled}+ desktopClassName="bg-background sticky top-0 z-40 flex flex-wrap items-center gap-2 border-b p-4"+ summary={+ <>+ <span className="text-sm font-bold">Session controls</span>+ <span+ className="text-muted-foreground min-w-0 truncate text-xs"+ title={`${session.countTraces} traces · ${usdFormatter(+ session.totalCost ?? 0,+ 2,+ )}`}>- LLM Calls per Trace- <ChevronDown className="ml-1 h-4 w-4" aria-hidden />- </Button>- </PopoverTrigger>- <PopoverContent align="start" className="w-72 p-1">- <div className="text-muted-foreground px-2 py-1.5 text-xs font-bold">- LLM Calls per Trace- </div>- {SESSION_DETAIL_LLM_CALL_PRESETS.map((preset) => {- const isActive = matchedView?.id === preset.id;- return (- <PopoverClose asChild key={preset.id}>- <button- type="button"- aria-current={isActive ? "true" : undefined}- className="hover:bg-accent flex w-full items-start justify-between gap-2 rounded-sm px-2 py-1.5 text-left text-sm"- onClick={() => applyLlmCallPreset(preset)}- >- <span className="flex flex-col">- <span className="font-bold">{preset.name}</span>- {preset.description ? (- <span className="text-muted-foreground text-xs">- {preset.description}- </span>- ) : null}- </span>- {isActive ? (- <CheckIcon- className="mt-0.5 h-4 w-4 shrink-0"- aria-hidden- />- ) : null}- </button>- </PopoverClose>- );- })}- </PopoverContent>- </Popover>- ) : null}-- {/* Saved Views */}- <TableViewPresetsDrawer- viewConfig={{- tableName: TableViewPresetTableName.SessionDetail,- projectId,- controllers: viewControllers,- }}- currentState={{- orderBy: null,- filters: queryFilter.filterState,- columnOrder,- columnVisibility,- searchQuery: "",- }}- systemFilterPresets={SESSION_DETAIL_SYSTEM_PRESETS}- triggerId={SESSION_DETAIL_VIEW_TRIGGER_ID}- />+ {session.countTraces} traces ·{" "}+ {usdFormatter(session.totalCost ?? 0, 2)}+ </span>+ </>+ }+ >+ {/* Saved Views */}+ {!isModernSessionEnabled ? (+ <TableViewPresetsDrawer+ viewConfig={{+ tableName: TableViewPresetTableName.SessionDetail,+ projectId,+ controllers: viewControllers,+ }}+ currentState={{+ orderBy: null,+ filters: queryFilter.filterState,+ columnOrder,+ columnVisibility,+ searchQuery: "",+ }}+ systemFilterPresets={SESSION_DETAIL_SYSTEM_PRESETS}+ triggerId={SESSION_DETAIL_VIEW_TRIGGER_ID}+ />+ ) : null}- {/* Refines the selected view by filtering observations within each+ {/* Refines the selected view by filtering observations within eachtrace (it does not filter the list of traces) — labelled to sayso (LFE-10520). */}- <PopoverFilterBuilder- columns={filterColumns}- filterState={visibleFilterState}- onChange={queryFilter.setFilterState}- columnsWithCustomSelect={filterColumnsWithCustomSelect}- label="Filter observations"- // Analytics (LFE-10781): session-detail observation refinement is a- // v3/legacy surface (the v4 events table filters via the grammar bar).- tableName="session-detail"- isV4={false}- />-- {/* Separator */}- <Separator orientation="vertical" className="h-6" />-- {/* Stats stay in the toolbar for the existing card layout. Modern+ {!isModernSessionEnabled ? (+ <PopoverFilterBuilder+ columns={filterColumns}+ filterState={visibleFilterState}+ onChange={queryFilter.setFilterState}+ columnsWithCustomSelect={filterColumnsWithCustomSelect}+ label="Filter observations"+ // Analytics (LFE-10781): session-detail observation refinement is a+ // v3/legacy surface (the v4 events table filters via the grammar bar).+ tableName="session-detail"+ isV4={false}+ />+ ) : null}++ {/* Separator */}+ {!isModernSessionEnabled ? (+ <Separator orientation="vertical" className="h-6" />+ ) : null}++ {/* Stats stay in the toolbar for the existing card layout. ModernSession shows trace count and cost in its minimap header. */}- {!isModernSessionEnabled ? (- <>- <Badge variant="outline">- Total traces: {session.countTraces}- </Badge>- <Badge variant="outline">- Total cost: {usdFormatter(session.totalCost ?? 0, 2)}- </Badge>- </>- ) : null}+ {!isModernSessionEnabled ? (+ <>+ <Badge variant="outline">+ Total traces: {session.countTraces}+ </Badge>+ <Badge variant="outline">+ Total cost: {usdFormatter(session.totalCost ?? 0, 2)}+ </Badge>+ </>+ ) : null}- {/* Users */}- {session.users?.length ? (- <SessionUsers projectId={projectId} users={session.users} />- ) : null}+ {/* Users */}+ {session.users?.length ? (+ <SessionUsers projectId={projectId} users={session.users} />+ ) : null}- {/* Scores */}- <SessionScores scores={session.scores} />- </SessionControlsBar>+ {/* Scores */}+ <SessionScores scores={session.scores} />+ </SessionControlsBar>+ ) : null}{!isModernSessionEnabled ? (<div ref={parentRef} className="flex-1 overflow-auto p-4"><div@@ -1766,19 +1744,44 @@ const LoadedSessionEventsPage: React.FC<{</div></div>) : (- <ModernSession- traces={traces ?? []}+ <ModernSessionFilterControlsprojectId={projectId}- sessionId={sessionId}- openPeek={openPeek}- traceCommentCounts={asCommentCounts(traceCommentCounts.data)}filterState={visibleFilterState}- filterMeasurementKey={visibleFilterMeasurementKey}- viewLabel={viewLabel}- totalCost={session.totalCost ?? 0}- showInlineToolCalls={showInlineToolCalls}- showSystemPrompt={showSystemPrompt}- />+ filterColumns={filterColumns}+ filterColumnsWithCustomSelect={filterColumnsWithCustomSelect}+ onChange={queryFilter.setFilterState}+ viewControllers={viewControllers}+ currentViewState={{+ orderBy: null,+ filters: queryFilter.filterState,+ columnOrder,+ columnVisibility,+ searchQuery: "",+ }}+ >+ {(sidebarFilterControls) => (+ <ModernSession+ tracesState={+ isTracesSuccess+ ? { type: "loaded", traces: traces ?? [] }+ : { type: "loading" }+ }+ projectId={projectId}+ sessionId={sessionId}+ sessionMinTimestamp={session.minTimestamp}+ sessionMaxTimestamp={session.maxTimestamp}+ openPeek={openPeek}+ traceCommentCounts={asCommentCounts(traceCommentCounts.data)}+ filterState={visibleFilterState}+ filterMeasurementKey={visibleFilterMeasurementKey}+ viewLabel={viewLabel}+ showInlineToolCalls={showInlineToolCalls}+ showSystemPrompt={showSystemPrompt}+ sidebarFilterControls={sidebarFilterControls}+ onExcludeObservation={excludeObservationsByName}+ />+ )}+ </ModernSessionFilterControls>)}</div><TablePeekViewTraceDetaildiff --git a/web/src/components/session/sessionIdleGap.clienttest.ts b/web/src/components/session/sessionIdleGap.clienttest.tsnew file mode 100644index 0000000000..c278ddd1b8--- /dev/null+++ b/web/src/components/session/sessionIdleGap.clienttest.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from "vitest";++import {+ computeIdleGapSeconds,+ formatIdleGap,+} from "@/src/components/session/sessionIdleGap";++describe("sessionIdleGap", () => {+ it("measures idle time after the previous trace ends", () => {+ const previous = {+ timestamp: new Date("2026-01-01T12:00:00.000Z"),+ latencyMs: 60_000,+ };+ const current = { timestamp: new Date("2026-01-01T12:06:00.000Z") };++ expect(computeIdleGapSeconds(previous, current)).toBe(300);+ });++ it("never returns a negative gap for overlapping traces", () => {+ const previous = {+ timestamp: new Date("2026-01-01T12:00:00.000Z"),+ latencyMs: 120_000,+ };+ const current = { timestamp: new Date("2026-01-01T12:01:00.000Z") };++ expect(computeIdleGapSeconds(previous, current)).toBe(0);+ });++ it("formats gaps as rounded minutes or hours", () => {+ expect(formatIdleGap(300)).toBe("5 min");+ expect(formatIdleGap(3600)).toBe("1 hr");+ expect(formatIdleGap(7200)).toBe("2 hrs");+ });+});diff --git a/web/src/components/session/sessionIdleGap.ts b/web/src/components/session/sessionIdleGap.tsnew file mode 100644index 0000000000..45cd9a698d--- /dev/null+++ b/web/src/components/session/sessionIdleGap.ts@@ -0,0 +1,16 @@+export const IDLE_GAP_THRESHOLD_SECONDS = 5 * 60;++export const computeIdleGapSeconds = (+ previous: { timestamp: Date; latencyMs: number | null },+ current: { timestamp: Date },+): number => {+ const previousEnd = previous.timestamp.getTime() + (previous.latencyMs ?? 0);+ return Math.max(0, (current.timestamp.getTime() - previousEnd) / 1000);+};++export const formatIdleGap = (seconds: number): string => {+ const rounded = Math.max(0, Math.round(seconds));+ if (rounded < 3600) return `${Math.round(rounded / 60)} min`;+ const hours = Math.round(rounded / 3600);+ return `${hours} ${hours === 1 ? "hr" : "hrs"}`;+};diff --git a/web/src/components/table/table-view-presets/components/data-table-view-presets-drawer.tsx b/web/src/components/table/table-view-presets/components/data-table-view-presets-drawer.tsxindex 6e26bdb1d0..539f3bf6c8 100644--- a/web/src/components/table/table-view-presets/components/data-table-view-presets-drawer.tsx+++ b/web/src/components/table/table-view-presets/components/data-table-view-presets-drawer.tsx@@ -54,7 +54,7 @@ import {type TableViewPresetTableName,type TableViewPresetState,} from "@langfuse/shared";-import { useCallback, useMemo, useState } from "react";+import { type ReactNode, useCallback, useMemo, useState } from "react";import {DropdownMenuItem,DropdownMenuTrigger,@@ -134,7 +134,7 @@ export interface SystemFilterPreset {filters: FilterState;}-interface TableViewPresetsDrawerProps {+interface TableViewPresetsDrawerContentProps {viewConfig: {tableName: TableViewPresetTableName;projectId: string;@@ -162,10 +162,38 @@ interface TableViewPresetsDrawerProps {};/** Page-specific system filter presets (e.g. "Last Generation in Trace") */systemFilterPresets?: SystemFilterPreset[];+}++interface TableViewPresetsDrawerProps extends TableViewPresetsDrawerContentProps {/** Optional DOM id on the trigger button so other UI can open the drawer. */triggerId?: string;}+type TableViewPresetsDrawerRootProps = {+ tableName: TableViewPresetTableName;+ children: ReactNode;+} & (+ | { open?: never; onOpenChange?: never }+ | { open: boolean; onOpenChange: (open: boolean) => void }+);++const useTableViewPresetsDrawerData = ({+ tableName,+ projectId,+}: {+ tableName: TableViewPresetTableName;+ projectId: string;+}) => {+ const { TableViewPresetsList } = useViewData({ tableName, projectId });+ const { data: defaultAssignments } =+ api.TableViewPresets.getDefaultAssignments.useQuery(+ { projectId, viewName: tableName },+ { enabled: !!projectId },+ );++ return { TableViewPresetsList, defaultAssignments };+};+function formatOrderBy(orderBy?: OrderByState) {return orderBy?.column ? `${orderBy.column} ${orderBy.order}` : "none";}@@ -182,17 +210,102 @@ function buildSystemFilterPresetState(};}+export function TableViewPresetsDrawerRoot({+ tableName,+ onOpenChange,+ ...props+}: TableViewPresetsDrawerRootProps) {+ const capture = usePostHogClientCapture();++ return (+ <Drawer+ {...props}+ forceDirection="responsive-left"+ onOpenChange={(open) => {+ onOpenChange?.(open);+ capture(open ? "saved_views:drawer_open" : "saved_views:drawer_close", {+ tableName,+ });+ }}+ />+ );+}+export function TableViewPresetsDrawer({viewConfig,currentState,systemFilterPresets,triggerId,}: TableViewPresetsDrawerProps) {+ const { tableName, projectId, controllers } = viewConfig;+ const { TableViewPresetsList, defaultAssignments } =+ useTableViewPresetsDrawerData({ tableName, projectId });+ const drawerPresetCount =+ TableViewPresetsList?.filter(+ (view) =>+ !view.category ||+ !view.isSystem ||+ view.id === defaultAssignments?.userDefaultViewId ||+ view.id === defaultAssignments?.projectDefaultViewId,+ ).length ?? 0;++ return (+ <TableViewPresetsDrawerRoot tableName={tableName}>+ <DrawerTrigger asChild>+ <Button variant="outline" id={triggerId} title="My Views">+ <span>My Views</span>+ {controllers.selectedViewId ? (+ <ChevronDown className="ml-1 h-4 w-4" />+ ) : (+ <div className="bg-input ml-1 rounded-sm px-1 text-xs">+ {drawerPresetCount}+ </div>+ )}+ </Button>+ </DrawerTrigger>+ <TableViewPresetsDrawerContentBody+ viewConfig={viewConfig}+ currentState={currentState}+ systemFilterPresets={systemFilterPresets}+ TableViewPresetsList={TableViewPresetsList}+ defaultAssignments={defaultAssignments}+ />+ </TableViewPresetsDrawerRoot>+ );+}++export function TableViewPresetsDrawerContent({+ viewConfig,+ currentState,+ systemFilterPresets,+}: TableViewPresetsDrawerContentProps) {+ const { tableName, projectId } = viewConfig;+ const { TableViewPresetsList, defaultAssignments } =+ useTableViewPresetsDrawerData({ tableName, projectId });++ return (+ <TableViewPresetsDrawerContentBody+ viewConfig={viewConfig}+ currentState={currentState}+ systemFilterPresets={systemFilterPresets}+ TableViewPresetsList={TableViewPresetsList}+ defaultAssignments={defaultAssignments}+ />+ );+}++function TableViewPresetsDrawerContentBody({+ viewConfig,+ currentState,+ systemFilterPresets,+ TableViewPresetsList,+ defaultAssignments,+}: TableViewPresetsDrawerContentProps &+ ReturnType<typeof useTableViewPresetsDrawerData>) {const [searchQuery, setSearchQueryLocal] = useState("");const { tableName, projectId, controllers } = viewConfig;const { handleSetViewId, applyViewState, selectedViewId, appliedViewId } =controllers;- const { TableViewPresetsList } = useViewData({ tableName, projectId });const {createMutation,updateConfigMutation,@@ -215,12 +328,6 @@ export function TableViewPresetsDrawer({scope: "TableViewPresets:CUD",});- const { data: defaultAssignments } =- api.TableViewPresets.getDefaultAssignments.useQuery(- { projectId, viewName: tableName },- { enabled: !!projectId },- );-const { setViewAsDefault, clearViewDefault, isSettingDefault } =useDefaultViewMutations({ tableName, projectId });@@ -445,435 +552,405 @@ export function TableViewPresetsDrawer({return (<>- <Drawer- forceDirection="responsive-left"- onOpenChange={(open) => {- if (open) {- capture("saved_views:drawer_open", { tableName });- } else {- capture("saved_views:drawer_close", { tableName });- }- }}- >- <DrawerTrigger asChild>- <Button variant="outline" id={triggerId} title="My Views">- <span>My Views</span>- {selectedViewId ? (- <ChevronDown className="ml-1 h-4 w-4" />- ) : (- <div className="bg-input ml-1 rounded-sm px-1 text-xs">- {drawerPresetList?.length ?? 0}- </div>- )}- </Button>- </DrawerTrigger>- <DrawerContent overlayClassName="bg-primary/10">- <div className="mx-auto w-full">- <DrawerHeader className="bg-modal flex flex-row items-center justify-between rounded-sm px-3 py-1.5">- <DrawerTitle className="flex flex-row items-center gap-1">- Views{" "}- <a- href="https://github.com/orgs/langfuse/discussions/4657"- target="_blank"- rel="noopener noreferrer"- className="inline-flex items-center"- title="Saving table view presets is currently in beta. Click here to provide feedback!"- ></a>- </DrawerTitle>- <DrawerClose asChild>- <Button variant="outline" size="icon">- <X className="h-4 w-4" />- </Button>- </DrawerClose>- </DrawerHeader>- <Separator />-- <Command className="h-fit rounded-none border-none pb-1 shadow-none">- <CommandInput- placeholder="Search views..."- value={searchQuery}- onValueChange={setSearchQueryLocal}- className="h-9 border-none focus:ring-0"- />- <CommandList className="max-h-[calc(100vh-150px)]">- <CommandEmpty>No views found</CommandEmpty>- <CommandGroup className="pb-0">- {/* System Preset: Langfuse Default - hidden when page-specific presets exist */}- {!systemFilterPresets?.length && (- <CommandItem- key={SYSTEM_PRESETS.DEFAULT.id}- onSelect={() => handleSetViewId(null)}- className={cn(- "hover:bg-muted/50 group mt-1 flex cursor-pointer items-center justify-between rounded-md p-2 transition-colors",- selectedViewId === null && "bg-muted",- )}- title="Reflects your current table settings without applying any saved custom table views"- >- <div className="flex flex-col">- <span className="text-muted-foreground text-sm">- {SYSTEM_PRESETS.DEFAULT.name}- </span>+ <DrawerContent overlayClassName="bg-primary/10">+ <div className="mx-auto w-full">+ <DrawerHeader className="bg-modal flex flex-row items-center justify-between rounded-sm px-3 py-1.5">+ <DrawerTitle className="flex flex-row items-center gap-1">+ Views{" "}+ <a+ href="https://github.com/orgs/langfuse/discussions/4657"+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex items-center"+ title="Saving table view presets is currently in beta. Click here to provide feedback!"+ ></a>+ </DrawerTitle>+ <DrawerClose asChild>+ <Button variant="outline" size="icon">+ <X className="h-4 w-4" />+ </Button>+ </DrawerClose>+ </DrawerHeader>+ <Separator />++ <Command className="h-fit rounded-none border-none pb-1 shadow-none">+ <CommandInput+ placeholder="Search views..."+ value={searchQuery}+ onValueChange={setSearchQueryLocal}+ className="h-9 border-none focus:ring-0"+ />+ <CommandList className="max-h-[calc(100vh-150px)]">+ <CommandEmpty>No views found</CommandEmpty>+ <CommandGroup className="pb-0">+ {/* System Preset: Langfuse Default - hidden when page-specific presets exist */}+ {!systemFilterPresets?.length && (+ <CommandItem+ key={SYSTEM_PRESETS.DEFAULT.id}+ onSelect={() => handleSetViewId(null)}+ className={cn(+ "hover:bg-muted/50 group mt-1 flex cursor-pointer items-center justify-between rounded-md p-2 transition-colors",+ selectedViewId === null && "bg-muted",+ )}+ title="Reflects your current table settings without applying any saved custom table views"+ >+ <div className="flex flex-col">+ <span className="text-muted-foreground text-sm">+ {SYSTEM_PRESETS.DEFAULT.name}+ </span>+ <span className="text-muted-foreground w-fit pl-0 text-xs">+ Your working view+ </span>+ </div>+ </CommandItem>+ )}++ {/* Page-specific System Filter Presets */}+ {systemFilterPresets?.map((preset) => (+ <CommandItem+ key={preset.id}+ onSelect={() => handleSelectSystemFilterPreset(preset)}+ className={cn(+ "hover:bg-muted/50 group mt-1 flex cursor-pointer items-center justify-between rounded-md p-2 transition-colors",+ selectedViewId === preset.id &&+ isEqual(+ normalizeForComparison(currentState.filters),+ normalizeForComparison(preset.filters),+ ) &&+ "bg-muted",+ )}+ >+ <div className="flex flex-col">+ <span className="flex items-center gap-1.5 text-sm">+ <LangfuseIcon size={14} />+ {preset.name}+ </span>+ {preset.description && (<span className="text-muted-foreground w-fit pl-0 text-xs">- Your working view+ {preset.description}</span>- </div>- </CommandItem>- )}+ )}+ </div>+ </CommandItem>+ ))}- {/* Page-specific System Filter Presets */}- {systemFilterPresets?.map((preset) => (+ {/* Separator between system and user presets */}+ {systemFilterPresets?.length && drawerPresetList?.length ? (+ <Separator className="my-2" />+ ) : null}++ {/* User Presets */}+ {drawerPresetList?.map((view) => {+ const isUserDefault =+ defaultAssignments?.userDefaultViewId === view.id;+ const isProjectDefault =+ defaultAssignments?.projectDefaultViewId === view.id;+ const isSystemView = view.isSystem === true;+ const previewText = summarizeTableViewPreset(view);++ return (<CommandItem- key={preset.id}- onSelect={() => handleSelectSystemFilterPreset(preset)}+ key={view.id}+ onSelect={() => handleSelectView(view)}className={cn("hover:bg-muted/50 group mt-1 flex cursor-pointer items-center justify-between rounded-md p-2 transition-colors",- selectedViewId === preset.id &&- isEqual(- normalizeForComparison(currentState.filters),- normalizeForComparison(preset.filters),- ) &&- "bg-muted",+ selectedViewId === view.id && "bg-muted",)}>- <div className="flex flex-col">- <span className="flex items-center gap-1.5 text-sm">- <LangfuseIcon size={14} />- {preset.name}- </span>- {preset.description && (- <span className="text-muted-foreground w-fit pl-0 text-xs">- {preset.description}- </span>- )}- </div>- </CommandItem>- ))}-- {/* Separator between system and user presets */}- {systemFilterPresets?.length && drawerPresetList?.length ? (- <Separator className="my-2" />- ) : null}-- {/* User Presets */}- {drawerPresetList?.map((view) => {- const isUserDefault =- defaultAssignments?.userDefaultViewId === view.id;- const isProjectDefault =- defaultAssignments?.projectDefaultViewId === view.id;- const isSystemView = view.isSystem === true;- const previewText = summarizeTableViewPreset(view);-- return (- <CommandItem- key={view.id}- onSelect={() => handleSelectView(view)}- className={cn(- "hover:bg-muted/50 group mt-1 flex cursor-pointer items-center justify-between rounded-md p-2 transition-colors",- selectedViewId === view.id && "bg-muted",- )}- >- <div className="flex min-w-0 flex-1 flex-col">- <div className="flex items-center gap-2">- <span- className={cn(- "text-sm",- isSystemView- ? "flex items-center gap-1.5"- : "truncate",- )}- title={view.name}- >- {isSystemView && <LangfuseIcon size={14} />}- {view.name}- </span>- {isUserDefault && (- <Badge variant="secondary" className="text-xs">- Your default- </Badge>+ <div className="flex min-w-0 flex-1 flex-col">+ <div className="flex items-center gap-2">+ <span+ className={cn(+ "text-sm",+ isSystemView+ ? "flex items-center gap-1.5"+ : "truncate",)}- {isProjectDefault && (- <Badge variant="outline" className="text-xs">- Project default- </Badge>- )}- </div>- {isSystemView ? (- view.description ? (- <span className="text-muted-foreground w-fit pl-0 text-xs">- {view.description}- </span>- ) : null- ) : previewText ? (- <span- className="text-muted-foreground truncate text-xs"- title={previewText}- >- {previewText}- </span>- ) : null}- {!isSystemView && view.id === selectedViewId && (- <Button- variant="ghost"- size="xs"- className={cn(- "w-fit pl-0 text-xs",- hasWriteAccess- ? "text-primary-accent"- : "text-muted-foreground",- )}- onClick={(e) => {- e.stopPropagation();- handleUpdateViewConfig({- name: view.name,- });- }}- disabled={!hasWriteAccess}- >- Update view with current filters- </Button>+ title={view.name}+ >+ {isSystemView && <LangfuseIcon size={14} />}+ {view.name}+ </span>+ {isUserDefault && (+ <Badge variant="secondary" className="text-xs">+ Your default+ </Badge>+ )}+ {isProjectDefault && (+ <Badge variant="outline" className="text-xs">+ Project default+ </Badge>)}</div>- <div className="flex flex-row gap-1">+ {isSystemView ? (+ view.description ? (+ <span className="text-muted-foreground w-fit pl-0 text-xs">+ {view.description}+ </span>+ ) : null+ ) : previewText ? (+ <span+ className="text-muted-foreground truncate text-xs"+ title={previewText}+ >+ {previewText}+ </span>+ ) : null}+ {!isSystemView && view.id === selectedViewId && (<Buttonvariant="ghost"- size="icon"+ size="xs"+ className={cn(+ "w-fit pl-0 text-xs",+ hasWriteAccess+ ? "text-primary-accent"+ : "text-muted-foreground",+ )}onClick={(e) => {e.stopPropagation();- handleGeneratePermalink(view.id);+ handleUpdateViewConfig({+ name: view.name,+ });}}- className="w-4 opacity-0 group-hover:opacity-100 peer-data-[state=open]:opacity-100"+ disabled={!hasWriteAccess}>- <Link className="h-4 w-4" />+ Update view with current filters</Button>- <DropdownMenu- open={dropdownId === view.id}- onOpenChange={(open) => {- setDropdownId(open ? view.id : null);- }}- >- <DropdownMenuTrigger asChild>- <Button- variant="ghost"- size="icon"- onClick={(e) => {- e.stopPropagation();- }}- className="opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100"- >- <MoreVertical className="h-4 w-4" />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent className="flex flex-col *:w-full *:justify-start">- {!isSystemView && (- <>- <DropdownMenuItem asChild>- <Popover- key={view.id + "-edit"}- open={isEditPopoverOpen}- onOpenChange={(open) => {- setIsEditPopoverOpen(open);- if (open) {- form.reset({ name: view.name });- capture(- "saved_views:update_form_open",- {- tableName,- viewId: view.id,- },- );- } else {- setDropdownId(null);- }- }}- >- <PopoverTrigger asChild>- <Button- variant="ghost"- onClick={(e) => {- e.stopPropagation();- }}- disabled={!hasWriteAccess}- >- {hasWriteAccess ? (- <Pen className="mr-2 h-4 w-4" />- ) : (- <Lock className="mr-2 h-4 w-4" />- )}- Rename- </Button>- </PopoverTrigger>- <PopoverContent- onClick={(e) => e.stopPropagation()}- >- <h2 className="mb-3 font-bold">Edit</h2>- <Form {...form}>- <form- onSubmit={form.handleSubmit(- onSubmit(view.id),- )}- className="space-y-2"- >- <FormField- control={form.control}- name="name"- render={({ field }) => (- <FormItem>- <FormLabel>- View name- </FormLabel>- <FormControl>- <Input- defaultValue={view.name}- {...field}- />- </FormControl>- <FormMessage />- </FormItem>- )}- />-- <div className="flex w-full justify-end">- <Button- type="submit"- loading={- updateNameMutation.isPending- }- disabled={- !!form.formState.errors.name- }- >- Save- </Button>- </div>- </form>- </Form>- </PopoverContent>- </Popover>- </DropdownMenuItem>- <DropdownMenuSeparator />- </>- )}- <DropdownMenuItem- onClick={(e) => {- e.stopPropagation();- if (isUserDefault) {- clearViewDefault("user");- } else {- setViewAsDefault(view.id, "user");- }- setDropdownId(null);- }}- disabled={isSettingDefault}- >- {isUserDefault ? (- <>Remove as my default</>- ) : (- <>Set as my default</>- )}- </DropdownMenuItem>- {/* Set as project default - requires write access */}- <DropdownMenuItem- onClick={(e) => {- e.stopPropagation();- if (isProjectDefault) {- clearViewDefault("project");- } else {- setViewAsDefault(view.id, "project");- }- setDropdownId(null);- }}- disabled={!hasWriteAccess || isSettingDefault}- >- {isProjectDefault ? (- <>Remove as project default</>- ) : (- <>Set as project default</>- )}- {!hasWriteAccess && (- <Lock className="ml-auto h-4 w-4" />- )}- </DropdownMenuItem>- {!isSystemView && (- <>- <DropdownMenuSeparator />- <DropdownMenuItem asChild>- <DeleteButton- itemId={view.id}- projectId={projectId}- scope="TableViewPresets:CUD"- entityToDeleteName="view"- executeDeleteMutation={async () => {- await handleDeleteView(view.id);- }}- isDeleteMutationLoading={- deleteMutation.isPending- }- invalidateFunc={() => {- utils.TableViewPresets.invalidate();- }}- captureDeleteOpen={() =>+ )}+ </div>+ <div className="flex flex-row gap-1">+ <Button+ variant="ghost"+ size="icon"+ onClick={(e) => {+ e.stopPropagation();+ handleGeneratePermalink(view.id);+ }}+ className="w-4 opacity-0 group-hover:opacity-100 peer-data-[state=open]:opacity-100"+ >+ <Link className="h-4 w-4" />+ </Button>+ <DropdownMenu+ open={dropdownId === view.id}+ onOpenChange={(open) => {+ setDropdownId(open ? view.id : null);+ }}+ >+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ size="icon"+ onClick={(e) => {+ e.stopPropagation();+ }}+ className="opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100"+ >+ <MoreVertical className="h-4 w-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent className="flex flex-col *:w-full *:justify-start">+ {!isSystemView && (+ <>+ <DropdownMenuItem asChild>+ <Popover+ key={view.id + "-edit"}+ open={isEditPopoverOpen}+ onOpenChange={(open) => {+ setIsEditPopoverOpen(open);+ if (open) {+ form.reset({ name: view.name });capture(- "saved_views:delete_form_open",+ "saved_views:update_form_open",{tableName,viewId: view.id,},- )+ );+ } else {+ setDropdownId(null);}- captureDeleteSuccess={() => {}}- />- </DropdownMenuItem>- </>+ }}+ >+ <PopoverTrigger asChild>+ <Button+ variant="ghost"+ onClick={(e) => {+ e.stopPropagation();+ }}+ disabled={!hasWriteAccess}+ >+ {hasWriteAccess ? (+ <Pen className="mr-2 h-4 w-4" />+ ) : (+ <Lock className="mr-2 h-4 w-4" />+ )}+ Rename+ </Button>+ </PopoverTrigger>+ <PopoverContent+ onClick={(e) => e.stopPropagation()}+ >+ <h2 className="mb-3 font-bold">Edit</h2>+ <Form {...form}>+ <form+ onSubmit={form.handleSubmit(+ onSubmit(view.id),+ )}+ className="space-y-2"+ >+ <FormField+ control={form.control}+ name="name"+ render={({ field }) => (+ <FormItem>+ <FormLabel>View name</FormLabel>+ <FormControl>+ <Input+ defaultValue={view.name}+ {...field}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />++ <div className="flex w-full justify-end">+ <Button+ type="submit"+ loading={+ updateNameMutation.isPending+ }+ disabled={+ !!form.formState.errors.name+ }+ >+ Save+ </Button>+ </div>+ </form>+ </Form>+ </PopoverContent>+ </Popover>+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ </>+ )}+ <DropdownMenuItem+ onClick={(e) => {+ e.stopPropagation();+ if (isUserDefault) {+ clearViewDefault("user");+ } else {+ setViewAsDefault(view.id, "user");+ }+ setDropdownId(null);+ }}+ disabled={isSettingDefault}+ >+ {isUserDefault ? (+ <>Remove as my default</>+ ) : (+ <>Set as my default</>)}- </DropdownMenuContent>- </DropdownMenu>- {!isSystemView && (- <div className="text-muted-foreground flex items-center text-xs">- <Avatar className="h-6 w-6">- <AvatarImage- src={view.createdByUser?.image ?? undefined}- alt={- view.createdByUser?.name ?? "User Avatar"- }- />- <AvatarFallback className="bg-tertiary">- {view.createdByUser?.name- ? view.createdByUser?.name- .split(" ")- .map((word) => word[0])- .slice(0, 2)- .concat("")- : null}- </AvatarFallback>- </Avatar>- </div>- )}- </div>- </CommandItem>- );- })}- </CommandGroup>- </CommandList>- </Command>-- <Separator />-- <div className="p-2">- <Button- onClick={() => {- setIsCreateDialogOpen(true);- capture("saved_views:create_form_open", { tableName });- }}- variant="ghost"- className="w-full justify-start px-1"- >- <Plus className="mr-2 h-4 w-4" />- Create Custom View- </Button>- </div>+ </DropdownMenuItem>+ {/* Set as project default - requires write access */}+ <DropdownMenuItem+ onClick={(e) => {+ e.stopPropagation();+ if (isProjectDefault) {+ clearViewDefault("project");+ } else {+ setViewAsDefault(view.id, "project");+ }+ setDropdownId(null);+ }}+ disabled={!hasWriteAccess || isSettingDefault}+ >+ {isProjectDefault ? (+ <>Remove as project default</>+ ) : (+ <>Set as project default</>+ )}+ {!hasWriteAccess && (+ <Lock className="ml-auto h-4 w-4" />+ )}+ </DropdownMenuItem>+ {!isSystemView && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem asChild>+ <DeleteButton+ itemId={view.id}+ projectId={projectId}+ scope="TableViewPresets:CUD"+ entityToDeleteName="view"+ executeDeleteMutation={async () => {+ await handleDeleteView(view.id);+ }}+ isDeleteMutationLoading={+ deleteMutation.isPending+ }+ invalidateFunc={() => {+ utils.TableViewPresets.invalidate();+ }}+ captureDeleteOpen={() =>+ capture("saved_views:delete_form_open", {+ tableName,+ viewId: view.id,+ })+ }+ captureDeleteSuccess={() => {}}+ />+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ {!isSystemView && (+ <div className="text-muted-foreground flex items-center text-xs">+ <Avatar className="h-6 w-6">+ <AvatarImage+ src={view.createdByUser?.image ?? undefined}+ alt={view.createdByUser?.name ?? "User Avatar"}+ />+ <AvatarFallback className="bg-tertiary">+ {view.createdByUser?.name+ ? view.createdByUser?.name+ .split(" ")+ .map((word) => word[0])+ .slice(0, 2)+ .concat("")+ : null}+ </AvatarFallback>+ </Avatar>+ </div>+ )}+ </div>+ </CommandItem>+ );+ })}+ </CommandGroup>+ </CommandList>+ </Command>++ <Separator />++ <div className="p-2">+ <Button+ onClick={() => {+ setIsCreateDialogOpen(true);+ capture("saved_views:create_form_open", { tableName });+ }}+ variant="ghost"+ className="w-full justify-start px-1"+ >+ <Plus className="mr-2 h-4 w-4" />+ Create Custom View+ </Button></div>- </DrawerContent>- </Drawer>+ </div>+ </DrawerContent>{/* Create View Dialog */}<Dialogdiff --git a/web/src/components/ui/dropdown-menu.tsx b/web/src/components/ui/dropdown-menu.tsxindex 1ae9ab8565..7dc03b052b 100644--- a/web/src/components/ui/dropdown-menu.tsx+++ b/web/src/components/ui/dropdown-menu.tsx@@ -326,7 +326,7 @@ const DropdownMenuItemWithSecondaryAction = (<PrimaryActionIcon className="mr-1.5 size-4" aria-hidden="true" />)}<span- className="max-w-36 overflow-hidden text-ellipsis whitespace-nowrap"+ className="min-w-0 flex-1 overflow-hidden text-left text-ellipsis whitespace-nowrap"title={props.disabled?.reason ?? props.title}>{props.title}diff --git a/web/src/features/filters/components/FilterToken.stories.tsx b/web/src/features/filters/components/FilterToken.stories.tsxnew file mode 100644index 0000000000..2edc3b1bbf--- /dev/null+++ b/web/src/features/filters/components/FilterToken.stories.tsx@@ -0,0 +1,25 @@+import preview from "../../../../.storybook/preview";++import { FilterToken } from "@/src/features/filters/components/FilterToken";++const meta = preview.meta({+ component: FilterToken,+});++export default meta;++export const Default = meta.story({+ args: {+ children: "type:any of GENERATION",+ deactivated: false,+ title: undefined,+ },+});++export const Deactivated = meta.story({+ args: {+ children: "environment:none of development",+ deactivated: true,+ title: "This filter is not applied on this surface",+ },+});diff --git a/web/src/features/filters/components/FilterToken.tsx b/web/src/features/filters/components/FilterToken.tsxnew file mode 100644index 0000000000..102bb2cd15--- /dev/null+++ b/web/src/features/filters/components/FilterToken.tsx@@ -0,0 +1,40 @@+import { cva } from "class-variance-authority";+import { type ReactNode } from "react";++const filterTokenVariants = cva(+ "inline max-w-full rounded border border-border bg-secondary px-1.5 py-0.5 text-secondary-foreground shadow-sm transition-colors hover:border-ring hover:bg-accent",+ {+ variants: {+ deactivated: {+ true: "opacity-50 line-through decoration-1",+ false: "",+ },+ },+ },+);++type FilterTokenProps = {+ children: ReactNode;+ deactivated: boolean;+ title: string | undefined;+} & {+ [key: `data-${string}`]: string | boolean | undefined;+};++export function FilterToken({+ children,+ deactivated,+ title,+ ...dataAttributes+}: FilterTokenProps) {+ return (+ <span+ {...dataAttributes}+ data-deactivated={deactivated || undefined}+ title={title}+ className={filterTokenVariants({ deactivated })}+ >+ {children}+ </span>+ );+}diff --git a/web/src/features/filters/components/filter-builder.tsx b/web/src/features/filters/components/filter-builder.tsxindex 1e976cefc5..ae809ca9f5 100644--- a/web/src/features/filters/components/filter-builder.tsx+++ b/web/src/features/filters/components/filter-builder.tsx@@ -40,6 +40,7 @@ import {TooltipTrigger,} from "@/src/components/ui/tooltip";import { MultiSelect } from "@/src/features/filters/components/multi-select";+import { FilterToken } from "@/src/features/filters/components/FilterToken";import {type WipFilterState,type WipFilterCondition,@@ -77,6 +78,13 @@ export type ColumnDefinitionWithAlert = ColumnDefinition & {};};+type AiFilterConfig = {+ organizationId: string | undefined;+ aiFeaturesEnabled: boolean;+ isPending: boolean;+ generateFilters: (prompt: string) => Promise<WipFilterState | null>;+};+// Has WipFilterState, passes all valid filters to parent onChangeexport function PopoverFilterBuilder({columns,@@ -108,6 +116,11 @@ export function PopoverFilterBuilder({isV4?: boolean;}) {const capture = usePostHogClientCapture();+ const { isLangfuseCloud } = useLangfuseCloudRegion();+ const projectId = useProjectIdFromURL();+ const { organization } = useQueryProject();+ const createFilterMutation =+ api.naturalLanguageFilters.createCompletion.useMutation();const [wipFilterState, _setWipFilterState] =useState<WipFilterState>(filterState);// Count of already-applied (valid) filters, so `setWipFilterState` can emit@@ -215,6 +228,24 @@ export function PopoverFilterBuilder({return newState;});};+ const aiFilter =+ filterWithAI && isLangfuseCloud+ ? {+ organizationId: organization?.id,+ aiFeaturesEnabled: organization?.aiFeaturesEnabled === true,+ isPending: createFilterMutation.isPending,+ generateFilters: async (prompt: string) => {+ if (!projectId) return null;+ const result = await createFilterMutation.mutateAsync({+ projectId,+ prompt,+ });+ return result && Array.isArray(result.filters)+ ? (result.filters as WipFilterState)+ : null;+ },+ }+ : undefined;return (<div className="flex items-center">@@ -286,7 +317,7 @@ export function PopoverFilterBuilder({filterState={wipFilterState}onChange={setWipFilterState}columnsWithCustomSelect={columnsWithCustomSelect}- filterWithAI={filterWithAI}+ aiFilter={aiFilter}/></PopoverContent></Popover>@@ -335,36 +366,69 @@ export function InlineFilterState({className?: string;}) {return filterState.map((filter, i) => {+ const column = (() => {+ if (+ filter.type === "stringObject" ||+ filter.type === "numberObject" ||+ filter.type === "booleanObject"+ ) {+ return `${filter.column}.${filter.key}`;+ }++ return filter.column;+ })();++ const value = (() => {+ if (filter.type === "positionInTrace") {+ return formatSessionPositionInTraceFilterValue(filter);+ }+ if (filter.type === "datetime") {+ return new Date(filter.value).toLocaleString();+ }+ if (filter.type === "stringOptions" || filter.type === "arrayOptions") {+ if (filter.value.length > 2) {+ return `${filter.value.length} selected`;+ }++ return filter.value.join(", ");+ }+ if (filter.type === "number" || filter.type === "numberObject") {+ return filter.value;+ }+ if (filter.type === "boolean" || filter.type === "booleanObject") {+ return `${filter.value}`;+ }+ if (filter.type === "null") {+ return "";+ }++ return `"${filter.value}"`;+ })();++ const numericValue =+ value !== "" && /^-?\d+(\.\d+)?$/.test(String(value).trim());+return (<spankey={i}- className={cn(- "bg-input ml-2 rounded-md px-2 py-1 text-xs whitespace-nowrap",- className,- )}+ className={cn("ml-2 inline-block text-xs whitespace-nowrap", className)}>- {filter.column}- {filter.type === "stringObject" ||- filter.type === "numberObject" ||- filter.type === "booleanObject"- ? `.${filter.key}`- : ""}{" "}- {filter.operator}{" "}- {filter.type === "positionInTrace"- ? formatSessionPositionInTraceFilterValue(filter)- : filter.type === "datetime"- ? new Date(filter.value).toLocaleString()- : filter.type === "stringOptions" || filter.type === "arrayOptions"- ? filter.value.length > 2- ? `${filter.value.length} selected`- : filter.value.join(", ")- : filter.type === "number" || filter.type === "numberObject"- ? filter.value- : filter.type === "boolean" || filter.type === "booleanObject"- ? `${filter.value}`- : filter.type === "null"- ? ""- : `"${filter.value}"`}+ <FilterToken deactivated={false} title={undefined}>+ <span className="text-qlang-field">{column}</span>{" "}+ <span className="text-muted-foreground">{filter.operator}</span>+ {value !== "" ? (+ <>+ {" "}+ <span+ className={+ numericValue ? "text-qlang-number" : "text-qlang-value"+ }+ >+ {value}+ </span>+ </>+ ) : null}+ </FilterToken></span>);});@@ -379,7 +443,6 @@ export function InlineFilterBuilder({columnIdentifier = "name",disabled,columnsWithCustomSelect,- filterWithAI = false,}: {columns: ColumnDefinitionWithAlert[];filterState: FilterState;@@ -390,7 +453,6 @@ export function InlineFilterBuilder({columnIdentifier?: ColumnIdentifier;disabled?: boolean;columnsWithCustomSelect?: string[];- filterWithAI?: boolean;}) {const [wipFilterState, _setWipFilterState] =useState<WipFilterState>(filterState);@@ -436,7 +498,6 @@ export function InlineFilterBuilder({onChange={setWipFilterState}disabled={disabled}columnsWithCustomSelect={columnsWithCustomSelect}- filterWithAI={filterWithAI}/></div>);@@ -479,7 +540,7 @@ function FilterBuilderForm({onChange,disabled,columnsWithCustomSelect = [],- filterWithAI = false,+ aiFilter,}: {columnIdentifier: ColumnIdentifier;columns: ColumnDefinitionWithAlert[];@@ -487,17 +548,11 @@ function FilterBuilderForm({onChange: Dispatch<SetStateAction<WipFilterState>>;disabled?: boolean;columnsWithCustomSelect?: string[];- filterWithAI?: boolean;+ aiFilter?: AiFilterConfig;}) {- const { isLangfuseCloud } = useLangfuseCloudRegion();const [showAiFilter, setShowAiFilter] = useState(false);const [aiPrompt, setAiPrompt] = useState("");const [aiError, setAiError] = useState<string | null>(null);- const projectId = useProjectIdFromURL();- const { organization } = useQueryProject();-- const createFilterMutation =- api.naturalLanguageFilters.createCompletion.useMutation();const handleFilterChange = (filter: WipFilterCondition, i: number) => {onChange((prev) => {const newState = [...prev];@@ -528,29 +583,23 @@ function FilterBuilderForm({};const handleAiFilterSubmit = async () => {- if (aiPrompt.trim() && !createFilterMutation.isPending && projectId) {+ if (aiPrompt.trim() && aiFilter && !aiFilter.isPending) {setAiError(null);try {- const result = await createFilterMutation.mutateAsync({- projectId,- prompt: aiPrompt.trim(),- });+ const filters = await aiFilter.generateFilters(aiPrompt.trim());- if (result && Array.isArray(result.filters)) {- if (result.filters.length === 0) {+ if (filters) {+ if (filters.length === 0) {setAiError("Failed to generate filters, try again");return;}// Set the filters from the API response- onChange(result.filters as WipFilterState);+ onChange(filters);setAiPrompt("");setShowAiFilter(false);} else {- console.error(- "filterBuilder.aiGenerate: invalid response format",- JSON.stringify(result),- );+ console.error("filterBuilder.aiGenerate: invalid response format");setAiError("Invalid response format from API");}} catch (error) {@@ -565,12 +614,12 @@ function FilterBuilderForm({return (<>{/* AI Filter Section at the top */}- {!disabled && isLangfuseCloud && filterWithAI && (+ {!disabled && aiFilter && (<div className="flex flex-col gap-2"><ButtononClick={() => {- if (!organization?.aiFeaturesEnabled && organization?.id) {- openAIFeaturesSettings(organization.id);+ if (!aiFilter.aiFeaturesEnabled && aiFilter.organizationId) {+ openAIFeaturesSettings(aiFilter.organizationId);} else {setShowAiFilter(!showAiFilter);}@@ -579,14 +628,14 @@ function FilterBuilderForm({variant="outline"size="default"title={- !organization?.aiFeaturesEnabled+ !aiFilter.aiFeaturesEnabled? "AI features are disabled for your organization. Click to enable them in organization settings.": undefined}className="text-muted-foreground w-full justify-start"><WandSparkles className="mr-2 h-4 w-4" />- {!organization?.aiFeaturesEnabled ? (+ {!aiFilter.aiFeaturesEnabled ? (<>AI Filters: Enable in Organization Settings (Admin Only)<ExternalLink className="ml-2 h-4 w-4" />@@ -607,13 +656,9 @@ function FilterBuilderForm({}}placeholder="Describe the filters you want to apply..."className="min-h-[80px] min-w-112 resize-none"- disabled={createFilterMutation.isPending}+ disabled={aiFilter.isPending}onKeyDown={(e) => {- if (- e.key === "Enter" &&- e.ctrlKey &&- !createFilterMutation.isPending- ) {+ if (e.key === "Enter" && e.ctrlKey && !aiFilter.isPending) {handleAiFilterSubmit();}}}@@ -624,11 +669,9 @@ function FilterBuilderForm({type="button"variant="default"size="sm"- disabled={createFilterMutation.isPending || !aiPrompt.trim()}+ disabled={aiFilter.isPending || !aiPrompt.trim()}>- {createFilterMutation.isPending- ? "Loading..."- : "Generate filters"}+ {aiFilter.isPending ? "Loading..." : "Generate filters"}</Button><Tooltip><TooltipTrigger asChild>diff --git a/web/src/features/search-bar/components/ComposerTokens.tsx b/web/src/features/search-bar/components/ComposerTokens.tsxindex d36a14fe37..2441eef313 100644--- a/web/src/features/search-bar/components/ComposerTokens.tsx+++ b/web/src/features/search-bar/components/ComposerTokens.tsx@@ -18,6 +18,7 @@ import {type FilterSegment,} from "@/src/features/search-bar/lib/composer-segments";import { indexOfOutsideQuotes } from "@/src/features/search-bar/lib/langQ";+import { FilterToken } from "@/src/features/filters/components/FilterToken";// Word joiner around pills: gives the DOM caret boundaries between tokens// without changing the query text. Stripped before the text reaches the model@@ -35,8 +36,7 @@ export const WORD_JOINER = "";export const composerTokenVariants = cva("max-w-full", {variants: {kind: {- filter:- "mr-1 inline rounded border px-1.5 py-0.5 border-border bg-secondary text-secondary-foreground shadow-sm transition-colors hover:border-ring hover:bg-accent",+ filter: "",freeText:"mr-1 inline rounded border px-1.5 py-0.5 border-transparent bg-muted/70 text-foreground/90 transition-colors hover:border-border hover:bg-accent",operator: "font-bold uppercase text-qlang-keyword",@@ -163,16 +163,8 @@ export function ComposerTokens({: segment.kind === "freeText"? `Full-text search — matches results containing "${segment.raw}". Searches ids, names, input and output by default; use input: or output: to search one payload, or name:/id: to narrow.`: segment.raw;- out.push(- <span- key={segment.id}- data-testid="search-bar-token"- data-kind={visibleKind}- data-deactivated={deactivated || undefined}- data-segment-id={segment.id}- title={title}- className={composerTokenVariants({ kind: visibleKind, deactivated })}- >+ const content = (+ <>{segment.kind === "filter" ? (<FilterTokenBody segment={segment} />) : (@@ -185,7 +177,33 @@ export function ComposerTokens({paint the caret past the padding + margin (the "caret renders outsidethe block" bug). */}{WORD_JOINER}- </span>,+ </>+ );+ out.push(+ segment.kind === "filter" ? (+ <FilterToken+ key={segment.id}+ data-testid="search-bar-token"+ data-kind={visibleKind}+ data-segment-id={segment.id}+ title={title}+ deactivated={deactivated}+ >+ {content}+ </FilterToken>+ ) : (+ <span+ key={segment.id}+ data-testid="search-bar-token"+ data-kind={visibleKind}+ data-deactivated={deactivated || undefined}+ data-segment-id={segment.id}+ title={title}+ className={composerTokenVariants({ kind: visibleKind, deactivated })}+ >+ {content}+ </span>+ ),);cursor = segment.to;}diff --git a/web/src/hooks/useVirtualizedScrollSpy.clienttest.ts b/web/src/hooks/useVirtualizedScrollSpy.clienttest.tsnew file mode 100644index 0000000000..758b52b7da--- /dev/null+++ b/web/src/hooks/useVirtualizedScrollSpy.clienttest.ts@@ -0,0 +1,118 @@+import { act, fireEvent, renderHook } from "@testing-library/react";+import { type Virtualizer } from "@tanstack/react-virtual";+import { describe, expect, it, vi } from "vitest";++import { useVirtualizedScrollSpy } from "@/src/hooks/useVirtualizedScrollSpy";++const items = Array.from({ length: 100 }, (_, index) => ({+ id: String(index),+}));+const virtualItems = items.map((_, index) => ({+ index,+ key: String(index),+ start: index * 100,+ end: (index + 1) * 100,+ size: 100,+ lane: 0,+}));++function renderScrollSpy(scrollOffset: number) {+ const scrollElement = document.createElement("div");+ scrollElement.scrollTo = vi.fn();+ const virtualizer = {+ scrollOffset,+ getTotalSize: () => 10_000,+ getVirtualItems: () => virtualItems,+ getOffsetForIndex: (index: number) => [index * 100],+ } as unknown as Virtualizer<HTMLDivElement, HTMLDivElement>;++ const hook = renderHook(() =>+ useVirtualizedScrollSpy({+ items,+ virtualizer,+ scrollElementRef: { current: scrollElement },+ viewportHeight: 1_000,+ endTransitionRatio: 0.2,+ }),+ );++ return { ...hook, scrollElement };+}++function renderFittingScrollSpy() {+ const fittingItems = items.slice(0, 5);+ const fittingVirtualItems = virtualItems.slice(0, 5);+ const scrollElement = document.createElement("div");+ scrollElement.scrollTo = vi.fn();+ const virtualizer = {+ scrollOffset: 0,+ getTotalSize: () => 500,+ getVirtualItems: () => fittingVirtualItems,+ getOffsetForIndex: (index: number) => [index * 100],+ } as unknown as Virtualizer<HTMLDivElement, HTMLDivElement>;++ const hook = renderHook(() =>+ useVirtualizedScrollSpy({+ items: fittingItems,+ virtualizer,+ scrollElementRef: { current: scrollElement },+ viewportHeight: 1_000,+ endTransitionRatio: 0.2,+ }),+ );++ return { ...hook, scrollElement };+}++describe("useVirtualizedScrollSpy", () => {+ it("tracks the item at the sticky top edge until the end transition", () => {+ expect(renderScrollSpy(0).result.current.activeItemId).toBe("0");+ expect(renderScrollSpy(100).result.current.activeItemId).toBe("1");+ expect(renderScrollSpy(200).result.current.activeItemId).toBe("2");+ expect(renderScrollSpy(5_000).result.current.activeItemId).toBe("50");+ expect(renderScrollSpy(8_900).result.current.activeItemId).toBe("93");+ expect(renderScrollSpy(9_000).result.current.activeItemId).toBe("99");+ });++ it("scrolls to the selected item start", () => {+ const { result, scrollElement } = renderScrollSpy(5_000);++ act(() => result.current.selectItem(89));++ expect(result.current.activeItemId).toBe("89");+ expect(scrollElement.scrollTo).toHaveBeenCalledWith({+ top: 8_900,+ behavior: "smooth",+ });+ });++ it("clamps a selected item start to the available scroll range", () => {+ const { result, scrollElement } = renderScrollSpy(5_000);++ act(() => result.current.selectItem(99));++ expect(scrollElement.scrollTo).toHaveBeenCalledWith({+ top: 9_000,+ behavior: "smooth",+ });+ expect(renderScrollSpy(9_000).result.current.activeItemId).toBe("99");+ });++ it("keeps an unscrollable selection active within a scroll buffer", () => {+ const { result, scrollElement } = renderFittingScrollSpy();++ act(() => result.current.selectItem(4));+ expect(result.current.activeItemId).toBe("4");++ act(() => result.current.selectItem(2));+ expect(result.current.activeItemId).toBe("2");++ scrollElement.scrollTop = 95;+ fireEvent.scroll(scrollElement);+ expect(result.current.activeItemId).toBe("2");++ scrollElement.scrollTop = 97;+ fireEvent.scroll(scrollElement);+ expect(result.current.activeItemId).toBe("0");+ });+});diff --git a/web/src/hooks/useVirtualizedScrollSpy.ts b/web/src/hooks/useVirtualizedScrollSpy.tsnew file mode 100644index 0000000000..fa539878db--- /dev/null+++ b/web/src/hooks/useVirtualizedScrollSpy.ts@@ -0,0 +1,179 @@+import { useCallback, useEffect, useState, type RefObject } from "react";+import { type Virtualizer } from "@tanstack/react-virtual";++/**+ * Returns the point in the virtualized content that determines the active item.+ *+ * The anchor moves through two phases as the user scrolls:+ *+ * 1. Through the normal scroll range, it stays at the viewport's top edge so+ * the active item matches a sticky item header.+ * 2. Near the end, it moves from the top to the viewport's bottom edge. This+ * allows the final items to become active without adding empty padding after+ * the content.+ *+ * The return value is an absolute content coordinate, not an offset within the+ * viewport. It can therefore be compared directly with TanStack Virtual's+ * `VirtualItem.start` and `VirtualItem.end` values.+ */+function getScrollSpyAnchor({+ scrollOffset,+ viewportHeight,+ totalSize,+ endTransitionRatio,+}: {+ scrollOffset: number;+ viewportHeight: number;+ totalSize: number;+ endTransitionRatio: number;+}) {+ const maxScrollOffset = Math.max(0, totalSize - viewportHeight);+ if (viewportHeight <= 0 || maxScrollOffset === 0) return scrollOffset;++ const clampedScrollOffset = Math.max(+ 0,+ Math.min(scrollOffset, maxScrollOffset),+ );+ const viewportBottomOffset = Math.max(0, viewportHeight - 1);+ const clampedEndTransitionRatio = Math.max(+ 0,+ Math.min(endTransitionRatio, 1),+ );+ const transitionDistance = Math.min(+ viewportHeight * clampedEndTransitionRatio,+ maxScrollOffset,+ );+ if (transitionDistance === 0) return clampedScrollOffset;++ const distanceToBottom = maxScrollOffset - clampedScrollOffset;+ if (distanceToBottom >= transitionDistance) {+ return clampedScrollOffset;+ }++ const endProgress = 1 - distanceToBottom / transitionDistance;+ // Stop one pixel before the viewport boundary. The item range comparison is+ // end-exclusive, so using viewportHeight exactly could produce totalSize and+ // leave no item containing the anchor at the natural scroll bottom.+ const anchorOffset = viewportBottomOffset * endProgress;+ return clampedScrollOffset + anchorOffset;+}++/**+ * Coordinates scroll-spy state for a TanStack Virtual list.+ *+ * The active item is derived from the virtual item containing a+ * viewport-relative anchor. Selecting an item smoothly scrolls to its start.+ *+ * If the list is too short to scroll to the selected item, selection remains+ * active until the user scrolls beyond a small viewport-relative buffer.+ *+ * The hook also returns the current `virtualItems` so the consumer renders the+ * same virtualizer snapshot used to derive `activeItemId`.+ *+ * `endTransitionRatio` controls how much of the final scroll range moves the+ * anchor from the viewport top to bottom. Values outside 0 through 1 are+ * clamped.+ */+export function useVirtualizedScrollSpy<+ TItem extends { id: string },+ TScrollElement extends HTMLElement,+ TItemElement extends Element,+>({+ items,+ virtualizer,+ scrollElementRef,+ viewportHeight,+ endTransitionRatio,+}: {+ items: TItem[];+ virtualizer: Virtualizer<TScrollElement, TItemElement>;+ scrollElementRef: RefObject<TScrollElement | null>;+ viewportHeight: number;+ endTransitionRatio: number;+}) {+ const [selectedFallback, setSelectedFallback] = useState<{+ itemId: string;+ scrollOffset: number;+ } | null>(null);+ const virtualItems = virtualizer.getVirtualItems();+ const scrollOffset = virtualizer.scrollOffset ?? 0;+ const fallbackBuffer = Math.min(96, viewportHeight * 0.1);+ const scrollSpyAnchor = getScrollSpyAnchor({+ scrollOffset,+ viewportHeight,+ totalSize: virtualizer.getTotalSize(),+ endTransitionRatio,+ });+ const activeVirtualItem =+ virtualItems.find(+ (item) => item.start <= scrollSpyAnchor && item.end > scrollSpyAnchor,+ ) ?? virtualItems.find((item) => item.start > scrollSpyAnchor);+ const scrollSpyItemId =+ items[activeVirtualItem?.index ?? 0]?.id ?? items[0]?.id;++ useEffect(() => {+ const scrollElement = scrollElementRef.current;+ if (!selectedFallback || !scrollElement) return;++ const clearFallbackOutsideBuffer = () => {+ if (+ Math.abs(scrollElement.scrollTop - selectedFallback.scrollOffset) <=+ fallbackBuffer+ ) {+ return;+ }++ setSelectedFallback((currentFallback) =>+ currentFallback === selectedFallback ? null : currentFallback,+ );+ };++ scrollElement.addEventListener("scroll", clearFallbackOutsideBuffer, {+ passive: true,+ });+ return () =>+ scrollElement.removeEventListener("scroll", clearFallbackOutsideBuffer);+ }, [fallbackBuffer, scrollElementRef, selectedFallback]);++ const selectItem = useCallback(+ (index: number) => {+ const scrollElement = scrollElementRef.current;+ const item = items[index];+ const offset = virtualizer.getOffsetForIndex(index, "start")?.[0];+ if (!item || !scrollElement || offset === undefined) return;++ const totalSize = virtualizer.getTotalSize();+ const scrollTarget = Math.min(+ offset,+ Math.max(0, totalSize - viewportHeight),+ );+ const targetAnchor = getScrollSpyAnchor({+ scrollOffset: scrollTarget,+ viewportHeight,+ totalSize,+ endTransitionRatio,+ });+ const nextItemOffset =+ virtualizer.getOffsetForIndex(index + 1, "start")?.[0] ?? totalSize;+ const selectionIsRepresented =+ offset <= targetAnchor && targetAnchor < nextItemOffset;++ setSelectedFallback(+ selectionIsRepresented+ ? null+ : { itemId: item.id, scrollOffset: scrollTarget },+ );++ // Native scrolling avoids TanStack's smooth-scroll retries against+ // dynamically measured rows stopping one row before the target.+ scrollElement.scrollTo({ top: scrollTarget, behavior: "smooth" });+ },+ [endTransitionRatio, items, scrollElementRef, viewportHeight, virtualizer],+ );++ return {+ activeItemId: selectedFallback?.itemId ?? scrollSpyItemId,+ virtualItems,+ selectItem,+ };+}