Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Settings: an unchanged config no longer redraws, and one session read on open (#6728)

Milind Sonic4521f86f4ec
diff --git a/src/components/BrowserProfilesManager.tsx b/src/components/BrowserProfilesManager.tsx
index e6c29b0247..f766617d13 100644
--- a/src/components/BrowserProfilesManager.tsx
+++ b/src/components/BrowserProfilesManager.tsx
@@ -4,7 +4,8 @@ import { SettingsDialog } from "./settings/SettingsDialog";
import { Globe, Plus, Trash2 } from "lucide-react";
import { api, ApiError, useStore, type Bot, type BotAnnouncement, type BrowserProfile, type ConfigStatus } from "@/state/store";
import { browserProfileDeletionBlockReason, browserProfilesMutation, newBrowserProfileId } from "@/lib/browser-profiles";
-import { isOwnerOrAdmin, readSessionState } from "@/lib/session";
+import { isOwnerOrAdmin } from "@/lib/session";
+import { readSharedSessionState } from "@/lib/shared-session";
import { t } from "@/lib/i18n";
import { computerDeviceText } from "@/lib/computer-device";
import { SignedInSites } from "./SignedInSites";
@@ -36,7 +37,7 @@ export function BrowserProfilesManager({ bot, onProfileChanged, disabled = false
useEffect(() => {
let alive = true;
- void readSessionState().then((session) => {
+ void readSharedSessionState().then((session) => {
if (alive) setCanManage(isOwnerOrAdmin(session));
});
return () => { alive = false; };
diff --git a/src/components/PeopleSection.tsx b/src/components/PeopleSection.tsx
index 6261a0d430..7bd1335d42 100644
--- a/src/components/PeopleSection.tsx
+++ b/src/components/PeopleSection.tsx
@@ -7,7 +7,8 @@ import { t } from "@/lib/i18n";
import { useCopyFeedback } from "@/lib/copy-text";
import { formatUsd, hasFiniteCost } from "@/lib/usage";
import { readMembership, type Membership } from "../lib/membership";
-import { readSessionState, type SessionState } from "../lib/session";
+import type { SessionState } from "../lib/session";
+import { readSharedSessionState } from "../lib/shared-session";
import { canPairDevices } from "./ServerPairingCard";
import { normalizeAccessEntry, withEntry, withoutEntry, type SignInLists } from "./SignInAccessCard";
import { Card } from "./SettingsPrimitives";
@@ -224,7 +225,7 @@ export function PeopleSection({ simple = false, startOpen = false }: { simple?:
}, []);
useEffect(() => {
- void readSessionState().then((state) => {
+ void readSharedSessionState().then((state) => {
setSession(state);
if (canPairDevices(state)) void load();
});
diff --git a/src/components/ServerPairingCard.tsx b/src/components/ServerPairingCard.tsx
index 890d63ffcc..da9804192c 100644
--- a/src/components/ServerPairingCard.tsx
+++ b/src/components/ServerPairingCard.tsx
@@ -4,7 +4,8 @@ import { QRCodeSVG } from "qrcode.react";
import { t } from "@/lib/i18n";
import { copyText, type CopyFeedback } from "@/lib/copy-text";
import { api } from "@/state/store";
-import { isOwnerOrAdmin, readSessionState, type SessionState } from "../lib/session";
+import { isOwnerOrAdmin, type SessionState } from "../lib/session";
+import { readSharedSessionState } from "../lib/shared-session";
import { readMembership } from "../lib/membership";
import { codeUntil, lastSeen } from "../lib/pairing-time";
import { revealPhonePairing, takePairOnOpen } from "../lib/phone-pairing";
@@ -113,7 +114,7 @@ export function ServerPairingCard({ initialSession = null, initialPairingCodes =
}
useEffect(() => {
- void readSessionState().then((state) => {
+ void readSharedSessionState().then((state) => {
setSession(state);
if (canPairDevices(state)) void loadDevices();
if (state.kind === "loopback" || state.kind === "session") {
diff --git a/src/components/SignInAccessCard.tsx b/src/components/SignInAccessCard.tsx
index 07f11911db..265cb91106 100644
--- a/src/components/SignInAccessCard.tsx
+++ b/src/components/SignInAccessCard.tsx
@@ -2,7 +2,8 @@ import { useEffect, useState } from "react";
import { t } from "@/lib/i18n";
import { api } from "@/state/store";
-import { readSessionState, type SessionState } from "../lib/session";
+import type { SessionState } from "../lib/session";
+import { readSharedSessionState } from "../lib/shared-session";
import { canPairDevices } from "./ServerPairingCard";
import { Card } from "./SettingsPrimitives";
@@ -54,7 +55,7 @@ export function SignInAccessCard() {
}
useEffect(() => {
- void readSessionState().then((state) => {
+ void readSharedSessionState().then((state) => {
setSession(state);
if (canPairDevices(state)) void load();
});
diff --git a/src/components/settings/account-summary.ts b/src/components/settings/account-summary.ts
index ce0239e422..98be88f101 100644
--- a/src/components/settings/account-summary.ts
+++ b/src/components/settings/account-summary.ts
@@ -2,7 +2,8 @@ import { useEffect, useState } from "react";
import type { CloudAccountState, CloudPlanSnapshot } from "../../../electron/cloud-account.mjs";
import { cloudPlanLabel, cloudPlanView } from "@/lib/cloud-plan";
import { t } from "@/lib/i18n";
-import { profileForSession, readSessionState, type SessionState } from "@/lib/session";
+import { profileForSession, type SessionState } from "@/lib/session";
+import { readSharedSessionState } from "@/lib/shared-session";
import { useStore } from "@/state/store";
export interface AccountSummary {
@@ -56,7 +57,7 @@ export function useYou(): { profile: { name?: string; email?: string; avatarUrl?
const [session, setSession] = useState<SessionState | null>(null);
useEffect(() => {
let alive = true;
- void readSessionState().then((next) => { if (alive) setSession(next); });
+ void readSharedSessionState().then((next) => { if (alive) setSession(next); });
return () => { alive = false; };
}, []);
return { profile: profileForSession(state.config?.profile, session), session };
diff --git a/src/components/settings/phone-status.ts b/src/components/settings/phone-status.ts
index fe0859186f..cf461571a7 100644
--- a/src/components/settings/phone-status.ts
+++ b/src/components/settings/phone-status.ts
@@ -2,7 +2,8 @@ import { useEffect, useState } from "react";
import { api, useStore } from "@/state/store";
import { companionBridge } from "@/lib/companion-bridge";
import { readMembership } from "@/lib/membership";
-import { isOwnerOrAdmin, readSessionState } from "@/lib/session";
+import { isOwnerOrAdmin } from "@/lib/session";
+import { readSharedSessionState } from "@/lib/shared-session";
import { useSidebarPhoneStatus } from "../SidebarPhoneButton";
export type PhonePlaceState =
@@ -14,6 +15,24 @@ export type PhonePlaceState =
| { kind: "chat-only" }
| { kind: "portal" };
+let lookup: Promise<PhonePlaceState> | null = null;
+
+/** What the server says of its paired phones. The nav and the page ask as they mount: both get the one lookup under way. */
+function serverPhoneState(): Promise<PhonePlaceState> {
+ if (lookup) return lookup;
+ const asked: Promise<PhonePlaceState> = readSharedSessionState().then(async (session): Promise<PhonePlaceState> => {
+ const config: unknown = await api("/api/config").catch(() => null);
+ const codes = readMembership(config).pairingCodes;
+ if (!isOwnerOrAdmin(session) && !(session.kind === "session" && session.team)) return { kind: codes ? "chat-only" : "portal" };
+ if (!codes) return { kind: "portal" };
+ const body = await api("/api/auth/sessions").catch(() => null) as { sessions?: unknown[]; current?: string } | null;
+ const count = Array.isArray(body?.sessions) ? body.sessions.length - (body?.current ? 1 : 0) : 0;
+ return count > 0 ? { kind: "paired", count, connected: false } : { kind: "none" };
+ }).catch((): PhonePlaceState => ({ kind: "none" })).finally(() => { if (lookup === asked) lookup = null; });
+ lookup = asked;
+ return asked;
+}
+
/** Phones paired with the place on screen, as the outer menu and the nav say it in a few words. */
export function usePhonePlaceState(enabled = true): PhonePlaceState {
const { state } = useStore();
@@ -24,18 +43,7 @@ export function usePhonePlaceState(enabled = true): PhonePlaceState {
useEffect(() => {
if (here || !enabled) return;
let alive = true;
- void readSessionState().then(async (session) => {
- const config: unknown = await api("/api/config").catch(() => null);
- const codes = readMembership(config).pairingCodes;
- if (!isOwnerOrAdmin(session) && !(session.kind === "session" && session.team)) {
- if (alive) setServer({ kind: codes ? "chat-only" : "portal" });
- return;
- }
- if (!codes) { if (alive) setServer({ kind: "portal" }); return; }
- const body = await api("/api/auth/sessions").catch(() => null) as { sessions?: unknown[]; current?: string } | null;
- const count = Array.isArray(body?.sessions) ? body.sessions.length - (body?.current ? 1 : 0) : 0;
- if (alive) setServer(count > 0 ? { kind: "paired", count, connected: false } : { kind: "none" });
- }).catch(() => { if (alive) setServer({ kind: "none" }); });
+ void serverPhoneState().then((next) => { if (alive) setServer(next); });
return () => { alive = false; };
}, [here, enabled]);
if (policy?.remoteAccess === false) return { kind: "managed", organization: policy.organizationName };
diff --git a/src/components/settings/settings-requests.dom.test.ts b/src/components/settings/settings-requests.dom.test.ts
new file mode 100644
index 0000000000..47ef1429a2
--- /dev/null
+++ b/src/components/settings/settings-requests.dom.test.ts
@@ -0,0 +1,111 @@
+// @vitest-environment happy-dom
+// The real provider, its live stream and the real Settings window in a browser tab on a server (no desktop bridge), signed
+// in as an admin, with every request counted by path.
+import { createElement } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import { forgetSharedSession } from "@/lib/session-reuse";
+import { readSharedSessionState } from "@/lib/shared-session";
+import type { Action, AppState } from "@/state/store";
+
+class FixtureEventSource {
+ static opened: FixtureEventSource[] = [];
+ onopen: (() => void) | null = null;
+ onerror: (() => void) | null = null;
+ onmessage: ((event: { data: string; lastEventId?: string }) => void) | null = null;
+ constructor(readonly url: string) { FixtureEventSource.opened.push(this); }
+ close() {}
+ send(frame: object, id?: string) { this.onmessage?.({ data: JSON.stringify(frame), lastEventId: id }); }
+}
+
+const CONFIG = {
+ composio: { configured: false }, box: { configured: false }, vps: { configured: false, sshAlias: "" },
+ rooms: { turnTimeoutMinutes: 10 }, localVm: { mode: "shared", maxInstances: 1 },
+ profile: { name: "Ada", email: "[email protected]" }, features: { savedSteps: false },
+ onboarding: { completedAt: "2026-01-01", version: 1, reelSeen: true, hintsSeen: [] },
+ edition: { edition: "community", features: [] }, browserProfiles: [], managedPolicy: null,
+ signIn: { admins: [], members: [] }, membership: { authority: "local", pairingCodes: true },
+};
+const SESSION = { kind: "session", id: "s1", label: "Chrome on Mac", email: "[email protected]", scopes: ["admin", "client"], expiresAt: 0 };
+const answers: Record<string, unknown> = {
+ "/api/instances": { instances: [] },
+ "/api/config": CONFIG,
+ "/api/auth/session": SESSION,
+ "/api/auth/sessions": { sessions: [{ id: "s1" }], current: "s1" },
+ "/api/routines": { routines: [], runs: [] },
+ "/api/webhooks": { webhooks: [], attempts: [] },
+ "/api/bots": { bots: [], groups: [] },
+};
+
+const requests: string[] = [];
+const gets = (path: string) => requests.filter((request) => request === `GET ${path}`).length;
+const { StoreProvider, useStore, api } = await import("@/state/store");
+const { useViewerEmail } = await import("@/lib/default-bot");
+const { SettingsModal } = await import("../SettingsModal");
+
+let seen!: AppState;
+let dispatch!: (action: Action) => void;
+function Probe() {
+ ({ state: seen, dispatch } = useStore());
+ useViewerEmail(); // the sidebar asks who is signed in long before Settings opens
+ return seen.appSettingsOpen ? createElement(SettingsModal) : null;
+}
+let root: Root;
+const task = () => new Promise((resolve) => setTimeout(resolve, 0));
+const settle = async () => { for (let i = 0; i < 20; i++) await task(); };
+
+beforeAll(async () => {
+ vi.stubGlobal("EventSource", FixtureEventSource);
+ vi.stubGlobal("fetch", (input: string | URL | Request, init?: RequestInit) => {
+ const path = String(input instanceof Request ? input.url : input).replace(/^https?:\/\/[^/]+/, "").replace(/\?.*$/, "");
+ requests.push(`${init?.method ?? "GET"} ${path}`);
+ return Promise.resolve(new Response(JSON.stringify(answers[path] ?? {})));
+ });
+ const container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ flushSync(() => root.render(createElement(StoreProvider, null, createElement(Probe))));
+ await settle();
+ FixtureEventSource.opened[0]!.send({ kind: "hello", resumed: false, cursor: "run:0" });
+ await settle();
+});
+afterAll(() => {
+ root.unmount();
+ vi.unstubAllGlobals();
+});
+
+const open = async () => {
+ forgetSharedSession();
+ requests.length = 0;
+ flushSync(() => dispatch({ type: "toggleAppSettings", open: true, section: "overview" }));
+ await settle();
+ expect(document.querySelector("[data-settings-page-body='overview']")).not.toBeNull();
+};
+const close = async () => {
+ flushSync(() => dispatch({ type: "toggleAppSettings", open: false }));
+ await settle();
+};
+
+describe("opening Settings on Overview", () => {
+ it("asks for the session once, and once each for what the phone row needs", async () => {
+ expect(seen.config, "the store holds the config before Settings opens").not.toBeNull();
+ await open();
+ expect(gets("/api/auth/session")).toBe(1);
+ expect(gets("/api/auth/sessions")).toBe(1);
+ expect(gets("/api/config")).toBe(1);
+ expect(document.querySelector("[data-glance='phone']")?.textContent).toContain("Not set up");
+ await close();
+ });
+
+ it("asks again after a sign-out, never serving the session kept from before it", async () => {
+ await readSharedSessionState();
+ requests.length = 0;
+ await readSharedSessionState();
+ expect(gets("/api/auth/session"), "kept for the moment").toBe(0);
+ await api("/api/auth/logout", { method: "POST" });
+ answers["/api/auth/session"] = { kind: "session", id: "s2", label: "Chrome on Mac", email: "[email protected]", scopes: ["client"], expiresAt: 0 };
+ expect(await readSharedSessionState()).toMatchObject({ id: "s2", scopes: ["client"] });
+ expect(gets("/api/auth/session")).toBe(1);
+ });
+});
diff --git a/src/lib/session-ended.ts b/src/lib/session-ended.ts
index 26fdd30f44..1bd94c8c5a 100644
--- a/src/lib/session-ended.ts
+++ b/src/lib/session-ended.ts
@@ -1,5 +1,6 @@
import { useSyncExternalStore } from "react";
import { readSessionState } from "./session";
+import { forgetSharedSession } from "./session-reuse";
export const SESSION_ENDED_REASON = "Your session ended. Pair this device again to keep using it.";
const ENDED_KEY = "omb.session-ended";
@@ -10,6 +11,7 @@ const listeners = new Set<() => void>();
/** A request was refused (401/403): asks the server once whether this device is still signed in. */
export function noteRefusedRequest(): void {
+ forgetSharedSession();
if (ended || checking) return;
checking = readSessionState().then((state) => {
if (state.kind !== "unauthenticated") return;
diff --git a/src/lib/session-reuse.test.ts b/src/lib/session-reuse.test.ts
new file mode 100644
index 0000000000..3b7b0f97fb
--- /dev/null
+++ b/src/lib/session-reuse.test.ts
@@ -0,0 +1,127 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { pairWithCode, verifyEmailSignIn, type SessionState } from "./session";
+import { forgetSharedSession, SESSION_REUSE_MS, sharedSessionRead } from "./session-reuse";
+import { noteRefusedRequest, sessionCheck } from "./session-ended";
+import { api } from "@/state/api";
+
+const admin: SessionState = { kind: "session", id: "s1", label: "", scopes: ["admin", "client"], expiresAt: 0 };
+const member: SessionState = { kind: "session", id: "s1", label: "", scopes: ["client"], expiresAt: 0 };
+let answer: SessionState = admin;
+let reads = 0;
+const read = () => { reads += 1; return Promise.resolve(answer); };
+const shared = () => sharedSessionRead(read);
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ forgetSharedSession();
+ answer = admin;
+ reads = 0;
+});
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe("the shared session read", () => {
+ it("gives readers that ask together one request", async () => {
+ expect(await Promise.all([shared(), shared(), shared()])).toEqual([admin, admin, admin]);
+ expect(reads).toBe(1);
+ });
+
+ it("serves the answer for a few seconds, then asks again", async () => {
+ await shared();
+ vi.advanceTimersByTime(SESSION_REUSE_MS - 1);
+ answer = member;
+ expect(await shared()).toBe(admin);
+ expect(reads).toBe(1);
+ vi.advanceTimersByTime(1);
+ expect(await shared()).toBe(member);
+ expect(reads).toBe(2);
+ });
+
+ it("asks again when the clock went back", async () => {
+ await shared();
+ vi.setSystemTime(Date.now() - 60_000);
+ await shared();
+ expect(reads).toBe(2);
+ });
+
+ it("keeps no refusal and no failed read", async () => {
+ answer = { kind: "unauthenticated", error: "401" };
+ await shared();
+ answer = { kind: "unreachable", error: "offline" };
+ await shared();
+ answer = admin;
+ expect(await shared()).toBe(admin);
+ expect(reads).toBe(3);
+ });
+
+ it("neither keeps nor shares a read that was under way when the session changed", async () => {
+ let finish!: (state: SessionState) => void;
+ const early = sharedSessionRead(() => { reads += 1; return new Promise((resolve) => { finish = resolve; }); });
+ forgetSharedSession();
+ answer = member;
+ expect(await shared(), "a reader after the change starts its own request").toBe(member);
+ finish(admin);
+ expect(await early).toBe(admin);
+ expect(await shared(), "the early answer was not kept over the later one").toBe(member);
+ expect(reads).toBe(2);
+ });
+
+ it("asks again after a rejected read", async () => {
+ await expect(sharedSessionRead(() => Promise.reject(new Error("down")))).rejects.toThrow("down");
+ expect(await shared()).toBe(admin);
+ expect(reads).toBe(1);
+ });
+});
+
+describe("what drops the kept session", () => {
+ const respond = (status: number) => vi.stubGlobal("fetch", () => Promise.resolve(new Response("{}", { status })));
+ const dropped = async () => { const before = reads; await shared(); return reads === before + 1; };
+
+ it("a sign-in by code or by email, whether or not it succeeds", async () => {
+ for (const status of [200, 403]) {
+ respond(status);
+ await shared();
+ await pairWithCode({ code: "c", label: "l" });
+ expect(await dropped()).toBe(true);
+ await verifyEmailSignIn({ email: "[email protected]", code: "1", label: "l" });
+ expect(await dropped()).toBe(true);
+ }
+ });
+
+ it("any write through api(), such as a sign-out or a removed device, and not a read", async () => {
+ respond(200);
+ await shared();
+ await api("/api/bots");
+ expect(await dropped()).toBe(false);
+ await api("/api/auth/logout", { method: "POST" });
+ expect(await dropped()).toBe(true);
+ await api("/api/auth/sessions/s9", { method: "DELETE" });
+ expect(await dropped()).toBe(true);
+ await api("/api/config", { method: "PUT", body: JSON.stringify({ signIn: { admins: [], members: [] } }) });
+ expect(await dropped()).toBe(true);
+ });
+
+ it("a write that never got an answer", async () => {
+ vi.stubGlobal("fetch", () => Promise.reject(new TypeError("Failed to fetch")));
+ await shared();
+ await expect(api("/api/auth/logout", { method: "POST" })).rejects.toThrow();
+ expect(await dropped()).toBe(true);
+ });
+
+ it("a refused request, and the check of whether the session ended", async () => {
+ for (const status of [401, 403]) {
+ respond(status);
+ await shared();
+ await expect(api("/api/bots")).rejects.toThrow();
+ await sessionCheck();
+ expect(await dropped()).toBe(true);
+ }
+ respond(200);
+ await shared();
+ noteRefusedRequest();
+ await sessionCheck();
+ expect(await dropped()).toBe(true);
+ });
+});
diff --git a/src/lib/session-reuse.ts b/src/lib/session-reuse.ts
new file mode 100644
index 0000000000..3f1f831f30
--- /dev/null
+++ b/src/lib/session-reuse.ts
@@ -0,0 +1,44 @@
+import type { SessionState } from "./session";
+
+/** How long an answer serves the readers that come after it. Long enough for one screen's parts to mount, short enough
+ * that nobody acts on an old answer. */
+export const SESSION_REUSE_MS = 3_000;
+
+let generation = 0;
+let kept: { state: SessionState; at: number } | null = null;
+let reading: Promise<SessionState> | null = null;
+let watching = false;
+
+/** Whatever may have changed who is signed in or what they may do calls this: the kept answer is dropped, and a read
+ * under way is neither kept nor joined by later readers. */
+export function forgetSharedSession(): void {
+ generation += 1;
+ kept = null;
+ reading = null;
+}
+
+function watchDesktopAccount(): void {
+ if (watching || typeof window === "undefined") return;
+ watching = true;
+ window.ogb?.cloudAccount?.onState?.(forgetSharedSession);
+}
+
+/** One session read for readers that ask together: they share the request under way, and its answer serves those that
+ * ask within SESSION_REUSE_MS. Only a session or this computer's own trust is kept; a refusal or a failed read is asked
+ * again by the next reader. */
+export function sharedSessionRead(read: () => Promise<SessionState>, now: () => number = Date.now): Promise<SessionState> {
+ watchDesktopAccount();
+ if (kept) {
+ const age = now() - kept.at;
+ if (age >= 0 && age < SESSION_REUSE_MS) return Promise.resolve(kept.state);
+ kept = null;
+ }
+ if (reading) return reading;
+ const asked = generation;
+ const request = read().then((state) => {
+ if (asked === generation && (state.kind === "session" || state.kind === "loopback")) kept = { state, at: now() };
+ return state;
+ }).finally(() => { if (reading === request) reading = null; });
+ reading = request;
+ return request;
+}
diff --git a/src/lib/session.ts b/src/lib/session.ts
index d87dea0fb8..f8136590d2 100644
--- a/src/lib/session.ts
+++ b/src/lib/session.ts
@@ -1,5 +1,6 @@
import { t } from "./i18n";
import { serverErrorText } from "./server-error";
+import { forgetSharedSession } from "./session-reuse";
export interface EnvironmentDescriptor {
environmentId: string;
@@ -148,6 +149,8 @@ export async function pairWithCode(
});
} catch (error) {
return { ok: false, error: t("pair.unreachable", { error: error instanceof Error ? error.message : String(error) }) };
+ } finally {
+ forgetSharedSession();
}
const body: unknown = await res.json().catch(() => ({}));
if (res.ok) return { ok: true };
@@ -185,6 +188,8 @@ async function postAuth(path: string, body: Record<string, unknown>, fetchImpl:
res = await fetchImpl(path, { method: "POST", credentials: "same-origin", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
} catch (error) {
return { ok: false, error: t("pair.unreachable", { error: error instanceof Error ? error.message : String(error) }) };
+ } finally {
+ forgetSharedSession();
}
const parsed: unknown = await res.json().catch(() => ({}));
if (res.ok) return { ok: true };
diff --git a/src/lib/shared-session.ts b/src/lib/shared-session.ts
new file mode 100644
index 0000000000..c13e1a277e
--- /dev/null
+++ b/src/lib/shared-session.ts
@@ -0,0 +1,9 @@
+import { readSessionState, type SessionState } from "./session";
+import { sharedSessionRead } from "./session-reuse";
+
+/** The session for a screen that shows who is here and what they may open: its parts share one request and the answer
+ * of the last few seconds. A decision that must hold right now, such as whether this device is still signed in, asks
+ * readSessionState. */
+export function readSharedSessionState(): Promise<SessionState> {
+ return sharedSessionRead(() => readSessionState());
+}
diff --git a/src/lib/use-owner-or-admin.ts b/src/lib/use-owner-or-admin.ts
index 401c2f321c..71cc53a733 100644
--- a/src/lib/use-owner-or-admin.ts
+++ b/src/lib/use-owner-or-admin.ts
@@ -1,6 +1,7 @@
import { useEffect, useState } from "react";
-import { isOwnerOrAdmin, readSessionState } from "./session";
+import { isOwnerOrAdmin } from "./session";
+import { readSharedSessionState } from "./shared-session";
const RETRY_MS = 10_000;
let known: boolean | null = null;
@@ -19,7 +20,7 @@ function lookUp(): void {
return;
}
looking = true;
- void readSessionState()
+ void readSharedSessionState()
.then((state) => state.kind === "unreachable" ? null : isOwnerOrAdmin(state), () => null)
.then((allowed) => {
looking = false;
diff --git a/src/state/api.ts b/src/state/api.ts
index 3a8989531f..6f7312d02e 100644
--- a/src/state/api.ts
+++ b/src/state/api.ts
@@ -4,6 +4,7 @@ import { asleepAnswer, BACKGROUND_HEADER, cloudAsleep, markCloudAsleep, markClou
import { lacksAdminScope } from "../lib/admin-scope";
import { isBotLimitRefusal, isBotPausedRefusal, showBotLimit } from "../lib/bot-limit";
import { noteRefusedRequest } from "../lib/session-ended";
+import { forgetSharedSession } from "../lib/session-reuse";
import { serverErrorText } from "../lib/server-error";
export class ApiError extends Error {
@@ -34,6 +35,10 @@ export async function api<T = any>(path: string, init?: ApiInit): Promise<T> {
}
const sent = new Headers(headers ?? { "content-type": "application/json" });
if (background) sent.set(BACKGROUND_HEADER, "1");
+ // A write, or whatever made the server refuse, may have changed who is signed in or what they may do: no session
+ // answer from before it is served again.
+ const writes = (rest.method ?? "GET").toUpperCase() !== "GET";
+ if (writes) forgetSharedSession();
const res = await fetch(path, {
...rest,
headers: sent,
@@ -42,7 +47,8 @@ export async function api<T = any>(path: string, init?: ApiInit): Promise<T> {
: signal
? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)])
: AbortSignal.timeout(timeoutMs),
- });
+ }).finally(() => { if (writes) forgetSharedSession(); });
+ if (res.status === 401 || res.status === 403) forgetSharedSession();
if (asleepAnswer(res)) markCloudAsleep();
const body = await res.json().catch(() => ({}));
if (!res.ok) {
diff --git a/src/state/config-change-count.test.ts b/src/state/config-change-count.test.ts
new file mode 100644
index 0000000000..67b13a8474
--- /dev/null
+++ b/src/state/config-change-count.test.ts
@@ -0,0 +1,156 @@
+// @vitest-environment happy-dom
+// The real provider and its live stream: how many times a store reader draws when a setting is switched, counting the
+// config frame the server broadcasts, the PATCH answer the row dispatches and the engine list read again after the frame.
+import { createElement } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import type { Action, AppState, ConfigStatus } from "./store";
+
+class FixtureEventSource {
+ static opened: FixtureEventSource[] = [];
+ onopen: (() => void) | null = null;
+ onerror: (() => void) | null = null;
+ onmessage: ((event: { data: string; lastEventId?: string }) => void) | null = null;
+ constructor(readonly url: string) { FixtureEventSource.opened.push(this); }
+ close() {}
+ send(frame: object, id?: string) { this.onmessage?.({ data: JSON.stringify(frame), lastEventId: id }); }
+}
+
+/** What a config frame carries into the store. */
+const framed = (savedSteps: boolean) => ({
+ xai: { configured: false }, anthropic: { configured: true, everyClaudeBot: true }, openai: { configured: false },
+ composio: { configured: false, mode: "hosted" }, box: { configured: false }, vps: { configured: false, sshAlias: "" },
+ rooms: { turnTimeoutMinutes: 10 }, mcp: { callTimeoutMinutes: 5 }, threads: { maxConcurrentPerBot: 3 },
+ localVm: { mode: "shared", maxInstances: 1, idleTimeoutMinutes: 30, preserveInstalledApps: false },
+ profile: { name: "Ada", email: "[email protected]", aboutMe: "" }, language: "", everyBotRules: "",
+ features: { skillAuthoring: true, showToolCalls: false, browser: true, savedSteps },
+ onboarding: { completedAt: "2026-01-01", version: 1, reelSeen: true, hintsSeen: ["a", "b"] },
+ edition: { edition: "community", features: [] }, browserProfiles: [{ id: "work", name: "Work" }],
+ budgets: {}, billing: { currency: "USD", prices: {} }, pausedBots: [], heldBots: [],
+});
+/** What GET and PATCH /api/config answer: the same, and the sections a frame leaves out. */
+const answered = (savedSteps: boolean) => ({
+ ...framed(savedSteps), computerName: "Studio", newBots: {}, signIn: { admins: [], members: [] },
+ membership: { authority: "local", pairingCodes: true }, decisions: { retentionDays: 30 }, safetyFloor: { enabled: true },
+});
+const INSTANCES = [{ instanceId: "codex", driverKind: "codex", displayName: "Codex", enabled: true, snapshot: { state: "available", authenticated: true, models: [{ id: "m", name: "M" }] } }];
+
+const json = (body: unknown) => Promise.resolve(new Response(JSON.stringify(body)));
+let config: unknown = answered(false);
+let instanceReads = 0;
+const { StoreProvider, useStore } = await import("./store");
+
+let renders = 0;
+let seen!: AppState;
+let dispatch!: (action: Action) => void;
+function Probe() {
+ ({ state: seen, dispatch } = useStore());
+ renders++;
+ return null;
+}
+let root: Root;
+const task = () => new Promise((resolve) => setTimeout(resolve, 0));
+const settle = async () => { for (let i = 0; i < 10; i++) await task(); };
+const paints: FrameRequestCallback[] = [];
+const paint = async () => {
+ for (const callback of paints.splice(0)) callback(performance.now());
+ await settle();
+};
+const stream = () => FixtureEventSource.opened[0]!;
+let cursor = 0;
+const configFrame = (body: object) => stream().send({ kind: "config", ...body, seq: ++cursor }, `run:${cursor}`);
+/** One switch flipped: the frame is broadcast before the PATCH answers, the row dispatches the answer, and the frame
+ * has the engine list read again. Returns how many times the reader drew. */
+async function flip(frameBody: object, answer: object): Promise<number> {
+ const before = renders, reads = instanceReads;
+ configFrame(frameBody);
+ await paint();
+ flushSync(() => dispatch({ type: "configStatus", config: structuredClone(answer) as ConfigStatus }));
+ await paint();
+ expect(instanceReads, "the frame has the engine list read again").toBe(reads + 1);
+ return renders - before;
+}
+
+beforeAll(async () => {
+ vi.stubGlobal("EventSource", FixtureEventSource);
+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => paints.push(callback));
+ vi.stubGlobal("cancelAnimationFrame", () => {});
+ vi.stubGlobal("fetch", (input: string) => {
+ const path = String(input).replace(/\?.*$/, "");
+ if (path === "/api/instances") { instanceReads++; return json({ instances: structuredClone(INSTANCES) }); }
+ if (path === "/api/config") return json(config);
+ if (path === "/api/bots") return json({ bots: [], groups: [] });
+ if (path === "/api/routines") return json({ routines: [], runs: [] });
+ if (path === "/api/webhooks") return json({ webhooks: [], attempts: [] });
+ return json({});
+ });
+ const container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ flushSync(() => root.render(createElement(StoreProvider, null, createElement(Probe))));
+ await settle();
+ stream().send({ kind: "hello", resumed: false, cursor: "run:0" });
+ await settle();
+ await paint();
+});
+afterAll(() => {
+ root.unmount();
+ vi.unstubAllGlobals();
+});
+
+describe("a switched setting reaches the store's readers", () => {
+ it("starts from the config and the engines the server answered", () => {
+ expect(seen.config).toEqual(answered(false));
+ expect(seen.instances).toEqual(INSTANCES);
+ });
+
+ it("draws nothing for a PATCH answer that says what the store already holds", async () => {
+ const before = renders, held = seen;
+ flushSync(() => dispatch({ type: "configStatus", config: structuredClone(answered(false)) as unknown as ConfigStatus }));
+ await paint();
+ expect(renders - before).toBe(0);
+ expect(seen).toBe(held);
+ });
+
+ it("draws once for the frame and once for the answer, and not again for the same engine list", async () => {
+ config = answered(true);
+ const counted = await flip(framed(true), answered(true));
+ expect(seen.config).toEqual(answered(true));
+ expect(counted).toBe(2);
+ });
+
+ it("draws once for a frame that repeats the answer, as it drops the sections a frame leaves out", async () => {
+ const before = renders, reads = instanceReads;
+ configFrame(framed(true));
+ await paint();
+ expect(instanceReads).toBe(reads + 1);
+ expect(seen.config).toEqual(framed(true));
+ expect(renders - before).toBe(1);
+ });
+
+ it("draws once when the answer says no more than the frame did", async () => {
+ config = framed(false);
+ const counted = await flip(framed(false), framed(false));
+ expect(seen.config?.features?.savedSteps).toBe(false);
+ expect(counted).toBe(1);
+ });
+
+ it("draws nothing for a config frame that repeats the last one, nor for the engine list read after it", async () => {
+ const before = renders, held = seen, reads = instanceReads;
+ configFrame(framed(false));
+ await paint();
+ expect(instanceReads).toBe(reads + 1);
+ expect(renders - before).toBe(0);
+ expect(seen).toBe(held);
+ });
+
+ it("still takes a changed engine list", async () => {
+ const before = renders;
+ INSTANCES[0]!.snapshot.models.push({ id: "n", name: "N" });
+ configFrame(framed(false));
+ await paint();
+ expect(seen.instances).toEqual(INSTANCES);
+ expect(renders - before).toBe(1);
+ });
+});
diff --git a/src/state/same-json.test.ts b/src/state/same-json.test.ts
new file mode 100644
index 0000000000..e9b35500cb
--- /dev/null
+++ b/src/state/same-json.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from "vitest";
+import { sameJson } from "./same-json";
+
+describe("sameJson", () => {
+ it("takes the same data in another key order, with undefined keys left out, as the same", () => {
+ expect(sameJson({ a: 1, b: { c: [1, { d: null }], e: "x" } }, { b: { e: "x", c: [1, { d: null }] }, a: 1, gone: undefined })).toBe(true);
+ expect(sameJson({ gone: undefined }, {})).toBe(true);
+ expect(sameJson([], [])).toBe(true);
+ expect(sameJson(null, null)).toBe(true);
+ });
+
+ it("tells any difference in a value, a key or a list apart", () => {
+ expect(sameJson({ a: 1 }, { a: 2 })).toBe(false);
+ expect(sameJson({ a: 1 }, { a: 1, b: false })).toBe(false);
+ expect(sameJson({ a: 1, b: null }, { a: 1 })).toBe(false);
+ expect(sameJson({ a: undefined, b: 1 }, { a: 1, b: undefined })).toBe(false);
+ expect(sameJson([1, 2], [2, 1])).toBe(false);
+ expect(sameJson([1], [1, 2])).toBe(false);
+ expect(sameJson([], {})).toBe(false);
+ expect(sameJson({ 0: "a", length: 1 }, ["a"])).toBe(false);
+ expect(sameJson(null, {})).toBe(false);
+ expect(sameJson("1", 1)).toBe(false);
+ expect(sameJson({ a: { b: [] } }, { a: { b: {} } })).toBe(false);
+ });
+});
diff --git a/src/state/same-json.ts b/src/state/same-json.ts
new file mode 100644
index 0000000000..5f5b4de536
--- /dev/null
+++ b/src/state/same-json.ts
@@ -0,0 +1,20 @@
+/** Whether two values parsed from JSON hold the same data. The order of an object's keys does not count, and a key
+ * holding undefined is the same as no key: JSON would have written neither. */
+export function sameJson(a: unknown, b: unknown): boolean {
+ if (a === b) return true;
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
+ if (Array.isArray(a) || Array.isArray(b)) {
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
+ for (let i = 0; i < a.length; i++) if (!sameJson(a[i], b[i])) return false;
+ return true;
+ }
+ const left = a as Record<string, unknown>, right = b as Record<string, unknown>;
+ let unmatched = 0;
+ for (const key of Object.keys(right)) if (right[key] !== undefined) unmatched++;
+ for (const key of Object.keys(left)) {
+ if (left[key] === undefined) continue;
+ if (right[key] === undefined || !sameJson(left[key], right[key])) return false;
+ unmatched--;
+ }
+ return unmatched === 0;
+}
diff --git a/src/state/store.tsx b/src/state/store.tsx
index 82b9c90d56..3d43540880 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -4,7 +4,7 @@ import { loadOlderPage, MESSAGE_PAGE_SIZE, reduceOlderMessages, reduceTrimHeldMe
export { MESSAGE_PAGE_SIZE } from "./message-history";
import { addForkOptimistic, reduceForkPanel, removeForkOptimistic, runForkEffect, type ForkPanelAction, type ForkPanelState } from "./fork-panel";
import { use, useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
-import { createAppStore } from "./app-store"; import { readOneBot } from "./bot-read"; import { StoreContext, StoreSourceContext } from "./store-context";
+import { createAppStore } from "./app-store"; import { readOneBot } from "./bot-read"; import { sameJson } from "./same-json"; import { forgetSharedSession } from "@/lib/session-reuse"; import { StoreContext, StoreSourceContext } from "./store-context";
import { flushSync } from "react-dom";
import type { BotMovedTo, BotVisibility, CardAnswerer, CloudBackend, ConnectorToolGrant, EffortLevel, InstalledPackageMetadata, LiveCallState, ServerFrame, GroupThreadUsage, ResolvedSender, SteerQueueReason, WireBot, WireGroup, WireTask, OptionCardData as WireOptionCard } from "../../shared/wire"; import type { InstanceEndpointInfo } from "../../shared/claude-endpoint";
import { movesThreadToTop } from "../../shared/wire"; import type { DefaultBotFields } from "../../shared/default-bot";
@@ -1016,7 +1016,7 @@ export function reducer(state: AppState, action: Action): AppState {
case "instances":
return { ...state, instances: action.instances };
case "configStatus":
- return { ...state, config: action.config };
+ return sameJson(state.config, action.config) ? state : { ...state, config: action.config };
case "liveCall":
return { ...state, liveCall: action.call, liveCallVersion: state.liveCallVersion + 1 };
case "liveCallLookup":
@@ -2886,7 +2886,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {
key: "instances",
request: async () => {
const answer = await unlessRefused<{ instances: InstanceInfo[] } | null>("/api/instances", async () => snapshotArrays<{ instances: InstanceInfo[] }>(await api("/api/instances"), "instances"), null);
- return () => { if (answer) rawDispatch({ type: "instances", instances: answer.instances }); };
+ return () => { if (answer && !sameJson(store.getState().instances, answer.instances)) rawDispatch({ type: "instances", instances: answer.instances }); };
},
},
{
@@ -3185,7 +3185,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {
}
case "window-pref": applyWindowPref(frame); break;
case "theme": applyThemeFrame(frame); break; case "apps-catalog": appCatalogAnnounced(); break;
- case "config":
+ case "config": forgetSharedSession();
rawDispatch({
type: "configStatus",
config: configStatusFromFrame(frame as unknown as ConfigStatusFrame),
@@ -3202,10 +3202,10 @@ export function StoreProvider({ children }: { children: ReactNode }) {
}
};
const stopLive = openLiveEvents({
- onOpen: () => rawDispatch({ type: "connected", value: true }),
- onError: () => rawDispatch({ type: "connected", value: false }),
+ onOpen: () => { forgetSharedSession(); rawDispatch({ type: "connected", value: true }); },
+ onError: () => { forgetSharedSession(); rawDispatch({ type: "connected", value: false }); },
onSnapshotRequired: () => {
- store.flushFrames(); // the old stream's waiting frames go first, so forgetLiveTurns() below has the last word
+ forgetSharedSession(); store.flushFrames(); // the old stream's waiting frames go first, so forgetLiveTurns() below has the last word
clearTimeout(hydrationFallback);
publishMissedFrames();
// Frames buffered before a non-resumable stream belong to an abandoned generation, and so do the turns they named.
diff --git a/src/state/team-presence.ts b/src/state/team-presence.ts
index e253ec3d52..9469979a5f 100644
--- a/src/state/team-presence.ts
+++ b/src/state/team-presence.ts
@@ -6,6 +6,7 @@ import { useEffect, useMemo, useRef, useSyncExternalStore } from "react";
import { HERE_REPEAT_MS, PRESENCE_HERE_PATH, type PresenceFrame, type PresenceHereBody } from "../../shared/team-presence";
import type { ServerFrame } from "../../shared/wire";
import { listenLiveFrames } from "@/lib/live-events";
+import { forgetSharedSession } from "@/lib/session-reuse";
import { api } from "./api";
import type { AppState } from "./store";
import { rereadTeamChats } from "./team-chats";
@@ -33,6 +34,7 @@ export function applyPresenceFrame(frame: PresenceFrame): void {
case "thread.presence":
return setThreads(new Map(threads).set(frame.threadId, frame.people));
case "team.people":
+ forgetSharedSession();
reloadTeamPeople();
rereadTeamChats();
}