Skip to content

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

Cloud browser: only real use keeps a sandbox session open; session cookies set again after its Chrome restarted; no shell command at its stop

milind-soniecbaff400b57
diff --git a/server/boat.ts b/server/boat.ts
index 5dc45e9274..2b3f29d06e 100644
--- a/server/boat.ts
+++ b/server/boat.ts
@@ -753,9 +753,9 @@ const QUIESCE_BROWSER = [
'for i in 1 2 3 4 5 6 7 8; do if ! pgrep -x chrome >/dev/null 2>&1 && ! pgrep -x google-chrome >/dev/null 2>&1 && ! pgrep -x chromium >/dev/null 2>&1 && ! pgrep -x chromium-browser >/dev/null 2>&1; then break; fi; sleep 0.25; done',
].join("; ");
-async function stopBoat(cfg: AppConfig, boxId: string): Promise<void> {
+async function stopBoat(cfg: AppConfig, boxId: string, browserSandbox = false): Promise<void> { // The Cloud's browser sandbox closes its Chromes itself before a stop (its pre-stop hook): no shell command goes to it.
assertBoatNotDeleting(boxId);
- await runCommand(cfg, boxId, QUIESCE_BROWSER, { timeoutMs: 5_000 }).catch(() => null);
+ if (!browserSandbox) await runCommand(cfg, boxId, QUIESCE_BROWSER, { timeoutMs: 5_000 }).catch(() => null);
const stopped = await boatJson(cfg, `/sandboxes/${boxId}/stop`, { method: "POST" });
if (!stopped.ok) {
throw Object.assign(new Error(boatErrorMessage(stopped.status, "boat sleep", stopped.body, usesIncludedBoat(cfg))), { status: stopped.status });
@@ -1162,7 +1162,7 @@ export async function sleepBoat(cfg: AppConfig, botId: string) {
cfg = snapshotBoatConfig(cfg);
const boat = await findBoat(cfg, botId);
if (!boat) throw new Error("no computer for this bot");
- await stopBoat(cfg, boat.id);
+ await stopBoat(cfg, boat.id, botId === "browser");
forgetBoatId(boat.id);
return { ok: true };
}
diff --git a/server/cloud-browser/cloud-browser.test.ts b/server/cloud-browser/cloud-browser.test.ts
index 1c88c819c7..8c9562ea6b 100644
--- a/server/cloud-browser/cloud-browser.test.ts
+++ b/server/cloud-browser/cloud-browser.test.ts
@@ -226,27 +226,84 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>
it("pushes the provider's own auto-stop ahead while a browser is used, at most every 10 minutes, so it stops the sandbox only when unused", async () => {
const cloud = browser();
- const cdpUrl = urlOf(await cloud.open(request()));
+ urlOf(await cloud.open(request()));
const patches = () => fake.requests.filter((one) => one.method === "PATCH" && one.body?.ttlSeconds !== undefined).map((one) => one.body);
- await act(cdpUrl, 1);
clock += 60_000;
+ cloud.touch("bot-scout");
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);
+ cloud.touch("bot-scout");
await cloud.closeIdle();
expect(patches(), "at most every 10 minutes").toHaveLength(1);
+ // A turn holds the browser for a long call: that is use too.
+ held = true;
clock += TTL_REFRESH_MS;
- await act(cdpUrl, 1);
await cloud.closeIdle();
expect(patches()).toHaveLength(2);
- held = true;
+ held = false;
clock += TTL_REFRESH_MS;
await cloud.closeIdle();
+ expect(cloud.active("bot-scout"), "unused since: closed").toBeNull();
expect(patches(), "unused since: the deadline is left to run out").toHaveLength(2);
});
+ it("closes a session whose attached engine sends keepalives forever: only a bot's call, a turn or a person counts as use", async () => {
+ const cloud = browser();
+ const cdpUrl = urlOf(await cloud.open(request()));
+ // The engine stays attached after its turn ended without a close, and keeps the connection alive.
+ const engine = new WebSocket(cdpUrl);
+ await new Promise<void>((resolve, reject) => { engine.once("open", () => resolve()); engine.once("error", reject); });
+ const keepalive = async () => { engine.send(JSON.stringify({ id: Math.random() })); await new Promise((resolve) => engine.once("message", resolve)); };
+ const patchesBefore = fake.requests.filter((one) => one.method === "PATCH").length;
+ for (let minute = 0; minute < 2; minute++) {
+ clock += 60_000;
+ await keepalive();
+ await cloud.closeIdle();
+ }
+ // A bot's call at minute 2 is real use: the 3 minutes count from it.
+ cloud.touch("bot-scout");
+ for (let minute = 0; minute < 2; minute++) {
+ clock += 60_000;
+ await keepalive();
+ await cloud.closeIdle();
+ }
+ expect(cloud.active("bot-scout"), "2 minutes after the last call").not.toBeNull();
+ clock += 60_000;
+ await keepalive();
+ await cloud.closeIdle();
+ expect(cloud.active("bot-scout"), "3 minutes after the last call, keepalives or not").toBeNull();
+ expect(engineClosed).toEqual(["bot-scout"]);
+ expect(fake.quits().at(-1)).toBe("quit-all");
+ expect(used.at(-1)).toEqual([BROWSER_SANDBOX_OWNER, 1_000]);
+ expect(fake.requests.filter((one) => one.method === "PATCH").length - patchesBefore, "keepalives never push the provider's deadline").toBeLessThanOrEqual(1);
+ engine.terminate();
+ });
+
+ it("sets the home's session cookies again after the sandbox's Chrome restarted, and touches nothing else of the profile", async () => {
+ const home = memorySignIns({ cookies: [SIGNED_IN], origins: [] });
+ const cloud = browser({ signIns: home.store });
+ urlOf(await cloud.open(request()));
+ clock += CLOUD_BROWSER_IDLE_MS;
+ await cloud.closeIdle();
+ // 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);
+ });
+
+ it("stops the browser sandbox through the cloud computers' sleep without sending it a shell command", async () => {
+ fake.requests.length = 0;
+ const { sleepBoat } = await import("../boat.ts");
+ await sleepBoat({} as AppConfig, BROWSER_SANDBOX_OWNER);
+ expect(fake.requests.filter((one) => one.path.endsWith("/commands")), "no QUIESCE: its pre-stop hook closes its Chromes").toEqual([]);
+ expect(fake.requests.filter((one) => one.path.endsWith("/stop"))).toHaveLength(1);
+ });
+
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();
@@ -318,6 +375,7 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>
expect(engineClosed, "a browser a turn holds stays").toEqual([]);
held = false;
await cloud.close("bot-writer");
+ clock += CLOUD_BROWSER_IDLE_MS;
expect(fake.quits().at(-1), "the other bot's Chrome keeps running").toBe(`quit:${profileKey("writer")}`);
expect(used.at(-1)).toEqual([BROWSER_SANDBOX_OWNER, CLOUD_BROWSER_IDLE_MS]);
await cloud.closeIdle();
@@ -638,9 +696,9 @@ describe("a bot's sign-ins between the home and its sandbox profile", () => {
expect(cloud.report().held).toBeNull();
clock += CLOUD_BROWSER_IDLE_MS;
await cloud.closeIdle();
- const sets = fake.commands.filter((one) => one.method === "Storage.setCookies").length;
+ const carries = fake.commands.filter((one) => one.method === "Storage.clearCookies").length;
urlOf(await cloud.open(request()));
- expect(fake.commands.filter((one) => one.method === "Storage.setCookies").length).toBe(sets);
+ expect(fake.commands.filter((one) => one.method === "Storage.clearCookies").length, "the same copy is not carried again").toBe(carries);
});
it("when Chrome takes nothing of the home's copy, opens in the home, never as a sandbox failure, and wakes the sandbox for it again only once the copy changes", async () => {
@@ -662,6 +720,8 @@ describe("a bot's sign-ins between the home and its sandbox profile", () => {
const home = memorySignIns(null);
const cloud = browser({ signIns: home.store });
const cdpUrl = urlOf(await cloud.open(request()));
+ // A long turn holds the browser all along.
+ held = true;
clock += SIGN_IN_SYNC_MS;
await act(cdpUrl, 1);
await cloud.closeIdle();
diff --git a/server/cloud-browser/companion.ts b/server/cloud-browser/companion.ts
index f4b95335c8..ebd0d15d13 100644
--- a/server/cloud-browser/companion.ts
+++ b/server/cloud-browser/companion.ts
@@ -8,7 +8,7 @@ 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, type SavedCookie } from "./sign-ins.ts";
+import { carryIn, carryOut, cookieChanges, mergeCookies, restoreSessionCookies, type SavedCookie } from "./sign-ins.ts";
/** Where a download lands in the bot's working folder. */
export const DOWNLOADS_SUBFOLDER = "downloads";
@@ -103,7 +103,12 @@ export class SandboxCompanion {
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) {
- this.#baseline = await carryOut(this.#cdp);
+ 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];
}
this.#syncedAt = this.#now();
await this.#cdp.send("Browser.setDownloadBehavior", { behavior: "allowAndName", downloadPath: this.downloadDir, eventsEnabled: true });
diff --git a/server/cloud-browser/index.ts b/server/cloud-browser/index.ts
index e33323f108..b1ee7cb28d 100644
--- a/server/cloud-browser/index.ts
+++ b/server/cloud-browser/index.ts
@@ -32,7 +32,8 @@ export interface CloudBrowserDeps {
used(owner: string, windowMs: number): void;
/** Closes the session's browser engine in the home (its connection to the sandbox goes with it). */
closeEngine(session: string): Promise<unknown>;
- /** A turn holds this session's browser now: it is not closed for being idle. */
+ /** A turn holds this session's browser, a call runs in it, or a person watches or drives it: real use, which keeps it open.
+ * Bytes on the connection are not: the attached engine's keepalives and the companion's own reads never count. */
held(session: string): boolean;
/** The home's saved sign-ins (agent-browser's restore file), carried in and back; null keeps them apart. */
signIns?: SignInStore | null;
@@ -84,6 +85,8 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
const pendingSessions = new Map<string, Promise<Opened>>();
const closing = new Set<string>();
const companions = new Map<string, SandboxCompanion>();
+ /** When each session was last really used (opened, a bot's call, held by a turn, a person): the only activity that counts. */
+ const lastUse = new Map<string, number>();
/** What a closed session's companion still had to say (a last download retry), for that session's next call. */
const leftNotes = new Map<string, string[]>();
/** One wake of the sandbox at a time, shared by every bot opening meanwhile. */
@@ -204,6 +207,7 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
rails.setCarryBad(key, null);
companions.set(request.session, companion);
sessions.set(request.session, request.botId);
+ lastUse.set(request.session, now());
rails.opened();
startSweep();
log(`browser ${request.session}: opened in the Cloud's browser sandbox${box.started ? " (started for it)" : ""}`);
@@ -278,6 +282,7 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
const notes = companion?.takeNotes() ?? [];
if (notes.length) leftNotes.set(session, notes);
companions.delete(session);
+ lastUse.delete(session);
await deps.closeEngine(session).catch(() => undefined);
doors.close(session);
sessions.delete(session);
@@ -294,7 +299,7 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
async function refreshTtl(at: number): Promise<void> {
const ops = deps.ops();
if (!ops || !boxId || at - ttlRefreshedAt < TTL_REFRESH_MS) return;
- const used = doors.sessions().some((session) => (doors.lastActivity(session) ?? 0) > ttlRefreshedAt);
+ const used = [...lastUse.values()].some((at) => at > ttlRefreshedAt);
if (!used) return;
ttlRefreshedAt = at;
await ops.refreshTtl(boxId, SANDBOX_IDLE_TTL_SECONDS).catch(() => undefined);
@@ -302,12 +307,13 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
async function closeIdle(): Promise<void> {
const at = now();
- await refreshTtl(at);
await Promise.all([...companions.values()].map((companion) => companion.periodic()));
await Promise.all(doors.sessions().map(async (session) => {
- const last = doors.lastActivity(session);
- if (last !== null && at - last >= CLOUD_BROWSER_IDLE_MS && !deps.held(session)) await close(session);
+ if (deps.held(session)) { lastUse.set(session, at); return; }
+ const last = lastUse.get(session);
+ if (last !== undefined && at - last >= CLOUD_BROWSER_IDLE_MS) await close(session);
}));
+ await refreshTtl(at);
if (doors.sessions().length === 0 && sweep) { clearInterval(sweep); sweep = null; }
}
@@ -322,6 +328,8 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
/** The engine's address for a session running in the sandbox, or null. */
active: (session: string): string | null => doors.url(session),
attached: (session: string): boolean => doors.url(session) !== null,
+ /** A bot's call (or a person's action) in the session's browser: real use, which keeps it open and the sandbox awake. */
+ touch: (session: string): void => { if (lastUse.has(session)) lastUse.set(session, now()); },
/** A browser is open or opening in the sandbox: its idle path must not stop it. */
busy: (owner: string): boolean => owner === BROWSER_SANDBOX_OWNER && bots().size > 0,
close,
@@ -353,6 +361,7 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
for (const companion of companions.values()) companion.close();
companions.clear();
doors.closeAll();
+ lastUse.clear();
sessions.clear();
},
};
diff --git a/server/cloud-browser/sign-ins.ts b/server/cloud-browser/sign-ins.ts
index 0f436123e7..436c00daac 100644
--- a/server/cloud-browser/sign-ins.ts
+++ b/server/cloud-browser/sign-ins.ts
@@ -122,6 +122,23 @@ 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)));
+ 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;
+}
+
/** 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/host/browser.ts b/server/host/browser.ts
index d5b648f5e6..938c3a77f2 100644
--- a/server/host/browser.ts
+++ b/server/host/browser.ts
@@ -256,6 +256,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {
annotate: (spec, result) => passkeyAnnotation(chromeEngine.onPane(spec) ? "pane" : CLOUD_HOME ? "cloud" : DESKTOP_MANAGED ? "desktop" : "server")(spec, result),
// agent-browser's own error names only the CDP connection; the door knows what went wrong on the way.
afterCall: (session, spec, answer) => {
+ cloudBrowser?.touch(session);
const result = withSandboxNotes(session, withCeilingNote(session, answer));
const failed = result as { isError?: unknown; content?: unknown };
const found = failed?.isError === true && viaDoor(session, spec) ? doors?.problem(session) : null;
@@ -290,7 +291,8 @@ export function createBrowserHost(deps: BrowserHostDeps) {
if (spec) await closeBrowser(session, spec);
await agentBrowserRuntime.close(session);
},
- held: (session) => !turnResources.free(`browser:${session}`),
+ // Real use only: a turn holding the browser, a call running in it, or a person watching or driving it.
+ held: (session) => !turnResources.free(`browser:${session}`) || agentBrowserRuntime.working(session) || agentBrowserRuntime.spare(session) === null,
folder: (botId) => deps.cloudBrowser?.folder?.(botId) ?? null,
// The home's saved sign-ins: agent-browser's encrypted restore file, under this server's key only.
signIns: {