🪢 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
fix(tracing): Update sidebar selection behavior (#19268)
Ben Bachem4a7a7e47e7cd
diff --git a/packages/shared/src/features/filters/filterQueryEncoding.ts b/packages/shared/src/features/filters/filterQueryEncoding.tsindex dc424ff553..0e4b01e40e 100644--- a/packages/shared/src/features/filters/filterQueryEncoding.ts+++ b/packages/shared/src/features/filters/filterQueryEncoding.ts@@ -1,4 +1,3 @@-/* eslint-disable no-nested-ternary */import { type FilterState } from "../../types";import {coerceLegacyEmptyMetadataFilters,@@ -190,13 +189,14 @@ export function decodeFiltersGeneric(query: string): FilterState {type === "categoryOptions") {// Split on unescaped pipe characters only, then unescape each value- parsedValue = decodedValue- ? splitOnUnescapedPipe(decodedValue).map(unescapePipeInValue)- : type === "arrayOptions"- ? [] // Empty array for arrayOptions — empty strings are not valid array values (e.g., tags)- : decodedValue === ""- ? [""] // allow empty strings for stringOptions (i.e, filter for empty trace name)- : [decodedValue];+ if (decodedValue) {+ parsedValue =+ splitOnUnescapedPipe(decodedValue).map(unescapePipeInValue);+ } else if (type === "arrayOptions") {+ parsedValue = [];+ } else {+ parsedValue = [""];+ }} else if (type === "boolean" || type === "booleanObject") {parsedValue = decodedValue === "true";} else {diff --git a/packages/shared/src/interfaces/filters.test.ts b/packages/shared/src/interfaces/filters.test.tsindex 5d68b235ef..4c0d93fd68 100644--- a/packages/shared/src/interfaces/filters.test.ts+++ b/packages/shared/src/interfaces/filters.test.ts@@ -16,6 +16,21 @@ const metadataFilter = (operator: string, value: string) => ({value,});+describe("empty categorical selections", () => {+ it.each(["stringOptions", "arrayOptions"])(+ "rejects any of [] for %s in single-filter and list schemas",+ (type) => {+ const filter = { type, column: "name", operator: "any of", value: [] };+ expect(singleFilter.safeParse(filter).success).toBe(false);+ expect(eventsTableSingleFilter.safeParse(filter).success).toBe(false);+ expect(singleFilterList.safeParse([filter]).success).toBe(false);+ expect(eventsTableSingleFilterList.safeParse([filter]).success).toBe(+ false,+ );+ },+ );+});+describe("stringObject empty substring handling", () => {it.each(["contains", "starts with", "ends with"])("no longer rejects an empty value for the substring operator %s at the single-filter schema",diff --git a/web/src/features/events/lib/appRootDefault.clienttest.ts b/web/src/features/events/lib/appRootDefault.clienttest.tsindex 3914d8e2f0..d9d54a648d 100644--- a/web/src/features/events/lib/appRootDefault.clienttest.ts+++ b/web/src/features/events/lib/appRootDefault.clienttest.ts@@ -9,6 +9,7 @@ import {getAppRootSavedViewComparisonFilters,getAppRootSuppressionToPersist,removeAppRootDefaultFilter,+ shouldRunAppRootFallbackQuery,storedViewOwnsEventsTableState,urlOwnsEventsTableState,} from "./appRootDefaultFilterPolicy";@@ -131,6 +132,82 @@ describe("app-root default policy", () => {).toEqual([levelFilter, APP_ROOT_OBSERVATION_FILTER]);});+ describe.each([+ {+ name: "neither boolean selected",+ rootFilters: [+ APP_ROOT_OBSERVATION_FILTER,+ { ...APP_ROOT_OBSERVATION_FILTER, value: false },+ ],+ },+ {+ name: "neither boolean selected in reverse order",+ rootFilters: [+ { ...APP_ROOT_OBSERVATION_FILTER, value: false },+ APP_ROOT_OBSERVATION_FILTER,+ ],+ },+ {+ name: "duplicate true filters",+ rootFilters: [APP_ROOT_OBSERVATION_FILTER, APP_ROOT_OBSERVATION_FILTER],+ },+ {+ name: "mixed operators",+ rootFilters: [+ APP_ROOT_OBSERVATION_FILTER,+ { ...APP_ROOT_OBSERVATION_FILTER, operator: "<>" },+ ],+ },+ {+ name: "false only",+ rootFilters: [{ ...APP_ROOT_OBSERVATION_FILTER, value: false }],+ },+ ] satisfies { name: string; rootFilters: FilterState }[])(+ "explicit root selection: $name",+ ({ rootFilters }) => {+ it("suppresses automatic defaults when replacing the default", () => {+ expect(+ getAppRootSuppressionToPersist({+ origin: "user",+ wasAutoManaged: true,+ previousFilters: [levelFilter, APP_ROOT_OBSERVATION_FILTER],+ nextFilters: [levelFilter, ...rootFilters],+ }),+ ).toBe("suppressed");+ });++ it("preserves the selection during default removal and saved-view comparison", () => {+ const filters = [levelFilter, ...rootFilters];+ expect(removeAppRootDefaultFilter(filters)).toEqual(filters);+ expect(getAppRootSavedViewComparisonFilters(filters, true)).toEqual(+ filters,+ );+ });++ it("does not probe or apply the automatic root fallback", () => {+ const filters = [levelFilter, ...rootFilters];+ expect(+ shouldRunAppRootFallbackQuery({+ enabled: true,+ filters,+ page: 1,+ rootQuerySucceeded: true,+ rootQueryIsPlaceholder: false,+ rootRowCount: 0,+ }),+ ).toBe(false);+ expect(+ getAppRootFallbackDecision({+ additionalRowsFound: true,+ isAutoManaged: true,+ filters,+ now,+ }),+ ).toMatchObject({ shouldRemoveFilter: false, nextFilters: filters });+ });+ },+ );+it("removes only the root filter and invalidates only a neutral recent probe", () => {const now = new Date("2026-07-13T12:00:00Z").getTime();expect(diff --git a/web/src/features/events/lib/appRootDefaultFilterPolicy.ts b/web/src/features/events/lib/appRootDefaultFilterPolicy.tsindex 9248283557..7938dadac9 100644--- a/web/src/features/events/lib/appRootDefaultFilterPolicy.ts+++ b/web/src/features/events/lib/appRootDefaultFilterPolicy.ts@@ -57,23 +57,25 @@ export const getAppRootDefaultPolicy = (params: {};};-const hasEnabledAppRootFilter = (filters: FilterState) =>- filters.some(- (filter) =>- filter.column === APP_ROOT_OBSERVATION_FILTER.column &&- filter.type === "boolean" &&- filter.operator === "=" &&- filter.value === true,+const hasEnabledAppRootFilter = (filters: FilterState) => {+ const rootFilters = filters.filter(+ (filter) => filter.column === APP_ROOT_OBSERVATION_FILTER.column,);+ if (rootFilters.length !== 1) return false;+ const [filter] = rootFilters;+ return (+ filter.type === "boolean" &&+ filter.operator === "=" &&+ filter.value === true+ );+};-export const removeAppRootDefaultFilter = (filters: FilterState) =>- filters.filter(- (filter) =>- filter.column !== APP_ROOT_OBSERVATION_FILTER.column ||- filter.type !== "boolean" ||- filter.operator !== "=" ||- filter.value !== true,+export const removeAppRootDefaultFilter = (filters: FilterState) => {+ if (!hasEnabledAppRootFilter(filters)) return filters;+ return filters.filter(+ (filter) => filter.column !== APP_ROOT_OBSERVATION_FILTER.column,);+};export const getAppRootSavedViewComparisonFilters = (filters: FilterState,diff --git a/web/src/features/events/systemPresetSearchBarRoundTrip.clienttest.ts b/web/src/features/events/systemPresetSearchBarRoundTrip.clienttest.tsindex 08f0825e54..4561fe800a 100644--- a/web/src/features/events/systemPresetSearchBarRoundTrip.clienttest.ts+++ b/web/src/features/events/systemPresetSearchBarRoundTrip.clienttest.ts@@ -18,7 +18,7 @@ import { filterStateToQueryText, planCommit } from "@/src/features/search-bar";// self-demote on a mere focus + blur with no edit.//// This holds for the whole catalog today but is catalog-fragile: e.g. an-// `id`/`name` stringOptions any-of-[single-value] re-commits as `string =`,+// `id` stringOptions any-of-[single-value] re-commits as `string =`,// and a `score_booleans` filter re-commits as `categoryOptions`. If a new// preset fails here, give it a grammar-stable filter shape (or extend the// grammar) — do not weaken the demote guard.diff --git a/web/src/features/filters/hooks/useFilterState.clienttest.ts b/web/src/features/filters/hooks/useFilterState.clienttest.tsnew file mode 100644index 0000000000..541b25a67e--- /dev/null+++ b/web/src/features/filters/hooks/useFilterState.clienttest.ts@@ -0,0 +1,52 @@+import { renderHook } from "@testing-library/react";+import {+ decodeFiltersGeneric,+ encodeFiltersGeneric,+ type FilterState,+} from "@langfuse/shared";+import { applyCheckboxSelection } from "../lib/sidebar-filter-actions";+import { useQueryFilterState } from "./useFilterState";++const url = vi.hoisted(() => ({ filter: "" }));+vi.mock("use-query-params", async () => ({+ ...(await vi.importActual("use-query-params")),+ useQueryParam: (+ _name: string,+ codec: { decode: (value: string) => FilterState | undefined },+ ) => [codec.decode(url.filter), vi.fn()],+}));++describe("legacy prompt filter decoding", () => {+ it.each([+ ["type", "Type", "stringOptions", "chat"],+ ["type", "Type", "stringOptions", ""],+ ["labels", "Labels", "arrayOptions", "production"],+ ["tags", "Tags", "arrayOptions", ""],+ ] as const)(+ "preserves a sidebar empty selection for %s (%s, %s, %s)",+ (column, name, type, value) => {+ const filters = applyCheckboxSelection(+ {+ facets: [{ column, label: name, type: "categorical" }],+ columnDefinitions: [+ { id: column, name, type, options: [], internal: column },+ ],+ options: { [column]: [value] },+ },+ [{ column, type, operator: "any of", value: [value] }],+ column,+ [],+ );+ url.filter = encodeFiltersGeneric(filters);+ const { result } = renderHook(() =>+ useQueryFilterState([], "prompts", "project"),+ );+ expect(result.current[0]).toEqual(+ decodeFiltersGeneric(url.filter).map((filter) => ({+ ...filter,+ column: name,+ })),+ );+ },+ );+});diff --git a/web/src/features/filters/hooks/useFilterState.ts b/web/src/features/filters/hooks/useFilterState.tsindex 2182ce950e..ad5724b1da 100644--- a/web/src/features/filters/hooks/useFilterState.ts+++ b/web/src/features/filters/hooks/useFilterState.ts@@ -83,7 +83,8 @@ const getCommaArrayParam = (table: TableName) => ({if (DEBUG_QUERY_STATE)console.log("values", [column, type, key, operator, value]);- const decodedValue = value ? decodeURIComponent(value) : undefined;+ const decodedValue =+ value !== undefined ? decodeURIComponent(value) : undefined;const normalizedKey =type === "positionInTrace"? normalizeLegacySessionPositionInTraceKey(key)@@ -104,6 +105,9 @@ const getCommaArrayParam = (table: TableName) => ({}return Number(decodedValue);}+ if (type === "arrayOptions" && decodedValue === "") {+ return [];+ }if (type === "stringOptions" ||type === "arrayOptions" ||diff --git a/web/src/features/filters/hooks/useSidebarFilterState.tsx b/web/src/features/filters/hooks/useSidebarFilterState.tsxindex aca3139b4b..a4e55bf093 100644--- a/web/src/features/filters/hooks/useSidebarFilterState.tsx+++ b/web/src/features/filters/hooks/useSidebarFilterState.tsx@@ -49,6 +49,7 @@ import {clearCategoricalColumn,deriveOperatorChange,hasMultipleFilterTargets,+ hasEmptyCheckboxSelection,removeColumnFiltersOfType,removeTextFilterEntry,type BooleanKeyValueFilterEntry,@@ -1761,19 +1762,19 @@ export function useSidebarFilterPresentation(const falseLabel = facet.falseLabel ?? "False";const invert = facet.invertValue ?? false;const availableOptions = [trueLabel, falseLabel];- const filterEntry = filterByColumn.get(facet.column);-- let selectedOptions = availableOptions;- if (filterEntry) {- const boolValue = filterEntry.value as boolean;- if (invert) {- // Inverted: filter value=true means falseLabel selected, value=false means trueLabel selected- selectedOptions = boolValue === true ? [falseLabel] : [trueLabel];- } else {- selectedOptions = boolValue === true ? [trueLabel] : [falseLabel];- }- }- const isActive = selectedOptions.length === 1;+ const booleanFilters = filterState.filter(+ (filter) =>+ filter.column === facet.column && filter.type === "boolean",+ );+ const selectedOptions = availableOptions.filter((label) => {+ const value = label === trueLabel ? !invert : invert;+ return booleanFilters.every((filter) =>+ filter.operator === "="+ ? filter.value === value+ : filter.value !== value,+ );+ });+ const isActive = booleanFilters.length > 0;const disableState = getFacetDisabledState(facet);// Build counts from options@@ -1813,31 +1814,29 @@ export function useSidebarFilterPresentation(isActive,isDisabled: disableState.isDisabled,disabledReason: disableState.reason,- onChange: (values: string[]) => {- if (values.length === 0 || values.length === 2) {- updateFilter(facet.column, []);- return;- }- if (values.includes(trueLabel) && !values.includes(falseLabel)) {- updateFilter(facet.column, [trueLabel]);- } else if (- values.includes(falseLabel) &&- !values.includes(trueLabel)- ) {- updateFilter(facet.column, [falseLabel]);- }- },+ onChange: (values: string[]) => updateFilter(facet.column, values),onOnlyChange: (value: string) => {if (selectedOptions.length === 1 &&selectedOptions.includes(value)) {- updateFilter(facet.column, []);+ updateFilter(facet.column, availableOptions);} else {updateFilter(facet.column, [value]);}},- onReset: () => updateFilter(facet.column, []),+ onReset: () => {+ const next = filterState.filter(+ (filter) => filter.column !== facet.column,+ );+ setFilterState(next);+ if (next.length < filterState.length) {+ emitFacetCleared(+ facet.column,+ filterState.length - next.length,+ );+ }+ },};}@@ -1875,10 +1874,13 @@ export function useSidebarFilterPresentation((f.type === "stringOptions" || f.type === "arrayOptions"),);- const selectedValues = computeSelectedValues(- availableValues,- checkboxFilter,+ const hasEmptyPositiveSelection = hasEmptyCheckboxSelection(+ filterState,+ facet.column,);+ const selectedValues = hasEmptyPositiveSelection+ ? []+ : computeSelectedValues(availableValues, checkboxFilter);// Determine current operator for ANY/ALL toggle// When a user selects items in an arrayOptions filter, we expose a toggle@@ -1959,6 +1961,7 @@ export function useSidebarFilterPresentation(// its "Clear" affordance.const isActive =hasTextFilters ||+ hasEmptyPositiveSelection ||(isManagedEnvironmentFacet? hasExplicitManagedEnvironmentFilter: (currentOperator === "all of" &&diff --git a/web/src/features/filters/lib/filter-query-encoding-decoding.clienttest.ts b/web/src/features/filters/lib/filter-query-encoding-decoding.clienttest.tsindex 3a118accde..e2e5d6c6ea 100644--- a/web/src/features/filters/lib/filter-query-encoding-decoding.clienttest.ts+++ b/web/src/features/filters/lib/filter-query-encoding-decoding.clienttest.ts@@ -468,6 +468,18 @@ describe("Filter Query Encoding & Decoding (Legacy Format)", () => {});describe("Round-trip consistency", () => {+ it.each([+ { value: [""] },+ { value: ["\\e"] },+ { value: ["\\\\e"] },+ { value: ["", "\\e", "a|b"] },+ ])("preserves empty strings and escaped values ($value)", ({ value }) => {+ const filters: FilterState = [+ { column: "name", type: "stringOptions", operator: "any of", value },+ ];+ expect(decodeFilters(encodeFilters(filters))).toEqual(filters);+ });+it("should maintain consistency through encode -> decode", () => {const originalFilters: FilterState = [{diff --git a/web/src/features/filters/lib/sidebar-filter-actions.clienttest.ts b/web/src/features/filters/lib/sidebar-filter-actions.clienttest.tsindex 6de0a7ffb8..abdf310eb6 100644--- a/web/src/features/filters/lib/sidebar-filter-actions.clienttest.ts+++ b/web/src/features/filters/lib/sidebar-filter-actions.clienttest.ts@@ -1,6 +1,11 @@// @vitest-environment node-import type { FilterState } from "@langfuse/shared";+import {+ type FilterState,+ singleFilter,+ encodeFiltersGeneric,+ decodeFiltersGeneric,+} from "@langfuse/shared";import {addTextFilterEntry,applyCheckboxSelection,@@ -57,6 +62,236 @@ const ctx: SidebarFilterActionContext = {};describe("applySelection", () => {+ it.each(["any of", "all of", "none of"] as const)(+ "keeps a legacy empty-selection pair when toggling to %s",+ (operator) => {+ const empty: FilterState = [+ {+ column: "tags",+ type: "arrayOptions",+ operator: "any of",+ value: ["a"],+ },+ {+ column: "tags",+ type: "arrayOptions",+ operator: "none of",+ value: ["a"],+ },+ ];+ const change = deriveOperatorChange(ctx, empty, "tags")!;+ expect(change.values).toEqual([]);+ expect(applySelection(ctx, empty, "tags", change.values, operator)).toBe(+ empty,+ );+ },+ );++ it.each(["env", "tags"])(+ "excludes available values when every default %s option is unchecked",+ (column) => {+ const type = column === "tags" ? "arrayOptions" : "stringOptions";+ const availableValues =+ column === "tags" ? ["a", "b"] : ["prod", "dev", "test"];+ const other: FilterState = [+ { column: "bookmarked", type: "boolean", operator: "=", value: true },+ ];+ for (const current of [+ other,+ [+ ...other,+ { column, type, operator: "none of", value: ["stale"] },+ ] satisfies FilterState,+ ]) {+ const empty = applyCheckboxSelection(ctx, current, column, []);+ const value =+ current.length > 1 ? [...availableValues, "stale"] : availableValues;+ expect(empty).toEqual([+ ...other,+ { column, type, operator: "none of", value },+ ]);+ expect(decodeFiltersGeneric(encodeFiltersGeneric(empty))).toEqual(+ empty,+ );+ }+ },+ );++ it("keeps an explicit empty all-of waiting for selection", () => {+ const change = deriveOperatorChange(ctx, [], "tags")!;+ const next = applySelection(ctx, [], "tags", change.values, "all of");+ expect(next).toEqual([+ { column: "tags", type: "arrayOptions", operator: "all of", value: [] },+ ]);+ expect(singleFilter.safeParse(next[0]).success).toBe(true);+ expect(applyCheckboxSelection(ctx, next, "tags", ["a"])).toEqual([+ {+ column: "tags",+ type: "arrayOptions",+ operator: "all of",+ value: ["a"],+ },+ ]);+ });++ it.each([+ {+ column: "env",+ type: "stringOptions",+ operator: "any of",+ value: ["prod"],+ target: "run-b",+ },+ {+ column: "tags",+ type: "arrayOptions",+ operator: "any of",+ value: ["a"],+ target: "run-b",+ },+ {+ column: "tags",+ type: "arrayOptions",+ operator: "all of",+ value: ["a"],+ target: "run-b",+ },+ ] satisfies FilterState)(+ "replaces an emptied positive selection with exclusions for $column ($operator)",+ (filter) => {+ const { column, type, value } = filter;+ const current: FilterState = [filter];+ const empty = applyCheckboxSelection(ctx, current, column, []);+ expect(empty).toEqual([+ {+ column,+ type,+ operator: "none of",+ value: column === "tags" ? ["a", "b"] : ["prod", "dev", "test"],+ target: "run-b",+ },+ ]);+ expect(+ empty.every((filter) => singleFilter.safeParse(filter).success),+ ).toBe(true);+ expect(decodeFiltersGeneric(encodeFiltersGeneric(empty))).toEqual(empty);+ expect(applyCheckboxSelection(ctx, empty, column, value)).toEqual([+ {+ column,+ type,+ operator: "none of",+ value: column === "tags" ? ["b"] : ["dev", "test"],+ target: "run-b",+ },+ ]);+ expect(clearCategoricalColumn(empty, column)).toEqual([]);+ },+ );++ it.each(["env", "tags"])(+ "keeps empty %s selections valid when options are blank or unavailable",+ (column) => {+ const type = column === "tags" ? "arrayOptions" : "stringOptions";+ for (const options of [[], [""]]) {+ const empty = applyCheckboxSelection(+ { ...ctx, options: { [column]: options } },+ [{ column, type, operator: "any of", value: [""] }],+ column,+ [],+ );+ expect(empty).toEqual([+ { column, type, operator: "none of", value: [""] },+ ]);+ expect(+ empty.every((filter) => singleFilter.safeParse(filter).success),+ ).toBe(true);+ }+ },+ );++ it("keeps all managed environments unchecked and allows reselecting one", () => {+ const managedCtx: SidebarFilterActionContext = {+ ...ctx,+ managedEnvironmentColumn: "env",+ hiddenEnvironments: ["test"],+ };+ const current: FilterState = [+ {+ column: "env",+ type: "stringOptions",+ operator: "none of",+ value: ["dev", "test"],+ },+ ];+ const empty = applyCheckboxSelection(managedCtx, current, "env", []);+ expect(empty).toEqual([+ {+ column: "env",+ type: "stringOptions",+ operator: "none of",+ value: ["prod", "dev", "test"],+ },+ ]);+ expect(applyCheckboxSelection(managedCtx, empty, "env", ["prod"])).toEqual([+ {+ column: "env",+ type: "stringOptions",+ operator: "none of",+ value: ["dev", "test"],+ },+ ]);+ expect(clearCategoricalColumn(empty, "env")).toEqual([]);+ });++ it.each([false, true])(+ "clears the boolean filter when its last label is unchecked (inverted: %s)",+ (invertValue) => {+ const booleanCtx: SidebarFilterActionContext = {+ ...ctx,+ facets: [+ {+ type: "boolean",+ column: "bookmarked",+ label: "Bookmarked",+ invertValue,+ },+ ],+ };+ const current: FilterState = [+ {+ column: "bookmarked",+ type: "boolean",+ operator: "=",+ value: !invertValue,+ },+ ];+ const other: FilterState = [+ {+ column: "env",+ type: "stringOptions",+ operator: "any of",+ value: ["prod"],+ },+ ];+ const empty = applyCheckboxSelection(+ booleanCtx,+ [...other, ...current],+ "bookmarked",+ [],+ );+ expect(empty).toEqual(other);+ expect(+ applyCheckboxSelection(booleanCtx, empty, "bookmarked", ["True"]),+ ).toEqual([...other, ...current]);+ expect(+ applyCheckboxSelection(booleanCtx, empty, "bookmarked", [+ "True",+ "False",+ ]),+ ).toEqual(other);+ },+ );+it("keeps a categorical filter's target and refuses to merge different targets", () => {const current = [{@@ -315,7 +550,7 @@ describe("applyCheckboxSelection", () => {).toEqual([]);});- it("keeps the managed environment reset when the last value is unchecked", () => {+ it("keeps every managed environment excluded when the last value is unchecked", () => {const managedCtx = { ...ctx, managedEnvironmentColumn: "env" };const current: FilterState = [{@@ -325,7 +560,9 @@ describe("applyCheckboxSelection", () => {value: ["prod", "dev"],},];- expect(applyCheckboxSelection(managedCtx, current, "env", [])).toEqual([]);+ expect(applyCheckboxSelection(managedCtx, current, "env", [])).toEqual([+ { ...current[0], value: ["prod", "dev", "test"] },+ ]);});it("drops the column's text filters before applying the selection", () => {diff --git a/web/src/features/filters/lib/sidebar-filter-actions.ts b/web/src/features/filters/lib/sidebar-filter-actions.tsindex 67c2f129a9..15fa75b95d 100644--- a/web/src/features/filters/lib/sidebar-filter-actions.ts+++ b/web/src/features/filters/lib/sidebar-filter-actions.ts@@ -16,6 +16,27 @@ import { partitionNoneOfEnvironmentValues } from "./managedEnvironmentPolicy";export type CheckboxOperator = "any of" | "all of" | "none of";export type TextFilterOperator = "contains" | "does not contain";+export function hasEmptyCheckboxSelection(+ current: FilterState,+ column: string,+) {+ return current.some(+ (filter) =>+ filter.column === column &&+ (filter.type === "stringOptions" || filter.type === "arrayOptions") &&+ filter.operator === "any of" &&+ filter.value.length > 0 &&+ current.some(+ (exclusion) =>+ exclusion.column === column &&+ exclusion.target === filter.target &&+ exclusion.type === filter.type &&+ exclusion.operator === "none of" &&+ filter.value.every((value) => exclusion.value.includes(value)),+ ),+ );+}+/** Options as the sidebar hook receives them (per-column value lists, or* nested key→values records for keyed facets). */type SidebarFilterOptions = Record<@@ -204,6 +225,15 @@ export function applySelection(operator?: CheckboxOperator,): FilterState {if (hasMultipleFilterTargets(current, column)) return current;+ // Changing operators without selecting values must not turn an empty+ // selection into a vacuous all-of/none-of that matches everything.+ if (+ operator !== undefined &&+ values.length === 0 &&+ hasEmptyCheckboxSelection(current, column)+ ) {+ return current;+ }const existingFilter = current.find((f) => f.column === column);const target = existingFilter?.target? { target: existingFilter.target }@@ -266,6 +296,33 @@ export function applySelection(return current;}+ const filterType: "arrayOptions" | "stringOptions" =+ colType === "arrayOptions" ? "arrayOptions" : "stringOptions";++ if (operator === undefined && values.length === 0) {+ const previousValues =+ existingFilter?.type === "stringOptions" ||+ existingFilter?.type === "arrayOptions"+ ? existingFilter.value+ : [];+ // Exclude unchecked options, including values no longer in the loaded+ // option list. Unlisted values may still match; this is not match-nothing.+ const excludedValues = [+ ...new Set([...availableValues, ...previousValues]),+ ];+ if (excludedValues.length === 0) return other;+ return [+ ...other,+ {+ column,+ ...target,+ type: filterType,+ operator: "none of",+ value: excludedValues,+ },+ ];+ }+// Determine operator and values based on contextlet finalOperator: CheckboxOperator;let finalValues: string[];@@ -274,8 +331,7 @@ export function applySelection(// "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). This also covers "none checked", which means- // exclude every listed value rather than reset. The managed+ // removed below). 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.@@ -301,13 +357,13 @@ export function applySelection(return other;}} else {- // If all items selected or none selected, remove filter+ // If all items are selected, remove the 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))))+ 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) {@@ -362,9 +418,6 @@ export function applySelection(}}- const filterType: "arrayOptions" | "stringOptions" =- colType === "arrayOptions" ? "arrayOptions" : "stringOptions";-if (filterType === "arrayOptions") {return [...other,@@ -498,6 +551,10 @@ export function deriveOperatorChange(return null;}+ if (hasEmptyCheckboxSelection(current, column)) {+ return { values: [], fromOperator: existingFilter.operator };+ }+// For "none of", the SELECTED values are the complement of the stored// exclusions (arrayOptions stores the exclusions directly).const availableValues = toValueList(ctx.options[column]) ?? [];diff --git a/web/src/features/filters/sidebarArrayOptionsExclusion.clienttest.tsx b/web/src/features/filters/sidebarArrayOptionsExclusion.clienttest.tsxindex 9dd8aa2a1f..b38ca37033 100644--- a/web/src/features/filters/sidebarArrayOptionsExclusion.clienttest.tsx+++ b/web/src/features/filters/sidebarArrayOptionsExclusion.clienttest.tsx@@ -14,12 +14,23 @@* like stringOptions none-of filters always have.*/-import { fireEvent, render, screen } from "@testing-library/react";+import {+ act,+ fireEvent,+ render,+ renderHook,+ screen,+} from "@testing-library/react";import {useSidebarFilterState,type CategoricalUIFilter,} from "./hooks/useSidebarFilterState";import type { FilterConfig } from "./lib/filter-config";+import {+ encodeFiltersGeneric,+ decodeFiltersGeneric,+ singleFilter,+} from "@langfuse/shared";// The hook calls useQueryParam unconditionally even for the "memory" state// location used here; stub it out so no QueryParamProvider is needed.@@ -159,6 +170,80 @@ const NAME_OPTIONS = {name: ["checkout", "search", "chat"],};+describe("deselecting the last checkbox", () => {+ it.each([+ [TAGS_FILTER_CONFIG, TAG_OPTIONS, "tags", "tag-1"],+ [NAME_FILTER_CONFIG, NAME_OPTIONS, "name", "checkout"],+ ] as const)(+ "keeps an empty categorical selection active (%s)",+ (config, options, column, value) => {+ const { result } = renderHook(() =>+ useSidebarFilterState(config, options, { stateLocation: "memory" }),+ );+ const facet = () =>+ result.current.filters.find(+ (filter): filter is CategoricalUIFilter => filter.column === column,+ )!;+ act(() => facet().onOnlyChange?.(value));+ act(() => facet().onChange([]));+ expect(facet().value).toEqual([]);+ expect(facet().isActive).toBe(true);+ const emptySelection = result.current.filterState;+ expect(+ emptySelection.every(+ (filter) => singleFilter.safeParse(filter).success,+ ),+ ).toBe(true);+ act(() =>+ result.current.setFilterState(+ decodeFiltersGeneric(encodeFiltersGeneric(emptySelection)),+ ),+ );+ expect(result.current.filterState).toEqual(emptySelection);+ expect(facet().value).toEqual([]);+ expect(facet().isActive).toBe(true);+ act(() => facet().onChange([value]));+ expect(facet().value).toEqual([value]);+ act(() => facet().onReset?.());+ expect(facet().isActive).toBe(false);+ expect(result.current.filterState).toEqual([]);+ },+ );++ it.each([false, true])(+ "returns to both boolean labels checked after unchecking the last (inverted: %s)",+ (invertValue) => {+ const config: FilterConfig = {+ tableName: "traces",+ columnDefinitions: [],+ facets: [+ {+ type: "boolean",+ column: "isRootObservation",+ label: "Root",+ invertValue,+ },+ ],+ };+ const { result } = renderHook(() =>+ useSidebarFilterState(config, {}, { stateLocation: "memory" }),+ );+ const facet = () => result.current.filters[0] as CategoricalUIFilter;+ act(() => facet().onChange(["True"]));+ act(() => facet().onChange([]));+ expect(facet().value).toEqual(["True", "False"]);+ expect(facet().isActive).toBe(false);+ expect(result.current.filterState).toEqual([]);+ act(() => facet().onChange(["False"]));+ expect(facet().value).toEqual(["False"]);+ act(() => facet().onReset?.());+ expect(facet().value).toEqual(["True", "False"]);+ expect(facet().isActive).toBe(false);+ expect(result.current.filterState).toEqual([]);+ },+ );+});+// stringOptions facets share the display pipeline: the operator must be// exposed there too so the none-of pinning in data-table-controls can surface// the just-unchecked row (the SOME/ALL/NONE toggle stays arrayOptions-only viadiff --git a/web/src/features/monitors/components/MonitorsTable.clienttest.ts b/web/src/features/monitors/components/MonitorsTable.clienttest.tsindex 965327393e..4a3fff2887 100644--- a/web/src/features/monitors/components/MonitorsTable.clienttest.ts+++ b/web/src/features/monitors/components/MonitorsTable.clienttest.ts@@ -5,6 +5,7 @@ import {type Monitor,MonitorNoDataModeSchema,MonitorSeveritySchema,+ ListMonitorFilterSchema,MonitorStatusSchema,MonitorThresholdOperatorSchema,} from "@langfuse/shared/monitors";@@ -72,6 +73,56 @@ describe("getMonitorFilterConfig", () => {});describe("filterStateToListMonitorFilter", () => {+ it.each([+ { column: "severity", type: "stringOptions", value: ["ALERT"] },+ { column: "evaluatorId", type: "stringOptions", value: ["eval-1"] },+ { column: "tags", type: "arrayOptions", value: ["prod"] },+ ] as const)(+ "matches nothing for an empty $column without losing other facets",+ ({ column, type, value }) => {+ const other = (+ [+ {+ column: "severity",+ type: "stringOptions",+ operator: "any of",+ value: ["WARNING"],+ },+ {+ column: "evaluatorId",+ type: "stringOptions",+ operator: "any of",+ value: ["eval-2"],+ },+ {+ column: "tags",+ type: "arrayOptions",+ operator: "all of",+ value: ["critical"],+ },+ ] satisfies FilterState+ ).filter((filter) => filter.column !== column);+ const state: FilterState = [+ ...other,+ { column, type, operator: "any of", value: [...value] },+ { column, type, operator: "none of", value: [...value] },+ ];+ const original = structuredClone(state);+ const request = filterStateToListMonitorFilter(state);+ expect(ListMonitorFilterSchema.safeParse(request).success).toBe(true);+ expect(request).toEqual([+ ...other.filter((filter) => filter.column !== "severity"),+ {+ column: "severity",+ type: "stringOptions",+ operator: "none of",+ value: MonitorSeveritySchema.options,+ },+ ]);+ expect(state).toEqual(original);+ },+ );+it("passes severity `any of` through with values intact", () => {const state: FilterState = [{diff --git a/web/src/features/monitors/components/MonitorsTable.tsx b/web/src/features/monitors/components/MonitorsTable.tsxindex 58a65d8242..11dd978ba5 100644--- a/web/src/features/monitors/components/MonitorsTable.tsx+++ b/web/src/features/monitors/components/MonitorsTable.tsx@@ -57,6 +57,7 @@ import { useTableViewFilterChange } from "@/src/components/table/table-view-presimport { TableSearchBar, toObservedOptions } from "@/src/features/search-bar";import { monitorsFieldRegistry } from "@/src/features/monitors/constants/monitorsSearchRegistry";+import { hasEmptyCheckboxSelection } from "@/src/features/filters/lib/sidebar-filter-actions";/** monitorsRefetchInterval keeps the list's severity and paused state current without a manual reload. */const monitorsRefetchInterval = 5_000;@@ -512,7 +513,29 @@ function MonitorRowActions({const filterStateToListMonitorFilter = (state: FilterState,): ListMonitorFilter => {- const parsed = ListMonitorFilterSchema.safeParse(state);+ const emptyColumns = new Set(+ state+ .filter((filter) => hasEmptyCheckboxSelection(state, filter.column))+ .map((filter) => filter.column),+ );+ // The monitor API allows only one filter per column. Excluding every+ // severity is a valid contradiction, independent of loaded facet options.+ const requestState: FilterState =+ emptyColumns.size > 0+ ? [+ ...state.filter(+ (filter) =>+ !emptyColumns.has(filter.column) && filter.column !== "severity",+ ),+ {+ column: "severity",+ type: "stringOptions",+ operator: "none of",+ value: MonitorSeveritySchema.options,+ },+ ]+ : state;+ const parsed = ListMonitorFilterSchema.safeParse(requestState);if (!parsed.success) return [];return parsed.data.map((row) => {if (diff --git a/web/src/features/search-bar/hooks/useEventsSearchBar.ts b/web/src/features/search-bar/hooks/useEventsSearchBar.tsindex f51b98cc54..83620a518c 100644--- a/web/src/features/search-bar/hooks/useEventsSearchBar.ts+++ b/web/src/features/search-bar/hooks/useEventsSearchBar.ts@@ -403,9 +403,18 @@ export function useEventsSearchBar({// Ordinary grammar edits preserve filters the grammar cannot represent.// Complete-query replacements can explicitly clear those hidden filters// instead of silently carrying old scope.- const committedFilters = options.replaceHidden- ? result.filters- : mergeWithSkipped(result.filters);+ const committedFilters = (() => {+ if (options.replaceHidden) return result.filters;+ // Unchanged text must not rewrite legacy filters into a different shape+ // and make a saved view look edited.+ if (draftText.trim() === committedTextRef.current.trim()) {+ return (+ pendingCommitRef.current?.next.filters ??+ appliedStateRef.current.filters+ );+ }+ return mergeWithSkipped(result.filters);+ })();// Register the full write before the optimistic filter setter can render// ahead of the URL-backed search query or scope setters.const committed = beginCommit({diff --git a/web/src/features/search-bar/lib/adapter.clienttest.ts b/web/src/features/search-bar/lib/adapter.clienttest.tsindex b9164bd104..0536f9ca4b 100644--- a/web/src/features/search-bar/lib/adapter.clienttest.ts+++ b/web/src/features/search-bar/lib/adapter.clienttest.ts@@ -5,6 +5,11 @@ import { validateQuery } from "@/src/features/search-bar/lib/validate";import type { FilterState } from "@langfuse/shared";import { createFieldRegistry, EVENTS_FIELD_REGISTRY } from "./fields";import { planCommit } from "./commit";+import {+ applyCheckboxSelection,+ hasEmptyCheckboxSelection,+ type SidebarFilterActionContext,+} from "@/src/features/filters/lib/sidebar-filter-actions";import {USERS_FIELD_REGISTRY,LEGACY_USERS_FIELD_REGISTRY,@@ -686,7 +691,12 @@ describe("astToFilterState", () => {}// `key:=value` is the explicit exact match.expect(lower("name:=checkout").filters).toEqual([- { type: "string", column: "name", operator: "=", value: "checkout" },+ {+ type: "stringOptions",+ column: "name",+ operator: "any of",+ value: ["checkout"],+ },]);// Negation is does-not-contain (flat-representable).expect(lower("-id:abc").filters).toEqual([@@ -702,7 +712,7 @@ describe("astToFilterState", () => {it("lowers negated exact on id/name to stringOptions none-of (exact inequality)", () => {// `-name:=abc` is exact-inequality — the faithful flat form is// stringOptions none-of (there is no `string !=`). It is the inverse of the- // positive `name:=abc` (`string =`) and the shape the facet emits when one+ // positive `name:=abc` and the shape the facet emits when one// value is unchecked, so it must lower cleanly rather than error.for (const column of ["id", "name"]) {const r = lower(`-${column}:=abc`);@@ -715,6 +725,102 @@ describe("astToFilterState", () => {expect(validateQuery("-name:=abc").valid).toBe(true);});+ it.each([+ {+ column: "ingestionApiKey",+ value: "pk-lf-1234567890",+ text: "-ingestionApiKey:pk-lf-1234567890",+ },+ { column: "name", value: "checkout", text: "-name:=checkout" },+ { column: "traceTags", value: "prod", text: "-traceTags:prod" },+ ])(+ "shows only an exclusion when the sole $column option is unchecked",+ ({ column, value, text }) => {+ const ctx: SidebarFilterActionContext = {+ facets: [{ type: "categorical", column, label: column }],+ columnDefinitions: [+ {+ id: column,+ name: column,+ type: column === "traceTags" ? "arrayOptions" : "stringOptions",+ options: [],+ internal: column,+ },+ ],+ options: { [column]: [value] },+ };+ const empty = applyCheckboxSelection(ctx, [], column, []);+ expect(empty).toEqual([+ {+ column,+ type: column === "traceTags" ? "arrayOptions" : "stringOptions",+ operator: "none of",+ value: [value],+ },+ ]);+ expect(filterStateToQueryText(empty).text).toBe(text);+ const commit = planCommit(`${text} env:prod`);+ expect(commit.status).toBe("committed");+ if (commit.status !== "committed") return;+ expect(+ commit.filters.filter((filter) => filter.column === column),+ ).toEqual(empty);+ expect(+ applyCheckboxSelection(ctx, commit.filters, column, [value]),+ ).toEqual(commit.filters.filter((filter) => filter.column !== column));+ },+ );++ it("preserves a legacy empty Name pair through a search-bar edit", () => {+ const ctx: SidebarFilterActionContext = {+ facets: [{ type: "categorical", column: "name", label: "Name" }],+ columnDefinitions: [+ {+ id: "name",+ name: "Name",+ type: "stringOptions",+ options: [],+ internal: "name",+ },+ ],+ options: { name: ["checkout", "chat"] },+ };+ const empty: FilterState = [+ {+ column: "name",+ type: "stringOptions",+ operator: "any of",+ value: ["checkout"],+ },+ {+ column: "name",+ type: "stringOptions",+ operator: "none of",+ value: ["checkout"],+ },+ ];+ const { text, skippedFilters } = filterStateToQueryText(empty);+ expect(text).toBe("name:=checkout -name:=checkout");+ expect(skippedFilters).toEqual([]);++ const commit = planCommit(`${text} env:prod`);+ expect(commit.status).toBe("committed");+ if (commit.status !== "committed") return;++ expect(commit.filters.filter((filter) => filter.column === "name")).toEqual(+ empty,+ );+ expect(hasEmptyCheckboxSelection(commit.filters, "name")).toBe(true);+ expect(+ applyCheckboxSelection(ctx, commit.filters, "name", ["chat"]),+ ).toContainEqual({+ column: "name",+ type: "stringOptions",+ operator: "any of",+ value: ["chat"],+ });+ });+it("lowers input:/output: to real column filters (not searchType)", () => {const r = lower("input:refund");expect(r.errors).toEqual([]);@@ -1214,10 +1320,12 @@ describe("filterStateToQueryText", () => {expect(skipped).toEqual([]);expect(text).toBe(`${column}:=abc`); // explicit exact, not bare `id:abc`const r = astToFilterState(validateQuery(text).ast);- // Stabilizes to {string,=} — same semantics (exact equality), never contains.- expect(r.filters).toEqual([- { type: "string", column, operator: "=", value: "abc" },- ]);+ // Name retains its categorical facet shape; ID uses string equality.+ const expected =+ column === "name"+ ? filters+ : [{ type: "string", column, operator: "=", value: "abc" }];+ expect(r.filters).toEqual(expected);// And the stabilized form is a fixpoint (no further drift).const echo = filterStateToQueryText(r.filters);expect(echo.text).toBe(`${column}:=abc`);diff --git a/web/src/features/search-bar/lib/fields.ts b/web/src/features/search-bar/lib/fields.tsindex ab1c450daf..ec2383bddd 100644--- a/web/src/features/search-bar/lib/fields.ts+++ b/web/src/features/search-bar/lib/fields.ts@@ -370,7 +370,7 @@ export function withFieldOptions(export const FIELDS: FieldDef[] = [{ id: "id", aliases: ["spanid", "span_id", "observationid", "observation_id"], kind: "text", syncMode: "textSearch", suggestObservedValues: true, label: "Observation ID", description: "Observation/span identifier" },{ id: "traceId", aliases: ["traceid", "trace_id"], kind: "text", syncMode: "textSearch", label: "Trace ID", description: "Trace identifier" },- { id: "name", aliases: [], kind: "text", syncMode: "textSearch", suggestObservedValues: true, label: "Name", description: "Observation name", nullable: true },+ { id: "name", aliases: [], kind: "text", syncMode: "textSearch", suggestObservedValues: true, exactMatchUsesOptions: true, label: "Name", description: "Observation name", nullable: true },{ id: "traceName", aliases: ["tracename", "trace_name"], kind: "text", syncMode: "exactOption", label: "Trace name", description: "Trace name", nullable: true },{ id: "type", aliases: [], kind: "text", syncMode: "exactOption", label: "Type", description: "Observation type" },{ id: "environment", aliases: ["env"], kind: "text", syncMode: "exactOption", label: "Environment", description: "Environment", nullable: true },