Skip to content

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

fix(browser): retain downloads while a turn holds the browser

Sebastian B520234ce3ebf
diff --git a/server/browser/engines.ts b/server/browser/engines.ts
index 70ff25615e..0fa72394f2 100644
--- a/server/browser/engines.ts
+++ b/server/browser/engines.ts
@@ -47,6 +47,7 @@ export interface ChromeEngineOptions {
platform?: NodeJS.Platform;
egressPort(key: string): Promise<number>;
idleMs(): number;
+ held?(session: string): boolean;
egressNotice(key: string): string | null;
log?: (line: string) => void;
}
@@ -96,6 +97,7 @@ export class ChromeEngine {
backend: () => backend,
maxRunning,
idleMs: options.idleMs,
+ held: options.held,
egressNotice: options.egressNotice,
...(options.log ? { log: options.log } : {}),
});
diff --git a/server/browser/service-downloads.test.ts b/server/browser/service-downloads.test.ts
index 25f67af1dd..5f95a3f155 100644
--- a/server/browser/service-downloads.test.ts
+++ b/server/browser/service-downloads.test.ts
@@ -1,22 +1,26 @@
-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, writeFileSync } from "node:fs";
+import { spawn } from "node:child_process";
+import { once } from "node:events";
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
-import { removeTempDir } from "../testing/cleanup.ts";
+import { removeTempDir, waitForExit } from "../testing/cleanup.ts";
+import { TurnResources } from "../turn-resources.ts";
import type { Backend } from "./backends.ts";
import { CdpBrowser } from "./cdp/browser.ts";
-import { BrowserService } from "./service.ts";
+import { BrowserService, type BrowserServiceOptions } from "./service.ts";
import { FakeBackend, FakeChrome } from "./testing/fake-chrome.ts";
const fixtures: Array<{ service: BrowserService; dataDir: string }> = [];
afterEach(async () => {
+ vi.useRealTimers();
for (const { service, dataDir } of fixtures.splice(0)) {
try { await service.closeAll(); } finally { await removeTempDir(dataDir); }
}
});
-function setup(key = "bot:fixture") {
+function setup(key = "bot:fixture", options: Partial<BrowserServiceOptions> = {}) {
const dataDir = mkdtempSync(join(tmpdir(), "omb-browser-downloads-"));
const backend: Backend = {
kind: "local",
@@ -28,7 +32,7 @@ function setup(key = "bot:fixture") {
return { browser, pid: null, version: "153.0.0.0", exited, close: () => browser.close() };
},
};
- const service = new BrowserService({ dataDir, backend: () => backend, maxRunning: 1, idleMs: () => 1_000 });
+ const service = new BrowserService({ dataDir, backend: () => backend, maxRunning: 1, idleMs: () => 1_000, ...options });
fixtures.push({ service, dataDir });
const target = { key, session: "bot-fixture" };
const profile = service.profile(target);
@@ -43,10 +47,82 @@ function setup(key = "bot:fixture") {
writeFileSync(join(profile.downloadDir, "partial.crdownload"), "partial");
return { run, file };
};
- return { service, target, profile, download };
+ return { service, target, profile, download, dataDir };
}
describe("browser download lifetime", () => {
+ it.each(["idle", "capacity"] as const)("%s retains a file while its owning turn still holds the browser", async (kind) => {
+ const claims = new TurnResources();
+ const owner = { threadId: "thread-fixture", generation: "generation-fixture" };
+ const { service, target, profile, download, dataDir } = setup(undefined, {
+ held: (session) => !claims.free(`browser:${session}`), capacityWaitMs: 1_000,
+ });
+ expect(claims.claim(`browser:${target.session}`, owner)).toBe(true);
+ const { file } = await download();
+ const copied = join(dataDir, "copied.txt");
+ const job = spawn(process.execPath, ["--input-type=commonjs", "-e", `
+ const fs = require('node:fs');
+ process.send({ exists: fs.existsSync(process.argv[1]) });
+ process.once('message', () => {
+ try { fs.copyFileSync(process.argv[1], process.argv[2]); process.send({ ok: true }); }
+ catch (error) { process.send({ ok: false, code: error.code }); }
+ process.disconnect();
+ });
+ `, file.path!, copied], { stdio: ["ignore", "ignore", "inherit", "ipc"] });
+ try {
+ const [ready] = await once(job, "message");
+ expect(ready).toEqual({ exists: true });
+ profile.lastUsed = 0;
+ let refused: unknown;
+ let settledBeforeDeadline: boolean | undefined;
+ if (kind === "idle") await service.closeIdle(1);
+ else {
+ vi.useFakeTimers();
+ let settled = false;
+ const starting = service.running(service.profile({ key: "bot:other", session: "bot-other" }))
+ .then(() => null, (error: unknown) => error).finally(() => { settled = true; });
+ await vi.advanceTimersByTimeAsync(500);
+ settledBeforeDeadline = settled;
+ await vi.advanceTimersByTimeAsync(500);
+ refused = await starting;
+ vi.useRealTimers();
+ }
+ expect(claims.owns(`browser:${target.session}`, owner)).toBe(true);
+ const outcome = once(job, "message");
+ const exited = once(job, "exit");
+ job.send("copy");
+ const [result] = await outcome;
+ await exited;
+ expect(result, "running file consumer lost its source").toEqual({ ok: true });
+ expect(readFileSync(copied, "utf8")).toBe("fixture download");
+ expect(service.download(target.session, file.id)?.path).toBe(file.path);
+ expect(await service.closeUnused(target.session)).toBe(false);
+ if (kind === "capacity") {
+ expect(settledBeforeDeadline).toBe(false);
+ expect(refused).toMatchObject({ message: expect.stringContaining("Wait for another bot to finish with its browser") });
+ }
+ claims.release(owner);
+ if (kind === "idle") expect(await service.closeIdle(1)).toEqual([target.key]);
+ else await service.running(service.profile({ key: "bot:other", session: "bot-other" }));
+ expect(existsSync(file.path!)).toBe(false);
+ expect(readFileSync(copied, "utf8")).toBe("fixture download");
+ } finally {
+ await waitForExit(job, { signal: "SIGTERM" });
+ }
+ });
+
+ it.each(["close", "erase"] as const)("explicit %s removes downloads even while a turn holds the browser", async (stop) => {
+ const claims = new TurnResources();
+ const { service, target, download } = setup(undefined, { held: (session) => !claims.free(`browser:${session}`) });
+ const owner = { threadId: "thread-fixture", generation: "generation-fixture" };
+ expect(claims.claim(`browser:${target.session}`, owner)).toBe(true);
+ const { file } = await download();
+ if (stop === "close") await service.close(target.session);
+ else await service.erase(target.key);
+ expect(claims.owns(`browser:${target.session}`, owner)).toBe(true);
+ expect(existsSync(file.path!)).toBe(false);
+ });
+
it("removes completed and partial files with their index across three idle cycles", async () => {
const { service, target, profile, download } = setup();
for (let cycle = 0; cycle < 3; cycle++) {
diff --git a/server/browser/service.ts b/server/browser/service.ts
index b3e85359e2..8a21042a47 100644
--- a/server/browser/service.ts
+++ b/server/browser/service.ts
@@ -50,6 +50,8 @@ export interface BrowserServiceOptions {
/** Browsers running at once on this server. */
maxRunning: number;
idleMs(): number;
+ /** A running turn holds this session between browser calls too. */
+ held?(session: string): boolean;
scrub?: (text: string) => string;
/** What the egress gate of this profile's browser refused since it was last asked, as one line. */
egressNotice?: (key: string) => string | null;
@@ -332,7 +334,8 @@ export class BrowserService {
#unused(profile: ProfileState, idleMs: number): boolean {
return profile.run !== null && !profile.starting && !profile.stopping && profile.calls === 0
- && profile.control.owner === null && profile.control.agents === 0 && !this.#lanes.held(profile.key) && Date.now() - profile.lastUsed >= idleMs;
+ && profile.control.owner === null && profile.control.agents === 0 && !this.#lanes.held(profile.key)
+ && !this.#options.held?.(profile.session) && Date.now() - profile.lastUsed >= idleMs;
}
/** The least recently used unwatched idle browser makes room; with none, the call waits, then is told why it cannot start. */
diff --git a/server/host/browser.test.ts b/server/host/browser.test.ts
index 74832277e1..5f1d086d69 100644
--- a/server/host/browser.test.ts
+++ b/server/host/browser.test.ts
@@ -6,6 +6,8 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { BUILT_IN_BROWSER_SYSTEM_PROMPT, browserEngineStatus, clearBrowserSessionState, closeBrowserSession, runningBrowserSessionNames } from "../browser-engine.ts";
import { CHROME_BROWSER_SYSTEM_PROMPT } from "../browser/prompt.ts";
+import { LocalBackend } from "../browser/backends.ts";
+import { FakeBackend } from "../browser/testing/fake-chrome.ts";
import { TOOL_LIST } from "../browser/tools.ts";
import { browserEgress } from "../browser/egress/registry.ts";
import { REDDIT_REFUSAL } from "../browser/egress/reddit.ts";
@@ -97,6 +99,25 @@ describe("the bots' browser host and the engine memory guard", () => {
});
describe("the bots' browser host with browserEngine.engine set to chrome", () => {
+ it("keeps Chrome open between browser calls until the host's whole-turn claim is released", async () => {
+ const backend = new FakeBackend();
+ const open = vi.spyOn(LocalBackend.prototype, "open").mockImplementation((request) => backend.open(request));
+ try {
+ const resources = new TurnResources();
+ const { host } = setup("chrome", { turnResources: resources });
+ const browser = (await host.browserIntegration("scout", undefined, turn))!;
+ const result = await host.browserRuntime.agentRpc(browser.session, browser.spec, "tools/call", { name: "agent_browser_status", arguments: {} }, () => {
+ expect(resources.claim(`browser:${browser.session}`, turn)).toBe(true);
+ });
+ expect(result).not.toHaveProperty("isError", true);
+ expect(await host.browserRuntime.closeUnused(browser.session, browser.spec)).toBe(false);
+ resources.release(turn);
+ expect(await host.browserRuntime.closeUnused(browser.session, browser.spec)).toBe(true);
+ } finally {
+ open.mockRestore();
+ }
+ });
+
it("gives a bot's turn the browser MCP server over its own profile on the new engine", async () => {
const { host, minted } = setup("chrome");
const browser = await host.browserIntegration("scout", undefined, turn);
diff --git a/server/host/browser.ts b/server/host/browser.ts
index be07f041ec..6d322fd857 100644
--- a/server/host/browser.ts
+++ b/server/host/browser.ts
@@ -123,6 +123,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {
egressPort: (key) => browserEgress.open(key),
egressNotice: (key) => browserEgress.takeNotice(key),
idleMs,
+ held: (session) => !turnResources.free(`browser:${session}`),
log: (line) => console.warn(line),
});
const lendRefusal = deps.lendRefusal ?? ((): LendRefusal => "unproven");