🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(observations): add grammar search bar for v4 events table (beta) (#14237)
Nikita Kabardin6717e7143dc6
diff --git a/.agents/AGENTS.md b/.agents/AGENTS.mdindex ab84ae67a4..8dc911dc0e 100644--- a/.agents/AGENTS.md+++ b/.agents/AGENTS.md@@ -20,6 +20,12 @@ evaluating, and debugging AI applications.- For documentation screenshots in Markdown, avoid fixed `height` on `<img>`tags; prefer Markdown images or width-only HTML so previews preserve aspectratio.+- When working on the search bar or any filtering UI/grammar, read+ `web/src/features/search-bar/README.md` first. It owns the grammar ↔+ `FilterState` contract, the validate/lower parity invariants, and the+ cross-view extension playbook — the bar is intended to become the primary+ filter interface for every filterable view, so new filtering work extends it+ through that contract rather than forking it.- Never commit secrets or credentials. Keep `.env*.example` files insync with required env vars.diff --git a/web/src/__tests__/server/userAccount.servertest.ts b/web/src/__tests__/server/userAccount.servertest.tsindex bffbcae70d..23ca80633b 100644--- a/web/src/__tests__/server/userAccount.servertest.ts+++ b/web/src/__tests__/server/userAccount.servertest.ts@@ -7,7 +7,7 @@ import { env } from "@/src/env.mjs";import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";-describe("userAccountRouter.setInAppAgentPreviewEnabled", () => {+describe("userAccountRouter.setFeaturePreviewEnabled", () => {const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;beforeEach(() => {@@ -23,13 +23,15 @@ describe("userAccountRouter.setInAppAgentPreviewEnabled", () => {includeProjectInSession: false,});- const result = await caller.userAccount.setInAppAgentPreviewEnabled({+ const result = await caller.userAccount.setFeaturePreviewEnabled({+ flag: "inAppAgent",enabled: true,});expect(result).toEqual({success: true,- inAppAgentPreviewEnabled: true,+ flag: "inAppAgent",+ enabled: true,});const user = await prisma.user.findUniqueOrThrow({@@ -39,25 +41,50 @@ describe("userAccountRouter.setInAppAgentPreviewEnabled", () => {expect(user.featureFlags).toEqual(["templateFlag", "inAppAgent"]);});- it("disables the in-app agent preview without requiring a project", async () => {+ it("enables the search bar preview, leaving other flags intact", async () => {const { caller, userId } = await createCaller({featureFlags: ["templateFlag", "inAppAgent"],});- const result = await caller.userAccount.setInAppAgentPreviewEnabled({+ const result = await caller.userAccount.setFeaturePreviewEnabled({+ flag: "searchBar",+ enabled: true,+ });++ expect(result).toEqual({ success: true, flag: "searchBar", enabled: true });++ const user = await prisma.user.findUniqueOrThrow({+ where: { id: userId },+ select: { featureFlags: true },+ });+ expect(user.featureFlags).toEqual([+ "templateFlag",+ "inAppAgent",+ "searchBar",+ ]);+ });++ it("disables a preview flag without touching the others", async () => {+ const { caller, userId } = await createCaller({+ featureFlags: ["templateFlag", "inAppAgent", "searchBar"],+ });++ const result = await caller.userAccount.setFeaturePreviewEnabled({+ flag: "searchBar",enabled: false,});expect(result).toEqual({success: true,- inAppAgentPreviewEnabled: false,+ flag: "searchBar",+ enabled: false,});const user = await prisma.user.findUniqueOrThrow({where: { id: userId },select: { featureFlags: true },});- expect(user.featureFlags).toEqual(["templateFlag"]);+ expect(user.featureFlags).toEqual(["templateFlag", "inAppAgent"]);});it("rejects enabling in self-hosted deployments", async () => {@@ -65,7 +92,8 @@ describe("userAccountRouter.setInAppAgentPreviewEnabled", () => {(env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;await expect(- caller.userAccount.setInAppAgentPreviewEnabled({+ caller.userAccount.setFeaturePreviewEnabled({+ flag: "inAppAgent",enabled: true,}),).rejects.toMatchObject({ code: "PRECONDITION_FAILED" });@@ -144,6 +172,7 @@ async function createCaller({],featureFlags: {inAppAgent: featureFlags.includes("inAppAgent"),+ searchBar: featureFlags.includes("searchBar"),templateFlag: featureFlags.includes("templateFlag"),excludeClickhouseRead: false,observationEvals: false,diff --git a/web/src/components/table/data-table-toolbar.tsx b/web/src/components/table/data-table-toolbar.tsxindex f08cffdb4b..5aa41f1e8e 100644--- a/web/src/components/table/data-table-toolbar.tsx+++ b/web/src/components/table/data-table-toolbar.tsx@@ -111,6 +111,10 @@ interface DataTableToolbarProps<TData, TValue> {columns: LangfuseColumnDef<TData, TValue>[];filterColumnDefinition?: ColumnDefinition[];searchConfig?: SearchConfig;+ /** Authoritative search query to persist into saved views. Use when the+ * toolbar's own search field is hidden (e.g. search-bar mode) so the live+ * query — not the toolbar's stale local mirror — is captured. */+ currentSearchQuery?: string;actionButtons?: React.ReactNode;filterState?: FilterState;setFilterState?:@@ -136,6 +140,7 @@ interface DataTableToolbarProps<TData, TValue> {viewConfig?: TableViewConfig;filterWithAI?: boolean;className?: string;+ rowClassName?: string;viewModeToggle?: React.ReactNode;}@@ -181,6 +186,7 @@ export function DataTableToolbar<TData, TValue>({columns,filterColumnDefinition,searchConfig,+ currentSearchQuery,actionButtons,filterState,setFilterState,@@ -197,6 +203,7 @@ export function DataTableToolbar<TData, TValue>({multiSelect,environmentFilter,className,+ rowClassName,orderByState,viewConfig,filterWithAI = false,@@ -225,7 +232,12 @@ export function DataTableToolbar<TData, TValue>({const hasNewSidebar = !filterColumnDefinition && filterState !== undefined;return (<div className={cn("grid h-fit w-full gap-0 px-2", className)}>- <div className="@container my-2 flex flex-wrap items-center gap-2">+ <div+ className={cn(+ "@container my-2 flex flex-wrap items-center gap-2",+ rowClassName,+ )}+ >{hasNewSidebar && <FilterToggleButton filterState={filterState} />}{!!columnVisibility && !!columnOrder && !!viewConfig && (<TableViewPresetsDrawer@@ -235,7 +247,7 @@ export function DataTableToolbar<TData, TValue>({filters: filterState ?? [],columnOrder,columnVisibility,- searchQuery: searchString,+ searchQuery: currentSearchQuery ?? searchString,}}systemFilterPresets={viewConfig.systemFilterPresets}/>@@ -423,7 +435,7 @@ export function DataTableToolbar<TData, TValue>({/>)}- <div className="flex flex-row flex-wrap gap-2 pr-0.5 @6xl:ml-auto">+ <div className="flex flex-row flex-wrap gap-2 pr-0.5 @3xl:ml-auto">{!!columnVisibility && !!setColumnVisibility && (<DataTableColumnVisibilityFiltercolumns={columns}diff --git a/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts b/web/src/components/table/table-view-presets/hooks/useTableViewManager.tsindex 18c3ba6558..3c23d70ef5 100644--- a/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts+++ b/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts@@ -25,7 +25,7 @@ interface TableStateUpdaters {setColumnVisibility: (columnVisibility: VisibilityState) => void;setOrderBy?: (orderBy: OrderByState) => void;setFilters?: (filters: FilterState) => void;- setSearchQuery?: (searchQuery: string) => void;+ setSearchQuery?: (searchQuery: string | null) => void;setExpandedFilters?: (expandedFilters: string[]) => void;}@@ -304,9 +304,11 @@ export function useTableViewManager({}}- // Handle search query (only set if non-empty to avoid use-query-params batching conflicts)- if (viewData.searchQuery && setSearchQueryRef.current) {- setSearchQueryRef.current(viewData.searchQuery);+ if (setSearchQueryRef.current) {+ // `||` (not `??`): a persisted empty string — the common case for views+ // saved without a free-text search — must map to null too, or it+ // serializes as a literal empty `?search=` param in the URL.+ setSearchQueryRef.current(viewData.searchQuery || null);}// Apply column order and visibility without validation since UI will handle gracefullydiff --git a/web/src/components/table/use-cases/useFullTextSearch.tsx b/web/src/components/table/use-cases/useFullTextSearch.tsxindex 390a931595..9f6d0b6afb 100644--- a/web/src/components/table/use-cases/useFullTextSearch.tsx+++ b/web/src/components/table/use-cases/useFullTextSearch.tsx@@ -15,9 +15,10 @@ export const useFullTextSearch = () => {withDefault(StringParam, null),);- // Search type can be either "id" or "metadata". Keep it untyped here and- // cast later to the stricter `TracingSearchType[]` to avoid type mismatch- // with the generic `ArrayParam` from `use-query-params`.+ // Search type is one of "id", "content", "input", or "output"+ // (TracingSearchType). Keep it untyped here and cast later to the stricter+ // `TracingSearchType[]` to avoid type mismatch with the generic `ArrayParam`+ // from `use-query-params`.const [searchType, handleSearchTypeChange] = useQueryParam("searchType",withDefault(ArrayParam, ["id"]),@@ -49,7 +50,14 @@ export const useFullTextSearch = () => {}const setSearchType = (newSearchType: TracingSearchType[]) => {- handleSearchTypeChange(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);};const typedSearchType = (searchType ?? ["id"]) as TracingSearchType[];diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsxindex ed46833311..54fd9fc809 100644--- a/web/src/features/events/components/EventsTable.tsx+++ b/web/src/features/events/components/EventsTable.tsx@@ -101,6 +101,12 @@ import { RunEvaluationDialog } from "@/src/features/batch-actions/components/Runimport { AddObservationsToDatasetDialog } from "@/src/features/batch-actions/components/AddObservationsToDatasetDialog/index";import { useHasEntitlement } from "@/src/features/entitlements/hooks";import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";+import { useSearchBarEnabled } from "@/src/features/search-bar/hooks/useSearchBarEnabled";+import { createPortal } from "react-dom";+import { useEventsSearchBar } from "@/src/features/search-bar/hooks/useEventsSearchBar";+import { EventsSearchBarRow } from "@/src/features/search-bar/components/EventsSearchBarRow";+import { EventsHeaderControls } from "@/src/features/search-bar/components/EventsHeaderControls";+import { toObservedOptions } from "@/src/features/search-bar/lib/observed-options";export type EventsTableRow = {// Identity fields@@ -183,6 +189,9 @@ export type EventsTableProps = {externalDateRange?: TableDateRange;limitRows?: number;sessionId?: string;+ /** Page-header DOM node to portal the time-range + refresh controls into+ * when the search bar is active (keeps the otherwise-full toolbar slim). */+ headerActionsContainer?: HTMLElement | null;};export default function ObservationsEventsTable({@@ -194,6 +203,7 @@ export default function ObservationsEventsTable({externalDateRange,limitRows,sessionId,+ headerActionsContainer,}: EventsTableProps) {const peekContext = usePeekTableState();const router = useRouter();@@ -405,6 +415,26 @@ export default function ObservationsEventsTable({queryFilterOptions,);+ // Grammar search bar (per-user Feature Preview opt-in): an ADDITIONAL editor+ // that coexists with the facet sidebar and the two stay in sync (Datadog model).+ // The 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 — bare text and+ // content:/input:/output: — goes inline in the bar); the sidebar and+ // time/refresh controls stay.+ const searchBarFlagEnabled = useSearchBarEnabled();+ const searchBarMode =+ searchBarFlagEnabled &&+ !hideControls &&+ !externalFilterState &&+ !peekContext &&+ // 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;+// Create ref-based wrapper to avoid stale closure when queryFilter updatesconst queryFilterRef = useRef(queryFilter);queryFilterRef.current = queryFilter;@@ -414,6 +444,25 @@ export default function ObservationsEventsTable({[],);+ const observedOptions = useMemo(+ () => toObservedOptions(filterOptions, isFilterOptionsPending),+ [filterOptions, isFilterOptionsPending],+ );++ const { store: searchBarStore, commit: searchBarCommit } = useEventsSearchBar(+ {+ projectId,+ enabled: searchBarMode,+ filterState: queryFilter.explicitFilterState,+ searchQuery,+ searchType,+ observed: observedOptions,+ setFilterState: setFiltersWrapper,+ setSearchQuery,+ setSearchType,+ },+ );+// Disabled for now because perhaps confusing// const viewModeFilter: FilterState =// viewMode === "trace"@@ -450,6 +499,8 @@ export default function ObservationsEventsTable({]: [];+ // The sidebar's effective filter state is the single source of truth in both+ // modes — the search bar syncs into it rather than replacing it.const combinedFilterState = queryFilter.effectiveFilterState.concat(dateRangeFilter).concat(userIdFilter)@@ -1417,100 +1468,170 @@ export default function ObservationsEventsTable({return (<DataTableControlsProvider tableName={eventsFilterConfig.tableName}><div className="flex h-full w-full flex-col">- {/* Toolbar spanning full width */}{!hideControls && (- <DataTableToolbar- columns={columns}- filterState={queryFilter.explicitFilterState}- searchConfig={{- metadataSearchFields: ["ID", "Name", "Trace Name", "Model"],- updateQuery: setSearchQuery,- currentQuery: searchQuery ?? undefined,- searchType,- setSearchType,- tableAllowsFullTextSearch: true,- }}- viewConfig={{- tableName: TableViewPresetTableName.ObservationsEvents,- projectId,- controllers: viewControllers,- }}- columnsWithCustomSelect={[- "providedModelName",- "name",- "promptName",- ]}- columnVisibility={columnVisibility}- setColumnVisibility={setColumnVisibilityState}- columnOrder={columnOrder}- setColumnOrder={setColumnOrder}- orderByState={orderByState}- rowHeight={rowHeight}- setRowHeight={setRowHeight}- timeRange={timeRange}- setTimeRange={setTimeRange}- // Disabled, for now moved to filter sidebar- // TODO: remove this toggle once v4 looks good as is- // viewModeToggle={- // <EventsViewModeToggle- // viewMode={viewMode}- // onViewModeChange={setViewMode}- // />- // }- refreshConfig={{- onRefresh: handleRefresh,- isRefreshing: observations.status === "loading",- interval: refreshInterval,- setInterval: setRefreshInterval,- }}- actionButtons={[- <BatchExportTableButton- {...{- projectId,- filterState,- orderByState,- searchQuery,- searchType,- }}- tableName={BatchExportTableName.Events}- key="batchExport"- />,- selectedObservationIds.length > 0 || selectAll ? (- <TableActionMenu- key="observations-multi-select-actions"- projectId={projectId}- actions={tableActions}- tableName={BatchExportTableName.Observations}- selectedCount={selectedObservationCount}- onClearSelection={() => {- setSelectedRows({});- setSelectAll(false);- }}- onCustomAction={(actionType) => {- if (actionType === ActionId.ObservationBatchEvaluation) {- setShowRunEvaluationDialog(true);+ <div+ className={cn(+ // This is a table-internal sticky band below PageHeader. Using+ // top-banner-offset here pushes the band down by the viewport+ // header/banner offset and leaves a large blank gap above it.+ // pb-1.5 gives the band a bit more breathing room above the table.+ searchBarMode && "bg-background sticky top-0 z-30 pb-1.5",+ )}+ >+ {/* Search bar row: (near) full-width query composer. In bar mode it+ sticks together with the toolbar below, so the toolbar controls+ cannot scroll underneath and render half-clipped. The time-range+ + refresh controls render into the page header when the host page+ provides a slot, and fall back to inline-by-the-bar otherwise. */}+ {searchBarMode &&+ (() => {+ const controls = (+ <EventsHeaderControls+ timeRange={timeRange}+ setTimeRange={setTimeRange}+ refreshConfig={{+ onRefresh: handleRefresh,+ isRefreshing: observations.status === "loading",+ interval: refreshInterval,+ setInterval: setRefreshInterval,+ }}+ />+ );+ const hasHeaderSlot =+ headerActionsContainer !== null &&+ headerActionsContainer !== undefined;+ return (+ <>+ <EventsSearchBarRow+ projectId={projectId}+ store={searchBarStore}+ commit={searchBarCommit}+ observed={observedOptions}+ inlineControls={hasHeaderSlot ? undefined : controls}+ />+ {hasHeaderSlot &&+ createPortal(controls, headerActionsContainer)}+ </>+ );+ })()}+ {/* Toolbar spanning full width */}+ <DataTableToolbar+ columns={columns}+ rowClassName={searchBarMode ? "my-1" : undefined}+ filterState={queryFilter.explicitFilterState}+ searchConfig={+ // In search-bar mode full-text search (bare text ++ // content:/input:/output:) lives inline in the bar, so the+ // legacy toolbar search field is hidden.+ searchBarMode+ ? undefined+ : {+ metadataSearchFields: [+ "ID",+ "Name",+ "Trace Name",+ "Model",+ ],+ updateQuery: setSearchQuery,+ currentQuery: searchQuery ?? undefined,+ searchType,+ setSearchType,+ tableAllowsFullTextSearch: true,}- if (actionType === ActionId.ObservationAddToDataset) {- setShowAddToDatasetDialog(true);+ }+ // In bar mode the toolbar search field is hidden, so source the+ // saved-view search query from the live URL state (the bar writes+ // free text there) rather than the toolbar's empty local mirror.+ currentSearchQuery={+ searchBarMode ? (searchQuery ?? "") : undefined+ }+ viewConfig={{+ tableName: TableViewPresetTableName.ObservationsEvents,+ projectId,+ controllers: viewControllers,+ }}+ columnsWithCustomSelect={[+ "providedModelName",+ "name",+ "promptName",+ ]}+ columnVisibility={columnVisibility}+ setColumnVisibility={setColumnVisibilityState}+ columnOrder={columnOrder}+ setColumnOrder={setColumnOrder}+ orderByState={orderByState}+ rowHeight={rowHeight}+ setRowHeight={setRowHeight}+ timeRange={searchBarMode ? undefined : timeRange}+ setTimeRange={searchBarMode ? undefined : setTimeRange}+ // Disabled, for now moved to filter sidebar+ // TODO: remove this toggle once v4 looks good as is+ // viewModeToggle={+ // <EventsViewModeToggle+ // viewMode={viewMode}+ // onViewModeChange={setViewMode}+ // />+ // }+ refreshConfig={+ searchBarMode+ ? undefined+ : {+ onRefresh: handleRefresh,+ isRefreshing: observations.status === "loading",+ interval: refreshInterval,+ setInterval: setRefreshInterval,}+ }+ actionButtons={[+ <BatchExportTableButton+ {...{+ projectId,+ filterState,+ orderByState,+ searchQuery,+ searchType,}}- />- ) : null,- ]}- multiSelect={{- selectAll,- setSelectAll,- selectedRowIds: selectedObservationIds,- setRowSelection: setSelectedRows,- totalCount,- pageSize: paginationState.limit,- pageIndex: paginationState.page - 1,- }}- filterWithAI- />+ tableName={BatchExportTableName.Events}+ key="batchExport"+ />,+ selectedObservationIds.length > 0 || selectAll ? (+ <TableActionMenu+ key="observations-multi-select-actions"+ projectId={projectId}+ actions={tableActions}+ tableName={BatchExportTableName.Observations}+ selectedCount={selectedObservationCount}+ onClearSelection={() => {+ setSelectedRows({});+ setSelectAll(false);+ }}+ onCustomAction={(actionType) => {+ if (actionType === ActionId.ObservationBatchEvaluation) {+ setShowRunEvaluationDialog(true);+ }+ if (actionType === ActionId.ObservationAddToDataset) {+ setShowAddToDatasetDialog(true);+ }+ }}+ />+ ) : null,+ ]}+ multiSelect={{+ selectAll,+ setSelectAll,+ selectedRowIds: selectedObservationIds,+ setRowSelection: setSelectedRows,+ totalCount,+ pageSize: paginationState.limit,+ pageIndex: paginationState.page - 1,+ }}+ filterWithAI+ />+ </div>)}- {/* Content area with sidebar and table */}+ {/* Content area with sidebar and table. The facet sidebar stays in+ search-bar mode and syncs bidirectionally with the bar. */}<ResizableFilterLayout>{!hideControls && (<DataTableControlsdiff --git a/web/src/features/feature-flags/available-flags.ts b/web/src/features/feature-flags/available-flags.tsindex d7a6d7280c..a8984dd3e8 100644--- a/web/src/features/feature-flags/available-flags.ts+++ b/web/src/features/feature-flags/available-flags.ts@@ -1,5 +1,6 @@export const availableFlags = ["inAppAgent",+ "searchBar","templateFlag","excludeClickhouseRead","v4BetaToggleVisible",diff --git a/web/src/features/feature-previews/assets/filter-search-bar-dark.svg b/web/src/features/feature-previews/assets/filter-search-bar-dark.svgnew file mode 100644index 0000000000..576c731f43--- /dev/null+++ b/web/src/features/feature-previews/assets/filter-search-bar-dark.svg@@ -0,0 +1,107 @@+<svg xmlns="http://www.w3.org/2000/svg" width="650" height="300" viewBox="0 0 650 300">+ <defs>+ <linearGradient id="barGlow" x1="62" y1="52" x2="595" y2="104" gradientUnits="userSpaceOnUse">+ <stop offset="0" stop-color="hsl(246, 55%, 70%)" stop-opacity="0.14"/>+ <stop offset="0.58" stop-color="hsl(217.2, 32.6%, 18%)" stop-opacity="0.72"/>+ <stop offset="1" stop-color="hsl(188, 53%, 63%)" stop-opacity="0.08"/>+ </linearGradient>+ <linearGradient id="rowGlow" x1="255" y1="173" x2="574" y2="196" gradientUnits="userSpaceOnUse">+ <stop offset="0" stop-color="hsl(246, 55%, 70%)" stop-opacity="0.2"/>+ <stop offset="1" stop-color="hsl(217.2, 32.6%, 16%)" stop-opacity="0.74"/>+ </linearGradient>+ </defs>++ <rect width="650" height="300" fill="hsl(222.2, 84%, 4.9%)"/>++ <g stroke="hsl(210, 40%, 83%)" stroke-width="1.5" fill="none" opacity="0.4">+ <path d="M14 32 V14 H32"/>+ <path d="M636 32 V14 H618"/>+ <path d="M14 268 V286 H32"/>+ <path d="M636 268 V286 H618"/>+ </g>++ <g opacity="0.22" fill="none" stroke="hsl(217.2, 32.6%, 36%)" stroke-width="1">+ <path d="M83 41 L584 40 L610 77 L560 118 L118 110 L55 76 Z"/>+ <path d="M153 41 L124 111"/>+ <path d="M321 41 L304 109"/>+ <path d="M476 40 L514 113"/>+ </g>++ <rect x="48" y="54" width="554" height="54" rx="10" fill="url(#barGlow)" stroke="hsl(217.2, 32.6%, 30%)"/>+ <polygon points="87,60 158,54 133,108 63,104" fill="hsl(246, 55%, 70%)" fill-opacity="0.06"/>+ <polygon points="420,54 589,54 559,108 455,108" fill="hsl(188, 53%, 63%)" fill-opacity="0.05"/>++ <circle cx="77" cy="78" r="7" fill="none" stroke="hsl(210, 40%, 83%)" stroke-width="2.2"/>+ <path d="M82 83 L90 91" stroke="hsl(210, 40%, 83%)" stroke-width="2.2" stroke-linecap="round"/>++ <g font-family="'Geist Mono', ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, monospace" font-size="12" font-weight="600" letter-spacing="0.01em" text-anchor="middle">+ <rect x="112" y="69" width="108" height="25" rx="6" fill="hsl(246, 55%, 70%)" fill-opacity="0.16" stroke="hsl(246, 55%, 70%)" stroke-opacity="0.8"/>+ <text x="166" y="86" fill="hsl(246, 72%, 85%)">level<tspan fill-opacity="0.5">:</tspan>ERROR</text>++ <rect x="230" y="69" width="86" height="25" rx="6" fill="hsl(217.2, 32.6%, 17.5%)" stroke="hsl(217.2, 32.6%, 36%)"/>+ <text x="273" y="86" fill="hsl(210, 40%, 86%)">env<tspan fill-opacity="0.5">:</tspan>prod</text>++ <rect x="326" y="69" width="100" height="25" rx="6" fill="hsl(217.2, 32.6%, 17.5%)" stroke="hsl(217.2, 32.6%, 36%)"/>+ <text x="376" y="86" fill="hsl(210, 40%, 86%)">latency<tspan fill-opacity="0.5">></tspan>2s</text>++ <rect x="436" y="69" width="86" height="25" rx="6" fill="hsl(217.2, 32.6%, 17.5%)" stroke="hsl(217.2, 32.6%, 36%)"/>+ <text x="479" y="86" fill="hsl(210, 40%, 86%)">score<tspan fill-opacity="0.5">></tspan>.8</text>++ <rect x="534" y="75" width="3" height="18" rx="1.5" fill="hsl(210, 40%, 83%)" opacity="0.85"/>+ </g>++ <g stroke="hsl(210, 40%, 83%)" stroke-width="1" stroke-dasharray="3 6" opacity="0.28" fill="none">+ <path d="M166 108 C 156 124, 139 135, 122 151"/>+ <path d="M273 108 C 277 129, 269 145, 274 165"/>+ <path d="M376 108 C 393 133, 411 149, 452 167"/>+ <path d="M479 108 C 487 131, 506 148, 540 168"/>+ </g>++ <g font-family="'Geist Mono', ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, monospace">+ <rect x="54" y="135" width="160" height="115" rx="8" fill="hsl(222.2, 84%, 4.9%)" stroke="hsl(217.2, 32.6%, 29%)"/>+ <polygon points="54,135 214,135 183,169 72,176" fill="hsl(217.2, 32.6%, 15%)" fill-opacity="0.4"/>+ <path d="M86 135 L122 250" stroke="hsl(217.2, 32.6%, 28%)" opacity="0.6"/>+ <path d="M183 135 L154 250" stroke="hsl(217.2, 32.6%, 24%)" opacity="0.6"/>++ <text x="72" y="156" font-size="9.5" font-weight="600" letter-spacing="0.16em" fill="hsl(215, 20.2%, 62%)">FILTER FIELD</text>+ <line x1="72" y1="168" x2="194" y2="168" stroke="hsl(217.2, 32.6%, 27.5%)"/>++ <circle cx="82" cy="194" r="4" fill="hsl(246, 55%, 70%)"/>+ <text x="100" y="198" font-size="12" font-weight="500" fill="hsl(210, 40%, 86%)">level</text>+ <polygon points="150,184 190,184 198,204 155,204" fill="hsl(246, 55%, 70%)" fill-opacity="0.16" stroke="hsl(246, 55%, 70%)" stroke-opacity="0.68"/>+ <text x="173" y="198" font-size="10" font-weight="600" letter-spacing="0.04em" text-anchor="middle" fill="hsl(246, 72%, 85%)">ERR</text>++ <circle cx="82" cy="228" r="4" fill="hsl(215, 20.2%, 55%)"/>+ <text x="100" y="232" font-size="12" font-weight="500" fill="hsl(215, 20.2%, 66%)">environment</text>+ </g>++ <g font-family="'Geist Mono', ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, monospace">+ <rect x="244" y="135" width="352" height="115" rx="8" fill="hsl(222.2, 84%, 4.9%)" stroke="hsl(217.2, 32.6%, 29%)"/>+ <polygon points="244,135 596,135 574,167 256,171" fill="hsl(217.2, 32.6%, 15%)" fill-opacity="0.34"/>+ <path d="M430 135 L406 250" stroke="hsl(217.2, 32.6%, 25%)" opacity="0.6"/>+ <path d="M550 135 L525 250" stroke="hsl(217.2, 32.6%, 24%)" opacity="0.6"/>++ <text x="266" y="156" font-size="9.5" font-weight="600" letter-spacing="0.16em" fill="hsl(215, 20.2%, 62%)">MATCHED TRACE</text>+ <line x1="266" y1="168" x2="574" y2="168" stroke="hsl(217.2, 32.6%, 27.5%)"/>++ <path d="M262 180 H574 L566 208 H262 Z" fill="url(#rowGlow)" stroke="hsl(246, 55%, 70%)" stroke-opacity="0.7"/>+ <rect x="262" y="217" width="304" height="22" rx="5" fill="hsl(222.2, 84%, 4.9%)" stroke="hsl(217.2, 32.6%, 28%)"/>++ <circle cx="282" cy="194" r="4" fill="hsl(246, 55%, 70%)"/>+ <text x="302" y="198" font-size="12" font-weight="500" fill="hsl(210, 40%, 87%)">checkout-flow</text>+ <text x="434" y="198" font-size="12" font-weight="600" fill="hsl(246, 72%, 85%)">ERROR</text>+ <text x="502" y="198" font-size="12" font-weight="500" fill="hsl(210, 40%, 80%)">2.4s</text>+ <polygon points="544,187 572,187 568,203 540,203" fill="hsl(246, 55%, 70%)" fill-opacity="0.22"/>+ <text x="556" y="198" font-size="10.5" font-weight="600" letter-spacing="0.02em" text-anchor="middle" fill="hsl(246, 72%, 85%)">.91</text>++ <circle cx="282" cy="228" r="3.5" fill="hsl(215, 20.2%, 55%)"/>+ <text x="302" y="232" font-size="12" font-weight="500" fill="hsl(215, 20.2%, 66%)">refund-agent</text>+ <text x="434" y="232" font-size="12" font-weight="500" fill="hsl(215, 20.2%, 62%)">WARN</text>+ <text x="502" y="232" font-size="12" font-weight="500" fill="hsl(215, 20.2%, 62%)">1.7s</text>+ </g>++ <g opacity="0.72">+ <path d="M214 195 C 226 194, 234 192, 244 190" stroke="hsl(246, 55%, 70%)" stroke-dasharray="3 5" fill="none"/>+ <circle cx="214" cy="195" r="3.5" fill="hsl(246, 55%, 70%)"/>+ </g>+</svg>diff --git a/web/src/features/feature-previews/assets/filter-search-bar-light.svg b/web/src/features/feature-previews/assets/filter-search-bar-light.svgnew file mode 100644index 0000000000..c80d33b199--- /dev/null+++ b/web/src/features/feature-previews/assets/filter-search-bar-light.svg@@ -0,0 +1,107 @@+<svg xmlns="http://www.w3.org/2000/svg" width="650" height="300" viewBox="0 0 650 300">+ <defs>+ <linearGradient id="barGlow" x1="62" y1="52" x2="595" y2="104" gradientUnits="userSpaceOnUse">+ <stop offset="0" stop-color="hsl(243, 75.4%, 58.6%)" stop-opacity="0.14"/>+ <stop offset="0.58" stop-color="hsl(210, 40%, 94%)" stop-opacity="0.72"/>+ <stop offset="1" stop-color="hsl(188, 60%, 42%)" stop-opacity="0.08"/>+ </linearGradient>+ <linearGradient id="rowGlow" x1="255" y1="173" x2="574" y2="196" gradientUnits="userSpaceOnUse">+ <stop offset="0" stop-color="hsl(243, 75.4%, 58.6%)" stop-opacity="0.2"/>+ <stop offset="1" stop-color="hsl(210, 40%, 95%)" stop-opacity="0.74"/>+ </linearGradient>+ </defs>++ <rect width="650" height="300" fill="hsl(0, 0%, 100%)"/>++ <g stroke="hsl(222.2, 47.4%, 11.2%)" stroke-width="1.5" fill="none" opacity="0.4">+ <path d="M14 32 V14 H32"/>+ <path d="M636 32 V14 H618"/>+ <path d="M14 268 V286 H32"/>+ <path d="M636 268 V286 H618"/>+ </g>++ <g opacity="0.22" fill="none" stroke="hsl(214.3, 31.8%, 82%)" stroke-width="1">+ <path d="M83 41 L584 40 L610 77 L560 118 L118 110 L55 76 Z"/>+ <path d="M153 41 L124 111"/>+ <path d="M321 41 L304 109"/>+ <path d="M476 40 L514 113"/>+ </g>++ <rect x="48" y="54" width="554" height="54" rx="10" fill="url(#barGlow)" stroke="hsl(214.3, 31.8%, 86%)"/>+ <polygon points="87,60 158,54 133,108 63,104" fill="hsl(243, 75.4%, 58.6%)" fill-opacity="0.06"/>+ <polygon points="420,54 589,54 559,108 455,108" fill="hsl(188, 60%, 42%)" fill-opacity="0.05"/>++ <circle cx="77" cy="78" r="7" fill="none" stroke="hsl(222.2, 47.4%, 11.2%)" stroke-width="2.2"/>+ <path d="M82 83 L90 91" stroke="hsl(222.2, 47.4%, 11.2%)" stroke-width="2.2" stroke-linecap="round"/>++ <g font-family="'Geist Mono', ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, monospace" font-size="12" font-weight="600" letter-spacing="0.01em" text-anchor="middle">+ <rect x="112" y="69" width="108" height="25" rx="6" fill="hsl(243, 75.4%, 58.6%)" fill-opacity="0.16" stroke="hsl(243, 75.4%, 58.6%)" stroke-opacity="0.8"/>+ <text x="166" y="86" fill="hsl(243, 75.4%, 45%)">level<tspan fill-opacity="0.5">:</tspan>ERROR</text>++ <rect x="230" y="69" width="86" height="25" rx="6" fill="hsl(210, 40%, 96.1%)" stroke="hsl(214.3, 31.8%, 82%)"/>+ <text x="273" y="86" fill="hsl(222.2, 47.4%, 11.2%)">env<tspan fill-opacity="0.5">:</tspan>prod</text>++ <rect x="326" y="69" width="100" height="25" rx="6" fill="hsl(210, 40%, 96.1%)" stroke="hsl(214.3, 31.8%, 82%)"/>+ <text x="376" y="86" fill="hsl(222.2, 47.4%, 11.2%)">latency<tspan fill-opacity="0.5">></tspan>2s</text>++ <rect x="436" y="69" width="86" height="25" rx="6" fill="hsl(210, 40%, 96.1%)" stroke="hsl(214.3, 31.8%, 82%)"/>+ <text x="479" y="86" fill="hsl(222.2, 47.4%, 11.2%)">score<tspan fill-opacity="0.5">></tspan>.8</text>++ <rect x="534" y="75" width="3" height="18" rx="1.5" fill="hsl(222.2, 47.4%, 11.2%)" opacity="0.85"/>+ </g>++ <g stroke="hsl(222.2, 47.4%, 11.2%)" stroke-width="1" stroke-dasharray="3 6" opacity="0.28" fill="none">+ <path d="M166 108 C 156 124, 139 135, 122 151"/>+ <path d="M273 108 C 277 129, 269 145, 274 165"/>+ <path d="M376 108 C 393 133, 411 149, 452 167"/>+ <path d="M479 108 C 487 131, 506 148, 540 168"/>+ </g>++ <g font-family="'Geist Mono', ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, monospace">+ <rect x="54" y="135" width="160" height="115" rx="8" fill="hsl(0, 0%, 100%)" stroke="hsl(214.3, 31.8%, 88%)"/>+ <polygon points="54,135 214,135 183,169 72,176" fill="hsl(210, 40%, 96.1%)" fill-opacity="0.4"/>+ <path d="M86 135 L122 250" stroke="hsl(214.3, 31.8%, 91.4%)" opacity="0.6"/>+ <path d="M183 135 L154 250" stroke="hsl(214.3, 31.8%, 88%)" opacity="0.6"/>++ <text x="72" y="156" font-size="9.5" font-weight="600" letter-spacing="0.16em" fill="hsl(215.4, 16.3%, 46.9%)">FILTER FIELD</text>+ <line x1="72" y1="168" x2="194" y2="168" stroke="hsl(214.3, 31.8%, 91.4%)"/>++ <circle cx="82" cy="194" r="4" fill="hsl(243, 75.4%, 58.6%)"/>+ <text x="100" y="198" font-size="12" font-weight="500" fill="hsl(222.2, 47.4%, 11.2%)">level</text>+ <polygon points="150,184 190,184 198,204 155,204" fill="hsl(243, 75.4%, 58.6%)" fill-opacity="0.16" stroke="hsl(243, 75.4%, 58.6%)" stroke-opacity="0.68"/>+ <text x="173" y="198" font-size="10" font-weight="600" letter-spacing="0.04em" text-anchor="middle" fill="hsl(243, 75.4%, 45%)">ERR</text>++ <circle cx="82" cy="228" r="4" fill="hsl(215.4, 16.3%, 55%)"/>+ <text x="100" y="232" font-size="12" font-weight="500" fill="hsl(215.4, 16.3%, 46.9%)">environment</text>+ </g>++ <g font-family="'Geist Mono', ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, monospace">+ <rect x="244" y="135" width="352" height="115" rx="8" fill="hsl(0, 0%, 100%)" stroke="hsl(214.3, 31.8%, 88%)"/>+ <polygon points="244,135 596,135 574,167 256,171" fill="hsl(210, 40%, 96.1%)" fill-opacity="0.34"/>+ <path d="M430 135 L406 250" stroke="hsl(214.3, 31.8%, 88%)" opacity="0.6"/>+ <path d="M550 135 L525 250" stroke="hsl(214.3, 31.8%, 88%)" opacity="0.6"/>++ <text x="266" y="156" font-size="9.5" font-weight="600" letter-spacing="0.16em" fill="hsl(215.4, 16.3%, 46.9%)">MATCHED TRACE</text>+ <line x1="266" y1="168" x2="574" y2="168" stroke="hsl(214.3, 31.8%, 91.4%)"/>++ <path d="M262 180 H574 L566 208 H262 Z" fill="url(#rowGlow)" stroke="hsl(243, 75.4%, 58.6%)" stroke-opacity="0.7"/>+ <rect x="262" y="217" width="304" height="22" rx="5" fill="hsl(0, 0%, 100%)" stroke="hsl(214.3, 31.8%, 91.4%)"/>++ <circle cx="282" cy="194" r="4" fill="hsl(243, 75.4%, 58.6%)"/>+ <text x="302" y="198" font-size="12" font-weight="500" fill="hsl(222.2, 84%, 4.9%)">checkout-flow</text>+ <text x="434" y="198" font-size="12" font-weight="600" fill="hsl(243, 75.4%, 45%)">ERROR</text>+ <text x="502" y="198" font-size="12" font-weight="500" fill="hsl(215.4, 16.3%, 35%)">2.4s</text>+ <polygon points="544,187 572,187 568,203 540,203" fill="hsl(243, 75.4%, 58.6%)" fill-opacity="0.22"/>+ <text x="556" y="198" font-size="10.5" font-weight="600" letter-spacing="0.02em" text-anchor="middle" fill="hsl(243, 75.4%, 45%)">.91</text>++ <circle cx="282" cy="228" r="3.5" fill="hsl(215.4, 16.3%, 55%)"/>+ <text x="302" y="232" font-size="12" font-weight="500" fill="hsl(215.4, 16.3%, 46.9%)">refund-agent</text>+ <text x="434" y="232" font-size="12" font-weight="500" fill="hsl(215.4, 16.3%, 46.9%)">WARN</text>+ <text x="502" y="232" font-size="12" font-weight="500" fill="hsl(215.4, 16.3%, 46.9%)">1.7s</text>+ </g>++ <g opacity="0.72">+ <path d="M214 195 C 226 194, 234 192, 244 190" stroke="hsl(243, 75.4%, 58.6%)" stroke-dasharray="3 5" fill="none"/>+ <circle cx="214" cy="195" r="3.5" fill="hsl(243, 75.4%, 58.6%)"/>+ </g>+</svg>diff --git a/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsx b/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsxindex 53e30eb512..71aaafd552 100644--- a/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsx+++ b/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsx@@ -1,3 +1,4 @@+import { useState } from "react";import { useSession } from "next-auth/react";import type { Session } from "next-auth";@@ -7,7 +8,11 @@ import { showErrorToast } from "@/src/features/notifications/showErrorToast";import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";import { api } from "@/src/utils/api";-import { FeaturePreviewModal } from "./FeaturePreviewModal";+import {+ FeaturePreviewModal,+ type PreviewFlag,+ type PreviewState,+} from "./FeaturePreviewModal";type ControlledFeaturePreviewModalProps = {session: Session;@@ -15,6 +20,11 @@ type ControlledFeaturePreviewModalProps = {onOpenChange: (open: boolean) => void;};+const PREVIEW_LABEL: Record<PreviewFlag, string> = {+ inAppAgent: "Langfuse Assistant",+ searchBar: "Filter Search Bar",+};+export function ControlledFeaturePreviewModal({session,open,@@ -23,20 +33,34 @@ export function ControlledFeaturePreviewModal({const authSession = useSession();const { project, organization } = useQueryProjectOrOrganization();const hasInAppAgentEntitlement = useHasEntitlement("in-app-agent");- const setInAppAgentPreviewEnabled =- api.userAccount.setInAppAgentPreviewEnabled.useMutation({+ // Track in-flight toggles per flag. useMutation only remembers the LATEST+ // .mutate() in `variables`, so toggling two previews in quick succession+ // would let an earlier still-pending row look idle and re-enable its Switch.+ const [pendingFlags, setPendingFlags] = useState<Set<PreviewFlag>>(new Set());+ const setFeaturePreviewEnabled =+ api.userAccount.setFeaturePreviewEnabled.useMutation({+ onMutate: (variables) => {+ setPendingFlags((prev) => new Set(prev).add(variables.flag));+ },onSuccess: async (_data, variables) => {await authSession.update();showSuccessToast({title: "Feature preview updated",- description: variables.enabled- ? "Langfuse Assistant preview has been enabled."- : "Langfuse Assistant preview has been disabled.",+ description: `${PREVIEW_LABEL[variables.flag]} preview has been ${+ variables.enabled ? "enabled" : "disabled"+ }.`,});},onError: (error) => {showErrorToast("Failed to update feature preview", error.message);},+ onSettled: (_data, _error, variables) => {+ setPendingFlags((prev) => {+ const next = new Set(prev);+ next.delete(variables.flag);+ return next;+ });+ },});const user = authSession.data?.user ?? session.user;@@ -44,28 +68,39 @@ export function ControlledFeaturePreviewModal({return null;}- const inAppAgentEnabledByUser = user.featureFlags.inAppAgent === true;- const warningReason = getInAppAgentWarningReason({- hasOrganizationContext: Boolean(organization),- hasProjectContext: Boolean(project),- hasInAppAgentEntitlement,- organizationAiFeaturesEnabled: organization?.aiFeaturesEnabled,- });+ const onToggle = (flag: PreviewFlag) => (enabled: boolean) =>+ setFeaturePreviewEnabled.mutate({ flag, enabled });+ // Each row reflects ITS OWN in-flight mutation, not just the latest one.+ const isToggling = (flag: PreviewFlag) => pendingFlags.has(flag);++ const state: Partial<Record<PreviewFlag, PreviewState>> = {+ inAppAgent: {+ enabled: user.featureFlags.inAppAgent === true,+ warningReason: getInAppAgentWarningReason({+ hasOrganizationContext: Boolean(organization),+ hasProjectContext: Boolean(project),+ hasInAppAgentEntitlement,+ organizationAiFeaturesEnabled: organization?.aiFeaturesEnabled,+ }),+ onToggle: onToggle("inAppAgent"),+ isToggling: isToggling("inAppAgent"),+ },+ searchBar: {+ enabled: user.featureFlags.searchBar === true,+ // The bar renders on the new (v4) Observations and Traces tables, so flag it.+ warningReason: user.v4BetaEnabled+ ? undefined+ : "The search bar appears on the new (v4) Observations and Traces tables. Turn on Fast (Preview) in the sidebar to use it after enabling this preview.",+ onToggle: onToggle("searchBar"),+ isToggling: isToggling("searchBar"),+ },+ };return (<FeaturePreviewModalopen={open}onOpenChange={onOpenChange}- inAppAgent={{- enabled: inAppAgentEnabledByUser,- warningReason,- onToggle: (enabled) => {- setInAppAgentPreviewEnabled.mutate({- enabled,- });- },- isToggling: setInAppAgentPreviewEnabled.isPending,- }}+ state={state}/>);}diff --git a/web/src/features/feature-previews/components/FeaturePreviewModal.stories.tsx b/web/src/features/feature-previews/components/FeaturePreviewModal.stories.tsxindex edf31209fa..95a1448dbd 100644--- a/web/src/features/feature-previews/components/FeaturePreviewModal.stories.tsx+++ b/web/src/features/feature-previews/components/FeaturePreviewModal.stories.tsx@@ -17,18 +17,25 @@ function StatefulFeaturePreviewModal(args: FeaturePreviewModalProps) {updateArgs({ open });args.onOpenChange(open);}}- inAppAgent={{- ...args.inAppAgent,- onToggle: (enabled) => {- updateArgs({- inAppAgent: {- ...args.inAppAgent,- enabled,- },- });- args.inAppAgent.onToggle(enabled);- },- }}+ state={Object.fromEntries(+ Object.entries(args.state).map(([flag, item]) => [+ flag,+ item+ ? {+ ...item,+ onToggle: (enabled: boolean) => {+ updateArgs({+ state: {+ ...args.state,+ [flag]: { ...item, enabled },+ },+ });+ item.onToggle(enabled);+ },+ }+ : item,+ ]),+ )}/>);}@@ -48,10 +55,9 @@ const meta = preview.meta({args: {open: true,onOpenChange: fn(),- inAppAgent: {- enabled: true,- onToggle: fn(),- isToggling: false,+ state: {+ inAppAgent: { enabled: true, onToggle: fn(), isToggling: false },+ searchBar: { enabled: false, onToggle: fn(), isToggling: false },},},render: StatefulFeaturePreviewModal,@@ -61,21 +67,28 @@ export const Default = meta.story({});export const Warning = meta.story({args: {- inAppAgent: {- enabled: false,- warningReason:- "The Assistant button is only shown inside a project. Open a project to use it after enabling the preview.",- onToggle: fn(),+ state: {+ inAppAgent: {+ enabled: false,+ warningReason:+ "The Assistant button is only shown inside a project. Open a project to use it after enabling the preview.",+ onToggle: fn(),+ },+ searchBar: {+ enabled: false,+ warningReason:+ "The search bar appears on the new (v4) Observations and Traces tables. Turn on Fast (Preview) in the sidebar to use it after enabling this preview.",+ onToggle: fn(),+ },},},});export const Loading = meta.story({args: {- inAppAgent: {- enabled: true,- onToggle: fn(),- isToggling: true,+ state: {+ inAppAgent: { enabled: true, onToggle: fn(), isToggling: true },+ searchBar: { enabled: false, onToggle: fn(), isToggling: false },},},});diff --git a/web/src/features/feature-previews/components/FeaturePreviewModal.tsx b/web/src/features/feature-previews/components/FeaturePreviewModal.tsxindex 6212cf5d5e..d98a2a58f1 100644--- a/web/src/features/feature-previews/components/FeaturePreviewModal.tsx+++ b/web/src/features/feature-previews/components/FeaturePreviewModal.tsx@@ -1,4 +1,5 @@import Image from "next/image";+import { useEffect, useState } from "react";import {Dialog,@@ -9,21 +10,77 @@ import {DialogTitle,} from "@/src/components/ui/dialog";import { Switch } from "@/src/components/ui/switch";+import { Button } from "@/src/components/ui/button";+import { cn } from "@/src/utils/tailwind";import inAppAgentDarkIllustration from "../assets/in-app-agent-dark.svg";import inAppAgentLightIllustration from "../assets/in-app-agent-light.svg";-import { Button } from "@/src/components/ui/button";+import filterSearchBarDarkIllustration from "../assets/filter-search-bar-dark.svg";+import filterSearchBarLightIllustration from "../assets/filter-search-bar-light.svg";++/** Flags the Feature Preview modal can toggle. Keep in sync with the+ * userAccount.setFeaturePreviewEnabled allowlist and available-flags.ts. */+export type PreviewFlag = "inAppAgent" | "searchBar";++type PreviewIllustration = {+ light: React.ComponentProps<typeof Image>["src"];+ dark: React.ComponentProps<typeof Image>["src"];+ alt: string;+};++type PreviewRegistryItem = {+ flag: PreviewFlag;+ title: string;+ sidebarLabel: string;+ description: string;+ details: string;+ feedbackUrl: string;+ illustration: PreviewIllustration;+};++/** Per-preview dynamic state, supplied by ControlledFeaturePreviewModal (which+ * owns the session + the toggle mutation). The static content lives here. */+export type PreviewState = {+ enabled: boolean;+ warningReason?: string;+ onToggle: (enabled: boolean) => void;+ isToggling?: boolean;+};-const IN_APP_AGENT_PREVIEW_ITEM = {- id: "in-app-agent",- title: "Langfuse Assistant",- sidebarLabel: "Langfuse Assistant",- description:- "Explore project data, understand connected Langfuse resources, and get practical help while investigating your application.",- details:- "This experimental preview can help you inspect traces and observations, look up related scores or prompts, and answer practical questions while you work in a project. Today, it is most useful for exploring project data and understanding how different Langfuse resources connect. Over time, the goal is to help teams generate insights faster and improve their agentic products with less manual investigation.",- feedbackUrl: "https://github.com/orgs/langfuse/discussions/14196",-} as const;+// Static registry — one entry per preview. Order = sidebar order; each+// preview ships separate light/dark illustrations.+const PREVIEW_REGISTRY: PreviewRegistryItem[] = [+ {+ flag: "inAppAgent",+ title: "Langfuse Assistant",+ sidebarLabel: "Langfuse Assistant",+ description:+ "Explore project data, understand connected Langfuse resources, and get practical help while investigating your application.",+ details:+ "This experimental preview can help you inspect traces and observations, look up related scores or prompts, and answer practical questions while you work in a project. Today, it is most useful for exploring project data and understanding how different Langfuse resources connect. Over time, the goal is to help teams generate insights faster and improve their agentic products with less manual investigation.",+ feedbackUrl: "https://github.com/orgs/langfuse/discussions/14196",+ illustration: {+ light: inAppAgentLightIllustration,+ dark: inAppAgentDarkIllustration,+ alt: "Langfuse Assistant connects traces, scores, and prompts to answer project questions.",+ },+ },+ {+ flag: "searchBar",+ title: "Filter Search Bar",+ sidebarLabel: "Filter Search Bar",+ description:+ "A keyboard-driven query bar on the Observations and Traces tables — type filters like level:ERROR -env:dev latency:>2 with inline suggestions, alongside the existing filter sidebar.",+ details:+ "The search bar lets you build and edit filters by typing a compact query language with autocomplete, instead of clicking through the sidebar. It stays in sync with the sidebar (both read and write the same filter state) and supports field filters, comparisons, any-of groups, negation, metadata/score paths, and full-text search across input/output. It is available on the new (v4) Observations and Traces tables.",+ feedbackUrl: "https://github.com/orgs/langfuse/discussions/14196",+ illustration: {+ light: filterSearchBarLightIllustration,+ dark: filterSearchBarDarkIllustration,+ alt: "The filter search bar turns typed queries like level:ERROR -env:dev into Observations and Traces table filters with inline suggestions.",+ },+ },+];const FEATURE_PREVIEW_MODAL_TITLE = "Feature Preview";const FEATURE_PREVIEW_MODAL_SUBTITLE =@@ -32,20 +89,28 @@ const FEATURE_PREVIEW_MODAL_SUBTITLE =export type FeaturePreviewModalProps = {open: boolean;onOpenChange: (open: boolean) => void;- inAppAgent: {- enabled: boolean;- warningReason?: string;- onToggle: (enabled: boolean) => void;- isToggling?: boolean;- };+ /** Dynamic state per preview flag. Only previews with an entry here render. */+ state: Partial<Record<PreviewFlag, PreviewState>>;};export function FeaturePreviewModal({open,onOpenChange,- inAppAgent,+ state,}: FeaturePreviewModalProps) {- const inAppAgentToggleDisabled = inAppAgent.isToggling === true;+ const items = PREVIEW_REGISTRY.filter((item) => state[item.flag]);+ const [selectedFlag, setSelectedFlag] = useState<PreviewFlag | null>(+ items[0]?.flag ?? null,+ );+ // Keep the selection valid if the available previews change.+ useEffect(() => {+ if (items.length > 0 && !items.some((i) => i.flag === selectedFlag)) {+ setSelectedFlag(items[0]!.flag);+ }+ }, [items, selectedFlag]);++ const selected = items.find((i) => i.flag === selectedFlag) ?? items[0];+ const selectedState = selected ? state[selected.flag] : undefined;return (<Dialog open={open} onOpenChange={onOpenChange}>@@ -67,62 +132,79 @@ export function FeaturePreviewModal({<DialogBody className="grid min-h-0 gap-0 overflow-hidden p-0 md:grid-cols-[220px_1fr]"><aside className="border-border bg-muted/20 border-b p-3 md:border-r md:border-b-0"><div className="flex gap-2 overflow-x-auto md:flex-col md:overflow-x-visible">- <button- type="button"- className="bg-muted text-foreground flex min-w-48 items-start rounded-md border border-transparent px-3 py-3 text-left transition-colors md:min-w-0"- >- <span className="min-w-0">- <span className="block text-sm font-medium">- {IN_APP_AGENT_PREVIEW_ITEM.sidebarLabel}- </span>- <span className="text-muted-foreground mt-1 line-clamp-2 block text-xs">- {inAppAgent.enabled ? "Enabled" : "Available"}- </span>- </span>- </button>+ {items.map((item) => {+ const isSelected = item.flag === selected?.flag;+ return (+ <button+ key={item.flag}+ type="button"+ onClick={() => setSelectedFlag(item.flag)}+ aria-pressed={isSelected}+ className={cn(+ "flex min-w-48 items-start rounded-md border px-3 py-3 text-left transition-colors md:min-w-0",+ isSelected+ ? "bg-muted text-foreground border-transparent"+ : "text-muted-foreground hover:bg-muted/50 border-transparent",+ )}+ >+ <span className="min-w-0">+ <span className="block text-sm font-medium">+ {item.sidebarLabel}+ </span>+ <span className="text-muted-foreground mt-1 line-clamp-2 block text-xs">+ {state[item.flag]?.enabled ? "Enabled" : "Available"}+ </span>+ </span>+ </button>+ );+ })}</div></aside><section className="bg-background min-h-0 overflow-y-auto p-6">- {inAppAgent.warningReason ? (- <div className="mb-4 rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-800 dark:text-yellow-200">- {inAppAgent.warningReason}- </div>- ) : null}+ {selected && selectedState ? (+ <>+ {selectedState.warningReason ? (+ <div className="mb-4 rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-800 dark:text-yellow-200">+ {selectedState.warningReason}+ </div>+ ) : null}- <div className="flex items-start justify-between gap-6">- <div>- <h2 className="text-foreground text-xl font-semibold">- {IN_APP_AGENT_PREVIEW_ITEM.title}- </h2>- <p className="text-muted-foreground mt-2 max-w-2xl text-sm leading-5">- {IN_APP_AGENT_PREVIEW_ITEM.description}- </p>- <Button asChild className="mt-4">- <a- href={IN_APP_AGENT_PREVIEW_ITEM.feedbackUrl}- target="_blank"- rel="noopener noreferrer"- >- Give feedback- </a>- </Button>- </div>- <div className="flex shrink-0 flex-col items-end gap-2">- <Switch- checked={inAppAgent.enabled}- disabled={inAppAgentToggleDisabled}- onCheckedChange={inAppAgent.onToggle}- aria-label={`Toggle ${IN_APP_AGENT_PREVIEW_ITEM.title}`}- />- </div>- </div>+ <div className="flex items-start justify-between gap-6">+ <div>+ <h2 className="text-foreground text-xl font-semibold">+ {selected.title}+ </h2>+ <p className="text-muted-foreground mt-2 max-w-2xl text-sm leading-5">+ {selected.description}+ </p>+ <Button asChild className="mt-4">+ <a+ href={selected.feedbackUrl}+ target="_blank"+ rel="noopener noreferrer"+ >+ Give feedback+ </a>+ </Button>+ </div>+ <div className="flex shrink-0 flex-col items-end gap-2">+ <Switch+ checked={selectedState.enabled}+ disabled={selectedState.isToggling === true}+ onCheckedChange={selectedState.onToggle}+ aria-label={`Toggle ${selected.title}`}+ />+ </div>+ </div>- <PreviewMockupPanel />+ <PreviewMockupPanel illustration={selected.illustration} />- <p className="text-muted-foreground mt-5 text-sm leading-5">- {IN_APP_AGENT_PREVIEW_ITEM.details}- </p>+ <p className="text-muted-foreground mt-5 text-sm leading-5">+ {selected.details}+ </p>+ </>+ ) : null}</section></DialogBody></DialogContent>@@ -130,17 +212,21 @@ export function FeaturePreviewModal({);}-function PreviewMockupPanel() {+function PreviewMockupPanel({+ illustration,+}: {+ illustration: PreviewIllustration;+}) {return (<div className="border-border bg-muted/30 mt-6 overflow-hidden rounded-2xl border shadow-inner"><Image- src={inAppAgentLightIllustration}- alt="Langfuse Assistant connects traces, scores, and prompts to answer project questions."+ src={illustration.light}+ alt={illustration.alt}className="block h-auto w-full dark:hidden"/><Image- src={inAppAgentDarkIllustration}- alt="Langfuse Assistant connects traces, scores, and prompts to answer project questions."+ src={illustration.dark}+ alt={illustration.alt}className="hidden h-auto w-full dark:block"/></div>diff --git a/web/src/features/search-bar/README.md b/web/src/features/search-bar/README.mdnew file mode 100644index 0000000000..6d8a984666--- /dev/null+++ b/web/src/features/search-bar/README.md@@ -0,0 +1,343 @@+# Search Bar (Observations v4)++Grammar-based query bar for the observations (v4 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).+Per-user **Feature Preview** opt-in. Based on the `langfuse-search-bar` prototype.++## Enablement++- Per-user **Feature Preview** opt-in (sidebar user menu → Feature Preview →+ "Filter Search Bar"), exactly like the Langfuse Assistant. Stored on+ `user.featureFlags` (the `searchBar` flag, see+ `features/feature-flags/available-flags.ts`); toggled via+ `userAccount.setFeaturePreviewEnabled({ flag, enabled })`; read through the+ session by `hooks/useSearchBarEnabled.ts`+ (`session.user.featureFlags.searchBar`). No project metadata, no `project:update`+ RBAC. The Feature Preview menu is Cloud-only, so the flag is Cloud-enableable.+- `EventsTable` activates the bar only when the user enabled the preview, the+ viewer has the **v4 beta** (the bar only renders on the v4 Observations+ table), and the table is a full-page surface+ (`!hideControls && !externalFilterState && !peekContext && !userId && !sessionId`).+ Default off — zero changes for users who don't opt in. The Feature Preview+ modal warns that the v4 beta is also required.++## Query language++`key:value` filters AND-joined, mirroring exactly what the flat+`FilterState` contract can express today:++- `level:(ERROR OR WARNING)` any-of, `-env:dev` none-of,+ `tags:(a AND b)` array all-of+- `latency:>2`, `startTime:>2026-06-01` comparisons+- text match via positional `*` globs (shown on a textSearch field, where the+ bare form defaults to contains): `statusMessage:*chat*` contains,+ `statusMessage:chat*` starts-with, `statusMessage:*chat` ends-with,+ `statusMessage:chat` bare (contains default), `statusMessage:=chat` exact+ (quote a literal `*`, e.g. `statusMessage:"a*b"`). `name:`/`id:` work the same+ way (bare = contains, `:=` = exact) but still suggest observed values.+- `metadata.region:eu`, `scores.accuracy:>0.8`, `traceScores.nps:positive`+- `has:endTime` / `-has:endTime` null checks+- full-text search (see below): bare text, or `input:`/`output:`/`name:`/`id:`++Cross-field OR, negated groups, and other shapes the flat contract cannot+represent are commit-blocking diagnostics, not silent drops. There is no+FTS `*` operator: the events tRPC filter contract has none.++**Full-text search.** It matches as a **contiguous substring** server-side+(`clickhouse-sql/search.ts`, `ILIKE %query%`) and is expressed field-style:++- **bare text** (`refund policy`) → `searchQuery`, default scope:+ `searchType=['id','content']` — i.e. `id` + `user_id` + `name` (the `id`+ lane) **and** `input` + `output` (the `content` lane). Typing plain text+ searches all of them. The adapter emits a `null` searchType (no scope token);+ `commit.ts`'s `DEFAULT_SEARCH_TYPE` supplies `['id','content']`.+- **`input:"refund"` / `output:"refund"`** → real `string` "contains" **column+ filters** on `e.input`/`e.output` (not `searchType`). Use them to narrow the+ search to one payload channel. They round-trip as `FilterState` like any+ other column filter, and support operators (`:=`, `*`/glob, `-` negation).+- **`name:"checkout"` / `id:"abc"`** → `string` "contains" column filters on+ `name`/`id`. Use them to narrow to that column. They are `textSearch` fields+ (bare = contains, `:=` = exact) but keep their observed-value autocomplete.++Typing bare text offers the scope rewrites (`input:`/`output:`) with hover+explanations. Scope is global per query (`searchType` is one value), so+multi-word free text is a **phrase**, not token-AND — `test media` matches+"Test Media" but not "Media — Test run" (open Decision A below).++Historical note: the old `in:<scope>` token and the `content:` pseudo-field are+both **gone**. `content:` searched input + output combined; that is now simply+the default (a bare query already searches both), so the token was removed (the+one capability it uniquely had — "payloads but NOT ids/names" — is dropped,+pending feedback). The reverse adapter canonicalizes a legacy+`searchType=input|output` to the `input:`/`output:` **column filter** on the+next commit (the chosen normalization), and treats any `id`/`content` searchType+as the default — rendered as bare text, no token.++**Known limitation (multi-scope legacy state).** The bar's scope is a single+value per query; the legacy toolbar's `searchType` was a _set_. `['id','content']`+now round-trips losslessly — it **is** the default, rendered as bare text. The+two remaining multi-scope states still drop their id channel on the next commit:+`['id','input']` / `['id','output']` canonicalize to `input:"…"` / `output:"…"`+**column filters** (per the historical note above) and drop the id-scope+`searchType`/`searchQuery`. There's no lossless single-token projection of those+two without a real per-column "all fields" scope — deferred past beta. Trigger is+narrow (a legacy URL from the old dropdown + the bar enabled + a commit).++Operator-looking tokens that aren't supported yet are **reserved** — they emit+an explicit "not supported yet" diagnostic instead of silently becoming free+text: `!`, lowercase `not`/`or`/`and` (use `-field:value` to exclude;+`field:(A OR B)` for one field's values). Quote a reserved word (`"or"`) to+search for it as literal text. (Top-level grouping with `(` `)` is tracked as a+follow-up.)++## Data flow (one source of truth, one direction)++The table's URL filter state — `FilterState` (the `filter` param, owned by the+facet sidebar's `useSidebarFilterState`) plus `searchQuery`/`searchType` (the+`search`/`searchType` params, owned by `useFullTextSearch`) — is the **single+source of truth**. The bar is a _controlled editor_ over it; the facet sidebar+is another. Neither stores a second copy.++```+URL filter state (FilterState + searchQuery/searchType) ← single source+ │ filterStateToQueryText (pure, derived)+ ▼+committedText ──resetTo──▶ store.draft ──(type/pick/remove)──▶ draft+ ▲ │ planCommit (pure)+ └──────────── setFilterState / setSearchQuery ◀── commit() ◀──┘+```++- The committed query text is **derived** from the source, never stored.+- The bar's only persistent local state is the **draft** (the edit buffer).+- There is exactly **one effect** (`resetTo` when the derived committed text+ changes) and it never writes back, so the cycle cannot loop. No+ reconciliation signature, no two-way sync — a commit's own echo settles+ because `resetTo` no-ops when the draft already matches.+- This mirrors the prototype's ADR-006 ("URL is canonical; everything derives+ from it") and "no write loops".++## Invariants (don't break these)++- **No silent drops or rewrites.** Every filter is either rendered in the bar,+ preserved untouched via `skippedFilters` (shapes the grammar can't express —+ `positionInTrace`, keys with grammar chars, single-value `all of`), or a+ commit-blocking diagnostic. Never silently dropped, reordered into a+ different filter, or rewritten.+- **validate ↔ lower parity, across _every_ site.** `draftValid` (store),+ token classification (`deriveComposerSegments`), and the commit gate+ (`planCommit` → `validateQuery` + `astToFilterState`) must all lower with the+ **same `scoreTypes`** context. If they diverge, the red-state gate (which+ reads `draftValid`) disagrees with the commit gate and Enter silently no-ops.+ This regressed twice — `scoreTypes` is now threaded through all three.+- **Negation is not a primitive.** `-`/`NOT` lower to existing inverse+ operators (`none of`, `does not contain`, `is null`) or flip a comparison /+ boolean. Anything without a native inverse is a diagnostic (`fields.ts`+ `negationIssue` is the spec) — the backend has no general NOT.++## Ownership map++- `lib/` — pure logic, no React/DOM. `langQ.ts` (tolerant lexer/parser ++ canonical serializer), `ast.ts`, `fields.ts` (field registry ++ operator-validity table mirroring `eventsTableCols`), `validate.ts` (commit+ gate; parity with the adapter by construction), `adapter.ts`+ (AST → flat `FilterState` + searchQuery/searchType), `commit.ts`+ (`planCommit`: the pure validate+lower gate that turns draft text into+ applied filter state), `filter-state-to-query.ts` (reverse: applied state →+ committed text — the derive direction), `completions.ts` (pure completion+ planner), `composer-segments.ts` (draft text → renderable token segments),+ `edits.ts` (span-local chip removal with AST-surgery fallback),+ `observed-options.ts` (filterOptions → per-column observed values),+ `searchBarInvariants.ts` (pure, registry-shaped property-test harness — the+ universal safety net reused per view; see Hardening).+- `store/searchBarStore.ts` — per-mount vanilla zustand store, **draft only**+ (`setDraft`/`resetTo`/`removeChipSpan`/`revealInvalid`). No committed copy,+ no commit workflow. Provided with the container's `commit` via+ `store/SearchBarStoreProvider.tsx` (`useSearchBarStore` selector,+ `useSearchBarCommit`).+- `hooks/useEventsSearchBar.ts` — the container/bridge. Derives `committedText`+ (memo), runs the one `resetTo` effect, and owns the `commit()` workflow+ (planCommit → write filter state + record recent). No URL param of its own;+ no signature guard.+- `components/`:+ - `SearchComposer.tsx` — the stateful contenteditable CONTROLLER: browser+ owns selection, mutations flow through `beforeinput`, undo/redo/caret/+ autocomplete state. Picking a value advances to "append next"; ArrowRight+ at the end of the query exits the last token. Paste inserts cleaned text+ (line-breaks/tabs → spaces) into the draft, which auto-tokenizes like typed+ text — there is no special structured-vs-raw paste branch. Editing a+ value works by placing the caret in it (click/arrow): the value-stage+ popover then offers that field's values with the current one active.+ - `ComposerTokens.tsx` — **presentational** (pure, prop-driven): draft text →+ styled token spans. `cva` token variants. Story: `ComposerTokens.stories`.+ - `AutocompleteListbox.tsx` — **presentational** ARIA listbox over a+ `CompletionPlan`. Story: `AutocompleteListbox.stories`. `AutocompletePopover`+ only positions it.+ - `EventsSearchBarRow.tsx` (full-width composer; `EventsTable` owns the+ sticky stack around the composer + toolbar),+ `EventsHeaderControls.tsx` (time range + refresh, portaled into the page+ header). The enablement toggle lives in the shared Feature Preview modal+ (`features/feature-previews/`), not in this feature.++## Integration (EventsTable)++The table always reads the sidebar's `effectiveFilterState` ++`searchQuery`/`searchType` — unchanged from non-bar mode. The events table is+mounted by both `/observations` and `/traces` in v4 mode (and embedded on the+user/session detail pages — page-scoped by `userId`/`sessionId` — and the+evaluator form via `hideControls`, where the bar stays off). In bar mode the+toolbar's legacy search field is hidden (full-text search is inline in the+bar); the time-range/refresh controls (`EventsHeaderControls`) render into+the page header when the host page provides a header-actions slot+(`actionButtonsRight` with a callback-ref DOM node), and **fall back to inline+beside the bar** when it does not — so they are never dropped if a page forgets+the slot. The facet sidebar, view drawer, filter toggle, and AI filter all+stay. Because both the bar and the sidebar are+controlled editors over the same source, they reflect each other with no+explicit sync. Saved views write through `setFilterState`, so they flow into+both surfaces. Order is preserved _within_ each category — filter-to-filter+order and within-free-text order survive the AST/serializer and URL+encode/decode round-trip. The flat URL contract (`FilterState` + `searchQuery`++- `searchType` as three separate params) has no slot for the relative position+ of filters vs free text, so on commit the reverse adapter canonicalizes to+ `<filters> <freetext>`: typing `refund level:ERROR`+ and pressing Enter re-renders the bar as `level:ERROR refund`. The typed+ interleave is preserved only in the recent-searches entry (`planCommit`'s+ `canonical`), not in the live bar.++## Extending to other views (the universality contract)++The bar is intended to become the primary filter interface for **every**+filterable view, not just the v4 events table. That is cheap _by design_ — but+only if new views extend it through the seam below instead of forking the+grammar. Read this before adding a second view.++**Why it's cheap: the back half is already universal.** Langfuse has ~15+filterable views (traces, sessions, observations, events v4, scores, prompts,+users, monitors, evaluators, eval-logs, experiments, experiment-items,+datasets…). Every one of them already rides ONE pipeline:++```+ColumnDefinition[] (per view — packages/shared/src/tableDefinitions/*,+ │ web/src/features/filters/config/*)+ ▼+flat FilterState (singleFilter — packages/shared/src/interfaces/filters.ts)+ ▼+createFilterFromFilterState → ClickHouse+ (packages/shared/src/server/queries/clickhouse-sql/factory.ts)+```++The bar's adapter emits that **same `FilterState`** (see the `fields.ts` header:+"the adapter never emits a filter shape the sidebar could not produce"). So the+lowering, the URL contract, and the facet sidebar are **already shared** with+the bar. The only thing forked per view is the **front half**: the field+registry + grammar + value validation. Keep it that way.++**The seam to open before the 2nd view.** Today `FIELDS` is a module-level const+hardcoded to `eventsTableCols`, and `resolveField`/`operatorIssue` close over+it. Multi-view requires making the registry an **injected parameter** of the+grammar — parser, validator, adapter, and completion planner take a+`FieldRegistry` instead of importing the const. This is the one structural+refactor; everything after it is data, not code.++**Recipe to add the bar to a view:**++1. **Derive the field registry from that view's `ColumnDefinition[]`** — do NOT+ hand-author a second 47-entry list. ~70% is mechanical: `type → kind`+ (`number`/`datetime`/`boolean` map directly, everything else → `text`),+ `nullable`, `options → observed values`, `unit`. Write a+ `fieldRegistryFromColumns(cols)` helper.+2. **Add a thin per-view grammar overlay** for what `ColumnDefinition`+ deliberately does not carry (it is a UI/SQL contract, not a grammar):+ user-facing **aliases** (`env`, `tags`, `ttft`), **dot-path roots**+ (`metadata.`, `scores.`/`traceScores.` and their score columns), and+ **value-parse hints** (datetime ISO, numeric, boolean). Keep it small and+ declarative.+3. **Reuse the view's `filterOptions` tRPC** for observed values —+ `observed-options.ts` already maps that payload to per-column observed+ values; point it at the new view's procedure (do not invent a parallel one).+4. **Keep the adapter targeting the shared `FilterState`.** Reuse the+ already-registry-driven `operatorIssue`/`negationIssue` and the existing+ per-kind lowering. Never add a second lowering path — that breaks the+ universality and re-opens the validate↔lower parity drift.+5. **Per-kind handlers, not per-field branches.** The recurring parity+ regressions came from a kind's _validate_ half (`validate.ts`) and _lower_+ half (`adapter.ts`) living apart. New value kinds should add a single handler+ that owns both, so the two cannot drift.+6. **Add the round-trip property test for the new registry** (see Hardening) —+ run it per registry. This is the universal safety net across views.++**What stays grammar-global — do not make per-view:** tokenizing, quoting+(`serializeValue` ↔ `reservedTokenIssue` is a **mirror invariant**: add a+reserved token to one, add it to the other, or the round-trip test fails),+operator precedence, and the `has:` pseudo-field. These are language, not+data — a new view inherits them unchanged.++**Do not couple to `ColumnDefinition` speculatively.** Build the derivation ++overlay when the first real second view lands, validated against that consumer —+not ahead of it (the same no-half-finished rule that removed the prototype's+unused planners).++## Hardening before default-on++- **Round-trip property test — implemented as a reusable harness**+ (`lib/searchBarInvariants.ts`, wired per view in+ `lib/searchBarInvariants.clienttest.ts`). The `FilterState ⇄ text` boundary+ (reverse adapter ↔ parse/lower) is where almost every correctness bug landed,+ so this is a deterministic matrix (fields × operators × adversarial values ×+ scoreTypes contexts, no new dep) checking three invariants that have each+ regressed in this PR's history:+ - **INV-1 commit-gate parity** — `validateQuery(text).valid === true` implies+ the commit-time lowering (`astToFilterState`) produces no errors. (The+ `6e84fe4`/`32215fb` class: validate clean while lower errored → empty filter+ set committed silently.)+ - **INV-2 no silent drop/rewrite** — `FilterState → text → FilterState` is+ stable: every filter round-trips unchanged or is reported in+ `skippedFilters`; none is rewritten into a different filter.+ - **INV-3 serialize ↔ parse symmetry** — a free-text value always re-parses to+ itself and stays valid. (Catches the `serializeValue`/`reservedTokenIssue`+ mirror-invariant drift — a bare reserved token like `or`/`!important` that+ the parser rejects. Verified to fail when that fix is reverted.)++ The harness is **pure and registry-shaped**: it generates the matrix from the+ passed `view.fields`, so it auto-covers added/changed fields, and a second+ filterable view gets the same coverage by adding one block to the+ `.clienttest.ts` with its registry — see "Extending to other views". When the+ grammar is parameterized over an injected registry, thread `view.registry`+ into the harness's parse/validate/lower calls; the generators and assertions+ do not change.++- **`SearchComposer` (~1.3k LOC) has no unit tests** — the contenteditable+ controller is browser-reviewed only. Extracting the selection/`beforeinput`+ machinery into a hook (below) is the prerequisite to testing it.+- **No e2e** for bar↔sidebar sync or the embedded-vs-full-page mount matrix+ (the bar leaking onto user/session detail was a review find, not caught by a+ test).++## Next slices++- Pill click-to-edit: a dedicated value-switcher dropdown anchored to a+ _selected pill_. (Editing a value already works by placing the caret in it —+ see SearchComposer; only the pill-anchored dropdown is unbuilt. The prototype's+ `planTokenValueCompletions` planner was removed as dead code in review, so this+ is a clean slice with nothing half-wired.)+- Saved-view round-trip for free text/search scopes.+- Strict-mode follow-ups (pending product decisions):+ - **Decision A — free-text semantics**: keep phrase (contiguous substring;+ free text already renders as one chip) vs. token-AND (match each word+ independently; needs a backend FTS change). See Query language above.+ - **Decision B — top-level grouping `( )`**: reserve it like the other+ operators, or leave it. Entangled with `tidyQueryText`/chip-removal (which+ strips redundant parens and would bail on a now-"invalid" paren) and+ removes documented top-level grouping — needs its own pass.+- App-wide **layer system** (z-index): the bar's overlays use a hardcoded local+ ladder (X z-20 < error tooltip z-30 < popover z-50) because the app has no+ shared z scale (overlays are just `z-50` + Radix portals). A proper layering+ system is a separate, app-level ticket.+- Optional: extract `SearchComposer`'s contenteditable selection/`beforeinput`+ machinery into a `useContentEditableController` hook to fully separate the+ imperative integration from the React component.diff --git a/web/src/features/search-bar/components/AutocompleteListbox.stories.tsx b/web/src/features/search-bar/components/AutocompleteListbox.stories.tsxnew file mode 100644index 0000000000..2f7fd85ee2--- /dev/null+++ b/web/src/features/search-bar/components/AutocompleteListbox.stories.tsx@@ -0,0 +1,114 @@+import { fn } from "storybook/test";+import preview from "../../../../.storybook/preview";+import { AutocompleteListbox } from "./AutocompleteListbox";+import type { CompletionPlan } from "@/src/features/search-bar/lib/completions";++const meta = preview.meta({+ component: AutocompleteListbox,+ args: {+ highlightedId: null,+ onPick: fn(),+ onHighlight: fn(),+ },+});++const fieldPlan: CompletionPlan = {+ stage: "field",+ from: 0,+ to: 3,+ loading: false,+ sections: [+ {+ title: "Fields",+ options: [+ {+ id: "field:level",+ kind: "field",+ label: "level",+ detail: "Observation level",+ fieldId: "level",+ },+ {+ id: "field:latency",+ kind: "field",+ label: "latency",+ detail: "Observation latency in seconds",+ fieldId: "latency",+ },+ ],+ },+ {+ title: "Patterns",+ options: [+ {+ id: "pat:anyof",+ kind: "pattern",+ label: "field:(a OR b)",+ detail: "any of",+ insert: "level:(ERROR OR WARNING)",+ },+ ],+ },+ ],+};++const valuePlan: CompletionPlan = {+ stage: "value",+ from: 6,+ to: 6,+ loading: false,+ sections: [+ {+ title: "Observed values",+ options: [+ {+ id: "value:ERROR",+ kind: "value",+ label: "ERROR",+ detail: "23",+ value: "ERROR",+ active: true,+ },+ {+ id: "value:WARNING",+ kind: "value",+ label: "WARNING",+ detail: "28",+ value: "WARNING",+ },+ ],+ },+ {+ title: "Match operators",+ options: [+ {+ id: "vop:contains",+ kind: "pattern",+ label: "*value*",+ detail: "contains — e.g. level:*refund*",+ insert: "*refund*",+ },+ ],+ },+ ],+};++export const Fields = meta.story({+ args: { plan: fieldPlan, highlightedId: "field:level" },+});++export const ObservedValues = meta.story({+ args: { plan: valuePlan },+});++export const Loading = meta.story({+ args: {+ plan: { stage: "value", from: 6, to: 6, loading: true, sections: [] },+ },+});++export const Empty = meta.story({+ args: {+ plan: { stage: "value", from: 0, to: 0, loading: false, sections: [] },+ },+});diff --git a/web/src/features/search-bar/components/AutocompleteListbox.tsx b/web/src/features/search-bar/components/AutocompleteListbox.tsxnew file mode 100644index 0000000000..ae4cd8f7ba--- /dev/null+++ b/web/src/features/search-bar/components/AutocompleteListbox.tsx@@ -0,0 +1,150 @@+// Presentational autocomplete listbox: a pure ARIA listbox over a+// CompletionPlan. No context, no data fetching — it renders sections/options+// and reports picks/highlights to the parent. The live composer wraps it in+// AutocompletePopover (positioning); Storybook renders it directly.++import * as React from "react";+import { Check, Clock, Parentheses, Search } from "lucide-react";++import { cn } from "@/src/utils/tailwind";+import type {+ CompletionOption,+ CompletionPlan,+} from "@/src/features/search-bar/lib/completions";+import { optionDomId } from "@/src/features/search-bar/components/presentation";++function OptionIcon({ kind }: { kind: CompletionOption["kind"] }) {+ const cls = "h-3.5 w-3.5 flex-none opacity-55";+ if (kind === "recent") return <Clock className={cls} aria-hidden />;+ if (kind === "operator" || kind === "pattern")+ return <Parentheses className={cls} aria-hidden />;+ return <Search className={cls} aria-hidden />;+}++export type AutocompleteListboxProps = {+ plan: CompletionPlan;+ highlightedId: string | null;+ onPick?: (option: CompletionOption) => void;+ onHighlight?: (id: string) => void;+ listboxId?: string;+};++export function AutocompleteListbox({+ plan,+ highlightedId,+ onPick,+ onHighlight,+ listboxId = "search-bar-listbox",+}: AutocompleteListboxProps) {+ // Hover may only highlight on REAL pointer movement. When the list+ // re-renders under a stationary mouse (typing/pasting grows the popover),+ // Chromium fires synthetic mouseover events — honoring those would arm+ // Enter with an option the user never chose (keyboard keeps authority).+ const lastPointer = React.useRef<{ x: number; y: number } | null>(null);++ // Keyboard navigation only moves the highlight id; the listbox is scrollable+ // and the empty-stage plan has ~50 options, so the active option can fall+ // outside the viewport. Scroll it back into view (the UA does not do this for+ // aria-activedescendant). `nearest` avoids jumping when already visible.+ const optionRefs = React.useRef(new Map<string, HTMLDivElement>());+ React.useEffect(() => {+ if (highlightedId === null) return;+ optionRefs.current.get(highlightedId)?.scrollIntoView?.({+ block: "nearest",+ });+ }, [highlightedId]);++ const highlightOnMove = onHighlight+ ? (id: string) => (e: React.MouseEvent) => {+ const last = lastPointer.current;+ if (last !== null && last.x === e.clientX && last.y === e.clientY)+ return;+ lastPointer.current = { x: e.clientX, y: e.clientY };+ onHighlight(id);+ }+ : undefined;+ return (+ <div+ id={listboxId}+ role="listbox"+ aria-label="Search suggestions"+ 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))]",+ "max-h-[min(420px,40vh)] overflow-x-hidden overflow-y-auto",+ "bg-popover text-popover-foreground rounded-md border py-1 shadow-md",+ )}+ >+ {plan.loading && (+ <div+ data-testid="search-bar-autocomplete-loading"+ className="text-muted-foreground mx-1 flex min-h-8 items-center gap-2 px-3 text-xs"+ >+ Loading values…+ </div>+ )}+ {!plan.loading && plan.sections.length === 0 && (+ <div className="text-muted-foreground mx-1 flex min-h-8 items-center gap-2 px-3 text-xs">+ No suggestions+ </div>+ )}+ {plan.sections.map((sec, i) => (+ <div+ key={sec.title}+ role="group"+ aria-label={sec.title}+ className={cn(i > 0 && "mt-1.5 border-t pt-1.5")}+ >+ <div+ data-testid="search-bar-autocomplete-section"+ className="text-muted-foreground px-3 pt-1.5 pb-1 text-[10px] tracking-[0.06em] uppercase"+ >+ {sec.title}+ </div>+ {sec.options.map((o) => (+ <div+ key={o.id}+ ref={(el) => {+ const refs = optionRefs.current;+ if (el) refs.set(o.id, el);+ else refs.delete(o.id);+ }}+ id={optionDomId(listboxId, o.id)}+ role="option"+ aria-selected={o.id === highlightedId}+ data-option-id={o.id}+ className={cn(+ "mx-1 flex min-h-8 cursor-pointer items-center gap-2 rounded-sm px-2",+ "font-mono text-xs leading-[1.4]",+ o.id === highlightedId+ ? "bg-accent text-accent-foreground"+ : "hover:bg-accent/50",+ )}+ // mousedown must not blur the composer input mid-pick+ onMouseDown={(e) => e.preventDefault()}+ onClick={onPick ? () => onPick(o) : undefined}+ onMouseMove={highlightOnMove?.(o.id)}+ >+ <OptionIcon kind={o.kind} />+ <span className="max-w-[480px] min-w-0 flex-none truncate">+ {o.label}+ </span>+ {o.kind === "value" && o.active && (+ <Check+ className="text-foreground/80 h-3.5 w-3.5 flex-none"+ aria-label="selected"+ />+ )}+ {"detail" in o && o.detail !== undefined && (+ <span className="text-muted-foreground ml-auto pl-6 font-sans text-[11px]">+ {o.detail}+ </span>+ )}+ </div>+ ))}+ </div>+ ))}+ </div>+ );+}diff --git a/web/src/features/search-bar/components/AutocompletePopover.tsx b/web/src/features/search-bar/components/AutocompletePopover.tsxnew file mode 100644index 0000000000..8eb081a4d4--- /dev/null+++ b/web/src/features/search-bar/components/AutocompletePopover.tsx@@ -0,0 +1,78 @@+// Positions the presentational AutocompleteListbox under the composer and+// clamps it to the viewport. The listbox itself is pure and lives in+// AutocompleteListbox.tsx (and has the Storybook story).++import * as React from "react";++import {+ AutocompleteListbox,+ type AutocompleteListboxProps,+} from "@/src/features/search-bar/components/AutocompleteListbox";++export type AutocompletePopoverProps = AutocompleteListboxProps & {+ /** Anchor x in px, relative to the positioned composer container. */+ anchorLeft: number;+ /** The positioned container (for viewport collision math). */+ containerRef: React.RefObject<HTMLElement | null>;+};++/**+ * Positions the listbox under the composer at `anchorLeft`, shifted left when+ * it would overflow the right viewport edge and never past the left edge.+ */+export function AutocompletePopover({+ anchorLeft,+ containerRef,+ ...listbox+}: AutocompletePopoverProps) {+ const popRef = React.useRef<HTMLDivElement>(null);+ const [left, setLeft] = React.useState(anchorLeft);++ // Collision math needs the rendered popover width — measurement, the one+ // thing React cannot derive.+ const clamp = React.useCallback(() => {+ const pop = popRef.current;+ const container = containerRef.current;+ if (!pop || !container) return;+ const containerLeft = container.getBoundingClientRect().left;+ const width = pop.getBoundingClientRect().width;+ const margin = 8;+ const maxLeft = window.innerWidth - margin - containerLeft - width;+ const minLeft = margin - containerLeft;+ setLeft(Math.max(minLeft, Math.min(anchorLeft, maxLeft)));+ }, [anchorLeft, containerRef]);++ // Re-clamp on every plan/anchor change.+ React.useLayoutEffect(() => {+ clamp();+ }, [clamp, listbox.plan]);++ // `window.innerWidth` and the container rect both shift on viewport reflow+ // (resize, browser zoom, sidebar collapse) without a re-render or a plan+ // change. Observe the container so an open popover re-clamps instead of+ // floating at a stale offset — same pattern as the X-button measurement in+ // SearchComposer.+ React.useEffect(() => {+ const container = containerRef.current;+ if (!container || typeof ResizeObserver === "undefined") return;+ const observer = new ResizeObserver(() => clamp());+ observer.observe(container);+ return () => observer.disconnect();+ }, [clamp, containerRef]);++ return (+ // Suppress focus moves across the WHOLE popover surface, not just the option+ // rows: a mousedown on a section title / divider / padding would otherwise+ // blur the composer and fire its onBlur commit, flashing the red invalid+ // state on a mid-completion draft (`level:`, `tags:(`, …). The per-option+ // guard in AutocompleteListbox stays (preventDefault is idempotent).+ <div+ ref={popRef}+ className="absolute top-full z-50 mt-1"+ style={{ left }}+ onMouseDown={(e) => e.preventDefault()}+ >+ <AutocompleteListbox {...listbox} />+ </div>+ );+}diff --git a/web/src/features/search-bar/components/ComposerTokens.stories.tsx b/web/src/features/search-bar/components/ComposerTokens.stories.tsxnew file mode 100644index 0000000000..3cde809dbd--- /dev/null+++ b/web/src/features/search-bar/components/ComposerTokens.stories.tsx@@ -0,0 +1,36 @@+import preview from "../../../../.storybook/preview";+import { ComposerTokens } from "./ComposerTokens";++const meta = preview.meta({+ component: ComposerTokens,+ args: { showDiagnostics: false },+ // ComposerTokens returns inline content; host it in a bar-like box so the+ // tokens render in a representative context.+ decorators: [+ (Story) => (+ <div className="border-input bg-background max-w-2xl rounded-md border px-3 py-2 font-mono text-xs leading-6">+ <Story />+ </div>+ ),+ ],+});++export const Default = meta.story({+ args: { draft: "level:ERROR -environment:dev latency:>2" },+});++export const Empty = meta.story({+ args: { draft: "" },+});++export const AnyOfGroup = meta.story({+ args: { draft: "level:(ERROR OR WARNING) type:GENERATION" },+});++export const FreeTextAndScopes = meta.story({+ args: { draft: "timeout input:refund scores.accuracy:>0.8" },+});++export const InvalidRevealed = meta.story({+ args: { draft: "level:ERROR nope:1", showDiagnostics: true },+});diff --git a/web/src/features/search-bar/components/ComposerTokens.tsx b/web/src/features/search-bar/components/ComposerTokens.tsxnew file mode 100644index 0000000000..7f0901d1a3--- /dev/null+++ b/web/src/features/search-bar/components/ComposerTokens.tsx@@ -0,0 +1,153 @@+// Presentational rendering of a query draft as styled inline tokens.+//+// Pure and context-free: given the draft text, it projects it to segments+// (deriveComposerSegments — a pure parser pass) and renders the same DOM the+// contenteditable composer needs (token spans + word-joiner caret boundaries ++// verbatim whitespace). Splitting it out separates the VISUAL layer from the+// stateful contenteditable controller in SearchComposer, and makes the token+// styling a Storybook-able, prop-driven unit. Token styling lives in a `cva`+// variant; the composer passes the visible kind (invalid tokens render as+// free text until diagnostics are revealed).++import * as React from "react";+import { cva } from "class-variance-authority";++import type { ScoreTypeContext } from "@/src/features/search-bar/lib/adapter";+import {+ deriveComposerSegments,+ type FilterSegment,+} from "@/src/features/search-bar/lib/composer-segments";++// Word joiner around pills: gives the DOM caret boundaries between tokens+// without changing the query text. Stripped before the text reaches the model+// or clipboard. Shared with SearchComposer's selection math.+export const WORD_JOINER = "";++// Token spans must stay NON-positioned: `position: relative` would promote the+// span's background above the editable root's in-flow paint phase (where+// Chromium draws the text caret), hiding the caret inside the token.+export const composerTokenVariants = cva("max-w-full", {+ variants: {+ kind: {+ filter:+ "mr-1 inline rounded border px-1.5 py-1 border-border bg-secondary text-secondary-foreground shadow-sm transition-colors hover:border-ring hover:bg-accent",+ freeText:+ "mr-1 inline rounded border px-1.5 py-1 border-transparent bg-muted/70 text-foreground/90 transition-colors hover:border-border hover:bg-accent",+ operator: "font-semibold uppercase text-qlang-keyword",+ paren: "text-muted-foreground",+ invalid:+ "mr-1 inline rounded border border-dashed px-1.5 py-1 border-destructive/70 bg-destructive/10 text-destructive transition-colors hover:border-destructive",+ },+ },+ defaultVariants: { kind: "freeText" },+});++type TokenKind = "filter" | "freeText" | "operator" | "paren" | "invalid";++function renderPlainText(text: string, keyPrefix: string): React.ReactNode[] {+ return text+ .split(/(\s+)/)+ .map((part, index) => (+ <React.Fragment key={`${keyPrefix}:${index}`}>{part}</React.Fragment>+ ));+}++function FilterTokenBody({ segment }: { segment: FilterSegment }) {+ const raw = segment.raw;+ const dash = segment.negated ? "-" : "";+ const body = segment.negated ? raw.slice(1) : raw;+ const colon = body.indexOf(":");+ const value = colon === -1 ? "" : body.slice(colon + 1);+ // Numeric values (latency:>2, totalTokens:100, totalCost:0.5) read as number+ // literals, not strings — color them distinctly. Grouped/text/boolean values+ // stay green.+ const numeric =+ segment.values.length > 0 &&+ segment.values.every((v) => /^-?\d+(\.\d+)?$/.test(v.trim()));+ return (+ <>+ {/* Keep the negation dash + field + colon on one line — the `-` is a+ hyphen, so a line wrap would otherwise break it away from its field.+ The value stays outside so long grouped values can still wrap. */}+ <span className="whitespace-nowrap">+ {dash && <span className="text-muted-foreground">-</span>}+ <span data-part="field" className="text-qlang-field">+ {segment.displayField}+ </span>+ <span data-part="operator" className="text-muted-foreground">+ :+ </span>+ </span>+ <span+ data-part="value"+ className={numeric ? "text-qlang-number" : "text-qlang-value"}+ >+ {value}+ </span>+ </>+ );+}++/**+ * Render `draft` as styled tokens. `showDiagnostics` controls whether invalid+ * tokens render in the error style or fall back to plain free-text styling+ * (the composer hides token errors until a commit is attempted).+ */+export function ComposerTokens({+ draft,+ showDiagnostics,+ scoreTypes,+}: {+ draft: string;+ showDiagnostics: boolean;+ scoreTypes?: ScoreTypeContext;+}): React.ReactNode {+ const segments = deriveComposerSegments(draft, scoreTypes);+ const out: React.ReactNode[] = [];+ let cursor = 0;+ for (const segment of segments) {+ if (segment.from > cursor) {+ out.push(+ ...renderPlainText(draft.slice(cursor, segment.from), `ws:${cursor}`),+ );+ }+ const visibleKind: TokenKind =+ segment.kind === "invalid" && !showDiagnostics+ ? "freeText"+ : segment.kind;+ // Invalid tokens get the styled per-token error tooltip (a positioned+ // overlay in SearchComposer), not the native browser title. Free text is a+ // full-text search — say so on hover so a standalone text chip explains+ // itself instead of looking like a stray block.+ const title =+ segment.kind === "invalid"+ ? undefined+ : segment.kind === "freeText"+ ? `Full-text search — matches results containing "${segment.raw}". Searches ids, names, input and output by default; use input: or output: to search one payload, or name:/id: to narrow.`+ : segment.raw;+ out.push(+ <span+ key={segment.id}+ data-testid="search-bar-token"+ data-kind={visibleKind}+ data-segment-id={segment.id}+ title={title}+ className={composerTokenVariants({ kind: visibleKind })}+ >+ {segment.kind === "filter" ? (+ <FilterTokenBody segment={segment} />+ ) : (+ segment.raw+ )}+ </span>,+ );+ out.push(+ <React.Fragment key={`wj:${segment.id}`}>{WORD_JOINER}</React.Fragment>,+ );+ cursor = segment.to;+ }+ if (cursor < draft.length) {+ out.push(...renderPlainText(draft.slice(cursor), `tail:${cursor}`));+ }+ return <>{out}</>;+}diff --git a/web/src/features/search-bar/components/EventsHeaderControls.tsx b/web/src/features/search-bar/components/EventsHeaderControls.tsxnew file mode 100644index 0000000000..cf1b3c2934--- /dev/null+++ b/web/src/features/search-bar/components/EventsHeaderControls.tsx@@ -0,0 +1,47 @@+// Time-range picker + refresh control, rendered into the page header (next to+// the "Tracing" title) when the search bar is active — the search bar itself+// takes the full width of its own row below.++import { TimeRangePicker } from "@/src/components/date-picker";+import {+ DataTableRefreshButton,+ type RefreshInterval,+} from "@/src/components/table/data-table-refresh-button";+import {+ TABLE_AGGREGATION_OPTIONS,+ type TimeRange,+} from "@/src/utils/date-range-utils";++export function EventsHeaderControls({+ timeRange,+ setTimeRange,+ refreshConfig,+}: {+ timeRange: TimeRange;+ setTimeRange: (timeRange: TimeRange) => void;+ refreshConfig?: {+ onRefresh: () => void;+ isRefreshing: boolean;+ interval: RefreshInterval;+ setInterval: (interval: RefreshInterval) => void;+ };+}) {+ return (+ <>+ <TimeRangePicker+ timeRange={timeRange}+ onTimeRangeChange={setTimeRange}+ timeRangePresets={TABLE_AGGREGATION_OPTIONS}+ className="my-0 max-w-full overflow-x-auto"+ />+ {refreshConfig && (+ <DataTableRefreshButton+ onRefresh={refreshConfig.onRefresh}+ isRefreshing={refreshConfig.isRefreshing}+ interval={refreshConfig.interval}+ setInterval={refreshConfig.setInterval}+ />+ )}+ </>+ );+}diff --git a/web/src/features/search-bar/components/EventsSearchBarRow.tsx b/web/src/features/search-bar/components/EventsSearchBarRow.tsxnew file mode 100644index 0000000000..25866de899--- /dev/null+++ b/web/src/features/search-bar/components/EventsSearchBarRow.tsx@@ -0,0 +1,41 @@+// Search-bar row: the query composer at (near) full width. EventsTable owns the+// sticky stack around this row + the toolbar so the toolbar cannot scroll under+// the composer. Time-range + refresh controls normally live in the page header+// (portaled by EventsTable). When the host page provides no header slot,+// EventsTable passes them here as `inlineControls` so they always render+// somewhere. Left padding matches the toolbar row below so the bar's left edge+// aligns with it.++import type { ReactNode } from "react";++import type { ObservedOptions } from "@/src/features/search-bar/lib/observed-options";+import { SearchComposer } from "@/src/features/search-bar/components/SearchComposer";+import { SearchBarStoreProvider } from "@/src/features/search-bar/store/SearchBarStoreProvider";+import type { SearchBarStore } from "@/src/features/search-bar/store/searchBarStore";++export function EventsSearchBarRow({+ projectId,+ store,+ commit,+ observed,+ inlineControls,+}: {+ projectId: string;+ store: SearchBarStore;+ commit: () => boolean;+ observed: ObservedOptions | undefined;+ /** Time-range + refresh, rendered inline when the page provides no header+ * slot. Undefined when those controls are portaled into the page header. */+ inlineControls?: ReactNode;+}) {+ return (+ <div className="flex items-start gap-2 px-2 pt-2 pb-1">+ <div className="min-w-0 flex-1">+ <SearchBarStoreProvider store={store} commit={commit}>+ <SearchComposer projectId={projectId} observed={observed} />+ </SearchBarStoreProvider>+ </div>+ {inlineControls}+ </div>+ );+}diff --git a/web/src/features/search-bar/components/SearchComposer.tsx b/web/src/features/search-bar/components/SearchComposer.tsxnew file mode 100644index 0000000000..400e665ac7--- /dev/null+++ b/web/src/features/search-bar/components/SearchComposer.tsx@@ -0,0 +1,1474 @@+// Grammar-aware search composer.+//+// The per-mount store owns draft/committed query state. This component owns+// autocomplete state and projects the draft string into inline token spans+// inside one contenteditable root.+//+// Selection model: the BROWSER owns selection. No mouse handler prevents+// default; click, drag, double-click, and Shift+Arrow are native. A document+// `selectionchange` listener mirrors the native selection into React state+// for completion planning — it never writes back. The selection is written+// programmatically in exactly three cases: restoring it across a controlled+// text mutation, query-aware Alt/Ctrl+Arrow word movement, and caret+// placement after a popover insert. All text mutations flow through+// `beforeinput` (plus copy/cut/paste interception) as range splices against+// the draft string.++import * as React from "react";+import { useShallow } from "zustand/react/shallow";+import { AlertCircle, X } from "lucide-react";++import { cn } from "@/src/utils/tailwind";++import {+ deriveComposerSegments,+ type ComposerSegment,+} from "@/src/features/search-bar/lib/composer-segments";+import { serializeValue, termAt } from "@/src/features/search-bar/lib/langQ";+import {+ scoreTypeContextFromObserved,+ type ObservedOptions,+} from "@/src/features/search-bar/lib/observed-options";+import { getRecentSearches } from "@/src/features/search-bar/lib/recent-searches";+import {+ flattenOptions,+ planInputCompletions,+ type CompletionOption,+ type CompletionPlan,+} from "@/src/features/search-bar/lib/completions";+import {+ useSearchBarStore,+ useSearchBarStoreApi,+ useSearchBarCommit,+} from "@/src/features/search-bar/store/SearchBarStoreProvider";+import { AutocompletePopover } from "@/src/features/search-bar/components/AutocompletePopover";+import {+ ComposerTokens,+ WORD_JOINER,+} from "@/src/features/search-bar/components/ComposerTokens";+import {+ COMPOSER_PLACEHOLDER,+ optionDomId,+} from "@/src/features/search-bar/components/presentation";++const LISTBOX_ID = "search-bar-listbox";+// Word joiners (shared with ComposerTokens) give the DOM caret boundaries+// between pills without changing the query text; stripped before the text+// reaches the model or clipboard.+const WORD_JOINER_RE = new RegExp(WORD_JOINER, "g");++// Stable empty recents reference so the plan memo doesn't churn when recents+// are intentionally suppressed (popover closed or append mode).+const NO_RECENTS: string[] = [];++// Surrogate-pair guards: a non-BMP codepoint (emoji, supplementary CJK) is two+// UTF-16 code units, so a ±1 caret step can split it. Used to step the whole+// pair in the Arrow-key handler. (charCodeAt returns NaN past the end → false.)+const isHighSurrogate = (code: number) => code >= 0xd800 && code <= 0xdbff;+const isLowSurrogate = (code: number) => code >= 0xdc00 && code <= 0xdfff;++type LogicalRange = { start: number; end: number };++function textFromRoot(root: HTMLElement): string {+ return (root.textContent ?? "").replace(WORD_JOINER_RE, "");+}++function rawOffsetForLogicalOffset(+ text: string,+ logicalOffset: number,+): number {+ if (logicalOffset <= 0) return 0;+ let logical = 0;+ for (let raw = 0; raw < text.length; raw++) {+ if (text[raw] === WORD_JOINER) continue;+ logical++;+ if (logical === logicalOffset) return raw + 1;+ }+ return text.length;+}++function logicalOffsetForDomPosition(+ root: HTMLElement,+ container: Node,+ offset: number,+): number {+ const probe = document.createRange();+ probe.selectNodeContents(root);+ probe.setEnd(container, offset);+ return probe.toString().replace(WORD_JOINER_RE, "").length;+}++function selectionOffsets(root: HTMLElement): LogicalRange {+ const selection = window.getSelection();+ if (selection === null || selection.rangeCount === 0) {+ const end = textFromRoot(root).length;+ return { start: end, end };+ }+ const range = selection.getRangeAt(0);+ if (+ !root.contains(range.startContainer) ||+ !root.contains(range.endContainer)+ ) {+ const end = textFromRoot(root).length;+ return { start: end, end };+ }+ return {+ start: logicalOffsetForDomPosition(+ root,+ range.startContainer,+ range.startOffset,+ ),+ end: logicalOffsetForDomPosition(root, range.endContainer, range.endOffset),+ };+}++function domPositionForLogicalOffset(+ root: HTMLElement,+ offset: number,+): { node: Node; offset: number } {+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);+ let seen = 0;+ let node = walker.nextNode();+ let lastText: Text | null = null;+ while (node !== null) {+ const text = node.textContent ?? "";+ const logicalLength = text.replace(WORD_JOINER_RE, "").length;+ if (logicalLength > 0) {+ if (offset <= seen + logicalLength) {+ return { node, offset: rawOffsetForLogicalOffset(text, offset - seen) };+ }+ lastText = node as Text;+ }+ seen += logicalLength;+ node = walker.nextNode();+ }+ if (lastText !== null) {+ return { node: lastText, offset: lastText.textContent?.length ?? 0 };+ }+ return { node: root, offset: root.childNodes.length };+}++function setSelectionRange(+ root: HTMLElement,+ start: number,+ end: number,+): void {+ const length = textFromRoot(root).length;+ const from = Math.max(0, Math.min(start, length));+ const to = Math.max(0, Math.min(end, length));+ const anchor = domPositionForLogicalOffset(root, from);+ const focus = from === to ? anchor : domPositionForLogicalOffset(root, to);+ const selection = window.getSelection();+ if (selection === null) return;+ const range = document.createRange();+ range.setStart(anchor.node, anchor.offset);+ range.setEnd(focus.node, focus.offset);+ selection.removeAllRanges();+ selection.addRange(range);+}++function replaceRange(+ text: string,+ from: number,+ to: number,+ insert: string,+): string {+ return text.slice(0, from) + insert + text.slice(to);+}++// Query-aware word boundaries: runs of identifier-ish characters and runs of+// punctuation are separate words, so Alt+Arrow stops at `level|:|ERROR`+// boundaries instead of jumping across the whole token.+function isSearchWordChar(char: string): boolean {+ // Unicode-aware: \p{L}/\p{N} cover CJK, Cyrillic, Greek, accented Latin, etc.+ // so Alt/Ctrl+Arrow and Alt+Backspace treat non-ASCII identifiers as words+ // (an ASCII-only class folded them into the punctuation bucket).+ return /[\p{L}\p{N}_-]/u.test(char);+}++function previousSearchWordBoundary(text: string, offset: number): number {+ let i = Math.max(0, Math.min(offset, text.length));+ while (i > 0 && /\s/.test(text[i - 1]!)) i--;+ if (i > 0 && isSearchWordChar(text[i - 1]!)) {+ while (i > 0 && isSearchWordChar(text[i - 1]!)) i--;+ } else {+ while (i > 0 && !/\s/.test(text[i - 1]!) && !isSearchWordChar(text[i - 1]!))+ i--;+ }+ return i;+}++function nextSearchWordBoundary(text: string, offset: number): number {+ let i = Math.max(0, Math.min(offset, text.length));+ while (i < text.length && /\s/.test(text[i]!)) i++;+ if (i < text.length && isSearchWordChar(text[i]!)) {+ while (i < text.length && isSearchWordChar(text[i]!)) i++;+ } else {+ while (+ i < text.length &&+ !/\s/.test(text[i]!) &&+ !isSearchWordChar(text[i]!)+ )+ i++;+ }+ return i;+}++function deletionRange(+ text: string,+ selection: LogicalRange,+ inputType: string,+): { from: number; to: number } | null {+ const start = Math.min(selection.start, selection.end);+ const end = Math.max(selection.start, selection.end);+ if (start !== end) return { from: start, to: end };++ switch (inputType) {+ case "deleteContentBackward":+ return { from: Math.max(0, start - 1), to: start };+ case "deleteContentForward":+ return { from: start, to: Math.min(text.length, start + 1) };+ case "deleteWordBackward":+ return { from: previousSearchWordBoundary(text, start), to: start };+ case "deleteWordForward":+ return { from: start, to: nextSearchWordBoundary(text, start) };+ case "deleteSoftLineBackward":+ case "deleteHardLineBackward":+ return { from: 0, to: start };+ case "deleteSoftLineForward":+ case "deleteHardLineForward":+ return { from: start, to: text.length };+ default:+ return null;+ }+}++/**+ * Is the click point past the rendered end of the text? Clicks there mean+ * "start a new entry", not "edit the last token" — detected AFTER the browser+ * placed the caret, never by preventing the mousedown.+ */+function isPastTextEnd(root: HTMLElement, x: number, y: number): boolean {+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);+ let lastRect: DOMRect | null = null;+ let node = walker.nextNode();+ while (node !== null) {+ const text = node.textContent ?? "";+ let lastVisible = -1;+ for (let i = 0; i < text.length; i++) {+ if (text[i] !== WORD_JOINER) lastVisible = i;+ }+ if (lastVisible >= 0) {+ const range = document.createRange();+ range.setStart(node, lastVisible);+ range.setEnd(node, lastVisible + 1);+ const rect = range.getBoundingClientRect();+ if (rect.width > 0 || rect.height > 0) lastRect = rect;+ }+ node = walker.nextNode();+ }+ if (lastRect === null) return true;+ if (y > lastRect.bottom + 2) return true;+ return y >= lastRect.top - 2 && x > lastRect.right + 2;+}++function useLatest<T>(value: T) {+ const ref = React.useRef(value);+ React.useLayoutEffect(() => {+ ref.current = value;+ });+ return ref;+}++export function SearchComposer({+ projectId,+ observed,+}: {+ projectId: string;+ /** Observed facet values for value suggestions; undefined = loading. */+ observed: ObservedOptions | undefined;+}) {+ const storeApi = useSearchBarStoreApi();+ const commitToFilterState = useSearchBarCommit();+ const { draft, valid, diagnostics, invalidRevealDraft } = useSearchBarStore(+ useShallow((s) => ({+ draft: s.draft,+ valid: s.draftValid,+ diagnostics: s.draftDiagnostics,+ invalidRevealDraft: s.invalidRevealDraft,+ })),+ );++ const [autocompleteOpen, setAutocompleteOpen] = React.useState(false);+ const [appendIntent, setAppendIntent] = React.useState(false);+ const [highlightedOptionId, setHighlightedOptionId] = React.useState<+ string | null+ >(null);+ const [hoveredTokenId, setHoveredTokenId] = React.useState<string | null>(+ null,+ );+ const [editorFocused, setEditorFocused] = React.useState(false);+ // Mirror of the native selection in logical (joiner-free) offsets.+ const [selectionSnapshot, setSelectionSnapshot] =+ React.useState<LogicalRange>({ start: 0, end: 0 });+ const rootRef = React.useRef<HTMLDivElement>(null);+ const containerRef = React.useRef<HTMLDivElement>(null);+ // Selection to restore after the next reprojection of a controlled edit.+ const pendingSelectionRef = React.useRef<LogicalRange | null>(null);++ const selectionCollapsed = selectionSnapshot.start === selectionSnapshot.end;+ const caret = selectionSnapshot.end;++ // Memoized so segment projection's one-slot cache stays warm across renders;+ // routes `scores.<name>` token validity by the same observed score type the+ // store and commit gate use.+ const scoreTypes = React.useMemo(+ () => scoreTypeContextFromObserved(observed),+ [observed],+ );++ // Read recents only while the popover is open (avoids a synchronous+ // localStorage read on every keystroke/selection render), and not in append+ // mode — a recent is a complete query, not a token to append, so showing+ // them there would let a pick silently replace the in-progress draft.+ const recents = React.useMemo(+ () =>+ autocompleteOpen && !appendIntent+ ? getRecentSearches(projectId)+ : NO_RECENTS,+ [autocompleteOpen, appendIntent, projectId],+ );++ const plan: CompletionPlan | null =+ autocompleteOpen && selectionCollapsed+ ? planInputCompletions({+ input: appendIntent ? "" : draft,+ caret: appendIntent ? 0 : Math.min(caret, draft.length),+ observed,+ recents,+ currentQueryText: draft,+ })+ : null;+ const options = flattenOptions(plan);+ // Highlight policy: Enter only picks what typing narrowed. Explicit user+ // highlights (arrows/hover) always win; otherwise only plans that completed+ // a partial token pre-highlight their best match. With nothing highlighted,+ // Enter falls through to committing the query.+ const highlightedId = options.some((o) => o.id === highlightedOptionId)+ ? highlightedOptionId+ : plan?.autoHighlight === true+ ? (options[0]?.id ?? null)+ : null;+ // Both the per-token red pill and the global border follow the same+ // "reveal on Enter/blur" rule — mid-typing and partial structured picks+ // (level:, tags:(, has:) must not flash red. The committed query is derived+ // from valid filter state and can never be invalid, so this depends only on+ // a revealed failed commit.+ const showGlobalDiagnostics = !valid && invalidRevealDraft === draft;+ const showTokenDiagnostics = showGlobalDiagnostics;+ const visibleDiagnostics = showGlobalDiagnostics ? diagnostics : [];++ const planRef = useLatest(plan);+ const highlightedRef = useLatest(highlightedId);+ const optionsRef = useLatest(options);+ const draftRef = useLatest(draft);++ // Draft undo/redo: snapshots of {text, selection} captured before each+ // controlled mutation. Single-character typing coalesces into one step.+ // The DOM is a projection, so the browser's native history is disabled+ // (beforeinput historyUndo/historyRedo) and replaced by this stack.+ const historyRef = React.useRef<{+ undo: Array<{ text: string; selection: LogicalRange }>;+ redo: Array<{ text: string; selection: LogicalRange }>;+ coalesce: "typing" | null;+ }>({ undo: [], redo: [], coalesce: null });+ const lastDraftRef = React.useRef(draft);+ // True once the user has focused/edited the bar. Until then, external draft+ // rewrites (the initial URL hydration) only move the baseline — they are NOT+ // pushed onto the undo stack, so a first Cmd+Z can't revert to the+ // pre-hydration empty draft and (via blur-commit) wipe the applied filters.+ const hasInteractedRef = React.useRef(false);++ const setDraftWithSelection = React.useCallback(+ (+ next: string,+ start: number,+ end = start,+ history: "push" | "coalesce" | "none" = "push",+ ) => {+ const bounded = (n: number) => Math.max(0, Math.min(n, next.length));+ if (history !== "none") {+ const stacks = historyRef.current;+ const continuingBurst =+ history === "coalesce" && stacks.coalesce === "typing";+ if (!continuingBurst) {+ const root = rootRef.current;+ const selection =+ root !== null && document.activeElement === root+ ? selectionOffsets(root)+ : {+ start: draftRef.current.length,+ end: draftRef.current.length,+ };+ stacks.undo.push({ text: draftRef.current, selection });+ if (stacks.undo.length > 100) stacks.undo.shift();+ }+ stacks.redo = [];+ stacks.coalesce = history === "coalesce" ? "typing" : null;+ }+ lastDraftRef.current = next;+ pendingSelectionRef.current = {+ start: bounded(start),+ end: bounded(end),+ };+ // setDraft clears any revealed invalid state as a side effect.+ storeApi.getState().actions.setDraft(next);+ },+ [draftRef, storeApi],+ );++ // External draft rewrites (saved views, sidebar edits) the user makes AFTER+ // interacting are undoable single steps too. But the pre-interaction URL+ // hydration must NOT be captured — otherwise Cmd+Z reverts to the empty+ // initial draft and the blur-commit wipes the applied filters.+ React.useEffect(() => {+ if (draft === lastDraftRef.current) return;+ if (hasInteractedRef.current) {+ const stacks = historyRef.current;+ const previous = lastDraftRef.current;+ stacks.undo.push({+ text: previous,+ selection: { start: previous.length, end: previous.length },+ });+ if (stacks.undo.length > 100) stacks.undo.shift();+ stacks.redo = [];+ stacks.coalesce = null;+ }+ lastDraftRef.current = draft;+ }, [draft]);++ const undo = React.useCallback(() => {+ const stacks = historyRef.current;+ const entry = stacks.undo.pop();+ if (entry === undefined) return;+ const root = rootRef.current;+ const selection =+ root !== null && document.activeElement === root+ ? selectionOffsets(root)+ : { start: draftRef.current.length, end: draftRef.current.length };+ stacks.redo.push({ text: draftRef.current, selection });+ stacks.coalesce = null;+ setDraftWithSelection(+ entry.text,+ entry.selection.start,+ entry.selection.end,+ "none",+ );+ }, [draftRef, setDraftWithSelection]);++ const redo = React.useCallback(() => {+ const stacks = historyRef.current;+ const entry = stacks.redo.pop();+ if (entry === undefined) return;+ const root = rootRef.current;+ const selection =+ root !== null && document.activeElement === root+ ? selectionOffsets(root)+ : { start: draftRef.current.length, end: draftRef.current.length };+ stacks.undo.push({ text: draftRef.current, selection });+ stacks.coalesce = null;+ setDraftWithSelection(+ entry.text,+ entry.selection.start,+ entry.selection.end,+ "none",+ );+ }, [draftRef, setDraftWithSelection]);++ const undoRef = useLatest(undo);+ const redoRef = useLatest(redo);++ const openAutocompleteAfterEdit = React.useCallback(() => {+ setAutocompleteOpen(true);+ setHighlightedOptionId(null);+ }, []);++ // Restore selection after a controlled mutation reprojected the DOM. Runs+ // before paint so the caret never visibly jumps. External draft changes+ // (URL nav) leave pendingSelectionRef null and the browser keeps whatever+ // selection state it had.+ React.useLayoutEffect(() => {+ const root = rootRef.current;+ const pending = pendingSelectionRef.current;+ if (root === null || pending === null) return;+ if (document.activeElement !== root) return;+ pendingSelectionRef.current = null;+ setSelectionRange(root, pending.start, pending.end);+ setSelectionSnapshot(pending);+ }, [draft]);++ // Mirror the native selection. Read-only: this effect never moves the+ // selection, it only snapshots it for completion planning and hover/focus+ // affordances.+ React.useEffect(() => {+ const onSelectionChange = () => {+ const root = rootRef.current;+ if (root === null || document.activeElement !== root) return;+ const next = selectionOffsets(root);+ setSelectionSnapshot((prev) =>+ prev.start === next.start && prev.end === next.end ? prev : next,+ );+ // Moving the caret away from the end abandons "new entry" intent.+ if (next.start !== next.end || next.end !== draftRef.current.length) {+ setAppendIntent(false);+ }+ };+ document.addEventListener("selectionchange", onSelectionChange);+ return () =>+ document.removeEventListener("selectionchange", onSelectionChange);+ }, [draftRef]);++ // Safety net for mutations that bypass beforeinput (IME composition,+ // browser quirks): re-read the DOM and reproject. Skipped mid-composition+ // so IMEs keep their composing run.+ const syncFromDom = React.useCallback(() => {+ const root = rootRef.current;+ if (root === null) return;+ const next = textFromRoot(root);+ if (next === draftRef.current) return;+ const caretNow = selectionOffsets(root).end;+ setDraftWithSelection(next, caretNow);+ openAutocompleteAfterEdit();+ }, [draftRef, openAutocompleteAfterEdit, setDraftWithSelection]);++ const applyTextInsert = React.useCallback(+ (insert: string) => {+ const root = rootRef.current;+ if (root === null) return;+ const offsets = selectionOffsets(root);+ const from = Math.min(offsets.start, offsets.end);+ const to = Math.max(offsets.start, offsets.end);+ const current = draftRef.current;+ const shouldAppend =+ appendIntent &&+ insert.length > 0 &&+ from === to &&+ from === current.length;+ const prefix =+ shouldAppend &&+ current.trim().length > 0 &&+ !/\s$/.test(current) &&+ !/^\s/.test(insert)+ ? " "+ : "";+ const next = replaceRange(current, from, to, prefix + insert);+ // Append intent is one-shot: any edit consumes it.+ setAppendIntent(false);+ // Plain single-character typing at a collapsed caret coalesces into one+ // undo step; spaces and replacements start a fresh step.+ const coalesce =+ insert.length === 1 &&+ !/\s/.test(insert) &&+ prefix === "" &&+ from === to;+ setDraftWithSelection(+ next,+ from + prefix.length + insert.length,+ undefined,+ coalesce ? "coalesce" : "push",+ );+ openAutocompleteAfterEdit();+ },+ [appendIntent, draftRef, openAutocompleteAfterEdit, setDraftWithSelection],+ );++ const applyTextDeletion = React.useCallback(+ (range: { from: number; to: number }) => {+ if (range.from === range.to) return;+ setAppendIntent(false);+ setDraftWithSelection(+ replaceRange(draftRef.current, range.from, range.to, ""),+ range.from,+ );+ openAutocompleteAfterEdit();+ },+ [draftRef, openAutocompleteAfterEdit, setDraftWithSelection],+ );++ // `beforeinput` is the single text-mutation boundary. It is deliberately+ // narrow: it intercepts mutations only, never selection or caret movement.+ React.useLayoutEffect(() => {+ const root = rootRef.current;+ if (root === null) return;+ const onBeforeInput = (event: Event) => {+ const native = event as InputEvent;+ if (native.isComposing) return;+ const type = native.inputType;++ if (type === "insertText" || type === "insertReplacementText") {+ event.preventDefault();+ // Collapse only line-breaking whitespace/tabs (the single-line surface+ // can't render them); preserve spaces inside quoted values verbatim.+ applyTextInsert((native.data ?? "").replace(/[\n\r\t]+/g, " "));+ return;+ }+ if (type === "insertParagraph" || type === "insertLineBreak") {+ event.preventDefault(); // single-line surface; Enter commits via keydown+ return;+ }+ if (type === "insertFromPaste" || type === "insertFromDrop") {+ event.preventDefault(); // paste runs through onPaste; drop is unsupported+ return;+ }+ if (type === "historyUndo" || type === "historyRedo") {+ event.preventDefault(); // the DOM is a projection; native undo would desync it+ if (type === "historyUndo") undoRef.current();+ else redoRef.current();+ return;+ }+ if (type.startsWith("delete")) {+ event.preventDefault();+ const current = draftRef.current;+ const selection = selectionOffsets(root);+ const collapsed = selection.start === selection.end;+ // Collapsed word-deletes use query-aware boundaries (same boundaries+ // as Alt+Arrow movement). Everything else trusts the browser's own+ // target range when it provides one.+ if (+ collapsed &&+ (type === "deleteWordBackward" || type === "deleteWordForward")+ ) {+ const range = deletionRange(current, selection, type);+ if (range !== null) applyTextDeletion(range);+ return;+ }+ const targets = native.getTargetRanges?.() ?? [];+ if (targets.length > 0) {+ const target = targets[0]!;+ const from = logicalOffsetForDomPosition(+ root,+ target.startContainer,+ target.startOffset,+ );+ const to = logicalOffsetForDomPosition(+ root,+ target.endContainer,+ target.endOffset,+ );+ // The browser's target range can span a zero-width WORD_JOINER (the+ // caret sits just after a token's trailing joiner — reachable with+ // ArrowRight or a click past the end). That maps to an EMPTY logical+ // range, so applying it would be a silent no-op and the delete would+ // look stuck. Fall through to the logical caret delete in that case.+ if (from !== to) {+ applyTextDeletion({+ from: Math.min(from, to),+ to: Math.max(from, to),+ });+ return;+ }+ }+ const range = deletionRange(current, selection, type);+ if (range !== null) applyTextDeletion(range);+ return;+ }+ };+ root.addEventListener("beforeinput", onBeforeInput);+ return () => root.removeEventListener("beforeinput", onBeforeInput);+ }, [applyTextDeletion, applyTextInsert, draftRef, redoRef, undoRef]);++ const commit = React.useCallback(() => {+ const root = rootRef.current;+ const actions = storeApi.getState().actions;+ // Sync any DOM-only edit (IME, browser quirk) into the store before+ // committing. Compare against the live store draft, not a render snapshot,+ // and rely on zustand's synchronous set so the commit reads the new value.+ if (root !== null) {+ const text = textFromRoot(root);+ if (text !== storeApi.getState().draft) actions.setDraft(text);+ }+ // The container validates, lowers, and writes the filter state; on failure+ // it reveals the invalid draft. A successful commit re-derives the+ // committed text and the resetTo effect canonicalizes the draft.+ const ok = commitToFilterState();+ if (ok) {+ setAppendIntent(false);+ setAutocompleteOpen(false);+ setHighlightedOptionId(null);+ // Close the undo-coalesce window at the commit boundary, mirroring undo()/+ // redo()/the external-draft sync. Otherwise a post-commit keystroke keeps+ // coalescing across the commit, so Cmd+Z jumps past the natural break.+ historyRef.current.coalesce = null;+ }+ }, [storeApi, commitToFilterState]);++ // Structured edits (autocomplete picks, chip removal) apply immediately, but+ // a pick can leave the draft mid-completion (e.g. "level:" after a field+ // pick). Commit only when valid so an intermediate invalid draft never+ // reveals the red diagnostics state — that is reserved for an explicit Enter+ // (the `commit` path above) or blur. writeDraft ran synchronously, so the+ // freshly-set draftValid is current here.+ const commitStructuredEdit = React.useCallback(() => {+ if (storeApi.getState().draftValid) commitToFilterState();+ }, [storeApi, commitToFilterState]);++ const pickOption = React.useCallback(+ (option: CompletionOption) => {+ const currentPlan = planRef.current;+ if (currentPlan === null) return;+ if (option.kind === "recent") {+ setDraftWithSelection(option.query, option.query.length);+ // A recent is a COMPLETE query the user explicitly picked, so it gets+ // the same Enter/blur reveal semantics: commit if valid, otherwise+ // reveal the red invalid state instead of silently no-op'ing (e.g. a+ // recent stored before a grammar tightening, or a since-retyped score).+ const state = storeApi.getState();+ if (state.draftValid) commitToFilterState();+ else state.actions.revealInvalid();+ setAppendIntent(false);+ setAutocompleteOpen(false);+ return;+ }++ const current = draftRef.current;+ let insert: string;+ let keepOpen: boolean;+ let replaceFrom = currentPlan.from;+ let replaceTo = currentPlan.to;+ if (option.kind === "field") {+ // Replacing the key of an existing filter: the span ends AT the colon,+ // so the insert must not bring its own.+ const colonFollows = current.slice(currentPlan.to).startsWith(":");+ insert = option.fieldId.endsWith(".")+ ? option.fieldId+ : colonFollows+ ? option.fieldId+ : `${option.fieldId}:`;+ keepOpen = true;+ // A dot-prefix field (`metadata.`/`scores.`/`traceScores.`) is itself a+ // partial key. When an existing `:value` follows the replaced key, the+ // bare prefix would splice in front of it (`meta:foo` -> broken+ // `metadata.:foo`). Consume the whole term so the user re-picks the key+ // from observed options instead.+ if (!appendIntent && option.fieldId.endsWith(".") && colonFollows) {+ replaceTo = termAt(current, currentPlan.from)?.to ?? currentPlan.to;+ }+ // Re-picking the same field that's already the last token: collapse to+ // a no-op instead of double-appending (`… level:` + pick `level` would+ // give `… level: level:`). The matched suffix must sit at a TOKEN+ // boundary (start-of-draft or after whitespace) — a bare `endsWith`+ // false-fires when the field name is a raw suffix of a longer key+ // (`metadata.level:` + pick `level`), silently discarding the pick.+ const trimmed = current.trimEnd();+ if (+ appendIntent &&+ trimmed.endsWith(insert) &&+ (trimmed.length === insert.length ||+ /\s/.test(trimmed[trimmed.length - insert.length - 1] ?? " "))+ ) {+ setDraftWithSelection(current, trimmed.length);+ setAppendIntent(false);+ setAutocompleteOpen(true);+ setHighlightedOptionId(null);+ return;+ }+ } else if (option.kind === "value") {+ insert = serializeValue(option.value);+ keepOpen = currentPlan.keepOpenOnPick ?? false;+ } else {+ insert = option.insert;+ // A scope rewrite carries its own span (the whole coalesced free-text+ // run), so it replaces that, not just the token under the caret.+ if (option.kind === "pattern" && option.replaceSpan) {+ replaceFrom = option.replaceSpan.from;+ replaceTo = option.replaceSpan.to;+ }+ // A trailing `:`, ` `, or `(` drops the caret into an interactive+ // context (value stage, next field, or an open array group like+ // `tags:(`) — keep the popover open so the next pick is immediate.+ keepOpen =+ option.insert.endsWith(":") ||+ option.insert.endsWith(" ") ||+ option.insert.endsWith("(");+ }++ // A pick that COMPLETES a filter token — a value (`name:checkout`) or a+ // ready-to-run suggestion (`level:DEFAULT`) — and sits at the END of the+ // draft advances to a fresh token: append a trailing space, drop the caret+ // AFTER it (OUTSIDE the just-completed pill), and reopen field suggestions+ // for the next filter, instead of leaving the caret inside the pill where+ // typing would edit what was just picked. Picks that invite more input (a+ // bare `field:` key, a `metadata.` prefix, an open `tags:(` group), grouped+ // value entry, and mid-query edits (non-whitespace follows) stay put. This+ // reuses the space-ending-insert path rather than the deferred appendIntent+ // that rendered the caret inside the pill with no space.+ const grouped = currentPlan.keepOpenOnPick ?? false;+ const invitesMoreInput =+ option.kind === "field" || // a `field:` key always needs a value next+ insert.endsWith(":") ||+ insert.endsWith(" ") ||+ insert.endsWith("(");+ const completesFilterAtEnd =+ !grouped &&+ !invitesMoreInput &&+ current.slice(replaceTo).trim().length === 0;+ if (completesFilterAtEnd) {+ insert += " ";+ // Consume any existing trailing whitespace so the space never doubles.+ if (!appendIntent) replaceTo = current.length;+ keepOpen = true;+ }++ const prefix =+ appendIntent && current.trim().length > 0 && !/\s$/.test(current)+ ? " "+ : "";+ const next = appendIntent+ ? `${current}${prefix}${insert}`+ : replaceRange(current, replaceFrom, replaceTo, insert);+ const caretAt = appendIntent+ ? current.length + prefix.length + insert.length+ : replaceFrom + insert.length;+ setDraftWithSelection(next, caretAt);+ setAppendIntent(false);+ setAutocompleteOpen(keepOpen);+ setHighlightedOptionId(null);+ // Apply when the pick produced a valid query; a partial draft (e.g. a+ // bare `level:` field pick) commits nothing and shows no error. A+ // dot-prefix field pick (`metadata.`, `scores.`, `traceScores.`) parses+ // as *valid free text*, so committing it would silently set searchQuery+ // to the bare prefix — defer until the user picks/types a key.+ if (!(option.kind === "field" && option.fieldId.endsWith("."))) {+ commitStructuredEdit();+ }+ },+ [+ appendIntent,+ draftRef,+ planRef,+ setDraftWithSelection,+ commitStructuredEdit,+ commitToFilterState,+ storeApi,+ ],+ );++ const removeSegment = React.useCallback(+ (segment: ComposerSegment) => {+ // removeChipSpan edits the draft; commit applies it when still valid.+ storeApi.getState().actions.removeChipSpan(segment.from, segment.to);+ commitStructuredEdit();+ setHoveredTokenId(null);+ setAppendIntent(false);+ setAutocompleteOpen(false);+ setHighlightedOptionId(null);+ },+ [storeApi, commitStructuredEdit],+ );++ const onKeyDown = (event: React.KeyboardEvent<HTMLElement>) => {+ if (event.nativeEvent.isComposing) return;++ if (+ (event.metaKey || event.ctrlKey) &&+ (event.key === "z" || event.key === "Z")+ ) {+ event.preventDefault();+ if (event.shiftKey) redo();+ else undo();+ return;+ }+ if ((event.metaKey || event.ctrlKey) && event.key === "y") {+ event.preventDefault();+ redo();+ return;+ }++ if ((event.metaKey || event.ctrlKey) && event.key === " ") {+ event.preventDefault();+ setAutocompleteOpen(true);+ return;+ }++ // Query-aware word movement: identifier runs and punctuation runs are+ // separate words. Shift extends the native selection to the same+ // boundaries so movement and selection agree.+ if (+ (event.key === "ArrowLeft" || event.key === "ArrowRight") &&+ (event.altKey || event.ctrlKey) &&+ !event.metaKey+ ) {+ const root = rootRef.current;+ if (root === null) return;+ event.preventDefault();+ const selection = window.getSelection();+ const offsets = selectionOffsets(root);+ const collapsedBase =+ event.key === "ArrowLeft"+ ? Math.min(offsets.start, offsets.end)+ : Math.max(offsets.start, offsets.end);+ // Shift extends from the selection FOCUS (the moving end), which native+ // selection tracks independently of document order.+ const focusBase =+ selection !== null &&+ selection.focusNode !== null &&+ root.contains(selection.focusNode)+ ? logicalOffsetForDomPosition(+ root,+ selection.focusNode,+ selection.focusOffset,+ )+ : collapsedBase;+ const base = event.shiftKey ? focusBase : collapsedBase;+ const target =+ event.key === "ArrowLeft"+ ? previousSearchWordBoundary(draft, base)+ : nextSearchWordBoundary(draft, base);+ if (event.shiftKey && selection !== null && selection.rangeCount > 0) {+ const position = domPositionForLogicalOffset(root, target);+ selection.extend(position.node, position.offset);+ } else {+ setSelectionRange(root, target, target);+ }+ setAppendIntent(false);+ return;+ }++ // ArrowRight at the very end of the query "exits" the last token, like+ // Space — minus the inserted space. Enter append mode (the next keystroke+ // space-prefixes into a NEW token via applyTextInsert), open the field+ // suggestions, AND move the caret PAST the pill's trailing zero-width+ // WORD_JOINER so it visibly leaves the pill: the joiner is a root-level node+ // after the pill span, so the after-joiner spot renders outside it. (The+ // old behavior pinned the caret at the logical end — inside the pill — so+ // the exit was invisible and felt like a dead keypress.) Backspace from the+ // after-joiner spot is handled by the trailing-joiner fall-through below.+ if (+ event.key === "ArrowRight" &&+ !event.shiftKey &&+ !event.altKey &&+ !event.ctrlKey &&+ !event.metaKey &&+ selectionCollapsed &&+ caret === draft.length &&+ draft.length > 0+ ) {+ event.preventDefault();+ const root = rootRef.current;+ const selection = window.getSelection();+ if (root !== null && selection !== null) {+ const range = document.createRange();+ range.selectNodeContents(root);+ range.collapse(false); // to the very end, after the trailing joiner+ selection.removeAllRanges();+ selection.addRange(range);+ }+ setAppendIntent(true);+ setAutocompleteOpen(true);+ setHighlightedOptionId(null);+ return;+ }++ // Plain Left/Right move ONE logical position, skipping the zero-width+ // WORD_JOINERs (and the redundant inter-block DOM spots they create: a pill+ // is followed by its trailing joiner AND the separating space, all sharing+ // one logical offset). Native movement stalls on those — e.g. ArrowLeft from+ // the start of a block takes two presses to actually cross into the previous+ // block. Moving by logical offset makes every press advance exactly one+ // character in both directions. (A non-collapsed selection collapses+ // natively; modifier/at-end arrows are handled above.)+ if (+ (event.key === "ArrowLeft" || event.key === "ArrowRight") &&+ !event.shiftKey &&+ !event.altKey &&+ !event.ctrlKey &&+ !event.metaKey+ ) {+ const root = rootRef.current;+ if (root === null) return;+ const { start, end } = selectionOffsets(root);+ if (start !== end) return; // let native collapse a selection+ let target =+ event.key === "ArrowLeft"+ ? Math.max(0, end - 1)+ : Math.min(draft.length, end + 1);+ // Step over a whole non-BMP character (emoji, supplementary CJK): offsets+ // count UTF-16 code units, so a ±1 step can land BETWEEN a surrogate pair.+ // Native arrow movement is grapheme-aware; restore that for the common+ // single-codepoint case so one press crosses the character.+ if (+ event.key === "ArrowLeft" &&+ target > 0 &&+ isLowSurrogate(draft.charCodeAt(target)) &&+ isHighSurrogate(draft.charCodeAt(target - 1))+ ) {+ target -= 1;+ } else if (+ event.key === "ArrowRight" &&+ target < draft.length &&+ isHighSurrogate(draft.charCodeAt(target - 1)) &&+ isLowSurrogate(draft.charCodeAt(target))+ ) {+ target += 1;+ }+ if (target === end) return; // at an edge — native no-op+ event.preventDefault();+ setSelectionRange(root, target, target);+ setAppendIntent(false);+ return;+ }++ if (event.key === "Enter") {+ event.preventDefault();+ const option = optionsRef.current.find(+ (o) => o.id === highlightedRef.current,+ );+ if (+ autocompleteOpen &&+ planRef.current !== null &&+ option !== undefined+ ) {+ pickOption(option);+ return;+ }+ commit();+ return;+ }++ if (event.key === "Escape") {+ if (autocompleteOpen) {+ event.preventDefault();+ setAppendIntent(false);+ setAutocompleteOpen(false);+ }+ return;+ }++ // Forward Tab picks the highlighted option; Shift+Tab must stay native+ // backward focus (key is "Tab" for both, so guard on shiftKey).+ if (event.key === "Tab" && !event.shiftKey) {+ const option = optionsRef.current.find(+ (o) => o.id === highlightedRef.current,+ );+ if (planRef.current !== null && option !== undefined) {+ event.preventDefault();+ pickOption(option);+ }+ return;+ }++ if (event.key === "ArrowDown" || event.key === "ArrowUp") {+ event.preventDefault();+ const ids = optionsRef.current.map((o) => o.id);+ if (!autocompleteOpen) {+ setAutocompleteOpen(true);+ return;+ }+ if (ids.length === 0) return;+ const current = highlightedRef.current;+ const idx = current === null ? -1 : ids.indexOf(current);+ const delta = event.key === "ArrowDown" ? 1 : -1;+ const next =+ idx === -1+ ? delta > 0+ ? 0+ : ids.length - 1+ : (idx + delta + ids.length) % ids.length;+ setHighlightedOptionId(ids[next]!);+ }+ };++ const onCopy = (event: React.ClipboardEvent<HTMLElement>) => {+ const root = rootRef.current;+ if (root === null) return;+ const { start, end } = selectionOffsets(root);+ if (start === end) return;+ event.preventDefault();+ event.clipboardData.setData(+ "text/plain",+ draft.slice(Math.min(start, end), Math.max(start, end)),+ );+ };++ const onCut = (event: React.ClipboardEvent<HTMLElement>) => {+ const root = rootRef.current;+ if (root === null) return;+ const { start, end } = selectionOffsets(root);+ if (start === end) return;+ event.preventDefault();+ const from = Math.min(start, end);+ const to = Math.max(start, end);+ event.clipboardData.setData("text/plain", draft.slice(from, to));+ applyTextDeletion({ from, to });+ };++ const onPaste = (event: React.ClipboardEvent<HTMLElement>) => {+ event.preventDefault();+ // Collapse only line-breaking whitespace/tabs (single-line surface);+ // preserve spaces inside quoted values (e.g. pasting `name:"a b"`).+ const clean = event.clipboardData+ .getData("text/plain")+ .replace(/[\n\r\t]+/g, " ");+ applyTextInsert(clean);+ };++ const onFocus = () => {+ setEditorFocused(true);+ hasInteractedRef.current = true;+ // A draft was set while the editor was blurred (an external structured+ // edit): the restore effect could not run then, so consume the pending+ // selection now that focus arrived.+ const root = rootRef.current;+ const pending = pendingSelectionRef.current;+ if (root !== null && pending !== null) {+ pendingSelectionRef.current = null;+ setSelectionRange(root, pending.start, pending.end);+ setSelectionSnapshot(pending);+ }+ setAutocompleteOpen(true);+ };++ const onBlur = () => {+ setEditorFocused(false);+ commit();+ setAppendIntent(false);+ setAutocompleteOpen(false);+ };++ // Click handling happens AFTER the browser placed the caret (click, not+ // mousedown), so native click/drag/double-click selection is untouched.+ // A collapsed click opens caret-contextual suggestions; a click past the+ // end of the text means "start a new entry".+ const onRootClick = (event: React.MouseEvent<HTMLElement>) => {+ if (event.target instanceof Element && event.target.closest("button"))+ return;+ const root = rootRef.current;+ if (root === null) return;+ const { start, end } = selectionOffsets(root);+ if (start !== end) return; // drag selection — selection is for editing, not suggesting+ const append =+ draft.length > 0 && isPastTextEnd(root, event.clientX, event.clientY);+ if (append && end !== draft.length) {+ // The browser put the caret on the nearest character of a wrapped line;+ // a past-end click still means append at the very end.+ setSelectionRange(root, draft.length, draft.length);+ setSelectionSnapshot({ start: draft.length, end: draft.length });+ }+ if (!append && end < draft.length && /\s/.test(draft[end] ?? "")) {+ // Additive gap affordance: a click in the whitespace BETWEEN tokens+ // (geometrically past the previous token's right edge, not on the token+ // or its padding) nudges the collapsed caret across the whitespace run,+ // so typing starts the next entry instead of gluing to the previous+ // token. Clicks on token text keep their native caret untouched.+ const segment = deriveComposerSegments(draft, scoreTypes).find(+ (s) => s.to === end,+ );+ const el =+ segment !== undefined+ ? root.querySelector(`[data-segment-id="${CSS.escape(segment.id)}"]`)+ : null;+ const rects = el?.getClientRects();+ const rect =+ rects !== undefined && rects.length > 0+ ? rects[rects.length - 1]!+ : null;+ if (+ rect !== null &&+ event.clientY >= rect.top - 2 &&+ event.clientY <= rect.bottom + 2 &&+ event.clientX > rect.right + 1+ ) {+ let next = end;+ while (next < draft.length && /\s/.test(draft[next]!)) next++;+ setSelectionRange(root, next, next);+ setSelectionSnapshot({ start: next, end: next });+ }+ }+ setAppendIntent(append);+ setAutocompleteOpen(true);+ setHighlightedOptionId(null);+ };++ const onRootMouseOver = (event: React.MouseEvent<HTMLElement>) => {+ const target = event.target instanceof Element ? event.target : null;+ if (target?.closest("[data-overlay-remove]")) return; // keep the X alive under the pointer+ const token = target?.closest("[data-segment-id]");+ setHoveredTokenId(token?.getAttribute("data-segment-id") ?? null);+ };++ const describedBy =+ visibleDiagnostics.length > 0 ? "search-bar-diagnostics" : undefined;++ const segments = deriveComposerSegments(draft, scoreTypes);+ // The remove affordance targets the hovered token, or — while the editor is+ // focused — the token holding a collapsed caret. Not at the trailing+ // insertion point, where the user is appending, not editing.+ const focusTokenId =+ editorFocused && selectionCollapsed && caret < draft.length+ ? (segments.find((s) => s.editable && s.from <= caret && caret <= s.to)+ ?.id ?? null)+ : null;+ const removeTargetId = hoveredTokenId ?? focusTokenId;+ const removeTarget =+ segments.find((s) => s.editable && s.id === removeTargetId) ?? null;+ // The hovered/caret token's diagnostic, shown as a styled per-token tooltip+ // once diagnostics are revealed — replaces the native title.+ // Shown even while the suggestions popover is open (you still need to see why+ // the block is red); the tooltip flips ABOVE the block then, so it doesn't+ // collide with the popover that drops BELOW the bar (see the render below).+ const errorTarget =+ showTokenDiagnostics && removeTarget?.kind === "invalid"+ ? removeTarget+ : null;++ // Measure the remove target's last client rect in the parent's layout+ // effect: it runs after every commit that can move text, and after all+ // subtree refs (root + container) are attached.+ const [removePosition, setRemovePosition] = React.useState<{+ left: number;+ top: number;+ } | null>(null);+ // Anchors for the per-token error tooltip — left edge of the token, plus its+ // bottom (default placement, just under the block) and top (used to flip the+ // tooltip ABOVE the block while the suggestions popover is open below).+ const [errorPosition, setErrorPosition] = React.useState<{+ left: number;+ top: number;+ aboveTop: number;+ } | null>(null);+ const removeTargetIdActual = removeTarget?.id ?? null;+ const measureRemovePosition = React.useCallback(() => {+ const root = rootRef.current;+ const container = containerRef.current;+ if (root === null || container === null || removeTargetIdActual === null) {+ setRemovePosition(null);+ setErrorPosition(null);+ return;+ }+ const el = root.querySelector(+ `[data-segment-id="${CSS.escape(removeTargetIdActual)}"]`,+ );+ if (el === null) {+ setRemovePosition(null);+ setErrorPosition(null);+ return;+ }+ const rects = el.getClientRects();+ const rect =+ rects.length > 0 ? rects[rects.length - 1]! : el.getBoundingClientRect();+ const firstRect = rects.length > 0 ? rects[0]! : rect;+ const containerRect = container.getBoundingClientRect();+ setRemovePosition({+ left: rect.right - containerRect.left - 6,+ top: rect.top - containerRect.top - 8,+ });+ setErrorPosition({+ left: firstRect.left - containerRect.left,+ top: firstRect.bottom - containerRect.top + 6,+ aboveTop: firstRect.top - containerRect.top,+ });+ }, [removeTargetIdActual]);++ // Re-measure when the target or draft text changes.+ React.useLayoutEffect(() => {+ measureRemovePosition();+ }, [measureRemovePosition, draft]);++ // Those deps miss layout reflows that don't change React state — window+ // resize, browser zoom, sidebar collapse — which re-wrap the full-width bar+ // and move the token. Observe the composer surface so the absolutely-+ // positioned X re-anchors to its token instead of leaving a stale ghost X.+ React.useEffect(() => {+ if (removeTargetIdActual === null) return;+ const container = containerRef.current;+ if (container === null || typeof ResizeObserver === "undefined") return;+ const observer = new ResizeObserver(() => measureRemovePosition());+ observer.observe(container);+ return () => observer.disconnect();+ }, [measureRemovePosition, removeTargetIdActual]);++ return (+ <div+ ref={containerRef}+ data-testid="search-bar"+ role="search"+ className="relative w-full"+ >+ <div+ data-testid="search-bar-surface"+ data-composer-text={draft}+ onMouseLeave={() => setHoveredTokenId(null)}+ className={cn(+ // Prominent primary control. Block (not flex) so inline pills never+ // break across a wrap. Balanced padding: a small, even gutter on all+ // sides (the left no longer dwarfs the inter-pill gap and top), py+ // centers a single line near min-h-9 and the box grows when wrapped.+ // pr-8 keeps the top-right error icon clear of the last token.+ "border-input bg-background relative min-h-9 rounded-md border px-2 py-1.5 pr-8",+ "focus-within:ring-ring focus-within:ring-1",+ showGlobalDiagnostics &&+ "border-destructive focus-within:ring-destructive/40",+ )}+ >+ {draft.length === 0 && (+ <div className="text-muted-foreground pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 truncate pr-8 font-mono text-xs">+ {COMPOSER_PLACEHOLDER}+ </div>+ )}+ <div+ ref={rootRef}+ role="combobox"+ aria-label="Search"+ aria-expanded={plan !== null}+ aria-controls={plan !== null ? LISTBOX_ID : undefined}+ aria-autocomplete="list"+ aria-activedescendant={+ plan !== null && highlightedId !== null+ ? optionDomId(LISTBOX_ID, highlightedId)+ : undefined+ }+ aria-describedby={describedBy}+ contentEditable+ suppressContentEditableWarning+ // The query is code-like grammar, not prose: suppress every mobile-+ // keyboard mutation, not just the spellcheck squiggle. Without these,+ // iOS/Android default autocorrect + sentence-capitalization can+ // rewrite a partial token (`tps` → something) before commit.+ spellCheck={false}+ autoCorrect="off"+ autoCapitalize="none"+ inputMode="text"+ data-testid="search-bar-input"+ className="min-h-6 font-mono text-xs leading-7 break-words whitespace-pre-wrap caret-[hsl(var(--foreground))] outline-none"+ onInput={(event) => {+ if (!(event.nativeEvent as InputEvent).isComposing) syncFromDom();+ }}+ onCompositionEnd={syncFromDom}+ // Disable drag-and-drop: an intra-bar drag fires deleteByDrag (which+ // the delete branch applies) without a matching insert, silently+ // dropping the dragged text. Drop is unsupported anyway; selection+ // and copy/cut/paste stay fully functional.+ onDragStart={(e) => e.preventDefault()}+ onKeyDown={onKeyDown}+ onCopy={onCopy}+ onCut={onCut}+ onPaste={onPaste}+ onFocus={onFocus}+ onBlur={onBlur}+ onClick={onRootClick}+ onMouseOver={onRootMouseOver}+ >+ <ComposerTokens+ draft={draft}+ showDiagnostics={showTokenDiagnostics}+ scoreTypes={scoreTypes}+ />+ </div>+ {/* Bar-local overlay stacking ladder (hardcoded for now — a proper+ app-wide layer system is a separate ticket): token text (base) <+ remove-X (z-20) < error tooltip (z-30) < autocomplete popover+ (z-50). The popover drops BELOW the bar; when it's open the error+ tooltip flips ABOVE the offending block (see errorAbove), so the two+ never overlap and the z order only needs to be self-consistent. */}+ {removeTarget !== null && removePosition !== null && (+ <RemoveTokenButton+ segment={removeTarget}+ position={removePosition}+ onRemove={removeSegment}+ />+ )}+ {errorTarget !== null && errorPosition !== null && (+ <div+ role="tooltip"+ style={+ plan !== null+ ? {+ left: errorPosition.left,+ top: errorPosition.aboveTop,+ transform: "translateY(calc(-100% - 6px))",+ }+ : { left: errorPosition.left, top: errorPosition.top }+ }+ // pointer-events-none so moving onto the tooltip doesn't change the+ // hovered token (which would make it flicker away).+ className={cn(+ "pointer-events-none absolute z-30 max-w-[min(360px,calc(100vw-32px))]",+ "border-destructive/40 bg-popover text-destructive rounded-md border",+ "px-2 py-1 font-sans text-xs leading-snug shadow-md",+ )}+ >+ {errorTarget.message}+ </div>+ )}+ </div>++ {showGlobalDiagnostics && (+ <div className="absolute top-1.5 right-2 flex items-center gap-1">+ <span+ className="text-destructive"+ title={visibleDiagnostics.map((d) => d.message).join("; ")}+ aria-label="invalid query"+ >+ <AlertCircle className="h-4 w-4" />+ </span>+ </div>+ )}++ {visibleDiagnostics.length > 0 && (+ <div id="search-bar-diagnostics" className="sr-only">+ {visibleDiagnostics.map((d) => d.message).join("; ")}+ </div>+ )}++ {plan !== null && (+ <AutocompletePopover+ plan={plan}+ highlightedId={highlightedId}+ onPick={pickOption}+ onHighlight={setHighlightedOptionId}+ listboxId={LISTBOX_ID}+ anchorLeft={0}+ containerRef={containerRef}+ />+ )}+ </div>+ );+}++/**+ * Remove control rendered OUTSIDE the contenteditable text flow: it is an+ * absolutely positioned sibling anchored to the token's measured pixels, so+ * hover/remove can never reflow text, join a selection range, or trap the+ * caret.+ */+function RemoveTokenButton({+ segment,+ position,+ onRemove,+}: {+ segment: ComposerSegment;+ position: { left: number; top: number };+ onRemove: (segment: ComposerSegment) => void;+}) {+ return (+ <button+ type="button"+ data-overlay-remove+ aria-label={`Remove ${segment.raw}`}+ title={`Remove ${segment.raw}`}+ style={{ left: position.left, top: position.top }}+ className={cn(+ "absolute z-20 inline-flex h-4 w-4 items-center justify-center rounded-sm",+ "border-border bg-background text-muted-foreground border shadow-sm",+ "hover:bg-accent hover:text-foreground focus:ring-ring focus:ring-1 focus:outline-none",+ )}+ onMouseDown={(event) => event.preventDefault()}+ onClick={(event) => {+ event.stopPropagation();+ onRemove(segment);+ }}+ >+ <X className="h-3 w-3" aria-hidden="true" />+ </button>+ );+}diff --git a/web/src/features/search-bar/components/presentation.clienttest.ts b/web/src/features/search-bar/components/presentation.clienttest.tsnew file mode 100644index 0000000000..265f4f34fa--- /dev/null+++ b/web/src/features/search-bar/components/presentation.clienttest.ts@@ -0,0 +1,24 @@+import { optionDomId } from "./presentation";++describe("optionDomId", () => {+ it("produces a whitespace-free id for values that contain spaces", () => {+ // Value option ids embed the observed value (`value:My Test Trace`); an id+ // with whitespace is invalid HTML and breaks aria-activedescendant.+ const id = optionDomId("search-bar-listbox", "value:My Test Trace");+ expect(/\s/.test(id)).toBe(false);+ });++ it("keeps simple ids stable (percent-encoded, whitespace-free)", () => {+ expect(optionDomId("lb", "field:level")).toBe("lb-opt-field%3Alevel");+ });++ it("maps space-vs-underscore values to DISTINCT ids", () => {+ // `My Test` and `My_Test` are different observed values; a `\s+ → _`+ // collapse aliased them to one duplicate DOM id, breaking aria-+ // activedescendant. encodeURIComponent is injective, so they stay distinct.+ expect(optionDomId("lb", "value:My Test")).not.toBe(+ optionDomId("lb", "value:My_Test"),+ );+ expect(/\s/.test(optionDomId("lb", "value:My Test"))).toBe(false);+ });+});diff --git a/web/src/features/search-bar/components/presentation.ts b/web/src/features/search-bar/components/presentation.tsnew file mode 100644index 0000000000..9540e81a16--- /dev/null+++ b/web/src/features/search-bar/components/presentation.ts@@ -0,0 +1,18 @@+// Pure presentational constants + helpers shared by the live composer and+// the autocomplete popover. A separate module (not a component file) so the+// component files keep Fast Refresh eligibility.++// Page-neutral: the bar mounts on both the Observations and Traces tables.+export const COMPOSER_PLACEHOLDER =+ "Search — e.g. level:ERROR, -env:dev, latency:>2, scores.accuracy:>0.8";++/** DOM id for an option row — referenced by aria-activedescendant. Option ids+ * embed observed values (`value:My Test Trace`) and recent queries, which can+ * contain whitespace; an id with whitespace is invalid HTML and breaks the+ * aria-activedescendant IDREF. encodeURIComponent escapes whitespace (→ `%20`)+ * while leaving underscore literal, so it is injective — distinct option ids+ * always map to distinct DOM ids (a `\s+ → _` collapse would alias+ * `My Test`/`My_Test` to the same duplicate id). */+export function optionDomId(listboxId: string, optionId: string): string {+ return `${listboxId}-opt-${encodeURIComponent(optionId)}`;+}diff --git a/web/src/features/search-bar/hooks/useEventsSearchBar.ts b/web/src/features/search-bar/hooks/useEventsSearchBar.tsnew file mode 100644index 0000000000..0b46171279--- /dev/null+++ b/web/src/features/search-bar/hooks/useEventsSearchBar.ts@@ -0,0 +1,156 @@+// Container hook: wires the draft-only search-bar store to the table's filter+// state with a single, one-way data direction.+//+// URL filter state (FilterState + searchQuery/searchType) ← single source+// │ filterStateToQueryText (pure, derived)+// ▼+// committedText ──resetTo──▶ store.draft ──(edit)──▶ draft+// ▲ │ 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.++import { useCallback, useEffect, useMemo, useRef, useState } from "react";++import type { FilterState, TracingSearchType } 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 {+ type ObservedOptions,+ scoreTypeContextFromObserved,+} from "@/src/features/search-bar/lib/observed-options";+import { recordRecentSearch } from "@/src/features/search-bar/lib/recent-searches";+import {+ createSearchBarStore,+ type SearchBarStore,+} from "@/src/features/search-bar/store/searchBarStore";++/** Order-independent scope-set equality (scopes are unique). */+function sameScopes(a: TracingSearchType[], b: TracingSearchType[]): boolean {+ if (a.length !== b.length) return false;+ const bs = new Set(b);+ return a.every((s) => bs.has(s));+}++/** Column + key identity, so keyed filters (metadata.<k>, scores.<k>) on the+ * same column don't collide while plain columns dedupe by column alone. */+function filterIdentity(f: FilterState[number]): string {+ return `${f.column}\u0000${"key" in f ? f.key : ""}`;+}++export function useEventsSearchBar({+ projectId,+ enabled,+ filterState,+ searchQuery,+ searchType,+ observed,+ setFilterState,+ setSearchQuery,+ setSearchType,+}: {+ projectId: string;+ enabled: boolean;+ /** The user's explicit facet filters (sidebar `explicitFilterState`). */+ filterState: FilterState;+ searchQuery: string | null;+ searchType: TracingSearchType[];+ /** Observed filter options — used to route `scores.<name>` by score type. */+ observed: ObservedOptions | undefined;+ setFilterState: (filters: FilterState) => void;+ setSearchQuery: (query: string | null) => void;+ setSearchType: (type: TracingSearchType[]) => void;+}): { store: SearchBarStore; commit: () => boolean } {+ // Latest observed options, read inside commit and by the store's draft+ // validation so both route `scores.<name>` by the same observed score type.+ const observedRef = useRef(observed);+ observedRef.current = observed;++ const [store] = useState(() =>+ createSearchBarStore(() =>+ scoreTypeContextFromObserved(observedRef.current),+ ),+ );++ // 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.+ const derived = useMemo(+ () => filterStateToQueryText(filterState, { searchQuery, searchType }),+ [filterState, searchQuery, searchType],+ );+ const committedText = derived.text;+ const skippedFiltersRef = useRef(derived.skippedFilters);+ skippedFiltersRef.current = derived.skippedFilters;++ // The one external→local sync: seed the draft whenever the committed+ // baseline changes (a commit echo, a sidebar edit, a saved view, or+ // navigation). resetTo is a no-op when the draft already matches, so a+ // commit's own echo settles immediately without clobbering the caret.+ useEffect(() => {+ if (!enabled) return;+ store.getState().actions.resetTo(committedText);+ }, [enabled, committedText, store]);++ // Re-validate when observed options load: a draft typed before score types+ // were known has a stale draftValid (the editor's red-border gate reads it),+ // so without this a `scores.<numeric>:<non-number>` typed during the load+ // window would commit-reject with no visible error. `observed` identity is+ // NOT stable across refetches (a relative range + auto-refresh rebuilds it+ // every tick), so this can fire on ticks where the score types are unchanged+ // — revalidate() bails on a set-equal context, keeping that path a no-op.+ useEffect(() => {+ if (!enabled) return;+ store.getState().actions.revalidate();+ }, [enabled, observed, store]);++ // Latest applied-state setters, read inside commit without rebuilding it.+ const applyRef = useRef({ setFilterState, setSearchQuery, setSearchType });+ applyRef.current = { setFilterState, setSearchQuery, setSearchType };++ // Latest searchType, so commit can skip writing an unchanged value.+ const searchTypeRef = useRef(searchType);+ searchTypeRef.current = searchType;++ const commit = useCallback((): boolean => {+ const result = planCommit(+ store.getState().draft,+ scoreTypeContextFromObserved(observedRef.current),+ );+ if (result.status === "invalid") {+ store.getState().actions.revealInvalid();+ return false;+ }+ const { setFilterState, setSearchQuery, setSearchType } = applyRef.current;+ // Re-attach the filters the grammar can't represent so the commit never+ // drops them (no-silent-drop contract) — but drop any skipped filter whose+ // (column, key) the bar just produced, so an explicit bar edit replaces it+ // instead of duplicating the column in URL state.+ const producedKeys = new Set(result.filters.map((f) => filterIdentity(f)));+ const preserved = skippedFiltersRef.current.filter(+ (f) => !producedKeys.has(filterIdentity(f)),+ );+ setFilterState(+ preserved.length > 0 ? [...result.filters, ...preserved] : result.filters,+ );+ setSearchQuery(result.searchQuery);+ // Only write searchType when it actually changed. planCommit coerces a+ // draft with no scope token to the default (`["id","content"]` — ids+names+ // +input+output); the bar's default deliberately differs from the legacy+ // toolbar's `["id"]`, so it IS written to the URL (that's how the content+ // lane persists). The guard just avoids a redundant rewrite when unchanged.+ if (!sameScopes(result.searchType, searchTypeRef.current)) {+ setSearchType(result.searchType);+ }+ if (result.canonical.length > 0) {+ recordRecentSearch(projectId, result.canonical);+ }+ return true;+ }, [store, projectId]);++ return { store, commit };+}diff --git a/web/src/features/search-bar/hooks/useSearchBarEnabled.ts b/web/src/features/search-bar/hooks/useSearchBarEnabled.tsnew file mode 100644index 0000000000..a24b14a21f--- /dev/null+++ b/web/src/features/search-bar/hooks/useSearchBarEnabled.ts@@ -0,0 +1,13 @@+import { useSession } from "next-auth/react";++/**+ * Whether the current user has opted into the grammar search bar via the+ * Feature Preview menu (sidebar user dropdown → Feature Preview → "Filter+ * Search Bar"). Per-user, stored on `user.featureFlags` (no project metadata,+ * no admin RBAC). The bar still only renders on the v4 events tables, so call+ * sites gate on `isBetaEnabled && useSearchBarEnabled()`.+ */+export function useSearchBarEnabled(): boolean {+ const session = useSession();+ return session.data?.user?.featureFlags.searchBar === true;+}diff --git a/web/src/features/search-bar/lib/adapter.clienttest.ts b/web/src/features/search-bar/lib/adapter.clienttest.tsnew file mode 100644index 0000000000..b2bc2ed177--- /dev/null+++ b/web/src/features/search-bar/lib/adapter.clienttest.ts@@ -0,0 +1,853 @@+import { astToFilterState } from "@/src/features/search-bar/lib/adapter";+import { filterStateToQueryText } from "@/src/features/search-bar/lib/filter-state-to-query";+import { parse } from "@/src/features/search-bar/lib/langQ";+import { validateQuery } from "@/src/features/search-bar/lib/validate";+import type { FilterState } from "@langfuse/shared";++function lower(text: string) {+ return astToFilterState(parse(text).ast);+}++describe("astToFilterState", () => {+ it("lowers a flat AND chain of facets plus free text", () => {+ const r = lower("timeout level:ERROR env:prod");+ expect(r.errors).toEqual([]);+ expect(r.searchQuery).toBe("timeout");+ expect(r.filters).toEqual([+ {+ type: "stringOptions",+ column: "level",+ operator: "any of",+ value: ["ERROR"],+ },+ {+ type: "stringOptions",+ column: "environment",+ operator: "any of",+ value: ["prod"],+ },+ ]);+ });++ it("lowers grouped values to any-of and negation to none-of", () => {+ expect(lower("level:(ERROR OR WARNING)").filters).toEqual([+ {+ type: "stringOptions",+ column: "level",+ operator: "any of",+ value: ["ERROR", "WARNING"],+ },+ ]);+ expect(lower("-env:(dev OR staging)").filters).toEqual([+ {+ type: "stringOptions",+ column: "environment",+ operator: "none of",+ value: ["dev", "staging"],+ },+ ]);+ });++ it("collapses top-level same-field OR chains into one any-of filter", () => {+ const r = lower("level:ERROR OR level:WARNING");+ expect(r.errors).toEqual([]);+ expect(r.filters).toEqual([+ {+ type: "stringOptions",+ column: "level",+ operator: "any of",+ value: ["ERROR", "WARNING"],+ },+ ]);+ });++ it("rejects cross-field OR", () => {+ const r = lower("level:ERROR OR env:dev");+ expect(r.errors.length).toBeGreaterThan(0);+ expect(r.filters).toEqual([]);+ });++ it("lowers comparisons and inverts them under negation", () => {+ expect(lower("latency:>2").filters).toEqual([+ { type: "number", column: "latency", operator: ">", value: 2 },+ ]);+ expect(lower("NOT latency:>2").filters).toEqual([+ { type: "number", column: "latency", operator: "<=", value: 2 },+ ]);+ });++ it("rejects negated numeric equality (would need an OR group)", () => {+ const r = lower("-latency:2");+ expect(r.errors.length).toBeGreaterThan(0);+ });++ it("lowers textSearch equality to contains; := to exact", () => {+ expect(lower("statusMessage:rate").filters).toEqual([+ {+ type: "string",+ column: "statusMessage",+ operator: "contains",+ value: "rate",+ },+ ]);+ expect(lower("statusMessage:=rate").filters).toEqual([+ { type: "string", column: "statusMessage", operator: "=", value: "rate" },+ ]);+ expect(lower("-statusMessage:*rate*").filters).toEqual([+ {+ type: "string",+ column: "statusMessage",+ operator: "does not contain",+ value: "rate",+ },+ ]);+ });++ it("lowers positional `*` globs to string match operators", () => {+ expect(lower("input:How*").filters).toEqual([+ {+ type: "string",+ column: "input",+ operator: "starts with",+ value: "How",+ },+ ]);+ expect(lower("output:*done").filters).toEqual([+ {+ type: "string",+ column: "output",+ operator: "ends with",+ value: "done",+ },+ ]);+ expect(lower('input:*"refund policy"*').filters).toEqual([+ {+ type: "string",+ column: "input",+ operator: "contains",+ value: "refund policy",+ },+ ]);+ });++ it("lowers array fields with any-of, none-of, and all-of", () => {+ expect(lower("tags:(a OR b)").filters).toEqual([+ {+ type: "arrayOptions",+ column: "traceTags",+ operator: "any of",+ value: ["a", "b"],+ },+ ]);+ expect(lower("-tags:a").filters).toEqual([+ {+ type: "arrayOptions",+ column: "traceTags",+ operator: "none of",+ value: ["a"],+ },+ ]);+ expect(lower("tags:(a AND b)").filters).toEqual([+ {+ type: "arrayOptions",+ column: "traceTags",+ operator: "all of",+ value: ["a", "b"],+ },+ ]);+ });++ it("lowers datetime comparisons to Date values", () => {+ const r = lower("startTime:>2026-06-01");+ expect(r.errors).toEqual([]);+ expect(r.filters).toHaveLength(1);+ const f = r.filters[0]!;+ expect(f.type).toBe("datetime");+ expect(f.operator).toBe(">");+ expect((f as { value: Date }).value instanceof Date).toBe(true);+ });++ it("lowers booleans and inverts the value under negation", () => {+ expect(lower("isRootObservation:true").filters).toEqual([+ {+ type: "boolean",+ column: "isRootObservation",+ operator: "=",+ value: true,+ },+ ]);+ expect(lower("-isRootObservation:true").filters).toEqual([+ {+ type: "boolean",+ column: "isRootObservation",+ operator: "=",+ value: false,+ },+ ]);+ });++ it("lowers metadata paths to stringObject filters", () => {+ expect(lower("metadata.region:eu").filters).toEqual([+ {+ type: "stringObject",+ column: "metadata",+ key: "region",+ operator: "=",+ value: "eu",+ },+ ]);+ expect(lower("-metadata.region:*eu*").filters).toEqual([+ {+ type: "stringObject",+ column: "metadata",+ key: "region",+ operator: "does not contain",+ value: "eu",+ },+ ]);+ expect(lower("metadata.region:>5").errors.length).toBeGreaterThan(0);+ expect(lower("-metadata.region:eu").errors.length).toBeGreaterThan(0);+ });++ it("lowers score paths to numeric or categorical columns", () => {+ expect(lower("scores.accuracy:>0.8").filters).toEqual([+ {+ type: "numberObject",+ column: "scores_avg",+ key: "accuracy",+ operator: ">",+ value: 0.8,+ },+ ]);+ expect(lower("scores.accuracy:0.5").filters).toEqual([+ {+ type: "numberObject",+ column: "scores_avg",+ key: "accuracy",+ operator: "=",+ value: 0.5,+ },+ ]);+ expect(lower("scores.feedback:positive").filters).toEqual([+ {+ type: "categoryOptions",+ column: "score_categories",+ key: "feedback",+ operator: "any of",+ value: ["positive"],+ },+ ]);+ expect(lower("-traceScores.feedback:(bad OR worse)").filters).toEqual([+ {+ type: "categoryOptions",+ column: "trace_score_categories",+ key: "feedback",+ operator: "none of",+ value: ["bad", "worse"],+ },+ ]);+ });++ it("routes numeric-looking values by observed score TYPE, not value syntax", () => {+ // `rating` is a categorical score whose labels happen to be numeric (1-5).+ // Without the score-type map the value-syntax heuristic wrongly picks the+ // numeric column; with it, the categorical column is targeted.+ const scoreTypes = {+ numericScoreNames: new Set<string>(["accuracy"]),+ categoricalScoreNames: new Set<string>(["rating"]),+ traceNumericScoreNames: new Set<string>(),+ traceCategoricalScoreNames: new Set<string>(["nps"]),+ };+ const lowerWith = (text: string) =>+ astToFilterState(parse(text).ast, scoreTypes);++ expect(lowerWith("scores.rating:5").filters).toEqual([+ {+ type: "categoryOptions",+ column: "score_categories",+ key: "rating",+ operator: "any of",+ value: ["5"],+ },+ ]);+ // A known-numeric score still lowers numeric.+ expect(lowerWith("scores.accuracy:0.5").filters).toEqual([+ {+ type: "numberObject",+ column: "scores_avg",+ key: "accuracy",+ operator: "=",+ value: 0.5,+ },+ ]);+ // Trace-level categorical with a numeric label.+ expect(lowerWith("traceScores.nps:9").filters).toEqual([+ {+ type: "categoryOptions",+ column: "trace_score_categories",+ key: "nps",+ operator: "any of",+ value: ["9"],+ },+ ]);+ // Unknown score (not observed) falls back to the value-syntax heuristic.+ expect(lowerWith("scores.unseen:5").filters).toEqual([+ {+ type: "numberObject",+ column: "scores_avg",+ key: "unseen",+ operator: "=",+ value: 5,+ },+ ]);+ });++ it("treats := (exact) on a categorical score as a category match", () => {+ // `:=positive` must behave like the bare `:positive` (any-of category),+ // not be rejected as a comparison.+ const scoreTypes = {+ numericScoreNames: new Set<string>(),+ categoricalScoreNames: new Set<string>(["feedback"]),+ traceNumericScoreNames: new Set<string>(),+ traceCategoricalScoreNames: new Set<string>(),+ };+ const r = astToFilterState(+ parse("scores.feedback:=positive").ast,+ scoreTypes,+ );+ expect(r.errors).toEqual([]);+ expect(r.filters).toEqual([+ {+ type: "categoryOptions",+ column: "score_categories",+ key: "feedback",+ operator: "any of",+ value: ["positive"],+ },+ ]);+ });++ it("rejects a comparison operator on a categorical score", () => {+ // `feedback` is categorical → `scores.feedback:>0.8` would otherwise route+ // to the numeric column (no data) and return an empty table with no error.+ const scoreTypes = {+ numericScoreNames: new Set<string>(),+ categoricalScoreNames: new Set<string>(["feedback"]),+ traceNumericScoreNames: new Set<string>(),+ traceCategoricalScoreNames: new Set<string>(),+ };+ const r = astToFilterState(parse("scores.feedback:>0.8").ast, scoreTypes);+ expect(r.errors.length).toBeGreaterThan(0);+ });++ it("rejects empty/whitespace numeric values instead of coercing to 0", () => {+ // Number("") and Number(" ") are both 0 (finite), so without an explicit+ // guard `latency:""` would silently filter for latency = 0.+ expect(lower('latency:""').errors.length).toBeGreaterThan(0);+ expect(lower('latency:" "').errors.length).toBeGreaterThan(0);+ });++ it("lowers has:/-has: to null filters", () => {+ expect(lower("has:endTime").filters).toEqual([+ { type: "null", column: "endTime", operator: "is not null", value: "" },+ ]);+ expect(lower("-has:userId").filters).toEqual([+ { type: "null", column: "userId", operator: "is null", value: "" },+ ]);+ expect(lower("has:(endTime OR userId)").errors.length).toBeGreaterThan(0);+ });++ it("lowers bare free text to searchQuery with the default scope", () => {+ // The bar emits no scope token; searchType is null and the caller applies+ // the default (ids+names+input+output). Multiple bare words are one phrase.+ const r = lower("refund policy");+ expect(r.errors).toEqual([]);+ expect(r.searchType).toBeNull();+ expect(r.searchQuery).toBe("refund policy");+ expect(r.filters).toEqual([]);+ });++ it("lowers id:/name: to contains string filters (not exact any-of)", () => {+ // id/name are textSearch now: bare `key:value` is a substring search.+ for (const column of ["id", "name"]) {+ const r = lower(`${column}:chat`);+ expect(r.errors).toEqual([]);+ expect(r.filters).toEqual([+ { type: "string", column, operator: "contains", value: "chat" },+ ]);+ }+ // `key:=value` is the explicit exact match.+ expect(lower("name:=checkout").filters).toEqual([+ { type: "string", column: "name", operator: "=", value: "checkout" },+ ]);+ // Negation is does-not-contain (flat-representable).+ expect(lower("-id:abc").filters).toEqual([+ {+ type: "string",+ column: "id",+ operator: "does not contain",+ value: "abc",+ },+ ]);+ });++ it("lowers input:/output: to real column filters (not searchType)", () => {+ const r = lower("input:refund");+ expect(r.errors).toEqual([]);+ expect(r.searchType).toBeNull();+ expect(r.filters).toEqual([+ {+ type: "string",+ column: "input",+ operator: "contains",+ value: "refund",+ },+ ]);+ });++ it("flattens parenthesized AND groups like the top-level chain", () => {+ const r = lower("(env:dev timeout)");+ expect(r.errors).toEqual([]);+ expect(r.searchQuery).toBe("timeout");+ expect(r.filters).toHaveLength(1);+ });++ it("errors instead of silently dropping unrepresentable nodes", () => {+ const cases = [+ "NOT (level:ERROR env:dev)",+ "level:ERROR OR env:dev",+ "latency:(1 OR 2)",+ "metadata.a:(x OR y)",+ "-tags:(a AND b)",+ ];+ for (const text of cases) {+ const r = lower(text);+ expect(r.errors.length, `expected errors: ${text}`).toBeGreaterThan(0);+ }+ });+});++describe("validateQuery / adapter parity", () => {+ it("everything validateQuery accepts lowers without errors", () => {+ const queries = [+ "",+ "level:ERROR env:prod timeout",+ "level:(ERROR OR WARNING)",+ "-env:dev latency:>2",+ "scores.accuracy:>0.8 traceScores.nps:positive",+ "metadata.region:*eu* has:endTime -has:userId",+ "input:refund tags:(a AND b)",+ "isRootObservation:true name:*chat*",+ "(level:ERROR OR level:WARNING) env:dev",+ ];+ for (const text of queries) {+ const v = validateQuery(text);+ expect(v.valid, `expected valid: ${text}`).toBe(true);+ const r = astToFilterState(v.ast);+ expect(r.errors, `expected lowering: ${text}`).toEqual([]);+ }+ });+});++describe("filterStateToQueryText", () => {+ it("round-trips legacy filter state through the grammar", () => {+ const filters: FilterState = [+ {+ type: "stringOptions",+ column: "type",+ operator: "any of",+ value: ["GENERATION", "AGENT"],+ },+ {+ type: "stringOptions",+ column: "environment",+ operator: "none of",+ value: ["dev"],+ },+ { type: "number", column: "latency", operator: ">", value: 2 },+ {+ type: "string",+ column: "statusMessage",+ operator: "contains",+ value: "rate limit",+ },+ {+ type: "boolean",+ column: "isRootObservation",+ operator: "=",+ value: true,+ },+ {+ type: "stringObject",+ column: "metadata",+ key: "region",+ operator: "=",+ value: "eu",+ },+ {+ type: "numberObject",+ column: "scores_avg",+ key: "accuracy",+ operator: ">",+ value: 0.8,+ },+ {+ type: "categoryOptions",+ column: "score_categories",+ key: "feedback",+ operator: "any of",+ value: ["positive"],+ },+ {+ type: "arrayOptions",+ column: "traceTags",+ operator: "all of",+ value: ["a", "b"],+ },+ { type: "null", column: "endTime", operator: "is not null", value: "" },+ ];++ const { text, skipped } = filterStateToQueryText(filters);+ expect(skipped).toEqual([]);++ const v = validateQuery(text);+ expect(v.valid, text).toBe(true);+ const r = astToFilterState(v.ast);+ expect(r.errors).toEqual([]);+ expect(r.filters).toEqual(filters);+ });++ it("maps display-name columns and boolean <> normalization", () => {+ const filters: FilterState = [+ { type: "string", column: "User ID", operator: "=", value: "u1" },+ {+ type: "boolean",+ column: "hasParentObservation",+ operator: "<>",+ value: true,+ },+ ];+ const { text, skipped } = filterStateToQueryText(filters);+ expect(skipped).toEqual([]);+ const r = astToFilterState(validateQuery(text).ast);+ expect(r.errors).toEqual([]);+ expect(r.filters).toEqual([+ {+ type: "stringOptions",+ column: "userId",+ operator: "any of",+ value: ["u1"],+ },+ {+ type: "boolean",+ column: "hasParentObservation",+ operator: "=",+ value: false,+ },+ ]);+ });++ it("reports unrepresentable filters in skipped (descriptions + objects)", () => {+ const positionFilter: FilterState[number] = {+ type: "positionInTrace",+ column: "positionInTrace",+ operator: "=",+ key: "root",+ };+ const { text, skipped, skippedFilters } = filterStateToQueryText([+ positionFilter,+ ]);+ expect(text).toBe("");+ expect(skipped).toHaveLength(1);+ // The actual objects are surfaced so the container can preserve them+ // across a commit (no silent drop).+ expect(skippedFilters).toEqual([positionFilter]);+ });++ it("skips a single-value array all-of instead of flipping it to any-of", () => {+ // `all of [a]` has no distinct grammar form (it equals any-of, and `(a)`+ // reparses as any-of). Preserve it via skippedFilters rather than silently+ // rewrite the operator shape on commit.+ const allOfOne: FilterState[number] = {+ type: "arrayOptions",+ column: "traceTags",+ operator: "all of",+ value: ["a"],+ };+ const r = filterStateToQueryText([allOfOne]);+ expect(r.text).toBe("");+ expect(r.skippedFilters).toEqual([allOfOne]);+ // Multi-value all-of still round-trips faithfully through the AND group.+ const multi: FilterState[number] = { ...allOfOne, value: ["a", "b"] };+ const back = astToFilterState(+ parse(filterStateToQueryText([multi]).text).ast,+ );+ expect(back.filters).toEqual([multi]);+ });++ it("skips keyed filters whose key carries grammar chars (would mis-parse)", () => {+ // `metadata.foo:bar` would reparse as key `metadata.foo` value `bar:…` and+ // silently corrupt the filter — so a key with a colon (or any NEEDS_QUOTES+ // char) must be preserved via skippedFilters, not serialized into text.+ const colonKeyMeta: FilterState[number] = {+ type: "stringObject",+ column: "metadata",+ key: "foo:bar",+ operator: "contains",+ value: "x",+ };+ const colonKeyScore: FilterState[number] = {+ type: "categoryOptions",+ column: "score_categories",+ key: "rate:test",+ operator: "any of",+ value: ["5"],+ };+ const r = filterStateToQueryText([colonKeyMeta, colonKeyScore]);+ expect(r.text).toBe("");+ expect(r.skippedFilters).toEqual([colonKeyMeta, colonKeyScore]);+ // A normal key still serializes into the query text (contains → `*x*`).+ expect(+ filterStateToQueryText([{ ...colonKeyMeta, key: "region" }]).text,+ ).toBe("metadata.region:*x*");+ });++ it("serializes metadata equality as the bare form, not :=value", () => {+ // `metadata.region:eu` lowers to a stringObject `=` filter; serializing it+ // back must produce the bare `metadata.region:eu` the user typed — the+ // explicit `metadata.region:=eu` would visibly rewrite the pill. Mirrors the+ // plain `string` exact carve-out.+ const eq: FilterState[number] = {+ type: "stringObject",+ column: "metadata",+ key: "region",+ operator: "=",+ value: "eu",+ };+ expect(filterStateToQueryText([eq]).text).toBe("metadata.region:eu");+ });++ it("serializes a textSearch contains as the bare form, not *value*", () => {+ // `input:refund` lowers to a string `contains` filter; serializing it back+ // must stay bare (`input:refund`), the documented contains-default — the+ // `input:*refund*` glob form would visibly rewrite the user's text on every+ // commit echo. Symmetric inverse of the metadata-equality carve-out.+ const contains: FilterState[number] = {+ type: "string",+ column: "input",+ operator: "contains",+ value: "refund",+ };+ expect(filterStateToQueryText([contains]).text).toBe("input:refund");+ // starts/ends-with stay as globs (no bare form expresses them).+ expect(+ filterStateToQueryText([{ ...contains, operator: "starts with" }]).text,+ ).toBe("input:refund*");+ // The NEGATED form must stay bare too (`-input:refund`, not `-input:*refund*`).+ expect(+ filterStateToQueryText([{ ...contains, operator: "does not contain" }])+ .text,+ ).toBe("-input:refund");+ });++ it("rejects content: as an unknown field (the pseudo-field was removed)", () => {+ // `content:` is no longer a field, so a value form errors as "Unknown field".+ const r = lower('content:"refund"');+ expect(r.errors).toEqual(['Unknown field "content"']);+ expect(r.searchQuery).toBeNull();+ expect(r.searchType).toBeNull();+ // Bare `content:` (no value) is left to the parser — the adapter stays silent+ // (empty-value FilterNode returns before resolveField), so no double.+ expect(lower("content:").errors).toEqual([]);+ });++ it("round-trips bare boolean keywords and leading-hyphen free text", () => {+ // serialize() must quote AND/OR/NOT (any case), !-prefix tokens, and -foo+ // so they reparse as free text rather than as operators/negation/reserved+ // tokens (otherwise the bar lands invalid on page load from URL state).+ for (const searchQuery of [+ "OR",+ "AND",+ "NOT",+ "-foo",+ "OR AND -x",+ "or",+ "and",+ "not",+ "team or kitten",+ "test not really",+ "!important",+ "!critical bug",+ ]) {+ const { text } = filterStateToQueryText([], { searchQuery });+ const v = validateQuery(text);+ expect(v.valid, `${searchQuery} -> ${text}`).toBe(true);+ const r = astToFilterState(v.ast);+ expect(r.errors).toEqual([]);+ expect(r.searchQuery).toBe(searchQuery);+ }+ });++ it("normalizes a residual input scope to an input: column filter", () => {+ // A residual input/output searchType (legacy URL or the legacy toolbar)+ // renders as the scoped token, which reparses to a real column filter — the+ // deliberate canonicalization (searchType → column filter on next commit).+ const { text } = filterStateToQueryText([], {+ searchQuery: "refund policy",+ searchType: ["input"],+ });+ const r = astToFilterState(validateQuery(text).ast);+ expect(r.errors).toEqual([]);+ expect(r.filters).toEqual([+ {+ type: "string",+ column: "input",+ operator: "contains",+ value: "refund policy",+ },+ ]);+ expect(r.searchQuery).toBeNull();+ expect(r.searchType).toBeNull();+ });++ it("renders the default scope (ids+names+input+output) as bare free text", () => {+ // Any subset of {id, content} is the default scope — no scope token, so it+ // round-trips to bare free text (and the caller re-applies the default).+ for (const searchType of [+ ["id"],+ ["id", "content"],+ ["content"],+ ] as const) {+ const { text } = filterStateToQueryText([], {+ searchQuery: "hello",+ searchType: [...searchType],+ });+ expect(text, `${searchType}`).toBe("hello");+ const r = astToFilterState(validateQuery(text).ast);+ expect(r.searchType).toBeNull();+ expect(r.searchQuery).toBe("hello");+ }+ });++ it("preserves EXACT semantics for a single-value stringOptions any-of on id/name", () => {+ // id/name are stringOptions columns in eventsTable (the facet sidebar emits+ // this shape), but textSearch fields in the bar. A single-value any-of must+ // NOT silently re-lower to `contains` — it must keep exact-match semantics.+ for (const column of ["id", "name"]) {+ const filters: FilterState = [+ { type: "stringOptions", column, operator: "any of", value: ["abc"] },+ ];+ const { text, skipped } = filterStateToQueryText(filters);+ expect(skipped).toEqual([]);+ expect(text).toBe(`${column}:=abc`); // explicit exact, not bare `id:abc`+ const r = astToFilterState(validateQuery(text).ast);+ // Stabilizes to {string,=} — same semantics (exact equality), never contains.+ expect(r.filters).toEqual([+ { type: "string", column, operator: "=", value: "abc" },+ ]);+ // And the stabilized form is a fixpoint (no further drift).+ const echo = filterStateToQueryText(r.filters);+ expect(echo.text).toBe(`${column}:=abc`);+ }+ });++ it("round-trips a multi-value stringOptions any-of on id/name losslessly", () => {+ const filters: FilterState = [+ {+ type: "stringOptions",+ column: "id",+ operator: "any of",+ value: ["a", "b"],+ },+ ];+ const { text, skipped } = filterStateToQueryText(filters);+ expect(skipped).toEqual([]);+ expect(astToFilterState(validateQuery(text).ast).filters).toEqual(filters);+ });++ it("preserves a single-value stringOptions none-of on id/name via skippedFilters", () => {+ // `-id:=abc` (negated exact) is not representable, so rather than rewrite it+ // to `does not contain` (a substring flip), the bar must skip + preserve it.+ const filters: FilterState = [+ {+ type: "stringOptions",+ column: "name",+ operator: "none of",+ value: ["abc"],+ },+ ];+ const { skippedFilters } = filterStateToQueryText(filters);+ expect(skippedFilters).toEqual(filters);+ });++ it("round-trips option values with operator-prefix, keyword, and empty forms", () => {+ const filters: FilterState = [+ {+ type: "stringOptions",+ column: "name",+ operator: "any of",+ value: [">weird", "OR", "", "normal"],+ },+ ];+ const { text, skipped } = filterStateToQueryText(filters);+ expect(skipped).toEqual([]);+ const v = validateQuery(text);+ expect(v.valid, text).toBe(true);+ expect(astToFilterState(v.ast).filters).toEqual(filters);+ });++ it("quotes free-text terms that carry grammar characters", () => {+ const { text } = filterStateToQueryText([], {+ searchQuery: "a:b (c)",+ });+ const v = validateQuery(text);+ expect(v.valid, text).toBe(true);+ const r = astToFilterState(v.ast);+ expect(r.filters).toEqual([]);+ expect(r.searchQuery).toBe("a:b (c)");+ });++ it("preserves a multi-space free-text phrase (no \\s+ collapse)", () => {+ const { text } = filterStateToQueryText([], {+ searchQuery: "hello world",+ });+ const r = astToFilterState(validateQuery(text).ast);+ expect(r.searchQuery).toBe("hello world");+ });++ it("renders a default multi-word phrase as ONE quoted token, not split terms", () => {+ // A default-scope searchQuery is a contiguous-substring phrase (ILIKE+ // %query%), so it derives to a single quoted token — consistent with the+ // scope-rewrite suggestions and preserving the user's quotes — rather than+ // whitespace-split bare terms that read as independent AND filters.+ expect(+ filterStateToQueryText([], { searchQuery: "abc abc abc" }).text,+ ).toBe('"abc abc abc"');+ // A single word needs no quotes.+ expect(filterStateToQueryText([], { searchQuery: "abc" }).text).toBe("abc");+ // Still round-trips to the same phrase.+ const r = astToFilterState(+ validateQuery(+ filterStateToQueryText([], { searchQuery: "abc abc abc" }).text,+ ).ast,+ );+ expect(r.searchQuery).toBe("abc abc abc");+ });++ it('round-trips an empty-value metadata filter (:="")', () => {+ const filters: FilterState = [+ {+ type: "stringObject",+ column: "metadata",+ key: "region",+ operator: "=",+ value: "",+ },+ ];+ const { text, skipped } = filterStateToQueryText(filters);+ expect(skipped).toEqual([]);+ const v = validateQuery(text);+ expect(v.valid, text).toBe(true);+ expect(astToFilterState(v.ast).filters).toEqual(filters);+ });+});diff --git a/web/src/features/search-bar/lib/adapter.ts b/web/src/features/search-bar/lib/adapter.tsnew file mode 100644index 0000000000..14efcab2e4--- /dev/null+++ b/web/src/features/search-bar/lib/adapter.ts@@ -0,0 +1,715 @@+// Editor AST → flat Langfuse filter contract.+//+// astToFilterState(ast) -> { filters, searchQuery, searchType, errors }+//+// Today's events table contract is a flat array of single filters joined+// with AND (`eventsTableFilterState`), plus a global full-text+// searchQuery/searchType pair. The grammar can parse more (cross-field OR,+// nested groups); everything the flat contract cannot represent produces an+// explicit error here — never silent dropping. validate.ts runs the same+// checks with source spans as the commit gate, so anything committed is+// guaranteed to lower.+//+// Rules:+// - Top-level AND chain: bare text nodes become searchQuery terms (the default+// scope searches ids+names+input+output); everything else lowers into one or+// more single filters. The bar emits no scope token, so searchType is null.+// - A top-level OR of same-field `key:v` equalities collapses to one any-of+// filter (`level:ERROR OR level:WARNING` === `level:(ERROR OR WARNING)`).+// Any other OR/nested group is not representable.+// - NOT lowers at this boundary (none-of / does-not-contain / inverted+// comparisons / inverted booleans); gaps error via fields.negationIssue.++import { type FilterState, type TracingSearchType } from "@langfuse/shared";++import type { ASTNode, FilterNode } from "./ast";+import {+ isDanglingDotPrefix,+ negationIssue,+ operatorIssue,+ resolveField,+ SCORE_COLUMNS,+ type FieldDef,+} from "./fields";++export type SingleEventsFilter = FilterState[number];++export type AstToFilterStateResult = {+ filters: FilterState;+ searchQuery: string | null;+ /**+ * Full-text scope. Always null today: the bar has no scope tokens — bare free+ * text uses the caller's default (ids+names+input+output), and `input:`/+ * `output:`/`name:`/`id:` are column filters, not scopes. Kept as the seam for+ * caller-default resolution (commit.ts) and any future scope token.+ */+ searchType: TracingSearchType[] | null;+ errors: string[];+};++/**+ * Observed score names by type, so `scores.<name>:<value>` lowers to the right+ * column. A categorical score can have numeric-looking labels (1–5 ratings,+ * 0–10 NPS), so we cannot infer the column from value syntax alone — when the+ * name is known categorical it must hit `score_categories`, not `scores_avg`.+ * Absent/unknown names fall back to the value-syntax heuristic.+ */+export type ScoreTypeContext = {+ numericScoreNames?: ReadonlySet<string>;+ categoricalScoreNames?: ReadonlySet<string>;+ traceNumericScoreNames?: ReadonlySet<string>;+ traceCategoricalScoreNames?: ReadonlySet<string>;+};++export function resolveScoreType(+ ctx: ScoreTypeContext | undefined,+ level: "observation" | "trace",+ name: string,+): "numeric" | "categorical" | "both" | "unknown" {+ if (ctx === undefined) return "unknown";+ const numeric =+ level === "trace" ? ctx.traceNumericScoreNames : ctx.numericScoreNames;+ const categorical =+ level === "trace"+ ? ctx.traceCategoricalScoreNames+ : ctx.categoricalScoreNames;+ const isNum = numeric?.has(name) ?? false;+ const isCat = categorical?.has(name) ?? false;+ if (isNum && isCat) return "both";+ if (isNum) return "numeric";+ if (isCat) return "categorical";+ return "unknown";+}++/**+ * A top-level OR whose children are all same-field single-value `=` filters+ * collapses to one any-of filter node. Null otherwise.+ */+function collapseSameFieldOr(node: ASTNode): FilterNode | null {+ if (node.kind !== "or") return null;+ const filters = node.children.filter(+ (c): c is FilterNode => c.kind === "filter",+ );+ if (filters.length !== node.children.length || filters.length < 2)+ return null;+ const first = filters[0]!;+ if (first.op !== "=" || first.values.length !== 1) return null;+ for (const f of filters) {+ if (f.key !== first.key || f.op !== "=" || f.values.length !== 1)+ return null;+ }+ return {+ kind: "filter",+ key: first.key,+ op: "=",+ values: filters.flatMap((f) => f.values),+ valueOp: "or",+ };+}++type LowerContext = {+ filters: SingleEventsFilter[];+ searchTerms: string[];+ errors: string[];+ scoreTypes?: ScoreTypeContext;+};++export function astToFilterState(+ ast: ASTNode | null,+ scoreTypes?: ScoreTypeContext,+): AstToFilterStateResult {+ const ctx: LowerContext = {+ filters: [],+ searchTerms: [],+ errors: [],+ scoreTypes,+ };++ if (ast !== null) {+ lowerTopLevel(ast, false, ctx);+ }++ return {+ filters: ctx.filters,+ searchQuery: ctx.searchTerms.length > 0 ? ctx.searchTerms.join(" ") : null,+ // The bar has no scope tokens; the caller (commit.ts) applies the default.+ searchType: null,+ errors: ctx.errors,+ };+}++// AND chains (top-level or parenthesized — semantically identical in the+// flat contract) accept free text (-> searchQuery; the default scope searches+// ids, names, input, and output) and lower everything else into single filters.+function lowerTopLevel(+ node: ASTNode,+ negated: boolean,+ ctx: LowerContext,+): void {+ switch (node.kind) {+ case "text":+ if (negated) {+ ctx.errors.push(+ `Free text "${node.value}" cannot be negated — search text is global`,+ );+ return;+ }+ // A bare dot-prefix (`metadata.`, `scores.`, …) parses as free text, so+ // committing it would silently set searchQuery to the prefix. Reject it+ // here so every commit path (typed Enter and structured pick) is gated.+ // Quoted text is an explicit literal search and is allowed.+ if (!node.quoted && isDanglingDotPrefix(node.value)) {+ ctx.errors.push(+ `Incomplete field "${node.value}" — add a key after the dot (e.g. metadata.region:eu)`,+ );+ return;+ }+ ctx.searchTerms.push(node.value);+ return;+ case "not":+ lowerTopLevel(node.child, !negated, ctx);+ return;+ case "and": {+ if (negated) {+ // NOT(a AND b) would need OR — not representable in the flat contract.+ ctx.errors.push(+ "Negated groups are not supported — negate individual filters instead (e.g. -env:dev)",+ );+ return;+ }+ // Nested parenthesized AND groups flatten into the top-level chain.+ for (const c of node.children) lowerTopLevel(c, false, ctx);+ return;+ }+ case "or": {+ const collapsed = collapseSameFieldOr(node);+ if (collapsed !== null) {+ // Route the collapsed node the SAME way as a directly-typed filter so+ // the two paths can't drift.+ lowerFilterNode(collapsed, negated, ctx);+ return;+ }+ ctx.errors.push(+ "OR is not supported yet, filters combine with AND. Use field:(a OR b) for any-of values",+ );+ return;+ }+ case "filter":+ lowerFilterNode(node, negated, ctx);+ return;+ }+}++// Route a single FilterNode into a flat filter. Both the direct `filter` case+// and the OR-collapse path go through here so the two can't drift.+function lowerFilterNode(+ node: FilterNode,+ negated: boolean,+ ctx: LowerContext,+): void {+ lowerFilter(node, negated, ctx.filters, ctx.errors, ctx.scoreTypes);+}++function lowerFilter(+ node: FilterNode,+ negated: boolean,+ out: SingleEventsFilter[],+ errors: string[],+ scoreTypes?: ScoreTypeContext,+): void {+ if (node.values.length === 0) {+ // The parser already flags every empty-value FilterNode at this span — and+ // with the exact wording for each shape (bare key, operator prefix+ // `key:=`, glob, grouped `key:()`), which a single adapter string can't+ // match. Return silently so the parser's message is the sole diagnostic+ // (validate.ts blocks the commit either way); pushing one here doubled it.+ return;+ }++ const ref = resolveField(node.key);+ if (ref === null) {+ errors.push(`Unknown field "${node.key}"`);+ return;+ }++ const opIssue = operatorIssue(ref, node.op, node.valueOp ?? "or");+ if (opIssue !== null) {+ errors.push(opIssue);+ return;+ }+ if (negated) {+ const negIssue = negationIssue(ref, node.op, node.valueOp ?? "or");+ if (negIssue !== null) {+ errors.push(negIssue);+ return;+ }+ }++ switch (ref.type) {+ case "pseudo":+ // `has` is the only pseudo-field.+ lowerHas(node, negated, out, errors);+ return;+ case "metadata":+ lowerMetadata(node, ref.key, negated, out, errors);+ return;+ case "scores":+ lowerScores(node, ref.key, ref.level, negated, out, errors, scoreTypes);+ return;+ case "field":+ switch (ref.field.kind) {+ case "number":+ lowerNumber(node, ref.field, negated, out, errors);+ return;+ case "datetime":+ lowerDatetime(node, ref.field, negated, out, errors);+ return;+ case "boolean":+ lowerBoolean(node, ref.field, negated, out, errors);+ return;+ case "text":+ lowerText(node, ref.field, negated, out, errors);+ return;+ }+ }+}++/** AST string op -> Langfuse string filter operator (positive polarity). */+function stringOperatorOf(+ op: FilterNode["op"],+): "contains" | "=" | "starts with" | "ends with" | null {+ switch (op) {+ case "~":+ return "contains";+ case "exact":+ return "=";+ case "^":+ return "starts with";+ case "$":+ return "ends with";+ default:+ return null;+ }+}++function lowerText(+ node: FilterNode,+ field: FieldDef,+ negated: boolean,+ out: SingleEventsFilter[],+ errors: string[],+): void {+ if (node.op === "~") {+ // Multiple contains on one field would be any-of (OR) — not flat.+ // Negated multi-value IS flat: AND of does-not-contain.+ if (!negated && node.values.length > 1) {+ errors.push(+ `"${field.id}" supports a single *value* — multiple contains terms cannot be combined with OR in the filter contract`,+ );+ return;+ }+ for (const v of node.values) {+ out.push({+ type: "string",+ column: field.id,+ operator: negated ? "does not contain" : "contains",+ value: v,+ });+ }+ return;+ }++ if (node.op === "^" || node.op === "$") {+ // negationIssue blocks negated forms before this point.+ if (node.values.length > 1) {+ const form = node.op === "^" ? "value*" : "*value";+ errors.push(`"${field.id}" supports a single ${form}`);+ return;+ }+ out.push({+ type: "string",+ column: field.id,+ operator: stringOperatorOf(node.op)!,+ value: node.values[0]!,+ });+ return;+ }++ if (node.op === "exact" && field.syncMode === "textSearch") {+ // negationIssue blocks the negated case before we get here.+ if (node.values.length > 1) {+ // Multiple exact values are any-of: representable via stringOptions.+ out.push({+ type: "stringOptions",+ column: field.id,+ operator: "any of",+ value: node.values,+ });+ return;+ }+ out.push({+ type: "string",+ column: field.id,+ operator: "=",+ value: node.values[0]!,+ });+ return;+ }++ // '=' default and 'exact' on option-backed fields: any-of / none-of.+ if (field.syncMode === "arrayOption") {+ if (node.valueOp === "and") {+ // negationIssue blocks negated all-of groups before this point.+ out.push({+ type: "arrayOptions",+ column: field.id,+ operator: "all of",+ value: node.values,+ });+ return;+ }+ out.push({+ type: "arrayOptions",+ column: field.id,+ operator: negated ? "none of" : "any of",+ value: node.values,+ });+ return;+ }+ if (field.syncMode === "exactOption") {+ out.push({+ type: "stringOptions",+ column: field.id,+ operator: negated ? "none of" : "any of",+ value: node.values,+ });+ return;+ }+ // textSearch fields: bare equality means "contains" (search semantics);+ // `key:=value` above is the explicit exact match. Grouped values lower to+ // stringOptions any-of/none-of (exact semantics — string columns accept+ // stringOptions filters in the contract).+ if (node.values.length > 1) {+ out.push({+ type: "stringOptions",+ column: field.id,+ operator: negated ? "none of" : "any of",+ value: node.values,+ });+ return;+ }+ out.push({+ type: "string",+ column: field.id,+ operator: negated ? "does not contain" : "contains",+ value: node.values[0]!,+ });+}++// Exported so the reverse adapter's negation-fold normalizer (foldDerivedNegation)+// inverts comparisons the SAME way this lowering does — keep them in one place.+export const INVERTED_COMPARISON = {+ ">": "<=",+ "<": ">=",+ ">=": "<",+ "<=": ">",+} as const;++type ComparisonOp = keyof typeof INVERTED_COMPARISON;++function isComparison(op: FilterNode["op"]): op is ComparisonOp {+ return op === ">" || op === "<" || op === ">=" || op === "<=";+}++function parseNumbers(+ node: FilterNode,+ label: string,+ errors: string[],+): number[] | null {+ // Number("") and Number(" ") are both 0 (finite), so guard empty/whitespace+ // explicitly — otherwise `latency:""` would silently filter for latency = 0.+ const bad = node.values.find(+ (v) => v.trim().length === 0 || !Number.isFinite(Number(v)),+ );+ if (bad !== undefined) {+ errors.push(`"${label}" expects a number, got "${bad}"`);+ return null;+ }+ return node.values.map((v) => Number(v));+}++function lowerNumber(+ node: FilterNode,+ field: FieldDef,+ negated: boolean,+ out: SingleEventsFilter[],+ errors: string[],+): void {+ const numbers = parseNumbers(node, field.id, errors);+ if (numbers === null) return;++ if (node.op === "=" || node.op === "exact") {+ // negationIssue blocks negated equality (needs < OR >) before this point.+ if (numbers.length > 1) {+ errors.push(+ `"${field.id}" expects a single value — any-of number lists are not supported`,+ );+ return;+ }+ out.push({+ type: "number",+ column: field.id,+ operator: "=",+ value: numbers[0]!,+ });+ return;+ }++ if (!isComparison(node.op)) {+ errors.push(`"${field.id}" does not support ${node.op}`);+ return;+ }+ out.push({+ type: "number",+ column: field.id,+ operator: negated ? INVERTED_COMPARISON[node.op] : node.op,+ value: numbers[0]!,+ });+}++function lowerDatetime(+ node: FilterNode,+ field: FieldDef,+ negated: boolean,+ out: SingleEventsFilter[],+ errors: string[],+): void {+ if (!isComparison(node.op)) {+ errors.push(+ `"${field.id}" is a datetime field — use a comparison (e.g. ${field.id}:>2026-06-01)`,+ );+ return;+ }+ const raw = node.values[0]!;+ const ms = Date.parse(raw);+ if (Number.isNaN(ms)) {+ errors.push(`"${field.id}" expects an ISO date, got "${raw}"`);+ return;+ }+ out.push({+ type: "datetime",+ column: field.id,+ operator: negated ? INVERTED_COMPARISON[node.op] : node.op,+ value: new Date(ms),+ });+}++function lowerBoolean(+ node: FilterNode,+ field: FieldDef,+ negated: boolean,+ out: SingleEventsFilter[],+ errors: string[],+): void {+ if ((node.op !== "=" && node.op !== "exact") || node.values.length !== 1) {+ errors.push(`"${field.id}" expects exactly one of true/false`);+ return;+ }+ const raw = node.values[0]!.toLowerCase();+ if (raw !== "true" && raw !== "false") {+ errors.push(`"${field.id}" expects true or false, got "${node.values[0]}"`);+ return;+ }+ const value = raw === "true";+ out.push({+ type: "boolean",+ column: field.id,+ operator: "=",+ value: negated ? !value : value,+ });+}++/**+ * Metadata dot-paths lower to stringObject filters (the only metadata filter+ * shape in the contract): single value, string ops, FTS matches.+ */+function lowerMetadata(+ node: FilterNode,+ key: string,+ negated: boolean,+ out: SingleEventsFilter[],+ errors: string[],+): void {+ if (node.values.length > 1) {+ errors.push(+ `metadata.${key} supports a single value — any-of metadata groups are not supported`,+ );+ return;+ }+ const value = node.values[0]!;++ if (node.op === "~") {+ out.push({+ type: "stringObject",+ column: "metadata",+ key,+ operator: negated ? "does not contain" : "contains",+ value,+ });+ return;+ }+ if (node.op === "^" || node.op === "$") {+ // negationIssue blocks negated forms before this point.+ out.push({+ type: "stringObject",+ column: "metadata",+ key,+ operator: stringOperatorOf(node.op)!,+ value,+ });+ return;+ }+ // '=' default and 'exact': exact match. Negated equality is blocked by+ // negationIssue for 'exact'; for '=' there is no "does not equal" either —+ // surface the same suggestion.+ if (negated) {+ errors.push(+ `negated equality on metadata is not representable — use -metadata.${key}:*value* (does not contain)`,+ );+ return;+ }+ out.push({+ type: "stringObject",+ column: "metadata",+ key,+ operator: "=",+ value,+ });+}++/**+ * Score dot-paths: comparisons and numeric values target the numeric score+ * column (numberObject keyed by score name); non-numeric values target the+ * categorical column (categoryOptions any-of/none-of).+ */+function lowerScores(+ node: FilterNode,+ key: string,+ level: "observation" | "trace",+ negated: boolean,+ out: SingleEventsFilter[],+ errors: string[],+ scoreTypes?: ScoreTypeContext,+): void {+ const columns = SCORE_COLUMNS[level];+ const path = level === "trace" ? `traceScores.${key}` : `scores.${key}`;++ const lowerNumeric = (): void => {+ const numbers = parseNumbers(node, path, errors);+ if (numbers === null) return;+ if (node.op === "=" || node.op === "exact") {+ if (negated) {+ errors.push(+ `negated numeric score equality is not representable — use comparisons (${path}:<n or ${path}:>n)`,+ );+ return;+ }+ if (numbers.length > 1) {+ errors.push(+ `${path} expects a single numeric value — any-of number lists are not supported`,+ );+ return;+ }+ out.push({+ type: "numberObject",+ column: columns.numeric,+ key,+ operator: "=",+ value: numbers[0]!,+ });+ return;+ }+ out.push({+ type: "numberObject",+ column: columns.numeric,+ key,+ operator: negated+ ? INVERTED_COMPARISON[node.op as ComparisonOp]+ : (node.op as ComparisonOp),+ value: numbers[0]!,+ });+ };++ const pushCategory = (): void => {+ out.push({+ type: "categoryOptions",+ column: columns.categorical,+ key,+ operator: negated ? "none of" : "any of",+ value: node.values,+ });+ };++ // Route by observed score TYPE when we know it — a categorical score with+ // numeric labels (e.g. a 1–5 rating) must hit the categorical column, not+ // scores_avg, or it silently targets a column with no data.+ const scoreType = resolveScoreType(scoreTypes, level, key);+ if (scoreType === "categorical") {+ // Comparisons (> < >= <=) are meaningless on a category. But exact (`:=x`)+ // and the bare `=` form are both just an exact category match, so they+ // lower to categoryOptions exactly like `scores.<name>:x`.+ if (isComparison(node.op)) {+ errors.push(+ `${path} is categorical — comparison operators only apply to numeric scores`,+ );+ return;+ }+ pushCategory();+ return;+ }++ // Numeric / unknown: comparisons and exact target the numeric column.+ if (isComparison(node.op) || node.op === "exact") {+ lowerNumeric();+ return;+ }++ // '=' default: numeric when known-numeric, else value-syntax fallback+ // (all-numeric → numeric) for unknown/both.+ const allNumeric = node.values.every((v) => Number.isFinite(Number(v)));+ if (scoreType === "numeric" || allNumeric) {+ lowerNumeric();+ return;+ }+ pushCategory();+}++/** `has:field` -> is-not-null; `-has:field` -> is-null. */+function lowerHas(+ node: FilterNode,+ negated: boolean,+ out: SingleEventsFilter[],+ errors: string[],+): void {+ if (node.values.length > 1 && !negated) {+ // has:(a OR b) would be an OR of null checks — not flat. The negated+ // form De-Morgans to an AND of is-null, which IS flat.+ errors.push(+ "has: accepts a single field — combine multiple has: filters with AND instead",+ );+ return;+ }+ for (const v of node.values) {+ const target = resolveField(v);+ if (target === null || target.type !== "field") {+ errors.push(`has: expects a field name, got "${v}"`);+ continue;+ }+ out.push({+ type: "null",+ column: target.field.id,+ operator: negated ? "is null" : "is not null",+ value: "",+ });+ }+}diff --git a/web/src/features/search-bar/lib/ast.ts b/web/src/features/search-bar/lib/ast.tsnew file mode 100644index 0000000000..c032fe7bfe--- /dev/null+++ b/web/src/features/search-bar/lib/ast.ts@@ -0,0 +1,146 @@+// Editor AST for the search-bar query language: a discriminated union+// expression tree produced by the grammar parser (langQ.ts). This is the+// *editor* representation — the table-facing contract is the flat+// `FilterState` from @langfuse/shared, derived via adapter.ts.+//+// Leaf nodes carry their source span so structured edits (chip removal)+// can rewrite the smallest relevant slice of the committed text instead of+// reserializing the whole query.++export type Span = { from: number; to: number };++// Filter operators: '=' is the per-field default (any-of / contains),+// 'exact' is the explicit `key:=v` string/number equality. The text-match ops+// are surfaced as positional `*` globs — '~' contains (`*v*`), '^' starts-with+// (`v*`), '$' ends-with (`*v`) — plus the comparisons. (The op names stay+// `~`/`^`/`$` internally; only the typed/serialized syntax is glob.)+export type CompareOp =+ | "="+ | "exact"+ | "~"+ | "^"+ | "$"+ | ">"+ | "<"+ | ">="+ | "<=";++export type AndNode = { kind: "and"; children: ASTNode[]; parenSpan?: Span };+export type OrNode = { kind: "or"; children: ASTNode[]; parenSpan?: Span };+export type NotNode = {+ kind: "not";+ child: ASTNode;+ span?: Span;+ parenSpan?: Span;+};+export type FilterNode = {+ kind: "filter";+ /** Canonical field id (registry-resolved) or `metadata.<key>`. */+ key: string;+ /** The key as the user typed it (alias/casing) — serializer prefers it. */+ rawKey?: string;+ op: CompareOp;+ /** Comma list for '='; exactly one entry for comparison ops. */+ values: string[];+ /** How grouped values combine: `key:(a OR b)` any-of (default) vs+ * `key:(a AND b)` all-of — the arrayOptions "all of" operator. */+ valueOp?: "or" | "and";+ span?: Span;+ /** When the node was the sole content of a paren group: span incl. parens. */+ parenSpan?: Span;+};+export type TextNode = {+ kind: "text";+ value: string;+ quoted?: boolean;+ span?: Span;+ parenSpan?: Span;+};++export type ASTNode = AndNode | OrNode | NotNode | FilterNode | TextNode;++// ---- helpers ----++function spanEq(a: Span | undefined, b: Span): boolean {+ return a !== undefined && a.from === b.from && a.to === b.to;+}++/** True when span `a` is fully contained within span `b`. */+function spanWithin(a: Span, b: Span): boolean {+ return a.from >= b.from && a.to <= b.to;+}++/** Semantic equality — ignores spans, parens, rawKey/quoted presentation. */+export function astEquals(a: ASTNode | null, b: ASTNode | null): boolean {+ if (a === null || b === null) return a === b;+ if (a.kind !== b.kind) return false;+ switch (a.kind) {+ case "filter": {+ const o = b as FilterNode;+ return (+ a.key === o.key &&+ a.op === o.op &&+ (a.valueOp ?? "or") === (o.valueOp ?? "or") &&+ a.values.length === o.values.length &&+ a.values.every((v, i) => v === o.values[i])+ );+ }+ case "text":+ return a.value === (b as TextNode).value;+ case "not":+ return astEquals(a.child, (b as NotNode).child);+ case "and":+ case "or": {+ const o = b as AndNode | OrNode;+ return (+ a.children.length === o.children.length &&+ a.children.every((c, i) => astEquals(c, o.children[i]!))+ );+ }+ }+}++/**+ * AST surgery: remove the node identified by `target` (matching its span or+ * parenSpan). Collapsing rules keep the tree valid: a NOT whose child is+ * removed disappears; groups drop to their single remaining child; empty+ * groups become null. Used as the reserialize fallback when a span-splice+ * would produce invalid text.+ */+export function removeNodeBySpan(node: ASTNode, target: Span): ASTNode | null {+ const ownSpan =+ node.kind === "and" || node.kind === "or" ? undefined : node.span;+ if (spanEq(ownSpan, target) || spanEq(node.parenSpan, target)) return null;+ switch (node.kind) {+ case "filter":+ case "text":+ // A leaf fully inside the target span is also removed: a coalesced+ // free-text chip's span covers several text leaves (matching none+ // exactly), and a `-foo` chip's target token span includes the leading+ // dash while the inner text leaf's span does not.+ if (ownSpan && spanWithin(ownSpan, target)) return null;+ return node;+ case "not": {+ const child = removeNodeBySpan(node.child, target);+ if (child === null) return null;+ return child === node.child ? node : { ...node, child };+ }+ case "and":+ case "or": {+ const kept: ASTNode[] = [];+ let changed = false;+ for (const c of node.children) {+ const r = removeNodeBySpan(c, target);+ if (r === null) changed = true;+ else {+ if (r !== c) changed = true;+ kept.push(r);+ }+ }+ if (!changed) return node;+ if (kept.length === 0) return null;+ if (kept.length === 1) return kept[0]!;+ return { ...node, children: kept };+ }+ }+}diff --git a/web/src/features/search-bar/lib/commit.clienttest.ts b/web/src/features/search-bar/lib/commit.clienttest.tsnew file mode 100644index 0000000000..052dfff50a--- /dev/null+++ b/web/src/features/search-bar/lib/commit.clienttest.ts@@ -0,0 +1,60 @@+import { planCommit } from "@/src/features/search-bar/lib/commit";++describe("planCommit", () => {+ it("lowers a valid draft to filters + search + canonical text", () => {+ const r = planCommit(" level:ERROR timeout ");+ expect(r.status).toBe("committed");+ if (r.status !== "committed") return;+ expect(r.filters).toEqual([+ {+ type: "stringOptions",+ column: "level",+ operator: "any of",+ value: ["ERROR"],+ },+ ]);+ expect(r.searchQuery).toBe("timeout");+ // Bare free text uses the default scope: ids+names+input+output.+ expect(r.searchType).toEqual(["id", "content"]);+ // Canonical text preserves the parsed (typed) order.+ expect(r.canonical).toBe("level:ERROR timeout");+ });++ it("applies the default searchType (ids+names+input+output)", () => {+ const r = planCommit("level:ERROR");+ expect(r.status).toBe("committed");+ if (r.status !== "committed") return;+ expect(r.searchType).toEqual(["id", "content"]);+ expect(r.searchQuery).toBeNull();+ });++ it("treats an empty draft as a committed empty query", () => {+ const r = planCommit(" ");+ expect(r.status).toBe("committed");+ if (r.status !== "committed") return;+ expect(r.filters).toEqual([]);+ expect(r.searchQuery).toBeNull();+ expect(r.canonical).toBe("");+ });++ it("returns invalid with diagnostics for unrepresentable queries", () => {+ const r = planCommit("level:ERROR OR env:dev");+ expect(r.status).toBe("invalid");+ if (r.status !== "invalid") return;+ expect(r.diagnostics.length).toBeGreaterThan(0);+ });++ it("blocks commit when validation and lowering disagree (score-type parity)", () => {+ // `accuracy` is a numeric score, so `accuracy:hello` can't lower. The+ // validity check must see the same scoreTypes the lowering does — otherwise+ // it commits an empty filter set and the user's input silently vanishes.+ const scoreTypes = {+ numericScoreNames: new Set<string>(["accuracy"]),+ categoricalScoreNames: new Set<string>(),+ traceNumericScoreNames: new Set<string>(),+ traceCategoricalScoreNames: new Set<string>(),+ };+ const r = planCommit("scores.accuracy:hello", scoreTypes);+ expect(r.status).toBe("invalid");+ });+});diff --git a/web/src/features/search-bar/lib/commit.ts b/web/src/features/search-bar/lib/commit.tsnew file mode 100644index 0000000000..466c6539ab--- /dev/null+++ b/web/src/features/search-bar/lib/commit.ts@@ -0,0 +1,75 @@+// The commit gate, as a pure function (no React, no store).+//+// "Committing" the search bar means: validate the draft text, and if it lowers+// cleanly, produce the flat filter state + full-text search the table consumes.+// This is the single boundary where editor text becomes applied filter state —+// the container calls it and writes the result to the URL filter state (the+// one source of truth). Keeping it pure makes the commit semantics unit-+// testable without rendering anything.++import type { FilterState, TracingSearchType } from "@langfuse/shared";++import { astToFilterState, type ScoreTypeContext } from "./adapter";+import { serialize, type Diagnostic } from "./langQ";+import { validateQuery } from "./validate";++// The full-text scope a bare query (no scope token) applies: ids & names+// (`id` lane) PLUS input & output (`content` lane). Typing plain text searches+// all of them. `input:`/`output:` narrow to one column; `name:`/`id:` narrow to+// those. `content` here is the backend searchType lane (input ∪ output), not a+// user-typed token — the `content:` grammar token has been removed.+export const DEFAULT_SEARCH_TYPE: TracingSearchType[] = ["id", "content"];++export type CommitResult =+ | {+ status: "committed";+ filters: FilterState;+ searchQuery: string | null;+ searchType: TracingSearchType[];+ /** Canonical serialization of the committed query (for recent searches). */+ canonical: string;+ }+ | { status: "invalid"; diagnostics: Diagnostic[] };++/**+ * Validate and lower `draftText`. `committed` carries everything the table+ * needs; `invalid` carries the span-tagged diagnostics for the editor to show.+ * `validateQuery` and `astToFilterState` agree by construction, so a valid+ * draft always lowers without errors. `scoreTypes` (observed score names by+ * type) lets `scores.<name>:<value>` lower to the right column.+ */+export function planCommit(+ draftText: string,+ scoreTypes?: ScoreTypeContext,+): CommitResult {+ const res = validateQuery(draftText.trim(), scoreTypes);+ if (!res.valid) {+ return { status: "invalid", diagnostics: res.diagnostics };+ }+ const { filters, searchQuery, searchType, errors } = astToFilterState(+ res.ast,+ scoreTypes,+ );+ // Parity belt-and-suspenders: validateQuery lowers with the same scoreTypes,+ // so a valid draft should never produce lowering errors. If it ever does+ // (a future divergence), refuse to commit rather than silently drop the+ // errored filters — never write a partial result with no signal.+ if (errors.length > 0) {+ return {+ status: "invalid",+ diagnostics: errors.map((message) => ({+ from: 0,+ to: draftText.length,+ severity: "error" as const,+ message,+ })),+ };+ }+ return {+ status: "committed",+ filters,+ searchQuery,+ searchType: searchType ?? DEFAULT_SEARCH_TYPE,+ canonical: serialize(res.ast),+ };+}diff --git a/web/src/features/search-bar/lib/completions.clienttest.ts b/web/src/features/search-bar/lib/completions.clienttest.tsnew file mode 100644index 0000000000..2c7a5f149d--- /dev/null+++ b/web/src/features/search-bar/lib/completions.clienttest.ts@@ -0,0 +1,458 @@+import {+ flattenOptions,+ planInputCompletions,+ SECTION_COMPARE_OPS,+ SECTION_FIELDS,+ SECTION_MATCH_OPS,+ SECTION_RECENT,+ SECTION_VALUES,+ type InputCompletionContext,+} from "@/src/features/search-bar/lib/completions";+import type { ObservedOptions } from "@/src/features/search-bar/lib/observed-options";++const OBSERVED: ObservedOptions = {+ level: [+ { value: "ERROR", count: 12 },+ { value: "WARNING", count: 3 },+ ],+ environment: [{ value: "production" }, { value: "dev" }],+ scores_avg: [{ value: "accuracy" }],+ score_categories: [{ value: "feedback" }],+ "score_categories.feedback": [{ value: "positive" }, { value: "negative" }],+ "metadata.region": [{ value: "eu" }, { value: "us" }],+};++function plan(+ input: string,+ caret: number,+ overrides: Partial<InputCompletionContext> = {},+) {+ return planInputCompletions({+ input,+ caret,+ observed: OBSERVED,+ recents: [],+ currentQueryText: input,+ ...overrides,+ });+}++describe("planInputCompletions", () => {+ it("plans the empty stage with fields and recents", () => {+ const p = plan("", 0, { recents: ["level:ERROR"] });+ expect(p?.stage).toBe("empty");+ const titles = p?.sections.map((s) => s.title);+ expect(titles).toContain(SECTION_FIELDS);+ expect(titles).toContain(SECTION_RECENT);+ });++ it("ranks fields against the typed key prefix but does NOT arm Enter (free-text-first)", () => {+ // A bare prefix lists the field but must not hijack Enter — the user may be+ // typing a free-text search. Enter commits the text; the field is one+ // arrow-press away.+ const p = plan("lev", 3);+ expect(p?.stage).toBe("field");+ expect(p?.autoHighlight).toBe(false);+ const first = flattenOptions(p);+ expect(first[0]).toMatchObject({ kind: "field", fieldId: "level" });+ });++ it("arms Enter only when a bare word EXACTLY names a field", () => {+ // Exact field/alias name → arm Enter to start the filter (`level` → `level:`).+ expect(plan("level", 5)?.autoHighlight).toBe(true);+ expect(plan("env", 3)?.autoHighlight).toBe(true); // alias of environment+ // Prefix / substring matches must stay free-text-first (the reported bug:+ // `n` → name:, `ess` → sessionId:).+ expect(plan("n", 1)?.autoHighlight).toBe(false);+ expect(plan("ess", 3)?.autoHighlight).toBe(false); // substring of sessionId+ // No field match at all is already free-text-first.+ expect(plan("abc", 3)?.autoHighlight ?? false).toBe(false);+ });++ it("plans observed values in the value stage", () => {+ const p = plan("level:", 6);+ expect(p?.stage).toBe("value");+ const values = flattenOptions(p).filter((o) => o.kind === "value");+ expect(values.map((o) => o.kind === "value" && o.value)).toEqual([+ "ERROR",+ "WARNING",+ ]);+ });++ it("keeps the observed-value picker for name:/id: while searching as contains", () => {+ // name/id are textSearch (so `name:chat` is a substring search) but carry+ // suggestObservedValues, so the value stage still LISTS observed values and+ // — once a value is typed — offers the glob/exact refinements alongside.+ for (const column of ["name", "id"]) {+ const p = plan(`${column}:`, column.length + 1, {+ observed: { ...OBSERVED, [column]: [{ value: "checkout" }] },+ });+ expect(p?.stage, column).toBe("value");+ const values = flattenOptions(p).filter((o) => o.kind === "value");+ expect(+ values.map((o) => o.kind === "value" && o.value),+ column,+ ).toEqual(["checkout"]);+ }+ const labels = flattenOptions(+ plan("name:chat", 9, {+ observed: { ...OBSERVED, name: [{ value: "chat" }] },+ }),+ ).map((o) => o.label);+ expect(labels).toContain("*chat*"); // contains (the bare-value default)+ expect(labels).toContain("=chat"); // exact+ });++ it("marks a complete typed value active without arming Enter", () => {+ const p = plan("level:ERROR", 11);+ expect(p?.autoHighlight).toBe(false);+ const first = flattenOptions(p)[0];+ expect(first).toMatchObject({+ kind: "value",+ value: "ERROR",+ active: true,+ });+ });++ it("plans the value stage when switching a quoted value (strips both quotes)", () => {+ // A picked value with a space serializes to `traceName:"My Test Trace"`.+ // Clicking back into it to switch must still match the observed value —+ // the typed text has to drop BOTH quotes, not just the leading one.+ const p = plan('traceName:"My Test Trace"', 25, {+ observed: { ...OBSERVED, traceName: [{ value: "My Test Trace" }] },+ });+ expect(p?.stage).toBe("value");+ const first = flattenOptions(p)[0];+ expect(first).toMatchObject({+ kind: "value",+ value: "My Test Trace",+ active: true,+ });+ });++ it("plans the value stage when switching a grouped quoted value", () => {+ // Same as the non-grouped case but inside `(... OR ...)`: clicking into+ // `"My Tag"` must match the observed tag, so both quotes have to drop.+ const p = plan('traceTags:("My Tag" OR "Other")', 14, {+ observed: {+ ...OBSERVED,+ traceTags: [{ value: "My Tag" }, { value: "Other" }],+ },+ });+ expect(p?.stage).toBe("value");+ const values = flattenOptions(p)+ .filter((o) => o.kind === "value")+ .map((o) => (o.kind === "value" ? o.value : null));+ expect(values).toContain("My Tag");+ });++ it("omits the negation pattern when the term already starts with '-'", () => {+ // The user has committed to negation by typing `-`; suggesting the+ // negation pattern (which inserts its own `-`) would double-dash to+ // `--environment:`.+ const ids = flattenOptions(plan("-", 1)).map((o) => o.id);+ expect(ids).not.toContain("pat:negation");+ });++ it("offers comparisons for numeric fields", () => {+ const p = plan("latency:", 8);+ expect(p?.sections.map((s) => s.title)).toContain(SECTION_COMPARE_OPS);+ // No dead-end option: every comparison pick must insert a symbol. The old+ // `=` entry inserted "" — picking it left the draft unchanged (silent).+ const opts = flattenOptions(p);+ expect(opts.length).toBeGreaterThan(0);+ for (const o of opts) {+ expect("insert" in o && o.insert, JSON.stringify(o)).toBeTruthy();+ }+ });++ it("does not offer match operators for array fields (operatorIssue rejects them)", () => {+ const p = plan("traceTags:", 10, {+ observed: { ...OBSERVED, traceTags: [{ value: "a" }, { value: "b" }] },+ });+ expect(p?.stage).toBe("value");+ expect(p?.sections.map((s) => s.title)).not.toContain(SECTION_MATCH_OPS);+ });++ it("offers glob match refinements once a text value is typed", () => {+ // Empty value → nothing to wrap, no match-op section.+ const empty = plan("statusMessage:", 14);+ expect(empty?.sections.map((s) => s.title) ?? []).not.toContain(+ SECTION_MATCH_OPS,+ );+ // Typed value → wrap it in positional `*` globs (+ exact).+ const p = plan("statusMessage:rate", 18);+ expect(p?.sections.map((s) => s.title)).toContain(SECTION_MATCH_OPS);+ const labels = flattenOptions(p).map((o) => o.label);+ expect(labels).toContain("*rate*"); // contains+ expect(labels).toContain("rate*"); // starts with+ expect(labels).toContain("*rate"); // ends with+ expect(labels).toContain("=rate"); // exact+ });++ it("quotes glob refinements for values with whitespace", () => {+ // `My Test` must serialize to `*"My Test"*`, not the raw `*My Test*` the+ // lexer would split in half.+ const p = plan('statusMessage:"My Test"', 23);+ const inserts = flattenOptions(p).flatMap((o) =>+ "insert" in o ? [o.insert] : [],+ );+ expect(inserts).toContain('*"My Test"*'); // contains+ expect(inserts).toContain('"My Test"*'); // starts with+ expect(inserts).toContain('="My Test"'); // exact+ });++ it("suggests score names for score dot paths", () => {+ const p = plan("scores.", 7);+ const labels = flattenOptions(p).map((o) => o.label);+ expect(labels).toContain("scores.accuracy");+ expect(labels).toContain("scores.feedback");+ });++ it("suggests trace-score names for every accepted alias incl. singular tracescore.", () => {+ // The parser resolves tracescore./tracescores./trace_scores.; each must also+ // produce the score-name dropdown, or that spelling parses but suggests+ // nothing. (The singular form was previously missing from PATH_PREFIXES.)+ const observed = { ...OBSERVED, trace_scores_avg: [{ value: "nps" }] };+ for (const prefix of ["tracescore.", "tracescores.", "trace_scores."]) {+ const p = plan(prefix, prefix.length, { observed });+ const labels = flattenOptions(p).map((o) => o.label);+ expect(labels, prefix).toContain("traceScores.nps");+ }+ });++ it("suggests categorical score values", () => {+ const p = plan("scores.feedback:", 16);+ expect(p?.sections.map((s) => s.title)).toContain(SECTION_VALUES);+ const values = flattenOptions(p).filter((o) => o.kind === "value");+ expect(values.map((o) => o.kind === "value" && o.value)).toEqual([+ "positive",+ "negative",+ ]);+ });++ it("suggests metadata values for known keys", () => {+ const p = plan("metadata.region:", 16);+ const values = flattenOptions(p).filter((o) => o.kind === "value");+ expect(values.map((o) => o.kind === "value" && o.value)).toEqual([+ "eu",+ "us",+ ]);+ });++ it("offers scoped full-text rewrites for free text, default scope first", () => {+ const p = plan("refund", 6);+ const opts = flattenOptions(p);+ // The typed text itself (default scope = ids+names+input+output) is the+ // first option — the anchor — ahead of the input:/output: rewrites.+ expect(opts[0]).toMatchObject({ id: "scope:default", label: "refund" });+ const labels = opts.map((o) => o.label);+ expect(labels).toContain("input:refund");+ expect(labels).toContain("output:refund");+ // content: was removed — the default already searches input + output.+ expect(labels).not.toContain("content:refund");+ });++ it("scopes the WHOLE coalesced free-text run, not just the caret word", () => {+ // Caret inside the middle word of `abc abc abc` — the rewrite must wrap the+ // whole run as a quoted phrase and carry its span, so picking it doesn't+ // strand the other words as free text.+ const p = plan("abc abc abc", 5);+ const opts = flattenOptions(p);+ const input = opts.find((o) => o.id === "scope:input");+ expect(input?.label).toBe('input:"abc abc abc"');+ expect(input && "insert" in input && input.insert).toBe(+ 'input:"abc abc abc"',+ );+ expect(input && "replaceSpan" in input && input.replaceSpan).toEqual({+ from: 0,+ to: 11,+ });+ });++ it("scopes the WHOLE run even when a bare word matches a field alias", () => {+ // `tags` is a registered alias (traceTags), but with no `:` it is free text+ // — the parser/composer treat it so, and the run must expand across it.+ // Otherwise the rewrite wraps only `hello` and picking it strands `tags`.+ const p = plan("tags hello", 8);+ const input = flattenOptions(p).find((o) => o.id === "scope:input");+ expect(input?.label).toBe('input:"tags hello"');+ expect(input && "replaceSpan" in input && input.replaceSpan).toEqual({+ from: 0,+ to: 10,+ });+ });++ it("does not double-quote an already-quoted free-text phrase on scope rewrite", () => {+ // `"hello world"` already carries quotes; the rewrite reconstructs the+ // logical phrase and re-serializes it once, so the insert is+ // `input:"hello world"` — not the broken doubly-quoted+ // `input:"\"hello world\""` that searches for literal quotes.+ const p = plan('"hello world"', 6);+ const input = flattenOptions(p).find((o) => o.id === "scope:input");+ expect(input && "insert" in input && input.insert).toBe(+ 'input:"hello world"',+ );+ });++ it("coalesces a quoted phrase + bare words into ONE clean phrase (no escaped quotes)", () => {+ // The compounding bug: a run that mixes an already-quoted phrase with bare+ // words (`"abc abc" abc`) must reconstruct to the logical `abc abc abc` and+ // re-serialize as a single `"abc abc abc"` — never `"abc abc\" abc"`.+ const p = plan('"abc abc" abc', 11);+ const opts = flattenOptions(p);+ const def = opts.find((o) => o.id === "scope:default");+ const input = opts.find((o) => o.id === "scope:input");+ expect(def && "insert" in def && def.insert).toBe('"abc abc abc"');+ expect(input && "insert" in input && input.insert).toBe(+ 'input:"abc abc abc"',+ );+ // The whole raw run (quotes and all) is the replace span.+ expect(def && "replaceSpan" in def && def.replaceSpan).toEqual({+ from: 0,+ to: 13,+ });+ });++ it("teaches the positional-glob contains form, not the retired ~value", () => {+ // pat:contains must advertise + insert the `*value*` glob the parser now+ // understands; the old `name:~chat` lowered to a literal any-of on `~chat`.+ const p = plan("field", 5);+ const pat = flattenOptions(p).find((o) => o.id === "pat:contains");+ expect(pat?.label).toBe("field:*value*");+ expect(pat && "insert" in pat && pat.insert).toBe("name:*chat*");+ });++ it("offers scope switches when the caret is in an input: value", () => {+ // input:/output: are full-text scopes too — clicking into input:abc must+ // offer output:/default (and the glob refinements), each rewriting the WHOLE+ // token, never a switch back to input:.+ const p = plan("input:abc", 9);+ const opts = flattenOptions(p);+ const ids = opts.map((o) => o.id);+ expect(ids).toEqual(+ expect.arrayContaining(["scope:output", "scope:default"]),+ );+ expect(ids).not.toContain("scope:input");+ // content: was removed — never offered as a switch target.+ expect(ids).not.toContain("scope:content");+ const toOutput = opts.find((o) => o.id === "scope:output");+ expect(toOutput && "insert" in toOutput && toOutput.insert).toBe(+ "output:abc",+ );+ expect(+ toOutput && "replaceSpan" in toOutput && toOutput.replaceSpan,+ ).toEqual({ from: 0, to: 9 });+ // Glob refinements still ride alongside the scope switches.+ const labels = opts.map((o) => o.label);+ expect(labels).toContain("*abc*");+ });++ it("does NOT offer scope switches for a negated input/output value", () => {+ // tokenSpan covers the leading `-`, so a scope rewrite would splice it away+ // and flip `does not contain` → `contains` (the complement). The value+ // stage must suppress the switches when negated (match-op refinements stay).+ for (const q of ["-input:refund", "-output:refund"]) {+ const opts = flattenOptions(plan(q, q.length));+ const ids = opts.map((o) => o.id);+ expect(ids, q).not.toContain("scope:content");+ expect(ids, q).not.toContain("scope:output");+ expect(ids, q).not.toContain("scope:input");+ expect(ids, q).not.toContain("scope:default");+ // Only the contains glob survives negation: starts/ends/exact have no+ // inverse operator, so offering them would yield drafts the validator+ // rejects. Contains stays; the other three are gone.+ const labels = opts.map((o) => o.label);+ expect(labels, q).toContain("*refund*");+ expect(labels, q).not.toContain("refund*"); // starts with+ expect(labels, q).not.toContain("*refund"); // ends with+ expect(labels, q).not.toContain("=refund"); // exact+ }+ });++ it("offers only contains on a negated exactOption value", () => {+ // Same parity as the textSearch case above, for exactOption text fields+ // (level/environment/name/…): starts-with (`^`) and ends-with (`$`) wrapped+ // in NOT are "not representable" (negationIssue), so picking them would land+ // a red invalid draft. The value stage must offer only the contains glob.+ const opts = flattenOptions(plan("-level:foo", "-level:foo".length));+ const labels = opts.map((o) => o.label);+ expect(labels).toContain("*foo*"); // contains (does not contain)+ expect(labels).not.toContain("foo*"); // starts with — no inverse op+ expect(labels).not.toContain("*foo"); // ends with — no inverse op+ expect(labels).not.toContain("=foo"); // exact — redundant w/ bare value+ });++ it("does not suggest observed metadata/score names with grammar chars", () => {+ // An observed score named `foo:bar` can't be suggested as `scores.foo:bar`:+ // picking it would reparse with the key split at the first colon and commit+ // a filter on a different key. Filter such names out of the key-path stage.+ const observed = {+ ...OBSERVED,+ scores_avg: [{ value: "accuracy" }, { value: "foo:bar" }],+ metadata: [{ value: "region" }, { value: "a:b" }],+ };+ const scoreLabels = flattenOptions(plan("scores.", 7, { observed })).map(+ (o) => o.label,+ );+ expect(scoreLabels).toContain("scores.accuracy");+ expect(scoreLabels).not.toContain("scores.foo:bar");+ const metaLabels = flattenOptions(plan("metadata.", 9, { observed })).map(+ (o) => o.label,+ );+ expect(metaLabels).toContain("metadata.region");+ expect(metaLabels).not.toContain("metadata.a:b");+ });++ it("keeps the value stage live for a glob value (re-form + re-scope)", () => {+ // `output:*ole*` is a contains glob. Clicking into the value must still+ // plan the value stage: a leading `*` is a glob ANCHOR, not a value-+ // suppressing operator prefix. Regression for the popover going dead on+ // any glob-wrapped full-text value.+ const p = plan("output:*ole*", 9);+ expect(p?.stage).toBe("value");+ const opts = flattenOptions(p);+ const labels = opts.map((o) => o.label);+ // Match-op refinements operate on the BARE core (`ole`), not `*ole*`.+ expect(labels).toContain("*ole*"); // contains (current form)+ expect(labels).toContain("ole*"); // starts with+ expect(labels).toContain("=ole"); // exact+ const ids = opts.map((o) => o.id);+ expect(ids).toEqual(+ expect.arrayContaining(["scope:input", "scope:default"]),+ );+ expect(ids).not.toContain("scope:output");+ expect(ids).not.toContain("scope:content");+ });++ it("treats leading ~/^/$ as literal value chars, not suppressing prefixes", () => {+ // The value-prefix regex must mirror langQ's OPERATOR_PREFIXES (>= <= > < =)+ // and nothing more. After the glob migration `~`/`^`/`$` are literal chars,+ // so a value starting with one must still plan the value stage (wrapping the+ // literal), never bail to a blank popover.+ for (const value of ["~chat", "^chat", "$chat"]) {+ const p = plan(`statusMessage:${value}`, `statusMessage:${value}`.length);+ expect(p?.stage).toBe("value");+ // The match-op refinements wrap the WHOLE literal value (incl. the `~`).+ const labels = flattenOptions(p).map((o) => o.label);+ expect(labels).toContain(`*${value}*`);+ }+ });++ it("plans grouped value segments with keep-open for incomplete groups", () => {+ const p = plan("level:(ERROR OR ", 16);+ expect(p?.stage).toBe("value");+ expect(p?.keepOpenOnPick).toBe(true);+ });++ it("shows a loading row while observed values load", () => {+ const p = plan("level:", 6, { observed: undefined });+ expect(p?.loading).toBe(true);+ });++ it("never suggests the OR keyword between filters", () => {+ const p = plan("O", 1);+ const operators = flattenOptions(p).filter((o) => o.kind === "operator");+ expect(operators.map((o) => o.label)).not.toContain("OR");+ });+});diff --git a/web/src/features/search-bar/lib/completions.ts b/web/src/features/search-bar/lib/completions.tsnew file mode 100644index 0000000000..4f8968c741--- /dev/null+++ b/web/src/features/search-bar/lib/completions.ts@@ -0,0 +1,1113 @@+// Completion planning — pure functions, zero React/DOM.+//+// Given the active input text + caret, produce a CompletionPlan the popover+// renders and the composer applies. Token boundaries come from the shared+// lexer (termAt / splitOutsideQuotes), so quoted phrases with spaces stay one+// token and colons/commas inside quotes never split stages.+//+// Every filter type gets a guided value stage — numbers/datetimes offer their+// operators with unit-aware examples, text fields offer the positional `*` glob+// match refinements (*v* contains, v* starts, *v ends, =v exact), metadata/+// scores suggest observed keys and values, has: enumerates its domain, and free+// text (plus input:/output:) offers scoped full-text search rewrites.++import {+ indexOfOutsideQuotes,+ lexTokens,+ NEEDS_QUOTES,+ parseGlob,+ serializeValue,+ splitOutsideQuotes,+ termAt,+} from "./langQ";+import {+ FIELDS,+ nullableFields,+ resolveField,+ type FieldDef,+ type FieldRef,+} from "./fields";+import type { ObservedOptions } from "./observed-options";++export type CompletionStage =+ | "empty"+ | "field"+ | "value"+ | "operator"+ | "recent";++export type CompletionOption =+ | {+ id: string;+ kind: "field";+ label: string;+ detail?: string;+ fieldId: string;+ }+ | {+ id: string;+ kind: "value";+ label: string;+ detail?: string;+ value: string;+ active?: boolean;+ }+ | {+ id: string;+ kind: "operator";+ label: string;+ detail?: string;+ insert: string;+ }+ | {+ id: string;+ kind: "pattern";+ label: string;+ detail?: string;+ insert: string;+ /** When set, the pick replaces THIS span instead of the plan's — used by+ * scope rewrites that wrap the whole coalesced free-text run, not just+ * the token under the caret. */+ replaceSpan?: { from: number; to: number };+ }+ | { id: string; kind: "recent"; label: string; query: string };++export type CompletionSection = { title: string; options: CompletionOption[] };++export type CompletionPlan = {+ stage: CompletionStage;+ /** Span in the active INPUT text that an accepted option replaces. */+ from: number;+ to: number;+ sections: CompletionSection[];+ /** Value stage waiting on observed values (popover shows a loading row). */+ loading: boolean;+ /** Defaults to false; useful for incomplete grouped value entry. */+ keepOpenOnPick?: boolean;+ /**+ * Highlight the first option on open. True only when the user TYPED a+ * partial token that the options complete — then Enter picks the match.+ * Empty terms and exact-complete tokens highlight nothing, so Enter falls+ * through to committing the query (defaults to false).+ */+ autoHighlight?: boolean;+};++export const SECTION_SUGGESTIONS = "Suggestions";+export const SECTION_FIELDS = "Fields";+export const SECTION_VALUES = "Observed values";+export const SECTION_OPERATORS = "Operators";+export const SECTION_PATTERNS = "Patterns";+export const SECTION_RECENT = "Recent searches";+export const SECTION_MATCH_OPS = "Match operators";+export const SECTION_COMPARE_OPS = "Comparisons";+export const SECTION_KEYS = "Observed keys";+export const SECTION_SCORE_NAMES = "Score names";+export const SECTION_SEARCH_IN = "Full-text search";++const MAX_RECENTS_SHOWN = 5;++// Operators insert with a trailing space so they tokenize out of the input+// immediately; patterns are complete expressions and merge on accept.+// No OR here: the flat filter contract has no cross-field OR — any-of values+// go through `field:(a OR b)` (see PATTERN_OPTIONS).+const OPERATOR_OPTIONS: CompletionOption[] = [+ { id: "op:AND", kind: "operator", label: "AND", insert: "AND " },+ { id: "op:NOT", kind: "operator", label: "NOT", insert: "NOT " },+];++const PATTERN_OPTIONS: CompletionOption[] = [+ {+ id: "pat:contains",+ kind: "pattern",+ label: "field:*value*",+ detail: "contains",+ insert: "name:*chat*",+ },+ {+ id: "pat:anyof",+ kind: "pattern",+ label: "field:(a OR b)",+ detail: "any of",+ insert: "level:(ERROR OR WARNING)",+ },+ {+ id: "pat:negation",+ kind: "pattern",+ label: "-field:value",+ detail: "negation (none of)",+ insert: "-environment:",+ },+ {+ id: "pat:comparison",+ kind: "pattern",+ label: "latency:>2",+ detail: "numeric comparison (seconds)",+ insert: "latency:>2",+ },+ {+ id: "pat:has",+ kind: "pattern",+ label: "has:field",+ detail: "field has a value (-has: for missing)",+ insert: "has:",+ },+ {+ id: "pat:allof",+ kind: "pattern",+ label: "tags:(a AND b)",+ detail: "array all-of",+ insert: "tags:(",+ },+];++/** Case-insensitive match; prefix matches rank before substring matches. */+function filterRank(label: string, query: string): number | null {+ if (query.length === 0) return 0;+ const l = label.toLowerCase();+ const q = query.toLowerCase();+ if (l.startsWith(q)) return 0;+ if (l.includes(q)) return 1;+ return null;+}++function rankFilter<T extends { label: string }>(+ options: T[],+ query: string,+): T[] {+ return options+ .map((o) => ({ o, rank: filterRank(o.label, query) }))+ .filter((x): x is { o: T; rank: number } => x.rank !== null)+ .sort((a, b) => a.rank - b.rank)+ .map((x) => x.o);+}++function fieldOptions(includeVirtual = true): CompletionOption[] {+ const opts: CompletionOption[] = FIELDS.map((f: FieldDef) => ({+ id: `field:${f.id}`,+ kind: "field",+ label: f.id,+ detail: f.description,+ fieldId: f.id,+ }));+ if (includeVirtual) {+ opts.push(+ {+ id: "field:metadata.",+ kind: "field",+ label: "metadata.",+ detail: "metadata key path, e.g. metadata.region:eu",+ fieldId: "metadata.",+ },+ {+ id: "field:scores.",+ kind: "field",+ label: "scores.",+ detail:+ "score by name, e.g. scores.accuracy:>0.8 or scores.feedback:positive",+ fieldId: "scores.",+ },+ {+ id: "field:traceScores.",+ kind: "field",+ label: "traceScores.",+ detail: "trace-level score by name, e.g. traceScores.nps:>8",+ fieldId: "traceScores.",+ },+ {+ id: "field:has",+ kind: "field",+ label: "has",+ detail: "field has a value, e.g. has:endTime (-has: for missing)",+ fieldId: "has",+ },+ );+ }+ return opts;+}++// Ready-to-run query suggestions for the empty state: the top observed value+// of a few showcase fields, inserted as complete filters.+const SUGGESTION_FIELDS = ["level", "type", "environment", "name"];++function querySuggestionOptions(+ observed: ObservedOptions | undefined,+): CompletionOption[] {+ if (observed === undefined) return [];+ const out: CompletionOption[] = [];+ for (const fieldId of SUGGESTION_FIELDS) {+ const top = observed[fieldId]?.[0];+ if (top === undefined) continue;+ const insert = `${fieldId}:${serializeValue(top.value)}`;+ out.push({+ id: `suggest:${insert}`,+ kind: "pattern",+ label: insert,+ detail: top.count !== undefined ? String(top.count) : undefined,+ insert,+ });+ }+ return out;+}++/**+ * Value-stage option list. An empty or exactly-matching typed value means the+ * caret sits on a COMPLETE value (click-to-edit): offer the full list with+ * the current value marked active and ranked first, so Enter re-picks it and+ * the dropdown reads as a switcher. A partial value means the user is typing:+ * prefix-filter.+ */+function valueOptions(+ all: CompletionOption[],+ typed: string,+): CompletionOption[] {+ if (typed.length === 0) return all;+ const exactIndex = all.findIndex(+ (o) => o.kind === "value" && o.value === typed,+ );+ if (exactIndex !== -1) {+ const exact = { ...all[exactIndex]!, active: true };+ return [exact, ...all.slice(0, exactIndex), ...all.slice(exactIndex + 1)];+ }+ return rankFilter(all, typed);+}++function recentOptions(+ recents: string[],+ currentQueryText: string,+): CompletionOption[] {+ return recents+ .filter((q) => q !== currentQueryText.trim())+ .slice(0, MAX_RECENTS_SHOWN)+ .map((q, i) => ({+ id: `recent:${i}:${q}`,+ kind: "recent" as const,+ label: q,+ query: q,+ }));+}++function section(+ title: string,+ options: CompletionOption[],+): CompletionSection[] {+ return options.length > 0 ? [{ title, options }] : [];+}++// ---- per-kind operator menus ----++/** Realistic threshold examples for numeric operator hints, by field id. */+const NUMERIC_EXAMPLE: Record<string, string> = {+ latency: "2",+ timeToFirstToken: "0.5",+ tokensPerSecond: "50",+ inputTokens: "1000",+ outputTokens: "500",+ totalTokens: "1500",+ inputCost: "0.001",+ outputCost: "0.001",+ totalCost: "0.01",+ promptVersion: "3",+ toolDefinitions: "3",+ toolCalls: "1",+ commentCount: "0",+};++const COMPARISON_LABELS: Array<{ symbol: string; name: string }> = [+ { symbol: ">", name: "greater than" },+ { symbol: ">=", name: "at least" },+ { symbol: "<", name: "less than" },+ { symbol: "<=", name: "at most" },+];++function numberOperatorOptions(+ fieldId: string,+ unit: string | undefined,+ example: string,+): CompletionOption[] {+ const unitNote = unit !== undefined ? ` (${unit})` : "";+ // No explicit `=` entry: a bare value already means equality (`latency:2`),+ // and an `=` option would either insert nothing (a silent dead-end pick) or+ // produce `latency:=2`, which the reverse adapter re-derives to the bare+ // `latency:2` — a visible rewrite echo. Typing the value is the equals path.+ return COMPARISON_LABELS.map(({ symbol, name }) => ({+ id: `vop:${symbol}`,+ kind: "operator",+ label: symbol,+ detail: `${name} — e.g. ${fieldId}:${symbol}${example}${unitNote}`,+ insert: symbol,+ }));+}++function datetimeOperatorOptions(fieldId: string): CompletionOption[] {+ return COMPARISON_LABELS.map(({ symbol, name }) => ({+ id: `vop:${symbol}`,+ kind: "operator",+ label: symbol,+ detail: `${name} — e.g. ${fieldId}:${symbol}2026-06-01`,+ insert: symbol,+ }));+}++// Glob/exact refinements for a value the user has already typed. Match ops are+// positional `*` wildcards, so they WRAP the typed value rather than prefix it+// (you type the value first, then anchor it). Caller only invokes this when+// `typed` is non-empty.+function matchOperatorOptions(+ typed: string,+ negated = false,+): CompletionOption[] {+ // Quote the value through the serializer so a value with whitespace/grammar+ // chars (`My Test`) becomes `*"My Test"*` — one lexer token — instead of a+ // raw `*My Test*` the lexer would tear in half.+ const v = serializeValue(typed);+ const contains: CompletionOption = {+ id: "vop:contains",+ kind: "pattern",+ label: `*${v}*`,+ detail: "contains (same as the bare value)",+ insert: `*${v}*`,+ };+ // Under negation only "contains" is representable (-> "does not contain").+ // Negated starts/ends/exact have no inverse operator, so the validator would+ // reject them on the next derive — don't offer drafts that can't commit.+ if (negated) return [contains];+ return [+ contains,+ {+ id: "vop:starts",+ kind: "pattern",+ label: `${v}*`,+ detail: "starts with",+ insert: `${v}*`,+ },+ {+ id: "vop:ends",+ kind: "pattern",+ label: `*${v}`,+ detail: "ends with",+ insert: `*${v}`,+ },+ {+ id: "vop:exact",+ kind: "pattern",+ label: `=${v}`,+ detail: "exact match",+ insert: `=${v}`,+ },+ ];+}++// ---- key-path suggestions (metadata.*, scores.*, traceScores.*) ----++type PathKind = {+ prefix: string;+ canonical: string;+ level?: "observation" | "trace";+};++// Must mirror fields.ts TRACE_SCORE_PREFIXES / resolveField — every alias the+// parser resolves needs a suggestion entry, or that spelling parses but offers+// no score-name dropdown. (`tracescore.` singular matches the `score.`/`scores.`+// observation-level pair.)+const PATH_PREFIXES: PathKind[] = [+ { prefix: "metadata.", canonical: "metadata." },+ { prefix: "tracescores.", canonical: "traceScores.", level: "trace" },+ { prefix: "trace_scores.", canonical: "traceScores.", level: "trace" },+ { prefix: "tracescore.", canonical: "traceScores.", level: "trace" },+ { prefix: "scores.", canonical: "scores.", level: "observation" },+ { prefix: "score.", canonical: "scores.", level: "observation" },+];++function pathKindOf(+ keyPart: string,+): { kind: PathKind; typedKey: string } | null {+ const lower = keyPart.toLowerCase();+ for (const kind of PATH_PREFIXES) {+ if (lower.startsWith(kind.prefix)) {+ return { kind, typedKey: keyPart.slice(kind.prefix.length) };+ }+ }+ return null;+}++function observedValues(observed: ObservedOptions | undefined, column: string) {+ return observed?.[column] ?? [];+}++function keyPathOptions(+ kind: PathKind,+ typedKey: string,+ observed: ObservedOptions | undefined,+): { title: string; options: CompletionOption[] } {+ // Observed names with grammar chars (a colon, space, …) can't be suggested:+ // picking `scores.foo:bar` would reparse with the key split at the FIRST+ // colon and silently commit a filter on a different/non-existent key. The+ // reverse adapter already drops these (filter-state-to-query NEEDS_QUOTES+ // guards); mirror that here so they're never offered.+ const suggestable = (name: string) => !NEEDS_QUOTES.test(name);+ if (kind.canonical === "metadata.") {+ const options = observedValues(observed, "metadata")+ .filter((o) => suggestable(o.value))+ .map((o) => ({+ id: `key:metadata.${o.value}`,+ kind: "field" as const,+ label: `metadata.${o.value}`,+ detail: o.count !== undefined ? String(o.count) : undefined,+ fieldId: `metadata.${o.value}`,+ }));+ return {+ title: SECTION_KEYS,+ options: rankFilter(options, `metadata.${typedKey}`),+ };+ }+ const numericColumn =+ kind.level === "trace" ? "trace_scores_avg" : "scores_avg";+ const categoricalColumn =+ kind.level === "trace" ? "trace_score_categories" : "score_categories";+ const seen = new Map<string, string>();+ for (const o of observedValues(observed, numericColumn))+ if (suggestable(o.value)) seen.set(o.value, "numeric score");+ for (const o of observedValues(observed, categoricalColumn)) {+ if (!suggestable(o.value)) continue;+ seen.set(+ o.value,+ seen.has(o.value) ? "numeric + categorical score" : "categorical score",+ );+ }+ const options = [...seen.entries()].map(([name, detail]) => ({+ id: `key:${kind.canonical}${name}`,+ kind: "field" as const,+ label: `${kind.canonical}${name}`,+ detail,+ fieldId: `${kind.canonical}${name}`,+ }));+ return {+ title: SECTION_SCORE_NAMES,+ options: rankFilter(options, `${kind.canonical}${typedKey}`),+ };+}++// ---- value-stage planning per resolved field kind ----++type ValueStageInput = {+ ref: FieldRef;+ typed: string;+ valuePrefix: string;+ observed: ObservedOptions | undefined;+ /** Whole-token span, for rewrites that replace the entire `key:value`. */+ tokenSpan: { from: number; to: number };+ /** The token carries a leading `-` (a negated filter). Scope rewrites must be+ * suppressed: tokenSpan covers the `-`, so a rewrite would splice it away and+ * silently flip `does not contain` → `contains` (the complement). */+ negated: boolean;+};++/** Sections for the caret-in-value context, or null when free-form entry. */+function valueStageSections(+ input: ValueStageInput,+): { sections: CompletionSection[]; loading: boolean } | null {+ const { ref, typed, valuePrefix, observed, tokenSpan, negated } = input;++ // An operator prefix was already typed: the rest is free-form entry.+ if (valuePrefix.length > 0) return null;++ switch (ref.type) {+ case "pseudo": {+ // `has` is the only pseudo-field: suggest the nullable fields it can name.+ const all = nullableFields().map((f) => ({+ id: `value:${f.id}`,+ kind: "value" as const,+ label: f.id,+ detail: f.description,+ value: f.id,+ }));+ return {+ sections: section(SECTION_VALUES, valueOptions(all, typed)),+ loading: false,+ };+ }++ case "metadata": {+ if (observed === undefined) return { sections: [], loading: true };+ const all = observedValues(observed, `metadata.${ref.key}`).map((o) => ({+ id: `value:${o.value}`,+ kind: "value" as const,+ label: o.value,+ detail: o.count !== undefined ? String(o.count) : undefined,+ value: o.value,+ }));+ const values = valueOptions(all, typed);+ const ops = typed.length > 0 ? matchOperatorOptions(typed, negated) : [];+ if (values.length + ops.length === 0) return null;+ return {+ sections: [+ ...section(SECTION_VALUES, values),+ ...section(SECTION_MATCH_OPS, ops),+ ],+ loading: false,+ };+ }++ case "scores": {+ if (observed === undefined) return { sections: [], loading: true };+ const numericColumn =+ ref.level === "trace" ? "trace_scores_avg" : "scores_avg";+ const categoricalColumn =+ ref.level === "trace" ? "trace_score_categories" : "score_categories";+ const path =+ ref.level === "trace" ? `traceScores.${ref.key}` : `scores.${ref.key}`;+ const isNumeric = observedValues(observed, numericColumn).some(+ (o) => o.value === ref.key,+ );+ const categories = observedValues(+ observed,+ `${categoricalColumn}.${ref.key}`,+ );+ const sections: CompletionSection[] = [];+ if (categories.length > 0) {+ const all = categories.map((o) => ({+ id: `value:${o.value}`,+ kind: "value" as const,+ label: o.value,+ detail: o.count !== undefined ? String(o.count) : undefined,+ value: o.value,+ }));+ sections.push(...section(SECTION_VALUES, valueOptions(all, typed)));+ }+ if ((isNumeric || categories.length === 0) && typed.length === 0) {+ sections.push(+ ...section(+ SECTION_COMPARE_OPS,+ numberOperatorOptions(path, undefined, "0.8"),+ ),+ );+ }+ if (sections.length === 0) return null;+ return { sections, loading: false };+ }++ case "field": {+ const f = ref.field;+ if (f.kind === "boolean") {+ const all = [+ {+ id: "value:true",+ kind: "value" as const,+ label: "true",+ value: "true",+ },+ {+ id: "value:false",+ kind: "value" as const,+ label: "false",+ value: "false",+ },+ ];+ return {+ sections: section(SECTION_VALUES, valueOptions(all, typed)),+ loading: false,+ };+ }+ if (f.kind === "number") {+ if (typed.length > 0) return null; // free numeric entry+ const example = NUMERIC_EXAMPLE[f.id] ?? "10";+ return {+ sections: section(+ SECTION_COMPARE_OPS,+ numberOperatorOptions(f.id, f.unit, example),+ ),+ loading: false,+ };+ }+ if (f.kind === "datetime") {+ if (typed.length > 0) return null;+ return {+ sections: section(SECTION_COMPARE_OPS, datetimeOperatorOptions(f.id)),+ loading: false,+ };+ }+ // text. A pure textSearch field (input/output) has no value list; an+ // observed-value picker is offered only when `suggestObservedValues` is+ // set (id/name), which fall through to the picker branch below.+ if (f.syncMode === "textSearch" && !f.suggestObservedValues) {+ // No enumerable values. Once a value is typed, offer glob/exact+ // refinements that wrap it (bare value already means contains).+ if (typed.length === 0) return null;+ // input:/output: are full-text scopes too, so also offer switching the+ // whole token to the other scope. NOT when negated: tokenSpan covers the+ // leading `-`, so the rewrite would drop it and flip the filter to its+ // complement (mirrors the free-text → scope path, gated on !negated).+ const scopeSwitches =+ !negated && (f.id === "input" || f.id === "output")+ ? scopeSwitchOptions(f.id, typed, tokenSpan)+ : [];+ return {+ sections: [+ ...section(SECTION_MATCH_OPS, matchOperatorOptions(typed, negated)),+ ...section(SECTION_SEARCH_IN, scopeSwitches),+ ],+ loading: false,+ };+ }+ // Observed-value picker: exactOption/arrayOption fields, plus textSearch+ // fields flagged `suggestObservedValues` (id/name — they search as+ // substring but still suggest existing values).+ if (observed === undefined) return { sections: [], loading: true };+ const all = observedValues(observed, f.id).map((o) => ({+ id: `value:${o.value}`,+ kind: "value" as const,+ label: o.value,+ detail: o.count !== undefined ? String(o.count) : undefined,+ value: o.value,+ }));+ const values = valueOptions(all, typed);+ // Array fields reject match operators — operatorIssue routes them to+ // value/any-of/all-of groups — so don't suggest them. For other option+ // fields, once a value is typed offer glob/exact refinements that wrap it.+ // Pass `negated` so a negated value only offers contains (the lone+ // refinement with an inverse op), mirroring the metadata/textSearch sites.+ const ops =+ typed.length > 0 && f.syncMode !== "arrayOption"+ ? matchOperatorOptions(typed, negated)+ : [];+ if (values.length + ops.length === 0) return null;+ return {+ sections: [+ ...section(SECTION_VALUES, values),+ ...section(SECTION_MATCH_OPS, ops),+ ],+ loading: false,+ };+ }+ }+}++/**+ * Strip surrounding quotes from a value token so it matches observed values.+ * A closed pair (`"My Tag"`) unescapes `\"`/`\\` like the parser's unquote; a+ * lone leading quote (mid-typing, no closing quote yet) is just stripped.+ * Stripping only the leading quote left a stray trailing one, so quoted values+ * matched nothing and the value-stage popover vanished on switch.+ */+function stripValueQuotes(raw: string): string {+ return raw.length >= 2 && raw.startsWith('"') && raw.endsWith('"')+ ? raw.slice(1, -1).replace(/\\(["\\])/g, "$1")+ : raw.replace(/^"/, "");+}++function groupedValueSegment(+ valuePart: string,+ relValuePos: number,+ valueStart: number,+): { from: number; to: number; typed: string; completeGroup: boolean } | null {+ if (!valuePart.startsWith("(") || relValuePos <= 0) return null;+ const close = indexOfOutsideQuotes(valuePart, ")");+ const groupEnd = close === -1 ? valuePart.length : close;+ if (relValuePos > groupEnd) return null;++ const inner = valuePart.slice(1, groupEnd);+ const innerCaret = Math.max(0, Math.min(relValuePos - 1, inner.length));+ let fromInner = 0;+ let toInner = inner.length;++ for (const token of lexTokens(inner)) {+ if (token.type !== "term" || (token.raw !== "OR" && token.raw !== "AND"))+ continue;+ if (token.span.to <= innerCaret) {+ fromInner = token.span.to;+ continue;+ }+ if (token.span.from >= innerCaret) {+ toInner = token.span.from;+ break;+ }+ }++ while (fromInner < toInner && /\s/.test(inner[fromInner]!)) fromInner++;+ while (toInner > fromInner && /\s/.test(inner[toInner - 1]!)) toInner--;++ return {+ from: valueStart + 1 + fromInner,+ to: valueStart + 1 + toInner,+ typed: stripValueQuotes(inner.slice(fromInner, toInner)),+ completeGroup: close !== -1,+ };+}++export type InputCompletionContext = {+ /** Active input text (the token(s) being typed). */+ input: string;+ /** Caret offset within `input`. */+ caret: number;+ /** Observed facet values; undefined = still loading. */+ observed: ObservedOptions | undefined;+ recents: string[];+ /** Full committed/draft query text (recents identical to it are hidden). */+ currentQueryText: string;+};++// The contiguous free-text run containing `caret` — the same block the composer+// coalesces visually. A scope rewrite (input:/output:) wraps this WHOLE run, not+// just the token under the caret, so picking it on a multi-word block produces+// `input:"abc abc abc"` rather than an `input:abc` that strands the rest as free+// text. Returns null when the caret isn't on a bare free-text word.+function freeTextRun(+ input: string,+ caret: number,+): { from: number; to: number; text: string } | null {+ // A bare token (no `:`) is free text regardless of whether it collides with a+ // field alias — the parser (parseTermNode) and composer (coalesceFreeText)+ // both treat `tags`/`env`/… as text, so the run must too. Without this, a run+ // like `tags hello` stops expanding at `tags`, the scope rewrite wraps only+ // `hello`, and picking `input:hello` would strand `tags` as separate free text.+ const isFreeText = (raw: string) =>+ !raw.startsWith("-") &&+ indexOfOutsideQuotes(raw, ":") === -1 &&+ !["AND", "OR", "NOT"].includes(raw);+ const terms = lexTokens(input).filter((t) => t.type === "term");+ const idx = terms.findIndex(+ (t) => caret >= t.span.from && caret <= t.span.to,+ );+ if (idx === -1 || !isFreeText(terms[idx]!.raw)) return null;+ // Expand over adjacent free-text terms separated only by whitespace (a paren+ // or any other token between two words breaks the run).+ let lo = idx;+ let hi = idx;+ const gapIsBlank = (a: number, b: number) => input.slice(a, b).trim() === "";+ while (+ lo > 0 &&+ isFreeText(terms[lo - 1]!.raw) &&+ gapIsBlank(terms[lo - 1]!.span.to, terms[lo]!.span.from)+ )+ lo--;+ while (+ hi < terms.length - 1 &&+ isFreeText(terms[hi + 1]!.raw) &&+ gapIsBlank(terms[hi]!.span.to, terms[hi + 1]!.span.from)+ )+ hi++;+ const from = terms[lo]!.span.from;+ const to = terms[hi]!.span.to;+ // `text` is the LOGICAL phrase: each term unquoted and joined by single+ // spaces — NOT the raw slice. So a run that already mixes a quoted phrase with+ // bare words (`"abc abc" abc`) reconstructs to `abc abc abc`, and the scope+ // rewrite re-serializes it as ONE clean `"abc abc abc"` instead of compounding+ // escaped quotes (`"abc abc\" abc"`). `from`/`to` stay the raw span so the+ // pick replaces the whole run, original quotes and all.+ const text = terms+ .slice(lo, hi + 1)+ .map((t) => stripValueQuotes(t.raw))+ .join(" ");+ return { from, to, text };+}++// The full-text scopes the bar can switch a value between. `default` is bare+// free text (ids, names, input & output); input:/output: are the scoped forms.+type FullTextScope = "default" | "input" | "output";++// Switch options that move a full-text value between scopes, carrying the value+// and replacing the WHOLE token/run (replaceSpan). Used in both directions:+// forward (bare text → input:/output:) and back/between (input:/output: → each+// other or default). `value` is the raw (unquoted) text; it's serialized so a+// multi-word phrase stays one token.+//+// `keepCurrentFirst` keeps the current scope in the list, listed first, instead+// of excluding it: for bare free text it surfaces the typed text itself as an+// explicit "this is the default-scope search" option (the anchor) ahead of the+// input:/output: rewrites. Value-stage switches leave it off, so an `input:`+// value never offers a no-op switch back to `input:`.+function scopeSwitchOptions(+ current: FullTextScope,+ value: string,+ span: { from: number; to: number },+ opts?: { keepCurrentFirst?: boolean },+): CompletionOption[] {+ const v = serializeValue(value);+ const defs: { scope: FullTextScope; insert: string; detail: string }[] = [+ {+ scope: "input",+ insert: `input:${v}`,+ detail: "search only the input payload",+ },+ {+ scope: "output",+ insert: `output:${v}`,+ detail: "search only the output payload",+ },+ {+ scope: "default",+ insert: v,+ detail: "default: ids, names, input & output",+ },+ ];+ const ordered = opts?.keepCurrentFirst+ ? [+ ...defs.filter((d) => d.scope === current),+ ...defs.filter((d) => d.scope !== current),+ ]+ : defs.filter((d) => d.scope !== current);+ return ordered.map((d) => ({+ id: `scope:${d.scope}`,+ kind: "pattern" as const,+ label: d.insert,+ detail: d.detail,+ insert: d.insert,+ replaceSpan: span,+ }));+}++/**+ * The completion plan for the caret context, or null when nothing matches.+ * The plan is a pure function of (text, caret, data) — never of HOW the+ * popover was opened. An empty term (empty bar, trailing blank, after an+ * operator, after delete-to-empty) always plans the empty stage; a key+ * position plans fields; a value position plans values.+ */+export function planInputCompletions(+ ctx: InputCompletionContext,+): CompletionPlan | null {+ const { input, caret } = ctx;++ const term = termAt(input, caret);+ const start = term?.from ?? caret;+ const token = term?.raw ?? "";++ const negated = token.startsWith("-");+ const tokenBody = negated ? token.slice(1) : token;+ const bodyStart = start + (negated ? 1 : 0);+ const colon = indexOfOutsideQuotes(tokenBody, ":");+ const relPos = caret - bodyStart;++ if (colon === -1 || relPos <= colon) {+ // Key / keyword stage (also the key part of an existing filter).+ const to = colon === -1 ? (term?.to ?? caret) : bodyStart + colon;++ if (token.length === 0) {+ // Empty-term state: ready-to-run query suggestions first, then fields,+ // recents last — operators and patterns are noise here.+ return {+ stage: "empty",+ from: bodyStart,+ to,+ loading: false,+ sections: [+ ...section(SECTION_SUGGESTIONS, querySuggestionOptions(ctx.observed)),+ ...section(SECTION_FIELDS, fieldOptions()),+ ...section(+ SECTION_RECENT,+ recentOptions(ctx.recents, ctx.currentQueryText),+ ),+ ],+ };+ }++ // Inside an existing filter, rank against the key part only — the caret+ // is in the key, so "level:ERROR" suggests fields matching "level".+ const keyPart = colon === -1 ? tokenBody : tokenBody.slice(0, colon);++ // Dot paths (metadata./scores./traceScores.) suggest observed keys.+ const path = pathKindOf(keyPart);+ if (path !== null) {+ const { title, options } = keyPathOptions(+ path.kind,+ path.typedKey,+ ctx.observed,+ );+ if (options.length === 0 && ctx.observed === undefined) {+ return {+ stage: "field",+ from: bodyStart,+ to,+ loading: true,+ sections: [],+ };+ }+ if (options.length === 0) return null;+ return {+ stage: "field",+ from: bodyStart,+ to,+ loading: false,+ autoHighlight: path.typedKey.length > 0,+ sections: [{ title, options }],+ };+ }++ const resolvedKey = colon === -1 ? null : resolveField(keyPart);+ // The COMPLETE key of an existing filter is a switcher (like a complete+ // value): offer every field, current one first, and leave Enter unarmed.+ // A partial key prefix-filters and arms Enter-to-complete.+ const allFields = fieldOptions();+ const fields =+ resolvedKey !== null+ ? (() => {+ const currentId =+ resolvedKey.type === "field" ? resolvedKey.field.id : keyPart;+ const index = allFields.findIndex(+ (o) => o.kind === "field" && o.fieldId === currentId,+ );+ return index === -1+ ? allFields+ : [+ allFields[index]!,+ ...allFields.slice(0, index),+ ...allFields.slice(index + 1),+ ];+ })()+ : rankFilter(allFields, keyPart);+ const operators =+ colon === -1 ? rankFilter(OPERATOR_OPTIONS, tokenBody) : [];+ const patterns =+ colon === -1+ ? rankFilter(PATTERN_OPTIONS, tokenBody).filter(+ // The term already starts with `-`; the negation pattern carries+ // its own `-`, so suggesting it would splice `--environment:`.+ (p) => !(negated && p.id === "pat:negation"),+ )+ : [];+ // Free-text guidance: a bare word (or a coalesced multi-word run) can become+ // a scoped full-text search. The rewrite wraps the WHOLE run — so it scopes+ // the block the user sees, not one word — and quotes via serializeValue so a+ // multi-word phrase stays one token. Strip any quotes the user already typed+ // (`"hello world"`) first, mirroring the value-stage path, so serializeValue+ // re-quotes once instead of emitting a doubly-quoted `input:"\"…\""`.+ const run =+ colon === -1 && !negated+ ? freeTextRun(ctx.currentQueryText, caret)+ : null;+ const searchScopes: CompletionOption[] =+ run !== null+ ? scopeSwitchOptions(+ "default",+ // run.text is already the logical (unquoted) phrase; serializeValue+ // re-quotes it once.+ run.text,+ { from: run.from, to: run.to },+ // Surface the typed text itself (default scope) as the first option,+ // ahead of the input:/output: rewrites.+ { keepCurrentFirst: true },+ )+ : [];+ if (+ fields.length ++ operators.length ++ patterns.length ++ searchScopes.length ===+ 0+ )+ return null;+ return {+ stage: "field",+ from: bodyStart,+ to,+ loading: false,+ // Arm Enter on a field only when a bare word EXACTLY names a field+ // (id/alias) — `name` → `name:`. A mere prefix/substring match (`n`,+ // `ess`) must NOT hijack Enter: the user is likely typing a free-text+ // search (e.g. `ess` to find "messages"), so Enter commits the text. The+ // field still appears in the dropdown for arrow/click selection. Inside an+ // existing `key:` (caret before the colon) the prefix-complete behavior is+ // unchanged.+ autoHighlight:+ colon === -1+ ? resolveField(keyPart) !== null+ : resolvedKey === null && fields.length > 0,+ sections: [+ ...section(SECTION_FIELDS, fields),+ ...section(SECTION_OPERATORS, operators),+ ...section(SECTION_PATTERNS, patterns),+ ...section(SECTION_SEARCH_IN, searchScopes),+ ],+ };+ }++ // Value stage: complete the comma segment under the caret.+ const keyRaw = tokenBody.slice(0, colon);+ const ref = resolveField(keyRaw);+ if (ref === null) return null;++ const valuePart = tokenBody.slice(colon + 1);+ const relValuePos = relPos - colon - 1;+ const valueStart = bodyStart + colon + 1;+ const grouped = groupedValueSegment(valuePart, relValuePos, valueStart);+ const segments = grouped === null ? splitOutsideQuotes(valuePart, ",") : [];+ const seg =+ grouped === null+ ? (segments.find(+ (s) =>+ relValuePos >= s.offset && relValuePos <= s.offset + s.text.length,+ ) ?? segments[segments.length - 1]!)+ : null;+ const segFromBase = grouped?.from ?? valueStart + seg!.offset;+ const activeValueText = grouped?.typed ?? seg!.text;+ // Comparison/exact operator prefixes belong to the op, not the typed value,+ // and put the value into free-form entry (valueStageSections bails on them).+ // This set MUST mirror langQ's OPERATOR_PREFIXES (>= <= > < =) — nothing more.+ // After the glob migration `~`/`^`/`$` are LITERAL value chars (not ops) and+ // `*` is a positional glob ANCHOR: treating any of them as a prefix wrongly+ // suppressed the popover for the canonical `name:*chat*` contains form. The+ // glob is instead unwrapped to its bare core below so the value stage stays+ // live and offers re-scope / re-form suggestions.+ const valuePrefix =+ grouped === null+ ? (activeValueText.match(/^(>=|<=|>|<|=)/)?.[0] ?? "")+ : "";+ const glob =+ grouped === null && valuePrefix === "" ? parseGlob(activeValueText) : null;+ const segFrom = segFromBase + valuePrefix.length;+ const segTo = grouped?.to ?? segFromBase + seg!.text.length;+ // Drop quotes so the typed text matches observed values (both the grouped+ // and non-grouped value segments go through the same helper). For a glob+ // value the typed text is the bare core inside the `*`s.+ const typed = stripValueQuotes(+ glob !== null ? glob.core : activeValueText.slice(valuePrefix.length),+ );+ const groupedPlanAttrs =+ grouped === null ? {} : { keepOpenOnPick: !grouped.completeGroup };++ const staged = valueStageSections({+ ref,+ typed,+ valuePrefix,+ observed: ctx.observed,+ tokenSpan: { from: start, to: term?.to ?? caret },+ negated,+ });+ if (staged === null) return null;+ if (staged.loading) {+ return {+ stage: "value",+ from: segFrom,+ to: segTo,+ loading: true,+ sections: [],+ ...groupedPlanAttrs,+ };+ }+ const flatValues = staged.sections+ .flatMap((s) => s.options)+ .filter((o) => o.kind === "value");+ return {+ stage: "value",+ from: segFrom,+ to: segTo,+ loading: false,+ // Partial typed values arm Enter-to-complete; an exact-complete value is+ // a switcher (Enter commits, the list is for browsing alternatives).+ autoHighlight:+ typed.length > 0 &&+ flatValues.length > 0 &&+ !flatValues.some((o) => o.kind === "value" && o.value === typed),+ sections: staged.sections,+ ...groupedPlanAttrs,+ };+}++/** Flat option list in render order (keyboard navigation walks this). */+export function flattenOptions(+ plan: CompletionPlan | null,+): CompletionOption[] {+ if (plan === null) return [];+ return plan.sections.flatMap((s) => s.options);+}diff --git a/web/src/features/search-bar/lib/composer-segments.ts b/web/src/features/search-bar/lib/composer-segments.tsnew file mode 100644index 0000000000..65f8a4e549--- /dev/null+++ b/web/src/features/search-bar/lib/composer-segments.ts@@ -0,0 +1,263 @@+// Segment projection — pure mapping from draft text to renderable composer+// segments.+//+// Segments are a token-level VIEW over the draft string: spans are offsets+// into the text, `raw` is the verbatim slice, and the projection never+// rewrites text. Token boundaries come from the real lexer and classification+// from the real parser + semantic validation, so the projection cannot drift+// from grammar semantics. Serialization stays separate and conservative+// (langQ.ts, edits.ts).++import type { ScoreTypeContext } from "./adapter";+import type { ASTNode, FilterNode, Span, TextNode } from "./ast";+import { lexTokens, type Diagnostic } from "./langQ";+import { validateQuery } from "./validate";++export type FilterSegment = {+ id: string;+ kind: "filter";+ from: number;+ to: number;+ raw: string;+ /** The key as the user typed it (alias/casing) — pills display this. */+ displayField: string;+ /** Parsed values — used to color numeric values distinctly. */+ values: string[];+ negated: boolean;+ editable: true;+};++export type PlainSegment = {+ id: string;+ kind: "freeText" | "operator" | "paren";+ from: number;+ to: number;+ raw: string;+ editable: boolean;+};++export type InvalidSegment = {+ id: string;+ kind: "invalid";+ from: number;+ to: number;+ raw: string;+ message: string;+ editable: true;+};++export type ComposerSegment = FilterSegment | PlainSegment | InvalidSegment;++// IDs derive from span + raw text (never array index alone) — appending+// tokens keeps earlier IDs stable; editing a token changes its own.+function segmentId(+ kind: ComposerSegment["kind"],+ span: Span,+ raw: string,+): string {+ return `${kind}:${span.from}:${raw}`;+}++// ---- AST leaf collection ----++type Leaf =+ | { span: Span; kind: "filter"; node: FilterNode; negated: boolean }+ | { span: Span; kind: "text"; node: TextNode };++function collectLeaves(node: ASTNode, text: string, out: Leaf[]): void {+ switch (node.kind) {+ case "filter":+ if (node.span)+ out.push({ span: node.span, kind: "filter", node, negated: false });+ return;+ case "text":+ if (node.span) out.push({ span: node.span, kind: "text", node });+ return;+ case "not":+ // "-env:dev" is one lexer term (the NOT span starts at the dash) → one+ // negated filter leaf. "NOT level:DEBUG" recurses: NOT is its own+ // keyword token (an operator segment), the child pills separately.+ if (+ node.child.kind === "filter" &&+ node.span &&+ text[node.span.from] === "-"+ ) {+ out.push({+ span: node.span,+ kind: "filter",+ node: node.child,+ negated: true,+ });+ return;+ }+ collectLeaves(node.child, text, out);+ return;+ case "and":+ case "or":+ for (const c of node.children) collectLeaves(c, text, out);+ return;+ }+}++function isKeywordTerm(raw: string): boolean {+ return raw === "AND" || raw === "OR" || raw === "NOT";+}++function overlappingErrors(diagnostics: Diagnostic[], span: Span): string[] {+ const messages: string[] = [];+ for (const d of diagnostics) {+ if (d.severity !== "error") continue;+ if (d.from < span.to && d.to > span.from && !messages.includes(d.message)) {+ messages.push(d.message);+ }+ }+ return messages;+}++// ---- projection ----++// One-slot memo: the composer and its consumers all derive from the same+// draft text within a render pass. Keyed on scoreTypes too, since it changes+// which `scores.<name>` tokens classify as invalid (callers pass a stable,+// memoized scoreTypes so the cache still hits across renders).+let cacheKey: string | null = null;+let cacheScoreTypes: ScoreTypeContext | undefined;+let cacheVal: ComposerSegment[] = [];++/**+ * Project `draftText` to renderable segments. Pure and total: never throws,+ * never rewrites text; every segment's `raw` is the verbatim slice of its+ * span and segments are ordered, non-overlapping, and cover every token.+ *+ * Classification per token:+ * 1. overlapped by an error diagnostic (parse OR semantic) → invalid+ * 2. parenthesis → paren, AND/OR/NOT keyword → operator (both non-editable)+ * 3. matches a filter AST leaf (incl. `-key:value` negation) → filter+ * 4. otherwise → freeText+ */+export function deriveComposerSegments(+ draftText: string,+ scoreTypes?: ScoreTypeContext,+): ComposerSegment[] {+ if (draftText === cacheKey && scoreTypes === cacheScoreTypes) return cacheVal;++ const { ast, diagnostics } = validateQuery(draftText, scoreTypes);+ const leaves: Leaf[] = [];+ if (ast !== null) collectLeaves(ast, draftText, leaves);+ const leafByFrom = new Map<number, Leaf>();+ for (const leaf of leaves) leafByFrom.set(leaf.span.from, leaf);++ const segments: ComposerSegment[] = [];+ for (const token of lexTokens(draftText)) {+ const { span } = token;+ const raw = draftText.slice(span.from, span.to);++ const messages = overlappingErrors(diagnostics, span);+ if (messages.length > 0) {+ segments.push({+ id: segmentId("invalid", span, raw),+ kind: "invalid",+ from: span.from,+ to: span.to,+ raw,+ message: messages.join("; "),+ editable: true,+ });+ continue;+ }++ if (token.type === "lparen" || token.type === "rparen") {+ segments.push({+ id: segmentId("paren", span, raw),+ kind: "paren",+ from: span.from,+ to: span.to,+ raw,+ editable: false,+ });+ continue;+ }++ if (isKeywordTerm(token.raw)) {+ segments.push({+ id: segmentId("operator", span, raw),+ kind: "operator",+ from: span.from,+ to: span.to,+ raw,+ editable: false,+ });+ continue;+ }++ const leaf = leafByFrom.get(span.from);+ if (+ leaf !== undefined &&+ leaf.kind === "filter" &&+ leaf.span.to === span.to+ ) {+ const node = leaf.node;+ segments.push({+ id: segmentId("filter", span, raw),+ kind: "filter",+ from: span.from,+ to: span.to,+ raw,+ displayField: node.rawKey ?? node.key,+ values: node.values,+ negated: leaf.negated,+ editable: true,+ });+ continue;+ }++ // Free text (and the defensive fallback for tokens the tolerant parser+ // absorbed without a matching leaf — they still render and stay editable).+ segments.push({+ id: segmentId("freeText", span, raw),+ kind: "freeText",+ from: span.from,+ to: span.to,+ raw,+ editable: true,+ });+ }++ const coalesced = coalesceFreeText(segments, draftText);+ cacheKey = draftText;+ cacheScoreTypes = scoreTypes;+ cacheVal = coalesced;+ return coalesced;+}++// Contiguous free-text words are ONE phrase semantically: they lower to a+// single `searchQuery` and the backend matches them as a contiguous substring+// (ILIKE %phrase%), not as independent AND terms. So `abc abc abc` must read as+// one chip, not three identical blocks. Merge runs of adjacent free-text+// segments (the lexer only separates them by whitespace) into a single span+// covering the whole phrase, internal spaces included.+function coalesceFreeText(+ segments: ComposerSegment[],+ text: string,+): ComposerSegment[] {+ const out: ComposerSegment[] = [];+ for (const seg of segments) {+ const prev = out[out.length - 1];+ if (seg.kind === "freeText" && prev?.kind === "freeText") {+ const from = prev.from;+ const to = seg.to;+ const raw = text.slice(from, to);+ out[out.length - 1] = {+ id: segmentId("freeText", { from, to }, raw),+ kind: "freeText",+ from,+ to,+ raw,+ editable: true,+ };+ continue;+ }+ out.push(seg);+ }+ return out;+}diff --git a/web/src/features/search-bar/lib/edits.clienttest.ts b/web/src/features/search-bar/lib/edits.clienttest.tsnew file mode 100644index 0000000000..b4de1ddb5a--- /dev/null+++ b/web/src/features/search-bar/lib/edits.clienttest.ts@@ -0,0 +1,65 @@+import { describe, expect, it } from "vitest";++import { removeToken } from "./edits";++function spanOf(text: string, token: string) {+ const from = text.indexOf(token);+ return { from, to: from + token.length };+}++describe("removeToken — semantic preservation", () => {+ // A bare parse check is not enough: removing `level:ERROR` from+ // `NOT level:ERROR env:dev` splices to `NOT env:dev`, which parses fine but+ // re-binds the stranded NOT keyword onto env:dev and silently inverts its+ // polarity. The removal must collapse the orphaned NOT instead.+ it("collapses a stranded NOT keyword instead of re-binding it to the neighbor", () => {+ const text = "NOT level:ERROR env:dev";+ expect(removeToken(text, spanOf(text, "level:ERROR"))).toBe("env:dev");+ });++ it("removes the whole dash-form negation pill", () => {+ const text = "-level:ERROR env:dev";+ expect(removeToken(text, spanOf(text, "-level:ERROR"))).toBe("env:dev");+ });++ it("keeps a surviving invalid `-foo` as-is instead of stripping the dash", () => {+ // `-foo` is an invalid free-text negation. Removing the neighbor must leave+ // `-foo` exactly (still red), NOT silently canonicalize to `foo` and commit+ // a free-text search the user never confirmed.+ const text = "-foo level:ERROR";+ expect(removeToken(text, spanOf(text, "level:ERROR"))).toBe("-foo");+ const text2 = "level:ERROR -foo";+ expect(removeToken(text2, spanOf(text2, "level:ERROR"))).toBe("-foo");+ });++ it("splices a plain adjacent filter, preserving the neighbor unchanged", () => {+ const text = "level:ERROR env:dev";+ expect(removeToken(text, spanOf(text, "level:ERROR"))).toBe("env:dev");+ });++ it("keeps a negated neighbor negated when removing an earlier filter", () => {+ const text = "level:ERROR -env:dev";+ expect(removeToken(text, spanOf(text, "level:ERROR"))).toBe("-env:dev");+ });++ // A coalesced free-text chip spans several text leaves; its × target span+ // matches none of them exactly, so removal must drop the contained leaves.+ it("removes a multi-word free-text chip as one unit", () => {+ expect(+ removeToken("refund policy", spanOf("refund policy", "refund policy")),+ ).toBe("");+ const text = "level:ERROR refund policy";+ expect(removeToken(text, spanOf(text, "refund policy"))).toBe(+ "level:ERROR",+ );+ });++ // An invalid `-foo` free-text-negation chip: the × target token span includes+ // the leading dash, but the inner text leaf's span does not — removal must+ // still drop the whole token, not strip the dash and keep `foo`.+ it("removes an invalid -word negation chip whole, not just the dash", () => {+ expect(removeToken("-foo", spanOf("-foo", "-foo"))).toBe("");+ const text = "level:ERROR -foo";+ expect(removeToken(text, spanOf(text, "-foo"))).toBe("level:ERROR");+ });+});diff --git a/web/src/features/search-bar/lib/edits.ts b/web/src/features/search-bar/lib/edits.tsnew file mode 100644index 0000000000..c43613034a--- /dev/null+++ b/web/src/features/search-bar/lib/edits.ts@@ -0,0 +1,183 @@+// Span-local structured edits over query text, with an AST-surgery fallback.+//+// Primary path: rewrite the smallest relevant slice of the text, preserving+// the user's aliases and surrounding formatting. Every result is re-parsed;+// if a splice would leave invalid text (removing a token from inside a group,+// stranding empty parens, …) the edit falls back to AST surgery + canonical+// reserialize — structured edits NEVER produce an uncommittable string.++import type { ASTNode, Span } from "./ast";+import { astEquals, removeNodeBySpan } from "./ast";+import { findClosingQuote, parse, serialize } from "./langQ";++function spliceSpan(+ text: string,+ from: number,+ to: number,+ replacement: string,+): string {+ let start = from;+ let end = to;+ if (replacement === "") {+ // Swallow one adjacent separator space so we don't leave double gaps.+ if (start > 0 && text[start - 1] === " ") start--;+ else if (end < text.length && text[end] === " ") end++;+ }+ return (text.slice(0, start) + replacement + text.slice(end)).trim();+}++/**+ * Splice, then verify; fall back to AST surgery when the splice is unsafe.+ *+ * A parse check alone is not enough: a splice can stay syntactically valid yet+ * change the semantics of the *untouched* subtrees. Removing `level:ERROR`+ * from `NOT level:ERROR env:dev` splices to `NOT env:dev`, which parses — but+ * the orphaned `NOT` keyword re-binds to `env:dev` and silently flips its+ * polarity. So accept the splice only when it reparses into the same AST as+ * the surgical removal (which collapses the stranded `NOT`); otherwise+ * reserialize the surgery result.+ */+function removeWithFallback(+ text: string,+ ast: ASTNode,+ span: Span,+ originalValid: boolean,+): string {+ const surgical = removeNodeBySpan(ast, span);+ const spliced = spliceSpan(text, span.from, span.to, "");+ const reparsed = parse(spliced);+ // Accept the splice when it reparses to the SAME AST as the surgical removal+ // AND it is no worse than before: either valid, or the query was ALREADY+ // invalid so we're not introducing breakage. The latter preserves a fragment+ // the user typed and the parser flags — `-foo` stays `-foo` (red), not+ // silently canonicalized to a `foo` search the user never confirmed. A splice+ // that NEWLY breaks a previously-valid query (a stranded `(OR …)`, empty+ // parens) or whose AST differs (a stranded NOT rebinding onto the neighbor)+ // reserializes the clean surgical AST instead.+ if (astEquals(reparsed.ast, surgical) && (reparsed.valid || !originalValid)) {+ return spliced;+ }+ return serialize(surgical);+}++function scanParenPairs(text: string): Array<{ open: number; close: number }> {+ const stack: number[] = [];+ const pairs: Array<{ open: number; close: number }> = [];+ let i = 0;+ while (i < text.length) {+ const c = text[i]!;+ if (c === '"') {+ const close = findClosingQuote(text, i);+ i = close === -1 ? text.length : close + 1;+ continue;+ }+ if (c === "(") stack.push(i);+ else if (c === ")") {+ const open = stack.pop();+ if (open !== undefined) pairs.push({ open, close: i });+ }+ i++;+ }+ return pairs;+}++/** Collapse whitespace runs to single spaces — never inside quotes. */+function collapseSpacesOutsideQuotes(text: string): string {+ let out = "";+ let pendingSpace = false;+ let i = 0;+ while (i < text.length) {+ const c = text[i]!;+ if (/\s/.test(c)) {+ pendingSpace = true;+ i++;+ continue;+ }+ if (pendingSpace && out.length > 0) out += " ";+ pendingSpace = false;+ if (c === '"') {+ const close = findClosingQuote(text, i);+ const end = close === -1 ? text.length : close + 1;+ out += text.slice(i, end);+ i = end;+ continue;+ }+ out += c;+ i++;+ }+ return out;+}++/**+ * Normalize a structured-edit result: collapse whitespace and strip paren+ * pairs that are PROVABLY redundant — a pair is removed only when the text+ * still parses and the AST is structurally identical, so necessary grouping+ * can never be lost. Only structured edits normalize; typed text is+ * preserved as-is.+ */+export function tidyQueryText(text: string): string {+ let current = collapseSpacesOutsideQuotes(text).trim();+ let parsed = parse(current);+ if (!parsed.valid) return current;++ let changed = true;+ while (changed) {+ changed = false;+ for (const { open, close } of scanParenPairs(current)) {+ const candidate = collapseSpacesOutsideQuotes(+ current.slice(0, open) ++ current.slice(open + 1, close) ++ current.slice(close + 1),+ ).trim();+ const res = parse(candidate);+ if (res.valid && astEquals(res.ast, parsed.ast)) {+ current = candidate;+ parsed = res;+ changed = true;+ break; // pair indices shifted — rescan+ }+ }+ }+ return current;+}++function findParenExtent(node: ASTNode, target: Span): Span | null {+ const ownSpan =+ node.kind === "and" || node.kind === "or" ? undefined : node.span;+ if (+ ownSpan !== undefined &&+ ownSpan.from === target.from &&+ ownSpan.to === target.to+ ) {+ return node.parenSpan ?? null;+ }+ switch (node.kind) {+ case "filter":+ case "text":+ return null;+ case "not":+ return findParenExtent(node.child, target);+ case "and":+ case "or":+ for (const c of node.children) {+ const found = findParenExtent(c, target);+ if (found !== null) return found;+ }+ return null;+ }+}++/**+ * Remove the token at `span` from `text` (composer pill × / keyboard+ * removal). Span-local splice first; AST surgery + reserialize when the+ * splice would not reparse.+ */+export function removeToken(text: string, span: Span): string {+ const parsed = parse(text);+ if (parsed.ast === null) return text;+ // Prefer the paren extent when the span identifies a parenthesized node.+ const target = findParenExtent(parsed.ast, span) ?? span;+ return tidyQueryText(+ removeWithFallback(text, parsed.ast, target, parsed.valid),+ );+}diff --git a/web/src/features/search-bar/lib/fields.ts b/web/src/features/search-bar/lib/fields.tsnew file mode 100644index 0000000000..b90f1f8dce--- /dev/null+++ b/web/src/features/search-bar/lib/fields.ts@@ -0,0 +1,332 @@+// Field registry — the single source of truth for autocomplete, validation,+// operator choice, and lowering into the flat Langfuse `FilterState`.+//+// Field ids/kinds mirror the v4 events table column definitions+// (packages/shared/src/eventsTable.ts) and the observations-events filter+// config (web/src/features/events/config/filter-config.ts). The registry only+// expresses what the existing events tRPC contract accepts today — the+// adapter never emits a filter shape the sidebar could not produce.+//+// Sync modes:+// exactOption — option-backed column; '=' lowers to stringOptions any-of+// arrayOption — array column (traceTags, toolNames); supports all-of+// textSearch — plain text/number/datetime column; '=' lowers to contains+//+// `syncMode` drives the LOWERING shape; `suggestObservedValues` drives the+// AUTOCOMPLETE picker independently — `id`/`name` are textSearch (so `id:abc`+// is a substring search) yet keep their observed-value picker.++import type { CompareOp } from "./ast";++export type FieldKind = "text" | "number" | "datetime" | "boolean";+export type SyncMode = "exactOption" | "arrayOption" | "textSearch";++export type FieldDef = {+ /** Canonical field id; also the filter `column` sent to the API. */+ id: string;+ /** Lowercase aliases accepted by the grammar (canonical id always works too). */+ aliases: string[];+ kind: FieldKind;+ syncMode: SyncMode;+ description: string;+ /** Display unit for numeric suggestion labels (filter-config units). */+ unit?: string;+ /** Column can be unset in the dataset — `has:`/`-has:` (null checks) apply. */+ nullable?: boolean;+ /**+ * Offer the observed-value picker in autocomplete even when `syncMode` is+ * `textSearch` (which otherwise has no value list). Lets `id`/`name` search+ * as substring while still suggesting existing values. Implied for+ * `exactOption`; only set this on `textSearch` fields that should suggest.+ */+ suggestObservedValues?: boolean;+};++// prettier-ignore+export const FIELDS: FieldDef[] = [+ { id: "id", aliases: ["spanid", "span_id", "observationid", "observation_id"], kind: "text", syncMode: "textSearch", suggestObservedValues: true, description: "Observation/span identifier" },+ { id: "traceId", aliases: ["traceid", "trace_id"], kind: "text", syncMode: "textSearch", description: "Trace identifier" },+ { id: "name", aliases: [], kind: "text", syncMode: "textSearch", suggestObservedValues: true, description: "Observation name", nullable: true },+ { id: "traceName", aliases: ["tracename", "trace_name"], kind: "text", syncMode: "exactOption", description: "Trace name", nullable: true },+ { id: "type", aliases: [], kind: "text", syncMode: "exactOption", description: "Observation type" },+ { id: "environment", aliases: ["env"], kind: "text", syncMode: "exactOption", description: "Environment", nullable: true },+ { id: "userId", aliases: ["userid", "user_id", "user"], kind: "text", syncMode: "exactOption", description: "Trace user id", nullable: true },+ { id: "sessionId", aliases: ["sessionid", "session_id", "session"], kind: "text", syncMode: "exactOption", description: "Trace session id", nullable: true },+ { id: "level", aliases: [], kind: "text", syncMode: "exactOption", description: "Observation level" },+ { id: "statusMessage", aliases: ["statusmessage", "status_message", "status"], kind: "text", syncMode: "textSearch", description: "Status message", nullable: true },+ { id: "modelId", aliases: ["modelid", "model_id"], kind: "text", syncMode: "exactOption", description: "Internal model id", nullable: true },+ { id: "providedModelName", aliases: ["providedmodelname", "provided_model_name", "model"], kind: "text", syncMode: "exactOption", description: "Provided model name", nullable: true },+ { id: "promptName", aliases: ["promptname", "prompt_name", "prompt"], kind: "text", syncMode: "exactOption", description: "Prompt name", nullable: true },+ { id: "promptVersion", aliases: ["promptversion", "prompt_version"], kind: "number", syncMode: "textSearch", description: "Prompt version", nullable: true },+ { id: "startTime", aliases: ["starttime", "start_time"], kind: "datetime", syncMode: "textSearch", description: "Observation start time" },+ { id: "endTime", aliases: ["endtime", "end_time"], kind: "datetime", syncMode: "textSearch", description: "Observation end time", nullable: true },+ { id: "latency", aliases: [], kind: "number", syncMode: "textSearch", description: "Observation latency in seconds", unit: "s", nullable: true },+ { id: "timeToFirstToken", aliases: ["timetofirsttoken", "time_to_first_token", "ttft"], kind: "number", syncMode: "textSearch", description: "Time to first token in seconds", unit: "s", nullable: true },+ { id: "tokensPerSecond", aliases: ["tokenspersecond", "tokens_per_second", "tps"], kind: "number", syncMode: "textSearch", description: "Output tokens per second", unit: "tok/s", nullable: true },+ { id: "inputTokens", aliases: ["inputtokens", "input_tokens"], kind: "number", syncMode: "textSearch", description: "Input token count", nullable: true },+ { id: "outputTokens", aliases: ["outputtokens", "output_tokens"], kind: "number", syncMode: "textSearch", description: "Output token count", nullable: true },+ { id: "totalTokens", aliases: ["totaltokens", "total_tokens", "tokens"], kind: "number", syncMode: "textSearch", description: "Total token count", nullable: true },+ { id: "inputCost", aliases: ["inputcost", "input_cost"], kind: "number", syncMode: "textSearch", description: "Input cost in USD", unit: "$", nullable: true },+ { id: "outputCost", aliases: ["outputcost", "output_cost"], kind: "number", syncMode: "textSearch", description: "Output cost in USD", unit: "$", nullable: true },+ { id: "totalCost", aliases: ["totalcost", "total_cost", "cost"], kind: "number", syncMode: "textSearch", description: "Total cost in USD", unit: "$", nullable: true },+ { id: "version", aliases: [], kind: "text", syncMode: "exactOption", description: "Version tag", nullable: true },+ { id: "traceTags", aliases: ["tracetags", "trace_tags", "tags", "tag"], kind: "text", syncMode: "arrayOption", description: "Trace tags" },+ { id: "isRootObservation", aliases: ["isrootobservation", "is_root_observation", "root"], kind: "boolean", syncMode: "textSearch", description: "Whether the observation is a trace root" },+ { id: "hasParentObservation", aliases: ["hasparentobservation", "has_parent_observation"], kind: "boolean", syncMode: "textSearch", description: "Whether the observation has a parent (inverse of root)" },+ { id: "toolNames", aliases: ["toolnames", "tool_names"], kind: "text", syncMode: "arrayOption", description: "Available tool names", nullable: true },+ { id: "calledToolNames", aliases: ["calledtoolnames", "called_tool_names", "calledtools", "called_tools"], kind: "text", syncMode: "arrayOption", description: "Called tool names", nullable: true },+ { id: "toolDefinitions", aliases: ["tooldefinitions", "tool_definitions"], kind: "number", syncMode: "textSearch", description: "Available tool count", nullable: true },+ { id: "toolCalls", aliases: ["toolcalls", "tool_calls"], kind: "number", syncMode: "textSearch", description: "Tool call count", nullable: true },+ { id: "commentCount", aliases: ["commentcount", "comment_count"], kind: "number", syncMode: "textSearch", description: "Comment count" },+ { id: "commentContent", aliases: ["commentcontent", "comment_content", "comment"], kind: "text", syncMode: "textSearch", description: "Comment text", nullable: true },+ { id: "experimentDatasetId", aliases: ["experimentdatasetid", "experiment_dataset_id", "dataset"], kind: "text", syncMode: "exactOption", description: "Experiment dataset identifier", nullable: true },+ { id: "experimentId", aliases: ["experimentid", "experiment_id"], kind: "text", syncMode: "exactOption", description: "Experiment identifier", nullable: true },+ { id: "experimentName", aliases: ["experimentname", "experiment_name", "experiment"], kind: "text", syncMode: "exactOption", description: "Experiment name", nullable: true },+ { id: "input", aliases: [], kind: "text", syncMode: "textSearch", description: "Observation input", nullable: true },+ { id: "output", aliases: [], kind: "text", syncMode: "textSearch", description: "Observation output", nullable: true },+];++const byName = new Map<string, FieldDef>();+for (const f of FIELDS) {+ byName.set(f.id.toLowerCase(), f);+ for (const a of f.aliases) byName.set(a, f);+}++export const METADATA_PREFIX = "metadata.";++// Score dot-paths. Lowercased prefixes accepted by the grammar; the+// canonical spellings are `scores.<name>` and `traceScores.<name>`.+const SCORE_PREFIXES = ["scores.", "score."];+const TRACE_SCORE_PREFIXES = ["tracescores.", "trace_scores.", "tracescore."];++// Pseudo-fields: not columns — `has:<field>` lowers to a null filter. (The+// former `content:` pseudo-field has been removed: a bare query now searches+// input + output by default, and `input:`/`output:` narrow to one column.)+export const HAS_KEY = "has";++/** Langfuse score filter columns (filter by score NAME via key-value ops). */+export const SCORE_COLUMNS = {+ observation: { numeric: "scores_avg", categorical: "score_categories" },+ trace: {+ numeric: "trace_scores_avg",+ categorical: "trace_score_categories",+ },+} as const;++export type FieldRef =+ | { type: "field"; field: FieldDef }+ | { type: "metadata"; key: string }+ | { type: "scores"; key: string; level: "observation" | "trace" }+ | { type: "pseudo"; id: typeof HAS_KEY };++/**+ * Resolve a user-typed key (case-insensitive, alias-aware) to a field, a+ * metadata/score dot path (the key keeps its case), or a pseudo-field.+ * Null = unknown key.+ */+export function resolveField(name: string): FieldRef | null {+ const lower = name.toLowerCase();+ if (lower.startsWith(METADATA_PREFIX)) {+ const key = name.slice(METADATA_PREFIX.length);+ return key.length > 0 ? { type: "metadata", key } : null;+ }+ for (const prefix of TRACE_SCORE_PREFIXES) {+ if (lower.startsWith(prefix)) {+ const key = name.slice(prefix.length);+ return key.length > 0 ? { type: "scores", key, level: "trace" } : null;+ }+ }+ for (const prefix of SCORE_PREFIXES) {+ if (lower.startsWith(prefix)) {+ const key = name.slice(prefix.length);+ return key.length > 0+ ? { type: "scores", key, level: "observation" }+ : null;+ }+ }+ if (lower === HAS_KEY) return { type: "pseudo", id: lower };+ const field = byName.get(lower);+ return field ? { type: "field", field } : null;+}++/**+ * A dot-path prefix typed/picked with no key after the dot (`metadata.`,+ * `scores.`, `traceScores.` and accepted aliases). These parse as free text+ * (no colon), so without this guard committing one would silently set the+ * full-text searchQuery to the bare prefix.+ */+export function isDanglingDotPrefix(value: string): boolean {+ const lower = value.toLowerCase();+ return (+ lower === METADATA_PREFIX ||+ SCORE_PREFIXES.includes(lower) ||+ TRACE_SCORE_PREFIXES.includes(lower)+ );+}++/** Fields that can be unset — the value domain of `has:` / `-has:`. */+export function nullableFields(): FieldDef[] {+ return FIELDS.filter((f) => f.nullable === true);+}++// ---- operator validity ----+//+// One table consulted by the parser (span diagnostics), the validator (commit+// gate), and the adapter (lowering guard), so the three layers cannot drift.+// Everything allowed here lowers to a filter shape the events tRPC contract+// accepts today (filterTypeCompatibility.ts in @langfuse/shared).++const COMPARISONS: ReadonlySet<CompareOp> = new Set([">", "<", ">=", "<="]);+const STRING_OPS: ReadonlySet<CompareOp> = new Set(["exact", "~", "^", "$"]);++const OP_LABEL: Record<string, string> = {+ "~": "contains (*term*)",+ "^": "starts-with (term*)",+ $: "ends-with (*term)",+ exact: "exact match (=)",+};++function label(op: CompareOp): string {+ return OP_LABEL[op] ?? op;+}++/**+ * Is `op` (with `valueOp` grouping) usable on the field `ref` points at?+ * Returns the error message, or null when valid. Value-level checks (numeric+ * parse, ISO dates, true/false, has:/in: domains, flat-contract limits) live+ * in validate.ts.+ */+export function operatorIssue(+ ref: FieldRef,+ op: CompareOp,+ valueOp: "or" | "and" = "or",+): string | null {+ if (valueOp === "and") {+ const isArray =+ ref.type === "field" && ref.field.syncMode === "arrayOption";+ if (!isArray) {+ const name = refName(ref);+ return `AND grouping (all of) only applies to array fields like traceTags — "${name}" is not an array`;+ }+ if (op !== "=")+ return `AND grouping only works with plain values, not ${label(op)}`;+ }++ switch (ref.type) {+ case "pseudo":+ // `has` is the only pseudo-field.+ if (op !== "=") {+ return `has: lists fields that have a value — it does not support ${label(op)}`;+ }+ return null;+ case "metadata":+ // stringObject filters support string ops only; there is no numeric+ // metadata filter in the current contract.+ if (COMPARISONS.has(op)) {+ return `metadata filters match text — ${op} comparisons are not supported`;+ }+ return null;+ case "scores":+ if (STRING_OPS.has(op) && op !== "exact") {+ return `score filters compare numbers (scores.${ref.key}:>0.8) or match categories (scores.${ref.key}:positive) — ${label(op)} is not supported`;+ }+ return null;+ case "field": {+ const f = ref.field;+ if (f.kind === "number") {+ if (op === "~" || op === "^" || op === "$") {+ return `"${f.id}" is a number field and does not support ${label(op)}`;+ }+ return null;+ }+ if (f.kind === "datetime") {+ if (op === "=" || op === "exact") {+ return `"${f.id}" is a datetime field — use a comparison (e.g. ${f.id}:>2026-06-01)`;+ }+ if (!COMPARISONS.has(op)) {+ return `"${f.id}" is a datetime field and does not support ${label(op)}`;+ }+ return null;+ }+ if (f.kind === "boolean") {+ if (op !== "=" && op !== "exact") {+ return `"${f.id}" is a boolean field and does not support ${label(op)}`;+ }+ return null;+ }+ // text+ if (COMPARISONS.has(op)) {+ return `"${f.id}" is a text field and does not support ${op}`;+ }+ if (f.syncMode === "arrayOption" && STRING_OPS.has(op)) {+ return `"${f.id}" is an array field — use values (${f.id}:a), any-of groups (${f.id}:(a OR b)), or all-of groups (${f.id}:(a AND b))`;+ }+ return null;+ }+ }+}++/**+ * Negation gaps: operations whose negative form has no counterpart in the+ * flat Langfuse filter contract.+ */+export function negationIssue(+ ref: FieldRef,+ op: CompareOp,+ valueOp: "or" | "and" = "or",+): string | null {+ if (valueOp === "and") {+ // NOT(all of) would mean "missing at least one" — no such array operator.+ return `negated all-of groups on "${refName(ref)}" are not representable — negate single values instead`;+ }+ if (ref.type === "pseudo") {+ return null; // `has` is the only pseudo; -has: is valid (missing value)+ }+ if (op === "^" || op === "$") {+ return `negation of ${label(op)} is not representable in the Langfuse filter contract`;+ }+ if (op === "exact" || op === "=") {+ if (ref.type === "metadata") {+ // stringObject has no "does not equal" — only does-not-contain.+ return op === "exact"+ ? `negated exact match on metadata is not representable — use -metadata.${ref.key}:*value* (does not contain)`+ : null; // '=' on metadata negates via categoryOptions? No — handled below.+ }+ if (ref.type === "scores") {+ // Numeric scores have no != ; categorical scores negate via none-of.+ return null; // checked per-value in validate.ts (numeric vs categorical)+ }+ if (ref.type === "field") {+ const f = ref.field;+ if (f.kind === "number") {+ return `negated equality on "${f.id}" is not representable — use comparisons (${f.id}:<n or ${f.id}:>n)`;+ }+ if (f.kind === "boolean") return null; // inverts the value+ if (f.kind === "text" && f.syncMode === "textSearch" && op === "exact") {+ return `negated exact match on "${f.id}" is not representable — use -${f.id}:*value* (does not contain)`;+ }+ return null;+ }+ }+ return null;+}++export function refName(ref: FieldRef): string {+ switch (ref.type) {+ case "field":+ return ref.field.id;+ case "metadata":+ return `metadata.${ref.key}`;+ case "scores":+ return ref.level === "trace"+ ? `traceScores.${ref.key}`+ : `scores.${ref.key}`;+ case "pseudo":+ return ref.id;+ }+}++/** Canonical query-text key for a resolved field reference. */+export function canonicalKey(ref: FieldRef): string {+ return refName(ref);+}diff --git a/web/src/features/search-bar/lib/filter-state-to-query.ts b/web/src/features/search-bar/lib/filter-state-to-query.tsnew file mode 100644index 0000000000..6667615842--- /dev/null+++ b/web/src/features/search-bar/lib/filter-state-to-query.ts@@ -0,0 +1,480 @@+// Reverse adapter: flat Langfuse `FilterState` (+ full-text searchQuery and+// searchType scopes) → query text.+//+// Drives the bar/sidebar sync: the facet sidebar owns the canonical+// `FilterState`, and whenever it changes the search bar re-seeds its text from+// here. Builds editor AST nodes and reuses the canonical serializer, so the+// produced text always reparses and round-trips through astToFilterState back+// to an equivalent flat filter list + search. Filters that have no grammar+// form (e.g. positionInTrace) are reported in `skipped`, never silently+// dropped.++import {+ eventsTableCols,+ type FilterState,+ type TracingSearchType,+} from "@langfuse/shared";++import {+ INVERTED_COMPARISON,+ resolveScoreType,+ type ScoreTypeContext,+} from "./adapter";+import type { ASTNode, FilterNode } from "./ast";+import { resolveField, SCORE_COLUMNS, type FieldRef } from "./fields";+import { NEEDS_QUOTES, serialize } from "./langQ";++// Legacy filters address columns by id ("userId") or display name ("User ID").+const COLUMN_ID_BY_KEY = new Map<string, string>();+for (const col of eventsTableCols) {+ COLUMN_ID_BY_KEY.set(col.id.toLowerCase(), col.id);+ COLUMN_ID_BY_KEY.set(col.name.toLowerCase(), col.id);+}++function columnIdOf(column: string): string | null {+ return COLUMN_ID_BY_KEY.get(column.toLowerCase()) ?? null;+}++function filterNode(+ key: string,+ op: FilterNode["op"],+ values: string[],+ valueOp?: "or" | "and",+): FilterNode {+ return { kind: "filter", key, op, values, valueOp };+}++function negate(node: FilterNode): ASTNode {+ return { kind: "not", child: node };+}++function scorePathOf(column: string, key: string): string | null {+ if (+ column === SCORE_COLUMNS.observation.numeric ||+ column === SCORE_COLUMNS.observation.categorical+ ) {+ return `scores.${key}`;+ }+ if (+ column === SCORE_COLUMNS.trace.numeric ||+ column === SCORE_COLUMNS.trace.categorical+ ) {+ return `traceScores.${key}`;+ }+ return null;+}++const STRING_OP_SYMBOL: Record<string, FilterNode["op"]> = {+ "=": "exact",+ contains: "~",+ "starts with": "^",+ "ends with": "$",+};++function lowerSingle(filter: FilterState[number]): ASTNode | null {+ switch (filter.type) {+ case "stringOptions":+ case "arrayOptions": {+ const id = columnIdOf(filter.column);+ if (id === null || filter.value.length === 0) return null;+ // A stringOptions/arrayOptions filter is EXACT-set semantics. On a+ // `textSearch` field (id/name) the bar reads a bare single value as+ // `contains`, so a single-value any-of would silently flip exact→substring+ // on the next commit (and a single-value none-of → does-not-contain). The+ // grouped multi-value forms reparse to exact any-of/none-of, so only the+ // single-value forms need care.+ const ref = resolveField(id);+ const isTextSearch =+ ref?.type === "field" && ref.field.syncMode === "textSearch";+ if (filter.operator === "none of") {+ // `-id:=abc` (negated exact) is not representable, so a single none-of on+ // a textSearch field has no faithful grammar form — skip it (preserved via+ // skippedFilters) rather than rewrite it to `does not contain`.+ if (isTextSearch && filter.value.length === 1) return null;+ return negate(filterNode(id, "=", filter.value));+ }+ if (filter.operator === "all of") {+ // A single-value all-of has no distinct grammar form — `(a)` reparses+ // as any-of, so emitting it would silently flip the operator shape on+ // the next commit. Skip it (preserved via skippedFilters) rather than+ // rewrite; multi-value all-of serializes to the `(a AND b)` group.+ if (filter.value.length < 2) return null;+ return filterNode(id, "=", filter.value, "and");+ }+ // Single-value any-of on a textSearch field: emit the explicit exact form+ // (`id:=abc`) so it round-trips to `{string,=}` (exact preserved), not the+ // bare `id:abc` that would re-lower to `contains`.+ if (isTextSearch && filter.value.length === 1) {+ return filterNode(id, "exact", filter.value);+ }+ return filterNode(id, "=", filter.value);+ }+ case "string": {+ const id = columnIdOf(filter.column);+ if (id === null) return null;+ if (filter.operator === "does not contain") {+ // Mirror the positive contains carve-out below: a textSearch field emits+ // the bare `-input:refund`, not the `-input:*refund*` glob, so the+ // negated form round-trips stably (no visible rewrite on commit echo).+ const ref = resolveField(id);+ if (ref?.type === "field" && ref.field.syncMode === "textSearch") {+ return negate(filterNode(id, "=", [filter.value]));+ }+ return negate(filterNode(id, "~", [filter.value]));+ }+ const op = STRING_OP_SYMBOL[filter.operator];+ if (op === undefined) return null;+ // '=' on option-backed fields reads better as the bare any-of form.+ if (op === "exact") {+ const ref = resolveField(id);+ if (+ ref?.type === "field" &&+ (ref.field.syncMode === "exactOption" ||+ ref.field.syncMode === "arrayOption")+ ) {+ return filterNode(id, "=", [filter.value]);+ }+ }+ // Bare `field:value` is the documented contains-default for textSearch+ // fields, so emit it bare rather than the `*value*` glob — otherwise the+ // commit echo visibly rewrites the user's typed `input:refund` to+ // `input:*refund*` (op `=` vs `~` aren't astEqual, so resetTo re-seeds).+ // Symmetric inverse of the metadata-equality carve-out.+ if (op === "~") {+ const ref = resolveField(id);+ if (ref?.type === "field" && ref.field.syncMode === "textSearch") {+ return filterNode(id, "=", [filter.value]);+ }+ }+ return filterNode(id, op, [filter.value]);+ }+ case "number": {+ const id = columnIdOf(filter.column);+ if (id === null) return null;+ const op = filter.operator === "=" ? "=" : filter.operator;+ return filterNode(id, op, [String(filter.value)]);+ }+ case "datetime": {+ const id = columnIdOf(filter.column);+ if (id === null) return null;+ const value =+ filter.value instanceof Date+ ? filter.value.toISOString()+ : String(filter.value);+ return filterNode(id, filter.operator, [value]);+ }+ case "boolean": {+ const id = columnIdOf(filter.column);+ if (id === null) return null;+ const value = filter.operator === "<>" ? !filter.value : filter.value;+ return filterNode(id, "=", [String(value)]);+ }+ case "stringObject": {+ const id = columnIdOf(filter.column);+ if (id !== "metadata") return null;+ // A key with grammar chars (`:`, space, …) would reparse as a different+ // key/value pair, silently corrupting the filter. Can't be expressed in+ // the grammar — skip so the container preserves it (no silent rewrite).+ if (NEEDS_QUOTES.test(filter.key)) return null;+ const key = `metadata.${filter.key}`;+ if (filter.operator === "does not contain") {+ return negate(filterNode(key, "~", [filter.value]));+ }+ const op = STRING_OP_SYMBOL[filter.operator];+ if (op === undefined) return null;+ // Mirror the `string` carve-out: metadata only supports+ // exact/contains/starts/ends (no contains-default ambiguity), so equality+ // reads as the bare `metadata.key:value` the user typed and the README+ // documents — not the explicit `metadata.key:=value` `exact` would emit.+ if (op === "exact") return filterNode(key, "=", [filter.value]);+ return filterNode(key, op, [filter.value]);+ }+ case "numberObject": {+ if (NEEDS_QUOTES.test(filter.key)) return null;+ const path = scorePathOf(filter.column, filter.key);+ if (path === null) return null;+ const op = filter.operator === "=" ? "=" : filter.operator;+ return filterNode(path, op, [String(filter.value)]);+ }+ case "categoryOptions": {+ if (NEEDS_QUOTES.test(filter.key)) return null;+ const path = scorePathOf(filter.column, filter.key);+ if (path === null || filter.value.length === 0) return null;+ const node = filterNode(path, "=", filter.value);+ return filter.operator === "none of" ? negate(node) : node;+ }+ case "null": {+ const id = columnIdOf(filter.column);+ if (id === null) return null;+ const node = filterNode("has", "=", [id]);+ return filter.operator === "is null" ? negate(node) : node;+ }+ default:+ return null;+ }+}++export type FilterStateToQueryResult = {+ text: string;+ /** Human-readable descriptions of filters that have no grammar form. */+ skipped: string[];+ /** The actual filter objects that have no grammar form. The container+ * preserves these across a bar commit so they are never silently dropped+ * (the bar can't display them, but it must not wipe them either). */+ skippedFilters: FilterState;+};++export type FilterStateToQueryOptions = {+ /** Global full-text query — rendered as bare text or a scoped field token. */+ searchQuery?: string | null;+ /** Search scope — a residual input/output searchType renders as input:/output:;+ * the default (`["id","content"]` and any id/content subset) renders as bare+ * free text. */+ searchType?: TracingSearchType[] | null;+};++// The default full-text scope searches ids, names, input, and output — the+// `id` and `content` searchType lanes together. There is no scope token for it+// (the `content:` token was removed), so it renders as bare free text.+// astToFilterState returns `null` searchType for the bar (no scope tokens); the+// sync layer maps that back to this default, hence `["id","content"]` (and any+// subset) must also be recognized as "default" so it round-trips to bare text+// rather than a stray scope token.+const DEFAULT_SEARCH_TYPES: ReadonlySet<TracingSearchType> = new Set([+ "id",+ "content",+]);++function isDefaultSearchType(+ searchType: TracingSearchType[] | null | undefined,+): boolean {+ return (+ searchType == null ||+ searchType.length === 0 ||+ searchType.every((t) => DEFAULT_SEARCH_TYPES.has(t))+ );+}++// The bar field that expresses a non-default search scope. input/output alone+// (e.g. from a pre-existing URL or the legacy toolbar) render as their real+// text columns, which reparse to column filters — the intended convergence.+// The default (ids+names+input+output) and id/content combos → null (bare text).+function scopedSearchField(+ searchType: TracingSearchType[] | null | undefined,+): "input" | "output" | null {+ if (isDefaultSearchType(searchType)) return null;+ const set = new Set(searchType ?? []);+ if (set.has("input")) return "input";+ if (set.has("output")) return "output";+ return null;+}++export function filterStateToQueryText(+ filters: FilterState,+ options: FilterStateToQueryOptions = {},+): FilterStateToQueryResult {+ const nodes: ASTNode[] = [];+ const skipped: string[] = [];+ const skippedFilters: FilterState = [];+ for (const filter of filters) {+ const node = lowerSingle(filter);+ if (node === null) {+ skipped.push(`${filter.column} (${filter.type} ${filter.operator})`);+ skippedFilters.push(filter);+ continue;+ }+ nodes.push(node);+ }++ // Full-text search. The default scope (ids+names+input+output) has no scope+ // token, so it renders as bare free text. A residual input/output searchType+ // (from a pre-existing URL or the legacy toolbar) bundles the whole query into+ // one `input:"…"`/`output:"…"` token, which reparses to its real column filter+ // — so such a searchType normalizes to a column filter on the next commit (the+ // deliberate canonicalization). The query is a single contiguous-substring+ // phrase (ILIKE %query%), so it renders as ONE token — quoted iff it has+ // whitespace via serializeValue. NOT whitespace-split: separate tokens would+ // misleadingly read as independent AND terms, disagree with the scope-rewrite+ // suggestions (which serialize the whole phrase), and strip a user's own+ // quotes on every derive.+ const searchQuery = options.searchQuery?.trim() ?? "";+ if (searchQuery.length > 0) {+ const scopeField = scopedSearchField(options.searchType);+ if (scopeField !== null) {+ nodes.push({+ kind: "filter",+ key: scopeField,+ op: "=",+ values: [searchQuery],+ });+ } else {+ nodes.push({ kind: "text", value: searchQuery });+ }+ }++ const ast: ASTNode | null =+ nodes.length === 0+ ? null+ : nodes.length === 1+ ? nodes[0]!+ : { kind: "and", children: nodes };+ return { text: serialize(ast), skipped, skippedFilters };+}++// Normalize an editor AST so a typed draft compares equal (via astEquals) to the+// canonical text the reverse adapter above re-derives, letting the typed form+// stand instead of being clobbered on the commit echo. Three equivalences the+// adapter introduces by lowering + re-deriving are reconciled here:+//+// - VALUE FORMAT (positive or negated): the lowering canonicalizes boolean+// case (`TRUE`→`true`), numeric format (`2.0`→`2`, `.5`→`0.5`, `2.5e1`→`25`),+// and datetime to full ISO — so the derived text differs from what was typed.+// - EXACT-OP (`:=` ↔ `:`): for every field except textSearch, `key:=value`+// and `key:value` lower to the IDENTICAL filter and the reverse adapter emits+// the bare `=` form — so a typed `level:=ERROR` must fold to match it.+// - NEGATION FOLD: `-` is folded into the value/operator (`-num:>2`→`num:<=2`,+// `-bool:true`→`bool:false`), leaving no NOT in FilterState to re-derive.+//+// The store's `resetTo` gate runs this on BOTH sides before astEquals, so typed+// forms like `latency:2.0` / `isRootObservation:TRUE` / `level:=ERROR` /+// `-latency:>2` stand — the same "no silent rewrite" carve-out already made for+// aliases/metadata. It preserves structure and order, so free-text+// canonicalization and alias casing are untouched. Negations WITHOUT a value/op+// fold (none-of, does-not-contain, is-null) keep their dash on re-derive, so+// they already round-trip and stay NOT.+export function foldDerivedNegation(+ node: ASTNode | null,+ scoreTypes?: ScoreTypeContext,+): ASTNode | null {+ if (node === null) return null;+ switch (node.kind) {+ case "not": {+ const child = foldDerivedNegation(node.child, scoreTypes) ?? node.child;+ if (child.kind === "filter") {+ const folded = foldNegatedFilter(child);+ if (folded !== null) return folded;+ }+ return { ...node, child };+ }+ case "and":+ case "or":+ return {+ ...node,+ children: node.children.map(+ (c) => foldDerivedNegation(c, scoreTypes) ?? c,+ ),+ };+ case "filter":+ return normalizeFilterValues(node, scoreTypes);+ default:+ return node;+ }+}++// Canonicalize a positive filter's op + values the same way the lowering + reverse+// derive do, so the typed form compares equal to the re-derived committed form.+function normalizeFilterValues(+ f: FilterNode,+ scoreTypes?: ScoreTypeContext,+): FilterNode {+ const ref = resolveField(f.key);+ if (ref === null) return f;+ // `:=` (exact) folds to `:` (=) everywhere the two lower identically.+ let op: FilterNode["op"] =+ f.op === "exact" && exactEqualsBareForm(ref) ? "=" : f.op;+ // On a textSearch text field, the explicit contains glob `*v*` (op `~`) and+ // the bare form `v` (op `=`) lower to the IDENTICAL contains filter, and the+ // reverse adapter emits the bare form — so fold a single-value `~` to `=` too.+ // Otherwise typing/picking `input:*foo*` (or `id:*foo*`, `name:*foo*`) is+ // silently rewritten to `input:foo` on the commit echo. Inverse condition to+ // the `exact` fold above (which excludes textSearch).+ if (+ op === "~" &&+ f.values.length === 1 &&+ ref.type === "field" &&+ ref.field.kind === "text" &&+ ref.field.syncMode === "textSearch"+ ) {+ op = "=";+ }+ const values = normalizeValuesFor(ref, f.values, scoreTypes);+ return { ...f, op, values };+}++// Fields where `key:=value` and `key:value` lower to the identical filter (so+// the reverse adapter always emits the bare `=`). textSearch is excluded — there+// `:` is contains and `:=` is exact, two different ops — as is datetime, which+// has only comparison forms.+function exactEqualsBareForm(ref: FieldRef): boolean {+ if (ref.type === "metadata" || ref.type === "scores") return true;+ if (ref.type === "field") {+ const k = ref.field.kind;+ return (+ k === "number" ||+ k === "boolean" ||+ (k === "text" && ref.field.syncMode !== "textSearch")+ );+ }+ return false;+}++function normalizeValuesFor(+ ref: FieldRef,+ values: string[],+ scoreTypes?: ScoreTypeContext,+): string[] {+ if (ref.type === "field") {+ const k = ref.field.kind;+ if (k === "boolean") return values.map((v) => v.toLowerCase());+ if (k === "number") return values.map(normalizeNumberString);+ if (k === "datetime") return values.map(normalizeIsoString);+ return values; // text — verbatim+ }+ if (ref.type === "scores") {+ // Numeric / unknown scores get Number-canonicalized by lowerNumeric; a+ // known-CATEGORICAL score keeps its label verbatim (a numeric-looking label+ // like "2.0" must NOT be rewritten to "2"). normalizeNumberString only+ // touches finite-number strings, but gate on type so a decimal category is+ // never folded.+ if (resolveScoreType(scoreTypes, ref.level, ref.key) === "categorical")+ return values;+ return values.map(normalizeNumberString);+ }+ return values; // metadata text / pseudo — verbatim+}++function normalizeNumberString(v: string): string {+ const n = Number(v);+ return v.trim().length > 0 && Number.isFinite(n) ? String(n) : v;+}++function normalizeIsoString(v: string): string {+ const ms = Date.parse(v);+ return Number.isNaN(ms) ? v : new Date(ms).toISOString();+}++// `f` arrives value-normalized (foldDerivedNegation normalizes the NOT's child+// before this runs), so only the op/boolean is inverted here.+function foldNegatedFilter(f: FilterNode): FilterNode | null {+ // Comparison: NOT (key op v) === key INVERT(op) v. Comparisons only validly+ // appear on numeric/datetime fields, so no field-kind check is needed.+ if (f.op in INVERTED_COMPARISON) {+ return {+ ...f,+ op: INVERTED_COMPARISON[f.op as keyof typeof INVERTED_COMPARISON],+ };+ }+ // Boolean equality: NOT (key = true) === key = false — but ONLY for a boolean+ // field. On an option field a "true" value lowers to a none-of, not a flip,+ // so it must keep its NOT (which round-trips with the dash anyway).+ if ((f.op === "=" || f.op === "exact") && f.values.length === 1) {+ const ref = resolveField(f.key);+ if (ref?.type === "field" && ref.field.kind === "boolean") {+ const v = f.values[0]!;+ if (v === "true" || v === "false") {+ return { ...f, op: "=", values: [v === "true" ? "false" : "true"] };+ }+ }+ }+ return null;+}diff --git a/web/src/features/search-bar/lib/langQ.clienttest.ts b/web/src/features/search-bar/lib/langQ.clienttest.tsnew file mode 100644index 0000000000..3607d1c6df--- /dev/null+++ b/web/src/features/search-bar/lib/langQ.clienttest.ts@@ -0,0 +1,469 @@+import type { ASTNode } from "@/src/features/search-bar/lib/ast";+import { parse, serialize, termAt } from "@/src/features/search-bar/lib/langQ";+import {+ removeToken,+ tidyQueryText,+} from "@/src/features/search-bar/lib/edits";+import { validateQuery } from "@/src/features/search-bar/lib/validate";++/** Structural copy without spans, for deep-equal comparisons. */+function strip(node: ASTNode | null): unknown {+ if (node === null) return null;+ switch (node.kind) {+ case "filter":+ return {+ kind: "filter",+ key: node.key,+ op: node.op,+ values: node.values,+ ...(node.valueOp === "and" ? { valueOp: "and" } : {}),+ };+ case "text":+ return { kind: "text", value: node.value };+ case "not":+ return { kind: "not", child: strip(node.child) };+ case "and":+ case "or":+ return { kind: node.kind, children: node.children.map(strip) };+ }+}++describe("langQ parser", () => {+ it("resolves aliases to canonical field ids", () => {+ const r = parse("env:prod");+ expect(r.valid).toBe(true);+ expect(strip(r.ast)).toEqual({+ kind: "filter",+ key: "environment",+ op: "=",+ values: ["prod"],+ });+ });++ it("parses grouped lists, comma lists, comparisons, and quoted values", () => {+ expect(strip(parse("level:(ERROR OR WARNING)").ast)).toEqual({+ kind: "filter",+ key: "level",+ op: "=",+ values: ["ERROR", "WARNING"],+ });+ expect(strip(parse("level:ERROR,WARNING").ast)).toEqual({+ kind: "filter",+ key: "level",+ op: "=",+ values: ["ERROR", "WARNING"],+ });+ expect(strip(parse("latency:>2.5").ast)).toEqual({+ kind: "filter",+ key: "latency",+ op: ">",+ values: ["2.5"],+ });+ expect(strip(parse('name:"hello world"').ast)).toEqual({+ kind: "filter",+ key: "name",+ op: "=",+ values: ["hello world"],+ });+ });++ it("parses all-of value groups on array fields", () => {+ expect(strip(parse("tags:(a AND b)").ast)).toEqual({+ kind: "filter",+ key: "traceTags",+ op: "=",+ values: ["a", "b"],+ valueOp: "and",+ });+ });++ it("preserves metadata dot-path key case", () => {+ expect(strip(parse("metadata.Region:eu").ast)).toEqual({+ kind: "filter",+ key: "metadata.Region",+ op: "=",+ values: ["eu"],+ });+ });++ it("mixes free text with filters via implicit AND", () => {+ expect(strip(parse("timeout level:ERROR").ast)).toEqual({+ kind: "and",+ children: [+ { kind: "text", value: "timeout" },+ { kind: "filter", key: "level", op: "=", values: ["ERROR"] },+ ],+ });+ });++ it("binds implicit AND tighter than OR and parses NOT/- negation", () => {+ expect(strip(parse("a:1 b:2 OR c:3").ast)).toMatchObject({+ kind: "or",+ });+ expect(strip(parse("-env:dev").ast)).toEqual({+ kind: "not",+ child: {+ kind: "filter",+ key: "environment",+ op: "=",+ values: ["dev"],+ },+ });+ expect(strip(parse("NOT level:DEBUG").ast)).toEqual({+ kind: "not",+ child: { kind: "filter", key: "level", op: "=", values: ["DEBUG"] },+ });+ });++ it("parses positional `*` globs into match operators", () => {+ // contains/starts/ends are positional wildcards, not prefix operators.+ expect(strip(parse("name:*chat*").ast)).toMatchObject({+ op: "~",+ values: ["chat"],+ });+ expect(strip(parse("input:How*").ast)).toMatchObject({+ op: "^",+ values: ["How"],+ });+ expect(strip(parse("output:*end").ast)).toMatchObject({+ op: "$",+ values: ["end"],+ });+ expect(strip(parse("name:=exact").ast)).toMatchObject({ op: "exact" });+ });++ it("treats a glob around a quoted value as a literal phrase match", () => {+ // The `*` lives outside the quotes; the phrase keeps its spaces.+ expect(strip(parse('input:*"refund policy"*').ast)).toMatchObject({+ op: "~",+ values: ["refund policy"],+ });+ // A bare value with no leading/trailing `*` is a plain contains-default.+ expect(strip(parse("name:gpt-4").ast)).toMatchObject({+ op: "=",+ values: ["gpt-4"],+ });+ });++ it('accepts a quoted empty exact value (round-trips :="")', () => {+ const r = parse('metadata.region:=""');+ expect(r.valid).toBe(true);+ expect(strip(r.ast)).toMatchObject({ op: "exact", values: [""] });+ });++ it('accepts quoted-empty glob values (input:*""* round-trips)', () => {+ // What the reverse adapter emits for an empty contains/starts/ends filter.+ expect(parse('input:*""*').valid).toBe(true);+ expect(parse('input:""*').valid).toBe(true);+ expect(parse('input:*""').valid).toBe(true);+ });++ it("rejects a key with quotes or spaces", () => {+ expect(parse('metadata."foo":bar').valid).toBe(false);+ });++ it("emits a single diagnostic for a bare AND, not a doubled one", () => {+ const errs = parse("AND").diagnostics.filter((d) => d.severity === "error");+ expect(errs).toHaveLength(1);+ });++ it("emits one separator diagnostic for a lone OR/AND inside a group", () => {+ // `level:(OR)` must not double the missing-left-hand and dangling messages+ // at the same span (mirrors the bare-AND fix in parseAnd).+ for (const q of ["level:(OR)", "traceTags:(AND)"]) {+ const sep = q.includes("OR") ? "OR" : "AND";+ const errs = parse(q).diagnostics.filter(+ (d) => d.severity === "error" && d.message.includes(sep),+ );+ expect(errs, q).toHaveLength(1);+ }+ });++ it("flags unknown fields with an error diagnostic", () => {+ const r = parse("nope:1");+ expect(r.valid).toBe(false);+ expect(r.diagnostics.some((d) => d.message.includes('"nope"'))).toBe(true);+ });++ it("flags structural issues without throwing", () => {+ for (const text of [+ "level:",+ "level:(ERROR",+ '"unclosed',+ "(env:dev",+ "env:dev)",+ "NOT",+ "AND",+ "level:ERROR OR",+ "AND env:dev", // leading AND with no left-hand expression+ "tags:(a OR b AND c)",+ "-freetext",+ ]) {+ const r = parse(text);+ expect(r.valid).toBe(false);+ }+ });++ it("keeps spans pointing at source slices", () => {+ const text = "timeout level:ERROR";+ const r = parse(text);+ expect(r.ast?.kind).toBe("and");+ if (r.ast?.kind !== "and") return;+ const [t, f] = r.ast.children;+ expect(t?.kind === "text" && text.slice(t.span!.from, t.span!.to)).toBe(+ "timeout",+ );+ expect(f?.kind === "filter" && text.slice(f.span!.from, f.span!.to)).toBe(+ "level:ERROR",+ );+ });++ it("termAt is quote-aware (one token across quoted spaces)", () => {+ const text = 'name:"hello world" x';+ expect(termAt(text, 8)?.raw).toBe('name:"hello world"');+ });++ it("treats unicode whitespace (NBSP) as a token separator", () => {+ const r = parse("level:ERROR env:dev");+ expect(strip(r.ast)).toEqual({+ kind: "and",+ children: [+ { kind: "filter", key: "level", op: "=", values: ["ERROR"] },+ { kind: "filter", key: "environment", op: "=", values: ["dev"] },+ ],+ });+ });+});++describe("langQ serializer", () => {+ it("round-trips canonical text", () => {+ for (const text of [+ "level:ERROR",+ "level:(ERROR OR WARNING)",+ "-env:dev",+ "latency:>2",+ 'name:"hello world"',+ "tags:(a AND b)",+ "timeout level:ERROR",+ "has:endTime",+ "-has:endTime",+ "metadata.region:eu",+ "scores.accuracy:>0.8",+ ]) {+ const first = parse(text);+ expect(first.valid).toBe(true);+ const canonical = serialize(first.ast);+ const second = parse(canonical);+ expect(strip(second.ast)).toEqual(strip(first.ast));+ }+ });++ it("escaped quotes and backslashes round-trip", () => {+ const node: ASTNode = {+ kind: "filter",+ key: "name",+ op: "=",+ values: ['say "hi" \\ done'],+ };+ const text = serialize(node);+ const r = parse(text);+ expect(strip(r.ast)).toEqual({+ kind: "filter",+ key: "name",+ op: "=",+ values: ['say "hi" \\ done'],+ });+ });++ it("collapses same-field OR chains into grouped values", () => {+ const r = parse("level:ERROR OR level:WARNING");+ expect(serialize(r.ast)).toBe("level:(ERROR OR WARNING)");+ });++ it("quotes values that would otherwise reparse as operators or keywords", () => {+ // Values starting with an operator prefix, equal to a boolean keyword, or+ // empty must round-trip through serialize → parse unchanged.+ for (const value of [+ ">5",+ "~foo",+ "=eq",+ "^x",+ "$y",+ "*z",+ "OR",+ "AND",+ "NOT",+ "",+ ]) {+ const node: ASTNode = {+ kind: "filter",+ key: "name",+ op: "=",+ values: [value],+ };+ const r = parse(serialize(node));+ expect(r.valid, `value ${JSON.stringify(value)} must round-trip`).toBe(+ true,+ );+ expect(strip(r.ast)).toEqual({+ kind: "filter",+ key: "name",+ op: "=",+ values: [value],+ });+ }+ });++ it("keeps a keyword value inside an any-of group", () => {+ const node: ASTNode = {+ kind: "filter",+ key: "name",+ op: "=",+ values: ["x", "OR"],+ };+ const r = parse(serialize(node));+ expect(r.valid).toBe(true);+ expect(strip(r.ast)).toEqual({+ kind: "filter",+ key: "name",+ op: "=",+ values: ["x", "OR"],+ });+ });++ it("does not over-quote values with mid-string hyphens or operators", () => {+ expect(serialize(parse("model:gpt-4-turbo").ast)).toBe("model:gpt-4-turbo");+ });+});++describe("edits", () => {+ it("removeToken splices when valid", () => {+ expect(removeToken("level:ERROR env:dev", { from: 0, to: 11 })).toBe(+ "env:dev",+ );+ expect(removeToken("level:ERROR env:dev", { from: 12, to: 19 })).toBe(+ "level:ERROR",+ );+ });++ it("removeToken falls back to AST surgery inside groups", () => {+ // Splicing "level:ERROR" out would leave "(OR level:WARNING)" — invalid,+ // so the edit reserializes from the surgically-edited AST instead.+ const next = removeToken("(level:ERROR OR level:WARNING)", {+ from: 1,+ to: 12,+ });+ expect(next).toBe("level:WARNING");+ });++ it("tidyQueryText strips only provably-redundant parens", () => {+ expect(tidyQueryText("(env:dev)")).toBe("env:dev");+ expect(tidyQueryText("((env:dev)) level:ERROR")).toBe(+ "env:dev level:ERROR",+ );+ });+});++describe("validateQuery", () => {+ it("accepts representable queries", () => {+ for (const text of [+ "",+ "level:ERROR",+ "level:(ERROR OR WARNING)",+ "-env:dev",+ "timeout level:ERROR",+ "latency:>2 -has:endTime",+ "scores.accuracy:>0.8",+ "traceScores.nps:positive",+ "metadata.region:*eu*",+ "input:refund",+ "name:checkout",+ "tags:(a AND b)",+ "isRootObservation:true",+ "-isRootObservation:true",+ "level:ERROR OR level:WARNING",+ ]) {+ const r = validateQuery(text);+ expect(r.valid, `expected valid: ${text}`).toBe(true);+ }+ });++ it("rejects forms the flat filter contract cannot represent", () => {+ for (const text of [+ "level:ERROR OR env:dev", // cross-field OR+ "NOT (level:ERROR env:dev)", // negated group+ "-latency:2", // negated numeric equality+ "-input:prefix*", // negated starts-with+ "-tags:(a AND b)", // negated all-of+ "metadata.region:>5", // metadata comparison+ "-metadata.region:eu", // negated metadata equality+ "latency:(1 OR 2)", // numeric any-of+ "has:(endTime OR userId)", // positive multi-has+ "in:nope", // bad scope+ "x:1", // unknown field+ "-(env:dev)", // standalone "-" before a group (must glue to the filter)+ "- env:dev", // stray "-" then a filter+ "metadata.", // dot-prefix field with no key+ "scores.", // dot-prefix score with no key+ "traceScores.", // dot-prefix trace score with no key+ "tags:(a,b)", // bare comma inside a group (must use OR/AND)+ "level:(ERROR,WARNING)", // same, on an option field+ "not level:ERROR", // lowercase `not` reserved (use -field:value)+ "!level:ERROR", // `!` reserved (use -field:value)+ "level:ERROR or env:dev", // lowercase `or` reserved+ "level:ERROR and env:dev", // lowercase `and` reserved+ ]) {+ const r = validateQuery(text);+ expect(r.valid, `expected invalid: ${text}`).toBe(false);+ }+ });++ it("nested AND groups behave like the top-level chain", () => {+ expect(validateQuery("(env:dev timeout)").valid).toBe(true);+ expect(validateQuery("(env:dev level:ERROR)").valid).toBe(true);+ });++ it("nested same-field OR groups collapse to any-of", () => {+ expect(validateQuery("(level:ERROR OR level:WARNING) env:dev").valid).toBe(+ true,+ );+ });++ it("warns (without blocking) on has: for non-nullable fields", () => {+ const r = validateQuery("has:level");+ expect(r.valid).toBe(true);+ expect(r.diagnostics.some((d) => d.severity === "warning")).toBe(true);+ });++ it("caps query length", () => {+ const long = `name:${"a".repeat(2100)}`;+ expect(validateQuery(long).valid).toBe(false);+ });++ it("flags a bare comma in a group with a single diagnostic, not a doubled one", () => {+ const errors = validateQuery("tags:(a,b)").diagnostics.filter(+ (d) => d.severity === "error",+ );+ expect(errors).toHaveLength(1);+ expect(errors[0]!.message).toMatch(/uppercase OR or AND/);+ });++ it("emits a single Unclosed-paren diagnostic for `level:(`", () => {+ const unclosed = validateQuery("level:(").diagnostics.filter((d) =>+ d.message.includes("Unclosed"),+ );+ expect(unclosed).toHaveLength(1);+ });++ it("reserves operator-looking tokens with a 'not supported yet' diagnostic", () => {+ const msgOf = (q: string) =>+ validateQuery(q)+ .diagnostics.map((d) => d.message)+ .join(" | ");+ expect(msgOf("not level:ERROR")).toMatch(/not.*not supported yet/i);+ expect(msgOf("!level:ERROR")).toMatch(/not supported yet/i);+ expect(msgOf("level:ERROR or env:dev")).toMatch(/not supported yet/i);+ // quoting escapes the reserved word back into free text+ expect(validateQuery('"not" level:ERROR').valid).toBe(true);+ });+});diff --git a/web/src/features/search-bar/lib/langQ.ts b/web/src/features/search-bar/lib/langQ.tsnew file mode 100644index 0000000000..701a8e1652--- /dev/null+++ b/web/src/features/search-bar/lib/langQ.ts@@ -0,0 +1,973 @@+// Search-bar query language: tolerant hand-rolled lexer + recursive-descent+// parser and the canonical serializer.+//+// Grammar (no time tokens — the table's date range picker owns time):+// expr := orExpr+// orExpr := andExpr (OR andExpr)*+// andExpr := unary ((AND)? unary)* -- implicit AND on adjacency+// unary := NOT unary | '-'term | '(' expr ')' | term+// term := key ':' valueExpr | freeText+// valueExpr := ('>'|'<'|'>='|'<=') scalar | '=' scalar | globValue | '(' value (OR value)* ')'+// globValue := value with optional leading/trailing '*' wildcards:+// 'v*' starts-with, '*v' ends-with, '*v*' contains, 'v' default+//+// The parser NEVER throws. It returns an AST (best-effort on broken input)+// plus diagnostics with source spans; severity 'error' blocks commit, the+// editor renders them as underlines. The parser accepts MORE than the flat+// Langfuse filter contract can represent (e.g. cross-field OR) — those forms+// are rejected with targeted messages in validate.ts, not here.++import type { ASTNode, CompareOp, FilterNode, Span, TextNode } from "./ast";+import { canonicalKey, operatorIssue, resolveField } from "./fields";++export type Diagnostic = {+ from: number;+ to: number;+ severity: "error" | "warning";+ message: string;+};++export type ParseResult = {+ ast: ASTNode | null;+ diagnostics: Diagnostic[];+ /** true when there are no error-severity diagnostics */+ valid: boolean;+};++// ---- lexer ----++export type LexToken =+ | { type: "lparen"; span: Span }+ | { type: "rparen"; span: Span }+ | { type: "term"; raw: string; span: Span };++type Token = LexToken;++/**+ * The raw token stream for `input` (diagnostics discarded). The composer's+ * segment projection consumes this so its token boundaries are the lexer's,+ * never a re-derivation.+ */+export function lexTokens(input: string): LexToken[] {+ const throwaway: Diagnostic[] = [];+ return lex(input, throwaway);+}++// \s covers Unicode space separators (NBSP & friends) — pastes from+// Slack/Notion routinely carry U+00A0, which must split tokens like ' '.+const WHITESPACE = /\s/;++function lex(input: string, diagnostics: Diagnostic[]): Token[] {+ const tokens: Token[] = [];+ let i = 0;+ while (i < input.length) {+ const ch = input[i]!;+ if (WHITESPACE.test(ch)) {+ i++;+ continue;+ }+ if (ch === "(") {+ tokens.push({ type: "lparen", span: { from: i, to: i + 1 } });+ i++;+ continue;+ }+ if (ch === ")") {+ tokens.push({ type: "rparen", span: { from: i, to: i + 1 } });+ i++;+ continue;+ }+ // term: consume until whitespace/paren, but a double quote consumes+ // greedily through its closing quote (so key:"a b" stays one term).+ const start = i;+ while (i < input.length) {+ const c = input[i]!;+ if (WHITESPACE.test(c) || c === ")") break;+ if (c === "(") {+ if (i > start && input[i - 1] === ":") {+ const close = findClosingParen(input, i);+ if (close === -1) {+ diagnostics.push({+ from: i,+ to: input.length,+ severity: "error",+ message: 'Unclosed "("',+ });+ i = input.length;+ break;+ }+ i = close + 1;+ continue;+ }+ break;+ }+ if (c === '"') {+ const close = findClosingQuote(input, i);+ if (close === -1) {+ diagnostics.push({+ from: i,+ to: input.length,+ severity: "error",+ message: "Unclosed quote",+ });+ i = input.length;+ break;+ }+ i = close + 1;+ continue;+ }+ i++;+ }+ tokens.push({+ type: "term",+ raw: input.slice(start, i),+ span: { from: start, to: i },+ });+ }+ return tokens;+}++export function findClosingQuote(input: string, openIdx: number): number {+ for (let j = openIdx + 1; j < input.length; j++) {+ if (input[j] === "\\") {+ j++;+ continue;+ }+ if (input[j] === '"') return j;+ }+ return -1;+}++function findClosingParen(input: string, openIdx: number): number {+ let depth = 0;+ for (let j = openIdx; j < input.length; j++) {+ const c = input[j]!;+ if (c === '"') {+ const close = findClosingQuote(input, j);+ j = close === -1 ? input.length : close;+ continue;+ }+ if (c === "(") depth++;+ if (c === ")") {+ depth--;+ if (depth === 0) return j;+ }+ }+ return -1;+}++/** Split outside double quotes; returns segments with offsets into `s`. */+export function splitOutsideQuotes(+ s: string,+ sep: string,+): Array<{ text: string; offset: number }> {+ const out: Array<{ text: string; offset: number }> = [];+ let segStart = 0;+ let j = 0;+ while (j < s.length) {+ const c = s[j]!;+ if (c === '"') {+ const close = findClosingQuote(s, j);+ j = close === -1 ? s.length : close + 1;+ continue;+ }+ if (c === sep) {+ out.push({ text: s.slice(segStart, j), offset: segStart });+ segStart = j + 1;+ }+ j++;+ }+ out.push({ text: s.slice(segStart), offset: segStart });+ return out;+}++export function indexOfOutsideQuotes(s: string, ch: string): number {+ let j = 0;+ while (j < s.length) {+ const c = s[j]!;+ if (c === '"') {+ const close = findClosingQuote(s, j);+ j = close === -1 ? s.length : close + 1;+ continue;+ }+ if (c === ch) return j;+ j++;+ }+ return -1;+}++function unquote(s: string): { value: string; quoted: boolean } {+ const t = s.trim();+ if (t.length >= 2 && t.startsWith('"') && t.endsWith('"')) {+ // Inverse of serializeValue: \" and \\ are escapes, everything else literal.+ return { value: t.slice(1, -1).replace(/\\(["\\])/g, "$1"), quoted: true };+ }+ return { value: t, quoted: false };+}++// ---- term classification ----++function isKeyword(raw: string): "and" | "or" | "not" | null {+ if (raw === "AND") return "and";+ if (raw === "OR") return "or";+ if (raw === "NOT") return "not";+ return null;+}++// Operator prefixes between ':' and the value. Longest first so '>=' wins+// over '>'. Text-match ops (~/^/$) are NOT prefixes — they are positional `*`+// globs handled by parseGlob below. The grouped/list default is separate.+const OPERATOR_PREFIXES: Array<{ prefix: string; op: CompareOp }> = [+ { prefix: ">=", op: ">=" },+ { prefix: "<=", op: "<=" },+ { prefix: ">", op: ">" },+ { prefix: "<", op: "<" },+ { prefix: "=", op: "exact" },+];++// Positional `*` glob on a single (un-grouped) value → a text-match op.+// `v*` starts-with, `*v` ends-with, `*v*` contains. The `*`s are recognized+// only as the first/last char of the raw segment (a quoted value's edges are+// `"`, and stars inside quotes are literal), so `"a*b"` and `a*b` stay literal.+// Returns null when there is no anchoring star or no value survives stripping.+export function parseGlob(+ rawSegment: string,+): { op: CompareOp; core: string } | null {+ const leading = rawSegment.startsWith("*");+ const trailing = rawSegment.endsWith("*") && rawSegment.length > 1;+ if (!leading && !trailing) return null;+ let core = rawSegment;+ if (leading) core = core.slice(1);+ if (trailing) core = core.slice(0, -1);+ if (core.length === 0) return null; // lone `*` / `**` → treat as literal+ const op: CompareOp = leading && trailing ? "~" : trailing ? "^" : "$";+ return { op, core };+}++// Operator-looking tokens we don't support yet. Rather than silently treat+// them as free text (lowercase `not`/`or`/`and`) or as a cryptic "unknown+// field" (`!foo:bar`), surface an explicit "not supported yet" error. Quoting+// (`"or"`) escapes the word back into free text.+function reservedTokenIssue(raw: string): string | null {+ if (raw.startsWith("!")) {+ return '"!" is not supported yet — use -field:value to exclude (e.g. -env:dev)';+ }+ const lower = raw.toLowerCase();+ if (lower === "not") {+ return '"not" is not supported yet — use -field:value to exclude (e.g. -env:dev)';+ }+ if (lower === "or" || lower === "and") {+ return `"${raw}" between filters is not supported yet — combine one field's values with field:(A OR B), or quote "${raw}" to search text`;+ }+ return null;+}++function parseTermNode(+ raw: string,+ span: Span,+ diagnostics: Diagnostic[],+): FilterNode | TextNode {+ const reserved = reservedTokenIssue(raw);+ if (reserved !== null) {+ diagnostics.push({+ from: span.from,+ to: span.to,+ severity: "error",+ message: reserved,+ });+ const { value, quoted } = unquote(raw);+ return { kind: "text", value, quoted, span };+ }++ const colon = indexOfOutsideQuotes(raw, ":");+ if (colon === -1) {+ const { value, quoted } = unquote(raw);+ return { kind: "text", value, quoted, span };+ }++ const keyRaw = raw.slice(0, colon);+ const valueRaw = raw.slice(colon + 1);+ const ref = keyRaw.length === 0 ? null : resolveField(keyRaw);++ if (ref === null) {+ diagnostics.push({+ from: span.from,+ to: span.from + Math.max(colon, 1),+ severity: "error",+ message: `Unknown field "${keyRaw}"`,+ });+ } else if (NEEDS_QUOTES.test(keyRaw)) {+ // A key with quotes/spaces/grammar chars (e.g. `metadata."foo"`) has no+ // representable form — the reverse adapter routes it to skippedFilters, so+ // committing would silently clear the bar. Reject it at parse time instead.+ diagnostics.push({+ from: span.from,+ to: span.from + colon,+ severity: "error",+ message: `Field name "${keyRaw}" cannot contain quotes or spaces`,+ });+ }++ const key = ref === null ? keyRaw : canonicalKey(ref);++ // Op×field validity comes from the shared table so parser, validator, and+ // adapter agree (fields.operatorIssue).+ const pushOpIssue = (op: CompareOp, valueOp: "or" | "and" = "or") => {+ if (ref === null) return;+ const issue = operatorIssue(ref, op, valueOp);+ if (issue !== null) {+ diagnostics.push({+ from: span.from,+ to: span.to,+ severity: "error",+ message: issue,+ });+ }+ };++ if (valueRaw.length === 0) {+ diagnostics.push({+ from: span.from,+ to: span.to,+ severity: "error",+ message: `Missing value after "${keyRaw}:"`,+ });+ return { kind: "filter", key, rawKey: keyRaw, op: "=", values: [], span };+ }++ if (valueRaw.startsWith("(")) {+ const group = parseGroupedValues(+ valueRaw,+ span.from + colon + 1,+ diagnostics,+ );+ if (!valueRaw.endsWith(")")) {+ diagnostics.push({+ from: span.from + colon + 1,+ to: span.to,+ severity: "error",+ message: 'Unclosed "("',+ });+ }+ if (group.values.length === 0) {+ diagnostics.push({+ from: span.from,+ to: span.to,+ severity: "error",+ message: `Missing grouped value after "${keyRaw}:("`,+ });+ }+ pushOpIssue("=", group.valueOp);+ return {+ kind: "filter",+ key,+ rawKey: keyRaw,+ op: "=",+ values: group.values,+ valueOp: group.valueOp,+ span,+ };+ }++ for (const { prefix, op } of OPERATOR_PREFIXES) {+ if (valueRaw.startsWith(prefix)) {+ const scalarRaw = valueRaw.slice(prefix.length);+ const { value, quoted } = unquote(scalarRaw);+ // A quoted empty string (`:=""`) is an intentional empty value (same as+ // the comma-list branch below); only a bare empty is an error. This keeps+ // `metadata.foo:=""` — what the reverse adapter emits for an empty+ // stringObject filter — round-tripping instead of landing red.+ if (value.length === 0 && !quoted) {+ diagnostics.push({+ from: span.from,+ to: span.to,+ severity: "error",+ message: `Missing value after "${keyRaw}:${prefix}"`,+ });+ }+ pushOpIssue(op);+ return {+ kind: "filter",+ key,+ rawKey: keyRaw,+ op,+ values: value.length > 0 || quoted ? [value] : [],+ span,+ };+ }+ }++ const segments = splitOutsideQuotes(valueRaw, ",");++ // A single un-grouped value can carry positional `*` glob wildcards.+ if (segments.length === 1) {+ const glob = parseGlob(segments[0]!.text);+ if (glob !== null) {+ const { value, quoted } = unquote(glob.core);+ // A quoted empty value (`input:*""*`) is intentional — same carve-out as+ // the OPERATOR_PREFIXES and comma-list branches; it's what the reverse+ // adapter emits for an empty contains/starts/ends filter, so it must+ // round-trip rather than land red.+ if (value.length === 0 && !quoted) {+ diagnostics.push({+ from: span.from,+ to: span.to,+ severity: "error",+ message: `Missing value in "${keyRaw}:${segments[0]!.text}"`,+ });+ }+ pushOpIssue(glob.op);+ return {+ kind: "filter",+ key,+ rawKey: keyRaw,+ op: glob.op,+ values: value.length > 0 || quoted ? [value] : [],+ span,+ };+ }+ }++ const values: string[] = [];+ for (const seg of segments) {+ const { value, quoted } = unquote(seg.text);+ // A quoted empty string ("") is an intentional empty value (e.g. a filter+ // for an empty trace name); only a bare empty segment is an error.+ if (value.length === 0 && !quoted) {+ diagnostics.push({+ from: span.from,+ to: span.to,+ severity: "error",+ message: "Empty value in comma list",+ });+ continue;+ }+ values.push(value);+ }+ pushOpIssue("=");+ return { kind: "filter", key, rawKey: keyRaw, op: "=", values, span };+}++function parseGroupedValues(+ raw: string,+ offset: number,+ diagnostics: Diagnostic[],+): { values: string[]; valueOp: "or" | "and" } {+ const innerEnd = raw.endsWith(")") ? raw.length - 1 : raw.length;+ const inner = raw.slice(1, innerEnd);+ const localDiagnostics: Diagnostic[] = [];+ const tokens = lex(inner, localDiagnostics);+ for (const d of localDiagnostics) {+ diagnostics.push({+ ...d,+ from: d.from + offset + 1,+ to: d.to + offset + 1,+ });+ }++ const values: string[] = [];+ let valueOp: "or" | "and" = "or";+ let sawSeparator: "or" | "and" | null = null;+ let expectValue = true;+ let lastSeparator: { span: Span; raw: string } | null = null;++ for (const token of tokens) {+ const span = {+ from: token.span.from + offset + 1,+ to: token.span.to + offset + 1,+ };+ if (token.type !== "term") {+ diagnostics.push({+ from: span.from,+ to: span.to,+ severity: "error",+ message: "Nested groups are not supported inside grouped values",+ });+ continue;+ }++ if (token.raw === "OR" || token.raw === "AND") {+ const sep = token.raw === "OR" ? "or" : "and";+ if (expectValue) {+ diagnostics.push({+ from: span.from,+ to: span.to,+ severity: "error",+ message: `${token.raw} is missing a left-hand value`,+ });+ }+ if (sawSeparator !== null && sawSeparator !== sep) {+ diagnostics.push({+ from: span.from,+ to: span.to,+ severity: "error",+ message: "Cannot mix AND and OR inside one value group",+ });+ }+ sawSeparator = sep;+ valueOp = sep;+ expectValue = true;+ lastSeparator = { span, raw: token.raw };+ continue;+ }++ if (!expectValue) {+ diagnostics.push({+ from: span.from,+ to: span.to,+ severity: "error",+ message:+ "Expected uppercase OR (any of) or AND (all of) between grouped values",+ });+ }++ const { value, quoted } = unquote(token.raw);+ // A quoted empty string ("") is an intentional empty value; only a bare+ // empty token is an error.+ if (value.length === 0 && !quoted) {+ diagnostics.push({+ from: span.from,+ to: span.to,+ severity: "error",+ message: "Empty grouped value",+ });+ } else {+ // A bare comma inside a group (`tags:(a,b)`) lexes as one token, so it+ // would otherwise become the literal value "a,b" with no diagnostic.+ // Grouped values separate with uppercase OR/AND — flag it, but still push+ // the value so parseTermNode doesn't stack a misleading "missing grouped+ // value" on top of the comma error.+ if (indexOfOutsideQuotes(token.raw, ",") !== -1) {+ diagnostics.push({+ from: span.from,+ to: span.to,+ severity: "error",+ message:+ "Separate grouped values with uppercase OR or AND, not commas",+ });+ }+ values.push(value);+ }+ expectValue = false;+ lastSeparator = null;+ }++ // Only a TRAILING separator after a real value (`level:(a OR)`) dangles. A+ // lone separator (`level:(OR)`) already got the missing-left-hand diagnostic+ // at the same span, so gating on values.length avoids doubling it — mirrors+ // the parseAnd dangling-AND fix.+ if (lastSeparator !== null && values.length > 0) {+ diagnostics.push({+ from: lastSeparator.span.from,+ to: lastSeparator.span.to,+ severity: "error",+ message: `Dangling ${lastSeparator.raw} — expected a grouped value after it`,+ });+ }++ return { values, valueOp };+}++// ---- parser ----++export function parse(input: string): ParseResult {+ const diagnostics: Diagnostic[] = [];+ const tokens = lex(input, diagnostics);+ let pos = 0;++ const peek = (): Token | null => tokens[pos] ?? null;+ const next = (): Token | null => tokens[pos++] ?? null;++ function parseOr(): ASTNode | null {+ let left = parseAnd();+ while (true) {+ const t = peek();+ if (t?.type === "term" && isKeyword(t.raw) === "or") {+ next();+ const right = parseAnd();+ if (right === null) {+ diagnostics.push({+ from: t.span.from,+ to: t.span.to,+ severity: "error",+ message: "Dangling OR — expected an expression after it",+ });+ return left;+ }+ if (left === null) {+ diagnostics.push({+ from: t.span.from,+ to: t.span.to,+ severity: "error",+ message: "OR is missing a left-hand expression",+ });+ left = right;+ continue;+ }+ if (left.kind === "or") {+ left.children.push(right);+ } else {+ left = { kind: "or", children: [left, right] };+ }+ continue;+ }+ return left;+ }+ }++ function parseAnd(): ASTNode | null {+ const children: ASTNode[] = [];+ while (true) {+ const t = peek();+ if (t === null || t.type === "rparen") break;+ if (t.type === "term") {+ const kw = isKeyword(t.raw);+ if (kw === "or") break;+ if (kw === "and") {+ next();+ if (children.length === 0) {+ // Leading AND has nothing to join — mirror parseOr instead of+ // silently swallowing it (the "no silent drops/rewrites" contract).+ diagnostics.push({+ from: t.span.from,+ to: t.span.to,+ severity: "error",+ message: "AND is missing a left-hand expression",+ });+ }+ const upcoming = peek();+ const ends =+ upcoming === null ||+ upcoming.type === "rparen" ||+ (upcoming.type === "term" && isKeyword(upcoming.raw) === "or");+ // Only the "missing left-hand" message fires for a bare `AND`; the+ // dangling-AND message is for an AND that HAD a left operand but no+ // right, so gate it on children so one typo gets one diagnostic.+ if (ends && children.length > 0) {+ diagnostics.push({+ from: t.span.from,+ to: t.span.to,+ severity: "error",+ message: "Dangling AND — expected an expression after it",+ });+ }+ continue;+ }+ }+ const node = parseUnary();+ if (node !== null) children.push(node);+ }+ if (children.length === 0) return null;+ if (children.length === 1) return children[0]!;+ return { kind: "and", children };+ }++ function parseUnary(): ASTNode | null {+ const t = peek();+ if (t === null) return null;++ if (t.type === "rparen") {+ next();+ diagnostics.push({+ from: t.span.from,+ to: t.span.to,+ severity: "error",+ message: 'Unmatched ")"',+ });+ return null;+ }++ if (t.type === "lparen") {+ next();+ const inner = parseOr();+ const close = peek();+ let closedTo: number | null = null;+ if (close?.type === "rparen") {+ next();+ closedTo = close.span.to;+ } else {+ diagnostics.push({+ from: t.span.from,+ to: t.span.to,+ severity: "error",+ message: 'Unclosed "("',+ });+ }+ if (inner === null) {+ diagnostics.push({+ from: t.span.from,+ to: t.span.to,+ severity: "error",+ message: 'Empty group "()"',+ });+ }+ // Remember the paren extent so structured edits can remove the wrapping+ // parens together with their sole content ("(env:dev)" → "" not "()").+ if (inner !== null && closedTo !== null) {+ inner.parenSpan = { from: t.span.from, to: closedTo };+ }+ return inner;+ }++ // term+ const kw = isKeyword(t.raw);+ if (kw === "not") {+ next();+ const child = parseUnary();+ if (child === null) {+ diagnostics.push({+ from: t.span.from,+ to: t.span.to,+ severity: "error",+ message: "Dangling NOT — expected an expression after it",+ });+ return null;+ }+ return {+ kind: "not",+ child,+ span: { from: t.span.from, to: nodeEnd(child) ?? t.span.to },+ };+ }++ next();+ if (t.raw === "-") {+ // A bare "-" is not a negation operator — the dash form must be glued to+ // its filter ("-env:dev"). Standalone (e.g. "-(env:dev)" or the typo+ // "- env:dev") it would otherwise lower to a meaningless free-text term+ // while the following group/filter stays positive, silently inverting+ // the user's intent. Reject it with the same message as "-freetext".+ diagnostics.push({+ from: t.span.from,+ to: t.span.to,+ severity: "error",+ message: "Negation (-) only applies to field filters, e.g. -env:dev",+ });+ return parseTermNode(t.raw, t.span, diagnostics);+ }+ if (t.raw.startsWith("-") && t.raw.length > 1) {+ const inner = parseTermNode(+ t.raw.slice(1),+ { from: t.span.from + 1, to: t.span.to },+ diagnostics,+ );+ if (inner.kind === "text") {+ // "-foo" as free text would be a negated search term; not supported.+ diagnostics.push({+ from: t.span.from,+ to: t.span.to,+ severity: "error",+ message: "Negation (-) only applies to field filters, e.g. -env:dev",+ });+ return inner;+ }+ return { kind: "not", child: inner, span: t.span };+ }+ return parseTermNode(t.raw, t.span, diagnostics);+ }++ let ast = parseOr();+ // Top-level recovery: unmatched ")" (parseAnd stops at rparen). Report it,+ // skip it, and AND-merge whatever parses after.+ let leftover: Token | null;+ while ((leftover = peek()) !== null) {+ next();+ diagnostics.push({+ from: leftover.span.from,+ to: leftover.span.to,+ severity: "error",+ message:+ leftover.type === "rparen" ? 'Unmatched ")"' : "Unexpected input",+ });+ const more = parseOr();+ if (more !== null) {+ if (ast === null) ast = more;+ else if (ast.kind === "and") ast.children.push(more);+ else ast = { kind: "and", children: [ast, more] };+ }+ }++ // Tolerant recovery can flag the same span from more than one path (e.g. an+ // unclosed "(" caught by both the lexer and parseTermNode). Drop exact+ // duplicates so the composer doesn't render the same message twice.+ const deduped = dedupeDiagnostics(diagnostics);+ return {+ ast,+ diagnostics: deduped,+ valid: !deduped.some((d) => d.severity === "error"),+ };+}++function dedupeDiagnostics(diagnostics: Diagnostic[]): Diagnostic[] {+ const seen = new Set<string>();+ return diagnostics.filter((d) => {+ const key = `${d.from}:${d.to}:${d.severity}:${d.message}`;+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });+}++function nodeEnd(node: ASTNode): number | null {+ if (node.kind === "filter" || node.kind === "text" || node.kind === "not") {+ return node.span?.to ?? null;+ }+ const last = node.children[node.children.length - 1];+ return last ? nodeEnd(last) : null;+}++/**+ * The whitespace/paren-delimited term containing `pos` (quote-aware: quoted+ * spans with spaces stay one term). Null when the position sits in whitespace+ * or on a paren. Used by the editor's completion source so token boundaries+ * agree with the lexer instead of re-deriving them quote-blind.+ */+export function termAt(+ input: string,+ pos: number,+): { raw: string; from: number; to: number } | null {+ const throwaway: Diagnostic[] = [];+ for (const token of lex(input, throwaway)) {+ if (token.type !== "term") continue;+ if (pos >= token.span.from && pos <= token.span.to) {+ return { raw: token.raw, from: token.span.from, to: token.span.to };+ }+ }+ return null;+}++// ---- serializer ----++export const NEEDS_QUOTES = /[\s:,()"\\]/;+// A value/term that STARTS with an operator prefix would otherwise be reparsed+// as that operator (`name:>5` → comparison, `name:=x` → exact), and a leading+// `-` would be read as negation when the term is free text (`-foo`). Only the+// leading position matters — mid-value `-`/`>` (e.g. "gpt-4-turbo") is fine and+// must NOT force quoting. ( `-` is placed first in the class so it is a+// literal, not a range.)+const LEADING_OPERATOR = /^[-=><]/;+// A literal value whose first OR last char is `*` would otherwise be read as a+// glob anchor (`*v`/`v*`), so it must be quoted to stay literal.+const STAR_ANCHOR = /^\*|\*$/;++// Tokens reservedTokenIssue rejects as bare free text — they must round-trip+// quoted or the bar lands invalid on the next derive. Mirror that set exactly:+// AND/OR/NOT in any case lex as boolean operators, and a leading "!" is+// reserved for future negation (and not covered by LEADING_OPERATOR).+const RESERVED_BARE_TOKEN = /^(?:and|or|not)$/i;++export function serializeValue(value: string): string {+ if (+ value.length === 0 ||+ NEEDS_QUOTES.test(value) ||+ LEADING_OPERATOR.test(value) ||+ STAR_ANCHOR.test(value) ||+ value.startsWith("!") ||+ RESERVED_BARE_TOKEN.test(value)+ ) {+ // Escape \ before " — must be the exact inverse of unquote.+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;+ }+ return value;+}++// Inverse of OPERATOR_PREFIXES: prefix-style AST op -> typed prefix. The glob+// ops (~/^/$) are NOT prefixes — they wrap the value (see serializeFilter).+const OP_SYMBOL: Partial<Record<CompareOp, string>> = {+ "=": "",+ exact: "=",+ ">": ">",+ "<": "<",+ ">=": ">=",+ "<=": "<=",+};++export function serializeFilter(node: FilterNode): string {+ // Prefer the user's typed key (alias/casing) — surgery fallbacks shouldn't+ // canonicalize untouched filters.+ const key = node.rawKey ?? node.key;+ if (node.op === "=" && node.values.length > 1) {+ const joiner = node.valueOp === "and" ? " AND " : " OR ";+ return `${key}:(${node.values.map(serializeValue).join(joiner)})`;+ }+ // Text-match ops render as positional `*` globs around the value.+ if (node.op === "~" || node.op === "^" || node.op === "$") {+ const v = serializeValue(node.values[0] ?? "");+ const wrapped =+ node.op === "~" ? `*${v}*` : node.op === "^" ? `${v}*` : `*${v}`;+ return `${key}:${wrapped}`;+ }+ return `${key}:${OP_SYMBOL[node.op] ?? ""}${node.values.map(serializeValue).join(",")}`;+}++function sameFieldOrGroup(node: ASTNode): FilterNode[] | null {+ if (node.kind !== "or") return null;+ const filters = node.children.filter(+ (c): c is FilterNode => c.kind === "filter",+ );+ if (filters.length !== node.children.length || filters.length < 2)+ return null;+ const first = filters[0]!;+ if (first.op !== "=" || first.values.length !== 1) return null;+ for (const f of filters) {+ if (f.key !== first.key || f.op !== "=" || f.values.length !== 1)+ return null;+ }+ return filters;+}++function serializeSameFieldOr(filters: FilterNode[], negated = false): string {+ const first = filters[0]!;+ const key = first.rawKey ?? first.key;+ const values = filters.flatMap((f) => f.values);+ return `${negated ? "-" : ""}${key}:(${values.map(serializeValue).join(" OR ")})`;+}++/**+ * Canonical text for an AST. Precedence-aware: AND children join with a space+ * (implicit AND), OR joins with " OR ", OR children inside AND get parens,+ * NOT serializes as "-" before a filter and "NOT (...)" before a group.+ */+export function serialize(ast: ASTNode | null): string {+ if (ast === null) return "";+ switch (ast.kind) {+ case "filter":+ return serializeFilter(ast);+ case "text":+ // Always route through serializeValue so bare keywords (AND/OR/NOT) and+ // leading-operator/hyphen free text get quoted and reparse as text.+ return serializeValue(ast.value);+ case "not": {+ const child = ast.child;+ if (child.kind === "filter") return `-${serializeFilter(child)}`;+ const sameField = sameFieldOrGroup(child);+ if (sameField !== null) return serializeSameFieldOr(sameField, true);+ if (child.kind === "not") return `NOT (${serialize(child)})`;+ if (child.kind === "text") return `NOT ${serialize(child)}`;+ return `NOT (${serialize(child)})`;+ }+ case "and":+ // Nested groups keep their parens: OR for precedence, AND so the+ // canonical text reparses to the same structure (a bare "a b AND c"+ // would flatten).+ return ast.children+ .map((c) => {+ if (c.kind === "or") {+ return sameFieldOrGroup(c) !== null+ ? serialize(c)+ : `(${serialize(c)})`;+ }+ return c.kind === "and" ? `(${serialize(c)})` : serialize(c);+ })+ .join(" ");+ case "or": {+ const sameField = sameFieldOrGroup(ast);+ if (sameField !== null) return serializeSameFieldOr(sameField);+ // A nested OR group (e.g. "a OR (b OR c)") must keep its parens or the+ // chain flattens on reparse; AND children reparse correctly bare+ // (implicit AND binds tighter than OR).+ return ast.children+ .map((c) => (c.kind === "or" ? `(${serialize(c)})` : serialize(c)))+ .join(" OR ");+ }+ }+}diff --git a/web/src/features/search-bar/lib/observed-options.ts b/web/src/features/search-bar/lib/observed-options.tsnew file mode 100644index 0000000000..66185624ee--- /dev/null+++ b/web/src/features/search-bar/lib/observed-options.ts@@ -0,0 +1,117 @@+// Bridge from the events filterOptions payload (useEventsFilterOptions) to+// the flat per-column observed-value map the completion planner consumes.+//+// Keys:+// <columnId> → observed values (with counts when known)+// scores_avg / trace_scores_avg → numeric score NAMES+// score_categories[.<name>] → categorical score names / their values+// (metadata keys are not enumerated by the API today — metadata key paths+// complete from free typing only)++import type { ScoreTypeContext } from "./adapter";++export type ObservedValue = { value: string; count?: number };+export type ObservedOptions = Record<string, ObservedValue[]>;++type RawOption = string | { value: string; count?: number };++type RawFilterOptions = Record<+ string,+ RawOption[] | Record<string, string[]> | undefined+>;++function toObservedValues(options: RawOption[]): ObservedValue[] {+ const out: ObservedValue[] = [];+ for (const o of options) {+ if (typeof o === "string") {+ if (o.length > 0) out.push({ value: o });+ } else if (o && typeof o.value === "string" && o.value.length > 0) {+ out.push(+ o.count !== undefined+ ? { value: o.value, count: o.count }+ : { value: o.value },+ );+ }+ }+ return out;+}++/**+ * Flatten the sidebar filter-options shape into observed-value lists keyed+ * the way the completion planner looks them up. Returns undefined while the+ * source is still loading so value stages can show a loading row.+ */+export function toObservedOptions(+ raw: RawFilterOptions | undefined,+ loading: boolean,+): ObservedOptions | undefined {+ if (loading || raw === undefined) return undefined;++ const out: ObservedOptions = {};+ for (const [column, options] of Object.entries(raw)) {+ if (options === undefined) continue;+ if (Array.isArray(options)) {+ out[column] = toObservedValues(options);+ continue;+ }+ // Keyed columns (score_categories & friends): Record<name, values[]>.+ out[column] = Object.keys(options).map((name) => ({ value: name }));+ for (const [name, values] of Object.entries(options)) {+ out[`${column}.${name}`] = values+ .filter((v) => v.length > 0)+ .map((v) => ({ value: v }));+ }+ }+ return out;+}++/**+ * Derive the score-name→type sets the adapter needs to route+ * `scores.<name>:<value>` to the numeric (`scores_avg`) vs categorical+ * (`score_categories`) column. Built from the same observed map the completion+ * planner reads, so the bar's suggestions and its commit agree on score types.+ */+export function scoreTypeContextFromObserved(+ observed: ObservedOptions | undefined,+): ScoreTypeContext {+ const names = (column: string): Set<string> =>+ new Set((observed?.[column] ?? []).map((o) => o.value));+ return {+ numericScoreNames: names("scores_avg"),+ categoricalScoreNames: names("score_categories"),+ traceNumericScoreNames: names("trace_scores_avg"),+ traceCategoricalScoreNames: names("trace_score_categories"),+ };+}++function nameSetsEqual(+ a: ReadonlySet<string> | undefined,+ b: ReadonlySet<string> | undefined,+): boolean {+ if (a === b) return true;+ const sizeA = a?.size ?? 0;+ const sizeB = b?.size ?? 0;+ if (sizeA !== sizeB) return false;+ if (a) for (const v of a) if (!b?.has(v)) return false;+ return true;+}++/**+ * Set-equality of the four score-name sets. `scoreTypeContextFromObserved`+ * builds a fresh context on every `filterOptions` refetch, so under+ * auto-refresh on a relative time range the context identity rotates every tick+ * even when the underlying score types are unchanged. Callers use this to skip+ * re-validating the draft when the routing-relevant data did not actually move.+ */+export function scoreTypeContextEqual(+ a: ScoreTypeContext | undefined,+ b: ScoreTypeContext | undefined,+): boolean {+ if (a === b) return true;+ return (+ nameSetsEqual(a?.numericScoreNames, b?.numericScoreNames) &&+ nameSetsEqual(a?.categoricalScoreNames, b?.categoricalScoreNames) &&+ nameSetsEqual(a?.traceNumericScoreNames, b?.traceNumericScoreNames) &&+ nameSetsEqual(a?.traceCategoricalScoreNames, b?.traceCategoricalScoreNames)+ );+}diff --git a/web/src/features/search-bar/lib/recent-searches.ts b/web/src/features/search-bar/lib/recent-searches.tsnew file mode 100644index 0000000000..e12faa88ed--- /dev/null+++ b/web/src/features/search-bar/lib/recent-searches.ts@@ -0,0 +1,38 @@+// Recent searches — localStorage-backed, newest first, scoped per project+// (the empty-state section of the search bar dropdown).++const KEY_PREFIX = "lf-search-bar-recents";+const MAX = 8;++function storageKey(projectId: string): string {+ return `${KEY_PREFIX}:${projectId}`;+}++export function getRecentSearches(projectId: string): string[] {+ if (typeof localStorage === "undefined") return [];+ try {+ const raw = JSON.parse(+ localStorage.getItem(storageKey(projectId)) ?? "[]",+ ) as unknown;+ return Array.isArray(raw)+ ? raw.filter((x): x is string => typeof x === "string")+ : [];+ } catch {+ return [];+ }+}++export function recordRecentSearch(projectId: string, query: string): void {+ if (typeof localStorage === "undefined") return;+ const trimmed = query.trim();+ if (trimmed.length === 0) return;+ const next = [+ trimmed,+ ...getRecentSearches(projectId).filter((q) => q !== trimmed),+ ].slice(0, MAX);+ try {+ localStorage.setItem(storageKey(projectId), JSON.stringify(next));+ } catch {+ // storage full/blocked — recents are best-effort+ }+}diff --git a/web/src/features/search-bar/lib/searchBarInvariants.clienttest.ts b/web/src/features/search-bar/lib/searchBarInvariants.clienttest.tsnew file mode 100644index 0000000000..432cf7785c--- /dev/null+++ b/web/src/features/search-bar/lib/searchBarInvariants.clienttest.ts@@ -0,0 +1,87 @@+import { describe, expect, it } from "vitest";++import { FIELDS } from "./fields";+import {+ generateQueryCases,+ runSearchBarInvariants,+ type RegistryUnderTest,+} from "./searchBarInvariants";++// Per-view wiring of the property harness. A second filterable view adopts the+// bar by adding its own block here with its registry — the harness is unchanged.+// See README.md "Extending to other views (the universality contract)".+const eventsView: RegistryUnderTest = {+ name: "events v4",+ fields: FIELDS,+ // Grammar overlay: dot-path examples + pseudo-fields (README step 2).+ extraKeys: [+ "metadata.region",+ "scores.accuracy",+ "traceScores.nps",+ "has:endTime",+ "has:latency",+ ],+ // Numeric vs categorical routing for scores.accuracy must not change which+ // invariants hold — only how a score lowers.+ scoreContexts: [+ {+ numericScoreNames: new Set(["accuracy"]),+ categoricalScoreNames: new Set(),+ traceNumericScoreNames: new Set(),+ traceCategoricalScoreNames: new Set(["nps"]),+ },+ {+ numericScoreNames: new Set(),+ categoricalScoreNames: new Set(["accuracy"]),+ traceNumericScoreNames: new Set(["nps"]),+ traceCategoricalScoreNames: new Set(),+ },+ ],+ fieldValues: ["x", "ERROR", "5", "0.8", "2026-06-01", "true", "a b", "gpt-4"],+ // Adversarial free text — the tokens the parser reserves/quotes. The bare+ // boolean keywords and `!`-prefix here are the exact #4 regression class.+ freeTextValues: [+ "hello",+ "refund policy",+ "or",+ "and",+ "not",+ "OR",+ "AND",+ "NOT",+ "team or kitten",+ "test not really",+ "!important",+ "!critical bug",+ "-foo",+ "a,b",+ "gpt-4-turbo",+ "key:value",+ "(grouped)",+ 'has "quote"',+ ],+};++describe("search bar invariants — events v4 registry", () => {+ it("generates a broad field × operator × value matrix", () => {+ // Sanity: the matrix actually exercises the registry (guards against a+ // future refactor silently emptying the generator).+ expect(generateQueryCases(eventsView).length).toBeGreaterThan(1000);+ });++ it("holds all three invariants (parity, round-trip, serialize symmetry)", () => {+ const failures = runSearchBarInvariants(eventsView);+ // Surface every failing case, not just the first, for a fast diagnosis.+ expect(+ failures,+ failures.length === 0+ ? "ok"+ : `\n${failures+ .slice(0, 25)+ .map((f) => ` [${f.invariant}] ${f.case} — ${f.detail}`)+ .join(+ "\n",+ )}${failures.length > 25 ? `\n …and ${failures.length - 25} more` : ""}`,+ ).toEqual([]);+ });+});diff --git a/web/src/features/search-bar/lib/searchBarInvariants.ts b/web/src/features/search-bar/lib/searchBarInvariants.tsnew file mode 100644index 0000000000..5f8b3037da--- /dev/null+++ b/web/src/features/search-bar/lib/searchBarInvariants.ts@@ -0,0 +1,203 @@+// Reusable property-test harness for the search bar — the universal safety net+// described in README.md ("Round-trip property test", "Extending to other+// views"). It is PURE (no vitest import, no global state) so it is safe in the+// build and so any *.clienttest.ts can drive it. A view wires its registry in+// once; the harness generates the field × operator × value matrix from that+// registry and checks three invariants that have each regressed in this PR's+// history:+//+// INV-1 commit-gate parity — validateQuery(text).valid === true MUST imply+// the commit-time lowering (astToFilterState) produces no errors.+// (Regressed in 6e84fe4 / 32215fb: validate clean while lower errored+// → an empty filter set committed silently.)+// INV-2 no silent drop/rewrite — FilterState → text → FilterState is stable:+// every filter round-trips unchanged or is reported in skippedFilters,+// and nothing is rewritten into a different filter.+// INV-3 serialize ↔ parse symmetry — a free-text value always re-parses to+// itself and stays valid. (Regressed in #4: serializeValue emitted a+// bare reserved token — `or`, `!important` — that the parser rejects.)+//+// "Repeats itself per view": when a second filterable view adopts the bar, call+// runSearchBarInvariants({ name, fields, extraKeys, ... }) with that view's+// registry. The generators read `view.fields`, so they cover new/changed fields+// automatically. Today parse/validate/lower close over the single global FIELDS+// registry; when the grammar is parameterized over an injected registry (the+// seam in README "Extending to other views"), thread `view.registry` into the+// parse/validate/lower calls below — the generators and assertions do not+// change.++import type { FieldDef } from "./fields";+import type { ScoreTypeContext } from "./adapter";+import type { FilterState } from "@langfuse/shared";+import { parse, serialize } from "./langQ";+import { astToFilterState } from "./adapter";+import { validateQuery } from "./validate";+import { filterStateToQueryText } from "./filter-state-to-query";++/** A filterable view's grammar surface under test. */+export type RegistryUnderTest = {+ /** Label for failure messages (e.g. "events v4"). */+ name: string;+ /** The field registry the grammar resolves against. */+ fields: FieldDef[];+ /**+ * Grammar-overlay keys that are not plain fields: dot-path examples+ * (`metadata.region`, `scores.accuracy`, `traceScores.nps`) and the `has:`+ * pseudo-field. These exercise resolveField branches the field list alone does+ * not reach.+ */+ extraKeys: string[];+ /** Score-type contexts to vary (routes scores.<name> numeric vs categorical). */+ scoreContexts: ScoreTypeContext[];+ /** Values tried as filter values across fields/operators. */+ fieldValues: string[];+ /**+ * Free-text values for INV-3. Include adversarial tokens the parser reserves+ * or quotes (boolean keywords any case, `!`-prefix, whitespace, commas,+ * leading operators, quotes) — these are what break serialize↔parse.+ */+ freeTextValues: string[];+};++export type InvariantFailure = {+ invariant: string;+ case: string;+ detail: string;+};++// Prefix operators a value can carry after the colon, plus positional `*` glob+// wraps (starts/ends/contains). INV-1 does not need to know which are valid for+// a given field — it only checks the two gates agree — so we throw the whole+// set at every field. `%s` is replaced by the value.+const OP_PREFIXES = ["", "=", ">", "<", ">=", "<="] as const;+const GLOB_FORMS = ["%s*", "*%s", "*%s*"] as const;+const GROUP_VALUES = ["(a OR b)", "(a AND b)", "(a)"] as const;++function stable(value: unknown): string {+ return JSON.stringify(value, (_k, v) =>+ v && typeof v === "object" && !Array.isArray(v)+ ? Object.fromEntries(+ Object.entries(v as Record<string, unknown>).sort(([a], [b]) =>+ a < b ? -1 : a > b ? 1 : 0,+ ),+ )+ : v,+ );+}++/** Multiset equality of two filter lists, order-independent. */+function sameFilters(a: FilterState, b: FilterState): boolean {+ if (a.length !== b.length) return false;+ const sortedA = a.map(stable).sort();+ const sortedB = b.map(stable).sort();+ return sortedA.every((s, i) => s === sortedB[i]);+}++/** Every query string the matrix generates for a view. */+export function generateQueryCases(view: RegistryUnderTest): string[] {+ const keys = [...view.fields.map((f) => f.id), ...view.extraKeys];+ const cases: string[] = [];+ for (const key of keys) {+ // `has:` entries already carry their own value in extraKeys.+ if (key.includes(":")) {+ cases.push(key, `-${key}`);+ continue;+ }+ for (const neg of ["", "-"]) {+ for (const value of view.fieldValues) {+ for (const op of OP_PREFIXES) {+ cases.push(`${neg}${key}:${op}${value}`);+ }+ for (const glob of GLOB_FORMS) {+ cases.push(`${neg}${key}:${glob.replace("%s", value)}`);+ }+ }+ for (const group of GROUP_VALUES) {+ cases.push(`${neg}${key}:${group}`);+ }+ }+ }+ return cases;+}++/** INV-1: a query the commit gate accepts must lower without errors. */+function checkParity(+ text: string,+ ctx: ScoreTypeContext | undefined,+): InvariantFailure | null {+ if (!validateQuery(text, ctx).valid) return null; // gate rejects → no claim+ const errors = astToFilterState(parse(text).ast, ctx).errors;+ if (errors.length === 0) return null;+ return {+ invariant: "INV-1 commit-gate parity",+ case: text,+ detail: `validateQuery accepted but lowering errored: ${errors.join("; ")}`,+ };+}++/** INV-2: FilterState → text → FilterState is stable (no drop, no rewrite). */+function checkFilterStateRoundTrip(+ text: string,+ ctx: ScoreTypeContext | undefined,+): InvariantFailure | null {+ if (!validateQuery(text, ctx).valid) return null;+ const first = astToFilterState(parse(text).ast, ctx);+ if (first.errors.length > 0 || first.filters.length === 0) return null;+ const fs1 = first.filters;+ const forward = filterStateToQueryText(fs1);+ const fs2 = astToFilterState(parse(forward.text).ast, ctx).filters;+ // Filters with no grammar form are preserved via skippedFilters, not text.+ const expected = fs1.filter(+ (f) => !forward.skippedFilters.some((s) => stable(s) === stable(f)),+ );+ if (sameFilters(fs2, expected)) return null;+ return {+ invariant: "INV-2 FilterState round-trip",+ case: text,+ detail: `expected ${stable(expected)} (+skipped ${stable(+ forward.skippedFilters,+ )}) but re-lowered "${forward.text}" to ${stable(fs2)}`,+ };+}++/** INV-3: a free-text value re-parses to itself and stays valid. */+function checkSerializeSymmetry(value: string): InvariantFailure | null {+ const text = serialize({ kind: "text", value });+ const res = parse(text);+ const ast = res.ast;+ const ok = res.valid && ast?.kind === "text" && ast.value === value;+ if (ok) return null;+ return {+ invariant: "INV-3 serialize↔parse symmetry",+ case: JSON.stringify(value),+ detail: `serialize→"${text}" reparsed valid=${res.valid}, value=${+ ast?.kind === "text" ? JSON.stringify(ast.value) : `<${ast?.kind}>`+ }`,+ };+}++/**+ * Run all three invariants over a view's registry and return every failure.+ * The caller (a *.clienttest.ts) asserts the list is empty.+ */+export function runSearchBarInvariants(+ view: RegistryUnderTest,+): InvariantFailure[] {+ const failures: InvariantFailure[] = [];+ const contexts: (ScoreTypeContext | undefined)[] =+ view.scoreContexts.length > 0 ? view.scoreContexts : [undefined];++ for (const text of generateQueryCases(view)) {+ for (const ctx of contexts) {+ const parity = checkParity(text, ctx);+ if (parity) failures.push(parity);+ const roundTrip = checkFilterStateRoundTrip(text, ctx);+ if (roundTrip) failures.push(roundTrip);+ }+ }+ for (const value of view.freeTextValues) {+ const symmetry = checkSerializeSymmetry(value);+ if (symmetry) failures.push(symmetry);+ }+ return failures;+}diff --git a/web/src/features/search-bar/lib/validate.clienttest.ts b/web/src/features/search-bar/lib/validate.clienttest.tsnew file mode 100644index 0000000000..4eba95bbf7--- /dev/null+++ b/web/src/features/search-bar/lib/validate.clienttest.ts@@ -0,0 +1,81 @@+import { describe, expect, it } from "vitest";++import { parse } from "./langQ";+import { semanticDiagnostics, validateQuery } from "./validate";++function warnings(query: string): string[] {+ const { ast } = parse(query);+ return semanticDiagnostics(ast, query.length)+ .filter((d) => d.severity === "warning")+ .map((d) => d.message);+}++describe("semanticDiagnostics — has: polarity", () => {+ it("positive has: on a non-nullable field matches everything", () => {+ expect(warnings("has:level")).toContain(+ '"level" always has a value — this filter matches everything',+ );+ });++ // `-has:level` lowers to `level IS NULL`, which is vacuously false on a+ // non-nullable column — it matches NOTHING, the opposite of the positive+ // form. The warning must flip with polarity.+ it("negated has: on a non-nullable field matches nothing (dash form)", () => {+ expect(warnings("-has:level")).toContain(+ '"level" always has a value — this filter matches nothing',+ );+ });++ it("negated has: on a non-nullable field matches nothing (NOT keyword)", () => {+ expect(warnings("NOT has:level")).toContain(+ '"level" always has a value — this filter matches nothing',+ );+ });++ it("double negation matches everything again", () => {+ expect(warnings("NOT NOT has:level")).toContain(+ '"level" always has a value — this filter matches everything',+ );+ });+});++describe("validateQuery — merged-diagnostic dedup", () => {+ // The parser (pushOpIssue) and the adapter (operatorIssue in lowerFilter)+ // both flag the same operator/field mismatch at the same span. validateQuery+ // merges the two lists, so it must dedupe — otherwise the global tooltip and+ // aria-live region announce the same message twice for a single typo.+ function errorMessages(query: string): string[] {+ return validateQuery(query)+ .diagnostics.filter((d) => d.severity === "error")+ .map((d) => d.message);+ }++ it.each(["metadata.region:>5", "level:>5", "traceTags:*tag*", "xyz:1"])(+ "emits each error message once for %s",+ (query) => {+ const messages = errorMessages(query);+ expect(messages.length).toBeGreaterThan(0);+ expect(new Set(messages).size).toBe(messages.length);+ },+ );++ // A `key:` typo (no value) is flagged by BOTH the parser and the adapter; the+ // two messages must be identical so dedup collapses them to ONE (two+ // different strings would both survive — the prior bug).+ it.each([+ ["level:", 'Missing value after "level:"'],+ ["tags:", 'Missing value after "tags:"'],+ ["metadata.region:", 'Missing value after "metadata.region:"'],+ ["has:", 'Missing value after "has:"'],+ // textSearch column with no value; operator-prefix forms carry the prefix+ // in the parser's wording — both previously doubled.+ ["input:", 'Missing value after "input:"'],+ ["level:=", 'Missing value after "level:="'],+ ["latency:>", 'Missing value after "latency:>"'],+ ])(+ "surfaces exactly one empty-value diagnostic for %s",+ (query, expected) => {+ expect(errorMessages(query)).toEqual([expected]);+ },+ );+});diff --git a/web/src/features/search-bar/lib/validate.ts b/web/src/features/search-bar/lib/validate.tsnew file mode 100644index 0000000000..9b9180ae14--- /dev/null+++ b/web/src/features/search-bar/lib/validate.ts@@ -0,0 +1,166 @@+// Semantic validation — the single "is this committable" gate.+//+// The tolerant parser accepts structurally-fine input that the flat Langfuse+// filter contract cannot represent (cross-field OR, junk values for typed+// fields, negations with no counterpart…). Commit must gate on BOTH, with+// span-carrying diagnostics so the editor can underline the offending token.+//+// Parity with the adapter is by construction: each top-level node is lowered+// through the real adapter and its errors become diagnostics at that node's+// span. `valid === true` therefore guarantees astToFilterState() lowers the+// whole query without errors.++import type { ASTNode, Span } from "./ast";+import { astToFilterState, type ScoreTypeContext } from "./adapter";+import { nullableFields, resolveField } from "./fields";+import { parse, type Diagnostic, type ParseResult } from "./langQ";++export const MAX_QUERY_LENGTH = 2048;++function nodeSpan(node: ASTNode, textLength: number): Span {+ if (node.kind === "and" || node.kind === "or") {+ if (node.parenSpan) return node.parenSpan;+ const first = node.children[0];+ const last = node.children[node.children.length - 1];+ if (first && last) {+ return {+ from: nodeSpan(first, textLength).from,+ to: nodeSpan(last, textLength).to,+ };+ }+ return { from: 0, to: textLength };+ }+ return node.parenSpan ?? node.span ?? { from: 0, to: textLength };+}++const NULLABLE_FIELD_IDS = new Set(nullableFields().map((f) => f.id));++/**+ * `has:` on a column that always has a value matches everything — and its+ * negation (`-has:` / `NOT has:`) lowers to `IS NULL`, which is vacuously+ * false on a non-nullable column, so it matches nothing. `negated` tracks+ * polarity through `NOT` so the warning states the right side.+ */+function hasFilterWarnings(+ node: ASTNode,+ textLength: number,+ out: Diagnostic[],+ negated = false,+): void {+ switch (node.kind) {+ case "filter": {+ const ref = resolveField(node.key);+ if (ref === null || ref.type !== "pseudo" || ref.id !== "has") return;+ for (const v of node.values) {+ const target = resolveField(v);+ if (+ target !== null &&+ target.type === "field" &&+ !NULLABLE_FIELD_IDS.has(target.field.id)+ ) {+ const span = nodeSpan(node, textLength);+ out.push({+ from: span.from,+ to: span.to,+ severity: "warning",+ message: negated+ ? `"${target.field.id}" always has a value — this filter matches nothing`+ : `"${target.field.id}" always has a value — this filter matches everything`,+ });+ }+ }+ return;+ }+ case "text":+ return;+ case "not":+ hasFilterWarnings(node.child, textLength, out, !negated);+ return;+ case "and":+ case "or":+ for (const c of node.children)+ hasFilterWarnings(c, textLength, out, negated);+ return;+ }+}++export function semanticDiagnostics(+ ast: ASTNode | null,+ textLength: number,+ scoreTypes?: ScoreTypeContext,+): Diagnostic[] {+ const out: Diagnostic[] = [];+ if (ast === null) return out;++ // Lower each top-level node independently so error spans point at the+ // offending node instead of the whole query. The lowering must see the same+ // 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];+ for (const node of topLevel) {+ const { errors } = astToFilterState(node, scoreTypes);+ const span = nodeSpan(node, textLength);+ for (const message of errors) {+ out.push({ from: span.from, to: span.to, severity: "error", message });+ }+ hasFilterWarnings(node, textLength, out);+ }++ return out;+}++/**+ * The parser and the adapter both run the same operator-/field-validity checks+ * (operatorIssue, ref resolution), so a single filter typo surfaces twice once+ * the two lists are merged — and the composer joins all messages into the+ * global tooltip + aria-live region, announcing it twice. parse() already+ * dedupes its own list by exact span+message, but the parser anchors the+ * unknown-field diagnostic at the key span (`xyz`) while the adapter wraps at+ * the full term span (`xyz:1`), so an exact key misses that pair. Drop a later+ * diagnostic whose severity+message duplicates an earlier kept one AND whose+ * span overlaps it — two distinct tokens never overlap, so per-token underlines+ * are preserved.+ */+function dedupeMergedDiagnostics(diagnostics: Diagnostic[]): Diagnostic[] {+ const kept: Diagnostic[] = [];+ for (const d of diagnostics) {+ const dup = kept.some(+ (k) =>+ k.severity === d.severity &&+ k.message === d.message &&+ k.from < d.to &&+ d.from < k.to,+ );+ if (!dup) kept.push(d);+ }+ return kept;+}++/**+ * parse() + semantic checks + length cap, merged. `valid === true` guarantees+ * the adapter can lower the query — the one commit gate. `scoreTypes` must+ * match what the commit-time lowering uses so the two stay in parity.+ */+export function validateQuery(+ text: string,+ scoreTypes?: ScoreTypeContext,+): ParseResult {+ const res = parse(text);+ const diagnostics = dedupeMergedDiagnostics([+ ...res.diagnostics,+ ...semanticDiagnostics(res.ast, text.length, scoreTypes),+ ]);+ if (text.length > MAX_QUERY_LENGTH) {+ diagnostics.push({+ from: 0,+ to: text.length,+ severity: "error",+ message: `Query is too long (${text.length} chars, max ${MAX_QUERY_LENGTH})`,+ });+ }+ return {+ ast: res.ast,+ diagnostics,+ valid: !diagnostics.some((d) => d.severity === "error"),+ };+}diff --git a/web/src/features/search-bar/store/SearchBarStoreProvider.tsx b/web/src/features/search-bar/store/SearchBarStoreProvider.tsxnew file mode 100644index 0000000000..3f565f3781--- /dev/null+++ b/web/src/features/search-bar/store/SearchBarStoreProvider.tsx@@ -0,0 +1,55 @@+import { createContext, useContext, useMemo, type ReactNode } from "react";+import { useStore } from "zustand";++import {+ type SearchBarStore,+ type SearchBarStoreState,+} from "@/src/features/search-bar/store/searchBarStore";++type SearchBarContextValue = {+ store: SearchBarStore;+ /** Apply the current draft to the table's filter state (single source of+ * truth). Returns false and reveals diagnostics when the draft is invalid. */+ commit: () => boolean;+};++const SearchBarContext = createContext<SearchBarContextValue | null>(null);++export function SearchBarStoreProvider({+ children,+ store,+ commit,+}: {+ children: ReactNode;+ store: SearchBarStore;+ commit: () => boolean;+}) {+ const value = useMemo(() => ({ store, commit }), [store, commit]);+ return (+ <SearchBarContext.Provider value={value}>+ {children}+ </SearchBarContext.Provider>+ );+}++function useSearchBarContext(): SearchBarContextValue {+ const ctx = useContext(SearchBarContext);+ if (!ctx) {+ throw new Error("useSearchBar* must be used within SearchBarStoreProvider");+ }+ return ctx;+}++export function useSearchBarStoreApi(): SearchBarStore {+ return useSearchBarContext().store;+}++export function useSearchBarStore<TValue>(+ selector: (state: SearchBarStoreState) => TValue,+): TValue {+ return useStore(useSearchBarContext().store, selector);+}++export function useSearchBarCommit(): () => boolean {+ return useSearchBarContext().commit;+}diff --git a/web/src/features/search-bar/store/searchBarStore.clienttest.ts b/web/src/features/search-bar/store/searchBarStore.clienttest.tsnew file mode 100644index 0000000000..0742901c28--- /dev/null+++ b/web/src/features/search-bar/store/searchBarStore.clienttest.ts@@ -0,0 +1,258 @@+import { createSearchBarStore } from "@/src/features/search-bar/store/searchBarStore";++describe("searchBarStore (draft-only)", () => {+ it("validates the draft on setDraft", () => {+ const store = createSearchBarStore();+ store.getState().actions.setDraft("level:ERROR");+ expect(store.getState().draft).toBe("level:ERROR");+ expect(store.getState().draftValid).toBe(true);++ store.getState().actions.setDraft("level:ERROR OR env:dev");+ expect(store.getState().draftValid).toBe(false);+ expect(store.getState().draftDiagnostics.length).toBeGreaterThan(0);+ });++ it("seeds the draft from the committed baseline via resetTo", () => {+ const store = createSearchBarStore();+ store.getState().actions.resetTo("env:prod latency:>2");+ expect(store.getState().draft).toBe("env:prod latency:>2");+ expect(store.getState().draftValid).toBe(true);+ });++ it("resetTo is a no-op when the draft already matches (settles a commit echo)", () => {+ const store = createSearchBarStore();+ store.getState().actions.setDraft("level:ERROR");+ let notified = 0;+ const unsub = store.subscribe(() => notified++);+ store.getState().actions.resetTo("level:ERROR");+ unsub();+ expect(notified).toBe(0);+ });++ it("resetTo keeps a typed alias when the canonical echo is equivalent", () => {+ // Commit bounces `env:dev` through canonical URL state and re-derives+ // `environment:dev`; resetTo must NOT clobber the user's typed alias, since+ // the two are semantically identical (no silent rewrite).+ const store = createSearchBarStore();+ store.getState().actions.setDraft("env:dev");+ store.getState().actions.resetTo("environment:dev");+ expect(store.getState().draft).toBe("env:dev");+ // But a genuinely different committed text (external edit) still re-seeds.+ store.getState().actions.resetTo("level:ERROR");+ expect(store.getState().draft).toBe("level:ERROR");+ });++ it("resetTo keeps a typed negation that the adapter folds into the value/op", () => {+ // The adapter folds `-` into the value/operator at lowering (no NOT left in+ // FilterState), so the reverse adapter re-derives the canonical positive+ // form: `-latency:>2` → `latency:<=2`, `-isRootObservation:true` →+ // `isRootObservation:false`. resetTo must keep the user's typed form — same+ // "no silent rewrite" guarantee as the alias case.+ const numeric = createSearchBarStore();+ numeric.getState().actions.setDraft("-latency:>2");+ numeric.getState().actions.resetTo("latency:<=2");+ expect(numeric.getState().draft).toBe("-latency:>2");++ const bool = createSearchBarStore();+ bool.getState().actions.setDraft("-isRootObservation:true");+ bool.getState().actions.resetTo("isRootObservation:false");+ expect(bool.getState().draft).toBe("-isRootObservation:true");++ // A genuinely different committed text (sidebar edit) still re-seeds.+ numeric.getState().actions.resetTo("latency:<=5");+ expect(numeric.getState().draft).toBe("latency:<=5");+ });++ it("resetTo keeps an explicit contains glob on a textSearch field (no silent *v* → v)", () => {+ // `*foo*` (op `~`) and bare `foo` (op `=`) lower to the IDENTICAL contains+ // filter; the reverse adapter re-derives the bare form. resetTo must keep the+ // user's typed glob — same "no silent rewrite" guarantee. Covers the fields+ // this PR moved to textSearch (id/name) plus a pre-existing one.+ for (const column of ["statusMessage", "id", "name"]) {+ const store = createSearchBarStore();+ store.getState().actions.setDraft(`${column}:*foo*`);+ store.getState().actions.resetTo(`${column}:foo`);+ expect(store.getState().draft, column).toBe(`${column}:*foo*`);+ }+ });++ it("resetTo keeps a typed value whose only difference is canonical formatting", () => {+ // The lowering canonicalizes boolean case + numeric/datetime format, so the+ // reverse adapter re-derives a normalized value. resetTo must keep the typed+ // form — the symmetric positive case of the negation-fold preservation.+ const bool = createSearchBarStore();+ bool.getState().actions.setDraft("isRootObservation:TRUE");+ bool.getState().actions.resetTo("isRootObservation:true");+ expect(bool.getState().draft).toBe("isRootObservation:TRUE");++ for (const [typed, derived] of [+ ["latency:2.0", "latency:2"],+ ["latency:.5", "latency:0.5"],+ ["latency:2.5e1", "latency:25"],+ ] as const) {+ const s = createSearchBarStore();+ s.getState().actions.setDraft(typed);+ s.getState().actions.resetTo(derived);+ expect(s.getState().draft, typed).toBe(typed);+ }++ const dt = createSearchBarStore();+ dt.getState().actions.setDraft("startTime:>2026-06-01");+ dt.getState().actions.resetTo('startTime:>"2026-06-01T00:00:00.000Z"');+ expect(dt.getState().draft).toBe("startTime:>2026-06-01");++ // A genuinely different value still re-seeds.+ const diff = createSearchBarStore();+ diff.getState().actions.setDraft("latency:2.0");+ diff.getState().actions.resetTo("latency:3");+ expect(diff.getState().draft).toBe("latency:3");+ });++ it("resetTo keeps a typed `:=` where it lowers identically to the bare `:`", () => {+ // `key:=value` (exact) and `key:value` (=) lower to the same filter for every+ // field except textSearch, and the reverse adapter emits the bare form — so+ // the typed `:=` must stand instead of being rewritten to `:`.+ for (const [typed, derived] of [+ ["level:=ERROR", "level:ERROR"],+ ["latency:=2", "latency:2"],+ ["isRootObservation:=true", "isRootObservation:true"],+ ["metadata.region:=eu", "metadata.region:eu"],+ ["scores.feedback:=positive", "scores.feedback:positive"],+ ] as const) {+ const s = createSearchBarStore();+ s.getState().actions.setDraft(typed);+ s.getState().actions.resetTo(derived);+ expect(s.getState().draft, typed).toBe(typed);+ }+ });++ it("resetTo re-seeds a textSearch `:=` (exact != contains, not foldable)", () => {+ // For textSearch fields `:` means contains and `:=` means exact — different+ // ops, NOT interchangeable. A bare derived form must re-seed (no silent+ // equivalence), unlike the option/number/metadata fields above.+ const store = createSearchBarStore();+ store.getState().actions.setDraft("statusMessage:=foo");+ store.getState().actions.resetTo("statusMessage:foo");+ expect(store.getState().draft).toBe("statusMessage:foo");+ });++ it("resetTo Number-normalizes a numeric score value (not categorical)", () => {+ // accuracy is numeric → `scores.accuracy:2.0` lowers + re-derives to `:2`;+ // keep the typed `.0`, mirroring `latency:2.0`.+ const scoreTypes = {+ numericScoreNames: new Set<string>(["accuracy"]),+ categoricalScoreNames: new Set<string>(),+ traceNumericScoreNames: new Set<string>(),+ traceCategoricalScoreNames: new Set<string>(),+ };+ const store = createSearchBarStore(() => scoreTypes);+ store.getState().actions.setDraft("scores.accuracy:2.0");+ store.getState().actions.resetTo("scores.accuracy:2");+ expect(store.getState().draft).toBe("scores.accuracy:2.0");+ });++ it("resetTo still canonicalizes free-text order (negation fold is order-preserving)", () => {+ // The flat URL contract has no slot for filter-vs-free-text interleave, so+ // the reverse adapter canonicalizes to `<filters> <freetext>`. The negation+ // fold must NOT erase that re-seed: typing `refund level:ERROR` and pressing+ // Enter re-renders as `level:ERROR refund` (documented behavior).+ const store = createSearchBarStore();+ store.getState().actions.setDraft("refund level:ERROR");+ store.getState().actions.resetTo("level:ERROR refund");+ expect(store.getState().draft).toBe("level:ERROR refund");+ });++ it("revealInvalid marks the current draft; setDraft clears it", () => {+ const store = createSearchBarStore();+ store.getState().actions.setDraft("level:ERROR OR env:dev");+ store.getState().actions.revealInvalid();+ expect(store.getState().invalidRevealDraft).toBe("level:ERROR OR env:dev");+ store.getState().actions.setDraft("level:ERROR");+ expect(store.getState().invalidRevealDraft).toBeNull();+ });++ it("removeChipSpan edits the draft and returns the new text", () => {+ const store = createSearchBarStore();+ store.getState().actions.setDraft("level:ERROR env:dev");+ const next = store.getState().actions.removeChipSpan(0, 11);+ expect(next).toBe("env:dev");+ expect(store.getState().draft).toBe("env:dev");+ });++ it("revalidate refreshes draftValid when scoreTypes change (async observed load)", () => {+ // The draft was typed before `observed` loaded (empty score sets → numeric+ // value falls back to a clean categorical filter). Once observed loads,+ // revalidate must re-run validation so draftValid agrees with planCommit.+ let st = {+ numericScoreNames: new Set<string>(),+ categoricalScoreNames: new Set<string>(),+ traceNumericScoreNames: new Set<string>(),+ traceCategoricalScoreNames: new Set<string>(),+ };+ const store = createSearchBarStore(() => st);+ store.getState().actions.setDraft("scores.accuracy:hello");+ expect(store.getState().draftValid).toBe(true);+ st = { ...st, numericScoreNames: new Set<string>(["accuracy"]) };+ store.getState().actions.revalidate();+ expect(store.getState().draftValid).toBe(false);+ });++ it("revalidate reveals the red state when a valid draft flips invalid", () => {+ // Committed against an empty context while filterOptions loaded; once score+ // types arrive and unmask it, the bar must paint red (not stay silently+ // invalid with no AlertCircle).+ let st = {+ numericScoreNames: new Set<string>(),+ categoricalScoreNames: new Set<string>(),+ traceNumericScoreNames: new Set<string>(),+ traceCategoricalScoreNames: new Set<string>(),+ };+ const store = createSearchBarStore(() => st);+ store.getState().actions.setDraft("scores.accuracy:hello");+ expect(store.getState().invalidRevealDraft).toBeNull();+ st = { ...st, numericScoreNames: new Set<string>(["accuracy"]) };+ store.getState().actions.revalidate();+ expect(store.getState().invalidRevealDraft).toBe("scores.accuracy:hello");+ });++ it("revalidate bails when scoreTypes are set-equal (no churn re-render)", () => {+ // observed identity rotates every auto-refresh tick, but when the score-name+ // sets are unchanged revalidate must NOT re-run validation / emit a fresh+ // diagnostics array (which would trigger a no-op subscriber re-render).+ let st = {+ numericScoreNames: new Set<string>(["accuracy"]),+ categoricalScoreNames: new Set<string>(),+ traceNumericScoreNames: new Set<string>(),+ traceCategoricalScoreNames: new Set<string>(),+ };+ const store = createSearchBarStore(() => st);+ store.getState().actions.setDraft("level:ERROR");+ let notified = 0;+ const unsub = store.subscribe(() => notified++);+ // New context object, identical sets (a refetch tick).+ st = { ...st, numericScoreNames: new Set<string>(["accuracy"]) };+ store.getState().actions.revalidate();+ expect(notified).toBe(0);+ // A real change still triggers a re-validate.+ st = { ...st, numericScoreNames: new Set<string>(["accuracy", "latency"]) };+ store.getState().actions.revalidate();+ expect(notified).toBe(1);+ unsub();+ });++ it("validates with scoreTypes so the store agrees with the commit gate", () => {+ // `accuracy` is numeric, so `scores.accuracy:hello` can't lower. Without+ // the same scoreTypes planCommit uses, the store would mark it valid and+ // the red-border gate (which reads draftValid) would show nothing on Enter.+ const scoreTypes = {+ numericScoreNames: new Set<string>(["accuracy"]),+ categoricalScoreNames: new Set<string>(),+ traceNumericScoreNames: new Set<string>(),+ traceCategoricalScoreNames: new Set<string>(),+ };+ const store = createSearchBarStore(() => scoreTypes);+ store.getState().actions.setDraft("scores.accuracy:hello");+ expect(store.getState().draftValid).toBe(false);+ expect(store.getState().draftDiagnostics.length).toBeGreaterThan(0);+ });+});diff --git a/web/src/features/search-bar/store/searchBarStore.ts b/web/src/features/search-bar/store/searchBarStore.tsnew file mode 100644index 0000000000..1c1210514f--- /dev/null+++ b/web/src/features/search-bar/store/searchBarStore.ts@@ -0,0 +1,157 @@+// Per-mount search-bar store — DRAFT ONLY.+//+// Data direction is deliberately dumb and one-way: the table's URL filter+// state (FilterState + searchQuery/searchType) is the single source of truth.+// The committed query is DERIVED from it (filterStateToQueryText) and seeded+// into this store's draft via `resetTo`. The store therefore holds only the+// live editing buffer — there is no second "committed" copy to keep in sync,+// and nothing here ever writes back to the filter state (that happens in the+// container's commit workflow). This removes the reconciliation/loop-guard the+// old two-source design needed.++import { createStore, type StoreApi } from "zustand/vanilla";++import type { ScoreTypeContext } from "../lib/adapter";+import { astEquals } from "../lib/ast";+import { removeToken } from "../lib/edits";+import { foldDerivedNegation } from "../lib/filter-state-to-query";+import { parse, type Diagnostic } from "../lib/langQ";+import { scoreTypeContextEqual } from "../lib/observed-options";+import { validateQuery } from "../lib/validate";++export type SearchBarStoreState = {+ /** Live editing buffer. */+ draft: string;+ /** Pure derivations of `draft`, cached on write to avoid re-parsing. */+ draftDiagnostics: Diagnostic[];+ draftValid: boolean;+ /**+ * The draft for which a commit was last attempted while invalid. The editor+ * shows global diagnostics only when this equals the current draft, so the+ * red state appears on Enter/blur — not while the user is mid-typing.+ */+ invalidRevealDraft: string | null;++ actions: {+ setDraft: (next: string) => void;+ /**+ * Seed the draft from the derived committed baseline (commit echo, sidebar+ * edit, saved view, navigation). The ONE external→local sync; it never+ * writes anywhere else, so it cannot loop.+ */+ resetTo: (committedText: string) => void;+ /** Remove the token at `[from,to)` in the draft; returns the new text so+ * the caller can commit it. */+ removeChipSpan: (from: number, to: number) => string;+ /** Mark the current draft as a failed commit so diagnostics can show. */+ revealInvalid: () => void;+ /**+ * Re-run validation on the current draft without changing the draft or the+ * reveal state. Called when async context (observed score types) loads+ * after the draft was typed, so `draftValid` doesn't stay stale.+ */+ revalidate: () => void;+ };+};++export type SearchBarStore = StoreApi<SearchBarStoreState>;++/**+ * `resolveScoreTypes` lets draft validation route `scores.<name>` by observed+ * score type — the SAME context planCommit uses — so the store's draftValid+ * (which the editor's red-border gate reads) never disagrees with the commit+ * gate. A thunk so it always reads the latest observed options.+ */+export function createSearchBarStore(+ resolveScoreTypes?: () => ScoreTypeContext | undefined,+): SearchBarStore {+ return createStore<SearchBarStoreState>((set, get) => {+ // The score-type context used by the most recent validation. revalidate()+ // bails when the context is set-equal to this, so observed-identity churn+ // (a relative range + auto-refresh rebuilds the context every tick) doesn't+ // re-parse the draft and emit a fresh diagnostics array for no change.+ let lastScoreTypes: ScoreTypeContext | undefined;+ let hasValidated = false;++ const writeDraft = (next: string) => {+ const scoreTypes = resolveScoreTypes?.();+ lastScoreTypes = scoreTypes;+ hasValidated = true;+ const res = validateQuery(next, scoreTypes);+ set({+ draft: next,+ draftDiagnostics: res.diagnostics,+ draftValid: res.valid,+ invalidRevealDraft: null,+ });+ };++ return {+ draft: "",+ draftDiagnostics: [],+ draftValid: true,+ invalidRevealDraft: null,++ actions: {+ setDraft: writeDraft,+ resetTo: (committedText) => {+ const draft = get().draft;+ if (committedText === draft) return;+ // Keep the user's typed form when it is SEMANTICALLY identical to the+ // re-derived committed text. The commit echo bounces through canonical+ // URL filter state (no slot for a typed alias), so a string compare+ // would clobber `env:dev` with `environment:dev` on every commit —+ // violating "no silent rewrites". An AST compare (which ignores+ // rawKey/casing) lets an equivalent draft stand; a genuinely different+ // commit (sidebar edit, saved view, external nav) still re-seeds.+ // foldDerivedNegation additionally normalizes what the lowering+ // canonicalizes — value format (`latency:2.0`↔`latency:2`,+ // `isRoot:TRUE`↔`isRoot:true`), the exact op (`level:=ERROR`↔`level:ERROR`),+ // and the negations folded into the value/operator (`-latency:>2`↔+ // `latency:<=2`) — so those typed forms stand too. scoreTypes lets it+ // Number-normalize numeric (not categorical) score values. It preserves+ // structure/order, so free-text canonicalization is kept.+ const scoreTypes = resolveScoreTypes?.();+ if (+ astEquals(+ foldDerivedNegation(parse(committedText).ast, scoreTypes),+ foldDerivedNegation(parse(draft).ast, scoreTypes),+ )+ )+ return;+ writeDraft(committedText);+ },+ removeChipSpan: (from, to) => {+ const next = removeToken(get().draft, { from, to });+ writeDraft(next);+ return next;+ },+ revealInvalid: () => set({ invalidRevealDraft: get().draft }),+ revalidate: () => {+ const scoreTypes = resolveScoreTypes?.();+ // Nothing to refresh: the draft was already validated against an+ // equal context (writeDraft and revalidate both record it), so the+ // result would be identical. Skip the parse + set to avoid a+ // no-op re-render from the fresh diagnostics array.+ if (hasValidated && scoreTypeContextEqual(scoreTypes, lastScoreTypes))+ return;+ lastScoreTypes = scoreTypes;+ hasValidated = true;+ const wasValid = get().draftValid;+ const res = validateQuery(get().draft, scoreTypes);+ set({+ draftDiagnostics: res.diagnostics,+ draftValid: res.valid,+ // If newly-arrived score types unmask an already-committed draft as+ // invalid (committed earlier against an empty context while+ // filterOptions was loading), reveal the red state so the bad+ // commit stops being silent.+ ...(wasValid && !res.valid+ ? { invalidRevealDraft: get().draft }+ : {}),+ });+ },+ },+ };+ });+}diff --git a/web/src/pages/project/[projectId]/observations/index.tsx b/web/src/pages/project/[projectId]/observations/index.tsxindex 0e3692526d..310f334dd2 100644--- a/web/src/pages/project/[projectId]/observations/index.tsx+++ b/web/src/pages/project/[projectId]/observations/index.tsx@@ -1,4 +1,4 @@-import React from "react";+import React, { useState } from "react";import { useRouter } from "next/router";import ObservationsTable from "@/src/components/table/use-cases/observations";import Page from "@/src/components/layouts/page";@@ -11,12 +11,23 @@ import {import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";import ObservationsEventsTable from "@/src/features/events/components/EventsTable";import { useQueryProject } from "@/src/features/projects/hooks";+import { useSearchBarEnabled } from "@/src/features/search-bar/hooks/useSearchBarEnabled";export default function Generations() {const router = useRouter();const projectId = router.query.projectId as string;const { isBetaEnabled, isInitializing } = useV4Beta();const { project } = useQueryProject();+ // The header-actions slot only has a consumer when the bar is actually+ // active, so gate it the same way the table gates searchBarMode — otherwise+ // it's a dead empty node in the header. The bar is a per-user Feature Preview+ // opt-in and only renders on the v4 table, so it needs the v4 beta too.+ const searchBarEnabled = useSearchBarEnabled();+ const searchBarActive = isBetaEnabled && searchBarEnabled;+ // Host for the events table's time-range + refresh controls, rendered into+ // the page header (which is otherwise under-utilized). The events table+ // portals into this node when the search bar is active.+ const [headerActions, setHeaderActions] = useState<HTMLElement | null>(null);// Check if the user has tracing configured// Skip polling entirely if the project flag is already set in the session@@ -47,6 +58,14 @@ export default function Generations() {"An observation captures a single function call in an application. See docs to learn more.",href: "https://langfuse.com/docs/observability/data-model",},+ // Only render the portal target when its sole consumer+ // (ObservationsEventsTable) actually mounts — i.e. not during onboarding+ // or the pre-beta-flag init window, where the slot would otherwise be a+ // dead, empty <div> with a callback ref that never receives a portal.+ actionButtonsRight:+ searchBarActive && !showOnboarding && !isInitializing ? (+ <div ref={setHeaderActions} className="flex items-center gap-2" />+ ) : undefined,tabsProps:isBetaEnabled || isInitializing? undefined@@ -68,7 +87,10 @@ export default function Generations() {resolves. */}</>) : isBetaEnabled ? (- <ObservationsEventsTable projectId={projectId} />+ <ObservationsEventsTable+ projectId={projectId}+ headerActionsContainer={headerActions}+ />) : (<ObservationsTable projectId={projectId} />)}diff --git a/web/src/pages/project/[projectId]/settings/index.tsx b/web/src/pages/project/[projectId]/settings/index.tsxindex f8da832a88..2cc7efd454 100644--- a/web/src/pages/project/[projectId]/settings/index.tsx+++ b/web/src/pages/project/[projectId]/settings/index.tsx@@ -49,7 +49,6 @@ export function useProjectSettingsPages(): ProjectSettingsPage[] {const showProtectedLabelsSettings = useHasEntitlement("prompt-protected-labels",);-if (!project || !organization || !router.query.projectId) {return [];}diff --git a/web/src/pages/project/[projectId]/traces/index.tsx b/web/src/pages/project/[projectId]/traces/index.tsxindex 304d21f4d2..fd735217a9 100644--- a/web/src/pages/project/[projectId]/traces/index.tsx+++ b/web/src/pages/project/[projectId]/traces/index.tsx@@ -1,4 +1,4 @@-import React from "react";+import React, { useState } from "react";import { useRouter } from "next/router";import TracesTable from "@/src/components/table/use-cases/traces";import Page from "@/src/components/layouts/page";@@ -11,12 +11,22 @@ import {import { useV4Beta } from "@/src/features/events/hooks/useV4Beta";import ObservationsEventsTable from "@/src/features/events/components/EventsTable";import { useQueryProject } from "@/src/features/projects/hooks";+import { useSearchBarEnabled } from "@/src/features/search-bar/hooks/useSearchBarEnabled";export default function Traces() {const router = useRouter();const projectId = router.query.projectId as string;const { isBetaEnabled, isInitializing } = useV4Beta();const { project } = useQueryProject();+ // The header-actions slot only has a consumer when the bar is actually+ // active, so gate it the same way the table gates searchBarMode — otherwise+ // it's a dead empty node in the header. The bar is a per-user Feature Preview+ // opt-in and only renders on the v4 table, so it needs the v4 beta too.+ const searchBarEnabled = useSearchBarEnabled();+ const searchBarActive = isBetaEnabled && searchBarEnabled;+ // Host for the events table's time-range + refresh controls in the page+ // header (the events table is shown here in v4 mode and portals into it).+ const [headerActions, setHeaderActions] = useState<HTMLElement | null>(null);// Check if the user has tracing configured// Skip polling entirely if the project flag is already set in the session@@ -79,6 +89,14 @@ export default function Traces() {),href: "https://langfuse.com/docs/observability/data-model",},+ // Mirror observations/index.tsx: only mount the portal target when its+ // consumer (the events table) does. Onboarding is handled by the early-+ // return Page above; the remaining window to guard is the pre-beta-flag+ // init transient.+ actionButtonsRight:+ searchBarActive && !isInitializing ? (+ <div ref={setHeaderActions} className="flex items-center gap-2" />+ ) : undefined,tabsProps:isBetaEnabled || isInitializing? undefined@@ -96,7 +114,10 @@ export default function Traces() {resolves. */}</>) : isBetaEnabled ? (- <ObservationsEventsTable projectId={projectId} />+ <ObservationsEventsTable+ projectId={projectId}+ headerActionsContainer={headerActions}+ />) : (<TracesTable projectId={projectId} />)}diff --git a/web/src/server/api/routers/userAccount.ts b/web/src/server/api/routers/userAccount.tsindex ca26aa96b6..4606a20c8d 100644--- a/web/src/server/api/routers/userAccount.ts+++ b/web/src/server/api/routers/userAccount.ts@@ -95,47 +95,57 @@ export const userAccountRouter = createTRPCRouter({};}),- setInAppAgentPreviewEnabled: authenticatedProcedure+ setFeaturePreviewEnabled: authenticatedProcedure.input(z.object({+ // Allowlist of user-toggleable Feature Preview flags (the Feature+ // Preview modal). Keep in sync with the modal's preview registry.+ flag: z.enum(["inAppAgent", "searchBar"]),enabled: z.boolean(),}),).mutation(async ({ input, ctx }) => {const userId = ctx.session.user.id;- const currentUser = await ctx.prisma.user.findUnique({- where: { id: userId },- select: { featureFlags: true },- });- if (!currentUser) {+ if (input.enabled && !env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {throw new TRPCError({- code: "NOT_FOUND",- message: "User not found",+ code: "PRECONDITION_FAILED",+ message:+ "Feature previews are not available in self-hosted deployments.",});}- if (input.enabled) {- if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {- throw new TRPCError({- code: "PRECONDITION_FAILED",- message: "Assistant is not available in self-hosted deployments.",+ // Serializable transaction: the read-modify-write of the featureFlags+ // array is not atomic on its own, so two parallel toggles of DIFFERENT+ // flags from one tab (the modal only disables the in-flight row) would+ // last-write-wins and silently drop one. Mirrors the `delete` mutation.+ await ctx.prisma.$transaction(+ async (tx) => {+ const currentUser = await tx.user.findUnique({+ where: { id: userId },+ select: { featureFlags: true },});- }- }-- const nextFeatureFlags = input.enabled- ? Array.from(new Set([...currentUser.featureFlags, "inAppAgent"]))- : currentUser.featureFlags.filter((flag) => flag !== "inAppAgent");-- await ctx.prisma.user.update({- where: { id: userId },- data: { featureFlags: { set: nextFeatureFlags } },- });+ if (!currentUser) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "User not found",+ });+ }+ const nextFeatureFlags = input.enabled+ ? Array.from(new Set([...currentUser.featureFlags, input.flag]))+ : currentUser.featureFlags.filter((flag) => flag !== input.flag);+ await tx.user.update({+ where: { id: userId },+ data: { featureFlags: { set: nextFeatureFlags } },+ });+ },+ { isolationLevel: Prisma.TransactionIsolationLevel.Serializable },+ );return {success: true,- inAppAgentPreviewEnabled: input.enabled,+ flag: input.flag,+ enabled: input.enabled,};}),diff --git a/web/src/styles/globals.css b/web/src/styles/globals.cssindex 21e6832727..356efbc8a1 100644--- a/web/src/styles/globals.css+++ b/web/src/styles/globals.css@@ -32,6 +32,13 @@--color-accent-light-blue: hsl(var(--accent-light-blue));--color-accent-dark-blue: hsl(var(--accent-dark-blue));+ /* Search-bar query syntax highlighting (key:value token parts). Operators+ (`:` `-` `(` `)`) reuse muted-foreground, so no token for them here. */+ --color-qlang-field: hsl(var(--qlang-field));+ --color-qlang-value: hsl(var(--qlang-value));+ --color-qlang-number: hsl(var(--qlang-number));+ --color-qlang-keyword: hsl(var(--qlang-keyword));+--color-border: hsl(var(--border));--color-input: hsl(var(--input));--color-ring: hsl(var(--ring));@@ -210,6 +217,18 @@--accent-light-blue: 251 95.2% 91.8%;--accent-dark-blue: 224 76.3% 38%;++ /* Search-bar query syntax highlighting — a DELIBERATE editor-style syntax+ theme (like a code editor's theme), intentionally its own thing rather+ than the app palette: field=violet, value=green, number=orange,+ keyword=blue. Scoped to the filter grammar (key:value pills); retune+ freely, a designer can own these later. Operators reuse muted-foreground.+ Values from the langfuse-search-bar prototype. */+ --qlang-field: 262 60% 47%;+ --qlang-value: 152 60% 30%;+ --qlang-number: 24 75% 42%;+ --qlang-keyword: 221 83% 53%;+--radius: 0.5rem;--sidebar-background: 0 0% 100%;--sidebar-foreground: 240 5.3% 26.1%;@@ -309,6 +328,13 @@--accent-light-blue: 263 60% 50.4%;--accent-dark-blue: 224 50% 90%;+ /* Search-bar query syntax highlighting (dark). Brighter than light so the+ key/value read against the dark surface. See :root for the contract. */+ --qlang-field: 255 92% 76%;+ --qlang-value: 158 64% 52%;+ --qlang-number: 27 96% 61%;+ --qlang-keyword: 213 94% 68%;+--radius: 0.5rem;--sidebar-background: 222.2 84% 4.9%;