Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Browser tab: say when Chrome's sandbox can't start in a container
Bugfixer 23b0beee28ed0
diff --git a/server/browser/chrome/host-setup.test.ts b/server/browser/chrome/host-setup.test.tsindex e09c66d962..a83fab931e 100644--- a/server/browser/chrome/host-setup.test.ts+++ b/server/browser/chrome/host-setup.test.ts@@ -4,7 +4,7 @@ import { join } from "node:path";import { afterAll, describe, expect, it } from "vitest";import { removeTempDir } from "../../testing/cleanup.ts";-import { appArmorProfile, BrowserHostError, diagnoseLaunchFailure, LIBRARIES_COMMAND, missingLibraries, SANDBOX_STEPS_URL, sandboxBlocked, sandboxDisabled, USERNS_RESTRICTION } from "./host-setup.ts";+import { appArmorProfile, BrowserHostError, diagnoseLaunchFailure, hostSetupOf, LIBRARIES_COMMAND, missingLibraries, SANDBOX_STEPS_URL, sandboxBlocked, sandboxDisabled, USERNS_RESTRICTION } from "./host-setup.ts";const folders: string[] = [];afterAll(async () => { for (const folder of folders) await removeTempDir(folder); });@@ -36,6 +36,28 @@ describe("host setup", () => {expect(sandboxDisabled({ OMB_BROWSER_SANDBOX: "0" })).toBe(true);});+ it("tells a container's operator how to run the browser without Chrome's sandbox, which cannot start there", async () => {+ const outputs = [+ // What Chrome prints as root, as in most containers (Railway, Docker's default user).+ "[1:1:1115/103658.971532:ERROR:content/browser/zygote_host/zygote_host_impl_linux.cc:101] Running as root without --no-sandbox is not supported. See https://crbug.com/638180.",+ "[0101/000000.000:FATAL:zygote_host_impl_linux.cc] No usable sandbox! ...",+ "Failed to move to new namespace: PID namespaces supported, Network namespace supported, but failed: errno = Operation not permitted",+ ];+ const inContainer = (path: string) => path === "/.dockerenv";+ for (const output of outputs) {+ const diagnosis = await diagnoseLaunchFailure({ executable: "/opt/chrome", output, platform: "darwin", exists: inContainer });+ expect(diagnosis?.kind).toBe("container");+ expect(diagnosis?.message).toBe("Chrome's sandbox can't start in this container. The operator can set OMB_BROWSER_SANDBOX=0 to run the browser without it and rely on the container's isolation, then restart OpenMausBot.");+ }+ // Root needs no container marker; a sandbox the host blocks elsewhere keeps the AppArmor steps.+ expect((await diagnoseLaunchFailure({ executable: "/opt/chrome", output: outputs[0]!, platform: "darwin", exists: () => false }))?.kind).toBe("container");+ expect((await diagnoseLaunchFailure({ executable: "/opt/chrome", output: outputs[1]!, platform: "darwin", exists: () => false }))?.kind).toBe("sandbox");+ // The diagnosis is found behind the errors that carry it to a viewer.+ const host = new BrowserHostError("container");+ expect(hostSetupOf(new Error("Chrome could not be started", { cause: new Error("launch", { cause: host }) }))).toBe(host);+ expect(hostSetupOf(new Error("Chrome could not be started"))).toBeNull();+ });+it.skipIf(process.platform === "win32")("asks the browser's own loader which libraries are missing, in the environment the browser launched with", async () => {const dir = mkdtempSync(join(tmpdir(), "omb-host-setup-test-"));folders.push(dir);diff --git a/server/browser/chrome/host-setup.ts b/server/browser/chrome/host-setup.tsindex 0af45af61e..53012ff425 100644--- a/server/browser/chrome/host-setup.ts+++ b/server/browser/chrome/host-setup.ts@@ -5,10 +5,11 @@// exact executable instead of a wildcard path.//// OMB never turns Chrome's sandbox off by itself on a host. A host that cannot-// give it one gets the manual setup steps instead, and only an operator's explicit-// OMB_BROWSER_SANDBOX=0 launches without it. The computer container image (also-// run on a VPS) is the exception: it drops capabilities, so its Chrome runs-// without its own sandbox and the container is the isolation boundary.+// give it one gets the manual setup steps instead (a container, that switch), and+// only an operator's explicit OMB_BROWSER_SANDBOX=0 launches without it. The+// computer container image (also run on a VPS) is the exception: it drops+// capabilities, so its Chrome runs without its own sandbox and the container is+// the isolation boundary.import { execFile } from "node:child_process";import { existsSync, readFileSync } from "node:fs";@@ -21,6 +22,12 @@ export const SANDBOX_STEPS_URL = "https://github.com/milind-soni/OpenMausBot/blo/** What Chrome prints before aborting when it cannot sandbox itself. */export const NO_SANDBOX_SIGNATURE = "No usable sandbox";+/** Chrome's sandbox refuses root, which most containers run as. */+const ROOT_SIGNATURE = "Running as root without --no-sandbox";+/** A sandbox with no user namespaces to move into, as in a container. */+const NAMESPACE_SIGNATURE = "Failed to move to new namespace";+/** Docker's and Podman's marks inside a container. */+const CONTAINER_MARKERS = ["/.dockerenv", "/run/.containerenv"];export function sandboxDisabled(env: Readonly<Record<string, string | undefined>>): boolean {return env.OMB_BROWSER_SANDBOX === "0";@@ -80,13 +87,17 @@ export const DEBIAN_PACKAGES: ReadonlyArray<ReadonlyArray<string>> = [["fonts-noto-cjk"],];+export type BrowserHostNeed = "sandbox" | "container" | "libraries";+export class BrowserHostError extends Error {- readonly kind: "sandbox" | "libraries";+ readonly kind: BrowserHostNeed;readonly libraries: readonly string[];- constructor(kind: "sandbox" | "libraries", libraries: readonly string[] = []) {+ constructor(kind: BrowserHostNeed, libraries: readonly string[] = []) {super(kind === "sandbox"? `This host blocks the sandbox the browser runs in (AppArmor on Ubuntu 23.10+). An administrator can allow it for one root-owned copy of Chrome, following ${SANDBOX_STEPS_URL}, then try again.`+ : kind === "container"+ ? "Chrome's sandbox can't start in this container. The operator can set OMB_BROWSER_SANDBOX=0 to run the browser without it and rely on the container's isolation, then restart OpenMausBot.": `This host is missing libraries the browser needs (${libraries.join(", ")}). Run \`${LIBRARIES_COMMAND}\` on the host to install them, then try again.`);this.name = "BrowserHostError";this.kind = kind;@@ -122,9 +133,26 @@ export async function missingLibraries(executable: string, env: NodeJS.ProcessEnreturn listed.length > 0 ? listed : [loaderError];}-/** After a launch fails, the host setup it is missing, or null when neither explains it. */-export async function diagnoseLaunchFailure(input: { executable: string; output: string; platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv }): Promise<BrowserHostError | null> {- if (input.output.includes(NO_SANDBOX_SIGNATURE)) return new BrowserHostError("sandbox");+/** The host setup a failure needs, found behind the errors that carried it, or null. */+export function hostSetupOf(error: unknown): BrowserHostError | null {+ for (let at = error, depth = 0; at instanceof Error && depth < 8; at = at.cause, depth += 1) {+ if (at instanceof BrowserHostError) return at;+ }+ return null;+}++/** After a launch fails, the host setup it is missing, or null when none explains it. */+export async function diagnoseLaunchFailure(input: {+ executable: string;+ output: string;+ platform?: NodeJS.Platform;+ env?: NodeJS.ProcessEnv;+ exists?: (path: string) => boolean;+}): Promise<BrowserHostError | null> {+ const { output, exists = existsSync } = input;+ const noSandbox = output.includes(NO_SANDBOX_SIGNATURE) || output.includes(NAMESPACE_SIGNATURE);+ if (output.includes(ROOT_SIGNATURE) || (noSandbox && CONTAINER_MARKERS.some(exists))) return new BrowserHostError("container");+ if (noSandbox) return new BrowserHostError("sandbox");if ((input.platform ?? process.platform) !== "linux") return null;const libraries = await missingLibraries(input.executable, input.env);return libraries.length ? new BrowserHostError("libraries", libraries) : null;diff --git a/server/browser/chrome/launch.ts b/server/browser/chrome/launch.tsindex dd966aba2b..544063c549 100644--- a/server/browser/chrome/launch.ts+++ b/server/browser/chrome/launch.ts@@ -4,7 +4,7 @@ import type { Readable, Writable } from "node:stream";import { spawnBotWork } from "../../oom-score.ts";import { pipeTransport, type CdpTransport } from "../cdp/transport.ts";import { chromeArgs, chromeEnv, type ChromeEnvInput, type ChromeFlagsInput } from "./flags.ts";-import { diagnoseLaunchFailure } from "./host-setup.ts";+import { diagnoseLaunchFailure, type BrowserHostError } from "./host-setup.ts";import type { ProcessRegistry } from "./processes.ts";export interface LaunchOptions extends ChromeFlagsInput, Omit<ChromeEnvInput, "host"> {@@ -45,8 +45,9 @@ export interface ChromeProcess {export class ChromeLaunchError extends Error {readonly output: string;- constructor(message: string, output: string) {- super(message);+ /** The host setup Chrome needs, when that is why it could not start, is the cause. */+ constructor(message: string, output: string, host: BrowserHostError | null = null) {+ super(message, host ? { cause: host } : undefined);this.name = "ChromeLaunchError";this.output = output;}@@ -129,7 +130,7 @@ export async function launchChrome(options: LaunchOptions): Promise<ChromeProceskillTree(child, "SIGKILL");await Promise.race([exited, new Promise((resolve) => setTimeout(resolve, 2_000))]);const diagnosis = await diagnoseLaunchFailure({ executable: options.executablePath, output, env }).catch(() => null);- throw new ChromeLaunchError(diagnosis?.message ?? (error instanceof Error ? error.message : String(error)), output);+ throw new ChromeLaunchError(diagnosis?.message ?? (error instanceof Error ? error.message : String(error)), output, diagnosis);}const wait = (ms: number) => Promise.race([exited, new Promise<null>((resolve) => setTimeout(() => resolve(null), ms))]);const stop = async (graceMs: number): Promise<ChromeExit> => {diff --git a/server/browser/chrome/launcher.test.ts b/server/browser/chrome/launcher.test.tsindex 52e51dfe7f..fb47b680b8 100644--- a/server/browser/chrome/launcher.test.ts+++ b/server/browser/chrome/launcher.test.ts@@ -6,6 +6,8 @@ import { afterAll, describe, expect, it, vi } from "vitest";import { removeTempDir } from "../../testing/cleanup.ts";import type { ChromeIdentity } from "./identity.ts";import { chromeForTestingExecutable, chromeForTestingPin, type installChromeForTesting } from "./install.ts";+import { BrowserHostError, hostSetupOf } from "./host-setup.ts";+import { ChromeLaunchError } from "./launch.ts";import { ChromeLauncher, runsLauncher } from "./launcher.ts";import { chromeHost } from "./resolve.ts";import type { IdentitySidecars } from "./sidecar.ts";@@ -216,6 +218,20 @@ describe("the Chrome launcher", () => {expect(existsSync(chrome.path)).toBe(false);});+ it("keeps what the host needs behind the error a viewer gets, when Chrome cannot start there", async () => {+ const named = mkdtempSync(join(tmpdir(), "omb-named-"));+ folders.push(named);+ writeFileSync(join(named, "chrome"), "#!/bin/sh\n", { mode: 0o755 });+ const host = new BrowserHostError("container");+ const chrome = launcher(mac({ env: { OMB_CHROME_PATH: join(named, "chrome") } }), {+ calibrate: async () => { throw new ChromeLaunchError(host.message, "Running as root without --no-sandbox is not supported.", host); },+ });+ const failure = await chrome.binary().catch((error: unknown) => error);+ expect(failure).toBeInstanceOf(Error);+ expect((failure as Error).message).toContain("OMB_BROWSER_SANDBOX=0");+ expect(hostSetupOf(failure)).toBe(host);+ });+it("keeps a working launcher when reading a newer binary fails, rather than switch browsers mid-session", async () => {const machine = mac();const calibrate = vi.fn(async () => identity("155"));diff --git a/server/browser/chrome/launcher.ts b/server/browser/chrome/launcher.tsindex 0f49f5ae5d..4d4d37d137 100644--- a/server/browser/chrome/launcher.ts+++ b/server/browser/chrome/launcher.ts@@ -22,7 +22,7 @@ type State =| { kind: "preparing" }| { kind: "downloading"; pin: ChromeForTestingPin; progress: DownloadProgress }| Ready- | { kind: "failed"; reason: string };+ | { kind: "failed"; reason: string; cause: unknown };type LaunchSpec = { command: string; env?: Record<string, string | undefined> };@@ -184,7 +184,7 @@ export class ChromeLauncher implements BrowserLaunch {this.log(`browser: ${this.describe()}`);}, (error: unknown) => {// A launcher that already works is kept as it is: switching browsers under a running session would lose its pages.- this.state = previous ? { ...previous, fingerprint: this.fingerprintOr(previous) } : { kind: "failed", reason: message(error) };+ this.state = previous ? { ...previous, fingerprint: this.fingerprintOr(previous) } : { kind: "failed", reason: message(error), cause: error };this.log(`browser: Chrome could not be prepared (${message(error)}); ${previous ? "keeping the browser already set up" : "bots keep the engine's own browser"}`);}).finally(() => { this.preparing = null; });return this.preparing;@@ -314,7 +314,7 @@ export class ChromeLauncher implements BrowserLaunch {? `Getting the browser ready (${megabytes(state.progress.received)} of ${megabytes(state.progress.total)} MB). Try again in a minute.`: "Getting the browser ready. Try again in a moment.");}- if (state.kind === "failed") throw new Error(`Chrome could not be started (${state.reason}).`);+ if (state.kind === "failed") throw new Error(`Chrome could not be started (${state.reason}).`, { cause: state.cause });if (state.kind !== "ready") throw new Error("Chrome is not ready yet. Try again in a moment.");return { path: state.chrome.path, identity: state.identity, product: state.product, source: state.chrome.source };}diff --git a/server/browser/viewers/stream-v2.ts b/server/browser/viewers/stream-v2.tsindex 510747fb7f..60e47a18ae 100644--- a/server/browser/viewers/stream-v2.ts+++ b/server/browser/viewers/stream-v2.ts@@ -11,7 +11,7 @@ import type { Socket } from "node:net";import { WebSocketServer, type RawData, type WebSocket } from "ws";-import { BrowserHostError } from "../chrome/host-setup.ts";+import { hostSetupOf } from "../chrome/host-setup.ts";import type { BrowserService, BrowserTarget } from "../service.ts";import { FRAME_CAP_LIMITS, type Viewer, type ViewerOptions, type ViewerOutput } from "./core.ts";import { requestedSize } from "./viewport.ts";@@ -307,7 +307,8 @@ export class StreamV2 {else session.attached(viewer, this.#service);} catch (error) {// The viewer knows the fix for each need: a close reason holds at most 123 bytes, too few for the steps link.- if (error instanceof BrowserHostError) session.close(STREAM_CLOSE.hostSetup, JSON.stringify({ need: error.kind }));+ const host = hostSetupOf(error);+ if (host) session.close(STREAM_CLOSE.hostSetup, JSON.stringify({ need: host.kind }));else session.close(STREAM_CLOSE.failed, "The browser could not start.");}}diff --git a/server/routes/browser-viewers.test.ts b/server/routes/browser-viewers.test.tsindex f129756446..91113864be 100644--- a/server/routes/browser-viewers.test.ts+++ b/server/routes/browser-viewers.test.ts@@ -310,6 +310,7 @@ describe("the v2 stream", () => {it.each([{ error: new BrowserHostError("sandbox"), need: "sandbox" },{ error: new BrowserHostError("libraries", ["libnss3.so"]), need: "libraries" },+ { error: new Error("Chrome could not be started.", { cause: new BrowserHostError("container") }), need: "container" },])("tells viewers what the host needs ($need), never a command that does not exist", async ({ error, need }) => {const fixture = await serve({ attach: async () => { throw error; } });const socket = new WebSocket(`ws://${fixture.origin}/api/bots/pepper/browser/stream`);diff --git a/src/components/browser/StreamSurface.test.ts b/src/components/browser/StreamSurface.test.tsindex f45269961d..e18f99fcfb 100644--- a/src/components/browser/StreamSurface.test.ts+++ b/src/components/browser/StreamSurface.test.ts@@ -315,5 +315,10 @@ describe("a host that cannot run the browser yet", () => {await act(async () => events().onHostSetup?.({ need: "libraries", command: PREVIEW_STREAM_LIBRARIES_COMMAND }));expect(host.querySelector("code")?.textContent).toBe(PREVIEW_STREAM_LIBRARIES_COMMAND);expect(host.querySelector("a")).toBeNull();+ await act(async () => button("Try again").click());+ await act(async () => events().onHostSetup?.({ need: "container", command: "OMB_BROWSER_SANDBOX=0" }));+ expect(host.querySelector("[role=alert]")?.textContent).toBe("Chrome's sandbox can't start in this server's container. Its operator can set this to run the browser without it and rely on the container's isolation, then restart OpenMausBot:");+ expect(host.querySelector("code")?.textContent).toBe("OMB_BROWSER_SANDBOX=0");+ expect(host.querySelector("a")).toBeNull();});});diff --git a/src/components/browser/StreamSurface.tsx b/src/components/browser/StreamSurface.tsxindex 6824573939..a6049bbea8 100644--- a/src/components/browser/StreamSurface.tsx+++ b/src/components/browser/StreamSurface.tsx@@ -766,7 +766,7 @@ export function StreamSurface(props: {{hostSetup ? (<div className="absolute inset-0 z-30 flex flex-col items-center justify-center gap-3 bg-card p-4 text-center"><p role="alert" className="max-w-sm text-[13px] text-ink-secondary">{previewStreamHostSetupMessage(hostSetup)}</p>- {hostSetup.need === "libraries" ? (+ {hostSetup.need !== "sandbox" ? (<code className="max-w-md select-all break-all rounded-lg bg-inset px-3 py-2 text-left text-[12px] text-ink">{hostSetup.command}</code>) : (<a href={PREVIEW_STREAM_SANDBOX_STEPS_URL} target="_blank" rel="noopener noreferrer" className="text-[12px] text-ink underline">Browser sandbox setup steps</a>diff --git a/src/lib/browser-stream-client.test.ts b/src/lib/browser-stream-client.test.tsindex a2d6fef009..16f8f6d435 100644--- a/src/lib/browser-stream-client.test.ts+++ b/src/lib/browser-stream-client.test.ts@@ -211,6 +211,9 @@ describe("preview stream downloads, uploads and messages", () => {FakeSocket.current.closeWith(4503, JSON.stringify({ need: "sandbox", command: "sudo openmausbot browser setup" }));expect(onHostSetup).toHaveBeenLastCalledWith({ need: "sandbox" });createPreviewStreamClient(target, events({ onHostSetup }));+ FakeSocket.current.closeWith(4503, JSON.stringify({ need: "container" }));+ expect(onHostSetup).toHaveBeenLastCalledWith({ need: "container", command: "OMB_BROWSER_SANDBOX=0" });+ createPreviewStreamClient(target, events({ onHostSetup }));FakeSocket.current.closeWith(4503, "not json");expect(onHostSetup).toHaveBeenLastCalledWith({ need: "sandbox" });createPreviewStreamClient(target, events({ onUnauthorized }));diff --git a/src/lib/browser-stream-client.ts b/src/lib/browser-stream-client.tsindex 281be6e304..3a5deb63d4 100644--- a/src/lib/browser-stream-client.ts+++ b/src/lib/browser-stream-client.ts@@ -9,13 +9,15 @@ import { t } from "./i18n";export const PREVIEW_STREAM_HOST_SETUP_CLOSE_CODE = 4503;export const PREVIEW_STREAM_TAB_GONE_CODE = 4404;-/** A sandbox has no command to run, only steps for an administrator; missing libraries have one. */+/** A sandbox has no command to run, only steps for an administrator; missing libraries have one, a container a setting. */export type PreviewStreamHostSetup =| { readonly need: "sandbox" }- | { readonly need: "libraries"; readonly command: string };+ | { readonly need: "libraries" | "container"; readonly command: string };/** The server's LIBRARIES_COMMAND and SANDBOX_STEPS_URL: a close reason is too short to carry the link. */export const PREVIEW_STREAM_LIBRARIES_COMMAND = "sudo openmausbot browser install --with-deps";+/** What a container's operator sets to run its browser without Chrome's own sandbox. */+export const PREVIEW_STREAM_SANDBOX_OFF = "OMB_BROWSER_SANDBOX=0";export const PREVIEW_STREAM_SANDBOX_STEPS_URL ="https://github.com/milind-soni/OpenMausBot/blob/main/docs/deploy-vps.md#ubuntu-2404-browser-sandbox";@@ -546,13 +548,17 @@ export function createPreviewFramePainter(const decodeHostSetup = (reason: string): PreviewStreamHostSetup => {try {// An older server's command for either need was `openmausbot browser setup`, which never existed.- if ((JSON.parse(reason) as { need?: unknown }).need === "libraries") return { need: "libraries", command: PREVIEW_STREAM_LIBRARIES_COMMAND };+ const need = (JSON.parse(reason) as { need?: unknown }).need;+ if (need === "libraries") return { need, command: PREVIEW_STREAM_LIBRARIES_COMMAND };+ if (need === "container") return { need, command: PREVIEW_STREAM_SANDBOX_OFF };} catch {}return { need: "sandbox" };};-/** What a viewer tells the person; beside it, the libraries `command` ready to copy or a link to the sandbox steps. */+/** What a viewer tells the person; beside it, the `command` ready to copy or a link to the sandbox steps. */export const previewStreamHostSetupMessage = (setup: PreviewStreamHostSetup) =>setup.need === "sandbox"? "This server's host blocks the sandbox its browser runs in. An administrator can allow it for one copy of Chrome with these steps, then try again:"+ : setup.need === "container"+ ? "Chrome's sandbox can't start in this server's container. Its operator can set this to run the browser without it and rely on the container's isolation, then restart OpenMausBot:": "This server's host is missing libraries its browser needs. Run this once on the host, then try again:";