Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(frontend): stop reporting an error when Web Storage is unavailable (#14719)

Bently0a18a845b22d
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/storage-unavailable.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/storage-unavailable.test.tsx
new file mode 100644
index 0000000000..86954adc9e
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/signup/__tests__/storage-unavailable.test.tsx
@@ -0,0 +1,95 @@
+import { render, screen } from "@/tests/integrations/test-utils";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import type { ReactNode } from "react";
+
+const captureException = vi.hoisted(() => vi.fn());
+const isServerSide = vi.hoisted(() => vi.fn(() => false));
+const mockUseAuth = vi.hoisted(() => vi.fn());
+
+vi.mock("@sentry/nextjs", () => ({ captureException }));
+
+vi.mock("@/services/environment", async (importOriginal) => {
+ const actual =
+ await importOriginal<typeof import("@/services/environment")>();
+ return { ...actual, environment: { ...actual.environment, isServerSide } };
+});
+
+vi.mock("@/providers/onboarding/onboarding-provider", () => ({
+ default: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+vi.mock("@/lib/auth/hooks/useAuth", () => ({ useAuth: mockUseAuth }));
+
+vi.mock("../actions", () => ({ signup: vi.fn() }));
+
+/**
+ * `/signup` is one of the three routes the "Local storage is not available"
+ * errors were filed against. The storage read comes from `OrgTeamProvider`,
+ * which `src/app/providers.tsx` wraps every route in.
+ */
+describe("/signup when localStorage is unavailable", () => {
+ const originalLocalStorage = Object.getOwnPropertyDescriptor(
+ window,
+ "localStorage",
+ );
+
+ beforeEach(() => {
+ vi.resetModules();
+ captureException.mockClear();
+ isServerSide.mockReturnValue(false);
+ mockUseAuth.mockReturnValue({
+ user: null,
+ isUserLoading: false,
+ isLoggedIn: false,
+ });
+ });
+
+ afterEach(() => {
+ if (originalLocalStorage) {
+ Object.defineProperty(window, "localStorage", originalLocalStorage);
+ }
+ });
+
+ test("server-rendering the route reports nothing to Sentry", async () => {
+ isServerSide.mockReturnValue(true);
+ const { renderToString } = await import("react-dom/server");
+ const { default: OrgTeamProvider } = await import(
+ "@/providers/org-team/OrgTeamProvider"
+ );
+ const { default: SignupPage } = await import("../page");
+
+ const html = renderToString(
+ <OrgTeamProvider>
+ <SignupPage />
+ </OrgTeamProvider>,
+ );
+
+ // /signup server-renders its loading shell until auth initialises in an
+ // effect (#14281); the marketing panel is in both states.
+ expect(html).toContain("Run in minutes");
+ expect(captureException).not.toHaveBeenCalled();
+ }, 20_000);
+
+ test("renders in a browser that blocks storage, reporting nothing", async () => {
+ Object.defineProperty(window, "localStorage", {
+ get() {
+ throw new Error("The operation is insecure.");
+ },
+ configurable: true,
+ });
+ const { default: OrgTeamProvider } = await import(
+ "@/providers/org-team/OrgTeamProvider"
+ );
+ const { default: SignupPage } = await import("../page");
+
+ render(
+ <OrgTeamProvider>
+ <SignupPage />
+ </OrgTeamProvider>,
+ );
+
+ expect(await screen.findByLabelText("Email")).toBeDefined();
+ expect(screen.getByRole("button", { name: "Sign up" })).toBeDefined();
+ expect(captureException).not.toHaveBeenCalled();
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/org-team/__tests__/store-storage-unavailable.test.ts b/autogpt_platform/frontend/src/services/org-team/__tests__/store-storage-unavailable.test.ts
new file mode 100644
index 0000000000..2bf1b5dd21
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/org-team/__tests__/store-storage-unavailable.test.ts
@@ -0,0 +1,59 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const captureException = vi.hoisted(() => vi.fn());
+const isServerSide = vi.hoisted(() => vi.fn(() => false));
+
+vi.mock("@sentry/nextjs", () => ({ captureException }));
+vi.mock("@/services/environment", () => ({ environment: { isServerSide } }));
+
+/**
+ * `OrgTeamProvider` sits in `src/app/providers.tsx`, so every route pulls this
+ * store in and zustand runs its initialiser — which reads localStorage — while
+ * the module is evaluated. That happens during server rendering too, and it is
+ * where the "Local storage is not available" flood came from.
+ */
+describe("useOrgTeamStore when storage is unavailable", () => {
+ beforeEach(() => {
+ vi.resetModules();
+ captureException.mockClear();
+ isServerSide.mockReturnValue(false);
+ window.localStorage.clear();
+ });
+
+ it("initialises during server rendering without reporting an error", async () => {
+ isServerSide.mockReturnValue(true);
+
+ const { useOrgTeamStore } = await import("../store");
+
+ const state = useOrgTeamStore.getState();
+ expect(state.activeOrgID).toBeNull();
+ expect(state.activeTeamID).toBeNull();
+ expect(captureException).not.toHaveBeenCalled();
+ });
+
+ it("initialises in a browser that blocks storage without reporting an error", async () => {
+ const original = Object.getOwnPropertyDescriptor(window, "localStorage");
+ Object.defineProperty(window, "localStorage", {
+ get() {
+ throw new Error("The operation is insecure.");
+ },
+ configurable: true,
+ });
+
+ try {
+ const { useOrgTeamStore } = await import("../store");
+
+ expect(useOrgTeamStore.getState().activeOrgID).toBeNull();
+
+ // Switching org still works, it just does not outlive the tab.
+ useOrgTeamStore.getState().setActiveOrg("org-1");
+ expect(useOrgTeamStore.getState().activeOrgID).toBe("org-1");
+
+ useOrgTeamStore.getState().clearContext();
+ expect(useOrgTeamStore.getState().activeOrgID).toBeNull();
+ expect(captureException).not.toHaveBeenCalled();
+ } finally {
+ if (original) Object.defineProperty(window, "localStorage", original);
+ }
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/storage/__tests__/local-storage.test.ts b/autogpt_platform/frontend/src/services/storage/__tests__/local-storage.test.ts
index a79dcaefa6..4feb0e7da8 100644
--- a/autogpt_platform/frontend/src/services/storage/__tests__/local-storage.test.ts
+++ b/autogpt_platform/frontend/src/services/storage/__tests__/local-storage.test.ts
@@ -41,7 +41,7 @@ describe("storage", () => {
});
describe("null localStorage", () => {
- it("returns undefined for set and clean instead of throwing", () => {
+ it("keeps values in memory instead of throwing", () => {
const original = Object.getOwnPropertyDescriptor(window, "localStorage");
Object.defineProperty(window, "localStorage", {
value: null,
@@ -49,7 +49,9 @@ describe("storage", () => {
});
try {
expect(storage.set(Key.COPILOT_MODE, "fast")).toBeUndefined();
+ expect(storage.get(Key.COPILOT_MODE)).toBe("fast");
expect(storage.clean(Key.COPILOT_MODE)).toBeUndefined();
+ expect(storage.get(Key.COPILOT_MODE)).toBeNull();
} finally {
if (original) {
Object.defineProperty(window, "localStorage", original);
@@ -84,19 +86,21 @@ describe("storage", () => {
});
describe("server-side guard", () => {
- it("returns undefined for get when on server side", () => {
+ // Every route pulls a module in that reads storage while zustand builds
+ // its store, so this path runs on every server render. It must be silent.
+ it("reads null on the server without reporting to Sentry", () => {
vi.mocked(environment.isServerSide).mockReturnValue(true);
- expect(storage.get(Key.COPILOT_MODE)).toBeUndefined();
- });
- it("returns undefined for set when on server side", () => {
- vi.mocked(environment.isServerSide).mockReturnValue(true);
- expect(storage.set(Key.COPILOT_MODE, "fast")).toBeUndefined();
+ expect(storage.get(Key.COPILOT_MODE)).toBeNull();
+ expect(Sentry.captureException).not.toHaveBeenCalled();
});
- it("returns undefined for clean when on server side", () => {
+ it("drops writes on the server without reporting to Sentry", () => {
vi.mocked(environment.isServerSide).mockReturnValue(true);
+
+ expect(storage.set(Key.COPILOT_MODE, "fast")).toBeUndefined();
expect(storage.clean(Key.COPILOT_MODE)).toBeUndefined();
+ expect(Sentry.captureException).not.toHaveBeenCalled();
});
});
});
diff --git a/autogpt_platform/frontend/src/services/storage/__tests__/safe-storage.test.ts b/autogpt_platform/frontend/src/services/storage/__tests__/safe-storage.test.ts
new file mode 100644
index 0000000000..b6f0207ea9
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/storage/__tests__/safe-storage.test.ts
@@ -0,0 +1,225 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@sentry/nextjs", () => ({
+ captureException: vi.fn(),
+}));
+
+vi.mock("@/services/environment", () => ({
+ environment: {
+ isServerSide: vi.fn(() => false),
+ },
+}));
+
+import * as Sentry from "@sentry/nextjs";
+import { environment } from "@/services/environment";
+import { createSafeStorage } from "../safe-storage";
+
+type TestKey = "a" | "b";
+
+/** Replaces `window.localStorage` for the duration of `run`. Pass a getter that
+ * throws to stand in for a browser that refuses storage outright. */
+function withLocalStorage(value: unknown | (() => never), run: () => void) {
+ const original = Object.getOwnPropertyDescriptor(window, "localStorage");
+ Object.defineProperty(
+ window,
+ "localStorage",
+ typeof value === "function"
+ ? { get: value as () => never, configurable: true }
+ : { value, configurable: true },
+ );
+ try {
+ run();
+ } finally {
+ if (original) Object.defineProperty(window, "localStorage", original);
+ }
+}
+
+describe("createSafeStorage", () => {
+ beforeEach(() => {
+ window.localStorage.clear();
+ window.sessionStorage.clear();
+ vi.mocked(Sentry.captureException).mockClear();
+ vi.mocked(environment.isServerSide).mockReturnValue(false);
+ // The in-memory fallback is module-scoped by design, so drop the keys
+ // this file uses between tests. `clean` reaches it as well as the real
+ // storage.
+ const keys: TestKey[] = ["a", "b"];
+ for (const area of ["local", "session"] as const) {
+ const storage = createSafeStorage<TestKey>(area);
+ keys.forEach((key) => storage.clean(key));
+ }
+ vi.mocked(Sentry.captureException).mockClear();
+ });
+
+ describe("server-side rendering", () => {
+ // The whole point of the fix: rendering a page on the server used to
+ // report "Local storage is not available" to Sentry on every request.
+ it("reads null and reports nothing", () => {
+ vi.mocked(environment.isServerSide).mockReturnValue(true);
+ const storage = createSafeStorage<TestKey>("local");
+
+ expect(storage.get("a")).toBeNull();
+ expect(Sentry.captureException).not.toHaveBeenCalled();
+ });
+
+ it("drops writes and reports nothing", () => {
+ vi.mocked(environment.isServerSide).mockReturnValue(true);
+ const storage = createSafeStorage<TestKey>("local");
+
+ storage.set("a", "1");
+ storage.clean("b");
+
+ expect(Sentry.captureException).not.toHaveBeenCalled();
+ expect(storage.get("a")).toBeNull();
+ });
+
+ it("does not carry a server-side write into the next read", () => {
+ // One node process serves every visitor. If the server kept writes in a
+ // module-scoped map, visitor B would be served visitor A's value.
+ vi.mocked(environment.isServerSide).mockReturnValue(true);
+ const storage = createSafeStorage<TestKey>("local");
+ storage.set("a", "visitor-a");
+
+ expect(createSafeStorage<TestKey>("local").get("a")).toBeNull();
+ });
+ });
+
+ describe("storage blocked by the browser", () => {
+ it("falls back to memory when reading the storage object throws", () => {
+ const storage = createSafeStorage<TestKey>("local");
+
+ withLocalStorage(
+ () => {
+ throw new Error("The operation is insecure.");
+ },
+ () => {
+ storage.set("a", "kept");
+ expect(storage.get("a")).toBe("kept");
+ storage.clean("a");
+ expect(storage.get("a")).toBeNull();
+ },
+ );
+
+ expect(Sentry.captureException).not.toHaveBeenCalled();
+ });
+
+ it("falls back to memory when the storage object is null", () => {
+ const storage = createSafeStorage<TestKey>("local");
+
+ withLocalStorage(null, () => {
+ storage.set("a", "kept");
+ expect(storage.get("a")).toBe("kept");
+ });
+
+ expect(Sentry.captureException).not.toHaveBeenCalled();
+ });
+
+ it("keeps the memory fallback out of the real storage once it comes back", () => {
+ const storage = createSafeStorage<TestKey>("local");
+
+ withLocalStorage(null, () => storage.set("a", "from-memory"));
+
+ expect(window.localStorage.getItem("a")).toBeNull();
+ });
+ });
+
+ describe("working storage", () => {
+ it("round-trips through the real storage", () => {
+ const storage = createSafeStorage<TestKey>("local");
+
+ storage.set("a", "1");
+ expect(window.localStorage.getItem("a")).toBe("1");
+ expect(storage.get("a")).toBe("1");
+
+ storage.clean("a");
+ expect(storage.get("a")).toBeNull();
+ });
+
+ it("keeps the two areas apart", () => {
+ createSafeStorage<TestKey>("local").set("a", "local-value");
+ createSafeStorage<TestKey>("session").set("a", "session-value");
+
+ expect(window.localStorage.getItem("a")).toBe("local-value");
+ expect(window.sessionStorage.getItem("a")).toBe("session-value");
+ });
+
+ it("reports unexpected write failures and still reads the value back", () => {
+ const error = new Error("QuotaExceededError");
+ const storage = createSafeStorage<TestKey>("local");
+ const setItem = vi
+ .spyOn(window.localStorage, "setItem")
+ .mockImplementation(() => {
+ throw error;
+ });
+
+ try {
+ storage.set("a", "too-big");
+ expect(Sentry.captureException).toHaveBeenCalledWith(error);
+ expect(storage.get("a")).toBe("too-big");
+ } finally {
+ setItem.mockRestore();
+ }
+
+ storage.clean("a");
+ expect(storage.get("a")).toBeNull();
+ });
+
+ it("reads back a failed overwrite of a key that already had a value", () => {
+ const storage = createSafeStorage<TestKey>("local");
+ storage.set("a", "persisted");
+
+ const setItem = vi
+ .spyOn(window.localStorage, "setItem")
+ .mockImplementation(() => {
+ throw new Error("QuotaExceededError");
+ });
+ try {
+ storage.set("a", "replacement");
+ // The old native value must not win over the write that just failed.
+ expect(storage.get("a")).toBe("replacement");
+ } finally {
+ setItem.mockRestore();
+ }
+
+ storage.clean("a");
+ expect(storage.get("a")).toBeNull();
+ });
+
+ it("stops the overlay masking the store once a write succeeds again", () => {
+ const storage = createSafeStorage<TestKey>("local");
+ const setItem = vi
+ .spyOn(window.localStorage, "setItem")
+ .mockImplementation(() => {
+ throw new Error("QuotaExceededError");
+ });
+ try {
+ storage.set("a", "only-in-memory");
+ } finally {
+ setItem.mockRestore();
+ }
+ expect(storage.get("a")).toBe("only-in-memory");
+
+ storage.set("a", "persisted");
+
+ expect(storage.get("a")).toBe("persisted");
+ expect(window.localStorage.getItem("a")).toBe("persisted");
+ });
+
+ it("reports unexpected removal failures", () => {
+ const error = new Error("SecurityError");
+ const storage = createSafeStorage<TestKey>("local");
+ const removeItem = vi
+ .spyOn(window.localStorage, "removeItem")
+ .mockImplementation(() => {
+ throw error;
+ });
+
+ try {
+ storage.clean("a");
+ expect(Sentry.captureException).toHaveBeenCalledWith(error);
+ } finally {
+ removeItem.mockRestore();
+ }
+ });
+ });
+});
diff --git a/autogpt_platform/frontend/src/services/storage/local-storage.ts b/autogpt_platform/frontend/src/services/storage/local-storage.ts
index 04fb72a0c3..99dfc108a7 100644
--- a/autogpt_platform/frontend/src/services/storage/local-storage.ts
+++ b/autogpt_platform/frontend/src/services/storage/local-storage.ts
@@ -1,5 +1,4 @@
-import * as Sentry from "@sentry/nextjs";
-import { environment } from "../environment";
+import { createSafeStorage } from "./safe-storage";
export enum Key {
LOGOUT = "supabase-logout",
@@ -33,65 +32,4 @@ export enum Key {
BUILDER_MOBILE_WARNING_SUPPRESSED = "builder-mobile-warning-suppressed",
}
-/** Returns true when localStorage is accessible — false when it is null or when
- * accessing it throws (e.g. cookies/storage blocked by the browser). */
-function hasStorage(): boolean {
- try {
- return window.localStorage !== null;
- } catch {
- return false;
- }
-}
-
-function get(key: Key) {
- if (environment.isServerSide()) {
- Sentry.captureException(new Error("Local storage is not available"));
- return;
- }
- try {
- return window.localStorage.getItem(key);
- } catch {
- // Fine, just return undefined not always items will be set on local storage
- return;
- }
-}
-
-function set(key: Key, value: string) {
- if (environment.isServerSide()) {
- Sentry.captureException(new Error("Local storage is not available"));
- return;
- }
- try {
- return window.localStorage.setItem(key, value);
- } catch (e) {
- // localStorage is null/blocked on some WebViews — silently ignore that case.
- // Any other error (e.g. QuotaExceededError) is unexpected and should be tracked.
- if (hasStorage()) {
- Sentry.captureException(e);
- }
- return;
- }
-}
-
-function clean(key: Key) {
- if (environment.isServerSide()) {
- Sentry.captureException(new Error("Local storage is not available"));
- return;
- }
- try {
- return window.localStorage.removeItem(key);
- } catch (e) {
- // localStorage is null/blocked on some WebViews — silently ignore that case.
- // Any other error is unexpected and should be tracked.
- if (hasStorage()) {
- Sentry.captureException(e);
- }
- return;
- }
-}
-
-export const storage = {
- clean,
- get,
- set,
-};
+export const storage = createSafeStorage<Key>("local");
diff --git a/autogpt_platform/frontend/src/services/storage/safe-storage.ts b/autogpt_platform/frontend/src/services/storage/safe-storage.ts
new file mode 100644
index 0000000000..2b5d4b93c5
--- /dev/null
+++ b/autogpt_platform/frontend/src/services/storage/safe-storage.ts
@@ -0,0 +1,96 @@
+import * as Sentry from "@sentry/nextjs";
+import { environment } from "../environment";
+
+type Area = "local" | "session";
+
+/**
+ * Stand-in used in the browser when the real Web Storage cannot be reached:
+ * private mode, third-party storage blocked, or an embedded WebView. Values
+ * survive for the life of the tab, which is enough for the preferences we
+ * keep here, and nothing throws.
+ *
+ * Deliberately never used server-side. One node process serves every visitor,
+ * so a module-scoped map there would hand one visitor's value to the next one
+ * in their HTML.
+ */
+const memory: Record<Area, Map<string, string>> = {
+ local: new Map(),
+ session: new Map(),
+};
+
+function memoryFor(area: Area): Map<string, string> | null {
+ return environment.isServerSide() ? null : memory[area];
+}
+
+/**
+ * The browser's storage object, or null when there isn't one to talk to.
+ * Reading the property is itself enough to throw on some WebViews, and some
+ * browsers hand back null rather than throwing.
+ */
+function nativeStorage(area: Area): Storage | null {
+ if (environment.isServerSide()) return null;
+ try {
+ const store =
+ area === "local" ? window.localStorage : window.sessionStorage;
+ return store ?? null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Web Storage that degrades instead of throwing, for a given storage area.
+ *
+ * Callers get a plain `string | null` and never need to guard for the server
+ * or for a browser that refuses storage.
+ */
+export function createSafeStorage<K extends string>(area: Area) {
+ function get(key: K): string | null {
+ const store = nativeStorage(area);
+ if (!store) return memoryFor(area)?.get(key) ?? null;
+ try {
+ // Memory is an overlay, not a cache: it only holds keys whose write to
+ // the real storage failed, and a successful write clears its entry. So
+ // an overlay hit is always newer than what the store has, and it wins —
+ // which is what keeps "a set reads back within the tab" true even when
+ // the key already had a value the failed write was meant to replace.
+ return memoryFor(area)?.get(key) ?? store.getItem(key) ?? null;
+ } catch {
+ return memoryFor(area)?.get(key) ?? null;
+ }
+ }
+
+ function set(key: K, value: string): void {
+ const store = nativeStorage(area);
+ if (!store) {
+ memoryFor(area)?.set(key, value);
+ return;
+ }
+ try {
+ store.setItem(key, value);
+ // The store is now authoritative for this key again; drop any overlay
+ // entry left by an earlier failed write so it cannot mask this value.
+ memoryFor(area)?.delete(key);
+ } catch (error) {
+ // The storage object is live, so this is something unexpected
+ // (QuotaExceededError and friends) rather than a browser that simply
+ // refuses storage — worth knowing about. Keep the value in memory so
+ // the tab still behaves as if the write landed.
+ Sentry.captureException(error);
+ memoryFor(area)?.set(key, value);
+ }
+ }
+
+ function clean(key: K): void {
+ const store = nativeStorage(area);
+ memoryFor(area)?.delete(key);
+ if (!store) return;
+ try {
+ store.removeItem(key);
+ } catch (error) {
+ Sentry.captureException(error);
+ }
+ }
+
+ return { get, set, clean };
+}
diff --git a/autogpt_platform/frontend/src/services/storage/session-storage.ts b/autogpt_platform/frontend/src/services/storage/session-storage.ts
index 1be82c98fb..079ebbd1e0 100644
--- a/autogpt_platform/frontend/src/services/storage/session-storage.ts
+++ b/autogpt_platform/frontend/src/services/storage/session-storage.ts
@@ -1,41 +1,8 @@
-import * as Sentry from "@sentry/nextjs";
-import { environment } from "../environment";
+import { createSafeStorage } from "./safe-storage";
export enum SessionKey {
CHAT_SENT_INITIAL_PROMPTS = "chat_sent_initial_prompts",
CHAT_INITIAL_PROMPTS = "chat_initial_prompts",
}
-function get(key: SessionKey) {
- if (environment.isServerSide()) {
- Sentry.captureException(new Error("Session storage is not available"));
- return;
- }
- try {
- return window.sessionStorage.getItem(key);
- } catch {
- return;
- }
-}
-
-function set(key: SessionKey, value: string) {
- if (environment.isServerSide()) {
- Sentry.captureException(new Error("Session storage is not available"));
- return;
- }
- return window.sessionStorage.setItem(key, value);
-}
-
-function clean(key: SessionKey) {
- if (environment.isServerSide()) {
- Sentry.captureException(new Error("Session storage is not available"));
- return;
- }
- return window.sessionStorage.removeItem(key);
-}
-
-export const sessionStorage = {
- clean,
- get,
- set,
-};
+export const sessionStorage = createSafeStorage<SessionKey>("session");