πͺ’ 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(filters): unify sidebar search and saved views (#17316)
Nikita Kabardindc8d67087c9d
diff --git a/packages/shared/src/domain/table-view-presets.ts b/packages/shared/src/domain/table-view-presets.tsindex 90a3e4be94..6b7dd76562 100644--- a/packages/shared/src/domain/table-view-presets.ts+++ b/packages/shared/src/domain/table-view-presets.ts@@ -14,6 +14,9 @@ export enum TableViewPresetTableName {ExperimentItems = "experiment-items",Evaluators = "evaluators-v2",EvaluationRules = "evaluation-rules-v2",+ Users = "users",+ Prompts = "prompts",+ Monitors = "monitors",}/**diff --git a/packages/shared/src/server/services/TableViewService/TableViewService.test.ts b/packages/shared/src/server/services/TableViewService/TableViewService.test.tsindex 002b75b3f8..013c04b4aa 100644--- a/packages/shared/src/server/services/TableViewService/TableViewService.test.ts+++ b/packages/shared/src/server/services/TableViewService/TableViewService.test.ts@@ -4,16 +4,19 @@ import { InvalidRequestError } from "../../../errors";import { TableViewService } from "./TableViewService";describe("TableViewService.generatePermalink", () => {- it("builds a list-page permalink for tables in the URL map", async () => {+ it.each([+ [TableViewPresetTableName.Sessions, "sessions"],+ [TableViewPresetTableName.Monitors, "alerts"],+ ])("builds a list-page permalink for %s", async (tableName, route) => {await expect(TableViewService.generatePermalink("https://us.cloud.langfuse.com","view_1",- TableViewPresetTableName.Sessions,+ tableName,"proj_1",),).resolves.toBe(- "https://us.cloud.langfuse.com/project/proj_1/sessions?viewId=view_1",+ `https://us.cloud.langfuse.com/project/proj_1/${route}?viewId=view_1`,);});diff --git a/packages/shared/src/server/services/TableViewService/TableViewService.ts b/packages/shared/src/server/services/TableViewService/TableViewService.tsindex 04abb6848c..ed6344f473 100644--- a/packages/shared/src/server/services/TableViewService/TableViewService.ts+++ b/packages/shared/src/server/services/TableViewService/TableViewService.ts@@ -30,6 +30,9 @@ const TABLE_NAME_TO_URL_MAP: Partial<Record<TableViewPresetTableName, string>> =[TableViewPresetTableName.ObservationsEvents]: "traces",[TableViewPresetTableName.Scores]: "scores",[TableViewPresetTableName.Sessions]: "sessions",+ [TableViewPresetTableName.Users]: "users",+ [TableViewPresetTableName.Prompts]: "prompts",+ [TableViewPresetTableName.Monitors]: "alerts",[TableViewPresetTableName.Datasets]: "datasets",[TableViewPresetTableName.Experiments]: "experiments",[TableViewPresetTableName.ExperimentItems]: "experiments/results",diff --git a/web/src/__tests__/posthog-session-replay-mask.clienttest.ts b/web/src/__tests__/posthog-session-replay-mask.clienttest.tsxsimilarity index 51%rename from web/src/__tests__/posthog-session-replay-mask.clienttest.tsrename to web/src/__tests__/posthog-session-replay-mask.clienttest.tsxindex 74e0aa87f9..33356a095a 100644--- a/web/src/__tests__/posthog-session-replay-mask.clienttest.ts+++ b/web/src/__tests__/posthog-session-replay-mask.clienttest.tsx@@ -1,6 +1,13 @@// @vitest-environment jsdomimport type { PostHogConfig } from "posthog-js";+import { createElement } from "react";+import { render, screen } from "@testing-library/react";+import { AutocompleteListbox } from "@/src/features/search-bar/components/AutocompleteListbox";+import { ComposerWithPreview } from "@/src/features/search-bar/components/ComposerWithPreview";+import { SearchComposer } from "@/src/features/search-bar/components/SearchComposer";+import { SearchBarStoreProvider } from "@/src/features/search-bar/store/SearchBarStoreProvider";+import { createSearchBarStore } from "@/src/features/search-bar/store/searchBarStore";const { initMock } = vi.hoisted(() => ({initMock: vi.fn(),@@ -23,6 +30,59 @@ describe("PostHog session replay privacy", () => {initMock.mockReset();});+ it("blocks observed search values outside the masked input", () => {+ render(+ createElement(AutocompleteListbox, {+ highlightedId: null,+ plan: {+ stage: "value",+ from: 0,+ to: 0,+ loading: false,+ sections: [+ {+ title: "Observed values",+ options: [+ {+ id: "private-option",+ kind: "value",+ label: "private-search-value",+ value: "private-search-value",+ },+ ],+ },+ ],+ },+ }),+ );++ expect(+ screen.getByText("private-search-value").closest(".ph-no-capture"),+ ).not.toBeNull();+ });++ it("blocks draft and preview attributes outside the contenteditable", () => {+ const store = createSearchBarStore();+ store.getState().actions.setDraft("private-draft");+ store.getState().actions.setPreview("private-preview");+ const { rerender } = render(+ <SearchBarStoreProvider store={store} commit={vi.fn()}>+ <SearchComposer observed={undefined} />+ </SearchBarStoreProvider>,+ );+ expect(+ screen.getByTestId("search-bar-surface").closest(".ph-no-capture"),+ ).not.toBeNull();+ rerender(+ <SearchBarStoreProvider store={store} commit={vi.fn()}>+ <ComposerWithPreview observed={undefined} />+ </SearchBarStoreProvider>,+ );+ expect(+ screen.getByTestId("search-bar-preview").closest(".ph-no-capture"),+ ).not.toBeNull();+ });+it("records regular UI text while masking input values", async () => {vi.stubEnv("NEXT_PUBLIC_POSTHOG_KEY", "phc_test");vi.stubEnv("NEXT_PUBLIC_POSTHOG_HOST", "https://eu.i.posthog.com");diff --git a/web/src/components/table/SearchScopeSelect.tsx b/web/src/components/table/SearchScopeSelect.tsxnew file mode 100644index 0000000000..a58808baaa--- /dev/null+++ b/web/src/components/table/SearchScopeSelect.tsx@@ -0,0 +1,83 @@+import { ChevronDown } from "lucide-react";+import type { TracingSearchType } from "@langfuse/shared";+import { Button } from "@/src/components/ui/button";+import {+ DropdownMenuController,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuSub,+ DropdownMenuSubTrigger,+ DropdownMenuSubContent,+} from "@/src/components/ui/dropdown-menu";+import {+ getSearchButtonLabel,+ getSearchMode,+ searchModeToType,+} from "@/src/components/table/utils/searchUtils";++export function SearchScopeSelect({+ searchType,+ setSearchType,+ metadataLabel,+ fullTextLabel,+ availableSearchTypes,+}: {+ searchType: TracingSearchType[];+ setSearchType: (types: TracingSearchType[]) => void;+ metadataLabel: string;+ fullTextLabel: string;+ availableSearchTypes: { content: boolean; input: boolean; output: boolean };+}) {+ const mode = getSearchMode(searchType, true);+ return (+ <DropdownMenuController+ align="end"+ renderMenu={() => (+ <DropdownMenuRadioGroup+ value={mode}+ onValueChange={(value) => setSearchType(searchModeToType(value))}+ >+ <DropdownMenuRadioItem value="metadata">+ {metadataLabel}+ </DropdownMenuRadioItem>+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>{fullTextLabel}</DropdownMenuSubTrigger>+ <DropdownMenuSubContent>+ <DropdownMenuRadioGroup+ value={mode}+ onValueChange={(value) =>+ setSearchType(searchModeToType(value))+ }+ >+ {availableSearchTypes.content && (+ <DropdownMenuRadioItem value="metadata_fulltext">+ Input/Output+ </DropdownMenuRadioItem>+ )}+ {availableSearchTypes.input && (+ <DropdownMenuRadioItem value="metadata_fulltext_input">+ Input+ </DropdownMenuRadioItem>+ )}+ {availableSearchTypes.output && (+ <DropdownMenuRadioItem value="metadata_fulltext_output">+ Output+ </DropdownMenuRadioItem>+ )}+ </DropdownMenuRadioGroup>+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ </DropdownMenuRadioGroup>+ )}+ >+ {({ Trigger }) => (+ <Trigger asChild>+ <Button variant="outline" size="sm" aria-label="Search scope">+ {getSearchButtonLabel(searchType, metadataLabel)}+ <ChevronDown className="h-4 w-4" />+ </Button>+ </Trigger>+ )}+ </DropdownMenuController>+ );+}diff --git a/web/src/components/table/data-table-controls.clienttest.tsx b/web/src/components/table/data-table-controls.clienttest.tsxindex c702653a77..293b40da04 100644--- a/web/src/components/table/data-table-controls.clienttest.tsx+++ b/web/src/components/table/data-table-controls.clienttest.tsx@@ -709,6 +709,22 @@ describe("DataTableControls facet ordering", () => {expect(labelOrder("Alpha", "Beta")).toBe(true);});+ it("clears drafts and view selection even when no filters are applied", () => {+ const clearAll = vi.fn();+ render(+ <TooltipProvider>+ <DataTableControls queryFilter={{ ...queryFilter([]), clearAll }} />+ </TooltipProvider>,+ );+ fireEvent.keyDown(screen.getByRole("button", { name: "Filter options" }), {+ key: "Enter",+ });+ const clear = screen.getByRole("menuitem", { name: "Clear all filters" });+ expect(clear).not.toHaveAttribute("aria-disabled", "true");+ fireEvent.click(clear);+ expect(clearAll).toHaveBeenCalledOnce();+ });+it("restores catalog order on Clear all, even with an in-list interaction outstanding", () => {const { rerender } = render(<TooltipProvider>diff --git a/web/src/components/table/data-table-controls.tsx b/web/src/components/table/data-table-controls.tsxindex c9036c21d8..b3b8125860 100644--- a/web/src/components/table/data-table-controls.tsx+++ b/web/src/components/table/data-table-controls.tsx@@ -1107,11 +1107,8 @@ export function DataTableControls({</Tooltip><DropdownMenuContent align="end" className="w-48"><DropdownMenuItem- // Enabled also when only value-less added facets exist β- // Clear all is the affordance that demotes them.- disabled={- !queryFilter.isFiltered && revealedColumns.length === 0- }+ // Clear also resets unfinished drafts and selected views,+ // even when no filter values have been applied.onClick={() => {// Explicit adds are part of "everything" too: without// this, a value-less added facet stays pinned afterdiff --git a/web/src/components/table/table-view-presets/README.md b/web/src/components/table/table-view-presets/README.mdindex ce0c1eb95e..900b74c39c 100644--- a/web/src/components/table/table-view-presets/README.md+++ b/web/src/components/table/table-view-presets/README.md@@ -23,6 +23,9 @@ original view available for updating without marking it active, including thecolumn-provenance guard for shared links. It also preserves the edited workingview across reloads instead of reapplying a default.+Saved views persist filters and `searchQuery`. Search scope stays in the host's+URL or local table state; applying a view leaves that scope unchanged.+## Robustness to Table ChangesThe table view presets system is designed to gracefully handle changes to table structure: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 1e86701884..ffb955d5df 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@@ -953,17 +953,19 @@ function TableViewPresetsDrawerContentBody({<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>+ <DrawerClose asChild>+ <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>+ </DrawerClose></div></div></DrawerContent>diff --git a/web/src/components/table/table-view-presets/hooks/useTableViewFilterChange.ts b/web/src/components/table/table-view-presets/hooks/useTableViewFilterChange.tsnew file mode 100644index 0000000000..a47e056247--- /dev/null+++ b/web/src/components/table/table-view-presets/hooks/useTableViewFilterChange.ts@@ -0,0 +1,23 @@+import { useCallback, useRef } from "react";+import type { UseSidebarFilterStateOptions } from "@/src/features/filters/hooks/useSidebarFilterState";+import type { useTableViewManager } from "./useTableViewManager";++export function useTableViewFilterChange() {+ const viewControllersRef = useRef<Pick<+ ReturnType<typeof useTableViewManager>,+ "handleUserStateChange"+ > | null>(null);++ const onExplicitFilterStateChange = useCallback<+ NonNullable<UseSidebarFilterStateOptions["onExplicitFilterStateChange"]>+ >((change) => {+ if (change.origin !== "user") return;+ viewControllersRef.current?.handleUserStateChange(+ change.previousFilters,+ change.nextFilters,+ { force: change.action === "clear" },+ );+ }, []);++ return { viewControllersRef, onExplicitFilterStateChange };+}diff --git a/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts b/web/src/components/table/table-view-presets/hooks/useTableViewManager.tsindex 31a7d52b08..9c45fefc8b 100644--- a/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts+++ b/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts@@ -69,6 +69,8 @@ interface UseTableStateProps {currentExpandedFilters?: string[];disabled?: boolean;allowBackendSystemPresets?: boolean;+ /** Called after an application even when the validated state is unchanged. */+ onViewApplied?: (state: TableViewPresetState) => void;}const isViewApplicableToTable = (@@ -110,6 +112,7 @@ export function useTableViewManager({currentExpandedFilters,disabled = false,allowBackendSystemPresets = false,+ onViewApplied,}: UseTableStateProps) {const router = useRouter();const isRouterReady = router.isReady;@@ -174,9 +177,14 @@ export function useTableViewManager({);const handleUserStateChange = useCallback(- (previousValue: unknown, nextValue: unknown) => {+ (+ previousValue: unknown,+ nextValue: unknown,+ options?: { force?: boolean },+ ) => {const viewId = selectedViewIdRef.current;- if (!viewId || isEqual(previousValue, nextValue)) return;+ if (!viewId || (!options?.force && isEqual(previousValue, nextValue)))+ return;const columnsApplied = storedViewIdRef.current === viewId;handleSetViewId(null, { updateType: "replaceIn" });setViewUpdateTarget({ viewId, columnsApplied });@@ -200,12 +208,14 @@ export function useTableViewManager({const setOrderByRef = useRef(setOrderBy);const setSearchQueryRef = useRef(setSearchQuery);const setExpandedFiltersRef = useRef(setExpandedFilters);+ const onViewAppliedRef = useRef(onViewApplied);// Update refs immediately on every rendersetFiltersRef.current = setFilters;setOrderByRef.current = setOrderBy;setSearchQueryRef.current = setSearchQuery;setExpandedFiltersRef.current = setExpandedFilters;+ onViewAppliedRef.current = onViewApplied;// Extract primitive for effect dep (rerender-dependencies: avoid object deps)const defaultViewId = resolvedDefault?.viewId;@@ -407,6 +417,12 @@ export function useTableViewManager({// Applying a view discards drafts; leaving a view while editing preserves them.setFilterEditorResetKey((key) => key + 1);+ onViewAppliedRef.current?.({+ ...viewData,+ filters: validFilters,+ orderBy: validOrderBy,+ searchQuery: viewData.searchQuery || null,+ });// Unlock as soon as the view is applied. Earlier versions kept the table// locked until a useEffect observer saw the filter change propagate todiff --git a/web/src/components/table/use-cases/observations.tsx b/web/src/components/table/use-cases/observations.tsxindex 09e266d18f..c64fa52d9a 100644--- a/web/src/components/table/use-cases/observations.tsx+++ b/web/src/components/table/use-cases/observations.tsx@@ -90,6 +90,10 @@ import {useDetailPageLists,} from "@/src/features/navigate-detail-pages/context";import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";+import { useTableViewFilterChange } from "@/src/components/table/table-view-presets/hooks/useTableViewFilterChange";+import { SearchScopeSelect } from "@/src/components/table/SearchScopeSelect";+import { TableSearchBar, toObservedOptions } from "@/src/features/search-bar";+import { observationsFieldRegistry } from "@/src/features/filters/config/tracingSearchRegistry";import { useRouter } from "next/router";import { useFullTextSearch } from "@/src/components/table/use-cases/useFullTextSearch";import { TableSelectionManager } from "@/src/features/table/components/TableSelectionManager";@@ -253,8 +257,6 @@ export default function ObservationsTable({utils.projects.environmentFilterOptions.invalidate(),]);}, [utils]);- const { searchQuery, searchType, setSearchQuery, setSearchType } =- useFullTextSearch();const legacyTracingSearchConfig = api.public.tracingSearchConfig.useQuery({ projectId },{@@ -266,6 +268,10 @@ export default function ObservationsTable({);const legacyTracingIoSearchEnabled =legacyTracingSearchConfig.data?.legacyTracingIoSearchEnabled ?? true;+ const { searchQuery, searchType, setSearchQuery, setSearchType } =+ useFullTextSearch({+ tableAllowsFullTextSearch: legacyTracingIoSearchEnabled,+ });const [paginationState, setPaginationState] = usePaginationState(0, 50, {page: "pageIndex",@@ -502,10 +508,15 @@ export default function ObservationsTable({const isSidebarFilterLoading =filterOptions.isPending || environmentFilterOptions.isPending;+ const { viewControllersRef, onExplicitFilterStateChange } =+ useTableViewFilterChange();+const queryFilterOptions: UseSidebarFilterStateOptions = useMemo(() => {const baseOptions = {loading: isSidebarFilterLoading,implicitDefaultConfig: DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG,+ onExplicitFilterStateChange,+ isV4: false,};if (peekContext) {@@ -534,6 +545,7 @@ export default function ObservationsTable({}, [hideControls,isSidebarFilterLoading,+ onExplicitFilterStateChange,peekContext,projectId,promptName,@@ -553,13 +565,19 @@ export default function ObservationsTable({facetOptions,queryFilterOptions,);+ const searchRegistry = observationsFieldRegistry(observationsFilterConfig);+ const observedOptions = toObservedOptions(+ facetOptions,+ isSidebarFilterLoading,+ );// Create ref-based wrapper to avoid stale closure when queryFilter updatesconst queryFilterRef = useRef(queryFilter);queryFilterRef.current = queryFilter;- const setFiltersWrapper = useCallback(- (filters: FilterState) => queryFilterRef.current?.setFilterState(filters),+ const setSavedViewFilters = useCallback(+ (filters: FilterState) =>+ queryFilterRef.current?.setFilterState(filters, { origin: "saved_view" }),[],);@@ -1182,7 +1200,7 @@ export default function ObservationsTable({projectId,stateUpdaters: {setOrderBy: setOrderByState,- setFilters: setFiltersWrapper,+ setFilters: setSavedViewFilters,setExpandedFilters: queryFilter.onExpandedChange,setColumnOrder: setColumnOrder,setColumnVisibility: setColumnVisibilityState,@@ -1199,6 +1217,38 @@ export default function ObservationsTable({currentExpandedFilters: queryFilter.expanded,disabled: hideControls,});+ viewControllersRef.current = viewControllers;++ const handleSearchQueryChange = (nextQuery: string | null) => {+ viewControllers.handleUserStateChange(searchQuery ?? "", nextQuery ?? "");+ setSearchQuery(nextQuery);+ };+ const handleSearchTypeChange = (nextType: TracingSearchType[]) => {+ if (searchQuery?.trim()) {+ viewControllers.handleUserStateChange(+ [...searchType].sort(),+ [...nextType].sort(),+ );+ }+ setSearchType(nextType);+ };+ const handleOrderByChange: typeof setOrderByState = (nextOrderBy) => {+ viewControllers.handleUserStateChange(orderByState, nextOrderBy);+ setOrderByState(nextOrderBy);+ };+ const handleColumnOrderChange: typeof setColumnOrder = (updater) => {+ const next = typeof updater === "function" ? updater(columnOrder) : updater;+ viewControllers.handleUserStateChange(columnOrder, next);+ setColumnOrder(next);+ };+ const handleColumnVisibilityChange: typeof setColumnVisibilityState = (+ updater,+ ) => {+ const next =+ typeof updater === "function" ? updater(columnVisibility) : updater;+ viewControllers.handleUserStateChange(columnVisibility, next);+ setColumnVisibilityState(next);+ };const peekConfig: DataTablePeekViewProps | undefined = useMemo(() => {if (hideControls) return undefined;@@ -1284,54 +1334,82 @@ export default function ObservationsTable({<div className="flex h-full w-full flex-col">{/* Toolbar spanning full width */}{!hideControls && (- <ObservationsDataTableToolbar- columns={columns}- filterState={queryFilter.explicitFilterState}- searchConfig={{- metadataSearchFields: ["ID", "Name", "Trace Name", "Model"],- updateQuery: setSearchQuery,- currentQuery: searchQuery ?? undefined,- tableAllowsFullTextSearch: legacyTracingIoSearchEnabled,- searchType,- setSearchType,- }}- viewConfig={{- tableName: TableViewPresetTableName.Observations,- projectId,- controllers: viewControllers,- }}- columnsWithCustomSelect={[- "model",- "name",- "traceName",- "promptName",- ]}- columnVisibility={columnVisibility}- setColumnVisibility={setColumnVisibilityState}- columnOrder={columnOrder}- setColumnOrder={setColumnOrder}- orderByState={orderByState}- rowHeight={rowHeight}- setRowHeight={setRowHeight}- timeRange={showControlsInPageHeader ? undefined : timeRange}- setTimeRange={showControlsInPageHeader ? undefined : setTimeRange}- refreshConfig={showControlsInPageHeader ? undefined : refreshConfig}- projectId={projectId}- backendFilterState={backendFilterState}- searchQuery={searchQuery}- searchType={searchType}- tableActions={tableActions}- totalCount={totalCount}- paginationState={paginationState}- />+ <div className="shrink-0 pb-1.5">+ <TableSearchBar+ key={`${viewControllers.filterEditorResetKey}-${queryFilter.draftResetKey}`}+ projectId={projectId}+ tableName={observationsFilterConfig.tableName}+ registry={searchRegistry}+ filterState={queryFilter.searchBarFilterState}+ setFilterState={queryFilter.setFilterState}+ observed={observedOptions}+ isV4={false}+ search={{+ query: searchQuery,+ type: searchType,+ setQuery: handleSearchQueryChange,+ }}+ searchScope={+ legacyTracingIoSearchEnabled ? (+ <SearchScopeSelect+ searchType={searchType}+ setSearchType={handleSearchTypeChange}+ metadataLabel="IDs / Names"+ fullTextLabel="Full Text"+ availableSearchTypes={{+ content: true,+ input: true,+ output: true,+ }}+ />+ ) : undefined+ }+ />+ <ObservationsDataTableToolbar+ rowClassName="my-1"+ isV4={false}+ columns={columns}+ filterState={queryFilter.explicitFilterState}+ viewConfig={{+ tableName: TableViewPresetTableName.Observations,+ projectId,+ controllers: viewControllers,+ }}+ currentSearchQuery={searchQuery ?? ""}+ columnsWithCustomSelect={[+ "model",+ "name",+ "traceName",+ "promptName",+ ]}+ columnVisibility={columnVisibility}+ setColumnVisibility={handleColumnVisibilityChange}+ columnOrder={columnOrder}+ setColumnOrder={handleColumnOrderChange}+ orderByState={orderByState}+ rowHeight={rowHeight}+ setRowHeight={setRowHeight}+ timeRange={showControlsInPageHeader ? undefined : timeRange}+ setTimeRange={showControlsInPageHeader ? undefined : setTimeRange}+ refreshConfig={+ showControlsInPageHeader ? undefined : refreshConfig+ }+ projectId={projectId}+ backendFilterState={backendFilterState}+ searchQuery={searchQuery}+ searchType={searchType}+ tableActions={tableActions}+ totalCount={totalCount}+ paginationState={paginationState}+ />+ </div>)}{/* Content area with sidebar and table */}<ResizableFilterLayout>{!hideControls && (<DataTableControls- // Remount the sidebar when the saved view changes so the new view's filters replace any stale draft UI state.- key={viewControllers.selectedViewId ?? "no-view"}+ key={`${viewControllers.filterEditorResetKey}-${queryFilter.draftResetKey}`}queryFilter={queryFilter}/>)}@@ -1366,12 +1444,12 @@ export default function ObservationsTable({state: paginationState,}}- setOrderBy={setOrderByState}+ setOrderBy={handleOrderByChange}orderBy={orderByState}columnOrder={columnOrder}- onColumnOrderChange={setColumnOrder}+ onColumnOrderChange={handleColumnOrderChange}columnVisibility={columnVisibility}- onColumnVisibilityChange={setColumnVisibilityState}+ onColumnVisibilityChange={handleColumnVisibilityChange}rowHeight={rowHeight}onRowClick={(row, event) => {// Handle Command/Ctrl+click to open observation in new tabdiff --git a/web/src/components/table/use-cases/scores.tsx b/web/src/components/table/use-cases/scores.tsxindex c3a82d92c2..116fa77e94 100644--- a/web/src/components/table/use-cases/scores.tsx+++ b/web/src/components/table/use-cases/scores.tsx@@ -66,6 +66,7 @@ import { useHasEntitlement } from "@/src/features/entitlements/hooks";import { useSelectAll } from "@/src/features/table/hooks/useSelectAll";import { TableSelectionManager } from "@/src/features/table/components/TableSelectionManager";import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";+import { useTableViewFilterChange } from "@/src/components/table/table-view-presets/hooks/useTableViewFilterChange";import { createIdTableColumn } from "@/src/components/design-system/table/columns/createIdTableColumn";import { usePaginationState } from "@/src/hooks/usePaginationState";import { useReadPath } from "@/src/features/events/hooks/useReadPath";@@ -273,12 +274,6 @@ export default function ScoresTable({);const chartActive =chartEnabled && chartTimeRange !== undefined && chartViewMode === "chart";- const searchBarEnabled =- isV4 &&- showControlsInPageHeader &&- chartEnabled &&- !chartActive &&- !peekContext;// Drill-in from the outlier strip writes the clicked bucket as an absolute// range. URL-only and deliberately NOT persisted as the project's default@@ -438,8 +433,13 @@ export default function ScoresTable({const isSidebarFilterLoading =filterOptions.isPending || environmentFilterOptions.isPending;+ const { viewControllersRef, onExplicitFilterStateChange } =+ useTableViewFilterChange();+const queryFilterOptions: UseSidebarFilterStateOptions = useMemo(() => {const baseOptions = {+ onExplicitFilterStateChange,+ isV4,loading: isSidebarFilterLoading,implicitDefaultConfig: showAllEnvironments? undefined@@ -468,6 +468,8 @@ export default function ScoresTable({};}, [disableUrlPersistence,+ onExplicitFilterStateChange,+ isV4,isSidebarFilterLoading,peekContext,projectId,@@ -1051,7 +1053,10 @@ export default function ScoresTable({projectId,stateUpdaters: {setOrderBy: setOrderByState,- setFilters: setFiltersWrapper,+ setFilters: (filters) =>+ queryFilterRef.current.setFilterState(filters, {+ origin: "saved_view",+ }),setExpandedFilters: queryFilter.onExpandedChange,setColumnOrder: setColumnOrder,setColumnVisibility: setColumnVisibility,@@ -1066,6 +1071,23 @@ export default function ScoresTable({currentFilterState: queryFilter.explicitFilterState,currentExpandedFilters: queryFilter.expanded,});+ viewControllersRef.current = viewControllers;++ const handleOrderByChange: typeof setOrderByState = (next) => {+ viewControllers.handleUserStateChange(orderByState, next);+ setOrderByState(next);+ };+ const handleColumnOrderChange: typeof setColumnOrder = (update) => {+ const next = typeof update === "function" ? update(columnOrder) : update;+ viewControllers.handleUserStateChange(columnOrder, next);+ setColumnOrder(next);+ };+ const handleColumnVisibilityChange: typeof setColumnVisibility = (update) => {+ const next =+ typeof update === "function" ? update(columnVisibility) : update;+ viewControllers.handleUserStateChange(columnVisibility, next);+ setColumnVisibility(next);+ };const visibleSelectedScoreIds = useMemo(() =>@@ -1091,23 +1113,24 @@ export default function ScoresTable({setTimeRange={setTimeRange}/>)}- {searchBarEnabled && (- <ScoresSearchBar- projectId={projectId}- filterState={queryFilter.searchBarFilterState}- setFilterState={setFiltersWrapper}- filterOptions={newFilterOptions}- isLoading={isSidebarFilterLoading}- />- )}+ <ScoresSearchBar+ key={`${viewControllers.filterEditorResetKey}-${queryFilter.draftResetKey}`}+ isV4={isV4}+ projectId={projectId}+ filterConfig={scoresFilterConfig}+ filterState={queryFilter.searchBarFilterState}+ setFilterState={setFiltersWrapper}+ filterOptions={newFilterOptions}+ isLoading={isSidebarFilterLoading}+ />{/* Toolbar spanning full width */}<DataTableToolbarcolumns={columns}filterState={queryFilter.explicitFilterState}columnVisibility={columnVisibility}- setColumnVisibility={setColumnVisibility}+ setColumnVisibility={handleColumnVisibilityChange}columnOrder={columnOrder}- setColumnOrder={setColumnOrder}+ setColumnOrder={handleColumnOrderChange}viewConfig={{tableName: TableViewPresetTableName.Scores,projectId,@@ -1163,7 +1186,7 @@ export default function ScoresTable({<ResizableFilterLayout><DataTableControls// Remount the sidebar when the saved view changes so the new view's filters replace any stale draft UI state.- key={viewControllers.selectedViewId ?? "no-view"}+ key={viewControllers.filterEditorResetKey}queryFilter={queryFilter}/>@@ -1231,15 +1254,15 @@ export default function ScoresTable({onChange: setPaginationState,state: paginationState,}}- setOrderBy={setOrderByState}+ setOrderBy={handleOrderByChange}orderBy={orderByState}rowSelection={selectedRows}highlightAllRows={selectAll}setRowSelection={setSelectedRows}columnVisibility={columnVisibility}- onColumnVisibilityChange={setColumnVisibility}+ onColumnVisibilityChange={handleColumnVisibilityChange}columnOrder={columnOrder}- onColumnOrderChange={setColumnOrder}+ onColumnOrderChange={handleColumnOrderChange}rowHeight={rowHeight}/>)}diff --git a/web/src/components/table/use-cases/sessions.tsx b/web/src/components/table/use-cases/sessions.tsxindex 18d82301f4..c264b46e78 100644--- a/web/src/components/table/use-cases/sessions.tsx+++ b/web/src/components/table/use-cases/sessions.tsx@@ -55,6 +55,7 @@ import { TableHeaderControls } from "@/src/components/table/table-header-controlimport { cn } from "@/src/utils/tailwind";import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";+import { useTableViewFilterChange } from "@/src/components/table/table-view-presets/hooks/useTableViewFilterChange";import { useSelectAll } from "@/src/features/table/hooks/useSelectAll";import { type TableAction } from "@/src/features/table/types";import { TableActionMenu } from "@/src/features/table/components/TableActionMenu";@@ -64,11 +65,9 @@ import { TableSelectionManager } from "@/src/features/table/components/TableSeleimport { useScoreColumns } from "@/src/features/scores/hooks/useScoreColumns";import { scoreFilters } from "@/src/features/scores/lib/scoreColumns";import { BatchExportTableButton } from "@/src/components/BatchExportTableButton";-import { SESSIONS_FIELD_REGISTRY } from "@/src/features/filters/config/sessionsSearchRegistry";+import { sessionsFieldRegistry } from "@/src/features/filters/config/sessionsSearchRegistry";import { toObservedOptions } from "@/src/features/search-bar/lib/observed-options";-import { DEFAULT_SEARCH_TYPE } from "@/src/features/search-bar/lib/commit";-import { useEventsSearchBar } from "@/src/features/search-bar/hooks/useEventsSearchBar";-import { EventsSearchBarRow } from "@/src/features/search-bar/components/EventsSearchBarRow";+import { TableSearchBar } from "@/src/features/search-bar/components/TableSearchBar";export type SessionTableRow = {id: string;@@ -267,9 +266,13 @@ export default function SessionsTable({const isSidebarFilterLoading =filterOptions.isPending || environmentFilterOptions.isPending;+ const { viewControllersRef, onExplicitFilterStateChange } =+ useTableViewFilterChange();+const queryFilterOptions: UseSidebarFilterStateOptions = useMemo(() => ({loading: isSidebarFilterLoading,+ onExplicitFilterStateChange,stateLocation: "urlAndSessionStorage",sessionFilterContextId: buildSidebarFilterSessionContextId(projectId,@@ -279,7 +282,13 @@ export default function SessionsTable({implicitDefaultConfig: DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG,isV4,}),- [isV4, isSidebarFilterLoading, projectId, userId],+ [+ isV4,+ isSidebarFilterLoading,+ projectId,+ userId,+ onExplicitFilterStateChange,+ ],);const queryFilter = useSidebarFilterState(@@ -297,39 +306,11 @@ export default function SessionsTable({[],);- // Grammar search bar (Feature Preview): an ADDITIONAL editor over the same- // FilterState the facet sidebar edits β the sidebar stays and the two reflect- // each other with no explicit sync. Off on the user-detail mount, which is- // page-scoped by a userId filter the bar must not fight (same embedded- // opt-out as EventsTable).- // Generally available on the v4 sessions table. Still off on the user-detail- // mount, which is page-scoped by a userId filter the bar must not fight (the- // same embedded opt-out EventsTable applies).- const sessionsSearchBarEnabled = isV4 && !userId;- const observedOptions = useMemo(- () => toObservedOptions(newFilterOptions, isSidebarFilterLoading),- [newFilterOptions, isSidebarFilterLoading],+ const searchRegistry = sessionsFieldRegistry(sessionsFilterConfig);+ const observedOptions = toObservedOptions(+ newFilterOptions,+ isSidebarFilterLoading,);- // Sessions has no full-text lane (`sessions.all*` takes no searchQuery), so- // the registry rejects free text and these stay inert.- const noSearchLane = useCallback(() => {}, []);- const {- store: searchBarStore,- commit: searchBarCommit,- applyFilters: searchBarApplyFilters,- } = useEventsSearchBar({- projectId,- tableName: sessionsFilterConfig.tableName,- enabled: sessionsSearchBarEnabled,- filterState: queryFilter.searchBarFilterState,- searchQuery: null,- searchType: DEFAULT_SEARCH_TYPE,- observed: observedOptions,- setFilterState: setFiltersWrapper,- setSearchQuery: noSearchLane,- setSearchType: noSearchLane,- registry: SESSIONS_FIELD_REGISTRY,- });const combinedFilterState = queryFilter.effectiveFilterState.concat(userIdFilter,@@ -749,7 +730,10 @@ export default function SessionsTable({projectId,stateUpdaters: {setOrderBy: setOrderByState,- setFilters: setFiltersWrapper,+ setFilters: (filters) =>+ queryFilterRef.current.setFilterState(filters, {+ origin: "saved_view",+ }),setExpandedFilters: queryFilter.onExpandedChange,setColumnOrder: setColumnOrder,setColumnVisibility: setColumnVisibility,@@ -764,6 +748,23 @@ export default function SessionsTable({currentFilterState: queryFilter.explicitFilterState,currentExpandedFilters: queryFilter.expanded,});+ viewControllersRef.current = viewControllers;++ const handleOrderByChange: typeof setOrderByState = (next) => {+ viewControllers.handleUserStateChange(orderByState, next);+ setOrderByState(next);+ };+ const handleColumnOrderChange: typeof setColumnOrder = (update) => {+ const next = typeof update === "function" ? update(columnOrder) : update;+ viewControllers.handleUserStateChange(columnOrder, next);+ setColumnOrder(next);+ };+ const handleColumnVisibilityChange: typeof setColumnVisibility = (update) => {+ const next =+ typeof update === "function" ? update(columnVisibility) : update;+ viewControllers.handleUserStateChange(columnVisibility, next);+ setColumnVisibility(next);+ };return (<DataTableControlsProvider tableName={sessionsFilterConfig.tableName}>@@ -778,26 +779,20 @@ export default function SessionsTable({(matching EventsTable) so the toolbar cannot scroll under thecomposer and render half-clipped; pb-1.5 gives the band the samebreathing room above the table that the events tables have. */}- <div- className={cn(- sessionsSearchBarEnabled &&- "bg-background sticky top-0 z-30 pb-1.5",- )}- >- {sessionsSearchBarEnabled && (- <EventsSearchBarRow- projectId={projectId}- tableName={sessionsFilterConfig.tableName}- store={searchBarStore}- commit={searchBarCommit}- observed={observedOptions}- onApplyFilters={searchBarApplyFilters}- registry={SESSIONS_FIELD_REGISTRY}- />- )}+ <div className="bg-background sticky top-0 z-30 pb-1.5">+ <TableSearchBar+ key={`${viewControllers.filterEditorResetKey}-${queryFilter.draftResetKey}`}+ isV4={isV4}+ filterState={queryFilter.searchBarFilterState}+ setFilterState={setFiltersWrapper}+ projectId={projectId}+ tableName={sessionsFilterConfig.tableName}+ observed={observedOptions}+ registry={searchRegistry}+ />{/* Toolbar spanning full width */}<DataTableToolbar- rowClassName={sessionsSearchBarEnabled ? "my-1" : undefined}+ rowClassName="my-1"filterState={queryFilter.explicitFilterState}actionButtons={[selectedSessionIds.length > 0 || selectAll ? (@@ -825,9 +820,9 @@ export default function SessionsTable({]}columns={columns}columnVisibility={columnVisibility}- setColumnVisibility={setColumnVisibility}+ setColumnVisibility={handleColumnVisibilityChange}columnOrder={columnOrder}- setColumnOrder={setColumnOrder}+ setColumnOrder={handleColumnOrderChange}viewConfig={{tableName: TableViewPresetTableName.Sessions,projectId,@@ -853,7 +848,7 @@ export default function SessionsTable({<ResizableFilterLayout><DataTableControls// Remount the sidebar when the saved view changes so the new view's filters replace any stale draft UI state.- key={viewControllers.selectedViewId ?? "no-view"}+ key={viewControllers.filterEditorResetKey}queryFilter={queryFilter}/>@@ -900,12 +895,12 @@ export default function SessionsTable({onChange: setPaginationState,state: paginationState,}}- setOrderBy={setOrderByState}+ setOrderBy={handleOrderByChange}orderBy={orderByState}columnVisibility={columnVisibility}- onColumnVisibilityChange={setColumnVisibility}+ onColumnVisibilityChange={handleColumnVisibilityChange}columnOrder={columnOrder}- onColumnOrderChange={setColumnOrder}+ onColumnOrderChange={handleColumnOrderChange}rowSelection={selectedRows}highlightAllRows={selectAll}setRowSelection={setSelectedRows}diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsxindex 331956e0eb..e02c680c1f 100644--- a/web/src/components/table/use-cases/traces.tsx+++ b/web/src/components/table/use-cases/traces.tsx@@ -90,6 +90,10 @@ import { sortOptionValues } from "@/src/features/filters/lib/option-sort";import { TablePeekViewTraceDetail } from "@/src/components/table/peek/peek-trace-detail";import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";+import { useTableViewFilterChange } from "@/src/components/table/table-view-presets/hooks/useTableViewFilterChange";+import { SearchScopeSelect } from "@/src/components/table/SearchScopeSelect";+import { TableSearchBar, toObservedOptions } from "@/src/features/search-bar";+import { tracesFieldRegistry } from "@/src/features/filters/config/tracingSearchRegistry";import { useFullTextSearch } from "@/src/components/table/use-cases/useFullTextSearch";import { type TableDateRange } from "@/src/utils/date-range-utils";import useSessionStorage from "@/src/components/useSessionStorage";@@ -106,11 +110,6 @@ import { DialogController } from "@/src/components/ui/dialog";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { usePostHogClientCapture } from "@/src/features/posthog-analytics";import { DeleteTraceDialogContent } from "@/src/features/traces/components/DeleteTraceDialogContent";-import {- demoteViewOnUserFilterEdit,- type ExplicitFilterStateChange,- type ViewDemotionControllers,-} from "@/src/features/events/lib/demoteViewOnUserFilterEdit";export type TracesTableRow = {// Shown by default@@ -389,19 +388,15 @@ function TracesTableInternal({const isSidebarFilterLoading =traceFilterOptionsResponse.isPending || environmentFilterOptions.isPending;- const viewControllersRef = useRef<ViewDemotionControllers | null>(null);- const onExplicitFilterStateChange = useCallback(- (change: ExplicitFilterStateChange) => {- demoteViewOnUserFilterEdit(change, viewControllersRef.current);- },- [],- );+ const { viewControllersRef, onExplicitFilterStateChange } =+ useTableViewFilterChange();const queryFilterOptions: UseSidebarFilterStateOptions = useMemo(() => {const baseOptions = {loading: isSidebarFilterLoading,implicitDefaultConfig: DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG,onExplicitFilterStateChange,+ isV4: false,};if (peekContext) {@@ -441,6 +436,11 @@ function TracesTableInternal({filterOptions,queryFilterOptions,);+ const searchRegistry = tracesFieldRegistry(tracesFilterConfig);+ const observedOptions = toObservedOptions(+ filterOptions,+ isSidebarFilterLoading,+ );const combinedFilterState = queryFilter.effectiveFilterState.concat(userIdFilter,@@ -455,8 +455,6 @@ function TracesTableInternal({? externalFilterState.concat(rowsDateRangeFilter): combinedFilterState;- const { searchQuery, searchType, setSearchQuery, setSearchType } =- useFullTextSearch();const legacyTracingSearchConfig = api.public.tracingSearchConfig.useQuery({ projectId },{@@ -468,6 +466,10 @@ function TracesTableInternal({);const legacyTracingIoSearchEnabled =legacyTracingSearchConfig.data?.legacyTracingIoSearchEnabled ?? true;+ const { searchQuery, searchType, setSearchQuery, setSearchType } =+ useFullTextSearch({+ tableAllowsFullTextSearch: legacyTracingIoSearchEnabled,+ });const tracesAllCountFilter = {projectId,@@ -1284,8 +1286,8 @@ function TracesTableInternal({});viewControllersRef.current = viewControllers;- const handleSearchQueryChange = (nextQuery: string) => {- viewControllers.handleUserStateChange(searchQuery ?? "", nextQuery);+ const handleSearchQueryChange = (nextQuery: string | null) => {+ viewControllers.handleUserStateChange(searchQuery ?? "", nextQuery ?? "");setSearchQuery(nextQuery);};const handleSearchTypeChange = (nextType: TracingSearchType[]) => {@@ -1392,95 +1394,125 @@ function TracesTableInternal({)}{/* Toolbar spanning full width */}{!hideControls && (- <DataTableToolbar- columns={columns}- filterWithAI- filterState={queryFilter.explicitFilterState}- tableName={tracesFilterConfig.tableName}- isV4={false}- viewConfig={{- tableName: TableViewPresetTableName.Traces,- projectId,- controllers: viewControllers,- }}- searchConfig={{- metadataSearchFields: ["ID", "Trace Name", "User ID"],- updateQuery: handleSearchQueryChange,- currentQuery: searchQuery ?? undefined,- tableAllowsFullTextSearch: legacyTracingIoSearchEnabled,- setSearchType: handleSearchTypeChange,- searchType,- }}- columnsWithCustomSelect={["traceName", "traceTags"]}- actionButtons={[- selectedTraceIds.length > 0 || selectAll ? (- <AddTracesToAnnotationQueueDialogController- key="traces-multi-select-actions"- projectId={projectId}- onSuccess={() => {- setSelectedRows({});- setSelectAll(false);+ <div className="shrink-0 pb-1.5">+ <TableSearchBar+ key={`${viewControllers.filterEditorResetKey}-${queryFilter.draftResetKey}`}+ projectId={projectId}+ tableName={tracesFilterConfig.tableName}+ registry={searchRegistry}+ filterState={queryFilter.searchBarFilterState}+ setFilterState={queryFilter.setFilterState}+ observed={observedOptions}+ isV4={false}+ search={{+ query: searchQuery,+ type: searchType,+ setQuery: handleSearchQueryChange,+ }}+ searchScope={+ legacyTracingIoSearchEnabled ? (+ <SearchScopeSelect+ searchType={searchType}+ setSearchType={handleSearchTypeChange}+ metadataLabel="IDs / Names"+ fullTextLabel="Full Text"+ availableSearchTypes={{+ content: true,+ input: true,+ output: true,+ }}+ />+ ) : undefined+ }+ />+ <DataTableToolbar+ rowClassName="my-1"+ columns={columns}+ filterWithAI+ filterState={queryFilter.explicitFilterState}+ tableName={tracesFilterConfig.tableName}+ isV4={false}+ viewConfig={{+ tableName: TableViewPresetTableName.Traces,+ projectId,+ controllers: viewControllers,+ }}+ currentSearchQuery={searchQuery ?? ""}+ columnsWithCustomSelect={["traceName", "traceTags"]}+ actionButtons={[+ selectedTraceIds.length > 0 || selectAll ? (+ <AddTracesToAnnotationQueueDialogController+ key="traces-multi-select-actions"+ projectId={projectId}+ onSuccess={() => {+ setSelectedRows({});+ setSelectAll(false);+ }}+ description={`Add ${displayCount} selected traces to an annotation queue.`}+ onAddToQueue={handleAddToAnnotationQueue}+ >+ {({ openDialog }) => (+ <TableActionMenu+ projectId={projectId}+ actions={tableActions}+ tableName={BatchExportTableName.Traces}+ selectedCount={selectedTraceCount}+ onClearSelection={() => {+ setSelectedRows({});+ setSelectAll(false);+ }}+ onCustomAction={(actionType) => {+ if (+ actionType === ActionId.TraceAddToAnnotationQueue+ ) {+ openDialog();+ }+ }}+ />+ )}+ </AddTracesToAnnotationQueueDialogController>+ ) : null,+ <BatchExportTableButton+ {...{+ projectId,+ filterState,+ orderByState,+ searchQuery,+ searchType,}}- description={`Add ${displayCount} selected traces to an annotation queue.`}- onAddToQueue={handleAddToAnnotationQueue}- >- {({ openDialog }) => (- <TableActionMenu- projectId={projectId}- actions={tableActions}- tableName={BatchExportTableName.Traces}- selectedCount={selectedTraceCount}- onClearSelection={() => {- setSelectedRows({});- setSelectAll(false);- }}- onCustomAction={(actionType) => {- if (actionType === ActionId.TraceAddToAnnotationQueue) {- openDialog();- }- }}- />- )}- </AddTracesToAnnotationQueueDialogController>- ) : null,- <BatchExportTableButton- {...{- projectId,- filterState,- orderByState,- searchQuery,- searchType,- }}- tableName={BatchExportTableName.Traces}- key="batchExport"- />,- ]}- orderByState={orderByState}- columnVisibility={columnVisibility}- setColumnVisibility={handleColumnVisibilityChange}- columnOrder={columnOrder}- setColumnOrder={handleColumnOrderChange}- rowHeight={rowHeight}- setRowHeight={setRowHeight}- timeRange={showControlsInPageHeader ? undefined : timeRange}- setTimeRange={showControlsInPageHeader ? undefined : setTimeRange}- refreshConfig={showControlsInPageHeader ? undefined : refreshConfig}- multiSelect={{- selectAll,- setSelectAll,- selectedRowIds: selectedTraceIds,- setRowSelection: setSelectedRows,- totalCount,- ...paginationState,- }}- />+ tableName={BatchExportTableName.Traces}+ key="batchExport"+ />,+ ]}+ orderByState={orderByState}+ columnVisibility={columnVisibility}+ setColumnVisibility={handleColumnVisibilityChange}+ columnOrder={columnOrder}+ setColumnOrder={handleColumnOrderChange}+ rowHeight={rowHeight}+ setRowHeight={setRowHeight}+ timeRange={showControlsInPageHeader ? undefined : timeRange}+ setTimeRange={showControlsInPageHeader ? undefined : setTimeRange}+ refreshConfig={+ showControlsInPageHeader ? undefined : refreshConfig+ }+ multiSelect={{+ selectAll,+ setSelectAll,+ selectedRowIds: selectedTraceIds,+ setRowSelection: setSelectedRows,+ totalCount,+ ...paginationState,+ }}+ />+ </div>)}{/* Content area with sidebar and table */}<ResizableFilterLayout>{!hideControls && (<DataTableControls- key={viewControllers.filterEditorResetKey}+ key={`${viewControllers.filterEditorResetKey}-${queryFilter.draftResetKey}`}queryFilter={queryFilter}filterWithAI/>diff --git a/web/src/components/table/use-cases/useFullTextSearch.clienttest.tsx b/web/src/components/table/use-cases/useFullTextSearch.clienttest.tsxnew file mode 100644index 0000000000..98cdf29449--- /dev/null+++ b/web/src/components/table/use-cases/useFullTextSearch.clienttest.tsx@@ -0,0 +1,110 @@+import { act, renderHook } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ PeekTableStateProvider,+ usePeekTableState,+} from "@/src/components/table/peek/contexts/PeekTableStateContext";+import { useFullTextSearch } from "./useFullTextSearch";++const h = vi.hoisted(() => ({+ scope: ["id", "input"],+ setScope: vi.fn(),+}));++vi.mock("use-query-params", async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ useQueryParam: (key: string) =>+ key === "searchType" ? [h.scope, h.setScope] : ["refund", vi.fn()],+}));++function setup(owner: string, allowed?: boolean) {+ const hook = renderHook(+ ({ allowed }: { allowed?: boolean }) => ({+ ...useFullTextSearch({ tableAllowsFullTextSearch: allowed }),+ peek: usePeekTableState(),+ }),+ {+ initialProps: { allowed },+ wrapper: owner === "peek" ? PeekTableStateProvider : undefined,+ },+ );+ act(() => {+ hook.result.current.peek?.setTableState((state) => ({+ ...state,+ search: { query: "refund", type: h.scope },+ }));+ });+ return hook;+}++describe.each(["URL", "peek"])("useFullTextSearch %s scope policy", (owner) => {+ beforeEach(() => {+ vi.clearAllMocks();+ h.scope = ["id", "input"];+ });++ it("normalizes scope changes using the disabled full-text policy", () => {+ const { result } = setup(owner, false);+ act(() => result.current.setSearchType(["id", "output"]));++ if (owner === "peek") {+ expect(result.current.peek?.tableState.search).toEqual({+ query: "refund",+ type: ["id"],+ });+ } else {+ expect(h.setScope).toHaveBeenCalledWith(undefined);+ }+ expect(result.current.searchType).toEqual(["id"]);+ expect(result.current.searchQuery).toBe("refund");+ });++ it("removes unsupported scopes when instance config resolves after restoration", () => {+ const { result, rerender } = setup(owner);+ expect(result.current.searchType).toEqual(["id", "input"]);+ expect(h.setScope).not.toHaveBeenCalled();++ rerender({ allowed: false });++ expect(result.current.searchType).toEqual(["id"]);+ expect(result.current.searchQuery).toBe("refund");+ });++ it("preserves supported scopes when full-text search is enabled", () => {+ const { result } = setup(owner);+ expect(result.current.searchType).toEqual(["id", "input"]);+ act(() => result.current.setSearchType(["id", "content"]));++ if (owner === "peek") {+ expect(result.current.peek?.tableState.search).toEqual({+ query: "refund",+ type: ["id", "content"],+ });+ } else {+ expect(h.setScope).toHaveBeenCalledWith(["id", "content"]);+ }+ });+});++it("composes peek filter, sorting, and search updates in one event", () => {+ const { result } = setup("peek");+ act(() => {+ result.current.peek?.setTableState((state) => ({+ ...state,+ filters: [+ { column: "name", type: "string", operator: "=", value: "checkout" },+ ],+ sorting: { column: "timestamp", order: "ASC" },+ }));+ result.current.setSearchType(["id", "output"]);+ result.current.setSearchQuery("response");+ });+ expect(result.current.peek?.tableState).toEqual({+ filters: [+ { column: "name", type: "string", operator: "=", value: "checkout" },+ ],+ sorting: { column: "timestamp", order: "ASC" },+ pagination: { pageIndex: 0, pageSize: 50 },+ search: { query: "response", type: ["id", "output"] },+ });+});diff --git a/web/src/components/table/use-cases/useFullTextSearch.tsx b/web/src/components/table/use-cases/useFullTextSearch.tsxindex 9f6d0b6afb..51b87184a0 100644--- a/web/src/components/table/use-cases/useFullTextSearch.tsx+++ b/web/src/components/table/use-cases/useFullTextSearch.tsx@@ -6,9 +6,18 @@ import {ArrayParam,} from "use-query-params";import { usePeekTableState } from "@/src/components/table/peek/contexts/PeekTableStateContext";+import { hasFullTextSearchType } from "@/src/components/table/utils/searchUtils";-export const useFullTextSearch = () => {+export const useFullTextSearch = ({+ tableAllowsFullTextSearch = true,+}: {+ tableAllowsFullTextSearch?: boolean;+} = {}) => {const peekContext = usePeekTableState();+ // Apply the host policy on reads too: instance config can resolve after a+ // URL has already restored its scope.+ const allowedSearchType = (type: TracingSearchType[]): TracingSearchType[] =>+ !tableAllowsFullTextSearch && hasFullTextSearchType(type) ? ["id"] : type;const [searchQuery, setSearchQuery] = useQueryParam("search",@@ -28,43 +37,47 @@ export const useFullTextSearch = () => {const { query, type } = peekContext.tableState.search;const setSearchQuery = (newQuery: string | null) => {- peekContext.setTableState({- ...peekContext.tableState,- search: { ...peekContext.tableState.search, query: newQuery },- });+ peekContext.setTableState((state) => ({+ ...state,+ search: { ...state.search, query: newQuery },+ }));};- const setSearchType = (newType: string[]) => {- peekContext.setTableState({- ...peekContext.tableState,- search: { ...peekContext.tableState.search, type: newType },- });+ const setSearchType = (newType: TracingSearchType[]) => {+ peekContext.setTableState((state) => ({+ ...state,+ search: {+ ...state.search,+ type: allowedSearchType(newType),+ },+ }));};return {searchQuery: query,- searchType: type as TracingSearchType[],+ searchType: allowedSearchType(type as TracingSearchType[]),setSearchQuery,setSearchType,};}const setSearchType = (newSearchType: TracingSearchType[]) => {+ const allowedType = allowedSearchType(newSearchType);// Reverting to the default scope (id) removes the `searchType` param// entirely instead of writing an explicit `?searchType=id`, so URLs and// saved views match the no-scope state regardless of which surface (search// bar or legacy toolbar) produced the change.const isDefault =- newSearchType.length === 0 ||- (newSearchType.length === 1 && newSearchType[0] === "id");- handleSearchTypeChange(isDefault ? undefined : newSearchType);+ allowedType.length === 0 ||+ (allowedType.length === 1 && allowedType[0] === "id");+ handleSearchTypeChange(isDefault ? undefined : allowedType);};const typedSearchType = (searchType ?? ["id"]) as TracingSearchType[];return {searchQuery,- searchType: typedSearchType,+ searchType: allowedSearchType(typedSearchType),setSearchQuery,setSearchType,};diff --git a/web/src/features/ai-gateway/components/GatewayModelsPage/components/GatewayModelsView/GatewayModelsView.tsx b/web/src/features/ai-gateway/components/GatewayModelsPage/components/GatewayModelsView/GatewayModelsView.tsxindex e0a3f591db..c136499f8b 100644--- a/web/src/features/ai-gateway/components/GatewayModelsPage/components/GatewayModelsView/GatewayModelsView.tsx+++ b/web/src/features/ai-gateway/components/GatewayModelsPage/components/GatewayModelsView/GatewayModelsView.tsx@@ -1,4 +1,3 @@-import { type FilterState, type ColumnDefinition } from "@langfuse/shared";import { useMemo, useState } from "react";import { RefreshCw } from "lucide-react";@@ -15,50 +14,16 @@ import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";import { ResizableFilterLayout } from "@/src/components/table/resizable-filter-layout";import type { LangfuseColumnDef } from "@/src/components/table/types";import { useSidebarFilterState } from "@/src/features/filters/hooks/useSidebarFilterState";-import type { FilterConfig } from "@/src/features/filters/lib/filter-config";import { providerLabels } from "@/src/features/ai-gateway/constants/providerLabels";-import type { GatewayProvider } from "@/src/features/ai-gateway/types/gatewayProvider";--const TABLE_NAME = "gateway-models";--export type GatewayModelRow = {- id: string;- availableVia: Array<{- connectionName: string;- provider: GatewayProvider;- }>;- apiFormats: string[];-};--const filterColumns: ColumnDefinition[] = [- {- name: "Provider",- id: "provider",- type: "arrayOptions",- internal: "provider",- options: Object.entries(providerLabels).map(([value, displayValue]) => ({- value,- displayValue,- })),- },- {- name: "API format",- id: "apiFormat",- type: "arrayOptions",- internal: "apiFormat",- options: [],- },-];+import { gatewayModelsFilterConfig } from "@/src/features/ai-gateway/constants/modelsFilterConfig";+import { GATEWAY_MODELS_FIELD_REGISTRY } from "@/src/features/ai-gateway/constants/modelsSearchRegistry";+import { TableSearchBar, toObservedOptions } from "@/src/features/search-bar";+import {+ filterGatewayModels,+ type GatewayModelRow,+} from "./filterGatewayModels";-const filterConfig: FilterConfig = {- tableName: TABLE_NAME,- columnDefinitions: filterColumns,- defaultExpanded: ["provider", "apiFormat"],- facets: [- { type: "categorical", column: "provider", label: "Provider" },- { type: "categorical", column: "apiFormat", label: "API format" },- ],-};+const TABLE_NAME = gatewayModelsFilterConfig.tableName;const columns: LangfuseColumnDef<GatewayModelRow, unknown>[] = [{@@ -145,9 +110,13 @@ export function GatewayModelsView({}),[models],);- const queryFilter = useSidebarFilterState(filterConfig, filterOptions, {- stateLocation: "memory",- });+ const queryFilter = useSidebarFilterState(+ gatewayModelsFilterConfig,+ filterOptions,+ {+ stateLocation: "memory",+ },+ );const filteredModels = useMemo(() => filterGatewayModels(models, searchQuery, queryFilter.filterState),[models, queryFilter.filterState, searchQuery],@@ -196,16 +165,23 @@ export function GatewayModelsView({<DataTableControlsProvider tableName={TABLE_NAME}><div className="flex min-h-0 w-full flex-1 flex-col overflow-hidden rounded-md border">+ <TableSearchBar+ key={queryFilter.draftResetKey}+ tableName={TABLE_NAME}+ registry={GATEWAY_MODELS_FIELD_REGISTRY}+ filterState={queryFilter.searchBarFilterState}+ setFilterState={queryFilter.setFilterState}+ observed={toObservedOptions(filterOptions, isLoading)}+ isV4={false}+ search={{+ query: searchQuery,+ setQuery: (query) => setSearchQuery(query ?? ""),+ }}+ /><DataTableToolbartableName={TABLE_NAME}columns={columns}filterState={queryFilter.filterState}- searchConfig={{- metadataSearchFields: ["Model"],- currentQuery: searchQuery,- tableAllowsFullTextSearch: false,- updateQuery: setSearchQuery,- }}/><div className="min-h-0 flex-1 overflow-hidden"><ResizableFilterLayout>@@ -258,59 +234,6 @@ function uniqueSorted(values: string[]) {);}-function getModelFilterValues(model: GatewayModelRow, column: string) {- switch (column) {- case "provider":- return model.availableVia.map((connection) => connection.provider);- case "apiFormat":- return model.apiFormats;- default:- return [];- }-}--function filterGatewayModels(- models: GatewayModelRow[],- searchQuery: string,- filters: FilterState,-) {- const normalizedSearch = searchQuery.trim().toLowerCase();-- return models.filter((model) => {- if (- normalizedSearch.length > 0 &&- !model.id.toLowerCase().includes(normalizedSearch)- ) {- return false;- }-- return filters.every((filter) => {- const values = getModelFilterValues(model, filter.column);-- if (filter.type === "string") {- const needle = filter.value.toLowerCase();- const contains = values.some((value) =>- value.toLowerCase().includes(needle),- );- return filter.operator === "does not contain" ? !contains : contains;- }-- if (filter.type !== "arrayOptions" && filter.type !== "stringOptions") {- return true;- }-- const selected = filter.value;- if (filter.operator === "none of") {- return selected.every((value) => !values.includes(value));- }- if (filter.operator === "all of") {- return selected.every((value) => values.includes(value));- }- return selected.some((value) => values.includes(value));- });- });-}-function getEmptyMessage({hasProviders,hasSynced,diff --git a/web/src/features/ai-gateway/components/GatewayModelsPage/components/GatewayModelsView/filterGatewayModels.clienttest.ts b/web/src/features/ai-gateway/components/GatewayModelsPage/components/GatewayModelsView/filterGatewayModels.clienttest.tsnew file mode 100644index 0000000000..d069b7a3a9--- /dev/null+++ b/web/src/features/ai-gateway/components/GatewayModelsPage/components/GatewayModelsView/filterGatewayModels.clienttest.ts@@ -0,0 +1,93 @@+// @vitest-environment node++import { describe, expect, it } from "vitest";+import { GATEWAY_MODELS_FIELD_REGISTRY } from "@/src/features/ai-gateway/constants/modelsSearchRegistry";+import { planCommit } from "@/src/features/search-bar/lib/commit";+import { runSearchBarInvariants } from "@/src/features/search-bar/lib/searchBarInvariants";+import {+ filterGatewayModels,+ type GatewayModelRow,+} from "./filterGatewayModels";++const models: GatewayModelRow[] = [+ {+ id: "model-small",+ availableVia: [{ connectionName: "Primary", provider: "OPENAI" }],+ apiFormats: ["OpenAI Responses", "OpenAI Chat Completions"],+ },+ {+ id: "model-large",+ availableVia: [{ connectionName: "Secondary", provider: "ANTHROPIC" }],+ apiFormats: ["Anthropic Messages"],+ },+];++function search(query: string) {+ const result = planCommit(query, undefined, GATEWAY_MODELS_FIELD_REGISTRY);+ if (result.status !== "committed") {+ throw new Error(`Query did not commit: ${query}`);+ }+ return filterGatewayModels(+ models,+ result.searchQuery ?? "",+ result.filters,+ ).map((model) => model.id);+}++describe("gateway model grammar", () => {+ it("keeps model-name substring search separate from provider filters", () => {+ expect(search("SMALL provider:OPENAI")).toEqual(["model-small"]);+ expect(search("Primary provider:OPENAI")).toEqual([]);+ });++ it("preserves API-format any-of, all-of and none-of semantics", () => {+ expect(+ search('apiFormat:("Anthropic Messages" OR "OpenAI Responses")'),+ ).toEqual(["model-small", "model-large"]);+ expect(+ search('apiFormat:("OpenAI Responses" AND "OpenAI Chat Completions")'),+ ).toEqual(["model-small"]);+ expect(search('-apiFormat:"OpenAI Responses"')).toEqual(["model-large"]);+ });++ it("preserves existing case-insensitive custom sidebar filters", () => {+ expect(+ filterGatewayModels(models, "", [+ {+ column: "apiFormat",+ type: "string",+ operator: "contains",+ value: "responses",+ },+ ]).map((model) => model.id),+ ).toEqual(["model-small"]);+ });++ it("rejects fields and operators the model catalog cannot apply", () => {+ for (const query of [+ "latency:>1",+ "metadata.region:eu",+ "provider:>OPENAI",+ "has:provider",+ "-has:provider",+ ]) {+ expect(+ planCommit(query, undefined, GATEWAY_MODELS_FIELD_REGISTRY).status,+ query,+ ).not.toBe("committed");+ }+ });++ it("keeps validation and lowering aligned with the sidebar registry", () => {+ expect(+ runSearchBarInvariants({+ name: "gateway model catalog",+ registry: GATEWAY_MODELS_FIELD_REGISTRY,+ fieldValues: ["OPENAI", "ANTHROPIC", "OpenAI Responses"],+ freeTextValues: ["model small"],+ extraKeys: ["metadata.region", "scores.quality"],+ scoreContexts: [],+ }),+ ).toEqual([]);+ });+});diff --git a/web/src/features/ai-gateway/components/GatewayModelsPage/components/GatewayModelsView/filterGatewayModels.ts b/web/src/features/ai-gateway/components/GatewayModelsPage/components/GatewayModelsView/filterGatewayModels.tsnew file mode 100644index 0000000000..20f65ca7d3--- /dev/null+++ b/web/src/features/ai-gateway/components/GatewayModelsPage/components/GatewayModelsView/filterGatewayModels.ts@@ -0,0 +1,64 @@+import type { FilterState } from "@langfuse/shared";+import type { GatewayProvider } from "@/src/features/ai-gateway/types/gatewayProvider";++export type GatewayModelRow = {+ id: string;+ availableVia: Array<{+ connectionName: string;+ provider: GatewayProvider;+ }>;+ apiFormats: string[];+};++function getModelFilterValues(model: GatewayModelRow, column: string) {+ switch (column) {+ case "provider":+ return model.availableVia.map((connection) => connection.provider);+ case "apiFormat":+ return model.apiFormats;+ default:+ return [];+ }+}++export function filterGatewayModels(+ models: GatewayModelRow[],+ searchQuery: string,+ filters: FilterState,+) {+ const normalizedSearch = searchQuery.trim().toLowerCase();++ return models.filter((model) => {+ if (+ normalizedSearch.length > 0 &&+ !model.id.toLowerCase().includes(normalizedSearch)+ ) {+ return false;+ }++ return filters.every((filter) => {+ const values = getModelFilterValues(model, filter.column);++ if (filter.type === "string") {+ const needle = filter.value.toLowerCase();+ const contains = values.some((value) =>+ value.toLowerCase().includes(needle),+ );+ return filter.operator === "does not contain" ? !contains : contains;+ }++ if (filter.type !== "arrayOptions" && filter.type !== "stringOptions") {+ return true;+ }++ const selected = filter.value;+ if (filter.operator === "none of") {+ return selected.every((value) => !values.includes(value));+ }+ if (filter.operator === "all of") {+ return selected.every((value) => values.includes(value));+ }+ return selected.some((value) => values.includes(value));+ });+ });+}diff --git a/web/src/features/ai-gateway/constants/modelsFilterConfig.ts b/web/src/features/ai-gateway/constants/modelsFilterConfig.tsnew file mode 100644index 0000000000..c75f2a11d2--- /dev/null+++ b/web/src/features/ai-gateway/constants/modelsFilterConfig.ts@@ -0,0 +1,33 @@+import type { ColumnDefinition } from "@langfuse/shared";+import type { FilterConfig } from "@/src/features/filters/lib/filter-config";+import { providerLabels } from "./providerLabels";++const filterColumns: ColumnDefinition[] = [+ {+ name: "Provider",+ id: "provider",+ type: "arrayOptions",+ internal: "provider",+ options: Object.entries(providerLabels).map(([value, displayValue]) => ({+ value,+ displayValue,+ })),+ },+ {+ name: "API format",+ id: "apiFormat",+ type: "arrayOptions",+ internal: "apiFormat",+ options: [],+ },+];++export const gatewayModelsFilterConfig: FilterConfig = {+ tableName: "gateway-models",+ columnDefinitions: filterColumns,+ defaultExpanded: ["provider", "apiFormat"],+ facets: [+ { type: "categorical", column: "provider", label: "Provider" },+ { type: "categorical", column: "apiFormat", label: "API format" },+ ],+};diff --git a/web/src/features/ai-gateway/constants/modelsSearchRegistry.ts b/web/src/features/ai-gateway/constants/modelsSearchRegistry.tsnew file mode 100644index 0000000000..95e053f13f--- /dev/null+++ b/web/src/features/ai-gateway/constants/modelsSearchRegistry.ts@@ -0,0 +1,24 @@+import { fieldRegistryFromColumns } from "@/src/features/search-bar/lib/fields";+import { gatewayModelsFilterConfig } from "./modelsFilterConfig";++const facetColumns = new Set(+ gatewayModelsFilterConfig.facets.map((facet) => facet.column),+);++export const GATEWAY_MODELS_FIELD_REGISTRY = fieldRegistryFromColumns(+ gatewayModelsFilterConfig.columnDefinitions.filter((column) =>+ facetColumns.has(column.id),+ ),+ {+ id: "gatewayModels",+ allowFreeText: true,+ filterStateErrors: (filters) =>+ filters.some((filter) => filter.type === "null")+ ? [+ "Gateway models do not support presence filters. Select a provider or API format instead.",+ ]+ : [],+ freeTextScopeLabel: "model names",+ searchExamples: ["provider:OPENAI", 'apiFormat:"Anthropic Messages"'],+ },+);diff --git a/web/src/features/datasets/components/DatasetsTable.tsx b/web/src/features/datasets/components/DatasetsTable.tsxindex dbb2841ab5..05a6e92cae 100644--- a/web/src/features/datasets/components/DatasetsTable.tsx+++ b/web/src/features/datasets/components/DatasetsTable.tsx@@ -18,7 +18,6 @@ import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";import {TableViewPresetTableName,type Prisma,- type TableViewPresetState,ActionId,BatchActionType,BatchExportTableName,@@ -66,12 +65,16 @@ type DatasetTableRow = {expectedOutputSchema?: Prisma.JsonValue | null;};-type DatasetTableViewControllers = {- applyViewState: (viewData: TableViewPresetState) => void;- selectedViewId: string | null;- appliedViewId: string | null;- handleSetViewId: (viewId: string | null) => void;-};+type DatasetTableViewControllers = Pick<+ ReturnType<typeof useTableViewManager>,+ | "applyViewState"+ | "selectedViewId"+ | "appliedViewId"+ | "handleSetViewId"+ | "handleUserStateChange"+ | "viewUpdateTarget"+ | "filterEditorResetKey"+>;function createRow(data: Partial<DatasetTableRow> & {@@ -200,7 +203,7 @@ function DatasetsTableToolbar({typeof useColumnVisibility<DatasetTableRow>>[1];setRowHeight: ReturnType<typeof useRowHeightLocalStorage>[1];- setSearchQuery: (value: string | null | undefined) => void;+ setSearchQuery: (query: string | null) => void;store: DatasetsTableStore;totalCount: number | null;viewControllers: DatasetTableViewControllers;@@ -229,6 +232,8 @@ function DatasetsTableToolbar({setSearchType: undefined,searchType: undefined,}}+ currentSearchQuery={searchQuery ?? ""}+ isV4={false}viewConfig={{tableName: TableViewPresetTableName.Datasets,projectId,@@ -578,6 +583,21 @@ export function DatasetsTable(props: { projectId: string }) {searchQuery,});+ const handleSearchQueryChange = (query: string | null) => {+ viewControllers.handleUserStateChange(searchQuery ?? "", query ?? "");+ setSearchQuery(query);+ };+ const handleColumnOrderChange: typeof setColumnOrder = (next) => {+ const value = typeof next === "function" ? next(columnOrder) : next;+ viewControllers.handleUserStateChange(columnOrder, value);+ setColumnOrder(value);+ };+ const handleColumnVisibilityChange: typeof setColumnVisibility = (next) => {+ const value = typeof next === "function" ? next(columnVisibility) : next;+ viewControllers.handleUserStateChange(columnVisibility, value);+ setColumnVisibility(value);+ };+return (<>{currentFolderPath && (@@ -587,18 +607,19 @@ export function DatasetsTable(props: { projectId: string }) {/>)}<DatasetsTableToolbar+ key={`${props.projectId}:${viewControllers.filterEditorResetKey}`}columns={columns}columnVisibility={columnVisibility}- setColumnVisibility={setColumnVisibility}+ setColumnVisibility={handleColumnVisibilityChange}columnOrder={columnOrder}- setColumnOrder={setColumnOrder}+ setColumnOrder={handleColumnOrderChange}rowHeight={rowHeight}setRowHeight={setRowHeight}currentFolderPath={currentFolderPath}paginationState={paginationState}projectId={props.projectId}searchQuery={searchQuery}- setSearchQuery={setSearchQuery}+ setSearchQuery={handleSearchQueryChange}store={datasetsTableStore}totalCount={datasets.data?.totalDatasets ?? null}viewControllers={viewControllers}@@ -629,9 +650,9 @@ export function DatasetsTable(props: { projectId: string }) {state: paginationState,}}columnVisibility={columnVisibility}- onColumnVisibilityChange={setColumnVisibility}+ onColumnVisibilityChange={handleColumnVisibilityChange}columnOrder={columnOrder}- onColumnOrderChange={setColumnOrder}+ onColumnOrderChange={handleColumnOrderChange}rowHeight={rowHeight}/></>diff --git a/web/src/features/evals/components/eval-log.tsx b/web/src/features/evals/components/eval-log.tsxindex 07dd961c70..247be74d90 100644--- a/web/src/features/evals/components/eval-log.tsx+++ b/web/src/features/evals/components/eval-log.tsx@@ -19,6 +19,9 @@ import {useColumnOrder,useColumnVisibility,} from "@/src/features/column-visibility";+import { TableSearchBar } from "@/src/features/search-bar/components/TableSearchBar";+import { toObservedOptions } from "@/src/features/search-bar/lib/observed-options";+import { EVAL_LOGS_FIELD_REGISTRY } from "@/src/features/evals/constants/tableSearchRegistry";import { evalLogFilterConfig } from "@/src/features/filters/config/eval-logs-config";import { useSidebarFilterState } from "@/src/features/filters";import { type RouterOutputs, api } from "@/src/utils/api";@@ -70,9 +73,14 @@ export default function EvalLogTable({pageSize: withDefault(NumberParam, 50),});+ const filterOptions = Object.fromEntries(+ evalLogFilterConfig.columnDefinitions.flatMap((column) =>+ column.type === "stringOptions" ? [[column.id, column.options]] : [],+ ),+ );const queryFilter = useSidebarFilterState(evalLogFilterConfig,- {}, // No dynamic options needed - status options are in column definition+ filterOptions,{loading: false,stateLocation: "urlAndSessionStorage",@@ -253,6 +261,16 @@ export default function EvalLogTable({defaultSidebarCollapsed={evalLogFilterConfig.defaultSidebarCollapsed}><div className="flex h-full w-full flex-col">+ <TableSearchBar+ key={queryFilter.draftResetKey}+ projectId={projectId}+ tableName={evalLogFilterConfig.tableName}+ registry={EVAL_LOGS_FIELD_REGISTRY}+ filterState={queryFilter.searchBarFilterState}+ setFilterState={queryFilter.setFilterState}+ observed={toObservedOptions(filterOptions, false)}+ isV4={false}+ /><DataTableToolbartableName="evalLogs"columns={columns}@@ -266,7 +284,10 @@ export default function EvalLogTable({/><ResizableFilterLayout>- <DataTableControls queryFilter={queryFilter} />+ <DataTableControls+ key={queryFilter.draftResetKey}+ queryFilter={queryFilter}+ /><div className="flex flex-1 flex-col overflow-hidden"><DataTablediff --git a/web/src/features/evals/components/evaluator-table.tsx b/web/src/features/evals/components/evaluator-table.tsxindex 1726633e05..b1a329d776 100644--- a/web/src/features/evals/components/evaluator-table.tsx+++ b/web/src/features/evals/components/evaluator-table.tsx@@ -11,6 +11,9 @@ import { type LangfuseColumnDef } from "@/src/components/table/types";import { useColumnVisibility } from "@/src/features/column-visibility";import { EvaluatorFilterCell } from "@/src/features/evals/components/EvaluatorFilterCell";import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";+import { TableSearchBar } from "@/src/features/search-bar/components/TableSearchBar";+import { toObservedOptions } from "@/src/features/search-bar/lib/observed-options";+import { LEGACY_EVALUATORS_FIELD_REGISTRY } from "@/src/features/evals/constants/tableSearchRegistry";import { evaluatorFilterConfig } from "@/src/features/filters/config/evaluators-config";import { useSidebarFilterState } from "@/src/features/filters";import { api } from "@/src/utils/api";@@ -430,6 +433,17 @@ export default function EvaluatorTable({ projectId }: { projectId: string }) {defaultSidebarCollapsed={evaluatorFilterConfig.defaultSidebarCollapsed}><div className="flex h-full w-full flex-col">+ <TableSearchBar+ key={queryFilter.draftResetKey}+ projectId={projectId}+ tableName={evaluatorFilterConfig.tableName}+ registry={LEGACY_EVALUATORS_FIELD_REGISTRY}+ filterState={queryFilter.searchBarFilterState}+ setFilterState={queryFilter.setFilterState}+ observed={toObservedOptions(newFilterOptions, false)}+ search={{ query: searchQuery, setQuery: setSearchQuery }}+ isV4={false}+ />{/* Toolbar spanning full width */}<DataTableToolbartableName="evaluators"@@ -437,19 +451,14 @@ export default function EvaluatorTable({ projectId }: { projectId: string }) {filterState={queryFilter.filterState}columnVisibility={columnVisibility}setColumnVisibility={setColumnVisibility}- searchConfig={{- metadataSearchFields: ["Name"],- updateQuery: setSearchQuery,- currentQuery: searchQuery ?? undefined,- tableAllowsFullTextSearch: false,- setSearchType: undefined,- searchType: undefined,- }}/>{/* Content area with sidebar and table */}<ResizableFilterLayout>- <DataTableControls queryFilter={queryFilter} />+ <DataTableControls+ key={queryFilter.draftResetKey}+ queryFilter={queryFilter}+ /><div className="flex flex-1 flex-col overflow-hidden"><DataTablediff --git a/web/src/features/evals/constants/tableSearchRegistry.clienttest.ts b/web/src/features/evals/constants/tableSearchRegistry.clienttest.tsnew file mode 100644index 0000000000..f3528ef4e2--- /dev/null+++ b/web/src/features/evals/constants/tableSearchRegistry.clienttest.ts@@ -0,0 +1,74 @@+// @vitest-environment node++import { describe, expect, it } from "vitest";+import { planCommit } from "@/src/features/search-bar/lib/commit";+import { runSearchBarInvariants } from "@/src/features/search-bar/lib/searchBarInvariants";+import {+ EVAL_LOGS_FIELD_REGISTRY,+ LEGACY_EVALUATORS_FIELD_REGISTRY,+} from "./tableSearchRegistry";++for (const registry of [+ LEGACY_EVALUATORS_FIELD_REGISTRY,+ EVAL_LOGS_FIELD_REGISTRY,+]) {+ it(`${registry.id} preserves facet filters through validation and lowering`, () => {+ expect(+ runSearchBarInvariants({+ name: registry.id,+ registry,+ extraKeys: ["metadata.region", "scores.quality"],+ scoreContexts: [],+ fieldValues: [+ "ACTIVE",+ "ERROR",+ "EVENT",+ "NEW",+ "HISTORIC",+ "example trace",+ ],+ freeTextValues: ["answer quality"],+ }),+ ).toEqual([]);+ });+}++describe("legacy evaluator search lanes", () => {+ it("keeps score and rule name search separate from structured filters", () => {+ expect(+ planCommit(+ "quality status:ACTIVE",+ undefined,+ LEGACY_EVALUATORS_FIELD_REGISTRY,+ ),+ ).toMatchObject({+ status: "committed",+ searchQuery: "quality",+ filters: [+ {+ column: "status",+ type: "stringOptions",+ operator: "any of",+ value: ["ACTIVE"],+ },+ ],+ });+ });++ it("lowers log searches into the supported trace ID filter", () => {+ expect(+ planCommit("example trace", undefined, EVAL_LOGS_FIELD_REGISTRY),+ ).toMatchObject({+ status: "committed",+ searchQuery: null,+ filters: [+ {+ column: "traceId",+ type: "string",+ operator: "contains",+ value: "example trace",+ },+ ],+ });+ });+});diff --git a/web/src/features/evals/constants/tableSearchRegistry.ts b/web/src/features/evals/constants/tableSearchRegistry.tsnew file mode 100644index 0000000000..a614ecc144--- /dev/null+++ b/web/src/features/evals/constants/tableSearchRegistry.ts@@ -0,0 +1,31 @@+import type { FilterConfig } from "@/src/features/filters/lib/filter-config";+import { evaluatorFilterConfig } from "@/src/features/filters/config/evaluators-config";+import { evalLogFilterConfig } from "@/src/features/filters/config/eval-logs-config";+import { fieldRegistryFromColumns } from "@/src/features/search-bar/lib/fields";++function facetColumns(config: FilterConfig) {+ const exposed = new Set(config.facets.map((facet) => facet.column));+ return config.columnDefinitions.filter((column) => exposed.has(column.id));+}++export const LEGACY_EVALUATORS_FIELD_REGISTRY = fieldRegistryFromColumns(+ facetColumns(evaluatorFilterConfig),+ {+ id: "legacyEvaluators",+ allowFreeText: true,+ freeTextScopeLabel: "score and rule names",+ searchExamples: ["quality", "status:ACTIVE", "target:EVENT"],+ recentSearches: true,+ },+);++export const EVAL_LOGS_FIELD_REGISTRY = fieldRegistryFromColumns(+ facetColumns(evalLogFilterConfig),+ {+ id: "evalLogs",+ allowFreeText: false,+ defaultTextField: "traceId",+ searchExamples: ["status:ERROR", "traceId:example-trace"],+ recentSearches: true,+ },+);diff --git a/web/src/features/evals/v2/components/Rules/RulesTable/RulesTable.tsx b/web/src/features/evals/v2/components/Rules/RulesTable/RulesTable.tsxindex a80ff47e0c..b41935961b 100644--- a/web/src/features/evals/v2/components/Rules/RulesTable/RulesTable.tsx+++ b/web/src/features/evals/v2/components/Rules/RulesTable/RulesTable.tsx@@ -1,4 +1,4 @@-import { useMemo, useState } from "react";+import { useMemo, useRef, useState } from "react";import { formatDistanceToNowStrict } from "date-fns";import { Copy, ExternalLink, MoreVertical, Pencil, Trash2 } from "lucide-react";import { useRouter } from "next/router";@@ -58,11 +58,14 @@ import {getRuleNavigationUrl,} from "@/src/features/evals/v2/utils/ruleNavigation";import { ruleExecutionsUrl } from "@/src/features/evals/v2/fns/rules/ruleExecutionsUrl";-import { TableViewPresetTableName } from "@langfuse/shared";+import { TableViewPresetTableName, type OrderByState } from "@langfuse/shared";import {omitFilterFacets,useSidebarFilterState,} from "@/src/features/filters";+import { TableSearchBar } from "@/src/features/search-bar/components/TableSearchBar";+import { toObservedOptions } from "@/src/features/search-bar/lib/observed-options";+import { evaluationRulesListFieldRegistry } from "@/src/features/evals/v2/constants/tableSearchRegistry";import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";import {evaluationRuleTableFilterColumns,@@ -164,11 +167,22 @@ export function RulesTable({),[filterOptionsQuery.data?.hasUpgradeRequired],);+ const viewControllersRef = useRef<Pick<+ ReturnType<typeof useTableViewManager>,+ "handleUserStateChange"+ > | null>(null);const queryFilter = useSidebarFilterState(filterConfig, filterOptions, {loading: filterOptionsQuery.isPending,stateLocation: "urlAndSessionStorage",sessionFilterContextId: projectId,- onExplicitFilterStateChange: () => {+ onExplicitFilterStateChange: (change) => {+ if (change.origin === "user") {+ viewControllersRef.current?.handleUserStateChange(+ change.previousFilters,+ change.nextFilters,+ { force: change.action === "clear" },+ );+ }setPagination({ page: 1, limit: pagination.limit });selectionStore.getState().actions.clearSelection();},@@ -513,29 +527,65 @@ export function RulesTable({currentFilterState: queryFilter.explicitFilterState,currentExpandedFilters: queryFilter.expanded,});+ viewControllersRef.current = viewControllers;++ const handleSearchChange = (query: string | null) => {+ viewControllers.handleUserStateChange(searchQuery ?? "", query ?? "");+ setSearchQuery(query);+ setPagination({ page: 1, limit: pagination.limit });+ selectionActions.clearSelection();+ };+ const handleOrderByChange = (next: OrderByState) => {+ viewControllers.handleUserStateChange(orderBy, next);+ setOrderBy(next);+ setPagination({ page: 1, limit: pagination.limit });+ selectionActions.clearSelection();+ };+ const handleColumnOrderChange: typeof setColumnOrder = (updater) => {+ const next = typeof updater === "function" ? updater(columnOrder) : updater;+ viewControllers.handleUserStateChange(columnOrder, next);+ setColumnOrder(next);+ };+ const handleColumnVisibilityChange: typeof setColumnVisibility = (+ updater,+ ) => {+ const next =+ typeof updater === "function" ? updater(columnVisibility) : updater;+ viewControllers.handleUserStateChange(columnVisibility, next);+ setColumnVisibility(next);+ };return (<DataTableControlsProvidertableName={evaluationRuleTableFilterConfig.tableName}><div className="flex h-full min-h-0 w-full min-w-0 flex-1 flex-col overflow-hidden">+ <TableSearchBar+ key={`${viewControllers.filterEditorResetKey}:${queryFilter.draftResetKey}`}+ projectId={projectId}+ tableName={filterConfig.tableName}+ registry={evaluationRulesListFieldRegistry(filterConfig)}+ filterState={queryFilter.searchBarFilterState}+ setFilterState={queryFilter.setFilterState}+ observed={toObservedOptions(+ filterOptions,+ filterOptionsQuery.isPending,+ )}+ search={{ query: searchQuery ?? null, setQuery: handleSearchChange }}+ isV4={false}+ /><RulesTableToolbarcolumns={columns}- currentQuery={searchQuery ?? undefined}- onSearchChange={(query) => {- setSearchQuery(query || null);- setPagination({ page: 1, limit: pagination.limit });- selectionActions.clearSelection();- }}+ currentQuery={searchQuery ?? ""}pageRowIds={rules.data?.rules.map(({ id }) => id) ?? []}pageSize={pagination.limit}pageIndex={pagination.page - 1}totalCount={rules.data?.totalItems ?? null}selectionStore={selectionStore}columnVisibility={columnVisibility}- setColumnVisibility={setColumnVisibility}+ setColumnVisibility={handleColumnVisibilityChange}columnOrder={columnOrder}- setColumnOrder={setColumnOrder}+ setColumnOrder={handleColumnOrderChange}rowHeight={rowHeight}setRowHeight={setRowHeight}filterState={filterState}@@ -548,7 +598,7 @@ export function RulesTable({/><ResizableFilterLayout><DataTableControls- key={viewControllers.selectedViewId ?? "no-view"}+ key={`${viewControllers.filterEditorResetKey}:${queryFilter.draftResetKey}`}queryFilter={queryFilter}/><div className="flex min-h-0 flex-1 flex-col overflow-hidden">@@ -572,16 +622,12 @@ export function RulesTable({}selectionStore={selectionStore}columnVisibility={columnVisibility}- onColumnVisibilityChange={setColumnVisibility}+ onColumnVisibilityChange={handleColumnVisibilityChange}columnOrder={columnOrder}- onColumnOrderChange={setColumnOrder}+ onColumnOrderChange={handleColumnOrderChange}rowHeight={rowHeight}orderBy={orderBy}- setOrderBy={(nextOrderBy) => {- setOrderBy(nextOrderBy);- setPagination({ page: 1, limit: pagination.limit });- selectionActions.clearSelection();- }}+ setOrderBy={handleOrderByChange}pagination={{totalCount: rules.data?.totalItems ?? null,state: {diff --git a/web/src/features/evals/v2/components/Rules/RulesTable/components/RulesTableToolbar/RulesTableToolbar.tsx b/web/src/features/evals/v2/components/Rules/RulesTable/components/RulesTableToolbar/RulesTableToolbar.tsxindex b15cad7fde..3edd9f1773 100644--- a/web/src/features/evals/v2/components/Rules/RulesTable/components/RulesTableToolbar/RulesTableToolbar.tsx+++ b/web/src/features/evals/v2/components/Rules/RulesTable/components/RulesTableToolbar/RulesTableToolbar.tsx@@ -13,7 +13,6 @@ import type { FilterState, OrderByState } from "@langfuse/shared";export function RulesTableToolbar({columns,currentQuery,- onSearchChange,pageRowIds,pageSize,pageIndex,@@ -31,7 +30,6 @@ export function RulesTableToolbar({}: {columns: LangfuseColumnDef<RuleTableRow>[];currentQuery: string | undefined;- onSearchChange: (query: string) => void;pageRowIds: string[];pageSize: number;pageIndex: number;@@ -60,12 +58,6 @@ export function RulesTableToolbar({orderByState={orderByState}currentSearchQuery={currentQuery}viewConfig={viewConfig}- searchConfig={{- metadataSearchFields: ["Name"],- currentQuery,- tableAllowsFullTextSearch: false,- updateQuery: onSearchChange,- }}multiSelect={{selectAll,setSelectAll: selectionActions.setSelectAll,diff --git a/web/src/features/evals/v2/constants/tableSearchRegistry.clienttest.ts b/web/src/features/evals/v2/constants/tableSearchRegistry.clienttest.tsnew file mode 100644index 0000000000..906a583849--- /dev/null+++ b/web/src/features/evals/v2/constants/tableSearchRegistry.clienttest.ts@@ -0,0 +1,166 @@+// @vitest-environment node++import { describe, expect, it } from "vitest";+import type { FilterState } from "@langfuse/shared";+import { planCommit } from "@/src/features/search-bar/lib/commit";+import { filterStateToQueryText } from "@/src/features/search-bar/lib/filter-state-to-query";+import { runSearchBarInvariants } from "@/src/features/search-bar/lib/searchBarInvariants";+import { validateQuery } from "@/src/features/search-bar/lib/validate";+import { evaluationRuleTableFilterConfig } from "./tableFilterColumns";+import {+ EVALUATORS_LIST_FIELD_REGISTRY,+ evaluationRulesListFieldRegistry,+} from "./tableSearchRegistry";++const rulesRegistry = evaluationRulesListFieldRegistry(+ evaluationRuleTableFilterConfig,+);++for (const registry of [EVALUATORS_LIST_FIELD_REGISTRY, rulesRegistry]) {+ describe(`${registry.id} search contract`, () => {+ it.each(["has:name", "-has:creator"])(+ "rejects presence filters unsupported by the list API: %s",+ (query) => {+ expect(planCommit(query, undefined, registry).status).toBe("invalid");+ },+ );++ it("keeps bare name searches in the existing search lane", () => {+ expect(planCommit("answer quality", undefined, registry)).toMatchObject({+ status: "committed",+ filters: [],+ searchQuery: "answer quality",+ });+ });++ it("preserves categorical exact matches alongside substring filters", () => {+ expect(+ planCommit("name:=quality creator:API", undefined, registry),+ ).toMatchObject({+ status: "committed",+ filters: [+ {+ type: "stringOptions",+ column: "name",+ operator: "any of",+ value: ["quality"],+ },+ {+ type: "string",+ column: "creator",+ operator: "contains",+ value: "API",+ },+ ],+ });+ });++ it("satisfies validation, lowering and saved-filter round trips", () => {+ const sidebarFilters: FilterState[] = [+ [+ {+ type: "stringOptions",+ column: "name",+ operator: "any of",+ value: ["answer quality"],+ },+ ],+ [+ {+ type: "stringOptions",+ column: "creator",+ operator: "none of",+ value: ["API", "Reviewer"],+ },+ ],+ ];+ expect(+ runSearchBarInvariants({+ name: registry.id,+ registry,+ extraKeys: ["metadata.region", "scores.quality"],+ scoreContexts: [],+ fieldValues: [+ "ACTIVE",+ "CODE",+ "LLM_AS_JUDGE",+ "true",+ "false",+ "API",+ "answer quality",+ "unknown",+ ],+ freeTextValues: ["answer quality", "quality"],+ sidebarFilters,+ }),+ ).toEqual([]);+ });+ });+}++describe("evaluator list enums", () => {+ it.each([+ "status:unknown",+ "status:(ACTIVE OR unknown)",+ "-type:unknown",+ "status:*ACT*",+ "type:CO*",+ ])("rejects unsupported enum values in %s", (query) => {+ expect(+ validateQuery(query, undefined, EVALUATORS_LIST_FIELD_REGISTRY).valid,+ ).toBe(false);+ expect(+ planCommit(query, undefined, EVALUATORS_LIST_FIELD_REGISTRY).status,+ ).toBe("invalid");+ });++ it("round-trips canonical enums", () => {+ expect(+ planCommit(+ "status:ACTIVE type:CODE",+ undefined,+ EVALUATORS_LIST_FIELD_REGISTRY,+ ),+ ).toMatchObject({+ status: "committed",+ filters: [+ {+ type: "stringOptions",+ column: "status",+ operator: "any of",+ value: ["ACTIVE"],+ },+ {+ type: "stringOptions",+ column: "type",+ operator: "any of",+ value: ["CODE"],+ },+ ],+ });+ });+});++describe("rule list facet scope", () => {+ it("preserves hidden upgrade filters while rejecting new hidden-field tokens", () => {+ const registry = evaluationRulesListFieldRegistry({+ ...evaluationRuleTableFilterConfig,+ facets: evaluationRuleTableFilterConfig.facets.filter(+ (facet) => facet.column !== "upgradeRequired",+ ),+ });+ const filters: FilterState = [+ {+ type: "boolean",+ column: "upgradeRequired",+ operator: "=",+ value: true,+ },+ ];+ const projection = filterStateToQueryText(filters, {}, registry);+ expect(projection.skippedFilters).toEqual(filters);+ expect(planCommit("upgradeRequired:true", undefined, registry).status).toBe(+ "invalid",+ );+ });+});diff --git a/web/src/features/evals/v2/constants/tableSearchRegistry.ts b/web/src/features/evals/v2/constants/tableSearchRegistry.tsnew file mode 100644index 0000000000..bbe02ddc6e--- /dev/null+++ b/web/src/features/evals/v2/constants/tableSearchRegistry.ts@@ -0,0 +1,70 @@+import type { FilterConfig } from "@/src/features/filters/lib/filter-config";+import type { FilterState } from "@langfuse/shared";+import {+ fieldRegistryFromColumns,+ withFieldOptions,+} from "@/src/features/search-bar/lib/fields";+import {+ evaluatorTableFilterConfig,+ evaluatorTableFilterOptions,+} from "./tableFilterColumns";++function facetColumns(config: FilterConfig) {+ const exposed = new Set(config.facets.map((facet) => facet.column));+ return config.columnDefinitions.filter((column) => exposed.has(column.id));+}++const NAME_AND_CREATOR_FIELDS = {+ name: { syncMode: "textSearch", suggestObservedValues: true },+ creator: { syncMode: "textSearch", suggestObservedValues: true },+} as const;++function presenceFilterErrors(filters: FilterState): string[] {+ return filters.some((filter) => filter.type === "null")+ ? [+ "This list does not support presence filters. Enter a field value instead.",+ ]+ : [];+}++const evaluatorsRegistry = fieldRegistryFromColumns(+ facetColumns(evaluatorTableFilterConfig),+ {+ id: "evaluatorsList",+ filterStateErrors: presenceFilterErrors,+ fields: {+ ...NAME_AND_CREATOR_FIELDS,+ status: { filterColumn: "status" },+ type: { filterColumn: "type" },+ model: { syncMode: "textSearch", suggestObservedValues: true },+ },+ allowFreeText: true,+ freeTextScopeLabel: "evaluator names",+ searchExamples: ["quality", "status:ACTIVE", "type:CODE"],+ recentSearches: true,+ },+);++// Status and type are closed enums in the list API. Keep their canonical values+// in query text while using the same adapter gate as other labeled options.+export const EVALUATORS_LIST_FIELD_REGISTRY = withFieldOptions(+ withFieldOptions(+ evaluatorsRegistry,+ "status",+ evaluatorTableFilterOptions.status.map(({ value }) => ({ value })),+ ),+ "type",+ evaluatorTableFilterOptions.type.map(({ value }) => ({ value })),+);++export function evaluationRulesListFieldRegistry(config: FilterConfig) {+ return fieldRegistryFromColumns(facetColumns(config), {+ id: "evaluationRulesList",+ filterStateErrors: presenceFilterErrors,+ fields: NAME_AND_CREATOR_FIELDS,+ allowFreeText: true,+ freeTextScopeLabel: "rule names",+ searchExamples: ["quality", "enabled:true", "creator:API"],+ recentSearches: true,+ });+}diff --git a/web/src/features/evals/v2/pages/EvaluatorsPage.tsx b/web/src/features/evals/v2/pages/EvaluatorsPage.tsxindex a968d72f2d..9dc2104822 100644--- a/web/src/features/evals/v2/pages/EvaluatorsPage.tsx+++ b/web/src/features/evals/v2/pages/EvaluatorsPage.tsx@@ -7,7 +7,7 @@ import {} from "@langfuse/shared";import { Plus, Trash2 } from "lucide-react";import { useRouter } from "next/router";-import { type ComponentProps, useMemo, useState } from "react";+import { type ComponentProps, useMemo, useRef, useState } from "react";import { StringParam, useQueryParam, withDefault } from "use-query-params";import { useStore } from "zustand";import Page from "@/src/components/layouts/page";@@ -42,6 +42,9 @@ import { useEvaluatorAlerts } from "@/src/features/evals/v2/hooks/useEvaluatorAlimport { TableSelectionManager } from "@/src/features/table/components/TableSelectionManager";import { usePaginationState } from "@/src/hooks/usePaginationState";import { useSidebarFilterState } from "@/src/features/filters";+import { TableSearchBar } from "@/src/features/search-bar/components/TableSearchBar";+import { toObservedOptions } from "@/src/features/search-bar/lib/observed-options";+import { EVALUATORS_LIST_FIELD_REGISTRY } from "../constants/tableSearchRegistry";import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";import {createEvaluatorsTableStore,@@ -233,11 +236,22 @@ export default function EvaluatorsPage() {}),[projectDefaultModel.defaultModel?.model],);+ const viewControllersRef = useRef<Pick<+ ReturnType<typeof useTableViewManager>,+ "handleUserStateChange"+ > | null>(null);const queryFilter = useSidebarFilterState(filterConfig, filterOptions, {loading: filterOptionsQuery.isPending,stateLocation: "urlAndSessionStorage",sessionFilterContextId: projectId,- onExplicitFilterStateChange: () => {+ onExplicitFilterStateChange: (change) => {+ if (change.origin === "user") {+ viewControllersRef.current?.handleUserStateChange(+ change.previousFilters,+ change.nextFilters,+ { force: change.action === "clear" },+ );+ }setPagination({ page: 1, limit: pagination.limit });selectionStore.getState().actions.clearSelection();},@@ -575,6 +589,31 @@ export default function EvaluatorsPage() {currentFilterState: queryFilter.explicitFilterState,currentExpandedFilters: queryFilter.expanded,});+ viewControllersRef.current = viewControllers;++ const handleSearchChange = (query: string | null) => {+ viewControllers.handleUserStateChange(searchQuery ?? "", query ?? "");+ setSearchQuery(query);+ setPagination({ page: 1, limit: pagination.limit });+ selectionStore.getState().actions.clearSelection();+ };+ const handleOrderByChange = (next: OrderByState) => {+ viewControllers.handleUserStateChange(orderBy, next);+ setEvaluatorOrderBy(next);+ };+ const handleColumnOrderChange: typeof setColumnOrder = (updater) => {+ const next = typeof updater === "function" ? updater(columnOrder) : updater;+ viewControllers.handleUserStateChange(columnOrder, next);+ setColumnOrder(next);+ };+ const handleColumnVisibilityChange: typeof setColumnVisibility = (+ updater,+ ) => {+ const next =+ typeof updater === "function" ? updater(columnVisibility) : updater;+ viewControllers.handleUserStateChange(columnVisibility, next);+ setColumnVisibility(next);+ };return (<Page@@ -660,6 +699,23 @@ export default function EvaluatorsPage() {) : (<DataTableControlsProvider tableName={filterConfig.tableName}><div className="flex h-full min-h-0 w-full flex-1 flex-col overflow-hidden">+ <TableSearchBar+ key={`${viewControllers.filterEditorResetKey}:${queryFilter.draftResetKey}`}+ projectId={projectId}+ tableName={filterConfig.tableName}+ registry={EVALUATORS_LIST_FIELD_REGISTRY}+ filterState={queryFilter.searchBarFilterState}+ setFilterState={queryFilter.setFilterState}+ observed={toObservedOptions(+ filterOptions,+ filterOptionsQuery.isPending,+ )}+ search={{+ query: searchQuery ?? null,+ setQuery: handleSearchChange,+ }}+ isV4={false}+ /><EvaluatorsTableToolbarselectionStore={selectionStore}pageRowIds={evaluatorIds}@@ -668,33 +724,23 @@ export default function EvaluatorsPage() {totalCount={evaluators.data?.totalItems ?? null}columns={columns}columnVisibility={columnVisibility}- setColumnVisibility={setColumnVisibility}+ setColumnVisibility={handleColumnVisibilityChange}columnOrder={columnOrder}- setColumnOrder={setColumnOrder}+ setColumnOrder={handleColumnOrderChange}rowHeight={rowHeight}setRowHeight={setRowHeight}filterState={filterState}orderByState={orderBy}- currentSearchQuery={searchQuery ?? undefined}+ currentSearchQuery={searchQuery ?? ""}viewConfig={{tableName: TableViewPresetTableName.Evaluators,projectId,controllers: viewControllers,}}- searchConfig={{- metadataSearchFields: ["Name"],- updateQuery: (query) => {- setSearchQuery(query || null);- setPagination({ page: 1, limit: pagination.limit });- selectionStore.getState().actions.clearSelection();- },- currentQuery: searchQuery ?? undefined,- tableAllowsFullTextSearch: false,- }}/><ResizableFilterLayout><DataTableControls- key={viewControllers.selectedViewId ?? "no-view"}+ key={`${viewControllers.filterEditorResetKey}:${queryFilter.draftResetKey}`}queryFilter={queryFilter}/><div className="flex min-h-0 flex-1 flex-col overflow-hidden">@@ -738,12 +784,12 @@ export default function EvaluatorsPage() {}}selectionStore={selectionStore}columnVisibility={columnVisibility}- onColumnVisibilityChange={setColumnVisibility}+ onColumnVisibilityChange={handleColumnVisibilityChange}columnOrder={columnOrder}- onColumnOrderChange={setColumnOrder}+ onColumnOrderChange={handleColumnOrderChange}rowHeight={rowHeight}orderBy={orderBy}- setOrderBy={setEvaluatorOrderBy}+ setOrderBy={handleOrderByChange}onRowClick={(row) =>router.push(`/project/${projectId}/evals/${row.id}`)}diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsxindex 3290d5c3e1..fe7401fbaf 100644--- a/web/src/features/events/components/EventsTable.tsx+++ b/web/src/features/events/components/EventsTable.tsx@@ -1,3 +1,6 @@+import { eventsSearchRegistry } from "../config/eventsSearchRegistry";+import { useEventsTableSearch } from "../hooks/useEventsTableSearch";+import { SearchScopeSelect } from "@/src/components/table/SearchScopeSelect";import { DataTable } from "@/src/components/table/data-table";import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";import {@@ -53,11 +56,11 @@ import { createTextTableColumn } from "@/src/components/design-system/table/coluimport { type LangfuseColumnDef } from "@/src/components/table/types";import {buildAiContext,+ DEFAULT_SEARCH_TYPE,EventsSearchBarRow,filterStateToQueryText,observedScoreNamesFromOptions,toObservedOptions,- useEventsSearchBar,useSearchBarEnabled,withMetadataPathOptions,} from "@/src/features/search-bar";@@ -322,6 +325,9 @@ export default function ObservationsEventsTable({const tableStatePolicy = getEventsTableStatePolicy({hideControls,isolateTableState,+ hasParentScope: Boolean(+ peekContext || userId || sessionId || promptName || promptVersion,+ ),});const searchQuery = tableStatePolicy.useIsolatedSearch? isolatedSearchQuery@@ -516,6 +522,9 @@ export default function ObservationsEventsTable({ReturnType<typeof useTableViewManager>,"selectedViewId" | "handleSetViewId" | "handleUserStateChange"> | null>(null);+ const resetSearchBarDraftRef = useRef<+ ((filters: FilterState) => void) | null+ >(null);const handleSearchQueryChange = (query: string | null) => {viewControllersRef.current?.handleUserStateChange(@@ -543,6 +552,9 @@ export default function ObservationsEventsTable({(change: ExplicitFilterStateChange) => {onAppRootExplicitFilterStateChange(change);demoteViewOnUserFilterEdit(change, viewControllersRef.current);+ if (change.origin === "user" && change.action === "clear") {+ resetSearchBarDraftRef.current?.(change.nextFilters);+ }},[onAppRootExplicitFilterStateChange],);@@ -719,17 +731,19 @@ export default function ObservationsEventsTable({// sidebar and time/refresh controls stay.const searchBarEnabled = useSearchBarEnabled();const searchBarMode =- searchBarEnabled &&- !hideControls &&- !externalFilterState &&- !peekContext &&- tableStatePolicy.allowGrammarSearch &&- // Embedded user/session-detail tables are page-scoped (a userId/sessionId- // filter is AND-combined into the query); the bar reads the full FIELDS- // registry and would let e.g. `userId:other` fight that scope. Keep it to- // full-page surfaces, matching the documented embedded opt-out.- !userId &&- !sessionId;+ searchBarEnabled && !hideControls && !externalFilterState;+ const searchRegistry = eventsSearchRegistry(+ [+ ...(eventsFilterConfig.omittedFilterColumns ?? []),+ ...(userId ? ["userId"] : []),+ ...(sessionId ? ["sessionId"] : []),+ ...(promptName ? ["promptName"] : []),+ ...(promptVersion ? ["promptVersion"] : []),+ ],+ tableStatePolicy.useHostSearchScopes,+ );+ const sidebarAiFiltersEnabled =+ !searchBarMode || !searchRegistry.aiFilterPrompt;// Create ref-based wrapper to avoid stale closure when queryFilter updatesconst queryFilterRef = useRef(queryFilter);@@ -768,10 +782,13 @@ export default function ObservationsEventsTable({store: searchBarStore,commit: searchBarCommit,applyFilters: searchBarApplyFilters,- } = useEventsSearchBar({+ resetDraft: resetSearchBarDraft,+ } = useEventsTableSearch({projectId,tableName: eventsFilterConfig.tableName,enabled: searchBarMode,+ useHostSearchScopes: tableStatePolicy.useHostSearchScopes,+ registry: searchRegistry,filterState: queryFilter.searchBarFilterState,searchQuery,searchType,@@ -780,6 +797,13 @@ export default function ObservationsEventsTable({setSearchQuery: handleSearchQueryChange,setSearchType: handleSearchTypeChange,});+ resetSearchBarDraftRef.current = (filters) => {+ resetSearchBarDraft({+ filters: projectFiltersForSearchBar(filters),+ searchQuery,+ searchType,+ });+ };// Non-destructive preview: while a category-chip preset row is hovered or// focused, show the query it would apply as the store's preview overlay. The@@ -792,14 +816,29 @@ export default function ObservationsEventsTable({const { actions } = searchBarStore.getState();if (state) {actions.setPreview(- filterStateToQueryText(projectFiltersForSearchBar(state.filters))- .text,+ filterStateToQueryText(+ projectFiltersForSearchBar(state.filters),+ {+ searchQuery: state.searchQuery,+ searchType: tableStatePolicy.useHostSearchScopes+ ? DEFAULT_SEARCH_TYPE+ : searchType,+ },+ searchRegistry,+ ).text,);} else {actions.clearPreview();}},- [searchBarMode, searchBarStore, projectFiltersForSearchBar],+ [+ searchBarMode,+ searchBarStore,+ projectFiltersForSearchBar,+ searchRegistry,+ tableStatePolicy.useHostSearchScopes,+ searchType,+ ],);// Disabled for now because perhaps confusing@@ -1615,6 +1654,12 @@ export default function ObservationsEventsTable({currentExpandedFilters: queryFilter.expanded,disabled: tableStatePolicy.disableSavedViews,allowBackendSystemPresets: true,+ onViewApplied: (viewState) =>+ resetSearchBarDraft({+ filters: projectFiltersForSearchBar(viewState.filters),+ searchQuery: viewState.searchQuery ?? null,+ searchType,+ }),});viewControllersRef.current = viewControllers;@@ -1753,6 +1798,15 @@ export default function ObservationsEventsTable({new Set((queryFilter.explicitFilterState ?? []).map((filter) => filter.column),).size + (searchQuery && searchQuery.trim().length > 0 ? 1 : 0);+ const searchScope = tableStatePolicy.useHostSearchScopes ? (+ <SearchScopeSelect+ searchType={searchType}+ setSearchType={handleSearchTypeChange}+ metadataLabel="IDs / Names"+ fullTextLabel="Full Text"+ availableSearchTypes={{ content: true, input: true, output: true }}+ />+ ) : null;return (<DataTableControlsProvider tableName={eventsFilterConfig.tableName}>@@ -1776,36 +1830,47 @@ export default function ObservationsEventsTable({onClearAll={() => {queryFilter.clearAll();handleSearchQueryChange("");+ resetSearchBarDraft({+ filters: projectFiltersForSearchBar([]),+ searchQuery: null,+ searchType,+ });}}search={searchBarMode ? (- <EventsSearchBarRow- projectId={projectId}- tableName={eventsFilterConfig.tableName}- store={searchBarStore}- commit={searchBarCommit}- observed={observedOptions}- erroredColumns={erroredColumns}- fieldReason={- chartActive ? chartSearchFieldReason : undefined- }- freeTextReason={- chartFreeTextIgnored- ? CHART_SEARCH_QUERY_REASON- : undefined- }- onApplyFilters={searchBarApplyFilters}- onRequestColumns={requestColumns}- aiDataContext={aiDataContext}- aiScoreNames={aiScoreNames}- // Flush inside the sheet: the section container owns the- // padding, so the bar lines up with time range / presets.- className="p-0"- />+ <div className="flex min-w-0 flex-col gap-2">+ <EventsSearchBarRow+ key={`${viewControllers.filterEditorResetKey}-${queryFilter.draftResetKey}`}+ registry={searchRegistry}+ projectId={projectId}+ tableName={eventsFilterConfig.tableName}+ isV4={true}+ store={searchBarStore}+ commit={searchBarCommit}+ observed={observedOptions}+ erroredColumns={erroredColumns}+ fieldReason={+ chartActive ? chartSearchFieldReason : undefined+ }+ freeTextReason={+ chartFreeTextIgnored+ ? CHART_SEARCH_QUERY_REASON+ : undefined+ }+ onApplyFilters={searchBarApplyFilters}+ onRequestColumns={requestColumns}+ aiDataContext={aiDataContext}+ aiScoreNames={aiScoreNames}+ // Flush inside the sheet: the section container owns the+ // padding, so the bar lines up with time range / presets.+ className="p-0"+ />+ {searchScope && (+ <div className="flex justify-end">{searchScope}</div>+ )}+ </div>) : (- // No grammar bar (userId/sessionId-scoped tables): fall back- // to the legacy full-text search so mobile keeps the search- // desktop has via the toolbar's searchConfig (LFE-11067).+ // Externally controlled filters retain the host's search input.<MobileFullTextSearchcurrentQuery={searchQuery ?? undefined}updateQuery={handleSearchQueryChange}@@ -1870,9 +1935,9 @@ export default function ObservationsEventsTable({}facets={<DataTableControls- key={viewControllers.filterEditorResetKey}+ key={`${viewControllers.filterEditorResetKey}-${queryFilter.draftResetKey}`}queryFilter={queryFilter}- filterWithAI={!searchBarMode}+ filterWithAI={sidebarAiFiltersEnabled}blockedColumnReason={chartActive ? chartFilterExclusionReason : undefined}@@ -1908,22 +1973,34 @@ export default function ObservationsEventsTable({page header via TableHeaderControls; otherwise they remain inthe toolbar row below. */}{searchBarMode && (- <EventsSearchBarRow- projectId={projectId}- tableName={eventsFilterConfig.tableName}- store={searchBarStore}- commit={searchBarCommit}- observed={observedOptions}- erroredColumns={erroredColumns}- fieldReason={chartActive ? chartSearchFieldReason : undefined}- freeTextReason={- chartFreeTextIgnored ? CHART_SEARCH_QUERY_REASON : undefined- }- onApplyFilters={searchBarApplyFilters}- onRequestColumns={requestColumns}- aiDataContext={aiDataContext}- aiScoreNames={aiScoreNames}- />+ <div className="flex min-w-0 items-center gap-2">+ <div className="min-w-0 flex-1">+ <EventsSearchBarRow+ key={`${viewControllers.filterEditorResetKey}-${queryFilter.draftResetKey}`}+ registry={searchRegistry}+ projectId={projectId}+ tableName={eventsFilterConfig.tableName}+ isV4={true}+ store={searchBarStore}+ commit={searchBarCommit}+ observed={observedOptions}+ erroredColumns={erroredColumns}+ fieldReason={+ chartActive ? chartSearchFieldReason : undefined+ }+ freeTextReason={+ chartFreeTextIgnored+ ? CHART_SEARCH_QUERY_REASON+ : undefined+ }+ onApplyFilters={searchBarApplyFilters}+ onRequestColumns={requestColumns}+ aiDataContext={aiDataContext}+ aiScoreNames={aiScoreNames}+ />+ </div>+ {searchScope}+ </div>)}{/* Toolbar spanning full width */}<DataTableToolbar@@ -2063,9 +2140,8 @@ export default function ObservationsEventsTable({pageIndex: paginationState.page - 1,}}- // In bar mode AI filtering lives in the search bar ("Ask AI"),- // so the legacy wand is only offered when the bar is absent.- filterWithAI={!searchBarMode}+ // Scoped registries keep AI filtering in the sidebar.+ filterWithAI={sidebarAiFiltersEnabled}// Category-preset chips + "My Views" pill share the toolbar row,// left-aligned, so they sit on the same line as the right-aligned// Columns/Export controls.@@ -2111,11 +2187,9 @@ export default function ObservationsEventsTable({in the layout). */}{!hideControls && !isMobile && (<DataTableControls- key={viewControllers.filterEditorResetKey}+ key={`${viewControllers.filterEditorResetKey}-${queryFilter.draftResetKey}`}queryFilter={queryFilter}- // In bar mode AI filtering lives in the search bar; only offer the- // sidebar wand on non-bar surfaces (embedded scoped tables).- filterWithAI={!searchBarMode}+ filterWithAI={sidebarAiFiltersEnabled}// In chart mode, block filters the chart can't apply β active or// not β dimmed + hover reason. Stateless per-column resolver,// matching the search bar.diff --git a/web/src/features/events/config/eventsSearchRegistry.clienttest.ts b/web/src/features/events/config/eventsSearchRegistry.clienttest.tsnew file mode 100644index 0000000000..3b494b2640--- /dev/null+++ b/web/src/features/events/config/eventsSearchRegistry.clienttest.ts@@ -0,0 +1,94 @@+// @vitest-environment node++import { describe, expect, it } from "vitest";+import type { FilterState } from "@langfuse/shared";+import { EVENTS_FIELD_REGISTRY } from "@/src/features/search-bar/lib/fields";+import { planCommit } from "@/src/features/search-bar/lib/commit";+import { filterStateToQueryText } from "@/src/features/search-bar/lib/filter-state-to-query";+import { runSearchBarInvariants } from "@/src/features/search-bar/lib/searchBarInvariants";+import { eventsSearchRegistry } from "./eventsSearchRegistry";++describe("events search scope", () => {+ it("preserves the full-page grammar and AI capability", () => {+ expect(eventsSearchRegistry([])).toBe(EVENTS_FIELD_REGISTRY);+ });++ it("keeps remaining fields' meaning while closing host-owned fields and aliases", () => {+ const registry = eventsSearchRegistry([+ "userId",+ "sessionId",+ "promptName",+ "promptVersion",+ ]);+ expect(registry.aiFilterPrompt).toBe(false);+ for (const field of [+ "userId",+ "user_id",+ "sessionId",+ "session_id",+ "promptName",+ "promptVersion",+ ])+ expect(registry.resolveField(field)).toBeNull();+ expect(planCommit("name:checkout", undefined, registry)).toMatchObject({+ status: "committed",+ filters: [+ {+ type: "string",+ column: "name",+ operator: "contains",+ value: "checkout",+ },+ ],+ });+ expect(planCommit("name:checkout", undefined, registry)).toEqual(+ planCommit("name:checkout", undefined, EVENTS_FIELD_REGISTRY),+ );+ });++ it("preserves hidden saved conditions without rendering broken tokens", () => {+ const registry = eventsSearchRegistry(["sessionId"]);+ const hidden: FilterState = [+ {+ type: "string",+ column: "sessionId",+ operator: "=",+ value: "parent-session",+ },+ ];+ const projection = filterStateToQueryText(hidden, {}, registry);+ expect(projection.text).toBe("");+ expect(projection.skippedFilters).toEqual(hidden);+ expect(planCommit("sessionId:other", undefined, registry).status).toBe(+ "invalid",+ );+ });++ it("keeps scoped validation and lowering aligned for supported facets", () => {+ const registry = eventsSearchRegistry([+ "userId",+ "promptName",+ "promptVersion",+ ]);+ expect(+ runSearchBarInvariants({+ name: "scoped events",+ registry,+ extraKeys: ["metadata.region", "scores.quality", "has:userId"],+ scoreContexts: [],+ fieldValues: ["checkout", "ERROR", "true", "false", "0.5", "or", "a,b"],+ freeTextValues: ["refund policy", "or", "!important"],+ sidebarFilters: [+ [+ {+ type: "string",+ column: "userId",+ operator: "=",+ value: "parent-user",+ },+ ],+ ],+ }),+ ).toEqual([]);+ });+});diff --git a/web/src/features/events/config/eventsSearchRegistry.ts b/web/src/features/events/config/eventsSearchRegistry.tsnew file mode 100644index 0000000000..2fd379d136--- /dev/null+++ b/web/src/features/events/config/eventsSearchRegistry.ts@@ -0,0 +1,40 @@+import {+ createFieldRegistry,+ EVENTS_FIELD_REGISTRY,+} from "@/src/features/search-bar/lib/fields";++export function eventsSearchRegistry(+ omittedColumns: readonly string[],+ useHostSearchScopes = false,+) {+ if (omittedColumns.length === 0 && !useHostSearchScopes)+ return EVENTS_FIELD_REGISTRY;+ const omitted = new Set(omittedColumns);+ return createFieldRegistry({+ ...EVENTS_FIELD_REGISTRY,+ fields: EVENTS_FIELD_REGISTRY.fields.filter(+ (field) => !omitted.has(field.filterColumn ?? field.id),+ ),+ columns: EVENTS_FIELD_REGISTRY.columns.filter(+ (column) => !omitted.has(column.id),+ ),+ metadata: EVENTS_FIELD_REGISTRY.metadata && !omitted.has("metadata"),+ scores:+ EVENTS_FIELD_REGISTRY.scores &&+ !["scores_avg", "score_categories", "score_booleans"].some((column) =>+ omitted.has(column),+ ),+ traceScores:+ EVENTS_FIELD_REGISTRY.traceScores &&+ ![+ "trace_scores_avg",+ "trace_score_categories",+ "trace_score_booleans",+ ].some((column) => omitted.has(column)),+ freeTextScopeLabel: useHostSearchScopes+ ? "the selected search scope"+ : EVENTS_FIELD_REGISTRY.freeTextScopeLabel,+ // A scoped registry cannot use the full events AI vocabulary.+ aiFilterPrompt: omittedColumns.length === 0,+ });+}diff --git a/web/src/features/events/hooks/useEventsTableSearch.clienttest.tsx b/web/src/features/events/hooks/useEventsTableSearch.clienttest.tsxnew file mode 100644index 0000000000..d839baebac--- /dev/null+++ b/web/src/features/events/hooks/useEventsTableSearch.clienttest.tsx@@ -0,0 +1,75 @@+import { act, renderHook } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import type { TracingSearchType } from "@langfuse/shared";+import { eventsSearchRegistry } from "../config/eventsSearchRegistry";+import { useEventsTableSearch } from "./useEventsTableSearch";++describe("embedded events search scopes", () => {+ it.each<TracingSearchType[]>([+ ["id"],+ ["id", "input"],+ ["id", "output"],+ ["content"],+ ])(+ "keeps the host scope %j when a phrase or another facet is edited",+ (...scope) => {+ const setSearchType = vi.fn();+ const setSearchQuery = vi.fn();+ const setFilterState = vi.fn();+ const { result } = renderHook(() =>+ useEventsTableSearch({+ projectId: "p",+ tableName: "observations-events",+ enabled: true,+ useHostSearchScopes: true,+ registry: eventsSearchRegistry(["sessionId"]),+ filterState: [],+ searchQuery: "refund",+ searchType: scope,+ observed: undefined,+ setFilterState,+ setSearchQuery,+ setSearchType,+ }),+ );+ expect(result.current.store.getState().draft).toBe("refund ");+ act(() =>+ result.current.store.getState().actions.setDraft("refund level:ERROR"),+ );+ act(() => result.current.commit("enter"));+ expect(setSearchType).not.toHaveBeenCalled();+ expect(setSearchQuery).toHaveBeenCalledWith("refund");+ expect(setFilterState).toHaveBeenCalledWith([+ {+ type: "stringOptions",+ column: "level",+ operator: "any of",+ value: ["ERROR"],+ },+ ]);+ },+ );++ it("keeps the full-page grammar's original full-text default", () => {+ const setSearchType = vi.fn();+ const { result } = renderHook(() =>+ useEventsTableSearch({+ projectId: "p",+ tableName: "observations-events",+ enabled: true,+ useHostSearchScopes: false,+ registry: eventsSearchRegistry([]),+ filterState: [],+ searchQuery: null,+ searchType: ["id"],+ observed: undefined,+ setFilterState: vi.fn(),+ setSearchQuery: vi.fn(),+ setSearchType,+ }),+ );+ act(() => result.current.store.getState().actions.setDraft("refund"));+ act(() => result.current.commit("enter"));+ expect(setSearchType).toHaveBeenCalledWith(["id", "content"]);+ });+});diff --git a/web/src/features/events/hooks/useEventsTableSearch.ts b/web/src/features/events/hooks/useEventsTableSearch.tsnew file mode 100644index 0000000000..e79dc53770--- /dev/null+++ b/web/src/features/events/hooks/useEventsTableSearch.ts@@ -0,0 +1,36 @@+import type { FilterState, TracingSearchType } from "@langfuse/shared";+import { useEventsSearchBar } from "@/src/features/search-bar/hooks/useEventsSearchBar";+import { DEFAULT_SEARCH_TYPE } from "@/src/features/search-bar/lib/commit";++const preserveHostSearchScope = () => {};++export function useEventsTableSearch({+ useHostSearchScopes,+ ...options+}: Parameters<typeof useEventsSearchBar>[0] & {+ useHostSearchScopes: boolean;+}) {+ const searchBar = useEventsSearchBar({+ ...options,+ searchType: useHostSearchScopes ? DEFAULT_SEARCH_TYPE : options.searchType,+ analyticsSearchType: useHostSearchScopes+ ? options.searchType+ : options.analyticsSearchType,+ setSearchType: useHostSearchScopes+ ? preserveHostSearchScope+ : options.setSearchType,+ });++ const resetDraft = (state: {+ filters: FilterState;+ searchQuery: string | null;+ searchType: TracingSearchType[];+ }) => {+ searchBar.resetDraft({+ ...state,+ searchType: useHostSearchScopes ? DEFAULT_SEARCH_TYPE : state.searchType,+ });+ };++ return { ...searchBar, resetDraft };+}diff --git a/web/src/features/events/lib/demoteViewOnUserFilterEdit.ts b/web/src/features/events/lib/demoteViewOnUserFilterEdit.tsindex 8482853214..6a825ad63a 100644--- a/web/src/features/events/lib/demoteViewOnUserFilterEdit.ts+++ b/web/src/features/events/lib/demoteViewOnUserFilterEdit.ts@@ -7,13 +7,18 @@ export type ViewDemotionControllers = {viewId: string | null,options?: { updateType?: UrlUpdateType },) => void;- handleUserStateChange: (previousValue: unknown, nextValue: unknown) => void;+ handleUserStateChange: (+ previousValue: unknown,+ nextValue: unknown,+ options?: { force?: boolean },+ ) => void;};export type ExplicitFilterStateChange = {previousFilters: FilterState;nextFilters: FilterState;origin: "user" | "saved_view" | "system";+ action?: "clear";};/** User edits leave the selected view; view application and reconciliation do not. */@@ -25,5 +30,6 @@ export function demoteViewOnUserFilterEdit(controllers?.handleUserStateChange(change.previousFilters,change.nextFilters,+ { force: change.action === "clear" },);}diff --git a/web/src/features/events/lib/eventsTableStatePolicy.clienttest.ts b/web/src/features/events/lib/eventsTableStatePolicy.clienttest.tsindex feec1790ac..18c49de4d7 100644--- a/web/src/features/events/lib/eventsTableStatePolicy.clienttest.ts+++ b/web/src/features/events/lib/eventsTableStatePolicy.clienttest.ts@@ -8,12 +8,13 @@ describe("getEventsTableStatePolicy", () => {getEventsTableStatePolicy({hideControls: false,isolateTableState: true,+ hasParentScope: true,}),).toEqual({filterStateLocation: "memory",useIsolatedSearch: true,- allowGrammarSearch: false,disableSavedViews: true,+ useHostSearchScopes: true,});});@@ -22,12 +23,13 @@ describe("getEventsTableStatePolicy", () => {getEventsTableStatePolicy({hideControls: false,isolateTableState: false,+ hasParentScope: false,}),).toEqual({filterStateLocation: "urlAndSessionStorage",useIsolatedSearch: false,- allowGrammarSearch: true,disableSavedViews: false,+ useHostSearchScopes: false,});});@@ -36,12 +38,28 @@ describe("getEventsTableStatePolicy", () => {getEventsTableStatePolicy({hideControls: true,isolateTableState: false,+ hasParentScope: false,}),).toEqual({filterStateLocation: "memory",useIsolatedSearch: false,- allowGrammarSearch: true,disableSavedViews: true,+ useHostSearchScopes: false,+ });+ });++ it("preserves parent-page search scopes without changing URL-backed filters", () => {+ expect(+ getEventsTableStatePolicy({+ hideControls: false,+ isolateTableState: false,+ hasParentScope: true,+ }),+ ).toEqual({+ filterStateLocation: "urlAndSessionStorage",+ useIsolatedSearch: false,+ disableSavedViews: false,+ useHostSearchScopes: true,});});});diff --git a/web/src/features/events/lib/eventsTableStatePolicy.ts b/web/src/features/events/lib/eventsTableStatePolicy.tsindex 7d846b97ed..81d23fcd71 100644--- a/web/src/features/events/lib/eventsTableStatePolicy.ts+++ b/web/src/features/events/lib/eventsTableStatePolicy.ts@@ -1,20 +1,22 @@export type EventsTableStatePolicy = {filterStateLocation: "memory" | "urlAndSessionStorage";useIsolatedSearch: boolean;- allowGrammarSearch: boolean;disableSavedViews: boolean;+ useHostSearchScopes: boolean;};export const getEventsTableStatePolicy = ({hideControls,isolateTableState,+ hasParentScope,}: {hideControls: boolean;isolateTableState: boolean;+ hasParentScope: boolean;}): EventsTableStatePolicy => ({filterStateLocation:hideControls || isolateTableState ? "memory" : "urlAndSessionStorage",useIsolatedSearch: isolateTableState,- allowGrammarSearch: !isolateTableState,disableSavedViews: hideControls || isolateTableState,+ useHostSearchScopes: isolateTableState || hasParentScope,});diff --git a/web/src/features/events/presetDemotionOnUserEdit.clienttest.tsx b/web/src/features/events/presetDemotionOnUserEdit.clienttest.tsxindex b8f8d4db9f..4f2b192df4 100644--- a/web/src/features/events/presetDemotionOnUserEdit.clienttest.tsx+++ b/web/src/features/events/presetDemotionOnUserEdit.clienttest.tsx@@ -12,6 +12,8 @@ import {type TableViewPresetState,} from "@langfuse/shared";import { useCallback, useRef } from "react";+import { useStore } from "zustand";+import { useEventsTableSearch } from "./hooks/useEventsTableSearch";import {type FilterConfig,useSidebarFilterState,@@ -207,6 +209,9 @@ const storedViewId = () => {function Harness({ projectId = PROJECT_ID }: { projectId?: string }) {const viewControllersRef = useRef<ViewDemotionControllers | null>(null);const [orderBy, setOrderBy] = useOrderByState(null);+ const resetSearchDraftRef = useRef<((filters: FilterState) => void) | null>(+ null,+ );const queryFilter = useSidebarFilterState(TEST_FILTER_CONFIG,@@ -214,8 +219,12 @@ function Harness({ projectId = PROJECT_ID }: { projectId?: string }) {{stateLocation: "urlAndSessionStorage",sessionFilterContextId: projectId,- onExplicitFilterStateChange: (change) =>- demoteViewOnUserFilterEdit(change, viewControllersRef.current),+ onExplicitFilterStateChange: (change) => {+ demoteViewOnUserFilterEdit(change, viewControllersRef.current);+ if (change.origin === "user" && change.action === "clear") {+ resetSearchDraftRef.current?.(change.nextFilters);+ }+ },},);@@ -226,6 +235,26 @@ function Harness({ projectId = PROJECT_ID }: { projectId?: string }) {queryFilterRef.current.setFilterState(filters, { origin: "saved_view" }),[],);+ const searchBar = useEventsTableSearch({+ projectId,+ tableName: "observations-events",+ enabled: true,+ useHostSearchScopes: false,+ filterState: queryFilter.searchBarFilterState,+ searchQuery: null,+ searchType: ["id", "content"],+ observed: undefined,+ setFilterState: queryFilter.setFilterState,+ setSearchQuery: () => {},+ setSearchType: () => {},+ });+ const searchDraft = useStore(searchBar.store, (state) => state.draft);+ resetSearchDraftRef.current = (filters) =>+ searchBar.resetDraft({+ filters: queryFilter.projectFiltersForSearchBar(filters),+ searchQuery: null,+ searchType: ["id", "content"],+ });const {selectedViewId,@@ -250,6 +279,12 @@ function Harness({ projectId = PROJECT_ID }: { projectId?: string }) {},currentFilterState: queryFilter.explicitFilterState,allowBackendSystemPresets: true,+ onViewApplied: (viewState) =>+ searchBar.resetDraft({+ filters: queryFilter.projectFiltersForSearchBar(viewState.filters),+ searchQuery: viewState.searchQuery ?? null,+ searchType: ["id", "content"],+ }),});viewControllersRef.current = {selectedViewId,@@ -271,6 +306,13 @@ function Harness({ projectId = PROJECT_ID }: { projectId?: string }) {<pre data-testid="explicit-state">{JSON.stringify(queryFilter.explicitFilterState)}</pre>+ <textarea+ aria-label="Search draft"+ value={searchDraft}+ onChange={(event) =>+ searchBar.store.getState().actions.setDraft(event.target.value)+ }+ /><KeyValueFilterBuilderkey={filterEditorResetKey}mode="string"@@ -304,6 +346,15 @@ function Harness({ projectId = PROJECT_ID }: { projectId?: string }) {<button onClick={() => queryFilter.setFilterState([])}>user-clear-filters</button>+ <button+ onClick={() => {+ handleSetViewId(USER_VIEW_ID);+ applyViewState({ ...USER_VIEW_STATE, filters: [] });+ }}+ >+ apply-empty-view+ </button>+ <button onClick={queryFilter.clearAll}>clear-all</button><button onClick={() => queryFilter.setFilterState(EXTRA_FILTERS)}>user-add-filter</button>@@ -475,6 +526,55 @@ describe("saved-view demotion on user filter edits", () => {expect(storedViewId()).toBe(PRESET_ID);});+ it("discards an invalid search draft when explicitly reapplying the same empty view", async () => {+ render(<Harness />);+ fireEvent.click(screen.getByRole("button", { name: "apply-empty-view" }));+ const draft = screen.getByRole("textbox", { name: "Search draft" });+ fireEvent.change(draft, { target: { value: "level:(" } });+ expect(draft).toHaveValue("level:(");+ fireEvent.click(screen.getByRole("button", { name: "apply-empty-view" }));+ expect(draft).toHaveValue("");+ });++ it("discards an invalid search draft when clearing an already-empty applied filter state", async () => {+ render(<Harness />);+ const draft = screen.getByRole("textbox", { name: "Search draft" });+ fireEvent.change(draft, { target: { value: "level:(" } });+ fireEvent.click(screen.getByRole("button", { name: "clear-all" }));+ expect(draft).toHaveValue("");+ });++ it("preserves a search draft while a sorting edit deselects its view", async () => {+ render(<Harness />);+ await applyPresetAndAssertActive();+ const draft = screen.getByRole("textbox", { name: "Search draft" });+ fireEvent.change(draft, { target: { value: "level:(" } });+ fireEvent.click(screen.getByRole("button", { name: "user-sort" }));+ expect(draft).toHaveValue("level:(");+ expect(screen.getByTestId("selected-view-id")).toHaveTextContent("null");+ });++ it("leaves an empty saved view on Clear all and retains its update destination", async () => {+ render(<Harness />);+ fireEvent.click(screen.getByRole("button", { name: "apply-empty-view" }));+ await waitFor(() => {+ expect(screen.getByTestId("selected-view-id").textContent).toBe(+ USER_VIEW_ID,+ );+ });++ fireEvent.click(screen.getByRole("button", { name: "clear-all" }));++ await waitFor(() => {+ expect(screen.getByTestId("selected-view-id").textContent).toBe("null");+ });+ expect(storedViewId()).toBe(null);+ expect(queryParamStore.has("viewId")).toBe(false);+ expect(screen.getByTestId("view-update-target").textContent).toContain(+ USER_VIEW_ID,+ );+ });+it("clears a user-saved view from shared state, URL and session on an actual filter edit", async () => {const { unmount } = render(<Harness />);diff --git a/web/src/features/experiments/components/table/ExperimentItemsTable.tsx b/web/src/features/experiments/components/table/ExperimentItemsTable.tsxindex 0525195cd7..0af9917647 100644--- a/web/src/features/experiments/components/table/ExperimentItemsTable.tsx+++ b/web/src/features/experiments/components/table/ExperimentItemsTable.tsx@@ -56,6 +56,14 @@ import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNaviimport { ExperimentGridView } from "./ExperimentGridView";import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";+import { useTableViewFilterChange } from "@/src/components/table/table-view-presets/hooks/useTableViewFilterChange";+import { TableSearchBar } from "@/src/features/search-bar/components/TableSearchBar";+import { toObservedOptions } from "@/src/features/search-bar/lib/observed-options";+import { EXPERIMENT_ITEMS_FIELD_REGISTRY } from "@/src/features/experiments/constants/experimentItemsSearchRegistry";+import {+ reconcileFilterTargets,+ hasAmbiguousTargetChange,+} from "@/src/features/experiments/lib/reconcileFilterTargets";import { TableSelectionManager } from "@/src/features/table/components/TableSelectionManager";import { useSelectAll } from "@/src/features/table/hooks/useSelectAll";import { useExperimentItemsTableData } from "../../hooks/useExperimentItemsTableData";@@ -634,32 +642,53 @@ export default function ExperimentItemsTable({// Use sidebar filter state for the sidebar UI (provides proper facets, options, etc.)// This is the single source of truth for filtersconst capture = usePostHogClientCapture();+ const { viewControllersRef, onExplicitFilterStateChange } =+ useTableViewFilterChange();+ const [filterTargetState, setFilterTargetState] = useState<{+ filters: FilterState;+ targets: Record<number, string>;+ }>({ filters: [], targets: {} });const queryFilter = useSidebarFilterState(experimentItemsFilterConfig,scoreFilterOptions,{stateLocation: "url",+ onExplicitFilterStateChange: (change) => {+ setFilterTargetState((state) => ({+ filters: change.nextFilters,+ targets:+ change.origin === "saved_view"+ ? {}+ : reconcileFilterTargets(+ change.previousFilters,+ change.nextFilters,+ reconcileFilterTargets(+ state.filters,+ change.previousFilters,+ state.targets,+ ),+ ),+ }));+ onExplicitFilterStateChange(change);+ },loading: isFilterOptionsLoading,// v4-only surface β drives `isV4` on filters:* analytics.isV4: true,},);+ // The assignment carries its condition so URL navigation cannot attach a+ // previous index's experiment to an unrelated condition.+ const filterTargets = reconcileFilterTargets(+ filterTargetState.filters,+ queryFilter.filterState,+ filterTargetState.targets,+ );+// Create ref-based wrapper to avoid stale closure when queryFilter updatesconst queryFilterRef = useRef(queryFilter);queryFilterRef.current = queryFilter;- const setFiltersWrapper = useCallback(- (filters: FilterState) => queryFilterRef.current?.setFilterState(filters),- [],- );-- // Per-experiment filter targeting state (maps filter index to experiment ID)- // Default: all filters target the baseline experiment- const [filterTargets, setFilterTargets] = useState<Record<number, string>>(- {},- );-// Build filter list for pills display// Group filters by their target experiment (defaults to baseline)const filtersByExperiment = useMemo(() => {@@ -697,7 +726,7 @@ export default function ExperimentItemsTable({const filterState = queryFilterRef.current.filterState;// Count filters up to the current group to find original index- let originalIndex = 0;+ let originalIndex = -1;let currentGroupIndex = 0;for (let i = 0; i < filterState.length; i++) {@@ -711,13 +740,18 @@ export default function ExperimentItemsTable({}}+ if (originalIndex < 0) return;+ viewControllersRef.current?.handleUserStateChange(+ filterTargets[originalIndex] ?? defaultFilterTargetExperimentId,+ toExperimentId,+ );// Update the target for this filter- setFilterTargets((prev) => ({- ...prev,- [originalIndex]: toExperimentId,- }));+ setFilterTargetState({+ filters: filterState,+ targets: { ...filterTargets, [originalIndex]: toExperimentId },+ });},- [filterTargets, defaultFilterTargetExperimentId],+ [filterTargets, defaultFilterTargetExperimentId, viewControllersRef],);// Handler for removing a filter via pill@@ -726,7 +760,7 @@ export default function ExperimentItemsTable({const filterState = queryFilterRef.current.filterState;// Find the original filter index- let originalIndex = 0;+ let originalIndex = -1;let currentGroupIndex = 0;for (let i = 0; i < filterState.length; i++) {@@ -740,24 +774,10 @@ export default function ExperimentItemsTable({}}+ if (originalIndex < 0) return;// Remove the filter from queryFilterconst newFilters = filterState.filter((_, idx) => idx !== originalIndex);queryFilterRef.current.setFilterState(newFilters);-- // Clean up the filter targets (shift indices down)- setFilterTargets((prev) => {- const newTargets: Record<number, string> = {};- Object.entries(prev).forEach(([key, value]) => {- const idx = parseInt(key);- if (idx < originalIndex) {- newTargets[idx] = value;- } else if (idx > originalIndex) {- newTargets[idx - 1] = value;- }- // Skip the removed index- });- return newTargets;- });},[filterTargets, defaultFilterTargetExperimentId],);@@ -1741,7 +1761,8 @@ export default function ExperimentItemsTable({projectId,stateUpdaters: {setOrderBy: setOrderByState,- setFilters: setFiltersWrapper,+ setFilters: (filters) =>+ queryFilter.setFilterState(filters, { origin: "saved_view" }),setExpandedFilters: queryFilter.onExpandedChange,setColumnOrder: setColumnOrder,setColumnVisibility: setColumnVisibilityState,@@ -1757,6 +1778,38 @@ export default function ExperimentItemsTable({currentExpandedFilters: queryFilter.expanded,});+ viewControllersRef.current = viewControllers;+ const handleColumnOrderChange: typeof setColumnOrder = (next) => {+ const value = typeof next === "function" ? next(columnOrder) : next;+ viewControllers.handleUserStateChange(columnOrder, value);+ setColumnOrder(value);+ };+ const handleColumnVisibilityChange: typeof setColumnVisibilityState = (+ next,+ ) => {+ const value = typeof next === "function" ? next(columnVisibility) : next;+ viewControllers.handleUserStateChange(columnVisibility, value);+ setColumnVisibilityState(value);+ };+ const handleOrderByChange: typeof setOrderByState = (next) => {+ viewControllers.handleUserStateChange(orderByState, next);+ setOrderByState(next);+ };+ const searchRegistry = {+ ...EXPERIMENT_ITEMS_FIELD_REGISTRY,+ filterStateErrors: (filters: FilterState) =>+ hasAmbiguousTargetChange(+ queryFilter.searchBarFilterState,+ filters,+ filterTargets,+ defaultFilterTargetExperimentId,+ )+ ? [+ "These edits cannot preserve the filtersβ experiment targets. Edit one condition at a time or use its experiment pill.",+ ]+ : [],+ };+const peekConfig: DataTablePeekViewProps | undefined = useMemo(() => {if (!canUsePeek) return undefined;return {@@ -1982,6 +2035,21 @@ export default function ExperimentItemsTable({tableName={experimentItemsFilterConfig.tableName}><div className="flex h-full w-full flex-col">+ {!hideControls && (+ <TableSearchBar+ key={`${projectId}:${viewControllers.filterEditorResetKey}:${queryFilter.draftResetKey}`}+ projectId={projectId}+ tableName="experiment-items"+ registry={searchRegistry}+ filterState={queryFilter.searchBarFilterState}+ setFilterState={queryFilter.setFilterState}+ observed={toObservedOptions(+ scoreFilterOptions,+ isFilterOptionsLoading,+ )}+ isV4={true}+ />+ )}{/* Toolbar spanning full width */}{!hideControls && (<DataTableToolbar@@ -1990,16 +2058,24 @@ export default function ExperimentItemsTable({viewConfig={{tableName: TableViewPresetTableName.ExperimentItems,projectId,- controllers: viewControllers,+ controllers: {+ ...viewControllers,+ applyViewState: (+ ...args: Parameters<typeof viewControllers.applyViewState>+ ) => {+ setFilterTargetState({ filters: [], targets: {} });+ viewControllers.applyViewState(...args);+ },+ },}}tableName={experimentItemsFilterConfig.tableName}isV4={true}onColumnGroupToggle={handleColumnGroupToggle}columnsWithCustomSelect={["datasetItemId"]}columnVisibility={columnVisibility}- setColumnVisibility={setColumnVisibilityState}+ setColumnVisibility={handleColumnVisibilityChange}columnOrder={columnOrder}- setColumnOrder={setColumnOrder}+ setColumnOrder={handleColumnOrderChange}orderByState={orderByState}rowHeight={rowHeight}setRowHeight={setRowHeight}@@ -2065,8 +2141,7 @@ export default function ExperimentItemsTable({<ResizableFilterLayout>{!hideControls && (<DataTableControls- // Remount the sidebar when the saved view changes so the new view's filters replace any stale draft UI state.- key={viewControllers.selectedViewId ?? "no-view"}+ key={viewControllers.filterEditorResetKey}queryFilter={queryFilter}/>)}@@ -2140,12 +2215,12 @@ export default function ExperimentItemsTable({pagination={pagination}rowSelection={selectedRows}setRowSelection={setSelectedRows}- setOrderBy={setOrderByState}+ setOrderBy={handleOrderByChange}orderBy={orderByState}columnOrder={columnOrder}- onColumnOrderChange={setColumnOrder}+ onColumnOrderChange={handleColumnOrderChange}columnVisibility={columnVisibility}- onColumnVisibilityChange={setColumnVisibilityState}+ onColumnVisibilityChange={handleColumnVisibilityChange}rowHeight={rowHeight}peekView={peekConfig}noResultsMessage={diff --git a/web/src/features/experiments/components/table/ExperimentsTable.tsx b/web/src/features/experiments/components/table/ExperimentsTable.tsxindex 250115d804..d43030f1ef 100644--- a/web/src/features/experiments/components/table/ExperimentsTable.tsx+++ b/web/src/features/experiments/components/table/ExperimentsTable.tsx@@ -16,12 +16,7 @@ import { usePaginationState } from "@/src/hooks/usePaginationState";import { experimentsFieldRegistry } from "@/src/features/experiments/constants/experimentsSearchRegistry";import { awaitsDatasetNames } from "@/src/features/experiments/fns/awaitsDatasetNames";import { withDatasetNamesResolved } from "@/src/features/experiments/fns/datasetNameFilter";-import {- DEFAULT_SEARCH_TYPE,- EventsSearchBarRow,- toObservedOptions,- useEventsSearchBar,-} from "@/src/features/search-bar";+import { TableSearchBar, toObservedOptions } from "@/src/features/search-bar";import {getExperimentsFilterConfig,getExperimentsColumnName,@@ -60,6 +55,7 @@ import { createIdTableColumn } from "@/src/components/design-system/table/columnimport { Skeleton } from "@/src/components/ui/skeleton";import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";+import { useTableViewFilterChange } from "@/src/components/table/table-view-presets/hooks/useTableViewFilterChange";import { useRouter } from "next/router";import { TableSelectionManager } from "@/src/features/table/components/TableSelectionManager";import {@@ -368,8 +364,12 @@ export default function ExperimentsTable({[fixedFilter, datasetNameById],);+ const { viewControllersRef, onExplicitFilterStateChange } =+ useTableViewFilterChange();+const queryFilter = useSidebarFilterState(filterConfig, filterOptions, {loading: isFilterOptionsPending,+ onExplicitFilterStateChange,stateLocation: "urlAndSessionStorage",sessionFilterContextId,// v4-only surface β drives `isV4` on filters:* analytics.@@ -385,7 +385,7 @@ export default function ExperimentsTable({!hasAppliedDefaultFilter.current) {hasAppliedDefaultFilter.current = true;- queryFilter.setFilterState(defaultFilter);+ queryFilter.setFilterState(defaultFilter, { origin: "system" });}}, [defaultFilter, queryFilter]);@@ -411,27 +411,6 @@ export default function ExperimentsTable({() => toObservedOptions(filterOptions, isFilterOptionsPending),[filterOptions, isFilterOptionsPending],);- // The experiments table has no full-text lane, so the registry rejects free- // text and these stay inert.- const noSearchLane = useCallback(() => {}, []);- const {- store: searchBarStore,- commit: searchBarCommit,- applyFilters: searchBarApplyFilters,- } = useEventsSearchBar({- projectId,- tableName: filterConfig.tableName,- enabled: true,- filterState: queryFilter.explicitFilterState,- searchQuery: null,- searchType: DEFAULT_SEARCH_TYPE,- observed: observedOptions,- setFilterState: setFiltersWrapper,- setSearchQuery: noSearchLane,- setSearchType: noSearchLane,- registry: searchRegistry,- });-const combinedFilterState = queryFilter.filterState.concat(dateRangeFilter,fixedFilter,@@ -865,7 +844,10 @@ export default function ExperimentsTable({projectId,stateUpdaters: {setOrderBy: setOrderByState,- setFilters: setFiltersWrapper,+ setFilters: (filters) =>+ queryFilterRef.current.setFilterState(filters, {+ origin: "saved_view",+ }),setExpandedFilters: queryFilter.onExpandedChange,setColumnOrder: setColumnOrder,setColumnVisibility: setColumnVisibilityState,@@ -883,6 +865,25 @@ export default function ExperimentsTable({currentFilterState: queryFilter.explicitFilterState,currentExpandedFilters: queryFilter.expanded,});+ viewControllersRef.current = viewControllers;++ const handleOrderByChange: typeof setOrderByState = (next) => {+ viewControllers.handleUserStateChange(orderByState, next);+ setOrderByState(next);+ };+ const handleColumnOrderChange: typeof setColumnOrder = (update) => {+ const next = typeof update === "function" ? update(columnOrder) : update;+ viewControllers.handleUserStateChange(columnOrder, next);+ setColumnOrder(next);+ };+ const handleColumnVisibilityChange: typeof setColumnVisibilityState = (+ update,+ ) => {+ const next =+ typeof update === "function" ? update(columnVisibility) : update;+ viewControllers.handleUserStateChange(columnVisibility, next);+ setColumnVisibilityState(next);+ };const rows: ExperimentsTableRow[] = useMemo(() => {return experiments.status === "success" && experiments.rows@@ -953,13 +954,14 @@ export default function ExperimentsTable({toolbar cannot scroll under the composer and render half-clipped;pb-1.5 matches the other bar surfaces' spacing above the table. */}<div className="bg-background sticky top-0 z-30 pb-1.5">- <EventsSearchBarRow+ <TableSearchBar+ key={`${viewControllers.filterEditorResetKey}-${queryFilter.draftResetKey}`}+ isV4={true}+ filterState={queryFilter.searchBarFilterState}+ setFilterState={setFiltersWrapper}projectId={projectId}tableName={filterConfig.tableName}- store={searchBarStore}- commit={searchBarCommit}observed={observedOptions}- onApplyFilters={searchBarApplyFilters}registry={searchRegistry}/>{/* Toolbar spanning full width */}@@ -977,9 +979,9 @@ export default function ExperimentsTable({onColumnGroupToggle={handleColumnGroupToggle}columnsWithCustomSelect={["name", "datasetId"]}columnVisibility={columnVisibility}- setColumnVisibility={setColumnVisibilityState}+ setColumnVisibility={handleColumnVisibilityChange}columnOrder={columnOrder}- setColumnOrder={setColumnOrder}+ setColumnOrder={handleColumnOrderChange}orderByState={orderByState}rowHeight={rowHeight}setRowHeight={setRowHeight}@@ -1011,7 +1013,7 @@ export default function ExperimentsTable({<ResizableFilterLayout><DataTableControls// Remount the sidebar when the saved view changes so the new view's filters replace any stale draft UI state.- key={viewControllers.selectedViewId ?? "no-view"}+ key={viewControllers.filterEditorResetKey}queryFilter={queryFilter}/>@@ -1069,12 +1071,12 @@ export default function ExperimentsTable({},}}selectionStore={experimentsTableStore}- setOrderBy={setOrderByState}+ setOrderBy={handleOrderByChange}orderBy={orderByState}columnOrder={columnOrder}- onColumnOrderChange={setColumnOrder}+ onColumnOrderChange={handleColumnOrderChange}columnVisibility={columnVisibility}- onColumnVisibilityChange={setColumnVisibilityState}+ onColumnVisibilityChange={handleColumnVisibilityChange}rowHeight={rowHeight}onRowClick={(row, event) => {// Handle Command/Ctrl+click to open experiment in new tabdiff --git a/web/src/features/experiments/constants/experimentItemsSearchRegistry.clienttest.ts b/web/src/features/experiments/constants/experimentItemsSearchRegistry.clienttest.tsnew file mode 100644index 0000000000..9e3baf8272--- /dev/null+++ b/web/src/features/experiments/constants/experimentItemsSearchRegistry.clienttest.ts@@ -0,0 +1,103 @@+import { describe, expect, it } from "vitest";+import { EXPERIMENT_ITEMS_FIELD_REGISTRY } from "./experimentItemsSearchRegistry";+import { planCommit } from "@/src/features/search-bar/lib/commit";+import { filterStateToQueryText } from "@/src/features/search-bar/lib/filter-state-to-query";+import { hasAmbiguousTargetChange } from "@/src/features/experiments/lib/reconcileFilterTargets";+import type { FilterState } from "@langfuse/shared";++describe("experiment item search contract", () => {+ it("lowers root/trace score conditions to the same canonical columns as the sidebar", () => {+ const result = planCommit(+ "status:ERROR scores.quality:>0.8",+ undefined,+ EXPERIMENT_ITEMS_FIELD_REGISTRY,+ );+ expect(result).toMatchObject({+ status: "committed",+ filters: [+ {+ column: "level",+ type: "stringOptions",+ operator: "any of",+ value: ["ERROR"],+ },+ {+ column: "scores_avg",+ type: "numberObject",+ key: "quality",+ operator: ">",+ value: 0.8,+ },+ ],+ });+ });+ it("preserves backend-specific metadata filters without emitting a generic metadata column", () => {+ const filters: FilterState = [+ {+ column: "itemMetadata",+ type: "stringObject",+ key: "language",+ operator: "=",+ value: "en",+ },+ {+ column: "eventMetadata",+ type: "stringObject",+ key: "model",+ operator: "=",+ value: "test",+ },+ ];+ expect(+ filterStateToQueryText(+ filters,+ undefined,+ EXPERIMENT_ITEMS_FIELD_REGISTRY,+ ).skippedFilters,+ ).toEqual(filters);+ expect(+ planCommit(+ "metadata.language:en",+ undefined,+ EXPERIMENT_ITEMS_FIELD_REGISTRY,+ ).status,+ ).toBe("invalid");+ expect(+ planCommit(+ "traceScores.quality:1",+ undefined,+ EXPERIMENT_ITEMS_FIELD_REGISTRY,+ ).status,+ ).toBe("invalid");+ });+ it("checks target ambiguity over the whole query, allowing unchanged duplicate conditions", () => {+ const filters: FilterState = [+ {+ column: "level",+ type: "stringOptions",+ operator: "any of",+ value: ["ERROR"],+ },+ {+ column: "level",+ type: "stringOptions",+ operator: "any of",+ value: ["ERROR"],+ },+ ];+ const registry = {+ ...EXPERIMENT_ITEMS_FIELD_REGISTRY,+ filterStateErrors: (next: FilterState) =>+ hasAmbiguousTargetChange(filters, next, { 0: "a", 1: "b" }, "a")+ ? ["Ambiguous target"]+ : [],+ };+ expect(+ planCommit("level:ERROR level:ERROR", undefined, registry).status,+ ).toBe("committed");+ expect(planCommit("level:ERROR", undefined, registry).status).toBe(+ "invalid",+ );+ expect(planCommit("", undefined, registry).status).toBe("committed");+ });+});diff --git a/web/src/features/experiments/constants/experimentItemsSearchRegistry.ts b/web/src/features/experiments/constants/experimentItemsSearchRegistry.tsnew file mode 100644index 0000000000..b82e838c0b--- /dev/null+++ b/web/src/features/experiments/constants/experimentItemsSearchRegistry.ts@@ -0,0 +1,24 @@+import { experimentItemsFilterConfig } from "@/src/features/experiments/config/experiment-items-filter-config";+import { fieldRegistryFromColumns } from "@/src/features/search-bar/lib/fields";++const facetColumns = new Set(+ experimentItemsFilterConfig.facets.map((facet) => facet.column),+);++export const EXPERIMENT_ITEMS_FIELD_REGISTRY = fieldRegistryFromColumns(+ experimentItemsFilterConfig.columnDefinitions.filter((column) =>+ facetColumns.has(column.id),+ ),+ {+ id: "experimentItems",+ allowFreeText: false,+ // Item and event metadata use different backend columns; the sidebar owns+ // those namespaces until the grammar can map each namespace independently.+ metadata: false,+ scores: true,+ traceScores: false,+ recentSearches: true,+ searchExamples: ["level:ERROR", "scores.quality:>0.8"],+ fields: { level: { aliases: ["status"] } },+ },+);diff --git a/web/src/features/experiments/lib/reconcileFilterTargets.clienttest.ts b/web/src/features/experiments/lib/reconcileFilterTargets.clienttest.tsnew file mode 100644index 0000000000..ba8dfb618c--- /dev/null+++ b/web/src/features/experiments/lib/reconcileFilterTargets.clienttest.ts@@ -0,0 +1,148 @@+import { describe, expect, it } from "vitest";+import type { FilterState } from "@langfuse/shared";+import {+ reconcileFilterTargets,+ hasAmbiguousTargetChange,+} from "./reconcileFilterTargets";++const previous: FilterState = [+ {+ type: "stringOptions",+ column: "level",+ operator: "any of",+ value: ["ERROR"],+ },+ {+ type: "numberObject",+ column: "scores_avg",+ key: "quality",+ operator: ">",+ value: 0.5,+ },+ {+ type: "numberObject",+ column: "scores_avg",+ key: "safety",+ operator: "<",+ value: 0.8,+ },+];++describe("experiment filter targets", () => {+ const scoreRange: FilterState = [+ {+ type: "numberObject",+ column: "scores_avg",+ key: "quality",+ operator: ">",+ value: 0.5,+ },+ {+ type: "numberObject",+ column: "scores_avg",+ key: "quality",+ operator: "<",+ value: 0.8,+ },+ ];+ const editedScoreRange: FilterState = [+ {+ type: "numberObject",+ column: "scores_avg",+ key: "quality",+ operator: ">",+ value: 0.6,+ },+ {+ type: "numberObject",+ column: "scores_avg",+ key: "quality",+ operator: "<",+ value: 0.9,+ },+ ];++ it("rejects ambiguous edits of the same score across different runs", () => {+ expect(+ hasAmbiguousTargetChange(+ scoreRange,+ editedScoreRange,+ {+ 0: "comparison-a",+ 1: "comparison-b",+ },+ "baseline",+ ),+ ).toBe(true);+ });++ it("preserves a common run when multiple conditions change together", () => {+ const targets = { 0: "comparison-a", 1: "comparison-a" };+ expect(+ hasAmbiguousTargetChange(+ scoreRange,+ editedScoreRange,+ targets,+ "baseline",+ ),+ ).toBe(false);+ expect(+ reconcileFilterTargets(scoreRange, editedScoreRange, targets),+ ).toEqual(targets);+ });++ it("keeps a run's condition on that run when the bar reorders and removes other filters", () => {+ const next = [structuredClone(previous[2]!), structuredClone(previous[0]!)];+ expect(+ reconcileFilterTargets(previous, next, {+ 0: "baseline",+ 1: "comparison-a",+ 2: "comparison-b",+ }),+ ).toEqual({+ 0: "comparison-b",+ 1: "baseline",+ });+ });+ it("preserves the target of a uniquely edited score and defaults newly added fields", () => {+ const next: FilterState = [+ { ...previous[1]!, value: 0.9 } as FilterState[number],+ {+ type: "booleanObject",+ column: "score_booleans",+ key: "approved",+ operator: "=",+ value: true,+ },+ ];+ expect(+ reconcileFilterTargets(previous, next, {+ 1: "comparison-a",+ 2: "comparison-b",+ }),+ ).toEqual({ 0: "comparison-a" });+ });+ it("uses retained object identity when a targeted pill removes one of two identical conditions", () => {+ const first = structuredClone(previous[0]!);+ const second = structuredClone(previous[0]!);+ expect(+ reconcileFilterTargets([first, second], [second], { 0: "a", 1: "b" }),+ ).toEqual({ 0: "b" });+ expect(+ hasAmbiguousTargetChange(+ [first, second],+ [structuredClone(second)],+ { 0: "a", 1: "b" },+ "baseline",+ ),+ ).toBe(true);+ expect(+ hasAmbiguousTargetChange(+ [first, second],+ [],+ { 0: "a", 1: "b" },+ "baseline",+ ),+ ).toBe(false);+ });+});diff --git a/web/src/features/experiments/lib/reconcileFilterTargets.ts b/web/src/features/experiments/lib/reconcileFilterTargets.tsnew file mode 100644index 0000000000..540a6be71f--- /dev/null+++ b/web/src/features/experiments/lib/reconcileFilterTargets.ts@@ -0,0 +1,130 @@+import type { FilterState } from "@langfuse/shared";+import isEqual from "lodash/isEqual";++function sameField(left: FilterState[number], right: FilterState[number]) {+ return (+ left.column === right.column &&+ ("key" in left ? left.key : null) === ("key" in right ? right.key : null)+ );+}++function matchFilterIndices(+ previousFilters: FilterState,+ nextFilters: FilterState,+) {+ const matched = new Set<number>();+ const matches = new Map<number, number>();+ const match = (nextIndex: number, previousIndex: number) => {+ if (previousIndex < 0) return;+ matched.add(previousIndex);+ matches.set(nextIndex, previousIndex);+ };++ // Sidebar removals retain object identity, which distinguishes identical+ // conditions assigned to different runs. Grammar commits reconstruct objects.+ nextFilters.forEach((filter, nextIndex) => {+ match(+ nextIndex,+ previousFilters.findIndex(+ (previous, index) => !matched.has(index) && previous === filter,+ ),+ );+ });+ nextFilters.forEach((filter, nextIndex) => {+ if (matches.has(nextIndex)) return;+ match(+ nextIndex,+ previousFilters.findIndex(+ (previous, index) => !matched.has(index) && isEqual(previous, filter),+ ),+ );+ });+ nextFilters.forEach((filter, nextIndex) => {+ if (matches.has(nextIndex)) return;+ const previousCandidates = previousFilters.flatMap((previous, index) =>+ !matched.has(index) && sameField(previous, filter) ? [index] : [],+ );+ const nextCandidates = nextFilters.filter(+ (next, index) => !matches.has(index) && sameField(next, filter),+ );+ if (previousCandidates.length === 1 && nextCandidates.length === 1) {+ match(nextIndex, previousCandidates[0]!);+ }+ });++ return { matched, matches };+}++/** Keep run assignments attached to conditions when editors reorder, remove or replace them. */+export function reconcileFilterTargets(+ previousFilters: FilterState,+ nextFilters: FilterState,+ targets: Readonly<Record<number, string>>,+): Record<number, string> {+ const { matched, matches } = matchFilterIndices(previousFilters, nextFilters);+ const nextTargets: Record<number, string> = {};+ for (const [nextIndex, previousIndex] of matches) {+ const target = targets[previousIndex];+ if (target !== undefined) nextTargets[nextIndex] = target;+ }+ nextFilters.forEach((filter, nextIndex) => {+ if (matches.has(nextIndex)) return;+ const previousCandidates = previousFilters.flatMap((previous, index) =>+ !matched.has(index) && sameField(previous, filter) ? [index] : [],+ );+ const nextCount = nextFilters.filter(+ (next, index) => !matches.has(index) && sameField(next, filter),+ ).length;+ const candidateTargets = new Set(+ previousCandidates.map((index) => targets[index]),+ );+ if (nextCount <= previousCandidates.length && candidateTargets.size === 1) {+ const target = targets[previousCandidates[0]!];+ if (target !== undefined) nextTargets[nextIndex] = target;+ }+ });+ return nextTargets;+}++/** Reject grammar changes that cannot preserve a condition's experiment assignment. */+export function hasAmbiguousTargetChange(+ previousFilters: FilterState,+ nextFilters: FilterState,+ targets: Readonly<Record<number, string>>,+ defaultTarget: string | undefined,+): boolean {+ const removedDuplicate = previousFilters.some((filter) => {+ const previousIndices = previousFilters.flatMap((previous, index) =>+ isEqual(previous, filter) ? [index] : [],+ );+ const remaining = nextFilters.filter((next) =>+ isEqual(next, filter),+ ).length;+ return (+ remaining > 0 &&+ remaining < previousIndices.length &&+ new Set(previousIndices.map((index) => targets[index] ?? defaultTarget))+ .size > 1+ );+ });+ if (removedDuplicate) return true;++ const { matched, matches } = matchFilterIndices(previousFilters, nextFilters);+ return nextFilters.some((filter, nextIndex) => {+ if (matches.has(nextIndex)) return false;+ const previousCandidates = previousFilters.flatMap((previous, index) =>+ !matched.has(index) && sameField(previous, filter) ? [index] : [],+ );+ const candidateTargets = new Set(+ previousCandidates.map((index) => targets[index] ?? defaultTarget),+ );+ const nextCount = nextFilters.filter(+ (next, index) => !matches.has(index) && sameField(next, filter),+ ).length;+ return (+ candidateTargets.size > 1 ||+ (nextCount > previousCandidates.length &&+ [...candidateTargets].some((target) => target !== defaultTarget))+ );+ });+}diff --git a/web/src/features/filters/config/sessionsSearchRegistry.ts b/web/src/features/filters/config/sessionsSearchRegistry.tsindex 2f79f9fec3..83df89d9e2 100644--- a/web/src/features/filters/config/sessionsSearchRegistry.ts+++ b/web/src/features/filters/config/sessionsSearchRegistry.ts@@ -93,6 +93,7 @@ const SESSION_FIELD_OVERLAY = {};function sessionsRegistry(config: FilterConfig, metadata: boolean) {+ const hasUserIds = config.facets.some((facet) => facet.column === "userIds");return fieldRegistryFromColumns(facetColumns(config), {id: "sessions",metadata,@@ -104,10 +105,10 @@ function sessionsRegistry(config: FilterConfig, metadata: boolean) {// by a wide margin, so a bare word means that rather than an error.allowFreeText: false,defaultTextField: "id",- hasExample: "userIds",+ hasExample: hasUserIds ? "userIds" : undefined,recentSearches: true,searchExamples: [- "userIds:alice",+ ...(hasUserIds ? ["userIds:alice"] : []),"tags:(billing AND urgent)","duration:>30","scores.helpfulness:>0.8",@@ -117,13 +118,13 @@ function sessionsRegistry(config: FilterConfig, metadata: boolean) {});}-/**- * v4 (events-backed) sessions. The v3 config differs by exactly one column β v4- * adds `metadata` β so one derivation parameterised by the metadata flag would- * cover both. Only the v4 registry exists because the bar is gated on v4; a v3- * variant would be unreachable, and the recipe forbids speculative registries.- */-export const SESSIONS_FIELD_REGISTRY: FieldRegistry = sessionsRegistry(+export function sessionsFieldRegistry(config: FilterConfig): FieldRegistry {+ return sessionsRegistry(+ config,+ config.facets.some((facet) => facet.column === "metadata"),+ );+}++export const SESSIONS_FIELD_REGISTRY = sessionsFieldRegistry(sessionEventsFilterConfig,- true,);diff --git a/web/src/features/filters/config/tracingSearchRegistry.clienttest.ts b/web/src/features/filters/config/tracingSearchRegistry.clienttest.tsnew file mode 100644index 0000000000..a919741d99--- /dev/null+++ b/web/src/features/filters/config/tracingSearchRegistry.clienttest.ts@@ -0,0 +1,180 @@+// @vitest-environment node++import { describe, expect, it } from "vitest";+import type { FilterState } from "@langfuse/shared";+import { planCommit } from "@/src/features/search-bar/lib/commit";+import { filterStateToQueryText } from "@/src/features/search-bar/lib/filter-state-to-query";+import { runSearchBarInvariants } from "@/src/features/search-bar/lib/searchBarInvariants";+import { validateQuery } from "@/src/features/search-bar/lib/validate";+import { getTraceFilterConfig } from "./traces-config";+import { getObservationsFilterConfig } from "./observations-config";+import {+ observationsFieldRegistry,+ tracesFieldRegistry,+} from "./tracingSearchRegistry";++const registries = [+ tracesFieldRegistry(getTraceFilterConfig()),+ observationsFieldRegistry(getObservationsFilterConfig()),+];++for (const registry of registries) {+ describe(`${registry.id} search registry`, () => {+ it("keeps bare phrases in the host's existing full-text search lane", () => {+ expect(planCommit("refund policy", undefined, registry)).toMatchObject({+ status: "committed",+ filters: [],+ searchQuery: "refund policy",+ });+ });++ it.each([+ "input:secret",+ "output:secret",+ "traceScores.quality:>0.8",+ "bookmarked:true",+ ])(+ "rejects unsupported filters without changing the query for %s",+ (query) => {+ expect(validateQuery(query, undefined, registry).valid).toBe(false);+ expect(planCommit(query, undefined, registry).status).toBe("invalid");+ },+ );++ it("round-trips supported names, tags, metadata, numeric ranges and score types", () => {+ const nameColumn = registry.id === "traces" ? "traceName" : "name";+ const tagsColumn = registry.id === "traces" ? "traceTags" : "tags";+ const sidebarFilters: FilterState[] = [+ [+ {+ column: nameColumn,+ type: "stringOptions",+ operator: "any of",+ value: ["refund agent"],+ },+ ],+ [+ {+ column: nameColumn,+ type: "string",+ operator: "contains",+ value: "refund",+ },+ ],+ [+ {+ column: tagsColumn,+ type: "arrayOptions",+ operator: "all of",+ value: ["billing", "urgent"],+ },+ ],+ [+ {+ column: "metadata",+ type: "stringObject",+ key: "review team",+ operator: "=",+ value: "quality",+ },+ ],+ [+ { column: "latency", type: "number", operator: ">=", value: 1.5 },+ { column: "latency", type: "number", operator: "<", value: 4 },+ ],+ [+ {+ column: "scores_avg",+ type: "numberObject",+ key: "helpfulness",+ operator: ">=",+ value: 0.8,+ },+ ],+ [+ {+ column: "score_categories",+ type: "categoryOptions",+ key: "resolution",+ operator: "any of",+ value: ["resolved"],+ },+ ],+ [+ {+ column: "score_booleans",+ type: "booleanObject",+ key: "policy",+ operator: "=",+ value: true,+ },+ ],+ ];+ const scoreContext = {+ numericScoreNames: new Set(["helpfulness"]),+ categoricalScoreNames: new Set(["resolution"]),+ booleanScoreNames: new Set(["policy"]),+ };+ expect(+ runSearchBarInvariants({+ name: registry.id,+ registry,+ extraKeys: [+ "metadata.region",+ 'metadata."review team"',+ "scores.helpfulness",+ "scores.resolution",+ "scores.policy",+ ],+ scoreContexts: [scoreContext],+ fieldValues: [+ "refund agent",+ "ERROR",+ "GENERATION",+ "true",+ "false",+ "0.5",+ "or",+ "a,b",+ ],+ freeTextValues: ["refund policy", "or", "a,b", "!important"],+ sidebarFilters,+ }),+ ).toEqual([]);+ for (const filters of sidebarFilters) {+ const projection = filterStateToQueryText(filters, {}, registry);+ expect(projection.skippedFilters).toEqual([]);+ expect(+ planCommit(projection.text, scoreContext, registry),+ ).toMatchObject({+ status: "committed",+ filters,+ });+ }+ });+ });+}++describe("embedded tracing scope", () => {+ it("does not offer user or session controls omitted by the host", () => {+ const registry = tracesFieldRegistry(+ getTraceFilterConfig(["userId", "sessionId"]),+ );+ expect(registry.resolveField("user")).toBeNull();+ expect(registry.resolveField("session")).toBeNull();+ expect(planCommit("name:checkout", undefined, registry).status).toBe(+ "committed",+ );+ });++ it("does not offer a prompt or model facet omitted by the host", () => {+ const registry = observationsFieldRegistry(+ getObservationsFilterConfig(["model", "promptName"]),+ );+ expect(registry.resolveField("model")).toBeNull();+ expect(registry.resolveField("promptName")).toBeNull();+ expect(planCommit("type:GENERATION", undefined, registry).status).toBe(+ "committed",+ );+ });+});diff --git a/web/src/features/filters/config/tracingSearchRegistry.ts b/web/src/features/filters/config/tracingSearchRegistry.tsnew file mode 100644index 0000000000..04f50e3fbb--- /dev/null+++ b/web/src/features/filters/config/tracingSearchRegistry.ts@@ -0,0 +1,59 @@+import type { FilterConfig } from "@/src/features/filters/lib/filter-config";+import {+ fieldRegistryFromColumns,+ type FieldOverlay,+ type FieldRegistry,+} from "@/src/features/search-bar/lib/fields";++function tracingFieldRegistry(+ config: FilterConfig,+ id: "traces" | "observations",+): FieldRegistry {+ const exposed = new Set(config.facets.map((facet) => facet.column));+ const fields: Record<string, FieldOverlay> = {+ environment: { aliases: ["env"] },+ userId: { aliases: ["user", "user_id"] },+ sessionId: { aliases: ["session", "session_id"] },+ traceName: {+ aliases: id === "traces" ? ["name", "trace_name"] : ["trace_name"],+ },+ traceTags: { aliases: ["tags", "tag", "trace_tags"] },+ tags: { aliases: ["tag", "traceTags", "trace_tags"] },+ timeToFirstToken: { aliases: ["ttft"] },+ totalTokens: { aliases: ["tokens", "total_tokens"] },+ totalCost: { aliases: ["cost", "total_cost"] },+ };+ for (const facet of config.facets) {+ fields[facet.column] = {+ ...fields[facet.column],+ label: facet.label,+ ...(facet.type === "numeric" ? { unit: facet.unit } : {}),+ };+ }++ return fieldRegistryFromColumns(+ config.columnDefinitions.filter((column) => exposed.has(column.id)),+ {+ id,+ fields,+ metadata: exposed.has("metadata"),+ scores: exposed.has("scores_avg"),+ traceScores: false,+ allowFreeText: true,+ freeTextScopeLabel: "the selected search scope",+ recentSearches: true,+ searchExamples:+ id === "traces"+ ? ["name:checkout", "tags:production", "latency:>2"]+ : ["name:assistant", "type:GENERATION", "scores.quality:>0.8"],+ },+ );+}++export function tracesFieldRegistry(config: FilterConfig): FieldRegistry {+ return tracingFieldRegistry(config, "traces");+}++export function observationsFieldRegistry(config: FilterConfig): FieldRegistry {+ return tracingFieldRegistry(config, "observations");+}diff --git a/web/src/features/filters/config/usersSearchRegistry.ts b/web/src/features/filters/config/usersSearchRegistry.tsindex 1782102d81..fd5fe97b43 100644--- a/web/src/features/filters/config/usersSearchRegistry.ts+++ b/web/src/features/filters/config/usersSearchRegistry.ts@@ -1,11 +1,12 @@import {createFieldRegistry,+ fieldRegistryFromColumns,EVENTS_FIELD_REGISTRY,type FieldRegistry,} from "@/src/features/search-bar/lib/fields";import type { FilterConfig } from "@/src/features/filters/lib/filter-config";-import { usersEventsFilterConfig } from "./users-config";+import { usersEventsFilterConfig, usersFilterConfig } from "./users-config";/*** The Users bar is the Events bar with the facets the Users query cannot answer@@ -33,8 +34,7 @@ function usersColumns(config: FilterConfig) {}/**- * v4 (events-backed) Users. Only the v4 registry exists because the bar is- * gated on v4 β a v3 variant would be unreachable.+ * Users grouped from the events read path.*/export const USERS_FIELD_REGISTRY: FieldRegistry = createFieldRegistry({id: "users",@@ -70,3 +70,17 @@ export const USERS_FIELD_REGISTRY: FieldRegistry = createFieldRegistry({{ observedOptionsKey: "level", promptLabel: "level" },],});++export const LEGACY_USERS_FIELD_REGISTRY = fieldRegistryFromColumns(+ usersColumns(usersFilterConfig),+ {+ id: "users",+ metadata: true,+ scores: false,+ traceScores: false,+ allowFreeText: true,+ freeTextScopeLabel: "user IDs",+ searchExamples: ["alice", "-env:dev", "tags:billing"],+ fields: { environment: { aliases: ["env"] } },+ },+);diff --git a/web/src/features/filters/hooks/useSidebarFilterState.tsx b/web/src/features/filters/hooks/useSidebarFilterState.tsxindex d7f25c2191..e70dcafc24 100644--- a/web/src/features/filters/hooks/useSidebarFilterState.tsx+++ b/web/src/features/filters/hooks/useSidebarFilterState.tsx@@ -482,6 +482,7 @@ type BaseUseSidebarFilterStateOptions = {previousFilters: FilterState;nextFilters: FilterState;origin: "user" | "saved_view" | "system";+ action?: "clear";}) => void;/*** Precise per-facet loading set (lazy filter-options): exactly the columns@@ -833,6 +834,7 @@ export function useSidebarFilterStateCore(options?: {updateType?: UrlUpdateType;origin?: "user" | "saved_view" | "system";+ action?: "clear";},) => {const explicitFilters = stripOmittedColumns(@@ -846,6 +848,7 @@ export function useSidebarFilterStateCore(previousFilters: explicitFilterState,nextFilters: explicitFilters,origin: options?.origin ?? "user",+ action: options?.action,});if (stateLocationType === "peekContext" && setPeekTableState) {@@ -1133,7 +1136,7 @@ export function useSidebarFilterPresentation(const clearAll = () => {const clearedCount = explicitFilterState.length;setDraftResetKey((key) => key + 1);- setFilterState([]);+ setFilterState([], { action: "clear" });if (clearedCount > 0) {capture("filters:cleared", {surface: "sidebar",diff --git a/web/src/features/monitors/components/MonitorsTable.tsx b/web/src/features/monitors/components/MonitorsTable.tsxindex 18fa24eb91..340867bd7e 100644--- a/web/src/features/monitors/components/MonitorsTable.tsx+++ b/web/src/features/monitors/components/MonitorsTable.tsx@@ -30,7 +30,7 @@ import { usePaginationState } from "@/src/hooks/usePaginationState";import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";import { api, type RouterInputs, type RouterOutputs } from "@/src/utils/api";import { cn } from "@/src/utils/tailwind";-import { type FilterState } from "@langfuse/shared";+import { type FilterState, TableViewPresetTableName } from "@langfuse/shared";import {type ListMonitorFilter,ListMonitorFilterSchema,@@ -40,6 +40,16 @@ import {} from "@langfuse/shared/monitors";import { MonitorSeverityBadge } from "./MonitorSeverityBadge";+import {+ useColumnOrder,+ useColumnVisibility,+} from "@/src/features/column-visibility";+import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";+import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";+import { useTableViewFilterChange } from "@/src/components/table/table-view-presets/hooks/useTableViewFilterChange";+import { TableSearchBar } from "@/src/features/search-bar/components/TableSearchBar";+import { toObservedOptions } from "@/src/features/search-bar/lib/observed-options";+import { monitorsFieldRegistry } from "@/src/features/monitors/constants/monitorsSearchRegistry";/** monitorsRefetchInterval keeps the list's severity and paused state current without a manual reload. */const monitorsRefetchInterval = 5_000;@@ -132,10 +142,13 @@ export function MonitorsTable() {);/** queryFilter is the bound sidebar filter state, synced to the URL and to session storage per project. */+ const { viewControllersRef, onExplicitFilterStateChange } =+ useTableViewFilterChange();const queryFilter = useSidebarFilterState(monitorFilterConfig,newFilterOptions,{+ onExplicitFilterStateChange,loading: filterOptions.isPending,stateLocation: "urlAndSessionStorage",sessionFilterContextId: projectId ?? null,@@ -250,16 +263,84 @@ export function MonitorsTable() {},];+ const [columnVisibility, setColumnVisibility] =+ useColumnVisibility<MonitorRow>("monitorsColumnVisibility", columns);+ const [columnOrder, setColumnOrder] = useColumnOrder<MonitorRow>(+ "monitorsColumnOrder",+ columns,+ );+ const { isLoading: isViewLoading, ...viewControllers } = useTableViewManager({+ tableName: TableViewPresetTableName.Monitors,+ projectId,+ stateUpdaters: {+ setColumnOrder,+ setColumnVisibility,+ setOrderBy: setOrderByState,+ setFilters: (filters) =>+ queryFilter.setFilterState(filters, { origin: "saved_view" }),+ setExpandedFilters: queryFilter.onExpandedChange,+ },+ validationContext: {+ columns,+ filterColumnDefinition: monitorFilterConfig.columnDefinitions,+ expandableFilterColumns: monitorFilterConfig.facets.map(+ (facet) => facet.column,+ ),+ },+ currentFilterState: queryFilter.explicitFilterState,+ currentExpandedFilters: queryFilter.expanded,+ });+ viewControllersRef.current = viewControllers;+ const handleColumnOrderChange: typeof setColumnOrder = (next) => {+ const value = typeof next === "function" ? next(columnOrder) : next;+ viewControllers.handleUserStateChange(columnOrder, value);+ setColumnOrder(value);+ };+ const handleColumnVisibilityChange: typeof setColumnVisibility = (next) => {+ const value = typeof next === "function" ? next(columnVisibility) : next;+ viewControllers.handleUserStateChange(columnVisibility, value);+ setColumnVisibility(value);+ };+return (<div className="flex h-full w-full flex-col">+ <TableSearchBar+ key={`${projectId}:${viewControllers.filterEditorResetKey}:${queryFilter.draftResetKey}`}+ projectId={projectId}+ tableName="monitors"+ registry={monitorsFieldRegistry(monitorFilterConfig)}+ filterState={queryFilter.searchBarFilterState}+ setFilterState={queryFilter.setFilterState}+ observed={toObservedOptions(newFilterOptions, filterOptions.isPending)}+ isV4={false}+ />+ <DataTableToolbar+ tableName="monitors"+ columns={columns}+ filterState={queryFilter.explicitFilterState}+ columnVisibility={columnVisibility}+ setColumnVisibility={handleColumnVisibilityChange}+ columnOrder={columnOrder}+ setColumnOrder={handleColumnOrderChange}+ orderByState={orderByState}+ isV4={false}+ viewConfig={{+ tableName: TableViewPresetTableName.Monitors,+ projectId,+ controllers: viewControllers,+ }}+ /><ResizableFilterLayout>- <DataTableControls queryFilter={queryFilter} />+ <DataTableControls+ key={viewControllers.filterEditorResetKey}+ queryFilter={queryFilter}+ /><div className="flex flex-1 flex-col overflow-hidden"><DataTabletableName="monitors"columns={columns}data={- monitors.isLoading+ monitors.isLoading || isViewLoading? { isLoading: true, isError: false }: monitors.isError? {@@ -274,7 +355,14 @@ export function MonitorsTable() {}}orderBy={orderByState}- setOrderBy={setOrderByState}+ setOrderBy={(next) => {+ viewControllers.handleUserStateChange(orderByState, next);+ setOrderByState(next);+ }}+ columnOrder={columnOrder}+ onColumnOrderChange={handleColumnOrderChange}+ columnVisibility={columnVisibility}+ onColumnVisibilityChange={handleColumnVisibilityChange}pagination={{totalCount: monitors.data?.totalCount ?? null,onChange: setPaginationState,diff --git a/web/src/features/monitors/constants/monitorsSearchRegistry.clienttest.ts b/web/src/features/monitors/constants/monitorsSearchRegistry.clienttest.tsnew file mode 100644index 0000000000..f4afcc8ab7--- /dev/null+++ b/web/src/features/monitors/constants/monitorsSearchRegistry.clienttest.ts@@ -0,0 +1,70 @@+import { describe, expect, it } from "vitest";+import { getMonitorFilterConfig } from "@/src/features/filters/config/monitors-config";+import { monitorsFieldRegistry } from "./monitorsSearchRegistry";+import { astToFilterState } from "@/src/features/search-bar/lib/adapter";+import { planCommit } from "@/src/features/search-bar/lib/commit";+import { parse } from "@/src/features/search-bar/lib/langQ";+import { validateQuery } from "@/src/features/search-bar/lib/validate";+import { createSearchBarStore } from "@/src/features/search-bar/store/searchBarStore";+import { ListMonitorFilterSchema } from "@langfuse/shared/monitors";++const registry = monitorsFieldRegistry(getMonitorFilterConfig(true));++describe("monitor search contract", () => {+ it.each([+ "severity:ALERT -severity:PAUSED",+ "severity:INVALID",+ "has:severity",+ ])("rejects a filter shape the monitor backend cannot apply: %s", (query) => {+ const parsed = parse(query, registry);+ expect(+ astToFilterState(parsed.ast, undefined, registry).errors.length,+ ).toBeGreaterThan(0);+ expect(validateQuery(query, undefined, registry).valid).toBe(false);+ expect(planCommit(query, undefined, registry).status).toBe("invalid");+ const store = createSearchBarStore(undefined, () => registry);+ store.getState().actions.setDraft(query);+ expect(store.getState().draftValid).toBe(false);+ });+ it("keeps grouped severity, evaluator and all-of tags in the existing backend schema", () => {+ const result = planCommit(+ "severity:(ALERT OR WARNING) evaluator:eval-1 tags:(prod AND critical)",+ undefined,+ registry,+ );+ expect(result.status).toBe("committed");+ if (result.status !== "committed") return;+ expect(ListMonitorFilterSchema.safeParse(result.filters).success).toBe(+ true,+ );+ expect(result.filters).toEqual([+ {+ column: "severity",+ type: "stringOptions",+ operator: "any of",+ value: ["ALERT", "WARNING"],+ },+ {+ column: "evaluatorId",+ type: "stringOptions",+ operator: "any of",+ value: ["eval-1"],+ },+ {+ column: "tags",+ type: "arrayOptions",+ operator: "all of",+ value: ["prod", "critical"],+ },+ ]);+ });+ it("offers evaluator filters only on the sidebar that owns the facet", () => {+ const scoped = monitorsFieldRegistry(getMonitorFilterConfig(false));+ expect(planCommit("evaluator:eval-1", undefined, scoped).status).toBe(+ "invalid",+ );+ expect(planCommit("name:alert", undefined, registry).status).toBe(+ "invalid",+ );+ });+});diff --git a/web/src/features/monitors/constants/monitorsSearchRegistry.ts b/web/src/features/monitors/constants/monitorsSearchRegistry.tsnew file mode 100644index 0000000000..b4e9075f30--- /dev/null+++ b/web/src/features/monitors/constants/monitorsSearchRegistry.ts@@ -0,0 +1,35 @@+import { ListMonitorFilterSchema } from "@langfuse/shared/monitors";+import type { FilterConfig } from "@/src/features/filters";+import { fieldRegistryFromColumns } from "@/src/features/search-bar/lib/fields";++export function monitorsFieldRegistry(config: FilterConfig) {+ const facetColumns = new Set(config.facets.map((facet) => facet.column));+ return fieldRegistryFromColumns(+ config.columnDefinitions.filter((column) => facetColumns.has(column.id)),+ {+ id: "monitors",+ allowFreeText: false,+ filterStateErrors: (filters) => {+ if (+ new Set(filters.map((filter) => filter.column)).size !==+ filters.length+ ) {+ return [+ "Alerts support one filter per field. Combine values in one group, such as severity:(ALERT OR WARNING).",+ ];+ }+ return ListMonitorFilterSchema.safeParse(filters).success+ ? []+ : [+ "This filter is not supported by alerts. Use severity, tags or an available evaluator.",+ ];+ },+ recentSearches: true,+ searchExamples: ["severity:ALERT", "tags:production"],+ fields: {+ tags: { aliases: ["tag"] },+ evaluatorId: { aliases: ["evaluator", "evaluator_id"] },+ },+ },+ );+}diff --git a/web/src/features/prompts/components/prompts-table.tsx b/web/src/features/prompts/components/prompts-table.tsxindex de57a48146..096a3a7e57 100644--- a/web/src/features/prompts/components/prompts-table.tsx+++ b/web/src/features/prompts/components/prompts-table.tsx@@ -1,5 +1,8 @@import { useEffect, useMemo } from "react";-import { normalizeOrderByForTable } from "@langfuse/shared";+import {+ normalizeOrderByForTable,+ TableViewPresetTableName,+} from "@langfuse/shared";import { DataTable } from "@/src/components/table/data-table";import {DataTableControlsProvider,@@ -26,7 +29,6 @@ import {import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";import { joinTableCoreAndMetrics } from "@/src/components/table/utils/joinTableCoreAndMetrics";import { Skeleton } from "@/src/components/ui/skeleton";-import { useDebounce } from "@/src/hooks/useDebounce";import { useFullTextSearch } from "@/src/components/table/use-cases/useFullTextSearch";import { useFolderPagination } from "@/src/features/folders/hooks/useFolderPagination";import { buildFullPath } from "@/src/features/folders/utils";@@ -35,6 +37,17 @@ import { createDateTableColumn } from "@/src/components/design-system/table/coluimport { createNumberTableColumn } from "@/src/components/design-system/table/columns/createNumberTableColumn";import { createTextTableColumn } from "@/src/components/design-system/table/columns/createTextTableColumn";+import {+ useColumnOrder,+ useColumnVisibility,+} from "@/src/features/column-visibility";+import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";+import { useTableViewFilterChange } from "@/src/components/table/table-view-presets/hooks/useTableViewFilterChange";+import { TableSearchBar } from "@/src/features/search-bar/components/TableSearchBar";+import { SearchScopeSelect } from "@/src/components/table/SearchScopeSelect";+import { toObservedOptions } from "@/src/features/search-bar/lib/observed-options";+import { PROMPTS_FIELD_REGISTRY } from "@/src/features/prompts/constants/promptsSearchRegistry";+type PromptTableRow = {id: string;name: string;@@ -255,10 +268,13 @@ export function PromptTable() {[promptFilterOptions.data],);+ const { viewControllersRef, onExplicitFilterStateChange } =+ useTableViewFilterChange();const queryFilter = useSidebarFilterState(promptFilterConfig,newFilterOptions,{+ onExplicitFilterStateChange,loading: promptFilterOptions.isPending,stateLocation: "urlAndSessionStorage",sessionFilterContextId: projectId ?? null,@@ -412,6 +428,57 @@ export function PromptTable() {},];+ const [columnVisibility, setColumnVisibility] =+ useColumnVisibility<PromptTableRow>(+ "promptsColumnVisibility",+ promptColumns,+ );+ const [columnOrder, setColumnOrder] = useColumnOrder<PromptTableRow>(+ "promptsColumnOrder",+ promptColumns,+ );+ const { isLoading: isViewLoading, ...viewControllers } = useTableViewManager({+ tableName: TableViewPresetTableName.Prompts,+ projectId,+ stateUpdaters: {+ setColumnVisibility,+ setColumnOrder,+ setOrderBy: setOrderByState,+ setFilters: (filters) =>+ queryFilter.setFilterState(filters, { origin: "saved_view" }),+ setSearchQuery,+ setExpandedFilters: queryFilter.onExpandedChange,+ },+ validationContext: {+ columns: promptColumns,+ filterColumnDefinition: promptFilterConfig.columnDefinitions,+ expandableFilterColumns: promptFilterConfig.facets.map(+ (facet) => facet.column,+ ),+ },+ currentFilterState: queryFilter.explicitFilterState,+ currentExpandedFilters: queryFilter.expanded,+ });+ viewControllersRef.current = viewControllers;+ const handleSearchQueryChange = (query: string | null) => {+ viewControllers.handleUserStateChange(searchQuery ?? "", query ?? "");+ setSearchQuery(query);+ };+ const handleSearchTypeChange = (next: typeof searchType) => {+ viewControllers.handleUserStateChange(searchType, next);+ setSearchType(next);+ };+ const handleColumnOrderChange: typeof setColumnOrder = (next) => {+ const value = typeof next === "function" ? next(columnOrder) : next;+ viewControllers.handleUserStateChange(columnOrder, value);+ setColumnOrder(value);+ };+ const handleColumnVisibilityChange: typeof setColumnVisibility = (next) => {+ const value = typeof next === "function" ? next(columnVisibility) : next;+ viewControllers.handleUserStateChange(columnVisibility, value);+ setColumnVisibility(value);+ };+return (<DataTableControlsProvidertableName={promptFilterConfig.tableName}@@ -425,41 +492,69 @@ export function PromptTable() {navigateToFolder={navigateToFolder}/>)}+ <TableSearchBar+ key={`${projectId}:${viewControllers.filterEditorResetKey}:${queryFilter.draftResetKey}`}+ projectId={projectId}+ tableName="prompts"+ registry={PROMPTS_FIELD_REGISTRY}+ filterState={queryFilter.searchBarFilterState}+ setFilterState={queryFilter.setFilterState}+ observed={toObservedOptions(+ newFilterOptions,+ promptFilterOptions.isPending,+ )}+ isV4={false}+ search={{+ query: searchQuery,+ type: searchType,+ setQuery: handleSearchQueryChange,+ }}+ searchScope={+ <SearchScopeSelect+ searchType={searchType}+ setSearchType={handleSearchTypeChange}+ metadataLabel="Names, Tags"+ fullTextLabel="Full Text"+ availableSearchTypes={{+ content: true,+ input: false,+ output: false,+ }}+ />+ }+ /><DataTableToolbartableName="prompts"columns={promptColumns}filterState={queryFilter.filterState}columnsWithCustomSelect={["labels", "tags"]}- searchConfig={{- metadataSearchFields: ["Name", "Tags", "Content"],- updateQuery: useDebounce(setSearchQuery, 300),- currentQuery: searchQuery ?? undefined,- tableAllowsFullTextSearch: true,- setSearchType,- searchType,- customDropdownLabels: {- metadata: "Names, Tags",- fullText: "Full Text",- },- hidePerformanceWarning: true,- availableSearchTypes: {- content: true,- input: false,- output: false,- },+ isV4={false}+ currentSearchQuery={searchQuery ?? ""}+ orderByState={orderBy}+ columnOrder={columnOrder}+ setColumnOrder={handleColumnOrderChange}+ columnVisibility={columnVisibility}+ setColumnVisibility={handleColumnVisibilityChange}+ viewConfig={{+ tableName: TableViewPresetTableName.Prompts,+ projectId,+ controllers: viewControllers,}}/>{/* Content area with sidebar and table */}<ResizableFilterLayout>- <DataTableControls queryFilter={queryFilter} />+ <DataTableControls+ key={viewControllers.filterEditorResetKey}+ queryFilter={queryFilter}+ /><div className="flex flex-1 flex-col overflow-hidden"><DataTabletableName="prompts"columns={promptColumns}data={- prompts.isLoading+ prompts.isLoading || isViewLoading? { isLoading: true, isError: false }: prompts.isError? {@@ -484,7 +579,14 @@ export function PromptTable() {}}orderBy={orderBy}- setOrderBy={setOrderByState}+ setOrderBy={(next) => {+ viewControllers.handleUserStateChange(orderByState, next);+ setOrderByState(next);+ }}+ columnOrder={columnOrder}+ onColumnOrderChange={handleColumnOrderChange}+ columnVisibility={columnVisibility}+ onColumnVisibilityChange={handleColumnVisibilityChange}pagination={{totalCount,onChange: setPaginationAndFolderState,diff --git a/web/src/features/prompts/constants/promptsSearchRegistry.clienttest.ts b/web/src/features/prompts/constants/promptsSearchRegistry.clienttest.tsnew file mode 100644index 0000000000..b05265bf96--- /dev/null+++ b/web/src/features/prompts/constants/promptsSearchRegistry.clienttest.ts@@ -0,0 +1,65 @@+import { describe, expect, it } from "vitest";+import { PROMPTS_FIELD_REGISTRY } from "./promptsSearchRegistry";+import { planCommit } from "@/src/features/search-bar/lib/commit";+import { filterStateToQueryText } from "@/src/features/search-bar/lib/filter-state-to-query";++describe("prompt search contract", () => {+ it("round trips the sidebar filters alongside the existing free-text lane", () => {+ const result = planCommit(+ 'type:chat label:production tags:(support AND qa) version:>1 "refund policy"',+ undefined,+ PROMPTS_FIELD_REGISTRY,+ );+ expect(result.status).toBe("committed");+ if (result.status !== "committed") return;+ expect(result.searchQuery).toBe("refund policy");+ expect(result.filters).toEqual([+ {+ column: "type",+ type: "stringOptions",+ operator: "any of",+ value: ["chat"],+ },+ {+ column: "labels",+ type: "arrayOptions",+ operator: "any of",+ value: ["production"],+ },+ {+ column: "tags",+ type: "arrayOptions",+ operator: "all of",+ value: ["support", "qa"],+ },+ { column: "version", type: "number", operator: ">", value: 1 },+ ]);+ const roundTrip = filterStateToQueryText(+ result.filters,+ { searchQuery: result.searchQuery, searchType: result.searchType },+ PROMPTS_FIELD_REGISTRY,+ );+ expect(roundTrip.skippedFilters).toEqual([]);+ expect(+ planCommit(roundTrip.text, undefined, PROMPTS_FIELD_REGISTRY),+ ).toMatchObject({+ status: "committed",+ filters: result.filters,+ searchQuery: "refund policy",+ });+ });+ it.each([+ "name:test",+ "input:test",+ "output:test",+ "metadata.foo:bar",+ "scores.quality:1",+ ])(+ "does not author a structured filter outside the prompt sidebar: %s",+ (query) => {+ expect(planCommit(query, undefined, PROMPTS_FIELD_REGISTRY).status).toBe(+ "invalid",+ );+ },+ );+});diff --git a/web/src/features/prompts/constants/promptsSearchRegistry.ts b/web/src/features/prompts/constants/promptsSearchRegistry.tsnew file mode 100644index 0000000000..bafd65159c--- /dev/null+++ b/web/src/features/prompts/constants/promptsSearchRegistry.ts@@ -0,0 +1,23 @@+import { promptFilterConfig } from "@/src/features/filters/config/prompts-config";+import { fieldRegistryFromColumns } from "@/src/features/search-bar/lib/fields";++const facetColumns = new Set(+ promptFilterConfig.facets.map((facet) => facet.column),+);++export const PROMPTS_FIELD_REGISTRY = fieldRegistryFromColumns(+ promptFilterConfig.columnDefinitions.filter((column) =>+ facetColumns.has(column.id),+ ),+ {+ id: "prompts",+ allowFreeText: true,+ freeTextScopeLabel: "prompt names, tags and content",+ recentSearches: true,+ searchExamples: ["type:chat", "labels:production", "version:>1"],+ fields: {+ labels: { aliases: ["label"] },+ tags: { aliases: ["tag"] },+ },+ },+);diff --git a/web/src/features/scores/README.md b/web/src/features/scores/README.mdindex 8e9fe033fb..2510e863ee 100644--- a/web/src/features/scores/README.md+++ b/web/src/features/scores/README.md@@ -6,12 +6,13 @@ Score rendering, annotation forms, mutations, and the project Scores search bar.edits the table's existing sidebar filter state; the only local state is theshared editor's draft. It uses the table's filter-option response.- `constants/scoresSearchRegistry.ts` derives the grammar from the Scores- sidebar's facets. Bare text searches within score names; exact selections,+ sidebar's facets, excluding parent-owned fields in scoped tables. Bare text+ searches within score names; exact selections,numeric ranges, boolean values, and categorical values retain their existingfilter shapes. There is no independent full-text search or aggregate-scorenamespace.- `components/table/use-cases/scores.tsx` (under `src/`) owns data fetching,- URL/saved-view filters, and the table. It mounts the bar only for the full-page- v4 table; scoped embeds and chart mode have different filter contracts.+ URL/saved-view filters, and the table. Sidebar tables share the bar and pass+ their filter configuration so the grammar matches their available facets.The shared grammar and extension contract live in `features/search-bar/README.md`.diff --git a/web/src/features/scores/components/ScoresSearchBar.tsx b/web/src/features/scores/components/ScoresSearchBar.tsxindex c61335266e..5adc90ed2f 100644--- a/web/src/features/scores/components/ScoresSearchBar.tsx+++ b/web/src/features/scores/components/ScoresSearchBar.tsx@@ -1,49 +1,41 @@import type { FilterState } from "@langfuse/shared";-import { EventsSearchBarRow } from "@/src/features/search-bar/components/EventsSearchBarRow";-import { useEventsSearchBar } from "@/src/features/search-bar/hooks/useEventsSearchBar";-import { DEFAULT_SEARCH_TYPE } from "@/src/features/search-bar/lib/commit";+import { useMemo } from "react";+import type { FilterConfig } from "@/src/features/filters/lib/filter-config";+import { TableSearchBar } from "@/src/features/search-bar/components/TableSearchBar";import { toObservedOptions } from "@/src/features/search-bar/lib/observed-options";-import { SCORES_FIELD_REGISTRY } from "@/src/features/scores/constants/scoresSearchRegistry";--const noSearchLane = () => {};+import { scoresFieldRegistry } from "@/src/features/scores/constants/scoresSearchRegistry";export function ScoresSearchBar({projectId,+ isV4,+ filterConfig,filterState,setFilterState,filterOptions,isLoading,}: {projectId: string;+ isV4: boolean;+ filterConfig: FilterConfig;filterState: FilterState;setFilterState: (filters: FilterState) => void;filterOptions: Parameters<typeof toObservedOptions>[0];isLoading: boolean;}) {+ const registry = useMemo(+ () => scoresFieldRegistry(filterConfig),+ [filterConfig],+ );const observed = toObservedOptions(filterOptions, isLoading);- const { store, commit, applyFilters } = useEventsSearchBar({- projectId,- tableName: "scores",- enabled: true,- filterState,- searchQuery: null,- searchType: DEFAULT_SEARCH_TYPE,- observed,- setFilterState,- setSearchQuery: noSearchLane,- setSearchType: noSearchLane,- registry: SCORES_FIELD_REGISTRY,- });-return (- <EventsSearchBarRow+ <TableSearchBarprojectId={projectId}tableName="scores"- store={store}- commit={commit}+ isV4={isV4}+ filterState={filterState}+ setFilterState={setFilterState}observed={observed}- onApplyFilters={applyFilters}- registry={SCORES_FIELD_REGISTRY}+ registry={registry}/>);}diff --git a/web/src/features/scores/constants/scoresSearchRegistry.ts b/web/src/features/scores/constants/scoresSearchRegistry.tsindex 24aaa15fbd..d8f97b8549 100644--- a/web/src/features/scores/constants/scoresSearchRegistry.ts+++ b/web/src/features/scores/constants/scoresSearchRegistry.ts@@ -1,50 +1,55 @@import { getScoreFilterConfig } from "@/src/features/filters/config/scores-config";+import type { FilterConfig } from "@/src/features/filters/lib/filter-config";import { fieldRegistryFromColumns } from "@/src/features/search-bar/lib/fields";-const config = getScoreFilterConfig();-const facetColumns = new Set(config.facets.map((facet) => facet.column));--export const SCORES_FIELD_REGISTRY = fieldRegistryFromColumns(- config.columnDefinitions.filter((column) => facetColumns.has(column.id)),- {- id: "scores",- metadata: true,- scores: false,- traceScores: false,- // Scores has no full-text lane. Bare text becomes a visible name filter.- allowFreeText: false,- defaultTextField: "name",- recentSearches: true,- aiFilterPrompt: false,- hasExample: "userId",- searchExamples: [- "name:helpfulness",- 'name:("Rouge Score" OR confidence)',- "source:EVAL",- "value:<0.5",- ],- fields: {- name: {- aliases: ["scoreName", "score_name"],- label: "Score name",- description: "Search within score names",- syncMode: "textSearch",- suggestObservedValues: true,- },- environment: { aliases: ["env"] },- dataType: { aliases: ["type", "data_type"] },- value: { label: "Numeric value" },- booleanValue: { aliases: ["boolean_value"] },- stringValue: {- aliases: ["category", "string_value"],- label: "Categorical value",+export function scoresFieldRegistry(config: FilterConfig) {+ const facetColumns = new Set(config.facets.map((facet) => facet.column));+ return fieldRegistryFromColumns(+ config.columnDefinitions.filter((column) => facetColumns.has(column.id)),+ {+ id: "scores",+ metadata: facetColumns.has("metadata"),+ scores: false,+ traceScores: false,+ // Scores has no full-text lane. Bare text becomes a visible name filter.+ allowFreeText: false,+ defaultTextField: "name",+ recentSearches: true,+ aiFilterPrompt: false,+ hasExample: facetColumns.has("userId") ? "userId" : undefined,+ searchExamples: [+ "name:helpfulness",+ 'name:("Rouge Score" OR confidence)',+ "source:EVAL",+ "value:<0.5",+ ],+ fields: {+ name: {+ aliases: ["scoreName", "score_name"],+ label: "Score name",+ description: "Search within score names",+ syncMode: "textSearch",+ suggestObservedValues: true,+ },+ environment: { aliases: ["env"] },+ dataType: { aliases: ["type", "data_type"] },+ value: { label: "Numeric value" },+ booleanValue: { aliases: ["boolean_value"] },+ stringValue: {+ aliases: ["category", "string_value"],+ label: "Categorical value",+ },+ traceId: { aliases: ["trace_id"] },+ sessionId: { aliases: ["session_id"] },+ observationId: { aliases: ["observation_id"] },+ traceName: { aliases: ["trace_name"] },+ userId: { aliases: ["user", "user_id"] },+ tags: { aliases: ["tag", "traceTags", "trace_tags"] },},- traceId: { aliases: ["trace_id"] },- sessionId: { aliases: ["session_id"] },- observationId: { aliases: ["observation_id"] },- traceName: { aliases: ["trace_name"] },- userId: { aliases: ["user", "user_id"] },- tags: { aliases: ["tag", "traceTags", "trace_tags"] },},- },+ );+}++export const SCORES_FIELD_REGISTRY = scoresFieldRegistry(+ getScoreFilterConfig(),);diff --git a/web/src/features/search-bar/README.md b/web/src/features/search-bar/README.mdindex 72c8471cf9..a587374189 100644--- a/web/src/features/search-bar/README.md+++ b/web/src/features/search-bar/README.md@@ -1,27 +1,25 @@# Search Bar-Grammar-based query bar shared by the observations (v4 events) table,-evaluation-rule observation filters, sessions, experiments, and scores tables. On the events table it does NOT replace-the facet sidebar β it is an ADDITIONAL keyboard-driven editor that coexists-with the sidebar and stays in sync with it. The facet sidebar's `FilterState`-(+ the table's full-text search) remains the single source of truth; the bar-reads from and writes to it. Only the legacy toolbar search field is replaced-(full-text search goes inline in the bar). Generally available on the v4 events-tables (no opt-in). Based on the `langfuse-search-bar` prototype.+Grammar-based query editor for tables with a facet sidebar, including legacy+and embedded read paths. The sidebar's `FilterState` and the host's search+state remain canonical; both editors update the same state.## Enablement-- **Generally available on the v4 events tables** β every user gets the bar; it- is no longer a per-user Feature Preview opt-in. `hooks/useSearchBarEnabled.ts`- now returns `true` for everyone, so the bar renders wherever the v4 events- table does.-- `EventsTable` activates the bar when the table is a full-page surface- (`!hideControls && !externalFilterState && !peekContext && !userId && !sessionId`).- The **v4 beta** gate is implicit: `EventsTable` only mounts on the v4- Observations/Traces tables, so call sites still read as- `isV4 && useSearchBarEnabled()`.-- The search bar is not a Feature Preview and has no user or organization- toggle.+- Each sidebar host supplies a registry derived from its exposed facets. Settings+ lists and other tables without a sidebar retain their existing controls.+- `EventsTable` enables the bar when its controls are visible and filters are+ internally owned. Embedded tables exclude fields locked by their parent.+- `TableSearchBar` wraps the shared store, commit hook, and row for other hosts.+ Pass the host's existing search query and scope without changing their meaning.+ Tables without a backend text-search lane use a registry default field or+ disable free text. Organization catalogs omit `projectId`, which disables+ project recent searches and AI filtering.+- Key the wrapper by the saved-view `filterEditorResetKey` and sidebar+ `draftResetKey`. Applying a view or clearing filters resets unfinished drafts;+ deselecting a view after a user edit preserves them.+- There is no search-bar feature toggle. A registry enables AI only when its+ backend has a matching prompt and the organization enables AI features.## Query language@@ -406,11 +404,9 @@ derived from the same `eventsEvalFilterColumns` used by backend validation, andthe v4 sessions table passes `SESSIONS_FIELD_REGISTRY`(`features/filters/config/sessionsSearchRegistry.ts`).-**Pass the registry to BOTH halves.** `registry` is an optional prop defaulting-to `EVENTS_FIELD_REGISTRY` on `useEventsSearchBar` AND on `EventsSearchBarRow`.-Give it to the hook only and the view still _works_: commits validate against-the right fields while the autocomplete offers the events list. Nothing throws β-so a new view must check the field dropdown, not just that Enter applies.+**Use `TableSearchBar` for table hosts.** It passes one registry to the hook and+row. A specialized host that uses `useEventsSearchBar` and `EventsSearchBarRow`+directly must pass the same registry to both, so autocomplete and commits agree.**Recipe to add the bar to a view:**diff --git a/web/src/features/search-bar/components/AutocompleteListbox.tsx b/web/src/features/search-bar/components/AutocompleteListbox.tsxindex 1f1ad25bd0..701655d467 100644--- a/web/src/features/search-bar/components/AutocompleteListbox.tsx+++ b/web/src/features/search-bar/components/AutocompleteListbox.tsx@@ -73,7 +73,7 @@ export function AutocompleteListbox({data-testid="search-bar-autocomplete"data-stage={plan.stage}className={cn(- "w-max max-w-[calc(100vw-16px)] min-w-[min(420px,calc(100vw-16px))]",+ "ph-no-capture w-max max-w-[calc(100vw-16px)] min-w-[min(420px,calc(100vw-16px))]","max-h-[min(420px,40vh)] overflow-x-hidden overflow-y-auto","bg-popover text-popover-foreground rounded-md border py-1 shadow-md",)}diff --git a/web/src/features/search-bar/components/ComposerWithPreview.tsx b/web/src/features/search-bar/components/ComposerWithPreview.tsxindex f273c38410..33cdb638d2 100644--- a/web/src/features/search-bar/components/ComposerWithPreview.tsx+++ b/web/src/features/search-bar/components/ComposerWithPreview.tsx@@ -44,7 +44,7 @@ export function ComposerWithPreview();return (- <div className="relative grid">+ <div className="ph-no-capture relative grid"><divclassName={cn("col-start-1 row-start-1 min-w-0",diff --git a/web/src/features/search-bar/components/EventsSearchBarRow.tsx b/web/src/features/search-bar/components/EventsSearchBarRow.tsxindex 13fc77fdb5..bfb4f081fa 100644--- a/web/src/features/search-bar/components/EventsSearchBarRow.tsx+++ b/web/src/features/search-bar/components/EventsSearchBarRow.tsx@@ -35,9 +35,35 @@ import type { SearchBarStore } from "@/src/features/search-bar/store/searchBarStimport type { SearchCommit } from "@/src/features/search-bar/hooks/useEventsSearchBar";import type { QueryPresetSection } from "@/src/features/search-bar/lib/completions";-export function EventsSearchBarRow({+type EventsSearchBarRowProps = Omit<+ React.ComponentProps<typeof EventsSearchBarRowContent>,+ "aiFeaturesEnabled"+>;++export function EventsSearchBarRow(props: EventsSearchBarRowProps) {+ const registry = props.registry ?? EVENTS_FIELD_REGISTRY;+ return props.projectId && registry.aiFilterPrompt ? (+ <ProjectSearchBarRow {...props} />+ ) : (+ <EventsSearchBarRowContent {...props} aiFeaturesEnabled={false} />+ );+}++function ProjectSearchBarRow(props: EventsSearchBarRowProps) {+ const { organization } = useQueryProject();+ return (+ <EventsSearchBarRowContent+ {...props}+ aiFeaturesEnabled={Boolean(organization?.aiFeaturesEnabled)}+ />+ );+}++function EventsSearchBarRowContent({+ aiFeaturesEnabled,projectId,tableName,+ isV4 = true,store,commit,observed,@@ -53,9 +79,11 @@ export function EventsSearchBarRow({className,registry = EVENTS_FIELD_REGISTRY,}: {- projectId: string;+ aiFeaturesEnabled: boolean;+ projectId?: string;/** Table this bar filters β threaded to AI-prompt analytics (LFE-10781). */tableName: string;+ isV4?: boolean;store: SearchBarStore;commit: SearchCommit;observed: ObservedOptions | undefined;@@ -98,14 +126,25 @@ export function EventsSearchBarRow({registry?: FieldRegistry;}) {const [aiOpen, setAiOpen] = React.useState(false);- const { organization } = useQueryProject();// Mirror the legacy wand gate: org-level AI features. The server// enforces it too, so this only governs whether the affordance is offered.// Org entitlement AND a prompt written for this view β see// FieldRegistry.aiFilterPrompt. Without the second half a new surface silently// inherits the events prompt.+ const aiRegistryId =+ registry.id === "events" ||+ registry.id === "evaluationRules" ||+ registry.id === "evaluatorSamples" ||+ registry.id === "ruleSamples" ||+ registry.id === "sessions" ||+ registry.id === "scores" ||+ registry.id === "experiments" ||+ registry.id === "users"+ ? registry.id+ : undefined;const aiAvailable =- Boolean(organization?.aiFeaturesEnabled) && registry.aiFilterPrompt;+ Boolean(projectId && aiRegistryId && aiFeaturesEnabled) &&+ registry.aiFilterPrompt;const activateAi = React.useCallback(() => {// Ground the model on real project values: lazily request the AI columns so@@ -116,14 +155,15 @@ export function EventsSearchBarRow({return (<div className={cn("min-w-0 px-2 pt-2 pb-1", className)}>- {aiOpen && aiAvailable ? (+ {aiOpen && aiAvailable && aiRegistryId && projectId ? (<SearchBarAiPromptprojectId={projectId}tableName={tableName}+ isV4={isV4}store={store}dataContext={aiDataContext}scoreNames={aiScoreNames}- registryId={registry.id}+ registryId={aiRegistryId}onApply={onApplyFilters}onExit={() => setAiOpen(false)}/>diff --git a/web/src/features/search-bar/components/SearchBarAiPrompt.tsx b/web/src/features/search-bar/components/SearchBarAiPrompt.tsxindex 81e5af91d5..97af5cf636 100644--- a/web/src/features/search-bar/components/SearchBarAiPrompt.tsx+++ b/web/src/features/search-bar/components/SearchBarAiPrompt.tsx@@ -40,6 +40,7 @@ function unknownScoresMessage(names: string[]): string {export function SearchBarAiPrompt({projectId,tableName,+ isV4 = true,store,dataContext,scoreNames,@@ -50,6 +51,7 @@ export function SearchBarAiPrompt({projectId: string;/** Table this bar filters β the `tableName` analytics dimension. */tableName: string;+ isV4?: boolean;/** The bar store; its `draft` is read as the live refine context. */store: SearchBarStore;/** Observed values + metadata keys + result count, so the model maps to the@@ -59,7 +61,17 @@ export function SearchBarAiPrompt({* model's returned score keys against these (a misspelled name would* otherwise apply as a dead filter that silently matches nothing). */scoreNames?: ObservedScoreNames;- registryId?: FieldRegistry["id"];+ registryId?: Extract<+ FieldRegistry["id"],+ | "events"+ | "evaluationRules"+ | "evaluatorSamples"+ | "ruleSamples"+ | "sessions"+ | "scores"+ | "experiments"+ | "users"+ >;/** Apply generated filters via the bar's setFilterState (apply-immediately). */onApply: (filters: FilterState) => void;/** Leave AI mode and restore the grammar composer. */@@ -116,13 +128,12 @@ export function SearchBarAiPrompt({// mid-request; the model returns the COMPLETE set based on this snapshot.const refine = store.getState().draft.trim();const refineMode = refine.length > 0;- // Analytics (LFE-10781): METADATA ONLY β `promptLength` is a CHAR COUNT, the- // prompt text itself is never sent. Ask-AI is a v4-only surface (isV4 true).+ // Report prompt length, never prompt text. The host supplies its read path.capture("filters:ai_generate_requested", {tableName,refineMode,promptLength: prompt.length,- isV4: true,+ isV4,});try {const result = await generateFilter.mutateAsync({@@ -145,7 +156,7 @@ export function SearchBarAiPrompt({tableName,refineMode,reason: "stale",- isV4: true,+ isV4,});setError("Filters changed while generating β try again.");return;@@ -155,7 +166,7 @@ export function SearchBarAiPrompt({tableName,refineMode,reason: "empty",- isV4: true,+ isV4,});// A dropped unknown score name explains the empty result better than// the generic rephrase hint ("no such score X" beats a dead filter).@@ -170,7 +181,7 @@ export function SearchBarAiPrompt({tableName,refineMode,generatedFilterCount: result.filters.length,- isV4: true,+ isV4,});onApply(result.filters as FilterState);if (result.unknownScoreNames.length > 0) {@@ -194,7 +205,7 @@ export function SearchBarAiPrompt({tableName,refineMode,reason: "error",- isV4: true,+ isV4,});setError("Couldn't reach the AI service. Please try again.");}diff --git a/web/src/features/search-bar/components/SearchComposer.tsx b/web/src/features/search-bar/components/SearchComposer.tsxindex 6457ce2046..156ae6c2e3 100644--- a/web/src/features/search-bar/components/SearchComposer.tsx+++ b/web/src/features/search-bar/components/SearchComposer.tsx@@ -311,7 +311,7 @@ export function SearchComposer({freeTextReason,registry = EVENTS_FIELD_REGISTRY,}: {- projectId: string;+ projectId?: string;/** Observed facet values for value suggestions; undefined = loading. */observed: ObservedOptions | undefined;/** Columns whose lazy fetch terminally errored β settle the value-stage@@ -384,7 +384,7 @@ export function SearchComposer({// so the plan memo doesn't churn).const recents = React.useMemo(() =>- autocompleteOpen && draft.trim().length === 0+ projectId && autocompleteOpen && draft.trim().length === 0? getRecentSearches(projectId): NO_RECENTS,[autocompleteOpen, draft, projectId],@@ -1359,7 +1359,7 @@ export function SearchComposer({ref={containerRef}data-testid="search-bar"role="search"- className="relative w-full"+ className="ph-no-capture relative w-full"><divdata-testid="search-bar-surface"@@ -1575,7 +1575,7 @@ export function SearchComposer({}}className={cn(- "pointer-events-none fixed max-w-[min(360px,calc(100vw-32px))]",+ "ph-no-capture pointer-events-none fixed max-w-[min(360px,calc(100vw-32px))]","bg-popover rounded-md border","px-2 py-1 font-sans text-xs leading-snug shadow-md",errorTarget !== nulldiff --git a/web/src/features/search-bar/components/TableSearchBar.tsx b/web/src/features/search-bar/components/TableSearchBar.tsxnew file mode 100644index 0000000000..8706607def--- /dev/null+++ b/web/src/features/search-bar/components/TableSearchBar.tsx@@ -0,0 +1,77 @@+import type { ReactNode } from "react";+import type { FilterState, TracingSearchType } from "@langfuse/shared";+import { EventsSearchBarRow } from "./EventsSearchBarRow";+import { useEventsSearchBar } from "../hooks/useEventsSearchBar";+import { DEFAULT_SEARCH_TYPE } from "../lib/commit";+import type { FieldRegistry } from "../lib/fields";+import type { ObservedOptions } from "../lib/observed-options";++const noSearchLane = () => {};++export function TableSearchBar({+ projectId,+ tableName,+ registry,+ filterState,+ setFilterState,+ observed,+ isV4,+ search,+ searchScope,+ onRequestColumns,+ erroredColumns,+}: {+ projectId?: string;+ tableName: string;+ registry: FieldRegistry;+ filterState: FilterState;+ setFilterState: (filters: FilterState) => void;+ observed: ObservedOptions | undefined;+ isV4: boolean;+ search?: {+ query: string | null;+ type?: TracingSearchType[];+ setQuery: (query: string | null) => void;+ };+ searchScope?: ReactNode;+ onRequestColumns?: (columns: readonly string[]) => void;+ erroredColumns?: ReadonlySet<string>;+}) {+ // The host owns search scopes. Bare text edits its existing search lane+ // without translating a persisted scope into a different column filter.+ const { store, commit, applyFilters } = useEventsSearchBar({+ projectId,+ tableName,+ registry,+ enabled: true,+ isV4,+ filterState,+ setFilterState,+ observed,+ searchQuery: search?.query ?? null,+ setSearchQuery: search?.setQuery ?? noSearchLane,+ searchType: DEFAULT_SEARCH_TYPE,+ analyticsSearchType: search?.type ?? [],+ setSearchType: noSearchLane,+ });++ return (+ <div className="flex min-w-0 items-center gap-2">+ <div className="min-w-0 flex-1">+ <EventsSearchBarRow+ projectId={projectId}+ tableName={tableName}+ registry={registry}+ isV4={isV4}+ store={store}+ commit={commit}+ observed={observed}+ onApplyFilters={applyFilters}+ onRequestColumns={onRequestColumns}+ erroredColumns={erroredColumns}+ />+ </div>+ {searchScope}+ </div>+ );+}diff --git a/web/src/features/search-bar/hooks/useEventsSearchBar.clienttest.tsx b/web/src/features/search-bar/hooks/useEventsSearchBar.clienttest.tsxindex 43ff44a90c..db21b79c37 100644--- a/web/src/features/search-bar/hooks/useEventsSearchBar.clienttest.tsx+++ b/web/src/features/search-bar/hooks/useEventsSearchBar.clienttest.tsx@@ -1,11 +1,21 @@import { act, renderHook } from "@testing-library/react";-import { describe, expect, it, vi } from "vitest";+import { useState } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import type { FilterState } from "@langfuse/shared";+import type { FilterState, TracingSearchType } from "@langfuse/shared";import { DEFAULT_SEARCH_TYPE } from "@/src/features/search-bar/lib/commit";import { useEventsSearchBar } from "@/src/features/search-bar/hooks/useEventsSearchBar";import { SCORES_FIELD_REGISTRY } from "@/src/features/scores/constants/scoresSearchRegistry";+import * as recentSearches from "@/src/features/search-bar/lib/recent-searches";++afterEach(() => vi.restoreAllMocks());++const { capture } = vi.hoisted(() => ({ capture: vi.fn() }));+vi.mock("@/src/features/posthog-analytics", () => ({+ usePostHogClientCapture: () => capture,+}));+beforeEach(() => capture.mockClear());const NEW_FILTERS: FilterState = [{ type: "string", column: "name", operator: "contains", value: "checkout" },@@ -35,7 +45,159 @@ function setup(return { result, setFilterState, setSearchQuery, setSearchType };}+function setupSplitEcho() {+ const setSearchQuery = vi.fn();+ return {+ setSearchQuery,+ ...renderHook(+ ({ searchQuery }: { searchQuery: string | null }) => {+ const [filterState, setFilterState] = useState<FilterState>([]);+ return {+ ...useEventsSearchBar({+ projectId: "p",+ tableName: "observations",+ enabled: true,+ filterState,+ searchQuery,+ searchType: DEFAULT_SEARCH_TYPE,+ observed: undefined,+ setFilterState,+ setSearchQuery,+ setSearchType: vi.fn(),+ }),+ navigateToFilters: setFilterState,+ };+ },+ { initialProps: { searchQuery: null as string | null } },+ ),+ };+}+describe("useEventsSearchBar.commit", () => {+ it("keeps a mixed commit intact while the filter echoes before the search URL", () => {+ const { result, rerender, setSearchQuery } = setupSplitEcho();++ act(() =>+ result.current.store.getState().actions.setDraft("level:ERROR refund"),+ );+ act(() => result.current.commit("enter"));+ expect(result.current.store.getState().draft.trim()).toBe(+ "level:ERROR refund",+ );++ act(() => result.current.commit("blur"));+ expect(setSearchQuery).toHaveBeenLastCalledWith("refund");+ expect(capture).toHaveBeenCalledTimes(1);++ act(() =>+ result.current.store+ .getState()+ .actions.setDraft("level:ERROR refund next"),+ );+ rerender({ searchQuery: "refund" });+ expect(result.current.store.getState().draft).toBe(+ "level:ERROR refund next",+ );++ act(() => result.current.navigateToFilters([]));+ rerender({ searchQuery: null });+ expect(result.current.store.getState().draft).toBe("");+ });++ it("replaces a pending commit when an explicit draft reset matches a partial echo", () => {+ const { result, rerender } = setupSplitEcho();+ act(() =>+ result.current.store.getState().actions.setDraft("level:ERROR refund"),+ );+ act(() => result.current.commit("enter"));+ act(() =>+ result.current.resetDraft({+ filters: [+ {+ type: "stringOptions",+ column: "level",+ operator: "any of",+ value: ["ERROR"],+ },+ ],+ searchQuery: null,+ searchType: DEFAULT_SEARCH_TYPE,+ }),+ );+ rerender({ searchQuery: null });+ expect(result.current.store.getState().draft.trim()).toBe("level:ERROR");+ });++ it.each(["back", "different filters"])(+ "honors external navigation before all commit lanes acknowledge: %s",+ (navigation) => {+ const { result } = setupSplitEcho();+ act(() =>+ result.current.store.getState().actions.setDraft("level:ERROR refund"),+ );+ act(() => result.current.commit("enter"));+ if (navigation === "back") {+ act(() => window.dispatchEvent(new PopStateEvent("popstate")));+ act(() => result.current.navigateToFilters([]));+ expect(result.current.store.getState().draft).toBe("");+ } else {+ act(() => result.current.navigateToFilters(NEW_FILTERS));+ expect(result.current.store.getState().draft.trim()).toBe(+ "name:checkout",+ );+ }+ },+ );++ it.each<{ scope: TracingSearchType[] }>([+ { scope: ["id"] },+ { scope: ["id", "output"] },+ { scope: [] },+ ])(+ "reports the host's actual search scope without changing grammar lowering: $scope",+ ({ scope }) => {+ const { result, setSearchType } = setup({+ analyticsSearchType: scope,+ isV4: false,+ });+ act(() =>+ result.current.store+ .getState()+ .actions.setDraft("sensitive scope phrase"),+ );+ act(() => result.current.commit("enter"));+ expect(capture).toHaveBeenCalledWith(+ "filters:search_submitted",+ expect.objectContaining({ searchType: scope, isV4: false }),+ );+ expect(setSearchType).not.toHaveBeenCalled();+ expect(JSON.stringify(capture.mock.calls)).not.toContain(+ "sensitive scope phrase",+ );+ },+ );+ it("commits outside a project without writing project recent searches", () => {+ const recordRecentSearch = vi+ .spyOn(recentSearches, "recordRecentSearch")+ .mockImplementation(() => {});+ const { result, setFilterState } = setup({+ projectId: undefined,+ searchQuery: null,+ });+ act(() => result.current.store.getState().actions.setDraft("level:ERROR"));+ act(() => result.current.commit("enter"));++ expect(setFilterState).toHaveBeenCalledWith([+ {+ column: "level",+ type: "stringOptions",+ operator: "any of",+ value: ["ERROR"],+ },+ ]);+ expect(recordRecentSearch).not.toHaveBeenCalled();+ });+it("preserves a Scores saved-view filter the bar cannot represent", () => {const hiddenFilter: FilterState = [{diff --git a/web/src/features/search-bar/hooks/useEventsSearchBar.ts b/web/src/features/search-bar/hooks/useEventsSearchBar.tsindex 593f3a4c3e..5489192e0f 100644--- a/web/src/features/search-bar/hooks/useEventsSearchBar.ts+++ b/web/src/features/search-bar/hooks/useEventsSearchBar.ts@@ -8,12 +8,11 @@// β² β planCommit (pure)// βββββββββββββ setFilterState/β¦ βββ commit() ββββββ//-// There is exactly one effect (seed the draft when the derived committed text-// changes) and it never writes back to the filter state, so the cycle cannot-// loop β no reconciliation signature, no second source of truth. The bar is a-// controlled editor over the same state the facet sidebar edits.+// The draft sync never writes back to applied state. A commit acknowledgment+// keeps separately updated host lanes from projecting a half-applied query.import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import isEqual from "lodash/isEqual";import type { FilterState, TracingSearchType } from "@langfuse/shared";@@ -53,6 +52,39 @@ function sameScopes(a: TracingSearchType[], b: TracingSearchType[]): boolean {return a.every((s) => bs.has(s));}+type AppliedSearchState = {+ filters: FilterState;+ query: string | null;+ scopes: TracingSearchType[];+};+type PendingCommit = {+ previous: AppliedSearchState;+ next: AppliedSearchState;+ text: string;+};++function sameAppliedState(a: AppliedSearchState, b: AppliedSearchState) {+ return (+ isEqual(a.filters, b.filters) &&+ (a.query ?? "") === (b.query ?? "") &&+ sameScopes(a.scopes, b.scopes)+ );+}++function isPartialCommitEcho(+ state: AppliedSearchState,+ { previous, next }: PendingCommit,+) {+ return (+ (isEqual(state.filters, previous.filters) ||+ isEqual(state.filters, next.filters)) &&+ ((state.query ?? "") === (previous.query ?? "") ||+ (state.query ?? "") === (next.query ?? "")) &&+ (sameScopes(state.scopes, previous.scopes) ||+ sameScopes(state.scopes, next.scopes))+ );+}+/*** The resting draft carries a trailing space when non-empty β the "ready for the* next filter" affordance. Baking it into the DERIVED committed text (and the@@ -77,23 +109,28 @@ export function useEventsSearchBar({projectId,tableName,enabled,+ isV4 = true,filterState,searchQuery,searchType,+ analyticsSearchType,observed,setFilterState,setSearchQuery,setSearchType,registry = EVENTS_FIELD_REGISTRY,}: {- projectId: string;+ projectId?: string;/** Table this bar filters β the `tableName` analytics dimension. */tableName: string;enabled: boolean;+ isV4?: boolean;/** Search-bar projection of the user's explicit facet filters. */filterState: FilterState;searchQuery: string | null;searchType: TracingSearchType[];+ /** The host's applied scope when grammar projection uses a different scope. */+ analyticsSearchType?: TracingSearchType[];/** Observed filter options β used to route `scores.<name>` by score type. */observed: ObservedOptions | undefined;setFilterState: (filters: FilterState) => void;@@ -104,6 +141,11 @@ export function useEventsSearchBar({store: SearchBarStore;commit: SearchCommit;applyFilters: (filters: FilterState) => void;+ resetDraft: (state: {+ filters: FilterState;+ searchQuery: string | null;+ searchType: TracingSearchType[];+ }) => void;} {const capture = usePostHogClientCapture();@@ -121,6 +163,34 @@ export function useEventsSearchBar({),);+ const appliedState = {+ filters: filterState,+ query: searchQuery,+ scopes: searchType,+ };+ const appliedStateRef = useRef(appliedState);+ appliedStateRef.current = appliedState;+ const pendingCommitRef = useRef<PendingCommit | null>(null);+ const pending = pendingCommitRef.current;+ if (+ pending &&+ (sameAppliedState(appliedState, pending.next) ||+ !isPartialCommitEcho(appliedState, pending))+ ) {+ pendingCommitRef.current = null;+ }++ const cancelPendingCommit = useCallback(() => {+ pendingCommitRef.current = null;+ }, []);++ // Back/Forward is an explicit external navigation, even when it restores+ // exactly the values from before an unacknowledged commit.+ useEffect(() => {+ window.addEventListener("popstate", cancelPendingCommit);+ return () => window.removeEventListener("popstate", cancelPendingCommit);+ }, [cancelPendingCommit]);+// Committed query DERIVED from the single source of truth (pure). `skipped`// are filters that have no grammar form β the bar can't show them, so they// must be preserved across a commit instead of being silently wiped.@@ -133,7 +203,8 @@ export function useEventsSearchBar({),[filterState, registry, searchQuery, searchType],);- const committedText = restingDraft(derived.text);+ const committedText =+ pendingCommitRef.current?.text ?? restingDraft(derived.text);const skippedFiltersRef = useRef(derived.skippedFilters);skippedFiltersRef.current = derived.skippedFilters;@@ -175,6 +246,41 @@ export function useEventsSearchBar({return preserved.length > 0 ? [...filters, ...preserved] : filters;}, []);+ const beginCommit = useCallback(+ (next: AppliedSearchState) => {+ const text = restingDraft(+ filterStateToQueryText(+ next.filters,+ { searchQuery: next.query, searchType: next.scopes },+ registry,+ ).text,+ );+ pendingCommitRef.current = {+ previous: appliedStateRef.current,+ next,+ text,+ };+ return text;+ },+ [registry],+ );++ const resetDraft = useCallback(+ (state: {+ filters: FilterState;+ searchQuery: string | null;+ searchType: TracingSearchType[];+ }) => {+ const text = beginCommit({+ filters: state.filters,+ query: state.searchQuery,+ scopes: state.searchType,+ });+ store.getState().actions.setDraft(text);+ },+ [beginCommit, store],+ );+// Apply an externally-produced filter set (the AI filter generator) the same// way a commit does β preserving skipped filters β instead of a raw replace// that would silently drop them. The model receives the bar's full committed@@ -188,13 +294,19 @@ export function useEventsSearchBar({(filters: FilterState) => {const { setFilterState, setSearchQuery, setSearchType } =applyRef.current;- setFilterState(mergeWithSkipped(filters));+ const committedFilters = mergeWithSkipped(filters);+ beginCommit({+ filters: committedFilters,+ query: null,+ scopes: DEFAULT_SEARCH_TYPE,+ });+ setFilterState(committedFilters);setSearchQuery(null);if (!sameScopes(DEFAULT_SEARCH_TYPE, searchTypeRef.current)) {setSearchType(DEFAULT_SEARCH_TYPE);}},- [mergeWithSkipped],+ [beginCommit, mergeWithSkipped],);// The committed text at the last render β the dedup baseline so a blur that@@ -220,13 +332,8 @@ export function useEventsSearchBar({);if (result.status === "invalid") {store.getState().actions.revealInvalid();- // Analytics (LFE-10781): a non-empty typed query was rejected (a UI- // error). METADATA ONLY β `orAttempted`/`reason` come from the AST shape- // + static diagnostic messages, `queryLength` is a char count; the query- // TEXT is never sent. The grammar bar is v4-only, so isV4 is always true.- // `orAttempted:true` (an OR between conditions β the parked cross-field- // OR, LFE-10421) is the headline demand signal. Fires once per failed- // commit: a blur that re-fails the same input is deduped.+ // Report diagnostic metadata and query length, never query text.+ // A blur that rejects the same draft twice is deduplicated.const trimmed = draftText.trim();const isBlurRefail =trigger === "blur" && draftText === lastErrorTextRef.current;@@ -241,7 +348,7 @@ export function useEventsSearchBar({reason,queryLength: trimmed.length,trigger,- isV4: true,+ isV4,});}lastErrorTextRef.current = draftText;@@ -258,6 +365,13 @@ export function useEventsSearchBar({const committedFilters = options.replaceHidden? result.filters: mergeWithSkipped(result.filters);+ // Register the full write before the optimistic filter setter can render+ // ahead of the URL-backed search query or scope setters.+ const committed = beginCommit({+ filters: committedFilters,+ query: result.searchQuery,+ scopes: result.searchType,+ });setFilterState(committedFilters);setSearchQuery(result.searchQuery);// Only write searchType when it actually changed. planCommit coerces a@@ -268,46 +382,39 @@ export function useEventsSearchBar({if (!sameScopes(result.searchType, searchTypeRef.current)) {setSearchType(result.searchType);}- if (result.canonical.length > 0) {+ if (projectId && result.canonical.length > 0) {recordRecentSearch(projectId, result.canonical);}- // Return the CANONICAL committed text in its RESTING form (trailing space) β- // exactly what the resetTo effect re-derives on the next render (same- // filters + searchQuery/searchType). The composer drops the caret after it,- // so the echo string-compares equal and the space survives even when the- // commit reorders the query (e.g. `refund level:ERROR` β `level:ERROR refund`).- const committed = restingDraft(- filterStateToQueryText(- committedFilters,- {- searchQuery: result.searchQuery,- searchType: result.searchType,- },- registry,- ).text,- );-- // Analytics (LFE-10781). METADATA ONLY β `queryLength` is a CHAR COUNT, we- // never send the query text itself. A blur that produced no change is a- // no-op (the resting draft re-settling), so it does not emit; an explicit- // enter/pick always counts even when re-submitting the same query. The- // grammar bar is a v4-only surface, so isV4 is always true.+ // Report query shape and length, never text. An unchanged blur is a+ // no-op; an explicit submission counts even for the same query.if (trigger !== "blur" || committed !== committedTextRef.current) {capture("filters:search_submitted", {tableName,filterCount: committedFilters.length,hasFreeText: (result.searchQuery ?? "").trim().length > 0,- searchType: result.searchType,+ searchType: analyticsSearchType ?? result.searchType,queryLength: committed.trim().length,trigger,- isV4: true,+ isV4,});}+ committedTextRef.current = committed;+return committed;},- [store, projectId, tableName, mergeWithSkipped, capture, registry],+ [+ store,+ projectId,+ tableName,+ mergeWithSkipped,+ capture,+ registry,+ isV4,+ analyticsSearchType,+ beginCommit,+ ],);- return { store, commit, applyFilters };+ return { store, commit, applyFilters, resetDraft };}diff --git a/web/src/features/search-bar/index.ts b/web/src/features/search-bar/index.tsindex a2035f9691..5c8d7f65d9 100644--- a/web/src/features/search-bar/index.ts+++ b/web/src/features/search-bar/index.ts@@ -6,6 +6,7 @@// would close a runtime cycle.export { ComposerTokens } from "@/src/features/search-bar/components/ComposerTokens";export { EventsSearchBarRow } from "@/src/features/search-bar/components/EventsSearchBarRow";+export { TableSearchBar } from "@/src/features/search-bar/components/TableSearchBar";export {COMPOSER_SURFACE_CLASSES,COMPOSER_TEXT_CLASSES,diff --git a/web/src/features/search-bar/lib/adapter.ts b/web/src/features/search-bar/lib/adapter.tsindex b2a83f2e96..21dcb76b35 100644--- a/web/src/features/search-bar/lib/adapter.ts+++ b/web/src/features/search-bar/lib/adapter.ts@@ -161,6 +161,7 @@ export function astToFilterState(}const defaultTextFilter = lowerDefaultTextField(ctx);+ ctx.errors.push(...(registry.filterStateErrors?.(ctx.filters) ?? []));return {filters: ctx.filters,diff --git a/web/src/features/search-bar/lib/fields.ts b/web/src/features/search-bar/lib/fields.tsindex f224deae45..c92905f4c5 100644--- a/web/src/features/search-bar/lib/fields.ts+++ b/web/src/features/search-bar/lib/fields.ts@@ -19,6 +19,7 @@import {eventsTableCols,type ColumnDefinition,+ type FilterState,type SingleValueOption,} from "@langfuse/shared";@@ -78,10 +79,22 @@ export type FieldRegistry = {| "sessions"| "scores"| "experiments"- | "users";+ | "users"+ | "traces"+ | "observations"+ | "evaluatorsList"+ | "evaluationRulesList"+ | "legacyEvaluators"+ | "evalLogs"+ | "prompts"+ | "monitors"+ | "gatewayModels"+ | "experimentItems";fields: readonly FieldDef[];columns: readonly ColumnDefinition[];allowFreeText: boolean;+ /** View-specific backend constraints beyond individual column operators. */+ filterStateErrors?: (filters: FilterState) => readonly string[];metadata: boolean;scores: boolean;/** Trace-level `traceScores.<name>` paths. Views whose backend has no@@ -159,6 +172,7 @@ export function fieldRegistryFromColumns(/** Defaults to `scores`. */traceScores?: boolean;allowFreeText?: boolean;+ filterStateErrors?: (filters: FilterState) => readonly string[];defaultTextField?: string;freeTextScopeLabel?: string;searchExamples?: readonly string[];@@ -222,6 +236,7 @@ export function fieldRegistryFromColumns(scores,traceScores: overlay.traceScores ?? scores,allowFreeText: overlay.allowFreeText ?? true,+ filterStateErrors: overlay.filterStateErrors,defaultTextField: overlay.defaultTextField ?? null,freeTextScopeLabel: overlay.freeTextScopeLabel ?? null,searchExamples: overlay.searchExamples ?? [],@@ -250,6 +265,7 @@ export function extendFieldRegistryWithColumns(scores: registry.scores,traceScores: registry.traceScores,allowFreeText: registry.allowFreeText,+ filterStateErrors: registry.filterStateErrors,defaultTextField: registry.defaultTextField,freeTextScopeLabel: registry.freeTextScopeLabel,searchExamples: registry.searchExamples,@@ -293,6 +309,7 @@ export function withFieldOptions(scores: registry.scores,traceScores: registry.traceScores,allowFreeText: registry.allowFreeText,+ filterStateErrors: registry.filterStateErrors,defaultTextField: registry.defaultTextField,freeTextScopeLabel: registry.freeTextScopeLabel,searchExamples: registry.searchExamples,@@ -414,6 +431,7 @@ export function createFieldRegistry({scores,traceScores,allowFreeText,+ filterStateErrors,defaultTextField,freeTextScopeLabel,searchExamples,@@ -429,6 +447,8 @@ export function createFieldRegistry({scores: boolean;traceScores: boolean;allowFreeText: boolean;+ /** View-specific backend constraints beyond individual column operators. */+ filterStateErrors?: (filters: FilterState) => readonly string[];defaultTextField: string | null;freeTextScopeLabel: string | null;searchExamples: readonly string[];@@ -462,6 +482,7 @@ export function createFieldRegistry({fields,columns,allowFreeText,+ filterStateErrors,metadata,scores,traceScores,diff --git a/web/src/features/search-bar/lib/searchBarInvariants.clienttest.ts b/web/src/features/search-bar/lib/searchBarInvariants.clienttest.tsindex fe58056f67..f82512965b 100644--- a/web/src/features/search-bar/lib/searchBarInvariants.clienttest.ts+++ b/web/src/features/search-bar/lib/searchBarInvariants.clienttest.ts@@ -13,11 +13,22 @@ import {RULE_SAMPLE_FIELD_REGISTRY,} from "@/src/features/evals/v2/constants/evaluatorSearchRegistry";import { SESSIONS_FIELD_REGISTRY } from "@/src/features/filters";+import { sessionsFieldRegistry } from "@/src/features/filters/config/sessionsSearchRegistry";+import { getSessionFilterConfig } from "@/src/features/filters/config/sessions-config";import { usersEventsFilterConfig } from "@/src/features/filters/config/users-config";-import { USERS_FIELD_REGISTRY } from "@/src/features/filters/config/usersSearchRegistry";+import {+ USERS_FIELD_REGISTRY,+ LEGACY_USERS_FIELD_REGISTRY,+} from "@/src/features/filters/config/usersSearchRegistry";import { EXPERIMENTS_FIELD_REGISTRY } from "@/src/features/experiments/constants/experimentsSearchRegistry";-import { SCORES_FIELD_REGISTRY } from "@/src/features/scores/constants/scoresSearchRegistry";-import { getScoreFilterConfig } from "@/src/features/filters/config/scores-config";+import {+ SCORES_FIELD_REGISTRY,+ scoresFieldRegistry,+} from "@/src/features/scores/constants/scoresSearchRegistry";+import {+ getScoreFilterConfig,+ type ScoresTableHiddenColumn,+} from "@/src/features/filters/config/scores-config";import type { FilterState } from "@langfuse/shared";import { validateQuery } from "./validate";import { DEFAULT_SEARCH_TYPE, planCommit } from "./commit";@@ -34,6 +45,77 @@ import {} from "./searchBarInvariants";describe("search bar invariants β Scores registry", () => {+ it("preserves parent-owned filters as skipped and rejects conflicting scoped fields", () => {+ const hiddenColumns: ScoresTableHiddenColumn[] = [+ "traceId",+ "observationId",+ "traceName",+ "userId",+ "traceTags",+ "jobConfigurationId",+ ];+ const registry = scoresFieldRegistry(getScoreFilterConfig(hiddenColumns));+ const parentFilters: FilterState = [+ { column: "traceId", type: "string", operator: "=", value: "trace" },+ {+ column: "observationId",+ type: "stringOptions",+ operator: "any of",+ value: ["", "observation"],+ },+ {+ column: "traceName",+ type: "stringOptions",+ operator: "any of",+ value: ["parent"],+ },+ {+ column: "userId",+ type: "stringOptions",+ operator: "any of",+ value: ["user"],+ },+ {+ column: "tags",+ type: "arrayOptions",+ operator: "all of",+ value: ["parent"],+ },+ ];+ const visibleFilter: FilterState = [+ {+ column: "name",+ type: "string",+ operator: "contains",+ value: "quality",+ },+ ];+ expect(+ filterStateToQueryText(+ [...parentFilters, ...visibleFilter],+ {},+ registry,+ ),+ ).toMatchObject({ text: "name:quality", skippedFilters: parentFilters });+ for (const query of [+ "trace_id:other",+ "observation_id:other",+ "trace_name:other",+ "user:other",+ "traceTags:other",+ "has:userId",+ ]) {+ expect(planCommit(query, undefined, registry).status, query).toBe(+ "invalid",+ );+ }+ expect(planCommit("quality", undefined, registry)).toMatchObject({+ status: "committed",+ filters: visibleFilter,+ });+ expect(registry.hasExample).toBeNull();+ });+it("searches within a score name", () => {const result = planCommit("Rouge Score", undefined, SCORES_FIELD_REGISTRY);expect(result).toMatchObject({@@ -685,6 +767,24 @@ const sessionsView: RegistryUnderTest = {};describe("search bar invariants β sessions registry", () => {+ it.each([false, true])(+ "offers only executable examples inside a user detail table (events: %s)",+ (fromEvents) => {+ const registry = sessionsFieldRegistry(+ getSessionFilterConfig(["userIds"], fromEvents),+ );+ const examples = [+ ...registry.searchExamples,+ ...(registry.hasExample ? [`has:${registry.hasExample}`] : []),+ ];+ for (const example of examples) {+ expect(planCommit(example, undefined, registry).status, example).toBe(+ "committed",+ );+ }+ },+ );+it("holds all three invariants (parity, round-trip, serialize symmetry)", () => {const failures = runSearchBarInvariants(sessionsView);expect(@@ -999,6 +1099,48 @@ const usersView: RegistryUnderTest = {};describe("search bar invariants β users registry", () => {+ it("preserves legacy user metadata while rejecting fields that require joins", () => {+ const registry = LEGACY_USERS_FIELD_REGISTRY;+ const filters: FilterState = [+ {+ type: "stringObject",+ column: "metadata",+ key: "region",+ operator: "=",+ value: "eu",+ },+ ];+ const projection = filterStateToQueryText(filters, {}, registry);+ expect(projection.skippedFilters).toEqual([]);+ expect(planCommit(projection.text, undefined, registry)).toMatchObject({+ status: "committed",+ filters,+ });+ expect(+ runSearchBarInvariants({+ ...usersView,+ name: "users legacy",+ registry,+ sidebarFilters: [filters],+ }),+ ).toEqual([]);+ for (const query of [+ "level:ERROR",+ "latency:>1",+ "scores.quality:>0.8",+ "traceScores.nps:>5",+ "comment:test",+ "input:test",+ ]) {+ expect(planCommit(query, undefined, registry).status).toBe("invalid");+ }+ expect(planCommit("alice smith", undefined, registry)).toMatchObject({+ status: "committed",+ searchQuery: "alice smith",+ filters: [],+ });+ });+it("holds all three invariants (parity, round-trip, serialize symmetry)", () => {const failures = runSearchBarInvariants(usersView);expect(diff --git a/web/src/features/search-bar/lib/validate.ts b/web/src/features/search-bar/lib/validate.tsindex 0a4eb0e25b..63067dabc8 100644--- a/web/src/features/search-bar/lib/validate.ts+++ b/web/src/features/search-bar/lib/validate.ts@@ -216,8 +216,11 @@ export function semanticDiagnostics(// scoreTypes the commit-time lowering does, or the two disagree on score// routing and a clean validation hides an error the commit then drops.const topLevel: ASTNode[] = ast.kind === "and" ? ast.children : [ast];+ const termRegistry = registry.filterStateErrors+ ? { ...registry, filterStateErrors: undefined }+ : registry;for (const node of topLevel) {- const { errors } = astToFilterState(node, scoreTypes, registry);+ const { errors } = astToFilterState(node, scoreTypes, termRegistry);const span = nodeSpan(node, textLength);for (const message of errors) {out.push({ from: span.from, to: span.to, severity: "error", message });@@ -225,6 +228,19 @@ export function semanticDiagnostics(hasFilterWarnings(node, textLength, out, false, registry);}+ // Some view contracts constrain the complete filter set (for example, one+ // filter per column). Check the complete lowering as well as each term so+ // draft validation and commit validation share the same backend boundary.+ if (registry.filterStateErrors) {+ const { errors } = astToFilterState(ast, scoreTypes, registry);+ const span = nodeSpan(ast, textLength);+ for (const message of errors) {+ if (!out.some((diagnostic) => diagnostic.message === message)) {+ out.push({ ...span, severity: "error", message });+ }+ }+ }+return out;}diff --git a/web/src/features/sessions/ModernSession.clienttest.tsx b/web/src/features/sessions/ModernSession.clienttest.tsxindex f23ef13430..bc863cdf85 100644--- a/web/src/features/sessions/ModernSession.clienttest.tsx+++ b/web/src/features/sessions/ModernSession.clienttest.tsx@@ -86,6 +86,9 @@ const defaultProps = {viewControllers: {selectedViewId: null,appliedViewId: null,+ viewUpdateTarget: null,+ filterEditorResetKey: 0,+ handleUserStateChange: vi.fn(),handleSetViewId: vi.fn(),applyViewState: vi.fn(),},diff --git a/web/src/features/sessions/ModernSessionFilterControls.clienttest.tsx b/web/src/features/sessions/ModernSessionFilterControls.clienttest.tsxnew file mode 100644index 0000000000..d0c877b8c4--- /dev/null+++ b/web/src/features/sessions/ModernSessionFilterControls.clienttest.tsx@@ -0,0 +1,170 @@+import { act, fireEvent, render, screen } from "@testing-library/react";+import type { ComponentProps, ReactNode } from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { FilterState } from "@langfuse/shared";+import { ModernSessionFilterControls } from "./ModernSessionFilterControls";++const { updateConfig, savedViews } = vi.hoisted(() => ({+ updateConfig: vi.fn(),+ savedViews: [+ {+ id: "saved-view",+ name: "Saved session",+ isSystem: false,+ filters: [],+ columnOrder: ["stored-column"],+ columnVisibility: { stored: false },+ },+ ],+}));+vi.mock("@/src/components/table/table-view-presets/hooks/useViewData", () => ({+ useViewData: () => ({ TableViewPresetsList: savedViews }),+}));+vi.mock(+ "@/src/components/table/table-view-presets/hooks/useViewMutations",+ () => ({+ useViewMutations: () => ({+ createMutation: { mutate: vi.fn(), isPending: false },+ updateConfigMutation: { mutate: updateConfig, isPending: false },+ }),+ }),+);+vi.mock("@/src/features/rbac/utils/checkProjectAccess", () => ({+ useHasProjectAccess: () => true,+}));+vi.mock("@/src/features/posthog-analytics/usePostHogClientCapture", () => ({+ usePostHogClientCapture: () => vi.fn(),+}));+vi.mock(+ "@/src/components/table/table-view-presets/components/data-table-view-presets-drawer",+ () => ({+ TableViewPresetsDrawerRoot: ({ children }: { children: ReactNode }) => (+ <>{children}</>+ ),+ TableViewPresetsDrawerContent: () => <div />,+ }),+);+vi.mock("@/src/components/ui/dialog", () => ({+ Dialog: ({ children }: { children: ReactNode }) => <>{children}</>,+}));+vi.mock("./ModernSessionFilterDialogContent", () => ({+ ModernSessionFilterDialogContent: ({+ initialFilters,+ viewActions,+ }: {+ initialFilters: FilterState;+ viewActions: {+ type: string;+ viewName?: string;+ onUpdate?: (filters: FilterState) => void;+ };+ }) => (+ <button onClick={() => viewActions.onUpdate?.(initialFilters)}>+ {viewActions.type === "update"+ ? `Update ${viewActions.viewName}`+ : "Create view"}+ </button>+ ),+}));+vi.mock("./ModernSessionSaveViewDialogContent", () => ({+ ModernSessionSaveViewDialogContent: () => <div />,+}));++type Props = ComponentProps<typeof ModernSessionFilterControls>;+const makeProps = (): Props => ({+ projectId: "project",+ filterState: [],+ filterColumns: [],+ filterColumnsWithCustomSelect: [],+ onChange: vi.fn(),+ viewControllers: {+ selectedViewId: "saved-view",+ appliedViewId: "saved-view",+ viewUpdateTarget: null,+ filterEditorResetKey: 0,+ handleSetViewId: vi.fn(),+ handleUserStateChange: vi.fn(),+ applyViewState: vi.fn(),+ },+ currentViewState: {+ orderBy: null,+ filters: [],+ columnOrder: ["local-column"],+ columnVisibility: { local: false },+ searchQuery: "",+ },+ children: (controls) => (+ <>+ <span>{controls.activeViewName ?? "No view"}</span>+ <button onClick={controls.onClearFilters}>Clear</button>+ <button onClick={controls.onOpenFilterDialog}>Edit filters</button>+ </>+ ),+});++describe("session detail saved-view controls", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {+ callback(0);+ return 0;+ });+ });+ it("marks the selected view by ID when explicit URL filters differ", () => {+ const props = makeProps();+ render(+ <ModernSessionFilterControls+ {...props}+ filterState={[+ {+ type: "stringOptions",+ column: "level",+ operator: "any of",+ value: ["ERROR"],+ },+ ]}+ />,+ );+ expect(screen.getByText("Saved session")).toBeInTheDocument();+ });+ it("forces Clear on an empty selected view without discarding its update target", () => {+ const props = makeProps();+ render(<ModernSessionFilterControls {...props} />);+ fireEvent.click(screen.getByText("Clear"));+ expect(props.viewControllers.handleUserStateChange).toHaveBeenCalledWith(+ [],+ [],+ { force: true },+ );+ expect(props.viewControllers.handleSetViewId).not.toHaveBeenCalled();+ expect(props.onChange).toHaveBeenCalledWith([]);+ });+ it.each([true, false])(+ "keeps the original update target after demotion, columnsApplied=%s",+ (columnsApplied) => {+ const props = makeProps();+ props.viewControllers.selectedViewId = null;+ props.viewControllers.appliedViewId = null;+ props.viewControllers.viewUpdateTarget = {+ viewId: "saved-view",+ columnsApplied,+ };+ render(<ModernSessionFilterControls {...props} />);+ expect(screen.getByText("No view")).toBeInTheDocument();+ act(() => {+ fireEvent.click(screen.getByText("Edit filters"));+ });+ fireEvent.click(screen.getByText("Update Saved session"));+ expect(updateConfig).toHaveBeenCalledWith(+ expect.objectContaining({+ id: "saved-view",+ columnOrder: columnsApplied ? ["local-column"] : ["stored-column"],+ columnVisibility: columnsApplied+ ? { local: false }+ : { stored: false },+ }),+ expect.any(Object),+ );+ },+ );+});diff --git a/web/src/features/sessions/ModernSessionFilterControls.tsx b/web/src/features/sessions/ModernSessionFilterControls.tsxindex 65db7b3b6a..40581d5e6a 100644--- a/web/src/features/sessions/ModernSessionFilterControls.tsx+++ b/web/src/features/sessions/ModernSessionFilterControls.tsx@@ -22,24 +22,23 @@ import {TableViewPresetsDrawerContent,TableViewPresetsDrawerRoot,} from "@/src/components/table/table-view-presets/components/data-table-view-presets-drawer";+import type { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";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 ViewControllers = Pick<+ ReturnType<typeof useTableViewManager>,+ | "selectedViewId"+ | "appliedViewId"+ | "viewUpdateTarget"+ | "filterEditorResetKey"+ | "handleSetViewId"+ | "handleUserStateChange"+ | "applyViewState"+>;type ModernSessionFilterControlsProps = {projectId: string;@@ -95,18 +94,16 @@ export function ModernSessionFilterControls({});const matchingSystemPreset = SESSION_DETAIL_SYSTEM_PRESETS.find(- (preset) =>- preset.id === viewControllers.selectedViewId &&- isEqual(normalizeFilters(preset.filters), normalizeFilters(filterState)),+ (preset) => preset.id === viewControllers.selectedViewId,);const matchingSavedView = TableViewPresetsList?.find(- (view) =>- view.id === viewControllers.selectedViewId &&- isEqual(normalizeFilters(view.filters), normalizeFilters(filterState)),+ (view) => view.id === viewControllers.selectedViewId,+ );+ const updateViewId =+ viewControllers.selectedViewId ?? viewControllers.viewUpdateTarget?.viewId;+ const updateView = TableViewPresetsList?.find(+ (view) => view.id === updateViewId && !view.isSystem,);- const matchingUserView = matchingSavedView?.isSystem- ? undefined- : matchingSavedView;const activeViewName = matchingSystemPreset?.name ?? matchingSavedView?.name;const openFilterDialog = () => {@@ -173,30 +170,32 @@ export function ModernSessionFilterControls({};const updateCurrentView = (filters: FilterState) => {- if (!matchingUserView) return;+ if (!updateView) return;capture("saved_views:update_config", {tableName: TableViewPresetTableName.SessionDetail,- viewId: matchingUserView.id,- name: matchingUserView.name,+ viewId: updateView.id,+ name: updateView.name,});const viewWasApplied =- viewControllers.appliedViewId === matchingUserView.id;+ viewControllers.appliedViewId === updateView.id ||+ (viewControllers.viewUpdateTarget?.viewId === updateView.id &&+ viewControllers.viewUpdateTarget.columnsApplied);updateConfigMutation.mutate({projectId,- name: matchingUserView.name,- id: matchingUserView.id,+ name: updateView.name,+ id: updateView.id,tableName: TableViewPresetTableName.SessionDetail,orderBy: null,filters,columnOrder: viewWasApplied? currentViewState.columnOrder- : matchingUserView.columnOrder,+ : updateView.columnOrder,columnVisibility: viewWasApplied? currentViewState.columnVisibility- : matchingUserView.columnVisibility,+ : updateView.columnVisibility,searchQuery: "",},{@@ -249,8 +248,8 @@ export function ModernSessionFilterControls({};const clearFilters = () => {+ viewControllers.handleUserStateChange(filterState, [], { force: true });onChange([]);- viewControllers.handleSetViewId(null);capture("filters:cleared", {surface: "filter_builder",tableName: "session-detail",@@ -262,10 +261,10 @@ export function ModernSessionFilterControls({let filterDialogViewActions: ModernSessionFilterDialogViewActions = {type: "none",};- if (hasWriteAccess && matchingUserView) {+ if (hasWriteAccess && updateView) {filterDialogViewActions = {type: "update",- viewName: matchingUserView.name,+ viewName: updateView.name,isUpdating: updateConfigMutation.isPending,onCreate: openSaveViewDialog,onUpdate: updateCurrentView,@@ -300,6 +299,7 @@ export function ModernSessionFilterControls({<Dialog open={filterDialogOpen} onOpenChange={setFilterDialogOpen}>{filterDialogOpen ? (<ModernSessionFilterDialogContent+ key={viewControllers.filterEditorResetKey}initialFilters={filterState}filterColumns={filterColumns}filterColumnsWithCustomSelect={filterColumnsWithCustomSelect}diff --git a/web/src/features/sessions/SessionPages.tsx b/web/src/features/sessions/SessionPages.tsxindex bc81a8bb4b..a5e5d79e6c 100644--- a/web/src/features/sessions/SessionPages.tsx+++ b/web/src/features/sessions/SessionPages.tsx@@ -78,6 +78,7 @@ import {import { StringParam, useQueryParam } from "use-query-params";import { PopoverFilterBuilder } from "@/src/features/filters/components/filter-builder";import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";+import { useTableViewFilterChange } from "@/src/components/table/table-view-presets/hooks/useTableViewFilterChange";import { TableViewPresetsDrawer } from "@/src/components/table/table-view-presets/components/data-table-view-presets-drawer";import { Separator } from "@/src/components/ui/separator";import {@@ -1283,11 +1284,18 @@ const LoadedSessionEventsPage: React.FC<{[filterColumns],);+ const { viewControllersRef, onExplicitFilterStateChange } =+ useTableViewFilterChange();+ const hasUserFilterEditRef = useRef(false);const queryFilter = useSidebarFilterState(sessionEventsFilterConfig,typedFilterOptions,{loading: isFilterOptionsPending,+ onExplicitFilterStateChange: (change) => {+ if (change.origin === "user") hasUserFilterEditRef.current = true;+ onExplicitFilterStateChange(change);+ },stateLocation: "urlAndSessionStorage",sessionFilterContextId: projectId,},@@ -1322,6 +1330,7 @@ const LoadedSessionEventsPage: React.FC<{(filters: FilterState) =>queryFilter.setFilterState(normalizeLegacySessionPositionInTraceFilters(filters),+ { origin: "saved_view" },),[queryFilter],);@@ -1346,6 +1355,8 @@ const LoadedSessionEventsPage: React.FC<{currentExpandedFilters: queryFilter.expanded,});+ viewControllersRef.current = viewControllers;+// Auto-apply path only (the drawer's user-driven preset selection has its// own handler). Writes with `replaceIn`: this is the page deciding its own// default, not a user step β pushing would leave the pre-default URL as a@@ -1354,7 +1365,10 @@ const LoadedSessionEventsPage: React.FC<{const applySystemPreset = useCallback((preset: SessionDetailSystemPreset) => {viewControllers.handleSetViewId(preset.id, { updateType: "replaceIn" });- queryFilter.setFilterState(preset.filters, { updateType: "replaceIn" });+ queryFilter.setFilterState(preset.filters, {+ updateType: "replaceIn",+ origin: "system",+ });},[queryFilter, viewControllers],);@@ -1384,20 +1398,11 @@ const LoadedSessionEventsPage: React.FC<{const selectedViewId = viewControllers.selectedViewId;- // Which named view drives the empty-state notice. Derived from the applied- // FilterState (the single source of truth) so the label survives the manager- // stripping the viewId on reload, and drops to null the moment the filter is- // edited. Mirrors the drawer trigger's rule: only name a view when it also- // matches the selected view id β so a selected saved view, or a filter- // hand-edited into another preset's exact shape, doesn't make the notice and- // the drawer trigger disagree.- const filterMatchedView = findSessionDetailViewByFilters(visibleFilterState);- const matchedView =- filterMatchedView &&- (!selectedViewId || filterMatchedView.id === selectedViewId)- ? filterMatchedView- : null;- const viewLabel = matchedView?.name ?? null;+ // A named view is selected explicitly; matching filter values alone cannot+ // turn a user's edited working state back into a selected preset.+ const viewLabel =+ SESSION_DETAIL_SYSTEM_PRESETS.find((preset) => preset.id === selectedViewId)+ ?.name ?? null;const hasSessionControls =!isModernSessionEnabled ||Boolean(session.users?.length || session.scores.length);@@ -1477,6 +1482,8 @@ const LoadedSessionEventsPage: React.FC<{useEffect(() => {if (isViewLoading) return;if (selectedViewId) return;+ if (viewControllers.viewUpdateTarget || hasUserFilterEditRef.current)+ return;const filterMatchedView =findSessionDetailViewByFilters(visibleFilterState);if (!filterMatchedView) return;@@ -1514,6 +1521,8 @@ const LoadedSessionEventsPage: React.FC<{if (defaultPresetResolvedSessionRef.current === sessionId) return;if (isViewLoading) return; // Wait for view manager to initializedefaultPresetResolvedSessionRef.current = sessionId;+ if (viewControllers.viewUpdateTarget || hasUserFilterEditRef.current)+ return;if (selectedViewId) return;if (initialViewIdRef.current) return;if (arrivedOnVisitedHistoryEntry) return;@@ -1530,6 +1539,7 @@ const LoadedSessionEventsPage: React.FC<{selectedViewId,sessionId,visibleFilterState,+ viewControllers.viewUpdateTarget,]);const virtualizer = useVirtualizer({@@ -1905,6 +1915,7 @@ const LoadedSessionEventsPage: React.FC<{so (LFE-10520). */}{!isModernSessionEnabled ? (<PopoverFilterBuilder+ key={viewControllers.filterEditorResetKey}columns={filterColumns}filterState={visibleFilterState}onChange={queryFilter.setFilterState}diff --git a/web/src/pages/project/[projectId]/users/index.tsx b/web/src/pages/project/[projectId]/users/index.tsxindex d425704090..5f4da767ae 100644--- a/web/src/pages/project/[projectId]/users/index.tsx+++ b/web/src/pages/project/[projectId]/users/index.tsx@@ -19,7 +19,10 @@ import { createLinkTableColumn } from "@/src/components/design-system/table/coluimport { createTextTableColumn } from "@/src/components/design-system/table/columns/createTextTableColumn";import { type LangfuseColumnDef } from "@/src/components/table/types";import { getUsersFilterConfig } from "@/src/features/filters/config/users-config";-import { USERS_FIELD_REGISTRY } from "@/src/features/filters/config/usersSearchRegistry";+import {+ USERS_FIELD_REGISTRY,+ LEGACY_USERS_FIELD_REGISTRY,+} from "@/src/features/filters/config/usersSearchRegistry";import {useSidebarFilterPresentation,useSidebarFilterStateCore,@@ -31,16 +34,18 @@ import { sortOptionValues } from "@/src/features/filters";import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";import { useEventsFilterOptions } from "@/src/features/events/hooks/useEventsFilterOptions";import { useReadPath } from "@/src/features/events/hooks/useReadPath";-import { EventsSearchBarRow } from "@/src/features/search-bar/components/EventsSearchBarRow";-import { useEventsSearchBar } from "@/src/features/search-bar/hooks/useEventsSearchBar";-import { DEFAULT_SEARCH_TYPE } from "@/src/features/search-bar/lib/commit";+import { TableSearchBar } from "@/src/features/search-bar/components/TableSearchBar";+import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";+import { useTableViewFilterChange } from "@/src/components/table/table-view-presets/hooks/useTableViewFilterChange";+import useColumnOrder from "@/src/features/column-visibility/hooks/useColumnOrder";+import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";import { toObservedOptions } from "@/src/features/search-bar/lib/observed-options";import { api } from "@/src/utils/api";import { compactNumberFormatter, usdFormatter } from "@/src/utils/numbers";-import { cn } from "@/src/utils/tailwind";import { type RouterOutput } from "@/src/utils/types";import {DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG,+ TableViewPresetTableName,type FilterState,type TimeFilter,} from "@langfuse/shared";@@ -188,16 +193,20 @@ const UsersTable = ({[dateRange],);+ const { viewControllersRef, onExplicitFilterStateChange } =+ useTableViewFilterChange();+const filterStateOptions: UseSidebarFilterStateOptions = useMemo(() => ({stateLocation: "urlAndSessionStorage",+ onExplicitFilterStateChange,sessionFilterContextId: buildSidebarFilterSessionContextId(projectId),// Environment is a sidebar facet here, like every other filter β the page// no longer keeps its own environment selection beside the filter state.implicitDefaultConfig: DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG,isV4,}),- [isV4, projectId],+ [isV4, projectId, onExplicitFilterStateChange],);// Split core/presentation so the v4 facet scan can refine its counts against@@ -337,10 +346,6 @@ const UsersTable = ({withDefault(StringParam, null),);- // The grammar bar is v4-only: it writes the events facet grammar, which the- // trace-backed v3 query cannot answer. v3 keeps the toolbar's search field.- const searchBarEnabled = isV4;-const queryFilterRef = useRef(queryFilter);queryFilterRef.current = queryFilter;@@ -350,34 +355,11 @@ const UsersTable = ({[],);- const observedOptions = useMemo(- () => toObservedOptions(v4FacetOptions, isV4FacetOptionsPending),- [v4FacetOptions, isV4FacetOptionsPending],+ const observedOptions = toObservedOptions(+ isV4 ? v4FacetOptions : v3FacetOptions,+ isSidebarFilterLoading,);- // Both users queries take a `searchQuery` but no search type β free text- // always lowers to `user_id ILIKE`. The bar reports the default lane; there- // is nothing on this page for a write to it to change.- const setSearchTypeNoop = useCallback(() => {}, []);-- const {- store: searchBarStore,- commit: searchBarCommit,- applyFilters: searchBarApplyFilters,- } = useEventsSearchBar({- projectId,- tableName: usersFilterConfig.tableName,- enabled: searchBarEnabled,- filterState: queryFilter.searchBarFilterState,- searchQuery,- searchType: DEFAULT_SEARCH_TYPE,- observed: observedOptions,- setFilterState: setFiltersWrapper,- setSearchQuery,- setSearchType: setSearchTypeNoop,- registry: USERS_FIELD_REGISTRY,- });-const filterState = queryFilter.effectiveFilterState.concat(dateRangeFilter);const usersV3 = api.users.all.useQuery(@@ -555,6 +537,55 @@ const UsersTable = ({}),];+ const [columnVisibility, setColumnVisibility] = useColumnVisibility(+ "users",+ columns,+ );+ const [columnOrder, setColumnOrder] = useColumnOrder<RowData>(+ "users",+ columns,+ );+ const { isLoading: isViewLoading, ...viewControllers } = useTableViewManager({+ tableName: TableViewPresetTableName.Users,+ projectId,+ stateUpdaters: {+ setFilters: (filters) =>+ queryFilterRef.current.setFilterState(filters, {+ origin: "saved_view",+ }),+ setExpandedFilters: queryFilter.onExpandedChange,+ setSearchQuery,+ setColumnOrder,+ setColumnVisibility,+ },+ currentFilterState: queryFilter.explicitFilterState,+ currentExpandedFilters: queryFilter.expanded,+ validationContext: {+ columns,+ filterColumnDefinition: usersFilterConfig.columnDefinitions,+ expandableFilterColumns: usersFilterConfig.facets.map(+ (facet) => facet.column,+ ),+ },+ });+ viewControllersRef.current = viewControllers;+ const handleSearchChange = (query: string | null) => {+ viewControllers.handleUserStateChange(searchQuery ?? "", query ?? "");+ setSearchQuery(query);+ setPaginationState({ pageIndex: 0 });+ };+ const handleColumnOrderChange: typeof setColumnOrder = (update) => {+ const next = typeof update === "function" ? update(columnOrder) : update;+ viewControllers.handleUserStateChange(columnOrder, next);+ setColumnOrder(next);+ };+ const handleColumnVisibilityChange: typeof setColumnVisibility = (update) => {+ const next =+ typeof update === "function" ? update(columnVisibility) : update;+ viewControllers.handleUserStateChange(columnVisibility, next);+ setColumnVisibility(next);+ };+return (<DataTableControlsProvider tableName={usersFilterConfig.tableName}><div className="flex h-full w-full flex-col">@@ -567,54 +598,51 @@ const UsersTable = ({{/* In bar mode the composer and the toolbar stick together as one bandso the toolbar cannot scroll under the composer and renderhalf-clipped. */}- <div- className={cn(- searchBarEnabled && "bg-background sticky top-0 z-30 pb-1.5",- )}- >- {searchBarEnabled && (- <EventsSearchBarRow- projectId={projectId}- tableName={usersFilterConfig.tableName}- store={searchBarStore}- commit={searchBarCommit}- observed={observedOptions}- erroredColumns={erroredColumns}- onApplyFilters={searchBarApplyFilters}- onRequestColumns={requestColumns}- registry={USERS_FIELD_REGISTRY}- />- )}+ <div className="bg-background sticky top-0 z-30 pb-1.5">+ <TableSearchBar+ key={`${viewControllers.filterEditorResetKey}-${queryFilter.draftResetKey}`}+ isV4={isV4}+ filterState={queryFilter.searchBarFilterState}+ setFilterState={setFiltersWrapper}+ search={{ query: searchQuery, setQuery: handleSearchChange }}+ projectId={projectId}+ tableName={usersFilterConfig.tableName}+ observed={observedOptions}+ erroredColumns={erroredColumns}+ onRequestColumns={requestColumns}+ registry={isV4 ? USERS_FIELD_REGISTRY : LEGACY_USERS_FIELD_REGISTRY}+ /><DataTableToolbartableName={usersFilterConfig.tableName}isV4={isV4}- rowClassName={searchBarEnabled ? "my-1" : undefined}+ rowClassName="my-1"filterState={queryFilter.explicitFilterState}columns={columns}timeRange={showControlsInPageHeader ? undefined : timeRange}setTimeRange={showControlsInPageHeader ? undefined : setTimeRange}- searchConfig={- searchBarEnabled- ? undefined- : {- metadataSearchFields: ["User ID"],- updateQuery: setSearchQuery,- currentQuery: searchQuery ?? undefined,- tableAllowsFullTextSearch: false,- setSearchType: undefined,- searchType: undefined,- }- }+ currentSearchQuery={searchQuery ?? ""}+ columnVisibility={columnVisibility}+ setColumnVisibility={handleColumnVisibilityChange}+ columnOrder={columnOrder}+ setColumnOrder={handleColumnOrderChange}+ viewConfig={{+ tableName: TableViewPresetTableName.Users,+ projectId,+ controllers: viewControllers,+ }}/></div><ResizableFilterLayout>- <DataTableControls queryFilter={queryFilter} />+ <DataTableControls+ key={viewControllers.filterEditorResetKey}+ queryFilter={queryFilter}+ /><div className="flex flex-1 flex-col overflow-hidden"><DataTabletableName="users"columns={columns}data={- users.isLoading+ users.isLoading || isViewLoading? { isLoading: true, isError: false }: users.isError? {@@ -656,6 +684,10 @@ const UsersTable = ({onChange: setPaginationState,state: paginationState,}}+ columnVisibility={columnVisibility}+ onColumnVisibilityChange={handleColumnVisibilityChange}+ columnOrder={columnOrder}+ onColumnOrderChange={handleColumnOrderChange}cellPadding="comfortable"/></div>