🪢 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(filters): preserve sidebar edits and show selected views (#17308)
Nikita Kabardin01ab340488e3
diff --git a/web/src/components/table/data-table-controls.clienttest.tsx b/web/src/components/table/data-table-controls.clienttest.tsxindex ed4c94b878..b23434606d 100644--- a/web/src/components/table/data-table-controls.clienttest.tsx+++ b/web/src/components/table/data-table-controls.clienttest.tsx@@ -1,15 +1,25 @@-import { fireEvent, render, screen } from "@testing-library/react";+import { act, fireEvent, render, screen } from "@testing-library/react";import * as AccordionPrimitive from "@radix-ui/react-accordion";+import { eventsTableCols, type FilterState } from "@langfuse/shared";+import { useStore } from "zustand";import { TooltipProvider } from "@/src/components/ui/tooltip";import {CategoricalFacet,DataTableControls,type QueryFilter,} from "./data-table-controls";-import type {- CategoricalUIFilter,- UIFilter,+import {+ useSidebarFilterState,+ type CategoricalUIFilter,+ type UIFilter,} from "@/src/features/filters/hooks/useSidebarFilterState";+import type { FilterConfig } from "@/src/features/filters/lib/filter-config";+import { useEventsSearchBar } from "@/src/features/search-bar/hooks/useEventsSearchBar";++vi.mock("use-query-params", async () => ({+ ...(await vi.importActual("use-query-params")),+ useQueryParam: () => [null, () => {}] as const,+}));// Spy on the posthog client so capture calls (event name + payload) can be// asserted at the wrapper seam.@@ -33,6 +43,134 @@ beforeAll(() => {Element.prototype.scrollIntoView = vi.fn();});+describe("delayed sidebar edits and search-bar commits", () => {+ const config: FilterConfig = {+ tableName: "observations-events",+ columnDefinitions: eventsTableCols,+ defaultExpanded: ["statusMessage", "latency"],+ facets: [+ { type: "string", column: "statusMessage", label: "Status Message" },+ {+ type: "numeric",+ column: "latency",+ label: "Latency",+ min: 0,+ max: 100,+ },+ { type: "categorical", column: "traceName", label: "Trace Name" },+ ],+ };++ function Harness() {+ const queryFilter = useSidebarFilterState(+ config,+ {},+ { stateLocation: "memory" },+ );+ const bar = useEventsSearchBar({+ projectId: "filter-test-project",+ tableName: config.tableName,+ enabled: true,+ filterState: queryFilter.searchBarFilterState,+ setFilterState: queryFilter.setFilterState,+ searchQuery: null,+ searchType: ["id", "content"],+ setSearchQuery: () => {},+ setSearchType: () => {},+ observed: undefined,+ });+ const draft = useStore(bar.store, (state) => state.draft);++ return (+ <>+ <DataTableControls queryFilter={queryFilter} />+ <button+ onClick={() => {+ bar.store.getState().actions.setDraft("-traceName:*turn*");+ bar.commit();+ }}+ >+ Commit trace filter+ </button>+ <button onClick={queryFilter.clearAll}>Reset filters</button>+ <pre data-testid="applied-filters">+ {JSON.stringify(queryFilter.filterState)}+ </pre>+ <pre data-testid="bar-draft">{draft}</pre>+ </>+ );+ }++ it.each([+ ["string", "string-statusMessage", "timeout", "statusMessage"],+ ["numeric", "min-latency", "10", "latency"],+ ])(+ "preserves the committed trace filter when a delayed %s edit lands",+ (_, inputId, value, column) => {+ vi.useFakeTimers();+ sessionStorage.clear();+ const { container, unmount } = render(<Harness />, {+ wrapper: TooltipProvider,+ });+ const appliedFilters = (): FilterState =>+ JSON.parse(screen.getByTestId("applied-filters").textContent ?? "[]");+ try {+ fireEvent.change(container.querySelector(`#${inputId}`)!, {+ target: { value },+ });+ fireEvent.click(+ screen.getByRole("button", { name: "Commit trace filter" }),+ );++ const traceFilter = {+ column: "traceName",+ type: "string",+ operator: "does not contain",+ value: "turn",+ };+ expect(appliedFilters()).toEqual([traceFilter]);+ expect(screen.getByTestId("bar-draft")).toHaveTextContent(+ "-traceName:*turn*",+ );++ act(() => vi.advanceTimersByTime(500));++ expect.soft(appliedFilters()).toContainEqual(traceFilter);+ expect(appliedFilters()).toEqual(+ expect.arrayContaining([expect.objectContaining({ column })]),+ );+ expect+ .soft(screen.getByTestId("bar-draft"))+ .toHaveTextContent("-traceName:*turn*");++ fireEvent.change(container.querySelector(`#${inputId}`)!, {+ target: { value: value === "10" ? "20" : "retry" },+ });+ fireEvent.click(screen.getByRole("button", { name: "Reset filters" }));+ expect(appliedFilters()).toEqual([]);+ act(() => vi.advanceTimersByTime(500));+ expect(appliedFilters()).toEqual([]);++ fireEvent.click(+ screen.getByRole("button", { name: "Commit trace filter" }),+ );+ fireEvent.change(container.querySelector(`#${inputId}`)!, {+ target: { value },+ });+ fireEvent.click(screen.getByRole("button", { name: "Reset filters" }));+ act(() => vi.advanceTimersByTime(500));+ expect(appliedFilters()).toEqual([]);+ expect(+ container.querySelector<HTMLInputElement>(`#${inputId}`)?.value,+ ).toBe("");+ } finally {+ unmount();+ vi.useRealTimers();+ }+ },+ );+});+describe("CategoricalFacet", () => {it("uses a custom option hover title", () => {render(@@ -453,6 +591,7 @@ describe("DataTableControls facet ordering", () => {expanded: [],onExpandedChange: () => {},clearAll: () => {},+ draftResetKey: 0,isFiltered: filters.some((f) => f.isActive),setFilterState: () => {},});@@ -861,6 +1000,7 @@ describe("DataTableControls blocked facets (LFE-11040)", () => {expanded,onExpandedChange: () => {},clearAll: () => {},+ draftResetKey: 0,isFiltered: filters.some((f) => f.isActive),setFilterState: () => {},});@@ -972,6 +1112,7 @@ describe("DataTableControls facet catalog", () => {expanded: [],onExpandedChange: () => {},clearAll: () => {},+ draftResetKey: 0,isFiltered: filters.some((f) => f.isActive),setFilterState: () => {},});@@ -1064,6 +1205,7 @@ describe("DataTableControls facet-name search", () => {expanded: [],onExpandedChange: () => {},clearAll: () => {},+ draftResetKey: 0,isFiltered: filters.some((f) => f.isActive),setFilterState: () => {},});diff --git a/web/src/components/table/data-table-controls.tsx b/web/src/components/table/data-table-controls.tsxindex ccad8a417a..22a986fee0 100644--- a/web/src/components/table/data-table-controls.tsx+++ b/web/src/components/table/data-table-controls.tsx@@ -173,6 +173,8 @@ export interface QueryFilter {expanded: string[];onExpandedChange: (value: string[]) => void;clearAll: () => void;+ /** Explicit Clear all discards facet drafts even when applied values are unchanged. */+ draftResetKey: number;isFiltered: boolean;setFilterState: (filters: FilterState) => void;/** v3-vs-v4 analytics dimension of the surface (see useSidebarFilterState). */@@ -770,7 +772,7 @@ export function DataTableControls({}nodes.push(<div- key={filter.column}+ key={`${filter.column}:${queryFilter.draftResetKey}`}hidden={!visibleColumns.has(filter.column)}>{renderFacet(filter)}@@ -2076,15 +2078,18 @@ function NumericFacet({setLocalValue(value);}const timeoutRef = useRef<NodeJS.Timeout | null>(null);+ const onChangeRef = useRef(onChange);+ onChangeRef.current = onChange;+ const [appliedMin, appliedMax] = value;- // Cleanup timeout on unmount+ // An external reset or replacement cancels the pending draft.useEffect(() => {return () => {if (timeoutRef.current) {clearTimeout(timeoutRef.current);}};- }, []);+ }, [appliedMin, appliedMax]);const updateWithDebounce = (newValue: [number, number]) => {setLocalValue(newValue);@@ -2096,7 +2101,7 @@ function NumericFacet({// Set new timeouttimeoutRef.current = setTimeout(() => {- onChange(newValue);+ onChangeRef.current(newValue);}, 120);};@@ -2241,15 +2246,17 @@ function StringFacet({setLocalValue(value);}const timeoutRef = useRef<NodeJS.Timeout | null>(null);+ const onChangeRef = useRef(onChange);+ onChangeRef.current = onChange;- // Cleanup timeout on unmount+ // An external reset or replacement cancels the pending draft.useEffect(() => {return () => {if (timeoutRef.current) {clearTimeout(timeoutRef.current);}};- }, []);+ }, [value]);const updateWithDebounce = (newValue: string) => {setLocalValue(newValue);@@ -2261,7 +2268,7 @@ function StringFacet({// Set new timeouttimeoutRef.current = setTimeout(() => {- onChange(newValue);+ onChangeRef.current(newValue);}, 500);};diff --git a/web/src/components/table/key-value-filter-builder.clienttest.tsx b/web/src/components/table/key-value-filter-builder.clienttest.tsxindex 41cbce3a54..bc56b833c2 100644--- a/web/src/components/table/key-value-filter-builder.clienttest.tsx+++ b/web/src/components/table/key-value-filter-builder.clienttest.tsx@@ -1,8 +1,73 @@import { fireEvent, render, screen } from "@testing-library/react";+import { useState } from "react";+import type { FilterState } from "@langfuse/shared";+import { applyKeyedFilterEntries } from "@/src/features/filters/lib/sidebar-filter-actions";import { KeyValueFilterBuilder } from "./key-value-filter-builder";const noop = () => {};+function MetadataBuilderHarness() {+ const [filters, setFilters] = useState<FilterState>([+ {+ column: "metadata",+ type: "stringObject",+ key: "region",+ operator: "=",+ value: "eu",+ },+ {+ column: "metadata",+ type: "stringObject",+ key: "team",+ operator: "=",+ value: "core",+ },+ ]);++ return (+ <>+ <KeyValueFilterBuilder+ mode="string"+ activeFilters={filters.flatMap((filter) =>+ filter.type === "stringObject" &&+ (filter.operator === "=" ||+ filter.operator === "contains" ||+ filter.operator === "does not contain")+ ? [+ {+ key: filter.key,+ operator: filter.operator,+ value: filter.value,+ },+ ]+ : [],+ )}+ onChange={(entries) =>+ setFilters((current) =>+ applyKeyedFilterEntries(current, "metadata", {+ kind: "stringObject",+ entries,+ }),+ )+ }+ />+ <button+ onClick={() =>+ setFilters((current) =>+ current.filter(+ (filter) => !("key" in filter && filter.key === "region"),+ ),+ )+ }+ >+ Remove region externally+ </button>+ <button onClick={() => setFilters([])}>Clear externally</button>+ <output data-testid="applied-filters">{JSON.stringify(filters)}</output>+ </>+ );+}+describe("KeyValueFilterBuilder", () => {beforeAll(() => {vi.stubGlobal(@@ -65,9 +130,6 @@ describe("KeyValueFilterBuilder", () => {fireEvent.change(screen.getByPlaceholderText("Key"), {target: { value: "draft-key" },});- fireEvent.change(screen.getByPlaceholderText("Value"), {- target: { value: "draft-value" },- });rerender(<KeyValueFilterBuilder@@ -77,6 +139,41 @@ describe("KeyValueFilterBuilder", () => {/>,);- expect(screen.getByDisplayValue("draft-value")).toBeInTheDocument();+ expect(screen.getByDisplayValue("draft-key")).toBeInTheDocument();+ });++ it("adopts external removals without reviving removed rows or losing incomplete edits", () => {+ render(<MetadataBuilderHarness />);+ fireEvent.click(screen.getByText("Add filter"));+ fireEvent.change(screen.getAllByPlaceholderText("Key")[2], {+ target: { value: "draft-key" },+ });++ fireEvent.click(screen.getByText("Remove region externally"));+ expect(screen.queryByDisplayValue("region")).not.toBeInTheDocument();+ expect(screen.getByDisplayValue("draft-key")).toBeInTheDocument();++ const value = screen.getByDisplayValue("core");+ value.focus();+ fireEvent.change(value, { target: { value: "" } });+ expect(screen.getByDisplayValue("team")).toBeInTheDocument();+ expect(value).toHaveFocus();+ fireEvent.change(value, { target: { value: "platform" } });+ expect(value).toHaveFocus();+ expect(+ JSON.parse(screen.getByTestId("applied-filters").textContent!),+ ).toEqual([+ {+ column: "metadata",+ type: "stringObject",+ key: "team",+ operator: "=",+ value: "platform",+ },+ ]);++ fireEvent.click(screen.getByText("Clear externally"));+ expect(screen.queryByDisplayValue("team")).not.toBeInTheDocument();+ expect(screen.getByDisplayValue("draft-key")).toBeInTheDocument();});});diff --git a/web/src/components/table/key-value-filter-builder.tsx b/web/src/components/table/key-value-filter-builder.tsxindex 260e3329c3..00abe3f63d 100644--- a/web/src/components/table/key-value-filter-builder.tsx+++ b/web/src/components/table/key-value-filter-builder.tsx@@ -74,6 +74,12 @@ type KeyValueFilterBuilderProps =keyPlaceholder?: string;};+type KeyedFilterEntry =+ | KeyValueFilterEntry+ | NumericKeyValueFilterEntry+ | BooleanKeyValueFilterEntry+ | StringKeyValueFilterEntry;+// Map operators to human-readable labelsconst NUMERIC_OPERATOR_LABELS = {"=": "equals",@@ -256,7 +262,6 @@ export function KeyValueFilterBuilder(props: KeyValueFilterBuilderProps) {keyOptions,keyLevels,activeFilters,- onChange,keyPlaceholder = "Key",} = props;const availableValues = mode === "categorical" ? props.availableValues : {};@@ -266,15 +271,40 @@ export function KeyValueFilterBuilder(props: KeyValueFilterBuilderProps) {// Track which popover is open (by index)const [openPopoverIndex, setOpenPopoverIndex] = useState<number | null>(null);- // Local UI state for filter rows (includes incomplete filters)- // Initialize once from activeFilters but don't sync on every change- // This allows incomplete filter rows to persist in the UI while being edited- const [localFilters, setLocalFilters] = useState<- | KeyValueFilterEntry[]- | NumericKeyValueFilterEntry[]- | BooleanKeyValueFilterEntry[]- | StringKeyValueFilterEntry[]- >(() => (activeFilters.length > 0 ? activeFilters : []));+ // Applied rows belong to the parent; only incomplete edits stay local.+ const [draftFilters, setDraftFilters] = useState<+ { index: number; filter: KeyedFilterEntry }[]+ >([]);+ const localFilters: KeyedFilterEntry[] = [...activeFilters];+ for (const draft of draftFilters) {+ localFilters.splice(draft.index, 0, draft.filter);+ }++ const isComplete = (filter: KeyedFilterEntry) =>+ !!filter.key &&+ (Array.isArray(filter.value)+ ? filter.value.length > 0+ : typeof filter.value === "string"+ ? filter.value.trim() !== ""+ : true);++ const updateFilters = (filters: KeyedFilterEntry[]) => {+ setDraftFilters(+ filters.flatMap((filter, index) =>+ isComplete(filter) ? [] : [{ index, filter }],+ ),+ );+ const completeFilters = filters.filter(isComplete);+ if (props.mode === "categorical") {+ props.onChange(completeFilters as KeyValueFilterEntry[]);+ } else if (props.mode === "numeric") {+ props.onChange(completeFilters as NumericKeyValueFilterEntry[]);+ } else if (props.mode === "boolean") {+ props.onChange(completeFilters as BooleanKeyValueFilterEntry[]);+ } else {+ props.onChange(completeFilters as StringKeyValueFilterEntry[]);+ }+ };const handleFilterChange = (index: number,@@ -284,108 +314,26 @@ export function KeyValueFilterBuilder(props: KeyValueFilterBuilderProps) {| Partial<BooleanKeyValueFilterEntry>| Partial<StringKeyValueFilterEntry>,) => {- // TypeScript can't narrow the union array type automatically, so we narrow explicitly based on mode- if (mode === "categorical") {- const filters = localFilters as KeyValueFilterEntry[];- const newFilters = [...filters];- newFilters[index] = {- ...newFilters[index],- ...updates,- } as KeyValueFilterEntry;- setLocalFilters(newFilters);- (onChange as (filters: KeyValueFilterEntry[]) => void)(newFilters);- } else if (mode === "numeric") {- const filters = localFilters as NumericKeyValueFilterEntry[];- const newFilters = [...filters];- newFilters[index] = {- ...newFilters[index],- ...updates,- } as NumericKeyValueFilterEntry;- setLocalFilters(newFilters);- (onChange as (filters: NumericKeyValueFilterEntry[]) => void)(newFilters);- } else if (mode === "boolean") {- const filters = localFilters as BooleanKeyValueFilterEntry[];- const newFilters = [...filters];- newFilters[index] = {- ...newFilters[index],- ...updates,- } as BooleanKeyValueFilterEntry;- setLocalFilters(newFilters);- (onChange as (filters: BooleanKeyValueFilterEntry[]) => void)(newFilters);- } else {- const filters = localFilters as StringKeyValueFilterEntry[];- const newFilters = [...filters];- newFilters[index] = {- ...newFilters[index],- ...updates,- } as StringKeyValueFilterEntry;- setLocalFilters(newFilters);- (onChange as (filters: StringKeyValueFilterEntry[]) => void)(newFilters);- }+ const filters = [...localFilters];+ filters[index] = { ...filters[index], ...updates } as KeyedFilterEntry;+ updateFilters(filters);};const handleAddFilter = () => {- if (mode === "categorical") {- const newFilter: KeyValueFilterEntry = {- key: "",- operator: "any of" as const,- value: [],- };- const filters = localFilters as KeyValueFilterEntry[];- const newFilters = [...filters, newFilter];- setLocalFilters(newFilters);- } else if (mode === "numeric") {- const newFilter: NumericKeyValueFilterEntry = {- key: "",- operator: "=" as const,- value: "",- };- const filters = localFilters as NumericKeyValueFilterEntry[];- const newFilters = [...filters, newFilter];- setLocalFilters(newFilters);- } else if (mode === "boolean") {- const newFilter: BooleanKeyValueFilterEntry = {- key: "",- operator: "=" as const,- value: "",- };- const filters = localFilters as BooleanKeyValueFilterEntry[];- const newFilters = [...filters, newFilter];- setLocalFilters(newFilters);- } else {- const newFilter: StringKeyValueFilterEntry = {- key: "",- operator: "=" as const,- value: "",- };- const filters = localFilters as StringKeyValueFilterEntry[];- const newFilters = [...filters, newFilter];- setLocalFilters(newFilters);- }+ setDraftFilters([+ ...draftFilters,+ {+ index: localFilters.length,+ filter:+ mode === "categorical"+ ? { key: "", operator: "any of", value: [] }+ : { key: "", operator: "=", value: "" },+ },+ ]);};const handleRemoveFilter = (index: number) => {- if (mode === "categorical") {- const filters = localFilters as KeyValueFilterEntry[];- const newFilters = filters.filter((_, i) => i !== index);- setLocalFilters(newFilters);- (onChange as (filters: KeyValueFilterEntry[]) => void)(newFilters);- } else if (mode === "numeric") {- const filters = localFilters as NumericKeyValueFilterEntry[];- const newFilters = filters.filter((_, i) => i !== index);- setLocalFilters(newFilters);- (onChange as (filters: NumericKeyValueFilterEntry[]) => void)(newFilters);- } else if (mode === "boolean") {- const filters = localFilters as BooleanKeyValueFilterEntry[];- const newFilters = filters.filter((_, i) => i !== index);- setLocalFilters(newFilters);- (onChange as (filters: BooleanKeyValueFilterEntry[]) => void)(newFilters);- } else {- const filters = localFilters as StringKeyValueFilterEntry[];- const newFilters = filters.filter((_, i) => i !== index);- setLocalFilters(newFilters);- (onChange as (filters: StringKeyValueFilterEntry[]) => void)(newFilters);- }+ updateFilters(localFilters.filter((_, i) => i !== index));};return (diff --git a/web/src/components/table/table-view-presets/README.md b/web/src/components/table/table-view-presets/README.mdindex 6df57a7c50..ce0c1eb95e 100644--- a/web/src/components/table/table-view-presets/README.md+++ b/web/src/components/table/table-view-presets/README.md@@ -10,6 +10,19 @@ Users can now:- Delete views they no longer need- Generate permalinks to share specific views+The My Views button displays only the selected custom view's name, including+a default applied on page load. Categorized patterns show their selection in+the pattern controls instead. `TableViewPresetsButton` owns this presentation;+the drawer resolves the name and default assignment from its existing queries.++On Tracing, editing filters, search, sorting, or columns clears the selected+view from the URL and session. No-op edits and automatic reconciliation preserve+selection. Incomplete sidebar inputs survive deselection; applying a view resets+them through `filterEditorResetKey`. A separate `viewUpdateTarget` keeps the+original view available for updating without marking it active, including the+column-provenance guard for shared links. It also preserves the edited working+view across reloads instead of reapplying a default.+## Robustness to Table ChangesThe table view presets system is designed to gracefully handle changes to table structure:diff --git a/web/src/components/table/table-view-presets/components/TableViewPresetsButton.stories.tsx b/web/src/components/table/table-view-presets/components/TableViewPresetsButton.stories.tsxnew file mode 100644index 0000000000..72560092f5--- /dev/null+++ b/web/src/components/table/table-view-presets/components/TableViewPresetsButton.stories.tsx@@ -0,0 +1,35 @@+import preview from "../../../../../.storybook/preview";+import { TableViewPresetsButton } from "./TableViewPresetsButton";++const meta = preview.meta({ component: TableViewPresetsButton });++export const Default = meta.story({+ args: { selectedView: null, count: 3 },+});++export const Selected = meta.story({+ args: {+ selectedView: { name: "Production errors", defaultLabel: null },+ count: 3,+ },+});++export const ProjectDefault = meta.story({+ args: {+ selectedView: {+ name: "Production traces",+ defaultLabel: "Project default",+ },+ count: 3,+ },+});++export const WithLongName = meta.story({+ args: {+ selectedView: {+ name: "Production agent traces with errors and high latency",+ defaultLabel: "Your default",+ },+ count: 3,+ },+});diff --git a/web/src/components/table/table-view-presets/components/TableViewPresetsButton.tsx b/web/src/components/table/table-view-presets/components/TableViewPresetsButton.tsxnew file mode 100644index 0000000000..ad6e3dc43a--- /dev/null+++ b/web/src/components/table/table-view-presets/components/TableViewPresetsButton.tsx@@ -0,0 +1,50 @@+import type { ComponentProps } from "react";+import { ChevronDown } from "lucide-react";+import { Button } from "@/src/components/ui/button";++type TableViewPresetsButtonProps = Pick<+ ComponentProps<typeof Button>,+ | "id"+ | "ref"+ | "onClick"+ | "onPointerDown"+ | "onKeyDown"+ | "aria-expanded"+ | "aria-controls"+ | "aria-haspopup"+> & {+ selectedView: {+ name: string;+ defaultLabel: "Your default" | "Project default" | null;+ } | null;+ count: number;+};++export function TableViewPresetsButton({+ selectedView,+ count,+ ...props+}: TableViewPresetsButtonProps) {+ const label = selectedView?.name ?? "My Views";+ const title = selectedView?.defaultLabel+ ? `${label} (${selectedView.defaultLabel})`+ : label;++ return (+ <Button+ {...props}+ variant={selectedView ? "default" : "outline"}+ className="max-w-64 gap-1.5"+ title={title}+ >+ <span className="truncate" title={title}>+ {label}+ </span>+ {selectedView ? (+ <ChevronDown className="h-4 w-4 shrink-0" aria-hidden />+ ) : (+ <span className="bg-input rounded-sm px-1 text-xs">{count}</span>+ )}+ </Button>+ );+}diff --git a/web/src/components/table/table-view-presets/components/data-table-view-presets-drawer.tsx b/web/src/components/table/table-view-presets/components/data-table-view-presets-drawer.tsxindex ee133857fc..1e86701884 100644--- a/web/src/components/table/table-view-presets/components/data-table-view-presets-drawer.tsx+++ b/web/src/components/table/table-view-presets/components/data-table-view-presets-drawer.tsx@@ -1,13 +1,5 @@import { Button } from "@/src/components/ui/button";-import {- X,- Plus,- ChevronDown,- Link,- MoreVertical,- Pen,- Lock,-} from "lucide-react";+import { X, Plus, Link, MoreVertical, Pen, Lock } from "lucide-react";import { Badge } from "@/src/components/ui/badge";import { LangfuseIcon } from "@/src/components/design-system/LangfuseIcon/LangfuseIcon";import {@@ -84,9 +76,9 @@ import { copyTextToClipboard } from "@/src/utils/clipboard";import { useUniqueNameValidation } from "@/src/hooks/useUniqueNameValidation";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";-import isEqual from "lodash/isEqual";import { useDefaultViewMutations } from "../hooks/useDefaultViewMutations";import { summarizeTableViewPreset } from "../lib/viewPreview";+import { TableViewPresetsButton } from "./TableViewPresetsButton";/*** Prefix for system preset IDs. These are page-specific presets defined in code@@ -116,21 +108,6 @@ const copyPermalinkAndToast = (href: string) => {);};-/** Recursively remove undefined values for consistent comparison */-function normalizeForComparison<T>(obj: T): T {- if (Array.isArray(obj)) {- return obj.map(normalizeForComparison) as T;- }- if (obj !== null && typeof obj === "object") {- return Object.fromEntries(- Object.entries(obj)- .filter(([, v]) => v !== undefined)- .map(([k, v]) => [k, normalizeForComparison(v)]),- ) as T;- }- return obj;-}-interface SystemPreset {id: string;name: string;@@ -161,6 +138,10 @@ interface TableViewPresetsDrawerContentProps {/** The view whose full state was actually applied this session (null on a* shared-link visit where the view is intentionally not applied). */appliedViewId: string | null;+ viewUpdateTarget?: {+ viewId: string;+ columnsApplied: boolean;+ } | null;handleSetViewId: (viewId: string | null) => void;applyViewState: (viewData: TableViewPresetState,@@ -266,20 +247,34 @@ export function TableViewPresetsDrawer({view.id === defaultAssignments?.userDefaultViewId ||view.id === defaultAssignments?.projectDefaultViewId,).length ?? 0;+ const selectedView =+ TableViewPresetsList?.find(+ // Categorized presets show their selection in the pattern controls.+ (view) => view.id === controllers.selectedViewId && !view.category,+ ) ??+ systemFilterPresets?.find((view) => view.id === controllers.selectedViewId);return (<TableViewPresetsDrawerRoot tableName={tableName}><DrawerTrigger asChild>- <Button variant="outline" id={triggerId} title="My Views">- <span>My Views</span>- {controllers.selectedViewId ? (- <ChevronDown className="ml-1 h-4 w-4" />- ) : (- <div className="bg-input ml-1 rounded-sm px-1 text-xs">- {drawerPresetCount}- </div>- )}- </Button>+ <TableViewPresetsButton+ id={triggerId}+ count={drawerPresetCount}+ selectedView={+ selectedView+ ? {+ name: selectedView.name,+ defaultLabel:+ selectedView.id === defaultAssignments?.userDefaultViewId+ ? "Your default"+ : selectedView.id ===+ defaultAssignments?.projectDefaultViewId+ ? "Project default"+ : null,+ }+ : null+ }+ /></DrawerTrigger><TableViewPresetsDrawerContentBodyviewConfig={viewConfig}@@ -322,8 +317,14 @@ function TableViewPresetsDrawerContentBody({ReturnType<typeof useTableViewPresetsDrawerData>) {const [searchQuery, setSearchQueryLocal] = useState("");const { tableName, projectId, controllers } = viewConfig;- const { handleSetViewId, applyViewState, selectedViewId, appliedViewId } =- controllers;+ const {+ handleSetViewId,+ applyViewState,+ selectedViewId,+ appliedViewId,+ viewUpdateTarget,+ } = controllers;+ const updateViewId = selectedViewId ?? viewUpdateTarget?.viewId;const {createMutation,updateConfigMutation,@@ -436,12 +437,13 @@ function TableViewPresetsDrawerContentBody({setIsCreateDialogOpen(false);};- const handleUpdateViewConfig = (updatedView: { name: string }) => {- if (!selectedViewId) return;-+ const handleUpdateViewConfig = (updatedView: {+ id: string;+ name: string;+ }) => {capture("saved_views:update_config", {tableName,- viewId: selectedViewId,+ viewId: updatedView.id,name: updatedView.name,});@@ -453,9 +455,12 @@ function TableViewPresetsDrawerContentBody({// the view's stored column layout instead (LFE-10486). Filters/sort/search// always come from the live state, since updating those to what the visitor// currently sees is exactly the intent.- const viewWasApplied = appliedViewId === selectedViewId;+ const viewWasApplied =+ appliedViewId === updatedView.id ||+ (viewUpdateTarget?.viewId === updatedView.id &&+ viewUpdateTarget.columnsApplied);const storedView = TableViewPresetsList?.find(- (view) => view.id === selectedViewId,+ (view) => view.id === updatedView.id,);const columnOrder =viewWasApplied || !storedView@@ -469,7 +474,7 @@ function TableViewPresetsDrawerContentBody({updateConfigMutation.mutate({projectId,name: updatedView.name,- id: selectedViewId,+ id: updatedView.id,tableName,orderBy: currentState.orderBy,filters: currentState.filters,@@ -637,12 +642,7 @@ function TableViewPresetsDrawerContentBody({onSelect={() => handleSelectSystemFilterPreset(preset)}className={cn("hover:bg-muted/50 group mt-1 flex cursor-pointer items-center justify-between rounded-md p-2 transition-colors",- selectedViewId === preset.id &&- isEqual(- normalizeForComparison(currentState.filters),- normalizeForComparison(preset.filters),- ) &&- "bg-muted",+ selectedViewId === preset.id && "bg-muted",)}><div className="flex flex-col">@@ -721,7 +721,7 @@ function TableViewPresetsDrawerContentBody({{previewText}</span>) : null}- {!isSystemView && view.id === selectedViewId && (+ {!isSystemView && view.id === updateViewId && (<Buttonvariant="ghost"size="xs"@@ -734,6 +734,7 @@ function TableViewPresetsDrawerContentBody({onClick={(e) => {e.stopPropagation();handleUpdateViewConfig({+ id: view.id,name: view.name,});}}diff --git a/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts b/web/src/components/table/table-view-presets/hooks/useTableViewManager.tsindex 11cac9f42a..31a7d52b08 100644--- a/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts+++ b/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts@@ -15,6 +15,7 @@ import {useQueryParam,} from "use-query-params";import useSessionStorage from "@/src/components/useSessionStorage";+import { useKeyedSessionStorageState } from "@/src/features/filters/hooks/useKeyedSessionStorageState";import { type LangfuseColumnDef } from "@/src/components/table/types";import { showErrorToast } from "@/src/features/notifications/showErrorToast";import isEqual from "lodash/isEqual";@@ -114,12 +115,19 @@ export function useTableViewManager({const isRouterReady = router.isReady;const [isInitialized, setIsInitialized] = useState(false);const [isLoading, setIsLoading] = useState(true);+ const [filterEditorResetKey, setFilterEditorResetKey] = useState(0);const capture = usePostHogClientCapture();const [storedViewId, setStoredViewId] = useSessionStorage<string | null>(`${tableName}-${projectId}-viewId`,null,);+ const [viewUpdateTarget, setViewUpdateTarget] = useKeyedSessionStorageState<{+ viewId: string;+ columnsApplied: boolean;+ } | null>(`${tableName}-${projectId}-viewUpdateTarget`, null);+ const storedViewIdRef = useRef(storedViewId);+ storedViewIdRef.current = storedViewId;const [selectedViewIdParam, setSelectedViewId] = useQueryParam("viewId",StringParam,@@ -148,6 +156,9 @@ export function useTableViewManager({// the write (LFE-10715).const handleSetViewId = useCallback((viewId: string | null, options?: { updateType?: UrlUpdateType }) => {+ selectedViewIdRef.current = viewId;+ storedViewIdRef.current = viewId;+ setViewUpdateTarget(null);setStoredViewId(viewId);setSelectedViewId(viewId, options?.updateType);@@ -159,7 +170,18 @@ export function useTableViewManager({setIsLoading(false);}},- [setStoredViewId, setSelectedViewId],+ [setStoredViewId, setSelectedViewId, setViewUpdateTarget],+ );++ const handleUserStateChange = useCallback(+ (previousValue: unknown, nextValue: unknown) => {+ const viewId = selectedViewIdRef.current;+ if (!viewId || isEqual(previousValue, nextValue)) return;+ const columnsApplied = storedViewIdRef.current === viewId;+ handleSetViewId(null, { updateType: "replaceIn" });+ setViewUpdateTarget({ viewId, columnsApplied });+ },+ [handleSetViewId, setViewUpdateTarget],);// Extract updater functions and store in refs to avoid stale closures@@ -210,22 +232,22 @@ export function useTableViewManager({!!selectedViewId &&(!isSystemPresetId(selectedViewId) || allowBackendSystemPresets);- // Explicit table state in the URL (`filter`/`search`/`searchType`/- // `orderBy`) is authoritative, even when a `viewId` is present. The viewId- // is a provenance reference — which saved view a link came from — but the- // URL's filters/sort/search are what is actually applied (the URL is the- // source of truth). We do NOT fetch or apply the saved view here: applying- // it would overwrite the URL's filters, and writing its column layout would- // silently mutate the visitor's own per-table localStorage on a- // non-deliberate link open. The viewId stays in the URL so the drawer still- // shows the originating view. Preserves deep-link precedence (#13865) and- // makes shared links carry in-view edits (LFE-10486).+ // Explicit URL filters, sorting and search are authoritative. Opening a+ // link must not apply the stored view over them or overwrite the visitor's+ // column layout. An incoming viewId remains selected until a user edit.if (hasExplicitTableStateInUrl(router.query)) {setIsInitialized(true);setIsLoading(false);return;}+ // An edited working view stays deselected on reload, including empty filters.+ if (!selectedViewId && viewUpdateTarget) {+ setIsInitialized(true);+ setIsLoading(false);+ return;+ }+// A real saved view (or an allowed backend system preset) in the URL with// no explicit table state → let the getById query resolve and hydrate it.if (hasResolvableView) {@@ -269,6 +291,7 @@ export function useTableViewManager({selectedViewId,router.query,storedViewId,+ viewUpdateTarget,isDefaultLoading,defaultViewId,allowBackendSystemPresets,@@ -382,6 +405,9 @@ export function useTableViewManager({)setColumnVisibility(viewData.columnVisibility);+ // Applying a view discards drafts; leaving a view while editing preserves them.+ setFilterEditorResetKey((key) => key + 1);+// Unlock as soon as the view is applied. Earlier versions kept the table// locked until a useEffect observer saw the filter change propagate to// `currentFilterState`; that observer was the source of LFE-7389@@ -580,6 +606,9 @@ export function useTableViewManager({isLoading: false,applyViewState: () => {},handleSetViewId: () => {},+ handleUserStateChange: () => {},+ filterEditorResetKey: 0,+ viewUpdateTarget: null,selectedViewId: null,appliedViewId: null,defaultViewScope: null,@@ -590,6 +619,9 @@ export function useTableViewManager({isLoading,applyViewState,handleSetViewId,+ handleUserStateChange,+ filterEditorResetKey,+ viewUpdateTarget,selectedViewId,// The view whose state is reflected in the live table — i.e. whose column// layout is in localStorage. We reuse `storedViewId` (session-persisted,diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsxindex d3fc3a9cca..331956e0eb 100644--- a/web/src/components/table/use-cases/traces.tsx+++ b/web/src/components/table/use-cases/traces.tsx@@ -49,6 +49,7 @@ import {TableViewPresetTableName,type TimeFilter,type ScoreAggregate,+ type TracingSearchType,DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG,} from "@langfuse/shared";import { useRowHeightLocalStorage } from "@/src/components/table/data-table-row-height-switch";@@ -105,6 +106,11 @@ import { DialogController } from "@/src/components/ui/dialog";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { usePostHogClientCapture } from "@/src/features/posthog-analytics";import { DeleteTraceDialogContent } from "@/src/features/traces/components/DeleteTraceDialogContent";+import {+ demoteViewOnUserFilterEdit,+ type ExplicitFilterStateChange,+ type ViewDemotionControllers,+} from "@/src/features/events/lib/demoteViewOnUserFilterEdit";export type TracesTableRow = {// Shown by default@@ -383,10 +389,19 @@ function TracesTableInternal({const isSidebarFilterLoading =traceFilterOptionsResponse.isPending || environmentFilterOptions.isPending;+ const viewControllersRef = useRef<ViewDemotionControllers | null>(null);+ const onExplicitFilterStateChange = useCallback(+ (change: ExplicitFilterStateChange) => {+ demoteViewOnUserFilterEdit(change, viewControllersRef.current);+ },+ [],+ );+const queryFilterOptions: UseSidebarFilterStateOptions = useMemo(() => {const baseOptions = {loading: isSidebarFilterLoading,implicitDefaultConfig: DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG,+ onExplicitFilterStateChange,};if (peekContext) {@@ -412,7 +427,14 @@ function TracesTableInternal({userId ? "user" : undefined,),};- }, [hideControls, isSidebarFilterLoading, peekContext, projectId, userId]);+ }, [+ hideControls,+ isSidebarFilterLoading,+ onExplicitFilterStateChange,+ peekContext,+ projectId,+ userId,+ ]);const queryFilter = useSidebarFilterState(tracesFilterConfig,@@ -1232,8 +1254,9 @@ function TracesTableInternal({const queryFilterRef = useRef(queryFilter);queryFilterRef.current = queryFilter;- const setFiltersWrapper = useCallback(- (filters: FilterState) => queryFilterRef.current?.setFilterState(filters),+ const setSavedViewFilters = useCallback(+ (filters: FilterState) =>+ queryFilterRef.current?.setFilterState(filters, { origin: "saved_view" }),[],);@@ -1242,7 +1265,7 @@ function TracesTableInternal({projectId,stateUpdaters: {setOrderBy: setOrderByState,- setFilters: setFiltersWrapper,+ setFilters: setSavedViewFilters,setExpandedFilters: queryFilter.onExpandedChange,setColumnOrder: setColumnOrder,setColumnVisibility: setColumnVisibility,@@ -1259,6 +1282,38 @@ function TracesTableInternal({currentExpandedFilters: queryFilter.expanded,disabled: hideControls,});+ viewControllersRef.current = viewControllers;++ const handleSearchQueryChange = (nextQuery: string) => {+ viewControllers.handleUserStateChange(searchQuery ?? "", nextQuery);+ setSearchQuery(nextQuery);+ };+ const handleSearchTypeChange = (nextType: TracingSearchType[]) => {+ if (searchQuery?.trim()) {+ viewControllers.handleUserStateChange(+ [...searchType].sort(),+ [...nextType].sort(),+ );+ }+ setSearchType(nextType);+ };+ const handleOrderByChange: typeof setOrderByState = (nextOrderBy) => {+ viewControllers.handleUserStateChange(orderByState, nextOrderBy);+ setOrderByState(nextOrderBy);+ };+ const handleColumnOrderChange: typeof setColumnOrder = (updater) => {+ const next = typeof updater === "function" ? updater(columnOrder) : updater;+ viewControllers.handleUserStateChange(columnOrder, next);+ setColumnOrder(next);+ };+ const handleColumnVisibilityChange: typeof setColumnVisibility = (+ updater,+ ) => {+ const next =+ typeof updater === "function" ? updater(columnVisibility) : updater;+ viewControllers.handleUserStateChange(columnVisibility, next);+ setColumnVisibility(next);+ };const rows = useMemo(() => {return traces.isSuccess@@ -1350,10 +1405,10 @@ function TracesTableInternal({}}searchConfig={{metadataSearchFields: ["ID", "Trace Name", "User ID"],- updateQuery: setSearchQuery,+ updateQuery: handleSearchQueryChange,currentQuery: searchQuery ?? undefined,tableAllowsFullTextSearch: legacyTracingIoSearchEnabled,- setSearchType,+ setSearchType: handleSearchTypeChange,searchType,}}columnsWithCustomSelect={["traceName", "traceTags"]}@@ -1402,9 +1457,9 @@ function TracesTableInternal({]}orderByState={orderByState}columnVisibility={columnVisibility}- setColumnVisibility={setColumnVisibility}+ setColumnVisibility={handleColumnVisibilityChange}columnOrder={columnOrder}- setColumnOrder={setColumnOrder}+ setColumnOrder={handleColumnOrderChange}rowHeight={rowHeight}setRowHeight={setRowHeight}timeRange={showControlsInPageHeader ? undefined : timeRange}@@ -1425,8 +1480,7 @@ function TracesTableInternal({<ResizableFilterLayout>{!hideControls && (<DataTableControls- // Remount the sidebar when the saved view changes so the new view's filters replace any stale draft UI state.- key={viewControllers.selectedViewId ?? "no-view"}+ key={viewControllers.filterEditorResetKey}queryFilter={queryFilter}filterWithAI/>@@ -1475,15 +1529,15 @@ function TracesTableInternal({state: paginationState,}}- setOrderBy={setOrderByState}+ setOrderBy={handleOrderByChange}orderBy={orderByState}rowSelection={selectedRows}highlightAllRows={selectAll}setRowSelection={setSelectedRows}columnVisibility={columnVisibility}- onColumnVisibilityChange={setColumnVisibility}+ onColumnVisibilityChange={handleColumnVisibilityChange}columnOrder={columnOrder}- onColumnOrderChange={setColumnOrder}+ onColumnOrderChange={handleColumnOrderChange}rowHeight={rowHeight}peekView={peekConfig}tableName="traces"diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsxindex 77f77382f8..3290d5c3e1 100644--- a/web/src/features/events/components/EventsTable.tsx+++ b/web/src/features/events/components/EventsTable.tsx@@ -23,6 +23,7 @@ import {DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG,type ObservationLevelType,type FilterState,+ type OrderByState,BatchExportTableName,type ObservationType,TableViewPresetTableName,@@ -111,7 +112,6 @@ import { useTableViewManager } from "@/src/components/table/table-view-presets/himport {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";@@ -512,7 +512,27 @@ export default function ObservationsEventsTable({// 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 viewControllersRef = useRef<Pick<+ ReturnType<typeof useTableViewManager>,+ "selectedViewId" | "handleSetViewId" | "handleUserStateChange"+ > | null>(null);++ const handleSearchQueryChange = (query: string | null) => {+ viewControllersRef.current?.handleUserStateChange(+ searchQuery ?? "",+ query ?? "",+ );+ setSearchQuery(query);+ };+ const handleSearchTypeChange = (next: TracingSearchType[]) => {+ if (searchQuery?.trim()) {+ viewControllersRef.current?.handleUserStateChange(+ [...searchType].sort(),+ [...next].sort(),+ );+ }+ setSearchType(next);+ };const onAppRootExplicitFilterStateChange =appRootDefault.onExplicitFilterStateChange;@@ -757,8 +777,8 @@ export default function ObservationsEventsTable({searchType,observed: observedOptions,setFilterState: setFiltersWrapper,- setSearchQuery,- setSearchType,+ setSearchQuery: handleSearchQueryChange,+ setSearchType: handleSearchTypeChange,});// Non-destructive preview: while a category-chip preset row is hovered or@@ -1598,6 +1618,24 @@ export default function ObservationsEventsTable({});viewControllersRef.current = viewControllers;+ const handleOrderByChange = (next: OrderByState) => {+ viewControllers.handleUserStateChange(orderByState, next);+ setOrderByState(next);+ };+ const handleColumnOrderChange: typeof setColumnOrder = (update) => {+ const next = typeof update === "function" ? update(columnOrder) : update;+ viewControllers.handleUserStateChange(columnOrder, next);+ setColumnOrder(next);+ };+ const handleColumnVisibilityChange: typeof setColumnVisibilityState = (+ update,+ ) => {+ const next =+ typeof update === "function" ? update(columnVisibility) : update;+ viewControllers.handleUserStateChange(columnVisibility, next);+ setColumnVisibilityState(next);+ };+const peekConfig: DataTablePeekViewProps | undefined = useMemo(() => {if (hideControls) return undefined;return {@@ -1737,7 +1775,7 @@ export default function ObservationsEventsTable({resultCount={totalCount}onClearAll={() => {queryFilter.clearAll();- setSearchQuery("");+ handleSearchQueryChange("");}}search={searchBarMode ? (@@ -1770,7 +1808,7 @@ export default function ObservationsEventsTable({// desktop has via the toolbar's searchConfig (LFE-11067).<MobileFullTextSearchcurrentQuery={searchQuery ?? undefined}- updateQuery={setSearchQuery}+ updateQuery={handleSearchQueryChange}tableAllowsFullTextSearchmetadataSearchFields={["ID", "Name", "Trace Name", "Model"]}tableName={eventsFilterConfig.tableName}@@ -1832,7 +1870,7 @@ export default function ObservationsEventsTable({}facets={<DataTableControls- key={viewControllers.selectedViewId ?? "no-view"}+ key={viewControllers.filterEditorResetKey}queryFilter={queryFilter}filterWithAI={!searchBarMode}blockedColumnReason={@@ -1907,10 +1945,10 @@ export default function ObservationsEventsTable({"Trace Name","Model",],- updateQuery: setSearchQuery,+ updateQuery: handleSearchQueryChange,currentQuery: searchQuery ?? undefined,searchType,- setSearchType,+ setSearchType: handleSearchTypeChange,tableAllowsFullTextSearch: true,}}@@ -1926,9 +1964,9 @@ export default function ObservationsEventsTable({"promptName",]}columnVisibility={columnVisibility}- setColumnVisibility={setColumnVisibilityState}+ setColumnVisibility={handleColumnVisibilityChange}columnOrder={columnOrder}- setColumnOrder={setColumnOrder}+ setColumnOrder={handleColumnOrderChange}orderByState={orderByState}rowHeight={rowHeight}setRowHeight={setRowHeight}@@ -2073,8 +2111,7 @@ export default function ObservationsEventsTable({in the layout). */}{!hideControls && !isMobile && (<DataTableControls- // Remount the sidebar when the saved view changes so the new view's filters replace any stale draft UI state.- key={viewControllers.selectedViewId ?? "no-view"}+ key={viewControllers.filterEditorResetKey}queryFilter={queryFilter}// In bar mode AI filtering lives in the search bar; only offer the// sidebar wand on non-bar surfaces (embedded scoped tables).@@ -2189,12 +2226,12 @@ export default function ObservationsEventsTable({rowSelection={selectedRows}highlightAllRows={selectAll}setRowSelection={setSelectedRows}- setOrderBy={setOrderByState}+ setOrderBy={handleOrderByChange}orderBy={orderByState}columnOrder={columnOrder}- onColumnOrderChange={setColumnOrder}+ onColumnOrderChange={handleColumnOrderChange}columnVisibility={columnVisibility}- onColumnVisibilityChange={setColumnVisibilityState}+ onColumnVisibilityChange={handleColumnVisibilityChange}rowHeight={rowHeight}onRowClick={(row, event) => {// Handle Command/Ctrl+click to open observation in new tabdiff --git a/web/src/features/events/lib/demoteViewOnUserFilterEdit.ts b/web/src/features/events/lib/demoteViewOnUserFilterEdit.tsindex dbb7fa1abd..8482853214 100644--- a/web/src/features/events/lib/demoteViewOnUserFilterEdit.ts+++ b/web/src/features/events/lib/demoteViewOnUserFilterEdit.ts@@ -1,7 +1,5 @@-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;@@ -9,6 +7,7 @@ export type ViewDemotionControllers = {viewId: string | null,options?: { updateType?: UrlUpdateType },) => void;+ handleUserStateChange: (previousValue: unknown, nextValue: unknown) => void;};export type ExplicitFilterStateChange = {@@ -17,43 +16,14 @@ export type ExplicitFilterStateChange = {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.- */+/** User edits leave the selected view; view application and reconciliation do not. */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" });+ controllers?.handleUserStateChange(+ change.previousFilters,+ change.nextFilters,+ );}diff --git a/web/src/features/events/presetDemotionOnUserEdit.clienttest.tsx b/web/src/features/events/presetDemotionOnUserEdit.clienttest.tsxindex 492176c1b8..b8f8d4db9f 100644--- a/web/src/features/events/presetDemotionOnUserEdit.clienttest.tsx+++ b/web/src/features/events/presetDemotionOnUserEdit.clienttest.tsx@@ -1,4 +1,10 @@-import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";import {TableViewPresetTableName,encodeFiltersGeneric,@@ -11,19 +17,15 @@ import {useSidebarFilterState,} from "@/src/features/filters";import { useTableViewManager } from "../../components/table/table-view-presets/hooks/useTableViewManager";+import { KeyValueFilterBuilder } from "@/src/components/table/key-value-filter-builder";+import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";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).+// Editing an applied view clears its selection in both URL and session+// storage, so a later table visit cannot restore the filters just edited.const mockUseRouter = vi.fn();const mockCapture = vi.fn();@@ -129,6 +131,12 @@ const TEST_FILTER_CONFIG: FilterConfig = {options: [],internal: "name",},+ {+ id: "metadata",+ name: "Metadata",+ type: "stringObject",+ internal: "metadata",+ },],facets: [{@@ -136,6 +144,7 @@ const TEST_FILTER_CONFIG: FilterConfig = {column: "name",label: "Name",},+ { type: "stringKeyValue", column: "metadata", label: "Metadata" },],};@@ -173,6 +182,20 @@ const PRESET_VIEW_DATA = {...PRESET_VIEW_STATE,};+const USER_VIEW_STATE: TableViewPresetState = {+ ...PRESET_VIEW_STATE,+ filters: [+ ...PRESET_FILTERS,+ {+ column: "metadata",+ type: "stringObject",+ key: "region",+ operator: "=",+ value: "eu",+ },+ ],+};+const storedViewId = () => {const raw = sessionStorage.getItem(VIEW_ID_STORAGE_KEY);return raw === null ? null : JSON.parse(raw);@@ -181,15 +204,16 @@ const storedViewId = () => {/** 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() {+function Harness({ projectId = PROJECT_ID }: { projectId?: string }) {const viewControllersRef = useRef<ViewDemotionControllers | null>(null);+ const [orderBy, setOrderBy] = useOrderByState(null);const queryFilter = useSidebarFilterState(TEST_FILTER_CONFIG,{ name: ["checkout", "search"] },{stateLocation: "urlAndSessionStorage",- sessionFilterContextId: PROJECT_ID,+ sessionFilterContextId: projectId,onExplicitFilterStateChange: (change) =>demoteViewOnUserFilterEdit(change, viewControllersRef.current),},@@ -203,34 +227,56 @@ function Harness() {[],);- 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,- });+ const {+ selectedViewId,+ appliedViewId,+ viewUpdateTarget,+ filterEditorResetKey,+ handleSetViewId,+ handleUserStateChange,+ applyViewState,+ } = useTableViewManager({+ tableName: TableViewPresetTableName.ObservationsEvents,+ projectId,+ stateUpdaters: {+ setFilters: setSavedViewFiltersWrapper,+ setOrderBy,+ setColumnOrder: () => {},+ setColumnVisibility: () => {},+ },+ validationContext: {+ columns: [],+ filterColumnDefinition: TEST_FILTER_CONFIG.columnDefinitions,+ },+ currentFilterState: queryFilter.explicitFilterState,+ allowBackendSystemPresets: true,+ });viewControllersRef.current = {selectedViewId,handleSetViewId,+ handleUserStateChange,};+ const metadataFacet = queryFilter.filters.find(+ (filter) => filter.type === "stringKeyValue",+ );+ if (!metadataFacet) throw new Error("Missing metadata facet");return (<div><div data-testid="selected-view-id">{selectedViewId ?? "null"}</div><div data-testid="applied-view-id">{appliedViewId ?? "null"}</div>+ <pre data-testid="view-update-target">+ {JSON.stringify(viewUpdateTarget ?? null)}+ </pre><pre data-testid="explicit-state">{JSON.stringify(queryFilter.explicitFilterState)}</pre>+ <KeyValueFilterBuilder+ key={filterEditorResetKey}+ mode="string"+ activeFilters={metadataFacet.value}+ onChange={metadataFacet.onChange}+ /><buttononClick={() => {// Mirrors a CategoryPresetChips row click.@@ -247,7 +293,7 @@ function Harness() {onClick={() => {// Mirrors the saved-views drawer's handleSelectView.handleSetViewId(USER_VIEW_ID);- applyViewState(PRESET_VIEW_STATE, {+ applyViewState(USER_VIEW_STATE, {trigger: "select",viewId: USER_VIEW_ID,});@@ -268,6 +314,30 @@ function Harness() {>user-recommit-same</button>+ <button+ onClick={() =>+ queryFilter.setFilterState(EXTRA_FILTERS, { origin: "system" })+ }+ >+ system-reconcile+ </button>+ <button+ onClick={() => {+ handleUserStateChange(orderBy, null);+ setOrderBy(null);+ }}+ >+ user-keep-sort+ </button>+ <button+ onClick={() => {+ const nextOrderBy = { column: "name", order: "ASC" as const };+ handleUserStateChange(orderBy, nextOrderBy);+ setOrderBy(nextOrderBy);+ }}+ >+ user-sort+ </button></div>);}@@ -286,7 +356,7 @@ const applyPresetAndAssertActive = async () => {});};-describe("system preset demotion on user filter edits (LFE-14699)", () => {+describe("saved-view demotion on user filter edits", () => {beforeEach(() => {vi.clearAllMocks();sessionStorage.clear();@@ -382,7 +452,7 @@ describe("system preset demotion on user filter edits (LFE-14699)", () => {});});- it("does not demote on a no-op user write (unchanged filters)", async () => {+ it("preserves selection for no-op edits and system reconciliation", async () => {render(<Harness />);await applyPresetAndAssertActive();@@ -394,14 +464,19 @@ describe("system preset demotion on user filter edits (LFE-14699)", () => {);expect(storedViewId()).toBe(PRESET_ID);});++ fireEvent.click(screen.getByRole("button", { name: "system-reconcile" }));+ await waitFor(() => {+ expect(screen.getByTestId("explicit-state").textContent).toContain(+ "search",+ );+ });+ 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 />);+ it("clears a user-saved view from shared state, URL and session on an actual filter edit", async () => {+ const { unmount } = render(<Harness />);fireEvent.click(screen.getByRole("button", { name: "apply-user-view" }));@@ -412,28 +487,87 @@ describe("system preset demotion on user filter edits (LFE-14699)", () => {expect(storedViewId()).toBe(USER_VIEW_ID);});+ fireEvent.click(screen.getByRole("button", { name: "user-recommit-same" }));+ 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("selected-view-id").textContent).toBe("null");+ expect(screen.getByTestId("applied-view-id").textContent).toBe("null");+ expect(queryParamStore.has("viewId")).toBe(false);+ expect(storedViewId()).toBe(null);+ expect(urlParamWrites).toContainEqual({+ key: "viewId",+ value: null,+ updateType: "replaceIn",+ });+ const updateTarget = {+ viewId: USER_VIEW_ID,+ columnsApplied: true,+ };+ expect(+ JSON.parse(screen.getByTestId("view-update-target").textContent!),+ ).toEqual(updateTarget);+ unmount();+ mockGetDefaultUseQuery.mockReturnValue({+ data: { viewId: USER_VIEW_ID, scope: "project" },+ isLoading: false,+ });+ render(<Harness />);+ expect(screen.getByTestId("selected-view-id").textContent).toBe("null");+ expect(+ JSON.parse(screen.getByTestId("view-update-target").textContent!),+ ).toEqual(updateTarget);+ fireEvent.click(screen.getByRole("button", { name: "apply-user-view" }));+ expect(screen.getByTestId("view-update-target").textContent).toBe("null");+ });++ it("keeps an edited view's update target scoped to its project during navigation", async () => {+ const otherProjectId = "project-2";+ const { rerender, unmount } = render(<Harness />);+ fireEvent.click(screen.getByRole("button", { name: "apply-user-view" }));+ fireEvent.click(screen.getByRole("button", { name: "user-clear-filters" }));++ const updateTarget = { viewId: USER_VIEW_ID, columnsApplied: true };+ const storageKey = (projectId: string) =>+ `${TableViewPresetTableName.ObservationsEvents}-${projectId}-viewUpdateTarget`;+ expect(JSON.parse(sessionStorage.getItem(storageKey(PROJECT_ID))!)).toEqual(+ updateTarget,);- expect(screen.getByTestId("applied-view-id").textContent).toBe(- USER_VIEW_ID,++ rerender(<Harness projectId={otherProjectId} />);+ await waitFor(() => {+ expect(screen.getByTestId("view-update-target").textContent).toBe("null");+ });+ expect(sessionStorage.getItem(storageKey(otherProjectId))).toBe("null");+ expect(JSON.parse(sessionStorage.getItem(storageKey(PROJECT_ID))!)).toEqual(+ updateTarget,);- expect(storedViewId()).toBe(USER_VIEW_ID);++ unmount();+ mockGetDefaultUseQuery.mockReturnValue({+ data: { viewId: PRESET_ID, scope: "project" },+ isLoading: false,+ });+ render(<Harness projectId={otherProjectId} />);+ await waitFor(() => {+ expect(screen.getByTestId("selected-view-id").textContent).toBe(+ PRESET_ID,+ );+ expect(screen.getByTestId("explicit-state").textContent).toContain(+ "checkout",+ );+ });});- 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.+ it("clears both IDs after editing a shared view whose session ID is stale", async () => {+ // A shared link with explicit state can leave the prior session ID intact.sessionStorage.setItem(VIEW_ID_STORAGE_KEY, JSON.stringify(PRESET_ID));queryParamStore.set("viewId", USER_VIEW_ID);queryParamStore.set("filter", encodeFiltersGeneric(PRESET_FILTERS));@@ -456,23 +590,66 @@ describe("system preset demotion on user filter edits (LFE-14699)", () => {"search",);});- // The user view's URL provenance survives; the demotion never fired.+ expect(screen.getByTestId("selected-view-id").textContent).toBe("null");+ expect(screen.getByTestId("applied-view-id").textContent).toBe("null");+ expect(queryParamStore.has("viewId")).toBe(false);+ expect(storedViewId()).toBe(null);+ expect(+ JSON.parse(screen.getByTestId("view-update-target").textContent!),+ ).toEqual({+ viewId: USER_VIEW_ID,+ columnsApplied: false,+ });+ });++ it("preserves an incomplete metadata edit on deselection and resets drafts only when a view is applied", () => {+ render(<Harness />);+ fireEvent.click(screen.getByRole("button", { name: "apply-user-view" }));++ const value = screen.getByDisplayValue("eu");+ act(() => value.focus());+ fireEvent.change(value, { target: { value: "" } });++ expect(screen.getByTestId("selected-view-id").textContent).toBe("null");+ expect(queryParamStore.has("viewId")).toBe(false);+ expect(storedViewId()).toBe(null);+ expect(screen.getByDisplayValue("region")).toBeInTheDocument();+ expect(value).toHaveFocus();++ fireEvent.change(screen.getByDisplayValue("region"), {+ target: { value: "draft-region" },+ });+ fireEvent.click(screen.getByRole("button", { name: "apply-user-view" }));+ expect(screen.queryByDisplayValue("draft-region")).not.toBeInTheDocument();+ expect(screen.getByDisplayValue("eu")).toBeInTheDocument();++ fireEvent.click(screen.getByText("Add filter"));+ fireEvent.change(screen.getAllByPlaceholderText("Key")[1], {+ target: { value: "pending-key" },+ });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.+ fireEvent.click(screen.getByRole("button", { name: "apply-user-view" }));+ expect(screen.queryByDisplayValue("pending-key")).not.toBeInTheDocument();+ expect(screen.getByDisplayValue("eu")).toBeInTheDocument();+ });++ it("keeps selection for unchanged sorting and clears it when the sort changes", async () => {+ render(<Harness />);+ await applyPresetAndAssertActive();++ fireEvent.click(screen.getByRole("button", { name: "user-keep-sort" }));+ expect(queryParamStore.get("viewId")).toBe(PRESET_ID);expect(storedViewId()).toBe(PRESET_ID);- expect(screen.getByTestId("selected-view-id").textContent).not.toBe(- PRESET_ID,- );++ fireEvent.click(screen.getByRole("button", { name: "user-sort" }));+ expect(queryParamStore.get("orderBy")).toEqual({+ column: "name",+ order: "ASC",+ });+ expect(queryParamStore.has("viewId")).toBe(false);+ expect(screen.getByTestId("selected-view-id").textContent).toBe("null");+ expect(storedViewId()).toBe(null);});});diff --git a/web/src/features/filters/hooks/useSidebarFilterState.tsx b/web/src/features/filters/hooks/useSidebarFilterState.tsxindex bcd945da10..0d25d691f9 100644--- a/web/src/features/filters/hooks/useSidebarFilterState.tsx+++ b/web/src/features/filters/hooks/useSidebarFilterState.tsx@@ -1038,6 +1038,7 @@ export function useSidebarFilterPresentation(presentationOptions: SidebarFilterPresentationOptions = {},) {const { loading, loadingColumns } = presentationOptions;+ const [draftResetKey, setDraftResetKey] = useState(0);const isV4Surface = presentationOptions.isV4 ?? false;const capture = usePostHogClientCapture();const {@@ -1138,6 +1139,7 @@ export function useSidebarFilterPresentation(const clearAll = () => {const clearedCount = explicitFilterState.length;+ setDraftResetKey((key) => key + 1);setFilterState([]);if (clearedCount > 0) {capture("filters:cleared", {@@ -2028,6 +2030,7 @@ export function useSidebarFilterPresentation(updateFilterOnly,updateOperator,clearAll,+ draftResetKey,isFiltered: explicitFilterState.length > 0,filters,expanded: expandedState,diff --git a/web/src/features/search-bar/README.md b/web/src/features/search-bar/README.mdindex 4d7a87a590..0a0bf0faa0 100644--- a/web/src/features/search-bar/README.md+++ b/web/src/features/search-bar/README.md@@ -528,6 +528,11 @@ real consumer and validate it against that view's backend filter contract.- **`SearchComposer` (~1.3k LOC) has no unit tests** — the contenteditablecontroller is browser-reviewed only. Extracting the selection/`beforeinput`machinery into a hook (below) is the prerequisite to testing it.+- **Client integration coverage** in `web/src/components/table/data-table-controls.clienttest.tsx`+ exercises real sidebar inputs, filter state, and bar commits: delayed string+ and numeric edits preserve newly committed bar filters, and clearing a facet+ cancels its pending edit. This does not cover the table's network request or+ rendered result rows.- **No e2e** for bar↔sidebar sync or the embedded-vs-full-page mount matrix(the bar leaking onto user/session detail was a review find, not caught by atest).