🪢 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(observations): checkboxes in traces/observations are more performant and support shift-selection (#14021)
Nikita Kabardin72ba6a094159
diff --git a/web/src/components/table/data-table.tsx b/web/src/components/table/data-table.tsxindex 8860c29980..5e787280a0 100644--- a/web/src/components/table/data-table.tsx+++ b/web/src/components/table/data-table.tsx@@ -48,6 +48,11 @@ import { type DataTablePeekViewProps } from "@/src/components/table/peek";import isEqual from "lodash/isEqual";import { useRouter } from "next/router";import { useColumnSizing } from "@/src/components/table/hooks/useColumnSizing";+import {+ type TableSelectionStoreLike,+ useTableRowIsSelected,+ useTableSelectAll,+} from "@/src/components/table/table-selection-store";interface DataTableProps<TData, TValue> {columns: LangfuseColumnDef<TData, TValue>[];@@ -62,6 +67,8 @@ interface DataTableProps<TData, TValue> {};rowSelection?: RowSelectionState;setRowSelection?: OnChangeFn<RowSelectionState>;+ /** External selection store; row highlight/checkbox state reads from it instead of TanStack rowSelection */+ selectionStore?: TableSelectionStoreLike;columnVisibility?: VisibilityState;onColumnVisibilityChange?: OnChangeFn<VisibilityState>;columnOrder?: ColumnOrderState;@@ -173,6 +180,7 @@ export function DataTable<TData extends object, TValue>({pagination,rowSelection,setRowSelection,+ selectionStore,columnVisibility,onColumnVisibilityChange,columnOrder,@@ -446,6 +454,7 @@ export function DataTable<TData extends object, TValue>({onRowClick={hasRowClickAction ? handleOnRowClick : undefined}getRowClassName={getRowClassName}highlightAllRows={highlightAllRows}+ selectionStore={selectionStore}topAlignCells={topAlignCells}cellPadding={cellPadding}tableSnapshot={{@@ -466,6 +475,7 @@ export function DataTable<TData extends object, TValue>({onRowClick={hasRowClickAction ? handleOnRowClick : undefined}getRowClassName={getRowClassName}highlightAllRows={highlightAllRows}+ selectionStore={selectionStore}topAlignCells={topAlignCells}cellPadding={cellPadding}/>@@ -514,6 +524,7 @@ interface TableBodyComponentProps<TData> {onRowClick?: (row: TData, event?: React.MouseEvent) => void;getRowClassName?: (row: TData) => string;highlightAllRows?: boolean;+ selectionStore?: TableSelectionStoreLike;topAlignCells?: boolean;cellPadding?: DataTableCellPadding;/** Used for React.memo comparison only */@@ -529,16 +540,27 @@ function TableRowComponent<TData>({onRowClick,getRowClassName,highlightAllRows = false,+ selectionStore,children,}: {row: Row<TData>;onRowClick?: (row: TData, event?: React.MouseEvent) => void;getRowClassName?: (row: TData) => string;highlightAllRows?: boolean;+ selectionStore?: TableSelectionStoreLike;children: React.ReactNode;}) {const router = useRouter();const selectedRowId = router.query.peek as string | undefined;+ const rowIsSelected = useTableRowIsSelected(+ selectionStore,+ row.id,+ row.getIsSelected(),+ );+ const shouldHighlightAllRows = useTableSelectAll(+ selectionStore,+ highlightAllRows,+ );return (<TableRow@@ -556,7 +578,7 @@ function TableRowComponent<TData>({className={cn("hover:bg-accent",!!onRowClick ? "cursor-pointer" : "cursor-default",- (row.getIsSelected() || highlightAllRows) &&+ (rowIsSelected || shouldHighlightAllRows) &&"bg-muted/40 dark:bg-muted",selectedRowId && selectedRowId === row.id? "bg-muted/40 dark:bg-muted"@@ -580,14 +602,17 @@ function TableBodyComponent<TData>({onRowClick,getRowClassName,highlightAllRows,+ selectionStore,topAlignCells = false,cellPadding = "compact",tableSnapshot: _tableSnapshot,}: TableBodyComponentProps<TData>) {const visibleColumns = table.getVisibleLeafColumns();+ const rowModelRows = table.getRowModel().rows;+ const tableState = table.getState();const skeletonRowCount = Math.max(1,- Math.min(table.getState().pagination?.pageSize ?? 8, 8),+ Math.min(tableState.pagination?.pageSize ?? 8, 8),);return (@@ -655,14 +680,15 @@ function TableBodyComponent<TData>({})}</TableRow>))- ) : table.getRowModel().rows.length ? (- table.getRowModel().rows.map((row) => (+ ) : rowModelRows.length ? (+ rowModelRows.map((row) => (<TableRowComponentkey={row.id}row={row}onRowClick={onRowClick}getRowClassName={getRowClassName}highlightAllRows={highlightAllRows}+ selectionStore={selectionStore}>{row.getVisibleCells().map((cell) => {const cellValue = cell.getValue();@@ -773,6 +799,7 @@ const MemoizedTableBody = React.memo(TableBodyComponent, (prev, next) => {if (prev.rowheighttw !== next.rowheighttw) return false;if (prev.rowHeight !== next.rowHeight) return false;if (prev.highlightAllRows !== next.highlightAllRows) return false;+ if (prev.selectionStore !== next.selectionStore) return false;if (prev.cellPadding !== next.cellPadding) return false;// Then do more expensive deep equality checksdiff --git a/web/src/components/table/table-selection-store.ts b/web/src/components/table/table-selection-store.tsnew file mode 100644index 0000000000..a2cd1f84a6--- /dev/null+++ b/web/src/components/table/table-selection-store.ts@@ -0,0 +1,80 @@+import { useSyncExternalStore } from "react";+import { type RowSelectionState, type Updater } from "@tanstack/react-table";++type RowSelectionUpdater = Updater<RowSelectionState>;+type BooleanUpdater = Updater<boolean>;++export interface TableSelectionStoreState {+ rowSelection: RowSelectionState;+ selectAll: boolean;+ selectedPageRowIds: string[];+ pageRowIds: string[];+ totalCount: number | null;+ actions: {+ setRowSelection: (updater: RowSelectionUpdater) => void;+ setSelectAll: (updater: BooleanUpdater) => void;+ toggleRow: (rowId: string, nextSelected: boolean) => void;+ toggleRows: (rowIds: string[], nextSelected: boolean) => void;+ togglePageRows: (rowIds: string[], nextSelected: boolean) => void;+ clearSelection: () => void;+ };+}++/**+ * Minimal store surface DataTable needs for selection rendering. Tables that+ * keep selection in an external store pass it explicitly via the+ * `selectionStore` prop; DataTable stays context-free so nested tables are+ * unaffected by each other's selection state.+ */+export interface TableSelectionStoreLike {+ subscribe: (listener: () => void) => () => void;+ getState: () => TableSelectionStoreState;+}++const subscribeNoop = () => () => undefined;++function useTableSelectionValue<TValue>(+ store: TableSelectionStoreLike | undefined,+ selector: (state: TableSelectionStoreState) => TValue,+ fallback: TValue,+) {+ return useSyncExternalStore(+ store?.subscribe ?? subscribeNoop,+ () => (store ? selector(store.getState()) : fallback),+ () => fallback,+ );+}++export function useTableRowIsSelected(+ store: TableSelectionStoreLike | undefined,+ rowId: string,+ fallbackSelected: boolean,+) {+ return useTableSelectionValue(+ store,+ (state) => Boolean(state.rowSelection[rowId]),+ fallbackSelected,+ );+}++export function useTableSelectAll(+ store: TableSelectionStoreLike | undefined,+ fallbackSelectAll: boolean,+) {+ return useTableSelectionValue(+ store,+ (state) => state.selectAll,+ fallbackSelectAll,+ );+}++export function useTableRowSelection(+ store: TableSelectionStoreLike | undefined,+ fallbackRowSelection: RowSelectionState,+) {+ return useTableSelectionValue(+ store,+ (state) => state.rowSelection,+ fallbackRowSelection,+ );+}diff --git a/web/src/components/table/use-cases/observations.tsx b/web/src/components/table/use-cases/observations.tsxindex b2a7b82057..a285c89877 100644--- a/web/src/components/table/use-cases/observations.tsx+++ b/web/src/components/table/use-cases/observations.tsx@@ -6,7 +6,14 @@ import {DataTableControls,} from "@/src/components/table/data-table-controls";import { ResizableFilterLayout } from "@/src/components/table/resizable-filter-layout";-import { useEffect, useMemo, useState, useRef, useCallback } from "react";+import {+ useEffect,+ useLayoutEffect,+ useMemo,+ useState,+ useRef,+ useCallback,+} from "react";import { TokenUsageBadge } from "@/src/components/token-usage-badge";import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";import { usePaginationState } from "@/src/hooks/usePaginationState";@@ -39,6 +46,8 @@ import {BatchActionType,ActionId,type TimeFilter,+ type OrderByState,+ type TracingSearchType,} from "@langfuse/shared";import { cn } from "@/src/utils/tailwind";import { LevelColors } from "@/src/components/level-colors";@@ -64,7 +73,6 @@ import { InfoIcon, PlusCircle } from "lucide-react";import { UpsertModelFormDialog } from "@/src/features/models/components/UpsertModelFormDialog";import { LocalIsoDate } from "@/src/components/LocalIsoDate";import { Badge } from "@/src/components/ui/badge";-import { type RowSelectionState } from "@tanstack/react-table";import TableIdOrName from "@/src/components/table/table-id";import { ItemBadge } from "@/src/components/ItemBadge";import { TablePeekViewObservationDetail } from "@/src/components/table/peek/peek-observation-detail";@@ -77,7 +85,6 @@ import { useTableViewManager } from "@/src/components/table/table-view-presets/himport { useRouter } from "next/router";import { useFullTextSearch } from "@/src/components/table/use-cases/useFullTextSearch";import { TableSelectionManager } from "@/src/features/table/components/TableSelectionManager";-import { useSelectAll } from "@/src/features/table/hooks/useSelectAll";import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";import { TableActionMenu } from "@/src/features/table/components/TableActionMenu";import { type TableAction } from "@/src/features/table/types";@@ -92,6 +99,11 @@ import {type RefreshInterval,REFRESH_INTERVALS,} from "@/src/components/table/data-table-refresh-button";+import {+ ObservationsTableStoreProvider,+ useObservationsTableStore,+} from "@/src/features/tracing-tables/observations/ObservationsTableStoreProvider";+import { useObservationsTableView } from "@/src/features/tracing-tables/observations/useObservationsTableView";export type ObservationsTableRow = {// Shown by default@@ -174,7 +186,9 @@ export default function ObservationsTable({const utils = api.useUtils();const { setDetailPageList } = useDetailPageLists();- const [selectedRows, setSelectedRows] = useState<RowSelectionState>({});+ const { store: observationsTableStore } = useObservationsTableView({+ projectId,+ });const [rawRefreshInterval, setRawRefreshInterval] =useSessionStorage<RefreshInterval>(`tableRefreshInterval-${projectId}`,@@ -231,9 +245,6 @@ export default function ObservationsTable({const legacyTracingIoSearchEnabled =legacyTracingSearchConfig.data?.legacyTracingIoSearchEnabled ?? true;- const { selectAll, setSelectAll } = useSelectAll(projectId, "observations");- const [showAddToDatasetDialog, setShowAddToDatasetDialog] = useState(false);-const [paginationState, setPaginationState] = usePaginationState(0, 50, {page: "pageIndex",limit: "pageSize",@@ -590,8 +601,9 @@ export default function ObservationsTable({const { selectActionColumn } = TableSelectionManager<ObservationsTableRow>({projectId,tableName: "observations",- setSelectedRows,- setSelectAll,+ setSelectedRows: observationsTableStore.getState().actions.setRowSelection,+ setSelectAll: observationsTableStore.getState().actions.setSelectAll,+ selectionStore: observationsTableStore,});const handleAddToAnnotationQueue = async ({@@ -601,10 +613,11 @@ export default function ObservationsTable({projectId: string;targetId: string;}) => {- const selectedGenerationIds = Object.keys(selectedRows).filter(- (generationId) =>- generations.data?.generations.map((g) => g.id).includes(generationId),- );+ const {+ actions,+ selectAll,+ selectedPageRowIds: selectedGenerationIds,+ } = observationsTableStore.getState();await addToQueueMutation.mutateAsync({projectId,@@ -617,7 +630,7 @@ export default function ObservationsTable({orderBy: orderByState,},});- setSelectedRows({});+ actions.clearSelection();};const tableActions: TableAction[] = [@@ -1376,24 +1389,23 @@ export default function ObservationsTable({: [];}, [generations]);- const selectedObservationIds = useMemo(- () =>- Object.keys(selectedRows).filter((generationId) =>- generations.data?.generations.map((g) => g.id).includes(generationId),- ),- [selectedRows, generations.data?.generations],- );+ const pageRowIds = useMemo(() => rows.map((row) => row.id), [rows]);- const selectedObservationCount = selectAll- ? totalCount- : selectedObservationIds.length;+ // Layout effect so store-subscribed consumers (toolbar count) update before+ // paint when the page rows change — no one-frame stale selection count.+ useLayoutEffect(() => {+ observationsTableStore.getState().actions.syncPageRows({+ pageRowIds,+ totalCount,+ });+ }, [observationsTableStore, pageRowIds, totalCount]);- return (- <DataTableControlsProvider tableName={observationsFilterConfig.tableName}>+ const content = (+ <><div className="flex h-full w-full flex-col">{/* Toolbar spanning full width */}{!hideControls && (- <DataTableToolbar+ <ObservationsDataTableToolbarcolumns={columns}filterState={queryFilter.explicitFilterState}searchConfig={{@@ -1431,45 +1443,13 @@ export default function ObservationsTable({interval: refreshInterval,setInterval: setRefreshInterval,}}- actionButtons={[- <BatchExportTableButton- {...{- projectId,- filterState: backendFilterState,- orderByState,- searchQuery,- searchType,- }}- tableName={BatchExportTableName.Observations}- key="batchExport"- />,- selectedObservationIds.length > 0 || selectAll ? (- <TableActionMenu- key="observations-multi-select-actions"- projectId={projectId}- actions={tableActions}- tableName={BatchExportTableName.Observations}- selectedCount={selectedObservationCount}- onClearSelection={() => {- setSelectedRows({});- setSelectAll(false);- }}- onCustomAction={(actionType) => {- if (actionType === ActionId.ObservationAddToDataset) {- setShowAddToDatasetDialog(true);- }- }}- />- ) : null,- ]}- multiSelect={{- selectAll,- setSelectAll,- selectedRowIds: selectedObservationIds,- setRowSelection: setSelectedRows,- totalCount,- ...paginationState,- }}+ projectId={projectId}+ backendFilterState={backendFilterState}+ searchQuery={searchQuery}+ searchType={searchType}+ tableActions={tableActions}+ totalCount={totalCount}+ paginationState={paginationState}/>)}@@ -1488,6 +1468,7 @@ export default function ObservationsTable({tableName={"observations"}columns={columns}peekView={peekConfig}+ selectionStore={observationsTableStore}data={generations.isPending || isViewLoading? { isLoading: true, isError: false }@@ -1512,9 +1493,6 @@ export default function ObservationsTable({state: paginationState,}}- rowSelection={selectedRows}- highlightAllRows={selectAll}- setRowSelection={setSelectedRows}setOrderBy={setOrderByState}orderBy={orderByState}columnOrder={columnOrder}@@ -1561,40 +1539,161 @@ export default function ObservationsTable({)}</div>- {/* Add to Dataset Dialog */}- {showAddToDatasetDialog && (- <AddObservationsToDatasetDialog- projectId={projectId}- selectedObservationIds={selectedObservationIds}- query={{- filter: backendFilterState,- orderBy: orderByState,- searchQuery: searchQuery ?? undefined,+ <ObservationsAddToDatasetDialog+ projectId={projectId}+ rows={rows}+ backendFilterState={backendFilterState}+ orderByState={orderByState}+ searchQuery={searchQuery}+ searchType={searchType}+ totalCount={totalCount}+ />+ </>+ );++ return (+ <DataTableControlsProvider tableName={observationsFilterConfig.tableName}>+ <ObservationsTableStoreProvider store={observationsTableStore}>+ {content}+ </ObservationsTableStoreProvider>+ </DataTableControlsProvider>+ );+}++type ObservationsDataTableToolbarProps = Omit<+ Parameters<typeof DataTableToolbar<ObservationsTableRow, unknown>>[0],+ "actionButtons" | "multiSelect"+> & {+ backendFilterState: FilterState;+ orderByState: OrderByState;+ paginationState: {+ pageIndex: number;+ pageSize: number;+ };+ projectId: string;+ searchQuery: string | null;+ searchType: TracingSearchType[];+ tableActions: TableAction[];+ totalCount: number | null;+};++function ObservationsDataTableToolbar({+ backendFilterState,+ orderByState,+ paginationState,+ projectId,+ searchQuery,+ searchType,+ tableActions,+ totalCount,+ ...toolbarProps+}: ObservationsDataTableToolbarProps) {+ const selectedObservationIds = useObservationsTableStore(+ (state) => state.selectedPageRowIds,+ );+ const selectAll = useObservationsTableStore((state) => state.selectAll);+ const actions = useObservationsTableStore((state) => state.actions);+ const selectedObservationCount = selectAll+ ? totalCount+ : selectedObservationIds.length;++ return (+ <DataTableToolbar+ {...toolbarProps}+ orderByState={orderByState}+ actionButtons={[+ <BatchExportTableButton+ {...{+ projectId,+ filterState: backendFilterState,+ orderByState,+ searchQuery,searchType,}}- selectAll={selectAll}- totalCount={totalCount ?? 0}- onClose={() => {- setShowAddToDatasetDialog(false);- setSelectedRows({});- setSelectAll(false);- }}- exampleObservation={(() => {- // Get the first selected observation to use for preview- const selectedIds = selectedObservationIds;- const firstId = selectedIds[0];- const firstGen = generations.data?.generations.find(- (g) => g.id === firstId,- );- return {- id: firstGen?.id ?? "",- traceId: firstGen?.traceId ?? "",- startTime: firstGen?.traceTimestamp ?? undefined,- };- })()}- />- )}- </DataTableControlsProvider>+ tableName={BatchExportTableName.Observations}+ key="batchExport"+ />,+ selectedObservationIds.length > 0 || selectAll ? (+ <TableActionMenu+ key="observations-multi-select-actions"+ projectId={projectId}+ actions={tableActions}+ tableName={BatchExportTableName.Observations}+ selectedCount={selectedObservationCount}+ onClearSelection={actions.clearSelection}+ onCustomAction={(actionType) => {+ if (actionType === ActionId.ObservationAddToDataset) {+ actions.setShowAddToDatasetDialog(true);+ }+ }}+ />+ ) : null,+ ]}+ multiSelect={{+ selectAll,+ setSelectAll: actions.setSelectAll,+ selectedRowIds: selectedObservationIds,+ setRowSelection: actions.setRowSelection,+ totalCount,+ ...paginationState,+ }}+ />+ );+}++function ObservationsAddToDatasetDialog({+ backendFilterState,+ orderByState,+ projectId,+ rows,+ searchQuery,+ searchType,+ totalCount,+}: {+ backendFilterState: FilterState;+ orderByState: OrderByState;+ projectId: string;+ rows: ObservationsTableRow[];+ searchQuery: string | null;+ searchType: TracingSearchType[];+ totalCount: number | null;+}) {+ const showAddToDatasetDialog = useObservationsTableStore(+ (state) => state.showAddToDatasetDialog,+ );+ const selectedObservationIds = useObservationsTableStore(+ (state) => state.selectedPageRowIds,+ );+ const selectAll = useObservationsTableStore((state) => state.selectAll);+ const actions = useObservationsTableStore((state) => state.actions);++ if (!showAddToDatasetDialog) return null;++ const firstId = selectedObservationIds[0];+ const firstRow = rows.find((row) => row.id === firstId);++ return (+ <AddObservationsToDatasetDialog+ projectId={projectId}+ selectedObservationIds={selectedObservationIds}+ query={{+ filter: backendFilterState,+ orderBy: orderByState,+ searchQuery: searchQuery ?? undefined,+ searchType,+ }}+ selectAll={selectAll}+ totalCount={totalCount ?? 0}+ onClose={() => {+ actions.setShowAddToDatasetDialog(false);+ actions.clearSelection();+ }}+ exampleObservation={{+ id: firstRow?.id ?? "",+ traceId: firstRow?.traceId ?? "",+ startTime: firstRow?.timestamp ?? undefined,+ }}+ />);}diff --git a/web/src/features/table/components/TableSelectionManager.clienttest.tsx b/web/src/features/table/components/TableSelectionManager.clienttest.tsxnew file mode 100644index 0000000000..9be4eccb60--- /dev/null+++ b/web/src/features/table/components/TableSelectionManager.clienttest.tsx@@ -0,0 +1,135 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { useMemo, useState } from "react";+import {+ flexRender,+ getCoreRowModel,+ useReactTable,+ type ColumnDef,+ type RowSelectionState,+} from "@tanstack/react-table";+import { TableSelectionManager } from "@/src/features/table/components/TableSelectionManager";++type TestRow = { id: string };++function Harness() {+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({});+ const { selectActionColumn } = TableSelectionManager<TestRow>({+ projectId: "project",+ tableName: "test",+ setSelectedRows: () => {},+ setSelectAll: () => {},+ });+ const data = useMemo(+ () => ["r1", "r2", "r3", "r4", "r5"].map((id) => ({ id })),+ [],+ );+ const table = useReactTable({+ data,+ columns: [selectActionColumn as ColumnDef<TestRow, unknown>],+ getCoreRowModel: getCoreRowModel(),+ getRowId: (row) => row.id,+ onRowSelectionChange: setRowSelection,+ state: { rowSelection },+ });++ return (+ <div>+ {table.getHeaderGroups().map((headerGroup) => (+ <div key={headerGroup.id}>+ {headerGroup.headers.map((header) => (+ <span key={header.id}>+ {flexRender(header.column.columnDef.header, header.getContext())}+ </span>+ ))}+ </div>+ ))}+ {table.getRowModel().rows.map((row) => (+ <div key={row.id}>+ {row.getVisibleCells().map((cell) => (+ <span key={cell.id}>+ {flexRender(cell.column.columnDef.cell, cell.getContext())}+ </span>+ ))}+ </div>+ ))}+ </div>+ );+}++// Re-query before every interaction: the column def is recreated per render,+// so flexRender remounts the checkbox cells and stale nodes go dead.+function getRowCheckboxes() {+ return screen.getAllByRole("checkbox", { name: "Select row" });+}++function clickRowCheckbox(index: number, options?: { shiftKey: boolean }) {+ fireEvent.click(getRowCheckboxes()[index]!, options);+}++function getCheckedStates() {+ return getRowCheckboxes().map(+ (checkbox) => checkbox.getAttribute("aria-checked") === "true",+ );+}++describe("TableSelectionManager shift-click range selection", () => {+ it("selects the range between the last clicked row and a shift-clicked row", () => {+ render(<Harness />);++ clickRowCheckbox(0);+ clickRowCheckbox(3, { shiftKey: true });++ expect(getCheckedStates()).toEqual([true, true, true, true, false]);+ });++ it("deselects the range when shift-clicking a selected row", () => {+ render(<Harness />);++ clickRowCheckbox(0);+ clickRowCheckbox(3, { shiftKey: true });+ // anchor is now r4; unchecking r2 with shift clears r2..r4+ clickRowCheckbox(1, { shiftKey: true });++ expect(getCheckedStates()).toEqual([true, false, false, false, false]);+ });++ it("treats a shift-click without a prior anchor as a single toggle", () => {+ render(<Harness />);++ clickRowCheckbox(2, { shiftKey: true });++ expect(getCheckedStates()).toEqual([false, false, true, false, false]);+ });++ it("plain clicks keep toggling single rows", () => {+ render(<Harness />);++ clickRowCheckbox(0);+ clickRowCheckbox(4);++ expect(getCheckedStates()).toEqual([true, false, false, false, true]);+ });++ it("header select-all/deselect-all resets the shift anchor", () => {+ render(<Harness />);++ clickRowCheckbox(0);+ const clickHeaderCheckbox = () =>+ fireEvent.click(screen.getByRole("checkbox", { name: "Select all" }));+ clickHeaderCheckbox();+ clickHeaderCheckbox();+ clickRowCheckbox(2, { shiftKey: true });++ expect(getCheckedStates()).toEqual([false, false, true, false, false]);+ });++ it("an emptied selection invalidates the shift anchor", () => {+ render(<Harness />);++ clickRowCheckbox(0);+ clickRowCheckbox(0); // selection is empty again, anchor would be stale+ clickRowCheckbox(3, { shiftKey: true });++ expect(getCheckedStates()).toEqual([false, false, false, true, false]);+ });+});diff --git a/web/src/features/table/components/TableSelectionManager.tsx b/web/src/features/table/components/TableSelectionManager.tsxindex 0e8d623098..1191c55547 100644--- a/web/src/features/table/components/TableSelectionManager.tsx+++ b/web/src/features/table/components/TableSelectionManager.tsx@@ -1,5 +1,11 @@+import { useRef, type RefObject } from "react";import { TableCheckboxLoadingCell } from "@/src/components/table/loading-cells";import { Checkbox } from "@/src/components/ui/checkbox";+import {+ type TableSelectionStoreLike,+ useTableRowIsSelected,+ useTableRowSelection,+} from "@/src/components/table/table-selection-store";import {type Table,type Row,@@ -11,6 +17,178 @@ interface TableSelectionManagerProps {tableName: string;setSelectedRows: (rows: RowSelectionState) => void;setSelectAll: (value: boolean) => void;+ /** External selection store; when set, checkboxes read/write it instead of TanStack rowSelection */+ selectionStore?: TableSelectionStoreLike;+}++function SelectionHeaderCheckbox<TData>({+ anchorRowIdRef,+ selectionStore,+ setSelectedRows,+ setSelectAll,+ table,+}: {+ anchorRowIdRef: RefObject<string | null>;+ selectionStore?: TableSelectionStoreLike;+ setSelectedRows: (rows: RowSelectionState) => void;+ setSelectAll: (value: boolean) => void;+ table: Table<TData>;+}) {+ const pageRows = table.getRowModel().rows;+ const pageRowIds = pageRows.map((row) => row.id);+ const rowSelection = useTableRowSelection(+ selectionStore,+ table.getState().rowSelection ?? {},+ );++ const allPageRowsSelected = selectionStore+ ? pageRowIds.length > 0 &&+ pageRowIds.every((rowId) => Boolean(rowSelection[rowId]))+ : table.getIsAllPageRowsSelected();+ const somePageRowsSelected = selectionStore+ ? !allPageRowsSelected &&+ pageRowIds.some((rowId) => Boolean(rowSelection[rowId]))+ : table.getIsSomePageRowsSelected();++ return (+ <div className="flex h-full items-center">+ <Checkbox+ checked={+ allPageRowsSelected+ ? true+ : somePageRowsSelected+ ? "indeterminate"+ : false+ }+ onCheckedChange={(value) => {+ const nextChecked = !!value;+ anchorRowIdRef.current = null;++ if (selectionStore) {+ if (nextChecked) {+ selectionStore+ .getState()+ .actions.togglePageRows(pageRowIds, nextChecked);+ } else {+ selectionStore.getState().actions.clearSelection();+ }+ return;+ }++ table.toggleAllPageRowsSelected(!!value);+ if (!value) {+ setSelectedRows({});+ setSelectAll(false);+ }+ }}+ aria-label="Select all"+ className="opacity-60"+ />+ </div>+ );+}++function SelectionRowCheckbox<TData>({+ row,+ table,+ anchorRowIdRef,+ selectionStore,+ setSelectAll,+}: {+ row: Row<TData>;+ table: Table<TData>;+ anchorRowIdRef: RefObject<string | null>;+ selectionStore?: TableSelectionStoreLike;+ setSelectAll: (value: boolean) => void;+}) {+ const shiftKeyRef = useRef(false);+ const rowIsSelected = useTableRowIsSelected(+ selectionStore,+ row.id,+ row.getIsSelected(),+ );++ const applyToRows = (rowIds: string[], nextSelected: boolean) => {+ if (selectionStore) {+ selectionStore.getState().actions.toggleRows(rowIds, nextSelected);+ return;+ }++ table.setRowSelection((previous) => {+ const next = { ...previous };+ for (const rowId of rowIds) {+ if (nextSelected) {+ next[rowId] = true;+ } else {+ delete next[rowId];+ }+ }+ return next;+ });+ if (!nextSelected) setSelectAll(false);+ };++ return (+ <div+ onClick={(e) => {+ e.stopPropagation();+ }}+ onClickCapture={(e) => {+ shiftKeyRef.current = e.shiftKey;+ }}+ onMouseDown={(e) => {+ // prevent text selection between rows on shift-click+ if (e.shiftKey) e.preventDefault();+ }}+ >+ <Checkbox+ checked={rowIsSelected}+ onCheckedChange={(value) => {+ const nextChecked = !!value;+ const pageRows = table.getRowModel().rows;+ const currentIndex = pageRows.findIndex(+ (pageRow) => pageRow.id === row.id,+ );+ // a range needs a live anchor: global clears (banner, action menu,+ // dialog close) empty the selection, which invalidates the anchor+ const currentRowSelection = selectionStore+ ? selectionStore.getState().rowSelection+ : (table.getState().rowSelection ?? {});+ const anchorIsLive =+ shiftKeyRef.current && Object.keys(currentRowSelection).length > 0;+ const anchorIndex = anchorIsLive+ ? pageRows.findIndex(+ (pageRow) => pageRow.id === anchorRowIdRef.current,+ )+ : -1;+ shiftKeyRef.current = false;+ anchorRowIdRef.current = row.id;++ if (anchorIndex !== -1 && currentIndex !== -1) {+ const [from, to] =+ anchorIndex < currentIndex+ ? [anchorIndex, currentIndex]+ : [currentIndex, anchorIndex];+ applyToRows(+ pageRows.slice(from, to + 1).map((pageRow) => pageRow.id),+ nextChecked,+ );+ return;+ }++ if (selectionStore) {+ selectionStore.getState().actions.toggleRow(row.id, nextChecked);+ return;+ }++ row.toggleSelected(!!value);+ if (!value) setSelectAll(false);+ }}+ aria-label="Select row"+ className="opacity-60"+ />+ </div>+ );}export function TableSelectionManager<TData>({@@ -18,7 +196,11 @@ export function TableSelectionManager<TData>({tableName: _tableName,setSelectedRows,setSelectAll,+ selectionStore,}: TableSelectionManagerProps) {+ // last explicitly clicked row; shift-click selects the range from it+ const anchorRowIdRef = useRef<string | null>(null);+return {selectActionColumn: {id: "select",@@ -28,43 +210,22 @@ export function TableSelectionManager<TData>({isPinnedLeft: true,loadingCell: <TableCheckboxLoadingCell />,header: ({ table }: { table: Table<TData> }) => (- <div className="flex h-full items-center">- <Checkbox- checked={- table.getIsAllPageRowsSelected()- ? true- : table.getIsSomePageRowsSelected()- ? "indeterminate"- : false- }- onCheckedChange={(value) => {- table.toggleAllPageRowsSelected(!!value);- if (!value) {- setSelectedRows({});- setSelectAll(false);- }- }}- aria-label="Select all"- className="opacity-60"- />- </div>+ <SelectionHeaderCheckbox+ table={table}+ anchorRowIdRef={anchorRowIdRef}+ selectionStore={selectionStore}+ setSelectedRows={setSelectedRows}+ setSelectAll={setSelectAll}+ />),- cell: ({ row }: { row: Row<TData> }) => (- <div- onClick={(e) => {- e.stopPropagation();- }}- >- <Checkbox- checked={row.getIsSelected()}- onCheckedChange={(value) => {- row.toggleSelected(!!value);- if (!value) setSelectAll(false);- }}- aria-label="Select row"- className="opacity-60"- />- </div>+ cell: ({ row, table }: { row: Row<TData>; table: Table<TData> }) => (+ <SelectionRowCheckbox+ row={row}+ table={table}+ anchorRowIdRef={anchorRowIdRef}+ selectionStore={selectionStore}+ setSelectAll={setSelectAll}+ />),},};diff --git a/web/src/features/tracing-tables/README.md b/web/src/features/tracing-tables/README.mdnew file mode 100644index 0000000000..c164448aa8--- /dev/null+++ b/web/src/features/tracing-tables/README.md@@ -0,0 +1,38 @@+# Tracing Tables++Per-mount local state for the tracing table surfaces (observations, later+traces), following the local-store pattern from+`.agents/skills/frontend-large-feature-architecture`.++## Owner Map++- `observations/observationsTableStore.ts` — vanilla zustand store owning row+ selection, select-all, selected-page-row derivation, and the+ add-to-dataset dialog flag. Pure logic, covered by+ `observationsTableStore.clienttest.ts`.+- `observations/useObservationsTableView.ts` — creates the store per mount+ (lazy `useState`) and bridges the URL/session-storage `useSelectAll` state+ into it.+- `observations/ObservationsTableStoreProvider.tsx` — feature-scoped context+ for feature components (toolbar, dialogs). Shared components never consume+ this context: `DataTable` and `TableSelectionManager` receive the store+ explicitly via the `selectionStore` prop+ (`web/src/components/table/table-selection-store.ts`), so nested tables+ (e.g. ScoresTable inside the observation peek) are unaffected.++## State Boundaries++- Selection state: this store.+- Server/query state: tRPC in the table use-case component.+- Route/filter state: URL hooks in the table use-case component (frozen —+ see below).++## Status / Remaining Spread++`ObservationsTable` (`web/src/components/table/use-cases/observations.tsx`)+is still a controller component: inline column building, query-state assembly+from multiple hooks, and data preparation in render. Per the 2026-06 decision,+the legacy observations page is frozen (bugfix-only); the filtering/search+vertical is being rebuilt behind a flag rather than migrated further. The+selection store and the context-free `DataTable` selection API from this+folder are reused by the rebuilt surface.diff --git a/web/src/features/tracing-tables/observations/ObservationsTableStoreProvider.tsx b/web/src/features/tracing-tables/observations/ObservationsTableStoreProvider.tsxnew file mode 100644index 0000000000..fd61407eb6--- /dev/null+++ b/web/src/features/tracing-tables/observations/ObservationsTableStoreProvider.tsx@@ -0,0 +1,37 @@+import { createContext, useContext, type ReactNode } from "react";+import { useStore } from "zustand";+import {+ type ObservationsTableStore,+ type ObservationsTableStoreState,+} from "@/src/features/tracing-tables/observations/observationsTableStore";++const ObservationsTableStoreContext =+ createContext<ObservationsTableStore | null>(null);++export function ObservationsTableStoreProvider({+ children,+ store,+}: {+ children: ReactNode;+ store: ObservationsTableStore;+}) {+ return (+ <ObservationsTableStoreContext.Provider value={store}>+ {children}+ </ObservationsTableStoreContext.Provider>+ );+}++export function useObservationsTableStore<TValue>(+ selector: (state: ObservationsTableStoreState) => TValue,+) {+ const store = useContext(ObservationsTableStoreContext);++ if (!store) {+ throw new Error(+ "useObservationsTableStore must be used within ObservationsTableStoreProvider",+ );+ }++ return useStore(store, selector);+}diff --git a/web/src/features/tracing-tables/observations/observationsTableStore.clienttest.ts b/web/src/features/tracing-tables/observations/observationsTableStore.clienttest.tsnew file mode 100644index 0000000000..0ec2aa6e0b--- /dev/null+++ b/web/src/features/tracing-tables/observations/observationsTableStore.clienttest.ts@@ -0,0 +1,193 @@+import { describe, expect, it, vi } from "vitest";+import { createObservationsTableStore } from "@/src/features/tracing-tables/observations/observationsTableStore";++function createTestStore({ initialSelectAll = false } = {}) {+ const onSelectAllChange = vi.fn();+ const store = createObservationsTableStore({+ initialSelectAll,+ onSelectAllChange,+ });+ return { store, onSelectAllChange };+}++describe("createObservationsTableStore", () => {+ it("toggles a row on and recomputes selected page rows", () => {+ const { store } = createTestStore();+ store.getState().actions.syncPageRows({+ pageRowIds: ["a", "b"],+ totalCount: 2,+ });++ store.getState().actions.toggleRow("a", true);++ expect(store.getState().rowSelection).toEqual({ a: true });+ expect(store.getState().selectedPageRowIds).toEqual(["a"]);+ });++ it("toggling a row off drops selectAll and notifies the bridge", () => {+ const { store, onSelectAllChange } = createTestStore({+ initialSelectAll: true,+ });+ store.getState().actions.syncPageRows({+ pageRowIds: ["a", "b"],+ totalCount: 2,+ });+ store.getState().actions.toggleRow("a", true);+ onSelectAllChange.mockClear();++ store.getState().actions.toggleRow("a", false);++ expect(store.getState().rowSelection).toEqual({});+ expect(store.getState().selectAll).toBe(false);+ expect(onSelectAllChange).toHaveBeenCalledWith(false);+ });++ it("toggleRows selects a range without touching other rows", () => {+ const { store } = createTestStore();+ store.getState().actions.syncPageRows({+ pageRowIds: ["a", "b", "c", "d"],+ totalCount: 4,+ });+ store.getState().actions.toggleRow("a", true);++ store.getState().actions.toggleRows(["b", "c"], true);++ expect(store.getState().rowSelection).toEqual({+ a: true,+ b: true,+ c: true,+ });+ expect(store.getState().selectedPageRowIds).toEqual(["a", "b", "c"]);+ });++ it("toggleRows deselect drops selectAll and notifies the bridge", () => {+ const { store, onSelectAllChange } = createTestStore({+ initialSelectAll: true,+ });+ store.getState().actions.syncPageRows({+ pageRowIds: ["a", "b", "c"],+ totalCount: 3,+ });+ store.getState().actions.toggleRows(["a", "b", "c"], true);+ onSelectAllChange.mockClear();++ store.getState().actions.toggleRows(["b", "c"], false);++ expect(store.getState().rowSelection).toEqual({ a: true });+ expect(store.getState().selectAll).toBe(false);+ expect(onSelectAllChange).toHaveBeenCalledWith(false);+ });++ it("togglePageRows selects all page rows and preserves other-page selection", () => {+ const { store } = createTestStore();+ store.getState().actions.syncPageRows({+ pageRowIds: ["a", "b"],+ totalCount: 4,+ });+ store.getState().actions.toggleRow("other-page-row", true);++ store.getState().actions.togglePageRows(["a", "b"], true);++ expect(store.getState().rowSelection).toEqual({+ "other-page-row": true,+ a: true,+ b: true,+ });+ expect(store.getState().selectedPageRowIds).toEqual(["a", "b"]);+ });++ it("togglePageRows off clears the entire selection", () => {+ const { store, onSelectAllChange } = createTestStore();+ store.getState().actions.syncPageRows({+ pageRowIds: ["a"],+ totalCount: 1,+ });+ store.getState().actions.toggleRow("a", true);+ store.getState().actions.toggleRow("other-page-row", true);+ onSelectAllChange.mockClear();++ store.getState().actions.togglePageRows(["a"], false);++ expect(store.getState().rowSelection).toEqual({});+ expect(store.getState().selectedPageRowIds).toEqual([]);+ expect(store.getState().selectAll).toBe(false);+ expect(onSelectAllChange).toHaveBeenCalledWith(false);+ });++ it("setRowSelection resolves functional updaters", () => {+ const { store } = createTestStore();+ store.getState().actions.syncPageRows({+ pageRowIds: ["a", "b"],+ totalCount: 2,+ });+ store.getState().actions.setRowSelection({ a: true });++ store.getState().actions.setRowSelection((previous) => ({+ ...previous,+ b: true,+ }));++ expect(store.getState().rowSelection).toEqual({ a: true, b: true });+ expect(store.getState().selectedPageRowIds).toEqual(["a", "b"]);+ });++ it("setSelectAll notifies the bridge only on actual changes", () => {+ const { store, onSelectAllChange } = createTestStore();++ store.getState().actions.setSelectAll(true);+ store.getState().actions.setSelectAll(true);++ expect(store.getState().selectAll).toBe(true);+ expect(onSelectAllChange).toHaveBeenCalledTimes(1);+ expect(onSelectAllChange).toHaveBeenCalledWith(true);+ });++ it("syncSelectAll updates state without echoing to the bridge", () => {+ const { store, onSelectAllChange } = createTestStore();++ store.getState().actions.syncSelectAll(true);++ expect(store.getState().selectAll).toBe(true);+ expect(onSelectAllChange).not.toHaveBeenCalled();+ });++ it("syncPageRows recomputes selected page rows for the new page", () => {+ const { store } = createTestStore();+ store.getState().actions.syncPageRows({+ pageRowIds: ["a", "b"],+ totalCount: 4,+ });+ store.getState().actions.toggleRow("a", true);++ store.getState().actions.syncPageRows({+ pageRowIds: ["c", "d"],+ totalCount: 4,+ });+ expect(store.getState().selectedPageRowIds).toEqual([]);++ store.getState().actions.syncPageRows({+ pageRowIds: ["a", "b"],+ totalCount: 4,+ });+ expect(store.getState().selectedPageRowIds).toEqual(["a"]);+ });++ it("clearSelection resets selection and selectAll", () => {+ const { store, onSelectAllChange } = createTestStore({+ initialSelectAll: true,+ });+ store.getState().actions.syncPageRows({+ pageRowIds: ["a"],+ totalCount: 1,+ });+ store.getState().actions.toggleRow("a", true);+ onSelectAllChange.mockClear();++ store.getState().actions.clearSelection();++ expect(store.getState().rowSelection).toEqual({});+ expect(store.getState().selectedPageRowIds).toEqual([]);+ expect(store.getState().selectAll).toBe(false);+ expect(onSelectAllChange).toHaveBeenCalledWith(false);+ });+});diff --git a/web/src/features/tracing-tables/observations/observationsTableStore.ts b/web/src/features/tracing-tables/observations/observationsTableStore.tsnew file mode 100644index 0000000000..ced99d491a--- /dev/null+++ b/web/src/features/tracing-tables/observations/observationsTableStore.ts@@ -0,0 +1,135 @@+import { createStore, type StoreApi } from "zustand/vanilla";+import { type RowSelectionState, type Updater } from "@tanstack/react-table";+import { type TableSelectionStoreState } from "@/src/components/table/table-selection-store";++type RowSelectionUpdater = Updater<RowSelectionState>;+type BooleanUpdater = Updater<boolean>;++export interface ObservationsTableStoreState extends TableSelectionStoreState {+ showAddToDatasetDialog: boolean;+ actions: TableSelectionStoreState["actions"] & {+ syncPageRows: (payload: {+ pageRowIds: string[];+ totalCount: number | null;+ }) => void;+ syncSelectAll: (selectAll: boolean) => void;+ setShowAddToDatasetDialog: (isOpen: boolean) => void;+ };+}++export type ObservationsTableStore = StoreApi<ObservationsTableStoreState>;++function resolveUpdater<TValue>(+ updater: Updater<TValue>,+ previousValue: TValue,+): TValue {+ return typeof updater === "function"+ ? (updater as (old: TValue) => TValue)(previousValue)+ : updater;+}++function getSelectedPageRowIds(+ rowSelection: RowSelectionState,+ pageRowIds: string[],+) {+ return pageRowIds.filter((rowId) => Boolean(rowSelection[rowId]));+}++export function createObservationsTableStore({+ initialSelectAll,+ onSelectAllChange,+}: {+ initialSelectAll: boolean;+ onSelectAllChange: (selectAll: boolean) => void;+}): ObservationsTableStore {+ return createStore<ObservationsTableStoreState>((set, get) => {+ const updateSelection = (+ rowSelection: RowSelectionState,+ selectAll = get().selectAll,+ ) => {+ const { pageRowIds } = get();++ set({+ rowSelection,+ selectAll,+ selectedPageRowIds: getSelectedPageRowIds(rowSelection, pageRowIds),+ });+ };++ const setSelectAll = (updater: BooleanUpdater) => {+ const nextSelectAll = resolveUpdater(updater, get().selectAll);+ if (nextSelectAll === get().selectAll) return;++ set({ selectAll: nextSelectAll });+ onSelectAllChange(nextSelectAll);+ };++ const clearSelection = () => {+ updateSelection({}, false);+ onSelectAllChange(false);+ };++ const toggleRows = (rowIds: string[], nextSelected: boolean) => {+ const nextRowSelection = { ...get().rowSelection };+ for (const rowId of rowIds) {+ if (nextSelected) {+ nextRowSelection[rowId] = true;+ } else {+ delete nextRowSelection[rowId];+ }+ }++ updateSelection(nextRowSelection, nextSelected ? get().selectAll : false);+ if (!nextSelected) onSelectAllChange(false);+ };++ return {+ rowSelection: {},+ selectAll: initialSelectAll,+ selectedPageRowIds: [],+ pageRowIds: [],+ totalCount: null,+ showAddToDatasetDialog: false,+ actions: {+ setRowSelection: (updater: RowSelectionUpdater) => {+ updateSelection(resolveUpdater(updater, get().rowSelection));+ },+ setSelectAll,+ toggleRow: (rowId: string, nextSelected: boolean) => {+ toggleRows([rowId], nextSelected);+ },+ toggleRows,+ togglePageRows: (rowIds: string[], nextSelected: boolean) => {+ if (!nextSelected) {+ clearSelection();+ return;+ }++ const nextRowSelection = { ...get().rowSelection };+ for (const rowId of rowIds) {+ nextRowSelection[rowId] = true;+ }++ updateSelection(nextRowSelection);+ },+ clearSelection,+ syncPageRows: ({ pageRowIds, totalCount }) => {+ const { rowSelection } = get();+ set({+ pageRowIds,+ totalCount,+ selectedPageRowIds: getSelectedPageRowIds(rowSelection, pageRowIds),+ });+ },+ syncSelectAll: (selectAll: boolean) => {+ if (selectAll !== get().selectAll) {+ set({ selectAll });+ }+ },+ setShowAddToDatasetDialog: (isOpen: boolean) => {+ set({ showAddToDatasetDialog: isOpen });+ },+ },+ };+ });+}diff --git a/web/src/features/tracing-tables/observations/useObservationsTableView.ts b/web/src/features/tracing-tables/observations/useObservationsTableView.tsnew file mode 100644index 0000000000..520bccf5d7--- /dev/null+++ b/web/src/features/tracing-tables/observations/useObservationsTableView.ts@@ -0,0 +1,28 @@+import { useLayoutEffect, useState } from "react";+import { useSelectAll } from "@/src/features/table/hooks/useSelectAll";+import {+ createObservationsTableStore,+ type ObservationsTableStore,+} from "@/src/features/tracing-tables/observations/observationsTableStore";++export function useObservationsTableView({+ projectId,+}: {+ projectId: string;+}): { store: ObservationsTableStore } {+ const { selectAll, setSelectAll } = useSelectAll(projectId, "observations");+ const [store] = useState(() =>+ createObservationsTableStore({+ initialSelectAll: selectAll,+ onSelectAllChange: setSelectAll,+ }),+ );++ // Layout effect so a selectAll reset (e.g. route change) reaches+ // store-subscribed rows before paint — no one-frame stale highlight.+ useLayoutEffect(() => {+ store.getState().actions.syncSelectAll(selectAll);+ }, [selectAll, store]);++ return { store };+}