Skip to content

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

Cloud browser: sign-ins kept by the sandbox reach the home; Chrome's own drops never remove one; truthful notes and logs; a faster first open

milind-soni660619a91ea5
diff --git a/server/browser-runtime.test.ts b/server/browser-runtime.test.ts
index b9eeac54f0..07db06be91 100644
--- a/server/browser-runtime.test.ts
+++ b/server/browser-runtime.test.ts
@@ -693,6 +693,18 @@ describe("server-owned browser MCP runtime", () => {
expect(next.content[0].text).not.toMatch(/are kept/);
});
+ it("tells a bot whose session moved to the Cloud's browser sandbox after an idle close that its sign-ins are kept", async () => {
+ const value = runtime({ closeBrowser: async () => true });
+ await value.agentRpc("m", spec(), "tools/call", { name: "echo" });
+ await new Promise((resolve) => setTimeout(resolve, 15));
+ expect(await value.closeIfIdle("m", 10)).toBe(true);
+ // The next call attaches to the sandbox's Chrome, whose spec never saves state itself: the sign-ins live in its profile.
+ const sandbox = { ...spec(), env: { ...spec().env, AGENT_BROWSER_CDP: "ws://127.0.0.1:1/devtools/browser/x", AGENT_BROWSER_RESTORE_SAVE: "never" } };
+ const next = await value.agentRpc("m", sandbox, "tools/call", { name: "echo" }) as { content: Array<{ text: string }> };
+ expect(next.content[0].text).toMatch(/sat unused and was closed.*saved sign-ins are kept/);
+ expect(next.content[0].text).not.toMatch(/sign-ins are gone/);
+ });
+
it("never closes a browser in use: a bot's call, a person's hold or input", async () => {
const closeBrowser = vi.fn(async () => true);
const value = runtime({ closeBrowser });
diff --git a/server/browser-runtime.ts b/server/browser-runtime.ts
index 40319aeb16..b7a4f9689e 100644
--- a/server/browser-runtime.ts
+++ b/server/browser-runtime.ts
@@ -467,7 +467,7 @@ export class BrowserRuntime {
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 || refusedSlot(result)) return scrubBrowserResult(result, this.scrub);
- const note = gate.reopened === "restart" ? PERSON_RESTARTED : idleClosedNote(spec.env.AGENT_BROWSER_RESTORE_SAVE !== "never");
+ const note = gate.reopened === "restart" ? PERSON_RESTARTED : idleClosedNote(spec.env.AGENT_BROWSER_RESTORE_SAVE !== "never" || attachesToChrome(spec.env)); // an attached browser keeps its sign-ins in its own profile
gate.reopened = null;
const content = (result as { content?: unknown } | null)?.content;
return scrubBrowserResult({ ...result as object, content: [{ type: "text", text: note }, ...Array.isArray(content) ? content : []] }, this.scrub);
diff --git a/server/cloud-browser/cloud-browser.test.ts b/server/cloud-browser/cloud-browser.test.ts
index e286dab0c4..51d3a45917 100644
--- a/server/cloud-browser/cloud-browser.test.ts
+++ b/server/cloud-browser/cloud-browser.test.ts
@@ -95,9 +95,9 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>
expect(cdpUrl).toMatch(/^ws:\/\/127\.0\.0\.1:\d+\/devtools\/browser\/[a-f0-9]{64}$/);
const key = profileKey("scout");
expect(await act(cdpUrl, 5)).toEqual([0, 1, 2, 3, 4].map((id) => `echo:${key}:${JSON.stringify({ id })}`));
- // One probe before the session was committed, the session's companion (sign-ins, downloads), and the engine's own
- // single connection for all five actions.
- expect(fake.upgrades).toHaveLength(3);
+ // The session's companion (sign-ins, downloads; its connection proves the path, no separate probe), and the engine's
+ // own single connection for all five actions.
+ expect(fake.upgrades).toHaveLength(2);
expect(cloud.dialed("bot-scout")).toBe(2);
for (const upgrade of fake.upgrades) {
expect(upgrade.path).toMatch(new RegExp(`^/${key}/[a-f0-9]{48}$`));
@@ -285,7 +285,7 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>
engine.terminate();
});
- it("sets the home's session cookies again after the sandbox's Chrome restarted, and touches nothing else of the profile", async () => {
+ it("sets the home's session cookies again after the sandbox's Chrome restarted, and keeps what the profile held", async () => {
const home = memorySignIns({ cookies: [SIGNED_IN], origins: [] });
const cloud = browser({ signIns: home.store });
urlOf(await cloud.open(request()));
@@ -294,10 +294,10 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>
// A stop and a new machine: Chrome restarted, so its session cookie is gone; a persistent one made in the sandbox stays.
const key = profileKey("scout");
fake.cookies.set(key, [{ name: "kept", value: "k", domain: "kept.example", path: "/", expires: 2_000_000_000 }]);
- const clears = fake.commands.filter((one) => one.method === "Storage.clearCookies").length;
urlOf(await cloud.open(request()));
expect(fake.cookies.get(key)?.map((cookie) => cookie.name).sort()).toEqual(["kept", "sid"]);
- expect(fake.commands.filter((one) => one.method === "Storage.clearCookies").length, "the profile is not cleared").toBe(clears);
+ // The one the sandbox kept and the home never saw went home too.
+ expect((home.store.load("bot-scout") as { state: { cookies: Array<{ name: string }> } }).state.cookies.map((cookie) => cookie.name).sort()).toEqual(["kept", "sid"]);
});
it("stops the browser sandbox through the cloud computers' sleep without sending it a shell command", async () => {
@@ -338,6 +338,10 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>
// 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));
+ // Given up during the launch: nothing more was spent on the abandoned call: no connection, no carry, its Chrome quit.
+ expect(fake.upgrades).toEqual([]);
+ expect(fake.commands, "no cookie carried").toEqual([]);
+ expect(fake.quits()).toEqual([`quit:${profileKey("scout")}`]);
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()));
@@ -396,6 +400,22 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>
expect(fake.erased).toEqual([profileKey("scout"), profileKey("writer")]);
});
+ it("logs why a session in the sandbox closed: its real idle time, a deleted bot, a stopped sandbox", async () => {
+ const lines: string[] = [];
+ const cloud = browser({ log: (line) => lines.push(line) });
+ urlOf(await cloud.open(request()));
+ clock += CLOUD_BROWSER_IDLE_MS + 60_000;
+ await cloud.closeIdle();
+ expect(lines.at(-1)).toBe("browser bot-scout: closed in the Cloud's browser sandbox: 4 minutes unused");
+ urlOf(await cloud.open(request()));
+ await cloud.erase("scout");
+ expect(lines).toContain("browser bot-scout: closed in the Cloud's browser sandbox: its bot was deleted");
+ urlOf(await cloud.open(request("writer")));
+ fake.state = "archived";
+ await cloud.failed("bot-writer");
+ expect(lines.at(-1)).toBe("browser bot-writer: closed in the Cloud's browser sandbox: its browser sandbox is archived");
+ });
+
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 });
@@ -891,6 +911,63 @@ describe("a bot's sign-ins between the home and its sandbox profile", () => {
.toMatchObject({ partitionKey: { topLevelSite: "https://top.example", hasCrossSiteAncestor: false } });
});
+ it("a sign-in the sandbox kept through a stop with no clean close (the auto-stop, the Admin's stop) reaches the home at the next open", async () => {
+ const home = memorySignIns({ cookies: [SIGNED_IN], origins: [] });
+ const cloud = browser({ signIns: home.store });
+ urlOf(await cloud.open(request()));
+ // The person signs in; the sandbox is stopped under the session (its pre-stop hook saved the cookie in the profile),
+ // and the home's close finds the sandbox gone, so nothing is written home then.
+ const key = profileKey("scout");
+ const made = { name: "ttl3b", value: "1", domain: "mail.example", path: "/", expires: 2_000_000_000 };
+ fake.cookies.set(key, [...fake.cookies.get(key) ?? [], made]);
+ fake.state = "archived";
+ await cloud.failed("bot-scout");
+ expect(home.writes, "nothing went home at that close").toEqual([]);
+ // The next open (a resume onto a new machine: the session cookie is gone, the persistent ones are on disk).
+ fake.cookies.set(key, (fake.cookies.get(key) ?? []).filter((cookie) => cookie.expires !== undefined));
+ urlOf(await cloud.open(request()));
+ const saved = (home.store.load("bot-scout") as { state: { cookies: Array<{ name: string }> } }).state.cookies.map((cookie) => cookie.name).sort();
+ expect(saved).toEqual(["sid", "ttl3b"]);
+ expect(fake.cookies.get(key)?.map((cookie) => cookie.name).sort(), "and the sandbox has both").toEqual(["sid", "ttl3b"]);
+ });
+
+ it("a carry-in never deletes a newer sandbox cookie the home never saw, while a sign-out made in the home still wins", async () => {
+ const other = { ...SIGNED_IN, name: "other", domain: "other.example" };
+ const home = memorySignIns({ cookies: [SIGNED_IN, other], origins: [] });
+ const cloud = browser({ signIns: home.store });
+ urlOf(await cloud.open(request()));
+ const key = profileKey("scout");
+ fake.cookies.set(key, [...fake.cookies.get(key) ?? [], { name: "fresh", value: "f", domain: "fresh.example", path: "/", expires: 2_000_000_000 }]);
+ fake.state = "archived";
+ await cloud.failed("bot-scout");
+ // Meanwhile, in the home, the person signs out of other.example: the home's copy changes, and is newer.
+ home.change({ cookies: [SIGNED_IN], origins: [] });
+ urlOf(await cloud.open(request()));
+ expect(fake.cookies.get(key)?.map((cookie) => cookie.name).sort(), "fresh kept, other signed out").toEqual(["fresh", "sid"]);
+ expect((home.store.load("bot-scout") as { state: { cookies: Array<{ name: string }> } }).state.cookies.map((cookie) => cookie.name).sort()).toEqual(["fresh", "sid"]);
+ });
+
+ it("a cookie Chrome dropped by itself after a carry-in (its per-site limit) is never deleted from the home, and the log says how many it took", async () => {
+ const many = Array.from({ length: 6 }, (_, i) => ({ ...SIGNED_IN, name: `c${i}`, domain: "capped.example", expires: 2_000_000_000, session: false }));
+ const lines: string[] = [];
+ const home = memorySignIns({ cookies: many, origins: [] });
+ fake.cookieCap = 4;
+ const cloud = browser({ signIns: home.store, log: (line) => lines.push(line) });
+ urlOf(await cloud.open(request()));
+ expect(lines.join("\n")).toContain("carried 4 of 6 saved cookies");
+ // The person signs in somewhere else in the session; the close writes that back, and nothing of the 6 is lost.
+ const key = profileKey("scout");
+ fake.cookies.set(key, [...fake.cookies.get(key) ?? [], { name: "new", value: "n", domain: "new.example", path: "/", expires: 2_000_000_000 }]);
+ clock += CLOUD_BROWSER_IDLE_MS;
+ await cloud.closeIdle();
+ const saved = (home.store.load("bot-scout") as { state: { cookies: Array<{ name: string }> } }).state.cookies.map((cookie) => cookie.name).sort();
+ expect(saved).toEqual(["c0", "c1", "c2", "c3", "c4", "c5", "new"]);
+ // And the next open does not carry the dropped ones again at every open.
+ const sets = fake.commands.filter((one) => one.method === "Storage.clearCookies").length;
+ urlOf(await cloud.open(request()));
+ expect(fake.commands.filter((one) => one.method === "Storage.clearCookies").length).toBe(sets);
+ });
+
it("never puts a cookie value in the log", async () => {
const lines: string[] = [];
const cloud = browser({ signIns: memorySignIns({ cookies: [SIGNED_IN], origins: [] }).store, log: (line) => lines.push(line) });
diff --git a/server/cloud-browser/companion.ts b/server/cloud-browser/companion.ts
index ebd0d15d13..f069b073fd 100644
--- a/server/cloud-browser/companion.ts
+++ b/server/cloud-browser/companion.ts
@@ -8,7 +8,8 @@ import type { Cdp, CdpEvent } from "../browser-sites.ts";
import { DOWNLOAD_LIMITS, safeFileName } from "../browser/cdp/downloads.ts";
import type { CloudBrowserRails } from "./rails.ts";
import type { ComputerOps } from "./remote.ts";
-import { carryIn, carryOut, cookieChanges, mergeCookies, restoreSessionCookies, type SavedCookie } from "./sign-ins.ts";
+import { carryIn, carryOut, type SavedCookie } from "./sign-ins.ts";
+import { mergeAtOpen, mergeInSession, prints, sandboxHolds, type SyncStore } from "./sync.ts";
/** Where a download lands in the bot's working folder. */
export const DOWNLOADS_SUBFOLDER = "downloads";
@@ -42,6 +43,8 @@ export interface CompanionDeps {
folder(botId: string): string | null;
connect(url: string, listeners: { event(message: CdpEvent): void }): Promise<Cdp>;
log(line: string): void;
+ /** Which side changed the sign-ins since the home and this sandbox last agreed (sync.ts). */
+ sync: SyncStore;
now?: () => number;
/** Bytes free and in all on the disk of a folder; tests pass their own. */
disk?(folder: string): { free: number; total: number };
@@ -73,10 +76,8 @@ export class SandboxCompanion {
#delivered = 0;
readonly #sizes = new Map<string, number>();
#delivering: Promise<void> = Promise.resolve();
- /** The profile's cookies as of the last carry or write-back: what the session changed is measured against them. */
+ /** What Chrome really held at the open, or at the last write-back: the session's own changes are measured against it. */
#baseline: SavedCookie[] | null = null;
- /** The home's copy was carried into this sandbox in this session, so a removal since then is the person's own. */
- #carried = false;
#syncedAt = 0;
#syncing = false;
@@ -91,50 +92,59 @@ export class SandboxCompanion {
#now(): number { return this.#deps.now?.() ?? Date.now(); }
async start(cdpUrl: string): Promise<void> {
- const { session, rails, signIns } = this.#deps;
+ const { session, signIns } = this.#deps;
const loaded = signIns ? signIns.load(session) : null;
if (loaded === "unreadable") throw new SignInsUnreadable();
this.#cdp = await this.#deps.connect(cdpUrl, { event: (message) => this.#event(message) });
- if (signIns && loaded && loaded.modified > rails.carried(this.#stamp)) {
- // The home's copy is newer than this sandbox's last sync: it is the truth at open, sign-outs included.
- const carried = await carryIn(this.#cdp, loaded.state).catch(() => { throw new CarryFailed(loaded.modified); });
- rails.setCarried(this.#stamp, loaded.modified);
- this.#carried = true;
- this.#baseline = carried.set;
- this.#deps.log(`browser ${session}: carried ${carried.cookies} saved cookies${carried.refused ? ` (${carried.refused} refused by Chrome and left out)` : ""} and ${carried.origins} sites' storage into the browser sandbox`);
- } else if (signIns) {
- const current = await carryOut(this.#cdp);
- // The profile's Chrome restarted since the last carry (a stop, a new machine): its session cookies, which live only in
- // a running Chrome, are gone. The home's are set again; nothing else of the profile is touched.
- const restored = loaded ? await restoreSessionCookies(this.#cdp, loaded.state.cookies, current) : [];
- if (restored.length) this.#deps.log(`browser ${session}: set ${restored.length} session cookies again after the browser sandbox's Chrome restarted`);
- this.#baseline = [...current, ...restored];
- }
+ if (signIns) await this.#syncAtOpen(this.#cdp, signIns, loaded);
this.#syncedAt = this.#now();
await this.#cdp.send("Browser.setDownloadBehavior", { behavior: "allowAndName", downloadPath: this.downloadDir, eventsEnabled: true });
}
- /** Writes the session's own cookie changes into the home's copy: a cookie the session never touched stays as the home
- * has it, and an empty profile that was never carried into never empties the home. */
+ /** The home and the sandbox profile made to agree at an open (sync.ts has the rules): what the sandbox kept that the home
+ * never saw goes home, and the home's copy is set in the sandbox when it differs from what the sandbox holds. */
+ async #syncAtOpen(cdp: Cdp, signIns: SignInStore, loaded: Exclude<ReturnType<SignInStore["load"]>, "unreadable">): Promise<void> {
+ const { session, rails, sync } = this.#deps;
+ const last = sync.load(this.#stamp);
+ const sandbox = await carryOut(cdp);
+ const home = loaded?.state.cookies ?? [];
+ const { merged, fromSandbox } = mergeAtOpen(home, sandbox, last);
+ let homeAt = loaded?.modified ?? 0;
+ if (fromSandbox > 0) {
+ homeAt = signIns.save(session, merged);
+ this.#deps.log(`browser ${session}: saved ${fromSandbox} sign-in cookies the browser sandbox kept but the home did not have`);
+ }
+ // The home's storage goes in only when its copy changed since this sandbox last had it.
+ const storage = loaded && loaded.modified > rails.carried(this.#stamp) ? loaded.state.origins : [];
+ let held = sandbox;
+ if (!sandboxHolds(merged, sandbox, last) || storage.length > 0) {
+ const carried = await carryIn(cdp, { cookies: merged, origins: storage }).catch(() => { throw new CarryFailed(loaded?.modified ?? 0); });
+ held = await carryOut(cdp);
+ const kept = new Set(Object.keys(prints(held)));
+ const took = merged.filter((cookie) => kept.has(JSON.stringify([cookie.name, cookie.domain, cookie.path, cookie.partitionKey ?? null]))).length;
+ this.#deps.log(`browser ${session}: carried ${took} of ${merged.length} saved cookies${carried.refused ? ` (${carried.refused} refused by Chrome)` : ""} and ${carried.origins} sites' storage into the browser sandbox`);
+ }
+ rails.setCarried(this.#stamp, homeAt);
+ sync.save(this.#stamp, { home: prints(merged), sandbox: prints(held) });
+ this.#baseline = held;
+ }
+
+ /** Writes the session's own cookie changes into the home's copy: set, changed and removed since what Chrome really held
+ * at the open (a cookie Chrome dropped by itself is no removal), except a cookie the home changed meanwhile. */
async syncSignIns(): Promise<void> {
- const { session, rails, signIns } = this.#deps;
+ const { session, rails, signIns, sync } = this.#deps;
if (!this.#cdp || !signIns || this.#baseline === null || this.#syncing) return;
this.#syncing = true;
try {
const current = await carryOut(this.#cdp);
- const changes = cookieChanges(this.#baseline, current);
this.#syncedAt = this.#now();
- if (!changes.set.length && !changes.removed.length) return;
const home = signIns.load(session);
if (home === "unreadable") return;
- const before = home?.state.cookies ?? [];
- const merged = mergeCookies(before, changes);
- if (!this.#carried && before.length > 0 && merged.length < before.length / 2) {
- this.#deps.log(`browser ${session}: kept the home's saved sign-ins: the browser sandbox's profile had far fewer and was never carried into this session`);
- return;
- }
- rails.setCarried(this.#stamp, signIns.save(session, merged));
+ const last = sync.load(this.#stamp);
+ const { merged, changed } = mergeInSession(home?.state.cookies ?? [], this.#baseline, current, last);
this.#baseline = current;
+ if (changed > 0) rails.setCarried(this.#stamp, signIns.save(session, merged));
+ sync.save(this.#stamp, { home: prints(merged), sandbox: prints(current) });
} finally {
this.#syncing = false;
}
diff --git a/server/cloud-browser/index.ts b/server/cloud-browser/index.ts
index 1bd679c42a..a79b6c2a70 100644
--- a/server/cloud-browser/index.ts
+++ b/server/cloud-browser/index.ts
@@ -4,10 +4,12 @@
// install never builds this. The one operator lever, never a product setting: OMB_CLOUD_BROWSER=home keeps every browser
// in the home, and after a day of it the sandbox is deleted.
import { randomBytes } from "node:crypto";
+import { join } from "node:path";
import { cloudFailureOf } from "../boat-limit.ts";
-import { CloudBrowserDoors, dialable, probeDoor, type DoorTarget } from "./door.ts";
import { connectCdp } from "../browser-sites.ts";
+import { CloudBrowserDoors, dialable, probeDoor, type DoorTarget } from "./door.ts";
+import { syncStore } from "./sync.ts";
import { CarryFailed, SandboxCompanion, SignInsUnreadable, type CompanionDeps, type SignInStore } from "./companion.ts";
import { createCloudBrowserRails, type CloudBrowserRails, type HomeReason } from "./rails.ts";
import { BROWSER_SANDBOX_CHROMES, BROWSER_SANDBOX_OWNER, COMPUTER_DOOR_PORT, OldRelay, profileKey, StaysHome, wakeSandbox, type ComputerOps } from "./remote.ts";
@@ -85,6 +87,7 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
const log = deps.log ?? ((line: string) => console.warn(line));
const rails = deps.rails ?? createCloudBrowserRails({ dataDir: deps.dataDir, now });
const doors = new CloudBrowserDoors(now);
+ const sync = syncStore(join(deps.dataDir, "cloud-browser", "sync"));
/** Each running session's bot; one Chrome per bot's profile. */
const sessions = new Map<string, string>();
/** Bots whose browser is being opened now. */
@@ -192,10 +195,11 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
async function erase(botId: string): Promise<void> {
const key = profileKey(botId);
rails.forgetProfile(key);
+ sync.forget(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 });
+ for (const [session, owner] of Array.from(sessions)) if (owner === botId) await close(session, { discard: true, why: "its bot was deleted" });
}
async function launch(request: OpenRequest, ops: ComputerOps, gaveUp: () => boolean): Promise<Opened> {
@@ -208,7 +212,11 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
box = await wake(ops);
if (gaveUp()) return { home: "slow" };
const secret = randomBytes(24).toString("hex");
+ // The door's port is put on the relay while Chrome starts: it needs no Chrome.
+ const hosted = ops.host(box.id, COMPUTER_DOOR_PORT).catch(() => null);
const answer = await ops.launch(box.id, key, secret);
+ // Given up while the launch ran: nothing more is spent on this call (no port, no carry); its Chrome quits.
+ if (gaveUp()) { await quit(); return { home: "slow" }; }
if (!answer.chrome || !answer.home) {
rails.failed();
await quit();
@@ -220,7 +228,7 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
await quit();
return home(request, "no-policy");
}
- const relay = await ops.host(box.id, COMPUTER_DOOR_PORT).catch(() => null);
+ const relay = await hosted;
const url = relay ? dialable(relay) : null;
if (!url) {
rails.noRoute();
@@ -228,16 +236,12 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
return home(request, "no-route");
}
const target: DoorTarget = { url, secret: `${key}/${secret}` };
- if (!await probeDoor(target)) {
- rails.failed();
- await quit();
- return home(request, "unreachable");
- }
+ // No separate probe of the path: the companion's own connection through the door, next, proves it (or fails the open).
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,
- folder: (botId) => deps.folder?.(botId) ?? null, log, now, ...(deps.disk ? { disk: deps.disk } : {}),
+ folder: (botId) => deps.folder?.(botId) ?? null, log, now, sync, ...(deps.disk ? { disk: deps.disk } : {}),
connect: deps.connect ?? ((url, listeners) => connectCdp(url, 10_000, listeners)),
});
try {
@@ -335,8 +339,10 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
}
/** The bot's Chrome quits cleanly (its cookies written), the engine's session ends, and the sandbox may sleep. */
- async function close(session: string, options: { discard?: boolean } = {}): Promise<void> {
+ /** `why`: what the log says; an idle close says how long it really sat unused. */
+ async function close(session: string, options: { discard?: boolean; why?: string } = {}): Promise<void> {
const botId = sessions.get(session);
+ const unusedFor = Math.round((now() - (lastUse.get(session) ?? now())) / 60_000);
if (!botId || closing.has(session)) return;
closing.add(session);
try {
@@ -354,7 +360,7 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
const ops = deps.ops();
if (ops && boxId) await ops.quit(boxId, bots().size > 0 ? profileKey(botId) : null).catch(() => undefined);
letSleep();
- log(`browser ${session}: closed in the Cloud's browser sandbox after ${Math.round(CLOUD_BROWSER_IDLE_MS / 60_000)} minutes unused`);
+ log(`browser ${session}: closed in the Cloud's browser sandbox: ${options.why ?? `${unusedFor} minutes unused`}`);
} finally {
closing.delete(session);
}
@@ -383,7 +389,7 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
const alive = state !== null && READY_STATES.has(state) && target !== null && await probeDoor(target, 5_000);
if (alive) return false;
log(`browser ${session}: its browser sandbox is ${state && !READY_STATES.has(state) ? `${state}` : "not answering"}; the session ends and the next call opens again`);
- await close(session);
+ await close(session, { why: `its browser sandbox is ${state && !READY_STATES.has(state) ? state : "not answering"}` });
return true;
}
diff --git a/server/cloud-browser/sign-ins.ts b/server/cloud-browser/sign-ins.ts
index e0acca1e27..8a3b6c996a 100644
--- a/server/cloud-browser/sign-ins.ts
+++ b/server/cloud-browser/sign-ins.ts
@@ -38,26 +38,6 @@ export function cookieParam(cookie: SavedCookie): Record<string, unknown> {
export const cookieId = (cookie: SavedCookie): string =>
JSON.stringify([cookie.name, cookie.domain, cookie.path, cookie.partitionKey ?? null]);
-/** The cookies a session changed: those it set or changed since `baseline`, and the ids of those it removed. */
-export function cookieChanges(baseline: readonly SavedCookie[], current: readonly SavedCookie[]) {
- const before = new Map(baseline.map((cookie) => [cookieId(cookie), cookie]));
- const now = new Map(current.map((cookie) => [cookieId(cookie), cookie]));
- const set = [...now.values()].filter((cookie) => {
- const old = before.get(cookieId(cookie));
- return !old || old.value !== cookie.value || old.expires !== cookie.expires;
- });
- const removed = [...before.keys()].filter((id) => !now.has(id));
- return { set, removed };
-}
-
-/** The home's cookies with only a session's own changes applied: a cookie the session never touched stays as the home has it. */
-export function mergeCookies(home: readonly unknown[], changes: ReturnType<typeof cookieChanges>): SavedCookie[] {
- const merged = new Map(home.filter(isSavedCookie).map((cookie) => [cookieId(cookie), cookie]));
- for (const id of changes.removed) merged.delete(id);
- for (const cookie of changes.set) merged.set(cookieId(cookie), cookie);
- return [...merged.values()].slice(0, MAX_COOKIES);
-}
-
interface Storage { origin: string; items: Array<{ name: string; value: string }> }
function storageOf(origins: readonly unknown[]): Storage[] {
@@ -82,15 +62,13 @@ const BATCH = 100;
async function setInBatches(cdp: Cdp, cookies: readonly SavedCookie[]): Promise<{ set: SavedCookie[]; refused: number }> {
const set: SavedCookie[] = [];
let refused = 0;
- for (let at = 0; at < cookies.length; at += BATCH) {
- const batch = cookies.slice(at, at + BATCH);
- try {
- await cdp.send("Storage.setCookies", { cookies: batch.map(cookieParam) });
- set.push(...batch);
- continue;
- } catch {
- // One of them is refused: each on its own.
- }
+ const batches: SavedCookie[][] = [];
+ for (let at = 0; at < cookies.length; at += BATCH) batches.push(cookies.slice(at, at + BATCH));
+ // Every batch is sent at once (Chrome takes them in order on the one connection): one round trip, not one per batch.
+ const answers = await Promise.all(batches.map((batch) => cdp.send("Storage.setCookies", { cookies: batch.map(cookieParam) }).then(() => true, () => false)));
+ for (const [i, batch] of batches.entries()) {
+ if (answers[i]) { set.push(...batch); continue; }
+ // One of them is refused: each on its own.
for (const cookie of batch) {
try {
await cdp.send("Storage.setCookies", { cookies: [cookieParam(cookie)] });
@@ -111,8 +89,11 @@ async function setInBatches(cdp: Cdp, cookies: readonly SavedCookie[]): Promise<
* 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);
+ // Sent together with the batches: Chrome clears first, then sets, in the order it got them.
+ const cleared = cdp.send("Storage.clearCookies", {});
+ const batches = setInBatches(cdp, saved);
+ await cleared;
+ const { set, refused } = await batches;
const cookies = set;
const storage = storageOf(state.origins);
let carried = 0;
@@ -142,14 +123,6 @@ export async function carryIn(cdp: Cdp, state: { cookies: readonly unknown[]; or
return { cookies: cookies.length, refused, origins: carried, set };
}
-/** The home's session cookies (no expiry: Chrome keeps them only while it runs) that the profile no longer has, set again
- * one at a time. Only these: a cookie the profile has, or one the session set since, is never replaced. */
-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)));
- 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. */
export async function carryOut(cdp: Cdp): Promise<SavedCookie[]> {
const { cookies } = await cdp.send("Storage.getCookies", {}) as { cookies?: unknown[] };
diff --git a/server/cloud-browser/sync.ts b/server/cloud-browser/sync.ts
new file mode 100644
index 0000000000..30f584074d
--- /dev/null
+++ b/server/cloud-browser/sync.ts
@@ -0,0 +1,137 @@
+// Which side changed a bot's sign-ins since the home and its sandbox profile last agreed. At each sync both sides are
+// remembered as fingerprints (one short hash of each cookie's value and attributes, by cookie): never a cookie's value.
+// The rules, so that no sign-in a person made is ever lost:
+// - at an open, the sandbox profile's cookies the home never saw (made in a session that ended without a clean close: the
+// provider's auto-stop, the Admin's stop, a home that slept) are added to the home's copy, and the home's newer copy is
+// the truth for everything else: a sign-out made in the home stays one;
+// - a cookie missing from the sandbox at an open is never a removal: Chrome drops session cookies on a restart and evicts
+// cookies past its per-site limit by itself. Only a removal seen during a session, against what Chrome really held at
+// its start, removes a cookie from the home;
+// - when both sides changed the same cookie since they last agreed, the home's wins.
+import { createHash } from "node:crypto";
+import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { cookieId, MAX_COOKIES, type SavedCookie } from "./sign-ins.ts";
+
+export type Prints = Record<string, string>;
+export interface SyncState { home: Prints; sandbox: Prints }
+
+const isCookie = (value: unknown): value is SavedCookie => {
+ const cookie = value as Partial<SavedCookie> | null;
+ return typeof cookie?.name === "string" && typeof cookie.value === "string" && typeof cookie.domain === "string" && typeof cookie.path === "string";
+};
+
+/** A cookie's value and attributes as one short hash, so a change is seen and no value is kept. */
+export function fingerprint(cookie: SavedCookie): string {
+ const expires = cookie.session || typeof cookie.expires !== "number" || cookie.expires < 0 ? -1 : Math.round(cookie.expires);
+ return createHash("sha256").update(JSON.stringify([cookie.value, expires, cookie.httpOnly === true, cookie.secure === true, cookie.sameSite ?? null])).digest("hex").slice(0, 16);
+}
+
+export function prints(cookies: readonly unknown[]): Prints {
+ const out: Prints = {};
+ for (const cookie of cookies) if (isCookie(cookie)) out[cookieId(cookie)] = fingerprint(cookie);
+ return out;
+}
+
+const byId = (cookies: readonly unknown[]) => new Map(cookies.filter(isCookie).map((cookie) => [cookieId(cookie), cookie]));
+
+/** The home changed this cookie since the last sync (changed it, or removed it): the home's side wins it. */
+function homeChanged(id: string, home: Map<string, SavedCookie>, last: SyncState | null): boolean {
+ if (!last) return home.has(id);
+ const was = last.home[id];
+ const now = home.get(id);
+ return now ? was !== fingerprint(now) : was !== undefined;
+}
+
+/** At an open: the home's copy, with the cookies the sandbox profile set or changed since the last sync that the home did not change. */
+export function mergeAtOpen(homeCookies: readonly unknown[], sandboxCookies: readonly SavedCookie[], last: SyncState | null): { merged: SavedCookie[]; fromSandbox: number } {
+ const home = byId(homeCookies);
+ const merged = new Map(home);
+ let fromSandbox = 0;
+ for (const cookie of sandboxCookies) {
+ const id = cookieId(cookie);
+ const changedInSandbox = last ? last.sandbox[id] !== fingerprint(cookie) : !home.has(id);
+ if (!changedInSandbox || homeChanged(id, home, last)) continue;
+ const kept = home.get(id);
+ if (kept && fingerprint(kept) === fingerprint(cookie)) continue;
+ merged.set(id, cookie);
+ fromSandbox += 1;
+ }
+ return { merged: [...merged.values()].slice(0, MAX_COOKIES), fromSandbox };
+}
+
+/** During a session: the home's copy with the session's own changes since `baseline` (what Chrome really held), removals
+ * included, except a cookie the home changed since the last sync. */
+export function mergeInSession(homeCookies: readonly unknown[], baseline: readonly SavedCookie[], current: readonly SavedCookie[], last: SyncState | null): { merged: SavedCookie[]; changed: number } {
+ const home = byId(homeCookies);
+ const before = byId(baseline);
+ const now = byId(current);
+ const merged = new Map(home);
+ let changed = 0;
+ for (const [id, cookie] of now) {
+ const was = before.get(id);
+ if (was && fingerprint(was) === fingerprint(cookie)) continue;
+ if (last && homeChanged(id, home, last)) continue;
+ merged.set(id, cookie);
+ changed += 1;
+ }
+ for (const id of before.keys()) {
+ if (now.has(id) || (last && homeChanged(id, home, last))) continue;
+ if (merged.delete(id)) changed += 1;
+ }
+ return { merged: [...merged.values()].slice(0, MAX_COOKIES), changed };
+}
+
+/** Whether the sandbox already holds what the merge asks of it: the same cookies, the same values. A cookie Chrome would
+ * not keep before (in the home at the last sync, absent from the sandbox then and now, unchanged in the home) is not asked
+ * again, so a per-site cap does not cost a carry at every open. */
+export function sandboxHolds(merged: readonly SavedCookie[], sandbox: readonly SavedCookie[], last: SyncState | null): boolean {
+ const have = prints(sandbox);
+ for (const cookie of merged) {
+ const id = cookieId(cookie);
+ const print = fingerprint(cookie);
+ if (have[id] === print) continue;
+ const notKept = last && have[id] === undefined && last.sandbox[id] === undefined && last.home[id] === print;
+ if (!notKept) return false;
+ }
+ const wanted = new Set(merged.map(cookieId));
+ return Object.keys(have).every((id) => wanted.has(id));
+}
+
+/** The remembered fingerprints of each sandbox and bot (`<box id>:<key>`), a file each, with no cookie value in it. */
+export function syncStore(dir: string) {
+ const file = (stamp: string) => join(dir, `${stamp.replace(":", "-")}.json`);
+ const valid = (stamp: string) => /^bx_[a-z0-9]{8}:[a-f0-9]{16}$/.test(stamp);
+ return {
+ load(stamp: string): SyncState | null {
+ if (!valid(stamp)) return null;
+ try {
+ const saved = JSON.parse(readFileSync(file(stamp), "utf8")) as Partial<SyncState>;
+ return saved.home && saved.sandbox && typeof saved.home === "object" && typeof saved.sandbox === "object" ? { home: saved.home, sandbox: saved.sandbox } : null;
+ } catch {
+ return null;
+ }
+ },
+ save(stamp: string, state: SyncState): void {
+ if (!valid(stamp)) return;
+ try {
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
+ const temporary = `${file(stamp)}.tmp`;
+ writeFileSync(temporary, JSON.stringify(state), { mode: 0o600 });
+ renameSync(temporary, file(stamp));
+ } catch {
+ // Without it the next open treats the sandbox as new: only cookies the home lacks are taken from it.
+ }
+ },
+ /** A deleted bot's: every sandbox's record of its profile. */
+ forget(key: string): void {
+ try {
+ for (const name of readdirSync(dir)) if (name.endsWith(`-${key}.json`)) rmSync(join(dir, name), { force: true });
+ } catch {
+ // None yet.
+ }
+ },
+ };
+}
+export type SyncStore = ReturnType<typeof syncStore>;
diff --git a/server/cloud-browser/testing/fake-computer.ts b/server/cloud-browser/testing/fake-computer.ts
index a9555c9c18..57e3f68917 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;
+ /** Cookies of one site Chrome keeps at most (its per-site limit); null keeps all. */
+ cookieCap: number | null;
/** 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). */
@@ -79,7 +81,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, takeBackFails: false, chromes: 2, caps: null, patchStatus: 200, oldRelayAnswer: 404, stall: new Map(), erased: [], 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, cookieCap: null, 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>>();
@@ -192,12 +194,18 @@ export async function startFakeComputer(): Promise<FakeComputer> {
fake.commands.push({ key, method: message.method, params });
let result: Record<string, unknown> = {};
const refusedCookie = message.method === "Storage.setCookies" && (params.cookies as Array<Record<string, unknown>>).some((cookie) => cookie.sameSite === "None" && cookie.secure !== true);
+ // A sandbox that stopped answers nothing on a connection it had: as if the machine went.
+ if (fake.state === "archived" || fake.state === "archiving") { ws.terminate(); return; }
if (fake.failing.has(message.method) || refusedCookie) {
ws.send(JSON.stringify({ id: message.id, error: { code: -32000, message: "Sanitizing cookie failed" } }));
return;
}
if (message.method === "Storage.clearCookies") fake.cookies.set(key, []);
- if (message.method === "Storage.setCookies") fake.cookies.set(key, [...(fake.cookies.get(key) ?? []), ...(params.cookies as Array<Record<string, unknown>>)]);
+ if (message.method === "Storage.setCookies") {
+ // Chrome keeps at most so many cookies of one site and drops the rest by itself, as it does past its per-site limit.
+ const all = [...(fake.cookies.get(key) ?? []), ...(params.cookies as Array<Record<string, unknown>>)];
+ fake.cookies.set(key, fake.cookieCap === null ? all : all.filter((cookie, i) => all.slice(0, i).filter((one) => one.domain === cookie.domain).length < fake.cookieCap!));
+ }
if (message.method === "Storage.getCookies") result = { cookies: (fake.cookies.get(key) ?? []).map((cookie) => ({ ...cookie, size: 1, session: cookie.expires === undefined, expires: cookie.expires ?? -1 })) };
if (message.method === "Browser.setDownloadBehavior") { const set = watchers.get(key) ?? new Set(); set.add(ws); watchers.set(key, set); }
if (message.method === "Target.createTarget") result = { targetId: "page-1" };
diff --git a/server/host/cloud-computer-power.test.ts b/server/host/cloud-computer-power.test.ts
index bb3c63e858..d46d3f8088 100644
--- a/server/host/cloud-computer-power.test.ts
+++ b/server/host/cloud-computer-power.test.ts
@@ -111,6 +111,17 @@ describe("cloud computer power", () => {
expect(logs).toEqual(["cloud computer bot-a: asleep after 600s idle"]);
});
+ it("says the browser sandbox's real idle time when it sleeps, not the computers' window", async () => {
+ fake.states.set("browser", "ready");
+ power.used("browser", 3 * MINUTE);
+ await vi.advanceTimersByTimeAsync(2 * MINUTE);
+ power.used("browser", 1_000);
+ // The shorter window never cuts the 3 minutes asked at the start: it sleeps then, a minute after its last use.
+ await vi.advanceTimersByTimeAsync(MINUTE);
+ expect(sleeps()).toEqual(["browser"]);
+ expect(logs).toEqual(["the Cloud's browser sandbox: asleep after 60s idle"]);
+ });
+
it("counts the window from the end of a turn, however long the turn ran", async () => {
fake.states.set("bot-a", "ready");
power.attached(turn("t1"), "bot-a");
diff --git a/server/host/cloud-computer-power.ts b/server/host/cloud-computer-power.ts
index 17221b8541..e4ca62e5d7 100644
--- a/server/host/cloud-computer-power.ts
+++ b/server/host/cloud-computer-power.ts
@@ -68,6 +68,8 @@ export interface CloudComputerReadyHooks {
export function createCloudComputerPower(deps: CloudComputerPowerDeps) {
const { cfg, broadcast } = deps;
const timers = new Map<string, ComputerIdleTimer>();
+ /** When each computer was last used, so its sleep says how long it really sat idle. */
+ const lastUsed = new Map<string, number>();
const turnOwners = new Map<string, { generation: string; owner: string }>();
/** A start can outlive the turn that asked for it; stopping a computer mid-create would make provisionBoat delete it. */
const starting = new Map<string, number>();
@@ -113,13 +115,16 @@ export function createCloudComputerPower(deps: CloudComputerPowerDeps) {
release();
}
forget(owner);
- deps.log(`cloud computer ${owner}: asleep after ${Math.round(CLOUD_COMPUTER_IDLE_MS / 1_000)}s idle`);
+ const idleFor = Math.round((Date.now() - (lastUsed.get(owner) ?? Date.now())) / 1_000);
+ lastUsed.delete(owner);
+ deps.log(`${owner === "browser" ? "the Cloud's browser sandbox" : `cloud computer ${owner}`}: asleep after ${idleFor}s idle`);
}
/** Starts, or restarts, this owner's idle window; `windowMs` asks for a shorter or longer one (the browser's), which
* never cuts a longer window another use asked for. */
function used(owner: string, windowMs?: number): void {
if (closed || !boat.boatConfigured(cfg)) return;
+ lastUsed.set(owner, Date.now());
let timer = timers.get(owner);
if (!timer) {
timer = new ComputerIdleTimer(CLOUD_COMPUTER_IDLE_MS, () => busy(owner), () => sleepIfIdle(owner), (error, retryInMs) => {