Skip to content

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

fix(browser): cap the default engine's browsers, close idle ones under a held turn, list tools once (#6182)

Milind Sonia03d66374a1f
diff --git a/server/browser-room.test.ts b/server/browser-room.test.ts
new file mode 100644
index 0000000000..1d309b02c2
--- /dev/null
+++ b/server/browser-room.test.ts
@@ -0,0 +1,168 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { BrowserRoom, browserRoomSize, pidsLimit, SharedToolLists, spareForRoom } from "./browser-room.ts";
+
+const files = (map: Record<string, string>) => (path: string) => map[path] ?? null;
+
+describe("the task limit a server runs under", () => {
+ it("reads a container's cgroup v2 limit, the tightest over the cgroup and its parents", () => {
+ expect(pidsLimit(files({ "/proc/self/cgroup": "0::/\n", "/sys/fs/cgroup/pids.max": "2048\n" }))).toBe(2048);
+ expect(pidsLimit(files({
+ "/proc/self/cgroup": "0::/system.slice/omb.service\n",
+ "/sys/fs/cgroup/system.slice/omb.service/pids.max": "max\n",
+ "/sys/fs/cgroup/system.slice/pids.max": "1000\n",
+ }))).toBe(1000);
+ });
+
+ it("reads cgroup v1's pids controller, and has none off Linux or without a limit", () => {
+ expect(pidsLimit(files({ "/proc/self/cgroup": "12:pids:/docker/abc\n4:memory:/docker/abc\n", "/sys/fs/cgroup/pids/docker/abc/pids.max": "512" }))).toBe(512);
+ expect(pidsLimit(files({ "/proc/self/cgroup": "0::/\n", "/sys/fs/cgroup/pids.max": "max" }))).toBeNull();
+ expect(pidsLimit(files({}))).toBeNull();
+ });
+
+ it("on a hybrid host, reads v1's limit when the unified v2 hierarchy has none, and takes the tighter of both", () => {
+ const hybrid = "12:pids:/system.slice/omb.service\n4:memory:/system.slice/omb.service\n0::/system.slice/omb.service\n";
+ expect(pidsLimit(files({ "/proc/self/cgroup": hybrid, "/sys/fs/cgroup/pids/system.slice/omb.service/pids.max": "700\n" }))).toBe(700);
+ expect(pidsLimit(files({
+ "/proc/self/cgroup": hybrid,
+ "/sys/fs/cgroup/pids/system.slice/omb.service/pids.max": "700\n",
+ "/sys/fs/cgroup/unified/system.slice/pids.max": "300\n",
+ }))).toBe(300);
+ });
+});
+
+describe("how many browsers run at once", () => {
+ const GiB = 1024 ** 3;
+ it("fits the browsers' share of the container's task limit and memory", () => {
+ expect(browserRoomSize({ pids: 2048, memoryBytes: 8 * GiB })).toBe(5);
+ expect(browserRoomSize({ pids: 1000, memoryBytes: 8 * GiB })).toBe(2);
+ expect(browserRoomSize({ pids: null, memoryBytes: 2 * GiB })).toBe(2);
+ expect(browserRoomSize({ pids: null, memoryBytes: 64 * GiB })).toBe(16);
+ expect(browserRoomSize({ pids: 200, memoryBytes: 512 * 1024 ** 2 })).toBe(1);
+ });
+
+ it("takes OMB_BROWSER_MAX_RUNNING over all of that", () => {
+ expect(browserRoomSize({ override: "9", pids: 1000, memoryBytes: GiB })).toBe(9);
+ });
+
+ it("refuses an OMB_BROWSER_MAX_RUNNING that is not 1 or more with a log line, 0 included, and sizes by the limits", () => {
+ for (const override of ["0", "zero", "-2", "1.5"]) {
+ const warn = vi.fn();
+ expect(browserRoomSize({ override, pids: 1000, memoryBytes: 8 * GiB }, warn)).toBe(2);
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining(`OMB_BROWSER_MAX_RUNNING="${override}" is not a whole number of at least 1`));
+ }
+ const quiet = vi.fn();
+ expect(browserRoomSize({ override: undefined, pids: 1000, memoryBytes: 8 * GiB }, quiet)).toBe(2);
+ expect(browserRoomSize({ override: "", pids: 1000, memoryBytes: 8 * GiB }, quiet)).toBe(2);
+ expect(quiet).not.toHaveBeenCalled();
+ });
+});
+
+describe("a browser over the limit", () => {
+ function room(options: { max: number; spare?: Record<string, number | null>; close?: (session: string) => Promise<boolean> }) {
+ const close = vi.fn(options.close ?? (async () => true));
+ const value = new BrowserRoom({ max: () => options.max, spare: (session) => options.spare?.[session] ?? null, close, waitMs: 300, pollMs: 20 });
+ return { value, close };
+ }
+
+ it("starts at once while there is room, and counts each browser once", async () => {
+ const { value } = room({ max: 2 });
+ expect(await value.enter("a", Date.now() + 1_000)).toBeNull();
+ expect(await value.enter("a", Date.now() + 1_000)).toBeNull();
+ expect(await value.enter("b", Date.now() + 1_000)).toBeNull();
+ expect(value.open).toBe(2);
+ });
+
+ it("closes the least recently used idle browser to make room", async () => {
+ const { value, close } = room({ max: 2, spare: { a: 5_000, b: 60_000 } });
+ await value.enter("a", Date.now() + 1_000);
+ await value.enter("b", Date.now() + 1_000);
+ expect(await value.enter("c", Date.now() + 1_000)).toBeNull();
+ expect(close.mock.calls).toEqual([["b"]]);
+ expect(value.open).toBe(2);
+ });
+
+ it("with none idle, waits for one to leave, else says why it cannot start", async () => {
+ const { value, close } = room({ max: 1 });
+ await value.enter("a", Date.now() + 1_000);
+ const waiting = value.enter("b", Date.now() + 1_000);
+ setTimeout(() => value.left("a"), 50);
+ expect(await waiting).toBeNull();
+ expect(await value.enter("c", Date.now() + 1_000)).toMatch(/^1 browser is already open on this computer, the most it runs at once/);
+ expect(close).not.toHaveBeenCalled();
+ });
+
+ it("does not count a browser it could not close as gone", async () => {
+ const { value, close } = room({ max: 1, spare: { a: 1_000 }, close: async () => false });
+ await value.enter("a", Date.now() + 1_000);
+ expect(await value.enter("b", Date.now() + 100)).toMatch(/already open/);
+ expect(close).toHaveBeenCalled();
+ expect(value.open).toBe(1);
+ });
+
+ it("tries the next least recently used idle browser when one will not close", async () => {
+ const { value, close } = room({ max: 3, spare: { a: 60_000, b: 30_000, c: 5_000 }, close: async (session) => session === "b" });
+ for (const session of ["a", "b", "c"]) await value.enter(session, Date.now() + 1_000);
+ expect(await value.enter("d", Date.now() + 1_000)).toBeNull();
+ expect(close.mock.calls).toEqual([["a"], ["b"]]);
+ expect(value.open).toBe(3);
+ });
+
+ it("says so in the plural with more than one browser open", async () => {
+ const { value } = room({ max: 2 });
+ await value.enter("a", Date.now() + 1_000);
+ await value.enter("b", Date.now() + 1_000);
+ expect(await value.enter("c", Date.now() + 50)).toMatch(/^2 browsers are already open/);
+ });
+
+ it("counts a browser a person's view started, so a bot's new one waits for room", async () => {
+ const { value } = room({ max: 1 });
+ value.entered("viewed");
+ expect(await value.enter("b", Date.now() + 50)).toMatch(/already open/);
+ value.left("viewed");
+ expect(await value.enter("b", Date.now() + 1_000)).toBeNull();
+ });
+});
+
+describe("which browser a bot waiting for a slot may close", () => {
+ const idle = (idleMs: number, savesSignIns = true) => ({ idleMs, savesSignIns });
+ it("any no turn holds, however recently used", () => {
+ expect(spareForRoom(idle(1_000), { holds: false, idleMs: 180_000 })).toBe(1_000);
+ expect(spareForRoom(idle(1_000, false), { holds: false, idleMs: 180_000 })).toBe(1_000);
+ });
+
+ it("one a running turn holds only after the idle time, and only when it reopens with its sign-ins", () => {
+ 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();
+ });
+
+ it("none a call, a person or a view has", () => {
+ expect(spareForRoom(null, { holds: false, idleMs: 180_000 })).toBeNull();
+ });
+});
+
+describe("agent-browser's tool list", () => {
+ it("is read once for each binary and arguments, whichever session asks", async () => {
+ const lists = new SharedToolLists();
+ const load = vi.fn(async () => ({ tools: [{ name: "agent_browser_open" }] }));
+ const spec = { command: "/bin/agent-browser", args: ["mcp"] };
+ const [one, two] = await Promise.all([lists.get(spec, load), lists.get({ ...spec }, load)]);
+ expect(one).toBe(two);
+ expect(await lists.get(spec, load)).toBe(one);
+ expect(lists.known(spec)).toBe(one);
+ expect(load).toHaveBeenCalledTimes(1);
+ await lists.get({ command: "/bin/agent-browser", args: ["mcp", "--other"] }, load);
+ expect(load).toHaveBeenCalledTimes(2);
+ });
+
+ it("is read again after a failed or empty answer", async () => {
+ const lists = new SharedToolLists();
+ const spec = { command: "/bin/agent-browser", args: ["mcp"] };
+ await expect(lists.get(spec, async () => { throw new Error("spawn EAGAIN"); })).rejects.toThrow(/EAGAIN/);
+ expect(await lists.get(spec, async () => ({ error: "no tools" }))).toEqual({ error: "no tools" });
+ expect(lists.known(spec)).toBeUndefined();
+ expect(await lists.get(spec, async () => ({ tools: [] }))).toEqual({ tools: [] });
+ expect(lists.known(spec)).toEqual({ tools: [] });
+ });
+});
diff --git a/server/browser-room.ts b/server/browser-room.ts
new file mode 100644
index 0000000000..ad218263a0
--- /dev/null
+++ b/server/browser-room.ts
@@ -0,0 +1,165 @@
+import { readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { boxMemory } from "./box-memory.ts";
+
+/** One open browser with one page in the server image (Chromium 156, agent-browser 0.37.0): 13 processes, about 160
+ * threads (each counts against a pids limit) and about 350 MB. */
+const BROWSER_THREADS = 160;
+const BROWSER_BYTES = 400 * 1024 * 1024;
+/** The part of the server's limits that browsers may fill; engines and their tools need the rest. */
+const BROWSER_SHARE = 0.4;
+const MOST_BROWSERS = 16;
+const ROOM_WAIT_MS = 30_000;
+
+type Read = (path: string) => string | null;
+const readText: Read = (path) => { try { return readFileSync(path, "utf8"); } catch { return null; } };
+
+/** The tightest `pids.max` from `at` up to the hierarchy's root under `root`. */
+function tightest(read: Read, root: string, from: string): number | null {
+ let limit: number | null = null;
+ for (let at = from.trim(); ; at = dirname(at)) {
+ const value = Number(read(join(root, at, "pids.max"))?.trim());
+ if (Number.isInteger(value) && value > 0) limit = Math.min(limit ?? value, value);
+ if (at === "/" || at === ".") return limit;
+ }
+}
+
+/** The tightest task limit over this process's own cgroup and its parents (a container's --pids-limit, a systemd
+ * TasksMax): cgroup v2 `pids.max` and v1's under the pids controller. A hybrid host lists both, and its limit is often
+ * only in v1's, so both are read. Null with no limit, and off Linux. */
+export function pidsLimit(read: Read = readText): number | null {
+ const membership = read("/proc/self/cgroup");
+ if (membership === null) return null;
+ const v2 = /^0::(\/.*)$/m.exec(membership)?.[1];
+ const v1 = /^\d+:(?:[^:]*,)?pids(?:,[^:]*)?:(\/.*)$/m.exec(membership)?.[1];
+ const limits = [
+ ...(v2 !== undefined ? [tightest(read, "/sys/fs/cgroup", v2), tightest(read, "/sys/fs/cgroup/unified", v2)] : []),
+ ...(v1 !== undefined ? [tightest(read, "/sys/fs/cgroup/pids", v1)] : []),
+ ].filter((limit): limit is number => limit !== null);
+ return limits.length > 0 ? Math.min(...limits) : null;
+}
+
+/** How many agent-browser browsers run at once: `OMB_BROWSER_MAX_RUNNING` (a whole number of at least 1), else what fits
+ * in the browsers' share of the task limit and of the memory this server may use. Any other value, 0 included, is not a
+ * way to turn browsers off (a bot's own browser switch is): it is refused with a log line and the computed size is used. */
+export function browserRoomSize(limits: { override?: string; pids: number | null; memoryBytes: number }, warn: (line: string) => void = () => undefined): number {
+ const override = limits.override?.trim() ? Number(limits.override) : undefined;
+ if (override !== undefined && Number.isInteger(override) && override > 0) return override;
+ if (override !== undefined) warn(`OMB_BROWSER_MAX_RUNNING=${JSON.stringify(limits.override)} is not a whole number of at least 1, so it is ignored; set it to 1 or more, or unset it to size the browsers by this server's limits`);
+ const byMemory = Math.floor((limits.memoryBytes * BROWSER_SHARE) / BROWSER_BYTES);
+ const byTasks = limits.pids === null ? MOST_BROWSERS : Math.floor((limits.pids * BROWSER_SHARE) / BROWSER_THREADS);
+ return Math.max(1, Math.min(MOST_BROWSERS, byMemory, byTasks));
+}
+
+let size: number | undefined;
+export function defaultBrowserRoomSize(env: NodeJS.ProcessEnv = process.env): number {
+ size ??= browserRoomSize({ override: env.OMB_BROWSER_MAX_RUNNING, pids: pidsLimit(), memoryBytes: boxMemory().bytes }, (line) => console.warn(`browser: ${line}`));
+ return size;
+}
+
+/** What the room may close for a bot waiting on a slot (how long the browser sat unused), or null. A browser no turn holds
+ * may go. One a running turn holds goes only here, never in the regular idle sweep, and only once it sat unused for the
+ * idle time and reopens with its sign-ins: open pages are lost either way, and a temporary browser would lose its
+ * sign-ins too, so the turn keeps it. */
+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;
+}
+
+export interface BrowserRoomOptions {
+ max(): number;
+ /** How long the session's browser has sat unused (ms) when it may be closed now; null while a call, a person, a view
+ * or a running turn that could not get the same browser back has it. */
+ spare(session: string): number | null;
+ /** Closes an unused browser; true once it is gone. */
+ close(session: string): Promise<boolean>;
+ waitMs?: number;
+ pollMs?: number;
+}
+
+/** Counts the browsers agent-browser runs for this server. A browser over the limit starts once the least recently used
+ * spare one is closed; with none to close its call waits, then is told why it cannot start. */
+export class BrowserRoom {
+ readonly #open = new Set<string>();
+ readonly #options: BrowserRoomOptions;
+
+ constructor(options: BrowserRoomOptions) { this.#options = options; }
+
+ get open(): number { return this.#open.size; }
+
+ /** Null once `session` may run a browser; otherwise the refusal for the bot. */
+ async enter(session: string, deadline: number): Promise<string | null> {
+ const until = Math.min(deadline, Date.now() + (this.#options.waitMs ?? ROOM_WAIT_MS));
+ for (;;) {
+ if (this.#open.has(session)) return null;
+ const others = [...this.#open];
+ if (others.length < Math.max(1, this.#options.max())) {
+ this.#open.add(session);
+ return null;
+ }
+ if (await this.#closeOneSpare(others)) continue;
+ if (Date.now() >= until) return `${others.length === 1 ? "1 browser is" : `${others.length} browsers are`} already open on this computer, the most it runs at once. Wait for another bot to finish with its browser, then try again.`;
+ await new Promise((resolve) => setTimeout(resolve, Math.min(this.#options.pollMs ?? 500, Math.max(1, until - Date.now()))));
+ }
+ }
+
+ /** Spare browsers, least recently used first, until one closes; one that will not close leaves the next to try. */
+ async #closeOneSpare(others: readonly string[]): Promise<boolean> {
+ const spare = others.flatMap((other) => { const idle = this.#options.spare(other); return idle === null ? [] : [{ other, idle }]; })
+ .sort((a, b) => b.idle - a.idle);
+ for (const { other } of spare) {
+ // Asked again just before closing: an earlier close's wait may have let a call or a person in.
+ if (!this.#open.has(other) || this.#options.spare(other) === null) continue;
+ if (await this.#options.close(other).catch(() => false)) {
+ this.#open.delete(other);
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /** A browser that runs whether or not a call started it, such as one a person's view opened. */
+ entered(session: string): void { this.#open.add(session); }
+
+ left(session: string): void { this.#open.delete(session); }
+}
+
+const REFUSED = new WeakSet<object>();
+/** A call's answer when every browser allowed is open: it reached no browser. */
+export function slotRefusal(text: string): { isError: true; content: Array<{ type: "text"; text: string }> } {
+ const refusal = { isError: true as const, content: [{ type: "text" as const, text }] };
+ REFUSED.add(refusal);
+ return refusal;
+}
+/** A slot refusal opened nothing, so a note that this call reopened the browser waits for the call that does. */
+export function refusedSlot(result: unknown): boolean { return typeof result === "object" && result !== null && REFUSED.has(result); }
+
+type ListedSpec = { command: string; args: readonly string[] };
+const listKey = (spec: ListedSpec) => JSON.stringify([spec.command, ...spec.args]);
+
+/** agent-browser's tool list follows from its binary and arguments, never from the session, so one answer serves every
+ * session and listing tools starts no `agent-browser mcp` process of its own. */
+export class SharedToolLists {
+ readonly #lists = new Map<string, Promise<unknown>>();
+ readonly #known = new Map<string, unknown>();
+
+ /** `check` runs first on every ask, as a session's own connection would check its launch settings. */
+ get(spec: ListedSpec, load: () => Promise<unknown>, check?: () => void): Promise<unknown> {
+ try { check?.(); } catch (error) { return Promise.reject(error); }
+ const key = listKey(spec);
+ let list = this.#lists.get(key);
+ if (!list) {
+ list = load().then((result) => {
+ if (Array.isArray((result as { tools?: unknown } | null)?.tools)) this.#known.set(key, result);
+ else this.#lists.delete(key);
+ return result;
+ }, (error: unknown) => { this.#lists.delete(key); throw error; });
+ this.#lists.set(key, list);
+ }
+ return list;
+ }
+
+ /** The list already read for these launch settings, if any. */
+ known(spec: ListedSpec): unknown { return this.#known.get(listKey(spec)); }
+}
diff --git a/server/browser-runtime.test.ts b/server/browser-runtime.test.ts
index aad1a04186..b9eeac54f0 100644
--- a/server/browser-runtime.test.ts
+++ b/server/browser-runtime.test.ts
@@ -6,6 +6,7 @@ import { addHeldSecretScrubber, HELD_SECRET_MASK } from "../shared/redact.ts";
import { BROWSER_VIEWPORT } from "./browser-page-size.ts";
import { BROWSER_CALL_DEFAULTS, BROWSER_HOVER_TOOL, BROWSER_RESTART_TOOL, BROWSER_UPLOAD_TOOL, BrowserRuntime, TransportError, browserRuntimeEnv, formatBrowserTiming, type BrowserSpawnSpec, type BrowserTiming } from "./browser-runtime.ts";
import { launchSettingsKey } from "./browser-launch-key.ts";
+import { BrowserRoom } from "./browser-room.ts";
import { HARNESS_CALL_BUDGET_MS, HARNESS_PROXY_TIMEOUT_MS } from "./harness-budget.ts";
import { RelayPorts } from "./browser-relay.ts";
import { BrowserSteps, type StepCall, type StepContext } from "./browser-steps.ts";
@@ -560,7 +561,9 @@ describe("server-owned browser MCP runtime", () => {
expect(responses.map((r) => r.pid)).toEqual([list.pid, list.pid]);
expect(responses[0].content[0].text).toContain("first");
expect(responses[1].content[0].text).toContain("second");
- const other = await value.agentRpc("two", spec(), "tools/list", {}) as { pid: number };
+ // Another session's list is the same answer and starts no engine process of its own; its calls get their own client.
+ expect(await value.agentRpc("two", spec(), "tools/list", {})).toEqual(list);
+ const other = await value.agentRpc("two", spec(), "tools/call", { name: "echo", arguments: { text: "other" } }) as { pid: number };
expect(other.pid).not.toBe(list.pid);
await value.take("one", "owner");
await expect(value.agentRpc("one", spec(), "tools/call", { name: "echo" })).rejects.toThrow(/paused/);
@@ -662,6 +665,23 @@ describe("server-owned browser MCP runtime", () => {
expect(after.content.map((part) => part.text).join("\n")).not.toMatch(/sat unused/);
});
+ it("keeps the reopened note for the call that reopens the browser, not one refused a slot", async () => {
+ const room = new BrowserRoom({ max: () => 1, spare: () => null, close: async () => false, waitMs: 30, pollMs: 10 });
+ const value = runtime({ closeBrowser: async () => true, room });
+ await value.agentRpc("s", spec(), "tools/call", { name: "echo", arguments: { text: "first" } });
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ expect(await value.closeIfIdle("s", 20)).toBe(true);
+ // Another bot's browser took the one slot while this one was closed.
+ expect(await room.enter("other", Date.now() + 1_000)).toBeNull();
+ const refused = await value.agentRpc("s", spec(), "tools/call", { name: "echo", arguments: { text: "again" } }) as { isError?: boolean; content: Array<{ text: string }> };
+ expect(refused.isError).toBe(true);
+ expect(refused.content.map((part) => part.text)).toEqual([expect.stringMatching(/^1 browser is already open on this computer/)]);
+ room.left("other");
+ const reopened = await value.agentRpc("s", spec(), "tools/call", { name: "echo", arguments: { text: "third" } }) as { content: Array<{ text: string }> };
+ expect(reopened.content[0].text).toMatch(/sat unused and was closed/);
+ expect(reopened.content[1].text).toContain("third");
+ });
+
it("tells a bot whose temporary browser closed while idle that its sign-ins went with it", async () => {
const value = runtime({ closeBrowser: async () => true });
const temporary = { ...spec(), env: { ...spec().env, AGENT_BROWSER_RESTORE_SAVE: "never" } };
@@ -991,23 +1011,24 @@ describe("server-owned browser MCP runtime", () => {
expect(value.canControl("s", "owner")).toBe(true);
});
- it("bounds concurrent requests without queuing more work behind a hung action", async () => {
+ it("queues no more work behind a hung action: the tool list answers from the one already read", async () => {
const value = runtime({ maxPending: 1, requestTimeoutMs: 250 });
- await value.agentRpc("s", spec(), "tools/list", {});
+ const list = await value.agentRpc("s", spec(), "tools/list", {});
const pending = value.agentRpc("s", spec(), "tools/call", { name: "hang" });
const observed = expect(pending).resolves.toMatchObject({ isError: true });
await new Promise((resolve) => setTimeout(resolve, 20)); // the hang reaches the engine
- await expect(value.agentRpc("s", spec(), "tools/list", {})).rejects.toThrow(/Too many pending/);
+ await expect(value.agentRpc("s", spec(), "tools/list", {})).resolves.toEqual(list);
await observed;
});
it("evicts idle transports without dropping a human hold", async () => {
const value = runtime({ idleMs: 30 });
- const before = await value.agentRpc("s", spec(), "tools/list", {}) as { pid: number };
+ const before = await value.agentRpc("s", spec(), "tools/call", { name: "echo" }) as { pid: number };
await value.take("s", "owner");
await new Promise((resolve) => setTimeout(resolve, 80));
expect(value.heldBy("s")).toBe("owner");
- const after = await value.agentRpc("s", spec(), "tools/list", {}) as { pid: number };
+ value.release("s", "owner");
+ const after = await value.agentRpc("s", spec(), "tools/call", { name: "echo" }) as { pid: number };
expect(after.pid).not.toBe(before.pid);
});
diff --git a/server/browser-runtime.ts b/server/browser-runtime.ts
index 1aed61fba3..5ba47e53b3 100644
--- a/server/browser-runtime.ts
+++ b/server/browser-runtime.ts
@@ -7,6 +7,7 @@ import { SECRET_ON_PAGE, SecretHolds, type SecretHold } from "./browser-secret-h
import type { BrowserSteps, StepCall, StepContext } from "./browser-steps.ts";
import { HARNESS_CALL_BUDGET_MS } from "./harness-budget.ts";
import { launchSettingsKey } from "./browser-launch-key.ts";
+import { refusedSlot, SharedToolLists, slotRefusal, type BrowserRoom } from "./browser-room.ts";
export interface BrowserSpawnSpec {
command: string;
@@ -333,12 +334,13 @@ export class BrowserRuntime {
private gates = new Map<string, Gate>();
private clients = new Map<string, ClientEntry>();
private recoveries = new Map<string, Promise<string | null>>();
- private toolLists = new Map<string, unknown>();
private idleCloseListeners = new Set<(session: string) => void>();
private options: { requestTimeoutMs: number; takeoverTimeoutMs: number; idleMs: number; maxPending: number; resultBudget: number; recoveryCheckMs: number; laneWaitMs: number; callBudgetMs: number; followUpReserveMs: number };
private closeBrowser: CloseBrowser;
private applyViewport?: ApplyViewport;
private launch?: BrowserLaunch;
+ private room?: BrowserRoom;
+ private listings = new SharedToolLists();
private relayCommand?: RelayCommand;
private steps?: Pick<BrowserSteps, "before" | "after" | "signIn" | "note" | "forget" | "recentFrame" | "personTook">;
private lanes = new BrowserLanes();
@@ -353,11 +355,11 @@ export class BrowserRuntime {
private scrub: (text: string) => string;
private onTiming?: (timing: BrowserTiming) => void;
- constructor({ closeBrowser, applyViewport, launch, relayCommand, steps, scrub, onTiming, ...options }: Partial<BrowserRuntime["options"]> & { closeBrowser?: CloseBrowser; applyViewport?: ApplyViewport; launch?: BrowserLaunch; relayCommand?: RelayCommand; steps?: BrowserRuntime["steps"]; scrub?: (text: string) => string; onTiming?: (timing: BrowserTiming) => void } = {}) {
+ constructor({ closeBrowser, applyViewport, launch, room, relayCommand, steps, scrub, onTiming, ...options }: Partial<BrowserRuntime["options"]> & { closeBrowser?: CloseBrowser; applyViewport?: ApplyViewport; launch?: BrowserLaunch; room?: BrowserRoom; relayCommand?: RelayCommand; steps?: BrowserRuntime["steps"]; scrub?: (text: string) => string; onTiming?: (timing: BrowserTiming) => void } = {}) {
this.options = { ...BROWSER_CALL_DEFAULTS, takeoverTimeoutMs: 15_000, idleMs: 60_000, maxPending: 16, resultBudget: DEFAULT_BROWSER_RESULT_BUDGET, recoveryCheckMs: 30_000, ...options };
this.closeBrowser = closeBrowser ?? (async () => false);
this.applyViewport = applyViewport;
- this.launch = launch;
+ this.launch = launch; this.room = room;
this.relayCommand = relayCommand;
this.steps = steps;
this.scrub = scrub ?? scrubHeldSecrets;
@@ -464,7 +466,7 @@ export class BrowserRuntime {
} finally { gate.calls--; gate.lastUsed = Date.now(); }
if (method !== "tools/call") return result;
if (result === null || result === undefined) return scrubBrowserResult({ isError: true, content: [{ type: "text", text: LANE_BUSY }] }, this.scrub);
- if (!gate.reopened) return scrubBrowserResult(result, this.scrub);
+ if (!gate.reopened || refusedSlot(result)) return scrubBrowserResult(result, this.scrub);
const note = gate.reopened === "restart" ? PERSON_RESTARTED : idleClosedNote(spec.env.AGENT_BROWSER_RESTORE_SAVE !== "never");
gate.reopened = null;
const content = (result as { content?: unknown } | null)?.content;
@@ -498,7 +500,7 @@ export class BrowserRuntime {
const toolName = toolNameOf(params);
const gate = this.gate(session);
if (gate.uncertain) {
- if (method === "tools/list") return withOmbTools(this.toolLists.get(session) ?? { tools: [] });
+ if (method === "tools/list") return withOmbTools(this.listings.known(spec) ?? { tools: [] });
if (gate.owner !== null) throw new Error(BROWSER_CONTROL_REFUSAL);
const lostCall = gate.lostCall;
if (lostCall === null) return stuckBrowserToolError();
@@ -513,6 +515,8 @@ export class BrowserRuntime {
const invoke = async () => {
const launchStarted = performance.now();
let dispatched = false;
+ const full = method === "tools/call" && toolName !== "agent_browser_close" && !attachesToChrome(spec.env) ? await this.room?.enter(session, deadline - this.options.followUpReserveMs) : null;
+ if (full) return slotRefusal(full);
if (method === "tools/call") await this.launchReady(spec);
const entry = this.connect(session, spec);
await entry.client.ready;
@@ -575,9 +579,7 @@ export class BrowserRuntime {
phases.engineMs = performance.now() - engineStarted;
beforeDispatch?.();
if (method === "tools/list") {
- const tools = withOmbTools(slimBrowserToolList(result));
- this.toolLists.set(session, tools);
- return tools;
+ return withOmbTools(slimBrowserToolList(result));
}
if (before && result && typeof result === "object" && (result as { isError?: boolean }).isError !== true &&
this.gate(session).owner === null) {
@@ -640,7 +642,7 @@ export class BrowserRuntime {
}
finally { if (dispatched) gate.dispatched--; }
};
- if (method !== "tools/call") return invoke();
+ if (method !== "tools/call") return this.listings.get(spec, invoke, () => this.sameLaunch(session, spec));
try {
return await this.timed(session, toolName ?? "unknown", phases, () => this.withAgentAction(session, invoke));
} catch (error) {
@@ -666,10 +668,14 @@ export class BrowserRuntime {
}
}
- private connect(session: string, spec: BrowserSpawnSpec): ClientEntry {
+ private sameLaunch(session: string, spec: BrowserSpawnSpec): string {
const key = launchSettingsKey(spec);
+ if (this.clients.get(session) && this.clients.get(session)!.key !== key) throw new Error("Browser launch settings changed. Close the browser before reconnecting.");
+ return key;
+ }
+ private connect(session: string, spec: BrowserSpawnSpec): ClientEntry {
+ const key = this.sameLaunch(session, spec);
const existing = this.clients.get(session);
- if (existing && existing.key !== key) throw new Error("Browser launch settings changed. Close the browser before reconnecting.");
if (existing) return existing;
const client = new BrowserClient(spec, this.options.requestTimeoutMs, this.options.idleMs, this.options.maxPending, () => {
if (this.clients.get(session)?.client === client) this.clients.delete(session);
@@ -831,6 +837,13 @@ export class BrowserRuntime {
/** Told just before an idle close stops a session's browser. */
onIdleClose(listener: (session: string) => void): void { this.idleCloseListeners.add(listener); }
+ private browserStopped(session: string): void { this.launch?.stopped(session); this.room?.left(session); }
+ /** How long the session's browser has sat unused and whether a reopened one keeps its sign-ins; null while a call, a person or a view has it. */
+ spare(session: string): { idleMs: number; savesSignIns: boolean } | null {
+ const gate = this.gates.get(session);
+ return !gate?.spec || gate.watchers > 0 || this.working(session) ? null : { idleMs: Date.now() - gate.lastUsed, savesSignIns: gate.spec.env.AGENT_BROWSER_RESTORE_SAVE === "auto" };
+ }
+
launchReady(spec: LaunchSpec): Promise<void> { return this.launch?.ready(spec) ?? Promise.resolve(); }
/** A browser without its identity still browses, so a failure here never fails the call. */
@@ -852,7 +865,7 @@ export class BrowserRuntime {
for (const listener of this.idleCloseListeners) listener(session);
if (!await this.closeBrowser(session, launch)) return false;
this.steps?.forget(session);
- this.launch?.stopped(session);
+ this.browserStopped(session);
await this.clients.get(session)?.client.stop();
await this.clients.get(session)?.client.stop();
gate.uncertain = false;
@@ -883,7 +896,7 @@ export class BrowserRuntime {
try {
await closeBrowser();
this.steps?.forget(session);
- this.launch?.stopped(session);
+ this.browserStopped(session);
await this.clients.get(session)?.client.stop();
// A tools/list admitted before closing can register a client during this stop; registration is synchronous, so one re-check suffices.
await this.clients.get(session)?.client.stop();
@@ -914,7 +927,7 @@ export class BrowserRuntime {
try {
if (!await closeBrowser()) throw new Error("The browser could not be closed. Ask the person to press Restart in the Browser panel of OpenMausBot on their computer, or to restart OpenMausBot.");
this.steps?.forget(session);
- this.launch?.stopped(session);
+ this.browserStopped(session);
await this.clients.get(session)?.client.stop();
await this.clients.get(session)?.client.stop();
gate.uncertain = false;
@@ -936,7 +949,7 @@ export class BrowserRuntime {
gate.closing = true;
gate.ready = false;
this.steps?.forget(session);
- this.launch?.stopped(session);
+ this.browserStopped(session);
// Clear before the awaited stop: any uncertain latch after this point must win.
gate.uncertain = false;
gate.lostCall = null;
@@ -944,7 +957,7 @@ export class BrowserRuntime {
await this.clients.get(session)?.client.stop();
gate.closing = false;
this.changed(gate);
- if (!gate.owner && !gate.agents && !gate.humans && !gate.watchers && !gate.calls) { this.gates.delete(session); this.toolLists.delete(session); }
+ if (!gate.owner && !gate.agents && !gate.humans && !gate.watchers && !gate.calls) this.gates.delete(session);
}
async closeAll(): Promise<void> {
diff --git a/server/host/browser.test.ts b/server/host/browser.test.ts
index ea2d896d9a..dec9497d42 100644
--- a/server/host/browser.test.ts
+++ b/server/host/browser.test.ts
@@ -45,10 +45,10 @@ afterEach(async () => { await Promise.all(hosts.splice(0).map((host) => host.bro
const turn = { threadId: "thread-1", generation: "gen-1" };
-function setup(engine: "chrome" | "agent-browser" | undefined, { cloudHome = false, server = false, hosted = false, device, lendRefusal, holder, audienceOf, bots: botIds = ["scout"], browserBox, lentChrome, turnResources }: {
+function setup(engine: "chrome" | "agent-browser" | undefined, { cloudHome = false, server = false, hosted = false, device, lendRefusal, holder, audienceOf, bots: botIds = ["scout"], browserBox, lentChrome, turnResources, browsersAtOnce }: {
cloudHome?: boolean; server?: boolean; hosted?: boolean; device?: BrowserHostDeps["device"]; lendRefusal?: BrowserHostDeps["lendRefusal"]; holder?: (resource: string) => TurnOwner | undefined;
audienceOf?: BrowserHostDeps["audienceOf"]; bots?: string[]; browserBox?: BrowserHostDeps["browserBox"];
- lentChrome?: BrowserHostDeps["lentChrome"]; turnResources?: BrowserHostDeps["turnResources"];
+ lentChrome?: BrowserHostDeps["lentChrome"]; turnResources?: BrowserHostDeps["turnResources"]; browsersAtOnce?: BrowserHostDeps["browsersAtOnce"];
} = {}) {
const cfg = {
features: { browser: true },
@@ -75,6 +75,7 @@ function setup(engine: "chrome" | "agent-browser" | undefined, { cloudHome = fal
audienceOf,
browserBox,
lentChrome,
+ browsersAtOnce,
});
hosts.push(host);
return { cfg, host, minted, bots };
@@ -622,6 +623,93 @@ describe("a deleted bot's browser", () => {
});
});
+describe("a running turn's agent-browser browser", () => {
+ const ENGINE = "/usr/local/bin/agent-browser";
+ const HOUR = 3_600_000;
+ const folders: string[] = [];
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.mocked(Date.now).mockRestore?.();
+ for (const folder of folders.splice(0)) rmSync(folder, { recursive: true, force: true });
+ });
+ function ready() {
+ vi.mocked(browserEngineStatus).mockImplementation(() => ({ kind: "ready", binaryPath: ENGINE, version: "0.37.0", managed: false }));
+ vi.mocked(closeBrowserSession).mockClear().mockResolvedValue(true);
+ vi.mocked(runningBrowserSessionNames).mockClear();
+ }
+ function daemons(sessions: string[]) {
+ const folder = mkdtempSync(join(tmpdir(), "omb-host-room-"));
+ folders.push(folder);
+ mkdirSync(join(folder, "agent-browser"));
+ for (const session of sessions) writeFileSync(join(folder, "agent-browser", `${session}.pid`), "0");
+ vi.stubEnv("XDG_RUNTIME_DIR", folder);
+ vi.mocked(runningBrowserSessionNames).mockResolvedValue(sessions);
+ }
+ /** Every browser's clock an hour on: each one has sat unused past a Cloud home's 3 minutes. */
+ function anHourLater() {
+ const real = Date.now.bind(Date);
+ vi.spyOn(Date, "now").mockImplementation(() => real() + HOUR);
+ }
+ const holding = (sessions: string[]): BrowserHostDeps["turnResources"] => ({
+ free: (resource) => !sessions.some((session) => resource === `browser:${session}`), holder: () => undefined, onClaim: () => () => {},
+ });
+ const closedSessions = () => vi.mocked(closeBrowserSession).mock.calls.map(([, env]) => env.AGENT_BROWSER_SESSION);
+ const keepsSignIns = { command: ENGINE, env: { AGENT_BROWSER_RESTORE_SAVE: "auto" } };
+ const temporary = { command: ENGINE, env: { AGENT_BROWSER_RESTORE_SAVE: "never" } };
+
+ it("is never closed by the idle sweep, however long it sat unused, while one no turn holds is", async () => {
+ for (const held of [true, false]) {
+ ready();
+ daemons(["bot-scout"]);
+ const { host } = setup(undefined, { cloudHome: true, turnResources: holding(held ? ["bot-scout"] : []) });
+ host.usedBrowserSessions.set("bot-scout", keepsSignIns);
+ expect(await host.browserRuntime.closeIfIdle("bot-scout", HOUR * 1_000, keepsSignIns)).toBe(false);
+ anHourLater();
+ host.browserSweep.start();
+ if (held) {
+ await vi.waitFor(() => expect(runningBrowserSessionNames).toHaveBeenCalled());
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(closedSessions()).toEqual([]);
+ } else {
+ await vi.waitFor(() => expect(closedSessions()).toEqual(["bot-scout"]));
+ }
+ vi.mocked(Date.now).mockRestore();
+ vi.mocked(closeBrowserSession).mockClear();
+ await host.browserSweep.closeAll();
+ }
+ });
+
+ it("is closed for a bot waiting on a full limit only once it sat unused for the idle time and keeps its sign-ins", async () => {
+ ready();
+ const { host } = setup(undefined, { cloudHome: true, turnResources: holding(["bot-a", "bot-t"]), browsersAtOnce: () => 2 });
+ for (const [session, spec] of [["bot-a", keepsSignIns], ["bot-t", temporary]] as const) {
+ expect(await host.browserRoom.enter(session, Date.now() + 1_000)).toBeNull();
+ expect(await host.browserRuntime.closeIfIdle(session, HOUR * 1_000, spec)).toBe(false);
+ }
+ // Just used: the waiting bot is told why, and the turn keeps both.
+ expect(await host.browserRoom.enter("bot-b", Date.now() + 100)).toMatch(/^2 browsers are already open/);
+ expect(closedSessions()).toEqual([]);
+ anHourLater();
+ expect(await host.browserRoom.enter("bot-b", Date.now() + 1_000)).toBeNull();
+ // The temporary browser would lose its sign-ins, so the turn keeps it.
+ expect(closedSessions()).toEqual(["bot-a"]);
+ expect(host.browserRoom.open).toBe(2);
+ });
+
+ it("counts toward the limit when a person's view started it, but not the person's own Chrome", async () => {
+ ready();
+ const { host } = setup(undefined, { cloudHome: true, browsersAtOnce: () => 1 });
+ // The live view tells agent-browser's runtime directly; the router hides it, so it is found through a call.
+ const closing = vi.spyOn(BrowserRuntime.prototype, "closeIfIdle");
+ await host.browserRuntime.closeIfIdle("bot-viewed", 1);
+ const agentBrowser = closing.mock.contexts[0] as BrowserRuntime;
+ closing.mockRestore();
+ await agentBrowser.launched("bot-viewed", keepsSignIns);
+ await agentBrowser.launched("bot-mine", { command: ENGINE, env: { AGENT_BROWSER_CDP: "http://127.0.0.1:9222" } });
+ expect(host.browserRoom.open).toBe(1);
+ });
+});
+
const teamAudiences = (threadId: string): Audience => ({ "ada-chat": "member:p_ada", "cleo-chat": "member:p_cleo", "room-chat": "room:launch" } as Record<string, Audience>)[threadId] ?? "team";
const at = (threadId: string) => ({ threadId, generation: "gen-1" });
const AUDIENCES_FILE = join(DATA_DIR, "browser", "audiences.json");
diff --git a/server/host/browser.ts b/server/host/browser.ts
index 202c1f89d2..ed8757df1d 100644
--- a/server/host/browser.ts
+++ b/server/host/browser.ts
@@ -28,6 +28,7 @@ import {
noteBrowserEngineUnavailable,
setBrowserViewport,
} from "../browser-engine.ts";
+import { BrowserRoom, defaultBrowserRoomSize, spareForRoom } from "../browser-room.ts";
import { BrowserSweep, browserIdleMs, type BrowserCleanupWireRequest } from "../browser-lifecycle-cleanup.ts";
import { AudienceBrowsers, audienceBrowserSuffix } from "../browser/audience.ts";
import type { BrowserSitesTarget } from "../browser-sites.ts";
@@ -82,6 +83,8 @@ export interface BrowserHostDeps {
audienceOf?(threadId: string): Audience;
/** The box every Chrome of the bots' browsers runs in (a Team Cloud's), or none. */
browserBox?(seccompFd: number, ro: readonly string[]): LauncherBox | null;
+ /** How many agent-browser browsers run at once; sized by this server's limits without it. */
+ browsersAtOnce?(): number;
}
/** The lent computer's connection for a browser's pages, under the rule for everything it lends: only while the last
@@ -105,10 +108,25 @@ export function createBrowserHost(deps: BrowserHostDeps) {
const store: Pick<Store, "bots" | "bot" | "botByThread"> = { get bots() { return deps.store().bots; }, bot: (id: string) => deps.store().bot(id),
botByThread: (threadId: string) => deps.store().botByThread(threadId) };
+ // Only a bot waiting for a slot closes a browser a running turn holds; the idle sweep below never does.
+ const browserRoom = new BrowserRoom({
+ max: deps.browsersAtOnce ?? (() => defaultBrowserRoomSize()),
+ spare: (session) => spareForRoom(agentBrowserRuntime.spare(session), { holds: !turnResources.free(`browser:${session}`), idleMs: idleMs() }),
+ close: (session) => agentBrowserRuntime.closeIfIdle(session, 1),
+ });
const agentBrowserRuntime = new BrowserRuntime({
closeBrowser: (session, spec) => closeBrowserSession(spec.command, browserRuntimeEnv({ ...spec.env, AGENT_BROWSER_SESSION: session })),
applyViewport: (spec, size) => setBrowserViewport(spec.command, spec.env, size),
- launch: chromeLauncher,
+ // A browser a person's view started counts toward the limit too. It is not refused, so a bot's next new one waits.
+ launch: {
+ ready: (spec) => chromeLauncher.ready(spec),
+ started: (session, spec) => {
+ if (!attachesToChrome(spec.env ?? {})) browserRoom.entered(session);
+ return chromeLauncher.started(session, spec);
+ },
+ stopped: (session) => chromeLauncher.stopped(session),
+ },
+ room: browserRoom,
relayCommand: (spec, session, command, timeoutMs) => relayCommand(spec, session, command, timeoutMs).catch((error: unknown) => {
throw error instanceof RelayTimeout ? new TransportError(error.message) : error;
}),
@@ -561,7 +579,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {
}
return {
- browserRuntime, browserLive, usedBrowserSessions, browserSweep, temporaryBrowserSessions, browserIdleMs: idleMs,
+ browserRuntime, browserLive, browserRoom, usedBrowserSessions, browserSweep, temporaryBrowserSessions, browserIdleMs: idleMs,
currentBrowserSession, forgetTemporaryBrowser, myChromeAvailable, lentChromeSummary, usesMyChrome, browserSessionSpec, browserIntegration,
browserReady, currentBrowserSpec, loginInput, browserSystemPrompt, signedInSitesRefusal, closeBrowser, browserEngineSwitched,
eraseDeletedBrowser, engineSummary, engineBrowsers, browserAudience, browserSessionsOf, signedInSitesTarget, uploadPaths,