Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
browser: browserEngine.cloudDisplay runs the new engine's Chrome on a private display, shown at /api/bots/:id/browser/desktop
milind-soni4dacbb98ca37
diff --git a/server/browser/backends.test.ts b/server/browser/backends.test.tsindex a0c14863a1..14d74479bf 100644--- a/server/browser/backends.test.ts+++ b/server/browser/backends.test.ts@@ -5,9 +5,10 @@ import { afterAll, describe, expect, it } from "vitest";import { removeTempDir } from "../testing/cleanup.ts";import { LocalBackend } from "./backends.ts";-import type { ChromeProcess } from "./chrome/launch.ts";+import type { ChromeProcess, 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";import { FAKE_IDENTITY, FakeChrome } from "./testing/fake-chrome.ts";const folders: string[] = [];@@ -90,3 +91,61 @@ describe("a local browser's profile folder", () => {expect(registry.reserved(dir)).toBe(false);});});++describe("a local browser on a private display", () => {+ function onDisplay(fail = false) {+ const dataDir = mkdtempSync(join(tmpdir(), "omb-backends-test-"));+ folders.push(dataDir);+ const launches: LaunchOptions[] = [];+ let released = 0;+ 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++; },+ };+ const local = new LocalBackend({+ dataDir,+ host: "container",+ platform: "linux",+ binary: async () => ({ path: "/fake/chrome", identity: { ...FAKE_IDENTITY } }),+ screen: async () => ({ width: 1920, height: 1080, deviceScaleFactor: 1 }),+ egressPort: async () => null,+ display: async () => display,+ launch: async (options) => {+ launches.push(options);+ if (fail) throw new Error("Chrome did not start");+ const chrome = new FakeChrome();+ const exited = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((resolve) => chrome.onClose(() => resolve({ code: 0, signal: null })));+ return {+ pid: 1, argv: [], transport: chrome, version: { product: "Chrome/153.0.8010.12", userAgent: "", protocolVersion: "1.3", revision: "" },+ exited, output: () => "", close: async () => { chrome.exit(); return exited; }, kill: async () => { chrome.exit(); return exited; },+ } satisfies ChromeProcess;+ },+ });+ 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 };+ }++ it("opens a window that fills the display, with nothing a headless browser pretends", async () => {+ const { open, launches, released, display } = onDisplay();+ const opened = await open();+ const launch = launches[0]!;+ expect(launch.mode).toBe("window");+ expect(launch.fillScreen).toEqual({ width: 1280, height: 800 });+ expect(launch.env?.DISPLAY).toBe(":21");+ expect(launch.env?.XAUTHORITY).toBe("/d21/Xauthority");+ expect(launch.wrap).toEqual(display.wrap);+ expect(launch.userAgent).toBeNull();+ expect(launch.screen).toBeNull();+ expect(opened.display).toBe(display);+ expect(opened.pageLimit).toBeNull();+ expect(opened.browser.viewport).toBeNull();+ await opened.close();+ 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");+ expect(released()).toBe(1);+ });+});diff --git a/server/browser/backends.ts b/server/browser/backends.tsindex e2e7927279..87c1939d4f 100644--- a/server/browser/backends.ts+++ b/server/browser/backends.ts@@ -8,6 +8,7 @@ import { fitPage, pageLimit, type BrowserMode, type HostKind, type ScreenSpec }import { 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";import { downgradeRefusal, ensureProfile, forgetOpenTabs, markCleanExit, profileDir, profileHash, recordOpenedBy, versionOf, workspaceId } from "./chrome/profile.ts";export type BackendKind = "local" | "my-chrome" | "cdp-url" | "pane";@@ -48,6 +49,8 @@ export interface OpenedBrowser {/** Where the person uses the page directly: holds the bot's input to a tab while the person has it (refs drop on* release), and says who acted last in it. */personControl?: { hold(targetId: string, held: boolean): void; owner(targetId: string): "person" | "bot" | null };+ /** The private display its window is on, which a person sees as a remote desktop; absent when it runs headless. */+ readonly display?: DesktopDisplay | null;}export interface Backend {@@ -81,6 +84,8 @@ export interface LocalBackendOptions {log?: (line: string) => void;/** Starts Chrome; tests pass a fake. */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>;}const LOCAL_CAPS: BackendCaps = { persistentProfile: true, window: true, egressGate: true, identityOverride: true, ownsAllTabs: true, downloads: "local", uploads: "path", botPasskeys: true };@@ -116,7 +121,9 @@ export class LocalBackend implements Backend {if (staleSingletonLock(dir)) clearSingleton(dir);markCleanExit(dir);if (request.fresh) forgetOpenTabs(dir);- const headless = request.mode === "headless";+ const display = (await options.display?.(request.key)) ?? null;+ const mode = display ? "window" : request.mode;+ const headless = mode === "headless";const locale = options.locale?.() ?? null;const egressPort = await options.egressPort(request.key);const screen = headless ? await options.screen() : null;@@ -125,7 +132,7 @@ export class LocalBackend implements Backend {const chrome: ChromeProcess = await (options.launch ?? launchChrome)({executablePath: binary.path,userDataDir: dir,- mode: request.mode,+ mode,host: options.host,platform,userAgent: headless ? binary.identity.userAgent : null,@@ -140,6 +147,10 @@ export class LocalBackend implements Backend {profileMarker: profileHash(workspaceId(options.dataDir), request.key),registry: options.registry ?? null,...(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;});const version = versionOf(chrome.version.product);try {@@ -147,7 +158,8 @@ export class LocalBackend implements Backend {const browserOptions: BrowserOptions = {identity: headless ? binary.identity : null,acceptLanguage: locale ? languageList(locale) : undefined,- headless,+ // A window on a private display is still one nobody sits at: file pickers and passkeys go to the panel.+ headless: headless || display !== null,downloadDir: request.downloadDir,platform,maxPages: 8,@@ -162,14 +174,17 @@ export class LocalBackend implements Backend {pageLimit: limit,pid: chrome.pid,version,- exited: chrome.exited.then(() => undefined),+ exited: chrome.exited.then(() => display?.release()),async close() {await browser.close();await chrome.close(5_000);+ await display?.release();},+ display,};} catch (error) {await chrome.kill();+ await display?.release();throw error;}}diff --git a/server/browser/chrome/flags.test.ts b/server/browser/chrome/flags.test.tsindex aa331fe36c..a9a1920fb0 100644--- a/server/browser/chrome/flags.test.ts+++ b/server/browser/chrome/flags.test.ts@@ -54,6 +54,15 @@ describe("Chrome's command line", () => {expect(chromeArgs({ userDataDir: "/p", mode: "headless", host: "desktop", viewport: { width: 1280, height: 800 } })).toContain("--window-size=1280,943");});+ it("fills a private display with a window at its corner, and only a window", () => {+ const filled = chromeArgs({ userDataDir: "/p", mode: "window", host: "container", fillScreen: { width: 1280, height: 800 }, viewport: { width: 1000, height: 700 } });+ expect(filled).toEqual(expect.arrayContaining(["--window-size=1280,800", "--window-position=0,0", "--start-maximized"]));+ expect(filled.some((flag) => flag.startsWith("--headless") || flag.startsWith("--screen-info"))).toBe(false);+ const headlessFill = chromeArgs({ userDataDir: "/p", mode: "headless", host: "container", fillScreen: { width: 1280, height: 800 } });+ expect(headlessFill).toContain("--window-size=1280,863");+ expect(headlessFill).not.toContain("--start-maximized");+ });+it("keeps a headless window within its screen, and a page that must shrink keeps its shape", () => {expect(pageLimit({ width: 1512, height: 982, deviceScaleFactor: 2 }, "darwin")).toEqual({ width: 1512, height: 839 });expect(pageLimit(SERVER_SCREEN, "linux")).toEqual({ width: 1920, height: 937 });diff --git a/server/browser/chrome/flags.ts b/server/browser/chrome/flags.tsindex e8448d196b..1ff8a4220e 100644--- a/server/browser/chrome/flags.ts+++ b/server/browser/chrome/flags.ts@@ -71,6 +71,8 @@ export interface ChromeFlagsInput {startUrl?: string | null;/** A window only: where it opens, e.g. parked off-screen. */windowPosition?: { x: number; y: number } | null;+ /** A window only: it fills this display from its top left corner, with no window manager to place it. */+ fillScreen?: { width: number; height: number } | null;}const LOCALE = /^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/;@@ -87,6 +89,11 @@ export function screenInfo(screen: ScreenSpec): string {return `{${parts.join(" ")}}`;}+function fillsScreen(input: ChromeFlagsInput): string | null {+ const screen = input.mode === "window" ? input.fillScreen : null;+ return screen ? `${Math.round(screen.width)},${Math.round(screen.height)}` : null;+}+export function chromeArgs(input: ChromeFlagsInput): string[] {const platform = input.platform ?? process.platform;const headless = input.mode === "headless";@@ -97,13 +104,14 @@ export function chromeArgs(input: ChromeFlagsInput): string[] {"--no-first-run","--no-default-browser-check","--disable-blink-features=AutomationControlled",- `--window-size=${input.viewport ? `${Math.round(input.viewport.width)},${Math.round(input.viewport.height) + HEADLESS_CHROME_HEIGHT}` : WINDOW_SIZE}`,+ `--window-size=${fillsScreen(input) ?? (input.viewport ? `${Math.round(input.viewport.width)},${Math.round(input.viewport.height) + HEADLESS_CHROME_HEIGHT}` : WINDOW_SIZE)}`,];if (headless && input.userAgent) {if (/[\r\n\0]/.test(input.userAgent)) throw new Error("The user agent holds a line break.");args.push(`--user-agent=${input.userAgent}`);}if (headless) args.push(`--screen-info=${screenInfo(input.screen ?? SERVER_SCREEN)}`);+ else if (fillsScreen(input)) args.push("--window-position=0,0", "--start-maximized", "--hide-crash-restore-bubble");else if (input.windowPosition) args.push(`--window-position=${Math.round(input.windowPosition.x)},${Math.round(input.windowPosition.y)}`);if (input.locale && LOCALE.test(input.locale)) args.push(`--lang=${input.locale}`);if (input.egressPort !== undefined && input.egressPort !== null) {diff --git a/server/browser/chrome/launch.ts b/server/browser/chrome/launch.tsindex dee704506d..262705ffbe 100644--- a/server/browser/chrome/launch.ts+++ b/server/browser/chrome/launch.ts@@ -15,6 +15,8 @@ export interface LaunchOptions extends ChromeFlagsInput, Omit<ChromeEnvInput, "h/** A first launch on a fresh machine can take half a minute (font caches, a virus scan of the binary). */handshakeTimeoutMs?: number;registry?: ProcessRegistry | null;+ /** A command Chrome starts under, its own command line following, such as a private mount namespace. */+ wrap?: { command: string; args: readonly string[] } | null;}export interface BrowserVersion {@@ -106,7 +108,8 @@ export async function launchChrome(options: LaunchOptions): Promise<ChromeProcessandboxHelper: options.sandboxHelper ?? null,profileMarker: options.profileMarker ?? null,});- const child = spawnBotWork(() => spawn(options.executablePath, argv, { stdio: ["ignore", "pipe", "pipe", "pipe", "pipe"], env, windowsHide: true }));+ const [command, args] = options.wrap ? [options.wrap.command, [...options.wrap.args, options.executablePath, ...argv]] : [options.executablePath, argv];+ const child = spawnBotWork(() => spawn(command, args, { stdio: ["ignore", "pipe", "pipe", "pipe", "pipe"], env, windowsHide: true }));let output = "";const keep = (chunk: Buffer) => {output = (output + chunk.toString("utf8")).slice(-OUTPUT_LIMIT);diff --git a/server/browser/config.test.ts b/server/browser/config.test.tsindex 8c89fb911b..a74948bf7e 100644--- a/server/browser/config.test.ts+++ b/server/browser/config.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { browserEngineConfigSchema, browserPaneWanted } from "./config.ts";+import { browserEngineConfigSchema, browserPaneWanted, cloudDisplayWanted } from "./config.ts";describe("browser engine proxy configuration", () => {it("accepts an unauthenticated SOCKS5 endpoint", () => {@@ -25,3 +25,25 @@ describe("the desktop pane setting", () => {expect(browserEngineConfigSchema.safeParse({ surface: "window" }).success).toBe(false);});});++describe("cloud display setting", () => {+ const on = { browserEngine: { engine: "chrome" as const, cloudDisplay: true } };++ it("is off unless asked for", () => {+ expect(browserEngineConfigSchema.parse({}).cloudDisplay).toBeUndefined();+ expect(cloudDisplayWanted({}, "container", "linux")).toBe(false);+ expect(cloudDisplayWanted({ browserEngine: { engine: "chrome" } }, "container", "linux")).toBe(false);+ });++ it("needs the new engine, a server and Linux", () => {+ expect(cloudDisplayWanted(on, "container", "linux")).toBe(true);+ expect(cloudDisplayWanted(on, "server", "linux")).toBe(true);+ expect(cloudDisplayWanted({ browserEngine: { cloudDisplay: true } }, "container", "linux")).toBe(false);+ expect(cloudDisplayWanted(on, "desktop", "linux")).toBe(false);+ expect(cloudDisplayWanted(on, "server", "darwin")).toBe(false);+ });++ it("accepts only a boolean", () => {+ expect(browserEngineConfigSchema.safeParse({ cloudDisplay: "yes" }).success).toBe(false);+ });+});diff --git a/server/browser/config.ts b/server/browser/config.tsindex c66612b509..a6fc422775 100644--- a/server/browser/config.ts+++ b/server/browser/config.ts@@ -28,6 +28,9 @@ export const browserEngineConfigSchema = z.object({engine: z.enum(["agent-browser", "chrome"]).optional(),/** "pane" shows the Chrome engine's browser on the desktop app as a real page the person uses directly, an early test; streamed when unset. */surface: z.enum(["stream", "pane"]).optional(),+ /** On a Linux server with Xvnc, the new engine's Chrome runs with its window on a private display that the browser panel+ * shows and a person drives as a remote desktop. Off by default. */+ cloudDisplay: z.boolean().optional(),});export interface BrowserEngineConfig {@@ -36,6 +39,7 @@ export interface BrowserEngineConfig {egress?: BrowserEgressConfig;engine?: BrowserEngineKind;surface?: "stream" | "pane";+ cloudDisplay?: boolean;}export function browserEngineKind(cfg: { browserEngine?: BrowserEngineConfig }): BrowserEngineKind {@@ -46,3 +50,8 @@ export function browserEngineKind(cfg: { browserEngine?: BrowserEngineConfig }):export function browserPaneWanted(cfg: { browserEngine?: BrowserEngineConfig }): boolean {return browserEngineKind(cfg) === "chrome" && cfg.browserEngine?.surface === "pane";}++/** The bots' browsers should run on a display a person sees: asked for in config, on the new engine, on a server. */+export function cloudDisplayWanted(cfg: { browserEngine?: BrowserEngineConfig }, host: "desktop" | "server" | "container", platform: NodeJS.Platform = process.platform): boolean {+ return cfg.browserEngine?.cloudDisplay === true && browserEngineKind(cfg) === "chrome" && host !== "desktop" && platform === "linux";+}diff --git a/server/browser/desktop/desktop.e2e.test.ts b/server/browser/desktop/desktop.e2e.test.tsnew file mode 100644index 0000000000..90e9bf2a58--- /dev/null+++ b/server/browser/desktop/desktop.e2e.test.ts@@ -0,0 +1,489 @@+// A bot's browser on a private display, end to end on real Chrome and a real Xvnc: a person's view through the desktop+// 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 { 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";+import { dirname, join } from "node:path";++import { afterAll, beforeAll, describe, expect, it } from "vitest";+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 { BROWSER_CONTROL_REFUSAL } from "../control.ts";+import type { BrowserTarget } from "../service.ts";+import { startService, until, type RealService } from "../testing/real-service.ts";+import { DESKTOP_SIZE, DisplaySupervisor, findXvnc } from "./displays.ts";+import { findBwrap } from "./policy.ts";+import { DesktopViews } from "./views.ts";++const XVNC = findXvnc();+const BWRAP = findBwrap();+const suite = CHROME && XVNC && BWRAP ? describe : describe.skip;+if (CHROME && (!XVNC || !BWRAP)) console.log("skipping the browser desktop suite: no Xvnc on PATH, or bubblewrap cannot run here");++const PAGE = `<!doctype html><title>desk</title><style>body{margin:0}</style>+<button id="b" style="position:absolute;left:100px;top:100px;width:200px;height:80px" onclick="document.body.dataset.clicks=String(Number(document.body.dataset.clicks||0)+1)">B</button>+<input id="f" aria-label="Field" style="position:absolute;left:100px;top:250px;width:300px;height:40px">+<select id="s" aria-label="Choice" style="position:absolute;left:100px;top:350px;width:200px;height:30px"><option>one</option><option>two</option><option>three</option></select>+<input id="up" type="file" aria-label="Upload" style="position:absolute;left:100px;top:420px;width:300px;height:40px">`;++/** A minimal RFB 3.8 client over the desktop route: the handshake, then raw messages. */+class RfbClient {+ readonly #ws: WebSocket;+ #buffer = Buffer.alloc(0);+ #waiting: (() => void) | null = null;+ closed: number | null = null;+ width = 0;+ height = 0;++ constructor(ws: WebSocket) {+ this.#ws = ws;+ ws.on("message", (data) => {+ this.#buffer = Buffer.concat([this.#buffer, Buffer.from(data as Buffer)]);+ this.#waiting?.();+ });+ ws.on("close", (code) => { this.closed = code; this.#waiting?.(); });+ }++ static async connect(url: string): Promise<RfbClient> {+ const ws = new WebSocket(url);+ // Listening before the handshake ends: the display's first bytes can come in the same packet as the upgrade.+ const client = new RfbClient(ws);+ await new Promise((resolve, reject) => { ws.once("open", resolve); ws.once("error", reject); });+ expect((await client.read(12)).toString("latin1")).toBe("RFB 003.008\n");+ client.send(Buffer.from("RFB 003.008\n", "latin1"));+ const count = (await client.read(1))[0]!;+ expect([...await client.read(count)]).toContain(1);+ client.send(Buffer.from([1]));+ expect((await client.read(4)).readUInt32BE(0)).toBe(0);+ client.send(Buffer.from([1]));+ const init = await client.read(24);+ client.width = init.readUInt16BE(0);+ client.height = init.readUInt16BE(2);+ await client.read(init.readUInt32BE(20));+ // Raw pixels, so an update is easy to recognise, and the display's own size changes (ExtendedDesktopSize).+ const encodings = Buffer.alloc(12);+ encodings[0] = 2;+ encodings.writeUInt16BE(2, 2);+ encodings.writeInt32BE(-308, 8);+ client.send(encodings);+ return client;+ }++ async read(bytes: number, timeoutMs = 15_000): Promise<Buffer> {+ const deadline = Date.now() + timeoutMs;+ while (this.#buffer.length < bytes) {+ if (this.closed !== null) throw new Error(`desktop view closed (${this.closed})`);+ if (Date.now() > deadline) throw new Error("desktop view sent too little");+ await new Promise<void>((resolve) => { this.#waiting = resolve; setTimeout(resolve, 100); });+ }+ const out = this.#buffer.subarray(0, bytes);+ this.#buffer = this.#buffer.subarray(bytes);+ return out;+ }++ /** Asks for a small corner of the screen and waits for the update that brings it. */+ async picture(): Promise<void> {+ this.#buffer = Buffer.alloc(0);+ this.send(Buffer.from([3, 0, 0, 0, 0, 0, 0, 16, 0, 16]));+ const head = await this.read(4);+ expect(head[0]).toBe(0);+ }++ send(bytes: Buffer): void {+ this.#ws.send(bytes);+ }++ click(x: number, y: number): void {+ const pointer = (mask: number) => { const message = Buffer.alloc(6); message[0] = 5; message[1] = mask; message.writeUInt16BE(x, 2); message.writeUInt16BE(y, 4); return message; };+ this.send(Buffer.concat([pointer(0), pointer(1), pointer(0)]));+ }++ type(text: string): void {+ this.keys([...text].map((char) => char.codePointAt(0)!));+ }++ /** Holds `modifiers` down while pressing `keysym`. */+ chord(modifiers: number[], keysym: number): void {+ const key = (down: boolean, sym: number) => { const message = Buffer.alloc(8); message[0] = 4; message[1] = down ? 1 : 0; message.writeUInt32BE(sym, 4); return message; };+ this.send(Buffer.concat([...modifiers.map((sym) => key(true, sym)), key(true, keysym), key(false, keysym), ...modifiers.reverse().map((sym) => key(false, sym))]));+ }++ /** Presses and lets go of each X keysym in turn. */+ keys(keysyms: number[]): void {+ const key = (down: boolean, keysym: number) => { const message = Buffer.alloc(8); message[0] = 4; message[1] = down ? 1 : 0; message.writeUInt32BE(keysym, 4); return message; };+ this.send(Buffer.concat(keysyms.flatMap((keysym) => [key(true, keysym), key(false, keysym)])));+ }++ /** Asks the display for a new size, as noVNC does for a view that resizes its session. */+ resize(width: number, height: number): void {+ const message = Buffer.alloc(8 + 16);+ message[0] = 251;+ message.writeUInt16BE(width, 2);+ message.writeUInt16BE(height, 4);+ message[6] = 1;+ message.writeUInt16BE(width, 16);+ message.writeUInt16BE(height, 18);+ this.send(message);+ }++ close(): void {+ this.#ws.close();+ }+}++/** A process and everything it started, from /proc. */+function treeOf(root: number): Set<number> {+ const parents = new Map<number, number>();+ for (const entry of readdirSync("/proc")) {+ if (!/^\d+$/.test(entry)) continue;+ try { parents.set(Number(entry), Number(readFileSync(`/proc/${entry}/stat`, "utf8").split(") ")[1]!.split(" ")[1])); } catch {}+ }+ const tree = new Set([root]);+ for (let grew = true; grew;) {+ grew = false;+ for (const [pid, parent] of parents) if (tree.has(parent) && !tree.has(pid)) { tree.add(pid); grew = true; }+ }+ return tree;+}++/** Memory of a process and everything it started, in MiB: proportional where the kernel reports it, else resident,+ * which counts shared pages once per process. */+function treeRss(root: number): number {+ let kib = 0;+ for (const pid of treeOf(root)) {+ let pss: string | undefined;+ try { pss = /^Pss:\s+(\d+)/m.exec(readFileSync(`/proc/${pid}/smaps_rollup`, "utf8"))?.[1]; } catch {}+ try { kib += Number(pss ?? /VmRSS:\s+(\d+)/.exec(readFileSync(`/proc/${pid}/status`, "utf8"))?.[1] ?? 0); } catch {}+ }+ return Math.round(kib / 1024);+}++/** CPU seconds the processes and everything they started used, from /proc. */+function cpuSeconds(roots: number[]): number {+ let ticks = 0;+ for (const pid of roots.flatMap((root) => [...treeOf(root)])) {+ try {+ const fields = readFileSync(`/proc/${pid}/stat`, "utf8").split(") ")[1]!.split(" ");+ ticks += Number(fields[11]) + Number(fields[12]);+ } catch {}+ }+ return ticks / 100;+}++/** The first byte of an X server's answer to a connection setup, as a client with `cookie` (or none): 1 is accepted, 0+ * refused. */+function xSetup(display: number, cookie: Buffer | null): Promise<number> {+ return new Promise((resolve, reject) => {+ const socket = connect(`/tmp/.X11-unix/X${display}`);+ const name = cookie ? Buffer.from("MIT-MAGIC-COOKIE-1") : Buffer.alloc(0);+ const data = cookie ?? Buffer.alloc(0);+ const padded = (bytes: Buffer) => Buffer.concat([bytes, Buffer.alloc((4 - (bytes.length % 4)) % 4)]);+ const head = Buffer.alloc(12);+ head[0] = 0x6c;+ head.writeUInt16LE(11, 2);+ head.writeUInt16LE(name.length, 6);+ head.writeUInt16LE(data.length, 8);+ socket.once("connect", () => socket.write(Buffer.concat([head, padded(name), padded(data)])));+ socket.once("data", (answer: Buffer) => { socket.destroy(); resolve(answer[0]!); });+ socket.once("error", reject);+ });+}++const BLOCKED = /This page is blocked|ERR_BLOCKED_BY_ADMINISTRATOR/;+const CONTROL = 0xffe3;+const SHIFT = 0xffe1;+const RETURN = 0xff0d;++/** Memory in use on the machine, in MiB. */+function usedMemory(): number {+ const info = readFileSync("/proc/meminfo", "utf8");+ const field = (name: string) => Number(new RegExp(`^${name}:\\s+(\\d+)`, "m").exec(info)?.[1] ?? 0);+ return Math.round((field("MemTotal") - field("MemAvailable")) / 1024);+}++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; }+});++suite("a bot's browser on a private display", () => {+ let fx: FixtureServer;+ let real: RealService;+ let displays: DisplaySupervisor;+ let views: DesktopViews;+ let server: Server;+ let root: string;+ let page: string;+ const target: BrowserTarget = { session: "desk", key: "bot:desk" };+ const filesTarget: BrowserTarget = { session: "files", key: "bot:files" };+ let workspace: string;+ const person = "alice";++ beforeAll(async () => {+ fx = await FixtureServer.start();+ page = fx.page("/desk", PAGE);+ root = mkdtempSync("/tmp/omb-desk-");+ displays = new DisplaySupervisor({ root, xvnc: XVNC, bwrap: BWRAP });+ 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] : []) });+ views = new DesktopViews({ desktop: (asked) => real.service.desktop(asked) });+ server = createServer();+ server.on("upgrade", (req, socket, head) => {+ const interactive = !(req.url ?? "").includes("interactive=false");+ views.open({ target, botId: "desk", owner: "session", person, canOperate: interactive, req, socket: socket as Socket, head, isCurrent: () => true });+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ }, hostTimeout(240_000));++ afterAll(async () => {+ views?.closeAll();+ server?.closeAllConnections();+ await new Promise((resolve) => server?.close(resolve));+ await real?.close();+ await displays?.closeAll();+ rmSync(root, { recursive: true, force: true });+ await fx?.close();+ });++ const url = () => `ws://127.0.0.1:${(server.address() as AddressInfo).port}/desktop`;+ const display = () => real.service.profiles().find((candidate) => candidate.key === target.key)!.run!.opened.display!;+ const read = <T>(expression: string) => real.peek<T>(target, expression);+ /** Where the page's point (x, y) is on the display: the window fills it from its corner, its tab strip above the page. */+ const onScreen = async (x: number, y: number) => {+ const [left, top] = await read<[number, number]>("[screenX + outerWidth - innerWidth, screenY + outerHeight - innerHeight]");+ return { x: left + x, y: top + y };+ };++ 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();+ 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.+ const [outerWidth, outerHeight] = await read<[number, number]>("[outerWidth, outerHeight]");+ expect(DESKTOP_SIZE.width - outerWidth).toBeLessThanOrEqual(1);+ expect(DESKTOP_SIZE.height - outerHeight).toBeLessThanOrEqual(1);++ const desk = await RfbClient.connect(url());+ expect([desk.width, desk.height]).toEqual([DESKTOP_SIZE.width, DESKTOP_SIZE.height]);+ await desk.picture();++ const button = await onScreen(200, 140);+ desk.click(button.x, button.y);+ await desk.picture();+ expect(await read<string | undefined>("document.body.dataset.clicks")).toBeUndefined();++ await profile.control.take(person);+ await expect(real.call(target, "agent_browser_click", { selector: "#b" })).rejects.toThrow(BROWSER_CONTROL_REFUSAL);+ expect(real.text(await real.call(target, "agent_browser_snapshot"))).toContain('button "B"');+ desk.click(button.x, button.y);+ expect(await until(() => read<string | undefined>("document.body.dataset.clicks"), (value) => value === "1")).toBe("1");+ const field = await onScreen(250, 270);+ desk.click(field.x, field.y);+ desk.type("hi");+ expect(await until(() => read<string>("document.getElementById('f').value"), (value) => value === "hi")).toBe("hi");+ // A <select> opens Chrome's own popup, a window of its own on the display: there Down only moves the highlight+ // (on a closed list it would choose at once), and Return chooses.+ const choice = await onScreen(200, 365);+ desk.click(choice.x, choice.y);+ await until(() => read<string | undefined>("document.activeElement?.id"), (id) => id === "s");+ await desk.picture();+ desk.keys([0xff54]);+ await desk.picture();+ await new Promise((resolve) => setTimeout(resolve, 1_000));+ expect(await read<string>("document.getElementById('s').value")).toBe("one");+ desk.keys([0xff0d]);+ expect(await until(() => read<string>("document.getElementById('s').value"), (value) => value === "two")).toBe("two");++ const watcher = await RfbClient.connect(`${url()}?interactive=false`);+ watcher.click(button.x, button.y);+ await watcher.picture();+ expect(await read<string>("document.body.dataset.clicks")).toBe("1");+ watcher.close();++ await profile.control.release(person, async () => true);+ desk.click(button.x, button.y);+ await desk.picture();+ expect(await read<string>("document.body.dataset.clicks")).toBe("1");++ expect((await real.call(target, "agent_browser_click", { selector: "#b" })).isError).toBeUndefined();+ expect(await read<string>("document.body.dataset.clicks")).toBe("2");+ expect((await real.call(target, "agent_browser_fill", { selector: "#f", text: "bot" })).isError).toBeUndefined();+ expect(await read<string>("document.getElementById('f').value")).toBe("bot");+ desk.close();+ }, hostTimeout(120_000));++ 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();+ const profile = real.service.profiles().find((candidate) => candidate.key === target.key)!;+ await profile.control.take(person);+ const desk = await RfbClient.connect(url());+ try {+ desk.resize(1600, 900);+ expect(await until(() => read<[number, number]>("[outerWidth, outerHeight]"), ([width, height]) => width >= 1599 && height >= 899, 10_000)).toEqual([expect.any(Number), expect.any(Number)]);+ desk.resize(400, 750);+ expect(await until(() => read<[number, number]>("[screen.width, screen.height]"), ([width, height]) => width === 1280 && height === 2400, 10_000)).toEqual([1280, 2400]);+ } finally {+ await profile.control.release(person, async () => true);+ desk.close();+ }+ const [width, height, outerWidth, outerHeight] = await until(() => read<[number, number, number, number]>("[screen.width, screen.height, outerWidth, outerHeight]"), ([screenWidth, screenHeight, outer]) => screenWidth === DESKTOP_SIZE.width && screenHeight === DESKTOP_SIZE.height && outer >= DESKTOP_SIZE.width - 1, 10_000);+ expect([width, height]).toEqual([DESKTOP_SIZE.width, DESKTOP_SIZE.height]);+ expect(DESKTOP_SIZE.width - outerWidth).toBeLessThanOrEqual(1);+ expect(DESKTOP_SIZE.height - outerHeight).toBeLessThanOrEqual(1);+ }, hostTimeout(120_000));++ it("keeps the display its browser's own: a private RFB socket, and X clients need the display's cookie", async () => {+ const display = real.service.profiles().find((candidate) => candidate.key === target.key)!.run!.opened.display!;+ expect(statSync(display.socket).mode & 0o777).toBe(0o600);+ expect(statSync(dirname(display.socket)).mode & 0o777).toBe(0o700);+ const cookie = readFileSync(display.env.XAUTHORITY).subarray(-16);+ expect(await xSetup(display.number, null)).toBe(0);+ expect(await xSetup(display.number, Buffer.alloc(16, 7))).toBe(0);+ expect(await xSetup(display.number, cookie)).toBe(1);+ }, hostTimeout(60_000));++ it("leaves every Chrome not on a display without the lock-down, and lets a display's Chrome open only its own files", async () => {+ const shown = async (service: RealService, at: BrowserTarget, url: string) => {+ const tab = service.service.profiles().find((candidate) => candidate.key === at.key)!.active()!;+ const answer = await tab.page.session.send<{ errorText?: string }>("Page.navigate", { url });+ if (answer.errorText) return answer.errorText;+ return until(async () => {+ const text = await tab.page.evaluate("document.documentElement.innerText", { world: "page" }).catch(() => "");+ return typeof text === "string" ? text : "";+ }, (text) => text.length > 0, 10_000);+ };+ // The bot's tools open http(s), about:blank and data: only, here as everywhere.+ 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();+ 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();+ try {+ const plain: BrowserTarget = { session: "plain", key: "bot:plain" };+ expect((await headless.call(plain, "agent_browser_open", { url: page })).isError).toBeUndefined();+ expect(await shown(headless, plain, `file://${workspace}/report.html`)).toContain("the bot's own report");+ expect(await shown(headless, plain, "file:///etc/hostname")).not.toMatch(/ERR_BLOCKED_BY_ADMINISTRATOR|This page is blocked/);+ } finally {+ await headless.close();+ }+ }, hostTimeout(120_000));++ 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();+ const profile = real.service.profiles().find((candidate) => candidate.key === target.key)!;+ const browser = profile.run!.browser;+ await profile.control.take(person);+ const desk = await RfbClient.connect(url());+ try {+ const targets = async () => (await browser.connection.root.send<{ targetInfos: Array<{ type: string; url: string; browserContextId?: string }> }>("Target.getTargets")).targetInfos;+ const textOf = async (tab: NonNullable<ReturnType<typeof profile.active>>) => {+ const text = await tab.page.evaluate("document.documentElement.innerText", { world: "page" }).catch(() => "");+ return typeof text === "string" ? text : "";+ };+ for (const address of ["file:///etc/passwd", "chrome://settings", "chrome://extensions", "chrome://settings/manageProfile", "chrome://inspect", "devtools://devtools/bundled/inspector.html", `view-source:${page}`, "about:settings"]) {+ // Each address in a new tab of its own, typed into Chrome's own address bar; the new tab page itself is allowed.+ const before = profile.tabs.list().length;+ desk.chord([CONTROL], 0x74);+ const opened = await until(() => profile.active(), (tab) => tab !== null && profile.tabs.list().length === before + 1, 10_000);+ await new Promise((resolve) => setTimeout(resolve, 1_000));+ expect(await textOf(opened!), `new tab before ${address}`).not.toMatch(BLOCKED);+ desk.type(address);+ desk.keys([RETURN]);+ const shown = await until(() => textOf(opened!), (text) => BLOCKED.test(text), 10_000).catch(async () => `${await textOf(opened!)} ${JSON.stringify((await targets()).map((info) => info.url))}`);+ expect(shown, address).toMatch(BLOCKED);+ desk.chord([CONTROL], 0x77);+ await until(() => profile.tabs.list().length, (count) => count === before, 10_000);+ }+ // A file input still asks the panel, never a file dialog on this computer.+ await profile.control.release(person, async () => true);+ expect((await real.call(target, "agent_browser_open", { url: page })).isError).toBeUndefined();+ await profile.control.take(person);+ const upload = await onScreen(250, 440);+ desk.click(upload.x, upload.y);+ const front = profile.active()!;+ await until(() => front.page.fileChoosers.open, (open) => open !== null, 10_000);+ await front.page.fileChoosers.answer([display().env.XAUTHORITY]);+ expect(await until(() => read<string | undefined>("document.getElementById('up').files[0]?.name"), (name) => name === "Xauthority")).toBe("Xauthority");++ // DevTools, an incognito window and a guest window stay shut from the keyboard.+ const pages = (await targets()).filter((info) => info.type === "page").length;+ desk.keys([0xffc9]);+ desk.chord([CONTROL, SHIFT], 0x49);+ desk.chord([CONTROL, SHIFT], 0x4a);+ desk.chord([CONTROL, SHIFT], 0x4e);+ await desk.picture();+ await new Promise((resolve) => setTimeout(resolve, 1_500));+ const after = await targets();+ expect(after.filter((info) => info.url.startsWith("devtools://"))).toEqual([]);+ expect(after.filter((info) => info.type === "page")).toHaveLength(pages);+ console.log(JSON.stringify({ viewportAfterDevToolsKeys: await read<[number, number]>("[innerWidth, innerHeight]") }));+ } finally {+ await profile.control.release(person, async () => true);+ desk.close();+ }+ }, hostTimeout(180_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();+ const profile = real.service.profiles().find((candidate) => candidate.key === target.key)!;+ const roots = [xvncPid(profile.run!.opened.display!.socket)!, profile.run!.opened.pid!];+ const desk = await RfbClient.connect(url());+ const busy = async () => {+ const before = cpuSeconds(roots);+ const end = Date.now() + 10_000;+ while (Date.now() < end) await desk.picture();+ return Math.round(((cpuSeconds(roots) - before) / 10) * 1000) / 10;+ };+ const watch = (frames: boolean) => real.service.attachViewer(target, { owner: "local-owner", canOperate: true, maxWidth: 1280, maxHeight: 800, ...(frames ? {} : { frames: false }) }, (output) => { if (output.type === "frame") output.ack(); });+ const pictured = await watch(true);+ const withPictures = await busy();+ await pictured.close();+ const frameless = await watch(false);+ const withoutPictures = await busy();+ await frameless.close();+ desk.close();+ console.log(JSON.stringify({ animatedPageDesktopWatched: { cpuPercentWithPictureStream: withPictures, cpuPercentWithoutPictureStream: withoutPictures } }));+ }, hostTimeout(120_000));++ it.runIf(process.env.OMB_DESKTOP_MEASURE === "1")("costs this much memory and CPU against a headless browser", async () => {+ expect((await real.call(target, "agent_browser_open", { url: page })).isError).toBeUndefined();+ const profile = real.service.profiles().find((candidate) => candidate.key === target.key)!;+ const xvnc = xvncPid(profile.run!.opened.display!.socket)!;+ const chrome = profile.run!.opened.pid!;+ const busy = async (pids: number[]) => {+ const before = cpuSeconds(pids);+ await new Promise((resolve) => setTimeout(resolve, 10_000));+ return Math.round(((cpuSeconds(pids) - before) / 10) * 1000) / 10;+ };+ const desk = await RfbClient.connect(url());+ const display = { xvncMiB: treeRss(xvnc), chromeMiB: treeRss(chrome), cpuPercentWatched: await busy([xvnc, chrome]) };+ desk.close();+ const idle = { cpuPercentIdle: await busy([xvnc, chrome]), usedMiB: usedMemory() };+ await real.service.closeAll();+ await displays.closeAll();+ await new Promise((resolve) => setTimeout(resolve, 3_000));+ const none = usedMemory();+ const headless = await startService();+ try {+ const plain: BrowserTarget = { session: "plain", key: "bot:plain" };+ await headless.call(plain, "agent_browser_open", { url: page });+ const run = headless.service.profiles().find((candidate) => candidate.key === plain.key)!.run!;+ await new Promise((resolve) => setTimeout(resolve, 3_000));+ const plainUsed = usedMemory();+ console.log(JSON.stringify({+ display: { ...display, ...idle, addedMiB: idle.usedMiB - none },+ headless: { chromeMiB: treeRss(run.opened.pid!), cpuPercentIdle: await busy([run.opened.pid!]), addedMiB: plainUsed - none },+ }));+ } finally {+ await headless.close();+ }+ }, hostTimeout(180_000));+});diff --git a/server/browser/engines.test.ts b/server/browser/engines.test.tsindex 586365eea5..34969e05f2 100644--- a/server/browser/engines.test.ts+++ b/server/browser/engines.test.ts@@ -1,4 +1,4 @@-import { existsSync, mkdtempSync } from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";@@ -49,6 +49,8 @@ function engines(options: RuntimeRouterOptions = {}) {},live: { open: vi.fn(async () => undefined), action: vi.fn(async () => "chrome"), has: vi.fn((viewerId: string) => viewerId === "v-chrome"), handBack: vi.fn(), closeForSession: vi.fn(), closeForOwner: vi.fn(), closeForBot: vi.fn(), closeAll: vi.fn() },stream: { open: vi.fn(), closeForSession: vi.fn(), closeForOwner: vi.fn(), closeForBot: vi.fn(), closeAll: vi.fn(), recheck: vi.fn() },+ desktop: { open: vi.fn(), closeForSession: vi.fn(), closeForOwner: vi.fn(), closeForBot: vi.fn(), closeAll: vi.fn(), recheck: vi.fn() },+ desktopView: vi.fn(() => true),close: vi.fn(async () => undefined),};const runtime = new RuntimeRouter(old as unknown as BrowserRuntime, chrome as unknown as ChromeEngine, options);@@ -258,6 +260,21 @@ describe("the live view router", () => {expect(chrome.live.closeAll).toHaveBeenCalledOnce();expect(chrome.stream.closeAll).toHaveBeenCalledOnce();expect(oldLive.closeAll).toHaveBeenCalledOnce();+ expect(chrome.desktop.recheck).toHaveBeenCalledOnce();+ expect(chrome.desktop.closeForSession).toHaveBeenCalledWith("s");+ expect(chrome.desktop.closeForOwner).toHaveBeenCalledWith("o");+ expect(chrome.desktop.closeAll).toHaveBeenCalledOnce();+ });++ it("opens a desktop view only for a new-engine session on a server that runs browsers on a display", () => {+ const { chrome, live } = engines();+ const request = { botId: "a", owner: "o", person: "p", canOperate: true, req: {} as never, socket: {} as never, head: Buffer.alloc(0), isCurrent: () => true };+ expect(live.desktop({ session: "s", spec: AGENT_BROWSER, ...request })).toBe(false);+ chrome.desktopView.mockReturnValueOnce(false);+ expect(live.desktop({ session: "s", spec: CHROME, ...request })).toBe(false);+ expect(chrome.desktop.open).not.toHaveBeenCalled();+ expect(live.desktop({ session: "s", spec: CHROME, ...request })).toBe(true);+ expect(chrome.desktop.open).toHaveBeenCalledWith({ ...request, target: { session: "s", key: "bot:a" } });});it("streams, takes uploads for and serves downloads of new-engine sessions only", async () => {@@ -358,3 +375,27 @@ describe("deleting a bot's browser on the desktop app, pane off", () => {}});});++describe("the new engine's desktop view", () => {+ it.skipIf(process.platform === "win32")("never looks for bubblewrap while the setting is off, and looks once when it is on", async () => {+ const dataDir = mkdtempSync(join(tmpdir(), "omb-chrome-engine-"));+ const bin = join(dataDir, "bin");+ mkdirSync(bin);+ writeFileSync(join(bin, "Xvnc"), "", { mode: 0o755 });+ let on = false;+ const probeBwrap = vi.fn(() => "/usr/bin/bwrap");+ const value = new ChromeEngine({ dataDir, host: "container", env: { PATH: bin }, platform: "linux", egressPort: async () => 0, idleMs: () => 180_000, egressNotice: () => null, cloudDisplay: () => on, probeBwrap });+ try {+ value.summary();+ expect(value.desktopView()).toBe(false);+ expect(probeBwrap).not.toHaveBeenCalled();+ on = true;+ value.desktopView();+ value.desktopView();+ expect(probeBwrap).toHaveBeenCalledTimes(1);+ } finally {+ await value.close();+ await removeTempDir(dataDir);+ }+ });+});diff --git a/server/browser/engines.ts b/server/browser/engines.tsindex 545c7ed1b8..ef50a7aa33 100644--- a/server/browser/engines.ts+++ b/server/browser/engines.ts@@ -15,7 +15,10 @@ import { ChromeLauncher } from "./chrome/launcher.ts";import { ProcessRegistry, sweep } from "./chrome/processes.ts";import { browserRoot } from "./chrome/profile.ts";import { browserLanguage, browserTimeZone, languageList } from "./chrome/wrapper.ts";-import { displayScreen } from "./display.ts";+import { displayScreen, parseDisplay } from "./display.ts";+import { DESKTOP_SIZE, DisplaySupervisor, findXvnc } from "./desktop/displays.ts";+import { findBwrap } from "./desktop/policy.ts";+import { DesktopViews, type DesktopRequest } from "./desktop/views.ts";import { botReason, browserInputLog, pageAction, type BotReason, type BrowserInputLog } from "./input-log.ts";import type { PaneBackend } from "./pane/backend.ts";import type { Download } from "./cdp/downloads.ts";@@ -54,6 +57,10 @@ export interface ChromeEngineOptions {language?(): string | undefined;/** The desktop app's panes, used for a browser that starts while they are wanted and the app shows them. */pane?: { backend: PaneBackend; wanted(): boolean };+ /** browserEngine.cloudDisplay is on here: a browser that starts gets a window on a private display. */+ cloudDisplay?(): boolean;+ /** Finds a usable bubblewrap; tests pass their own. */+ probeBwrap?: (env: NodeJS.ProcessEnv, platform: NodeJS.Platform) => string | null;log?: (line: string) => void;}@@ -68,6 +75,8 @@ export class ChromeEngine {readonly service: BrowserService;readonly live: LiveV1;readonly stream: StreamV2;+ readonly desktop: DesktopViews;+ readonly displays: DisplaySupervisor;readonly #targets = new Map<string, string>();readonly #registry: ProcessRegistry;readonly #options: ChromeEngineOptions;@@ -84,6 +93,13 @@ export class ChromeEngine {this.#registry = new ProcessRegistry(browserRoot(options.dataDir));let screen: ReturnType<typeof displayScreen> | null = null;const locale = () => browserLanguage(env, options.language?.()) ?? null;+ this.displays = new DisplaySupervisor({+ root: join(browserRoot(options.dataDir), "displays"),+ xvnc: options.host === "desktop" ? null : findXvnc(env, platform),+ bwrap: options.host === "desktop" ? null : () => (options.probeBwrap ?? findBwrap)(env, platform),+ ...(options.log ? { log: options.log } : {}),+ });+ const desktopSize = parseDisplay(env.OMB_BROWSER_SCREEN?.trim() ?? "") ?? DESKTOP_SIZE;const backend = new LocalBackend({dataDir: options.dataDir,host: options.host,@@ -99,6 +115,7 @@ export class ChromeEngine {egressPort: (key) => options.egressPort(key),registry: this.#registry,sandbox,+ display: async (key) => (this.desktopView() ? this.displays.acquire(key, { width: desktopSize.width, height: desktopSize.height }) : null),...(options.log ? { log: options.log } : {}),});options.pane?.backend.fallBackTo(backend);@@ -114,6 +131,12 @@ export class ChromeEngine {});this.live = new LiveV1({ service: this.service, target: (session) => this.target(session) });this.stream = new StreamV2({ service: this.service });+ this.desktop = new DesktopViews({ desktop: (target) => this.service.desktop(target) });+ }++ /** 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;}/** The spec a session gets on the new engine, remembered so its live view finds the profile. */@@ -163,7 +186,9 @@ export class ChromeEngine {this.#timer = null;this.live.closeAll();this.stream.closeAll();+ this.desktop.closeAll();await this.service.closeAll();+ await this.displays.closeAll();}/** A deleted bot's or profile's browser: stopped, and its folder, downloads and screenshots gone. */@@ -182,10 +207,10 @@ export class ChromeEngine {}/** For the browser status: what the new engine will run here. */- summary(): { kind: "engine"; version: string; chrome: string } | { kind: "unavailable"; reason: string } {+ summary(): { kind: "engine"; version: string; chrome: string; desktopView?: true } | { kind: "unavailable"; reason: string } {const plan = this.launcher.plan();if (plan.kind === "legacy") return { kind: "unavailable", reason: `Chrome is needed for the new browser: ${plan.reason}` };- return { kind: "engine", version: "omb-cdp", chrome: this.launcher.describe() };+ return { kind: "engine", version: "omb-cdp", chrome: this.launcher.describe(), ...(this.desktopView() ? { desktopView: true as const } : {}) };}/** fill_login's reads and typing on the new engine. */@@ -352,6 +377,14 @@ export class LiveRouter {return this.#chrome.live.has(options.viewerId) ? this.#chrome.live.action(options) : this.#old.action(options);}+ /** False when the session's browser cannot run on a private display: the panel keeps the picture view. */+ desktop({ session, spec, ...request }: SessionSpec & Omit<DesktopRequest, "target">): boolean {+ const target = chromeTarget(session, spec);+ if (!target || !this.#chrome.desktopView()) return false;+ this.#chrome.desktop.open({ ...request, target });+ return true;+ }+/** False when the session runs on agent-browser, whose only view is v1. */stream({ session, spec, ...request }: SessionSpec & Omit<StreamRequest, "target">): boolean {const target = chromeTarget(session, spec);@@ -373,10 +406,10 @@ export class LiveRouter {}handBack(session: string): void { this.#chrome.live.handBack(session); this.#old.handBack(session); }- closeForSession(session: string): void { this.#chrome.live.closeForSession(session); this.#chrome.stream.closeForSession(session); this.#old.closeForSession(session); }- closeForOwner(owner: string): void { this.#chrome.live.closeForOwner(owner); this.#chrome.stream.closeForOwner(owner); this.#old.closeForOwner(owner); }- closeForBot(botId: string): void { this.#chrome.live.closeForBot(botId); this.#chrome.stream.closeForBot(botId); this.#old.closeForBot(botId); }- closeAll(): void { this.#chrome.live.closeAll(); this.#chrome.stream.closeAll(); this.#old.closeAll(); }- /** Who may see what changed: every v2 view that no longer shows its browser to a person allowed to see it closes now. */- recheck(): void { this.#chrome.stream.recheck(); }+ closeForSession(session: string): void { this.#chrome.live.closeForSession(session); this.#chrome.stream.closeForSession(session); this.#chrome.desktop.closeForSession(session); this.#old.closeForSession(session); }+ closeForOwner(owner: string): void { this.#chrome.live.closeForOwner(owner); this.#chrome.stream.closeForOwner(owner); this.#chrome.desktop.closeForOwner(owner); this.#old.closeForOwner(owner); }+ closeForBot(botId: string): void { this.#chrome.live.closeForBot(botId); this.#chrome.stream.closeForBot(botId); this.#chrome.desktop.closeForBot(botId); this.#old.closeForBot(botId); }+ closeAll(): void { this.#chrome.live.closeAll(); this.#chrome.stream.closeAll(); this.#chrome.desktop.closeAll(); this.#old.closeAll(); }+ /** Who may see what changed: every v2 or desktop view that no longer shows its browser to a person allowed to see it closes now. */+ recheck(): void { this.#chrome.stream.recheck(); this.#chrome.desktop.recheck(); }}diff --git a/server/browser/service.ts b/server/browser/service.tsindex 551235730d..f6418ffe29 100644--- a/server/browser/service.ts+++ b/server/browser/service.ts@@ -23,6 +23,8 @@ import type { CdpPage } from "./cdp/page.ts";import { browserRoot, profileDir, profileHash, profileKind, removeProfile, workspaceId } from "./chrome/profile.ts";import { BROWSER_CONTROL_REFUSAL, ProfileControl, type TakeResult } from "./control.ts";import { executeTool, personUrl, readsDuringHold, toolFailure, type ToolContext } from "./dispatch.ts";+import type { DesktopTarget } from "./desktop/views.ts";+import { fillDisplay, resizeDisplay } from "./desktop/window.ts";import { installedExtensions } from "./extensions.ts";import { HealthShown, pageHealthLine } from "./health.ts";import type { HoldLimits } from "./hold.ts";@@ -71,6 +73,8 @@ interface Running {readonly browser: CdpBrowser;readonly offs: Array<() => void>;closing: boolean;+ /** The person resized the browser's display away from its usual size. */+ resized?: boolean;}type Reopened = { kind: "idle" | "restart" | "crash"; pages: string[] } | null;@@ -242,6 +246,13 @@ export class BrowserService {}));if (browser.downloads) run.offs.push(browser.downloads.onChange((download) => profile.hub.downloaded(download)));if (opened.onPersonInput) run.offs.push(opened.onPersonInput(() => { profile.lastUsed = Date.now(); }));+ // A display the person resized goes back to its usual size when they hand the browser back, as the page does.+ const display = opened.display;+ if (display) run.offs.push(profile.control.onChange(() => {+ if (profile.control.owner !== null || !run.resized || run.closing) return;+ run.resized = false;+ void resizeDisplay(display.socket, display.size).then(() => fillDisplay(browser, display.size)).catch(() => undefined);+ }));try {this.#stillWanted(profile, epoch);await browser.waitForPage(() => true, 15_000);@@ -644,6 +655,20 @@ export class BrowserService {return profile.hub.attach(options, push);}+ /** The display a person sees this browser's window on: "pictures" when it runs headless, "stopped" while it does not+ * run. A desktop view never starts a browser: the person's v2 view does, and an idle one stays closed. */+ async desktop(target: BrowserTarget): Promise<DesktopTarget | "pictures" | "stopped"> {+ const profile = this.#profiles.get(target.key);+ const run = profile?.run && !profile.run.closing ? profile.run : await profile?.starting?.catch(() => null);+ if (!profile || !run || run.closing) return "stopped";+ const display = run.opened.display;+ if (!display) return "pictures";+ return { socket: display.socket, control: profile.control, used: () => profile.hub.personUsed(), resized: (width, height) => {+ run.resized = width !== display.size.width || height !== display.size.height;+ void fillDisplay(run.browser, { width, height });+ } };+ }+heldBy(session: string): string | null {return this.#bySession(session)?.control.owner ?? null;}@@ -710,6 +735,7 @@ export class BrowserService {running: async () => { await this.running(profile); },used: () => { profile.lastUsed = Date.now(); },pageLimit: () => (profile.run && !profile.run.closing ? profile.run.opened.pageLimit ?? null : null),+ desktop: () => Boolean(profile.run?.opened.display),take: async (owner: string): Promise<TakeResult> => {await this.running(profile);const taken = await profile.control.take(owner);diff --git a/server/browser/testing/fake-chrome.ts b/server/browser/testing/fake-chrome.tsindex 7d7ed7423b..4e2bb3e60e 100644--- a/server/browser/testing/fake-chrome.ts+++ b/server/browser/testing/fake-chrome.ts@@ -3,6 +3,7 @@import type { Backend, BackendCaps, OpenedBrowser, OpenRequest } from "../backends.ts";import { CdpBrowser } from "../cdp/browser.ts";import { fitPage } from "../chrome/flags.ts";+import type { DesktopDisplay } from "../desktop/displays.ts";import type { Identity } from "../cdp/identity.ts";import type { CdpTransport } from "../cdp/transport.ts";@@ -449,10 +450,13 @@ export class FakeBackend implements Backend {readonly opened: OpenRequest[] = [];readonly #make: (request: OpenRequest) => FakeChrome;readonly #pageLimit: { width: number; height: number } | null;+ readonly #display: DesktopDisplay | null;- constructor(make: (request: OpenRequest) => FakeChrome = () => new FakeChrome(), { pageLimit = null }: { pageLimit?: { width: number; height: number } | null } = {}) {+ /** `display`: every browser opens with its window on that private display, as LocalBackend does with cloudDisplay on. */+ constructor(make: (request: OpenRequest) => FakeChrome = () => new FakeChrome(), { pageLimit = null, display = null }: { pageLimit?: { width: number; height: number } | null; display?: DesktopDisplay | null } = {}) {this.#make = make;this.#pageLimit = pageLimit;+ this.#display = display;}get chrome(): FakeChrome {@@ -470,10 +474,11 @@ export class FakeBackend implements Backend {chrome.window.height = viewport.height + CHROME_HEIGHT;this.chromes.push(chrome);const screen = limit ? { width: limit.width, height: limit.height + CHROME_HEIGHT } : null;- const browser = await CdpBrowser.connect(chrome, { identity: FAKE_IDENTITY, headless: true, downloadDir: null, permissions: true, platform: "darwin", maxPages: 8, viewport, screen, handleAuth: true });+ const display = this.#display;+ const browser = await CdpBrowser.connect(chrome, { identity: display ? null : FAKE_IDENTITY, headless: true, downloadDir: null, permissions: true, platform: "darwin", maxPages: 8, viewport: display ? null : viewport, screen: display ? null : screen, handleAuth: true });let exited!: () => void;const done = new Promise<void>((resolve) => { exited = resolve; });chrome.onClose(() => exited());- return { browser, pageLimit: limit, pid: null, version: "153.0.8010.12", exited: done, close: async () => { await browser.close(); } };+ return { browser, pageLimit: display ? null : limit, pid: null, version: "153.0.8010.12", exited: done, close: async () => { await browser.close(); }, display };}}diff --git a/server/browser/testing/real-service.ts b/server/browser/testing/real-service.tsindex 4dac8a3e69..d987675a62 100644--- a/server/browser/testing/real-service.ts+++ b/server/browser/testing/real-service.ts@@ -4,7 +4,7 @@ import { mkdtempSync } from "node:fs";import { join } from "node:path";import { removeTempDir } from "../../testing/cleanup.ts";-import { LocalBackend } from "../backends.ts";+import { LocalBackend, type LocalBackendOptions } from "../backends.ts";import { calibrateIdentity, chromeFingerprint, type CalibratedIdentity } from "../chrome/calibrate.ts";import type { ScreenSpec } from "../chrome/flags.ts";import { sandboxDisabled } from "../chrome/host-setup.ts";@@ -39,7 +39,7 @@ export interface RealService {close(): Promise<void>;}-export async function startService({ screen, egressPort, ...options }: Partial<BrowserServiceOptions> & { screen?: ScreenSpec; egressPort?: (key: string) => Promise<number | null> } = {}): Promise<RealService> {+export async function startService({ screen, egressPort, display, ...options }: Partial<BrowserServiceOptions> & { screen?: ScreenSpec; egressPort?: (key: string) => Promise<number | null>; display?: LocalBackendOptions["display"] } = {}): Promise<RealService> {if (!CHROME) throw new Error("No Chrome to test with.");const executablePath = CHROME;const sandbox = !sandboxDisabled(process.env);@@ -54,6 +54,7 @@ export async function startService({ screen, egressPort, ...options }: Partial<BegressPort: egressPort ?? (async () => null),sandbox,handshakeTimeoutMs: FIRST_LAUNCH_MS,+ ...(display ? { display } : {}),});const service = new BrowserService({ dataDir, backend: () => backend, maxRunning: 4, idleMs: () => 600_000, ...options });const call = (target: BrowserTarget, name: string, args: Record<string, unknown> = {}) =>diff --git a/server/browser/viewers/core.test.ts b/server/browser/viewers/core.test.tsindex fa57147901..a2fff41163 100644--- a/server/browser/viewers/core.test.ts+++ b/server/browser/viewers/core.test.ts@@ -5,6 +5,7 @@ import { afterAll, afterEach, describe, expect, it } from "vitest";import { removeTempDir } from "../../testing/cleanup.ts";import { BrowserService } from "../service.ts";+import type { DesktopDisplay } from "../desktop/displays.ts";import type { HoldLimits } from "../hold.ts";import { FakeBackend, FakeChrome, type FakeDocument } from "../testing/fake-chrome.ts";import { personUrl } from "../dispatch.ts";@@ -33,12 +34,12 @@ const same = (expected: unknown) => (actual: unknown) => JSON.stringify(actual)const PAGE: FakeDocument = { title: "Page", text: "hello", elements: [{ role: "textbox", name: "Name", selector: "#name", editable: true, box: [10, 10, 200, 30] }] };-type WatchOptions = { owner?: string; size?: { width: number; height: number }; maxWidth?: number; maxHeight?: number; pace?: "hi" | "lo"; ack?: boolean; authPrompts?: boolean; pointer?: boolean };+type WatchOptions = { owner?: string; size?: { width: number; height: number }; maxWidth?: number; maxHeight?: number; pace?: "hi" | "lo"; ack?: boolean; authPrompts?: boolean; pointer?: boolean; frames?: boolean };-async function setup({ pageLimit = null, document = PAGE, holdLimits }: { pageLimit?: { width: number; height: number } | null; document?: FakeDocument; holdLimits?: HoldLimits } = {}) {+async function setup({ pageLimit = null, document = PAGE, holdLimits, display = null }: { pageLimit?: { width: number; height: number } | null; document?: FakeDocument; holdLimits?: HoldLimits; display?: DesktopDisplay | null } = {}) {const dataDir = mkdtempSync(join(tmpdir(), "omb-viewers-"));folders.push(dataDir);- const backend = new FakeBackend(() => new FakeChrome({ documents: () => ({ ...document, elements: document.elements.map((element) => ({ ...element })) }) }), { pageLimit });+ const backend = new FakeBackend(() => new FakeChrome({ documents: () => ({ ...document, elements: document.elements.map((element) => ({ ...element })) }) }), { pageLimit, display });const service = new BrowserService({ dataDir, backend: () => backend, maxRunning: 4, idleMs: () => 600_000, takeoverMs: 200, ...(holdLimits ? { holdLimits } : {}) });services.push(service);const target = { session: "bot-a", key: "bot:a" };@@ -46,7 +47,7 @@ async function setup({ pageLimit = null, document = PAGE, holdLimits }: { pageLiawait call("agent_browser_open", { url: "https://example.com/" });const watch = async (options: WatchOptions = {}) => {const outputs: ViewerOutput[] = [];- const viewer = await service.attachViewer(target, { owner: options.owner ?? "local-owner", canOperate: true, maxWidth: options.maxWidth ?? 3200, maxHeight: options.maxHeight ?? 2000, pace: options.pace ?? "hi", authPrompts: options.authPrompts === true, ...(options.pointer === false ? { pointer: false } : {}), ...(options.size ? { size: options.size } : {}) }, (output) => {+ const viewer = await service.attachViewer(target, { owner: options.owner ?? "local-owner", canOperate: true, maxWidth: options.maxWidth ?? 3200, maxHeight: options.maxHeight ?? 2000, pace: options.pace ?? "hi", authPrompts: options.authPrompts === true, ...(options.pointer === false ? { pointer: false } : {}), ...(options.frames === false ? { frames: false } : {}), ...(options.size ? { size: options.size } : {}) }, (output) => {outputs.push(output);if (output.type === "frame" && options.ack !== false) output.ack();});@@ -70,6 +71,35 @@ describe("the page fills the panel", () => {await until(() => chrome().viewport, same(UNATTACHED_VIEWPORT));});+ it("sends no pictures to a view whose person sees the window on a remote desktop, and keeps its hold and tabs", async () => {+ const { watch, chrome, page } = await setup();+ const pictured = await watch();+ const desktop = await watch({ frames: false });+ await until(() => pictured.outputs, (seen) => seen.some((output) => output.type === "frame"));+ expect(desktop.outputs.some((output) => output.type === "control")).toBe(true);+ expect(desktop.outputs.some((output) => output.type === "tabs")).toBe(true);+ await desktop.viewer.input({ type: "takeControl" });+ await until(() => desktop.viewer.controlState().controlling, (controlling) => controlling);+ expect(desktop.outputs.filter((output) => output.type === "frame")).toEqual([]);+ const casts = chrome().sentTo(page()).filter((sent) => sent.method === "Page.startScreencast").length;+ await pictured.viewer.close();+ expect(chrome().sentTo(page()).filter((sent) => sent.method === "Page.startScreencast").length).toBe(casts);+ await desktop.viewer.close();+ });++ it("leaves a window on a private display as it is: the person sees that display, not a page sized to their panel", async () => {+ 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: ["--"] }, exited: new Promise(() => {}), release: async () => {} };+ const { watch, chrome, page } = await setup({ display });+ const before = { ...chrome().window };+ const { viewer } = await watch({ size: { width: 1600, height: 1000 } });+ await viewer.input({ type: "resize", width: 400, height: 750 });+ await viewer.input({ type: "takeControl" });+ await viewer.input({ type: "zoom", factor: 1.5 });+ expect(chrome().window).toEqual(before);+ expect(page().emulated ?? null).toBeNull();+ await viewer.close();+ });+it("gives a narrow panel a desktop page of its shape, never a phone's, and no taller than twice its width", async () => {const { watch, chrome, call } = await setup();const { viewer, outputs } = await watch({ size: { width: 400, height: 750 } });diff --git a/server/browser/viewers/core.ts b/server/browser/viewers/core.tsindex 15ce112314..e60007fb02 100644--- a/server/browser/viewers/core.ts+++ b/server/browser/viewers/core.ts@@ -89,6 +89,7 @@ export interface ViewerOptions {pagePopups?: boolean;/** The viewer draws the agent's pointer, which the agent's actions wait for; false for the v1 view, which draws none. */pointer?: boolean;+ frames?: boolean; // false: its person sees the browser's window another way, on a remote desktop, so no screencast runs}/** What a hub needs from the browser service. */@@ -111,6 +112,7 @@ export interface HubHost {showTab(tab: Tab): Promise<void>;download(id: string): Download | undefined;extensions(): InstalledExtension[]; // installed in this browser's profile with a page to open; empty where OMB keeps none+ desktop?(): boolean; // its window fills a display the person sees as it is, so no viewer sizes it}const num = (value: unknown, fallback = 0) => (typeof value === "number" && Number.isFinite(value) ? value : fallback);@@ -165,7 +167,7 @@ export class Viewer {pace: options.pace ?? "hi",authPrompts: options.authPrompts === true,pagePopups: options.pagePopups === true,- pointer: options.pointer !== false,+ pointer: options.pointer !== false, frames: options.frames !== false,};}@@ -177,9 +179,7 @@ export class Viewer {try { this.#push(output); } catch {}}- get session(): CdpSession | null {- return this.#session;- }+ get session(): CdpSession | null { return this.#session; }/** Follows the tab in front: a new session and screencast for it, the old ones let go. */bind(tab: Tab | null): Promise<void> {@@ -228,7 +228,7 @@ export class Viewer {this.#scale = scale;const session = this.#session;this.#params = this.#params.then(async () => {- if (!session || session !== this.#session || session.detached || this.#paused > 0 || this.#hidden || this.closed) return;+ if (!session || session !== this.#session || session.detached || this.#paused > 0 || this.#hidden || this.closed || !this.options.frames) return;await session.send("Page.stopScreencast").catch(() => {});await session.send("Page.startScreencast", {format: "jpeg",@@ -338,7 +338,7 @@ export class Viewer {async pushStill(): Promise<void> {const tab = this.tab;const session = this.#session;- if (!tab || !session || session.detached || this.#hidden || this.closed) return;+ if (!tab || !session || session.detached || this.#hidden || this.closed || !this.options.frames) return;try {const metrics = await session.send<{ cssVisualViewport: { pageX: number; pageY: number; clientWidth: number; clientHeight: number; scale?: number } }>("Page.getLayoutMetrics");const view = metrics.cssVisualViewport;@@ -447,9 +447,8 @@ export class ViewerHub {handBack(): Promise<void> { return this.#hold.handBack(); }- get size(): number {- return this.viewers.size;- }+ get size(): number { return this.viewers.size; }+ personUsed(): void { this.host.used(); this.#hold.used(); } // input from a remote desktop of the browser's window/** Someone watching could answer a site's HTTP sign-in. */answersAuth(): boolean {@@ -470,7 +469,7 @@ export class ViewerHub {async #apply(): Promise<void> {const browser = this.host.browser();- if (!browser) return;+ if (!browser || this.host.desktop?.()) return;const size = this.viewport();const zoom = this.zoom;const emulated = size.width < MIN_WINDOW_WIDTH || zoom !== 1 || !fitsScreen(size, this.host.pageLimit());diff --git a/server/browser/viewers/stream-v2.e2e.test.ts b/server/browser/viewers/stream-v2.e2e.test.tsindex f026e4ec32..67e38ad400 100644--- a/server/browser/viewers/stream-v2.e2e.test.ts+++ b/server/browser/viewers/stream-v2.e2e.test.ts@@ -68,6 +68,7 @@ suite("the v2 stream on real Chrome", () => {open: async () => {},action: async () => ({ ok: true }),stream: ({ session: _session, spec: _spec, ...request }) => { stream.open({ ...request, target }); return true; },+ desktop: () => false,fileChooserOffered: (_browser, owner, chooser) => real.service.fileChooserOffered(target.session, owner, chooser),answerFileChooser: (_browser, owner, chooser, paths) => real.service.answerFileChooser(target.session, owner, chooser, paths),download: (_browser, id) => real.service.download(target.session, id),diff --git a/server/browser/viewers/stream-v2.ts b/server/browser/viewers/stream-v2.tsindex b166f0bc7a..148152a8b8 100644--- a/server/browser/viewers/stream-v2.ts+++ b/server/browser/viewers/stream-v2.ts@@ -301,6 +301,8 @@ export class StreamV2 {pace: "hi",authPrompts: true,pagePopups: true,+ // The panel shows this browser's window on a remote desktop instead: the stream still carries its hold and tabs.+ ...(params.get("frames") === "0" ? { frames: false } : {}),...(size && request.canOperate ? { size } : {}),};try {diff --git a/server/cloud-team-browser.e2e.test.ts b/server/cloud-team-browser.e2e.test.tsindex d7411e9d8e..4d1710fb5c 100644--- a/server/cloud-team-browser.e2e.test.ts+++ b/server/cloud-team-browser.e2e.test.ts@@ -70,6 +70,16 @@ afterAll(async () => {if (stub) rmSync(stub.dir, { recursive: true, force: true });});+it("lets only the owner or an admin turn the browser's desktop view on, as every browser setting", async () => {+ const set = (token: string, browserEngine: Record<string, unknown>) => team.as(token, "PATCH", "/api/config", { browserEngine });+ expect((await set(ada, { cloudDisplay: true })).status).toBe(403);+ expect((await set(ada, { idleTimeoutMinutes: 5 })).status).toBe(403);+ const byAdmin = await set(admin, { cloudDisplay: true });+ expect(byAdmin.status, JSON.stringify(byAdmin.body)).toBe(200);+ const byOwner = await set(owner, { cloudDisplay: false });+ expect(byOwner.status, JSON.stringify(byOwner.body)).toBe(200);+});+/** The live view's first answer: a refusal names its reason; an open view (a real browser) is cut off after its headers. */async function liveView(token: string, threadId?: string): Promise<{ status: number; error?: string }> {const abort = new AbortController();diff --git a/server/cloud-team-privacy-holes.e2e.test.ts b/server/cloud-team-privacy-holes.e2e.test.tsindex 17866718d6..299a9e79c5 100644--- a/server/cloud-team-privacy-holes.e2e.test.ts+++ b/server/cloud-team-privacy-holes.e2e.test.ts@@ -155,7 +155,7 @@ const SUFFIXES = ["", "/tasks", "/tasks/t1", "/tasks/t1/title", "/tasks/delete","/activity", "/overview", "/projects", "/projects/p1", "/projects/order", "/queue/q1", "/queue/q1/steer", "/read", "/respond", "/interrupt", "/compact","/active-branch", "/start-fresh", "/setup-request", "/helper-followup", "/tool-budget", "/threads/follow-model", "/mcp-servers", "/data", "/data/x", "/computer","/computer/exec", "/computer/control", "/computer/viewer-close", "/local-computer", "/local-computer/run", "/local-computer/join", "/local-computer/screenshot",- "/browser/live", "/browser/action", "/browser/upload", "/browser/download/d1", "/browser/stream", "/cards/c1", "/command-allowlist", "/command-allowlist/x",+ "/browser/live", "/browser/action", "/browser/upload", "/browser/download/d1", "/browser/stream", "/browser/desktop", "/cards/c1", "/command-allowlist", "/command-allowlist/x","/connector-cards/c1/status", "/connector-cards/c1/authorize", "/secret-cards/c1/provide", "/secret-cards/c1/save", "/sign-in-cards/c1/done", "/saved-steps/s1","/requests/aaaaaaaaaaaaaaaaaaaa", "/requests/aaaaaaaaaaaaaaaaaaaa/interrupt", "/apps/a1/rpc", "/apps/a1/context", "/avatar/generate", "/slack-management", "/webhooks", "/routines", "/files", "/no-such-route"];const METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];diff --git a/server/host/browser.ts b/server/host/browser.tsindex fe2273f209..d8a45660b6 100644--- a/server/host/browser.ts+++ b/server/host/browser.ts@@ -39,7 +39,7 @@ import type { BrowserSitesRef } from "../routes/browser-sites.ts";import { chromeLauncher } from "../browser/chrome/launcher.ts";import { LAUNCHER_SECCOMP_FD, browserLanguage, type LauncherBox } from "../browser/chrome/wrapper.ts";import type { HostKind } from "../browser/chrome/flags.ts";-import { browserEngineKind, browserPaneWanted, type BrowserEngineKind } from "../browser/config.ts";+import { browserEngineKind, browserPaneWanted, cloudDisplayWanted, type BrowserEngineKind } from "../browser/config.ts";import { parseSocks5Proxy } from "../browser/egress/policy.ts";import { ChromeEngine, chromeTarget, LiveRouter, profileKey, RuntimeRouter } from "../browser/engines.ts";import { CEILING_TICK_MS, ceilingLines, createBrowserCeiling } from "../browser/memory-ceiling.ts";@@ -177,6 +177,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {egressNotice: (key) => browserEgress.takeNotice(key),idleMs,language: deps.language,+ cloudDisplay: () => cloudDisplayWanted(cfg, host),held: (session) => !turnResources.free(`browser:${session}`),log: (line) => console.warn(line),});diff --git a/server/index.ts b/server/index.tsindex e77ffdf0ed..63cd4dd84b 100644--- a/server/index.ts+++ b/server/index.ts@@ -2387,7 +2387,7 @@ const emailIntegration = (bot: BotRecord, turn: { threadId: string; generation:let browserEngineInstall: Promise<void> | null = null;let browserEngineInstallError: string | null = null;-export function browserEngineSummary(): { kind: "engine" | "unavailable"; reason?: string; installable?: boolean; version?: string; chrome?: string; noChrome?: true; installing?: boolean; installError?: string; myChrome: boolean; proxyConfigured?: boolean; proxySaved?: boolean; myChromeOn?: { name: string; device: "PC" | "Mac" | "computer"; online: boolean }; myChromeLendable?: true; serverSites?: boolean; engine: "agent-browser" | "chrome" } {+export function browserEngineSummary(): { kind: "engine" | "unavailable"; reason?: string; installable?: boolean; version?: string; chrome?: string; noChrome?: true; installing?: boolean; installError?: string; myChrome: boolean; proxyConfigured?: boolean; proxySaved?: boolean; myChromeOn?: { name: string; device: "PC" | "Mac" | "computer"; online: boolean }; myChromeLendable?: true; serverSites?: boolean; engine: "agent-browser" | "chrome"; desktopView?: true } {const status = browserEngineStatus();const progress = { myChrome: myChromeAvailable(), ...lentChromeSummary(), ...(browserEngineInstall ? { installing: true } : {}), ...(browserEngineInstallError ? { installError: browserEngineInstallError } : {}) };return engineSummary(status.kind === "ready"diff --git a/server/request-auth.test.ts b/server/request-auth.test.tsindex 53750f66d5..69d5d45859 100644--- a/server/request-auth.test.ts+++ b/server/request-auth.test.ts@@ -441,7 +441,8 @@ describe("resolveRequestAuth", () => {expect(connectorRefresh.auth).toBeNull();expect(connectorRefresh.status).toBe(403);for (const path of ["/api/desktop-viewer/vps/bot-1", "/api/desktop-viewer/local/shared/websockify", "/api/webhooks/hook-1/address", "/api/setup-import/grok",- "/api/local-computer", "/api/bots/bot-1/local-computer", "/api/usb-phones/PHONE1/stream", "/api/usb-phones/emulator-5554/stream", "/api/usb-phones/SM.G991B/stream"]) {+ "/api/local-computer", "/api/bots/bot-1/local-computer", "/api/usb-phones/PHONE1/stream", "/api/usb-phones/emulator-5554/stream", "/api/usb-phones/SM.G991B/stream",+ "/api/bots/bot-1/browser/stream", "/api/bots/bot-1/browser/desktop"]) {expect(resolveRequestAuth(request({ host: "127.0.0.1:8799" }, "GET"), options(path)).status, path).toBe(403);expect(resolveRequestAuth(request({ host: "127.0.0.1:8799", "x-openmausbot-desktop-owner": "owner-token-123" }, "GET"), options(path)).auth?.kind, path).toBe("loopback");diff --git a/server/request-auth.ts b/server/request-auth.tsindex b976462311..2b67a311f6 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -624,7 +624,7 @@ function mutatingPublicRoute(method: string, path: string): boolean {// Hands out what a Grok Bot wrote about the person, from their Downloads folder.if (upper === "GET" && path === "/api/setup-import/grok") return true;// Drives a bot's browser: a WebSocket upgrade is a GET, but what it carries is input.- if (/^\/api\/bots\/[\w-]+\/browser\/stream$/.test(path)) return true;+ if (/^\/api\/bots\/[\w-]+\/browser\/(?:stream|desktop)$/.test(path)) return true;// Shows the bots' USB phone: a WebSocket upgrade is a GET that a local process could send without an Origin.if (/^\/api\/usb-phones\/[^/]+\/stream$/.test(path)) return true;if (["GET", "HEAD", "OPTIONS"].includes(upper)) return false;diff --git a/server/routes/browser-viewers.test.ts b/server/routes/browser-viewers.test.tsindex 67d143909f..8e4b7df0a2 100644--- a/server/routes/browser-viewers.test.ts+++ b/server/routes/browser-viewers.test.ts@@ -16,6 +16,7 @@ import type { Download } from "../browser/cdp/downloads.ts";import type { BrowserService } from "../browser/service.ts";import type { Viewer, ViewerOptions, ViewerOutput } from "../browser/viewers/core.ts";import { STREAM_CLOSE, StreamV2 } from "../browser/viewers/stream-v2.ts";+import { DESKTOP_CLOSE, DesktopViews, type DesktopRequest } from "../browser/desktop/views.ts";import { json, readBody } from "../harness/http.ts";import type { RequestAuth } from "../request-auth.ts";import { removeTempDir } from "../testing/cleanup.ts";@@ -64,6 +65,8 @@ interface Fixture {/** The last v1 view's check that it still shows the browser it opened on. */isCurrent: () => boolean;dataDir: string;+ /** The desktop views opened, as the route asked for them. */+ desktops: Array<Omit<DesktopRequest, "target" | "req" | "socket" | "head">>;}const servers: Server[] = [];@@ -74,7 +77,8 @@ afterEach(async () => {for (const folder of folders.splice(0)) await removeTempDir(folder);});-async function serve({ attach, current = () => true, download, audience = () => "team", action = async () => ({ ok: true }), inputLog }: {+async function serve({ attach, current = () => true, download, audience = () => "team", action = async () => ({ ok: true }), inputLog, desktopView = true }: {+ desktopView?: boolean;attach?: (options: ViewerOptions, push: (output: ViewerOutput) => void) => Promise<Viewer>;current?: () => boolean;download?: (id: string) => Download | undefined;@@ -82,7 +86,7 @@ async function serve({ attach, current = () => true, download, audience = () =>action?: (body: unknown) => Promise<unknown>;inputLog?: BrowserInputLog;} = {}): Promise<Fixture> {- const fixture = { origin: "", attachments: [], inputs: [], answers: [], pickerChecks: 0, resumes: [], people: [], sizes: [], opened: [], checked: [], dataDir: mkdtempSync(join(tmpdir(), "omb-browser-viewers-")) } as unknown as Fixture;+ const fixture = { origin: "", attachments: [], inputs: [], answers: [], pickerChecks: 0, resumes: [], people: [], sizes: [], opened: [], checked: [], desktops: [], dataDir: mkdtempSync(join(tmpdir(), "omb-browser-viewers-")) } as unknown as Fixture;folders.push(fixture.dataDir);const viewer = { id: "viewer", input: async (message: unknown) => { fixture.inputs.push(message); }, close: async () => {} } as unknown as Viewer;const service = {@@ -94,6 +98,7 @@ async function serve({ attach, current = () => true, download, audience = () =>} as unknown as BrowserService;const stream = new StreamV2({ service });fixture.stream = stream;+ const desktops = new DesktopViews({ desktop: async () => "pictures" });const upgrades = createUpgrades();const deps: BrowserViewerRouteDeps = {upgrades,@@ -112,6 +117,13 @@ async function serve({ attach, current = () => true, download, audience = () =>stream.open({ ...request, target: { session, key: "bot:pepper" } });return true;},+ desktop: ({ session, spec: _spec, ...request }) => {+ if (!desktopView) return false;+ const { req: _req, socket: _socket, head: _head, ...asked } = request;+ fixture.desktops.push(asked);+ desktops.open({ ...request, target: { session, key: "bot:pepper" } });+ return true;+ },fileChooserOffered: (_browser, _owner, chooser) => {fixture.pickerChecks++;return chooser === "chooser-1";@@ -222,6 +234,15 @@ describe("the v2 stream", () => {}]);});+ it("opens a view without pictures for a panel that shows the browser's window on a remote desktop", async () => {+ const fixture = await serve();+ const socket = new WebSocket(`ws://${fixture.origin}/api/bots/pepper/browser/stream?frames=0`);+ await new Promise((resolve) => socket.addEventListener("open", resolve));+ await until(() => fixture.attachments.length === 1);+ expect(fixture.attachments[0]).toMatchObject({ frames: false });+ socket.close();+ });+it("refuses an upgrade from another origin, and a plain request, before attaching a viewer", async () => {const fixture = await serve();const refused = await new Promise<number>((resolve) => {@@ -502,3 +523,39 @@ describe("whose browser a view shows on a Team Cloud", () => {expect(fixture.opened).toEqual(["member:p_ada", "member:p_ada"]);});});++describe("the desktop view", () => {+ const closeCode = (url: string, headers?: Record<string, string>) => new Promise<number>((resolve) => {+ const socket = new WebSocket(url, headers ? { headers } as unknown as string[] : undefined);+ socket.addEventListener("close", (event) => resolve(event.code));+ });++ it("opens for the person allowed to see the browser, read-only when asked", async () => {+ const fixture = await serve();+ expect(await closeCode(`ws://${fixture.origin}/api/bots/pepper/browser/desktop`)).toBe(DESKTOP_CLOSE.pictures);+ expect(await closeCode(`ws://${fixture.origin}/api/bots/pepper/browser/desktop?interactive=false&threadId=t1`)).toBe(DESKTOP_CLOSE.pictures);+ expect(fixture.desktops.map(({ owner, person, canOperate, botId }) => ({ owner, person, canOperate, botId }))).toEqual([+ { owner: "local-owner", person: "local-owner", canOperate: true, botId: "pepper" },+ { owner: "local-owner", person: "local-owner", canOperate: false, botId: "pepper" },+ ]);+ expect(fixture.desktops[0]!.isCurrent()).toBe(true);+ });++ it("refuses another origin, a plain request, a hidden conversation and a stale view before opening", async () => {+ const hidden = await serve({ audience: () => null });+ expect(await closeCode(`ws://${hidden.origin}/api/bots/pepper/browser/desktop`)).toBe(1006);+ expect(hidden.desktops).toEqual([]);+ const fixture = await serve();+ expect(await closeCode(`ws://${fixture.origin}/api/bots/pepper/browser/desktop`, { origin: "https://attacker.invalid" })).toBe(1006);+ expect((await fetch(`http://${fixture.origin}/api/bots/pepper/browser/desktop`)).status).toBe(426);+ const stale = await serve({ current: () => false });+ expect(await closeCode(`ws://${stale.origin}/api/bots/pepper/browser/desktop`)).toBe(1006);+ expect([fixture.desktops, stale.desktops]).toEqual([[], []]);+ });++ it("is refused where the browser has no desktop view", async () => {+ const fixture = await serve({ desktopView: false });+ expect(await closeCode(`ws://${fixture.origin}/api/bots/pepper/browser/desktop`)).toBe(1006);+ expect(fixture.desktops).toEqual([]);+ });+});diff --git a/server/routes/browser-viewers.ts b/server/routes/browser-viewers.tsindex 3c748a8da8..b08542311b 100644--- a/server/routes/browser-viewers.ts+++ b/server/routes/browser-viewers.ts@@ -1,8 +1,9 @@// People's views of a bot's browser. v1 (GET …/browser/live as server-sent events, POST …/browser/action) is what the// phone apps speak, and its contract is frozen. v2 (GET …/browser/stream, a WebSocket) is the desktop panel's and the// web UI's, on the new engine only: a page's file picker is answered by POST …/browser/upload and a finished download-// is fetched from GET …/browser/download/:id. Never mix login frames into the general events feed, which every device-// reads.+// is fetched from GET …/browser/download/:id. GET …/browser/desktop (a WebSocket) is the remote-desktop view of a browser+// whose window is on a private display, beside the v2 stream. Never mix login frames into the general events feed, which+// every device reads.import { createReadStream, rmSync } from "node:fs";import type { IncomingMessage } from "node:http";import { dirname, join } from "node:path";@@ -21,7 +22,7 @@ import { PASS, type RouteHandler } from "./table.ts";import type { Upgrades } from "./upgrades.ts";const LIVE = /^\/api\/bots\/([\w-]+)\/browser\/(live|action)$/;-const STREAM = /^\/api\/bots\/([\w-]+)\/browser\/stream$/;+const STREAM = /^\/api\/bots\/([\w-]+)\/browser\/(stream|desktop)$/;const UPLOAD = /^\/api\/bots\/([\w-]+)\/browser\/upload$/;const DOWNLOAD = /^\/api\/bots\/([\w-]+)\/browser\/download\/([\w-]{1,64})$/;const CHOOSER = /^[\w-]{1,64}$/;@@ -33,7 +34,7 @@ type Failure = { status: number; error: string };export interface BrowserViewerRouteDeps {upgrades: Upgrades;- viewers: Pick<LiveRouter, "open" | "action" | "stream" | "fileChooserOffered" | "answerFileChooser" | "download">;+ viewers: Pick<LiveRouter, "open" | "action" | "stream" | "desktop" | "fileChooserOffered" | "answerFileChooser" | "download">;/** Who is watching, as a hold of the browser knows them: every view and device of one person shares their hold. */person(auth: RequestAuth): string;/** Whose browser of the bot this person's view shows (`threadId` names the conversation they look at); null when@@ -176,6 +177,16 @@ export function createBrowserViewerRoutes(deps: BrowserViewerRouteDeps): RouteHaif (pending.socket.destroyed) return;if (!isCurrent()) return json(res, 409, { error: "This browser session changed. Reopen the browser panel." });pending.release();+ if (stream[2] === "desktop") {+ const opened = deps.viewers.desktop({+ session: browser.session, spec: browser.spec, botId: browser.botId, owner, person,+ canOperate: url.searchParams.get("interactive") !== "false",+ req, socket: pending.socket, head: pending.head, isCurrent,+ });+ if (!opened) return json(res, 409, { error: "This browser has no desktop view." });+ res.detachSocket(pending.socket);+ return;+ }const opened = deps.viewers.stream({session: browser.session, spec: browser.spec, botId: browser.botId, owner, person,canOperate: url.searchParams.get("interactive") !== "false",