Skip to content

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

Cloud browser: a 12 s open deadline, timed from the start, 403 old-relay, deleted bots erased, a reopened-browser line, no start for a refused call

milind-soni05170fda0085
diff --git a/server/cloud-browser/cloud-browser.test.ts b/server/cloud-browser/cloud-browser.test.ts
index 4a3fe588c7..e286dab0c4 100644
--- a/server/cloud-browser/cloud-browser.test.ts
+++ b/server/cloud-browser/cloud-browser.test.ts
@@ -11,7 +11,7 @@ import { ComputerIdleTimer } from "../computer-idle.ts";
import { LOCAL_SCHEME_REFUSAL, localSchemeRefusal } from "./guards.ts";
import { SESSION_DOWNLOAD_BYTES, SIGN_IN_SYNC_MS, UPLOAD_MAX_BYTES, type SignInStore } from "./companion.ts";
import { cookieParam } from "./sign-ins.ts";
-import { CLOUD_BROWSER_IDLE_MS, createCloudBrowser, SANDBOX_IDLE_TTL_SECONDS, TTL_REFRESH_MS, type CloudBrowserDeps } from "./index.ts";
+import { CLOUD_BROWSER_IDLE_MS, createCloudBrowser, OPEN_DEADLINE_MS, REOPENED_NOTE, SANDBOX_IDLE_TTL_SECONDS, TTL_REFRESH_MS, type CloudBrowserDeps } from "./index.ts";
import { CLOUD_BROWSER_BACKOFF_MS, createCloudBrowserRails } from "./rails.ts";
import { BROWSER_SANDBOX_CHROMES, BROWSER_SANDBOX_OWNER, browserSandboxCreateBody, profileKey, providerOps, ttlSecondsOf } from "./remote.ts";
import { RELAY_KEY, RELAY_TOKEN, startFakeComputer, type FakeComputer } from "./testing/fake-computer.ts";
@@ -326,6 +326,84 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>
expect(cloud.report().resumes).toBe(1);
});
+ it("never keeps a call waiting past the open deadline: a sandbox stuck coming up opens the home's browser, and is ready for the next call", async () => {
+ expect(OPEN_DEADLINE_MS).toBe(12_000);
+ fake.state = "archived";
+ fake.stall.set("/browser", 600);
+ const cloud = browser({ openDeadlineMs: 150 });
+ const started = Date.now();
+ expect(await cloud.open(request())).toEqual({ home: "slow" });
+ expect(Date.now() - started, "answered at the deadline, not when the sandbox was").toBeLessThan(550);
+ expect(cloud.report().fallbacks).toMatchObject({ slow: 1 });
+ // It went on coming up meanwhile, timed by the idle path from its start: the next call finds it awake.
+ await vi.waitFor(() => expect(fake.launches()).toBe(1));
+ await vi.waitFor(() => expect(cloud.busy(BROWSER_SANDBOX_OWNER)).toBe(false));
+ expect(used[0]).toEqual([BROWSER_SANDBOX_OWNER, CLOUD_BROWSER_IDLE_MS]);
+ expect(cloud.active("bot-scout"), "this call stayed in the home: its session is not on the sandbox").toBeNull();
+ urlOf(await cloud.open(request()));
+ expect(fake.resumes(), "the next call needs no start").toBe(1);
+ });
+
+ it("times a sandbox from the moment its start was sent, even when the wake then fails", async () => {
+ fake.state = "archived";
+ fake.startStatus = 500;
+ fake.startBody = { ok: false, message: "resume failed" };
+ const cloud = browser();
+ expect(await cloud.open(request())).toEqual({ home: "start-failed" });
+ expect(used[0], "armed at the start, never left untimed").toEqual([BROWSER_SANDBOX_OWNER, CLOUD_BROWSER_IDLE_MS]);
+ });
+
+ it("treats an older Admin's 403 not_available on the probe as the old relay too", async () => {
+ fake.exists = false;
+ fake.oldRelay = true;
+ fake.oldRelayAnswer = 403;
+ const cloud = browser();
+ expect(await cloud.open(request())).toEqual({ home: "old-relay" });
+ expect(fake.creates()).toBe(0);
+ });
+
+ it("tells the bot's next call that the browser was reopened after its session in the sandbox closed, here or in the home", async () => {
+ const cloud = browser();
+ urlOf(await cloud.open(request()));
+ clock += CLOUD_BROWSER_IDLE_MS;
+ await cloud.closeIdle();
+ expect(cloud.takeNotes("bot-scout")).toEqual([REOPENED_NOTE]);
+ expect(cloud.takeNotes("bot-scout"), "said once").toEqual([]);
+ // A session that ended because its sandbox stopped: the same line, whatever opens next.
+ urlOf(await cloud.open(request()));
+ fake.state = "archived";
+ await cloud.failed("bot-scout");
+ expect(cloud.takeNotes("bot-scout")).toEqual([REOPENED_NOTE]);
+ });
+
+ it("erases a deleted bot's profile in the sandbox, ends its session without writing its sign-ins home, and keeps the erase for the next wake when asleep", async () => {
+ const home = memorySignIns({ cookies: [SIGNED_IN], origins: [] });
+ const cloud = browser({ signIns: home.store });
+ urlOf(await cloud.open(request()));
+ fake.cookies.set(profileKey("scout"), [{ name: "late", value: "x", domain: "late.example", path: "/" }]);
+ await cloud.erase("scout");
+ expect(fake.erased).toEqual([profileKey("scout")]);
+ expect(home.writes, "the deleted bot's cookies never go back to the home").toEqual([]);
+ expect(cloud.takeNotes("bot-scout")).toEqual([]);
+ // Asleep: kept, and done at the next wake for anyone.
+ clock += CLOUD_BROWSER_IDLE_MS;
+ await cloud.closeIdle();
+ fake.state = "archived";
+ await cloud.erase("writer");
+ expect(fake.erased).toEqual([profileKey("scout")]);
+ expect(fake.resumes(), "a deletion never wakes the sandbox").toBe(0);
+ urlOf(await cloud.open(request("chief")));
+ expect(fake.erased).toEqual([profileKey("scout"), profileKey("writer")]);
+ });
+
+ it("carries the home's cookies in batches, not one call each", async () => {
+ const many = Array.from({ length: 250 }, (_, i) => ({ ...SIGNED_IN, name: `c${i}` }));
+ const cloud = browser({ signIns: memorySignIns({ cookies: many, origins: [] }).store });
+ urlOf(await cloud.open(request()));
+ expect(fake.commands.filter((one) => one.method === "Storage.setCookies")).toHaveLength(3);
+ expect(fake.cookies.get(profileKey("scout"))).toHaveLength(250);
+ });
+
it("wakes a stopped sandbox with exactly one resume, then reads only", async () => {
fake.state = "archived";
const cloud = browser();
@@ -900,7 +978,7 @@ describe("downloads and uploads of a browser in the sandbox", () => {
await finish("late-guid", "late.txt", Buffer.from("x"));
await vi.waitFor(() => expect(cloud.takeNotes("bot-scout")).toHaveLength(1));
await cloud.close("bot-scout");
- expect(cloud.takeNotes("bot-scout")).toEqual([expect.stringContaining(`"late.txt" was downloaded in the browser but could not be brought`)]);
+ expect(cloud.takeNotes("bot-scout")).toEqual([REOPENED_NOTE, expect.stringContaining(`"late.txt" was downloaded in the browser but could not be brought`)]);
expect(cloud.takeNotes("bot-scout")).toEqual([]);
available = true;
});
diff --git a/server/cloud-browser/index.ts b/server/cloud-browser/index.ts
index 457e1a5e54..1bd679c42a 100644
--- a/server/cloud-browser/index.ts
+++ b/server/cloud-browser/index.ts
@@ -15,6 +15,11 @@ import { BROWSER_SANDBOX_CHROMES, BROWSER_SANDBOX_OWNER, COMPUTER_DOOR_PORT, Old
/** A browser in the sandbox with no activity this long is closed; the sandbox sleeps once none is left. */
export const CLOUD_BROWSER_IDLE_MS = 3 * 60_000;
const SWEEP_MS = 30_000;
+/** However the sandbox is doing, a browser call waits at most this long for it: past it the call opens the home's browser,
+ * and the sandbox goes on coming up for the next one. Well inside the 60 s an engine gives a tool call. */
+export const OPEN_DEADLINE_MS = 12_000;
+/** What the bot's next call is told after its browser in the sandbox was closed (unused, or its machine stopped). */
+export const REOPENED_NOTE = "The browser was reopened: the earlier page and tabs are gone, so open the page again before acting on it.";
const LEVER_CLEANUP_GAP_MS = 60 * 60_000;
/** While a browser is used, the provider's own auto-stop is pushed to this far ahead, at most every TTL_REFRESH_MS: it then
* stops the sandbox by itself when everything here died, and never in the middle of a session in use. */
@@ -52,6 +57,7 @@ export interface CloudBrowserDeps {
/** Tests: a shorter sweep and wake reads. */
sweepMs?: number;
pollMs?: number;
+ openDeadlineMs?: number;
}
export interface OpenRequest {
@@ -103,11 +109,12 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
/** How many bots' Chromes this Cloud's sandbox takes at once, as the relay last said (by its size). */
let chromesAllowed = BROWSER_SANDBOX_CHROMES;
- const home = (request: OpenRequest, reason: HomeReason): Opened => {
+ const fallback = (request: OpenRequest, reason: HomeReason): Opened => {
rails.home(reason);
log(`browser ${request.session}: opens in the home, not in the Cloud's browser sandbox (${reason})`);
return { home: reason };
};
+ const home = fallback;
const bots = () => new Set([...sessions.values(), ...opening]);
/** A refusal's own words decide: the account's starts, the sandbox's minutes, or a failure that counts toward the back-off. */
@@ -147,26 +154,59 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
waking ??= wakeSandbox(ops, {
mayStart: () => rails.refusal(true) === null,
allowed: () => allowed(ops),
- starting: () => rails.resumed(),
+ // Timed from the moment a start is sent, whatever follows: a sandbox started is never left untimed.
+ starting: () => { rails.resumed(); armed(); },
...(deps.pollMs ? { pollMs: deps.pollMs } : {}),
}).finally(() => { waking = null; });
const box = await waking;
boxId = box.id;
- awake = true;
// Woken now: the deadline the Admin set at the resume is fresh.
if (box.started) ttlRefreshedAt = now();
+ armed();
+ await erasePending(ops, box.id);
+ return box;
+ }
+
+ /** On from here: the sandbox's idle path times it, whatever happens next. */
+ function armed(): void {
+ awake = true;
rails.awake();
- // On from here: the idle path times it, whatever happens next.
deps.used(BROWSER_SANDBOX_OWNER, CLOUD_BROWSER_IDLE_MS);
- return box;
}
- async function launch(request: OpenRequest, ops: ComputerOps): Promise<Opened> {
+ /** Deleted bots' profiles, erased while the sandbox is awake anyway: a deletion never wakes it on its own. */
+ async function erasePending(ops: ComputerOps, id: string): Promise<void> {
+ for (const key of rails.pendingErasures()) {
+ try {
+ await ops.erase(id, key);
+ rails.erased(key);
+ log("browser sandbox: erased a deleted bot's profile");
+ } catch {
+ // Kept for the next wake (an Admin without the action keeps it pending).
+ }
+ }
+ }
+
+ /** A deleted bot: its sessions end without their sign-ins going home, its sync stamps go, and its profile in the
+ * sandbox is erased now if the sandbox is awake, else at its next wake. */
+ async function erase(botId: string): Promise<void> {
+ const key = profileKey(botId);
+ rails.forgetProfile(key);
+ const ops = deps.ops();
+ // Erased while the sandbox is still awake for this session, before its close lets it sleep.
+ if (awake && boxId && ops) await erasePending(ops, boxId);
+ for (const [session, owner] of Array.from(sessions)) if (owner === botId) await close(session, { discard: true });
+ }
+
+ async function launch(request: OpenRequest, ops: ComputerOps, gaveUp: () => boolean): Promise<Opened> {
const key = profileKey(request.botId);
let box: { id: string; started: boolean } | null = null;
const quit = async () => { if (box) await ops.quit(box.id, key).catch(() => undefined); };
+ // Past the deadline this call already opened the home's browser: what follows only readies the sandbox for the next.
+ const home = (_request: OpenRequest, reason: HomeReason): Opened => (gaveUp() ? { home: reason } : fallback(request, reason));
try {
box = await wake(ops);
+ if (gaveUp()) return { home: "slow" };
const secret = randomBytes(24).toString("hex");
const answer = await ops.launch(box.id, key, secret);
if (!answer.chrome || !answer.home) {
@@ -193,6 +233,7 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
await quit();
return home(request, "unreachable");
}
+ if (gaveUp()) { await quit(); return { home: "slow" }; }
const cdpUrl = await doors.open(request.session, target);
const companion = new SandboxCompanion({
session: request.session, botId: request.botId, key, boxId: box.id, home: answer.home, ops, rails, signIns: deps.signIns ?? null,
@@ -210,6 +251,12 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
rails.failed();
return home(request, "unreachable");
}
+ if (gaveUp()) {
+ companion.close();
+ doors.close(request.session);
+ await quit();
+ return { home: "slow" };
+ }
rails.setCarryBad(key, null);
companions.set(request.session, companion);
sessions.set(request.session, request.botId);
@@ -269,24 +316,36 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
const bad = rails.carryBad(profileKey(request.botId));
if (bad !== null && known && known !== "unreadable" && known.modified === bad) return home(request, "sign-ins");
opening.add(request.botId);
- try {
- return await launch(request, ops);
- } finally {
+ let late = false;
+ const attempt = launch(request, ops, () => late).finally(() => {
opening.delete(request.botId);
letSleep();
- }
+ });
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const deadline = new Promise<null>((resolve) => {
+ timer = setTimeout(() => resolve(null), deps.openDeadlineMs ?? OPEN_DEADLINE_MS);
+ timer.unref?.();
+ });
+ const first = await Promise.race([attempt, deadline]);
+ clearTimeout(timer);
+ if (first) return first;
+ late = true;
+ void attempt.catch(() => undefined);
+ return home(request, "slow");
}
/** The bot's Chrome quits cleanly (its cookies written), the engine's session ends, and the sandbox may sleep. */
- async function close(session: string): Promise<void> {
+ async function close(session: string, options: { discard?: boolean } = {}): Promise<void> {
const botId = sessions.get(session);
if (!botId || closing.has(session)) return;
closing.add(session);
try {
const companion = companions.get(session);
- await companion?.stop().catch(() => undefined);
- const notes = companion?.takeNotes() ?? [];
- if (notes.length) leftNotes.set(session, notes);
+ if (options.discard) companion?.close();
+ else await companion?.stop().catch(() => undefined);
+ // The bot's next call opens a fresh browser (here or in the home): it is told the earlier page is gone.
+ const notes = options.discard ? [] : [REOPENED_NOTE, ...companion?.takeNotes() ?? []];
+ if (notes.length) leftNotes.set(session, notes); else leftNotes.delete(session);
companions.delete(session);
lastUse.delete(session);
await deps.closeEngine(session).catch(() => undefined);
@@ -359,6 +418,7 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
closeIdle,
dialed: (session: string): number => doors.dialed(session),
failed,
+ erase,
/** Lines for the session's next browser call (downloads that arrived, or could not). */
takeNotes: (session: string): string[] => {
const left = leftNotes.get(session) ?? [];
diff --git a/server/cloud-browser/rails.ts b/server/cloud-browser/rails.ts
index d6238308b8..d8128a5903 100644
--- a/server/cloud-browser/rails.ts
+++ b/server/cloud-browser/rails.ts
@@ -7,7 +7,7 @@ import { dirname, join } from "node:path";
import type { CloudLimit } from "../../shared/place-view.ts";
/** Resumes a Cloud may spend on its bots' browsers in one UTC day; past it, every browser opens in the home. */
-export const CLOUD_BROWSER_DAILY_RESUMES = 100;
+export const CLOUD_BROWSER_DAILY_RESUMES = 30;
/** Minutes the Cloud's browser sandbox may be awake in one UTC day; past it, every browser opens in the home. */
export const CLOUD_BROWSER_DAILY_AWAKE_MINUTES = 1_080;
/** Failed starts in a row before the back-off. */
@@ -17,7 +17,7 @@ export const CLOUD_BROWSER_BACKOFF_MS = 15 * 60_000;
/** Why a browser session opened in the home instead: names only, for the log and the health report. */
export type HomeReason =
| "lever" | "team" | "not-eligible" | "own-key" | "sign-ins" | "no-machine" | "no-policy" | "not-set-up" | "busy" | "lent-connection"
- | "old-relay" | "unavailable" | "budget" | "minutes-used" | "sandbox-full" | "backoff" | "account-limit" | "hours-used" | "at-once" | "no-route" | "start-failed" | "unreachable";
+ | "slow" | "old-relay" | "unavailable" | "budget" | "minutes-used" | "sandbox-full" | "backoff" | "account-limit" | "hours-used" | "at-once" | "no-route" | "start-failed" | "unreachable";
interface Day {
day: string;
@@ -49,6 +49,8 @@ interface State extends Day {
carried: Record<string, number>;
/** Per bot's profile key: the home copy (by file time) Chrome would not take, not tried again until it changes. */
carryBad: Record<string, number>;
+ /** Deleted bots' profile keys, still to erase in the sandbox at its next wake. */
+ pendingErase: string[];
/** Since when the operator lever has kept every browser in the home; 0 when it does not. */
leverSince: number;
}
@@ -78,7 +80,7 @@ export function createCloudBrowserRails(options: CloudBrowserRailsOptions) {
let awakeCapMs = (options.awakeMinutes ?? CLOUD_BROWSER_DAILY_AWAKE_MINUTES) * 60_000;
const file = join(options.dataDir, "cloud-browser", "rails.json");
const fresh = (day: string): Day => ({ day, resumes: 0, awakeMs: 0, computer: 0, home: 0, fallbacks: {} });
- let state: State = { ...fresh(utcDay(now())), failuresInRow: 0, backoffUntil: 0, accountUntil: 0, hoursUntil: 0, noRouteDay: null, awakeSince: 0, leverSince: 0, oldRelayUntil: 0, unavailableUntil: 0, carried: {}, carryBad: {} };
+ let state: State = { ...fresh(utcDay(now())), failuresInRow: 0, backoffUntil: 0, accountUntil: 0, hoursUntil: 0, noRouteDay: null, awakeSince: 0, leverSince: 0, oldRelayUntil: 0, unavailableUntil: 0, carried: {}, carryBad: {}, pendingErase: [] };
try {
const saved = JSON.parse(readFileSync(file, "utf8")) as Partial<State>;
const number = (value: unknown) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0);
@@ -94,6 +96,7 @@ export function createCloudBrowserRails(options: CloudBrowserRailsOptions) {
oldRelayUntil: 0, unavailableUntil: number(saved.unavailableUntil),
carried: Object.fromEntries(Object.entries(saved.carried && typeof saved.carried === "object" ? saved.carried : {})
.filter(([key, at]) => /^bx_[a-z0-9]{8}:[a-f0-9]{16}$/.test(key) && typeof at === "number" && Number.isFinite(at))),
+ pendingErase: Array.isArray(saved.pendingErase) ? saved.pendingErase.filter((key): key is string => typeof key === "string" && /^[a-f0-9]{16}$/.test(key)) : [],
carryBad: Object.fromEntries(Object.entries(saved.carryBad && typeof saved.carryBad === "object" ? saved.carryBad : {})
.filter(([key, at]) => /^[a-f0-9]{16}$/.test(key) && typeof at === "number" && Number.isFinite(at))),
};
@@ -212,6 +215,20 @@ export function createCloudBrowserRails(options: CloudBrowserRailsOptions) {
},
carried: (key: string): number => today().carried[key] ?? 0,
carryBad: (key: string): number | null => today().carryBad[key] ?? null,
+ /** A deleted bot's profile: its stamps go, and its erase in the sandbox is kept until done. */
+ forgetProfile(key: string): void {
+ const current = today();
+ for (const stamp of Object.keys(current.carried)) if (stamp.endsWith(`:${key}`)) delete current.carried[stamp];
+ delete current.carryBad[key];
+ if (!current.pendingErase.includes(key)) current.pendingErase.push(key);
+ save();
+ },
+ pendingErasures: (): string[] => [...today().pendingErase],
+ erased(key: string): void {
+ const current = today();
+ current.pendingErase = current.pendingErase.filter((one) => one !== key);
+ save();
+ },
setCarryBad(key: string, at: number | null): void {
const current = today();
if (at === null) delete current.carryBad[key]; else current.carryBad[key] = at;
diff --git a/server/cloud-browser/remote.ts b/server/cloud-browser/remote.ts
index b8b166ea2b..831d4a671c 100644
--- a/server/cloud-browser/remote.ts
+++ b/server/cloud-browser/remote.ts
@@ -52,6 +52,8 @@ export interface ComputerOps {
fetchFile(boxId: string, path: string, folder: string, to: string): Promise<CopyOutcome>;
/** A file of the Cloud (`from`, inside `folder`) copied to a sandbox path for an upload. */
sendFile(boxId: string, folder: string, from: string, path: string): Promise<CopyOutcome>;
+ /** A deleted bot's profile, door secret and files in the sandbox, erased. */
+ erase(boxId: string, key: string): Promise<void>;
/** A download the sandbox no longer needs to keep. */
removeDownload(boxId: string, key: string, name: string): Promise<void>;
/** One bot's Chrome asked to quit (it writes its cookies); `key` null: every Chrome and the door. */
@@ -134,7 +136,8 @@ export function providerOps(cfg: () => AppConfig): ComputerOps {
return {
async probe() {
const answer = await json(cfg(), "/browser-sandbox");
- if (answer.status === 404) return { kind: "old-relay" };
+ // An Admin from before the browser sandbox answers its unknown route with 404, or 403 `not_available`.
+ if (answer.status === 404 || (answer.status === 403 && (answer.body?.code ?? answer.body?.error?.code) === "not_available")) return { kind: "old-relay" };
if (!answer.ok || typeof answer.body?.available !== "boolean") throw boatRefusal(answer.status, "asking about the browser sandbox", answer.body, true);
const chromes = Number.isInteger(answer.body.chromes) && answer.body.chromes >= 1 && answer.body.chromes <= 4 ? answer.body.chromes as number : null;
const count = (value: unknown) => (typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : null);
@@ -166,6 +169,10 @@ export function providerOps(cfg: () => AppConfig): ComputerOps {
},
fetchFile: (boxId, path, folder, to) => copyFromComputer(cfg(), boxId, folder, { path, to }, AbortSignal.timeout(10 * 60_000)),
sendFile: (boxId, folder, from, path) => copyToComputer(cfg(), boxId, folder, { from, path }, AbortSignal.timeout(10 * 60_000)),
+ async erase(boxId, key) {
+ if (!HEX16.test(key)) throw new Error("bad browser profile key");
+ await action(boxId, { action: "erase", key });
+ },
async removeDownload(boxId, key, name) {
if (!HEX16.test(key)) throw new Error("bad browser profile key");
await action(boxId, { action: "remove-download", key, name });
diff --git a/server/cloud-browser/sign-ins.ts b/server/cloud-browser/sign-ins.ts
index 436c00daac..e0acca1e27 100644
--- a/server/cloud-browser/sign-ins.ts
+++ b/server/cloud-browser/sign-ins.ts
@@ -75,24 +75,44 @@ function storageOf(origins: readonly unknown[]): Storage[] {
return kept;
}
-/** The home's saved sign-ins made the sandbox profile's, the home being the newer: the profile's cookies are cleared first
- * (so a site signed out of in the home stays signed out), then each cookie is set on its own, so one Chrome refuses (a
- * SameSite=None one without Secure, say) is skipped and counted instead of failing the rest. Then, as best it can, each
- * site's local storage through one blank page of its own (Chrome may want a page of that site first; a site it refuses
- * keeps its cookies). Returns the cookies now in the profile from the home's copy. */
-export async function carryIn(cdp: Cdp, state: { cookies: readonly unknown[]; origins: readonly unknown[] }): Promise<{ cookies: number; refused: number; origins: number; set: SavedCookie[] }> {
- const saved = state.cookies.filter(isSavedCookie).slice(0, MAX_COOKIES);
- await cdp.send("Storage.clearCookies", {});
+const BATCH = 100;
+
+/** Cookies set a hundred at a time; a batch Chrome refuses (one cookie in it it won't take) is set one at a time, so that
+ * cookie alone is left out and counted. */
+async function setInBatches(cdp: Cdp, cookies: readonly SavedCookie[]): Promise<{ set: SavedCookie[]; refused: number }> {
const set: SavedCookie[] = [];
let refused = 0;
- for (const cookie of saved) {
+ for (let at = 0; at < cookies.length; at += BATCH) {
+ const batch = cookies.slice(at, at + BATCH);
try {
- await cdp.send("Storage.setCookies", { cookies: [cookieParam(cookie)] });
- set.push(cookie);
+ await cdp.send("Storage.setCookies", { cookies: batch.map(cookieParam) });
+ set.push(...batch);
+ continue;
} catch {
- refused += 1;
+ // One of them is refused: each on its own.
+ }
+ for (const cookie of batch) {
+ try {
+ await cdp.send("Storage.setCookies", { cookies: [cookieParam(cookie)] });
+ set.push(cookie);
+ } catch {
+ refused += 1;
+ }
}
}
+ return { set, refused };
+}
+
+/** The home's saved sign-ins made the sandbox profile's, the home being the newer: the profile's cookies are cleared first
+ * (so a site signed out of in the home stays signed out), then the cookies are set in batches, and a batch Chrome refuses
+ * one cookie of (a SameSite=None one without Secure, say) one at a time, so that one is skipped and counted instead of
+ * failing the rest. Then, as best it can, each
+ * site's local storage through one blank page of its own (Chrome may want a page of that site first; a site it refuses
+ * keeps its cookies). Returns the cookies now in the profile from the home's copy. */
+export async function carryIn(cdp: Cdp, state: { cookies: readonly unknown[]; origins: readonly unknown[] }): Promise<{ cookies: number; refused: number; origins: number; set: SavedCookie[] }> {
+ const saved = state.cookies.filter(isSavedCookie).slice(0, MAX_COOKIES);
+ await cdp.send("Storage.clearCookies", {});
+ const { set, refused } = await setInBatches(cdp, saved);
const cookies = set;
const storage = storageOf(state.origins);
let carried = 0;
@@ -127,16 +147,7 @@ export async function carryIn(cdp: Cdp, state: { cookies: readonly unknown[]; or
export async function restoreSessionCookies(cdp: Cdp, home: readonly unknown[], current: readonly SavedCookie[]): Promise<SavedCookie[]> {
const have = new Set(current.map(cookieId));
const missing = home.filter(isSavedCookie).filter((cookie) => (cookie.session === true || (typeof cookie.expires === "number" && cookie.expires < 0)) && !have.has(cookieId(cookie)));
- const set: SavedCookie[] = [];
- for (const cookie of missing.slice(0, MAX_COOKIES)) {
- try {
- await cdp.send("Storage.setCookies", { cookies: [cookieParam(cookie)] });
- set.push(cookie);
- } catch {
- // Refused by Chrome: left out, as at a carry.
- }
- }
- return set;
+ return (await setInBatches(cdp, missing.slice(0, MAX_COOKIES))).set;
}
/** The sandbox's cookies as the home saves them (Chrome's own shape, as agent-browser writes it), at most MAX_COOKIES. */
diff --git a/server/cloud-browser/testing/fake-computer.ts b/server/cloud-browser/testing/fake-computer.ts
index 5a1e4c7f35..a9555c9c18 100644
--- a/server/cloud-browser/testing/fake-computer.ts
+++ b/server/cloud-browser/testing/fake-computer.ts
@@ -29,6 +29,12 @@ export interface FakeComputer {
hostRoute: boolean;
unprotected: boolean;
chromeStarts: boolean;
+ /** How an Admin from before the browser sandbox answers its probe: 404, or 403 `not_available`. */
+ oldRelayAnswer: 403 | 404;
+ /** Answers the relay holds back, by path ending: the request waits this many ms (a sandbox stuck provisioning). */
+ stall: Map<string, number>;
+ /** The profile keys an erase action named. */
+ erased: string[];
/** The caps the probe says this Cloud's plan has. */
caps: { resumesPerDay: number; awakeMinutesPerDay: number } | null;
/** Status the PATCH of a sandbox answers with. */
@@ -73,16 +79,23 @@ export async function startFakeComputer(): Promise<FakeComputer> {
let retired = true;
const fake = {
base: "", state: "ready", exists: true, startStatus: 200, startBody: { ok: true }, oldRelay: false, available: true, unavailableReason: "fleet_starts",
- unavailableUntil: null, hostRoute: true, unprotected: false, chromeStarts: true, policy: true, takeBackFails: false, chromes: 2, caps: null, patchStatus: 200, requests: [], upgrades: [], frames: [], boxId: "bx_23456789",
+ unavailableUntil: null, hostRoute: true, unprotected: false, chromeStarts: true, policy: true, takeBackFails: false, chromes: 2, caps: null, patchStatus: 200, oldRelayAnswer: 404, stall: new Map(), erased: [], requests: [], upgrades: [], frames: [], boxId: "bx_23456789",
files: new Map(), cookies: new Map(), commands: [], failing: new Set(),
} as unknown as FakeComputer;
const watchers = new Map<string, Set<import("ws").WebSocket>>();
const HOME = "/home/user";
+ /** A held-back answer waits its time first (a sandbox stuck provisioning); every other answers at once. */
+ const after = (path: string, respond: () => void) => {
+ const entry = [...fake.stall].find(([ending]) => path.endsWith(ending));
+ if (!entry) return respond();
+ fake.stall.delete(entry[0]);
+ setTimeout(respond, entry[1]);
+ };
const server: Server = createServer((req, res) => {
const url = new URL(req.url ?? "/", "http://fake");
const chunks: Buffer[] = [];
req.on("data", (chunk: Buffer) => { chunks.push(chunk); });
- req.on("end", () => {
+ req.on("end", () => after(url.pathname, () => {
// The transfer links: no bearer, as the provider's signed links need none.
if (url.pathname === "/file" && req.method === "GET") {
const file = fake.files.get(url.searchParams.get("p") ?? "");
@@ -105,7 +118,7 @@ export async function startFakeComputer(): Promise<FakeComputer> {
const row = { id: boxId, name: legacyName("browser"), state: fake.state };
const rest = url.pathname.replace(/^\/api\/v1/, "");
if (rest === "/browser-sandbox") {
- if (fake.oldRelay) return send(404, { ok: false, code: "not_found" });
+ if (fake.oldRelay) return fake.oldRelayAnswer === 403 ? send(403, { ok: false, code: "not_available", message: "Not available." }) : send(404, { ok: false, code: "not_found" });
return send(200, { ok: true, type: "browser.sandbox", available: fake.available, boxId: fake.exists ? boxId : null, sandboxType: fake.chromes > 2 ? "default" : "small", chromes: fake.chromes, ...(fake.caps ? { caps: fake.caps } : {}),
...(fake.available ? {} : { reason: fake.unavailableReason, ...(fake.unavailableUntil ? { resetsAt: fake.unavailableUntil } : {}) }) });
}
@@ -142,6 +155,7 @@ export async function startFakeComputer(): Promise<FakeComputer> {
secrets.set(body.key, body.secret);
return send(200, { ok: true, chrome: fake.chromeStarts, policy: fake.policy, home: HOME });
}
+ if (body.action === "erase" && typeof body.key === "string") { fake.erased.push(body.key); fake.cookies.delete(body.key); return send(200, { ok: true }); }
if (body.action === "remove-download") fake.files.delete(`${HOME}/.omb-browser/.downloads/${String(body.key)}/${String(body.name)}`);
return send(200, { ok: true });
}
@@ -154,7 +168,7 @@ export async function startFakeComputer(): Promise<FakeComputer> {
}
if (rest === `/sandboxes/${boxId}/stop`) { fake.state = "archived"; return send(200, { ok: true }); }
send(404, { ok: false, code: "not_found" });
- });
+ }));
});
server.on("upgrade", (req: IncomingMessage, socket: Duplex, head: Buffer) => {
const url = new URL(req.url ?? "/", "http://fake");
diff --git a/server/host/browser.ts b/server/host/browser.ts
index 201d9d7fd1..7f5fce9c33 100644
--- a/server/host/browser.ts
+++ b/server/host/browser.ts
@@ -767,6 +767,9 @@ export function createBrowserHost(deps: BrowserHostDeps) {
return results.every(Boolean);
}
async function eraseOneBrowser(request: BrowserCleanupWireRequest): Promise<boolean> {
+ // A deleted bot's profile in the Cloud's browser sandbox goes too, and its open session there ends without writing its
+ // sign-ins back to the home, whose copy is erased below.
+ if (request.type === "openmausbot:browser-bot-deleted" && request.botId) await cloudBrowser?.erase(request.botId).catch(() => undefined);
const session = request.type === "openmausbot:browser-bot-deleted" && request.botId ? browserSessionId(request.botId, "")
: request.partitionId ? browserSessionId("", request.partitionId) : null;
const engine = cleanupEngine();
diff --git a/server/index.ts b/server/index.ts
index bcbd9b6d19..badd15408c 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -12900,7 +12900,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
if (!bot || bot.browser === false || bot.computer === "off" || !builtInBrowserEnabled(cfg)) {
return json(res, 403, { error: "browser tools are not enabled for this bot" });
}
- const browser = await browserIntegration(bot.id, bot.browserProfile, undefined, teamHost.browserAudience(internalCapability.threadId), { opening: body?.method === "tools/call" ? String(body?.params?.name ?? "") || null : null });
+ let browser = await browserIntegration(bot.id, bot.browserProfile, undefined, teamHost.browserAudience(internalCapability.threadId));
if (!browser || browser.session !== internalCapability.browserSession) {
return json(res, 409, { error: "this browser profile changed; start a new turn" });
}
@@ -12910,7 +12910,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
if (body.method === "tools/call") {
const abort = new AbortController(); res.once("close", () => { if (!res.writableEnded) abort.abort(); });
const refused = await browserSeats.take(internalCapability, browser.session, abort.signal); requireActiveInternalCapability();
- if (refused) return json(res, 200, { result: { isError: true, content: [{ type: "text", text: refused }] } });
+ if (refused) return json(res, 200, { result: { isError: true, content: [{ type: "text", text: refused }] } }); if (!claimTurnResource(internalCapability, `browser:${browser.session}`)) throw Object.assign(new Error("another thread is using this browser — pause browser work until that thread finishes"), { status: 409 }); browser = (await browserIntegration(bot.id, bot.browserProfile, undefined, teamHost.browserAudience(internalCapability.threadId), { opening: String(body?.params?.name ?? "") || null })) ?? browser; // Only now, past the seat and the claim, may it open the Cloud's browser sandbox: a refused call never spends a start.
}
let params = body.params;
if (body.method === "tools/call" && params?.name === BROWSER_UPLOAD_TOOL) {
diff --git a/server/parallel-threads.e2e.test.ts b/server/parallel-threads.e2e.test.ts
index 9c1492536a..afd7f0f3c9 100644
--- a/server/parallel-threads.e2e.test.ts
+++ b/server/parallel-threads.e2e.test.ts
@@ -1,5 +1,5 @@
// Three threads of one bot, each with a turn held open by a gate only the test releases, as a desktop, personal Cloud and Team Cloud server.
-import { randomBytes, randomUUID } from "node:crypto";
+import { createHash, randomBytes, randomUUID } from "node:crypto";
import { spawn, type ChildProcess } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
import { createServer, type Server } from "node:http";
@@ -545,3 +545,52 @@ describe("a Starter Cloud", () => {
await whenStarted(threads[1]!);
}, 90_000);
});
+
+// The Cloud's browser sandbox, behind a stand-in of the Admin's relay that counts its starts: a call that waits for
+// another thread's browser and is refused must never have spent one.
+describe.skipIf(process.platform === "win32")("a refused browser call on a personal Cloud with the browser sandbox", () => {
+ let f: Fixture;
+ const servers: Server[] = [];
+ afterEach(async () => {
+ await f?.stop();
+ for (const server of servers.splice(0)) { server.closeAllConnections(); server.close(); }
+ });
+
+ it("is refused by its seat before the sandbox is asked anything, so it spends no start", async () => {
+ const legacyName = `ogb-browser-${createHash("sha256").update("browser").digest("hex").slice(0, 6)}`;
+ const box = { id: "bx_23456789", name: legacyName, state: "archived" };
+ let resumes = 0, probes = 0;
+ const relay = createServer((req, res) => {
+ const path = new URL(req.url ?? "/", "http://relay.test").pathname.replace(/^\/relay\/api\/box\/v1/, "");
+ req.resume();
+ req.on("end", () => {
+ const answer = (status: number, payload: unknown) => { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(payload)); };
+ if (path === "/browser-sandbox") { probes += 1; return answer(200, { ok: true, type: "browser.sandbox", available: true, boxId: box.id, chromes: 2 }); }
+ if (path === "/boxes" && req.method === "GET") return answer(200, { ok: true, boxes: [box], pageInfo: { nextCursor: null } });
+ if (path === `/boxes/${box.id}` && req.method === "GET") return answer(200, { ok: true, box });
+ if (path === `/boxes/${box.id}/resume`) { resumes += 1; box.state = "ready"; return answer(200, { ok: true }); }
+ // Chrome does not come up: the call opens the home's browser, and the sandbox is stopped again.
+ if (path === `/boxes/${box.id}/browser`) { box.state = "archived"; return answer(200, { ok: true, chrome: false, policy: true, home: "/home/user" }); }
+ return answer(404, { ok: false, code: "not_found", message: "Not found" });
+ });
+ });
+ servers.push(relay);
+ await new Promise<void>((resolve) => relay.listen(0, "127.0.0.1", resolve));
+ const relayBase = `http://127.0.0.1:${(relay.address() as AddressInfo).port}`;
+ f = new Fixture("home");
+ f.extraEnv = { OMB_AGENT_BROWSER_PATH: inertBrowser(f.home), OMB_COMPUTER_CALL_WAIT_MS: "500", OMB_CLOUD_BOAT_URL: `${relayBase}/relay/api/box/v1`, OMB_CLOUD_BOAT_TOKEN: "box_omb_fixture" };
+ await f.start();
+ const { botId, threads } = await botWithThreads(f, CLAUDE, 2);
+ await send(f, botId, threads[0]!, "First job");
+ await send(f, botId, threads[1]!, "Second job");
+ await expect.poll(() => f.claudeTurnsStarted(), { timeout: 20_000, interval: 50 }).toBe(2);
+ expect((await browse(f, threads[0]!)).body.result.isError, "the first thread browses, in the home after the sandbox failed it").toBeFalsy();
+ expect(resumes).toBe(1);
+ const waiting = await browse(f, threads[1]!);
+ expect(waiting.body.result).toEqual({ isError: true, content: [{ type: "text", text: browserBusyText(500) }] });
+ expect(resumes, "the refused call woke nothing").toBe(1);
+ expect(probes).toBe(1);
+ f.release();
+ await expect.poll(async () => (await botRow(f, botId)).busy, { timeout: 20_000, interval: 100 }).toBe(false);
+ }, 90_000);
+});