Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Browser desktop view: the minute sweep keeps a display's Chrome, a crash ends the hold, no flag bar (#6937)
Milind Soni5326d2bac87c
diff --git a/server/browser/chrome/processes.test.ts b/server/browser/chrome/processes.test.tsindex 27558e4523..f576ee48eb 100644--- a/server/browser/chrome/processes.test.ts+++ b/server/browser/chrome/processes.test.ts@@ -48,6 +48,29 @@ describe("the process sweep", () => {expect(strays({ processes, registered, root, alive }).map((listed) => listed.pid)).toEqual([11, 12, 16]);});+ it("leaves a wrapped launch's Chrome to the server that registered its wrapper, and sweeps it once that server is gone", () => {+ // A Chrome on a private display starts under bubblewrap: the launch registers bwrap's pid, whose argv carries+ // Chrome's own, and Chrome is bwrap's child.+ const root = "/data/browser", dir = "/data/browser/profiles/a";+ const chromeArgv = ["/opt/chrome/chrome", "--remote-debugging-pipe", `--user-data-dir=${dir}`];+ const wrapperArgv = ["/usr/bin/bwrap", "--dev-bind", "/", "/", "--die-with-parent", "--", ...chromeArgv];+ const tree = (wrapper: number): ListedProcess[] => [+ { pid: wrapper, ppid: 23, startTime: "t", args: wrapperArgv.join(" "), argv: wrapperArgv },+ { pid: wrapper + 1, ppid: wrapper, startTime: "t", args: chromeArgv.join(" "), argv: chromeArgv },+ { pid: wrapper + 2, ppid: wrapper + 1, startTime: "t", args: `${chromeArgv.join(" ")} --type=zygote`, argv: [...chromeArgv, "--type=zygote"] },+ ];+ const registered = (wrapper: number, ownerPid: number) => ({ pid: wrapper, startTime: null, userDataDir: dir, ownerPid, launchedAt: "" });+ const alive = (pid: number) => pid === 500;+ expect(strays({ processes: tree(235), registered: [registered(235, 500)], root, alive })).toEqual([]);+ // The server that launched it is gone: its wrapper and its Chrome are both left behind.+ expect(strays({ processes: tree(235), registered: [registered(235, 501)], root, alive }).map((listed) => listed.pid)).toEqual([235, 236]);+ // Nobody registered it at all.+ expect(strays({ processes: tree(235), registered: [], root, alive }).map((listed) => listed.pid)).toEqual([235, 236]);+ // A live server's wrapper covers only its own Chrome: a Chrome under it on another profile is still a stray.+ const other = tree(300).map((listed) => listed.pid === 301 ? { ...listed, args: listed.args.replace(dir, "/data/browser/profiles/b"), argv: listed.argv!.map((arg) => arg.replace(dir, "/data/browser/profiles/b")) } : listed);+ expect(strays({ processes: other, registered: [registered(300, 500)], root, alive }).map((listed) => listed.pid)).toEqual([301]);+ });+it("clears a stale lock, deletes unused temporary profiles and forgets processes that are gone", async () => {const root = scratch();const busy = join(root, "profiles", "busy");diff --git a/server/browser/chrome/processes.ts b/server/browser/chrome/processes.tsindex 0c117ce434..386076d1de 100644--- a/server/browser/chrome/processes.ts+++ b/server/browser/chrome/processes.ts@@ -157,21 +157,37 @@ export function processAlive(pid: number): boolean {}}-/** Browsers on OMB's profiles that no live server registered: left behind by a crash or a force-quit. */+/** How far above a Chrome its registered launch may be: a wrapper (bubblewrap) and its own monitor process. */+const WRAPPER_DEPTH = 3;++/**+ * Browsers on OMB's profiles that no live server registered: left behind by a crash or a force-quit. A launch wrapped in+ * another program (a Chrome on a private display starts under bubblewrap) registers the wrapper's pid, so a Chrome under+ * a live registered launch of the same profile is that launch's, not a stray.+ */export function strays({ processes, registered, root, alive = processAlive }: {processes: readonly ListedProcess[];registered: readonly RegisteredProcess[];root: string;alive?: (pid: number) => boolean;}): ListedProcess[] {+ const byPid = new Map(processes.map((listed) => [listed.pid, listed]));+ const launchOf = (listed: ListedProcess): RegisteredProcess | null => {+ const entry = registered.find((candidate) => candidate.pid === listed.pid);+ if (!entry) return null;+ if (entry.startTime !== null && listed.startTime !== null && entry.startTime !== listed.startTime) return null;+ return alive(entry.ownerPid) ? entry : null;+ };return processes.filter((listed) => {if (!isBrowserProcess(listed)) return false;const dir = userDataDirOf(listed);if (!dir || !inside(root, dir)) return false;- const entry = registered.find((candidate) => candidate.pid === listed.pid);- if (!entry) return true;- if (entry.startTime !== null && listed.startTime !== null && entry.startTime !== listed.startTime) return true;- return !alive(entry.ownerPid);+ let at: ListedProcess | undefined = listed;+ for (let depth = 0; at && depth <= WRAPPER_DEPTH; depth++, at = at.ppid === at.pid ? undefined : byPid.get(at.ppid)) {+ const launch = launchOf(at);+ if (launch && resolve(launch.userDataDir) === resolve(dir)) return false;+ }+ return true;});}diff --git a/server/browser/desktop/desktop.e2e.test.ts b/server/browser/desktop/desktop.e2e.test.tsindex ce84a0e22c..4272bc655f 100644--- a/server/browser/desktop/desktop.e2e.test.ts+++ b/server/browser/desktop/desktop.e2e.test.ts@@ -2,6 +2,7 @@// route sees the window, its clicks and keys reach the page only while the person holds the browser, and the bot's own// clicks and typing still work on the same page once it is handed back. Runs where OMB_CDP_CHROME (or OMB_CDP_E2E=1) names// a Chrome and Xvnc is installed; skipped elsewhere. OMB_DESKTOP_MEASURE=1 also prints memory and CPU against headless.+import { spawnSync } from "node:child_process";import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";import { createServer, type Server } from "node:http";import { connect, type AddressInfo, type Socket } from "node:net";@@ -13,6 +14,8 @@ import { WebSocket } from "ws";import { hostTimeout } from "../../testing/host-timeout.ts";import { FixtureServer } from "../cdp/testing/fixtures.ts";import { CHROME } from "../cdp/testing/real-chrome.ts";+import { listProcesses, isBrowserProcess, sweep, userDataDirOf } from "../chrome/processes.ts";+import { browserRoot, profileDir } from "../chrome/profile.ts";import { BROWSER_CONTROL_REFUSAL } from "../control.ts";import type { BrowserTarget } from "../service.ts";import { startService, until, type RealService } from "../testing/real-service.ts";@@ -218,6 +221,20 @@ async function shownState(profile: { run: { browser: { connection: { root: { senreturn JSON.stringify({ targets, page });}+/** The browser processes (no renderers or helpers) on one profile: a display's launch is bubblewrap with Chrome under+ * it, both carrying the profile. */+async function browsersOn(dataDir: string, key: string): Promise<number[]> {+ const dir = profileDir(dataDir, key);+ return ((await listProcesses()) ?? []).filter((listed) => isBrowserProcess(listed) && userDataDirOf(listed) === dir).map((listed) => listed.pid).sort((a, b) => a - b);+}++/** A pid nothing runs as any more. */+function deadPid(): number {+ const pid = spawnSync("true").pid;+ if (!pid) throw new Error("could not start true");+ return pid;+}+const xvncPid = (socket: string) => readdirSync("/proc").filter((entry) => /^\d+$/.test(entry)).map(Number).find((pid) => {try { return readFileSync(`/proc/${pid}/cmdline`, "utf8").includes(socket); } catch { return false; }});@@ -250,6 +267,7 @@ suite("a bot's browser on a private display", () => {real = await startService({display: (key) => displays.acquire(key, DESKTOP_SIZE, key === filesTarget.key ? [workspace] : []),displayFailed: (reason) => { displayFailures.push(reason); },+ registry: true,});views = new DesktopViews({ desktop: (asked) => real.service.desktop(asked) });server = createServer();@@ -464,6 +482,66 @@ suite("a bot's browser on a private display", () => {}}, hostTimeout(180_000));+ it("keeps its Chrome through the engine's minute sweep while a person watches and holds it", async () => {+ expect((await real.call(target, "agent_browser_open", { url: page })).isError).toBeUndefined();+ startedOnDisplay();+ const profile = real.service.profiles().find((candidate) => candidate.key === target.key)!;+ const launched = await browsersOn(real.dataDir, target.key);+ // bubblewrap, which the launch registered, and the Chrome it started.+ expect(launched).toHaveLength(2);+ expect(launched).toContain(profile.run!.opened.pid);+ const desk = await RfbClient.connect(url());+ await desk.picture();+ await profile.control.take(person);+ for (let tick = 1; tick <= 3; tick++) {+ const report = await sweep({ root: browserRoot(real.dataDir), registry: real.registry! });+ expect(report.killed, `sweep ${tick}`).toEqual([]);+ }+ expect(await browsersOn(real.dataDir, target.key)).toEqual(launched);+ expect(profile.control.owner).toBe(person);+ const button = await onScreen(200, 140);+ const clicks = Number(await read<string | undefined>("document.body.dataset.clicks") ?? 0);+ desk.click(button.x, button.y);+ expect(await until(() => read<string | undefined>("document.body.dataset.clicks"), (value) => value === String(clicks + 1))).toBe(String(clicks + 1));+ desk.close();+ }, hostTimeout(120_000));++ it("ends the person's hold when its Chrome is swept after its server is gone, and leaves nothing of it running", async () => {+ expect((await real.call(target, "agent_browser_open", { url: page })).isError).toBeUndefined();+ startedOnDisplay();+ const profile = real.service.profiles().find((candidate) => candidate.key === target.key)!;+ const shown = profile.run!.opened.display!;+ const launched = await browsersOn(real.dataDir, target.key);+ await profile.control.take(person);+ // The registry now says the server that launched it is gone, as after a crash of the server.+ const gone = deadPid();+ for (const entry of real.registry!.list()) if (entry.userDataDir === profileDir(real.dataDir, target.key)) real.registry!.add({ ...entry, ownerPid: gone });+ const report = await sweep({ root: browserRoot(real.dataDir), registry: real.registry! });+ expect([...report.killed].sort((a, b) => a - b)).toEqual(launched);+ await until(() => profile.run, (run) => run === null);+ expect(profile.control.owner).toBeNull();+ await Promise.race([shown.exited, new Promise((_, reject) => setTimeout(() => reject(new Error("its display is still running")), 10_000))]);+ expect(xvncPid(shown.socket)).toBeUndefined();+ expect(await browsersOn(real.dataDir, target.key)).toEqual([]);+ // The bot's next call starts it again, and nothing refuses it for a hold of the browser that died.+ const again = await real.call(target, "agent_browser_status");+ expect(again.isError).toBeUndefined();+ expect(real.text(again)).toContain("stopped unexpectedly");+ }, hostTimeout(120_000));++ it("shows the page with no bar over it, and keeps navigator.webdriver false", async () => {+ // A fresh launch: Chrome's startup bars go on its first tab.+ const bars: BrowserTarget = { session: "bars", key: "bot:bars" };+ expect((await real.call(bars, "agent_browser_open", { url: page })).isError).toBeUndefined();+ startedOnDisplay();+ const first = await real.peek<number>(bars, "outerHeight - innerHeight");+ expect(await real.peek<boolean>(bars, "navigator.webdriver")).toBe(false);+ expect((await real.call(bars, "agent_browser_tabs", { action: "new", url: page })).isError).toBeUndefined();+ // A later tab never has them: the window's own top is all there is above the page.+ expect(await real.peek<number>(bars, "outerHeight - innerHeight")).toBe(first);+ await real.service.close(bars.session);+ }, hostTimeout(120_000));+it.runIf(process.env.OMB_DESKTOP_MEASURE === "1")("spends this much CPU on a picture stream under the desktop view, and none without one", async () => {const animated = fx.page("/spin", `<!doctype html><style>@keyframes spin{to{transform:rotate(360deg)}}#s{width:300px;height:300px;background:#36c;animation:spin 1s linear infinite}</style><div id="s"></div>`);expect((await real.call(target, "agent_browser_open", { url: animated })).isError).toBeUndefined();diff --git a/server/browser/desktop/policy.test.ts b/server/browser/desktop/policy.test.tsindex f2690b8c6d..7e93e9f24b 100644--- a/server/browser/desktop/policy.test.ts+++ b/server/browser/desktop/policy.test.ts@@ -19,6 +19,7 @@ describe("the lock-down policy of a Chrome on a private display", () => {expect(policy).not.toHaveProperty("DeveloperToolsAvailability");expect(policy.PrivacySandboxPromptEnabled).toBe(false);expect(policy.PromotionsEnabled).toBe(false);+ expect(policy.CommandLineFlagSecurityWarningsEnabled).toBe(false);});it("lets through only the folders named, and nothing beside them", () => {diff --git a/server/browser/desktop/policy.ts b/server/browser/desktop/policy.tsindex bc510cb04b..d905764b48 100644--- a/server/browser/desktop/policy.ts+++ b/server/browser/desktop/policy.ts@@ -30,6 +30,9 @@ export function desktopPolicy(fileRoots: readonly string[] = []): Record<string,// page a person sees on the display, as no headless Chrome shows them.PrivacySandboxPromptEnabled: false,PromotionsEnabled: false,+ // The bar over the page that calls --disable-blink-features=AutomationControlled unsupported: without that flag a+ // windowed Chrome on a DevTools pipe shows its pages navigator.webdriver === true.+ CommandLineFlagSecurityWarningsEnabled: false,};}diff --git a/server/browser/service.test.ts b/server/browser/service.test.tsindex 9f46d06010..bd0fd8dbb9 100644--- a/server/browser/service.test.ts+++ b/server/browser/service.test.ts@@ -240,6 +240,20 @@ describe("a person and the bot sharing one browser", () => {expect((await call("agent_browser_tabs", { action: "switch", tab: "t2" })).isError).toBeUndefined();});+ it("ends the person's hold when the browser they hold dies, so the bot is not left paused for a browser that is gone", async () => {+ const { service, call, text, target, backend } = setup();+ await call("agent_browser_open", { url: "https://example.com/form" });+ const viewer = await service.attachViewer(target, { owner: "local-owner", canOperate: true, maxWidth: 2560, maxHeight: 1600 }, () => {});+ await viewer.input({ type: "takeControl" });+ expect(service.heldBy("bot-a")).toBe("local-owner");+ backend.chrome.exit("killed");+ await sleep(50);+ expect(service.heldBy("bot-a")).toBeNull();+ const again = await call("agent_browser_status");+ expect(again.isError).toBeUndefined();+ expect(text(again)).toContain("stopped unexpectedly");+ });+it("waits for the bot's running action before the person's control starts, and turns that action's answer into the refusal", async () => {const { service, call, target, backend } = setup({ takeoverMs: 2_000 });await call("agent_browser_open", { url: "https://example.com/form" });diff --git a/server/browser/service.ts b/server/browser/service.tsindex 76de8fcb01..7dbe04ef8d 100644--- a/server/browser/service.ts+++ b/server/browser/service.ts@@ -297,6 +297,9 @@ export class BrowserService {}profile.reopened = { kind: "crash", pages: [] };profile.control.settle();+ // A hold of a browser that is gone ends with it: the bot is not left paused for nobody, and the person's views show+ // the browser free when it starts again.+ if (profile.control.owner !== null) void profile.hub.handBack();this.#options.log?.(`browser ${profile.key}: Chrome exited unexpectedly; the next call starts it again`);profile.hub.stopped("crashed");}diff --git a/server/browser/testing/real-service.ts b/server/browser/testing/real-service.tsindex aa0dc714c7..a9efd74d42 100644--- a/server/browser/testing/real-service.ts+++ b/server/browser/testing/real-service.ts@@ -6,6 +6,8 @@ import { join } from "node:path";import { removeTempDir } from "../../testing/cleanup.ts";import { LocalBackend, type LocalBackendOptions } from "../backends.ts";import { calibrateIdentity, chromeFingerprint, type CalibratedIdentity } from "../chrome/calibrate.ts";+import { ProcessRegistry } from "../chrome/processes.ts";+import { browserRoot } from "../chrome/profile.ts";import type { ScreenSpec } from "../chrome/flags.ts";import { sandboxDisabled } from "../chrome/host-setup.ts";import { CHROME, FIRST_LAUNCH_MS, HOST, testRoot } from "../cdp/testing/real-chrome.ts";@@ -29,6 +31,8 @@ function identityOf(executablePath: string, sandbox: boolean): Promise<Calibrateexport interface RealService {service: BrowserService;dataDir: string;+ /** Every Chrome this service launched, as the engine's own registry records them (`registry: true`). */+ registry: ProcessRegistry | null;call(target: BrowserTarget, name: string, args?: Record<string, unknown>): Promise<ToolResult>;/** The answer's text, pictures as [image]. */text(result: ToolResult): string;@@ -39,12 +43,13 @@ export interface RealService {close(): Promise<void>;}-export async function startService({ screen, egressPort, display, displayFailed, ...options }: Partial<BrowserServiceOptions> & { screen?: ScreenSpec; egressPort?: (key: string) => Promise<number | null>; display?: LocalBackendOptions["display"]; displayFailed?: LocalBackendOptions["displayFailed"] } = {}): Promise<RealService> {+export async function startService({ screen, egressPort, display, displayFailed, registry: registered = false, ...options }: Partial<BrowserServiceOptions> & { screen?: ScreenSpec; egressPort?: (key: string) => Promise<number | null>; display?: LocalBackendOptions["display"]; displayFailed?: LocalBackendOptions["displayFailed"]; registry?: boolean } = {}): Promise<RealService> {if (!CHROME) throw new Error("No Chrome to test with.");const executablePath = CHROME;const sandbox = !sandboxDisabled(process.env);await identityOf(executablePath, sandbox);const dataDir = mkdtempSync(join(testRoot(), "omb-browser-service-"));+ const registry = registered ? new ProcessRegistry(browserRoot(dataDir)) : null;const backend = new LocalBackend({dataDir,host: HOST,@@ -56,6 +61,7 @@ export async function startService({ screen, egressPort, display, displayFailed,handshakeTimeoutMs: FIRST_LAUNCH_MS,...(display ? { display } : {}),...(displayFailed ? { displayFailed } : {}),+ ...(registry ? { registry } : {}),});const service = new BrowserService({ dataDir, backend: () => backend, maxRunning: 4, idleMs: () => 600_000, ...options });const call = (target: BrowserTarget, name: string, args: Record<string, unknown> = {}) =>@@ -64,6 +70,7 @@ export async function startService({ screen, egressPort, display, displayFailed,return {service,dataDir,+ registry,call,text,async read<T>(target: BrowserTarget, expression: string): Promise<T> {