Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(sessions): stop Back-button bounce from default-view URL pushes (LFE-10715) (#14857)

Nikita Kabardin2105ba736921
diff --git a/web/src/components/session/index.tsx b/web/src/components/session/index.tsx
index d6bef0793f..b945b861f4 100644
--- a/web/src/components/session/index.tsx
+++ b/web/src/components/session/index.tsx
@@ -75,6 +75,7 @@ import { downloadSessionAsJson } from "@/src/components/session/actions/download
import { SessionDetailStoreProvider } from "@/src/components/session/SessionDetailStoreProvider";
import { SessionVirtualizedRow } from "@/src/components/session/SessionVirtualizedRow";
import { createSessionDetailStore } from "@/src/components/session/sessionDetailStore";
+import { useHistoryEntryRevisit } from "@/src/components/session/useHistoryEntryRevisit";
import {
areDetailPageListsEqual,
asCommentCounts,
@@ -919,10 +920,15 @@ const LoadedSessionEventsPage: React.FC<{
currentExpandedFilters: queryFilter.expanded,
});
+ // Auto-apply path only (the drawer's user-driven preset selection has its
+ // own handler). Writes with `replaceIn`: this is the page deciding its own
+ // default, not a user step β€” pushing would leave the pre-default URL as a
+ // history entry that Back lands on and that re-applies the default, making
+ // Back bounce forward (LFE-10715).
const applySystemPreset = useCallback(
(preset: SessionDetailSystemPreset) => {
- viewControllers.handleSetViewId(preset.id);
- queryFilter.setFilterState(preset.filters);
+ viewControllers.handleSetViewId(preset.id, { updateType: "replaceIn" });
+ queryFilter.setFilterState(preset.filters, { updateType: "replaceIn" });
},
[queryFilter, viewControllers],
);
@@ -983,18 +989,35 @@ const LoadedSessionEventsPage: React.FC<{
const shouldRecover =
filterMatchedView.id === initialViewIdRef.current ||
visibleFilterState.length > 0;
- if (shouldRecover) viewControllers.handleSetViewId(filterMatchedView.id);
+ // replaceIn: recovery is a programmatic correction of the current URL β€”
+ // pushing would mint a viewId-less history entry that Back re-triggers
+ // (the filter survives in sessionStorage, so this effect re-fires on any
+ // pop to a param-less URL β€” LFE-10715).
+ if (shouldRecover)
+ viewControllers.handleSetViewId(filterMatchedView.id, {
+ updateType: "replaceIn",
+ });
}, [isViewLoading, selectedViewId, visibleFilterState, viewControllers]);
+ // Whether this arrival is a Back/Forward revisit of an existing history
+ // entry rather than a fresh navigation. Keyed to sessionId so in-place
+ // prev/next session navigation re-decides, mirroring initialViewIdRef.
+ const arrivedOnVisitedHistoryEntry = useHistoryEntryRevisit(sessionId);
+
// Fresh load with nothing in the URL β†’ apply the default view. Skipped on
// reload/shared-link (a viewId was in the URL) so the recovery effect above,
// not the default, decides the view β€” otherwise "All observations" would be
- // silently replaced by the default on every reload.
+ // silently replaced by the default on every reload. Also skipped when the
+ // user arrived via Back/Forward: a revisited entry's param-less URL is a
+ // recorded "no view" state, not a fresh arrival, and re-applying the
+ // default would overwrite what the user deliberately left there
+ // (LFE-10715).
useEffect(() => {
if (defaultPresetAppliedRef.current) return;
if (isViewLoading) return; // Wait for view manager to initialize
if (selectedViewId) return;
if (initialViewIdRef.current) return;
+ if (arrivedOnVisitedHistoryEntry) return;
const presetToApply = getSessionDetailPresetToApply({
selectedViewId: null,
hasFilters: visibleFilterState.length > 0,
@@ -1002,7 +1025,13 @@ const LoadedSessionEventsPage: React.FC<{
if (!presetToApply) return;
defaultPresetAppliedRef.current = true;
applySystemPreset(presetToApply);
- }, [applySystemPreset, isViewLoading, selectedViewId, visibleFilterState]);
+ }, [
+ applySystemPreset,
+ arrivedOnVisitedHistoryEntry,
+ isViewLoading,
+ selectedViewId,
+ visibleFilterState,
+ ]);
const virtualizer = useVirtualizer({
count: traces?.length ?? 0,
diff --git a/web/src/components/session/useHistoryEntryRevisit.clienttest.tsx b/web/src/components/session/useHistoryEntryRevisit.clienttest.tsx
new file mode 100644
index 0000000000..0906b0ea0f
--- /dev/null
+++ b/web/src/components/session/useHistoryEntryRevisit.clienttest.tsx
@@ -0,0 +1,133 @@
+import { renderHook } from "@testing-library/react";
+import { StrictMode } from "react";
+import { useHistoryEntryRevisit } from "./useHistoryEntryRevisit";
+
+// LFE-10715: the session page auto-applies a default view when the URL has no
+// viewId. That must only happen on a fresh arrival β€” when the user reaches the
+// param-less URL via Back/Forward (a history entry they already left once),
+// "no view" is a recorded state and re-applying the default would overwrite
+// it. The hook detects such revisits via the Next.js Pages Router per-entry
+// `key` in window.history.state.
+
+const mockRouter = { asPath: "/project/p1/sessions/s1" };
+
+vi.mock("next/router", () => ({
+ useRouter: () => mockRouter,
+}));
+
+const setHistoryEntry = (key: string | null) => {
+ window.history.replaceState(key === null ? null : { key, __N: true }, "");
+};
+
+describe("useHistoryEntryRevisit (LFE-10715)", () => {
+ beforeEach(() => {
+ sessionStorage.clear();
+ setHistoryEntry(null);
+ mockRouter.asPath = "/project/p1/sessions/s1";
+ });
+
+ it("treats the first arrival at a history entry as fresh", () => {
+ setHistoryEntry("entry-1");
+
+ const { result } = renderHook(() => useHistoryEntryRevisit("session-1"));
+
+ expect(result.current).toBe(false);
+ });
+
+ it("treats a return to an entry that was left as a revisit", () => {
+ setHistoryEntry("entry-1");
+ const { unmount } = renderHook(() => useHistoryEntryRevisit("session-1"));
+ // Leaving the page (unmount) records the entry as visited.
+ unmount();
+
+ // Back: the same history entry (same key) is active again on a new mount.
+ const { result } = renderHook(() => useHistoryEntryRevisit("session-1"));
+
+ expect(result.current).toBe(true);
+ });
+
+ it("records entries left via in-page navigation, not just unmount", () => {
+ setHistoryEntry("entry-1");
+ const { rerender, unmount } = renderHook(
+ () => useHistoryEntryRevisit("session-1"),
+ { initialProps: {} },
+ );
+
+ // An in-page push (e.g. a filter edit) moves to a new entry; the old one
+ // must be recorded as visited even though the component stays mounted.
+ setHistoryEntry("entry-2");
+ mockRouter.asPath = "/project/p1/sessions/s1?filter=x";
+ rerender({});
+ unmount();
+
+ // Back onto the first entry after a remount.
+ setHistoryEntry("entry-1");
+ mockRouter.asPath = "/project/p1/sessions/s1";
+ const { result } = renderHook(() => useHistoryEntryRevisit("session-1"));
+
+ expect(result.current).toBe(true);
+ });
+
+ it("keeps the arrival decision stable for the lifetime of the mount", () => {
+ setHistoryEntry("entry-1");
+ const { result, rerender } = renderHook(
+ () => useHistoryEntryRevisit("session-1"),
+ { initialProps: {} },
+ );
+ expect(result.current).toBe(false);
+
+ // A same-mount pop back onto an already-visited entry does not flip the
+ // arrival decision β€” same-mount navigation is the caller's concern.
+ setHistoryEntry("entry-2");
+ mockRouter.asPath = "/project/p1/sessions/s1?filter=x";
+ rerender({});
+ setHistoryEntry("entry-1");
+ mockRouter.asPath = "/project/p1/sessions/s1";
+ rerender({});
+
+ expect(result.current).toBe(false);
+ });
+
+ it("recomputes the decision when the scope key changes", () => {
+ setHistoryEntry("entry-1");
+ const { result, rerender } = renderHook(
+ ({ scope }: { scope: string }) => useHistoryEntryRevisit(scope),
+ { initialProps: { scope: "session-1" } },
+ );
+ expect(result.current).toBe(false);
+
+ // Navigate to another session (push, new entry) β€” fresh for that scope.
+ setHistoryEntry("entry-2");
+ mockRouter.asPath = "/project/p1/sessions/s2";
+ rerender({ scope: "session-2" });
+ expect(result.current).toBe(false);
+
+ // Pop back to the first session's entry with a scope change: the entry
+ // was left, so the new scope's arrival is a revisit.
+ setHistoryEntry("entry-1");
+ mockRouter.asPath = "/project/p1/sessions/s1";
+ rerender({ scope: "session-1" });
+ expect(result.current).toBe(true);
+ });
+
+ it("does not flag a fresh arrival as revisit under StrictMode double-mounting", () => {
+ setHistoryEntry("entry-1");
+
+ const { result } = renderHook(() => useHistoryEntryRevisit("session-1"), {
+ wrapper: StrictMode,
+ });
+
+ expect(result.current).toBe(false);
+ });
+
+ it("degrades to fresh when the history entry has no key", () => {
+ setHistoryEntry(null);
+
+ const { result, unmount } = renderHook(() =>
+ useHistoryEntryRevisit("session-1"),
+ );
+
+ expect(result.current).toBe(false);
+ expect(() => unmount()).not.toThrow();
+ });
+});
diff --git a/web/src/components/session/useHistoryEntryRevisit.ts b/web/src/components/session/useHistoryEntryRevisit.ts
new file mode 100644
index 0000000000..9af003032f
--- /dev/null
+++ b/web/src/components/session/useHistoryEntryRevisit.ts
@@ -0,0 +1,94 @@
+import { useRouter } from "next/router";
+import { useEffect, useRef } from "react";
+
+/**
+ * Detects whether the current page arrival is a *revisit* of a browser
+ * history entry (Back/Forward) rather than a fresh navigation (LFE-10715).
+ *
+ * The session-detail page auto-applies a default view when the URL carries no
+ * `viewId`. That is only correct on a fresh arrival: when the user reaches a
+ * param-less URL through Back/Forward, the entry's state β€” including "no view
+ * selected" β€” was already decided when the entry was live, and re-applying
+ * the default would overwrite it (pre-fix it even *pushed*, so Back bounced
+ * forward and was unusable).
+ *
+ * Mechanism: the Next.js Pages Router stamps every history entry with a
+ * stable per-entry `key` in `window.history.state` (`replaceState` keeps the
+ * current key, `pushState` mints a new one). An entry's key is recorded in
+ * sessionStorage when the entry is *left* β€” in-page query navigation,
+ * page-leave unmount β€” never on arrival, so a StrictMode double-mount cannot
+ * poison a fresh arrival, and a reload (same key, never left) still counts as
+ * fresh. Arriving on a recorded key β‡’ revisit.
+ *
+ * The decision is snapshotted per arrival (mount, or `scopeKey` change for
+ * in-place detail navigation like prev/next session) and stays stable for
+ * that arrival's lifetime; same-mount pops are the caller's concern. Missing
+ * key or unavailable sessionStorage degrades to "fresh".
+ */
+
+const STORAGE_KEY = "lf-visited-history-entries";
+const MAX_TRACKED_ENTRIES = 100;
+
+const readHistoryEntryKey = (): string | null => {
+ if (typeof window === "undefined") return null;
+ const state: unknown = window.history.state;
+ if (typeof state !== "object" || state === null) return null;
+ const key = (state as { key?: unknown }).key;
+ return typeof key === "string" ? key : null;
+};
+
+const readVisitedKeys = (): string[] => {
+ try {
+ const raw = window.sessionStorage.getItem(STORAGE_KEY);
+ if (!raw) return [];
+ const parsed: unknown = JSON.parse(raw);
+ return Array.isArray(parsed)
+ ? parsed.filter((key): key is string => typeof key === "string")
+ : [];
+ } catch {
+ return [];
+ }
+};
+
+const wasHistoryEntryVisited = (key: string): boolean =>
+ readVisitedKeys().includes(key);
+
+const markHistoryEntryVisited = (key: string): void => {
+ try {
+ const keys = readVisitedKeys().filter((visited) => visited !== key);
+ keys.push(key);
+ window.sessionStorage.setItem(
+ STORAGE_KEY,
+ JSON.stringify(keys.slice(-MAX_TRACKED_ENTRIES)),
+ );
+ } catch {
+ // sessionStorage unavailable β†’ every arrival counts as fresh.
+ }
+};
+
+export function useHistoryEntryRevisit(scopeKey: string): boolean {
+ const router = useRouter();
+
+ // Guarded render-phase snapshot (same pattern as the session page's
+ // initialViewIdSessionRef): computed once per arrival, before any effect
+ // can record the entry, and preserved across StrictMode remounts.
+ const decisionRef = useRef<{ scope: string; revisit: boolean } | null>(null);
+ if (decisionRef.current === null || decisionRef.current.scope !== scopeKey) {
+ const entryKey = readHistoryEntryKey();
+ decisionRef.current = {
+ scope: scopeKey,
+ revisit: entryKey !== null && wasHistoryEntryVisited(entryKey),
+ };
+ }
+
+ // Record the active entry as visited when it is left: cleanup fires on
+ // every asPath change (in-page pushes/pops included) and on unmount.
+ const asPath = router.asPath;
+ useEffect(() => {
+ const entryKey = readHistoryEntryKey();
+ if (entryKey === null) return;
+ return () => markHistoryEntryVisited(entryKey);
+ }, [asPath]);
+
+ return decisionRef.current.revisit;
+}
diff --git a/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts b/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts
index 0b3ba5c138..7ec940dd99 100644
--- a/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts
+++ b/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts
@@ -9,7 +9,7 @@ import {
import { type NextRouter, useRouter } from "next/router";
import { useEffect, useCallback, useState, useRef } from "react";
import { type VisibilityState } from "@tanstack/react-table";
-import { StringParam } from "use-query-params";
+import { StringParam, type UrlUpdateType } from "use-query-params";
import useSessionStorage from "@/src/components/useSessionStorage";
import { useQueryParam } from "use-query-params";
import { type LangfuseColumnDef } from "@/src/components/table/types";
@@ -122,11 +122,16 @@ export function useTableViewManager({
},
);
- // Keep track of the viewId in session storage and in the query params
+ // Keep track of the viewId in session storage and in the query params.
+ // `updateType` controls the browser-history semantics of the URL write:
+ // user-initiated selections keep the default (push β€” a Back-able step),
+ // while programmatic corrections pass `replaceIn` so the pre-write URL does
+ // not survive as a history entry that Back lands on and that re-triggers
+ // the write (LFE-10715).
const handleSetViewId = useCallback(
- (viewId: string | null) => {
+ (viewId: string | null, options?: { updateType?: UrlUpdateType }) => {
setStoredViewId(viewId);
- setSelectedViewId(viewId);
+ setSelectedViewId(viewId, options?.updateType);
// Explicitly selecting "My view (default)" should stop bootstrap restore.
// Otherwise an in-flight bootstrap can restore a previously selected view.
@@ -179,7 +184,7 @@ export function useTableViewManager({
isSystemPresetId(selectedViewId) &&
!allowBackendSystemPresets
) {
- handleSetViewId(null);
+ handleSetViewId(null, { updateType: "replaceIn" });
return;
}
@@ -223,7 +228,7 @@ export function useTableViewManager({
if (defaultViewId) {
if (isSystemPresetId(defaultViewId) && !allowBackendSystemPresets) {
- handleSetViewId(null);
+ handleSetViewId(null, { updateType: "replaceIn" });
return;
}
setStoredViewId(defaultViewId);
@@ -398,7 +403,7 @@ export function useTableViewManager({
if (selectedViewIdRef.current !== requestedViewId) return;
if (selectedViewData.id !== requestedViewId) return;
if (!isViewApplicableToTable(tableName, selectedViewData.tableName)) {
- handleSetViewId(null);
+ handleSetViewId(null, { updateType: "replaceIn" });
return;
}
@@ -440,7 +445,7 @@ export function useTableViewManager({
isInitializedRef.current = true;
setIsInitialized(true);
setIsLoading(false);
- handleSetViewId(null);
+ handleSetViewId(null, { updateType: "replaceIn" });
showErrorToast("Error applying view", selectedViewError.message, "WARNING");
}, [
disabled,
diff --git a/web/src/features/filters/hooks/useSidebarFilterState.tsx b/web/src/features/filters/hooks/useSidebarFilterState.tsx
index 451728d2ed..714c8730d8 100644
--- a/web/src/features/filters/hooks/useSidebarFilterState.tsx
+++ b/web/src/features/filters/hooks/useSidebarFilterState.tsx
@@ -1,6 +1,10 @@
import type React from "react";
import { useCallback, useMemo, useEffect, useState } from "react";
-import { StringParam, useQueryParam } from "use-query-params";
+import {
+ StringParam,
+ useQueryParam,
+ type UrlUpdateType,
+} from "use-query-params";
import {
type FilterState,
singleFilter,
@@ -665,8 +669,13 @@ export function useSidebarFilterState(
],
);
+ // `options.updateType` controls the history semantics of the URL write:
+ // user-initiated filter edits keep the default (push β€” a Back-able step);
+ // programmatic writes (e.g. the session default-view auto-apply) pass
+ // `replaceIn` so they don't mint a history entry Back would bounce off
+ // (LFE-10715). Ignored for non-URL state locations.
const setFilterState = useCallback(
- (newFilters: FilterState) => {
+ (newFilters: FilterState, options?: { updateType?: UrlUpdateType }) => {
const explicitFilters = stripImplicitEnvironmentFilterFromExplicitState({
explicitFilters: newFilters,
config: managedEnvironmentPolicyConfig,
@@ -687,7 +696,7 @@ export function useSidebarFilterState(
const encoded = encodeFiltersGeneric(explicitFilters);
setPendingFiltersQuery(encoded);
- setUrlFiltersQuery(encoded || null);
+ setUrlFiltersQuery(encoded || null, options?.updateType);
if (stateLocationType === "urlAndSessionStorage") {
setStoredFiltersQuery(encoded);
}
@@ -736,7 +745,10 @@ export function useSidebarFilterState(
if (typeof urlFiltersQuery === "string") {
if (urlFiltersQuery !== canonicalFiltersQuery) {
setPendingFiltersQuery(canonicalFiltersQuery);
- setUrlFiltersQuery(canonicalFiltersQuery || null);
+ // replaceIn: sanitizing is a programmatic correction of the current
+ // URL β€” pushing would mint a history entry holding the non-canonical
+ // filter, which Back lands on and this effect re-fires (LFE-10715).
+ setUrlFiltersQuery(canonicalFiltersQuery || null, "replaceIn");
}
if (
diff --git a/web/src/features/filters/viewStateHistoryWrites.clienttest.tsx b/web/src/features/filters/viewStateHistoryWrites.clienttest.tsx
new file mode 100644
index 0000000000..d3e5e34552
--- /dev/null
+++ b/web/src/features/filters/viewStateHistoryWrites.clienttest.tsx
@@ -0,0 +1,332 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { TableViewPresetTableName, type FilterState } from "@langfuse/shared";
+import { useState } from "react";
+import { useSidebarFilterState } from "./hooks/useSidebarFilterState";
+import type { FilterConfig } from "./lib/filter-config";
+import { useTableViewManager } from "../../components/table/table-view-presets/hooks/useTableViewManager";
+
+// LFE-10715: programmatic view-state URL writes (stripping a stale frontend
+// system-preset viewId, auto-applying the session default view) must REPLACE
+// the current history entry, not push a new one. A push turns the pre-write
+// URL into a separate history entry, so the browser Back button lands on it
+// and the write re-triggers β€” Back bounces forward and is unusable.
+
+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 TEST_FILTER_CONFIG: FilterConfig = {
+ tableName: "traces",
+ columnDefinitions: [
+ {
+ id: "name",
+ name: "Name",
+ type: "stringOptions",
+ options: [],
+ internal: "name",
+ },
+ ],
+ facets: [
+ {
+ type: "categorical",
+ column: "name",
+ label: "Name",
+ },
+ ],
+};
+
+const TEST_FILTERS: FilterState = [
+ {
+ column: "name",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["checkout"],
+ },
+];
+
+function ViewManagerHarness({
+ tableName = TableViewPresetTableName.SessionDetail,
+}: {
+ tableName?: TableViewPresetTableName;
+}) {
+ const [appliedFilters, setAppliedFilters] = useState<FilterState>([]);
+ const { selectedViewId, handleSetViewId } = useTableViewManager({
+ tableName,
+ projectId: "project-1",
+ stateUpdaters: {
+ setFilters: setAppliedFilters,
+ setColumnOrder: () => {},
+ setColumnVisibility: () => {},
+ },
+ validationContext: {
+ columns: [],
+ filterColumnDefinition: TEST_FILTER_CONFIG.columnDefinitions,
+ },
+ currentFilterState: appliedFilters,
+ });
+
+ return (
+ <div>
+ <div data-testid="selected-view-id">{selectedViewId ?? "null"}</div>
+ <button
+ onClick={() => handleSetViewId("view-1", { updateType: "replaceIn" })}
+ >
+ set-view-replace
+ </button>
+ <button onClick={() => handleSetViewId("view-1")}>set-view</button>
+ </div>
+ );
+}
+
+function FilterStateHarness() {
+ const queryFilter = useSidebarFilterState(
+ TEST_FILTER_CONFIG,
+ { name: ["checkout", "search"] },
+ {
+ stateLocation: "urlAndSessionStorage",
+ sessionFilterContextId: "project-1",
+ },
+ );
+
+ return (
+ <div>
+ <pre data-testid="explicit-state">
+ {JSON.stringify(queryFilter.explicitFilterState)}
+ </pre>
+ <button
+ onClick={() =>
+ queryFilter.setFilterState(TEST_FILTERS, { updateType: "replaceIn" })
+ }
+ >
+ set-filters-replace
+ </button>
+ <button onClick={() => queryFilter.setFilterState(TEST_FILTERS)}>
+ set-filters
+ </button>
+ </div>
+ );
+}
+
+describe("view-state URL writes and browser history (LFE-10715)", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ sessionStorage.clear();
+ queryParamStore.clear();
+ urlParamWrites.length = 0;
+
+ mockUseRouter.mockReturnValue({
+ isReady: true,
+ query: {},
+ });
+ mockGetDefaultUseQuery.mockReturnValue({
+ data: null,
+ isLoading: false,
+ });
+ mockGetByIdUseQuery.mockReturnValue({
+ data: undefined,
+ error: null,
+ isSuccess: false,
+ isError: false,
+ });
+ });
+
+ it("strips a stale frontend system-preset viewId with a replace, not a push", async () => {
+ queryParamStore.set("viewId", "__langfuse_with_io__");
+ mockUseRouter.mockReturnValue({
+ isReady: true,
+ query: { viewId: "__langfuse_with_io__" },
+ });
+
+ render(<ViewManagerHarness />);
+
+ await waitFor(() => {
+ expect(screen.getByTestId("selected-view-id").textContent).toBe("null");
+ });
+
+ const viewIdWrites = urlParamWrites.filter(
+ (write) => write.key === "viewId",
+ );
+ expect(viewIdWrites.length).toBeGreaterThan(0);
+ for (const write of viewIdWrites) {
+ expect(write).toMatchObject({ value: null, updateType: "replaceIn" });
+ }
+ });
+
+ it("forwards a replaceIn updateType through handleSetViewId", async () => {
+ render(<ViewManagerHarness tableName={TableViewPresetTableName.Traces} />);
+
+ fireEvent.click(screen.getByRole("button", { name: "set-view-replace" }));
+
+ await waitFor(() => {
+ expect(
+ urlParamWrites.filter((write) => write.key === "viewId"),
+ ).toContainEqual({
+ key: "viewId",
+ value: "view-1",
+ updateType: "replaceIn",
+ });
+ });
+ });
+
+ it("keeps user-initiated view selection on the default (push) updateType", async () => {
+ render(<ViewManagerHarness tableName={TableViewPresetTableName.Traces} />);
+
+ fireEvent.click(screen.getByRole("button", { name: "set-view" }));
+
+ await waitFor(() => {
+ expect(
+ urlParamWrites.filter((write) => write.key === "viewId"),
+ ).toContainEqual({
+ key: "viewId",
+ value: "view-1",
+ updateType: undefined,
+ });
+ });
+ });
+
+ it("forwards a replaceIn updateType through setFilterState", async () => {
+ render(<FilterStateHarness />);
+
+ fireEvent.click(
+ screen.getByRole("button", { name: "set-filters-replace" }),
+ );
+
+ await waitFor(() => {
+ const filterWrites = urlParamWrites.filter(
+ (write) => write.key === "filter",
+ );
+ expect(filterWrites.length).toBeGreaterThan(0);
+ expect(filterWrites.at(-1)?.updateType).toBe("replaceIn");
+ });
+ });
+
+ it("sanitizes a non-canonical URL filter with a replace, not a push", async () => {
+ // A bookmarked/shared URL can carry a filter that decodes to a different
+ // canonical form (display-name column, alias, migrated legacy shape). The
+ // sanitize effect rewrites the URL on mount β€” a programmatic correction
+ // that must not mint a history entry, or Back bounces off it re-firing
+ // the sanitize (same LFE-10715 class as the viewId writes).
+ const { encodeFiltersGeneric } =
+ await import("./lib/filter-query-encoding");
+ const canonical = encodeFiltersGeneric(TEST_FILTERS);
+ expect(canonical.startsWith("name;")).toBe(true);
+ const nonCanonical = canonical.replace(/^name;/, "Name;");
+ queryParamStore.set("filter", nonCanonical);
+ mockUseRouter.mockReturnValue({
+ isReady: true,
+ query: { filter: nonCanonical },
+ });
+
+ render(<FilterStateHarness />);
+
+ await waitFor(() => {
+ const filterWrites = urlParamWrites.filter(
+ (write) => write.key === "filter",
+ );
+ expect(filterWrites.length).toBeGreaterThan(0);
+ expect(filterWrites.at(-1)).toMatchObject({
+ value: canonical,
+ updateType: "replaceIn",
+ });
+ });
+ });
+
+ it("keeps user-initiated filter edits on the default (push) updateType", async () => {
+ render(<FilterStateHarness />);
+
+ fireEvent.click(screen.getByRole("button", { name: "set-filters" }));
+
+ await waitFor(() => {
+ const filterWrites = urlParamWrites.filter(
+ (write) => write.key === "filter",
+ );
+ expect(filterWrites.length).toBeGreaterThan(0);
+ expect(filterWrites.at(-1)?.updateType).toBeUndefined();
+ });
+ });
+});