πͺ’ 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(table-views): demote active system preset when user edits its filters (LFE-14699) (#15768)
Nikita Kabardin5c68de289de5
diff --git a/packages/shared/src/domain/index.ts b/packages/shared/src/domain/index.tsindex bfadb57f19..70d750bca1 100644--- a/packages/shared/src/domain/index.ts+++ b/packages/shared/src/domain/index.ts@@ -3,6 +3,7 @@ export * from "./observations";export * from "./traces";export * from "./scores";export * from "./table-view-presets";+export * from "./table-view-presets-catalog";export * from "./automations";export * from "./webhooks";export * from "./prompts";diff --git a/packages/shared/src/domain/table-view-presets-catalog.ts b/packages/shared/src/domain/table-view-presets-catalog.tsnew file mode 100644index 0000000000..6cf048fa18--- /dev/null+++ b/packages/shared/src/domain/table-view-presets-catalog.ts@@ -0,0 +1,221 @@+// The system table-view preset catalog. Lives in the domain layer (not the+// server TableViewService) because the definitions are plain data with+// client-safe deps β client code (e.g. the events-table preset tests) reads+// the catalog without pulling in the server barrel. The server service+// re-exports it, so server callers are unchanged.+import {+ SystemTableViewPresetCategory,+ type TableViewPresetState,+ TableViewPresetTableName,+} from "./table-view-presets";++export const SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX = "__langfuse_";++export const isSystemTableViewPresetId = (+ id: string | undefined | null,+): boolean => !!id?.startsWith(SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX);++export interface SystemTableViewPreset {+ id: string;+ name: string;+ description?: string;+ tableName: TableViewPresetTableName;+ /**+ * When set, the preset is surfaced as a quick-access chip beneath the search+ * bar, grouped under this category. Uncategorized presets appear only in the+ * views drawer.+ */+ category?: SystemTableViewPresetCategory;+ state: TableViewPresetState;+}++const buildSystemPreset = ({+ id,+ name,+ description,+ tableName,+ category,+ filters,+ orderBy = null,+}: {+ id: string;+ name: string;+ description?: string;+ tableName: TableViewPresetTableName;+ category?: SystemTableViewPresetCategory;+ filters: TableViewPresetState["filters"];+ orderBy?: TableViewPresetState["orderBy"];+}): SystemTableViewPreset => ({+ id,+ name,+ description,+ tableName,+ category,+ state: {+ filters,+ columnOrder: [],+ columnVisibility: {},+ orderBy,+ searchQuery: "",+ },+});++const OBSERVATIONS_EVENTS_SYSTEM_TABLE_VIEW_PRESETS: SystemTableViewPreset[] = [+ buildSystemPreset({+ id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}errors_only`,+ name: "Errors Only",+ description: "Focus on observations that failed",+ tableName: TableViewPresetTableName.ObservationsEvents,+ category: SystemTableViewPresetCategory.Errors,+ filters: [+ {+ column: "level",+ type: "stringOptions",+ operator: "any of",+ value: ["ERROR"],+ },+ ],+ }),++ // --- Slow calls -----------------------------------------------------------+ buildSystemPreset({+ id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}latency_over_10s`,+ name: "Latency over 10s",+ description: "Observations taking longer than 10 seconds",+ tableName: TableViewPresetTableName.ObservationsEvents,+ category: SystemTableViewPresetCategory.SlowCalls,+ filters: [{ column: "latency", type: "number", operator: ">", value: 10 }],+ orderBy: { column: "latency", order: "DESC" },+ }),+ buildSystemPreset({+ id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}slow_generations`,+ name: "Slow generations",+ description: "Generation calls slower than 5 seconds",+ tableName: TableViewPresetTableName.ObservationsEvents,+ category: SystemTableViewPresetCategory.SlowCalls,+ filters: [+ {+ column: "type",+ type: "stringOptions",+ operator: "any of",+ value: ["GENERATION"],+ },+ { column: "latency", type: "number", operator: ">", value: 5 },+ ],+ orderBy: { column: "latency", order: "DESC" },+ }),++ // --- Errors ---------------------------------------------------------------+ buildSystemPreset({+ id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}warnings_and_errors`,+ name: "Warnings & errors",+ description: "Observations logged at WARNING or ERROR level",+ tableName: TableViewPresetTableName.ObservationsEvents,+ category: SystemTableViewPresetCategory.Errors,+ filters: [+ {+ column: "level",+ type: "stringOptions",+ operator: "any of",+ value: ["ERROR", "WARNING"],+ },+ ],+ }),+ buildSystemPreset({+ // Shipped-id stability: this is the pre-chips "Generations Only" preset+ // (identical filters) renamed and categorized. Its id already lives in+ // bookmarked `?viewId=` URLs and `default_views` rows (view_id has no FK+ // on purpose), so the rename keeps the id β retiring it would strand+ // those references. Never mint a new id for a preset whose meaning+ // survives a catalog iteration β and conversely, the FILTER SEMANTICS+ // under this id are frozen: tightening this preset (e.g. adding score or+ // output filters) would silently morph every old bookmark/default, so a+ // preset with a different meaning must get a new id.+ id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}generations_only`,+ name: "Review output (generations)",+ description: "LLM generation outputs, for reviewing response quality",+ tableName: TableViewPresetTableName.ObservationsEvents,+ category: SystemTableViewPresetCategory.Errors,+ filters: [+ {+ column: "type",+ type: "stringOptions",+ operator: "any of",+ value: ["GENERATION"],+ },+ ],+ }),+ buildSystemPreset({+ id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}missed_tool_calls`,+ name: "Missed tool calls",+ description: "LLM calls that had tools available but didn't call any",+ tableName: TableViewPresetTableName.ObservationsEvents,+ category: SystemTableViewPresetCategory.Errors,+ filters: [+ {+ column: "type",+ type: "stringOptions",+ operator: "any of",+ value: ["GENERATION"],+ },+ { column: "toolDefinitions", type: "number", operator: ">", value: 0 },+ { column: "toolCalls", type: "number", operator: "=", value: 0 },+ ],+ }),++ // --- Cost regression ------------------------------------------------------+ buildSystemPreset({+ id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}high_cost`,+ name: "High cost (> $1)",+ description: "Observations costing more than $1",+ tableName: TableViewPresetTableName.ObservationsEvents,+ category: SystemTableViewPresetCategory.CostRegression,+ filters: [{ column: "totalCost", type: "number", operator: ">", value: 1 }],+ orderBy: { column: "totalCost", order: "DESC" },+ }),+ buildSystemPreset({+ id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}high_token_usage`,+ name: "High token usage",+ description: "Observations using more than 50k tokens",+ tableName: TableViewPresetTableName.ObservationsEvents,+ category: SystemTableViewPresetCategory.CostRegression,+ filters: [+ {+ column: "totalTokens",+ type: "number",+ operator: ">",+ value: 50000,+ },+ ],+ orderBy: { column: "totalTokens", order: "DESC" },+ }),+];++const SYSTEM_TABLE_VIEW_PRESETS: Partial<+ Record<TableViewPresetTableName, SystemTableViewPreset[]>+> = {+ [TableViewPresetTableName.ObservationsEvents]:+ OBSERVATIONS_EVENTS_SYSTEM_TABLE_VIEW_PRESETS,+};++export const getSystemTableViewPresets = (+ tableName: TableViewPresetTableName,+) => SYSTEM_TABLE_VIEW_PRESETS[tableName] ?? [];++export const getSystemTableViewPresetByTableAndId = (+ tableName: TableViewPresetTableName,+ id: string,+): SystemTableViewPreset | null =>+ getSystemTableViewPresets(tableName).find((preset) => preset.id === id) ??+ null;++export const getSystemTableViewPresetById = (+ id: string,+): SystemTableViewPreset | null => {+ for (const presets of Object.values(SYSTEM_TABLE_VIEW_PRESETS)) {+ const preset = presets?.find((candidate) => candidate.id === id);+ if (preset) return preset;+ }++ return null;+};diff --git a/packages/shared/src/server/services/TableViewService/systemPresets.ts b/packages/shared/src/server/services/TableViewService/systemPresets.tsindex 583c850b58..badf36b2b2 100644--- a/packages/shared/src/server/services/TableViewService/systemPresets.ts+++ b/packages/shared/src/server/services/TableViewService/systemPresets.ts@@ -1,216 +1,3 @@-import {- SystemTableViewPresetCategory,- type TableViewPresetState,- TableViewPresetTableName,-} from "../../../domain/table-view-presets";--export const SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX = "__langfuse_";--export const isSystemTableViewPresetId = (- id: string | undefined | null,-): boolean => !!id?.startsWith(SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX);--export interface SystemTableViewPreset {- id: string;- name: string;- description?: string;- tableName: TableViewPresetTableName;- /**- * When set, the preset is surfaced as a quick-access chip beneath the search- * bar, grouped under this category. Uncategorized presets appear only in the- * views drawer.- */- category?: SystemTableViewPresetCategory;- state: TableViewPresetState;-}--const buildSystemPreset = ({- id,- name,- description,- tableName,- category,- filters,- orderBy = null,-}: {- id: string;- name: string;- description?: string;- tableName: TableViewPresetTableName;- category?: SystemTableViewPresetCategory;- filters: TableViewPresetState["filters"];- orderBy?: TableViewPresetState["orderBy"];-}): SystemTableViewPreset => ({- id,- name,- description,- tableName,- category,- state: {- filters,- columnOrder: [],- columnVisibility: {},- orderBy,- searchQuery: "",- },-});--const OBSERVATIONS_EVENTS_SYSTEM_TABLE_VIEW_PRESETS: SystemTableViewPreset[] = [- buildSystemPreset({- id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}errors_only`,- name: "Errors Only",- description: "Focus on observations that failed",- tableName: TableViewPresetTableName.ObservationsEvents,- category: SystemTableViewPresetCategory.Errors,- filters: [- {- column: "level",- type: "stringOptions",- operator: "any of",- value: ["ERROR"],- },- ],- }),-- // --- Slow calls ------------------------------------------------------------ buildSystemPreset({- id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}latency_over_10s`,- name: "Latency over 10s",- description: "Observations taking longer than 10 seconds",- tableName: TableViewPresetTableName.ObservationsEvents,- category: SystemTableViewPresetCategory.SlowCalls,- filters: [{ column: "latency", type: "number", operator: ">", value: 10 }],- orderBy: { column: "latency", order: "DESC" },- }),- buildSystemPreset({- id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}slow_generations`,- name: "Slow generations",- description: "Generation calls slower than 5 seconds",- tableName: TableViewPresetTableName.ObservationsEvents,- category: SystemTableViewPresetCategory.SlowCalls,- filters: [- {- column: "type",- type: "stringOptions",- operator: "any of",- value: ["GENERATION"],- },- { column: "latency", type: "number", operator: ">", value: 5 },- ],- orderBy: { column: "latency", order: "DESC" },- }),-- // --- Errors ---------------------------------------------------------------- buildSystemPreset({- id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}warnings_and_errors`,- name: "Warnings & errors",- description: "Observations logged at WARNING or ERROR level",- tableName: TableViewPresetTableName.ObservationsEvents,- category: SystemTableViewPresetCategory.Errors,- filters: [- {- column: "level",- type: "stringOptions",- operator: "any of",- value: ["ERROR", "WARNING"],- },- ],- }),- buildSystemPreset({- // Shipped-id stability: this is the pre-chips "Generations Only" preset- // (identical filters) renamed and categorized. Its id already lives in- // bookmarked `?viewId=` URLs and `default_views` rows (view_id has no FK- // on purpose), so the rename keeps the id β retiring it would strand- // those references. Never mint a new id for a preset whose meaning- // survives a catalog iteration β and conversely, the FILTER SEMANTICS- // under this id are frozen: tightening this preset (e.g. adding score or- // output filters) would silently morph every old bookmark/default, so a- // preset with a different meaning must get a new id.- id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}generations_only`,- name: "Review output (generations)",- description: "LLM generation outputs, for reviewing response quality",- tableName: TableViewPresetTableName.ObservationsEvents,- category: SystemTableViewPresetCategory.Errors,- filters: [- {- column: "type",- type: "stringOptions",- operator: "any of",- value: ["GENERATION"],- },- ],- }),- buildSystemPreset({- id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}missed_tool_calls`,- name: "Missed tool calls",- description: "LLM calls that had tools available but didn't call any",- tableName: TableViewPresetTableName.ObservationsEvents,- category: SystemTableViewPresetCategory.Errors,- filters: [- {- column: "type",- type: "stringOptions",- operator: "any of",- value: ["GENERATION"],- },- { column: "toolDefinitions", type: "number", operator: ">", value: 0 },- { column: "toolCalls", type: "number", operator: "=", value: 0 },- ],- }),-- // --- Cost regression ------------------------------------------------------- buildSystemPreset({- id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}high_cost`,- name: "High cost (> $1)",- description: "Observations costing more than $1",- tableName: TableViewPresetTableName.ObservationsEvents,- category: SystemTableViewPresetCategory.CostRegression,- filters: [{ column: "totalCost", type: "number", operator: ">", value: 1 }],- orderBy: { column: "totalCost", order: "DESC" },- }),- buildSystemPreset({- id: `${SYSTEM_TABLE_VIEW_PRESET_ID_PREFIX}high_token_usage`,- name: "High token usage",- description: "Observations using more than 50k tokens",- tableName: TableViewPresetTableName.ObservationsEvents,- category: SystemTableViewPresetCategory.CostRegression,- filters: [- {- column: "totalTokens",- type: "number",- operator: ">",- value: 50000,- },- ],- orderBy: { column: "totalTokens", order: "DESC" },- }),-];--const SYSTEM_TABLE_VIEW_PRESETS: Partial<- Record<TableViewPresetTableName, SystemTableViewPreset[]>-> = {- [TableViewPresetTableName.ObservationsEvents]:- OBSERVATIONS_EVENTS_SYSTEM_TABLE_VIEW_PRESETS,-};--export const getSystemTableViewPresets = (- tableName: TableViewPresetTableName,-) => SYSTEM_TABLE_VIEW_PRESETS[tableName] ?? [];--export const getSystemTableViewPresetByTableAndId = (- tableName: TableViewPresetTableName,- id: string,-): SystemTableViewPreset | null =>- getSystemTableViewPresets(tableName).find((preset) => preset.id === id) ??- null;--export const getSystemTableViewPresetById = (- id: string,-): SystemTableViewPreset | null => {- for (const presets of Object.values(SYSTEM_TABLE_VIEW_PRESETS)) {- const preset = presets?.find((candidate) => candidate.id === id);- if (preset) return preset;- }-- return null;-};+// The catalog moved to the domain layer (client-safe data, no server deps);+// re-exported here so server-side callers keep their import path.+export * from "../../../domain/table-view-presets-catalog";diff --git a/web/src/features/events/components/CategoryPresetChips.tsx b/web/src/features/events/components/CategoryPresetChips.tsxindex bd9718ef0e..3ba6fbcacd 100644--- a/web/src/features/events/components/CategoryPresetChips.tsx+++ b/web/src/features/events/components/CategoryPresetChips.tsx@@ -1,5 +1,11 @@import { useMemo, useRef } from "react";-import { DollarSign, ThumbsDown, Timer, type LucideIcon } from "lucide-react";+import {+ Check,+ DollarSign,+ ThumbsDown,+ Timer,+ type LucideIcon,+} from "lucide-react";import {SYSTEM_TABLE_VIEW_PRESET_CATEGORIES_ORDERED,SYSTEM_TABLE_VIEW_PRESET_CATEGORY_META,@@ -225,7 +231,13 @@ export function CategoryPresetChips({if (event.key === "Enter" || event.key === " ")pointerDownRef.current = false;}}- className={cn("gap-1.5", isCategoryActive && "bg-primary/5")}+ className={cn(+ "gap-1.5",+ // Filled like the sibling ViewModeToggle's on-state+ // (toggleVariants) β bg-primary/5 was invisible in dark mode.+ isCategoryActive &&+ "bg-primary text-primary-foreground border-primary hover:bg-primary/90 hover:text-primary-foreground",+ )}><Icon className="h-4 w-4" aria-hidden />{label}@@ -325,6 +337,9 @@ export function CategoryPresetChips({preset.disabled? "cursor-default opacity-60": "hover:bg-accent",+ // bg-muted is indistinguishable from the dark popover+ // surface; accent + check marks the active row.+ isPresetActive && "bg-accent",)}><span className="flex flex-col">@@ -342,6 +357,12 @@ export function CategoryPresetChips({</span>)}</span>+ {isPresetActive && (+ <Check+ className="mt-0.5 h-4 w-4 shrink-0"+ aria-hidden+ />+ )}</button>);// The disabled placeholder never applies, so it isn't wrappeddiff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsxindex 4e289800f2..28e4dc9eb7 100644--- a/web/src/features/events/components/EventsTable.tsx+++ b/web/src/features/events/components/EventsTable.tsx@@ -79,6 +79,11 @@ import {useDetailPageLists,} from "@/src/features/navigate-detail-pages/context";import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";+import {+ demoteViewOnUserFilterEdit,+ type ExplicitFilterStateChange,+ type ViewDemotionControllers,+} from "@/src/features/events/lib/demoteViewOnUserFilterEdit";import { useFullTextSearch } from "@/src/components/table/use-cases/useFullTextSearch";import { TableSelectionManager } from "@/src/features/table/components/TableSelectionManager";import { useSelectAll } from "@/src/features/table/hooks/useSelectAll";@@ -497,13 +502,32 @@ export default function ObservationsEventsTable({projectId,});+ // Late-bound view controllers for the demotion callback below: the filter+ // hook (and its onExplicitFilterStateChange) is created before+ // useTableViewManager runs, so reach the controllers through a ref (same+ // pattern as queryFilterRef).+ const viewControllersRef = useRef<ViewDemotionControllers | null>(null);++ const onAppRootExplicitFilterStateChange =+ appRootDefault.onExplicitFilterStateChange;++ // Composes the app-root default policy with the view demotion on user-origin+ // filter edits (LFE-14699).+ const onExplicitFilterStateChange = useCallback(+ (change: ExplicitFilterStateChange) => {+ onAppRootExplicitFilterStateChange(change);+ demoteViewOnUserFilterEdit(change, viewControllersRef.current);+ },+ [onAppRootExplicitFilterStateChange],+ );+// Route-state half of the sidebar filters, ahead of the facet-options query// so the same state that scopes the rows can refine the counts (LFE-14489).const filterStateOptions: UseSidebarFilterStateOptions = useMemo(() => {const baseOptions = {implicitDefaultConfig: DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG,defaultExplicitFilterState: appRootDefault.defaultExplicitFilterState,- onExplicitFilterStateChange: appRootDefault.onExplicitFilterStateChange,+ onExplicitFilterStateChange,};if (peekContext) {@@ -531,7 +555,7 @@ export default function ObservationsEventsTable({peekContext,projectId,appRootDefault.defaultExplicitFilterState,- appRootDefault.onExplicitFilterStateChange,+ onExplicitFilterStateChange,]);const filterCore = useSidebarFilterStateCore(@@ -1753,6 +1777,7 @@ export default function ObservationsEventsTable({disabled: tableStatePolicy.disableSavedViews,allowBackendSystemPresets: true,});+ viewControllersRef.current = viewControllers;const peekConfig: DataTablePeekViewProps | undefined = useMemo(() => {if (hideControls) return undefined;@@ -1956,10 +1981,10 @@ export default function ObservationsEventsTable({tableStatePolicy.disableSavedViews ? undefined : (<CategoryPresetChipsprojectId={projectId}- activeViewId={- viewControllers.appliedViewId ??- viewControllers.selectedViewId- }+ // URL viewId only β the sessionStorage appliedViewId can+ // go stale under explicit URL state and light the wrong+ // chip (see demoteViewOnUserFilterEdit).+ activeViewId={viewControllers.selectedViewId}onApplyView={viewControllers.handleSetViewId}applyViewState={viewControllers.applyViewState}onPreviewView={previewViewInSearchBar}@@ -2164,10 +2189,10 @@ export default function ObservationsEventsTable({<div className="flex flex-wrap items-center gap-2"><CategoryPresetChipsprojectId={projectId}- activeViewId={- viewControllers.appliedViewId ??- viewControllers.selectedViewId- }+ // URL viewId only β the sessionStorage appliedViewId+ // can go stale under explicit URL state and light the+ // wrong chip (see demoteViewOnUserFilterEdit).+ activeViewId={viewControllers.selectedViewId}onApplyView={viewControllers.handleSetViewId}applyViewState={viewControllers.applyViewState}onPreviewView={previewViewInSearchBar}diff --git a/web/src/features/events/lib/demoteViewOnUserFilterEdit.ts b/web/src/features/events/lib/demoteViewOnUserFilterEdit.tsnew file mode 100644index 0000000000..dbb7fa1abd--- /dev/null+++ b/web/src/features/events/lib/demoteViewOnUserFilterEdit.ts@@ -0,0 +1,59 @@+import isEqual from "lodash/isEqual";+import { type FilterState } from "@langfuse/shared";+import { type UrlUpdateType } from "use-query-params";+import { isSystemPresetId } from "@/src/components/table/table-view-presets/components/data-table-view-presets-drawer";++export type ViewDemotionControllers = {+ selectedViewId: string | null;+ handleSetViewId: (+ viewId: string | null,+ options?: { updateType?: UrlUpdateType },+ ) => void;+};++export type ExplicitFilterStateChange = {+ previousFilters: FilterState;+ nextFilters: FilterState;+ origin: "user" | "saved_view" | "system";+};++/**+ * A user-origin filter edit diverges the table from an active SYSTEM preset,+ * so demote it β otherwise the session-storage restore resurrects the+ * just-edited filters on the next clean-URL mount, with the chip staying lit+ * (LFE-14699). System presets are code-defined with no "Update view" flow, so+ * a full deselect is safe (chip unlights, URL + session storage cleared,+ * `replaceIn` so Back does not bounce, LFE-10715).+ *+ * The decision keys off `selectedViewId` (the URL `?viewId`) ONLY β never the+ * sessionStorage-backed `appliedViewId`. The stored id is deliberately not+ * synced when a link with explicit table state is opened+ * (hasExplicitTableStateInUrl), so it can go stale: chip applied earlier in+ * the tab β user opens a saved view's permalink β stored id still names the+ * preset while the URL names the user view. Keying off the stale stored id+ * would strip the user view's `?viewId` on the next edit. Every intended+ * demotion path (chip apply, session restore) sets the URL param, so the URL+ * is both sufficient and authoritative.+ *+ * Deliberately scoped to system presets: USER-SAVED views keep today's+ * behavior wholesale. Demoting one by dropping only its session restore+ * degrades "Update view" β `appliedViewId === selectedViewId` is the+ * load-bearing column-trust signal (LFE-10486), and breaking it silently+ * reverts live column edits to the view's stored snapshot on the next update.+ * Extending demotion to user-saved views first needs the session-restore+ * signal decoupled from the column-trust signal.+ */+export function demoteViewOnUserFilterEdit(+ change: ExplicitFilterStateChange,+ controllers: ViewDemotionControllers | null,+): void {+ if (change.origin !== "user") return;+ // A no-op write (e.g. re-committing unchanged search-bar text) is not a+ // divergence. Relies on every system preset's filters surviving the+ // search-bar grammar round-trip deep-equal β guarded by+ // systemPresetSearchBarRoundTrip.clienttest.ts.+ if (isEqual(change.previousFilters, change.nextFilters)) return;+ if (!controllers) return;+ if (!isSystemPresetId(controllers.selectedViewId)) return;+ controllers.handleSetViewId(null, { updateType: "replaceIn" });+}diff --git a/web/src/features/events/presetDemotionOnUserEdit.clienttest.tsx b/web/src/features/events/presetDemotionOnUserEdit.clienttest.tsxnew file mode 100644index 0000000000..d58205acff--- /dev/null+++ b/web/src/features/events/presetDemotionOnUserEdit.clienttest.tsx@@ -0,0 +1,476 @@+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import {+ TableViewPresetTableName,+ encodeFiltersGeneric,+ type FilterState,+ type TableViewPresetState,+} from "@langfuse/shared";+import { useCallback, useRef } from "react";+import { useSidebarFilterState } from "../filters/hooks/useSidebarFilterState";+import type { FilterConfig } from "../filters/lib/filter-config";+import { useTableViewManager } from "../../components/table/table-view-presets/hooks/useTableViewManager";+import {+ demoteViewOnUserFilterEdit,+ type ViewDemotionControllers,+} from "./lib/demoteViewOnUserFilterEdit";++// LFE-14699: applying a system preset chip (e.g. "Latency over 10s") writes+// `?viewId` to the URL AND to sessionStorage. Deleting the preset's filter+// used to clear only the filter layer β the stored viewId survived, so the+// next clean-URL mount ("Priority 1: Session storage" bootstrap) re-fetched+// the preset and resurrected the filter the user just deleted, with the chip+// staying lit the whole time. A user-origin filter edit must fully demote an+// active SYSTEM preset (URL + session storage). User-saved views are+// deliberately untouched (see demoteViewOnUserFilterEdit).++const mockUseRouter = vi.fn();+const mockCapture = vi.fn();+const mockGetDefaultUseQuery = vi.fn();+const mockGetByIdUseQuery = vi.fn();++const queryParamStore = new Map<string, unknown>();++/** Every URL write performed through the use-query-params setter, in order. */+const urlParamWrites: Array<{+ key: string;+ value: unknown;+ updateType: string | undefined;+}> = [];++vi.mock("next/router", () => ({+ useRouter: () => mockUseRouter(),+}));++vi.mock("posthog-js/react", () => ({+ usePostHog: () => ({+ capture: mockCapture,+ }),+}));++vi.mock(+ "../../components/table/table-view-presets/components/data-table-view-presets-drawer",+ () => ({+ isSystemPresetId: (id: string | undefined | null) =>+ !!id?.startsWith("__langfuse_"),+ }),+);++vi.mock("../../utils/api", () => ({+ api: {+ TableViewPresets: {+ getDefault: {+ useQuery: (...args: unknown[]) => mockGetDefaultUseQuery(...args),+ },+ getById: {+ useQuery: (...args: unknown[]) => mockGetByIdUseQuery(...args),+ },+ },+ },+}));++vi.mock("use-query-params", async () => {+ const React = require("react");+ const actual = await vi.importActual("use-query-params");++ const StringParam = { __type: "string" } as const;++ return {+ ...actual,+ StringParam,+ useQueryParam: (key: string) => {+ const initialValue = queryParamStore.has(key)+ ? queryParamStore.get(key)+ : null;+ const [value, setValue] = React.useState(initialValue);++ const setQueryValue = React.useCallback(+ (+ next: unknown | ((previous: unknown) => unknown) | null | undefined,+ updateType?: string,+ ) => {+ const previous = queryParamStore.has(key)+ ? queryParamStore.get(key)+ : null;+ const resolved = typeof next === "function" ? next(previous) : next;++ urlParamWrites.push({ key, value: resolved, updateType });++ if (resolved === null || resolved === undefined || resolved === "") {+ queryParamStore.delete(key);+ setValue(null);+ return;+ }++ queryParamStore.set(key, resolved);+ setValue(resolved);+ },+ [key],+ );++ return [value, setQueryValue];+ },+ };+});++const PROJECT_ID = "project-1";+const PRESET_ID = "__langfuse_latency_over_10s";+const USER_VIEW_ID = "view-1";+const VIEW_ID_STORAGE_KEY = `${TableViewPresetTableName.ObservationsEvents}-${PROJECT_ID}-viewId`;++const TEST_FILTER_CONFIG: FilterConfig = {+ tableName: "traces",+ columnDefinitions: [+ {+ id: "name",+ name: "Name",+ type: "stringOptions",+ options: [],+ internal: "name",+ },+ ],+ facets: [+ {+ type: "categorical",+ column: "name",+ label: "Name",+ },+ ],+};++const PRESET_FILTERS: FilterState = [+ {+ column: "name",+ type: "stringOptions",+ operator: "any of",+ value: ["checkout"],+ },+];++const EXTRA_FILTERS: FilterState = [+ ...PRESET_FILTERS,+ {+ column: "name",+ type: "stringOptions",+ operator: "none of",+ value: ["search"],+ },+];++const PRESET_VIEW_STATE: TableViewPresetState = {+ filters: PRESET_FILTERS,+ orderBy: null,+ columnOrder: [],+ columnVisibility: {},+ searchQuery: "",+};++const PRESET_VIEW_DATA = {+ id: PRESET_ID,+ name: "Latency over 10s",+ tableName: TableViewPresetTableName.ObservationsEvents,+ ...PRESET_VIEW_STATE,+};++const storedViewId = () => {+ const raw = sessionStorage.getItem(VIEW_ID_STORAGE_KEY);+ return raw === null ? null : JSON.parse(raw);+};++/** Mirrors the EventsTable wiring: sidebar filter state with the demotion+ * callback (reading late-bound view controllers through a ref), and the view+ * manager applying saved-view filters with origin "saved_view". */+function Harness() {+ const viewControllersRef = useRef<ViewDemotionControllers | null>(null);++ const queryFilter = useSidebarFilterState(+ TEST_FILTER_CONFIG,+ { name: ["checkout", "search"] },+ {+ stateLocation: "urlAndSessionStorage",+ sessionFilterContextId: PROJECT_ID,+ onExplicitFilterStateChange: (change) =>+ demoteViewOnUserFilterEdit(change, viewControllersRef.current),+ },+ );++ const queryFilterRef = useRef(queryFilter);+ queryFilterRef.current = queryFilter;+ const setSavedViewFiltersWrapper = useCallback(+ (filters: FilterState) =>+ queryFilterRef.current.setFilterState(filters, { origin: "saved_view" }),+ [],+ );++ const { selectedViewId, appliedViewId, handleSetViewId, applyViewState } =+ useTableViewManager({+ tableName: TableViewPresetTableName.ObservationsEvents,+ projectId: PROJECT_ID,+ stateUpdaters: {+ setFilters: setSavedViewFiltersWrapper,+ setColumnOrder: () => {},+ setColumnVisibility: () => {},+ },+ validationContext: {+ columns: [],+ filterColumnDefinition: TEST_FILTER_CONFIG.columnDefinitions,+ },+ currentFilterState: queryFilter.explicitFilterState,+ allowBackendSystemPresets: true,+ });+ viewControllersRef.current = {+ selectedViewId,+ handleSetViewId,+ };++ return (+ <div>+ <div data-testid="selected-view-id">{selectedViewId ?? "null"}</div>+ <div data-testid="applied-view-id">{appliedViewId ?? "null"}</div>+ <pre data-testid="explicit-state">+ {JSON.stringify(queryFilter.explicitFilterState)}+ </pre>+ <button+ onClick={() => {+ // Mirrors a CategoryPresetChips row click.+ handleSetViewId(PRESET_ID);+ applyViewState(PRESET_VIEW_STATE, {+ trigger: "system_preset",+ viewId: PRESET_ID,+ });+ }}+ >+ apply-preset+ </button>+ <button+ onClick={() => {+ // Mirrors the saved-views drawer's handleSelectView.+ handleSetViewId(USER_VIEW_ID);+ applyViewState(PRESET_VIEW_STATE, {+ trigger: "select",+ viewId: USER_VIEW_ID,+ });+ }}+ >+ apply-user-view+ </button>+ <button onClick={() => queryFilter.setFilterState([])}>+ user-clear-filters+ </button>+ <button onClick={() => queryFilter.setFilterState(EXTRA_FILTERS)}>+ user-add-filter+ </button>+ <button+ onClick={() =>+ queryFilter.setFilterState(queryFilterRef.current.explicitFilterState)+ }+ >+ user-recommit-same+ </button>+ </div>+ );+}++const applyPresetAndAssertActive = async () => {+ fireEvent.click(screen.getByRole("button", { name: "apply-preset" }));++ // The saved_view-origin apply must not demote itself.+ await waitFor(() => {+ expect(screen.getByTestId("selected-view-id").textContent).toBe(PRESET_ID);+ expect(screen.getByTestId("applied-view-id").textContent).toBe(PRESET_ID);+ expect(screen.getByTestId("explicit-state").textContent).toContain(+ "checkout",+ );+ expect(storedViewId()).toBe(PRESET_ID);+ });+};++describe("system preset demotion on user filter edits (LFE-14699)", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ sessionStorage.clear();+ queryParamStore.clear();+ urlParamWrites.length = 0;++ mockUseRouter.mockImplementation(() => ({+ isReady: true,+ query: Object.fromEntries(queryParamStore),+ }));+ mockGetDefaultUseQuery.mockReturnValue({+ data: null,+ isLoading: false,+ });+ mockGetByIdUseQuery.mockImplementation(+ (input: { viewId?: string }, options?: { enabled?: boolean }) => {+ if (options?.enabled && input?.viewId === PRESET_ID) {+ return {+ data: PRESET_VIEW_DATA,+ error: null,+ isSuccess: true,+ isError: false,+ };+ }+ return {+ data: undefined,+ error: null,+ isSuccess: false,+ isError: false,+ };+ },+ );+ });++ it("restores a stored preset viewId on a clean-URL mount (the resurrection path demotion must stop)", async () => {+ sessionStorage.setItem(VIEW_ID_STORAGE_KEY, JSON.stringify(PRESET_ID));++ render(<Harness />);++ await waitFor(() => {+ expect(screen.getByTestId("selected-view-id").textContent).toBe(+ PRESET_ID,+ );+ expect(screen.getByTestId("explicit-state").textContent).toContain(+ "checkout",+ );+ });+ });++ it("fully demotes an active system preset on a user filter edit; a remount does not re-apply it", async () => {+ const { unmount } = render(<Harness />);+ await applyPresetAndAssertActive();++ fireEvent.click(screen.getByRole("button", { name: "user-clear-filters" }));++ await waitFor(() => {+ expect(screen.getByTestId("selected-view-id").textContent).toBe("null");+ expect(screen.getByTestId("applied-view-id").textContent).toBe("null");+ expect(storedViewId()).toBe(null);+ });++ // The demotion is a programmatic correction: replace, not push+ // (LFE-10715 β Back must not bounce off a resurrected viewId).+ expect(urlParamWrites).toContainEqual({+ key: "viewId",+ value: null,+ updateType: "replaceIn",+ });++ // Clean-URL remount (nav to Traces/Observations): nothing restores.+ unmount();+ expect(queryParamStore.has("viewId")).toBe(false);+ render(<Harness />);++ await waitFor(() => {+ expect(screen.getByTestId("selected-view-id").textContent).toBe("null");+ });+ expect(screen.getByTestId("explicit-state").textContent).not.toContain(+ "checkout",+ );+ expect(storedViewId()).toBe(null);+ });++ it("demotes an active system preset when the user adds a filter on top of it", async () => {+ render(<Harness />);+ await applyPresetAndAssertActive();++ fireEvent.click(screen.getByRole("button", { name: "user-add-filter" }));++ await waitFor(() => {+ expect(screen.getByTestId("selected-view-id").textContent).toBe("null");+ expect(storedViewId()).toBe(null);+ });+ });++ it("does not demote on a no-op user write (unchanged filters)", async () => {+ render(<Harness />);+ await applyPresetAndAssertActive();++ fireEvent.click(screen.getByRole("button", { name: "user-recommit-same" }));++ await waitFor(() => {+ expect(screen.getByTestId("selected-view-id").textContent).toBe(+ PRESET_ID,+ );+ expect(storedViewId()).toBe(PRESET_ID);+ });+ });++ it("does not demote a user-saved view on a user filter edit (system presets only)", async () => {+ // Deliberate scoping: demoting a user-saved view (even session-only)+ // breaks the appliedViewId === selectedViewId column-trust signal the+ // drawer's "Update view" relies on (LFE-10486) β user views keep today's+ // behavior wholesale.+ render(<Harness />);++ fireEvent.click(screen.getByRole("button", { name: "apply-user-view" }));++ await waitFor(() => {+ expect(screen.getByTestId("selected-view-id").textContent).toBe(+ USER_VIEW_ID,+ );+ expect(storedViewId()).toBe(USER_VIEW_ID);+ });++ fireEvent.click(screen.getByRole("button", { name: "user-clear-filters" }));++ await waitFor(() => {+ expect(screen.getByTestId("explicit-state").textContent).toBe("[]");+ });+ // URL viewId AND session restore both stay: user views are untouched.+ expect(screen.getByTestId("selected-view-id").textContent).toBe(+ USER_VIEW_ID,+ );+ expect(screen.getByTestId("applied-view-id").textContent).toBe(+ USER_VIEW_ID,+ );+ expect(storedViewId()).toBe(USER_VIEW_ID);+ });++ it("ignores a stale sessionStorage preset id when the URL names a user view", async () => {+ // sessionStorage's storedViewId is deliberately NOT synced when a link+ // with explicit table state is opened (hasExplicitTableStateInUrl), so it+ // can go stale: chip applied earlier in the tab β user opens a saved+ // view's permalink. Keying the demotion off the stale stored id would+ // strip the user view's ?viewId on the next edit β the decision must read+ // the URL's selectedViewId only.+ sessionStorage.setItem(VIEW_ID_STORAGE_KEY, JSON.stringify(PRESET_ID));+ queryParamStore.set("viewId", USER_VIEW_ID);+ queryParamStore.set("filter", encodeFiltersGeneric(PRESET_FILTERS));++ render(<Harness />);++ await waitFor(() => {+ expect(screen.getByTestId("selected-view-id").textContent).toBe(+ USER_VIEW_ID,+ );+ expect(screen.getByTestId("explicit-state").textContent).toContain(+ "checkout",+ );+ });++ fireEvent.click(screen.getByRole("button", { name: "user-add-filter" }));++ await waitFor(() => {+ expect(screen.getByTestId("explicit-state").textContent).toContain(+ "search",+ );+ });+ // The user view's URL provenance survives; the demotion never fired.+ expect(screen.getByTestId("selected-view-id").textContent).toBe(+ USER_VIEW_ID,+ );+ expect(queryParamStore.get("viewId")).toBe(USER_VIEW_ID);+ expect(+ urlParamWrites.filter(+ (write) => write.key === "viewId" && write.value === null,+ ),+ ).toEqual([]);+ // The two signals diverge for the whole visit: sessionStorage still names+ // the stale preset while the URL names the user view. selectedViewId is+ // what the events table feeds CategoryPresetChips as activeViewId β the+ // stale stored id must not light a chip either.+ expect(storedViewId()).toBe(PRESET_ID);+ expect(screen.getByTestId("selected-view-id").textContent).not.toBe(+ PRESET_ID,+ );+ });+});diff --git a/web/src/features/events/systemPresetSearchBarRoundTrip.clienttest.ts b/web/src/features/events/systemPresetSearchBarRoundTrip.clienttest.tsnew file mode 100644index 0000000000..b65bab33fe--- /dev/null+++ b/web/src/features/events/systemPresetSearchBarRoundTrip.clienttest.ts@@ -0,0 +1,68 @@+import isEqual from "lodash/isEqual";+import {+ TableViewPresetTableName,+ getSystemTableViewPresets,+ type FilterState,+} from "@langfuse/shared";+import { filterStateToQueryText } from "../search-bar/lib/filter-state-to-query";+import { planCommit } from "../search-bar/lib/commit";++// Catalog guard for the LFE-14699 demote-on-user-edit no-op check+// (demoteViewOnUserFilterEdit): a user-origin filter write only demotes the+// active system preset when the filters actually CHANGED (lodash isEqual).+// That guard is only sound if every system preset's filters survive the+// search-bar grammar round-trip (filterStateToQueryText β planCommit β+// mergeWithSkipped) deep-equal β the bar re-commits the derived text on+// enter/blur, so a preset whose filters come back in a different shape would+// 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 =`,+// 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.++/** Mirrors filterIdentity + mergeWithSkipped in useEventsSearchBar: filters+ * the grammar can't represent are re-attached after a commit (no-silent-drop+ * contract), deduped by column+key against what the commit produced. */+const filterIdentity = (f: FilterState[number]): string =>+ `${f.column}\u0000${"key" in f ? f.key : ""}`;++const mergeWithSkipped = (+ produced: FilterState,+ skipped: FilterState,+): FilterState => {+ const producedKeys = new Set(produced.map(filterIdentity));+ const preserved = skipped.filter((f) => !producedKeys.has(filterIdentity(f)));+ return preserved.length > 0 ? [...produced, ...preserved] : produced;+};++const allPresets = Object.values(TableViewPresetTableName).flatMap(+ (tableName) => getSystemTableViewPresets(tableName),+);++describe("system preset filters round-trip the search-bar grammar (LFE-14699 demote guard)", () => {+ it("catalog is non-empty (guard cannot go vacuous)", () => {+ expect(allPresets.length).toBeGreaterThan(0);+ });++ for (const preset of allPresets) {+ it(`${preset.id} (${preset.name}) re-commits deep-equal`, () => {+ const { text, skippedFilters } = filterStateToQueryText(+ preset.state.filters,+ );++ // No ScoreTypeContext: no preset uses scores.* filters today. If one+ // does and fails to lower here, thread the score types through instead+ // of removing the preset from this guard.+ const commit = planCommit(text);+ expect(commit.status).toBe("committed");+ if (commit.status !== "committed") return;++ const merged = mergeWithSkipped(commit.filters, skippedFilters);+ expect(merged).toEqual(preset.state.filters);+ // Exactly the demote guard's comparison semantics.+ expect(isEqual(merged, preset.state.filters)).toBe(true);+ });+ }+});