Skip to content

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

feat(browser): keep signed-in sessions across idle closes and allow never-close timeout

jonathanwxh-cell13e5d88af052
diff --git a/server/app-settings/host.test.ts b/server/app-settings/host.test.ts
index b6dbcf1898..de46f54077 100644
--- a/server/app-settings/host.test.ts
+++ b/server/app-settings/host.test.ts
@@ -584,6 +584,17 @@ describe("every other setting applies at once with Undo, Full access or not", ()
expect(fx.saved).toEqual([{ browserEngine: { egress: { proxy: "socks5://proxy.example:1080" } } }, { browserEngine: { egress: { proxy: "" } } }]);
});
+ it("the browser idle timeout accepts 0 (never) and 1-60 minutes, and rejects out-of-range values", async () => {
+ const fx = fixture();
+ expect((await fx.set("desktops.browserIdleTimeout", "-1")).status).toBe(400);
+ expect((await fx.set("desktops.browserIdleTimeout", "61")).status).toBe(400);
+ const never = await fx.set("desktops.browserIdleTimeout", "0");
+ expect(never.status).toBe(200);
+ expect(fx.saved.at(-1)).toEqual({ browserEngine: { idleTimeoutMinutes: 0 } });
+ expect(await fx.undo()).toEqual({ claimed: true, state: "undone" });
+ expect(fx.saved.at(-1)).toEqual({ browserEngine: { idleTimeoutMinutes: null } });
+ });
+
it("a bot's library skills are set from the full list, and Undo gives back the earlier list", async () => {
const fx = fixture();
await fx.set("bots.skills", JSON.stringify({ botId: "clive", skills: [] }));
diff --git a/server/app-settings/registry-config.ts b/server/app-settings/registry-config.ts
index 029b2cb13a..546dfddf60 100644
--- a/server/app-settings/registry-config.ts
+++ b/server/app-settings/registry-config.ts
@@ -143,6 +143,12 @@ export function configEntries(deps: Pick<RegistryDeps, "cfg" | "saveConfig" | "b
synonyms: ["browser engine", "chrome", "new browser", "agent-browser"], value: z.enum(["agent-browser", "chrome"]), allowed: "agent-browser or chrome",
current: () => cfg().browserEngine?.engine ?? "agent-browser", patch: (engine) => ({ browserEngine: { engine } }),
}),
+ section({
+ id: "desktops.browserIdleTimeout", label: "Close unused browsers after", help: "Minutes before an unused built-in browser closes; 0 keeps browsers open to preserve site logins.", where: "browser",
+ synonyms: ["idle timeout", "keep signed in", "browser idle", "never close", "cookies", "login"], value: z.number().int().min(0).max(60).nullable(), allowed: "0 (never), 1 to 60 minutes, or null to restore default",
+ current: () => cfg().browserEngine?.idleTimeoutMinutes ?? null, patch: (idleTimeoutMinutes) => ({ browserEngine: { idleTimeoutMinutes } }),
+ says: (minutes) => (minutes === null ? "Restore the default unused browser close timeout" : minutes === 0 ? "Keep unused built-in browsers open to preserve site logins" : `Close unused built-in browsers after ${minutes} minute${minutes === 1 ? "" : "s"}`),
+ }),
feature("desktops.savedSteps", "Saved steps", "Bots may repeat saved browser steps without AI.", "saved-steps", ["saved steps", "repeat", "without ai"], "savedSteps", true,
"Let bots repeat saved steps without AI", "Turn off saved steps"),
section({
diff --git a/server/browser-lifecycle-cleanup.test.ts b/server/browser-lifecycle-cleanup.test.ts
index a98b7416ca..9d4a07ef2d 100644
--- a/server/browser-lifecycle-cleanup.test.ts
+++ b/server/browser-lifecycle-cleanup.test.ts
@@ -360,10 +360,44 @@ describe("closing this data dir's browsers nothing uses", () => {
info.mockRestore();
});
- it("closes an unused browser after ten minutes, three on a Cloud home, unless config.json says otherwise", () => {
+ it("closes an unused browser after ten minutes, three on a Cloud home, 0 for never, unless config.json says otherwise", () => {
expect(browserIdleMs({})).toBe(10 * 60_000);
expect(browserIdleMs({}, { cloudHome: true })).toBe(3 * 60_000);
+ expect(browserIdleMs({ browserEngine: { idleTimeoutMinutes: 0 } })).toBe(0);
+ expect(browserIdleMs({ browserEngine: { idleTimeoutMinutes: 0 } }, { cloudHome: true })).toBe(0);
expect(browserIdleMs({ browserEngine: { idleTimeoutMinutes: 2 } })).toBe(2 * 60_000);
expect(browserIdleMs({ browserEngine: { idleTimeoutMinutes: 20 } }, { cloudHome: true })).toBe(20 * 60_000);
});
+
+ it("pings live sessions on keepAliveInterval when idle closing is turned off", async () => {
+ const info = vi.spyOn(console, "info").mockImplementation(() => {});
+ const homeDir = mkdtempSync(join(tmpdir(), "openmaus-sweep-keepalive-"));
+ folders.push(homeDir);
+ const runtimeDir = join(homeDir, "rt");
+ mkdirSync(join(runtimeDir, "agent-browser"), { recursive: true });
+ writeFileSync(join(runtimeDir, "agent-browser", "bot-keep.pid"), "123\n");
+ vi.stubEnv("HOME", homeDir);
+ vi.stubEnv("XDG_RUNTIME_DIR", runtimeDir);
+ vi.mocked(runningBrowserSessionNames).mockResolvedValueOnce(["bot-keep"]);
+ vi.mocked(runningBrowserSessionNames).mockResolvedValueOnce(["bot-keep"]);
+ const keepAlive = vi.fn(async () => {});
+ let now = 1_000;
+ const running = new BrowserSweep({
+ engine: () => "/bin/agent-browser",
+ owns: (session) => session === "bot-keep",
+ live: (session) => session === "bot-keep",
+ held: () => false,
+ closeIdle: async () => false,
+ keepAlive,
+ keepAliveIntervalMs: 500,
+ now: () => now,
+ });
+ await running.sweep();
+ expect(keepAlive).not.toHaveBeenCalled();
+ now += 600;
+ await running.sweep();
+ expect(keepAlive).toHaveBeenCalledExactlyOnceWith("bot-keep");
+ vi.unstubAllEnvs();
+ info.mockRestore();
+ });
});
diff --git a/server/browser-lifecycle-cleanup.ts b/server/browser-lifecycle-cleanup.ts
index b16f9874e6..f51766384a 100644
--- a/server/browser-lifecycle-cleanup.ts
+++ b/server/browser-lifecycle-cleanup.ts
@@ -376,7 +376,7 @@ export class BrowserCleanupCoordinator {
}
}
-/** Defaults for config.json's browserEngine.idleTimeoutMinutes (1-60); agent-browser's own backstop closes an idle daemon after an hour. */
+/** Defaults for config.json's browserEngine.idleTimeoutMinutes (0-60; 0 keeps browsers open, while agent-browser's own backstop closes an idle daemon after an hour). */
export const DEFAULT_BROWSER_IDLE_MINUTES = 10;
export const CLOUD_HOME_BROWSER_IDLE_MINUTES = 3;
@@ -401,6 +401,10 @@ export class BrowserSweep {
readonly #live: (session: string) => boolean;
readonly #held: (session: string) => boolean;
readonly #closeIdle: (session: string) => Promise<boolean>;
+ readonly #keepAlive?: (session: string) => Promise<void>;
+ readonly #keepAliveIntervalMs: number;
+ readonly #now: () => number;
+ readonly #lastKeepAlive = new Map<string, number>();
readonly #intervalMs: number;
readonly #warned = new Set<string>();
#timer: ReturnType<typeof setInterval> | undefined;
@@ -414,6 +418,10 @@ export class BrowserSweep {
/** A turn holds it until it finishes: never closed while one does. */
held: (session: string) => boolean;
closeIdle: (session: string) => Promise<boolean>;
+ /** Called periodically on live unclosed sessions so agent-browser's built-in 1h idle timer stays reset when idle-close is off. */
+ keepAlive?: (session: string) => Promise<void>;
+ keepAliveIntervalMs?: number;
+ now?: () => number;
intervalMs?: number;
}) {
this.#engine = options.engine;
@@ -421,6 +429,9 @@ export class BrowserSweep {
this.#live = options.live;
this.#held = options.held;
this.#closeIdle = options.closeIdle;
+ this.#keepAlive = options.keepAlive;
+ this.#keepAliveIntervalMs = options.keepAliveIntervalMs ?? 25 * 60_000;
+ this.#now = options.now ?? Date.now;
this.#intervalMs = options.intervalMs ?? 60_000;
}
@@ -457,11 +468,30 @@ export class BrowserSweep {
}
}
this.#hadDaemons = owned !== null;
+ const ownedSet = new Set(owned ?? []);
+ for (const session of this.#lastKeepAlive.keys()) {
+ if (!ownedSet.has(session) || !this.#live(session)) this.#lastKeepAlive.delete(session);
+ }
for (const session of owned ?? []) {
// Read per browser, after the awaits before it: a turn may have started using it.
- if (this.#held(session)) continue;
+ if (this.#held(session)) {
+ if (this.#keepAlive && this.#live(session)) this.#lastKeepAlive.set(session, this.#now());
+ continue;
+ }
if (this.#live(session)) {
- if (await this.#closeIdle(session)) console.info(`browser ${session}: closed after it sat unused`);
+ if (await this.#closeIdle(session)) {
+ this.#lastKeepAlive.delete(session);
+ console.info(`browser ${session}: closed after it sat unused`);
+ } else if (this.#keepAlive) {
+ const now = this.#now();
+ const last = this.#lastKeepAlive.get(session);
+ if (last === undefined) {
+ this.#lastKeepAlive.set(session, now);
+ } else if (now - last >= this.#keepAliveIntervalMs) {
+ this.#lastKeepAlive.set(session, now);
+ await this.#keepAlive(session);
+ }
+ }
continue;
}
const closed = await closeBrowserSession(binaryPath, browserRuntimeEnv({ AGENT_BROWSER_SESSION: session }));
diff --git a/server/browser-room.test.ts b/server/browser-room.test.ts
index c86d76f88a..9608257d26 100644
--- a/server/browser-room.test.ts
+++ b/server/browser-room.test.ts
@@ -154,6 +154,7 @@ describe("which browser a bot waiting for a slot may close", () => {
expect(spareForRoom(idle(179_999), { holds: true, idleMs: 180_000 })).toBeNull();
expect(spareForRoom(idle(180_000), { holds: true, idleMs: 180_000 })).toBe(180_000);
expect(spareForRoom(idle(600_000, false), { holds: true, idleMs: 180_000 })).toBeNull();
+ expect(spareForRoom(idle(600_000), { holds: true, idleMs: 0 })).toBeNull();
});
it("none a call, a person or a view has", () => {
diff --git a/server/browser-room.ts b/server/browser-room.ts
index 7a06e3d5a4..a611f4242b 100644
--- a/server/browser-room.ts
+++ b/server/browser-room.ts
@@ -65,7 +65,7 @@ export function defaultBrowserRoomSize(env: NodeJS.ProcessEnv = process.env): nu
export function spareForRoom(spare: { idleMs: number; savesSignIns: boolean } | null, turn: { holds: boolean; idleMs: number }): number | null {
if (spare === null) return null;
if (!turn.holds) return spare.idleMs;
- return spare.savesSignIns && spare.idleMs >= turn.idleMs ? spare.idleMs : null;
+ return turn.idleMs > 0 && spare.savesSignIns && spare.idleMs >= turn.idleMs ? spare.idleMs : null;
}
export interface BrowserRoomOptions {
diff --git a/server/browser/chrome/cookie-jar.ts b/server/browser/chrome/cookie-jar.ts
new file mode 100644
index 0000000000..273da1e404
--- /dev/null
+++ b/server/browser/chrome/cookie-jar.ts
@@ -0,0 +1,162 @@
+import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
+import { mkdirSync, readFileSync, rmSync } from "node:fs";
+import { dirname, join } from "node:path";
+
+import { writeFileAtomic } from "../../atomic.ts";
+import { browserEngineEncryptionKey } from "../../browser-engine.ts";
+import type { CdpBrowser } from "../cdp/browser.ts";
+import type { SourceCookie, WritableCookie } from "../cookies/policy.ts";
+import { cdpSink } from "../cookies/sinks.ts";
+import { profileDir } from "./profile.ts";
+
+const JAR_FILE = "omb-cookies.enc";
+const CDP_TIMEOUT_MS = 2_000;
+
+export interface StoredCookie {
+ name: string;
+ value: string;
+ domain: string;
+ path: string;
+ expires?: number;
+ httpOnly?: boolean;
+ secure?: boolean;
+ session?: boolean;
+ sameSite?: string;
+ partitionKey?: unknown;
+}
+
+interface EncryptedJar {
+ v: 1;
+ iv: string;
+ tag: string;
+ data: string;
+}
+
+function jarKey(dataDir: string): Buffer {
+ return Buffer.from(browserEngineEncryptionKey(dataDir), "hex");
+}
+
+function jarPath(dataDir: string, profileKey: string): string {
+ return join(profileDir(dataDir, profileKey), JAR_FILE);
+}
+
+function cookieIdentity(cookie: Pick<StoredCookie, "name" | "domain" | "path">): string {
+ return `${cookie.name}\0${cookie.domain}\0${cookie.path || "/"}`;
+}
+
+function isLivePersistableCookie(cookie: StoredCookie, nowSec: number): boolean {
+ if (!cookie.name || !cookie.domain || cookie.partitionKey != null) return false;
+ if (cookie.session !== true && typeof cookie.expires === "number" && cookie.expires > 0 && cookie.expires <= nowSec) {
+ return false;
+ }
+ return true;
+}
+
+function normalizeSameSite(value: string | undefined, secure: boolean): SourceCookie["sameSite"] {
+ if (value === "Strict") return "strict";
+ if (value === "Lax") return "lax";
+ if (value === "None" && secure) return "no_restriction";
+ return "unspecified";
+}
+
+function toWritableCookie(cookie: StoredCookie): WritableCookie {
+ const secure = cookie.secure === true;
+ const host = cookie.domain.startsWith(".") ? cookie.domain.slice(1) : cookie.domain;
+ const path = cookie.path && cookie.path.startsWith("/") ? cookie.path : "/";
+ const persistent = cookie.session !== true && typeof cookie.expires === "number" && cookie.expires > 0;
+ return {
+ url: `${secure ? "https" : "http"}://${host}${path}`,
+ name: cookie.name,
+ value: cookie.value,
+ ...(cookie.domain.startsWith(".") ? { domain: cookie.domain } : {}),
+ path,
+ secure,
+ httpOnly: cookie.httpOnly === true,
+ sameSite: normalizeSameSite(cookie.sameSite, secure),
+ ...(persistent ? { expirationDate: cookie.expires } : {}),
+ };
+}
+
+function readJar(dataDir: string, profileKey: string): StoredCookie[] {
+ const file = jarPath(dataDir, profileKey);
+ let raw: string;
+ try {
+ raw = readFileSync(file, "utf8");
+ } catch {
+ return [];
+ }
+ try {
+ const parsed = JSON.parse(raw) as Partial<EncryptedJar>;
+ if (parsed.v !== 1 || typeof parsed.iv !== "string" || typeof parsed.tag !== "string" || typeof parsed.data !== "string") {
+ return [];
+ }
+ const decipher = createDecipheriv("aes-256-gcm", jarKey(dataDir), Buffer.from(parsed.iv, "base64"));
+ decipher.setAuthTag(Buffer.from(parsed.tag, "base64"));
+ const plaintext = Buffer.concat([
+ decipher.update(Buffer.from(parsed.data, "base64")),
+ decipher.final(),
+ ]).toString("utf8");
+ const cookies = JSON.parse(plaintext);
+ return Array.isArray(cookies) ? (cookies as StoredCookie[]) : [];
+ } catch {
+ return [];
+ }
+}
+
+function writeJar(dataDir: string, profileKey: string, cookies: StoredCookie[]): void {
+ const file = jarPath(dataDir, profileKey);
+ if (cookies.length === 0) {
+ rmSync(file, { force: true });
+ return;
+ }
+ const iv = randomBytes(12);
+ const cipher = createCipheriv("aes-256-gcm", jarKey(dataDir), iv);
+ const ciphertext = Buffer.concat([cipher.update(JSON.stringify(cookies), "utf8"), cipher.final()]);
+ const payload: EncryptedJar = {
+ v: 1,
+ iv: iv.toString("base64"),
+ tag: cipher.getAuthTag().toString("base64"),
+ data: ciphertext.toString("base64"),
+ };
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
+ writeFileAtomic(file, JSON.stringify(payload), { mode: 0o600 });
+}
+
+/** Captures current Chrome cookies (including session cookies) into an encrypted per-profile jar on disk. */
+export async function snapshotCookies(
+ browser: CdpBrowser,
+ dataDir: string,
+ profileKey: string,
+ nowSec = Math.floor(Date.now() / 1000),
+ shouldWrite: () => boolean = () => true,
+): Promise<number> {
+ const response = await browser.connection.root.send<{ cookies?: StoredCookie[] }>("Storage.getCookies", {}, { timeoutMs: CDP_TIMEOUT_MS });
+ const deduped = new Map<string, StoredCookie>();
+ for (const cookie of response.cookies ?? []) {
+ if (!isLivePersistableCookie(cookie, nowSec)) continue;
+ deduped.set(cookieIdentity(cookie), cookie);
+ }
+ const kept = [...deduped.values()];
+ if (!shouldWrite()) return 0;
+ writeJar(dataDir, profileKey, kept);
+ return kept.length;
+}
+
+/** Restores any missing cookies from the encrypted jar back into Chrome without clobbering newer live cookies. */
+export async function remountCookies(
+ browser: CdpBrowser,
+ dataDir: string,
+ profileKey: string,
+ nowSec = Math.floor(Date.now() / 1000),
+): Promise<number> {
+ const stored = readJar(dataDir, profileKey).filter((cookie) => isLivePersistableCookie(cookie, nowSec));
+ if (stored.length === 0) return 0;
+ const live = await browser.connection.root.send<{ cookies?: StoredCookie[] }>("Storage.getCookies", {}, { timeoutMs: CDP_TIMEOUT_MS });
+ const present = new Set((live.cookies ?? []).map(cookieIdentity));
+ const missing = stored.filter((cookie) => !present.has(cookieIdentity(cookie)));
+ if (missing.length === 0) return 0;
+ const result = await cdpSink((method, params) => browser.connection.root.send(method, params, { timeoutMs: CDP_TIMEOUT_MS })).write(
+ missing.map(toWritableCookie),
+ );
+ return result.written;
+}
diff --git a/server/browser/config.ts b/server/browser/config.ts
index a167e6b6c1..96eeb9d024 100644
--- a/server/browser/config.ts
+++ b/server/browser/config.ts
@@ -22,7 +22,7 @@ export type BrowserEngineKind = "agent-browser" | "chrome";
export const browserEngineConfigSchema = z.object({
attachCdpUrl: z.string().trim().max(2048).refine((value) => value === "" || isValidCdpTarget(value),
{ message: "browserEngine.attachCdpUrl must be a CDP port (1-65535) or an http(s)/ws(s) URL" }).optional(),
- idleTimeoutMinutes: z.number().int().min(1).max(60).optional(), // an unused browser closes after this; 10 when unset, 3 on MausBot Cloud
+ idleTimeoutMinutes: z.number().int().min(0).max(60).optional(), // an unused browser closes after this in minutes (0 keeps it open; 10 when unset, 3 on MausBot Cloud)
egress: browserEgressConfigSchema.optional(),
/** "chrome" runs the bots' browsers on OpenMausBot's own Chrome driver, an early test; agent-browser is the default. */
engine: z.enum(["agent-browser", "chrome"]).optional(),
@@ -35,6 +35,10 @@ export const browserEngineConfigSchema = z.object({
paneIdentity: z.enum(["native", "cleaned"]).optional(),
});
+export const browserEnginePatchSchema = browserEngineConfigSchema.extend({
+ idleTimeoutMinutes: browserEngineConfigSchema.shape.idleTimeoutMinutes.nullable(),
+});
+
export interface BrowserEngineConfig {
attachCdpUrl?: string;
idleTimeoutMinutes?: number;
diff --git a/server/browser/lent-chrome.test.ts b/server/browser/lent-chrome.test.ts
index a8c90fad0c..8b44f25aa8 100644
--- a/server/browser/lent-chrome.test.ts
+++ b/server/browser/lent-chrome.test.ts
@@ -197,11 +197,18 @@ describe("LentChromeDoors", () => {
expect((await nextData(b)).toString()).toBe("still");
});
- it("a connection unused for the idle time is closed", async () => {
+ it("a connection unused for the idle time is closed, and stays open when idleMs is 0 (never)", async () => {
const target = await echo();
const { door } = make(joining(target.port), { idleMs: () => 50, sweepMs: 10 });
const socket = await client(await door.door("s1"));
await closed(socket);
+
+ const { door: neverIdle } = make(joining(target.port), { idleMs: () => 0, sweepMs: 10 });
+ const persistent = await client(await neverIdle.door("s2"));
+ await nextData(persistent);
+ await new Promise((resolve) => setTimeout(resolve, 60));
+ persistent.write("alive");
+ expect((await nextData(persistent)).toString()).toBe("alive");
});
it("guidance names the computer and what to do", () => {
diff --git a/server/browser/lent-chrome.ts b/server/browser/lent-chrome.ts
index 32d2617220..ac8e970eb8 100644
--- a/server/browser/lent-chrome.ts
+++ b/server/browser/lent-chrome.ts
@@ -111,7 +111,7 @@ export class LentChromeDoors {
const limit = this.#deps.idleMs();
for (const [socket, seen] of this.#joined) {
if (socket.bytesRead !== seen.bytes) { seen.bytes = socket.bytesRead; seen.at = now; }
- else if (now - seen.at >= limit) socket.destroy();
+ else if (limit > 0 && now - seen.at >= limit) socket.destroy();
}
}, this.#deps.sweepMs ?? 30_000);
this.#sweep.unref();
diff --git a/server/browser/service.test.ts b/server/browser/service.test.ts
index a657b0948d..30a291f54e 100644
--- a/server/browser/service.test.ts
+++ b/server/browser/service.test.ts
@@ -1,9 +1,10 @@
-import { mkdtempSync } from "node:fs";
+import { existsSync, mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, afterEach, describe, expect, it, vi } from "vitest";
import { removeTempDir } from "../testing/cleanup.ts";
+import { profileDir } from "./chrome/profile.ts";
import { forbiddenCommand } from "./cdp/testing/real-chrome.ts";
import { BROWSER_CONTROL_REFUSAL } from "./control.ts";
import { REDDIT_REFUSAL } from "./egress/reddit.ts";
@@ -697,7 +698,79 @@ describe("browsers on one computer", () => {
const replacement = service.profile(target);
await service.running(replacement);
await Promise.all([closing, ...erases]);
- const { existsSync } = await import("node:fs");
expect(existsSync(replacement.downloadDir)).toBe(true);
});
+
+ it("remounts the persistent cookie jar (including session cookies) across idle close and relaunch, and drops it on temporary or erased profiles", async () => {
+ const { service, backend, call } = setup();
+ await call("agent_browser_open", { url: "https://facebook.com" });
+ backend.chromes[0]!.cookies.push(
+ { name: "c_user", value: "1001", domain: ".facebook.com", path: "/", secure: true, httpOnly: true, sameSite: "None", expires: Math.floor(Date.now() / 1000) + 3_600 },
+ { name: "xs", value: "session-secret", domain: ".facebook.com", path: "/", secure: true, httpOnly: true, sameSite: "None", expires: -1 },
+ { name: "stale", value: "old", domain: ".facebook.com", path: "/", secure: true, httpOnly: false, expires: 100 },
+ );
+ await sleep(25);
+ expect(await service.closeIdle(10)).toEqual(["bot:a"]);
+
+ await call("agent_browser_get_url");
+ expect(backend.chromes).toHaveLength(2);
+ expect(backend.chromes[1]!.cookies).toEqual(expect.arrayContaining([
+ expect.objectContaining({ name: "c_user", value: "1001", domain: ".facebook.com" }),
+ expect.objectContaining({ name: "xs", value: "session-secret", domain: ".facebook.com" }),
+ ]));
+ expect(backend.chromes[1]!.cookies.some((c) => c.name === "stale")).toBe(false);
+
+ await service.erase("bot:a");
+ await call("agent_browser_open", { url: "https://facebook.com" });
+ expect(backend.chromes[2]!.cookies).toEqual([]);
+
+ const tempTarget = { session: "guest-1", key: "temp:guest-1" };
+ await call("agent_browser_open", { url: "https://example.com" }, tempTarget);
+ backend.chromes[3]!.cookies.push({ name: "tmp", value: "1", domain: ".example.com", path: "/", expires: -1 });
+ await sleep(25);
+ expect(await service.closeIdle(10)).toEqual(["bot:a", "temp:guest-1"]);
+ await call("agent_browser_get_url", {}, tempTarget);
+ expect(backend.chromes[4]!.cookies).toEqual([]);
+ });
+
+ it("keeps running browsers open when idle timeout is 0 and never recreates cookies when erase races a live snapshot", async () => {
+ const { service, backend, call, dataDir } = setup({ idleMs: () => 0 });
+ await call("agent_browser_open", { url: "https://facebook.com" });
+ await sleep(25);
+ expect(await service.closeIdle()).toEqual([]);
+ expect(await service.closeIdle(0)).toEqual([]);
+ expect(backend.chromes).toHaveLength(1);
+
+ const profile = service.profile({ session: "bot-a", key: "bot:a" });
+ const root = profile.run!.browser.connection.root;
+ const origSend = root.send.bind(root);
+ let signalGetCookies!: () => void;
+ const getCookiesStarted = new Promise<void>((resolve) => { signalGetCookies = resolve; });
+ let allowGetCookiesReturn!: () => void;
+ const getCookiesCanReturn = new Promise<void>((resolve) => { allowGetCookiesReturn = resolve; });
+ root.send = (async (method: string, params: Record<string, unknown>, opts?: { timeoutMs?: number }) => {
+ const result = await origSend(method, params, opts);
+ if (method === "Storage.getCookies") {
+ signalGetCookies();
+ await getCookiesCanReturn;
+ }
+ return result;
+ }) as typeof root.send;
+
+ backend.chromes[0]!.cookies.push({ name: "xs", value: "session-secret", domain: ".facebook.com", path: "/", secure: true, expires: -1 });
+ const baseNow = Date.now();
+ const nowSpy = vi.spyOn(Date, "now").mockReturnValue(baseNow + 35_000);
+ try {
+ const pendingCall = call("agent_browser_open", { url: "https://facebook.com/home" });
+ await getCookiesStarted;
+ const erased = service.erase("bot:a");
+ await erased;
+ allowGetCookiesReturn();
+ await pendingCall;
+ } finally {
+ nowSpy.mockRestore();
+ }
+ expect(existsSync(join(profileDir(dataDir, "bot:a"), "omb-cookies.enc"))).toBe(false);
+ expect(existsSync(profileDir(dataDir, "bot:a"))).toBe(false);
+ });
});
diff --git a/server/browser/service.ts b/server/browser/service.ts
index 6a433863fb..a057dedfeb 100644
--- a/server/browser/service.ts
+++ b/server/browser/service.ts
@@ -20,6 +20,7 @@ import type { CdpBrowser } from "./cdp/browser.ts";
import type { Download } from "./cdp/downloads.ts";
import { isUnanswered } from "./cdp/errors.ts";
import type { CdpPage } from "./cdp/page.ts";
+import { remountCookies, snapshotCookies } from "./chrome/cookie-jar.ts";
import { browserRoot, profileDir, profileHash, profileKind, removeProfile, workspaceId } from "./chrome/profile.ts";
import { BROWSER_CONTROL_REFUSAL, ProfileControl, type TakeResult } from "./control.ts";
import { executeTool, personUrl, readsDuringHold, toolFailure, type ToolContext } from "./dispatch.ts";
@@ -162,6 +163,7 @@ export class BrowserService {
return this.#lanes.run(profile.key, () => profile.control.agent(null, clear), this.#options.laneWaitMs).then((ran) => ran !== null);
});
readonly #scrub: (text: string) => string;
+ readonly #lastCookieSnapshot = new Map<string, number>();
constructor(options: BrowserServiceOptions) {
this.#options = { callBudgetMs: BROWSER_CALL_DEFAULTS.callBudgetMs, laneWaitMs: BROWSER_CALL_DEFAULTS.laneWaitMs, takeoverMs: 15_000, capacityWaitMs: CAPACITY_WAIT_MS, ...options };
@@ -222,7 +224,8 @@ export class BrowserService {
profile.fresh = false;
rmSync(profile.downloadDir, { recursive: true, force: true });
mkdirSync(profile.downloadDir, { recursive: true, mode: 0o700 });
- const opened = await this.#options.backend(profile.key).open({ key: profile.key, mode: "headless", fresh, viewport: profile.hub.viewport(), downloadDir: profile.downloadDir });
+ const backend = this.#options.backend(profile.key);
+ const opened = await backend.open({ key: profile.key, mode: "headless", fresh, viewport: profile.hub.viewport(), downloadDir: profile.downloadDir });
const run: Running = { opened, browser: opened.browser, offs: [], closing: false };
const browser = opened.browser;
const adopt = (page: CdpPage, origin: Tab["origin"]) => {
@@ -264,6 +267,11 @@ export class BrowserService {
}));
try {
this.#stillWanted(profile, epoch);
+ if (!profile.temporary && backend.kind === "local") {
+ await remountCookies(browser, this.#options.dataDir, profile.key).catch(() => 0);
+ this.#lastCookieSnapshot.set(profile.key, Date.now());
+ this.#stillWanted(profile, epoch);
+ }
// A Chrome that dies before any tab runs says so at once, not when the wait ends.
const firstTab = browser.waitForPage(() => true, FIRST_TAB_MS);
const died = opened.exited.then(() => { throw new Error("Chrome closed before its first tab opened."); });
@@ -306,6 +314,7 @@ export class BrowserService {
for (const off of run.offs) off();
profile.run = null;
profile.tabs.clear();
+ this.#lastCookieSnapshot.delete(profile.key);
if (run.closing) return;
try {
rmSync(profile.downloadDir, { recursive: true, force: true });
@@ -335,6 +344,10 @@ export class BrowserService {
if (run) {
run.closing = true;
for (const off of run.offs) off();
+ if (!erase && !profile.temporary && run.browser.connected && this.#options.backend(profile.key).kind === "local") {
+ await snapshotCookies(run.browser, this.#options.dataDir, profile.key, undefined, () => this.#profiles.get(profile.key) === profile).catch(() => undefined);
+ }
+ this.#lastCookieSnapshot.delete(profile.key);
profile.hub.stopped(reopened?.kind === "idle" ? "asleep" : "closed");
await run.opened.close().catch(() => undefined);
}
@@ -520,6 +533,24 @@ export class BrowserService {
control.call = parsed.call.name;
try {
const result = await executeTool(this.#context(profile, run, deadline), parsed.call);
+ if (
+ !profile.temporary &&
+ !run.closing &&
+ !profile.stopping &&
+ !readsDuringHold(parsed.call) &&
+ run.browser.connected &&
+ this.#options.backend(profile.key).kind === "local" &&
+ Date.now() - (this.#lastCookieSnapshot.get(profile.key) ?? 0) >= 30_000
+ ) {
+ this.#lastCookieSnapshot.set(profile.key, Date.now());
+ await snapshotCookies(
+ run.browser,
+ this.#options.dataDir,
+ profile.key,
+ undefined,
+ () => !run.closing && !profile.stopping && this.#profiles.get(profile.key) === profile,
+ ).catch(() => undefined);
+ }
beforeDispatch?.();
return shapeResult(result, parsed.call.name);
} catch (error) {
diff --git a/server/browser/testing/fake-chrome.ts b/server/browser/testing/fake-chrome.ts
index 4e2bb3e60e..8ee537fc12 100644
--- a/server/browser/testing/fake-chrome.ts
+++ b/server/browser/testing/fake-chrome.ts
@@ -62,6 +62,7 @@ const MIN_WIDTH = 500;
export class FakeChrome implements CdpTransport {
readonly sent: SentToFake[] = [];
readonly pages = new Map<string, FakePage>();
+ readonly cookies: Array<Record<string, unknown>> = [];
readonly window = { width: 1280, height: 720 + CHROME_HEIGHT };
dpr = 2;
/** Commands that never answer, to stand for a browser that hung. */
@@ -233,6 +234,22 @@ export class FakeChrome implements CdpTransport {
return {};
case "Browser.getVersion":
return { product: "Chrome/153.0.8010.12", userAgent: "Mozilla/5.0 Chrome/153.0.0.0", protocolVersion: "1.3", revision: "@x" };
+ case "Storage.getCookies":
+ return { cookies: this.cookies.map((cookie) => ({ ...cookie })) };
+ case "Storage.setCookies": {
+ const added = Array.isArray(params.cookies) ? params.cookies as Array<Record<string, unknown>> : [];
+ for (const cookie of added) {
+ const domain = typeof cookie.domain === "string"
+ ? cookie.domain
+ : (() => { try { return new URL(String(cookie.url ?? "")).hostname; } catch { return ""; } })();
+ const path = typeof cookie.path === "string" ? cookie.path : "/";
+ const idx = this.cookies.findIndex((existing) => existing.name === cookie.name && existing.domain === domain && existing.path === path);
+ const stored = { ...cookie, domain, path };
+ if (idx >= 0) this.cookies[idx] = stored;
+ else this.cookies.push(stored);
+ }
+ return {};
+ }
default:
return {};
}
diff --git a/server/config.test.ts b/server/config.test.ts
index 12cc042746..2c608dade7 100644
--- a/server/config.test.ts
+++ b/server/config.test.ts
@@ -563,13 +563,25 @@ describe("configuration boundaries", () => {
expect(browserEngineAttachCdpUrl({ browserEngine: { attachCdpUrl: "" } })).toBeNull();
});
- it("takes browserEngine.idleTimeoutMinutes as whole minutes up to the engine's own hour", () => {
- for (const value of [1, 10, 60]) {
+ it("takes browserEngine.idleTimeoutMinutes as whole minutes from 0 (never) up to the engine's own hour, and clears on null patch", () => {
+ for (const value of [0, 1, 10, 60]) {
expect(parseStoredConfig({ browserEngine: { idleTimeoutMinutes: value } })).toEqual({ browserEngine: { idleTimeoutMinutes: value } });
expect(parseConfigPatch({ browserEngine: { idleTimeoutMinutes: value } })).toEqual({ browserEngine: { idleTimeoutMinutes: value } });
}
- for (const value of [0, 61, 2.5, -1, "10"]) expect(() => parseConfigPatch({ browserEngine: { idleTimeoutMinutes: value } })).toThrow();
+ expect(parseConfigPatch({ browserEngine: { idleTimeoutMinutes: null } })).toEqual({ browserEngine: { idleTimeoutMinutes: null } });
+ expect(() => parseStoredConfig({ browserEngine: { idleTimeoutMinutes: null } })).toThrow("browserEngine.idleTimeoutMinutes");
+ for (const value of [61, 2.5, -1, "10"]) expect(() => parseConfigPatch({ browserEngine: { idleTimeoutMinutes: value } })).toThrow();
expect(parseConfigPatch({ browserEngine: { attachCdpUrl: "9333", idleTimeoutMinutes: 5 } })).toEqual({ browserEngine: { attachCdpUrl: "9333", idleTimeoutMinutes: 5 } });
+
+ const path = join(DATA_DIR, "config.json");
+ mkdirSync(DATA_DIR, { recursive: true });
+ writeFileSync(path, JSON.stringify({ browserEngine: { engine: "chrome", idleTimeoutMinutes: 0 } }));
+ try {
+ saveConfig({ browserEngine: { idleTimeoutMinutes: null } });
+ expect(JSON.parse(readFileSync(path, "utf8")).browserEngine).toEqual({ engine: "chrome" });
+ } finally {
+ rmSync(path, { force: true });
+ }
});
it("keeps a browser profile's My Chrome choice through saving, loading and migration, and nothing else", () => {
diff --git a/server/config.ts b/server/config.ts
index 08ed3234a7..6b2fc0a1b5 100644
--- a/server/config.ts
+++ b/server/config.ts
@@ -31,7 +31,7 @@ import { isRemoteMcpServer, mcpServerServes, parseStoredMcpServer } from "./mcp-
import { parseJson, schemaIssue, type JsonObject, type JsonValue } from "./schema.ts";
import { deciderConfigSchema, type DeciderConfig } from "./decider/config.ts";
import { fishKeyFromLiveKey, liveConfigSchema, liveConfigWithEnv, liveSettingEnv, type LiveConfig } from "./live-config.ts"; import { hearingConfigShape } from "./tts/hearing-config.ts";
-import { browserEngineConfigSchema, isValidCdpTarget, type BrowserEngineConfig } from "./browser/config.ts";
+import { browserEngineConfigSchema, browserEnginePatchSchema, isValidCdpTarget, type BrowserEngineConfig } from "./browser/config.ts";
import { roomContextSettings } from "./room-context-settings.ts"; import { usageCapsSchema, type UsageCapsConfig } from "./usage-caps-config.ts";
import { localVmConfigSchema } from "./local-vm-settings.ts";
export * from "./local-vm-settings.ts";
@@ -411,7 +411,7 @@ const storedAppConfigSchema = appConfigSchema.extend(helperStoredShape).extend({
}).optional(),
});
const appConfigPatchSchema = appConfigSchema.omit({ instances: true, mcpServers: true, cliStartup: true, customDomain: true })
- .extend({ threads: threadsPatchSchema.optional(), newBots: newBotsPatchSchema.optional(), imageGen: imageGenPatchSchema.optional() }); export const CONFIG_PATCH_FIELDS = appConfigPatchSchema.shape;
+ .extend({ threads: threadsPatchSchema.optional(), newBots: newBotsPatchSchema.optional(), imageGen: imageGenPatchSchema.optional(), browserEngine: browserEnginePatchSchema.optional() }); export const CONFIG_PATCH_FIELDS = appConfigPatchSchema.shape;
const jsonObjectSchema = z.record(z.string(), z.json());
export interface AppConfig extends HelperConfig {
@@ -769,7 +769,7 @@ export function cacheUntilConfigChanges<T>(derive: (config: AppConfig) => T): ()
}
/** Keeps process.env in step with a saved credential ("" drops the var), because loadConfig() prefers env. */
-export function syncCredentialEnv(patch: Partial<Omit<AppConfig, "threads" | "newBots" | "imageGen">> & { imageGen?: ImageGenCredentialPatch }): void {
+export function syncCredentialEnv(patch: Partial<Omit<AppConfig, "threads" | "newBots" | "imageGen" | "browserEngine">> & { imageGen?: ImageGenCredentialPatch }): void {
const secrets: Array<[value: string | undefined, name: string]> = [
[patch.xai?.key, "XAI_API_KEY"],
[patch.mistral?.key, "MISTRAL_API_KEY"],
@@ -872,19 +872,16 @@ export function onConfigSaved(listener: (before: JsonObject, after: JsonObject)
}
/** Secrets are never echoed back; callers report configured-or-not only. */
+type SaveSectionOverrides = Pick<ConfigPatch, "threads" | "newBots" | "imageGen" | "browserEngine">;
export function saveConfig(
- patch: Partial<Omit<AppConfig, "threads" | "newBots" | "imageGen">> & {
- threads?: z.output<typeof threadsPatchSchema>;
- newBots?: z.output<typeof newBotsPatchSchema>;
- imageGen?: z.output<typeof imageGenPatchSchema>;
- },
+ patch: Partial<Omit<AppConfig, keyof SaveSectionOverrides>> & SaveSectionOverrides,
options: { replaceInstances?: boolean } = {},
): void {
const p = join(DATA_DIR, "config.json");
const read = readConfigFile(p);
if (read.state === "unreadable" || read.state === "invalid") throw configSaveRefusal(read, p);
const disk: JsonObject = read.state === "ok" ? read.value : {};
- const checkedPatch = appConfigSchema.partial().extend({ threads: threadsPatchSchema.optional(), newBots: newBotsPatchSchema.optional(), imageGen: imageGenPatchSchema.optional() }).parse(patch);
+ const checkedPatch = appConfigSchema.partial().extend({ threads: threadsPatchSchema.optional(), newBots: newBotsPatchSchema.optional(), imageGen: imageGenPatchSchema.optional(), browserEngine: browserEnginePatchSchema.optional() }).parse(patch);
const before = configSaveListeners.size ? structuredClone(disk) : disk;
const keepImageModels = keepKeysOutOfImageModels(disk, checkedPatch.imageGen);
const storedProfiles = storedBrowserProfilesSchema.safeParse(disk.browserProfiles);
diff --git a/server/host/browser.test.ts b/server/host/browser.test.ts
index 9d2b7473dc..f3f625a917 100644
--- a/server/host/browser.test.ts
+++ b/server/host/browser.test.ts
@@ -505,21 +505,25 @@ describe("My Chrome on My Cloud, through the person's lent Chrome", () => {
});
describe("how long an unused browser stays open", () => {
- it("is three minutes on a Cloud home and ten on a desktop, unless config.json sets it", () => {
+ it("is three minutes on a Cloud home and ten on a desktop, unless config.json sets it (including 0 for never)", () => {
const cloud = setup(undefined, { cloudHome: true });
expect(cloud.host.browserIdleMs()).toBe(3 * 60_000);
cloud.cfg.browserEngine = { idleTimeoutMinutes: 20 };
expect(cloud.host.browserIdleMs()).toBe(20 * 60_000);
+ cloud.cfg.browserEngine = { idleTimeoutMinutes: 0 };
+ expect(cloud.host.browserIdleMs()).toBe(0);
expect(setup(undefined).host.browserIdleMs()).toBe(10 * 60_000);
});
});
describe("the bots' browser host by default", () => {
- it("keeps agent-browser's prompt and status", () => {
- const { host } = setup(undefined);
+ it("keeps agent-browser's prompt and status, and exposes idleTimeoutMinutes only when set", () => {
+ const { cfg, host } = setup(undefined);
expect(host.browserSystemPrompt(undefined)).toBe(BUILT_IN_BROWSER_SYSTEM_PROMPT);
expect(host.signedInSitesRefusal("work")).toBeNull();
expect(host.engineSummary({ kind: "engine", version: "0.37.0", myChrome: true })).toEqual({ kind: "engine", version: "0.37.0", myChrome: true, engine: "agent-browser" });
+ cfg.browserEngine = { idleTimeoutMinutes: 0 };
+ expect(host.engineSummary({ kind: "engine", version: "0.37.0", myChrome: true })).toEqual({ kind: "engine", version: "0.37.0", myChrome: true, engine: "agent-browser", idleTimeoutMinutes: 0 });
});
it("says when agent-browser runs its headless shell because Google Chrome is not installed", () => {
diff --git a/server/host/browser.ts b/server/host/browser.ts
index 361bfd9381..cade2c7725 100644
--- a/server/host/browser.ts
+++ b/server/host/browser.ts
@@ -286,6 +286,12 @@ export function createBrowserHost(deps: BrowserHostDeps) {
live: (session) => usedBrowserSessions.has(session) && belongs(session),
held: (session) => !turnResources.free(`browser:${session}`),
closeIdle: (session) => browserRuntime.closeIfIdle(session, idleMs(), usedBrowserSessions.get(session)),
+ keepAlive: async (session) => {
+ if (idleMs() > 0) return;
+ const spec = usedBrowserSessions.get(session);
+ if (!spec || chromeTarget(session, spec) || attachesToChrome(spec.env)) return;
+ await inRunningBrowser(spec.command, browserRuntimeEnv({ ...spec.env, AGENT_BROWSER_SESSION: session }), ["get", "url"]).then(() => undefined, () => undefined);
+ },
});
// A browser that has ended keeps no loopback listener: its gate opens again with it, on the same port where it can, and
// the session's launch settings are worked out again then.
@@ -745,12 +751,13 @@ export function createBrowserHost(deps: BrowserHostDeps) {
return { binaryPath: engine.binaryPath, session, env: browserSessionSpec(engine.binaryPath, session, profile, await browserEgress.open(session)).env, encryptionKey: browserEngineEncryptionKey() };
}
/** What Settings shows of the engine that runs bots' browsers here; My Chrome stays on agent-browser. */
- function engineSummary<T extends { kind: "engine" | "unavailable"; myChrome: boolean }>(agentBrowser: T): (T | (ReturnType<ChromeEngine["summary"]> & { myChrome: boolean })) & { engine: BrowserEngineKind; pane?: true; cookieImport?: true; noChrome?: true; serverSites?: boolean; proxyConfigured?: boolean; proxySaved?: boolean } {
+ function engineSummary<T extends { kind: "engine" | "unavailable"; myChrome: boolean }>(agentBrowser: T): (T | (ReturnType<ChromeEngine["summary"]> & { myChrome: boolean })) & { engine: BrowserEngineKind; pane?: true; cookieImport?: true; noChrome?: true; serverSites?: boolean; proxyConfigured?: boolean; proxySaved?: boolean; idleTimeoutMinutes?: number } {
const serverSites = sitesSwitch ? { serverSites: cfg.browserEngine?.egress?.localNetwork === true } : {};
const engine = browserEngineKind(cfg);
const proxyValue = cfg.browserEngine?.egress?.proxy;
const proxySaved = typeof proxyValue === "string" && proxyValue.trim().length > 0;
const proxyConfigured = builtInBrowserEnabled(cfg) && !hostedServer && parseSocks5Proxy(proxyValue) !== null;
+ const idleTimeoutMinutes = cfg.browserEngine?.idleTimeoutMinutes;
return {
...(engine === "chrome" ? { ...chromeEngine.summary(), myChrome: agentBrowser.myChrome, ...lentChromeSummary(), engine } : { ...agentBrowser, engine }),
...(paneLink?.available && browserPaneWanted(cfg) ? { pane: true as const } : {}),
@@ -759,6 +766,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {
...serverSites,
...(proxyConfigured ? { proxyConfigured: true } : {}),
...(proxySaved ? { proxySaved: true } : {}),
+ ...(idleTimeoutMinutes !== undefined ? { idleTimeoutMinutes } : {}),
};
}
diff --git a/server/index.ts b/server/index.ts
index a91036467f..558c9aad49 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -2387,7 +2387,7 @@ const emailIntegration = (bot: BotRecord, turn: { threadId: string; generation:
let browserEngineInstall: Promise<void> | null = null;
let browserEngineInstallError: string | null = null;
-export function browserEngineSummary(): { kind: "engine" | "unavailable"; reason?: string; installable?: boolean; version?: string; chrome?: string; noChrome?: true; installing?: boolean; installError?: string; myChrome: boolean; proxyConfigured?: boolean; proxySaved?: boolean; myChromeOn?: { name: string; device: "PC" | "Mac" | "computer"; online: boolean }; myChromeLendable?: true; serverSites?: boolean; engine: "agent-browser" | "chrome"; desktopView?: true } {
+export function browserEngineSummary(): { kind: "engine" | "unavailable"; reason?: string; installable?: boolean; version?: string; chrome?: string; noChrome?: true; installing?: boolean; installError?: string; myChrome: boolean; proxyConfigured?: boolean; proxySaved?: boolean; myChromeOn?: { name: string; device: "PC" | "Mac" | "computer"; online: boolean }; myChromeLendable?: true; serverSites?: boolean; idleTimeoutMinutes?: number; engine: "agent-browser" | "chrome"; desktopView?: true } {
const status = browserEngineStatus();
const progress = { myChrome: myChromeAvailable(), ...lentChromeSummary(), ...(browserEngineInstall ? { installing: true } : {}), ...(browserEngineInstallError ? { installError: browserEngineInstallError } : {}) };
return engineSummary(status.kind === "ready"
diff --git a/src/components/BrowserSettingsRows.test.ts b/src/components/BrowserSettingsRows.test.ts
index d0d5a31ee0..2a334d7006 100644
--- a/src/components/BrowserSettingsRows.test.ts
+++ b/src/components/BrowserSettingsRows.test.ts
@@ -5,7 +5,7 @@ import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { setLocale } from "@/lib/i18n";
-import { BrowserProxyRow, BuiltInBrowserRow, NewBrowserSettings, ServerSitesRow } from "./BrowserSettingsRows";
+import { BrowserIdleTimeoutRow, BrowserProxyRow, BuiltInBrowserRow, NewBrowserSettings, ServerSitesRow } from "./BrowserSettingsRows";
const fixture = vi.hoisted(() => ({
config: undefined as Record<string, unknown> | undefined,
@@ -182,3 +182,37 @@ describe("Built-in browser without Google Chrome", () => {
expect(row()).not.toContain("Google Chrome");
});
});
+
+describe("BrowserIdleTimeoutRow", () => {
+ const show = () => flushSync(() => root.render(createElement(BrowserIdleTimeoutRow)));
+ const select = () => host.querySelector<HTMLSelectElement>('select[aria-label="Close unused browsers after"]');
+
+ it("shows when built-in browser is on, defaults to 10 min (3 on Cloud), and saves 0 (never) via PATCH /api/config", async () => {
+ fixture.config = { features: { browser: false }, browserEngine: { kind: "engine" } };
+ show();
+ expect(select()).toBeNull();
+
+ fixture.config = { features: { browser: true }, cloudHome: true, browserEngine: { kind: "engine" } };
+ show();
+ expect(select()?.value).toBe("3");
+
+ fixture.config = { features: { browser: true }, browserEngine: { kind: "engine" } };
+ show();
+ expect(select()?.value).toBe("10");
+ expect([...select()!.options].map((option) => option.value)).toContain("0");
+
+ const saved = { features: { browser: true }, browserEngine: { kind: "engine", idleTimeoutMinutes: 0 } };
+ fixture.api.mockResolvedValue(saved);
+ flushSync(() => {
+ select()!.value = "0";
+ select()!.dispatchEvent(new Event("change", { bubbles: true }));
+ });
+ await vi.waitFor(() => expect(fixture.dispatch).toHaveBeenCalledWith({ type: "configStatus", config: saved }));
+ expect(fixture.api).toHaveBeenCalledWith("/api/config", {
+ method: "PATCH",
+ body: JSON.stringify({ browserEngine: { idleTimeoutMinutes: 0 } }),
+ });
+ show();
+ expect(select()?.value).toBe("0");
+ });
+});
diff --git a/src/components/BrowserSettingsRows.tsx b/src/components/BrowserSettingsRows.tsx
index 6ca7dd3ee9..3f47b54e6e 100644
--- a/src/components/BrowserSettingsRows.tsx
+++ b/src/components/BrowserSettingsRows.tsx
@@ -5,6 +5,7 @@ import { browserAvailable, browserUnavailableReason, builtInBrowserEnabled } fro
import { t } from "@/lib/i18n";
import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";
import { api, type ConfigStatus } from "@/state/store";
+import { Select } from "./Select";
import { MoreText, SettingRow, Switch } from "./SettingsPrimitives";
import { sameFields, useStoreDispatch, useStoreSelector } from "@/state/store-select";
@@ -70,6 +71,40 @@ export function BuiltInBrowserRow() {
);
}
+const IDLE_TIMEOUT_PRESETS = [3, 5, 10, 15, 30, 60] as const;
+
+export function BrowserIdleTimeoutRow() {
+ const state = useStoreSelector((s) => ({ config: s.config }), sameFields);
+ const { saving, error, save } = useConfigSave();
+ if (!builtInBrowserEnabled(state.config)) return null;
+
+ const fallback = state.config?.cloudHome ? 3 : 10;
+ const current = state.config?.browserEngine?.idleTimeoutMinutes ?? fallback;
+ const options = current > 0 && !IDLE_TIMEOUT_PRESETS.includes(current as (typeof IDLE_TIMEOUT_PRESETS)[number])
+ ? [...IDLE_TIMEOUT_PRESETS, current].sort((a, b) => a - b)
+ : IDLE_TIMEOUT_PRESETS;
+
+ return (
+ <SettingRow
+ title={t("settings.browser.idleTimeout")}
+ subtitle={t("settings.browser.idleTimeoutHint")}
+ message={error ? <p role="alert" className="text-danger">{error}</p> : null}
+ >
+ <Select
+ aria-label={t("settings.browser.idleTimeout")}
+ value={String(current)}
+ disabled={saving}
+ onChange={(event) => void save({ browserEngine: { idleTimeoutMinutes: Number(event.target.value) } })}
+ >
+ {options.map((minutes) => (
+ <option key={minutes} value={String(minutes)}>{t("settings.browser.idleMinutes", { minutes })}</option>
+ ))}
+ <option value="0">{t("settings.browser.idleNever")}</option>
+ </Select>
+ </SettingRow>
+ );
+}
+
/** Self-hosted servers only, for the owner: browserEngine.egress.localNetwork lets bots' browsers open this server's
* own sites and its local network. OpenMausBot's own ports, cloud metadata and link-local addresses stay closed. */
export function ServerSitesRow() {
diff --git a/src/components/SettingsModal.keys.dom.test.ts b/src/components/SettingsModal.keys.dom.test.ts
index 74213eeb60..12ee8fd4c5 100644
--- a/src/components/SettingsModal.keys.dom.test.ts
+++ b/src/components/SettingsModal.keys.dom.test.ts
@@ -50,7 +50,7 @@ vi.mock("./ActivitySection", () => ({ ActivitySection: marker("activity") }));
vi.mock("./UsageSection", () => ({ UsageSection: marker("usage") }));
vi.mock("./ImportSettings", () => ({ ImportSettings: marker("import") }));
vi.mock("./VaultSettings", () => ({ VaultSettings: marker("logins") }));
-vi.mock("./BrowserSettingsRows", () => ({ BuiltInBrowserRow: marker("browser"), ServerSitesRow: () => null, BrowserProxyRow: () => null }));
+vi.mock("./BrowserSettingsRows", () => ({ BuiltInBrowserRow: marker("browser"), BrowserIdleTimeoutRow: () => null, ServerSitesRow: () => null, BrowserProxyRow: () => null }));
vi.mock("./WindowPlaceTitle", () => ({ useWindowPlace: () => null, windowPlaceName: () => "This computer" }));
const { SettingsModal } = await import("./SettingsModal");
diff --git a/src/components/settings/pages/PlacePages.tsx b/src/components/settings/pages/PlacePages.tsx
index 01ce68bc08..bef1714cca 100644
--- a/src/components/settings/pages/PlacePages.tsx
+++ b/src/components/settings/pages/PlacePages.tsx
@@ -9,7 +9,7 @@ import { AdminOnly } from "../../AdminOnly";
import { AutomaticRecoverySettings } from "../../AutomaticRecoverySettings";
import { AwayEmailsSetting } from "../../AwayEmailsSetting";
import { PausedBotsButton } from "../../AwakeBotsPicker";
-import { BrowserProxyRow, BuiltInBrowserRow, NewBrowserSettings, ServerSitesRow } from "../../BrowserSettingsRows";
+import { BrowserIdleTimeoutRow, BrowserProxyRow, BuiltInBrowserRow, NewBrowserSettings, ServerSitesRow } from "../../BrowserSettingsRows";
import { CacheKeepWarmSettings } from "../../CacheKeepWarmSettings";
import { TeamPeopleCard } from "../../CloudAccountSettings";
import { CloudKeepHere } from "../../CloudKeepHere";
@@ -186,7 +186,7 @@ export function DesktopsPage() {
const [details, setDetails] = useState(anchor === "desktop-details");
return <>
<AdvancedPagePart anchor="browser"><SettingsGroup label={t("settings.desktops.browserSection")} block="browser">
- <SettingsRows><BuiltInBrowserRow /><ServerSitesRow /><BrowserProxyRow />{ctx.advanced && <div data-settings-block="new-browser" className="contents"><NewBrowserSettings /></div>}</SettingsRows>
+ <SettingsRows><BuiltInBrowserRow /><BrowserIdleTimeoutRow /><ServerSitesRow /><BrowserProxyRow />{ctx.advanced && <div data-settings-block="new-browser" className="contents"><NewBrowserSettings /></div>}</SettingsRows>
</SettingsGroup></AdvancedPagePart>
<AdvancedPagePart anchor="desktops"><AdminOnly><DesktopKinds /></AdminOnly></AdvancedPagePart>
<AdvancedPagePart anchor="browser"><BrowserProfilesRow /></AdvancedPagePart>
diff --git a/src/locales/en.json b/src/locales/en.json
index 293b0f0101..0973cc2b95 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -11420,6 +11420,10 @@
"settings.browser.proxyInactive": "Saved, but active only with the built-in browser on supported hosts.",
"settings.browser.proxySave": "Save",
"settings.browser.proxyClear": "Remove",
+ "settings.browser.idleTimeout": "Close unused browsers after",
+ "settings.browser.idleTimeoutHint": "Keep open (Never) keeps websites signed in even if a site relies on session-only cookies.",
+ "settings.browser.idleMinutes": "{minutes} min",
+ "settings.browser.idleNever": "Never (keep signed in)",
"together.onCloud": "On My Cloud",
"together.onComputer": "On this computer",
"together.state.asleep": "My Cloud is asleep. Open a bot to wake it.",
diff --git a/src/state/config-status.ts b/src/state/config-status.ts
index 0c597e8acf..7501622db9 100644
--- a/src/state/config-status.ts
+++ b/src/state/config-status.ts
@@ -240,6 +240,8 @@ export interface BrowserEngineSummary {
proxySaved?: boolean;
/** Team Cloud only: whether this caller may change the shared SOCKS5 upstream. */
proxyEditable?: boolean;
+ /** Idle close timeout in minutes (0 keeps browsers open; unset means 10 min on desktop or 3 min on Cloud). */
+ idleTimeoutMinutes?: number;
}
export interface BrowserProfile {