Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(filters): default hide langfuse environments (#12346)

Nimar84f0eef58392
diff --git a/AGENTS.md b/AGENTS.md
index 8c32a4c8ea..da31bb0480 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -73,6 +73,7 @@ Minimum verification matrix:
- Keep each test independent and parallel-safe.
- `web/src/__tests__/server`: avoid `pruneDatabase` calls.
- Client tests contain `....clienttest.ts`
+- When you write a test for a bug or similar, write the test that fails first. Check that it fails. Only then fix the bug. Otherwise, the test is not good!
## Commit & Pull Request Guidelines
- Follow Conventional Commits.
diff --git a/web/src/components/session/index.tsx b/web/src/components/session/index.tsx
index 1e9c3e2322..55f63320e5 100644
--- a/web/src/components/session/index.tsx
+++ b/web/src/components/session/index.tsx
@@ -54,7 +54,11 @@ import {
decodeAndNormalizeFilters,
useSidebarFilterState,
} from "@/src/features/filters/hooks/useSidebarFilterState";
-import { StringParam, useQueryParam, withDefault } from "use-query-params";
+import {
+ buildSidebarFilterQueryStorageKey,
+ readPersistedSidebarFilterQuery,
+} from "@/src/features/filters/lib/persistedSidebarFilterQuery";
+import { StringParam, useQueryParam } from "use-query-params";
import { PopoverFilterBuilder } from "@/src/features/filters/components/filter-builder";
import { useTableViewManager } from "@/src/components/table/table-view-presets/hooks/useTableViewManager";
import {
@@ -644,8 +648,23 @@ export const SessionEventsPage: React.FC<{
detailPagelists.traces,
]);
- // Decode time filters from URL for scoping filter options
- const [filtersQuery] = useQueryParam("filter", withDefault(StringParam, ""));
+ const sessionEventsTableName = "session-events";
+ const sessionFilterStorageKey = buildSidebarFilterQueryStorageKey({
+ tableName: sessionEventsTableName,
+ contextId: projectId,
+ });
+ const [urlFiltersQuery] = useQueryParam("filter", StringParam);
+ const filtersQuery = React.useMemo(
+ () =>
+ urlFiltersQuery ??
+ readPersistedSidebarFilterQuery({
+ storageKey: sessionFilterStorageKey,
+ contextId: projectId,
+ }),
+ [urlFiltersQuery, sessionFilterStorageKey, projectId],
+ );
+
+ // Decode time filters from URL/session filter state for scoping filter options
const timeFiltersForOptions = React.useMemo(() => {
const allFilters = decodeAndNormalizeFilters(
filtersQuery,
@@ -666,7 +685,7 @@ export const SessionEventsPage: React.FC<{
const sessionEventsFilterConfig = React.useMemo(() => {
return {
...observationEventsFilterConfig,
- tableName: "session-events",
+ tableName: sessionEventsTableName,
columnDefinitions: observationEventsFilterConfig.columnDefinitions,
facets: observationEventsFilterConfig.facets
.filter(
@@ -680,7 +699,7 @@ export const SessionEventsPage: React.FC<{
mutuallyExclusiveWith: undefined,
})),
};
- }, []);
+ }, [sessionEventsTableName]);
const filterColumns = React.useMemo<ColumnDefinition[]>(() => {
const scoreCategoryOptions = filterOptions.score_categories
@@ -753,8 +772,10 @@ export const SessionEventsPage: React.FC<{
const queryFilter = useSidebarFilterState(
sessionEventsFilterConfig,
filterOptions,
- projectId,
- isFilterOptionsPending,
+ {
+ loading: isFilterOptionsPending,
+ sessionFilterContextId: projectId,
+ },
);
const visibleFilterState = React.useMemo(
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 12fa9b4405..ac00d0f6d4 100644
--- a/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts
+++ b/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts
@@ -10,7 +10,7 @@ import { type DefaultViewScope } from "@langfuse/shared/src/server";
import { useRouter } from "next/router";
import { useEffect, useCallback, useState, useRef } from "react";
import { type VisibilityState } from "@tanstack/react-table";
-import { StringParam, withDefault } from "use-query-params";
+import { StringParam } from "use-query-params";
import useSessionStorage from "@/src/components/useSessionStorage";
import { useQueryParam } from "use-query-params";
import { type LangfuseColumnDef } from "@/src/components/table/types";
@@ -50,20 +50,26 @@ export function useTableViewManager({
currentFilterState,
}: UseTableStateProps) {
const router = useRouter();
- const { viewId } = router.query;
+ const isRouterReady = router.isReady;
const [isInitialized, setIsInitialized] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const capture = usePostHogClientCapture();
const pendingFiltersRef = useRef<FilterState | null>(null);
+ const pendingFiltersPreviousStateRef = useRef<FilterState | null>(null);
const [storedViewId, setStoredViewId] = useSessionStorage<string | null>(
`${tableName}-${projectId}-viewId`,
null,
);
- const [selectedViewId, setSelectedViewId] = useQueryParam(
+ const [selectedViewIdParam, setSelectedViewId] = useQueryParam(
"viewId",
- withDefault(StringParam, storedViewId),
+ StringParam,
);
+ const selectedViewId = selectedViewIdParam ?? null;
+ const selectedViewIdRef = useRef<string | null>(selectedViewId);
+ selectedViewIdRef.current = selectedViewId;
+ const isInitializedRef = useRef(isInitialized);
+ isInitializedRef.current = isInitialized;
// Query for resolved default view (user > project > null)
const { data: resolvedDefault, isLoading: isDefaultLoading } =
@@ -78,16 +84,16 @@ export function useTableViewManager({
// Keep track of the viewId in session storage and in the query params
const handleSetViewId = useCallback(
(viewId: string | null) => {
- // to ensure immediate sync -> update URL
- const url = new URL(window.location.href);
- if (viewId === null) {
- url.searchParams.delete("viewId");
- } else {
- url.searchParams.set("viewId", viewId);
- }
- window.history.replaceState({}, "", url.toString());
setStoredViewId(viewId);
setSelectedViewId(viewId);
+
+ // Explicitly selecting "My view (default)" should stop bootstrap restore.
+ // Otherwise an in-flight bootstrap can restore a previously selected view.
+ if (viewId === null && !isInitializedRef.current) {
+ isInitializedRef.current = true;
+ setIsInitialized(true);
+ setIsLoading(false);
+ }
},
[setStoredViewId, setSelectedViewId],
);
@@ -112,43 +118,34 @@ export function useTableViewManager({
setOrderByRef.current = setOrderBy;
setSearchQueryRef.current = setSearchQuery;
- // Ref to prevent re-dispatching setSelectedViewId while waiting for router.query to catch up.
- const pendingResolveRef = useRef(false);
// Extract primitive for effect dep (rerender-dependencies: avoid object deps)
const defaultViewId = resolvedDefault?.viewId;
// Single resolve effect: walk priority list and either return early (pending) or initialize.
- //
- // IMPORTANT: This effect must NOT call handleSetViewId to set a viewId, because
- // handleSetViewId does replaceState before setSelectedViewId.
- // use-query-params reads window.location.search to detect changes,
- // so the prior replaceState makes it think nothing changed (skipUpdateWhenNoChange)
- // → router.replace is never called → router.query never updates → getById query never fires.
- // Instead, call setSelectedViewId directly so use-query-params sees a genuine URL change.
+ // `selectedViewId` (use-query-params state) is the single source of truth for bootstrap/fetch.
useEffect(() => {
if (isInitialized) return;
+ if (!isRouterReady) return;
- // If viewId already in router.query and not a system preset → getById query handles it.
+ // If viewId already in URL and not a system preset → getById query handles it.
// Sync to session storage so navigating away and back restores the view.
- if (viewId && !isSystemPresetId(viewId as string)) {
- setStoredViewId(viewId as string);
+ if (selectedViewId && !isSystemPresetId(selectedViewId)) {
+ if (storedViewId !== selectedViewId) {
+ setStoredViewId(selectedViewId);
+ }
return;
}
- // Already dispatched a viewId via setSelectedViewId, waiting for router.query to update
- if (pendingResolveRef.current) return;
-
- // Clear stale system preset from URL (e.g. navigated from session detail)
- if (viewId && isSystemPresetId(viewId as string)) {
+ // Clear stale system preset from URL (e.g. navigated from session detail).
+ if (selectedViewId && isSystemPresetId(selectedViewId)) {
handleSetViewId(null);
- // fall through to resolve from other sources
+ return;
}
// Priority 1: Session storage (from a previous visit to this table)
if (storedViewId && !isSystemPresetId(storedViewId)) {
- pendingResolveRef.current = true;
setSelectedViewId(storedViewId);
- return; // router.query updates next render → early return above → getById fires
+ return;
}
// Priority 2: Default view (wait for query to resolve)
@@ -156,24 +153,22 @@ export function useTableViewManager({
if (defaultViewId) {
if (isSystemPresetId(defaultViewId)) {
- // System presets don't need data fetching, initialize immediately
- setSelectedViewId(defaultViewId);
- setIsInitialized(true);
- setIsLoading(false);
+ // Resolved defaults should never point to system presets; clear if they do.
+ handleSetViewId(null);
return;
}
- pendingResolveRef.current = true;
setStoredViewId(defaultViewId);
setSelectedViewId(defaultViewId);
- return; // router.query updates next render → early return above → getById fires
+ return;
}
// Priority 3: Nothing to apply
setIsInitialized(true);
setIsLoading(false);
}, [
- viewId,
isInitialized,
+ isRouterReady,
+ selectedViewId,
storedViewId,
isDefaultLoading,
defaultViewId,
@@ -182,16 +177,6 @@ export function useTableViewManager({
setSelectedViewId,
]);
- // Fetch view data if viewId is provided (skip for system presets)
- const { data: viewData, error: viewError } =
- api.TableViewPresets.getById.useQuery(
- { viewId: viewId as string, projectId },
- {
- enabled:
- !!viewId && !isInitialized && !isSystemPresetId(viewId as string),
- },
- );
-
// Method to apply state from a view
const applyViewState = useCallback(
(viewData: TableViewPresetDomain) => {
@@ -236,9 +221,12 @@ export function useTableViewManager({
if (setFiltersRef.current) {
setFiltersRef.current(validFilters);
// Track expected filters to observe when state actually updates (for useEffect below)
- // If filters are already applied, don't set pending ref (will unlock immediately)
+ // If filters are already applied, don't set pending ref (will unlock immediately).
+ // Also track pre-apply state so we can unlock when filters propagate but get
+ // canonicalized into an equivalent shape by downstream hooks.
if (!filtersAlreadyApplied) {
pendingFiltersRef.current = validFilters;
+ pendingFiltersPreviousStateRef.current = currentFilterState ?? [];
}
}
@@ -269,48 +257,84 @@ export function useTableViewManager({
],
);
- // Handle successful view data fetch
+ // Fetch view data if viewId is provided (skip for system presets)
+ const {
+ data: selectedViewData,
+ error: selectedViewError,
+ isSuccess: isSelectedViewSuccess,
+ isError: isSelectedViewError,
+ } = api.TableViewPresets.getById.useQuery(
+ { viewId: selectedViewId as string, projectId },
+ {
+ enabled:
+ isRouterReady &&
+ !!selectedViewId &&
+ !isInitialized &&
+ !isSystemPresetId(selectedViewId),
+ },
+ );
+
useEffect(() => {
- if (viewData && !isInitialized) {
- // Track permalink visit
- capture("saved_views:permalink_visit", {
- tableName,
- viewId: viewId as string,
- name: viewData.name,
- });
-
- applyViewState(viewData);
- setIsInitialized(true);
- }
+ if (!isSelectedViewSuccess || !selectedViewData) return;
+ const requestedViewId = selectedViewId;
+ if (!requestedViewId) return;
+ if (isInitializedRef.current) return;
+ if (selectedViewIdRef.current !== requestedViewId) return;
+ if (selectedViewData.id !== requestedViewId) return;
+
+ // Track permalink visit
+ capture("saved_views:permalink_visit", {
+ tableName,
+ viewId: requestedViewId,
+ name: selectedViewData.name,
+ });
+
+ applyViewState(selectedViewData);
+ isInitializedRef.current = true;
+ setIsInitialized(true);
}, [
- viewData,
- isInitialized,
+ isSelectedViewSuccess,
+ selectedViewData,
+ selectedViewId,
capture,
tableName,
- viewId,
applyViewState,
- setIsLoading,
]);
- // Handle view data fetch error
useEffect(() => {
- if (viewError && !isInitialized) {
- setIsInitialized(true);
- setIsLoading(false);
- handleSetViewId(null);
- showErrorToast("Error applying view", viewError.message, "WARNING");
- }
- }, [viewError, isInitialized, setIsLoading, handleSetViewId]);
+ if (!isSelectedViewError || !selectedViewError) return;
+ const requestedViewId = selectedViewId;
+ if (!requestedViewId) return;
+ if (isInitializedRef.current) return;
+ if (selectedViewIdRef.current !== requestedViewId) return;
+
+ isInitializedRef.current = true;
+ setIsInitialized(true);
+ setIsLoading(false);
+ handleSetViewId(null);
+ showErrorToast("Error applying view", selectedViewError.message, "WARNING");
+ }, [isSelectedViewError, selectedViewError, selectedViewId, handleSetViewId]);
// Observe when filter state propagates from saved view
// After calling setFilters, URL updates async → filterState recalculates → this effect detects completion
useEffect(() => {
- if (pendingFiltersRef.current && currentFilterState) {
- if (isEqual(currentFilterState, pendingFiltersRef.current)) {
- // Filter state has synchronized - safe to unlock table
- pendingFiltersRef.current = null;
- setIsLoading(false);
- }
+ const pendingFilters = pendingFiltersRef.current;
+ if (!pendingFilters || currentFilterState === undefined) return;
+
+ const preApplyFilters = pendingFiltersPreviousStateRef.current ?? [];
+ const hasExpectedShape = isEqual(currentFilterState, pendingFilters);
+ const hasPropagatedWithCanonicalization = !isEqual(
+ currentFilterState,
+ preApplyFilters,
+ );
+
+ if (hasExpectedShape || hasPropagatedWithCanonicalization) {
+ // Filter state has synchronized - safe to unlock table.
+ // `hasPropagatedWithCanonicalization` handles equivalent rewrites
+ // (for example legacy env-delta -> canonical none-of shape).
+ pendingFiltersRef.current = null;
+ pendingFiltersPreviousStateRef.current = null;
+ setIsLoading(false);
}
}, [currentFilterState]);
diff --git a/web/src/components/table/use-cases/observations.tsx b/web/src/components/table/use-cases/observations.tsx
index 24e4f4d239..12d001a741 100644
--- a/web/src/components/table/use-cases/observations.tsx
+++ b/web/src/components/table/use-cases/observations.tsx
@@ -15,6 +15,7 @@ import {
observationFilterConfig,
OBSERVATION_COLUMN_TO_BACKEND_KEY,
} from "@/src/features/filters/config/observations-config";
+import { DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG } from "@/src/features/filters/constants/internal-environments";
import { transformFiltersForBackend } from "@/src/features/filters/lib/filter-transform";
import { formatIntervalSeconds } from "@/src/utils/dates";
import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";
@@ -434,9 +435,13 @@ export default function ObservationsTable({
const queryFilter = useSidebarFilterState(
observationFilterConfig,
newFilterOptions,
- projectId,
- filterOptions.isPending || environmentFilterOptions.isPending,
- hideControls, // Disable URL persistence for embedded preview tables
+ {
+ loading: filterOptions.isPending || environmentFilterOptions.isPending,
+ disableUrlPersistence: hideControls, // Disable URL persistence for embedded preview tables
+ sessionFilterContextId: projectId,
+ // Sidebar-only implicit environment defaults
+ implicitDefaultConfig: DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG,
+ },
);
// Create ref-based wrapper to avoid stale closure when queryFilter updates
@@ -448,7 +453,7 @@ export default function ObservationsTable({
[],
);
- const combinedFilterState = queryFilter.filterState.concat(
+ const combinedFilterState = queryFilter.effectiveFilterState.concat(
dateRangeFilter,
promptNameFilter,
promptVersionFilter,
@@ -1219,7 +1224,7 @@ export default function ObservationsTable({
columns,
filterColumnDefinition: observationFilterConfig.columnDefinitions,
},
- currentFilterState: queryFilter.filterState,
+ currentFilterState: queryFilter.explicitFilterState,
});
const peekConfig: DataTablePeekViewProps | undefined = useMemo(() => {
@@ -1285,7 +1290,7 @@ export default function ObservationsTable({
{!hideControls && (
<DataTableToolbar
columns={columns}
- filterState={queryFilter.filterState}
+ filterState={queryFilter.explicitFilterState}
searchConfig={{
metadataSearchFields: ["ID", "Name", "Trace Name", "Model"],
updateQuery: setSearchQuery,
diff --git a/web/src/components/table/use-cases/scores.tsx b/web/src/components/table/use-cases/scores.tsx
index fe44b9018c..d0959353ab 100644
--- a/web/src/components/table/use-cases/scores.tsx
+++ b/web/src/components/table/use-cases/scores.tsx
@@ -16,6 +16,7 @@ import {
scoreFilterConfig,
SCORE_COLUMN_TO_BACKEND_KEY,
} from "@/src/features/filters/config/scores-config";
+import { DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG } from "@/src/features/filters/constants/internal-environments";
import { transformFiltersForBackend } from "@/src/features/filters/lib/filter-transform";
import { isNumericDataType } from "@/src/features/scores/lib/helpers";
import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";
@@ -288,9 +289,13 @@ export default function ScoresTable({
const queryFilter = useSidebarFilterState(
scoreFilterConfig,
newFilterOptions,
- projectId,
- filterOptions.isPending || environmentFilterOptions.isPending,
- disableUrlPersistence,
+ {
+ loading: filterOptions.isPending || environmentFilterOptions.isPending,
+ disableUrlPersistence,
+ sessionFilterContextId: projectId,
+ // Sidebar-only implicit environment defaults
+ implicitDefaultConfig: DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG,
+ },
);
// Create ref-based wrapper to avoid stale closure when queryFilter updates
@@ -303,7 +308,7 @@ export default function ScoresTable({
);
const filterState = createFilterState(
- queryFilter.filterState.concat(dateRangeFilter),
+ queryFilter.effectiveFilterState.concat(dateRangeFilter),
[
...(userId ? [{ key: "User ID", value: userId }] : []),
...(traceId ? [{ key: "Trace ID", value: traceId }] : []),
@@ -815,7 +820,7 @@ export default function ScoresTable({
columns,
filterColumnDefinition: scoreFilterConfig.columnDefinitions,
},
- currentFilterState: queryFilter.filterState,
+ currentFilterState: queryFilter.explicitFilterState,
});
return (
@@ -827,7 +832,7 @@ export default function ScoresTable({
{/* Toolbar spanning full width */}
<DataTableToolbar
columns={columns}
- filterState={queryFilter.filterState}
+ filterState={queryFilter.explicitFilterState}
columnVisibility={columnVisibility}
setColumnVisibility={setColumnVisibility}
columnOrder={columnOrder}
diff --git a/web/src/components/table/use-cases/sessions.tsx b/web/src/components/table/use-cases/sessions.tsx
index a9864436f5..3951169295 100644
--- a/web/src/components/table/use-cases/sessions.tsx
+++ b/web/src/components/table/use-cases/sessions.tsx
@@ -15,6 +15,7 @@ import {
sessionFilterConfig,
SESSION_COLUMN_TO_BACKEND_KEY,
} from "@/src/features/filters/config/sessions-config";
+import { DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG } from "@/src/features/filters/constants/internal-environments";
import { transformFiltersForBackend } from "@/src/features/filters/lib/filter-transform";
import {
type FilterState,
@@ -240,8 +241,12 @@ export default function SessionsTable({
const queryFilter = useSidebarFilterState(
sessionFilterConfig,
newFilterOptions,
- projectId,
- filterOptions.isPending || environmentFilterOptions.isPending,
+ {
+ loading: filterOptions.isPending || environmentFilterOptions.isPending,
+ sessionFilterContextId: projectId,
+ // Sidebar-only implicit environment defaults
+ implicitDefaultConfig: DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG,
+ },
);
// Create ref-based wrapper to avoid stale closure when queryFilter updates
@@ -253,7 +258,7 @@ export default function SessionsTable({
[],
);
- const combinedFilterState = queryFilter.filterState.concat(
+ const combinedFilterState = queryFilter.effectiveFilterState.concat(
userIdFilter,
dateRangeFilter,
);
@@ -751,7 +756,7 @@ export default function SessionsTable({
columns,
filterColumnDefinition: sessionFilterConfig.columnDefinitions,
},
- currentFilterState: queryFilter.filterState,
+ currentFilterState: queryFilter.explicitFilterState,
});
return (
@@ -759,7 +764,7 @@ export default function SessionsTable({
<div className="flex h-full w-full flex-col">
{/* Toolbar spanning full width */}
<DataTableToolbar
- filterState={queryFilter.filterState}
+ filterState={queryFilter.explicitFilterState}
actionButtons={[
Object.keys(selectedRows).filter((sessionId) =>
sessions.data?.sessions.map((s) => s.id).includes(sessionId),
diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsx
index d52ef9673e..35f4437321 100644
--- a/web/src/components/table/use-cases/traces.tsx
+++ b/web/src/components/table/use-cases/traces.tsx
@@ -74,6 +74,7 @@ import { Button } from "@/src/components/ui/button";
import TableIdOrName from "@/src/components/table/table-id";
import { useSidebarFilterState } from "@/src/features/filters/hooks/useSidebarFilterState";
import { traceFilterConfig } from "@/src/features/filters/config/traces-config";
+import { DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG } from "@/src/features/filters/constants/internal-environments";
import { PeekViewTraceDetail } from "@/src/components/table/peek/peek-trace-detail";
import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";
import { TablePeekView } from "@/src/components/table/peek";
@@ -325,15 +326,17 @@ export default function TracesTable({
};
}, [environmentFilterOptions.data, traceFilterOptionsResponse.data]);
- const queryFilter = useSidebarFilterState(
- traceFilterConfig,
- filterOptions,
- projectId,
- traceFilterOptionsResponse.isPending || environmentFilterOptions.isPending,
- hideControls, // Disable URL persistence for embedded preview tables
- );
+ const queryFilter = useSidebarFilterState(traceFilterConfig, filterOptions, {
+ loading:
+ traceFilterOptionsResponse.isPending ||
+ environmentFilterOptions.isPending,
+ disableUrlPersistence: hideControls, // Disable URL persistence for embedded preview tables
+ sessionFilterContextId: projectId,
+ // Sidebar-only implicit environment defaults
+ implicitDefaultConfig: DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG,
+ });
- const combinedFilterState = queryFilter.filterState.concat(
+ const combinedFilterState = queryFilter.effectiveFilterState.concat(
userIdFilter,
dateRangeFilter,
);
@@ -1246,7 +1249,7 @@ export default function TracesTable({
columns,
filterColumnDefinition: traceFilterConfig.columnDefinitions,
},
- currentFilterState: queryFilter.filterState,
+ currentFilterState: queryFilter.explicitFilterState,
});
const rows = useMemo(() => {
@@ -1303,7 +1306,7 @@ export default function TracesTable({
<DataTableToolbar
columns={columns}
filterWithAI
- filterState={queryFilter.filterState}
+ filterState={queryFilter.explicitFilterState}
viewConfig={{
tableName: TableViewPresetTableName.Traces,
projectId,
diff --git a/web/src/features/evals/components/eval-log.tsx b/web/src/features/evals/components/eval-log.tsx
index dd9d644e02..aea809b79a 100644
--- a/web/src/features/evals/components/eval-log.tsx
+++ b/web/src/features/evals/components/eval-log.tsx
@@ -52,8 +52,10 @@ export default function EvalLogTable({
const queryFilter = useSidebarFilterState(
evalLogFilterConfig,
{}, // No dynamic options needed - status options are in column definition
- projectId,
- false,
+ {
+ loading: false,
+ sessionFilterContextId: projectId,
+ },
);
const logs = api.evals.getLogs.useQuery({
diff --git a/web/src/features/evals/components/evaluator-table.tsx b/web/src/features/evals/components/evaluator-table.tsx
index 5523554a34..e067e09877 100644
--- a/web/src/features/evals/components/evaluator-table.tsx
+++ b/web/src/features/evals/components/evaluator-table.tsx
@@ -162,10 +162,10 @@ export default function EvaluatorTable({ projectId }: { projectId: string }) {
const queryFilter = useSidebarFilterState(
evaluatorFilterConfig,
newFilterOptions,
- projectId,
- false,
- false,
- [],
+ {
+ loading: false,
+ sessionFilterContextId: projectId,
+ },
);
const evaluators = api.evals.allConfigs.useQuery({
diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsx
index cd432fbdd0..4640bf3981 100644
--- a/web/src/features/events/components/EventsTable.tsx
+++ b/web/src/features/events/components/EventsTable.tsx
@@ -13,6 +13,7 @@ import {
getEventsColumnName,
observationEventsFilterConfig,
} from "../config/filter-config";
+import { DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG } from "@/src/features/filters/constants/internal-environments";
import { formatIntervalSeconds } from "@/src/utils/dates";
import { type LangfuseColumnDef } from "@/src/components/table/types";
import {
@@ -349,9 +350,13 @@ export default function ObservationsEventsTable({
const queryFilter = useSidebarFilterState(
observationEventsFilterConfig,
filterOptions,
- projectId,
- isFilterOptionsPending,
- hideControls, // Disable URL persistence for embedded preview tables
+ {
+ loading: isFilterOptionsPending,
+ disableUrlPersistence: hideControls, // Disable URL persistence for embedded preview tables
+ sessionFilterContextId: projectId,
+ // Sidebar-only implicit environment defaults
+ implicitDefaultConfig: DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG,
+ },
);
// Create ref-based wrapper to avoid stale closure when queryFilter updates
@@ -399,7 +404,7 @@ export default function ObservationsEventsTable({
]
: [];
- const combinedFilterState = queryFilter.filterState
+ const combinedFilterState = queryFilter.effectiveFilterState
.concat(dateRangeFilter)
.concat(userIdFilter)
.concat(sessionIdFilter);
@@ -1127,7 +1132,7 @@ export default function ObservationsEventsTable({
columns,
filterColumnDefinition: observationEventsFilterConfig.columnDefinitions,
},
- currentFilterState: queryFilter.filterState,
+ currentFilterState: queryFilter.explicitFilterState,
});
const peekConfig: DataTablePeekViewProps | undefined = useMemo(() => {
@@ -1235,7 +1240,7 @@ export default function ObservationsEventsTable({
{!hideControls && (
<DataTableToolbar
columns={columns}
- filterState={queryFilter.filterState}
+ filterState={queryFilter.explicitFilterState}
searchConfig={{
metadataSearchFields: ["ID", "Name", "Trace Name", "Model"],
updateQuery: setSearchQuery,
diff --git a/web/src/features/filters/constants/internal-environments.ts b/web/src/features/filters/constants/internal-environments.ts
new file mode 100644
index 0000000000..8a45c6621d
--- /dev/null
+++ b/web/src/features/filters/constants/internal-environments.ts
@@ -0,0 +1,9 @@
+export const DEFAULT_SIDEBAR_HIDDEN_ENVIRONMENTS = [
+ "langfuse-prompt-experiment",
+ "langfuse-evaluation",
+ "sdk-experiment",
+] as const;
+
+export const DEFAULT_SIDEBAR_IMPLICIT_ENVIRONMENT_CONFIG = {
+ hiddenEnvironments: DEFAULT_SIDEBAR_HIDDEN_ENVIRONMENTS,
+} as const;
diff --git a/web/src/features/filters/filter-integration.clienttest.ts b/web/src/features/filters/filter-integration.clienttest.ts
index 132e4ff218..b3ffbe6189 100644
--- a/web/src/features/filters/filter-integration.clienttest.ts
+++ b/web/src/features/filters/filter-integration.clienttest.ts
@@ -22,6 +22,12 @@ import {
decodeAndNormalizeFilters,
resolveCheckboxOperator,
} from "./hooks/useSidebarFilterState";
+import {
+ buildManagedEnvironmentPolicyConfig,
+ buildImplicitEnvironmentFilter,
+ buildEffectiveEnvironmentFilter,
+ stripImplicitEnvironmentFilterFromExplicitState,
+} from "./lib/managedEnvironmentPolicy";
// Helper to simulate complete URL flow
function simulateUrlFlow(filters: FilterState): FilterState {
@@ -719,3 +725,173 @@ describe("resolveCheckboxOperator (arrayOptions vs stringOptions)", () => {
});
});
});
+
+describe("Implicit Environment Defaults (sidebar only)", () => {
+ const hiddenEnvironments = [
+ "langfuse-prompt-experiment",
+ "langfuse-evaluation",
+ "sdk-experiment",
+ ];
+ const availableValues = [
+ "production",
+ "staging",
+ ...hiddenEnvironments,
+ ] as const;
+ const managedEnvironmentConfig = buildManagedEnvironmentPolicyConfig({
+ managedEnvironmentColumn: "environment",
+ hiddenEnvironments,
+ });
+ const strip = (explicitFilters: FilterState) =>
+ stripImplicitEnvironmentFilterFromExplicitState({
+ explicitFilters,
+ availableEnvironmentValues: [...availableValues],
+ config: managedEnvironmentConfig,
+ });
+
+ it("applies implicit env exclusion only when no explicit env filter exists", () => {
+ expect(
+ buildImplicitEnvironmentFilter({
+ explicitFilters: [
+ {
+ column: "name",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["trace-a"],
+ },
+ ],
+ config: managedEnvironmentConfig,
+ }),
+ ).toEqual([
+ {
+ column: "environment",
+ type: "stringOptions",
+ operator: "none of",
+ value: hiddenEnvironments,
+ },
+ ]);
+
+ expect(
+ buildImplicitEnvironmentFilter({
+ explicitFilters: [
+ {
+ column: "environment",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["production"],
+ },
+ ],
+ config: managedEnvironmentConfig,
+ }),
+ ).toEqual([]);
+ });
+
+ it("strips default-equivalent env filters before URL/session persistence", () => {
+ const explicitWithExactDefault: FilterState = [
+ {
+ column: "environment",
+ type: "stringOptions",
+ operator: "none of",
+ value: hiddenEnvironments,
+ },
+ {
+ column: "name",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["trace-a"],
+ },
+ ];
+
+ expect(strip(explicitWithExactDefault)).toEqual([
+ {
+ column: "name",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["trace-a"],
+ },
+ ]);
+
+ expect(
+ strip([
+ {
+ column: "environment",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["production", "staging"],
+ },
+ ]),
+ ).toEqual([]);
+ });
+
+ it("keeps explicit overrides that enable hidden environments", () => {
+ const explicitWithHiddenEnabled: FilterState = [
+ {
+ column: "environment",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["production", "langfuse-evaluation"],
+ },
+ {
+ column: "name",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["trace-a"],
+ },
+ ];
+
+ expect(strip(explicitWithHiddenEnabled)).toEqual(explicitWithHiddenEnabled);
+
+ const explicitAll: FilterState = [
+ {
+ column: "environment",
+ type: "stringOptions",
+ operator: "any of",
+ value: [...availableValues],
+ },
+ ];
+
+ expect(strip(explicitAll)).toEqual(explicitAll);
+ });
+
+ it("keeps hidden-only explicit selection as explicit override", () => {
+ expect(
+ strip([
+ {
+ column: "environment",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["langfuse-evaluation"],
+ },
+ ]),
+ ).toEqual([
+ {
+ column: "environment",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["langfuse-evaluation"],
+ },
+ ]);
+ });
+
+ it("returns explicit environment filters as effective state", () => {
+ expect(
+ buildEffectiveEnvironmentFilter({
+ explicitFilters: [
+ {
+ column: "environment",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["langfuse-evaluation"],
+ },
+ ],
+ config: managedEnvironmentConfig,
+ }),
+ ).toEqual([
+ {
+ column: "environment",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["langfuse-evaluation"],
+ },
+ ]);
+ });
+});
diff --git a/web/src/features/filters/hooks/useKeyedSessionStorageState.ts b/web/src/features/filters/hooks/useKeyedSessionStorageState.ts
new file mode 100644
index 0000000000..224ea25ec7
--- /dev/null
+++ b/web/src/features/filters/hooks/useKeyedSessionStorageState.ts
@@ -0,0 +1,90 @@
+import { useCallback, useEffect, useState } from "react";
+
+function readSessionStorageValue<T>(params: {
+ storageKey: string;
+ fallback: T;
+}): T {
+ const { storageKey, fallback } = params;
+ if (typeof window === "undefined") return fallback;
+
+ try {
+ const storedValue = sessionStorage.getItem(storageKey);
+ return storedValue ? (JSON.parse(storedValue) as T) : fallback;
+ } catch (error) {
+ console.error("Error reading from session storage", error);
+ return fallback;
+ }
+}
+
+/**
+ * Session storage state that rehydrates on key changes before writing.
+ * This prevents stale values from the previous key from leaking into the new key.
+ */
+export function useKeyedSessionStorageState<T>(
+ storageKey: string,
+ initialValue: T,
+): [T, React.Dispatch<React.SetStateAction<T>>, () => void] {
+ const [state, setState] = useState<{ key: string; value: T }>(() => ({
+ key: storageKey,
+ value: readSessionStorageValue({ storageKey, fallback: initialValue }),
+ }));
+
+ useEffect(() => {
+ if (state.key === storageKey) return;
+
+ setState({
+ key: storageKey,
+ value: readSessionStorageValue({
+ storageKey,
+ fallback: initialValue,
+ }),
+ });
+ }, [state.key, storageKey, initialValue]);
+
+ useEffect(() => {
+ if (typeof window === "undefined") return;
+ if (state.key !== storageKey) return;
+
+ try {
+ sessionStorage.setItem(storageKey, JSON.stringify(state.value));
+ } catch (error) {
+ console.error("Error writing to session storage", error);
+ }
+ }, [state.key, state.value, storageKey]);
+
+ const setValue: React.Dispatch<React.SetStateAction<T>> = useCallback(
+ (next) => {
+ setState((previous) => {
+ const baseValue =
+ previous.key === storageKey ? previous.value : initialValue;
+ const resolved =
+ typeof next === "function"
+ ? (next as (value: T) => T)(baseValue)
+ : next;
+
+ return {
+ key: storageKey,
+ value: resolved,
+ };
+ });
+ },
+ [storageKey, initialValue],
+ );
+
+ const clearValue = useCallback(() => {
+ if (typeof window !== "undefined") {
+ try {
+ sessionStorage.removeItem(storageKey);
+ } catch (error) {
+ console.error("Error clearing session storage", error);
+ }
+ }
+
+ setState({
+ key: storageKey,
+ value: initialValue,
+ });
+ }, [storageKey, initialValue]);
+
+ return [state.value, setValue, clearValue] as const;
+}
diff --git a/web/src/features/filters/hooks/useSidebarFilterState.tsx b/web/src/features/filters/hooks/useSidebarFilterState.tsx
index f6038cda2c..f2bbb6f508 100644
--- a/web/src/features/filters/hooks/useSidebarFilterState.tsx
+++ b/web/src/features/filters/hooks/useSidebarFilterState.tsx
@@ -1,6 +1,6 @@
import type React from "react";
-import { useCallback, useMemo, useEffect, useRef } from "react";
-import { StringParam, useQueryParam, withDefault } from "use-query-params";
+import { useCallback, useMemo, useEffect, useState } from "react";
+import { StringParam, useQueryParam } from "use-query-params";
import {
type FilterState,
singleFilter,
@@ -12,9 +12,22 @@ import {
encodeFiltersGeneric,
decodeFiltersGeneric,
} from "../lib/filter-query-encoding";
+import {
+ buildSidebarFilterQueryStorageKey,
+ createPersistedSidebarFilterQueryState,
+ getPersistedSidebarFilterQueryForContext,
+ type PersistedSidebarFilterQueryState,
+} from "../lib/persistedSidebarFilterQuery";
import { normalizeFilterColumnNames } from "../lib/filter-transform";
+import {
+ buildEffectiveEnvironmentFilter,
+ buildManagedEnvironmentPolicyConfig,
+ stripImplicitEnvironmentFilterFromExplicitState,
+ type ManagedEnvironmentPolicyInput,
+} from "../lib/managedEnvironmentPolicy";
+import { areStringSetsEqual } from "../lib/stringSetUtils";
+import { useKeyedSessionStorageState } from "./useKeyedSessionStorageState";
import useSessionStorage from "@/src/components/useSessionStorage";
-import useLocalStorage from "@/src/components/useLocalStorage";
import type { FilterConfig } from "../lib/filter-config";
import { usePeekTableState } from "@/src/components/table/peek/contexts/PeekTableStateContext";
@@ -309,6 +322,22 @@ type UpdateFilter = (
operator?: "any of" | "none of" | "all of",
) => void;
+type UseSidebarFilterStateOptions = {
+ loading?: boolean;
+ /**
+ * If true, prevents filter state from being persisted to/read from URL query params.
+ * Use this for embedded tables (e.g., preview tables in forms) to avoid polluting
+ * the parent page's URL with filters that don't apply to the parent context.
+ */
+ disableUrlPersistence?: boolean;
+ /**
+ * Optional context identifier (for example projectId) to guard against
+ * carrying persisted filters across contexts.
+ */
+ sessionFilterContextId?: string | null;
+ implicitDefaultConfig?: ManagedEnvironmentPolicyInput;
+};
+
/**
* Pure function that determines the operator and values for checkbox-based
* filter interactions. Extracted for testability.
@@ -365,21 +394,14 @@ export function useSidebarFilterState(
string,
(string | SingleValueOption)[] | Record<string, string[]> | undefined
>,
- projectId?: string,
- loading?: boolean,
- /**
- * If true, prevents filter state from being persisted to/read from URL query params.
- * Use this for embedded tables (e.g., preview tables in forms) to avoid polluting
- * the parent page's URL with filters that don't apply to the parent context.
- */
- disableUrlPersistence?: boolean,
- /**
- * Default filters to apply on initial page load (when no URL filters are present).
- * These apply every time the component mounts, but respect user's manual filter changes.
- * If a user clears all filters, defaults won't reapply until the component remounts (new page visit).
- */
- defaultFilters?: FilterState,
+ hookOptions: UseSidebarFilterStateOptions = {},
) {
+ const {
+ loading,
+ disableUrlPersistence,
+ sessionFilterContextId,
+ implicitDefaultConfig,
+ } = hookOptions;
const peekContext = usePeekTableState();
const FILTER_EXPANDED_STORAGE_KEY = `${config.tableName}-filters-expanded`;
@@ -399,10 +421,48 @@ export function useSidebarFilterState(
[setExpandedString],
);
- const [filtersQuery, setFiltersQuery] = useQueryParam(
+ const normalizedSessionFilterContextId = sessionFilterContextId ?? null;
+ const FILTER_QUERY_SESSION_STORAGE_KEY = buildSidebarFilterQueryStorageKey({
+ tableName: config.tableName,
+ contextId: normalizedSessionFilterContextId,
+ });
+
+ const [storedFilterQueryState, setStoredFilterQueryState] =
+ useKeyedSessionStorageState<PersistedSidebarFilterQueryState>(
+ FILTER_QUERY_SESSION_STORAGE_KEY,
+ createPersistedSidebarFilterQueryState(
+ normalizedSessionFilterContextId,
+ "",
+ ),
+ );
+
+ const storedFiltersQuery = getPersistedSidebarFilterQueryForContext({
+ state: storedFilterQueryState,
+ contextId: normalizedSessionFilterContextId,
+ });
+ const setStoredFiltersQuery = useCallback(
+ (query: string) => {
+ setStoredFilterQueryState(
+ createPersistedSidebarFilterQueryState(
+ normalizedSessionFilterContextId,
+ query,
+ ),
+ );
+ },
+ [setStoredFilterQueryState, normalizedSessionFilterContextId],
+ );
+ const [urlFiltersQuery, setUrlFiltersQuery] = useQueryParam(
"filter",
- withDefault(StringParam, ""),
+ StringParam,
+ );
+ // Optimistic query state: prevents stale URL reads from overriding immediate
+ // local changes while use-query-params updates the URL asynchronously.
+ const [pendingFiltersQuery, setPendingFiltersQuery] = useState<string | null>(
+ null,
);
+ const filtersQuery = disableUrlPersistence
+ ? ""
+ : (pendingFiltersQuery ?? urlFiltersQuery ?? storedFiltersQuery);
const mutualExclusionContext = useMemo(
() => buildMutualExclusionContext(config),
@@ -430,15 +490,55 @@ export function useSidebarFilterState(
? peekContext.tableState.filters
: urlFilterState;
- const filterState: FilterState = useMemo(
+ const managedEnvironmentPolicyConfig = useMemo(
+ () => buildManagedEnvironmentPolicyConfig(implicitDefaultConfig),
+ [implicitDefaultConfig],
+ );
+
+ const managedEnvironmentColumn =
+ managedEnvironmentPolicyConfig.managedEnvironmentColumn;
+
+ const availableEnvironmentValues = useMemo(() => {
+ const rawOptions = options[managedEnvironmentColumn];
+ if (!Array.isArray(rawOptions)) return [];
+ return rawOptions.map((option) =>
+ typeof option === "string" ? option : option.value,
+ );
+ }, [options, managedEnvironmentColumn]);
+
+ const explicitFilterState: FilterState = useMemo(
() =>
reconcileMutuallyExclusiveFilters(rawFilterState, mutualExclusionContext),
[rawFilterState, mutualExclusionContext],
);
- // Track if user has manually interacted with filters
- // This prevents default filters from overriding user's explicit "clear all" action
- const userHasInteractedRef = useRef(false);
+ const effectiveEnvironmentFilterState: FilterState = useMemo(
+ () =>
+ buildEffectiveEnvironmentFilter({
+ explicitFilters: explicitFilterState,
+ config: managedEnvironmentPolicyConfig,
+ }),
+ [explicitFilterState, managedEnvironmentPolicyConfig],
+ );
+
+ const filterState: FilterState = useMemo(
+ () =>
+ reconcileMutuallyExclusiveFilters(
+ [
+ ...explicitFilterState.filter(
+ (filter) => filter.column !== managedEnvironmentColumn,
+ ),
+ ...effectiveEnvironmentFilterState,
+ ],
+ mutualExclusionContext,
+ ),
+ [
+ explicitFilterState,
+ effectiveEnvironmentFilterState,
+ mutualExclusionContext,
+ managedEnvironmentColumn,
+ ],
+ );
const setFilterState = useCallback(
(newFilters: FilterState) => {
@@ -448,11 +548,16 @@ export function useSidebarFilterState(
newFilters,
mutualExclusionContext,
);
+ const explicitFilters = stripImplicitEnvironmentFilterFromExplicitState({
+ explicitFilters: reconciledFilters,
+ availableEnvironmentValues,
+ config: managedEnvironmentPolicyConfig,
+ });
if (peekContext) {
peekContext.setTableState({
...peekContext.tableState,
- filters: reconciledFilters,
+ filters: explicitFilters,
});
return;
}
@@ -460,102 +565,58 @@ export function useSidebarFilterState(
// Don't modify URL if persistence is disabled
if (disableUrlPersistence) return;
- // Mark that user has manually interacted with filters
- // Exception: Don't mark as interacted if this is the initial default filter application
- if (userHasInteractedRef.current || reconciledFilters.length > 0) {
- userHasInteractedRef.current = true;
- }
-
- const encoded = encodeFiltersGeneric(reconciledFilters);
- setFiltersQuery(encoded || null);
+ const encoded = encodeFiltersGeneric(explicitFilters);
+ setPendingFiltersQuery(encoded);
+ setUrlFiltersQuery(encoded || null);
+ setStoredFiltersQuery(encoded);
},
[
- setFiltersQuery,
+ setUrlFiltersQuery,
+ setStoredFiltersQuery,
disableUrlPersistence,
peekContext,
mutualExclusionContext,
+ managedEnvironmentPolicyConfig,
+ availableEnvironmentValues,
],
);
- // track if defaults have been applied before, versioned to support future changes
- // per project tracking because people want a default experience in a new project
- const storageKey = projectId
- ? `${config.tableName}-${projectId}-env-defaults-v1`
- : `${config.tableName}-env-defaults-v1`;
- const [defaultsApplied, setDefaultsApplied] = useLocalStorage<boolean>(
- storageKey,
- false,
- );
-
- // Apply default filters when no URL filters are present
+ // Drop optimistic override once URL catches up to the requested value.
useEffect(() => {
- // Skip auto-applying defaults for embedded tables
if (disableUrlPersistence) return;
+ if (peekContext) return;
+ if (pendingFiltersQuery === null) return;
- // If there are already filters in URL, don't apply defaults
- if (filterState.length > 0) return;
-
- // If user has manually interacted with filters (e.g., cleared them), respect their choice
- // This prevents defaults from reapplying when user clears filters in the same session
- if (userHasInteractedRef.current) return;
-
- let filtersToApply: FilterState = [];
-
- // Priority 1: Apply custom default filters if provided
- if (defaultFilters && defaultFilters.length > 0) {
- filtersToApply = defaultFilters;
- }
- // Priority 2: Fallback to legacy environment filter (one-time with localStorage)
- else if (!defaultsApplied) {
- const environmentFacet = config.facets.find(
- (f) => f.column === "environment" && f.type === "categorical",
- );
-
- if (environmentFacet) {
- const environmentOptions = options["environment"];
- if (
- Array.isArray(environmentOptions) &&
- environmentOptions.length > 0
- ) {
- const environments = environmentOptions.map((opt) =>
- typeof opt === "string" ? opt : opt.value,
- );
-
- const langfuseEnvironments = environments.filter((env) =>
- env.startsWith("langfuse-"),
- );
-
- if (langfuseEnvironments.length > 0) {
- filtersToApply = [
- {
- column: "environment",
- type: "stringOptions",
- operator: "none of",
- value: langfuseEnvironments,
- },
- ];
- }
- }
- }
+ const normalizedUrlFiltersQuery = urlFiltersQuery ?? "";
+ if (normalizedUrlFiltersQuery === pendingFiltersQuery) {
+ setPendingFiltersQuery(null);
}
+ }, [
+ disableUrlPersistence,
+ peekContext,
+ pendingFiltersQuery,
+ urlFiltersQuery,
+ ]);
- // Apply filters if any were determined
- if (filtersToApply.length > 0) {
- setFilterState(filtersToApply);
- // Only mark as applied for legacy environment filter (not for custom defaultFilters)
- if (!defaultFilters || defaultFilters.length === 0) {
- setDefaultsApplied(true);
- }
- }
+ // Mirror explicit URL filter state into session fallback storage.
+ useEffect(() => {
+ if (disableUrlPersistence) return;
+ if (peekContext) return;
+ if (pendingFiltersQuery !== null) return;
+ if (typeof urlFiltersQuery !== "string") return;
+ if (!urlFiltersQuery) return;
+ if (urlFiltersQuery === storedFiltersQuery) return;
+
+ // Keep session fallback aligned to explicit URL links without clearing
+ // previously saved state when URL has no `filter` parameter.
+ setStoredFiltersQuery(urlFiltersQuery);
}, [
- filterState.length,
- defaultsApplied,
- config.facets,
- options,
disableUrlPersistence,
- setFilterState,
- setDefaultsApplied,
- defaultFilters,
+ peekContext,
+ pendingFiltersQuery,
+ urlFiltersQuery,
+ storedFiltersQuery,
+ setStoredFiltersQuery,
]);
const clearAll = () => {
@@ -646,6 +707,22 @@ export function useSidebarFilterState(
(values.length === availableValues.length &&
availableValues.every((v) => values.includes(v)))
) {
+ const isManagedEnvironmentColumn =
+ column === managedEnvironmentColumn &&
+ managedEnvironmentPolicyConfig.hiddenEnvironments.length > 0;
+
+ // Keep explicit override when user intentionally enables all environments.
+ if (isManagedEnvironmentColumn && values.length > 0) {
+ return [
+ ...other,
+ {
+ column,
+ type: "stringOptions" as const,
+ operator: "any of" as const,
+ value: values,
+ },
+ ];
+ }
return other;
}
// Checkbox interaction - smart operator selection
@@ -690,7 +767,7 @@ export function useSidebarFilterState(
},
];
},
- [config, options],
+ [config, options, managedEnvironmentColumn, managedEnvironmentPolicyConfig],
);
const updateFilter: UpdateFilter = useCallback(
@@ -1508,14 +1585,33 @@ export function useSidebarFilterState(
const hasCheckboxSelections =
selectedValues.length > 0 &&
selectedValues.length !== availableValues.length;
+ const isManagedEnvironmentFacet =
+ facet.column === managedEnvironmentColumn &&
+ managedEnvironmentPolicyConfig.hiddenEnvironments.length > 0;
+ const hasManagedEnvironmentSelectionOverride =
+ isManagedEnvironmentFacet &&
+ !areStringSetsEqual(
+ selectedValues,
+ availableValues.filter(
+ (value) =>
+ !managedEnvironmentPolicyConfig.hiddenEnvironments.includes(
+ value,
+ ),
+ ),
+ );
- // isActive check: filter is active if we have text filters OR checkbox selections
- // Special case: "all of" with all values selected is still an active filter
+ // isActive check:
+ // - Managed environment facet: active only when selection differs from default
+ // (implicit hidden-env default should not surface a "Clear" badge).
+ // - Other facets: active when text filters exist or checkbox selections differ from unfiltered.
+ // Special case: "all of" with all values selected is still active.
const isActive =
hasTextFilters ||
- (currentOperator === "all of" &&
- selectedValues.length === availableValues.length) ||
- hasCheckboxSelections;
+ (isManagedEnvironmentFacet
+ ? hasManagedEnvironmentSelectionOverride
+ : (currentOperator === "all of" &&
+ selectedValues.length === availableValues.length) ||
+ hasCheckboxSelections);
const disableState = getFacetDisabledState(facet, isActive);
return {
@@ -1593,16 +1689,20 @@ export function useSidebarFilterState(
expandedState,
setFilterState,
mutualExclusionContext,
+ managedEnvironmentColumn,
+ managedEnvironmentPolicyConfig.hiddenEnvironments,
]);
return {
filterState,
+ effectiveFilterState: filterState,
+ explicitFilterState,
setFilterState,
updateFilter,
updateFilterOnly,
updateOperator,
clearAll,
- isFiltered: filterState.length > 0,
+ isFiltered: explicitFilterState.length > 0,
filters,
expanded: expandedState,
onExpandedChange,
diff --git a/web/src/features/filters/lib/managedEnvironmentPolicy.ts b/web/src/features/filters/lib/managedEnvironmentPolicy.ts
new file mode 100644
index 0000000000..573bef8e5a
--- /dev/null
+++ b/web/src/features/filters/lib/managedEnvironmentPolicy.ts
@@ -0,0 +1,147 @@
+import type { FilterState } from "@langfuse/shared";
+import { computeSelectedValues } from "./filter-query-encoding";
+import { areStringSetsEqual } from "./stringSetUtils";
+
+type EnvironmentFilter = Extract<
+ FilterState[number],
+ { type: "stringOptions" }
+>;
+
+export type ManagedEnvironmentPolicyInput = {
+ hiddenEnvironments?: readonly string[];
+ managedEnvironmentColumn?: string;
+};
+
+export type ManagedEnvironmentPolicyConfig = {
+ hiddenEnvironments: string[];
+ managedEnvironmentColumn: string;
+};
+
+export function buildManagedEnvironmentPolicyConfig(
+ input?: ManagedEnvironmentPolicyInput,
+): ManagedEnvironmentPolicyConfig {
+ return {
+ managedEnvironmentColumn: input?.managedEnvironmentColumn ?? "environment",
+ hiddenEnvironments: Array.from(new Set(input?.hiddenEnvironments ?? [])),
+ };
+}
+
+function isEquivalentToImplicitEnvironmentDefault(params: {
+ envFilter: EnvironmentFilter;
+ hiddenEnvironments: string[];
+ availableEnvironmentValues: string[];
+}): boolean {
+ const { envFilter, hiddenEnvironments, availableEnvironmentValues } = params;
+
+ if (hiddenEnvironments.length === 0) return false;
+
+ const exactDefaultMatch =
+ envFilter.operator === "none of" &&
+ areStringSetsEqual(envFilter.value, hiddenEnvironments);
+
+ if (exactDefaultMatch) return true;
+
+ if (availableEnvironmentValues.length === 0) return false;
+
+ const selectedFromFilter = computeSelectedValues(
+ availableEnvironmentValues,
+ envFilter,
+ );
+ const hiddenSet = new Set(hiddenEnvironments);
+ const selectedFromDefault = availableEnvironmentValues.filter(
+ (value) => !hiddenSet.has(value),
+ );
+
+ return areStringSetsEqual(selectedFromFilter, selectedFromDefault);
+}
+
+export function stripImplicitEnvironmentFilterFromExplicitState(params: {
+ explicitFilters: FilterState;
+ availableEnvironmentValues: string[];
+ config: ManagedEnvironmentPolicyConfig;
+}): FilterState {
+ const { explicitFilters, availableEnvironmentValues, config } = params;
+ const { managedEnvironmentColumn, hiddenEnvironments } = config;
+
+ if (hiddenEnvironments.length === 0) return explicitFilters;
+
+ const managedColumnFilters = explicitFilters.filter(
+ (filter) => filter.column === managedEnvironmentColumn,
+ );
+
+ // Only canonicalize the standard environment checkbox filter shape.
+ if (
+ managedColumnFilters.length !== 1 ||
+ managedColumnFilters[0]?.type !== "stringOptions"
+ ) {
+ return explicitFilters;
+ }
+
+ const envFilter = managedColumnFilters[0] as EnvironmentFilter;
+ const otherFilters = explicitFilters.filter((filter) => filter !== envFilter);
+
+ if (
+ isEquivalentToImplicitEnvironmentDefault({
+ envFilter,
+ hiddenEnvironments,
+ availableEnvironmentValues,
+ })
+ ) {
+ return otherFilters;
+ }
+ return explicitFilters;
+}
+
+export function buildImplicitEnvironmentFilter(params: {
+ explicitFilters: FilterState;
+ config: ManagedEnvironmentPolicyConfig;
+}): FilterState {
+ const { explicitFilters, config } = params;
+ const { managedEnvironmentColumn, hiddenEnvironments } = config;
+
+ if (hiddenEnvironments.length === 0) return [];
+
+ const hasExplicitEnvironmentFilter = explicitFilters.some(
+ (filter) => filter.column === managedEnvironmentColumn,
+ );
+
+ if (hasExplicitEnvironmentFilter) return [];
+
+ return [
+ {
+ column: managedEnvironmentColumn,
+ type: "stringOptions" as const,
+ operator: "none of" as const,
+ value: hiddenEnvironments,
+ },
+ ];
+}
+
+export function buildEffectiveEnvironmentFilter(params: {
+ explicitFilters: FilterState;
+ config: ManagedEnvironmentPolicyConfig;
+}): FilterState {
+ const { explicitFilters, config } = params;
+ const { managedEnvironmentColumn } = config;
+
+ const managedColumnFilters = explicitFilters.filter(
+ (filter) => filter.column === managedEnvironmentColumn,
+ );
+
+ if (managedColumnFilters.length === 0) {
+ return buildImplicitEnvironmentFilter({
+ explicitFilters,
+ config,
+ });
+ }
+
+ if (
+ managedColumnFilters.length !== 1 ||
+ managedColumnFilters[0]?.type !== "stringOptions"
+ ) {
+ return managedColumnFilters;
+ }
+
+ const envFilter = managedColumnFilters[0] as EnvironmentFilter;
+ return [envFilter];
+}
diff --git a/web/src/features/filters/lib/persistedSidebarFilterQuery.ts b/web/src/features/filters/lib/persistedSidebarFilterQuery.ts
new file mode 100644
index 0000000000..547bfbb6f7
--- /dev/null
+++ b/web/src/features/filters/lib/persistedSidebarFilterQuery.ts
@@ -0,0 +1,75 @@
+export type PersistedSidebarFilterQueryState = {
+ contextId: string | null;
+ query: string;
+};
+
+export function buildSidebarFilterQueryStorageKey(params: {
+ tableName: string;
+ contextId?: string | null;
+}): string {
+ const { tableName, contextId } = params;
+ const scopedContextId = contextId ?? "global";
+ return `${tableName}-filter-query-${scopedContextId}`;
+}
+
+export function createPersistedSidebarFilterQueryState(
+ contextId: string | null,
+ query: string,
+): PersistedSidebarFilterQueryState {
+ return { contextId, query };
+}
+
+export function parsePersistedSidebarFilterQueryState(
+ rawState: string | null,
+): PersistedSidebarFilterQueryState | null {
+ if (!rawState) return null;
+
+ try {
+ const parsed = JSON.parse(rawState) as unknown;
+
+ if (!parsed || typeof parsed !== "object") return null;
+
+ const contextId =
+ "contextId" in parsed && typeof parsed.contextId === "string"
+ ? parsed.contextId
+ : "contextId" in parsed && parsed.contextId === null
+ ? null
+ : undefined;
+ const query =
+ "query" in parsed && typeof parsed.query === "string"
+ ? parsed.query
+ : undefined;
+
+ if (contextId === undefined || query === undefined) return null;
+
+ return { contextId, query };
+ } catch {
+ return null;
+ }
+}
+
+export function getPersistedSidebarFilterQueryForContext(params: {
+ state: PersistedSidebarFilterQueryState | null;
+ contextId: string | null;
+}): string {
+ const { state, contextId } = params;
+ if (!state) return "";
+ return state.contextId === contextId ? state.query : "";
+}
+
+export function readPersistedSidebarFilterQuery(params: {
+ storageKey: string;
+ contextId: string | null;
+}): string {
+ const { storageKey, contextId } = params;
+ if (typeof window === "undefined") return "";
+
+ const persistedState = parsePersistedSidebarFilterQueryState(
+ sessionStorage.getItem(storageKey),
+ );
+
+ return getPersistedSidebarFilterQueryForContext({
+ state: persistedState,
+ contextId,
+ });
+}
diff --git a/web/src/features/filters/lib/stringSetUtils.ts b/web/src/features/filters/lib/stringSetUtils.ts
new file mode 100644
index 0000000000..834a0d32dc
--- /dev/null
+++ b/web/src/features/filters/lib/stringSetUtils.ts
@@ -0,0 +1,6 @@
+export function areStringSetsEqual(left: string[], right: string[]): boolean {
+ if (left.length !== right.length) return false;
+ const leftSet = new Set(left);
+ if (leftSet.size !== new Set(right).size) return false;
+ return right.every((value) => leftSet.has(value));
+}
diff --git a/web/src/features/filters/savedViewImplicitEnvironmentRegression.clienttest.tsx b/web/src/features/filters/savedViewImplicitEnvironmentRegression.clienttest.tsx
new file mode 100644
index 0000000000..2613d21ae8
--- /dev/null
+++ b/web/src/features/filters/savedViewImplicitEnvironmentRegression.clienttest.tsx
@@ -0,0 +1,434 @@
+import {
+ act,
+ 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";
+
+const mockUseRouter = jest.fn();
+const mockCapture = jest.fn();
+const mockGetDefaultUseQuery = jest.fn();
+const mockGetByIdUseQuery = jest.fn();
+
+const queryParamStore = new Map<string, unknown>();
+
+jest.mock("next/router", () => ({
+ useRouter: () => mockUseRouter(),
+}));
+
+jest.mock("posthog-js/react", () => ({
+ usePostHog: () => ({
+ capture: mockCapture,
+ }),
+}));
+
+jest.mock(
+ "../../components/table/table-view-presets/components/data-table-view-presets-drawer",
+ () => ({
+ isSystemPresetId: () => false,
+ }),
+);
+
+jest.mock("../../utils/api", () => ({
+ api: {
+ TableViewPresets: {
+ getDefault: {
+ useQuery: (...args: unknown[]) => mockGetDefaultUseQuery(...args),
+ },
+ getById: {
+ useQuery: (...args: unknown[]) => {
+ const result = mockGetByIdUseQuery(...args) as
+ | {
+ data?: unknown;
+ error?: unknown;
+ isSuccess?: boolean;
+ isError?: boolean;
+ }
+ | undefined;
+
+ return {
+ data: result?.data,
+ error: result?.error ?? null,
+ isSuccess: result?.isSuccess ?? result?.data !== undefined,
+ isError: result?.isError ?? !!result?.error,
+ };
+ },
+ },
+ },
+ },
+}));
+
+jest.mock("use-query-params", () => {
+ const React = require("react");
+ const actual = jest.requireActual("use-query-params");
+
+ const StringParam = { __type: "string" } as const;
+ const withDefault = (param: unknown, defaultValue: unknown) => ({
+ ...(typeof param === "object" && param !== null ? param : {}),
+ __default: defaultValue,
+ });
+
+ const readDefault = (config: unknown) =>
+ typeof config === "object" &&
+ config !== null &&
+ "__default" in config &&
+ (config as { __default?: unknown }).__default !== undefined
+ ? (config as { __default: unknown }).__default
+ : null;
+
+ return {
+ ...actual,
+ StringParam,
+ withDefault,
+ useQueryParam: (key: string, config?: unknown) => {
+ const defaultValue = readDefault(config);
+ const initialValue = queryParamStore.has(key)
+ ? queryParamStore.get(key)
+ : defaultValue;
+ const [value, setValue] = React.useState(initialValue);
+
+ const setQueryValue = React.useCallback(
+ (
+ next: unknown | ((previous: unknown) => unknown) | null | undefined,
+ ) => {
+ const previous = queryParamStore.has(key)
+ ? queryParamStore.get(key)
+ : defaultValue;
+ const resolved = typeof next === "function" ? next(previous) : next;
+
+ if (resolved === null || resolved === undefined || resolved === "") {
+ queryParamStore.delete(key);
+ setValue(defaultValue);
+ return;
+ }
+
+ queryParamStore.set(key, resolved);
+ setValue(resolved);
+ },
+ [key, defaultValue],
+ );
+
+ React.useEffect(() => {
+ if (value === null || value === undefined || value === "") {
+ queryParamStore.delete(key);
+ return;
+ }
+ queryParamStore.set(key, value);
+ }, [key, value]);
+
+ return [value, setQueryValue];
+ },
+ };
+});
+
+const HIDDEN_ENVIRONMENTS = [
+ "langfuse-prompt-experiment",
+ "langfuse-evaluation",
+ "sdk-experiment",
+];
+
+const TEST_FILTER_CONFIG: FilterConfig = {
+ tableName: "traces",
+ columnDefinitions: [
+ {
+ id: "environment",
+ name: "Environment",
+ type: "stringOptions",
+ options: [],
+ internal: "environment",
+ },
+ {
+ id: "name",
+ name: "Name",
+ type: "stringOptions",
+ options: [],
+ internal: "name",
+ },
+ ],
+ facets: [
+ {
+ type: "categorical",
+ column: "environment",
+ label: "Environment",
+ },
+ {
+ type: "categorical",
+ column: "name",
+ label: "Name",
+ },
+ ],
+};
+
+const TEST_OPTIONS = {
+ environment: [
+ "production",
+ "staging",
+ "langfuse-prompt-experiment",
+ "langfuse-evaluation",
+ "sdk-experiment",
+ ],
+ name: ["checkout", "search"],
+};
+
+function SavedViewHarness() {
+ const queryFilter = useSidebarFilterState(TEST_FILTER_CONFIG, TEST_OPTIONS, {
+ implicitDefaultConfig: {
+ hiddenEnvironments: [...HIDDEN_ENVIRONMENTS],
+ },
+ });
+
+ const { isLoading } = useTableViewManager({
+ tableName: TableViewPresetTableName.Traces,
+ projectId: "project-1",
+ stateUpdaters: {
+ setFilters: queryFilter.setFilterState,
+ setColumnOrder: () => {},
+ setColumnVisibility: () => {},
+ },
+ validationContext: {
+ columns: [],
+ filterColumnDefinition: TEST_FILTER_CONFIG.columnDefinitions,
+ },
+ // Saved-view synchronization must compare against explicit state.
+ // Effective state includes implicit environment defaults and can deadlock.
+ currentFilterState: queryFilter.explicitFilterState,
+ });
+
+ return (
+ <div>
+ <div data-testid="loading-state">{isLoading ? "loading" : "ready"}</div>
+ <pre data-testid="explicit-state">
+ {JSON.stringify(queryFilter.explicitFilterState)}
+ </pre>
+ <pre data-testid="effective-state">
+ {JSON.stringify(queryFilter.filterState)}
+ </pre>
+ </div>
+ );
+}
+
+function ViewSelectionHarness() {
+ const [appliedFilters, setAppliedFilters] = useState<FilterState>([]);
+ const { selectedViewId, handleSetViewId } = useTableViewManager({
+ tableName: TableViewPresetTableName.Traces,
+ 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>
+ <div data-testid="applied-filter-count">{appliedFilters.length}</div>
+ <button onClick={() => handleSetViewId("view-1")}>select-view</button>
+ <button onClick={() => handleSetViewId(null)}>select-default</button>
+ </div>
+ );
+}
+
+const OLD_SAVED_VIEW_FILTERS: FilterState = [
+ {
+ column: "name",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["checkout"],
+ },
+];
+
+describe("Saved view restore with implicit environment defaults", () => {
+ let savedViewFilters: FilterState;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ sessionStorage.clear();
+ queryParamStore.clear();
+ savedViewFilters = OLD_SAVED_VIEW_FILTERS;
+
+ queryParamStore.set("viewId", "view-1");
+ mockUseRouter.mockReturnValue({
+ isReady: true,
+ query: { viewId: "view-1" },
+ });
+
+ mockGetDefaultUseQuery.mockReturnValue({
+ data: null,
+ isLoading: false,
+ });
+
+ mockGetByIdUseQuery.mockReturnValue({
+ data: {
+ id: "view-1",
+ name: "Old saved query without explicit env",
+ tableName: TableViewPresetTableName.Traces,
+ projectId: "project-1",
+ orderBy: null,
+ filters: savedViewFilters,
+ columnOrder: null,
+ columnVisibility: null,
+ searchQuery: "",
+ createdAt: new Date("2026-01-01T00:00:00.000Z"),
+ updatedAt: new Date("2026-01-01T00:00:00.000Z"),
+ createdBy: "user-1",
+ createdByUser: null,
+ },
+ error: null,
+ });
+ });
+
+ it("restores old saved views and stays ready when implicit env defaults are active", async () => {
+ render(<SavedViewHarness />);
+
+ await waitFor(() => {
+ expect(screen.getByTestId("loading-state").textContent).toBe("ready");
+ });
+
+ expect(screen.getByTestId("explicit-state").textContent).toContain(
+ "checkout",
+ );
+ expect(screen.getByTestId("effective-state").textContent).toContain(
+ '"environment"',
+ );
+ });
+
+ it("applies stored saved view when URL has no viewId", async () => {
+ queryParamStore.delete("viewId");
+ mockUseRouter.mockReturnValue({
+ isReady: true,
+ query: {},
+ });
+
+ sessionStorage.setItem("traces-project-1-viewId", JSON.stringify("view-1"));
+
+ mockGetByIdUseQuery.mockReturnValue({
+ data: {
+ id: "view-1",
+ name: "Stored saved view",
+ tableName: TableViewPresetTableName.Traces,
+ projectId: "project-1",
+ orderBy: null,
+ filters: OLD_SAVED_VIEW_FILTERS,
+ columnOrder: null,
+ columnVisibility: null,
+ searchQuery: "",
+ createdAt: new Date("2026-01-01T00:00:00.000Z"),
+ updatedAt: new Date("2026-01-01T00:00:00.000Z"),
+ createdBy: "user-1",
+ createdByUser: null,
+ },
+ error: null,
+ });
+
+ render(<SavedViewHarness />);
+
+ await waitFor(() => {
+ expect(screen.getByTestId("loading-state").textContent).toBe("ready");
+ });
+ expect(screen.getByTestId("explicit-state").textContent).toContain(
+ "checkout",
+ );
+ });
+
+ it("does not re-apply a saved view after explicit default selection during bootstrap", async () => {
+ queryParamStore.set("viewId", "view-1");
+
+ mockUseRouter.mockReturnValue({
+ isReady: true,
+ query: { viewId: "view-1" },
+ });
+
+ // Simulate unresolved getById request so bootstrap remains in-progress.
+ mockGetByIdUseQuery.mockReturnValue({
+ data: undefined,
+ error: null,
+ });
+
+ render(<ViewSelectionHarness />);
+
+ await waitFor(() => {
+ expect(screen.getByTestId("selected-view-id").textContent).toBe("view-1");
+ });
+
+ fireEvent.click(screen.getByRole("button", { name: "select-default" }));
+
+ await waitFor(() => {
+ expect(screen.getByTestId("selected-view-id").textContent).toBe("null");
+ });
+
+ await waitFor(() => {
+ expect(queryParamStore.has("viewId")).toBe(false);
+ });
+ });
+
+ it("ignores late saved-view responses after explicit default selection", async () => {
+ let returnLateResponse = false;
+
+ queryParamStore.set("viewId", "view-1");
+ mockUseRouter.mockReturnValue({
+ isReady: true,
+ query: { viewId: "view-1" },
+ });
+
+ mockGetByIdUseQuery.mockImplementation(() => {
+ if (!returnLateResponse) {
+ return { data: undefined, error: null, isSuccess: false };
+ }
+
+ return {
+ data: {
+ id: "view-1",
+ name: "Late response view",
+ tableName: TableViewPresetTableName.Traces,
+ projectId: "project-1",
+ orderBy: null,
+ filters: OLD_SAVED_VIEW_FILTERS,
+ columnOrder: null,
+ columnVisibility: null,
+ searchQuery: "",
+ createdAt: new Date("2026-01-01T00:00:00.000Z"),
+ updatedAt: new Date("2026-01-01T00:00:00.000Z"),
+ createdBy: "user-1",
+ createdByUser: null,
+ },
+ error: null,
+ };
+ });
+
+ const { rerender } = render(<ViewSelectionHarness />);
+
+ await waitFor(() => {
+ expect(screen.getByTestId("selected-view-id").textContent).toBe("view-1");
+ });
+
+ fireEvent.click(screen.getByRole("button", { name: "select-default" }));
+
+ await waitFor(() => {
+ expect(screen.getByTestId("selected-view-id").textContent).toBe("null");
+ });
+
+ expect(screen.getByTestId("applied-filter-count").textContent).toBe("0");
+
+ act(() => {
+ returnLateResponse = true;
+ });
+ rerender(<ViewSelectionHarness />);
+
+ await waitFor(() => {
+ expect(screen.getByTestId("selected-view-id").textContent).toBe("null");
+ expect(screen.getByTestId("applied-filter-count").textContent).toBe("0");
+ });
+ });
+});
diff --git a/web/src/features/filters/sidebarFilterSessionPersistence.clienttest.tsx b/web/src/features/filters/sidebarFilterSessionPersistence.clienttest.tsx
new file mode 100644
index 0000000000..30c4307a85
--- /dev/null
+++ b/web/src/features/filters/sidebarFilterSessionPersistence.clienttest.tsx
@@ -0,0 +1,262 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import type { FilterState } from "@langfuse/shared";
+import { useSidebarFilterState } from "./hooks/useSidebarFilterState";
+import type { FilterConfig } from "./lib/filter-config";
+import { encodeFiltersGeneric } from "./lib/filter-query-encoding";
+import { buildSidebarFilterQueryStorageKey } from "./lib/persistedSidebarFilterQuery";
+
+const queryParamStore = new Map<string, unknown>();
+
+jest.mock("use-query-params", () => {
+ const React = require("react");
+ const actual = jest.requireActual("use-query-params");
+
+ 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,
+ ) => {
+ queueMicrotask(() => {
+ setValue((previous: unknown) => {
+ const resolved =
+ typeof next === "function" ? next(previous) : (next ?? null);
+
+ if (resolved === null || resolved === "") {
+ queryParamStore.delete(key);
+ return null;
+ }
+
+ queryParamStore.set(key, resolved);
+ return resolved;
+ });
+ });
+ },
+ [key],
+ );
+
+ React.useEffect(() => {
+ if (value === null || value === "") {
+ queryParamStore.delete(key);
+ return;
+ }
+
+ queryParamStore.set(key, value);
+ }, [key, value]);
+
+ return [value, setQueryValue] as const;
+ },
+ };
+});
+
+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_OPTIONS = {
+ name: ["checkout", "search"],
+};
+
+const FILTER_A: FilterState = [
+ {
+ column: "name",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["checkout"],
+ },
+];
+
+const FILTER_B: FilterState = [
+ {
+ column: "name",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["search"],
+ },
+];
+
+function SessionPersistenceHarness(props: { contextId?: string | null }) {
+ const queryFilter = useSidebarFilterState(TEST_FILTER_CONFIG, TEST_OPTIONS, {
+ sessionFilterContextId: props.contextId ?? null,
+ });
+
+ return (
+ <div>
+ <pre data-testid="explicit-state">
+ {JSON.stringify(queryFilter.explicitFilterState)}
+ </pre>
+ <button
+ data-testid="set-filter-b"
+ onClick={() => queryFilter.setFilterState(FILTER_B)}
+ >
+ Set B
+ </button>
+ <button
+ data-testid="clear-filters"
+ onClick={() => queryFilter.setFilterState([])}
+ >
+ Clear
+ </button>
+ </div>
+ );
+}
+
+describe("useSidebarFilterState session persistence", () => {
+ const encodedFilterA = encodeFiltersGeneric(FILTER_A);
+ const encodedFilterB = encodeFiltersGeneric(FILTER_B);
+ const buildSessionKey = (contextId: string | null = null) =>
+ buildSidebarFilterQueryStorageKey({
+ tableName: TEST_FILTER_CONFIG.tableName,
+ contextId,
+ });
+ const encodeStoredState = (query: string, contextId: string | null = null) =>
+ JSON.stringify({ contextId, query });
+
+ beforeEach(() => {
+ sessionStorage.clear();
+ queryParamStore.clear();
+ });
+
+ const getExplicitState = () =>
+ JSON.parse(screen.getByTestId("explicit-state").textContent ?? "[]");
+
+ it.each([
+ {
+ name: "falls back to session filter state when URL filter is missing",
+ setup: () => {
+ sessionStorage.setItem(
+ buildSessionKey(),
+ encodeStoredState(encodedFilterA),
+ );
+ },
+ expectedState: FILTER_A,
+ expectedSessionQuery: encodedFilterA,
+ expectUrlFilter: false,
+ },
+ {
+ name: "prefers URL filter over session and mirrors URL filter into session",
+ setup: () => {
+ sessionStorage.setItem(
+ buildSessionKey(),
+ encodeStoredState(encodedFilterA),
+ );
+ queryParamStore.set("filter", encodedFilterB);
+ },
+ expectedState: FILTER_B,
+ expectedSessionQuery: encodedFilterB,
+ expectUrlFilter: true,
+ },
+ ])(
+ "$name",
+ async ({ setup, expectedState, expectedSessionQuery, expectUrlFilter }) => {
+ const sessionKey = buildSessionKey();
+ setup();
+
+ render(<SessionPersistenceHarness />);
+
+ await waitFor(() => {
+ expect(getExplicitState()).toEqual(expectedState);
+ });
+
+ await waitFor(() => {
+ expect(sessionStorage.getItem(sessionKey)).toBe(
+ encodeStoredState(expectedSessionQuery),
+ );
+ });
+
+ expect(queryParamStore.has("filter")).toBe(expectUrlFilter);
+ },
+ );
+
+ it("writes URL and session on update and clears both on reset", async () => {
+ const sessionKey = buildSessionKey();
+
+ render(<SessionPersistenceHarness />);
+
+ fireEvent.click(screen.getByTestId("set-filter-b"));
+
+ await waitFor(() => {
+ expect(queryParamStore.get("filter")).toBe(encodedFilterB);
+ });
+ expect(sessionStorage.getItem(sessionKey)).toBe(
+ encodeStoredState(encodedFilterB),
+ );
+
+ fireEvent.click(screen.getByTestId("clear-filters"));
+
+ await waitFor(() => {
+ expect(queryParamStore.has("filter")).toBe(false);
+ });
+ expect(sessionStorage.getItem(sessionKey)).toBe(encodeStoredState(""));
+ });
+
+ it("resets persisted query when session context changes", async () => {
+ const oldSessionKey = buildSessionKey("old");
+ const newSessionKey = buildSessionKey("new");
+
+ sessionStorage.setItem(
+ oldSessionKey,
+ encodeStoredState(encodedFilterA, "old"),
+ );
+
+ render(<SessionPersistenceHarness contextId="new" />);
+
+ await waitFor(() => {
+ expect(getExplicitState()).toEqual([]);
+ });
+
+ expect(sessionStorage.getItem(newSessionKey)).toBe(
+ encodeStoredState("", "new"),
+ );
+ });
+
+ it("clears filter state immediately and eventually clears URL/session", async () => {
+ const sessionKey = buildSessionKey();
+ queryParamStore.set("filter", encodedFilterB);
+
+ render(<SessionPersistenceHarness />);
+
+ await waitFor(() => {
+ expect(getExplicitState()).toEqual(FILTER_B);
+ });
+
+ fireEvent.click(screen.getByTestId("clear-filters"));
+
+ // Regression contract: UI state clears in the same interaction.
+ expect(getExplicitState()).toEqual([]);
+
+ await waitFor(
+ () => {
+ expect(queryParamStore.has("filter")).toBe(false);
+ },
+ { timeout: 300 },
+ );
+
+ await waitFor(() => {
+ expect(sessionStorage.getItem(sessionKey)).toBe(encodeStoredState(""));
+ });
+ });
+});
diff --git a/web/src/features/prompts/components/prompts-table.tsx b/web/src/features/prompts/components/prompts-table.tsx
index 86ab6c41bc..29cf4a2abd 100644
--- a/web/src/features/prompts/components/prompts-table.tsx
+++ b/web/src/features/prompts/components/prompts-table.tsx
@@ -230,8 +230,10 @@ export function PromptTable() {
const queryFilter = useSidebarFilterState(
promptFilterConfig,
newFilterOptions,
- projectId,
- promptFilterOptions.isPending,
+ {
+ loading: promptFilterOptions.isPending,
+ sessionFilterContextId: projectId ?? null,
+ },
);
useEffect(() => {