Skip to content

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

Cloud browser: two Chromes per sandbox, take back a sandbox still stopping, ttlSeconds only as a whole number

milind-soni1f246aa51e7d
diff --git a/server/cloud-browser/cloud-browser.test.ts b/server/cloud-browser/cloud-browser.test.ts
index 078d3c3d0b..1c88c819c7 100644
--- a/server/cloud-browser/cloud-browser.test.ts
+++ b/server/cloud-browser/cloud-browser.test.ts
@@ -13,7 +13,7 @@ import { SESSION_DOWNLOAD_BYTES, SIGN_IN_SYNC_MS, UPLOAD_MAX_BYTES, type SignInS
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_BACKOFF_MS, createCloudBrowserRails } from "./rails.ts";
-import { BROWSER_SANDBOX_CHROMES, BROWSER_SANDBOX_OWNER, browserSandboxCreateBody, profileKey, providerOps } from "./remote.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";
let fake: FakeComputer;
@@ -232,6 +232,7 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>
clock += 60_000;
await cloud.closeIdle();
expect(patches()).toEqual([{ ttlSeconds: SANDBOX_IDLE_TTL_SECONDS }]);
+ expect(Number.isInteger(patches()[0]?.ttlSeconds), "the provider takes a non-number as an hour").toBe(true);
clock += 60_000;
await act(cdpUrl, 1);
await cloud.closeIdle();
@@ -246,6 +247,24 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>
expect(patches(), "unused since: the deadline is left to run out").toHaveLength(2);
});
+ it("takes back a sandbox that is still stopping: one resume, no start counted, no question to the relay", async () => {
+ fake.state = "archiving";
+ const cloud = browser();
+ urlOf(await cloud.open(request()));
+ expect(fake.resumes()).toBe(1);
+ expect(cloud.report().resumes, "the kept machine is no start").toBe(0);
+ expect(fake.requests.filter((one) => one.path.endsWith("/browser-sandbox"))).toEqual([]);
+ });
+
+ it("when the take-back comes too late, sends one real resume, counted like any", async () => {
+ fake.state = "archiving";
+ fake.takeBackFails = true;
+ const cloud = browser();
+ urlOf(await cloud.open(request()));
+ expect(fake.resumes()).toBe(2);
+ expect(cloud.report().resumes).toBe(1);
+ });
+
it("wakes a stopped sandbox with exactly one resume, then reads only", async () => {
fake.state = "archived";
const cloud = browser();
@@ -261,16 +280,17 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>
expect(fake.resumes() + fake.creates()).toBe(0);
});
- it("gives each bot its own profile and Chrome, carries up to three at once, and keeps a fourth in the home", async () => {
+ it("gives each bot its own profile and Chrome, carries up to two at once, and keeps a third in the home", async () => {
fake.state = "archived";
const cloud = browser();
- const bots = ["scout", "writer", "chief", "fourth"];
+ const bots = ["scout", "writer", "chief"];
const opened = await Promise.all(bots.slice(0, BROWSER_SANDBOX_CHROMES).map((bot) => cloud.open(request(bot))));
expect(fake.resumes(), "bots opening together share one wake").toBe(1);
- for (const [i, bot] of bots.slice(0, 3).entries()) expect(await act(urlOf(opened[i]!), 1)).toEqual([`echo:${profileKey(bot)}:{"id":0}`]);
- expect(new Set(fake.profiles())).toEqual(new Set(bots.slice(0, 3).map(profileKey)));
+ expect(BROWSER_SANDBOX_CHROMES, "one heavy page measured 954 MB on a 4 GB sandbox").toBe(2);
+ for (const [i, bot] of bots.slice(0, 2).entries()) expect(await act(urlOf(opened[i]!), 1)).toEqual([`echo:${profileKey(bot)}:{"id":0}`]);
+ expect(new Set(fake.profiles())).toEqual(new Set(bots.slice(0, 2).map(profileKey)));
expect(profileKey("scout")).toMatch(/^[a-f0-9]{16}$/);
- expect(await cloud.open(request("fourth"))).toEqual({ home: "sandbox-full" });
+ expect(await cloud.open(request("chief"))).toEqual({ home: "sandbox-full" });
});
it("reuses a bot's profile after the sandbox slept", async () => {
@@ -654,6 +674,14 @@ describe("a bot's sign-ins between the home and its sandbox profile", () => {
expect(cloud.active("bot-scout"), "the session goes on").toBe(cdpUrl);
});
+ it("sends ttlSeconds only as a whole number within the Admin's range", () => {
+ expect(ttlSecondsOf(1200)).toBe(1200);
+ expect(ttlSecondsOf(1199.6)).toBe(1200);
+ expect(ttlSecondsOf(Number.NaN)).toBe(300);
+ expect(ttlSecondsOf(10)).toBe(300);
+ expect(ttlSecondsOf(1e9)).toBe(1800);
+ });
+
it("keeps a cookie's partition, saved as an object or as a site's text", () => {
expect(cookieParam({ ...SIGNED_IN, partitionKey: "https://top.example" })).toMatchObject({ partitionKey: "https://top.example" });
expect(cookieParam({ ...SIGNED_IN, partitionKey: { topLevelSite: "https://top.example", hasCrossSiteAncestor: false } }))
diff --git a/server/cloud-browser/remote.ts b/server/cloud-browser/remote.ts
index 77ef65273e..639e9a99eb 100644
--- a/server/cloud-browser/remote.ts
+++ b/server/cloud-browser/remote.ts
@@ -18,8 +18,9 @@ const TERMINAL = new Set(["error", "cancelled"]);
export const BROWSER_SANDBOX_OWNER = "browser";
/** The provider's smallest size that runs Chrome well: 2 vCPU, 4 GB. A heavy page measured 0.8–0.87 GB per Chrome. */
export const BROWSER_SANDBOX_TYPE = "small";
-/** Chromes at once in one sandbox (one per bot browsing); past this a bot's browser opens in the home. */
-export const BROWSER_SANDBOX_CHROMES = 3;
+/** Chromes at once in one sandbox (one per bot browsing); past this a bot's browser opens in the home. One heavy page
+ * measured 954 MB on `small` (4 GB), so two; the Admin's launch also refuses a Chrome when under 1 GiB is free. */
+export const BROWSER_SANDBOX_CHROMES = 2;
/** The port the sandbox's small door listens on, on its loopback only; the provider's relay reaches it there. */
export const COMPUTER_DOOR_PORT = 39231;
@@ -176,7 +177,7 @@ export function providerOps(cfg: () => AppConfig): ComputerOps {
},
async refreshTtl(boxId, seconds) {
// A refusal (the Admin's maximum session age, say) leaves the deadline as it is: that is the point of it.
- await json(cfg(), `/sandboxes/${boxId}`, { method: "PATCH", body: JSON.stringify({ ttlSeconds: seconds }) });
+ await json(cfg(), `/sandboxes/${boxId}`, { method: "PATCH", body: JSON.stringify({ ttlSeconds: ttlSecondsOf(seconds) }) });
},
async remove(boxId) {
const name = await boatNameFor(BROWSER_SANDBOX_OWNER);
@@ -185,6 +186,9 @@ export function providerOps(cfg: () => AppConfig): ComputerOps {
};
}
+/** The provider silently takes a ttlSeconds that is not a number as an hour: only a whole number within the Admin's range goes. */
+export const ttlSecondsOf = (seconds: number): number => Math.min(1_800, Math.max(300, Math.round(Number.isFinite(seconds) ? seconds : 300)));
+
/** Not a failure of the sandbox: the browser opens in the home, and nothing is counted against it. */
export class StaysHome extends Error {
readonly reason: "busy" | "budget";
@@ -210,23 +214,32 @@ export interface WakeOptions {
export async function wakeSandbox(ops: ComputerOps, options: WakeOptions): Promise<{ id: string; started: boolean }> {
let found = await ops.find();
if (found && READY.has(found.state)) return { id: found.id, started: false };
- // Archiving: its snapshot must land before it can be resumed, and another stop path owns it now.
- if (found?.state === "archiving") throw new StaysHome("busy");
const broken = found && TERMINAL.has(found.state) ? found.id : found ? null : ops.dead();
if (broken) {
await ops.remove(broken);
found = null;
}
- let started = false;
- if (!found || SLEEPING_BOAT_STATES.has(found.state)) {
+ const counted = async (box: { id: string; state: string } | null): Promise<{ id: string; state: string }> => {
if (!options.mayStart()) throw new StaysHome("budget");
await options.allowed();
options.starting();
+ if (!box) return ops.create();
+ await ops.resume(box.id);
+ return box;
+ };
+ let started = false;
+ /** Taken back while still stopping: the same machine, ready in about 0.3 s, and no start (measured). Only the home asks
+ * for a browser, so a stop the Admin made because the home was down is never undone by this; the newest request wins. */
+ let takenBack = false;
+ if (found?.state === "archiving") {
+ await ops.resume(found.id);
+ takenBack = true;
+ started = true;
+ } else if (!found || SLEEPING_BOAT_STATES.has(found.state)) {
+ found = await counted(found);
started = true;
- if (!found) found = await ops.create();
- else await ops.resume(found.id);
}
- const id = found.id;
+ const id = found!.id;
const deadline = Date.now() + (options.budgetMs ?? 45_000);
// Quick reads first: a resume after a short stop is ready in well under a second.
for (let reads = 0; Date.now() < deadline; reads++) {
@@ -234,6 +247,8 @@ export async function wakeSandbox(ops: ComputerOps, options: WakeOptions): Promi
const state = await ops.state(id).catch(() => null);
if (state && READY.has(state)) return { id, started };
if (state && TERMINAL.has(state)) break;
+ // The take-back came too late (the machine went with the stop): one real, counted resume instead.
+ if (takenBack && state === "archived") { takenBack = false; await counted({ id, state }); }
// Never a second start: a refused resume is billed as one too.
}
throw new Error("the browser sandbox did not become ready in time");
diff --git a/server/cloud-browser/testing/fake-computer.ts b/server/cloud-browser/testing/fake-computer.ts
index 24ae08a73e..c5c44319e1 100644
--- a/server/cloud-browser/testing/fake-computer.ts
+++ b/server/cloud-browser/testing/fake-computer.ts
@@ -29,6 +29,8 @@ export interface FakeComputer {
hostRoute: boolean;
unprotected: boolean;
chromeStarts: boolean;
+ /** A resume during `archiving` finds the machine already gone. */
+ takeBackFails: boolean;
/** Whether the launch could write the Chrome policy (sudo in the sandbox). */
policy: boolean;
requests: Request[];
@@ -65,7 +67,7 @@ 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, requests: [], upgrades: [], frames: [], boxId: "bx_23456789",
+ unavailableUntil: null, hostRoute: true, unprotected: false, chromeStarts: true, policy: true, takeBackFails: false, 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>>();
@@ -119,6 +121,8 @@ export async function startFakeComputer(): Promise<FakeComputer> {
return send(200, { ok: true, operation: { id: `bdop_${"a".repeat(32)}`, status: "completed", kind: "sandbox", targetId: boxId } });
}
if (rest === `/sandboxes/${boxId}/resume`) {
+ // Taken back while still stopping, unless the machine already went: then the stop finishes and the answer is 409.
+ if (fake.state === "archiving" && fake.takeBackFails) { fake.state = "archived"; return send(409, { ok: false, code: "sandbox_stopping" }); }
if (fake.startStatus < 300) fake.state = "ready";
return send(fake.startStatus, fake.startBody);
}