Skip to content

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

browser: a Chrome that cannot start on its display starts headless, and the desktop suite reports why

milind-sonifcfb4edda009
diff --git a/server/browser/backends.test.ts b/server/browser/backends.test.ts
index 14d74479bf..9002ce26d7 100644
--- a/server/browser/backends.test.ts
+++ b/server/browser/backends.test.ts
@@ -5,7 +5,7 @@ import { afterAll, describe, expect, it } from "vitest";
import { removeTempDir } from "../testing/cleanup.ts";
import { LocalBackend } from "./backends.ts";
-import type { ChromeProcess, LaunchOptions } from "./chrome/launch.ts";
+import { ChromeLaunchError, type ChromeProcess, type LaunchOptions } from "./chrome/launch.ts";
import { ProcessRegistry } from "./chrome/processes.ts";
import { browserRoot, profileDir } from "./chrome/profile.ts";
import type { DesktopDisplay } from "./desktop/displays.ts";
@@ -93,11 +93,12 @@ describe("a local browser's profile folder", () => {
});
describe("a local browser on a private display", () => {
- function onDisplay(fail = false) {
+ function onDisplay(failOnDisplay = false) {
const dataDir = mkdtempSync(join(tmpdir(), "omb-backends-test-"));
folders.push(dataDir);
const launches: LaunchOptions[] = [];
let released = 0;
+ const failures: string[] = [];
const display: DesktopDisplay = {
number: 21, socket: "/d21/rfb", env: { DISPLAY: ":21", XAUTHORITY: "/d21/Xauthority" }, size: { width: 1280, height: 800 }, wrap: { command: "/usr/bin/bwrap", args: ["--dev-bind", "/", "/", "--"] },
exited: new Promise(() => {}), release: async () => { released++; },
@@ -110,9 +111,10 @@ describe("a local browser on a private display", () => {
screen: async () => ({ width: 1920, height: 1080, deviceScaleFactor: 1 }),
egressPort: async () => null,
display: async () => display,
+ displayFailed: (reason) => { failures.push(reason); },
launch: async (options) => {
launches.push(options);
- if (fail) throw new Error("Chrome did not start");
+ if (failOnDisplay && options.mode === "window") throw new ChromeLaunchError("Chrome did not start", "[FATAL:zygote_host_impl_linux.cc] No usable sandbox!\n");
const chrome = new FakeChrome();
const exited = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((resolve) => chrome.onClose(() => resolve({ code: 0, signal: null })));
return {
@@ -122,7 +124,7 @@ describe("a local browser on a private display", () => {
},
});
const open = () => local.open({ key: "bot:a", mode: "headless", fresh: false, viewport: { width: 1000, height: 700 }, downloadDir: join(dataDir, "downloads") });
- return { open, launches, released: () => released, display };
+ return { open, launches, released: () => released, display, failures };
}
it("opens a window that fills the display, with nothing a headless browser pretends", async () => {
@@ -143,9 +145,16 @@ describe("a local browser on a private display", () => {
expect(released()).toBeGreaterThanOrEqual(1);
});
- it("gives the display back when Chrome does not start", async () => {
- const { open, released } = onDisplay(true);
- await expect(open()).rejects.toThrow("Chrome did not start");
+ it("gives the display back when Chrome does not start on it, says why, and starts the browser headless instead", async () => {
+ const { open, released, launches, failures } = onDisplay(true);
+ const opened = await open();
expect(released()).toBe(1);
+ expect(launches.map((launch) => launch.mode)).toEqual(["window", "headless"]);
+ expect(launches[1]!.wrap ?? null).toBeNull();
+ expect(opened.display ?? null).toBeNull();
+ expect(failures).toHaveLength(1);
+ expect(failures[0]).toContain("Chrome did not start");
+ expect(failures[0]).toContain("No usable sandbox!");
+ await opened.close();
});
});
diff --git a/server/browser/backends.ts b/server/browser/backends.ts
index 87c1939d4f..96d1bfd185 100644
--- a/server/browser/backends.ts
+++ b/server/browser/backends.ts
@@ -5,7 +5,7 @@ import { loopbackPage, openOwnPage } from "./chrome/calibrate.ts";
import type { Identity } from "./cdp/identity.ts";
import { webSocketTransport } from "./cdp/transport.ts";
import { fitPage, pageLimit, type BrowserMode, type HostKind, type ScreenSpec } from "./chrome/flags.ts";
-import { launchChrome, type ChromeProcess, type LaunchOptions } from "./chrome/launch.ts";
+import { ChromeLaunchError, launchChrome, type ChromeProcess, type LaunchOptions } from "./chrome/launch.ts";
import { clearSingleton, staleSingletonLock, type ProcessRegistry } from "./chrome/processes.ts";
import { languageList } from "./chrome/wrapper.ts";
import type { DesktopDisplay } from "./desktop/displays.ts";
@@ -86,6 +86,19 @@ export interface LocalBackendOptions {
launch?: (options: LaunchOptions) => Promise<ChromeProcess>;
/** A private display for this profile's window, or null to run it headless. */
display?: (key: string) => Promise<DesktopDisplay | null>;
+ /** Chrome could not start on its display, so it was started headless instead; `reason` is what Chrome said. */
+ displayFailed?: (reason: string) => void;
+}
+
+/** Chrome did not start on its private display. */
+class DisplayLaunchError extends Error {
+ readonly reason: string;
+ constructor(error: unknown) {
+ const output = error instanceof ChromeLaunchError ? error.output.trim().split("\n").slice(-20).join("\n") : "";
+ const reason = `${error instanceof Error ? error.message : String(error)}${output ? `\n${output}` : ""}`;
+ super(reason);
+ this.reason = reason;
+ }
}
const LOCAL_CAPS: BackendCaps = { persistentProfile: true, window: true, egressGate: true, identityOverride: true, ownsAllTabs: true, downloads: "local", uploads: "path", botPasskeys: true };
@@ -105,13 +118,21 @@ export class LocalBackend implements Backend {
const platform = options.platform ?? process.platform;
const release = options.registry?.reserve(profileDir(options.dataDir, request.key));
try {
- return await this.#open(request, platform);
+ try {
+ return await this.#open(request, platform, true);
+ } catch (error) {
+ if (!(error instanceof DisplayLaunchError)) throw error;
+ // A host whose Chrome cannot keep its sandbox in the display's mount namespace (an AppArmor-confined bubblewrap)
+ // still gets the bot's browser: headless, shown as pictures.
+ options.displayFailed?.(error.reason);
+ return await this.#open(request, platform, false);
+ }
} finally {
release?.();
}
}
- async #open(request: OpenRequest, platform: NodeJS.Platform): Promise<OpenedBrowser> {
+ async #open(request: OpenRequest, platform: NodeJS.Platform, onDisplay: boolean): Promise<OpenedBrowser> {
const options = this.#options;
const binary = await options.binary();
const { dir, record, created } = ensureProfile(options.dataDir, request.key, { acceptLanguages: options.acceptLanguages?.() ?? "en-US,en" });
@@ -121,7 +142,7 @@ export class LocalBackend implements Backend {
if (staleSingletonLock(dir)) clearSingleton(dir);
markCleanExit(dir);
if (request.fresh) forgetOpenTabs(dir);
- const display = (await options.display?.(request.key)) ?? null;
+ const display = onDisplay ? (await options.display?.(request.key)) ?? null : null;
const mode = display ? "window" : request.mode;
const headless = mode === "headless";
const locale = options.locale?.() ?? null;
@@ -149,8 +170,9 @@ export class LocalBackend implements Backend {
...(options.handshakeTimeoutMs === undefined ? {} : { handshakeTimeoutMs: options.handshakeTimeoutMs }),
...(display ? { env: { ...process.env, ...display.env }, fillScreen: display.size, wrap: display.wrap } : {}),
}).catch(async (error: unknown) => {
- await display?.release();
- throw error;
+ if (!display) throw error;
+ await display.release();
+ throw new DisplayLaunchError(error);
});
const version = versionOf(chrome.version.product);
try {
diff --git a/server/browser/desktop/desktop.e2e.test.ts b/server/browser/desktop/desktop.e2e.test.ts
index 90e9bf2a58..6e333878b9 100644
--- a/server/browser/desktop/desktop.e2e.test.ts
+++ b/server/browser/desktop/desktop.e2e.test.ts
@@ -220,6 +220,10 @@ suite("a bot's browser on a private display", () => {
let page: string;
const target: BrowserTarget = { session: "desk", key: "bot:desk" };
const filesTarget: BrowserTarget = { session: "files", key: "bot:files" };
+ /** What Chrome said each time it could not start on its display (it then starts headless): the first failure's whole
+ * text, Chrome's own last lines included, is what a failing run reports. */
+ const displayFailures: string[] = [];
+ const startedOnDisplay = () => expect(displayFailures.join("\n\n") || "started on its display").toBe("started on its display");
let workspace: string;
const person = "alice";
@@ -231,7 +235,10 @@ suite("a bot's browser on a private display", () => {
workspace = join(root, "workspace");
mkdirSync(workspace);
writeFileSync(join(workspace, "report.html"), "<!doctype html><title>report</title><p>the bot's own report</p>");
- real = await startService({ display: (key) => displays.acquire(key, DESKTOP_SIZE, key === filesTarget.key ? [workspace] : []) });
+ real = await startService({
+ display: (key) => displays.acquire(key, DESKTOP_SIZE, key === filesTarget.key ? [workspace] : []),
+ displayFailed: (reason) => { displayFailures.push(reason); },
+ });
views = new DesktopViews({ desktop: (asked) => real.service.desktop(asked) });
server = createServer();
server.on("upgrade", (req, socket, head) => {
@@ -262,6 +269,7 @@ suite("a bot's browser on a private display", () => {
it("shows a window that fills the display, and lets only the person holding the browser drive 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)!;
expect(profile.run?.opened.display?.size).toEqual(DESKTOP_SIZE);
// With no window manager, X11 Chrome 156 keeps its window a pixel short of the size it was given.
@@ -320,6 +328,7 @@ suite("a bot's browser on a private display", () => {
it("lets the person's view size the display as the picture view sizes the page, the window follow it, and gives it back on hand-back", 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)!;
await profile.control.take(person);
const desk = await RfbClient.connect(url());
@@ -362,6 +371,7 @@ suite("a bot's browser on a private display", () => {
const refused = real.text(await real.call(filesTarget, "agent_browser_open", { url: `file://${workspace}/report.html` }));
expect(refused).toMatch(/Only http\(s\), about:blank and data: addresses open here/);
expect((await real.call(filesTarget, "agent_browser_open", { url: page })).isError).toBeUndefined();
+ startedOnDisplay();
expect(await shown(real, filesTarget, `file://${workspace}/report.html`)).toContain("the bot's own report");
expect(await shown(real, filesTarget, "file:///etc/hostname")).toMatch(/ERR_BLOCKED_BY_ADMINISTRATOR|This page is blocked/);
const headless = await startService();
@@ -377,6 +387,7 @@ suite("a bot's browser on a private display", () => {
it("keeps Chrome's own address bar and shortcuts away from files, Chrome's pages and DevTools", 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 browser = profile.run!.browser;
await profile.control.take(person);
diff --git a/server/browser/engines.ts b/server/browser/engines.ts
index 626f1e349d..3f9aad76d5 100644
--- a/server/browser/engines.ts
+++ b/server/browser/engines.ts
@@ -83,6 +83,8 @@ export class ChromeEngine {
#timer: ReturnType<typeof setInterval> | null = null;
#inUse = false;
#cleared = false;
+ /** Why Chrome could not start on a display here: every browser then stays headless until the server restarts. */
+ #displayRefused: string | null = null;
constructor(options: ChromeEngineOptions) {
this.#options = options;
@@ -116,6 +118,11 @@ export class ChromeEngine {
registry: this.#registry,
sandbox,
display: async (key) => (this.desktopView() ? this.displays.acquire(key, { width: desktopSize.width, height: desktopSize.height }) : null),
+ displayFailed: (reason) => {
+ if (this.#displayRefused !== null) return;
+ this.#displayRefused = reason;
+ options.log?.(`browser display: Chrome could not start on a private display, so browsers stay headless and show as pictures: ${reason}`);
+ },
...(options.log ? { log: options.log } : {}),
});
options.pane?.backend.fallBackTo(backend);
@@ -136,7 +143,7 @@ export class ChromeEngine {
/** A browser that starts now shows its window on a private display, which the panel shows as a remote desktop. */
desktopView(): boolean {
- return this.#options.cloudDisplay?.() === true && this.displays.available;
+ return this.#options.cloudDisplay?.() === true && this.#displayRefused === null && this.displays.available;
}
/** The spec a session gets on the new engine, remembered so its live view finds the profile. */
diff --git a/server/browser/testing/real-service.ts b/server/browser/testing/real-service.ts
index d987675a62..aa0dc714c7 100644
--- a/server/browser/testing/real-service.ts
+++ b/server/browser/testing/real-service.ts
@@ -39,7 +39,7 @@ export interface RealService {
close(): Promise<void>;
}
-export async function startService({ screen, egressPort, display, ...options }: Partial<BrowserServiceOptions> & { screen?: ScreenSpec; egressPort?: (key: string) => Promise<number | null>; display?: LocalBackendOptions["display"] } = {}): Promise<RealService> {
+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> {
if (!CHROME) throw new Error("No Chrome to test with.");
const executablePath = CHROME;
const sandbox = !sandboxDisabled(process.env);
@@ -55,6 +55,7 @@ export async function startService({ screen, egressPort, display, ...options }:
sandbox,
handshakeTimeoutMs: FIRST_LAUNCH_MS,
...(display ? { display } : {}),
+ ...(displayFailed ? { displayFailed } : {}),
});
const service = new BrowserService({ dataDir, backend: () => backend, maxRunning: 4, idleMs: () => 600_000, ...options });
const call = (target: BrowserTarget, name: string, args: Record<string, unknown> = {}) =>