Skip to content

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

fix(version-update): only prompt reload when the frontend is 48+ hours stale (#15785)

Nikita Kabardinfbbe26637dc6
diff --git a/web/src/features/version-update/VersionUpdateBanner.clienttest.tsx b/web/src/features/version-update/VersionUpdateBanner.clienttest.tsx
index a839ad9bc3..196a8aa822 100644
--- a/web/src/features/version-update/VersionUpdateBanner.clienttest.tsx
+++ b/web/src/features/version-update/VersionUpdateBanner.clienttest.tsx
@@ -1,85 +1,107 @@
-import { render, screen, fireEvent } from "@testing-library/react";
+import { act, render, screen, fireEvent } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { VersionUpdateBanner } from "./VersionUpdateBanner";
import { VersionUpdateBannerView } from "./VersionUpdateBannerView";
+import {
+ createVersionUpdateStore,
+ VERSION_UPDATE_MIN_STALENESS_MS,
+ VERSION_UPDATE_DISMISS_SUPPRESSION_MS,
+ VERSION_UPDATE_SUPPRESSED_UNTIL_KEY,
+ type VersionUpdateStore,
+} from "./versionUpdateStore";
+import type * as versionUpdateStoreModule from "./versionUpdateStore";
-// Shared mutable mock state (hoisted above the vi.mock factories).
+// Hoisted mock state. With `h.store` set, the mocked singleton and the
+// availability hook delegate to that REAL store (integration tests); otherwise
+// the plain stubs apply.
const h = vi.hoisted(() => ({
capture: vi.fn(),
dismiss: vi.fn(),
markShownReported: vi.fn(() => true),
available: true,
settled: true,
+ store: null as VersionUpdateStore | null,
}));
-// The connected banner portals into the top-most overlay layer, whose DOM
-// container only exists via _document.tsx; render children inline for the test.
+// The banner portals into an overlay layer that only exists via _document.tsx.
vi.mock("@/src/components/ui/layer", () => ({
Layer: ({ children }: { children?: unknown }) => children,
}));
vi.mock("@/src/features/posthog-analytics/usePostHogClientCapture", () => ({
usePostHogClientCapture: () => h.capture,
}));
-vi.mock("./versionUpdateStore", () => ({
- versionUpdateStore: {
- dismiss: h.dismiss,
- markShownReported: h.markShownReported,
- },
-}));
-vi.mock("./useVersionUpdateAvailable", () => ({
- useVersionUpdateAvailable: () => h.available,
-}));
+vi.mock("./versionUpdateStore", async (importOriginal) => {
+ const actual = await importOriginal<typeof versionUpdateStoreModule>();
+ return {
+ ...actual,
+ versionUpdateStore: {
+ dismiss: () => (h.store ? h.store.dismiss() : h.dismiss()),
+ markShownReported: () =>
+ h.store ? h.store.markShownReported() : h.markShownReported(),
+ },
+ };
+});
+vi.mock("./useVersionUpdateAvailable", async () => {
+ const { useSyncExternalStore } = await import("react");
+ const subscribeNoop = () => () => {};
+ return {
+ useVersionUpdateAvailable: () =>
+ useSyncExternalStore(
+ h.store ? h.store.subscribe : subscribeNoop,
+ h.store ? h.store.getSnapshot : () => h.available,
+ () => false,
+ ),
+ };
+});
vi.mock("./useAppSettled", () => ({
useAppSettled: () => h.settled,
}));
-describe("VersionUpdateBannerView", () => {
- it("renders a reload and a dismiss control", () => {
- render(
- <VersionUpdateBannerView onReload={() => {}} onDismiss={() => {}} />,
- );
- expect(screen.getByRole("button", { name: "Reload" })).toBeInTheDocument();
- expect(screen.getByRole("button", { name: "Dismiss" })).toBeInTheDocument();
+const createFakeStorage = () => {
+ const data = new Map<string, string>();
+ return {
+ getItem: (key: string) => data.get(key) ?? null,
+ setItem: (key: string, value: string) => {
+ data.set(key, value);
+ },
+ };
+};
+
+beforeEach(() => {
+ h.capture.mockClear();
+ h.dismiss.mockClear();
+ h.markShownReported.mockClear();
+ h.markShownReported.mockReturnValue(true);
+ h.available = true;
+ h.settled = true;
+ h.store = null;
+ // Reload is invoked on the Reload click; stub it for jsdom.
+ Object.defineProperty(window, "location", {
+ configurable: true,
+ value: { reload: vi.fn() },
});
+});
- it("invokes the callbacks when the controls are clicked", () => {
- const onReload = vi.fn();
- const onDismiss = vi.fn();
- render(
- <VersionUpdateBannerView onReload={onReload} onDismiss={onDismiss} />,
- );
+afterEach(() => {
+ h.store = null;
+ vi.restoreAllMocks();
+});
- fireEvent.click(screen.getByRole("button", { name: "Reload" }));
- expect(onReload).toHaveBeenCalledTimes(1);
+it("VersionUpdateBannerView renders both controls and invokes their callbacks", () => {
+ const onReload = vi.fn();
+ const onDismiss = vi.fn();
+ render(<VersionUpdateBannerView onReload={onReload} onDismiss={onDismiss} />);
- fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));
- expect(onDismiss).toHaveBeenCalledTimes(1);
- });
+ fireEvent.click(screen.getByRole("button", { name: "Reload" }));
+ expect(onReload).toHaveBeenCalledTimes(1);
+ fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));
+ expect(onDismiss).toHaveBeenCalledTimes(1);
});
describe("VersionUpdateBanner (connected)", () => {
- beforeEach(() => {
- h.capture.mockClear();
- h.dismiss.mockClear();
- h.markShownReported.mockClear();
- h.markShownReported.mockReturnValue(true);
- h.available = true;
- h.settled = true;
- // Reload is invoked on the Reload click; stub it so jsdom doesn't complain.
- Object.defineProperty(window, "location", {
- configurable: true,
- value: { reload: vi.fn() },
- });
- });
-
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
- it("shows and reports banner_shown when an update is available and the app has settled", () => {
+ it("shows and reports banner_shown exactly once when available and settled", () => {
render(<VersionUpdateBanner />);
expect(screen.getByRole("button", { name: "Reload" })).toBeInTheDocument();
- expect(h.capture).toHaveBeenCalledWith("version_update:banner_shown");
expect(
h.capture.mock.calls.filter(
(c) => c[0] === "version_update:banner_shown",
@@ -87,25 +109,15 @@ describe("VersionUpdateBanner (connected)", () => {
).toHaveLength(1);
});
- it("delegates the once-per-appearance guard to the store (no banner_shown when it returns false)", () => {
- // Simulates a remount for an appearance the store already reported.
- h.markShownReported.mockReturnValue(false);
- render(<VersionUpdateBanner />);
- expect(screen.getByRole("button", { name: "Reload" })).toBeInTheDocument();
- expect(h.capture).not.toHaveBeenCalledWith("version_update:banner_shown");
- });
-
- it("stays hidden until the app has settled", () => {
+ it("renders nothing (and captures nothing) while unsettled or without an update", () => {
h.settled = false;
- render(<VersionUpdateBanner />);
+ const unsettled = render(<VersionUpdateBanner />);
expect(
screen.queryByRole("button", { name: "Reload" }),
).not.toBeInTheDocument();
- expect(h.capture).not.toHaveBeenCalled();
- expect(h.markShownReported).not.toHaveBeenCalled();
- });
+ unsettled.unmount();
- it("renders nothing when no update is available", () => {
+ h.settled = true;
h.available = false;
render(<VersionUpdateBanner />);
expect(
@@ -120,11 +132,73 @@ describe("VersionUpdateBanner (connected)", () => {
expect(h.capture).toHaveBeenCalledWith("version_update:reload_clicked");
expect(window.location.reload).toHaveBeenCalledTimes(1);
});
+});
+
+describe("VersionUpdateBanner (integration: real store + fake storage)", () => {
+ it("renders nothing and fires no banner_shown until the frontend is 48 h stale", () => {
+ const storage = createFakeStorage();
+ let now = 0;
+ const store = createVersionUpdateStore(() => "running", {
+ debounceMs: 0,
+ now: () => now,
+ getStorage: () => storage,
+ });
+ h.store = store;
- it("captures dismissed and calls the store on Dismiss", () => {
render(<VersionUpdateBanner />);
+ act(() => {
+ store.reportObservedBuildId("deployed");
+ });
+ expect(
+ screen.queryByRole("button", { name: "Reload" }),
+ ).not.toBeInTheDocument();
+ expect(h.capture).not.toHaveBeenCalled();
+
+ // 48 h later the next response surfaces it; banner_shown fires once.
+ act(() => {
+ now = VERSION_UPDATE_MIN_STALENESS_MS;
+ store.reportObservedBuildId("deployed");
+ });
+ expect(screen.getByRole("button", { name: "Reload" })).toBeInTheDocument();
+ expect(
+ h.capture.mock.calls.filter(
+ (c) => c[0] === "version_update:banner_shown",
+ ),
+ ).toHaveLength(1);
+ });
+
+ it("dismiss captures, hides, persists the 24 h window, and keeps new builds quiet", () => {
+ const storage = createFakeStorage();
+ let now = 1_000;
+ const store = createVersionUpdateStore(() => "running", {
+ debounceMs: 0,
+ minStalenessMs: 0,
+ now: () => now,
+ getStorage: () => storage,
+ });
+ h.store = store;
+
+ render(<VersionUpdateBanner />);
+ act(() => {
+ store.reportObservedBuildId("deployed");
+ });
+ expect(screen.getByRole("button", { name: "Reload" })).toBeInTheDocument();
+
fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));
expect(h.capture).toHaveBeenCalledWith("version_update:dismissed");
- expect(h.dismiss).toHaveBeenCalledTimes(1);
+ expect(
+ screen.queryByRole("button", { name: "Reload" }),
+ ).not.toBeInTheDocument();
+ expect(storage.getItem(VERSION_UPDATE_SUPPRESSED_UNTIL_KEY)).toBe(
+ String(1_000 + VERSION_UPDATE_DISMISS_SUPPRESSION_MS),
+ );
+
+ act(() => {
+ now = 2_000;
+ store.reportObservedBuildId("deployed-2"); // genuinely new β€” still quiet
+ });
+ expect(
+ screen.queryByRole("button", { name: "Reload" }),
+ ).not.toBeInTheDocument();
});
});
diff --git a/web/src/features/version-update/versionUpdateStore.clienttest.ts b/web/src/features/version-update/versionUpdateStore.clienttest.ts
index 9cba094fdf..9216083c47 100644
--- a/web/src/features/version-update/versionUpdateStore.clienttest.ts
+++ b/web/src/features/version-update/versionUpdateStore.clienttest.ts
@@ -1,282 +1,284 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { describe, it, expect, vi, afterEach } from "vitest";
import {
createVersionUpdateStore,
isVersionMismatch,
- VERSION_UPDATE_DEBOUNCE_MS,
+ VERSION_UPDATE_MIN_STALENESS_MS,
+ VERSION_UPDATE_SHOW_THROTTLE_MS,
+ VERSION_UPDATE_DISMISS_SUPPRESSION_MS,
+ VERSION_UPDATE_LAST_SHOWN_AT_KEY,
+ VERSION_UPDATE_SUPPRESSED_UNTIL_KEY,
+ VERSION_UPDATE_STALE_SINCE_KEY,
} from "./versionUpdateStore";
-describe("isVersionMismatch", () => {
- it("is true only when both ids are present and differ", () => {
- expect(isVersionMismatch("build-a", "build-b")).toBe(true);
- });
-
- it("is false when the ids are equal", () => {
- expect(isVersionMismatch("build-a", "build-a")).toBe(false);
- });
-
- it("is false when either id is missing", () => {
- // running missing
- expect(isVersionMismatch(null, "build-b")).toBe(false);
- expect(isVersionMismatch(undefined, "build-b")).toBe(false);
- expect(isVersionMismatch("", "build-b")).toBe(false);
- // observed missing
- expect(isVersionMismatch("build-a", null)).toBe(false);
- expect(isVersionMismatch("build-a", undefined)).toBe(false);
- expect(isVersionMismatch("build-a", "")).toBe(false);
- // both missing
- expect(isVersionMismatch(null, null)).toBe(false);
- expect(isVersionMismatch(undefined, undefined)).toBe(false);
- });
+const noStorage = () => undefined;
+
+// Map-backed Storage double, shareable across stores to simulate reloads/tabs.
+const createFakeStorage = () => {
+ const data = new Map<string, string>();
+ return {
+ getItem: (key: string) => data.get(key) ?? null,
+ setItem: (key: string, value: string) => {
+ data.set(key, value);
+ },
+ };
+};
+
+it("isVersionMismatch is true only when both ids are present and differ", () => {
+ expect(isVersionMismatch("build-a", "build-b")).toBe(true);
+ expect(isVersionMismatch("build-a", "build-a")).toBe(false);
+ expect(isVersionMismatch(null, "build-b")).toBe(false);
+ expect(isVersionMismatch(undefined, "build-b")).toBe(false);
+ expect(isVersionMismatch("", "build-b")).toBe(false);
+ expect(isVersionMismatch("build-a", null)).toBe(false);
+ expect(isVersionMismatch("build-a", "")).toBe(false);
+ expect(isVersionMismatch(null, null)).toBe(false);
});
describe("versionUpdateStore", () => {
- it("starts with no update available", () => {
- const store = createVersionUpdateStore(() => "running", 0);
- expect(store.getSnapshot()).toBe(false);
- });
+ // Mechanics tests disable the staleness gate and storage so each pins one behavior.
+ const mechanics = { debounceMs: 0, minStalenessMs: 0, getStorage: noStorage };
- it("stays silent when the observed build matches the running build", () => {
- const store = createVersionUpdateStore(() => "running", 0);
- store.reportObservedBuildId("running");
- expect(store.getSnapshot()).toBe(false);
- });
-
- it("becomes available when a differing build id is observed", () => {
- const store = createVersionUpdateStore(() => "running", 0);
- store.reportObservedBuildId("deployed");
- expect(store.getSnapshot()).toBe(true);
+ afterEach(() => {
+ vi.useRealTimers();
});
- it("stays silent when the running build id is unknown", () => {
- const store = createVersionUpdateStore(() => undefined, 0);
- store.reportObservedBuildId("deployed");
+ it("arms only on a real mismatch", () => {
+ const store = createVersionUpdateStore(() => "running", mechanics);
expect(store.getSnapshot()).toBe(false);
- });
-
- it("ignores empty/absent observed build ids", () => {
- const store = createVersionUpdateStore(() => "running", 0);
+ store.reportObservedBuildId("running");
store.reportObservedBuildId(null);
- store.reportObservedBuildId(undefined);
store.reportObservedBuildId("");
expect(store.getSnapshot()).toBe(false);
- });
-
- it("hides after dismiss and re-shows only when a not-yet-seen build arrives", () => {
- const store = createVersionUpdateStore(() => "running", 0);
-
- store.reportObservedBuildId("deployed-1");
- expect(store.getSnapshot()).toBe(true);
-
- store.dismiss();
- expect(store.getSnapshot()).toBe(false);
-
- // The same build id must not re-trigger the banner after dismissal.
- store.reportObservedBuildId("deployed-1");
- expect(store.getSnapshot()).toBe(false);
-
- // A build id the user has not seen re-shows it.
- store.reportObservedBuildId("deployed-2");
+ store.reportObservedBuildId("deployed");
expect(store.getSnapshot()).toBe(true);
- });
-
- // Rolling deploy: one tab sees responses from BOTH old and new pods, in any
- // order, and build ids are opaque (no orderable newer/older). These guard the
- // three failure modes flagged in review.
- describe("rolling deploy robustness", () => {
- it("stays available once a differing build is seen β€” a later old-pod response cannot suppress it", () => {
- const store = createVersionUpdateStore(() => "running", 0);
-
- store.reportObservedBuildId("deployed"); // new pod
- expect(store.getSnapshot()).toBe(true);
-
- // Old pod still serving the running build id β€” must NOT clear the banner.
- store.reportObservedBuildId("running");
- expect(store.getSnapshot()).toBe(true);
-
- // Alternating pods likewise keep it sticky.
- store.reportObservedBuildId("deployed");
- store.reportObservedBuildId("running");
- expect(store.getSnapshot()).toBe(true);
- });
-
- it("does not reopen a dismissed banner when an already-seen build re-appears (old pod)", () => {
- const store = createVersionUpdateStore(() => "running", 0);
- store.reportObservedBuildId("deployed");
- store.dismiss();
- expect(store.getSnapshot()).toBe(false);
-
- // Old pods keep alternating: re-observing the running id or the
- // already-seen deployed id must not reopen the dismissed banner.
- store.reportObservedBuildId("running");
- store.reportObservedBuildId("deployed");
- expect(store.getSnapshot()).toBe(false);
- });
-
- it("re-observing an already-seen build never flaps the snapshot (no extra notifications)", () => {
- const store = createVersionUpdateStore(() => "running", 0);
- const listener = vi.fn();
- store.subscribe(listener);
-
- store.reportObservedBuildId("deployed"); // 1 change: false→true
- store.reportObservedBuildId("deployed"); // seen β†’ no-op
- store.reportObservedBuildId("running"); // matches running β†’ no-op
- store.reportObservedBuildId("deployed"); // seen β†’ no-op
- expect(listener).toHaveBeenCalledTimes(1);
- expect(store.getSnapshot()).toBe(true);
- });
+ // Unknown running build (self-hosted without a build id) proves nothing.
+ const unknown = createVersionUpdateStore(() => undefined, mechanics);
+ unknown.reportObservedBuildId("deployed");
+ expect(unknown.getSnapshot()).toBe(false);
});
- it("notifies subscribers when the snapshot changes and after unsubscribe stops", () => {
- const store = createVersionUpdateStore(() => "running", 0);
+ it("is sticky and flap-free while rolling-deploy pods serve mixed responses", () => {
+ const store = createVersionUpdateStore(() => "running", mechanics);
const listener = vi.fn();
const unsubscribe = store.subscribe(listener);
- store.reportObservedBuildId("deployed");
+ store.reportObservedBuildId("deployed"); // false→true
+ store.reportObservedBuildId("running"); // old pod β€” cannot clear it
+ store.reportObservedBuildId("deployed"); // re-observation β€” no flap
+ expect(store.getSnapshot()).toBe(true);
expect(listener).toHaveBeenCalledTimes(1);
+ expect(store.getServerSnapshot()).toBe(false);
- // No snapshot change β†’ no extra notification.
- store.reportObservedBuildId("deployed");
+ unsubscribe();
+ store.dismiss();
expect(listener).toHaveBeenCalledTimes(1);
+ });
+ it("dismiss hides the visible banner; only a never-seen build re-shows (in-memory)", () => {
+ const store = createVersionUpdateStore(() => "running", mechanics);
+ store.reportObservedBuildId("deployed-1");
+ expect(store.getSnapshot()).toBe(true);
store.dismiss();
- expect(listener).toHaveBeenCalledTimes(2);
-
- unsubscribe();
- store.reportObservedBuildId("deployed-next");
- expect(listener).toHaveBeenCalledTimes(2);
+ expect(store.getSnapshot()).toBe(false);
+ store.reportObservedBuildId("deployed-1"); // already seen
+ expect(store.getSnapshot()).toBe(false);
+ store.reportObservedBuildId("deployed-2"); // genuinely new
+ expect(store.getSnapshot()).toBe(true);
});
- it("has a server snapshot that is always false", () => {
- const store = createVersionUpdateStore(() => "running", 0);
- store.reportObservedBuildId("deployed");
- expect(store.getServerSnapshot()).toBe(false);
+ it("markShownReported is true once per appearance and re-arms on a new build", () => {
+ const store = createVersionUpdateStore(() => "running", mechanics);
+ store.reportObservedBuildId("deployed-1");
+ expect(store.markShownReported()).toBe(true);
+ expect(store.markShownReported()).toBe(false); // remount/StrictMode replay
+ store.reportObservedBuildId("deployed-1"); // re-observation β€” no reset
+ expect(store.markShownReported()).toBe(false);
+ store.reportObservedBuildId("deployed-2"); // fresh appearance
+ expect(store.markShownReported()).toBe(true);
});
- // `banner_shown` fires once per appearance; the guard lives here (not in
- // component state) so a banner remount cannot double-count one appearance.
- describe("markShownReported (banner_shown once-per-appearance guard)", () => {
- it("returns true once per appearance, then false", () => {
- const store = createVersionUpdateStore(() => "running", 0);
- store.reportObservedBuildId("deployed");
-
- expect(store.markShownReported()).toBe(true);
- // A remount / StrictMode-double-invoked effect calls it again for the same
- // appearance β€” must not count twice.
- expect(store.markShownReported()).toBe(false);
- expect(store.markShownReported()).toBe(false);
+ it("debounces from the FIRST sighting; a second new build does not extend the wait", () => {
+ vi.useFakeTimers();
+ const store = createVersionUpdateStore(() => "running", {
+ debounceMs: 180_000,
+ minStalenessMs: 0,
+ getStorage: noStorage,
});
+ store.reportObservedBuildId("deployed-1");
+ vi.advanceTimersByTime(100_000);
+ store.reportObservedBuildId("deployed-2");
+ vi.advanceTimersByTime(79_999);
+ expect(store.getSnapshot()).toBe(false);
+ vi.advanceTimersByTime(1); // 180_000 since the first sighting
+ expect(store.getSnapshot()).toBe(true);
+ });
- it("resets for a genuinely new build id (a fresh appearance)", () => {
- const store = createVersionUpdateStore(() => "running", 0);
-
- store.reportObservedBuildId("deployed-1");
- expect(store.markShownReported()).toBe(true);
- expect(store.markShownReported()).toBe(false);
-
- // A new, never-seen build id is a new appearance β†’ report again.
- store.reportObservedBuildId("deployed-2");
- expect(store.markShownReported()).toBe(true);
- expect(store.markShownReported()).toBe(false);
+ it("shows only once the running build has been superseded for 48 h", () => {
+ const storage = createFakeStorage();
+ let now = 0;
+ const store = createVersionUpdateStore(() => "running", {
+ debounceMs: 0,
+ now: () => now,
+ getStorage: () => storage,
});
+ store.reportObservedBuildId("deployed");
+ expect(store.getSnapshot()).toBe(false); // superseded, but not stale yet
+ now = VERSION_UPDATE_MIN_STALENESS_MS - 1;
+ store.reportObservedBuildId("deployed");
+ expect(store.getSnapshot()).toBe(false);
+ now = VERSION_UPDATE_MIN_STALENESS_MS;
+ store.reportObservedBuildId("deployed"); // responses are the clock ticks
+ expect(store.getSnapshot()).toBe(true);
+ });
- it("does not reset when an already-seen build id is re-observed", () => {
- const store = createVersionUpdateStore(() => "running", 0);
-
- store.reportObservedBuildId("deployed");
- expect(store.markShownReported()).toBe(true);
-
- // Re-observing the same (or the running) id is a no-op β€” no new appearance.
- store.reportObservedBuildId("deployed");
- store.reportObservedBuildId("running");
- expect(store.markShownReported()).toBe(false);
+ it("keeps stale-since across a reload of the SAME running build", () => {
+ const storage = createFakeStorage();
+ let now = 0;
+ createVersionUpdateStore(() => "running", {
+ debounceMs: 0,
+ now: () => now,
+ getStorage: () => storage,
+ }).reportObservedBuildId("deployed"); // stale-since recorded at t=0
+
+ now = VERSION_UPDATE_MIN_STALENESS_MS;
+ const reloaded = createVersionUpdateStore(() => "running", {
+ debounceMs: 0,
+ now: () => now,
+ getStorage: () => storage,
});
+ reloaded.reportObservedBuildId("deployed");
+ expect(reloaded.getSnapshot()).toBe(true); // 48 h since the FIRST sighting
});
- // A page loaded mid-deploy sees the new build id immediately; prompting a
- // reload right then reloads into a still-switching pod (LFE-14537). The
- // snapshot must stay false until the settling window elapses.
- describe("new-version debounce (LFE-14537)", () => {
- beforeEach(() => {
- vi.useFakeTimers();
+ it("restarts stale-since when the tab reloads onto a NEW running build", () => {
+ const storage = createFakeStorage();
+ let now = 0;
+ createVersionUpdateStore(() => "build-1", {
+ debounceMs: 0,
+ now: () => now,
+ getStorage: () => storage,
+ }).reportObservedBuildId("build-2"); // { buildId: build-1, ts: 0 }
+
+ now = VERSION_UPDATE_MIN_STALENESS_MS;
+ const after = createVersionUpdateStore(() => "build-2", {
+ debounceMs: 0,
+ now: () => now,
+ getStorage: () => storage,
});
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it("stays hidden until the debounce elapses after the first new build id", () => {
- const store = createVersionUpdateStore(() => "running", 180_000);
-
- store.reportObservedBuildId("deployed");
- // Available, but within the settling window β†’ still not shown.
- expect(store.getSnapshot()).toBe(false);
-
- vi.advanceTimersByTime(179_999);
- expect(store.getSnapshot()).toBe(false);
+ after.reportObservedBuildId("build-3");
+ expect(after.getSnapshot()).toBe(false); // clock restarted for build-2
+ expect(storage.getItem(VERSION_UPDATE_STALE_SINCE_KEY)).toBe(
+ JSON.stringify({ buildId: "build-2", ts: now }),
+ );
+ now = 2 * VERSION_UPDATE_MIN_STALENESS_MS;
+ after.reportObservedBuildId("build-3");
+ expect(after.getSnapshot()).toBe(true);
+ });
- vi.advanceTimersByTime(1);
- expect(store.getSnapshot()).toBe(true);
+ it("throttles a second appearance within 2 h across a reload; never hides a visible banner", () => {
+ const storage = createFakeStorage();
+ let now = 0;
+ const before = createVersionUpdateStore(() => "build-1", {
+ debounceMs: 0,
+ minStalenessMs: 0,
+ now: () => now,
+ getStorage: () => storage,
});
-
- it("notifies subscribers exactly once, when the window elapses (not on detection)", () => {
- const store = createVersionUpdateStore(() => "running", 180_000);
- const listener = vi.fn();
- store.subscribe(listener);
-
- store.reportObservedBuildId("deployed");
- expect(listener).not.toHaveBeenCalled(); // hidden β†’ snapshot unchanged
-
- vi.advanceTimersByTime(180_000);
- expect(listener).toHaveBeenCalledTimes(1);
- expect(store.getSnapshot()).toBe(true);
+ before.reportObservedBuildId("build-2");
+ expect(before.markShownReported()).toBe(true); // actual appearance …
+ expect(storage.getItem(VERSION_UPDATE_LAST_SHOWN_AT_KEY)).toBe("0"); // … recorded
+
+ // The windows gate new appearances only β€” a new build must not hide it.
+ before.reportObservedBuildId("build-2b");
+ expect(before.getSnapshot()).toBe(true);
+
+ // Reload onto build-2; another release lands 30 min later β†’ throttled.
+ now = 30 * 60 * 1000;
+ const after = createVersionUpdateStore(() => "build-2", {
+ debounceMs: 0,
+ minStalenessMs: 0,
+ now: () => now,
+ getStorage: () => storage,
});
+ after.reportObservedBuildId("build-3");
+ expect(after.getSnapshot()).toBe(false);
- it("keys the window to the FIRST sighting β€” a second new build within it does not extend the wait", () => {
- const store = createVersionUpdateStore(() => "running", 180_000);
-
- store.reportObservedBuildId("deployed-1");
- vi.advanceTimersByTime(100_000);
- // A second genuinely-new build mid-window must not re-arm the timer.
- store.reportObservedBuildId("deployed-2");
- vi.advanceTimersByTime(79_999);
- expect(store.getSnapshot()).toBe(false);
+ now = VERSION_UPDATE_SHOW_THROTTLE_MS + 1; // expiry re-allows
+ after.reportObservedBuildId("build-3");
+ expect(after.getSnapshot()).toBe(true);
+ });
- vi.advanceTimersByTime(1); // 180_000 total since the first sighting
- expect(store.getSnapshot()).toBe(true);
+ it("dismiss suppresses even genuinely new builds for 24 h, across reloads", () => {
+ const storage = createFakeStorage();
+ let now = 0;
+ const store = createVersionUpdateStore(() => "running", {
+ debounceMs: 0,
+ minStalenessMs: 0,
+ now: () => now,
+ getStorage: () => storage,
});
+ store.reportObservedBuildId("deployed-1");
+ store.dismiss();
+ expect(storage.getItem(VERSION_UPDATE_SUPPRESSED_UNTIL_KEY)).toBe(
+ String(VERSION_UPDATE_DISMISS_SUPPRESSION_MS),
+ );
- it("re-prompts immediately for a new build once the window has already passed", () => {
- const store = createVersionUpdateStore(() => "running", 180_000);
-
- store.reportObservedBuildId("deployed-1");
- vi.advanceTimersByTime(180_000);
- expect(store.getSnapshot()).toBe(true);
-
- store.dismiss();
- expect(store.getSnapshot()).toBe(false);
+ now = 3 * 60 * 60 * 1000; // inside the window: even a new build stays quiet
+ store.reportObservedBuildId("deployed-2");
+ expect(store.getSnapshot()).toBe(false);
- // The settling window is already satisfied β†’ a later new build shows at once.
- store.reportObservedBuildId("deployed-2");
- expect(store.getSnapshot()).toBe(true);
+ const reloaded = createVersionUpdateStore(() => "running", {
+ debounceMs: 0,
+ minStalenessMs: 0,
+ now: () => now,
+ getStorage: () => storage,
});
+ reloaded.reportObservedBuildId("deployed-2");
+ expect(reloaded.getSnapshot()).toBe(false);
- it("arms no timer when only the running build id is observed", () => {
- const store = createVersionUpdateStore(() => "running", 180_000);
+ now = VERSION_UPDATE_DISMISS_SUPPRESSION_MS + 1; // expiry re-allows
+ store.reportObservedBuildId("deployed-2");
+ expect(store.getSnapshot()).toBe(true);
+ });
- store.reportObservedBuildId("running"); // matches β†’ no new-version signal
- vi.advanceTimersByTime(180_000);
- expect(store.getSnapshot()).toBe(false);
+ it("degrades to in-memory behavior on throwing storage; future-dated stamps are ignored", () => {
+ const throwing = {
+ getItem: () => {
+ throw new Error("denied");
+ },
+ setItem: () => {
+ throw new Error("denied");
+ },
+ };
+ const store = createVersionUpdateStore(() => "running", {
+ debounceMs: 0,
+ minStalenessMs: 0,
+ now: () => 0,
+ getStorage: () => throwing,
});
+ store.reportObservedBuildId("deployed-1");
+ expect(store.getSnapshot()).toBe(true); // read errors don't block showing
+ expect(store.markShownReported()).toBe(true); // write error swallowed
+ store.dismiss();
+ expect(store.getSnapshot()).toBe(false);
+ store.reportObservedBuildId("deployed-2"); // in-memory: new build re-prompts
+ expect(store.getSnapshot()).toBe(true);
- it("defaults the debounce window to three minutes", () => {
- expect(VERSION_UPDATE_DEBOUNCE_MS).toBe(3 * 60 * 1000);
-
- const store = createVersionUpdateStore(() => "running");
- store.reportObservedBuildId("deployed");
- vi.advanceTimersByTime(VERSION_UPDATE_DEBOUNCE_MS - 1);
- expect(store.getSnapshot()).toBe(false);
- vi.advanceTimersByTime(1);
- expect(store.getSnapshot()).toBe(true);
+ // Clock skew: a last-shown-at ahead of now must be ignored, not clamped β€”
+ // a clamp floats with now and would suppress until the clock caught up.
+ const skewed = createFakeStorage();
+ skewed.setItem(
+ VERSION_UPDATE_LAST_SHOWN_AT_KEY,
+ String(5 * 60 * 60 * 1000),
+ );
+ const skewStore = createVersionUpdateStore(() => "running", {
+ debounceMs: 0,
+ minStalenessMs: 0,
+ now: () => 1_000,
+ getStorage: () => skewed,
});
+ skewStore.reportObservedBuildId("deployed");
+ expect(skewStore.getSnapshot()).toBe(true);
});
});
diff --git a/web/src/features/version-update/versionUpdateStore.ts b/web/src/features/version-update/versionUpdateStore.ts
index d3dab07a6a..87c50d23a1 100644
--- a/web/src/features/version-update/versionUpdateStore.ts
+++ b/web/src/features/version-update/versionUpdateStore.ts
@@ -1,33 +1,14 @@
/**
- * External store tracking whether a newer app build has been deployed while the
- * current tab stayed open.
- *
- * Frequent deploys + long-lived tabs leave a tab running a stale JS bundle,
- * which then 404s on code-split chunks and mints stale-fingerprint Sentry noise
- * (LFE-10978, Β§4.9). This store powers a persistent "reload to update" banner so
- * the user can refresh on their own terms β€” we NEVER auto-reload (that would
- * throw away unsaved work: open annotations, editors, ...).
- *
- * It is fed imperatively from the tRPC `buildIdLink` (see `src/utils/api.ts`),
- * which captures the `x-build-id` response header on every tRPC response. React
- * reads it via {@link useVersionUpdateAvailable} (a `useSyncExternalStore` hook)
- * β€” no polling, no effect-driven state sync.
- *
- * New-version debounce (LFE-14537): a page loaded while the web container is
- * mid-deploy can see the new build id immediately, and prompting a reload right
- * then reloads the tab into the still-switching pod (a broken loading state). So
- * "update available" only flips the snapshot to `true` once at least
- * {@link VERSION_UPDATE_DEBOUNCE_MS} has elapsed since the FIRST new build id was
- * seen β€” a settling window for the deploy to finish. This gate is combined at the
- * banner with a post-load grace (see `useAppSettled`); both must pass.
+ * External store behind the "reload to update" banner (LFE-10978): long-lived
+ * tabs on a superseded bundle 404 on code-split chunks, so we offer (never
+ * force) a reload. Fed by the tRPC `buildIdLink` (`x-build-id` header on every
+ * response); read via `useSyncExternalStore`. Gate chain (LFE-14537, LFE-14765):
+ * superseded β‰₯ 48 h β†’ 3 min deploy debounce β†’ not shown in the last 2 h β†’ not
+ * dismissed in the last 24 h. Windows persist in localStorage (shared across
+ * tabs/reloads) and degrade to in-memory behavior without storage.
*/
-/**
- * True only when both build ids are present and they differ. When either id is
- * missing we cannot conclude anything (a self-hosted build without
- * `NEXT_PUBLIC_BUILD_ID`, or a response that carried no `x-build-id`), so we
- * stay silent rather than nag on a false positive.
- */
+/** True only when both build ids are known and differ; unknown ids prove nothing. */
export function isVersionMismatch(
runningBuildId: string | null | undefined,
observedBuildId: string | null | undefined,
@@ -37,117 +18,176 @@ export function isVersionMismatch(
);
}
-/**
- * How long after the FIRST new build id is observed before the banner is allowed
- * to appear β€” a debounce so a deploy that's still switching pods doesn't
- * immediately prompt a reload into a half-deployed state (LFE-14537). Keyed on
- * the first sighting, not re-armed per response, so it can't be starved by a
- * rolling deploy re-serving build ids.
- */
+/** Settling window after the FIRST differing build id, so we don't prompt a reload into a mid-rollout deploy (LFE-14537). */
export const VERSION_UPDATE_DEBOUNCE_MS = 3 * 60 * 1000;
+/** At most one banner appearance per window, across tabs and reloads. */
+export const VERSION_UPDATE_SHOW_THROTTLE_MS = 2 * 60 * 60 * 1000;
+
+/** An explicit dismiss silences the banner this long, even for new build ids. */
+export const VERSION_UPDATE_DISMISS_SUPPRESSION_MS = 24 * 60 * 60 * 1000;
+
+/** The running build must have been superseded this long before any prompt. */
+export const VERSION_UPDATE_MIN_STALENESS_MS = 48 * 60 * 60 * 1000;
+
+/** localStorage key: epoch ms of the banner's last actual appearance. */
+export const VERSION_UPDATE_LAST_SHOWN_AT_KEY = "version-update-last-shown-at";
+/** localStorage key: epoch ms until which a dismiss suppresses the banner. */
+export const VERSION_UPDATE_SUPPRESSED_UNTIL_KEY =
+ "version-update-suppressed-until";
+/** localStorage key: JSON `{ buildId, ts }` β€” when the running build was first seen superseded (single overwritten entry). */
+export const VERSION_UPDATE_STALE_SINCE_KEY = "version-update-stale-since";
+
export type VersionUpdateStore = {
- /** Subscribe to snapshot changes (for `useSyncExternalStore`). */
+ /** Subscribe to snapshot changes (`useSyncExternalStore`). */
subscribe: (listener: () => void) => () => void;
- /**
- * Current snapshot: is an update available, not yet dismissed, AND has the
- * new-version debounce ({@link VERSION_UPDATE_DEBOUNCE_MS}) elapsed?
- */
+ /** Should the banner render right now? */
getSnapshot: () => boolean;
- /** SSR snapshot β€” always `false`; the mismatch only exists in a live tab. */
+ /** Always false β€” the mismatch only exists in a live tab. */
getServerSnapshot: () => boolean;
- /**
- * Record a build id observed from a server response. Safe to call on every
- * tRPC response with any value. Once a build id different from the running one
- * has been seen, "update available" is STICKY β€” later responses (including an
- * old pod still serving the running build during a rolling deploy) can never
- * clear it.
- */
+ /** Feed a build id from a server response; safe on every response, any value. */
reportObservedBuildId: (observedBuildId: string | null | undefined) => void;
- /**
- * Dismiss the banner for the current session. It re-shows only when a build id
- * that has NOT been seen before arrives β€” never on a re-observation of an
- * already-seen build (an old pod during a rolling deploy).
- */
+ /** Hide until a never-seen build id arrives; persists the 24 h suppression. */
dismiss: () => void;
/**
- * Returns `true` exactly once per appearance, `false` afterwards; the flag
- * resets when a genuinely new build id arrives (a fresh appearance). Kept in
- * the store β€” not in component state β€” so the `banner_shown` analytics event
- * fires once per logical appearance even if the banner component unmounts and
- * remounts in between (e.g. AppLayout switching between AuthenticatedLayout
- * and MinimalLayout), and once (not twice) under a StrictMode double-invoked
- * effect.
+ * True exactly once per appearance β€” store-held so remounts/StrictMode can't
+ * double-fire `banner_shown`. A `true` also records the show-throttle stamp.
*/
markShownReported: () => boolean;
};
+/** Injection points for deterministic tests; the app singleton uses the defaults. */
+export type VersionUpdateStoreOptions = {
+ /** Settling window; ≀ 0 elapses synchronously (no timer). */
+ debounceMs?: number;
+ /** Required supersession age before the banner may appear; ≀ 0 disables. */
+ minStalenessMs?: number;
+ now?: () => number;
+ /** Lazy (SSR-safe); may return undefined or throw β€” every access is guarded. */
+ getStorage?: () => Pick<Storage, "getItem" | "setItem"> | undefined;
+};
+
/**
- * Builds a version-update store. `getRunningBuildId` returns the build id of the
- * bundle this tab is running; injecting it (rather than reading the module-level
- * env directly) keeps the store deterministic and testable.
- *
- * Rolling-deploy correctness: during a rollout, one tab sees responses from
- * BOTH the old and new pods, in any order, and build ids are opaque hashes with
- * no orderable "newer/older". So the store cannot ask "is the observed build
- * newer?" β€” it asks only "have we ever seen a build id β‰  ours?". That makes the
- * signal:
- * - **sticky** β€” a subsequent old-pod response carrying the running build id
- * cannot flip the banner back off; and
- * - **flap-free** β€” re-observing an already-seen build id does nothing, so the
- * banner does not blink or reopen as responses alternate between pods.
- * Reloading always converges the tab to whatever build is currently served, so
- * "a build β‰  yours exists β†’ offer reload" is the right action even though we
- * can't prove the other build is strictly newer.
- *
- * `debounceMs` is the new-version settling window (default
- * {@link VERSION_UPDATE_DEBOUNCE_MS}); injected for deterministic testing. A
- * value ≀ 0 disables the debounce (the update shows as soon as it is available)
- * and stays synchronous β€” no timer β€” which keeps the detection/stickiness tests
- * free of fake timers.
+ * Build ids are opaque and unorderable, so "update available" is simply "ever
+ * saw a build id β‰  ours" β€” sticky and flap-free while rolling-deploy pods serve
+ * mixed responses; reloading converges the tab to whatever is currently served.
*/
export function createVersionUpdateStore(
getRunningBuildId: () => string | null | undefined,
- debounceMs: number = VERSION_UPDATE_DEBOUNCE_MS,
+ {
+ debounceMs = VERSION_UPDATE_DEBOUNCE_MS,
+ minStalenessMs = VERSION_UPDATE_MIN_STALENESS_MS,
+ now = () => Date.now(),
+ getStorage = () =>
+ typeof window === "undefined" ? undefined : window.localStorage,
+ }: VersionUpdateStoreOptions = {},
): VersionUpdateStore {
const listeners = new Set<() => void>();
- // Every build id observed that differs from the running one. Membership is
- // what makes re-observation a no-op (no flapping) and dismiss durable.
+ // Membership makes re-observation a no-op (no flapping, no dismiss reopen).
const seenDifferingBuildIds = new Set<string>();
- // Sticky: set true the first time a differing build id is seen, never unset.
- let updateAvailable = false;
+ let updateAvailable = false; // sticky
let dismissed = false;
- // `banner_shown` analytics guard β€” true once the current appearance has been
- // reported. Reset when a genuinely new build id arrives (new appearance).
+ // `banner_shown` once-guard; reset when a genuinely new build id arrives.
let shownReported = false;
- // New-version debounce (LFE-14537). `debounceStarted` guards the one-shot
- // timer so it is armed exactly once β€” on the FIRST new build id, keyed to that
- // sighting (never re-armed by later responses, so a rolling deploy can't
- // starve it). `debounceElapsed` is sticky: once the window passes the update
- // is eligible forever, and a later genuinely-new build re-prompts immediately.
+ // One-shot, keyed to the FIRST new build id; `debounceElapsed` stays true.
let debounceStarted = false;
let debounceElapsed = false;
+ // First-superseded-at for the running build; resolved once, then in-memory.
+ let staleSince: number | null = null;
- const compute = (): boolean =>
+ // Storage may be absent or throw: failed reads β†’ null, writes are dropped.
+ const readTimestamp = (key: string): number | null => {
+ try {
+ const raw = getStorage()?.getItem(key);
+ if (!raw) return null;
+ const parsed = Number(raw);
+ return Number.isFinite(parsed) ? parsed : null;
+ } catch {
+ return null;
+ }
+ };
+ const writeTimestamp = (key: string, value: number) => {
+ try {
+ getStorage()?.setItem(key, String(value));
+ } catch {
+ // best-effort; in-memory gates still apply
+ }
+ };
+
+ // Adopt a persisted stale-since for the SAME running build; otherwise (other
+ // build, future-dated ts, garbage) restart at now and overwrite the entry.
+ const resolveStaleSince = (): number => {
+ const t = now();
+ const runningBuildId = getRunningBuildId();
+ try {
+ const raw = getStorage()?.getItem(VERSION_UPDATE_STALE_SINCE_KEY);
+ if (raw) {
+ const parsed = JSON.parse(raw) as { buildId?: unknown; ts?: unknown };
+ if (
+ parsed &&
+ parsed.buildId === runningBuildId &&
+ typeof parsed.ts === "number" &&
+ Number.isFinite(parsed.ts) &&
+ parsed.ts <= t
+ ) {
+ return parsed.ts;
+ }
+ }
+ } catch {
+ // unreadable β†’ treat as absent
+ }
+ try {
+ getStorage()?.setItem(
+ VERSION_UPDATE_STALE_SINCE_KEY,
+ JSON.stringify({ buildId: runningBuildId, ts: t }),
+ );
+ } catch {
+ // best-effort; in-memory value still applies
+ }
+ return t;
+ };
+
+ const isStaleEnough = (): boolean =>
+ staleSince !== null && now() - staleSince >= minStalenessMs;
+
+ // Future-dated stamps are ignored, not clamped β€” a clamp floats with `now`
+ // and would suppress until the wall clock caught up.
+ const isSuppressed = (): boolean => {
+ const t = now();
+ const lastShownAt = readTimestamp(VERSION_UPDATE_LAST_SHOWN_AT_KEY);
+ if (
+ lastShownAt !== null &&
+ lastShownAt <= t &&
+ t < lastShownAt + VERSION_UPDATE_SHOW_THROTTLE_MS
+ ) {
+ return true;
+ }
+ const suppressedUntil = readTimestamp(VERSION_UPDATE_SUPPRESSED_UNTIL_KEY);
+ return (
+ suppressedUntil !== null &&
+ t < suppressedUntil &&
+ // A valid write is at most one dismiss window ahead of now.
+ suppressedUntil <= t + VERSION_UPDATE_DISMISS_SUPPRESSION_MS
+ );
+ };
+
+ const computeEligible = (): boolean =>
updateAvailable && !dismissed && debounceElapsed;
- // Cache the snapshot so `getSnapshot` returns a referentially stable value
- // between changes β€” `useSyncExternalStore` requires this to avoid re-render
- // loops (it compares snapshots with `Object.is`).
- let snapshot = compute();
+ // Cached: `useSyncExternalStore` needs a referentially stable snapshot.
+ let snapshot = false;
const emitChange = () => {
- const next = compute();
+ // Staleness/suppression gate the hidden→shown transition only — a banner
+ // already on screen is never hidden by them.
+ const next =
+ computeEligible() && (snapshot || (isStaleEnough() && !isSuppressed()));
if (next === snapshot) return;
snapshot = next;
for (const listener of listeners) listener();
};
- // Arm the new-version debounce once, on the first new build id. When it
- // elapses the update becomes eligible; the timer emits so a tab that has been
- // sitting on a settling deploy re-renders the banner in without any further
- // response. A non-positive window elapses synchronously (no timer left
- // running). One-shot and self-completing β€” nothing to clean up.
+ // Armed once, on the first new build id; ≀ 0 elapses synchronously.
const startDebounce = () => {
if (debounceStarted) return;
debounceStarted = true;
@@ -175,40 +215,40 @@ export function createVersionUpdateStore(
return false;
},
reportObservedBuildId(observedBuildId) {
- if (!observedBuildId) return;
- if (!isVersionMismatch(getRunningBuildId(), observedBuildId)) return;
- // A differing build id. If we've already seen this exact one, do nothing β€”
- // re-observation (old pod re-serving it) must not flap or reopen a dismiss.
- if (seenDifferingBuildIds.has(observedBuildId)) return;
- seenDifferingBuildIds.add(observedBuildId);
- updateAvailable = true; // sticky
- // A genuinely new (never-seen) differing build β†’ worth re-prompting even
- // if the user dismissed an earlier one, and worth counting as a fresh
- // appearance for analytics.
- dismissed = false;
- shownReported = false;
- // Arm the settling window on the first new build; a no-op on later ones
- // (the debounce is keyed to the first sighting, not re-armed per build).
- startDebounce();
+ if (
+ observedBuildId &&
+ isVersionMismatch(getRunningBuildId(), observedBuildId) &&
+ !seenDifferingBuildIds.has(observedBuildId) // re-observation = no-op
+ ) {
+ seenDifferingBuildIds.add(observedBuildId);
+ updateAvailable = true;
+ if (staleSince === null) staleSince = resolveStaleSince();
+ // A never-seen build is a fresh appearance: undo dismiss, re-arm analytics.
+ dismissed = false;
+ shownReported = false;
+ startDebounce();
+ }
+ // Responses are the clock ticks that mature staleness / expire windows.
emitChange();
},
dismiss() {
dismissed = true;
+ writeTimestamp(
+ VERSION_UPDATE_SUPPRESSED_UNTIL_KEY,
+ now() + VERSION_UPDATE_DISMISS_SUPPRESSION_MS,
+ );
emitChange();
},
markShownReported() {
if (shownReported) return false;
shownReported = true;
+ writeTimestamp(VERSION_UPDATE_LAST_SHOWN_AT_KEY, now()); // arm the throttle
return true;
},
};
}
-/**
- * App-wide singleton, wired to the running build id. `NEXT_PUBLIC_BUILD_ID` is
- * inlined into the client bundle at build time, so this reflects the exact
- * bundle the tab loaded.
- */
+/** App singleton; `NEXT_PUBLIC_BUILD_ID` is inlined at build time. */
export const versionUpdateStore = createVersionUpdateStore(
() => process.env.NEXT_PUBLIC_BUILD_ID,
);