🪢 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): filter sidebar UX overhaul (LFE-10883) (#15049)
Nikita Kabardin1cc258d60649
diff --git a/23-rounded-blocks.png b/23-rounded-blocks.pngnew file mode 100644index 0000000000..77b72d9333Binary files /dev/null and b/23-rounded-blocks.png differdiff --git a/ff-scrollbar.png b/ff-scrollbar.pngnew file mode 100644index 0000000000..8a8b4af2d1Binary files /dev/null and b/ff-scrollbar.png differdiff --git a/web/src/components/layouts/doc-popup.tsx b/web/src/components/layouts/doc-popup.tsxindex 899139f681..c0239dbcc6 100644--- a/web/src/components/layouts/doc-popup.tsx+++ b/web/src/components/layouts/doc-popup.tsx@@ -1,3 +1,4 @@+import { useState } from "react";import {HoverCard,HoverCardContent,@@ -6,7 +7,7 @@ import {} from "@/src/components/ui/hover-card";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { cn } from "@/src/utils/tailwind";-import { Info } from "lucide-react";+import { ExternalLink, Info } from "lucide-react";export type DocPopupProps = {description: React.ReactNode;@@ -20,34 +21,35 @@ export default function DocPopup({className,}: DocPopupProps) {const capture = usePostHogClientCapture();+ // Controlled so a CLICK/TAP on the icon also opens the card: HoverCard+ // never opens on touch by itself, and the old click-to-navigate behavior+ // is gone — docs open only via the explicit link inside the card.+ const [open, setOpen] = useState(false);+ // Single open-change path: Radix only calls onOpenChange from its own+ // hover/focus handling, so the click handler must route through here too+ // or tap-opens (the only way in on touch) would never be captured.+ const handleOpenChange = (nextOpen: boolean) => {+ setOpen(nextOpen);+ if (nextOpen) {+ capture("help_popup:opened", {+ hfref: href,+ description: description,+ });+ }+ };return (- <HoverCard- openDelay={200}- onOpenChange={(open) => {- if (open) {- capture("help_popup:opened", {- hfref: href,- description: description,- });- }- }}- >- <HoverCardTrigger- className={cn("mx-1", href ? "cursor-pointer" : "cursor-default")}- asChild- >+ <HoverCard openDelay={200} open={open} onOpenChange={handleOpenChange}>+ {/* The ⓘ itself never navigates; a click toggles the card (touch+ support) and must not bubble into whatever the icon sits on —+ e.g. a filter facet's accordion trigger. */}+ <HoverCardTrigger className="mx-1 cursor-help" asChild><divclassName="text-muted-foreground inline-block whitespace-nowrap sm:pl-0"onClick={(e) => {- if (!href) return;e.preventDefault();e.stopPropagation();- window.open(href, "_blank");- capture("help_popup:href_clicked", {- href: href,- description: description,- });+ handleOpenChange(!open);}}><Info className="h-3 w-3" />@@ -63,6 +65,24 @@ export default function DocPopup({>{description}</div>+ {href && (+ <a+ href={href}+ target="_blank"+ rel="noopener noreferrer"+ onClick={(e) => {+ e.stopPropagation();+ capture("help_popup:href_clicked", {+ href: href,+ description: description,+ });+ }}+ className="text-muted-foreground hover:text-primary mt-2 inline-flex items-center gap-1 text-xs underline underline-offset-2"+ >+ Read docs+ <ExternalLink className="h-3 w-3" />+ </a>+ )}</HoverCardContent></HoverCardPortal></HoverCard>diff --git a/web/src/components/level-colors.tsx b/web/src/components/level-colors.tsxindex 4541a7d5ed..8208706a2d 100644--- a/web/src/components/level-colors.tsx+++ b/web/src/components/level-colors.tsx@@ -1,4 +1,6 @@+import type React from "react";import { type ObservationLevelType } from "@langfuse/shared";+import { cn } from "@/src/utils/tailwind";export const LevelColors = {DEFAULT: { text: "", bg: "" },@@ -7,6 +9,27 @@ export const LevelColors = {ERROR: { text: "text-dark-red", bg: "bg-light-red" },};+// Colored bar per level value for the Status filter facet (LFE-10883):+// red = error, yellow = warning, green = the ok/default path, muted = debug.+const levelBarColors: Record<string, string> = {+ DEFAULT: "bg-accent-dark-green",+ DEBUG: "bg-muted-foreground/40",+ WARNING: "bg-dark-yellow",+ ERROR: "bg-dark-red",+};++/** Renders the colored status bar for a level facet option (renderIcon). */+export function renderLevelIcon(value: string): React.ReactNode {+ const color = levelBarColors[value.toUpperCase()];+ if (!color) return null;+ return (+ <span+ aria-hidden+ className={cn("inline-block h-3.5 w-1 shrink-0 rounded-full", color)}+ />+ );+}+export const LevelSymbols = {DEFAULT: "ℹ️",DEBUG: "🔍",diff --git a/web/src/components/table/data-table-controls.clienttest.tsx b/web/src/components/table/data-table-controls.clienttest.tsxindex a2d03f6978..bb84ea70eb 100644--- a/web/src/components/table/data-table-controls.clienttest.tsx+++ b/web/src/components/table/data-table-controls.clienttest.tsx@@ -1,6 +1,35 @@-import { render, screen } from "@testing-library/react";+import { fireEvent, render, screen } from "@testing-library/react";import { Accordion } from "@/src/components/ui/accordion";-import { CategoricalFacet } from "./data-table-controls";+import { TooltipProvider } from "@/src/components/ui/tooltip";+import {+ CategoricalFacet,+ DataTableControls,+ type QueryFilter,+} from "./data-table-controls";+import type {+ CategoricalUIFilter,+ UIFilter,+} from "@/src/features/filters/hooks/useSidebarFilterState";++// Spy on the posthog client so capture calls (event name + payload) can be+// asserted at the wrapper seam.+const captureSpy = vi.fn();+vi.mock("posthog-js/react", () => ({+ usePostHog: () => ({ capture: captureSpy }),+}));++// Radix ScrollArea (wrapping the facet list) needs ResizeObserver, which+// jsdom does not implement.+beforeAll(() => {+ vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ },+ );+});describe("CategoricalFacet", () => {it("shows selected values even when the backend returns no options", () => {@@ -20,6 +49,9 @@ describe("CategoricalFacet", () => {onReset={() => {}}/></Accordion>,+ // The active-facet clear affordance renders a Tooltip, which needs the+ // provider the app supplies globally.+ { wrapper: TooltipProvider },);expect(screen.getByText("AGENT")).toBeInTheDocument();@@ -43,6 +75,9 @@ describe("CategoricalFacet", () => {onReset={() => {}}/></Accordion>,+ // The active-facet clear affordance renders a Tooltip, which needs the+ // provider the app supplies globally.+ { wrapper: TooltipProvider },);expect(screen.getByLabelText("Clear Type filter")).toBeInTheDocument();@@ -68,6 +103,9 @@ describe("CategoricalFacet", () => {onReset={() => {}}/></Accordion>,+ // The active-facet clear affordance renders a Tooltip, which needs the+ // provider the app supplies globally.+ { wrapper: TooltipProvider },);// The list is long enough to be capped...@@ -86,6 +124,50 @@ describe("CategoricalFacet", () => {).toBeTruthy();});+ it("reveals values in portions — 'more' means more, not all — and collapses back", () => {+ // 80 options: one "Show more" click must reveal the next chunk (+50),+ // not the entire list.+ const options = Array.from({ length: 80 }, (_, i) => `opt-${i}`);+ render(+ <Accordion type="multiple" value={["c"]}>+ <CategoricalFacet+ label="C"+ filterKey="c"+ expanded+ loading={false}+ options={options}+ counts={new Map()}+ value={[]}+ onChange={() => {}}+ isActive={false}+ isDisabled={false}+ onReset={() => {}}+ />+ </Accordion>,+ { wrapper: TooltipProvider },+ );++ fireEvent.click(screen.getByRole("button", { name: "Show more values" }));+ // One portion revealed (12 + 50 = 62 values)…+ expect(screen.getByText("opt-61")).toBeInTheDocument();+ // …but NOT the whole list…+ expect(screen.queryByText("opt-62")).not.toBeInTheDocument();+ // …and both continue and collapse affordances are offered.+ expect(+ screen.getByRole("button", { name: "Show more values" }),+ ).toBeInTheDocument();+ const collapse = screen.getByRole("button", {+ name: "Show fewer values",+ });+ // Collapsing re-applies the cap.+ fireEvent.click(collapse);+ expect(screen.queryByText("opt-61")).not.toBeInTheDocument();+ expect(screen.queryByText("opt-12")).not.toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Show fewer values" }),+ ).not.toBeInTheDocument();+ });+it("keeps the 'Show more' cap when every option is reported selected (no-filter default)", () => {// useSidebarFilterState returns value === options when no filter is applied// (computeSelectedValues). That all-selected default must NOT be treated as@@ -107,6 +189,9 @@ describe("CategoricalFacet", () => {onReset={() => {}}/></Accordion>,+ // The active-facet clear affordance renders a Tooltip, which needs the+ // provider the app supplies globally.+ { wrapper: TooltipProvider },);// The cap is preserved: "Show more" still renders and a deep value stays hidden.@@ -137,6 +222,9 @@ describe("CategoricalFacet", () => {onReset={() => {}}/></Accordion>,+ // The active-facet clear affordance renders a Tooltip, which needs the+ // provider the app supplies globally.+ { wrapper: TooltipProvider },);expect(@@ -171,6 +259,9 @@ describe("CategoricalFacet", () => {onReset={() => {}}/></Accordion>,+ // The active-facet clear affordance renders a Tooltip, which needs the+ // provider the app supplies globally.+ { wrapper: TooltipProvider },);// The cap still applies...@@ -189,6 +280,57 @@ describe("CategoricalFacet", () => {).toBeTruthy();});+ it("disables 'None of' with an explanation while it would be a no-op", () => {+ // No persisted filter (operator undefined): switching to none-of is a+ // deliberate no-op in the state model, so the tab must read disabled+ // instead of silently doing nothing.+ render(+ <Accordion type="multiple" value={["tags"]}>+ <CategoricalFacet+ label="Tags"+ filterKey="tags"+ expanded+ loading={false}+ options={["a", "b"]}+ counts={new Map()}+ value={["a", "b"]}+ onChange={() => {}}+ operator={undefined}+ onOperatorChange={() => {}}+ isActive={false}+ isDisabled={false}+ onReset={() => {}}+ />+ </Accordion>,+ { wrapper: TooltipProvider },+ );+ expect(screen.getByRole("tab", { name: "None of" })).toBeDisabled();++ // With a persisted selection the operator conversion is meaningful.+ render(+ <Accordion type="multiple" value={["tags2"]}>+ <CategoricalFacet+ label="Tags2"+ filterKey="tags2"+ expanded+ loading={false}+ options={["a", "b"]}+ counts={new Map()}+ value={["a"]}+ onChange={() => {}}+ operator="any of"+ onOperatorChange={() => {}}+ isActive+ isDisabled={false}+ onReset={() => {}}+ />+ </Accordion>,+ { wrapper: TooltipProvider },+ );+ const tabs = screen.getAllByRole("tab", { name: "None of" });+ expect(tabs[tabs.length - 1]).toBeEnabled();+ });+it("does not reorder short, fully-visible lists", () => {render(<Accordion type="multiple" value={["c"]}>@@ -206,6 +348,9 @@ describe("CategoricalFacet", () => {onReset={() => {}}/></Accordion>,+ // The active-facet clear affordance renders a Tooltip, which needs the+ // provider the app supplies globally.+ { wrapper: TooltipProvider },);// No cap, no "Show more": the natural order is preserved (a, b, c) — the@@ -217,3 +362,240 @@ describe("CategoricalFacet", () => {).toBeTruthy();});});++describe("DataTableControls facet ordering", () => {+ const categoricalFilter = (+ column: string,+ label: string,+ isActive: boolean,+ ): CategoricalUIFilter => ({+ type: "categorical",+ column,+ label,+ loading: false,+ expanded: false,+ isActive,+ isDisabled: false,+ onReset: () => {},+ value: isActive ? ["x"] : [],+ options: ["x", "y"],+ counts: new Map(),+ onChange: () => {},+ // enables the Select/Text mode tabs in tests that need them+ onTextFilterAdd: () => {},+ onTextFilterRemove: () => {},+ });++ const queryFilter = (filters: UIFilter[]): QueryFilter => ({+ filters,+ expanded: [],+ onExpandedChange: () => {},+ clearAll: () => {},+ isFiltered: filters.some((f) => f.isActive),+ setFilterState: () => {},+ });++ 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("promotes facets with an active filter above inactive ones", () => {+ render(+ <TooltipProvider>+ <DataTableControls+ queryFilter={queryFilter([+ categoricalFilter("alpha", "Alpha", false),+ categoricalFilter("beta", "Beta", true),+ ])}+ />+ </TooltipProvider>,+ );++ // Config order is [Alpha, Beta]; active Beta renders first.+ expect(labelOrder("Beta", "Alpha")).toBe(true);+ });++ it("re-sorts immediately when a facet's activity changes", () => {+ const { rerender } = render(+ <TooltipProvider>+ <DataTableControls+ queryFilter={queryFilter([+ categoricalFilter("alpha", "Alpha", false),+ categoricalFilter("beta", "Beta", true),+ ])}+ />+ </TooltipProvider>,+ );+ expect(labelOrder("Beta", "Alpha")).toBe(true);++ // Alpha becoming active promotes it right away (config order among+ // equally-active facets)…+ rerender(+ <TooltipProvider>+ <DataTableControls+ queryFilter={queryFilter([+ categoricalFilter("alpha", "Alpha", true),+ categoricalFilter("beta", "Beta", true),+ ])}+ />+ </TooltipProvider>,+ );+ expect(labelOrder("Alpha", "Beta")).toBe(true);++ // …and Beta clearing demotes it below the still-active Alpha.+ rerender(+ <TooltipProvider>+ <DataTableControls+ queryFilter={queryFilter([+ categoricalFilter("alpha", "Alpha", true),+ categoricalFilter("beta", "Beta", false),+ ])}+ />+ </TooltipProvider>,+ );+ expect(labelOrder("Alpha", "Beta")).toBe(true);+ });++ it("captures sidebar_toggled and facet_mode_switched with their dimensions", () => {+ captureSpy.mockClear();+ render(+ <TooltipProvider>+ <DataTableControls+ queryFilter={{+ ...queryFilter([categoricalFilter("alpha", "Alpha", true)]),+ // facet expanded so the Select/Text mode tabs render+ expanded: ["alpha"],+ isV4: true,+ }}+ />+ </TooltipProvider>,+ );++ // Header hide button -> one sidebar_toggled with trigger + dimension.+ fireEvent.click(screen.getByRole("button", { name: "Hide filters" }));+ const toggled = captureSpy.mock.calls.filter(+ ([event]) => event === "filters:sidebar_toggled",+ );+ expect(toggled).toHaveLength(1);+ expect(toggled[0][1]).toMatchObject({+ open: false,+ trigger: "header",+ isV4: true,+ });++ // Facet mode tab -> one facet_mode_switched carrying the column.+ // (Radix Tabs activate on mousedown, not click.)+ fireEvent.mouseDown(screen.getByRole("tab", { name: "Text" }));+ fireEvent.click(screen.getByRole("tab", { name: "Text" }));+ const switched = captureSpy.mock.calls.filter(+ ([event]) => event === "filters:facet_mode_switched",+ );+ expect(switched).toHaveLength(1);+ expect(switched[0][1]).toMatchObject({+ column: "alpha",+ mode: "text",+ isV4: true,+ });++ // Privacy: no payload of any captured event carries a filter value.+ for (const [, payload] of captureSpy.mock.calls) {+ expect(JSON.stringify(payload ?? {})).not.toContain('"x"');+ }+ });++ it("expands and collapses all facets from the header toggle", () => {+ const expandedChanges: string[][] = [];+ const qf = queryFilter([+ categoricalFilter("alpha", "Alpha", false),+ categoricalFilter("beta", "Beta", true),+ ]);+ qf.onExpandedChange = (value) => expandedChanges.push(value);+ render(+ <TooltipProvider>+ <DataTableControls queryFilter={qf} />+ </TooltipProvider>,+ );++ // Nothing expanded -> the toggle offers Expand all with every column.+ fireEvent.click(screen.getByRole("button", { name: "Expand all filters" }));+ expect(expandedChanges.at(-1)).toEqual(["beta", "alpha"]);+ });++ it("shows only active facets plus an Add filter picker when active-only mode is on", () => {+ // The header … menu persists the mode per table; no provider here, so+ // the storage key is the unscoped default.+ localStorage.setItem("data-table-controls-active-only", "true");+ try {+ render(+ <TooltipProvider>+ <DataTableControls+ queryFilter={queryFilter([+ categoricalFilter("alpha", "Alpha", false),+ categoricalFilter("beta", "Beta", true),+ ])}+ />+ </TooltipProvider>,+ );++ expect(screen.getByText("Beta")).toBeInTheDocument();+ expect(screen.queryByText("Alpha")).not.toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: /Add filter/ }),+ ).toBeInTheDocument();+ } finally {+ localStorage.removeItem("data-table-controls-active-only");+ }+ });++ it("tracks late-arriving URL filters (Pages Router populates params after mount)", () => {+ const { rerender } = render(+ <TooltipProvider>+ <DataTableControls+ queryFilter={queryFilter([+ categoricalFilter("alpha", "Alpha", false),+ categoricalFilter("beta", "Beta", false),+ ])}+ />+ </TooltipProvider>,+ );+ expect(labelOrder("Alpha", "Beta")).toBe(true);++ // Filters decoded from the URL a few renders after mount still promote.+ rerender(+ <TooltipProvider>+ <DataTableControls+ queryFilter={queryFilter([+ categoricalFilter("alpha", "Alpha", false),+ categoricalFilter("beta", "Beta", true),+ ])}+ />+ </TooltipProvider>,+ );+ expect(labelOrder("Beta", "Alpha")).toBe(true);+ });++ it("shows the 'what is selected' summary in the facet header", () => {+ render(+ <TooltipProvider>+ <DataTableControls+ queryFilter={queryFilter([+ {+ ...categoricalFilter("alpha", "Alpha", true),+ value: ["x", "y"],+ options: ["x", "y", "z"],+ },+ categoricalFilter("beta", "Beta", false),+ ])}+ />+ </TooltipProvider>,+ );++ expect(screen.getByText("2 selected")).toBeInTheDocument();+ // Inactive checkbox facet reads "All" — all-checked means no filter.+ expect(screen.getByText("All")).toBeInTheDocument();+ });+});diff --git a/web/src/components/table/data-table-controls.tsx b/web/src/components/table/data-table-controls.tsxindex 29ac0fe2f7..14009ea115 100644--- a/web/src/components/table/data-table-controls.tsx+++ b/web/src/components/table/data-table-controls.tsx@@ -7,13 +7,46 @@ import {useRef,useCallback,} from "react";+import { ScrollArea } from "@/src/components/ui/scroll-area";+import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/src/components/ui/select";+import {+ getFacetSummary,+ getFacetSummaryValue,+ rankFacetOptions,+} from "@/src/features/filters/lib/facet-display";import { useMediaQuery } from "react-responsive";import useLocalStorage from "@/src/components/useLocalStorage";import { cn } from "@/src/utils/tailwind";import { compactNumberFormatter } from "@/src/utils/numbers";import { Accordion } from "@/src/components/ui/accordion";import * as AccordionPrimitive from "@radix-ui/react-accordion";-import { ChevronDown, PanelLeftClose, PanelLeftOpen } from "lucide-react";+import {+ Check,+ ChevronDown,+ ChevronRight,+ ChevronUp,+ FoldVertical,+ MoreVertical,+ PanelLeftClose,+ PanelLeftOpen,+ Plus,+ UnfoldVertical,+} from "lucide-react";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/src/components/ui/dropdown-menu";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { Badge } from "@/src/components/ui/badge";import { Checkbox } from "@/src/components/ui/checkbox";import { Button } from "@/src/components/ui/button";@@ -111,6 +144,8 @@ export interface QueryFilter {clearAll: () => void;isFiltered: boolean;setFilterState: (filters: FilterState) => void;+ /** v3-vs-v4 analytics dimension of the surface (see useSidebarFilterState). */+ isV4?: boolean;}interface DataTableControlsProps {@@ -125,22 +160,165 @@ interface DataTableControlsProps {deactivatedColumnReason?: (column: string) => string | null;}+// Module-stable initial value: a fresh {} per render would re-subscribe+// useLocalStorage's cross-tab listener on every render.+const EMPTY_RECENCY: Record<string, number> = {};+export function DataTableControls({queryFilter,filterWithAI,deactivatedColumnReason,}: DataTableControlsProps) {const { isLangfuseCloud } = useLangfuseCloudRegion();- const { setOpen } = useDataTableControls();+ const { setOpen, tableName } = useDataTableControls();+ const capture = usePostHogClientCapture();const [aiPopoverOpen, setAiPopoverOpen] = useState(false);const activeFilterCount = queryFilter.filters.filter((filter) => filter.isActive,).length;+ const storagePrefix = tableName+ ? `data-table-controls-${tableName}`+ : "data-table-controls";++ // "Show only active" (the header … menu): the list collapses to the+ // promoted facets. Explicit "Add filter" picks are tracked per mount.+ const [showOnlyActive, setShowOnlyActive] = useLocalStorage(+ `${storagePrefix}-active-only`,+ false,+ );+ const [revealedColumns, setRevealedColumns] = useState<string[]>([]);++ // Selected filters on top: a facet is PROMOTED when it carries an active+ // filter OR the user explicitly added it via "Add filter" — the explicit+ // add is a promotion in itself, so typing a first value (facet becomes+ // active) or clearing it again (inactive) never moves the facet around+ // while someone is working in it. Config order is preserved within each+ // group, the sort updates immediately, and both display modes share the+ // exact same order. When an interaction does move a facet (activation by+ // direct click), the follow-scroll effect below keeps it in view.+ const revealedSet = new Set(revealedColumns);+ const isPromoted = (filter: UIFilter) =>+ filter.isActive || revealedSet.has(filter.column);+ const orderedFilters = [...queryFilter.filters].sort(+ (a, b) => Number(isPromoted(b)) - Number(isPromoted(a)),+ );+ const displayedFilters = showOnlyActive+ ? orderedFilters.filter(isPromoted)+ : orderedFilters;++ // 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<+ Record<string, number>+ >(`${storagePrefix}-recent-facets`, EMPTY_RECENCY);+ const addableFilters = showOnlyActive+ ? orderedFilters+ .filter(+ (filter) =>+ !filter.isActive && !revealedColumns.includes(filter.column),+ )+ .sort(+ (a, b) =>+ (recentColumns[b.column] ?? 0) - (recentColumns[a.column] ?? 0),+ )+ : [];++ // Follow-scroll + recency: DOM scrolling is the external system here, so an+ // effect is the right integration boundary. When exactly one facet changed+ // activity (the user's own interaction — bulk changes like Clear all, AI+ // apply, or a restored view skip the scroll), the re-sort has already moved+ // it by the time this runs; scroll the list to its new position.+ const scrollRootRef = useRef<HTMLDivElement>(null);+ // Last focused element inside the list: re-sorting moves DOM nodes, and a+ // reinserted node loses focus even when React merely reorders it — typing+ // the first character into a facet's input must not kick the caret out.+ const lastFocusedRef = useRef<HTMLElement | null>(null);+ const activeColumnsKey = queryFilter.filters+ .filter((filter) => filter.isActive)+ .map((filter) => filter.column)+ .join(",");+ const prevActiveColumnsRef = useRef(activeColumnsKey);+ useEffect(() => {+ const prevKey = prevActiveColumnsRef.current;+ if (prevKey === activeColumnsKey) return;+ prevActiveColumnsRef.current = activeColumnsKey;+ const prev = new Set(prevKey.split(",").filter(Boolean));+ const current = new Set(activeColumnsKey.split(",").filter(Boolean));+ const became = [...current].filter((column) => !prev.has(column));+ const ceased = [...prev].filter((column) => !current.has(column));++ if (became.length > 0) {+ const now = Date.now();+ setRecentColumns((existing) => ({+ ...existing,+ ...Object.fromEntries(became.map((column) => [column, now])),+ }));+ }++ // Restore focus dropped by the reorder's DOM move (inputs keep their own+ // selection state across blur, so focus() alone restores the caret).+ const lastFocused = lastFocusedRef.current;+ if (+ lastFocused &&+ lastFocused.isConnected &&+ (document.activeElement === document.body ||+ document.activeElement === null)+ ) {+ lastFocused.focus({ preventScroll: true });+ }++ const changed = [...became, ...ceased];+ if (changed.length !== 1) return;+ const facetElement = scrollRootRef.current?.querySelector(+ `[data-facet-column="${CSS.escape(changed[0])}"]`,+ );+ facetElement?.scrollIntoView?.({ behavior: "smooth", block: "nearest" });+ }, [activeColumnsKey, setRecentColumns]);++ const handleAddFilter = (column: string) => {+ setRevealedColumns((current) =>+ current.includes(column) ? current : [...current, column],+ );+ if (!queryFilter.expanded.includes(column)) {+ queryFilter.onExpandedChange([...queryFilter.expanded, column]);+ }+ // The added facet lands at its config-order slot within the promoted+ // group — bring it into view once the re-render has painted.+ requestAnimationFrame(() => {+ scrollRootRef.current+ ?.querySelector(`[data-facet-column="${CSS.escape(column)}"]`)+ ?.scrollIntoView?.({ behavior: "smooth", block: "nearest" });+ });+ capture("filters:facet_added", {+ tableName,+ column,+ isV4: queryFilter.isV4 ?? false,+ });+ };++ // Sidebar open/collapse adoption — the headline question for the whole+ // surface. `trigger` = which affordance; metadata only.+ const emitSidebarToggled = (open: boolean, trigger: string) => {+ capture("filters:sidebar_toggled", {+ tableName,+ open,+ trigger,+ isV4: queryFilter.isV4 ?? false,+ });+ };const handleFiltersGenerated = useCallback((filters: FilterState) => {// Apply filtersqueryFilter.setFilterState(filters);+ // The v3 wand previously emitted nothing at its only intent seam+ // (metadata only: count of generated conditions, never their values).+ capture("filters:ai_generate_applied", {+ surface: "sidebar_wand",+ tableName,+ generatedCount: filters.length,+ isV4: queryFilter.isV4 ?? false,+ });// Extract unique column names from filtersconst columnsToExpand = [...new Set(filters.map((f) => f.column))];@@ -155,9 +333,199 @@ export function DataTableControls({// Close popoversetAiPopoverOpen(false);},- [queryFilter],+ [queryFilter, capture, tableName],);+ const promotedFacetCount = displayedFilters.filter(isPromoted).length;++ const renderFacet = (filter: UIFilter) => {+ // "Not applied on this surface" (e.g. the chart can't filter on this+ // column — #15187). Only an ACTIVE filter deactivates — an empty facet+ // stays usable. Overrides isDisabled/disabledReason so the facet dims+ // and explains on hover while Clear still works.+ const deactivatedReason = filter.isActive+ ? (deactivatedColumnReason?.(filter.column) ?? null)+ : null;+ const facetDisabled = filter.isDisabled || deactivatedReason !== null;+ const facetDisabledReason = deactivatedReason ?? filter.disabledReason;+ if (filter.type === "categorical") {+ const summaryValue = getFacetSummaryValue(filter);+ return (+ <CategoricalFacet+ key={filter.column}+ filterKey={filter.column}+ label={filter.label}+ tooltip={filter.tooltip}+ help={filter.help}+ summary={getFacetSummary(filter)}+ summaryIcon={+ summaryValue !== null+ ? filter.renderIcon?.(summaryValue)+ : undefined+ }+ isV4={queryFilter.isV4 ?? false}+ expanded={filter.expanded}+ options={filter.options}+ counts={filter.counts}+ displayByValue={filter.displayByValue}+ loading={filter.loading}+ value={filter.value}+ onChange={filter.onChange}+ onOnlyChange={filter.onOnlyChange}+ renderIcon={filter.renderIcon}+ isActive={filter.isActive}+ onReset={filter.onReset}+ operator={filter.operator}+ onOperatorChange={filter.onOperatorChange}+ textFilters={filter.textFilters}+ onTextFilterAdd={filter.onTextFilterAdd}+ onTextFilterRemove={filter.onTextFilterRemove}+ isDisabled={facetDisabled}+ disabledReason={facetDisabledReason}+ />+ );+ }++ if (filter.type === "numeric") {+ return (+ <NumericFacet+ key={filter.column}+ filterKey={filter.column}+ label={filter.label}+ tooltip={filter.tooltip}+ help={filter.help}+ summary={getFacetSummary(filter)}+ expanded={filter.expanded}+ loading={filter.loading}+ min={filter.min}+ max={filter.max}+ value={filter.value}+ onChange={filter.onChange}+ unit={filter.unit}+ isActive={filter.isActive}+ onReset={filter.onReset}+ isDisabled={facetDisabled}+ disabledReason={facetDisabledReason}+ />+ );+ }++ if (filter.type === "string") {+ return (+ <StringFacet+ key={filter.column}+ filterKey={filter.column}+ label={filter.label}+ tooltip={filter.tooltip}+ help={filter.help}+ summary={getFacetSummary(filter)}+ expanded={filter.expanded}+ loading={filter.loading}+ value={filter.value}+ onChange={filter.onChange}+ isActive={filter.isActive}+ onReset={filter.onReset}+ isDisabled={facetDisabled}+ disabledReason={facetDisabledReason}+ />+ );+ }++ if (filter.type === "keyValue") {+ return (+ <KeyValueFacet+ key={filter.column}+ filterKey={filter.column}+ label={filter.label}+ tooltip={filter.tooltip}+ help={filter.help}+ summary={getFacetSummary(filter)}+ expanded={filter.expanded}+ loading={filter.loading}+ keyOptions={filter.keyOptions}+ availableValues={filter.availableValues}+ value={filter.value}+ onChange={filter.onChange}+ isActive={filter.isActive}+ onReset={filter.onReset}+ keyPlaceholder="Name"+ isDisabled={facetDisabled}+ disabledReason={facetDisabledReason}+ />+ );+ }++ if (filter.type === "numericKeyValue") {+ return (+ <NumericKeyValueFacet+ key={filter.column}+ filterKey={filter.column}+ label={filter.label}+ tooltip={filter.tooltip}+ help={filter.help}+ summary={getFacetSummary(filter)}+ expanded={filter.expanded}+ loading={filter.loading}+ keyOptions={filter.keyOptions}+ value={filter.value}+ onChange={filter.onChange}+ isActive={filter.isActive}+ onReset={filter.onReset}+ keyPlaceholder="Name"+ isDisabled={facetDisabled}+ disabledReason={facetDisabledReason}+ />+ );+ }++ if (filter.type === "booleanKeyValue") {+ return (+ <BooleanKeyValueFacet+ key={filter.column}+ filterKey={filter.column}+ label={filter.label}+ tooltip={filter.tooltip}+ help={filter.help}+ summary={getFacetSummary(filter)}+ expanded={filter.expanded}+ loading={filter.loading}+ keyOptions={filter.keyOptions}+ value={filter.value}+ onChange={filter.onChange}+ isActive={filter.isActive}+ onReset={filter.onReset}+ keyPlaceholder="Name"+ isDisabled={facetDisabled}+ disabledReason={facetDisabledReason}+ />+ );+ }++ if (filter.type === "stringKeyValue") {+ return (+ <StringKeyValueFacet+ key={filter.column}+ filterKey={filter.column}+ label={filter.label}+ tooltip={filter.tooltip}+ help={filter.help}+ summary={getFacetSummary(filter)}+ expanded={filter.expanded}+ loading={filter.loading}+ keyOptions={filter.keyOptions}+ value={filter.value}+ onChange={filter.onChange}+ isActive={filter.isActive}+ onReset={filter.onReset}+ isDisabled={facetDisabled}+ disabledReason={facetDisabledReason}+ />+ );+ }++ return null;+ };+return (<>{/* Collapsed rail: shown when the sidebar is collapsed on desktop, where@@ -172,7 +540,10 @@ export function DataTableControls({<Buttonvariant="ghost"size="icon"- onClick={() => setOpen(true)}+ onClick={() => {+ setOpen(true);+ emitSidebarToggled(true, "rail");+ }}aria-label="Show filters"className="h-6 w-6">@@ -185,31 +556,65 @@ export function DataTableControls({{activeFilterCount > 0 && (<Tooltip><TooltipTrigger asChild>- <Badge variant="secondary" className="mt-2 h-5 px-1.5 text-xs">- {activeFilterCount}- </Badge>+ {/* The badge doubles as an expand affordance: the rail hides+ everything else about the filters, so the count is where+ people click to see them. */}+ <button+ type="button"+ onClick={() => {+ setOpen(true);+ emitSidebarToggled(true, "rail_badge");+ }}+ aria-label={`Show ${activeFilterCount} active ${+ activeFilterCount === 1 ? "filter" : "filters"+ }`}+ className="mt-2 cursor-pointer"+ >+ <Badge variant="secondary" className="h-5 px-1.5 text-xs">+ {activeFilterCount}+ </Badge>+ </button></TooltipTrigger>- <TooltipContent side="right">- {activeFilterCount} active{" "}- {activeFilterCount === 1 ? "filter" : "filters"}+ <TooltipContent side="right" className="max-w-64 text-xs">+ <p className="font-medium">+ {activeFilterCount} active{" "}+ {activeFilterCount === 1 ? "filter" : "filters"}+ </p>+ {queryFilter.filters+ .filter((filter) => filter.isActive)+ .slice(0, 6)+ .map((filter) => {+ const line = `${filter.label}: ${+ getFacetSummary(filter) ?? "filtered"+ }`;+ return (+ <p key={filter.column} className="truncate" title={line}>+ {line}+ </p>+ );+ })}+ {activeFilterCount > 6 && <p>+{activeFilterCount - 6} more</p>}</TooltipContent></Tooltip>)}</div><divclassName={cn(- "bg-background flex h-full w-full flex-col overflow-auto border-t",+ "bg-background flex h-full w-full flex-col overflow-hidden border-t","group-data-[expanded=false]/controls:hidden",)}>- <div className="bg-background sticky top-0 z-20 mb-1 flex h-10 shrink-0 items-center justify-between border-b px-3">+ <div className="bg-background flex h-10 shrink-0 items-center justify-between border-b px-3"><div className="flex items-center gap-1.5"><Tooltip><TooltipTrigger asChild><Buttonvariant="ghost"size="icon"- onClick={() => setOpen(false)}+ onClick={() => {+ setOpen(false);+ emitSidebarToggled(false, "header");+ }}aria-label="Hide filters"className="-ml-1 h-6 w-6">@@ -219,23 +624,13 @@ export function DataTableControls({<TooltipContent>Hide filters</TooltipContent></Tooltip><span className="text-sm font-medium">Filters</span>+ {activeFilterCount > 0 && (+ <Badge variant="secondary" className="h-5 px-1.5 text-xs">+ {activeFilterCount}+ </Badge>+ )}</div><div className="flex items-center gap-1">- {queryFilter.isFiltered && (- <Tooltip>- <TooltipTrigger asChild>- <Button- variant="ghost"- size="sm"- onClick={() => queryFilter.clearAll()}- className="h-7 px-2 text-xs"- >- Clear all- </Button>- </TooltipTrigger>- <TooltipContent>Clear all filters</TooltipContent>- </Tooltip>- )}{filterWithAI && isLangfuseCloud && (<Popover open={aiPopoverOpen} onOpenChange={setAiPopoverOpen}><Tooltip>@@ -255,188 +650,208 @@ export function DataTableControls({</PopoverContent></Popover>)}+ {/* Expand/collapse all facets — same affordance and icons as+ the trace tree/timeline header. */}+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ size="icon"+ className="h-6 w-6"+ onClick={() =>+ queryFilter.onExpandedChange(+ queryFilter.expanded.length === 0+ ? displayedFilters.map((filter) => filter.column)+ : [],+ )+ }+ aria-label={+ queryFilter.expanded.length === 0+ ? "Expand all filters"+ : "Collapse all filters"+ }+ >+ {queryFilter.expanded.length === 0 ? (+ <UnfoldVertical className="h-3.5 w-3.5" />+ ) : (+ <FoldVertical className="h-3.5 w-3.5" />+ )}+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ {queryFilter.expanded.length === 0+ ? "Expand all filters"+ : "Collapse all filters"}+ </TooltipContent>+ </Tooltip>+ <DropdownMenu>+ <Tooltip>+ <TooltipTrigger asChild>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ size="icon"+ className="h-6 w-6"+ aria-label="Filter options"+ >+ <MoreVertical className="h-3.5 w-3.5" />+ </Button>+ </DropdownMenuTrigger>+ </TooltipTrigger>+ <TooltipContent>Filter options</TooltipContent>+ </Tooltip>+ <DropdownMenuContent align="end" className="w-48">+ <DropdownMenuItem+ // Enabled also when only value-less added facets exist —+ // Clear all is the affordance that demotes them.+ disabled={+ !queryFilter.isFiltered && revealedColumns.length === 0+ }+ onClick={() => {+ // Explicit adds are part of "everything" too: without+ // this, a value-less added facet stays pinned after+ // Clear all and the active-only empty state can never+ // render again this mount.+ setRevealedColumns([]);+ queryFilter.clearAll();+ }}+ className="cursor-pointer"+ >+ Clear all filters+ </DropdownMenuItem>+ {/* Plain item with a TRAILING check instead of+ DropdownMenuCheckboxItem: its reserved leading indicator+ slot (pl-8) reads as broken indentation next to the+ non-checkbox items, and a trailing check keeps the label+ aligned in both states. */}+ <DropdownMenuItem+ role="menuitemcheckbox"+ aria-checked={showOnlyActive}+ className="cursor-pointer"+ onClick={() => {+ const enabled = !showOnlyActive;+ setShowOnlyActive(enabled);+ capture("filters:active_only_toggled", {+ tableName,+ enabled,+ isV4: queryFilter.isV4 ?? false,+ });+ }}+ >+ Show only active+ {showOnlyActive && <Check className="ml-auto h-3.5 w-3.5" />}+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onClick={() => {+ setOpen(false);+ emitSidebarToggled(false, "menu");+ }}+ className="cursor-pointer"+ >+ Collapse sidebar+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu></div></div>- <div className="pb-10">- <Accordion- type="multiple"- className="w-full"- value={queryFilter.expanded}- onValueChange={queryFilter.onExpandedChange}- >- {queryFilter.filters.map((filter) => {- // "Not applied on this surface" (e.g. the chart can't filter on- // this column). Only an ACTIVE filter deactivates — an empty facet- // stays usable. Overrides isDisabled/disabledReason below so the- // facet dims + explains on hover while Clear still works.- const deactivatedReason = filter.isActive- ? (deactivatedColumnReason?.(filter.column) ?? null)- : null;- if (filter.type === "categorical") {- return (- <CategoricalFacet- key={filter.column}- filterKey={filter.column}- label={filter.label}- tooltip={filter.tooltip}- help={filter.help}- expanded={filter.expanded}- options={filter.options}- counts={filter.counts}- displayByValue={filter.displayByValue}- loading={filter.loading}- value={filter.value}- onChange={filter.onChange}- onOnlyChange={filter.onOnlyChange}- renderIcon={filter.renderIcon}- isActive={filter.isActive}- onReset={filter.onReset}- operator={filter.operator}- onOperatorChange={filter.onOperatorChange}- textFilters={filter.textFilters}- onTextFilterAdd={filter.onTextFilterAdd}- onTextFilterRemove={filter.onTextFilterRemove}- isDisabled={filter.isDisabled || deactivatedReason !== null}- disabledReason={deactivatedReason ?? filter.disabledReason}- />- );- }-- if (filter.type === "numeric") {- return (- <NumericFacet- key={filter.column}- filterKey={filter.column}- label={filter.label}- tooltip={filter.tooltip}- help={filter.help}- expanded={filter.expanded}- loading={filter.loading}- min={filter.min}- max={filter.max}- value={filter.value}- onChange={filter.onChange}- unit={filter.unit}- isActive={filter.isActive}- onReset={filter.onReset}- isDisabled={filter.isDisabled || deactivatedReason !== null}- disabledReason={deactivatedReason ?? filter.disabledReason}- />- );- }-- if (filter.type === "string") {- return (- <StringFacet- key={filter.column}- filterKey={filter.column}- label={filter.label}- tooltip={filter.tooltip}- help={filter.help}- expanded={filter.expanded}- loading={filter.loading}- value={filter.value}- onChange={filter.onChange}- isActive={filter.isActive}- onReset={filter.onReset}- isDisabled={filter.isDisabled || deactivatedReason !== null}- disabledReason={deactivatedReason ?? filter.disabledReason}- />- );- }-- if (filter.type === "keyValue") {- return (- <KeyValueFacet- key={filter.column}- filterKey={filter.column}- label={filter.label}- tooltip={filter.tooltip}- help={filter.help}- expanded={filter.expanded}- loading={filter.loading}- keyOptions={filter.keyOptions}- availableValues={filter.availableValues}- value={filter.value}- onChange={filter.onChange}- isActive={filter.isActive}- onReset={filter.onReset}- keyPlaceholder="Name"- isDisabled={filter.isDisabled || deactivatedReason !== null}- disabledReason={deactivatedReason ?? filter.disabledReason}- />- );- }-- if (filter.type === "numericKeyValue") {- return (- <NumericKeyValueFacet- key={filter.column}- filterKey={filter.column}- label={filter.label}- tooltip={filter.tooltip}- help={filter.help}- expanded={filter.expanded}- loading={filter.loading}- keyOptions={filter.keyOptions}- value={filter.value}- onChange={filter.onChange}- isActive={filter.isActive}- onReset={filter.onReset}- keyPlaceholder="Name"- isDisabled={filter.isDisabled || deactivatedReason !== null}- disabledReason={deactivatedReason ?? filter.disabledReason}- />- );- }-- if (filter.type === "booleanKeyValue") {- return (- <BooleanKeyValueFacet- key={filter.column}- filterKey={filter.column}- label={filter.label}- tooltip={filter.tooltip}- help={filter.help}- expanded={filter.expanded}- loading={filter.loading}- keyOptions={filter.keyOptions}- value={filter.value}- onChange={filter.onChange}- isActive={filter.isActive}- onReset={filter.onReset}- keyPlaceholder="Name"- isDisabled={filter.isDisabled || deactivatedReason !== null}- disabledReason={deactivatedReason ?? filter.disabledReason}- />- );- }-- if (filter.type === "stringKeyValue") {- return (- <StringKeyValueFacet- key={filter.column}- filterKey={filter.column}- label={filter.label}- tooltip={filter.tooltip}- help={filter.help}- expanded={filter.expanded}- loading={filter.loading}- keyOptions={filter.keyOptions}- value={filter.value}- onChange={filter.onChange}- isActive={filter.isActive}- onReset={filter.onReset}- isDisabled={filter.isDisabled || deactivatedReason !== null}- disabledReason={deactivatedReason ?? filter.disabledReason}- />- );- }-- return null;- })}- </Accordion>- </div>+ <ScrollArea+ // contain:paint — during handle drags the browser (notably+ // Firefox) can leave stale fragments of the sticky headers+ // painted outside the shrinking panel; paint containment pins+ // every layer inside the scroll root.+ className="min-h-0 flex-1 [contain:paint]"+ ref={scrollRootRef}+ onFocusCapture={(event) => {+ lastFocusedRef.current = event.target as HTMLElement;+ }}+ >+ {/* w-0 + min-w-full pins the content to the viewport width: the+ Radix viewport wraps children in an inline-styled+ `display: table; min-width: 100%` div that otherwise grows to+ CONTENT width — long value labels would stop truncating and+ hover-revealed affordances would widen the whole list. width: 0+ zeroes the content's intrinsic contribution (the table stays at+ min-width: 100%), then min-w-full stretches this wrapper back to+ the now-fixed table width. */}+ <div className="w-0 min-w-full pt-1 pb-10">+ <Accordion+ type="multiple"+ className="w-full"+ value={queryFilter.expanded}+ onValueChange={queryFilter.onExpandedChange}+ >+ {/* ONE keyed child array — not two .map() slices: React can+ only match keys within the same array, so a facet crossing+ the promoted/rest boundary would REMOUNT (wiping input+ focus and draft state) instead of moving. */}+ {displayedFilters.flatMap((filter, index) => {+ const nodes = [];+ if (index === promotedFacetCount && promotedFacetCount > 0) {+ // Clear spatial break between the active/added block and+ // the inactive rest of the catalog.+ nodes.push(+ // The one line that means something: the boundary+ // between the active/added block and the catalog.+ <div+ key="promoted-separator"+ className="border-border mx-2 my-2 border-t"+ aria-hidden+ />,+ );+ }+ nodes.push(renderFacet(filter));+ return nodes;+ })}+ </Accordion>++ {/* Active-only mode: surface the rest of the catalog behind an+ explicit "Add filter" picker, most-recently-used first, so+ the filters someone actually works with are one click away. */}+ {showOnlyActive && (+ <div+ className={cn(+ "px-3 pt-4",+ displayedFilters.length === 0 &&+ "flex flex-col items-center gap-1 pt-8 text-center",+ )}+ >+ {displayedFilters.length === 0 && (+ <p className="text-muted-foreground pb-2 text-xs">+ No active filters.+ </p>+ )}+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="outline"+ size="sm"+ className="text-xs"+ disabled={addableFilters.length === 0}+ >+ <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) => (+ <DropdownMenuItem+ key={filter.column}+ onClick={() => handleAddFilter(filter.column)}+ className="cursor-pointer"+ >+ {filter.label}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ )}+ </div>+ </ScrollArea></div></>);@@ -449,8 +864,9 @@ interface BaseFacetProps {description: React.ReactNode;href?: string;};+ /** One-line "what is selected?" header summary; see getFacetSummary. */+ summary?: string | null;filterKey: string;- filterKeyShort?: string | null;expanded?: boolean;loading?: boolean;isActive?: boolean;@@ -460,6 +876,10 @@ interface BaseFacetProps {}interface CategoricalFacetProps extends BaseFacetProps {+ /** Color-coded icon of the single value the summary names (renderIcon). */+ summaryIcon?: React.ReactNode;+ /** v3-vs-v4 analytics dimension of the surface (Rule 4). */+ isV4?: boolean;options: string[];counts: Map<string, number>;displayByValue?: Map<string, string>;@@ -530,16 +950,23 @@ const FilterAccordionTrigger = ({children,...props}: React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Trigger>) => (- <AccordionPrimitive.Header className="bg-background sticky top-10 z-10 flex">+ // top-0: the panel header row sits outside the scroll container+ // (ScrollArea wraps only the facet list), so triggers stick to its top.+ // The expand chevron leads the row (> closed, v open); the clear button+ // overlays on hover without reserving layout space.+ <AccordionPrimitive.Header className="bg-background sticky top-0 z-[1] flex px-2 py-0.5"><AccordionPrimitive.TriggerclassName={cn(- "flex flex-1 items-center justify-between text-left font-medium hover:underline [&[data-state=open]>svg]:rotate-180",+ // min-w-0: without it the trigger's automatic min width equals the+ // nowrap chip's full text width, so long chips push the row past the+ // panel edge (clipped) instead of ellipsing.+ "group/facet relative flex min-w-0 flex-1 items-center gap-1.5 text-left font-medium hover:underline [&[data-state=open]>svg:first-child]:rotate-90",className,)}{...props}>+ <ChevronRight className="text-muted-foreground h-3.5 w-3.5 shrink-0 transition-transform" />{children}- <ChevronDown className="h-4 w-4 shrink-0" /></AccordionPrimitive.Trigger></AccordionPrimitive.Header>);@@ -561,8 +988,11 @@ interface FilterAccordionItemProps {description: React.ReactNode;href?: string;};+ /** One-line "what is selected?" summary rendered in the header. */+ summary?: string | null;+ /** Color-coded icon of the single value the summary names. */+ summaryIcon?: React.ReactNode;filterKey: string;- filterKeyShort?: string | null;children: React.ReactNode;isActive?: boolean;isDisabled?: boolean;@@ -574,8 +1004,9 @@ export function FilterAccordionItem({label,tooltip,help,+ summary,+ summaryIcon,filterKey,- filterKeyShort,children,isActive,isDisabled,@@ -583,25 +1014,35 @@ export function FilterAccordionItem({onReset,}: FilterAccordionItemProps) {return (- <FilterAccordionItemPrimitive value={filterKey} className="border-none">+ <FilterAccordionItemPrimitive+ value={filterKey}+ className="py-0.5"+ // Anchor for the follow-scroll after a re-sort moves this facet.+ data-facet-column={filterKey}+ ><FilterAccordionTriggerclassName={cn(- "text-muted-foreground hover:text-foreground px-3 py-1.5 text-sm font-normal hover:no-underline",+ "text-muted-foreground hover:text-foreground bg-muted hover:bg-accent min-h-6 rounded-md px-2 py-1 text-xs font-normal transition-colors hover:no-underline",+ isActive && "text-foreground font-semibold",isDisabled &&- "text-muted-foreground/60 hover:text-muted-foreground/60 cursor-not-allowed",+ "text-muted-foreground/60 hover:text-muted-foreground/60 cursor-not-allowed hover:bg-transparent",)}>- <div className="flex grow items-center gap-1.5 pr-2">+ {/* Two-line-max header: line 1 is the label, which NEVER wraps —+ it ellipses so the clear button keeps its place — and the chip+ drops to its own second line when it doesn't fit inline.+ flex-wrap breaks lines by content sizes, so the chip wraps+ before anything shrinks; only an item alone on its line+ shrink-truncates. The clear button and chevron sit outside the+ wrap container and never move. */}+ <div className="flex min-w-0 grow flex-wrap items-center gap-x-1.5 gap-y-0.5">{isDisabled && disabledReason ? (<Tooltip delayDuration={80}><TooltipTrigger asChild>- <span className="flex grow items-baseline gap-1">- {label}- {filterKeyShort && (- <code className="text-muted-foreground/70 hidden font-mono text-xs">- {filterKeyShort}- </code>- )}+ <span className="flex min-w-0 items-center gap-1">+ <span className="min-w-0 truncate" title={label}>+ {label}+ </span></span></TooltipTrigger><TooltipContent className="max-w-80 text-xs">@@ -609,65 +1050,102 @@ export function FilterAccordionItem({</TooltipContent></Tooltip>) : help ? (- <div className="flex grow items-center gap-1">- {label}+ <div className="flex min-w-0 items-center gap-1">+ <span className="min-w-0 truncate" title={label}>+ {label}+ </span><DocPopup description={help.description} href={help.href} />- {filterKeyShort && (- <code className="text-muted-foreground/70 hidden font-mono text-xs">- {filterKeyShort}- </code>- )}</div>) : tooltip ? (- <Tooltip delayDuration={80}>- <TooltipTrigger asChild>- <span className="flex grow items-center gap-1">- {label}+ // The tooltip triggers on the ⓘ icon only — hovering the label+ // itself must not pop explanatory text.+ <span className="flex min-w-0 items-center gap-1">+ <span className="min-w-0 truncate" title={label}>+ {label}+ </span>+ <Tooltip delayDuration={80}>+ <TooltipTrigger asChild><InfoIcon className="text-muted-foreground h-3 w-3 shrink-0" />- {filterKeyShort && (- <code className="text-muted-foreground/70 hidden font-mono text-xs">- {filterKeyShort}- </code>- )}- </span>- </TooltipTrigger>- <TooltipContent className="max-w-80 text-xs">- {tooltip}- </TooltipContent>- </Tooltip>+ </TooltipTrigger>+ <TooltipContent className="max-w-80 text-xs">+ {tooltip}+ </TooltipContent>+ </Tooltip>+ </span>) : (- <span className="flex grow items-baseline gap-1">- {label}- {filterKeyShort && (- <code className="text-muted-foreground/70 hidden font-mono text-xs">- {filterKeyShort}- </code>- )}+ <span className="flex min-w-0 items-center gap-1">+ <span className="min-w-0 truncate" title={label}>+ {label}+ </span></span>)}- {isActive && onReset && (- <div- role="button"- tabIndex={0}- onClick={(e) => {- e.stopPropagation();- onReset();- }}- onKeyDown={(e) => {- if (e.key === "Enter" || e.key === " ") {- e.stopPropagation();- e.preventDefault();- onReset();- }- }}- className="bg-background hover:bg-accent hover:text-accent-foreground inline-flex h-5 cursor-pointer items-center gap-1 rounded-full border px-2 text-xs"- aria-label={`Clear ${label} filter`}+ {summary && (+ // Only useful while collapsed: the expanded facet shows the+ // selection itself, so the chip hides (data-state on the+ // trigger = the group/facet element).+ <span+ className={cn(+ // explicit h-4: the chip box must exactly equal the label line so the+ // header height cannot jitter between open (chip hidden) and+ // closed states.+ "h-4 max-w-full min-w-0 truncate text-[11px] leading-4",+ "group-data-[state=open]/facet:hidden",+ // bg-background pops the chip out of the tinted header band+ // in both themes. No border/vertical padding: the chip's box+ // must equal the label's line height so headers with and+ // without a value render at the same height.+ isActive+ ? "bg-background text-foreground rounded px-1 font-medium"+ : "text-muted-foreground/60 font-normal",+ )}+ title={summary}>- <span>Clear</span>- <IconX className="h-3 w-3" />- </div>+ {summaryIcon && (+ <span className="mr-1 inline-flex align-text-bottom">+ {summaryIcon}+ </span>+ )}+ {summary}+ </span>)}</div>+ {isActive && onReset && (+ <Tooltip delayDuration={80}>+ <TooltipTrigger asChild>+ {/* div[role=button], not <Button>: the accordion trigger is+ already a <button> and buttons cannot nest. Rendered as a+ hover/focus-revealed OVERLAY (absolute, own background) so+ it never shifts the header layout. */}+ <div+ role="button"+ tabIndex={0}+ onClick={(e) => {+ e.stopPropagation();+ onReset();+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter" || e.key === " ") {+ e.stopPropagation();+ e.preventDefault();+ onReset();+ }+ }}+ // top-1 anchors the button to the label line — a 20px+ // button in the 28px single-line header reads centered, and+ // on two-line headers it stays top-right. bg-accent matches+ // the hovered header band (the button is only visible while+ // the band shows its hover color).+ className="bg-accent text-muted-foreground hover:text-foreground absolute top-0.5 right-1 flex h-5 w-5 cursor-pointer items-center justify-center rounded-sm opacity-0 transition-opacity group-hover/facet:opacity-100 focus-visible:opacity-100"+ aria-label={`Clear ${label} filter`}+ >+ <IconX className="h-3 w-3" />+ </div>+ </TooltipTrigger>+ <TooltipContent side="right" className="text-xs">+ Clear {label.toLowerCase()} filter+ </TooltipContent>+ </Tooltip>+ )}</FilterAccordionTrigger><FilterAccordionContent className="pb-2"><fieldset@@ -688,9 +1166,11 @@ export function CategoricalFacet({label,tooltip,help,+ summary,+ summaryIcon,+ isV4,filterKey,- filterKeyShort,- expanded,+ expanded: _expanded,loading,options,counts,@@ -709,52 +1189,147 @@ export function CategoricalFacet({onTextFilterAdd,onTextFilterRemove,}: CategoricalFacetProps) {- const [showAll, setShowAll] = useState(false);- const [searchQuery, setSearchQuery] = useState("");- // Track which filter mode is active (select checkboxes vs text filters)- const [filterMode, setFilterMode] = useState<"select" | "text">("select");+ const capture = usePostHogClientCapture();+ const { tableName } = useContext(ControlsContext) ?? {};+ // Which input mode the facet is in (checkbox select vs contains/does-not-+ // contain text). Seeded from the applied filters so a deep link carrying+ // text filters opens in text mode instead of hiding them behind the tab.+ const hasTextFilters = (textFilters?.length ?? 0) > 0;+ const [filterMode, setFilterMode] = useState<"select" | "text">(() =>+ hasTextFilters ? "text" : "select",+ );+ // Adopt DURING render as well: on a hard reload the Pages Router delivers+ // `?filter=` a few renders after mount (LFE-10164 in the state hook), so+ // the mount seed alone would leave a text-filter deep link on the Select+ // tab. Only the 0→n transition switches — removing the last text filter+ // or picking a tab by hand is never overridden.+ const [prevHasTextFilters, setPrevHasTextFilters] = useState(hasTextFilters);+ if (hasTextFilters !== prevHasTextFilters) {+ setPrevHasTextFilters(hasTextFilters);+ if (hasTextFilters) setFilterMode("text");+ }- // Reset showAll and searchQuery state when accordion is collapsed- useEffect(() => {- if (!expanded) {- setShowAll(false);- setSearchQuery("");- }- }, [expanded]);-- // Handle mode change with auto-clear of filters from the other mode- const handleModeChange = useCallback(- (newMode: "select" | "text") => {- setFilterMode(newMode);-- // Clear filters from the other mode- if (newMode === "select") {- textFilters?.forEach((f) => onTextFilterRemove?.(f.operator, f.value));- } else {- onChange([]);- }- },- [textFilters, onTextFilterRemove, onChange],+ // Switching modes is NON-destructive: the other mode's applied filters stay+ // until the user applies something in the new mode — the state hook already+ // enforces select/text mutual exclusivity at apply time (updateFilter drops+ // the column's text filters, addTextFilter drops its checkbox filters).+ // Clearing on the tab click itself deleted a shared link's filters one+ // exploratory click after opening it, with no undo. Captured here at the+ // user-intent seam (Tabs only fires on actual change); the render-time+ // text-mode adoption above deliberately bypasses this and emits nothing.+ const handleModeChange = (newMode: "select" | "text") => {+ setFilterMode(newMode);+ capture("filters:facet_mode_switched", {+ tableName,+ column: filterKey,+ mode: newMode,+ isV4: isV4 ?? false,+ });+ };++ return (+ <FilterAccordionItem+ label={label}+ tooltip={tooltip}+ help={help}+ summary={summary}+ summaryIcon={summaryIcon}+ filterKey={filterKey}+ isActive={isActive}+ isDisabled={isDisabled}+ disabledReason={disabledReason}+ onReset={onReset}+ >+ <div className="flex flex-col">+ {/* Tab switcher - only show when text filtering is supported */}+ {onTextFilterAdd && (+ <FilterModeTabs mode={filterMode} onModeChange={handleModeChange} />+ )}++ {/* SELECT MODE: checkboxes with optional counts */}+ {filterMode === "select" && (+ <CategoricalSelectContent+ filterKey={filterKey}+ loading={loading}+ options={options}+ counts={counts}+ displayByValue={displayByValue}+ value={value}+ onChange={onChange}+ onOnlyChange={onOnlyChange}+ renderIcon={renderIcon}+ operator={operator}+ onOperatorChange={onOperatorChange}+ />+ )}++ {/* TEXT MODE: Contains/Does Not Contain filters */}+ {filterMode === "text" && onTextFilterAdd && (+ <div className="px-2 py-1">+ <TextFilterSection+ allFilters={textFilters ?? []}+ onAdd={onTextFilterAdd}+ onRemove={onTextFilterRemove}+ />+ </div>+ )}+ </div>+ </FilterAccordionItem>);+}+// Values shown per facet before "Show more values" gates the rest.+const MAX_VISIBLE_OPTIONS = 12;+// Each "Show more values" click reveals this many additional values.+const SHOW_MORE_INCREMENT = 50;++// Select-mode body of a categorical facet. A separate stateful child so its+// transient list UI state (value search, "show more") lives inside the+// accordion content and unmounts — and therefore resets — when the facet is+// collapsed (Radix unmounts closed content), instead of a reset effect in+// the always-mounted facet wrapper.+function CategoricalSelectContent({+ filterKey,+ loading,+ options,+ counts,+ displayByValue,+ value,+ onChange,+ onOnlyChange,+ renderIcon,+ operator,+ onOperatorChange,+}: Pick<+ CategoricalFacetProps,+ | "filterKey"+ | "loading"+ | "options"+ | "counts"+ | "displayByValue"+ | "value"+ | "onChange"+ | "onOnlyChange"+ | "renderIcon"+ | "operator"+ | "onOperatorChange"+>) {+ // "Show more values" reveals the next PORTION (it does what it says — not+ // expand-everything: value lists can run to 1000+ user IDs); "Show fewer+ // values" collapses back to the cap. Resets by unmounting on collapse.+ const [visibleCount, setVisibleCount] = useState(MAX_VISIBLE_OPTIONS);+ const [searchQuery, setSearchQuery] = useState("");const { tableName = "data" } = useContext(ControlsContext) ?? {};-- const MAX_VISIBLE_OPTIONS = 12;const visibleOptionValues = Array.from(new Set([...options, ...value.filter((option) => option.length > 0)]),);const hasMoreOptions = visibleOptionValues.length > MAX_VISIBLE_OPTIONS;- // Filter options by search query (check both raw value and display label)+ // Filter options by search query (raw value and display label), ranked the+ // way the search bar ranks its completions: prefix matches before+ // substring matches, instead of plain unordered substring filtering.const filteredOptions = searchQuery- ? visibleOptionValues.filter((option) => {- const search = searchQuery.toLowerCase();- const displayLabel = displayByValue?.get(option) ?? option;- return (- option.toLowerCase().includes(search) ||- displayLabel.toLowerCase().includes(search)- );- })+ ? rankFacetOptions(visibleOptionValues, searchQuery, displayByValue): visibleOptionValues;// Order the applied filter to the top of the list so it is immediately@@ -784,7 +1359,10 @@ export function CategoricalFacet({visibleOptionValues.filter((option) => !selectedSet.has(option)),): selectedSet;+ // While searching, rankFacetOptions owns the order (prefix matches first);+ // pinning checked rows above better matches would fight it.const pinApplied =+ !searchQuery &&hasMoreOptions &&value.length > 0 &&value.length < visibleOptionValues.length;@@ -795,10 +1373,9 @@ export function CategoricalFacet({]: filteredOptions;- const hasMoreFilteredOptions = orderedOptions.length > MAX_VISIBLE_OPTIONS;- const visibleOptions = showAll- ? orderedOptions- : orderedOptions.slice(0, MAX_VISIBLE_OPTIONS);+ const visibleOptions = orderedOptions.slice(0, visibleCount);+ const canShowMore = orderedOptions.length > visibleCount;+ const canShowFewer = visibleCount > MAX_VISIBLE_OPTIONS;// Split the visible slice so a separator can mark where the pinned rows// end. When not pinning, everything renders in natural order (no divider).@@ -832,237 +1409,222 @@ export function CategoricalFacet({};return (- <FilterAccordionItem- label={label}- tooltip={tooltip}- help={help}- filterKey={filterKey}- filterKeyShort={filterKeyShort}- isActive={isActive}- isDisabled={isDisabled}- disabledReason={disabledReason}- onReset={onReset}- >- <div className="flex flex-col">- {/* Tab switcher - only show when text filtering is supported */}- {onTextFilterAdd && (- <FilterModeTabs mode={filterMode} onModeChange={handleModeChange} />- )}-- {/* SELECT MODE: Checkboxes with optional counts */}- {filterMode === "select" && (- <div className="px-2">- {/* SOME/ALL/NONE operator toggle for arrayOptions filters-- This toggle appears for multi-valued array columns (arrayOptions) like tags.- It allows switching between the supported array matching modes:- - SOME: Match items with ANY selected value (OR logic)- - ALL: Match items with ALL selected values (AND logic)- - NONE: Exclude items carrying any UNCHECKED value (the filter- stores the exclusions; checkboxes show the kept complement,- LFE-10717)-- Toggling between modes carries the stored value list over, so- SOME "match a or b" becomes NONE "exclude a and b" — the- checked set visually flips to its complement.-- NONE mode usually engages by itself: unchecking a value from- the all-checked default persists `none of [value]`. The toggle- remains for converting an existing selection or persisting an- operator preference before any values are selected. Other- filter types (stringOptions, boolean, numeric) don't get this- toggle because these array-specific modes are not semantically- meaningful there.-- Currently enabled for:- - Traces: tags- - Sessions: userIds, tags- - Prompts: labels, tags- - Monitors: tags- */}- {onOperatorChange && (- <div className="mb-1.5 flex items-center gap-1.5 px-2">- <span className="text-muted-foreground/80 text-[10px]">- Match:- </span>- <div className="border-input/50 bg-background inline-flex rounded border text-[10px]">- <button- onClick={() => onOperatorChange("any of")}- className={cn(- "rounded-l px-1.5 py-0.5 transition-colors",- operator === "any of" || !operator- ? "bg-accent text-accent-foreground font-medium"- : "text-muted-foreground hover:text-foreground",- )}- >- SOME- </button>- <div className="bg-border/50 w-px" />- <button- onClick={() => onOperatorChange("all of")}- className={cn(- "px-1.5 py-0.5 transition-colors",- operator === "all of"- ? "bg-accent text-accent-foreground font-medium"- : "text-muted-foreground hover:text-foreground",- )}- >- ALL- </button>- <div className="bg-border/50 w-px" />- <button- onClick={() => onOperatorChange("none of")}- className={cn(- "rounded-r px-1.5 py-0.5 transition-colors",- operator === "none of"- ? "bg-accent text-accent-foreground font-medium"- : "text-muted-foreground hover:text-foreground",- )}- >- NONE- </button>- </div>- </div>- )}-- {/* Loading / Empty / Options */}- {loading ? (- <>- {[1, 2].map((i) => (- <div key={i} className="relative flex items-center px-2">- <div className="group/checkbox flex items-center rounded-sm p-1">- <Skeleton className="h-4 w-4 rounded-sm" />- </div>- <div className="group/label flex min-w-0 flex-1 items-center rounded-sm px-1 py-1">- <Skeleton className="h-3 w-24" />- <Skeleton className="ml-auto h-3 w-8" />- </div>- </div>- ))}- </>- ) : visibleOptionValues.length === 0 ? (- <div className="text-muted-foreground py-1 text-xs">- {filterKey === "sessionId" ? (- <span>- Sessions group {tableName} together, which is useful for- tracing multi-step workflows.{" "}- <a- href="https://langfuse.com/docs/observability/features/sessions"- target="_blank"- rel="noopener noreferrer"- className="hover:text-foreground underline"- >- See docs- </a>{" "}- to learn how to add sessions to your {tableName}.- </span>- ) : filterKey === "name" ? (- <span>- No {tableName} names found in the given time range.- </span>- ) : filterKey === "tags" ? (- <span>- Tags let you filter {tableName} according to custom- categories (e.g. feature flags).{" "}- <a- href="https://langfuse.com/docs/observability/features/tags"- target="_blank"- rel="noopener noreferrer"- className="hover:text-foreground underline"+ <div className="px-2">+ {/* Any of / All of / None of operator toggle for arrayOptions filters++ This toggle appears for multi-valued array columns (arrayOptions)+ like tags. It switches between the supported array matching modes:+ - Any of: match items with ANY selected value (OR logic)+ - All of: match items with ALL selected values (AND logic)+ - None of: exclude items carrying any UNCHECKED value (the filter+ stores the exclusions; checkboxes show the kept complement,+ LFE-10717)++ Toggling between modes carries the stored value list over, so+ any-of "match a or b" becomes none-of "exclude a and b" — the+ checked set visually flips to its complement.++ None-of mode usually engages by itself: unchecking a value from+ the all-checked default persists `none of [value]`. The toggle+ remains for converting an existing selection or persisting an+ operator preference before any values are selected. Other+ filter types (stringOptions, boolean, numeric) don't get this+ toggle because these array-specific modes are not semantically+ meaningful there.++ Currently enabled for:+ - Traces: tags+ - Sessions: userIds, tags+ - Prompts: labels, tags+ - Monitors: tags+ */}+ {onOperatorChange && (+ <div className="mb-2 px-2">+ <Tabs+ value={operator ?? "any of"}+ onValueChange={(newOperator) =>+ onOperatorChange(newOperator as "any of" | "all of" | "none of")+ }+ >+ <TabsList className="grid h-6 w-full grid-cols-3 p-0.5">+ <TabsTrigger value="any of" className="h-5 px-1 text-xs">+ Any of+ </TabsTrigger>+ <TabsTrigger value="all of" className="h-5 px-1 text-xs">+ All of+ </TabsTrigger>+ {/* Without a persisted selection, switching to "none of" is a+ deliberate no-op in the state model (an empty exclusion+ would persist a vacuous filter — LFE-10717), which used to+ read as a broken button. Disable it and say why; it+ enables as soon as any selection exists, and NONE mode+ engages by itself when a value is unchecked. */}+ <Tooltip delayDuration={80}>+ <TooltipTrigger asChild>+ <span className="min-w-0">+ <TabsTrigger+ value="none of"+ disabled={operator === undefined}+ className="h-5 w-full px-1 text-xs disabled:cursor-not-allowed disabled:opacity-50">- See docs- </a>{" "}- to learn how to add tags to your {tableName}.+ None of+ </TabsTrigger></span>- ) : (- "No options found"+ </TooltipTrigger>+ {operator === undefined && (+ <TooltipContent className="max-w-64 text-xs">+ Nothing to exclude yet — uncheck a value to exclude it, or+ select values first.+ </TooltipContent>)}+ </Tooltip>+ </TabsList>+ </Tabs>+ </div>+ )}++ {/* Loading / Empty / Options */}+ {loading ? (+ <>+ {[1, 2].map((i) => (+ <div key={i} className="relative flex items-center px-2">+ <div className="group/checkbox flex items-center rounded-sm p-0.5">+ <Skeleton className="h-3.5 w-3.5 rounded-sm" /></div>- ) : (- <>- {/* Search box for many options */}- {hasMoreOptions && (- <div className="mb-2 px-2">- <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="Filter values"- value={searchQuery}- onChange={(e) => setSearchQuery(e.target.value)}- className="h-8 pl-7 text-xs"- />- </div>- </div>- )}+ <div className="group/label flex min-w-0 flex-1 items-center rounded-sm px-1 py-0.5">+ <Skeleton className="h-3 w-24" />+ <Skeleton className="ml-auto h-3 w-8" />+ </div>+ </div>+ ))}+ </>+ ) : visibleOptionValues.length === 0 ? (+ // px-2 on top of the outer px-2 = the same 16px inset as the mode+ // tabs and inputs, so empty states don't stick to the panel edge.+ <div className="text-muted-foreground px-2 py-1 text-xs">+ {filterKey === "sessionId" ? (+ <span>+ Sessions group {tableName} together, which is useful for tracing+ multi-step workflows.{" "}+ <a+ href="https://langfuse.com/docs/observability/features/sessions"+ target="_blank"+ rel="noopener noreferrer"+ className="hover:text-foreground underline"+ >+ See docs+ </a>{" "}+ to learn how to add sessions to your {tableName}.+ </span>+ ) : filterKey === "name" ? (+ <span>No {tableName} names found in the given time range.</span>+ ) : filterKey === "tags" ? (+ <span>+ Tags let you filter {tableName} according to custom categories+ (e.g. feature flags).{" "}+ <a+ href="https://langfuse.com/docs/observability/features/tags"+ target="_blank"+ rel="noopener noreferrer"+ className="hover:text-foreground underline"+ >+ See docs+ </a>{" "}+ to learn how to add tags to your {tableName}.+ </span>+ ) : (+ "No options found"+ )}+ </div>+ ) : (+ <>+ {/* Search box for many options */}+ {hasMoreOptions && (+ <div className="mb-2 px-2">+ <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="Filter values"+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}+ className="h-8 pl-7 text-xs"+ />+ </div>+ </div>+ )}- {/* Checkbox list */}- {filteredOptions.length === 0 ? (- <div className="text-muted-foreground py-1 text-center text-sm">- No matches found- </div>- ) : (- <>- {/* Applied-filter rows (selected, or excluded under+ {/* Checkbox list */}+ {filteredOptions.length === 0 ? (+ <div className="text-muted-foreground py-1 text-center text-sm">+ No matches found+ </div>+ ) : (+ <>+ {/* Applied-filter rows (selected, or excluded under`none of`), pinned to the top (long lists only) */}- {visiblePinnedOptions.map(renderOption)}-- {/* Separator between the pinned rows and the rest */}- {visiblePinnedOptions.length > 0 &&- visibleRemainingOptions.length > 0 && (- <div- className="border-border/60 mx-3 my-1 border-t"- aria-hidden- />- )}-- {/* Remaining options, capped */}- {visibleRemainingOptions.map(renderOption)}- {hasMoreFilteredOptions && !showAll && (- <div className="px-2">- <Button- variant="ghost"- size="sm"- onClick={() => setShowAll(true)}- className="mt-1 h-auto w-full justify-start py-1 pl-7 text-xs"- >- Show more values- </Button>- </div>- )}- </>+ {visiblePinnedOptions.map(renderOption)}++ {/* Separator between the pinned rows and the rest */}+ {visiblePinnedOptions.length > 0 &&+ visibleRemainingOptions.length > 0 && (+ <div+ className="border-border/60 mx-3 my-1 border-t"+ aria-hidden+ />)}- {filterKey === "environment" &&- visibleOptionValues.length === 1 &&- visibleOptionValues[0]?.toLowerCase() === "default" ? (- <div className="text-muted-foreground mt-2 px-2 text-xs">- <a- href="https://langfuse.com/docs/observability/features/environments"- target="_blank"- rel="noopener noreferrer"- className="hover:text-foreground underline"- >- See docs- </a>{" "}- on how to add environments to your {tableName}.- </div>- ) : null}- </>- )}- </div>- )}- {/* TEXT MODE: Contains/Does Not Contain filters */}- {filterMode === "text" && onTextFilterAdd && (- <div className="px-2 py-1">- <TextFilterSection- allFilters={textFilters ?? []}- onAdd={onTextFilterAdd}- onRemove={onTextFilterRemove}- />- </div>- )}- </div>- </FilterAccordionItem>+ {/* Remaining options, capped */}+ {visibleRemainingOptions.map(renderOption)}+ {(canShowMore || canShowFewer) && (+ <div className="flex flex-col px-2">+ {canShowFewer && (+ <Button+ variant="ghost"+ size="sm"+ onClick={() => setVisibleCount(MAX_VISIBLE_OPTIONS)}+ className="mt-1 h-auto w-full justify-start py-1 pl-7 text-xs"+ >+ <ChevronUp className="mr-1 h-3 w-3" />+ Show fewer values+ </Button>+ )}+ {canShowMore && (+ <Button+ variant="ghost"+ size="sm"+ onClick={() =>+ setVisibleCount(+ (current) => current + SHOW_MORE_INCREMENT,+ )+ }+ className="mt-0.5 h-auto w-full justify-start py-1 pl-7 text-xs"+ >+ <ChevronDown className="mr-1 h-3 w-3" />+ Show more values+ </Button>+ )}+ </div>+ )}+ </>+ )}+ {filterKey === "environment" &&+ visibleOptionValues.length === 1 &&+ visibleOptionValues[0]?.toLowerCase() === "default" ? (+ <div className="text-muted-foreground mt-2 px-2 text-xs">+ <a+ href="https://langfuse.com/docs/observability/features/environments"+ target="_blank"+ rel="noopener noreferrer"+ className="hover:text-foreground underline"+ >+ See docs+ </a>{" "}+ on how to add environments to your {tableName}.+ </div>+ ) : null}+ </>+ )}+ </div>);}@@ -1070,8 +1632,8 @@ export function NumericFacet({label,tooltip,help,+ summary,filterKey,- filterKeyShort,expanded: _expanded,loading,min,@@ -1085,11 +1647,16 @@ export function NumericFacet({onReset,}: NumericFacetProps) {const [localValue, setLocalValue] = useState<[number, number]>(value);- const timeoutRef = useRef<NodeJS.Timeout | null>(null);-- useEffect(() => {+ // Adopt external value changes (reset, URL navigation) during render — the+ // "adjust state when a prop changes" pattern — rather than via a mirror+ // effect. `lastValue` tracks the last adopted prop so pending local edits+ // (which lead the prop while the debounce runs) survive unrelated renders.+ const [lastValue, setLastValue] = useState<[number, number]>(value);+ if (lastValue[0] !== value[0] || lastValue[1] !== value[1]) {+ setLastValue(value);setLocalValue(value);- }, [value]);+ }+ const timeoutRef = useRef<NodeJS.Timeout | null>(null);// Cleanup timeout on unmountuseEffect(() => {@@ -1154,8 +1721,8 @@ export function NumericFacet({label={label}tooltip={tooltip}help={help}+ summary={summary}filterKey={filterKey}- filterKeyShort={filterKeyShort}isActive={isActive}isDisabled={isDisabled}disabledReason={disabledReason}@@ -1236,8 +1803,8 @@ export function StringFacet({label,tooltip,help,+ summary,filterKey,- filterKeyShort,expanded: _expanded,loading,value,@@ -1248,11 +1815,13 @@ export function StringFacet({onReset,}: StringFacetProps) {const [localValue, setLocalValue] = useState<string>(value);- const timeoutRef = useRef<NodeJS.Timeout | null>(null);-- useEffect(() => {+ // Same render-time adoption as NumericFacet above (no mirror effect).+ const [lastValue, setLastValue] = useState<string>(value);+ if (lastValue !== value) {+ setLastValue(value);setLocalValue(value);- }, [value]);+ }+ const timeoutRef = useRef<NodeJS.Timeout | null>(null);// Cleanup timeout on unmountuseEffect(() => {@@ -1286,8 +1855,8 @@ export function StringFacet({label={label}tooltip={tooltip}help={help}+ summary={summary}filterKey={filterKey}- filterKeyShort={filterKeyShort}isActive={isActive}isDisabled={isDisabled}disabledReason={disabledReason}@@ -1315,8 +1884,8 @@ export function KeyValueFacet({label,tooltip,help,+ summary,filterKey,- filterKeyShort,expanded: _expanded,loading,keyOptions,@@ -1334,8 +1903,8 @@ export function KeyValueFacet({label={label}tooltip={tooltip}help={help}+ summary={summary}filterKey={filterKey}- filterKeyShort={filterKeyShort}isActive={isActive}isDisabled={isDisabled}disabledReason={disabledReason}@@ -1363,8 +1932,8 @@ export function NumericKeyValueFacet({label,tooltip,help,+ summary,filterKey,- filterKeyShort,expanded: _expanded,loading,keyOptions,@@ -1381,8 +1950,8 @@ export function NumericKeyValueFacet({label={label}tooltip={tooltip}help={help}+ summary={summary}filterKey={filterKey}- filterKeyShort={filterKeyShort}isActive={isActive}isDisabled={isDisabled}disabledReason={disabledReason}@@ -1409,8 +1978,8 @@ export function BooleanKeyValueFacet({label,tooltip,help,+ summary,filterKey,- filterKeyShort,expanded: _expanded,loading,keyOptions,@@ -1427,8 +1996,8 @@ export function BooleanKeyValueFacet({label={label}tooltip={tooltip}help={help}+ summary={summary}filterKey={filterKey}- filterKeyShort={filterKeyShort}isActive={isActive}isDisabled={isDisabled}disabledReason={disabledReason}@@ -1455,8 +2024,8 @@ export function StringKeyValueFacet({label,tooltip,help,+ summary,filterKey,- filterKeyShort,expanded: _expanded,loading,keyOptions,@@ -1473,8 +2042,8 @@ export function StringKeyValueFacet({label={label}tooltip={tooltip}help={help}+ summary={summary}filterKey={filterKey}- filterKeyShort={filterKeyShort}isActive={isActive}isDisabled={isDisabled}disabledReason={disabledReason}@@ -1505,33 +2074,22 @@ interface FilterModeTabsProps {function FilterModeTabs({ mode, onModeChange }: FilterModeTabsProps) {return (- <div className="@container mb-2 flex flex-wrap items-center gap-1.5 px-4">- <span className="text-muted-foreground/80 text-[10px]">Mode:</span>- <div className="border-input/50 bg-background flex flex-1 flex-col rounded border text-[10px] @[7.5rem]:min-w-[140px] @[7.5rem]:flex-row">- <button- onClick={() => onModeChange("select")}- className={cn(- "flex-1 rounded-t px-3 py-0.5 transition-colors @[7.5rem]:rounded-l @[7.5rem]:rounded-tr-none",- mode === "select"- ? "bg-accent text-accent-foreground font-medium"- : "text-muted-foreground hover:text-foreground",- )}- >- SELECT- </button>- <div className="bg-border/50 h-px @[7.5rem]:h-auto @[7.5rem]:w-px" />- <button- onClick={() => onModeChange("text")}- className={cn(- "flex-1 rounded-b px-3 py-0.5 transition-colors @[7.5rem]:rounded-r @[7.5rem]:rounded-bl-none",- mode === "text"- ? "bg-accent text-accent-foreground font-medium"- : "text-muted-foreground hover:text-foreground",- )}- >- TEXT- </button>- </div>+ // mt-1 evens the rhythm: content opens with pt-1, so the tabs sit 8px+ // from the header band and 8px (mb-2) from the list below.+ <div className="mt-1 mb-2 px-4">+ <Tabs+ value={mode}+ onValueChange={(newMode) => onModeChange(newMode as "select" | "text")}+ >+ <TabsList className="grid h-6 w-full grid-cols-2 p-0.5">+ <TabsTrigger value="select" className="h-5 px-2 text-xs">+ Select+ </TabsTrigger>+ <TabsTrigger value="text" className="h-5 px-2 text-xs">+ Text+ </TabsTrigger>+ </TabsList>+ </Tabs></div>);}@@ -1562,33 +2120,26 @@ function TextFilterSection({return (<div className="space-y-2">- {/* Operator toggle */}- <div className="flex items-center gap-1 px-2">- <div className="border-input/50 bg-background inline-flex rounded border text-[10px]">- <button- onClick={() => setSelectedOperator("contains")}- className={cn(- "rounded-l px-2 py-0.5 transition-colors",- selectedOperator === "contains"- ? "bg-accent text-accent-foreground font-medium"- : "text-muted-foreground hover:text-foreground",- )}- >- contains- </button>- <div className="bg-border/50 w-px" />- <button- onClick={() => setSelectedOperator("does not contain")}- className={cn(- "rounded-r px-2 py-0.5 transition-colors",- selectedOperator === "does not contain"- ? "bg-accent text-accent-foreground font-medium"- : "text-muted-foreground hover:text-foreground",- )}- >- does not contain- </button>- </div>+ {/* Operator picker */}+ <div className="px-2">+ <Select+ value={selectedOperator}+ onValueChange={(operator) =>+ setSelectedOperator(operator as "contains" | "does not contain")+ }+ >+ <SelectTrigger className="h-7 w-full text-xs">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="contains" className="text-xs">+ contains+ </SelectItem>+ <SelectItem value="does not contain" className="text-xs">+ does not contain+ </SelectItem>+ </SelectContent>+ </Select></div>{/* Input + Add button */}@@ -1624,7 +2175,7 @@ function TextFilterSection({key={idx}className="group/textfilter border-border/40 bg-muted/30 flex items-center gap-2 rounded border px-2 py-1 text-xs">- <span className="text-muted-foreground shrink-0 text-[10px] font-medium">+ <span className="text-muted-foreground shrink-0 text-[11px] font-medium">{f.operator === "contains" ? "contains" : "does not contain"}</span><span@@ -1687,20 +2238,20 @@ export function FilterValueCheckbox({)}>{/* Checkbox hover area */}- <div className="group/checkbox hover:bg-accent flex items-center rounded-sm p-1 transition-colors">+ <div className="group/checkbox hover:bg-accent flex items-center rounded-sm p-0.5 transition-colors"><Checkboxid={id}checked={checked}onCheckedChange={onCheckedChange}disabled={disabled}- className="pointer-events-auto"+ className="pointer-events-auto h-3.5 w-3.5 [&_svg]:h-3 [&_svg]:w-3"/></div>{/* Label hover area */}<divclassName={cn(- "group/label hover:bg-accent flex min-w-0 flex-1 cursor-pointer items-center rounded-sm px-1 py-1 transition-colors",+ "group/label hover:bg-accent flex min-w-0 flex-1 cursor-pointer items-center rounded-sm px-1 py-0.5 transition-colors",disabled && "pointer-events-none",)}onClick={onLabelClick}@@ -1716,15 +2267,17 @@ export function FilterValueCheckbox({{displayLabel}</span>- {/* "Only" or "All" indicator when hovering label */}+ {/* "Only" or "All" indicator when hovering label. shrink-0 ++ whitespace-nowrap: appearing may only re-truncate the label —+ never widen the row. */}{onLabelClick && !disabled && (- <span className="text-muted-foreground hidden pl-1 text-xs group-hover/label:block">+ <span className="text-muted-foreground hidden shrink-0 pl-1 text-xs whitespace-nowrap group-hover/label:block">{labelText}</span>)}{count > 0 ? (- <span className="text-muted-foreground ml-auto w-7 pl-1 text-right text-xs">+ <span className="text-muted-foreground ml-auto w-7 shrink-0 pl-1 text-right text-xs">{compactNumberFormatter(count, 0)}</span>) : null}diff --git a/web/src/components/table/resizable-filter-layout.tsx b/web/src/components/table/resizable-filter-layout.tsxindex 64bad49766..15e29f60a1 100644--- a/web/src/components/table/resizable-filter-layout.tsx+++ b/web/src/components/table/resizable-filter-layout.tsx@@ -9,7 +9,19 @@ import { useDataTableControls } from "./data-table-controls";// of hiding, the sidebar collapses to a thin rail carrying a re-open button// (rendered by DataTableControls). Dragging below the min snaps to the rail.const FILTER_PANEL_COLLAPSED_PX = 40;+// The floor is where the layout genuinely stops working (the three-way+// operator tabs start clipping), not where it merely gets cozy — compact+// headers ellipse/wrap fine well below the comfortable default.const FILTER_PANEL_MIN_PX = 160;+// Comfortable default width. The panel API takes percentages, so this is+// converted against the window width at mount — computing the percentage+// ourselves keeps the default deterministic, unlike a px defaultSize, which+// react-resizable-panels resolves against a transient first-measure width+// and eagerly persists (LFE-10601). Percentage-only defaults are wrong in+// the other direction: 15% was cramped on laptops and needlessly wide on+// ultrawides. Capped so the table keeps priority on narrow windows.+const FILTER_PANEL_DEFAULT_PX = 280;+const FILTER_PANEL_MAX_DEFAULT_PCT = 30;/** Resizable layout for filter sidebar and table content.* On mobile, renders a stacked layout instead of resizable panels.@@ -40,8 +52,16 @@ export function ResizableFilterLayout({ children }: PropsWithChildren) {);}- const filterDefault = 15;- const tableDefault = 85;+ // Only reached on desktop (the mobile branch returned above), so `window`+ // exists; the guard covers SSR type narrowing.+ const filterDefault =+ typeof window === "undefined"+ ? FILTER_PANEL_MAX_DEFAULT_PCT / 2+ : Math.min(+ FILTER_PANEL_MAX_DEFAULT_PCT,+ (FILTER_PANEL_DEFAULT_PX / Math.max(window.innerWidth, 1)) * 100,+ );+ const tableDefault = 100 - filterDefault;// If sidebar doesn't exist, render only the table contentif (!filterSidebar) {diff --git a/web/src/components/ui/scroll-area.tsx b/web/src/components/ui/scroll-area.tsxindex 9a5e2ca1a6..de18bf8f0a 100644--- a/web/src/components/ui/scroll-area.tsx+++ b/web/src/components/ui/scroll-area.tsx@@ -31,7 +31,9 @@ const ScrollBar = React.forwardRef<ref={ref}orientation={orientation}className={cn(- "flex touch-none transition-colors select-none",+ // z-[1]: overlay scrollbars must paint above sticky in-content rows+ // (e.g. the filter sidebar's sticky facet headers); local stacking only.+ "z-[1] flex touch-none transition-colors select-none",orientation === "vertical" &&"h-full w-2.5 border-l border-l-transparent p-px",orientation === "horizontal" &&diff --git a/web/src/features/events/config/filter-config.ts b/web/src/features/events/config/filter-config.tsindex be16b1225c..6f956eb31a 100644--- a/web/src/features/events/config/filter-config.ts+++ b/web/src/features/events/config/filter-config.ts@@ -5,6 +5,7 @@ import {} from "@/src/features/filters/lib/filter-config";import type { ColumnToBackendKeyMap } from "@/src/features/filters/lib/filter-transform";import { renderFilterIcon } from "@/src/components/ItemBadge";+import { renderLevelIcon } from "@/src/components/level-colors";// Helper function to get column name from eventsTableCols by IDexport const getEventsColumnName = (id: string): string => {@@ -131,9 +132,12 @@ export const observationEventsFilterConfig: FilterConfig = {label: getEventsColumnName("traceTags"),},{+ // Display relabel to "Status" (see traces-config); column id stays+ // `level` until the cross-surface rename lands.type: "categorical" as const,column: "level",- label: getEventsColumnName("level"),+ label: "Status",+ renderIcon: renderLevelIcon,},{type: "categorical" as const,diff --git a/web/src/features/filters/config/observations-config.ts b/web/src/features/filters/config/observations-config.tsindex 98133589a1..27e246ccd7 100644--- a/web/src/features/filters/config/observations-config.ts+++ b/web/src/features/filters/config/observations-config.ts@@ -5,6 +5,7 @@ import {} from "@/src/features/filters/lib/filter-config";import type { ColumnToBackendKeyMap } from "@/src/features/filters/lib/filter-transform";import { renderFilterIcon } from "@/src/components/ItemBadge";+import { renderLevelIcon } from "@/src/components/level-colors";export type ObservationsOmittableFilterColumn = "model" | "promptName";@@ -53,9 +54,12 @@ export const observationFilterConfig: FilterConfig = {label: "Trace Tags",},{+ // Display relabel to "Status" (see traces-config); column id stays+ // `level` until the cross-surface rename lands.type: "categorical" as const,column: "level",- label: "Level",+ label: "Status",+ renderIcon: renderLevelIcon,},{type: "categorical" as const,diff --git a/web/src/features/filters/config/traces-config.ts b/web/src/features/filters/config/traces-config.tsindex beac5a7a0c..aaca1943e0 100644--- a/web/src/features/filters/config/traces-config.ts+++ b/web/src/features/filters/config/traces-config.ts@@ -3,6 +3,7 @@ import {omitFilterFacets,type FilterConfig,} from "@/src/features/filters/lib/filter-config";+import { renderLevelIcon } from "@/src/components/level-colors";export type TraceOmittableFilterColumn = "userId" | "sessionId";@@ -81,9 +82,13 @@ export const traceFilterConfig: FilterConfig = {label: "Comment Content",},{+ // Product direction is to call observation levels "Status" everywhere+ // (display relabel only here; the column id / grammar field stays+ // `level` until the cross-surface rename lands).type: "categorical" as const,column: "level",- label: "Level",+ label: "Status",+ renderIcon: renderLevelIcon,},{type: "numeric" as const,diff --git a/web/src/features/filters/hooks/useSidebarFilterState.tsx b/web/src/features/filters/hooks/useSidebarFilterState.tsxindex 0c33e853ff..399eb627f0 100644--- a/web/src/features/filters/hooks/useSidebarFilterState.tsx+++ b/web/src/features/filters/hooks/useSidebarFilterState.tsx@@ -33,6 +33,27 @@ import {import { useKeyedSessionStorageState } from "./useKeyedSessionStorageState";import useSessionStorage from "@/src/components/useSessionStorage";import type { FilterConfig, FilterStateMigration } from "../lib/filter-config";+import {+ addTextFilterEntry,+ applyCheckboxSelection,+ applyKeyedFilterEntries,+ applyNumericRange,+ applyStringContains,+ buildOnlySelection,+ clearCategoricalColumn,+ deriveOperatorChange,+ removeColumnFiltersOfType,+ removeTextFilterEntry,+ type BooleanKeyValueFilterEntry,+ type KeyValueFilterEntry,+ type KeyedFilterKind,+ type NumericKeyValueFilterEntry,+ type SidebarFilterActionContext,+ type StringKeyValueFilterEntry,+} from "../lib/sidebar-filter-actions";++// Re-exported so existing consumers (tests, session view) keep their path.+export { resolveCheckboxOperator } from "../lib/sidebar-filter-actions";import type { PeekTableStateContextValue } from "@/src/components/table/peek/contexts/PeekTableStateContext";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";@@ -166,6 +187,14 @@ export interface CategoricalUIFilter extends BaseUIFilter {* the exclusions; checkboxes display the kept complement)*/operator?: "any of" | "all of" | "none of";+ /**+ * Raw stored exclusions of an active "none of" filter, INCLUDING carried+ * exclusions outside the current (time-scoped, top-N-capped) option list+ * that the checked=kept checkbox display cannot show (LFE-10717).+ * Display-only — lets the facet header summary report the whole filter+ * instead of just its visible part.+ */+ excludedValues?: string[];/*** Callback to change the operator. Only provided for arrayOptions columns.* When called, updates the filter to use the specified operator.@@ -186,10 +215,6 @@ export interface CategoricalUIFilter extends BaseUIFilter {operator: "contains" | "does not contain",value: string,) => void;- // True if any text filters are active for this column- hasTextFilters?: boolean;- // True if any checkboxes are selected (excluding "all selected" state)- hasCheckboxSelections?: boolean;}export interface NumericUIFilter extends BaseUIFilter {@@ -207,35 +232,15 @@ export interface StringUIFilter extends BaseUIFilter {onChange: (value: string) => void;}-// Represents one active filter row in the key-value facet UI-// Example: key="accuracy", operator="any of", value=["good", "excellent"]-export type KeyValueFilterEntry = {- key: string;- operator: "any of" | "none of";- value: string[];-};--// Represents one active numeric filter row in the numeric key-value facet UI-// Example: key="accuracy", operator=">=", value=0.8-export type NumericKeyValueFilterEntry = {- key: string;- operator: "=" | ">" | "<" | ">=" | "<=";- value: number | "";-};--export type BooleanKeyValueFilterEntry = {- key: string;- operator: "=" | "<>";- value: boolean | "";-};--// Represents one active string filter row in the string key-value facet UI-// Example: key="environment", operator="=", value="production"-export type StringKeyValueFilterEntry = {- key: string;- operator: "=" | "contains" | "does not contain";- value: string;-};+// The keyed-facet row shapes live beside the pure state transitions in+// sidebar-filter-actions; re-exported here so existing consumers keep their+// import path.+export type {+ KeyValueFilterEntry,+ NumericKeyValueFilterEntry,+ BooleanKeyValueFilterEntry,+ StringKeyValueFilterEntry,+} from "../lib/sidebar-filter-actions";export interface KeyValueUIFilter extends BaseUIFilter {type: "keyValue";@@ -420,98 +425,6 @@ const DEFAULT_HOOK_OPTIONS: UseSidebarFilterStateOptions = {const toUrlFilterQuery = (encoded: string): string =>encoded.length > MAX_URL_FILTER_QUERY_LENGTH ? "" : encoded;-/**- * Pure function that determines the operator and values for checkbox-based- * filter interactions. Extracted for testability.- *- * Checkboxes always show the KEPT set — "no filter" renders every option- * checked (implicit all). Unchecking from that state therefore expresses an- * exclusion, and the deselected values persist as `none of [deselected]`- * (LFE-10717). Materializing the complement (`any of [remaining]`) instead is- * wrong twice over for multi-valued columns (arrayOptions): a row carrying an- * excluded value alongside a still-checked one keeps matching (a session with- * users [X, Y] matches "any of [everyone-but-X]" via Y), and the complement is- * O(option-count) — at ~1000 user IDs it blows the URL budget (HTTP 431).- *- * An EXPLICIT positive selection is never inverted (a trace with tags- * [tag-1, tag-3] matches "any of [tag-1, tag-2]" but not- * "none of [tag-3, tag-4, tag-5]"): once an "any of" filter exists, checkbox- * changes keep it positive, and "all of" is likewise preserved. While a- * "none of" filter is active, the checked set is the complement of the stored- * exclusions, so interactions re-derive the exclusions from what is unchecked- * — carrying over exclusions that fell out of the (top-N-capped, time-scoped)- * option list, which cannot have been re-checked while invisible.- *- * stringOptions (e.g., environment) behave the same way; each row has a- * single value there, so "none of [deselected]" is exactly equivalent to- * "any of [selected]".- *- * @param params - Filter context including column type, existing filter, selected and available values- * @returns Object with finalOperator and finalValues to apply- */-export function resolveCheckboxOperator(params: {- colType: string | undefined;- existingFilter: FilterState[number] | undefined;- values: string[];- availableValues: string[];-}): { finalOperator: "any of" | "none of" | "all of"; finalValues: string[] } {- const { colType, existingFilter, values, availableValues } = params;-- if (colType === "arrayOptions") {- if (- existingFilter?.operator === "all of" &&- existingFilter.type === "arrayOptions"- ) {- return { finalOperator: "all of", finalValues: values };- }- if (- existingFilter?.operator === "none of" &&- existingFilter.type === "arrayOptions"- ) {- const checked = new Set(values);- const availableSet = new Set(availableValues);- const carriedExclusions = existingFilter.value.filter(- (v) => !availableSet.has(v),- );- const deselected = availableValues.filter((v) => !checked.has(v));- return {- finalOperator: "none of",- finalValues: [...carriedExclusions, ...deselected],- };- }- if (!existingFilter) {- const checked = new Set(values);- const deselected = availableValues.filter((v) => !checked.has(v));- return { finalOperator: "none of", finalValues: deselected };- }- return { finalOperator: "any of", finalValues: values };- }-- // For single-valued columns (stringOptions), "none of" inversion is safe- if (!existingFilter) {- const deselected = availableValues.filter((v) => !values.includes(v));- return { finalOperator: "none of", finalValues: deselected };- }- if (- existingFilter.operator === "none of" &&- existingFilter.type === "stringOptions"- ) {- // Same carry-over as the arrayOptions branch above: exclusions outside- // the current option list are invisible and cannot have been re-checked.- const checked = new Set(values);- const availableSet = new Set(availableValues);- const carriedExclusions = existingFilter.value.filter(- (v) => !availableSet.has(v),- );- const deselected = availableValues.filter((v) => !checked.has(v));- return {- finalOperator: "none of",- finalValues: [...carriedExclusions, ...deselected],- };- }- return { finalOperator: "any of", finalValues: values };-}-export function useSidebarFilterState(config: FilterConfig,options: Record<@@ -745,6 +658,29 @@ export function useSidebarFilterState(const managedEnvironmentColumn =managedEnvironmentPolicyConfig.managedEnvironmentColumn;+ // Context the pure facet-action functions (lib/sidebar-filter-actions)+ // read: facet/column metadata, the option lists, and — only while the+ // managed-environment policy is active — the managed column, which gates+ // its explicit enable-all-environments override.+ const actionContext: SidebarFilterActionContext = useMemo(+ () => ({+ facets: config.facets,+ columnDefinitions: config.columnDefinitions,+ options,+ managedEnvironmentColumn:+ managedEnvironmentPolicyConfig.hiddenEnvironments.length > 0+ ? managedEnvironmentColumn+ : undefined,+ }),+ [+ config.facets,+ config.columnDefinitions,+ options,+ managedEnvironmentColumn,+ managedEnvironmentPolicyConfig.hiddenEnvironments,+ ],+ );+const effectiveEnvironmentFilterState: FilterState = useMemo(() =>buildEffectiveEnvironmentFilter({@@ -971,7 +907,7 @@ export function useSidebarFilterState(const colFilters = next.filter((f) => f.column === column);if (colFilters.length === 0) return;const identity = (f: FilterState[number]): string =>- `${"key" in f ? f.key : ""} ${f.operator} ${JSON.stringify(+ `${"key" in f ? f.key : ""}\u0000${f.operator}\u0000${JSON.stringify("value" in f ? f.value : null,)}`;const prevIdentities = new Set(@@ -1002,253 +938,58 @@ export function useSidebarFilterState(capture("filters:cleared", {surface: "sidebar",tableName: config.tableName,+ scope: "all",clearedCount,isV4: isV4Surface,});}};- // Generic apply selection logic- const applySelection = useCallback(- (- current: FilterState,- column: string,- values: string[],- operator?: "any of" | "none of" | "all of",- ): FilterState => {- const other = current.filter((f) => f.column !== column);-- const facet = config.facets.find((f) => f.column === column);- if (!facet) return current;-- const colDef = config.columnDefinitions.find(- (c) => c.id === column || c.name === column,- );- const colType = colDef?.type;-- // Handle boolean facets- if (facet.type === "boolean") {- const trueLabel = facet.trueLabel ?? "True";- const falseLabel = facet.falseLabel ?? "False";- const invert = facet.invertValue ?? false;-- if (values.length === 0 || values.length === 2) return other;- if (values.includes(trueLabel)) {- return [- ...other,- {- column,- type: "boolean" as const,- operator: "=" as const,- value: !invert,- },- ];- }- if (values.includes(falseLabel)) {- return [- ...other,- {- column,- type: "boolean" as const,- operator: "=" as const,- value: !!invert,- },- ];- }- return other;- }-- // Handle numeric facets- if (facet.type === "numeric") {- return other;- }-- // Handle categorical facets- if (!(column in options)) return current;- const availableValuesRaw = options[column];-- // For nested structures (keyValue filters), skip this logic- if (!Array.isArray(availableValuesRaw)) {- return current;- }-- const availableValues = availableValuesRaw.map((opt) =>- typeof opt === "string" ? opt : opt.value,- );-- // Determine operator and values based on context- let finalOperator: "any of" | "none of" | "all of";- let finalValues: string[];- const existingFilter = current.find((f) => f.column === column);- const isManagedEnvironmentColumn =- column === managedEnvironmentColumn &&- managedEnvironmentPolicyConfig.hiddenEnvironments.length > 0;- // For an active "none of" filter, "all checked" is not the same as- // "no filter": exclusions outside the current option list may still be- // live. Skip the all-selected removal shortcut and let- // resolveCheckboxOperator re-derive the exclusion set (an emptied set is- // removed below). For arrayOptions this also covers "none checked",- // which means exclude-everything rather than reset; stringOptions keeps- // its long-standing uncheck-everything-resets behavior. The managed- // environment column is exempt: its all-selected shortcut persists the- // explicit enable-all-environments override, and its hidden- // environments are always listed, so there is nothing to carry.- const preserveNoneOfOperator =- (colType === "arrayOptions" &&- existingFilter?.type === "arrayOptions" &&- existingFilter.operator === "none of") ||- (colType !== "arrayOptions" &&- existingFilter?.type === "stringOptions" &&- existingFilter.operator === "none of" &&- values.length > 0 &&- !isManagedEnvironmentColumn);-- if (operator !== undefined) {- // Explicit operator provided (e.g., from "Only" button or operator toggle) - use as-is- finalOperator = operator;- finalValues = values;-- // An empty "none of" excludes nothing: since deselecting from the- // all-checked default now enters NONE mode by itself, toggling NONE- // without a selection is a no-op rather than a persisted vacuous- // filter (which would light the badge while matching everything).- if (finalOperator === "none of" && finalValues.length === 0) {- return other;- }- } else {- // If all items selected or none selected, remove filter- // (only for implicit/checkbox-based selection, not when operator is explicitly set)- if (- !preserveNoneOfOperator &&- (values.length === 0 ||- (values.length === availableValues.length &&- availableValues.every((v) => values.includes(v))))- ) {- // Keep explicit override when user intentionally enables all environments.- if (isManagedEnvironmentColumn && values.length > 0) {- return [- ...other,- {- column,- type: "stringOptions" as const,- operator: "any of" as const,- value: values,- },- ];- }- return other;- }- // Checkbox interaction - smart operator selection- ({ finalOperator, finalValues } = resolveCheckboxOperator({- colType,- existingFilter,- values,- availableValues,- }));-- // Re-checking the last excluded value empties the exclusion set:- // return to the implicit-all default instead of persisting an empty- // "none of" filter.- if (finalOperator === "none of" && finalValues.length === 0) {- return other;- }- }-- const filterType: "arrayOptions" | "stringOptions" =- colType === "arrayOptions" ? "arrayOptions" : "stringOptions";-- if (filterType === "arrayOptions") {- return [- ...other,- {- column,- type: "arrayOptions" as const,- operator: finalOperator,- value: finalValues,- },- ];- }-- // stringOptions only supports "any of" | "none of", not "all of"- // finalOperator can be "all of" because UpdateFilter type signature allows it,- // but this shouldn't happen. UI only shows operator toggle for arrayOptions,- // which cannot be set to "all of". We just prevent a TS build error here.- const stringOperator: "any of" | "none of" =- finalOperator === "all of" ? "any of" : finalOperator;-- return [- ...other,- {- column,- type: "stringOptions" as const,- operator: stringOperator,- value: finalValues,- },- ];+ // One facet's clear affordance (the header ✕ / reset paths). Metadata+ // only: the column id and how many filter rows were removed.+ const emitFacetCleared = useCallback(+ (column: string, clearedCount: number) => {+ capture("filters:cleared", {+ surface: "sidebar",+ tableName: config.tableName,+ scope: "facet",+ column,+ clearedCount,+ isV4: isV4Surface,+ });},- [config, options, managedEnvironmentColumn, managedEnvironmentPolicyConfig],+ [capture, config.tableName, isV4Surface],);const updateFilter: UpdateFilter = useCallback((column, values, operator?: "any of" | "none of" | "all of") => {- // Remove text filters for this column (they're mutually exclusive with checkboxes)- const withoutTextFilters = filterState.filter(- (f) =>- !(- f.column === column &&- f.type === "string" &&- (f.operator === "contains" || f.operator === "does not contain")- ),+ const next = applyCheckboxSelection(+ actionContext,+ filterState,+ column,+ values,+ operator,);-- const next = applySelection(withoutTextFilters, column, values, operator);setFilterState(next);if (!suppressAppliedCaptureRef.current) {emitFilterApplied("sidebar", column, next);}},- [filterState, applySelection, setFilterState, emitFilterApplied],+ [actionContext, filterState, setFilterState, emitFilterApplied],);const updateFilterOnly = useCallback((column: string, value: string) => {- const facet = config.facets.find((f) => f.column === column);- if (!facet) return;-- // Handle boolean specially- if (facet.type === "boolean") {- updateFilter(column, [value]);- return;- }-- if (!(column in options)) return;- // Only apply for array-type options (not nested objects)- const optionValue = options[column];- if (!Array.isArray(optionValue)) return;- const columnType = config.columnDefinitions.find(- (columnDefinition) => columnDefinition.id === column,- )?.type;- const existingFilter = filterState.find((f) => f.column === column);- // "Only" is a positive selection: an active "none of" exclusion is- // replaced rather than preserved — `none of [value]` would mean- // everything-EXCEPT-value, the opposite of "only". "all of" is kept- // (all of one value = has that value).- const operator =- columnType === "arrayOptions" &&- existingFilter?.type === "arrayOptions" &&- (existingFilter.operator === "any of" ||- existingFilter.operator === "all of")- ? existingFilter.operator- : "any of";- updateFilter(column, [value], operator);+ const selection = buildOnlySelection(+ actionContext,+ filterState,+ column,+ value,+ );+ if (!selection) return;+ updateFilter(column, selection.values, selection.operator);},- [- config.columnDefinitions,- config.facets,- filterState,- options,- updateFilter,- ],+ [actionContext, filterState, updateFilter],);const emitOperatorToggled = useCallback(@@ -1291,59 +1032,17 @@ export function useSidebarFilterState(const updateOperator = useCallback((column: string, newOperator: "any of" | "all of" | "none of") => {- // Find the existing filter for this column- const existingFilter = filterState.find((f) => f.column === column);- const fromOperator =- existingFilter?.type === "arrayOptions" ||- existingFilter?.type === "stringOptions"- ? existingFilter.operator- : undefined;- if (!existingFilter) {- // Without selected values there is no valid persisted filter yet.- applyOperatorChange(column, [], newOperator);- emitOperatorToggled(column, fromOperator, newOperator, 0);- return;- }-- // Only works for arrayOptions and stringOptions filters- if (- existingFilter.type !== "arrayOptions" &&- existingFilter.type !== "stringOptions"- ) {- return;- }-- // Get the current selected values- // For "none of", we need to compute the actual selected values- const availableValuesRaw = options[column];- const availableValues = Array.isArray(availableValuesRaw)- ? availableValuesRaw.map((opt) =>- typeof opt === "string" ? opt : opt.value,- )- : [];-- let currentValues: string[];- if (existingFilter.operator === "none of") {- currentValues =- existingFilter.type === "arrayOptions"- ? existingFilter.value- : availableValues.filter(- (v) => !new Set(existingFilter.value).has(v),- );- } else {- currentValues = existingFilter.value;- }-- // Update the filter with the new operator- applyOperatorChange(column, currentValues, newOperator);+ const change = deriveOperatorChange(actionContext, filterState, column);+ if (!change) return;+ applyOperatorChange(column, change.values, newOperator);emitOperatorToggled(column,- fromOperator,+ change.fromOperator,newOperator,- currentValues.length,+ change.values.length,);},- [filterState, applyOperatorChange, emitOperatorToggled, options],+ [actionContext, filterState, applyOperatorChange, emitOperatorToggled],);const updateNumericFilter = useCallback(@@ -1353,62 +1052,30 @@ export function useSidebarFilterState(_defaultMin: number,_defaultMax: number,) => {- // Remove existing numeric filters for this column- const withoutNumeric = filterState.filter((f) => f.column !== column);-- // If value is null, clear the filter (reset case)- if (value === null) {- setFilterState(withoutNumeric);- return;- }-- // Always add both filters when user interacts (even at min/max bounds)- // This ensures the filter is marked as "active" and UI shows values- const filters: FilterState = [- {- column,- type: "number" as const,- operator: ">=" as const,- value: value[0],- },- {- column,- type: "number" as const,- operator: "<=" as const,- value: value[1],- },- ];-- const next: FilterState = [...withoutNumeric, ...filters];+ const next = applyNumericRange(filterState, column, value);setFilterState(next);- emitFilterApplied("sidebar", column, next);+ // null clears the column — a reset, not an apply.+ if (value !== null) {+ emitFilterApplied("sidebar", column, next);+ } else if (next.length < filterState.length) {+ emitFacetCleared(column, filterState.length - next.length);+ }},- [filterState, setFilterState, emitFilterApplied],+ [filterState, setFilterState, emitFilterApplied, emitFacetCleared],);const updateStringFilter = useCallback((column: string, value: string) => {- const withoutString = filterState.filter((f) => f.column !== column);-- if (value.trim() === "") {- // Empty value means no filter- setFilterState(withoutString);- } else {- // Add string filter with contains operator- const next: FilterState = [- ...withoutString,- {- column,- type: "string" as const,- operator: "contains" as const,- value,- },- ];- setFilterState(next);+ const next = applyStringContains(filterState, column, value);+ setFilterState(next);+ // Blank input clears the column — a reset, not an apply.+ if (value.trim() !== "") {emitFilterApplied("sidebar", column, next);+ } else if (next.length < filterState.length) {+ emitFacetCleared(column, filterState.length - next.length);}},- [filterState, setFilterState, emitFilterApplied],+ [filterState, setFilterState, emitFilterApplied, emitFacetCleared],);// Text filter management for categorical filters@@ -1419,28 +1086,8 @@ export function useSidebarFilterState(operator: "contains" | "does not contain",value: string,) => {- if (!value.trim()) {- return;- }-- // Remove all checkbox filters (stringOptions/arrayOptions) for this column- const withoutCheckboxFilters = filterState.filter(- (f) =>- !(- f.column === column &&- (f.type === "stringOptions" || f.type === "arrayOptions")- ),- );-- // Add the new text filter- const newFilter: FilterState[number] = {- column,- type: "string",- operator,- value: value.trim(),- };-- const next: FilterState = [...withoutCheckboxFilters, newFilter];+ const next = addTextFilterEntry(filterState, column, operator, value);+ if (next === null) return; // blank inputsetFilterState(next);emitFilterApplied("sidebar", column, next);},@@ -1453,19 +1100,45 @@ export function useSidebarFilterState(operator: "contains" | "does not contain",value: string,) => {- const newFilters = filterState.filter(- (f) =>- !(- f.column === column &&- f.type === "string" &&- f.operator === operator &&- f.value === value- ),- );+ const next = removeTextFilterEntry(filterState, column, operator, value);+ setFilterState(next);+ // Removing the LAST row on the column is a facet clear; removing one+ // of several is an edit and stays silent.+ if (+ next.length < filterState.length &&+ !next.some((f) => f.column === column)+ ) {+ emitFacetCleared(column, 1);+ }+ },+ [filterState, setFilterState, emitFacetCleared],+ );++ // Keyed facets (metadata, categorical/numeric/boolean/string scores) share+ // one apply/reset pair; the per-kind row semantics live in+ // applyKeyedFilterEntries. Unifying them here also closes an analytics gap:+ // boolean-score applies previously called the raw setter and emitted+ // nothing (Rule 5 of the instrumentation skill).+ const updateKeyedFilter = useCallback(+ (column: string, update: Parameters<typeof applyKeyedFilterEntries>[2]) => {+ const next = applyKeyedFilterEntries(filterState, column, update);+ setFilterState(next);+ // Analytics (LFE-10781): `prev` attributes the event to the row the+ // user just added or changed, not the column's oldest row.+ emitFilterApplied("sidebar", column, next, filterState);+ },+ [filterState, setFilterState, emitFilterApplied],+ );- setFilterState(newFilters);+ const resetKeyedFilter = useCallback(+ (column: string, kind: KeyedFilterKind) => {+ const next = removeColumnFiltersOfType(filterState, column, kind);+ setFilterState(next);+ if (next.length < filterState.length) {+ emitFacetCleared(column, filterState.length - next.length);+ }},- [filterState, setFilterState],+ [filterState, setFilterState, emitFacetCleared],);const filters: UIFilter[] = useMemo((): UIFilter[] => {@@ -1628,47 +1301,12 @@ export function useSidebarFilterState(isActive,isDisabled: disableState.isDisabled,disabledReason: disableState.reason,- onChange: (filters: KeyValueFilterEntry[]) => {- // Remove all existing categoryOptions filters for this column- const withoutCategory = filterState.filter(- (f) =>- !(f.column === facet.column && f.type === "categoryOptions"),- );-- // Only add filters that have both key and values selected- // This filters at the filterState level, not the UI level- const validFilters = filters.filter(- (entry) => entry.key && entry.value.length > 0,- );-- const newFilters: FilterState = [- ...withoutCategory,- ...validFilters.map((entry) => ({- column: facet.column,- type: "categoryOptions" as const,- operator: entry.operator,- key: entry.key,- value: entry.value,- })),- ];-- setFilterState(newFilters);- // Analytics (LFE-10781): keyed metadata/category-score facet apply.- emitFilterApplied(- "sidebar",- facet.column,- newFilters,- filterState,- );- },- onReset: () => {- // Remove all categoryOptions filters for this column- const newFilters = filterState.filter(- (f) =>- !(f.column === facet.column && f.type === "categoryOptions"),- );- setFilterState(newFilters);- },+ onChange: (filters: KeyValueFilterEntry[]) =>+ updateKeyedFilter(facet.column, {+ kind: "categoryOptions",+ entries: filters,+ }),+ onReset: () => resetKeyedFilter(facet.column, "categoryOptions"),};}@@ -1743,46 +1381,12 @@ export function useSidebarFilterState(isActive,isDisabled: disableState.isDisabled,disabledReason: disableState.reason,- onChange: (filters: NumericKeyValueFilterEntry[]) => {- // Remove all existing numberObject filters for this column- const withoutNumeric = filterState.filter(- (f) =>- !(f.column === facet.column && f.type === "numberObject"),- );-- // Only add filters that have key and valid numeric value- const validFilters = filters.filter(- (entry) => entry.key && entry.value !== "",- );-- const newFilters: FilterState = [- ...withoutNumeric,- ...validFilters.map((entry) => ({- column: facet.column,- type: "numberObject" as const,- operator: entry.operator,- key: entry.key,- value: entry.value as number,- })),- ];-- setFilterState(newFilters);- // Analytics (LFE-10781): keyed numeric-score facet apply.- emitFilterApplied(- "sidebar",- facet.column,- newFilters,- filterState,- );- },- onReset: () => {- // Remove all numberObject filters for this column- const newFilters = filterState.filter(- (f) =>- !(f.column === facet.column && f.type === "numberObject"),- );- setFilterState(newFilters);- },+ onChange: (filters: NumericKeyValueFilterEntry[]) =>+ updateKeyedFilter(facet.column, {+ kind: "numberObject",+ entries: filters,+ }),+ onReset: () => resetKeyedFilter(facet.column, "numberObject"),};}@@ -1828,36 +1432,12 @@ export function useSidebarFilterState(isActive,isDisabled: disableState.isDisabled,disabledReason: disableState.reason,- onChange: (filters: BooleanKeyValueFilterEntry[]) => {- const withoutBoolean = filterState.filter(- (f) =>- !(f.column === facet.column && f.type === "booleanObject"),- );-- const validFilters = filters.filter(- (entry) => entry.key && entry.value !== "",- );-- const newFilters: FilterState = [- ...withoutBoolean,- ...validFilters.map((entry) => ({- column: facet.column,- type: "booleanObject" as const,- operator: entry.operator,- key: entry.key,- value: entry.value as boolean,- })),- ];-- setFilterState(newFilters);- },- onReset: () => {- const newFilters = filterState.filter(- (f) =>- !(f.column === facet.column && f.type === "booleanObject"),- );- setFilterState(newFilters);- },+ onChange: (filters: BooleanKeyValueFilterEntry[]) =>+ updateKeyedFilter(facet.column, {+ kind: "booleanObject",+ entries: filters,+ }),+ onReset: () => resetKeyedFilter(facet.column, "booleanObject"),};}@@ -1908,46 +1488,12 @@ export function useSidebarFilterState(isActive,isDisabled: disableState.isDisabled,disabledReason: disableState.reason,- onChange: (filters: StringKeyValueFilterEntry[]) => {- // Remove all existing stringObject filters for this column- const withoutString = filterState.filter(- (f) =>- !(f.column === facet.column && f.type === "stringObject"),- );-- // Only add filters that have key and non-empty value- const validFilters = filters.filter(- (entry) => entry.key && entry.value.trim() !== "",- );-- const newFilters: FilterState = [- ...withoutString,- ...validFilters.map((entry) => ({- column: facet.column,- type: "stringObject" as const,- operator: entry.operator,- key: entry.key,- value: entry.value,- })),- ];-- setFilterState(newFilters);- // Analytics (LFE-10781): keyed metadata/string-score facet apply.- emitFilterApplied(- "sidebar",- facet.column,- newFilters,- filterState,- );- },- onReset: () => {- // Remove all stringObject filters for this column- const newFilters = filterState.filter(- (f) =>- !(f.column === facet.column && f.type === "stringObject"),- );- setFilterState(newFilters);- },+ onChange: (filters: StringKeyValueFilterEntry[]) =>+ updateKeyedFilter(facet.column, {+ kind: "stringObject",+ entries: filters,+ }),+ onReset: () => resetKeyedFilter(facet.column, "stringObject"),};}@@ -2195,23 +1741,21 @@ export function useSidebarFilterState(},onReset: () => {// Reset both checkboxes AND text filters- const withoutAll = filterState.filter(- (f) =>- !(- f.column === facet.column &&- (f.type === "stringOptions" ||- f.type === "arrayOptions" ||- (f.type === "string" &&- (f.operator === "contains" ||- f.operator === "does not contain")))- ),- );- setFilterState(withoutAll);+ const next = clearCategoricalColumn(filterState, facet.column);+ setFilterState(next);+ if (next.length < filterState.length) {+ emitFacetCleared(facet.column, filterState.length - next.length);+ }},// The operator is exposed for every checkbox facet so the "none of"// display logic (pinning excluded rows) works on stringOptions too;// the SOME/ALL/NONE toggle itself is gated on onOperatorChange below.operator: currentOperator,+ excludedValues:+ checkboxFilter?.operator === "none of" &&+ Array.isArray(checkboxFilter.value)+ ? (checkboxFilter.value as string[])+ : undefined,onOperatorChange: isArrayOptions? (op: "any of" | "all of" | "none of") =>updateOperator(facet.column, op)@@ -2227,9 +1771,6 @@ export function useSidebarFilterState(!isArrayOptions && !textFilterDisabled? (op, val) => removeTextFilter(facet.column, op, val): undefined,- hasTextFilters:- !isArrayOptions && !textFilterDisabled ? hasTextFilters : undefined,- hasCheckboxSelections,};}).filter((f): f is UIFilter => f !== null);@@ -2247,9 +1788,11 @@ export function useSidebarFilterState(updateStringFilter,addTextFilter,removeTextFilter,+ updateKeyedFilter,+ resetKeyedFilter,+ emitFacetCleared,expandedState,setFilterState,- emitFilterApplied,managedEnvironmentColumn,managedEnvironmentPolicyConfig.hiddenEnvironments,]);@@ -2267,5 +1810,8 @@ export function useSidebarFilterState(filters,expanded: expandedState,onExpandedChange,+ // Exposed so view-layer captures (DataTableControls) carry the same+ // v3-vs-v4 dimension as the hook's own events.+ isV4: isV4Surface,};}diff --git a/web/src/features/filters/lib/facet-display.clienttest.ts b/web/src/features/filters/lib/facet-display.clienttest.tsnew file mode 100644index 0000000000..cb4ec899b6--- /dev/null+++ b/web/src/features/filters/lib/facet-display.clienttest.ts@@ -0,0 +1,277 @@+import { getFacetSummary, rankFacetOptions } from "./facet-display";+import type {+ CategoricalUIFilter,+ NumericUIFilter,+ StringUIFilter,+ StringKeyValueUIFilter,+} from "@/src/features/filters/hooks/useSidebarFilterState";++const baseFacet = {+ column: "col",+ label: "Col",+ loading: false,+ expanded: false,+ isDisabled: false,+ onReset: () => {},+};++function categorical(+ overrides: Partial<CategoricalUIFilter>,+): CategoricalUIFilter {+ return {+ ...baseFacet,+ type: "categorical",+ isActive: false,+ value: [],+ options: [],+ counts: new Map(),+ onChange: () => {},+ ...overrides,+ };+}++describe("getFacetSummary", () => {+ it("reads 'All' for an inactive checkbox facet with options (all-checked = no filter)", () => {+ expect(+ getFacetSummary(categorical({ options: ["a", "b"], value: ["a", "b"] })),+ ).toBe("All");+ });++ it("stays quiet for an inactive facet without options", () => {+ expect(getFacetSummary(categorical({}))).toBeNull();+ });++ it("describes the kept subset of an inactive facet under an implicit default (managed environments)", () => {+ expect(+ getFacetSummary(+ categorical({+ options: ["default", "sdk-experiment", "langfuse-evaluation"],+ value: ["default"],+ }),+ ),+ ).toBe("default");+ expect(+ getFacetSummary(+ categorical({+ options: ["default", "dev", "sdk-experiment"],+ value: ["default", "dev"],+ }),+ ),+ ).toBe("2 selected");+ });++ it("names a single selected value, honoring display labels", () => {+ expect(+ getFacetSummary(+ categorical({+ isActive: true,+ options: ["prod-id", "dev-id"],+ value: ["prod-id"],+ displayByValue: new Map([["prod-id", "production"]]),+ }),+ ),+ ).toBe("production");+ });++ it("counts a multi-value selection", () => {+ expect(+ getFacetSummary(+ categorical({+ isActive: true,+ options: ["a", "b", "c"],+ value: ["a", "b"],+ }),+ ),+ ).toBe("2 selected");+ });++ it("describes none-of filters by their exclusions, not the kept complement", () => {+ expect(+ getFacetSummary(+ categorical({+ isActive: true,+ operator: "none of",+ options: ["a", "b", "c"],+ value: ["a", "b"],+ }),+ ),+ ).toBe("not c");+ expect(+ getFacetSummary(+ categorical({+ isActive: true,+ operator: "none of",+ options: ["a", "b", "c"],+ value: ["a"],+ }),+ ),+ ).toBe("not 2 values");+ });++ it("stays quiet on single-option facets instead of a meaningless 'All'", () => {+ expect(+ getFacetSummary(+ categorical({ options: ["default"], value: ["default"] }),+ ),+ ).toBeNull();+ });++ it("reports both checkbox and text parts when a column carries both", () => {+ expect(+ getFacetSummary(+ categorical({+ isActive: true,+ operator: "any of",+ options: ["a", "b", "c"],+ value: ["a"],+ textFilters: [{ operator: "does not contain", value: "x" }],+ }),+ ),+ ).toBe('a · not "x"');+ });++ it("counts carried exclusions outside the option list via excludedValues (LFE-10717)", () => {+ // Deep-linked `none of [c, legacy]` where only `c` is still observed:+ // the visible complement alone would undercount to "not c".+ expect(+ getFacetSummary(+ categorical({+ isActive: true,+ operator: "none of",+ options: ["a", "b", "c"],+ value: ["a", "b"],+ excludedValues: ["c", "legacy"],+ }),+ ),+ ).toBe("not 2 values");+ // Every exclusion out-of-list: previously the generic "filtered".+ expect(+ getFacetSummary(+ categorical({+ isActive: true,+ operator: "none of",+ options: ["a", "b"],+ value: ["a", "b"],+ excludedValues: ["legacy"],+ }),+ ),+ ).toBe("not legacy");+ });++ it("reads an explicit keep-everything filter as an active 'All' (managed env override)", () => {+ expect(+ getFacetSummary(+ categorical({+ isActive: true,+ operator: "any of",+ options: ["default", "dev"],+ value: ["default", "dev"],+ }),+ ),+ ).toBe("All");+ });++ it("says 'filtered' for a live none-of whose exclusions fell out of the option list", () => {+ expect(+ getFacetSummary(+ categorical({+ isActive: true,+ operator: "none of",+ options: ["a", "b"],+ value: ["a", "b"],+ }),+ ),+ ).toBe("filtered");+ });++ it("describes text filters", () => {+ expect(+ getFacetSummary(+ categorical({+ isActive: true,+ textFilters: [{ operator: "contains", value: "chat" }],+ }),+ ),+ ).toBe('contains "chat"');+ expect(+ getFacetSummary(+ categorical({+ isActive: true,+ textFilters: [+ { operator: "does not contain", value: "chat" },+ { operator: "contains", value: "bot" },+ ],+ }),+ ),+ ).toBe("2 text filters");+ });++ it("formats numeric ranges with their unit", () => {+ const numeric: NumericUIFilter = {+ ...baseFacet,+ type: "numeric",+ isActive: true,+ value: [0.5, 30],+ min: 0,+ max: 60,+ unit: "s",+ onChange: () => {},+ };+ expect(getFacetSummary(numeric)).toBe("0.5–30 s");+ expect(getFacetSummary({ ...numeric, isActive: false })).toBeNull();+ });++ it("quotes string filters", () => {+ const str: StringUIFilter = {+ ...baseFacet,+ type: "string",+ isActive: true,+ value: "checkout",+ onChange: () => {},+ };+ expect(getFacetSummary(str)).toBe('"checkout"');+ });++ it("names the key of a single keyed condition and counts several", () => {+ const keyed: StringKeyValueUIFilter = {+ ...baseFacet,+ type: "stringKeyValue",+ isActive: true,+ value: [{ key: "env", operator: "=", value: "prod" }],+ onChange: () => {},+ };+ expect(getFacetSummary(keyed)).toBe("env");+ expect(+ getFacetSummary({+ ...keyed,+ value: [+ { key: "env", operator: "=", value: "prod" },+ { key: "region", operator: "contains", value: "eu" },+ ],+ }),+ ).toBe("2 conditions");+ });+});++describe("rankFacetOptions", () => {+ it("ranks prefix matches before substring matches (search-bar parity)", () => {+ expect(rankFacetOptions(["my-chat", "chat-bot", "other"], "chat")).toEqual([+ "chat-bot",+ "my-chat",+ ]);+ });++ it("matches display labels and keeps the better rank", () => {+ expect(+ rankFacetOptions(+ ["id-1", "id-2"],+ "prod",+ new Map([["id-2", "production"]]),+ ),+ ).toEqual(["id-2"]);+ });++ it("returns everything unchanged for an empty query", () => {+ expect(rankFacetOptions(["b", "a"], "")).toEqual(["b", "a"]);+ });+});diff --git a/web/src/features/filters/lib/facet-display.ts b/web/src/features/filters/lib/facet-display.tsnew file mode 100644index 0000000000..eba3c7a62e--- /dev/null+++ b/web/src/features/filters/lib/facet-display.ts@@ -0,0 +1,198 @@+import type { UIFilter } from "@/src/features/filters/hooks/useSidebarFilterState";+import { filterRank } from "@/src/features/search-bar/lib/rank";++// Pure display helpers for the faceted filter sidebar+// (data-table-controls.tsx). No React, no state — unit-testable.++const displayValue = (+ value: string,+ displayByValue?: Map<string, string>,+): string => displayByValue?.get(value) ?? (value === "" ? "(empty)" : value);++/**+ * One-line header summary answering "what is selected?" for a facet.+ *+ * The root ambiguity this resolves: for checkbox facets, all-checked means+ * "no filter" (computeSelectedValues reports every option as selected), so+ * the checkbox list alone cannot tell "everything kept on purpose" apart+ * from "not filtered". The header therefore states it explicitly:+ * - inactive checkbox facets read "All"+ * - active facets read a compact description of the applied filter+ * (the single selected value, "N selected", "N excluded", a numeric+ * range, the searched text, or the condition count for keyed facets).+ *+ * Returns null when there is nothing useful to say (e.g. inactive facets of+ * types that have no all-checked ambiguity, or empty option lists).+ */+export function getFacetSummary(filter: UIFilter): string | null {+ if (filter.type === "categorical") {+ if (!filter.isActive) {+ // "All" only makes sense once there are several options to keep; while+ // options are loading, absent, or a lone value the header stays quiet.+ if (filter.options.length === 0) return null;+ // An inactive facet can still keep a strict subset: the managed+ // environment policy applies an implicit `none of [hidden]` default+ // that never counts as user-authored (isActive stays false, no Clear).+ // Saying "All" there would contradict the visibly unchecked hidden+ // environments — describe the kept set instead.+ if (+ filter.value.length > 0 &&+ filter.value.length < filter.options.length+ ) {+ return filter.value.length === 1+ ? displayValue(filter.value[0], filter.displayByValue)+ : `${filter.value.length} selected`;+ }+ return filter.options.length > 1 ? "All" : null;+ }++ // A column can carry BOTH a checkbox filter and text filters (authorable+ // via URL or the search bar even though the sidebar applies them+ // mutually exclusively) — report every part, not just one.+ const parts: string[] = [];++ if (filter.operator === "none of") {+ // Checkboxes show the KEPT complement (LFE-10717); the applied filter+ // is the unchecked rest. Prefer the hook's raw exclusion list — it+ // includes carried exclusions outside the current option list that the+ // visible-options complement misses (a deep-linked `none of [a, b, c]`+ // with only `b` still observed must not read as just "not b"). The+ // complement fallback covers manually constructed filters.+ const kept = new Set(filter.value);+ const excluded =+ filter.excludedValues ??+ filter.options.filter((option) => !kept.has(option));+ if (excluded.length === 1) {+ parts.push(`not ${displayValue(excluded[0], filter.displayByValue)}`);+ } else if (excluded.length > 1) {+ parts.push(`not ${excluded.length} values`);+ }+ } else if (+ filter.value.length === 1 &&+ // a real checkbox filter (operator set) or a strict subset — NOT the+ // all-checked default of a single-option facet under a text filter+ (filter.operator !== undefined ||+ filter.value.length < filter.options.length)+ ) {+ parts.push(displayValue(filter.value[0], filter.displayByValue));+ } else if (+ filter.value.length > 1 &&+ filter.value.length === filter.options.length &&+ filter.operator === "any of"+ ) {+ // An explicit keep-everything filter (the managed-env column persists+ // an all-selected override): an ACTIVE "All" chip reads truer than+ // "N selected".+ parts.push("All");+ } else if (+ filter.value.length > 1 &&+ (filter.value.length < filter.options.length ||+ filter.operator === "all of")+ ) {+ parts.push(`${filter.value.length} selected`);+ }++ if (filter.textFilters && filter.textFilters.length > 0) {+ if (filter.textFilters.length === 1) {+ const entry = filter.textFilters[0];+ parts.push(+ entry.operator === "contains"+ ? `contains "${entry.value}"`+ : `not "${entry.value}"`,+ );+ } else {+ parts.push(`${filter.textFilters.length} text filters`);+ }+ }++ return parts.length > 0 ? parts.join(" · ") : "filtered";+ }++ if (filter.type === "numeric") {+ if (!filter.isActive) return null;+ const unit = filter.unit ? ` ${filter.unit}` : "";+ return `${filter.value[0]}–${filter.value[1]}${unit}`;+ }++ if (filter.type === "string") {+ if (!filter.isActive) return null;+ return `"${filter.value}"`;+ }++ // Keyed facets (metadata, categorical/numeric/boolean scores): one entry →+ // name the key; several → count them.+ if (!filter.isActive) return null;+ if (filter.value.length === 1) return filter.value[0].key;+ return `${filter.value.length} conditions`;+}++/**+ * The single option value a categorical facet's summary refers to, or null+ * when the summary is not about exactly one value (counts, text filters,+ * inactive "All", …). Lets the header chip reuse the facet's per-value+ * color coding (renderIcon) — e.g. the Status chip carries the level color.+ * Mirrors getFacetSummary's single-value branches.+ */+export function getFacetSummaryValue(filter: UIFilter): string | null {+ if (filter.type !== "categorical") return null;+ if (filter.textFilters && filter.textFilters.length > 0) return null;++ if (!filter.isActive) {+ // inactive strict-subset kept set (managed environments) with one value+ if (+ filter.options.length > 0 &&+ filter.value.length === 1 &&+ filter.value.length < filter.options.length+ ) {+ return filter.value[0];+ }+ return null;+ }++ if (filter.operator === "none of") {+ const kept = new Set(filter.value);+ const excluded =+ filter.excludedValues ??+ filter.options.filter((option) => !kept.has(option));+ return excluded.length === 1 ? excluded[0] : null;+ }++ if (+ filter.value.length === 1 &&+ (filter.operator !== undefined ||+ filter.value.length < filter.options.length)+ ) {+ return filter.value[0];+ }+ return null;+}++/**+ * Rank a facet's option values for its search box the way the search bar+ * ranks completions (prefix matches before substring matches, stable within+ * a rank) instead of plain substring filtering. Matches against the raw+ * value and its display label; the better rank wins.+ */+export function rankFacetOptions(+ options: string[],+ query: string,+ displayByValue?: Map<string, string>,+): 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);+ 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);+}diff --git a/web/src/features/filters/lib/sidebar-filter-actions.clienttest.ts b/web/src/features/filters/lib/sidebar-filter-actions.clienttest.tsnew file mode 100644index 0000000000..e12b3737a5--- /dev/null+++ b/web/src/features/filters/lib/sidebar-filter-actions.clienttest.ts@@ -0,0 +1,414 @@+import type { FilterState } from "@langfuse/shared";+import {+ addTextFilterEntry,+ applyCheckboxSelection,+ applyKeyedFilterEntries,+ applyNumericRange,+ applySelection,+ applyStringContains,+ buildOnlySelection,+ clearCategoricalColumn,+ deriveOperatorChange,+ removeColumnFiltersOfType,+ removeTextFilterEntry,+ type SidebarFilterActionContext,+} from "./sidebar-filter-actions";++// The exclusion/complement gestures (LFE-10717) are covered end-to-end in+// sidebarArrayOptionsExclusion.clienttest.tsx; these tests pin the pure+// per-action transitions directly.++const ctx: SidebarFilterActionContext = {+ facets: [+ { type: "categorical", column: "env", label: "Environment" },+ { type: "categorical", column: "tags", label: "Tags" },+ {+ type: "boolean",+ column: "bookmarked",+ label: "Bookmarked",+ trueLabel: "Starred",+ falseLabel: "Not starred",+ },+ { type: "numeric", column: "latency", label: "Latency", min: 0, max: 10 },+ ],+ columnDefinitions: [+ {+ id: "env",+ name: "Environment",+ type: "stringOptions",+ options: [],+ internal: "e",+ },+ {+ id: "tags",+ name: "Tags",+ type: "arrayOptions",+ options: [],+ internal: "t",+ },+ ],+ options: {+ env: ["prod", "dev", "test"],+ tags: ["a", "b"],+ bookmarked: [],+ },+};++describe("applySelection", () => {+ it("returns current for unknown columns and non-enumerable options", () => {+ const current: FilterState = [];+ expect(applySelection(ctx, current, "nope", ["x"])).toBe(current);+ expect(+ applySelection(+ { ...ctx, options: { env: { a: ["b"] } } },+ current,+ "env",+ ["x"],+ ),+ ).toBe(current);+ });++ it("maps boolean facet labels to boolean filters, honoring invertValue", () => {+ expect(applySelection(ctx, [], "bookmarked", ["Starred"])).toEqual([+ { column: "bookmarked", type: "boolean", operator: "=", value: true },+ ]);+ expect(applySelection(ctx, [], "bookmarked", ["Not starred"])).toEqual([+ { column: "bookmarked", type: "boolean", operator: "=", value: false },+ ]);+ // both labels = no filter+ expect(+ applySelection(ctx, [], "bookmarked", ["Starred", "Not starred"]),+ ).toEqual([]);+ });++ it("removes the filter when every option is selected implicitly", () => {+ const current: FilterState = [+ {+ column: "env",+ type: "stringOptions",+ operator: "any of",+ value: ["prod"],+ },+ ];+ expect(+ applySelection(ctx, current, "env", ["prod", "dev", "test"]),+ ).toEqual([]);+ });++ it("persists an explicit keep-everything override for the managed env column", () => {+ const managedCtx = { ...ctx, managedEnvironmentColumn: "env" };+ expect(+ applySelection(managedCtx, [], "env", ["prod", "dev", "test"]),+ ).toEqual([+ {+ column: "env",+ type: "stringOptions",+ operator: "any of",+ value: ["prod", "dev", "test"],+ },+ ]);+ });++ it("treats an explicit empty none-of as a no-op reset", () => {+ const current: FilterState = [+ {+ column: "env",+ type: "stringOptions",+ operator: "any of",+ value: ["prod"],+ },+ ];+ expect(applySelection(ctx, current, "env", [], "none of")).toEqual([]);+ });+});++describe("applyCheckboxSelection", () => {+ it("drops the column's text filters before applying the selection", () => {+ const current: FilterState = [+ { column: "env", type: "string", operator: "contains", value: "pr" },+ { column: "other", type: "string", operator: "contains", value: "x" },+ ];+ const next = applyCheckboxSelection(+ ctx,+ current,+ "env",+ ["prod"],+ "any of",+ );+ expect(next).toEqual([+ { column: "other", type: "string", operator: "contains", value: "x" },+ {+ column: "env",+ type: "stringOptions",+ operator: "any of",+ value: ["prod"],+ },+ ]);+ });+});++describe("buildOnlySelection", () => {+ it("returns a plain single value for boolean facets (no operator)", () => {+ expect(buildOnlySelection(ctx, [], "bookmarked", "Starred")).toEqual({+ values: ["Starred"],+ });+ });++ it("replaces an active none-of with a positive any-of", () => {+ const current: FilterState = [+ {+ column: "tags",+ type: "arrayOptions",+ operator: "none of",+ value: ["a"],+ },+ ];+ expect(buildOnlySelection(ctx, current, "tags", "b")).toEqual({+ values: ["b"],+ operator: "any of",+ });+ });++ it("keeps an active all-of operator", () => {+ const current: FilterState = [+ {+ column: "tags",+ type: "arrayOptions",+ operator: "all of",+ value: ["a"],+ },+ ];+ expect(buildOnlySelection(ctx, current, "tags", "b")).toEqual({+ values: ["b"],+ operator: "all of",+ });+ });++ it("returns null for unknown columns", () => {+ expect(buildOnlySelection(ctx, [], "nope", "x")).toBeNull();+ });+});++describe("deriveOperatorChange", () => {+ it("derives the kept complement for a stringOptions none-of filter", () => {+ const current: FilterState = [+ {+ column: "env",+ type: "stringOptions",+ operator: "none of",+ value: ["prod"],+ },+ ];+ expect(deriveOperatorChange(ctx, current, "env")).toEqual({+ values: ["dev", "test"],+ fromOperator: "none of",+ });+ });++ it("keeps the stored exclusions for an arrayOptions none-of filter", () => {+ const current: FilterState = [+ {+ column: "tags",+ type: "arrayOptions",+ operator: "none of",+ value: ["a", "stale"],+ },+ ];+ expect(deriveOperatorChange(ctx, current, "tags")).toEqual({+ values: ["a", "stale"],+ fromOperator: "none of",+ });+ });++ it("returns empty values without a persisted filter, null for non-checkbox filters", () => {+ expect(deriveOperatorChange(ctx, [], "tags")).toEqual({+ values: [],+ fromOperator: undefined,+ });+ const numeric: FilterState = [+ { column: "tags", type: "number", operator: ">=", value: 1 },+ ];+ expect(deriveOperatorChange(ctx, numeric, "tags")).toBeNull();+ });+});++describe("numeric / string / text transitions", () => {+ it("applyNumericRange persists both bounds and clears on null", () => {+ const next = applyNumericRange([], "latency", [1, 5]);+ expect(next).toEqual([+ { column: "latency", type: "number", operator: ">=", value: 1 },+ { column: "latency", type: "number", operator: "<=", value: 5 },+ ]);+ expect(applyNumericRange(next, "latency", null)).toEqual([]);+ });++ it("applyStringContains sets a contains filter and clears on blank", () => {+ const next = applyStringContains([], "id", "abc");+ expect(next).toEqual([+ { column: "id", type: "string", operator: "contains", value: "abc" },+ ]);+ expect(applyStringContains(next, "id", " ")).toEqual([]);+ });++ it("addTextFilterEntry trims, rejects blank, and drops checkbox filters", () => {+ expect(addTextFilterEntry([], "env", "contains", " ")).toBeNull();+ const current: FilterState = [+ {+ column: "env",+ type: "stringOptions",+ operator: "any of",+ value: ["prod"],+ },+ ];+ expect(addTextFilterEntry(current, "env", "contains", " pr ")).toEqual([+ { column: "env", type: "string", operator: "contains", value: "pr" },+ ]);+ });++ it("removeTextFilterEntry removes exactly the matching entry", () => {+ const current: FilterState = [+ { column: "env", type: "string", operator: "contains", value: "a" },+ {+ column: "env",+ type: "string",+ operator: "does not contain",+ value: "a",+ },+ ];+ expect(removeTextFilterEntry(current, "env", "contains", "a")).toEqual([+ {+ column: "env",+ type: "string",+ operator: "does not contain",+ value: "a",+ },+ ]);+ });+});++describe("keyed facet transitions", () => {+ it("persists only complete rows and replaces just its own kind", () => {+ const current: FilterState = [+ {+ column: "metadata",+ type: "stringObject",+ operator: "=",+ key: "old",+ value: "gone",+ },+ {+ column: "metadata",+ type: "string",+ operator: "contains",+ value: "keep",+ },+ ];+ const next = applyKeyedFilterEntries(current, "metadata", {+ kind: "stringObject",+ entries: [+ { key: "env", operator: "=", value: "prod" },+ { key: "", operator: "=", value: "draft-no-key" },+ { key: "draft-no-value", operator: "=", value: " " },+ ],+ });+ expect(next).toEqual([+ {+ column: "metadata",+ type: "string",+ operator: "contains",+ value: "keep",+ },+ {+ column: "metadata",+ type: "stringObject",+ operator: "=",+ key: "env",+ value: "prod",+ },+ ]);+ });++ it("filters numeric and boolean drafts by their empty-value sentinel", () => {+ expect(+ applyKeyedFilterEntries([], "scores_avg", {+ kind: "numberObject",+ entries: [+ { key: "acc", operator: ">=", value: 0 },+ { key: "acc", operator: ">=", value: "" },+ ],+ }),+ ).toEqual([+ {+ column: "scores_avg",+ type: "numberObject",+ operator: ">=",+ key: "acc",+ value: 0,+ },+ ]);+ expect(+ applyKeyedFilterEntries([], "score_booleans", {+ kind: "booleanObject",+ entries: [{ key: "flag", operator: "=", value: false }],+ }),+ ).toEqual([+ {+ column: "score_booleans",+ type: "booleanObject",+ operator: "=",+ key: "flag",+ value: false,+ },+ ]);+ });++ it("removeColumnFiltersOfType scopes to column and kind", () => {+ const current: FilterState = [+ {+ column: "metadata",+ type: "stringObject",+ operator: "=",+ key: "a",+ value: "1",+ },+ {+ column: "other",+ type: "stringObject",+ operator: "=",+ key: "b",+ value: "2",+ },+ ];+ expect(+ removeColumnFiltersOfType(current, "metadata", "stringObject"),+ ).toEqual([+ {+ column: "other",+ type: "stringObject",+ operator: "=",+ key: "b",+ value: "2",+ },+ ]);+ });+});++describe("clearCategoricalColumn", () => {+ it("clears checkbox and text filters but leaves other filter types", () => {+ const current: FilterState = [+ {+ column: "env",+ type: "stringOptions",+ operator: "any of",+ value: ["prod"],+ },+ { column: "env", type: "string", operator: "contains", value: "p" },+ { column: "env", type: "number", operator: ">=", value: 1 },+ { column: "other", type: "string", operator: "contains", value: "x" },+ ];+ expect(clearCategoricalColumn(current, "env")).toEqual([+ { column: "env", type: "number", operator: ">=", value: 1 },+ { column: "other", type: "string", operator: "contains", value: "x" },+ ]);+ });+});diff --git a/web/src/features/filters/lib/sidebar-filter-actions.ts b/web/src/features/filters/lib/sidebar-filter-actions.tsnew file mode 100644index 0000000000..86d8110c07--- /dev/null+++ b/web/src/features/filters/lib/sidebar-filter-actions.ts@@ -0,0 +1,644 @@+import type {+ ColumnDefinition,+ FilterState,+ SingleValueOption,+} from "@langfuse/shared";+import type { FilterConfig } from "./filter-config";++// Pure FilterState transitions behind the sidebar's facet interactions.+// No React: every function maps (context, current state, user input) to the+// next FilterState; useSidebarFilterState wires them to setFilterState and+// analytics. Keeping them here makes each user action a directly+// unit-testable function instead of a branch inside a 2000-line hook.++export type CheckboxOperator = "any of" | "all of" | "none of";+export type TextFilterOperator = "contains" | "does not contain";++/** Options as the sidebar hook receives them (per-column value lists, or+ * nested key→values records for keyed facets). */+export type SidebarFilterOptions = Record<+ string,+ (string | SingleValueOption)[] | Record<string, string[]> | undefined+>;++export type SidebarFilterActionContext = {+ facets: FilterConfig["facets"];+ columnDefinitions: ColumnDefinition[];+ options: SidebarFilterOptions;+ /**+ * The managed environment column, set ONLY while the managed-environment+ * policy is active (hidden environments exist). Drives the explicit+ * enable-all-environments override in applySelection.+ */+ managedEnvironmentColumn?: string;+};++// Represents one active filter row in the key-value facet UI+// Example: key="accuracy", operator="any of", value=["good", "excellent"]+export type KeyValueFilterEntry = {+ key: string;+ operator: "any of" | "none of";+ value: string[];+};++// Represents one active numeric filter row in the numeric key-value facet UI+// Example: key="accuracy", operator=">=", value=0.8+export type NumericKeyValueFilterEntry = {+ key: string;+ operator: "=" | ">" | "<" | ">=" | "<=";+ value: number | "";+};++export type BooleanKeyValueFilterEntry = {+ key: string;+ operator: "=" | "<>";+ value: boolean | "";+};++// Represents one active string filter row in the string key-value facet UI+// Example: key="environment", operator="=", value="production"+export type StringKeyValueFilterEntry = {+ key: string;+ operator: "=" | "contains" | "does not contain";+ value: string;+};++const toValueList = (options: SidebarFilterOptions[string]): string[] | null =>+ Array.isArray(options)+ ? options.map((opt) => (typeof opt === "string" ? opt : opt.value))+ : null;++/**+ * Pure function that determines the operator and values for checkbox-based+ * filter interactions.+ *+ * Checkboxes always show the KEPT set — "no filter" renders every option+ * checked (implicit all). Unchecking from that state therefore expresses an+ * exclusion, and the deselected values persist as `none of [deselected]`+ * (LFE-10717). Materializing the complement (`any of [remaining]`) instead is+ * wrong twice over for multi-valued columns (arrayOptions): a row carrying an+ * excluded value alongside a still-checked one keeps matching (a session with+ * users [X, Y] matches "any of [everyone-but-X]" via Y), and the complement is+ * O(option-count) — at ~1000 user IDs it blows the URL budget (HTTP 431).+ *+ * An EXPLICIT positive selection is never inverted (a trace with tags+ * [tag-1, tag-3] matches "any of [tag-1, tag-2]" but not+ * "none of [tag-3, tag-4, tag-5]"): once an "any of" filter exists, checkbox+ * changes keep it positive, and "all of" is likewise preserved. While a+ * "none of" filter is active, the checked set is the complement of the stored+ * exclusions, so interactions re-derive the exclusions from what is unchecked+ * — carrying over exclusions that fell out of the (top-N-capped, time-scoped)+ * option list, which cannot have been re-checked while invisible.+ *+ * stringOptions (e.g., environment) behave the same way; each row has a+ * single value there, so "none of [deselected]" is exactly equivalent to+ * "any of [selected]".+ *+ * @param params - Filter context including column type, existing filter, selected and available values+ * @returns Object with finalOperator and finalValues to apply+ */+export function resolveCheckboxOperator(params: {+ colType: string | undefined;+ existingFilter: FilterState[number] | undefined;+ values: string[];+ availableValues: string[];+}): { finalOperator: CheckboxOperator; finalValues: string[] } {+ const { colType, existingFilter, values, availableValues } = params;++ if (colType === "arrayOptions") {+ if (+ existingFilter?.operator === "all of" &&+ existingFilter.type === "arrayOptions"+ ) {+ return { finalOperator: "all of", finalValues: values };+ }+ if (+ existingFilter?.operator === "none of" &&+ existingFilter.type === "arrayOptions"+ ) {+ const checked = new Set(values);+ const availableSet = new Set(availableValues);+ const carriedExclusions = existingFilter.value.filter(+ (v) => !availableSet.has(v),+ );+ const deselected = availableValues.filter((v) => !checked.has(v));+ return {+ finalOperator: "none of",+ finalValues: [...carriedExclusions, ...deselected],+ };+ }+ if (!existingFilter) {+ const checked = new Set(values);+ const deselected = availableValues.filter((v) => !checked.has(v));+ return { finalOperator: "none of", finalValues: deselected };+ }+ return { finalOperator: "any of", finalValues: values };+ }++ // For single-valued columns (stringOptions), "none of" inversion is safe+ if (!existingFilter) {+ const deselected = availableValues.filter((v) => !values.includes(v));+ return { finalOperator: "none of", finalValues: deselected };+ }+ if (+ existingFilter.operator === "none of" &&+ existingFilter.type === "stringOptions"+ ) {+ // Same carry-over as the arrayOptions branch above: exclusions outside+ // the current option list are invisible and cannot have been re-checked.+ const checked = new Set(values);+ const availableSet = new Set(availableValues);+ const carriedExclusions = existingFilter.value.filter(+ (v) => !availableSet.has(v),+ );+ const deselected = availableValues.filter((v) => !checked.has(v));+ return {+ finalOperator: "none of",+ finalValues: [...carriedExclusions, ...deselected],+ };+ }+ return { finalOperator: "any of", finalValues: values };+}++/**+ * Applies a checkbox/boolean facet selection to the state. Returns `current`+ * unchanged when the column is unknown or its options are not enumerable.+ */+export function applySelection(+ ctx: SidebarFilterActionContext,+ current: FilterState,+ column: string,+ values: string[],+ operator?: CheckboxOperator,+): FilterState {+ const other = current.filter((f) => f.column !== column);++ const facet = ctx.facets.find((f) => f.column === column);+ if (!facet) return current;++ const colDef = ctx.columnDefinitions.find(+ (c) => c.id === column || c.name === column,+ );+ const colType = colDef?.type;++ // Handle boolean facets+ if (facet.type === "boolean") {+ const trueLabel = facet.trueLabel ?? "True";+ const falseLabel = facet.falseLabel ?? "False";+ const invert = facet.invertValue ?? false;++ if (values.length === 0 || values.length === 2) return other;+ if (values.includes(trueLabel)) {+ return [+ ...other,+ {+ column,+ type: "boolean" as const,+ operator: "=" as const,+ value: !invert,+ },+ ];+ }+ if (values.includes(falseLabel)) {+ return [+ ...other,+ {+ column,+ type: "boolean" as const,+ operator: "=" as const,+ value: !!invert,+ },+ ];+ }+ return other;+ }++ // Handle numeric facets+ if (facet.type === "numeric") {+ return other;+ }++ // Handle categorical facets+ if (!(column in ctx.options)) return current;+ const availableValues = toValueList(ctx.options[column]);++ // For nested structures (keyValue filters), skip this logic+ if (availableValues === null) {+ return current;+ }++ // Determine operator and values based on context+ let finalOperator: CheckboxOperator;+ let finalValues: string[];+ const existingFilter = current.find((f) => f.column === column);+ const isManagedEnvironmentColumn = column === ctx.managedEnvironmentColumn;+ // For an active "none of" filter, "all checked" is not the same as+ // "no filter": exclusions outside the current option list may still be+ // live. Skip the all-selected removal shortcut and let+ // resolveCheckboxOperator re-derive the exclusion set (an emptied set is+ // removed below). For arrayOptions this also covers "none checked",+ // which means exclude-everything rather than reset; stringOptions keeps+ // its long-standing uncheck-everything-resets behavior. The managed+ // environment column is exempt: its all-selected shortcut persists the+ // explicit enable-all-environments override, and its hidden+ // environments are always listed, so there is nothing to carry.+ const preserveNoneOfOperator =+ (colType === "arrayOptions" &&+ existingFilter?.type === "arrayOptions" &&+ existingFilter.operator === "none of") ||+ (colType !== "arrayOptions" &&+ existingFilter?.type === "stringOptions" &&+ existingFilter.operator === "none of" &&+ values.length > 0 &&+ !isManagedEnvironmentColumn);++ if (operator !== undefined) {+ // Explicit operator provided (e.g., from "Only" button or operator toggle) - use as-is+ finalOperator = operator;+ finalValues = values;++ // An empty "none of" excludes nothing: since deselecting from the+ // all-checked default now enters NONE mode by itself, toggling NONE+ // without a selection is a no-op rather than a persisted vacuous+ // filter (which would light the badge while matching everything).+ if (finalOperator === "none of" && finalValues.length === 0) {+ return other;+ }+ } else {+ // If all items selected or none selected, remove filter+ // (only for implicit/checkbox-based selection, not when operator is explicitly set)+ if (+ !preserveNoneOfOperator &&+ (values.length === 0 ||+ (values.length === availableValues.length &&+ availableValues.every((v) => values.includes(v))))+ ) {+ // Keep explicit override when user intentionally enables all environments.+ if (isManagedEnvironmentColumn && values.length > 0) {+ return [+ ...other,+ {+ column,+ type: "stringOptions" as const,+ operator: "any of" as const,+ value: values,+ },+ ];+ }+ return other;+ }+ // Checkbox interaction - smart operator selection+ ({ finalOperator, finalValues } = resolveCheckboxOperator({+ colType,+ existingFilter,+ values,+ availableValues,+ }));++ // Re-checking the last excluded value empties the exclusion set:+ // return to the implicit-all default instead of persisting an empty+ // "none of" filter.+ if (finalOperator === "none of" && finalValues.length === 0) {+ return other;+ }+ }++ const filterType: "arrayOptions" | "stringOptions" =+ colType === "arrayOptions" ? "arrayOptions" : "stringOptions";++ if (filterType === "arrayOptions") {+ return [+ ...other,+ {+ column,+ type: "arrayOptions" as const,+ operator: finalOperator,+ value: finalValues,+ },+ ];+ }++ // stringOptions only supports "any of" | "none of", not "all of".+ // finalOperator can be "all of" because the caller's signature allows it,+ // but this shouldn't happen: the UI only shows the operator toggle for+ // arrayOptions. We just prevent a TS build error here.+ const stringOperator: "any of" | "none of" =+ finalOperator === "all of" ? "any of" : finalOperator;++ return [+ ...other,+ {+ column,+ type: "stringOptions" as const,+ operator: stringOperator,+ value: finalValues,+ },+ ];+}++/**+ * A checkbox interaction: text filters on the column are dropped first+ * (mutually exclusive with checkbox selections), then the selection applies.+ */+export function applyCheckboxSelection(+ ctx: SidebarFilterActionContext,+ current: FilterState,+ column: string,+ values: string[],+ operator?: CheckboxOperator,+): FilterState {+ const withoutTextFilters = current.filter(+ (f) =>+ !(+ f.column === column &&+ f.type === "string" &&+ (f.operator === "contains" || f.operator === "does not contain")+ ),+ );+ return applySelection(ctx, withoutTextFilters, column, values, operator);+}++/**+ * Derives the selection an "Only <value>" click should apply, or null when+ * the column cannot take one (unknown facet, non-enumerable options).+ *+ * "Only" is a positive selection: an active "none of" exclusion is replaced+ * rather than preserved — `none of [value]` would mean everything-EXCEPT-+ * value, the opposite of "only". "all of" is kept (all of one value = has+ * that value).+ */+export function buildOnlySelection(+ ctx: SidebarFilterActionContext,+ current: FilterState,+ column: string,+ value: string,+): { values: string[]; operator?: CheckboxOperator } | null {+ const facet = ctx.facets.find((f) => f.column === column);+ if (!facet) return null;++ // Boolean facets take the plain single-value path (no operator).+ if (facet.type === "boolean") {+ return { values: [value] };+ }++ if (!(column in ctx.options)) return null;+ // Only applies for array-type options (not nested objects)+ if (toValueList(ctx.options[column]) === null) return null;++ const columnType = ctx.columnDefinitions.find(+ (columnDefinition) => columnDefinition.id === column,+ )?.type;+ const existingFilter = current.find((f) => f.column === column);+ const operator: CheckboxOperator =+ columnType === "arrayOptions" &&+ existingFilter?.type === "arrayOptions" &&+ (existingFilter.operator === "any of" ||+ existingFilter.operator === "all of")+ ? existingFilter.operator+ : "any of";+ return { values: [value], operator };+}++/**+ * Derives the values an operator toggle (Any of / All of / None of) should+ * re-apply under the new operator, plus the previous operator for analytics.+ * Returns null when the column's existing filter cannot take an operator+ * change (non-checkbox filter types).+ */+export function deriveOperatorChange(+ ctx: SidebarFilterActionContext,+ current: FilterState,+ column: string,+): { values: string[]; fromOperator?: string } | null {+ const existingFilter = current.find((f) => f.column === column);+ if (!existingFilter) {+ // Without selected values there is no valid persisted filter yet.+ return { values: [], fromOperator: undefined };+ }++ // Only works for arrayOptions and stringOptions filters+ if (+ existingFilter.type !== "arrayOptions" &&+ existingFilter.type !== "stringOptions"+ ) {+ return null;+ }++ // For "none of", the SELECTED values are the complement of the stored+ // exclusions (arrayOptions stores the exclusions directly).+ const availableValues = toValueList(ctx.options[column]) ?? [];+ const currentValues =+ existingFilter.operator === "none of"+ ? existingFilter.type === "arrayOptions"+ ? existingFilter.value+ : availableValues.filter((v) => !new Set(existingFilter.value).has(v))+ : existingFilter.value;++ return { values: currentValues, fromOperator: existingFilter.operator };+}++/**+ * Applies a numeric range facet. `null` clears the column; a range always+ * persists both bounds (even at min/max) so the facet reads as active.+ */+export function applyNumericRange(+ current: FilterState,+ column: string,+ value: [number, number] | null,+): FilterState {+ const withoutNumeric = current.filter((f) => f.column !== column);+ if (value === null) return withoutNumeric;++ return [+ ...withoutNumeric,+ {+ column,+ type: "number" as const,+ operator: ">=" as const,+ value: value[0],+ },+ {+ column,+ type: "number" as const,+ operator: "<=" as const,+ value: value[1],+ },+ ];+}++/** Applies a plain string facet as a `contains` filter; blank clears it. */+export function applyStringContains(+ current: FilterState,+ column: string,+ value: string,+): FilterState {+ const withoutString = current.filter((f) => f.column !== column);+ if (value.trim() === "") return withoutString;+ return [+ ...withoutString,+ {+ column,+ type: "string" as const,+ operator: "contains" as const,+ value,+ },+ ];+}++/**+ * Adds a contains/does-not-contain text filter, dropping the column's+ * checkbox filters (mutually exclusive). Returns null for blank input+ * (caller no-ops).+ */+export function addTextFilterEntry(+ current: FilterState,+ column: string,+ operator: TextFilterOperator,+ value: string,+): FilterState | null {+ if (!value.trim()) return null;++ const withoutCheckboxFilters = current.filter(+ (f) =>+ !(+ f.column === column &&+ (f.type === "stringOptions" || f.type === "arrayOptions")+ ),+ );++ return [+ ...withoutCheckboxFilters,+ {+ column,+ type: "string",+ operator,+ value: value.trim(),+ },+ ];+}++/** Removes one text filter identified by operator + value. */+export function removeTextFilterEntry(+ current: FilterState,+ column: string,+ operator: TextFilterOperator,+ value: string,+): FilterState {+ return current.filter(+ (f) =>+ !(+ f.column === column &&+ f.type === "string" &&+ f.operator === operator &&+ f.value === value+ ),+ );+}++export type KeyedFilterKind =+ | "categoryOptions"+ | "numberObject"+ | "booleanObject"+ | "stringObject";++/** Removes every filter of the given type on the column (keyed facet reset). */+export function removeColumnFiltersOfType(+ current: FilterState,+ column: string,+ type: KeyedFilterKind,+): FilterState {+ return current.filter((f) => !(f.column === column && f.type === type));+}++/**+ * Replaces a keyed facet's rows (metadata, categorical/numeric/boolean+ * scores): drops the column's existing filters of that kind and appends the+ * COMPLETE rows — entries still missing a key or value are UI drafts and are+ * filtered out here, not persisted.+ */+export function applyKeyedFilterEntries(+ current: FilterState,+ column: string,+ update:+ | { kind: "categoryOptions"; entries: KeyValueFilterEntry[] }+ | { kind: "numberObject"; entries: NumericKeyValueFilterEntry[] }+ | { kind: "booleanObject"; entries: BooleanKeyValueFilterEntry[] }+ | { kind: "stringObject"; entries: StringKeyValueFilterEntry[] },+): FilterState {+ const without = removeColumnFiltersOfType(current, column, update.kind);++ switch (update.kind) {+ case "categoryOptions":+ return [+ ...without,+ ...update.entries+ .filter((entry) => entry.key && entry.value.length > 0)+ .map((entry) => ({+ column,+ type: "categoryOptions" as const,+ operator: entry.operator,+ key: entry.key,+ value: entry.value,+ })),+ ];+ case "numberObject":+ return [+ ...without,+ ...update.entries+ .filter((entry) => entry.key && entry.value !== "")+ .map((entry) => ({+ column,+ type: "numberObject" as const,+ operator: entry.operator,+ key: entry.key,+ value: entry.value as number,+ })),+ ];+ case "booleanObject":+ return [+ ...without,+ ...update.entries+ .filter((entry) => entry.key && entry.value !== "")+ .map((entry) => ({+ column,+ type: "booleanObject" as const,+ operator: entry.operator,+ key: entry.key,+ value: entry.value as boolean,+ })),+ ];+ case "stringObject":+ return [+ ...without,+ ...update.entries+ .filter((entry) => entry.key && entry.value.trim() !== "")+ .map((entry) => ({+ column,+ type: "stringObject" as const,+ operator: entry.operator,+ key: entry.key,+ value: entry.value,+ })),+ ];+ }+}++/**+ * Categorical facet reset: clears the column's checkbox filters AND its+ * text (contains / does not contain) filters in one step.+ */+export function clearCategoricalColumn(+ current: FilterState,+ column: string,+): FilterState {+ return current.filter(+ (f) =>+ !(+ f.column === column &&+ (f.type === "stringOptions" ||+ f.type === "arrayOptions" ||+ (f.type === "string" &&+ (f.operator === "contains" || f.operator === "does not contain")))+ ),+ );+}diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.tsindex 407435ff12..654cca354f 100644--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts@@ -297,6 +297,10 @@ export const events = {"applied","cleared","facet_operator_toggled",+ "active_only_toggled",+ "facet_added",+ "facet_mode_switched",+ "sidebar_toggled","search_submitted","search_error","ai_generate_requested",diff --git a/web/src/features/search-bar/lib/completions.ts b/web/src/features/search-bar/lib/completions.tsindex 35e5a9dbaa..8d240ca0df 100644--- a/web/src/features/search-bar/lib/completions.ts+++ b/web/src/features/search-bar/lib/completions.ts@@ -28,6 +28,7 @@ import {type FieldRef,} from "./fields";import { quoteIfNeeded } from "./quoting";+import { rankFilter } from "./rank";import type { ObservedOptions } from "./observed-options";export type CompletionStage =@@ -170,26 +171,8 @@ const PATTERN_OPTIONS: CompletionOption[] = [},];-/** 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);-}+// Ranking (prefix-before-substring) lives in ./rank so the filter sidebar's+// per-facet value search can share it — see that module's header.function fieldOptions(includeVirtual = true): CompletionOption[] {const opts: CompletionOption[] = FIELDS.map((f: FieldDef) => ({diff --git a/web/src/features/search-bar/lib/rank.ts b/web/src/features/search-bar/lib/rank.tsnew file mode 100644index 0000000000..bd7b612e05--- /dev/null+++ b/web/src/features/search-bar/lib/rank.ts@@ -0,0 +1,27 @@+// Shared completion/option ranking — pure, dependency-free.+//+// Owned by the search bar (its dropdown ranking is the reference behavior);+// the filter sidebar's per-facet value search imports it so both surfaces+// rank identically (prefix matches before substring matches) instead of the+// sidebar forking its own plain-substring filter.++/** Case-insensitive match; prefix matches rank before substring matches. */+export 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;+}++export 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);+}