πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(filters): search the filter sidebar by facet name (#16045)
Nikita Kabardine37d75334adb
diff --git a/web/src/components/table/data-table-controls.clienttest.tsx b/web/src/components/table/data-table-controls.clienttest.tsxindex 6a828602ee..a8a4411dd7 100644--- a/web/src/components/table/data-table-controls.clienttest.tsx+++ b/web/src/components/table/data-table-controls.clienttest.tsx@@ -18,8 +18,9 @@ vi.mock("posthog-js/react", () => ({usePostHog: () => ({ capture: captureSpy }),}));-// Radix ScrollArea (wrapping the facet list) needs ResizeObserver, which-// jsdom does not implement.+// Radix ScrollArea (wrapping the facet list) needs ResizeObserver, and the+// Add-filter picker's command list scrolls its active item into view β neither+// of which jsdom implements.beforeAll(() => {vi.stubGlobal("ResizeObserver",@@ -29,6 +30,7 @@ beforeAll(() => {disconnect() {}},);+ Element.prototype.scrollIntoView = vi.fn();});describe("CategoricalFacet", () => {@@ -777,14 +779,10 @@ describe("DataTableControls blocked facets (LFE-11040)", () => {</TooltipProvider>,);- // Open the Add-filter dropdown. Radix opens the menu on the trigger's- // pointer-down, which jsdom doesn't synthesize reliably; the keyboard- // path (Enter) opens it without depending on PointerEvent support.- const addButton = screen.getByRole("button", { name: /Add filter/ });- fireEvent.keyDown(addButton, { key: "Enter" });+ fireEvent.click(screen.getByRole("button", { name: /Add filter/ }));- const blockedItem = screen.getByRole("menuitem", { name: "Blocked" });- const forwardableItem = screen.getByRole("menuitem", {+ const blockedItem = screen.getByRole("option", { name: "Blocked" });+ const forwardableItem = screen.getByRole("option", {name: "Forwardable",});// Blocked column stays visible but is disabled, with the reason on hover.@@ -798,3 +796,227 @@ describe("DataTableControls blocked facets (LFE-11040)", () => {}});});++describe("DataTableControls facet-name search", () => {+ // A catalog long enough to earn the search box (the traces sidebar's shape).+ const CATALOG: [column: string, label: string][] = [+ ["environment", "Environment"],+ ["name", "Trace Name"],+ ["id", "Trace ID"],+ ["userId", "User ID"],+ ["sessionId", "Session ID"],+ ["tags", "Tags"],+ ["metadata", "Metadata"],+ ["version", "Version"],+ ["release", "Release"],+ ["bookmarked", "Bookmarked"],+ ["level", "Status"],+ ["latency", "Latency"],+ ["totalTokens", "Total Tokens"],+ ];++ const catalog = (activeColumns: string[] = []): CategoricalUIFilter[] =>+ CATALOG.map(([column, label]) => ({+ type: "categorical",+ column,+ label,+ loading: false,+ expanded: false,+ isActive: activeColumns.includes(column),+ isDisabled: false,+ onReset: () => {},+ value: activeColumns.includes(column) ? ["x"] : [],+ options: ["x", "y"],+ counts: new Map(),+ onChange: () => {},+ // enables the Select/Text mode tabs, so a text-filter draft can be typed+ onTextFilterAdd: () => {},+ onTextFilterRemove: () => {},+ }));++ const queryFilter = (filters: UIFilter[]): QueryFilter => ({+ filters,+ expanded: [],+ onExpandedChange: () => {},+ clearAll: () => {},+ isFiltered: filters.some((f) => f.isActive),+ setFilterState: () => {},+ });++ const controls = (filters: UIFilter[]) => (+ <TooltipProvider>+ <DataTableControls queryFilter={queryFilter(filters)} />+ </TooltipProvider>+ );++ const searchFor = (query: string) =>+ fireEvent.change(screen.getByLabelText("Search filters"), {+ target: { value: query },+ });++ const labelOrder = (first: string, second: string) => {+ const a = screen.getByText(first);+ const b = screen.getByText(second);+ return Boolean(+ a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING,+ );+ };++ it("filters facet names immediately, and clearing restores the list with the selection intact", () => {+ render(controls(catalog(["userId"])));++ searchFor("token");+ expect(screen.getByText("Total Tokens")).toBeVisible();+ expect(screen.getByText("Environment")).not.toBeVisible();+ // The column key matches too: the label's space would defeat "userid".+ searchFor("userid");+ expect(screen.getByText("User ID")).toBeVisible();+ expect(screen.getByText("Trace Name")).not.toBeVisible();++ fireEvent.click(+ screen.getByRole("button", { name: "Clear filter search" }),+ );+ expect(screen.getByText("Environment")).toBeVisible();+ // The selection was never touched β its header summary still reads it.+ expect(screen.getByText("x")).toBeInTheDocument();+ });++ it("keeps a selected facet visible when it does not match, and says so", () => {+ const { rerender } = render(controls(catalog(["userId"])));++ searchFor("zzz");+ // Pinned by its selection, not by the query.+ expect(screen.getByText("User ID")).toBeVisible();+ expect(screen.getByText("Environment")).not.toBeVisible();+ expect(+ screen.getByText('No other filters match "zzz"'),+ ).toBeInTheDocument();++ // With nothing pinned above it, the same dead end drops the "other".+ rerender(controls(catalog()));+ expect(screen.getByText('No filters match "zzz"')).toBeInTheDocument();+ });++ it("hides a non-matching facet rather than unmounting it, so an open draft survives", () => {+ // Facets hold uncommitted local state (a typed-but-not-added text filter, a+ // metadata condition mid-build, a debounced numeric draft). Dropping them+ // from the tree while someone types in the search box above would discard+ // that silently, so the search only hides them.+ const qf = queryFilter(catalog());+ qf.expanded = ["environment"];+ render(+ <TooltipProvider>+ <DataTableControls queryFilter={qf} />+ </TooltipProvider>,+ );+ // Radix Tabs commit on mouse-down; jsdom needs both events.+ fireEvent.mouseDown(screen.getByRole("tab", { name: "Text" }));+ fireEvent.click(screen.getByRole("tab", { name: "Text" }));+ const draft = screen.getByPlaceholderText("Enter value...");+ fireEvent.change(draft, { target: { value: "half-typed" } });++ searchFor("token");+ expect(screen.getByText("Environment")).not.toBeVisible();+ // Same input node, same value: not remounted, not reset.+ expect(screen.getByPlaceholderText("Enter value...")).toBe(draft);+ expect(draft).toHaveValue("half-typed");++ fireEvent.click(+ screen.getByRole("button", { name: "Clear filter search" }),+ );+ expect(screen.getByText("Environment")).toBeVisible();+ expect(draft).toHaveValue("half-typed");+ });++ it("does not count typing in the search box as working the facet list", () => {+ // The list's keydown capture marks in-list edits so the order freezes+ // under the user's hands. Typing a query is not such an edit: an external+ // change while searching must still re-settle the order.+ const { rerender } = render(controls(catalog(["totalTokens"])));+ expect(labelOrder("Total Tokens", "Environment")).toBe(true);++ // "e" matches both compared facets, so only the order is under test.+ searchFor("e");+ expect(labelOrder("Total Tokens", "Environment")).toBe(true);++ rerender(controls(catalog(["environment", "totalTokens"])));+ expect(labelOrder("Environment", "Total Tokens")).toBe(true);+ });++ it("points the expand-all toggle at the facets the search leaves on screen", () => {+ const expandedChanges: string[][] = [];+ const qf = queryFilter(catalog());+ qf.expanded = ["environment"];+ qf.onExpandedChange = (value) => expandedChanges.push(value);+ render(+ <TooltipProvider>+ <DataTableControls queryFilter={qf} />+ </TooltipProvider>,+ );++ // Environment is expanded but a "token" query hides it, so the toggle must+ // offer to expand what IS on screen rather than to collapse the invisible.+ searchFor("token");+ fireEvent.click(screen.getByRole("button", { name: "Expand all filters" }));+ // The hidden facet keeps its expansion; the visible match joins it.+ expect(expandedChanges.at(-1)).toEqual(["environment", "totalTokens"]);+ });++ it("leaves a short sidebar without search chrome", () => {+ render(controls(catalog().slice(0, 3)));++ expect(screen.queryByLabelText("Search filters")).not.toBeInTheDocument();+ });++ it("searches the Add filter picker over the whole catalog", () => {+ localStorage.setItem("data-table-controls-active-only", "true");+ try {+ render(controls(catalog(["userId"])));++ // Active-only mode hands the catalog to the picker, so the list's own+ // search box steps aside.+ expect(screen.queryByLabelText("Search filters")).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: /Add filter/ }));++ const pickerSearch = screen.getByPlaceholderText("Search filters");+ fireEvent.change(pickerSearch, { target: { value: "token" } });+ expect(+ screen.getByRole("option", { name: "Total Tokens" }),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("option", { name: "Environment" }),+ ).not.toBeInTheDocument();++ fireEvent.change(pickerSearch, { target: { value: "zzz" } });+ expect(screen.getByText(/No filters match "zzz"/)).toBeInTheDocument();+ } finally {+ localStorage.removeItem("data-table-controls-active-only");+ }+ });++ it("captures facet_search once per search session, without the query text", () => {+ captureSpy.mockClear();+ render(controls(catalog()));++ searchFor("tok");+ searchFor("token");+ const searchEvents = captureSpy.mock.calls.filter(+ ([event]) => event === "filters:facet_search",+ );+ expect(searchEvents).toHaveLength(1);+ expect(searchEvents[0][1]).toEqual({+ tableName: undefined,+ surface: "facet_list",+ isV4: false,+ });++ // Clearing ends the session, so the next search is a new one.+ searchFor("");+ searchFor("latency");+ expect(+ captureSpy.mock.calls.filter(+ ([event]) => event === "filters:facet_search",+ ),+ ).toHaveLength(2);+ });+});diff --git a/web/src/components/table/data-table-controls.tsx b/web/src/components/table/data-table-controls.tsxindex 7d1d39ff5d..145dc05331 100644--- a/web/src/components/table/data-table-controls.tsx+++ b/web/src/components/table/data-table-controls.tsx@@ -18,9 +18,11 @@ import {SelectValue,} from "@/src/components/ui/select";import {+ facetNameRank,getFacetSummary,getFacetSummaryValue,rankFacetOptions,+ rankFacetsByName,} from "@/src/features/filters/lib/facet-display";import {advanceFacetOrder,@@ -55,6 +57,13 @@ import {DropdownMenuSeparator,DropdownMenuTrigger,} from "@/src/components/ui/dropdown-menu";+import {+ InputCommand,+ InputCommandGroup,+ InputCommandInput,+ InputCommandItem,+ InputCommandList,+} from "@/src/components/ui/input-command";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { Badge } from "@/src/components/ui/badge";import { Checkbox } from "@/src/components/design-system/Checkbox/Checkbox";@@ -263,6 +272,47 @@ export function DataTableControls({? orderedFilters.filter(isPromoted): orderedFilters;+ // Facet-NAME search over a long catalog. Two surfaces search the same names:+ // this list, and the active-only "Add filter" picker below.+ const [facetSearch, setFacetSearch] = useState("");+ // Only worth its chrome on a long list β a dozen is where the per-facet value+ // search appears too, and a 3-facet sidebar (eval logs, monitors) needs none.+ // Active-only mode has no catalog left in the list to search; its picker+ // carries the search instead.+ const showFacetSearch = !showOnlyActive && queryFilter.filters.length > 12;+ // Read through the visibility gate: a query left behind by a hidden input+ // must never narrow the list behind the user's back.+ const facetSearchQuery = showFacetSearch ? facetSearch.trim() : "";++ // Matching facet columns, or null when not searching. Selected/added facets+ // stay visible whether or not they match β a query must never hide what is+ // currently filtering β so the match set is also what tells "nothing matched"+ // apart from "only the pinned ones are left".+ const facetSearchMatches = facetSearchQuery+ ? new Set(+ displayedFilters+ .filter((filter) => facetNameRank(filter, facetSearchQuery) !== null)+ .map((filter) => filter.column),+ )+ : null;+ // Search FILTERS, it does not reorder: the settled promoted block and config+ // order still own every position.+ //+ // Non-matching facets are HIDDEN, never unmounted. Every facet holds+ // uncommitted local state β a typed-but-not-added text filter, a metadata+ // condition mid-build, a "show more" expansion, a debounced numeric draft β+ // and unmounting throws all of it away with nothing said. Typing in a box+ // above the list must not be able to do that.+ const visibleFilters = facetSearchMatches+ ? displayedFilters.filter(+ (filter) => facetSearchMatches.has(filter.column) || isPromoted(filter),+ )+ : displayedFilters;+ const visibleColumns = new Set(visibleFilters.map((filter) => filter.column));+ const expandedVisibleCount = queryFilter.expanded.filter((column) =>+ visibleColumns.has(column),+ ).length;+// Facet-usage recency, feeding the "Add filter" dropdown's ordering so the// filters someone actually uses on this table surface first.const [recentColumns, setRecentColumns] = useLocalStorage<@@ -279,6 +329,40 @@ export function DataTableControls({(recentColumns[b.column] ?? 0) - (recentColumns[a.column] ?? 0),): [];+ const [addFilterOpen, setAddFilterOpen] = useState(false);+ const [addFilterSearch, setAddFilterSearch] = useState("");+ // An empty query keeps the recency order (the point of the picker); a query+ // ranks by match quality, matching the list's search semantics.+ const rankedAddableFilters = addFilterSearch.trim()+ ? rankFacetsByName(addableFilters, addFilterSearch.trim())+ : addableFilters;++ // Adoption of the name search, per surface: one event per search session+ // (the first keystroke), never per keystroke, and never the query text.+ const searchedSurfacesRef = useRef(new Set<string>());+ const noteFacetSearch = (+ surface: "facet_list" | "add_filter_picker",+ query: string,+ ) => {+ if (query.trim() === "") {+ searchedSurfacesRef.current.delete(surface);+ return;+ }+ if (searchedSurfacesRef.current.has(surface)) return;+ searchedSurfacesRef.current.add(surface);+ capture("filters:facet_search", {+ tableName,+ surface,+ isV4: queryFilter.isV4 ?? false,+ });+ };+ // Closing ends the picker's search session β a controlled Popover closed+ // programmatically never reaches onOpenChange, so both paths route here.+ const closeAddFilterPicker = () => {+ setAddFilterOpen(false);+ setAddFilterSearch("");+ noteFacetSearch("add_filter_picker", "");+ };// Follow-scroll + recency: DOM scrolling is the external system here, so an// effect is the right integration boundary. A single facet's activity change@@ -402,13 +486,19 @@ export function DataTableControls({// Separator position: the SETTLED promoted block, not the live one β a facet// activated mid-session keeps its place below the line until the next settle.// Active-only mode has no inactive catalog to divide from, so no separator:- // counting every displayed facet keeps the divider out of the render loop's- // range, as the live count did before.+ // counting every displayed facet leaves no facet for the divider to sit+ // before, as the out-of-range index did before.const promotedFacetCount = showOnlyActive- ? displayedFilters.length- : displayedFilters.filter((filter) =>- facetOrder.promoted.has(filter.column),- ).length;+ ? visibleFilters.length+ : visibleFilters.filter((filter) => facetOrder.promoted.has(filter.column))+ .length;+ // Anchored to the first VISIBLE catalog facet rather than to an index: rows+ // hidden by a search stay in the list, so an index would count them.+ const firstCatalogColumn = visibleFilters.find(+ (filter) => !facetOrder.promoted.has(filter.column),+ )?.column;+ const showPromotedSeparator =+ promotedFacetCount > 0 && firstCatalogColumn !== undefined;const renderFacet = (filter: UIFilter) => {// A column the current surface can't honour blocks the facet whether or@@ -615,7 +705,8 @@ export function DataTableControls({// to CONTENT width, breaking label truncation). inline has no such// viewport, so a plain w-full block is correct.layout === "inline" ? "w-full" : "w-0 min-w-full",- "pt-1 pb-10",+ // The search row above supplies the list's top air when it is there.+ showFacetSearch ? "pb-10" : "pt-0.5 pb-10",)}// Any interaction in the list marks the filter change it causes as the// user's own edit, so the order holds still (LFE-14843). Capture phase,@@ -634,12 +725,15 @@ export function DataTableControls({{/* ONE keyed child array β not two .map() slices: React canonly match keys within the same array, so a facet crossingthe promoted/rest boundary would REMOUNT (wiping input- focus and draft state) instead of moving. */}- {displayedFilters.flatMap((filter, index) => {+ focus and draft state) instead of moving.++ Every facet renders; a search only sets `hidden` on the rows+ it excludes. The wrapper is always present for the same+ reason the array is single: swapping the element around a+ facet would remount it and lose its draft state. */}+ {displayedFilters.flatMap((filter) => {const nodes = [];- if (index === promotedFacetCount && promotedFacetCount > 0) {- // Clear spatial break between the active/added block and- // the inactive rest of the catalog.+ if (showPromotedSeparator && filter.column === firstCatalogColumn) {nodes.push(// The one line that means something: the boundary// between the active/added block and the catalog.@@ -650,11 +744,29 @@ export function DataTableControls({/>,);}- nodes.push(renderFacet(filter));+ nodes.push(+ <div+ key={filter.column}+ hidden={!visibleColumns.has(filter.column)}+ >+ {renderFacet(filter)}+ </div>,+ );return nodes;})}</Accordion>+ {/* Nothing in the catalog matched. Says "other" when pinned+ selections are still listed above, so the message never+ contradicts the facets on screen. */}+ {facetSearchMatches?.size === 0 && (+ <p className="text-muted-foreground px-3 pt-6 text-center text-xs break-words">+ {visibleFilters.length > 0+ ? `No other filters match "${facetSearchQuery}"`+ : `No filters match "${facetSearchQuery}"`}+ </p>+ )}+{/* Active-only mode: surface the rest of the catalog behind anexplicit "Add filter" picker, most-recently-used first, sothe filters someone actually works with are one click away. */}@@ -662,17 +774,25 @@ export function DataTableControls({<divclassName={cn("px-3 pt-4",- displayedFilters.length === 0 &&+ visibleFilters.length === 0 &&"flex flex-col items-center gap-1 pt-8 text-center",)}>- {displayedFilters.length === 0 && (+ {visibleFilters.length === 0 && (<p className="text-muted-foreground pb-2 text-xs">No active filters.</p>)}- <DropdownMenu>- <DropdownMenuTrigger asChild>+ {/* Popover + command list, not a DropdownMenu: the catalog runs to+ ~30 facets and needs a search box, which a Radix menu cannot+ host (it claims keystrokes for its own typeahead). */}+ <Popover+ open={addFilterOpen}+ onOpenChange={(open) =>+ open ? setAddFilterOpen(true) : closeAddFilterPicker()+ }+ >+ <PopoverTrigger asChild><Buttonvariant="outline"size="sm"@@ -682,31 +802,54 @@ export function DataTableControls({<Plus className="mr-1.5 h-3.5 w-3.5" />Add filter</Button>- </DropdownMenuTrigger>- <DropdownMenuContent- align="start"- className="max-h-72 w-56 overflow-y-auto"- >- {addableFilters.map((filter) => {- // A column the surface can't honour stays visible but is- // not addable β adding it would only land a facet that- // immediately reads blocked (chart view β #15187 /- // #15049). Same reason on hover.- const reason = blockedColumnReason?.(filter.column) ?? null;- return (- <DropdownMenuItem- key={filter.column}- disabled={!!reason}- title={reason ?? undefined}- onClick={() => handleAddFilter(filter.column)}- className="cursor-pointer"- >- {filter.label}- </DropdownMenuItem>- );- })}- </DropdownMenuContent>- </DropdownMenu>+ </PopoverTrigger>+ <PopoverContent align="start" className="w-56 p-0">+ <InputCommand shouldFilter={false}>+ <InputCommandInput+ placeholder="Search filters"+ variant="bottom"+ value={addFilterSearch}+ onValueChange={(query) => {+ setAddFilterSearch(query);+ noteFacetSearch("add_filter_picker", query);+ }}+ />+ <InputCommandList className="max-h-72">+ {rankedAddableFilters.length === 0 ? (+ <p className="text-muted-foreground px-2 py-6 text-center text-xs">+ No filters match "{addFilterSearch.trim()}"+ </p>+ ) : (+ <InputCommandGroup>+ {rankedAddableFilters.map((filter) => {+ // A column the surface can't honour stays visible but+ // is not addable β adding it would only land a facet+ // that immediately reads blocked (chart view β+ // #15187 / #15049). Same reason on hover.+ const reason =+ blockedColumnReason?.(filter.column) ?? null;+ return (+ <InputCommandItem+ key={filter.column}+ value={filter.column}+ disabled={!!reason}+ title={reason ?? undefined}+ onSelect={() => {+ handleAddFilter(filter.column);+ closeAddFilterPicker();+ }}+ className="cursor-pointer"+ >+ {filter.label}+ </InputCommandItem>+ );+ })}+ </InputCommandGroup>+ )}+ </InputCommandList>+ </InputCommand>+ </PopoverContent>+ </Popover></div>)}</div>@@ -868,7 +1011,10 @@ export function DataTableControls({</Popover>)}{/* Expand/collapse all facets β same affordance and icons as- the trace tree/timeline header. */}+ the trace tree/timeline header. Label and action both read the+ facets ON SCREEN, so a search narrowing the list cannot leave+ the button offering to collapse something nobody can see.+ Facets hidden by a query keep whatever expansion they had. */}<Tooltip><TooltipTrigger asChild><Button@@ -877,18 +1023,25 @@ export function DataTableControls({className="h-6 w-6"onClick={() =>queryFilter.onExpandedChange(- queryFilter.expanded.length === 0- ? displayedFilters.map((filter) => filter.column)- : [],+ expandedVisibleCount === 0+ ? [+ ...new Set([+ ...queryFilter.expanded,+ ...visibleFilters.map((filter) => filter.column),+ ]),+ ]+ : queryFilter.expanded.filter(+ (column) => !visibleColumns.has(column),+ ),)}aria-label={- queryFilter.expanded.length === 0+ expandedVisibleCount === 0? "Expand all filters": "Collapse all filters"}>- {queryFilter.expanded.length === 0 ? (+ {expandedVisibleCount === 0 ? (<UnfoldVertical className="h-3.5 w-3.5" />) : (<FoldVertical className="h-3.5 w-3.5" />@@ -896,7 +1049,7 @@ export function DataTableControls({</Button></TooltipTrigger><TooltipContent>- {queryFilter.expanded.length === 0+ {expandedVisibleCount === 0? "Expand all filters": "Collapse all filters"}</TooltipContent>@@ -949,6 +1102,10 @@ export function DataTableControls({onClick={() => {const enabled = !showOnlyActive;setShowOnlyActive(enabled);+ // The mode swaps which surface owns the name search, so a+ // query left in the other one would read as a stale filter.+ setFacetSearch("");+ noteFacetSearch("facet_list", "");capture("filters:active_only_toggled", {tableName,enabled,@@ -981,6 +1138,64 @@ export function DataTableControls({</DropdownMenu></div></div>+ {/* Facet-name search. Above the scroll area, so it stays put while the+ list scrolls β and OUTSIDE the facet list, whose keydown capture+ would otherwise read typing here as working the list and freeze the+ facet order mid-search. */}+ {showFacetSearch && (+ // px-2 and h-6 are the facet row's own inset and height β the search+ // field lines up with the labels it filters. No bottom border: the+ // list below is already a stack of bordered rows.+ //+ // The space below the field lives HERE rather than in the list,+ // because anything inside the list scrolls away: a facet header+ // pinning to the top of the scroll area would otherwise sit tight+ // against the field. pb-0.5 + the header's own 6px = the 8px above+ // the field, at rest and scrolled alike.+ <div className="bg-background shrink-0 px-2 pt-2 pb-0.5">+ <div className="relative">+ <Search className="text-muted-foreground absolute top-1/2 left-2 h-3.5 w-3.5 -translate-y-1/2" />+ <Input+ placeholder="Search filters"+ aria-label="Search filters"+ value={facetSearch}+ onChange={(event) => {+ setFacetSearch(event.target.value);+ noteFacetSearch("facet_list", event.target.value);+ }}+ onKeyDown={(event) => {+ // Escape clears the query; only once it is empty does it+ // reach the collapse-on-Escape chrome around it. Inside the+ // mobile Filters sheet the sheet still closes on the same+ // keystroke β Radix dismisses from a document capture-phase+ // listener, which no handler inside the tree can get ahead+ // of β so the clear button always works where this cannot.+ if (event.key === "Escape" && facetSearch !== "") {+ event.preventDefault();+ event.stopPropagation();+ setFacetSearch("");+ noteFacetSearch("facet_list", "");+ }+ }}+ className="h-6 pr-6 pl-7 text-xs"+ />+ {facetSearch !== "" && (+ <Button+ variant="ghost"+ size="icon"+ onClick={() => {+ setFacetSearch("");+ noteFacetSearch("facet_list", "");+ }}+ aria-label="Clear filter search"+ className="absolute top-1/2 right-0.5 h-5 w-5 -translate-y-1/2"+ >+ <IconX className="h-3 w-3" />+ </Button>+ )}+ </div>+ </div>+ )}{layout === "inline" ? (// inline: no internal scroll β the facet list flows at natural// height inside the host's outer scroll (the mobile Filters sheet).@@ -1118,7 +1333,10 @@ const FilterAccordionTrigger = ({// (ScrollArea wraps only the facet list), so triggers stick to its top.// The expand chevron leads the row (> closed, v open); the clear button// sits at the row's right edge and stays visible whenever a value is set.- <AccordionPrimitive.Header className="bg-background sticky top-0 z-[1] flex px-2 py-0.5">+ // pt-1.5/pb-0.5 rather than an even py: the 8px between two rows is split so+ // that 6px of it sits INSIDE this sticky box, which is what keeps a pinned+ // header the same distance from whatever is above it as it was at rest.+ <AccordionPrimitive.Header className="bg-background sticky top-0 z-[1] flex px-2 pt-1.5 pb-0.5"><AccordionPrimitive.TriggerclassName={cn(// min-w-0: without it the trigger's automatic min width equals the@@ -1180,8 +1398,9 @@ export function FilterAccordionItem({return (<FilterAccordionItemPrimitivevalue={filterKey}- className="py-0.5"- // Anchor for the follow-scroll after a re-sort moves this facet.+ // No padding here: the row rhythm lives on the STICKY header instead, so+ // a header keeps the same gap above it pinned as it had at rest β padding+ // on this wrapper scrolls away with it and the gap would shift.data-facet-column={filterKey}><FilterAccordionTriggerdiff --git a/web/src/features/filters/lib/facet-display.clienttest.ts b/web/src/features/filters/lib/facet-display.clienttest.tsindex cb4ec899b6..dbe1bd1d03 100644--- a/web/src/features/filters/lib/facet-display.clienttest.ts+++ b/web/src/features/filters/lib/facet-display.clienttest.ts@@ -1,4 +1,8 @@-import { getFacetSummary, rankFacetOptions } from "./facet-display";+import {+ getFacetSummary,+ rankFacetOptions,+ rankFacetsByName,+} from "./facet-display";import type {CategoricalUIFilter,NumericUIFilter,@@ -275,3 +279,30 @@ describe("rankFacetOptions", () => {expect(rankFacetOptions(["b", "a"], "")).toEqual(["b", "a"]);});});++describe("rankFacetsByName", () => {+ const facets = [+ { column: "userId", label: "User ID" },+ { column: "sessionId", label: "Session ID" },+ { column: "totalTokens", label: "Total Tokens" },+ ];++ it("matches the column key as well as the label", () => {+ // The label's space defeats a label-only match on "userid".+ expect(rankFacetsByName(facets, "userid")).toEqual([facets[0]]);+ expect(rankFacetsByName(facets, "tokens")).toEqual([facets[2]]);+ });++ it("ranks prefix matches before substring matches", () => {+ // "name" is the Trace Name facet's own key (prefix) and only part of the+ // Prompt Name one (substring) β the traces sidebar's real shape.+ const named = [+ { column: "promptName", label: "Prompt Name" },+ { column: "name", label: "Trace Name" },+ ];+ expect(rankFacetsByName(named, "name").map((f) => f.column)).toEqual([+ "name",+ "promptName",+ ]);+ });+});diff --git a/web/src/features/filters/lib/facet-display.ts b/web/src/features/filters/lib/facet-display.tsindex eba3c7a62e..90a0790779 100644--- a/web/src/features/filters/lib/facet-display.ts+++ b/web/src/features/filters/lib/facet-display.ts@@ -167,6 +167,10 @@ export function getFacetSummaryValue(filter: UIFilter): string | null {return null;}+/** Better of two ranks when either string may not match at all. */+const bestRank = (a: number | null, b: number | null): number | null =>+ a === null ? b : b === null ? a : Math.min(a, b);+/*** Rank a facet's option values for its search box the way the search bar* ranks completions (prefix matches before substring matches, stable within@@ -180,19 +184,49 @@ export function rankFacetOptions(): string[] {return options.map((option) => {- const valueRank = filterRank(option, query);const display = displayByValue?.get(option);- const displayRank =- display !== undefined ? filterRank(display, query) : null;- const rank =- valueRank === null- ? displayRank- : displayRank === null- ? valueRank- : Math.min(valueRank, displayRank);+ const rank = bestRank(+ filterRank(option, query),+ display !== undefined ? filterRank(display, query) : null,+ );return { option, rank };}).filter((x): x is { option: string; rank: number } => x.rank !== null).sort((a, b) => a.rank - b.rank).map((x) => x.option);}++/** A facet as the name search sees it: its visible label and its column key. */+type NamedFacet = { label: string; column: string };++/**+ * Rank of a facet against the sidebar's facet-NAME search, or null when it+ * does not match. The one matching authority for both name-search surfaces+ * (the facet list and the "Add filter" picker), so they agree.+ *+ * Matches the column key as well as the label because the label is spaced and+ * the key is not: "userid" has to find "User ID".+ */+export function facetNameRank(facet: NamedFacet, query: string): number | null {+ return bestRank(+ filterRank(facet.label, query),+ filterRank(facet.column, query),+ );+}++/**+ * Facets matching a name search, best match first (prefix before substring,+ * stable within a rank). For pickers, where match quality is the only order+ * that matters; the facet LIST filters with facetNameRank instead and keeps+ * its own deliberate order (promoted block first, then config order).+ */+export function rankFacetsByName<T extends NamedFacet>(+ facets: readonly T[],+ query: string,+): T[] {+ return facets+ .map((facet) => ({ facet, rank: facetNameRank(facet, query) }))+ .filter((x): x is { facet: T; rank: number } => x.rank !== null)+ .sort((a, b) => a.rank - b.rank)+ .map((x) => x.facet);+}diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.tsindex 8a5aed44a9..b10bf30029 100644--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts@@ -354,6 +354,7 @@ export const events = {"facet_operator_toggled","active_only_toggled","facet_added",+ "facet_search","facet_mode_switched","sidebar_toggled","search_submitted",