Skip to content

The platform for continuously improving AI agents.

Keep the Console up when the browser blocks site storage (#340)

Freyam Mehta9d1b02dff6e9
diff --git a/AGENTS.md b/AGENTS.md
index cd47bb7a..da4547d2 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -60,6 +60,7 @@ Ruff enforces formatting and line length. What it can't:
- The Console is dark-only, including first paint, authentication, charts and flow canvases. Use semantic tokens, with no `dark:` variants: `border-success/40 bg-success/10 text-success`.
- Flat surfaces: `shadow-*` utilities are disabled. Depth is surface layering plus 1px borders.
- Icons come only from `import { Icon } from "@/components/ui/icons"`; `check:design` fails on `lucide-react` or the vendored glyph table.
+- Browser storage goes through `localStore` / `sessionStore` in `lib/storage.ts`. Chrome throws on the `window.localStorage` read itself when a user blocks site data.
- Tokens, primitives, the border-contrast floor and the two table implementations: frontend-design skill.
### UI copy
diff --git a/frontend/src/blocked-storage.test.tsx b/frontend/src/blocked-storage.test.tsx
new file mode 100644
index 00000000..8e6b3c1a
--- /dev/null
+++ b/frontend/src/blocked-storage.test.tsx
@@ -0,0 +1,85 @@
+// @vitest-environment jsdom
+// covers: boot
+import { cleanup, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+
+vi.mock("@clerk/clerk-react", () => ({
+ useAuth: () => ({
+ getToken: async () => null,
+ isLoaded: true,
+ isSignedIn: false,
+ signOut: async () => {},
+ }),
+ useUser: () => ({ user: null }),
+}));
+
+const areas = ["localStorage", "sessionStorage"] as const;
+const saved = new Map<string, PropertyDescriptor | undefined>();
+
+// Chrome throws on the property read itself when the user blocks site data.
+beforeEach(() => {
+ for (const area of areas) {
+ saved.set(area, Object.getOwnPropertyDescriptor(window, area));
+ Object.defineProperty(window, area, {
+ configurable: true,
+ get() {
+ throw new DOMException("Access is denied for this document.", "SecurityError");
+ },
+ });
+ }
+});
+
+afterEach(() => {
+ cleanup();
+ for (const area of areas) {
+ const descriptor = saved.get(area);
+ if (descriptor) Object.defineProperty(window, area, descriptor);
+ else Reflect.deleteProperty(window, area);
+ }
+ vi.unstubAllEnvs();
+ vi.resetModules();
+});
+
+it.each([
+ ["hosted", "false", "pk_test_blocked"],
+ ["self-hosted", "true", ""],
+])("the %s Console renders when the browser blocks site storage", async (_, selfHosted, key) => {
+ vi.stubEnv("VITE_SELF_HOSTED", selfHosted);
+ vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", key);
+ vi.resetModules();
+ const { AuthProvider } = await import("@/contexts/auth-context");
+
+ render(
+ <AuthProvider>
+ <p>Console</p>
+ </AuthProvider>
+ );
+
+ expect(screen.getByText("Console")).toBeTruthy();
+});
+
+it("keeps a guest's tokens for the page when the browser blocks storage", async () => {
+ const { getAccessToken, getRefreshToken, setTokens } = await import("@/client");
+
+ setTokens("access", "refresh");
+
+ expect([getAccessToken(), getRefreshToken()]).toEqual(["access", "refresh"]);
+});
+
+it("reads a refused write back instead of the older stored value", async () => {
+ Object.defineProperty(window, "localStorage", {
+ configurable: true,
+ value: {
+ getItem: () => "rotated-away",
+ removeItem: () => {},
+ setItem: () => {
+ throw new DOMException("The quota has been exceeded.", "QuotaExceededError");
+ },
+ },
+ });
+ const { localStore } = await import("@/lib/storage");
+
+ expect(localStore.set("jwt_access", "current")).toBe(false);
+
+ expect(localStore.get("jwt_access")).toBe("current");
+});
diff --git a/frontend/src/client.ts b/frontend/src/client.ts
index 796aa1a8..dd828785 100644
--- a/frontend/src/client.ts
+++ b/frontend/src/client.ts
@@ -19,6 +19,7 @@ import {
} from "./lib/guest";
import { emitPlanLimitToast, PlanLimitError, planLimitFromBody } from "./lib/plan-limits";
import { dismissSessionRecovery, requireSessionRecovery } from "./lib/session-recovery";
+import { localStore } from "./lib/storage";
import type { ModelSwapPrompt } from "./openapi";
import {
ActivityApi,
@@ -96,14 +97,14 @@ export function setAsyncTokenGetter(
export async function resolveToken(): Promise<string | null> {
if (_asyncTokenGetter) return _asyncTokenGetter();
- return localStorage.getItem(TOKEN_KEY);
+ return localStore.get(TOKEN_KEY);
}
export function getAccessToken(): string | null {
- return localStorage.getItem(TOKEN_KEY);
+ return localStore.get(TOKEN_KEY);
}
export function getRefreshToken(): string | null {
- return localStorage.getItem(REFRESH_KEY);
+ return localStore.get(REFRESH_KEY);
}
// Token claims only bind cached UI identity; the API still verifies every credential.
export function getLocalAccountId(token = getAccessToken()): string | null {
@@ -119,12 +120,12 @@ export function getLocalAccountId(token = getAccessToken()): string | null {
}
export function rememberLocalIdentity(user: { id: string | number; email: string }) {
- localStorage.setItem(IDENTITY_KEY, JSON.stringify({ email: user.email, id: String(user.id) }));
+ localStore.set(IDENTITY_KEY, JSON.stringify({ email: user.email, id: String(user.id) }));
}
export function getLocalIdentity(): { id: string; email: string } | null {
try {
- const user = JSON.parse(localStorage.getItem(IDENTITY_KEY) ?? "null");
+ const user = JSON.parse(localStore.get(IDENTITY_KEY) ?? "null");
return user &&
typeof user.id === "string" &&
typeof user.email === "string" &&
@@ -144,19 +145,19 @@ export function setTokens(
changeSession();
storeTokens(access, refresh);
if (user) rememberLocalIdentity(user);
- else localStorage.removeItem(IDENTITY_KEY);
+ else localStore.remove(IDENTITY_KEY);
}
function storeTokens(access: string, refresh: string) {
- localStorage.setItem(TOKEN_KEY, access);
- localStorage.setItem(REFRESH_KEY, refresh);
+ localStore.set(TOKEN_KEY, access);
+ localStore.set(REFRESH_KEY, refresh);
}
export function clearTokens() {
changeSession();
- localStorage.removeItem(TOKEN_KEY);
- localStorage.removeItem(REFRESH_KEY);
- localStorage.removeItem(EMAIL_KEY);
- localStorage.removeItem(IDENTITY_KEY);
+ localStore.remove(TOKEN_KEY);
+ localStore.remove(REFRESH_KEY);
+ localStore.remove(EMAIL_KEY);
+ localStore.remove(IDENTITY_KEY);
clearGuestSession();
}
if (typeof window !== "undefined") {
diff --git a/frontend/src/components/assistant/assistant-result.tsx b/frontend/src/components/assistant/assistant-result.tsx
index 60f09940..83c7e11a 100644
--- a/frontend/src/components/assistant/assistant-result.tsx
+++ b/frontend/src/components/assistant/assistant-result.tsx
@@ -21,6 +21,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Textarea } from "@/components/ui/textarea";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { useTableSort } from "@/hooks/use-table-sort";
+import { sessionStore } from "@/lib/storage";
import { cn } from "@/lib/utils";
import type {
ChartNode,
@@ -330,7 +331,7 @@ function ResultImage({ node }: { node: Extract<ResultNode, { type: "Image" }> })
function draftOf(key: string): Record<string, unknown> {
try {
- return JSON.parse(sessionStorage.getItem(key) ?? "{}");
+ return JSON.parse(sessionStore.get(key) ?? "{}");
} catch {
return {};
}
@@ -357,13 +358,13 @@ function Question({ node }: { node: QuestionNode | ChoicesNode }) {
const set = (name: string, value: unknown) =>
setValues((old) => {
const next = { ...old, [name]: value };
- sessionStorage.setItem(draftKey, JSON.stringify(next));
+ sessionStore.set(draftKey, JSON.stringify(next));
return next;
});
const answer = (given: Record<string, unknown>, text: string) => {
// The draft stays until the answer is queued: a failed send keeps it for a retry.
actions.onAnswer(text, { call, id: node.id, values: given }, () =>
- sessionStorage.removeItem(draftKey)
+ sessionStore.remove(draftKey)
);
};
diff --git a/frontend/src/components/quickstart/prompt-agent-actions.tsx b/frontend/src/components/quickstart/prompt-agent-actions.tsx
index 5a4ef157..a838139e 100644
--- a/frontend/src/components/quickstart/prompt-agent-actions.tsx
+++ b/frontend/src/components/quickstart/prompt-agent-actions.tsx
@@ -13,6 +13,7 @@ import {
import { Icon } from "@/components/ui/icons";
import { writeClipboardText } from "@/lib/clipboard";
import { isMobileBrowser } from "@/lib/platform";
+import { localStore } from "@/lib/storage";
import { cn } from "@/lib/utils";
// OpenCode's desktop link needs a local directory, which the Console does not know.
@@ -27,22 +28,15 @@ const agents: { id: string; label: string; url?: string }[] = [
const MAX_LINK_LENGTH = 10_000;
const preferenceKey = "preferred-coding-agent";
const preferenceEvent = "coding-agent-preference";
-let unsavedPreference: string | null = null;
function readPreference() {
- if (unsavedPreference) return unsavedPreference;
- try {
- const value = localStorage.getItem(preferenceKey);
- return agents.some((agent) => agent.id === value) ? value : null;
- } catch {
- return null;
- }
+ const value = localStore.get(preferenceKey);
+ return agents.some((agent) => agent.id === value) ? value : null;
}
function subscribePreference(listener: () => void) {
const onStorage = (event: StorageEvent) => {
if (event.key !== null && event.key !== preferenceKey) return;
- unsavedPreference = null;
listener();
};
window.addEventListener("storage", onStorage);
@@ -54,11 +48,7 @@ function subscribePreference(listener: () => void) {
}
function chooseAgent(value: string) {
- try {
- localStorage.setItem(preferenceKey, value);
- unsavedPreference = null;
- } catch {
- unsavedPreference = value;
+ if (!localStore.set(preferenceKey, value)) {
toast.error("Couldn't save the coding-agent preference.");
}
window.dispatchEvent(new Event(preferenceEvent));
diff --git a/frontend/src/components/traces/filters.tsx b/frontend/src/components/traces/filters.tsx
index fc85f8d7..f4c033ee 100644
--- a/frontend/src/components/traces/filters.tsx
+++ b/frontend/src/components/traces/filters.tsx
@@ -26,6 +26,7 @@ import {
} from "@/components/ui/select";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { UNBOUND_CAPABILITY } from "@/hooks/use-traces";
+import { localStore } from "@/lib/storage";
import { cn } from "@/lib/utils";
type FilterLookup = "eq" | "icontains" | "gte" | "lte" | "gt" | "lt" | "isnull";
@@ -676,9 +677,8 @@ export function describeFilter(entry: FilterEntry, valueLabel?: string): string
export function useRecentFilterParams(storageKey = "overmind:traces:recentFilters") {
const get = useCallback((): SearchParams[] => {
- if (typeof window === "undefined") return [];
try {
- const raw = window.localStorage.getItem(storageKey);
+ const raw = localStore.get(storageKey);
if (!raw) return [];
const parsed = JSON.parse(raw) as SearchParams[];
return Array.isArray(parsed) ? parsed.slice(0, 8) : [];
@@ -688,14 +688,13 @@ export function useRecentFilterParams(storageKey = "overmind:traces:recentFilter
}, [storageKey]);
const push = useCallback(
(entry: SearchParams) => {
- if (typeof window === "undefined") return;
const meaningful = Object.entries(entry).filter(([, v]) => v !== undefined && v !== "");
if (meaningful.length === 0) return;
const current = get();
const key = JSON.stringify(entry);
const deduped = current.filter((e) => JSON.stringify(e) !== key);
const next = [entry, ...deduped].slice(0, 8);
- window.localStorage.setItem(storageKey, JSON.stringify(next));
+ localStore.set(storageKey, JSON.stringify(next));
},
[get, storageKey]
);
diff --git a/frontend/src/components/ui/data-table.tsx b/frontend/src/components/ui/data-table.tsx
index a638f1d8..d21a377b 100644
--- a/frontend/src/components/ui/data-table.tsx
+++ b/frontend/src/components/ui/data-table.tsx
@@ -40,6 +40,7 @@ import {
import { TablePagination } from "@/components/ui/table-pagination";
import { cycleDrfOrdering, parseDrfOrdering } from "@/lib/drf-ordering";
import { errorMessage } from "@/lib/notify";
+import { localStore } from "@/lib/storage";
import { cn } from "@/lib/utils";
/** Structurally matches every generated `Paginated*List` model. */
@@ -254,7 +255,7 @@ export function DataTable<T>({
useEffect(() => {
if (!storageKey) return;
try {
- const raw = localStorage.getItem(storageKey);
+ const raw = localStore.get(storageKey);
setColumnSizing(
raw ? clampColumnSizing(JSON.parse(raw) as ColumnSizingState, cappedColumns) : {}
);
@@ -264,11 +265,7 @@ export function DataTable<T>({
}, [storageKey, cappedColumns]);
useEffect(() => {
if (!storageKey) return;
- try {
- localStorage.setItem(storageKey, JSON.stringify(columnSizing));
- } catch {
- // quota / disabled storage
- }
+ localStore.set(storageKey, JSON.stringify(columnSizing));
}, [storageKey, columnSizing]);
const table = useReactTable({
diff --git a/frontend/src/contexts/auth-context.tsx b/frontend/src/contexts/auth-context.tsx
index 7dec6c47..d99e5e6e 100644
--- a/frontend/src/contexts/auth-context.tsx
+++ b/frontend/src/contexts/auth-context.tsx
@@ -151,8 +151,7 @@ function ClerkAuthProvider({ children }: { children: React.ReactNode }) {
}
function readIsSignedIn(): boolean {
- if (typeof window === "undefined") return false;
- return !!localStorage.getItem("jwt_access");
+ return !!getAccessToken();
}
function readLocalUser(): AuthUser | null {
@@ -207,7 +206,7 @@ function SelfHostedAuthProvider({ children }: { children: React.ReactNode }) {
return () => window.removeEventListener("storage", onStorage);
}, [refreshAuth]);
- const getToken = useCallback(async () => localStorage.getItem("jwt_access"), []);
+ const getToken = useCallback(async () => getAccessToken(), []);
const handleSignOut = useCallback(async () => {
identityRequest.current++;
diff --git a/frontend/src/hooks/use-nudge-dismissal.ts b/frontend/src/hooks/use-nudge-dismissal.ts
index b66f960a..1e9c946f 100644
--- a/frontend/src/hooks/use-nudge-dismissal.ts
+++ b/frontend/src/hooks/use-nudge-dismissal.ts
@@ -1,21 +1,23 @@
import { useEffect, useState } from "react";
+import { localStore } from "@/lib/storage";
+
export function useNudgeDismissal(storageKey: string): {
dismissed: boolean;
dismiss: () => void;
} {
const [dismissed, setDismissed] = useState(
- () => !!storageKey && localStorage.getItem(storageKey) === "1"
+ () => !!storageKey && localStore.get(storageKey) === "1"
);
useEffect(() => {
- setDismissed(!!storageKey && localStorage.getItem(storageKey) === "1");
+ setDismissed(!!storageKey && localStore.get(storageKey) === "1");
}, [storageKey]);
return {
dismiss: () => {
if (!storageKey) return;
- localStorage.setItem(storageKey, "1");
+ localStore.set(storageKey, "1");
setDismissed(true);
},
dismissed: !storageKey || dismissed,
@@ -31,17 +33,15 @@ export function useNudgeDismissalCount(
dismissed: boolean;
dismiss: () => void;
} {
- const [dismissedAt, setDismissedAt] = useState(() =>
- Number(localStorage.getItem(storageKey) ?? 0)
- );
+ const [dismissedAt, setDismissedAt] = useState(() => Number(localStore.get(storageKey) ?? 0));
useEffect(() => {
- setDismissedAt(Number(localStorage.getItem(storageKey) ?? 0));
+ setDismissedAt(Number(localStore.get(storageKey) ?? 0));
}, [storageKey]);
return {
dismiss: () => {
- localStorage.setItem(storageKey, String(currentCount));
+ localStore.set(storageKey, String(currentCount));
setDismissedAt(currentCount);
},
dismissed: currentCount <= dismissedAt,
diff --git a/frontend/src/hooks/use-persisted-state.ts b/frontend/src/hooks/use-persisted-state.ts
index 7212150a..51b76a51 100644
--- a/frontend/src/hooks/use-persisted-state.ts
+++ b/frontend/src/hooks/use-persisted-state.ts
@@ -1,14 +1,14 @@
import { useCallback, useState } from "react";
-/** `useState` persisted to `localStorage` under `key`. Storage failures (quota,
- * privacy mode, SSR) degrade to in-memory state. */
+import { localStore } from "@/lib/storage";
+/** `useState` persisted to `localStorage` under `key`; a refused write keeps in-memory state. */
export function usePersistedState<T>(
key: string,
defaultValue: T
): [T, (value: T | ((prev: T) => T)) => void] {
const [state, setState] = useState<T>(() => {
try {
- const raw = localStorage.getItem(key);
+ const raw = localStore.get(key);
return raw != null ? (JSON.parse(raw) as T) : defaultValue;
} catch {
return defaultValue;
@@ -19,11 +19,7 @@ export function usePersistedState<T>(
(value: T | ((prev: T) => T)) => {
setState((prev) => {
const next = typeof value === "function" ? (value as (p: T) => T)(prev) : value;
- try {
- localStorage.setItem(key, JSON.stringify(next));
- } catch {
- // ignore quota / privacy-mode / SSR errors — fall back to in-memory
- }
+ localStore.set(key, JSON.stringify(next));
return next;
});
},
diff --git a/frontend/src/hooks/use-project-search-sync.ts b/frontend/src/hooks/use-project-search-sync.ts
index 3b311881..1da0ece8 100644
--- a/frontend/src/hooks/use-project-search-sync.ts
+++ b/frontend/src/hooks/use-project-search-sync.ts
@@ -3,19 +3,20 @@ import { useEffect } from "react";
import { useNavigate, useRouterState, useSearch } from "@tanstack/react-router";
import { useProjectsList } from "@/hooks/use-projects";
+import { localStore } from "@/lib/storage";
const SELECTED_PROJECT_STORAGE_KEY = "__selectedProject";
function getStoredProjectId(): string {
- return localStorage.getItem(SELECTED_PROJECT_STORAGE_KEY) || "";
+ return localStore.get(SELECTED_PROJECT_STORAGE_KEY) || "";
}
export function setStoredProjectId(projectId: string) {
- localStorage.setItem(SELECTED_PROJECT_STORAGE_KEY, projectId);
+ localStore.set(SELECTED_PROJECT_STORAGE_KEY, projectId);
}
function clearStoredProjectId() {
- localStorage.removeItem(SELECTED_PROJECT_STORAGE_KEY);
+ localStore.remove(SELECTED_PROJECT_STORAGE_KEY);
}
export function selectProject(projectId: string) {
diff --git a/frontend/src/hooks/use-recent-items.ts b/frontend/src/hooks/use-recent-items.ts
index 0da835d4..55c4e41f 100644
--- a/frontend/src/hooks/use-recent-items.ts
+++ b/frontend/src/hooks/use-recent-items.ts
@@ -1,5 +1,7 @@
import { useCallback, useEffect, useRef, useState } from "react";
+import { localStore } from "@/lib/storage";
+
export type RecentItem = {
id: string;
type: "capability" | "project" | "resource";
@@ -14,10 +16,9 @@ const STORAGE_KEY = "overmind:recents";
const MAX_RECENTS = 5;
const TTL_MS = 7 * 24 * 60 * 60 * 1000;
-// Unguarded localStorage: CSR-only Vite app. SSR would need a window guard.
function readFromStorage(): RecentItem[] {
try {
- const raw = localStorage.getItem(STORAGE_KEY);
+ const raw = localStore.get(STORAGE_KEY);
if (!raw) return [];
const parsed = JSON.parse(raw);
if (!Array.isArray(parsed)) return [];
@@ -38,11 +39,7 @@ function readFromStorage(): RecentItem[] {
}
function writeToStorage(items: RecentItem[]): void {
- try {
- localStorage.setItem(STORAGE_KEY, JSON.stringify(items));
- } catch {
- // ignore storage errors
- }
+ localStore.set(STORAGE_KEY, JSON.stringify(items));
}
export function useRecentItems() {
diff --git a/frontend/src/lib/auth-load-recovery.ts b/frontend/src/lib/auth-load-recovery.ts
index 2e87722d..a28fa230 100644
--- a/frontend/src/lib/auth-load-recovery.ts
+++ b/frontend/src/lib/auth-load-recovery.ts
@@ -1,40 +1,24 @@
import { trackEvent } from "@/analytics";
import { isChunkLoadError } from "@/lib/chunk-error";
+import { sessionStore } from "@/lib/storage";
export type AuthLoadFailure = "script" | "chunk";
// One automatic reload per tab: "done" stays set after recovery, so a repeat failure cannot loop.
const RETRY_KEY = "overmind.auth-load-retry";
-function readRetry(): string | null | undefined {
- try {
- return window.sessionStorage.getItem(RETRY_KEY);
- } catch {
- return undefined;
- }
-}
-
-function writeRetry(value: string): boolean {
- try {
- window.sessionStorage.setItem(RETRY_KEY, value);
- return true;
- } catch {
- return false;
- }
-}
-
/** Reloads once per tab and returns true; returns false when the fallback must show instead. */
export function retryAuthLoad(failure: AuthLoadFailure): boolean {
- if (readRetry() !== null) return false;
- if (!writeRetry(failure)) return false;
+ if (sessionStore.get(RETRY_KEY) !== null) return false;
+ if (!sessionStore.set(RETRY_KEY, failure)) return false;
window.location.reload();
return true;
}
export function markAuthLoaded() {
- const failure = readRetry();
+ const failure = sessionStore.get(RETRY_KEY);
if (failure !== "script" && failure !== "chunk") return;
- if (!writeRetry("done")) return;
+ if (!sessionStore.set(RETRY_KEY, "done")) return;
trackEvent("auth_load_recovered", { failure });
}
diff --git a/frontend/src/lib/guest.ts b/frontend/src/lib/guest.ts
index dc61202d..f203bcd2 100644
--- a/frontend/src/lib/guest.ts
+++ b/frontend/src/lib/guest.ts
@@ -1,3 +1,5 @@
+import { localStore } from "./storage";
+
const GUEST_FLAG = "guest_session";
const GUEST_PROJECT = "guest_project_id";
@@ -11,23 +13,21 @@ export function isGuestAllowedPath(pathname: string): boolean {
}
export function hasGuestSession(): boolean {
- if (typeof window === "undefined") return false;
- return localStorage.getItem(GUEST_FLAG) === "1";
+ return localStore.get(GUEST_FLAG) === "1";
}
export function getGuestProjectId(): string | null {
- if (typeof window === "undefined") return null;
- return localStorage.getItem(GUEST_PROJECT);
+ return localStore.get(GUEST_PROJECT);
}
export function markGuestSession(projectId: string): void {
- localStorage.setItem(GUEST_FLAG, "1");
- localStorage.setItem(GUEST_PROJECT, projectId);
+ localStore.set(GUEST_FLAG, "1");
+ localStore.set(GUEST_PROJECT, projectId);
}
export function clearGuestSession(): void {
- localStorage.removeItem(GUEST_FLAG);
- localStorage.removeItem(GUEST_PROJECT);
+ localStore.remove(GUEST_FLAG);
+ localStore.remove(GUEST_PROJECT);
}
type Listener = () => void;
diff --git a/frontend/src/lib/storage.ts b/frontend/src/lib/storage.ts
new file mode 100644
index 00000000..3958d7ef
--- /dev/null
+++ b/frontend/src/lib/storage.ts
@@ -0,0 +1,37 @@
+// Reading window.localStorage itself throws a SecurityError when the browser blocks
+// site data, so every storage access in the Console goes through these wrappers.
+function guarded(area: () => Storage) {
+ // A refused write lives for this page and shadows any older stored copy, so a
+ // rotated token never falls back to the one it replaced.
+ const refused = new Map<string, string>();
+ return {
+ get(key: string): string | null {
+ if (refused.has(key)) return refused.get(key) ?? null;
+ try {
+ return area().getItem(key);
+ } catch {
+ return null;
+ }
+ },
+ remove(key: string): void {
+ refused.delete(key);
+ try {
+ area().removeItem(key);
+ } catch {}
+ },
+ /** Returns false when the browser refused the write; the value then lasts for this page only. */
+ set(key: string, value: string): boolean {
+ try {
+ area().setItem(key, value);
+ refused.delete(key);
+ return true;
+ } catch {
+ refused.set(key, value);
+ return false;
+ }
+ },
+ };
+}
+
+export const localStore = guarded(() => window.localStorage);
+export const sessionStore = guarded(() => window.sessionStorage);
diff --git a/frontend/src/routes/_auth/index.tsx b/frontend/src/routes/_auth/index.tsx
index e345c91e..cbb2b1ac 100644
--- a/frontend/src/routes/_auth/index.tsx
+++ b/frontend/src/routes/_auth/index.tsx
@@ -22,6 +22,7 @@ import { useOnboardingMilestones } from "@/hooks/use-activity";
import { useProjectsList } from "@/hooks/use-projects";
import { getGuestProjectId } from "@/lib/guest";
import { errorMessage } from "@/lib/notify";
+import { localStore } from "@/lib/storage";
import { cn } from "@/lib/utils";
import type { AgentGraph, CapabilityList } from "@/openapi";
@@ -52,13 +53,7 @@ function AgentHeader({ graph }: { graph?: AgentGraph }) {
function OnboardingStrip({ projectId }: { projectId: string }) {
const storageKey = `onboarding-dismissed:${projectId}`;
- const [dismissed, setDismissed] = useState(() => {
- try {
- return localStorage.getItem(storageKey) === "1";
- } catch {
- return false;
- }
- });
+ const [dismissed, setDismissed] = useState(() => localStore.get(storageKey) === "1");
const onboarding = useOnboardingMilestones(projectId, "agent");
const steps = onboarding.data ?? [];
const completed = steps.filter((step) => step.completedAt).length;
@@ -101,9 +96,7 @@ function OnboardingStrip({ projectId }: { projectId: string }) {
<Button
aria-label="Dismiss onboarding progress"
onClick={() => {
- try {
- localStorage.setItem(storageKey, "1");
- } catch {}
+ localStore.set(storageKey, "1");
setDismissed(true);
}}
size="icon-sm"
diff --git a/frontend/src/routes/_auth/projects.$projectId.index.tsx b/frontend/src/routes/_auth/projects.$projectId.index.tsx
index 637e09a5..687ae7eb 100644
--- a/frontend/src/routes/_auth/projects.$projectId.index.tsx
+++ b/frontend/src/routes/_auth/projects.$projectId.index.tsx
@@ -37,6 +37,7 @@ import { ApiError } from "@/lib/api-error";
import { featureFlags } from "@/lib/feature-flags";
import { PUBLIC_PRICING_URL } from "@/lib/marketing";
import { notify } from "@/lib/notify";
+import { localStore } from "@/lib/storage";
import { PROSE, TITLE } from "@/lib/typography";
import { cn } from "@/lib/utils";
import { PlanEnum } from "@/openapi";
@@ -437,8 +438,8 @@ function DeleteProjectCard({ projectId }: { projectId: string }) {
onSuccess: () => {
toast.success("Project deleted.");
void queryClient.invalidateQueries({ queryKey: ["projects"] });
- if (localStorage.getItem(SELECTED_PROJECT_KEY) === projectId) {
- localStorage.removeItem(SELECTED_PROJECT_KEY);
+ if (localStore.get(SELECTED_PROJECT_KEY) === projectId) {
+ localStore.remove(SELECTED_PROJECT_KEY);
}
if (activeProjectId === projectId) {
navigate({ search: {}, to: "/projects" });
diff --git a/sandbox/__main__.py b/sandbox/__main__.py
index 4daf6ce0..14675f38 100644
--- a/sandbox/__main__.py
+++ b/sandbox/__main__.py
@@ -11,6 +11,7 @@ def main() -> None:
parser = argparse.ArgumentParser(prog="python -m sandbox")
parser.add_argument("--host", default="0.0.0.0")
parser.add_argument("--port", type=int, default=8080)
+ parser.add_argument("--fd", type=int, help="Serve on this inherited listening socket instead.")
args = parser.parse_args()
if not os.environ.get("SANDBOX_TOKEN"):
sys.exit("SANDBOX_TOKEN is required.")
@@ -21,7 +22,7 @@ def main() -> None:
)
if os.geteuid() == 0 and not execute.can_trace():
sys.exit("The sandbox needs CAP_SYS_PTRACE to see the files a run holds open.")
- uvicorn.run("sandbox.server:app", host=args.host, port=args.port, workers=1)
+ uvicorn.run("sandbox.server:app", host=args.host, port=args.port, fd=args.fd, workers=1)
main()
diff --git a/tests/conftest.py b/tests/conftest.py
index 0881a395..96f160cb 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -374,10 +374,7 @@ def import_version(dataset, records, *, name="Native transformation"):
@pytest.fixture(scope="session")
def sandbox_server():
- with socket.socket() as probe:
- probe.bind(("127.0.0.1", 0))
- port = probe.getsockname()[1]
- url, token = f"http://127.0.0.1:{port}", secrets.token_hex(16)
+ token = secrets.token_hex(16)
scratch = tempfile.TemporaryDirectory(prefix="sandbox-test-")
# Deeper than a Unix socket path holds, as a deployment's temporary directory may be.
deep = Path(scratch.name) / ("deep-" * 20)
@@ -390,7 +387,7 @@ def sandbox_server():
# Its own memory ledger: parallel test servers must not share /tmp/sandbox.
"TMPDIR": str(deep),
}
- command = [sys.executable, "-m", "sandbox", "--host", "127.0.0.1", "--port", str(port)]
+ image = os.environ.get("SANDBOX_TEST_IMAGE", "overmind-dev")
container = None
proxy = None
if sys.platform == "darwin" or os.environ.get("SANDBOX_CONTAINER_TESTS") == "1":
@@ -432,12 +429,19 @@ def sandbox_server():
"SYS_PTRACE",
):
command += ["--cap-add", capability]
- command += [os.environ.get("SANDBOX_TEST_IMAGE", "overmind-dev"), "-m", "sandbox"]
- proc = subprocess.Popen(
- command,
- cwd=Path(__file__).resolve().parents[1],
- env=env,
- )
+ command += [image, "-m", "sandbox"]
+ proc = subprocess.Popen(command, cwd=Path(__file__).resolve().parents[1], env=env)
+ else:
+ # The server inherits a socket this process already listens on. A port probed and then
+ # released can be taken by another xdist worker's sandbox before this one binds it.
+ with socket.create_server(("127.0.0.1", 0)) as listener:
+ url = f"http://127.0.0.1:{listener.getsockname()[1]}"
+ proc = subprocess.Popen(
+ [sys.executable, "-m", "sandbox", "--fd", str(listener.fileno())],
+ cwd=Path(__file__).resolve().parents[1],
+ env=env,
+ pass_fds=[listener.fileno()],
+ )
try:
if container:
# Docker Desktop cannot publish an internal-only container to macOS.
@@ -466,10 +470,10 @@ socketserver.ThreadingTCPServer(('0.0.0.0',8080),Relay).serve_forever()
"--network",
"bridge",
"-p",
- f"127.0.0.1:{port}:8080",
+ "127.0.0.1::8080",
"--entrypoint",
"python",
- os.environ.get("SANDBOX_TEST_IMAGE", "overmind-dev"),
+ image,
"-c",
forwarding,
container,
@@ -480,6 +484,10 @@ socketserver.ThreadingTCPServer(('0.0.0.0',8080),Relay).serve_forever()
subprocess.run(
["docker", "network", "connect", container, proxy], check=True, capture_output=True
)
+ published = subprocess.run(
+ ["docker", "port", proxy, "8080/tcp"], check=True, capture_output=True, text=True
+ )
+ url = f"http://{published.stdout.split()[0]}"
deadline = time.monotonic() + 30
while True:
try:
diff --git a/tests/journeys/test_boot.py b/tests/journeys/test_boot.py
index 4d4e842d..de62e3d7 100644
--- a/tests/journeys/test_boot.py
+++ b/tests/journeys/test_boot.py
@@ -2,7 +2,6 @@ import os
import socket
import subprocess
import sys
-import time
from pathlib import Path
import pytest
@@ -67,34 +66,28 @@ def _environment(**overrides: str) -> dict[str, str]:
return {key: value for key, value in env.items() if value is not None}
-def _free_port() -> int:
- with socket.socket() as sock:
- sock.bind(("127.0.0.1", 0))
- return sock.getsockname()[1]
-
-
def _serve(env: dict[str, str]) -> tuple[subprocess.Popen, str]:
- port = _free_port()
- server = subprocess.Popen(
- [sys.executable, "-m", "uvicorn", "overbae.asgi:application", "--port", str(port)],
- cwd=ROOT,
- env=env,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT,
- text=True,
- )
- url = f"http://127.0.0.1:{port}"
- deadline = time.monotonic() + 60
- while time.monotonic() < deadline:
- if server.poll() is not None:
- raise AssertionError(f"server exited {server.returncode}:\n{server.stdout.read()}")
- try:
- requests.get(f"{url}/health", timeout=2)
- return server, url
- except requests.ConnectionError:
- time.sleep(0.2)
- server.kill()
- raise AssertionError(f"server never listened:\n{server.stdout.read()}")
+ # The server inherits a socket this process already listens on, so no parallel worker
+ # can take its port between choosing it and binding it.
+ with socket.create_server(("127.0.0.1", 0)) as listener:
+ url = f"http://127.0.0.1:{listener.getsockname()[1]}"
+ server = subprocess.Popen(
+ [sys.executable, "-m", "uvicorn", "overbae.asgi:application"]
+ + ["--fd", str(listener.fileno())],
+ cwd=ROOT,
+ env=env,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ text=True,
+ pass_fds=[listener.fileno()],
+ )
+ # The socket accepts connections from the start; the request waits for the app to answer.
+ try:
+ requests.get(f"{url}/health", timeout=60)
+ except requests.RequestException as error:
+ server.kill()
+ raise AssertionError(f"server never answered: {error}\n{server.stdout.read()}") from error
+ return server, url
def _health(env: dict[str, str]) -> requests.Response:
@@ -129,7 +122,10 @@ def test_the_hosted_environment_boots():
def test_health_fails_when_the_database_is_unreachable():
- response = _health(_environment(POSTGRES_PORT=str(_free_port())))
+ # Bound and never listening: the port refuses connections and stays this test's.
+ with socket.socket() as unreachable:
+ unreachable.bind(("127.0.0.1", 0))
+ response = _health(_environment(POSTGRES_PORT=str(unreachable.getsockname()[1])))
assert response.status_code >= 500
diff --git a/tests/load/processes.py b/tests/load/processes.py
index 5d1f48e3..70db58b0 100644
--- a/tests/load/processes.py
+++ b/tests/load/processes.py
@@ -19,10 +19,6 @@ from overbae.celery import app
class ProcessAPI:
def __init__(self, settings, directory, workers=2):
# Match the hosted API's two workers without sharing the load generator's interpreter.
- with socket.socket() as listener:
- listener.bind(("127.0.0.1", 0))
- self.port = listener.getsockname()[1]
- self.url = f"http://127.0.0.1:{self.port}"
self.workers = workers
self.log_path = Path(directory) / "api-processes.log"
self.env = {
@@ -39,26 +35,29 @@ class ProcessAPI:
def __enter__(self):
self.log = self.log_path.open("w")
- self.process = subprocess.Popen(
- [
- sys.executable,
- "-m",
- "uvicorn",
- "overbae.asgi:application",
- "--host",
- "127.0.0.1",
- "--port",
- str(self.port),
- "--workers",
- str(self.workers),
- "--log-level",
- "warning",
- "--no-access-log",
- ],
- env=self.env,
- stdout=self.log,
- stderr=subprocess.STDOUT,
- )
+ # The API inherits a socket this process already listens on, so no other process
+ # can take its port between choosing it and binding it.
+ with socket.create_server(("127.0.0.1", 0)) as listener:
+ self.url = f"http://127.0.0.1:{listener.getsockname()[1]}"
+ self.process = subprocess.Popen(
+ [
+ sys.executable,
+ "-m",
+ "uvicorn",
+ "overbae.asgi:application",
+ "--fd",
+ str(listener.fileno()),
+ "--workers",
+ str(self.workers),
+ "--log-level",
+ "warning",
+ "--no-access-log",
+ ],
+ env=self.env,
+ stdout=self.log,
+ stderr=subprocess.STDOUT,
+ pass_fds=[listener.fileno()],
+ )
deadline = time.monotonic() + 30
while self.process.poll() is None and time.monotonic() < deadline:
try:
diff --git a/tests/test_assistant_turn.py b/tests/test_assistant_turn.py
index 32acf898..7475a1ce 100644
--- a/tests/test_assistant_turn.py
+++ b/tests/test_assistant_turn.py
@@ -1,4 +1,5 @@
import json
+import time
from datetime import timedelta
import pytest
@@ -135,16 +136,19 @@ def test_a_message_waits_for_its_source_and_landing_starts_the_turn(
def test_stop_ends_the_turn_at_its_next_step_and_drops_the_queue(fake_llm, user, thread, woken):
def reply(_request):
- # The user stops while the model writes a call.
+ # The user stops while the model writes a call, and the reply streams on past the
+ # next draft, where the turn sees the stop.
AssistantThread.objects.filter(pk=thread.pk).update(stop_requested=True)
threads.send(thread, user, request_key="later", text="And then?")
+ time.sleep(turn.DRAFT_INTERVAL_SECONDS * 2)
query = {"summary": "Counting", "dataset": str(thread.dataset_id), "sql": "select 1"}
return {"content": None, "tool_calls": [tool_call("query_dataset", query)], "usage": {}}
fake_llm.on(lambda request: bool(request.body.get("stream")), reply)
say(thread, user, "Count.")
- assert kinds(thread) == ["user", "assistant", "status"]
+ # The unfinished reply is dropped and its call never runs.
+ assert kinds(thread) == ["user", "status"]
assert thread.events.last().payload["state"] == "stopped"
assert thread.state == AssistantThread.State.IDLE and not thread.stop_requested
assert not thread.inputs.filter(state="queued").exists()