πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(web): banner to prompt reload on a new deploy (LFE-10978) (#15279)
Nikita Kabardine584d9bc8a22
diff --git a/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsx b/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsxindex 4f083d6a5d..934266a3da 100644--- a/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsx+++ b/web/src/components/layouts/app-layout/variants/AuthenticatedLayout.tsx@@ -13,6 +13,7 @@ import { SidebarPresenceProvider } from "@/src/components/nav/sidebar-presence";import { Toaster } from "@/src/components/ui/sonner";import { Layer } from "@/src/components/ui/layer";import { TopBannerProvider } from "@/src/features/top-banner";+import { VersionUpdateBanner } from "@/src/features/version-update";import { AppContentWithRightDrawer } from "../right-drawer/AppContentWithRightDrawer";import { ThemeToggle } from "@/src/features/theming/ThemeToggle";import {@@ -173,6 +174,7 @@ export function AuthenticatedLayout({<SidebarProvider><div className="flex h-dvh w-full flex-col"><PaymentBanner />+ <VersionUpdateBanner /><div className="pt-banner-offset flex min-h-0 flex-1"><AppSidebarnavItems={navigation.mainNavigation}diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.tsindex a619a8d4da..c843b0ff20 100644--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts@@ -232,6 +232,10 @@ export const events = {"compare_run_added","compare_run_removed",],+ // Version-update reload notification (LFE-10978). `banner_shown` fires once+ // per appearance; the two actions measure the reload-vs-dismiss split. No+ // props carry user content.+ version_update: ["banner_shown", "reload_clicked", "dismissed"],notification: ["click_link", "dismiss_notification"],toast: ["report_issue", "dismiss"],tag: [diff --git a/web/src/features/version-update/VersionUpdateBanner.clienttest.tsx b/web/src/features/version-update/VersionUpdateBanner.clienttest.tsxnew file mode 100644index 0000000000..a839ad9bc3--- /dev/null+++ b/web/src/features/version-update/VersionUpdateBanner.clienttest.tsx@@ -0,0 +1,130 @@+import { render, screen, fireEvent } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { VersionUpdateBanner } from "./VersionUpdateBanner";+import { VersionUpdateBannerView } from "./VersionUpdateBannerView";++// Shared mutable mock state (hoisted above the vi.mock factories).+const h = vi.hoisted(() => ({+ capture: vi.fn(),+ dismiss: vi.fn(),+ markShownReported: vi.fn(() => true),+ available: true,+ settled: true,+}));++// The connected banner portals into the top-most overlay layer, whose DOM+// container only exists via _document.tsx; render children inline for the test.+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("./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();+ });++ it("invokes the callbacks when the controls are clicked", () => {+ const onReload = vi.fn();+ const onDismiss = vi.fn();+ render(+ <VersionUpdateBannerView onReload={onReload} onDismiss={onDismiss} />,+ );++ 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", () => {+ 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",+ ),+ ).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", () => {+ h.settled = false;+ render(<VersionUpdateBanner />);+ expect(+ screen.queryByRole("button", { name: "Reload" }),+ ).not.toBeInTheDocument();+ expect(h.capture).not.toHaveBeenCalled();+ expect(h.markShownReported).not.toHaveBeenCalled();+ });++ it("renders nothing when no update is available", () => {+ h.available = false;+ render(<VersionUpdateBanner />);+ expect(+ screen.queryByRole("button", { name: "Reload" }),+ ).not.toBeInTheDocument();+ expect(h.capture).not.toHaveBeenCalled();+ });++ it("captures reload_clicked and reloads on Reload", () => {+ render(<VersionUpdateBanner />);+ fireEvent.click(screen.getByRole("button", { name: "Reload" }));+ expect(h.capture).toHaveBeenCalledWith("version_update:reload_clicked");+ expect(window.location.reload).toHaveBeenCalledTimes(1);+ });++ it("captures dismissed and calls the store on Dismiss", () => {+ render(<VersionUpdateBanner />);+ fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));+ expect(h.capture).toHaveBeenCalledWith("version_update:dismissed");+ expect(h.dismiss).toHaveBeenCalledTimes(1);+ });+});diff --git a/web/src/features/version-update/VersionUpdateBanner.tsx b/web/src/features/version-update/VersionUpdateBanner.tsxnew file mode 100644index 0000000000..de7bcd9165--- /dev/null+++ b/web/src/features/version-update/VersionUpdateBanner.tsx@@ -0,0 +1,57 @@+import { useEffect } from "react";+import { Layer } from "@/src/components/ui/layer";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { versionUpdateStore } from "./versionUpdateStore";+import { useVersionUpdateAvailable } from "./useVersionUpdateAvailable";+import { useAppSettled } from "./useAppSettled";+import { VersionUpdateBannerView } from "./VersionUpdateBannerView";++/**+ * App-wide notification prompting the user to reload when a newer build has+ * been deployed while their tab stayed open (LFE-10978, Β§4.9).+ *+ * Visibility is `updateAvailable && appSettled` β both read from module-level+ * external stores via `useSyncExternalStore` (no effect-driven state sync).+ * `updateAvailable` comes from {@link versionUpdateStore} (fed by the tRPC+ * `buildIdLink`); {@link useAppSettled} holds the banner out of the noisy+ * startup window. Keeping both in module scope means the state survives banner+ * remounts (e.g. AppLayout switching between AuthenticatedLayout and+ * MinimalLayout) rather than re-hiding for the grace period each time.+ *+ * Renders into the top-most overlay layer (`toast`) so it floats above content+ * rather than pushing page chrome down. Analytics: `banner_shown` once per+ * appearance, plus the reload / dismiss actions.+ */+export function VersionUpdateBanner() {+ const updateAvailable = useVersionUpdateAvailable();+ const appSettled = useAppSettled();+ const isVisible = updateAvailable && appSettled;+ const capture = usePostHogClientCapture();++ // Analytics side-effect (external system = PostHog): report `banner_shown`+ // once per appearance. The once-guard lives in the store, so a banner remount+ // cannot double-count one continuous appearance and a StrictMode-double-+ // invoked effect still fires the event only once.+ useEffect(() => {+ if (isVisible && versionUpdateStore.markShownReported()) {+ capture("version_update:banner_shown");+ }+ }, [isVisible, capture]);++ if (!isVisible) return null;++ return (+ <Layer name="toast">+ <VersionUpdateBannerView+ onReload={() => {+ capture("version_update:reload_clicked");+ window.location.reload();+ }}+ onDismiss={() => {+ capture("version_update:dismissed");+ versionUpdateStore.dismiss();+ }}+ />+ </Layer>+ );+}diff --git a/web/src/features/version-update/VersionUpdateBannerView.stories.tsx b/web/src/features/version-update/VersionUpdateBannerView.stories.tsxnew file mode 100644index 0000000000..91d09c1f5e--- /dev/null+++ b/web/src/features/version-update/VersionUpdateBannerView.stories.tsx@@ -0,0 +1,18 @@+import { fn } from "storybook/test";+import preview from "../../../.storybook/preview";+import { VersionUpdateBannerView } from "./VersionUpdateBannerView";++const meta = preview.meta({+ component: VersionUpdateBannerView,+ args: {+ onReload: fn(),+ onDismiss: fn(),+ },+});++/**+ * The banner only exists in its "a new version is available" state β it renders+ * nothing otherwise β so this default IS that state. It pins to the top of the+ * viewport (as in the app) and offers Reload plus a dismiss control.+ */+export const Default = meta.story({});diff --git a/web/src/features/version-update/VersionUpdateBannerView.tsx b/web/src/features/version-update/VersionUpdateBannerView.tsxnew file mode 100644index 0000000000..111b633236--- /dev/null+++ b/web/src/features/version-update/VersionUpdateBannerView.tsx@@ -0,0 +1,74 @@+import { RotateCw, Sparkles, X } from "lucide-react";+import { Button } from "@/src/components/ui/button";+import { cn } from "@/src/utils/tailwind";++export type VersionUpdateBannerViewProps = {+ /** Reload the tab to pick up the new build. */+ onReload: () => void;+ /** Hide the notification for this session. */+ onDismiss: () => void;+ className?: string;+};++/**+ * Presentational "Langfuse just got an update" notification β a floating,+ * frosted-glass pill pinned center-top, NOT a layout-pushing top bar. It sits+ * over page content (the connected banner renders it into the top-most overlay+ * layer), so it may cover whatever is directly behind it; the rest of the app+ * stays interactive (there is no backdrop). It does respect the top-banner+ * offset, so it drops below a full-width top banner (e.g. the payment banner)+ * instead of overlapping it.+ *+ * Purely props-driven (no store/context/data) so it renders in isolation β see+ * `VersionUpdateBannerView.stories.tsx`. The connected {@link VersionUpdateBanner}+ * wires it to the store, the overlay layer, and analytics.+ *+ * We prompt rather than auto-reload: reloading would discard unsaved work (open+ * annotations, editors); the user reloads when it is safe for them.+ */+export function VersionUpdateBannerView({+ onReload,+ onDismiss,+ className,+}: VersionUpdateBannerViewProps) {+ return (+ <div+ role="status"+ aria-live="polite"+ className={cn(+ // `top-banner-offset` = safe-area + any registered top banner's height,+ // so the pill sits below a full-width top banner (e.g. PaymentBanner)+ // rather than overlapping it; `mt-4` keeps a 16px gap (and, with no top+ // banner, places it ~16px from the viewport top).+ "top-banner-offset fixed left-1/2 mt-4 -translate-x-1/2",+ "flex items-center gap-3 rounded-full py-1.5 pr-1.5 pl-4",+ "border-border/60 bg-background/80 border shadow-xl ring-1 ring-black/5 backdrop-blur-xl dark:ring-white/10",+ // `fill-mode-both` holds the entrance keyframes' start state on the+ // mount frame, before the animation's first tick β without it the pill+ // can paint one frame at its final position/opacity and then snap back+ // to animate (a flash that reads as a "jump"; Firefox is most prone).+ "animate-in fade-in-0 slide-in-from-top-4 zoom-in-95 fill-mode-both duration-500 ease-out",+ className,+ )}+ >+ <Sparkles className="text-primary h-4 w-4 shrink-0" />+ <span className="text-foreground text-sm whitespace-nowrap">+ Langfuse just got an update+ </span>+ <Button size="sm" className="rounded-full" onClick={onReload}>+ <RotateCw className="mr-1.5 h-3.5 w-3.5" />+ Reload+ </Button>+ <Button+ size="icon-sm"+ variant="ghost"+ className="text-muted-foreground rounded-full"+ onClick={onDismiss}+ aria-label="Dismiss"+ title="Dismiss"+ >+ <X className="h-4 w-4" />+ </Button>+ </div>+ );+}diff --git a/web/src/features/version-update/index.ts b/web/src/features/version-update/index.tsnew file mode 100644index 0000000000..74b596a562--- /dev/null+++ b/web/src/features/version-update/index.ts@@ -0,0 +1,8 @@+export { VersionUpdateBanner } from "./VersionUpdateBanner";+export { useVersionUpdateAvailable } from "./useVersionUpdateAvailable";+export {+ versionUpdateStore,+ createVersionUpdateStore,+ isVersionMismatch,+ type VersionUpdateStore,+} from "./versionUpdateStore";diff --git a/web/src/features/version-update/useAppSettled.clienttest.ts b/web/src/features/version-update/useAppSettled.clienttest.tsnew file mode 100644index 0000000000..527662d1a5--- /dev/null+++ b/web/src/features/version-update/useAppSettled.clienttest.ts@@ -0,0 +1,76 @@+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { createAppSettledGate } from "./useAppSettled";++describe("createAppSettledGate", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ it("starts unsettled and settles after the delay once subscribed", () => {+ const gate = createAppSettledGate(5000);+ expect(gate.getSnapshot()).toBe(false);++ const listener = vi.fn();+ gate.subscribe(listener);+ expect(gate.getSnapshot()).toBe(false);++ vi.advanceTimersByTime(4999);+ expect(gate.getSnapshot()).toBe(false);+ expect(listener).not.toHaveBeenCalled();++ vi.advanceTimersByTime(1);+ expect(gate.getSnapshot()).toBe(true);+ expect(listener).toHaveBeenCalledTimes(1);+ });++ it("does not start the timer until the first subscription", () => {+ const gate = createAppSettledGate(5000);+ // No subscriber yet β timer never started, so time passing does nothing.+ vi.advanceTimersByTime(10000);+ expect(gate.getSnapshot()).toBe(false);++ gate.subscribe(vi.fn());+ vi.advanceTimersByTime(5000);+ expect(gate.getSnapshot()).toBe(true);+ });++ it("starts the timer once across subscribe/unsubscribe/resubscribe (StrictMode) and remounts", () => {+ const gate = createAppSettledGate(5000);++ // StrictMode mounts, unmounts, remounts synchronously before the timer.+ const unsub = gate.subscribe(vi.fn());+ unsub();+ gate.subscribe(vi.fn());++ vi.advanceTimersByTime(5000);+ expect(gate.getSnapshot()).toBe(true);+ });++ it("reports settled immediately to a subscriber that mounts after settling (remount survives)", () => {+ const gate = createAppSettledGate(5000);+ const first = gate.subscribe(vi.fn());+ vi.advanceTimersByTime(5000);+ expect(gate.getSnapshot()).toBe(true);++ // The component unmounts (e.g. AuthenticatedLayout -> MinimalLayout) and a+ // fresh one mounts later β it must see the already-settled value, not reset.+ first();+ const listener = vi.fn();+ gate.subscribe(listener);+ expect(gate.getSnapshot()).toBe(true);+ // Already settled β no further timer, no extra notification needed.+ vi.advanceTimersByTime(5000);+ expect(listener).not.toHaveBeenCalled();+ });++ it("has a server snapshot that is always false", () => {+ const gate = createAppSettledGate(5000);+ gate.subscribe(vi.fn());+ vi.advanceTimersByTime(5000);+ expect(gate.getSnapshot()).toBe(true);+ expect(gate.getServerSnapshot()).toBe(false);+ });+});diff --git a/web/src/features/version-update/useAppSettled.ts b/web/src/features/version-update/useAppSettled.tsnew file mode 100644index 0000000000..7d1642be65--- /dev/null+++ b/web/src/features/version-update/useAppSettled.ts@@ -0,0 +1,72 @@+import { useSyncExternalStore } from "react";++/**+ * How long after the app first mounts before the version-update banner is+ * allowed to appear. During the initial mount/hydration window the layout+ * flickers and React StrictMode double-invokes mounts; because the banner+ * renders through an overlay portal, a mount landing in that churn is torn down+ * and recreated, replaying its entrance animation (a visible "jump"). Holding it+ * back until the app is quiet means it mounts exactly once, cleanly β and reads+ * better (no banner flashing in during startup).+ */+export const APP_SETTLE_DELAY_MS = 5000;++/**+ * A one-shot "the app has settled after first render" gate as an external store.+ *+ * It is module-scoped (a singleton below), NOT component state, so the settled+ * flag survives banner unmount/remount β e.g. when `AppLayout` switches between+ * `AuthenticatedLayout` and `MinimalLayout` (navigating to `/onboarding`,+ * `/auth/*`, `/public/*` and back). A component-local timer would restart the+ * grace period on every such remount, re-hiding an already-acknowledged banner+ * for another {@link APP_SETTLE_DELAY_MS}. Once settled it stays settled, so+ * later mounts see `true` immediately.+ *+ * Exposed as a factory for deterministic testing; the app uses the singleton.+ */+export function createAppSettledGate(delayMs = APP_SETTLE_DELAY_MS) {+ let settled = false;+ let timerStarted = false;+ const listeners = new Set<() => void>();++ // The timer is the external system this store owns. Start it once, on first+ // subscription (the app's first client mount); it is idempotent across the+ // StrictMode subscribe/unsubscribe/subscribe cycle and across remounts.+ const startTimer = () => {+ if (timerStarted || settled) return;+ timerStarted = true;+ setTimeout(() => {+ settled = true;+ for (const listener of listeners) listener();+ }, delayMs);+ };++ return {+ subscribe(listener: () => void) {+ startTimer();+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ getSnapshot: () => settled,+ // Never settled on the server; the banner only exists in a live tab.+ getServerSnapshot: () => false,+ };+}++const appSettledGate = createAppSettledGate();++/**+ * `true` once the app has settled after first render (see+ * {@link createAppSettledGate}). Read via `useSyncExternalStore` β no+ * effect-driven state, and the value is shared across all consumers and+ * survives component remounts.+ */+export function useAppSettled(): boolean {+ return useSyncExternalStore(+ appSettledGate.subscribe,+ appSettledGate.getSnapshot,+ appSettledGate.getServerSnapshot,+ );+}diff --git a/web/src/features/version-update/useVersionUpdateAvailable.ts b/web/src/features/version-update/useVersionUpdateAvailable.tsnew file mode 100644index 0000000000..6105db9f9c--- /dev/null+++ b/web/src/features/version-update/useVersionUpdateAvailable.ts@@ -0,0 +1,15 @@+import { useSyncExternalStore } from "react";+import { versionUpdateStore } from "./versionUpdateStore";++/**+ * `true` when a newer app build has been deployed while this tab stayed open and+ * the user has not dismissed the prompt for it. Reads the module-level+ * {@link versionUpdateStore} via `useSyncExternalStore` β no effect, no polling.+ */+export function useVersionUpdateAvailable(): boolean {+ return useSyncExternalStore(+ versionUpdateStore.subscribe,+ versionUpdateStore.getSnapshot,+ versionUpdateStore.getServerSnapshot,+ );+}diff --git a/web/src/features/version-update/versionUpdateStore.clienttest.ts b/web/src/features/version-update/versionUpdateStore.clienttest.tsnew file mode 100644index 0000000000..69d862727a--- /dev/null+++ b/web/src/features/version-update/versionUpdateStore.clienttest.ts@@ -0,0 +1,194 @@+import { describe, it, expect, vi } from "vitest";+import {+ createVersionUpdateStore,+ isVersionMismatch,+} 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);+ });+});++describe("versionUpdateStore", () => {+ it("starts with no update available", () => {+ const store = createVersionUpdateStore(() => "running");+ expect(store.getSnapshot()).toBe(false);+ });++ it("stays silent when the observed build matches the running build", () => {+ const store = createVersionUpdateStore(() => "running");+ store.reportObservedBuildId("running");+ expect(store.getSnapshot()).toBe(false);+ });++ it("becomes available when a differing build id is observed", () => {+ const store = createVersionUpdateStore(() => "running");+ store.reportObservedBuildId("deployed");+ expect(store.getSnapshot()).toBe(true);+ });++ it("stays silent when the running build id is unknown", () => {+ const store = createVersionUpdateStore(() => undefined);+ store.reportObservedBuildId("deployed");+ expect(store.getSnapshot()).toBe(false);+ });++ it("ignores empty/absent observed build ids", () => {+ const store = createVersionUpdateStore(() => "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");++ 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");+ 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");++ 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");++ 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");+ 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);+ });+ });++ it("notifies subscribers when the snapshot changes and after unsubscribe stops", () => {+ const store = createVersionUpdateStore(() => "running");+ const listener = vi.fn();+ const unsubscribe = store.subscribe(listener);++ store.reportObservedBuildId("deployed");+ expect(listener).toHaveBeenCalledTimes(1);++ // No snapshot change β no extra notification.+ store.reportObservedBuildId("deployed");+ expect(listener).toHaveBeenCalledTimes(1);++ store.dismiss();+ expect(listener).toHaveBeenCalledTimes(2);++ unsubscribe();+ store.reportObservedBuildId("deployed-next");+ expect(listener).toHaveBeenCalledTimes(2);+ });++ it("has a server snapshot that is always false", () => {+ const store = createVersionUpdateStore(() => "running");+ store.reportObservedBuildId("deployed");+ expect(store.getServerSnapshot()).toBe(false);+ });++ // `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");+ 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("resets for a genuinely new build id (a fresh appearance)", () => {+ const store = createVersionUpdateStore(() => "running");++ 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("does not reset when an already-seen build id is re-observed", () => {+ const store = createVersionUpdateStore(() => "running");++ 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);+ });+ });+});diff --git a/web/src/features/version-update/versionUpdateStore.ts b/web/src/features/version-update/versionUpdateStore.tsnew file mode 100644index 0000000000..c5c68f06f7--- /dev/null+++ b/web/src/features/version-update/versionUpdateStore.ts@@ -0,0 +1,158 @@+/**+ * 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.+ */++/**+ * 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.+ */+export function isVersionMismatch(+ runningBuildId: string | null | undefined,+ observedBuildId: string | null | undefined,+): boolean {+ return (+ !!runningBuildId && !!observedBuildId && runningBuildId !== observedBuildId+ );+}++export type VersionUpdateStore = {+ /** Subscribe to snapshot changes (for `useSyncExternalStore`). */+ subscribe: (listener: () => void) => () => void;+ /** Current snapshot: is an update available and not yet dismissed? */+ getSnapshot: () => boolean;+ /** SSR snapshot β 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.+ */+ 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).+ */+ 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.+ */+ markShownReported: () => boolean;+};++/**+ * 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.+ */+export function createVersionUpdateStore(+ getRunningBuildId: () => string | null | undefined,+): 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.+ const seenDifferingBuildIds = new Set<string>();+ // Sticky: set true the first time a differing build id is seen, never unset.+ let updateAvailable = false;+ 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).+ let shownReported = false;++ const compute = (): boolean => updateAvailable && !dismissed;++ // 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();++ const emitChange = () => {+ const next = compute();+ if (next === snapshot) return;+ snapshot = next;+ for (const listener of listeners) listener();+ };++ return {+ subscribe(listener) {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ getSnapshot() {+ return snapshot;+ },+ getServerSnapshot() {+ 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;+ emitChange();+ },+ dismiss() {+ dismissed = true;+ emitChange();+ },+ markShownReported() {+ if (shownReported) return false;+ shownReported = true;+ 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.+ */+export const versionUpdateStore = createVersionUpdateStore(+ () => process.env.NEXT_PUBLIC_BUILD_ID,+);diff --git a/web/src/utils/api.ts b/web/src/utils/api.tsindex 376e1c35e6..2f0b238d0b 100644--- a/web/src/utils/api.ts+++ b/web/src/utils/api.ts@@ -24,6 +24,7 @@ import { observable } from "@trpc/server/observable";import superjson from "superjson";import { env } from "@/src/env.mjs";import { showVersionUpdateToast } from "@/src/features/notifications/showVersionUpdateToast";+import { versionUpdateStore } from "@/src/features/version-update/versionUpdateStore";import { type AppRouter } from "@/src/server/api/root";import { setUpSuperjson } from "@/src/utils/superjson";import { trpcErrorToast } from "@/src/utils/trpcErrorToast";@@ -276,22 +277,33 @@ const handleTrpcError = (error: unknown, shouldSilenceError = false) => {}};-// onError update build id to compare versions+// Reads the `x-build-id` response header (the build id serving this response)+// and records it: the module-level `buildId` still drives the legacy+// stale-cache toast, and the version-update store drives the persistent reload+// banner (see src/features/version-update). Called on EVERY response β success+// and error β so a mismatch is detected on the first response after a deploy,+// not only when a stale chunk 404s.+const captureBuildId = (response: unknown) => {+ if (!(response instanceof Response)) return;+ const observed = response.headers.get("x-build-id");+ if (!observed) return;+ buildId = observed;+ versionUpdateStore.reportObservedBuildId(observed);+};++// Track the build id serving tRPC responses to compare against the running one.const buildIdLink = (): TRPCLink<AppRouter> => () => {return ({ next, op }) => {return observable((observer) => {const unsubscribe = next(op).subscribe({next(value) {+ captureBuildId(value.context?.response);observer.next(value);},error(err) {- if (- err.meta &&- err.meta.response &&- err.meta.response instanceof Response- ) {- buildId = err.meta.response.headers.get("x-build-id");- }+ captureBuildId(+ err.meta && err.meta.response ? err.meta.response : undefined,+ );observer.error(err);},complete() {