Skip to content

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

fix(filters): persist global time range across views (URL ⊕ localStorage) (LFE-10497) (#14535)

Nikita Kabardin2c2dcd9cff0a
diff --git a/web/src/features/global-time-range/README.md b/web/src/features/global-time-range/README.md
new file mode 100644
index 0000000000..324288e590
--- /dev/null
+++ b/web/src/features/global-time-range/README.md
@@ -0,0 +1,46 @@
+# Global time range (LFE-10497)
+
+The global time filter that persists across views within a project (Home ↔
+Trace ↔ Sessions …). Foundation for the date picker (LFE-8156), which is the
+editor that reads/writes this state.
+
+## Owner map
+
+- `globalDateRangeStore.ts` — global singleton Zustand store (with `persist`).
+ Single source of truth for the **per-user default**, namespaced by project
+ (`defaultsByProject: Record<projectId, token>`), in relative meta-format.
+ Owns the localStorage boundary (one key, `langfuse-global-date-range`). The
+ store is global because the default is cross-route product state; the data is
+ per-project because switching projects must give each its own range.
+- `useGlobalDateRange.ts` — composition hook. Pure, no effects: derives the
+ displayed `TimeRange` from the URL `?dateRange=` (route source of truth) **⊕**
+ the store default (presence-XOR, no merging), via `resolveTimeRange`. The only
+ writer is `setTimeRange` (explicit pick) → URL + store default.
+- `resolveTimeRange` / `rangeToString` / `rangeFromString` — pure encoding +
+ XOR resolution, in `@/src/utils/date-range-utils.ts` (co-located with the
+ other range utilities); covered by `date-range-utils.clienttest.ts`.
+
+Consumers don't use these directly: `useDashboardDateRange` and
+`useTableDateRange` (in `@/src/hooks/`) are thin per-view delegators that pass
+the view's allowed presets + fallback.
+
+## Data flow (one-way)
+
+```
+URL ?dateRange (route SoT, explicit) ─┐
+ ├─ resolveTimeRange (pure) ─▶ timeRange ─▶ views
+store default (per-project, persisted)┘
+ ▲
+ setTimeRange ──▶ setQueryParams(URL) + store.setProjectDefault ──▶ persist→localStorage
+```
+
+The default is never auto-written to the URL: clean navigations read the store
+default and leave the URL clean, so shared links carry only explicitly-set
+params.
+
+## Next slice
+
+If project-scoped client state recurs (column/view prefs, drafts), promote the
+"select this project's slice" pattern into a shared `<ProjectScope>` provider;
+`useGlobalDateRange` already reads only the active project's slice, so it can
+move without consumer churn.
diff --git a/web/src/features/global-time-range/globalDateRangeStore.clienttest.ts b/web/src/features/global-time-range/globalDateRangeStore.clienttest.ts
new file mode 100644
index 0000000000..89f4297b24
--- /dev/null
+++ b/web/src/features/global-time-range/globalDateRangeStore.clienttest.ts
@@ -0,0 +1,29 @@
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { useGlobalDateRangeStore } from "@/src/features/global-time-range/globalDateRangeStore";
+
+describe("globalDateRangeStore", () => {
+ beforeEach(() => {
+ useGlobalDateRangeStore.setState({ defaultsByProject: {} });
+ });
+
+ it("stores a project's default in relative meta-format", () => {
+ useGlobalDateRangeStore.getState().actions.setProjectDefault("projA", "7d");
+ expect(useGlobalDateRangeStore.getState().defaultsByProject).toEqual({
+ projA: "7d",
+ });
+ });
+
+ it("scopes defaults per project — one project never clobbers another", () => {
+ const { setProjectDefault } = useGlobalDateRangeStore.getState().actions;
+ setProjectDefault("projA", "7d");
+ setProjectDefault("projB", "30d");
+ // Re-setting A must not touch B (the project-switch clobber regression).
+ setProjectDefault("projA", "1h");
+
+ expect(useGlobalDateRangeStore.getState().defaultsByProject).toEqual({
+ projA: "1h",
+ projB: "30d",
+ });
+ });
+});
diff --git a/web/src/features/global-time-range/globalDateRangeStore.ts b/web/src/features/global-time-range/globalDateRangeStore.ts
new file mode 100644
index 0000000000..7d0a693fef
--- /dev/null
+++ b/web/src/features/global-time-range/globalDateRangeStore.ts
@@ -0,0 +1,74 @@
+// Global time-range store — the persisted per-user DEFAULT, one source per concern.
+//
+// Data direction is deliberately one-way and un-merged (the presence-XOR rule;
+// LFE-10497). There are two independent sources, reconciled by a pure resolver
+// (`resolveTimeRange`) in `useGlobalDateRange`, never merged:
+//
+// - the URL `?dateRange=` is the route source of truth for an EXPLICIT
+// selection (shareable / deep-linkable), owned by use-query-params;
+// - this store is the cross-route source of truth for the per-user DEFAULT,
+// in relative meta-format ("7d" / "<from>-<to>"), persisted to localStorage.
+//
+// The default is kept here — not in the URL — so a clean navigation reads the
+// default and leaves the URL clean, and a shared link carries only what the
+// user explicitly set.
+//
+// Why a single global store keyed by project (not a per-mount hook reading a
+// per-project localStorage key): the whole map lives in one in-memory store, so
+// switching projects merely selects a different field. There is no per-mount
+// re-hydration and therefore no way to clobber project B's default with project
+// A's value on an in-app project switch.
+
+import { create } from "zustand";
+import {
+ createJSONStorage,
+ persist,
+ type StateStorage,
+} from "zustand/middleware";
+
+export const GLOBAL_DATE_RANGE_STORAGE_KEY = "langfuse-global-date-range";
+
+// No-op storage on the server; the real localStorage is used on the client.
+const noopStorage: StateStorage = {
+ getItem: () => null,
+ setItem: () => {},
+ removeItem: () => {},
+};
+
+type GlobalDateRangeState = {
+ /**
+ * Per-project default time range in relative meta-format. Scoped by project so
+ * a tightly-zoomed debugging range in one project does not leak into another.
+ */
+ defaultsByProject: Record<string, string>;
+ actions: {
+ /** Persist the per-user default for a project (an explicit user pick). */
+ setProjectDefault: (projectId: string, encoded: string) => void;
+ };
+};
+
+export const useGlobalDateRangeStore = create<GlobalDateRangeState>()(
+ persist(
+ (set) => ({
+ defaultsByProject: {},
+ actions: {
+ setProjectDefault: (projectId, encoded) =>
+ set((state) => ({
+ defaultsByProject: {
+ ...state.defaultsByProject,
+ [projectId]: encoded,
+ },
+ })),
+ },
+ }),
+ {
+ name: GLOBAL_DATE_RANGE_STORAGE_KEY,
+ // Hydrates from localStorage on the client; no-op during SSR.
+ storage: createJSONStorage(() =>
+ typeof window !== "undefined" ? window.localStorage : noopStorage,
+ ),
+ // Persist only data, never the actions object.
+ partialize: (state) => ({ defaultsByProject: state.defaultsByProject }),
+ },
+ ),
+);
diff --git a/web/src/features/global-time-range/useGlobalDateRange.ts b/web/src/features/global-time-range/useGlobalDateRange.ts
new file mode 100644
index 0000000000..82b46a782d
--- /dev/null
+++ b/web/src/features/global-time-range/useGlobalDateRange.ts
@@ -0,0 +1,97 @@
+import { useQueryParams, StringParam } from "use-query-params";
+import { useCallback, useMemo } from "react";
+import { useRouter } from "next/router";
+import {
+ rangeToString,
+ resolveTimeRange,
+ type TimeRange,
+} from "@/src/utils/date-range-utils";
+import { useGlobalDateRangeStore } from "@/src/features/global-time-range/globalDateRangeStore";
+
+export interface UseGlobalDateRangeOutput {
+ timeRange: TimeRange;
+ setTimeRange: (timeRange: TimeRange) => void;
+}
+
+/**
+ * Shared foundation for the global time filter (LFE-10497).
+ *
+ * One-way data flow, no effects: the displayed `timeRange` is a pure derivation
+ * of two independent sources, reconciled by the presence-XOR rule (no merging):
+ *
+ * - the URL `?dateRange=` (route source of truth, authoritative when present
+ * so deep/shared links reproduce what the sharer sees); and
+ * - the per-user default in {@link useGlobalDateRangeStore} (cross-route,
+ * persisted to localStorage) used when the URL carries no time param.
+ *
+ * An explicit pick is the only writer: it sets the URL (shareable) and the
+ * store default (the new baseline for clean navigations). Relative presets are
+ * stored in meta-format and re-evaluated to "now" on each read; absolute
+ * timestamps are stored only for a user-selected custom range. Both the
+ * dashboard and table date-range hooks delegate here so the views share one
+ * contract.
+ *
+ * `persistAsDefault` (default true) marks a surface as the shared cross-view
+ * session filter. Pass `false` for an authoring/preview surface (e.g. the
+ * widget editor) whose picker is transient editor state, not the user's
+ * default: it then neither reads nor writes the shared default, and only syncs
+ * to the URL — so previewing a range never overwrites the default for
+ * Home/Traces/Sessions/etc.
+ */
+export function useGlobalDateRange<T extends string>({
+ allowedRanges,
+ fallback,
+ persistAsDefault = true,
+}: {
+ allowedRanges: readonly T[];
+ fallback: T;
+ persistAsDefault?: boolean;
+}): UseGlobalDateRangeOutput {
+ const router = useRouter();
+ const projectId =
+ typeof router.query.projectId === "string"
+ ? router.query.projectId
+ : undefined;
+
+ // Selector returns a primitive (this project's stored token, or null). Always
+ // current — switching projects selects a different field of the same store.
+ // Page-local surfaces (persistAsDefault === false) ignore the shared default.
+ const storedValue = useGlobalDateRangeStore((state) =>
+ persistAsDefault && projectId
+ ? (state.defaultsByProject[projectId] ?? null)
+ : null,
+ );
+ const setProjectDefault = useGlobalDateRangeStore(
+ (state) => state.actions.setProjectDefault,
+ );
+
+ // Route state stays in the router/query hook. Read WITHOUT a default so
+ // presence distinguishes "URL carries a range" from "URL has none".
+ const [queryParams, setQueryParams] = useQueryParams({
+ dateRange: StringParam,
+ });
+
+ const setTimeRange = useCallback(
+ (next: TimeRange) => {
+ const encoded = rangeToString(next);
+ // The URL becomes authoritative (shareable); the store default becomes the
+ // baseline for subsequent clean navigations — unless this surface is
+ // page-local (an authoring/preview picker), which never persists.
+ setQueryParams({ dateRange: encoded });
+ if (persistAsDefault && projectId) setProjectDefault(projectId, encoded);
+ },
+ [persistAsDefault, projectId, setProjectDefault, setQueryParams],
+ );
+
+ return useMemo(
+ () => ({
+ timeRange: resolveTimeRange(
+ { urlValue: queryParams.dateRange, storedValue },
+ allowedRanges,
+ fallback,
+ ),
+ setTimeRange,
+ }),
+ [queryParams.dateRange, storedValue, allowedRanges, fallback, setTimeRange],
+ );
+}
diff --git a/web/src/features/widgets/components/WidgetForm.tsx b/web/src/features/widgets/components/WidgetForm.tsx
index 1847295103..d94b70ae55 100644
--- a/web/src/features/widgets/components/WidgetForm.tsx
+++ b/web/src/features/widgets/components/WidgetForm.tsx
@@ -439,9 +439,12 @@ export function WidgetForm({
initialDefaultSort?.order ?? "DESC",
);
- // Filter state
+ // Filter state. The picker here is a transient PREVIEW control — the widget
+ // does not own a time range (the host dashboard supplies one at render time),
+ // so it must not write the user's shared cross-view default.
const { timeRange, setTimeRange } = useDashboardDateRange({
defaultRelativeAggregation: "last7Days",
+ persistAsDefault: false,
});
// Convert timeRange to absolute date range for compatibility
diff --git a/web/src/hooks/useDashboardDateRange.tsx b/web/src/hooks/useDashboardDateRange.tsx
index 74696f7e63..2012a5bdb9 100644
--- a/web/src/hooks/useDashboardDateRange.tsx
+++ b/web/src/hooks/useDashboardDateRange.tsx
@@ -1,50 +1,30 @@
-import { useQueryParams, StringParam, withDefault } from "use-query-params";
import {
type DashboardDateRangeAggregationOption,
DEFAULT_DASHBOARD_AGGREGATION_SELECTION,
DASHBOARD_AGGREGATION_OPTIONS,
- rangeToString,
- rangeFromString,
- getAbbreviatedTimeRange,
- type TimeRange,
} from "@/src/utils/date-range-utils";
-import { useMemo } from "react";
+import {
+ useGlobalDateRange,
+ type UseGlobalDateRangeOutput,
+} from "@/src/features/global-time-range/useGlobalDateRange";
-export interface UseDashboardDateRangeOutput {
- timeRange: TimeRange;
- setTimeRange: (timeRange: TimeRange) => void;
-}
+export type UseDashboardDateRangeOutput = UseGlobalDateRangeOutput;
export function useDashboardDateRange(
options: {
defaultRelativeAggregation?: DashboardDateRangeAggregationOption;
+ /**
+ * Set false on authoring/preview surfaces (e.g. the widget editor) whose
+ * picker is transient editor state — see {@link useGlobalDateRange}.
+ */
+ persistAsDefault?: boolean;
} = {},
): UseDashboardDateRangeOutput {
- const fallbackAggregation =
- options.defaultRelativeAggregation ??
- DEFAULT_DASHBOARD_AGGREGATION_SELECTION;
-
- const [queryParams, setQueryParams] = useQueryParams({
- dateRange: withDefault(
- StringParam,
- getAbbreviatedTimeRange(fallbackAggregation),
- ),
+ return useGlobalDateRange({
+ allowedRanges: DASHBOARD_AGGREGATION_OPTIONS,
+ fallback:
+ options.defaultRelativeAggregation ??
+ DEFAULT_DASHBOARD_AGGREGATION_SELECTION,
+ persistAsDefault: options.persistAsDefault,
});
-
- return useMemo(() => {
- const timeRange = rangeFromString(
- queryParams.dateRange,
- DASHBOARD_AGGREGATION_OPTIONS,
- fallbackAggregation,
- );
-
- const setTimeRange = (timeRange: TimeRange) => {
- setQueryParams({ dateRange: rangeToString(timeRange) });
- };
-
- return {
- timeRange,
- setTimeRange,
- };
- }, [queryParams.dateRange, fallbackAggregation, setQueryParams]);
}
diff --git a/web/src/hooks/useTableDateRange.tsx b/web/src/hooks/useTableDateRange.tsx
index ff2a728d0c..9a1bb6e7be 100644
--- a/web/src/hooks/useTableDateRange.tsx
+++ b/web/src/hooks/useTableDateRange.tsx
@@ -1,61 +1,25 @@
-import { useQueryParams, StringParam, withDefault } from "use-query-params";
import {
type TableDateRangeAggregationOption,
TABLE_AGGREGATION_OPTIONS,
- rangeToString,
- rangeFromString,
- getAbbreviatedTimeRange,
- type TimeRange,
} from "@/src/utils/date-range-utils";
-import { useMemo } from "react";
-import useSessionStorage from "@/src/components/useSessionStorage";
+import {
+ useGlobalDateRange,
+ type UseGlobalDateRangeOutput,
+} from "@/src/features/global-time-range/useGlobalDateRange";
-export interface UseTableDateRangeOutput {
- timeRange: TimeRange;
- setTimeRange: (timeRange: TimeRange) => void;
-}
+export type UseTableDateRangeOutput = UseGlobalDateRangeOutput;
export function useTableDateRange(
- projectId: string,
+ // Kept for call-site compatibility; the storage key is derived from the
+ // active project route inside useGlobalDateRange so dashboard and table views
+ // share a single per-project key.
+ _projectId: string,
options: {
defaultRelativeAggregation?: TableDateRangeAggregationOption;
} = {},
): UseTableDateRangeOutput {
- const fallbackAggregation = options.defaultRelativeAggregation ?? "last1Day";
-
- // Get stored preference from local storage
- const [storedDateRange, setStoredDateRange] = useSessionStorage(
- `tableDateRangeState-${projectId}`,
- getAbbreviatedTimeRange(fallbackAggregation),
- );
-
- // Use stored preference as default if no URL param is set
- const [queryParams, setQueryParams] = useQueryParams({
- dateRange: withDefault(StringParam, storedDateRange),
+ return useGlobalDateRange({
+ allowedRanges: TABLE_AGGREGATION_OPTIONS,
+ fallback: options.defaultRelativeAggregation ?? "last1Day",
});
-
- return useMemo(() => {
- const timeRange = rangeFromString(
- queryParams.dateRange,
- TABLE_AGGREGATION_OPTIONS,
- fallbackAggregation,
- );
-
- const setTimeRange = (timeRange: TimeRange) => {
- const newParam = rangeToString(timeRange);
- setQueryParams({ dateRange: newParam });
- // Also update local storage for future sessions
- setStoredDateRange(newParam);
- };
-
- return {
- timeRange,
- setTimeRange,
- };
- }, [
- queryParams.dateRange,
- fallbackAggregation,
- setQueryParams,
- setStoredDateRange,
- ]);
}
diff --git a/web/src/utils/date-range-utils.clienttest.ts b/web/src/utils/date-range-utils.clienttest.ts
new file mode 100644
index 0000000000..f79194dc73
--- /dev/null
+++ b/web/src/utils/date-range-utils.clienttest.ts
@@ -0,0 +1,94 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ DASHBOARD_AGGREGATION_OPTIONS,
+ DEFAULT_DASHBOARD_AGGREGATION_SELECTION,
+ rangeToString,
+ resolveTimeRange,
+} from "@/src/utils/date-range-utils";
+
+describe("resolveTimeRange (presence-XOR)", () => {
+ const allowed = DASHBOARD_AGGREGATION_OPTIONS;
+ const fallback = DEFAULT_DASHBOARD_AGGREGATION_SELECTION;
+
+ it("uses the URL value when present, ignoring the stored preference", () => {
+ expect(
+ resolveTimeRange(
+ { urlValue: "7d", storedValue: "30d" },
+ allowed,
+ fallback,
+ ),
+ ).toEqual({ range: "last7Days" });
+ });
+
+ it("falls back to the stored preference when the URL has no time param", () => {
+ expect(
+ resolveTimeRange(
+ { urlValue: undefined, storedValue: "30d" },
+ allowed,
+ fallback,
+ ),
+ ).toEqual({ range: "last30Days" });
+ });
+
+ it("degrades to the fallback when the URL preset is invalid for this view (does not fall through to storage)", () => {
+ // "6h" (last6Hours) is a table-only option, absent from the dashboard set.
+ // Because the URL is present it wins under XOR, so the stored "30d" must be
+ // ignored entirely and the result must be the fallback — never "30d".
+ expect(
+ resolveTimeRange(
+ { urlValue: "6h", storedValue: "30d" },
+ allowed,
+ fallback,
+ ),
+ ).toEqual({ range: fallback });
+ });
+
+ it("treats an empty-string URL value as absent", () => {
+ expect(
+ resolveTimeRange({ urlValue: "", storedValue: "7d" }, allowed, fallback),
+ ).toEqual({ range: "last7Days" });
+ });
+
+ it("uses the view fallback when neither source is set", () => {
+ expect(
+ resolveTimeRange(
+ { urlValue: undefined, storedValue: null },
+ allowed,
+ fallback,
+ ),
+ ).toEqual({ range: fallback });
+ });
+
+ it("degrades to the fallback when the stored preset is invalid for this view", () => {
+ // "6h" (last6Hours) is a table-only option, absent from the dashboard set.
+ expect(
+ resolveTimeRange(
+ { urlValue: undefined, storedValue: "6h" },
+ allowed,
+ fallback,
+ ),
+ ).toEqual({ range: fallback });
+ });
+
+ it("round-trips an absolute custom range from either source", () => {
+ const from = new Date("2026-01-01T00:00:00.000Z");
+ const to = new Date("2026-01-08T00:00:00.000Z");
+ const encoded = rangeToString({ from, to });
+
+ expect(
+ resolveTimeRange(
+ { urlValue: encoded, storedValue: null },
+ allowed,
+ fallback,
+ ),
+ ).toEqual({ from, to });
+ expect(
+ resolveTimeRange(
+ { urlValue: undefined, storedValue: encoded },
+ allowed,
+ fallback,
+ ),
+ ).toEqual({ from, to });
+ });
+});
diff --git a/web/src/utils/date-range-utils.ts b/web/src/utils/date-range-utils.ts
index 060fe6b1d4..b76ddbd76a 100644
--- a/web/src/utils/date-range-utils.ts
+++ b/web/src/utils/date-range-utils.ts
@@ -642,6 +642,41 @@ export function rangeFromString<T extends string>(
return { range: fallback };
}
+/**
+ * Resolves the active time range from its two possible sources using the
+ * presence-XOR rule (no merging):
+ * - If the URL carries an explicit `dateRange` value, it wins outright — shared
+ * links are authoritative and we ignore the persisted preference.
+ * - Otherwise we fall back to the per-user stored default (relative
+ * meta-format), so clean navigations keep the last chosen range.
+ * - Otherwise the view's fallback preset.
+ *
+ * A stored value that is not valid for this view's `allowedRanges` (e.g. a
+ * table-only preset surfacing on a dashboard) degrades to the fallback rather
+ * than merging.
+ */
+export function resolveTimeRange<T extends string>(
+ sources: { urlValue?: string | null; storedValue?: string | null },
+ allowedRanges: readonly T[],
+ fallback: T,
+): TimeRange {
+ const fromUrl =
+ sources.urlValue != null && sources.urlValue !== ""
+ ? sources.urlValue
+ : null;
+ const fromStorage =
+ sources.storedValue != null && sources.storedValue !== ""
+ ? sources.storedValue
+ : null;
+
+ const source = fromUrl ?? fromStorage;
+ if (source == null) {
+ return { range: fallback };
+ }
+
+ return rangeFromString(source, allowedRanges, fallback);
+}
+
/**
* =======================
* Chart Formatting