Skip to content

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

Browser: a real local pane for the desktop app (off by default) (#6886)

Milind Sonifa280ddaef61
diff --git a/electron/browser-pane-main.mjs b/electron/browser-pane-main.mjs
new file mode 100644
index 0000000000..56664b235d
--- /dev/null
+++ b/electron/browser-pane-main.mjs
@@ -0,0 +1,411 @@
+// The bots' browsers as native views in the app window: one WebContentsView per tab on the profile's own partition,
+// its debugger relayed to the app's own server, shown over the Browser panel's rectangle when the panel asks.
+// Security: views are created and their debuggers attached only here, never for a webContents the renderer names;
+// the renderer only says which bot's panel shows where.
+import { randomUUID } from "node:crypto";
+import path from "node:path";
+
+import desktopWorkspace from "./desktop-workspace.cjs";
+import { PANE_MESSAGE, PANE_PARTITION, PANE_TABS_PER_BROWSER, paneMessageToMain, paneUserAgent } from "./browser-pane-wire.mjs";
+
+const { normalizeDesktopWorkspaceBounds } = desktopWorkspace;
+const PERSON_INPUT = new Set(["mouseDown", "keyDown", "rawKeyDown", "char", "mouseWheel", "gestureScrollBegin", "touchStart"]);
+const PING_MS = 250;
+/** Input events this soon after the bot's own input count as the bot's, should Electron report debugger input too. */
+const BOT_INPUT_ECHO_MS = 150;
+const RESOLVE_MS = 5_000;
+const CAPTURE_MS = 10_000;
+const HIDDEN_SIZE = { width: 1280, height: 800 };
+/** Granted as a normal profile has them; everything else is refused without a prompt. */
+const GRANTED = new Set(["clipboard-sanitized-write", "fullscreen", "pointerLock"]);
+const BOT = /^[\w.-]{1,128}$/;
+const PROFILE = /^[\w.:-]{1,128}$/;
+
+const hostOf = (url) => { try { return new URL(url).hostname; } catch { return ""; } };
+const isObject = (value) => Object.prototype.toString.call(value) === "[object Object]";
+const NO_PANEL = Object.freeze({ botId: null, threadId: null, profile: null, wanted: false, bounds: null, browser: null });
+const samePanel = (a, b) => a.botId === b.botId && a.threadId === b.threadId && a.profile === b.profile;
+
+/**
+ * `createView(options)`: a WebContentsView. `fromPartition(name)`: Electron's session. `owner()`: the app window or null.
+ * `chromeVersion`: process.versions.chrome.
+ */
+export function createBrowserPanes({ createView, fromPartition, owner, chromeVersion, log = () => {}, now = Date.now, captureMs = CAPTURE_MS }) {
+ const browsers = new Map();
+ const configured = new Set();
+ const pings = new Map();
+ const resolving = new Map();
+ const watched = new WeakSet();
+ let server = null;
+ let tabCount = 0;
+ let requests = 0;
+ let asks = 0;
+ let panel = NO_PANEL;
+
+ const post = (message) => {
+ try {
+ server?.postMessage({ type: PANE_MESSAGE, ...message });
+ } catch (error) {
+ log(`browser pane: could not reach the server: ${error?.message ?? error}`);
+ }
+ };
+
+ function tabOf(contents) {
+ for (const [key, browser] of browsers) {
+ for (const entry of browser.tabs.values()) if (entry.contents === contents) return { key, browser, entry };
+ }
+ return null;
+ }
+
+ /** Every download is saved into the profile's download folder, never through a Save dialog, and reported. */
+ function download(item, contents) {
+ const found = tabOf(contents);
+ if (!found) {
+ item.cancel();
+ return;
+ }
+ const { key, browser, entry } = found;
+ const guid = randomUUID();
+ const file = path.join(browser.downloads, guid);
+ item.setSavePath(file);
+ browser.items.set(guid, item);
+ post({ op: "download", browser: key, tab: entry.tab, guid, state: "begin", url: item.getURL(), name: item.getFilename() });
+ item.on("updated", () => {
+ post({ op: "download", browser: key, tab: entry.tab, guid, state: "inProgress", received: item.getReceivedBytes(), total: item.getTotalBytes() });
+ });
+ item.once("done", (_event, state) => {
+ browser.items.delete(guid);
+ const completed = state === "completed";
+ post({ op: "download", browser: key, tab: entry.tab, guid, state: completed ? "completed" : "canceled", received: item.getReceivedBytes(), total: item.getTotalBytes(), ...(completed ? { path: file } : {}) });
+ });
+ }
+
+ function configure(partition) {
+ const session = fromPartition(partition);
+ if (configured.has(partition)) return session;
+ configured.add(partition);
+ const electronAgent = session.getUserAgent();
+ const agent = paneUserAgent(electronAgent);
+ session.setUserAgent(agent);
+ session.webRequest.onBeforeSendHeaders((details, callback) => {
+ const host = hostOf(details.url);
+ const wanted = host ? paneUserAgent(electronAgent, host) : agent;
+ callback({ requestHeaders: wanted === agent ? details.requestHeaders : { ...details.requestHeaders, "User-Agent": wanted } });
+ });
+ session.setPermissionRequestHandler((_contents, permission, callback) => callback(GRANTED.has(permission)));
+ session.setPermissionCheckHandler((_contents, permission) => GRANTED.has(permission));
+ session.on("will-download", (_event, item, contents) => download(item, contents));
+ return session;
+ }
+
+ function size() {
+ return panel.bounds ? { width: panel.bounds.width, height: panel.bounds.height } : HIDDEN_SIZE;
+ }
+
+ function layout() {
+ const win = owner();
+ for (const [key, browser] of browsers) {
+ for (const [tab, entry] of browser.tabs) {
+ const visible = Boolean(panel.wanted && panel.bounds && panel.browser === key && browser.active === tab);
+ try {
+ if (visible) {
+ entry.view.setBounds(panel.bounds);
+ if (!entry.visible && win && !win.isDestroyed()) win.contentView.addChildView(entry.view);
+ }
+ entry.view.setVisible(visible);
+ } catch (error) {
+ log(`browser pane: could not place ${tab}: ${error?.message ?? error}`);
+ }
+ entry.visible = visible;
+ }
+ }
+ }
+
+ /**
+ * Known open risk: Chromium draws nothing for a view it does not show, and a screenshot of an undrawn page waits for a
+ * frame that never comes. A hidden pane is shown for the capture with all but one pixel past the window's corner.
+ */
+ function paintHold(entry) {
+ const win = owner();
+ if (entry.visible || !win || win.isDestroyed()) return () => {};
+ const [width, height] = win.getContentSize();
+ const page = size();
+ entry.view.setBounds({ x: Math.max(0, width - 1), y: Math.max(0, height - 1), ...page });
+ entry.view.setVisible(true);
+ return () => {
+ if (entry.visible) return;
+ entry.view.setVisible(false);
+ entry.view.setBounds({ x: 0, y: 0, ...page });
+ };
+ }
+
+ function ping(key, entry) {
+ if (entry.botInputs > 0 || now() - entry.botInputAt < BOT_INPUT_ECHO_MS) return;
+ const last = pings.get(key);
+ if (last !== undefined && last.tab === entry.tab && now() - last.at < PING_MS) return;
+ pings.set(key, { tab: entry.tab, at: now() });
+ post({ op: "input", browser: key, tab: entry.tab });
+ }
+
+ async function targetOf(contents) {
+ const { frameTree } = await contents.debugger.sendCommand("Page.getFrameTree");
+ return String(frameTree.frame.id);
+ }
+
+ function info(key, entry) {
+ if (!entry.target) return;
+ post({ op: "tab", browser: key, tab: entry.tab, target: entry.target, url: entry.contents.getURL() || "about:blank", title: entry.contents.getTitle(), ...(entry.opener ? { opener: entry.opener } : {}) });
+ }
+
+ /** Why no tab can open in this browser now, or null. */
+ function tabRefusal(key) {
+ const browser = browsers.get(key);
+ const win = owner();
+ if (!browser) return "Target closed";
+ if (!win || win.isDestroyed()) return "The app window is closed.";
+ if (browser.tabs.size >= PANE_TABS_PER_BROWSER) return `This browser already has ${PANE_TABS_PER_BROWSER} tabs open. Close one before opening another.`;
+ return null;
+ }
+
+ function createTab(key, { background = false, adopt, opener } = {}) {
+ const refusal = tabRefusal(key);
+ if (refusal) throw new Error(refusal);
+ const browser = browsers.get(key);
+ const win = owner();
+ const view = createView({
+ webPreferences: { partition: browser.partition, sandbox: true, contextIsolation: true, nodeIntegration: false, webviewTag: false, backgroundThrottling: false, safeDialogs: true },
+ ...(adopt ? { webContents: adopt } : {}),
+ });
+ const contents = view.webContents;
+ contents.setWebRTCIPHandlingPolicy("disable_non_proxied_udp");
+ // DevTools would take the debugger from the bot: one client per webContents.
+ contents.on("devtools-opened", () => contents.closeDevTools());
+ const entry = { tab: `p${++tabCount}`, view, contents, window: win, target: null, visible: false, botInputs: 0, botInputAt: -Infinity, ...(opener ? { opener } : {}) };
+ contents.debugger.attach("1.3");
+ browser.tabs.set(entry.tab, entry);
+ contents.debugger.on("message", (_event, method, params, sessionId) => {
+ post({ op: "event", browser: key, tab: entry.tab, method, params: isObject(params) ? params : {}, ...(sessionId ? { session: sessionId } : {}) });
+ });
+ contents.debugger.on("detach", () => removeTab(key, entry.tab));
+ contents.on("render-process-gone", () => removeTab(key, entry.tab, true));
+ contents.on("destroyed", () => removeTab(key, entry.tab));
+ for (const event of ["did-navigate", "did-navigate-in-page", "page-title-updated"]) contents.on(event, () => info(key, entry));
+ contents.on("input-event", (_event, input) => { if (PERSON_INPUT.has(input?.type)) ping(key, entry); });
+ contents.setWindowOpenHandler(() => (tabRefusal(key) ? { action: "deny" } : {
+ action: "allow",
+ // OAuth pop-ups answer their opener, so the popup is the page's own child, made a tab here.
+ createWindow: (options) => {
+ const popup = createTab(key, { adopt: options?.webContents, opener: entry.tab });
+ void targetOf(popup.contents).then((target) => { popup.target = target; info(key, popup); }, () => removeTab(key, popup.tab));
+ return popup.contents;
+ },
+ }));
+ view.setBounds({ x: 0, y: 0, ...size() });
+ view.setVisible(false);
+ win.contentView.addChildView(view);
+ if (!background) browser.active = entry.tab;
+ layout();
+ return entry;
+ }
+
+ function removeTab(key, tab, crashed = false) {
+ const browser = browsers.get(key);
+ const entry = browser?.tabs.get(tab);
+ if (!entry) return;
+ browser.tabs.delete(tab);
+ if (browser.active === tab) browser.active = [...browser.tabs.keys()].at(-1) ?? null;
+ try { entry.view.setVisible(false); } catch {}
+ try { if (!entry.window.isDestroyed()) entry.window.contentView.removeChildView(entry.view); } catch {}
+ try { if (entry.contents.debugger.isAttached()) entry.contents.debugger.detach(); } catch {}
+ try { if (!entry.contents.isDestroyed()) entry.contents.close({ waitForBeforeUnload: false }); } catch {}
+ post({ op: "tab-gone", browser: key, tab, ...(crashed ? { crashed: true } : {}) });
+ layout();
+ }
+
+ function closeBrowser(key, announce = true) {
+ const browser = browsers.get(key);
+ if (!browser) return;
+ for (const tab of browser.tabs.keys()) removeTab(key, tab);
+ for (const item of browser.items.values()) {
+ try { item.cancel(); } catch {}
+ }
+ browsers.delete(key);
+ pings.delete(key);
+ if (announce) post({ op: "closed", browser: key, reason: "closed by the app" });
+ }
+
+ async function open(message) {
+ const win = owner();
+ if (!win || win.isDestroyed()) {
+ post({ op: "failed", browser: message.browser, error: "The app window is closed.", reason: "no-window" });
+ return;
+ }
+ try {
+ closeBrowser(message.browser, false);
+ const session = configure(message.partition);
+ // Security: the panes reach the network only through the profile's egress gate, as a launched Chrome does.
+ await session.setProxy({ proxyRules: `socks5://127.0.0.1:${message.egress}`, proxyBypassRules: "<-loopback>" });
+ browsers.set(message.browser, { partition: message.partition, downloads: message.downloads, tabs: new Map(), items: new Map(), active: null });
+ post({ op: "opened", browser: message.browser, version: chromeVersion, userAgent: session.getUserAgent() });
+ // The profile a panel shows may have just changed.
+ if (panel.botId) void ask();
+ layout();
+ } catch (error) {
+ post({ op: "failed", browser: message.browser, error: error?.message ?? String(error) });
+ }
+ }
+
+ /** A renderer that reloads or crashes never hides what its panel showed. */
+ function watchRenderer(win) {
+ if (watched.has(win.webContents)) return;
+ watched.add(win.webContents);
+ const hide = () => {
+ panel = NO_PANEL;
+ layout();
+ };
+ win.webContents.on("did-start-navigation", (_event, _url, isInPlace, isMainFrame) => { if (isMainFrame && !isInPlace) hide(); });
+ win.webContents.on("render-process-gone", hide);
+ }
+
+ async function create(message) {
+ try {
+ const entry = createTab(message.browser, { background: message.background === true });
+ entry.target = await targetOf(entry.contents);
+ if (message.url !== "about:blank") void entry.contents.loadURL(message.url).catch(() => undefined);
+ post({ op: "created", browser: message.browser, req: message.req, tab: entry.tab, target: entry.target, url: message.url, title: "" });
+ } catch (error) {
+ post({ op: "answer", browser: message.browser, req: message.req, error: { message: error?.message ?? String(error) } });
+ }
+ }
+
+ async function command(message) {
+ const entry = browsers.get(message.browser)?.tabs.get(message.tab);
+ if (!entry) {
+ post({ op: "answer", browser: message.browser, req: message.req, error: { message: "Target closed" } });
+ return;
+ }
+ const capture = message.method === "Page.captureScreenshot" && !message.session;
+ const input = message.method.startsWith("Input.");
+ const release = capture ? paintHold(entry) : () => {};
+ if (input) entry.botInputs++;
+ let timer;
+ try {
+ const sent = entry.contents.debugger.sendCommand(message.method, message.params, message.session);
+ // Chromium keeps an undrawn capture pending for good: the bot hears why instead of waiting.
+ const result = capture ? await Promise.race([sent, new Promise((_resolve, reject) => {
+ timer = setTimeout(() => reject(new Error(`The page did not draw within ${captureMs / 1000} s, so no screenshot was taken.`)), captureMs);
+ })]) : await sent;
+ post({ op: "answer", browser: message.browser, req: message.req, result: isObject(result) ? result : {} });
+ } catch (error) {
+ post({ op: "answer", browser: message.browser, req: message.req, error: { message: error?.message ?? String(error), ...(typeof error?.code === "number" ? { code: error.code } : {}) } });
+ } finally {
+ clearTimeout(timer);
+ if (input) {
+ entry.botInputs--;
+ entry.botInputAt = now();
+ }
+ release();
+ }
+ }
+
+ function handle(message) {
+ switch (message.op) {
+ case "hello":
+ post({ op: "hello" });
+ return;
+ case "open": return void open(message);
+ case "create": return void create(message);
+ case "cdp": return void command(message);
+ case "front": {
+ const browser = browsers.get(message.browser);
+ if (browser?.tabs.has(message.tab)) browser.active = message.tab;
+ layout();
+ return;
+ }
+ case "close-tab": return removeTab(message.browser, message.tab);
+ case "close": return closeBrowser(message.browser);
+ case "cancel-download": {
+ const item = browsers.get(message.browser)?.items.get(message.guid);
+ try { item?.cancel(); } catch {}
+ return;
+ }
+ case "erase": {
+ if (!PANE_PARTITION.test(message.partition)) return;
+ const session = fromPartition(message.partition);
+ void Promise.all([session.clearStorageData(), session.clearCache()]).catch((error) => log(`browser pane: could not erase a profile: ${error?.message ?? error}`));
+ return;
+ }
+ case "resolved": {
+ const resolve = resolving.get(message.req);
+ resolving.delete(message.req);
+ resolve?.(message.browser);
+ return;
+ }
+ }
+ }
+
+ function resolveBrowser(botId, threadId) {
+ if (!server) return Promise.resolve(null);
+ const req = ++requests;
+ return new Promise((resolve) => {
+ const timer = setTimeout(() => { resolving.delete(req); resolve(null); }, RESOLVE_MS);
+ resolving.set(req, (browser) => { clearTimeout(timer); resolve(browser); });
+ post({ op: "which", req, botId, threadId });
+ });
+ }
+
+ /** Asks the server which browser the panel shows. No answer is kept as an answer: the next show or open asks again. */
+ async function ask() {
+ const asked = panel;
+ const generation = ++asks;
+ const browser = await resolveBrowser(asked.botId, asked.threadId);
+ if (!samePanel(asked, panel) || generation !== asks) return;
+ panel = { ...panel, browser };
+ layout();
+ }
+
+ return {
+ /** A new server child: the panes the old one drove are gone with it. */
+ attach(proc) {
+ for (const key of browsers.keys()) closeBrowser(key, false);
+ for (const resolve of resolving.values()) resolve(null);
+ resolving.clear();
+ panel = NO_PANEL;
+ server = proc;
+ post({ op: "hello" });
+ },
+
+ /** True when the message was a pane message from the current server. */
+ receive(proc, raw) {
+ if (!isObject(raw) || raw.type !== PANE_MESSAGE) return false;
+ if (proc !== server) return true;
+ const message = paneMessageToMain(raw);
+ if (!message) {
+ log("browser pane: refused a malformed message from the server");
+ return true;
+ }
+ handle(message);
+ return true;
+ },
+
+ /** The Browser panel of `botId` (in `threadId`, on browser profile `profile`) is at `bounds`, shown or not. */
+ async show(input) {
+ if (!isObject(input) || typeof input.botId !== "string" || !BOT.test(input.botId)) throw new Error("Browser pane input is invalid");
+ const threadId = typeof input.threadId === "string" && BOT.test(input.threadId) ? input.threadId : null;
+ const profile = typeof input.profile === "string" && PROFILE.test(input.profile) ? input.profile : null;
+ const win = owner();
+ if (win && !win.isDestroyed()) watchRenderer(win);
+ const wanted = input.visible === true && Boolean(win) && !win.isDestroyed();
+ const bounds = wanted ? normalizeDesktopWorkspaceBounds(input.bounds, win.getContentSize()) : panel.bounds;
+ const next = { botId: input.botId, threadId, profile };
+ panel = samePanel(next, panel) ? { ...panel, wanted, bounds } : { ...next, wanted, bounds, browser: null };
+ layout();
+ if (panel.browser === null) await ask();
+ return { shown: Boolean(panel.wanted && panel.browser && browsers.get(panel.browser)?.active) };
+ },
+
+ closeAll() {
+ for (const key of browsers.keys()) closeBrowser(key);
+ },
+ };
+}
diff --git a/electron/browser-pane-main.node-test.mjs b/electron/browser-pane-main.node-test.mjs
new file mode 100644
index 0000000000..939c036a8e
--- /dev/null
+++ b/electron/browser-pane-main.node-test.mjs
@@ -0,0 +1,416 @@
+import assert from "node:assert/strict";
+import { EventEmitter } from "node:events";
+import path from "node:path";
+import test from "node:test";
+
+import { createBrowserPanes } from "./browser-pane-main.mjs";
+import { paneUserAgent } from "./browser-pane-wire.mjs";
+
+const PARTITION = "persist:omb-pane-0123456789abcdef01234567";
+const MSG = "openmausbot:browser-pane";
+const DOWNLOADS = "/tmp/omb-pane-downloads";
+const tick = () => new Promise((resolve) => setImmediate(resolve));
+
+function fakeElectron() {
+ const views = [];
+ const sessions = new Map();
+ const window = {
+ webContents: new EventEmitter(),
+ destroyed: false,
+ children: [],
+ isDestroyed() { return this.destroyed; },
+ getContentSize: () => [1400, 900],
+ contentView: {
+ addChildView(view) { window.children = window.children.filter((child) => child !== view).concat(view); },
+ removeChildView(view) { window.children = window.children.filter((child) => child !== view); },
+ },
+ };
+ const createView = (options) => {
+ const debuggerEvents = new EventEmitter();
+ const sent = [];
+ const contents = Object.assign(options.webContents ?? new EventEmitter(), {
+ url: "about:blank",
+ loaded: [],
+ closed: false,
+ openHandler: null,
+ webrtc: null,
+ setWebRTCIPHandlingPolicy(policy) { this.webrtc = policy; },
+ getURL() { return this.url; },
+ getTitle: () => "",
+ loadURL(url) { this.loaded.push(url); return Promise.resolve(); },
+ setWindowOpenHandler(handler) { this.openHandler = handler; },
+ isDestroyed() { return this.closed; },
+ close() { this.closed = true; },
+ devtoolsClosed: 0,
+ closeDevTools() { this.devtoolsClosed++; },
+ });
+ let attached = false;
+ contents.debugger = Object.assign(debuggerEvents, {
+ sent,
+ attach(version) { assert.equal(version, "1.3"); attached = true; },
+ detach() { attached = false; },
+ isAttached: () => attached,
+ async sendCommand(method, params, sessionId) {
+ sent.push({ method, params, sessionId });
+ if (method === "Page.getFrameTree") return { frameTree: { frame: { id: `FRAME${views.length}` } } };
+ if (method === "DOM.fail") throw Object.assign(new Error("No node with given id found"), { code: -32000 });
+ if (method === "Page.captureScreenshot") return contents.neverDraws ? new Promise(() => {}) : { data: "x", visibleDuring: view.visible };
+ return {};
+ },
+ });
+ const view = { options, webContents: contents, bounds: null, visible: null, setBounds(bounds) { this.bounds = bounds; }, setVisible(visible) { this.visible = visible; } };
+ views.push(view);
+ return view;
+ };
+ const fromPartition = (name) => {
+ if (!sessions.has(name)) {
+ sessions.set(name, Object.assign(new EventEmitter(), {
+ agent: "Mozilla/5.0 (Macintosh) AppleWebKit/537.36 (KHTML, like Gecko) OpenMausBot/0.1.175 Chrome/146.0.7680.0 Electron/43.7.9 Safari/537.36",
+ erased: 0,
+ getUserAgent() { return this.agent; },
+ setUserAgent(agent) { this.agent = agent; },
+ setPermissionRequestHandler(handler) { this.request = handler; },
+ setPermissionCheckHandler(handler) { this.check = handler; },
+ async clearStorageData() { this.erased++; },
+ async clearCache() {},
+ async setProxy(config) { this.proxy = config; },
+ webRequest: { onBeforeSendHeaders(handler) { sessions.get(name).headers = handler; } },
+ }));
+ }
+ return sessions.get(name);
+ };
+ return { views, sessions, window, createView, fromPartition };
+}
+
+function setup({ captureMs } = {}) {
+ const electron = fakeElectron();
+ let clock = 0;
+ const panes = createBrowserPanes({ createView: electron.createView, fromPartition: electron.fromPartition, owner: () => (electron.window.destroyed ? null : electron.window), chromeVersion: "146.0.7680.0", now: () => clock, ...(captureMs ? { captureMs } : {}) });
+ const posted = [];
+ const server = { postMessage: (message) => posted.push(message) };
+ panes.attach(server);
+ const send = (message) => panes.receive(server, { type: MSG, ...message });
+ const last = (op) => posted.filter((message) => message.op === op).at(-1);
+ return { electron, panes, server, posted, send, last, advance: (ms) => { clock += ms; } };
+}
+
+test("says hello to the server it starts, again when that server asks, and ignores any other process", () => {
+ const { panes, posted, send } = setup();
+ assert.deepEqual(posted[0], { type: MSG, op: "hello" });
+ send({ op: "hello" });
+ assert.deepEqual(posted[1], { type: MSG, op: "hello" });
+ posted.length = 1;
+ assert.equal(panes.receive({ postMessage() {} }, { type: MSG, op: "open", browser: "bot:a", partition: PARTITION }), true);
+ assert.equal(posted.length, 1);
+ assert.equal(panes.receive({}, { type: "something-else" }), false);
+});
+
+test("opens a profile on its partition, behind its egress gate, with Electron's and the app's tokens out of the user agent", async () => {
+ const { send, last, electron } = setup();
+ send({ op: "open", browser: "bot:a", partition: PARTITION, egress: 41000, downloads: DOWNLOADS });
+ await tick();
+ const opened = last("opened");
+ assert.equal(opened.version, "146.0.7680.0");
+ assert.equal(opened.userAgent, "Mozilla/5.0 (Macintosh) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.7680.0 Safari/537.36");
+ const session = electron.sessions.get(PARTITION);
+ assert.deepEqual(session.proxy, { proxyRules: "socks5://127.0.0.1:41000", proxyBypassRules: "<-loopback>" });
+ let granted = null;
+ session.request(null, "geolocation", (value) => { granted = value; });
+ assert.equal(granted, false);
+ assert.equal(session.check(null, "fullscreen"), true);
+ assert.equal(session.check(null, "notifications"), false);
+ let sent = null;
+ session.headers({ url: "https://accounts.example/", requestHeaders: { "User-Agent": opened.userAgent, Accept: "*/*" } }, (answer) => { sent = answer; });
+ assert.deepEqual(sent.requestHeaders, { "User-Agent": opened.userAgent, Accept: "*/*" });
+});
+
+test("can give one host Electron's own user agent, and every other the stripped one", () => {
+ const electronAgent = "Mozilla/5.0 Chrome/146.0.7680.0 Electron/43.7.9 OpenMausBot/0.1.175 Safari/537.36";
+ const hosts = new Map([["accounts.example", "electron"]]);
+ assert.equal(paneUserAgent(electronAgent, "Accounts.Example", hosts), electronAgent);
+ assert.equal(paneUserAgent(electronAgent, "example.com", hosts), "Mozilla/5.0 Chrome/146.0.7680.0 Safari/537.36");
+ assert.equal(paneUserAgent(electronAgent), "Mozilla/5.0 Chrome/146.0.7680.0 Safari/537.36");
+});
+
+test("refuses a partition outside the pane pattern, and a profile without an egress gate", async () => {
+ const { send, posted, electron } = setup();
+ send({ op: "open", browser: "bot:a", partition: "persist:openmausbot-app", egress: 41000, downloads: DOWNLOADS });
+ send({ op: "open", browser: "bot:a", partition: PARTITION });
+ await tick();
+ assert.equal(posted.length, 1);
+ assert.equal(electron.sessions.size, 0);
+});
+
+test("creates a sandboxed view per tab, attaches its debugger and relays its CDP both ways", async () => {
+ const { send, last, electron, posted } = setup();
+ send({ op: "open", browser: "bot:a", partition: PARTITION, egress: 41000, downloads: DOWNLOADS });
+ await tick();
+ send({ op: "create", browser: "bot:a", req: 1, url: "https://example.com/" });
+ await tick();
+ const created = last("created");
+ assert.deepEqual({ tab: created.tab, target: created.target, req: created.req }, { tab: "p1", target: "FRAME1", req: 1 });
+ const [view] = electron.views;
+ assert.equal(view.options.webPreferences.partition, PARTITION);
+ assert.equal(view.options.webPreferences.sandbox, true);
+ assert.equal(view.options.webPreferences.nodeIntegration, false);
+ view.webContents.emit("devtools-opened");
+ assert.equal(view.webContents.devtoolsClosed, 1);
+ assert.deepEqual(view.webContents.loaded, ["https://example.com/"]);
+ assert.equal(view.webContents.webrtc, "disable_non_proxied_udp");
+ assert.deepEqual(view.bounds, { x: 0, y: 0, width: 1280, height: 800 });
+ assert.equal(view.visible, false);
+
+ send({ op: "cdp", browser: "bot:a", req: 2, tab: "p1", method: "Runtime.evaluate", params: { expression: "1" }, session: "CHILD1" });
+ await tick();
+ assert.deepEqual(view.webContents.debugger.sent.at(-1), { method: "Runtime.evaluate", params: { expression: "1" }, sessionId: "CHILD1" });
+ assert.deepEqual(last("answer"), { type: MSG, op: "answer", browser: "bot:a", req: 2, result: {} });
+ send({ op: "cdp", browser: "bot:a", req: 3, tab: "p1", method: "DOM.fail", params: {} });
+ await tick();
+ assert.deepEqual(last("answer").error, { message: "No node with given id found", code: -32000 });
+ send({ op: "cdp", browser: "bot:a", req: 4, tab: "p9", method: "Page.enable", params: {} });
+ await tick();
+ assert.deepEqual(last("answer").error, { message: "Target closed" });
+
+ view.webContents.debugger.emit("message", {}, "Page.loadEventFired", { timestamp: 1 }, "");
+ view.webContents.debugger.emit("message", {}, "Page.frameNavigated", { frame: {} }, "CHILD1");
+ const events = posted.filter((message) => message.op === "event");
+ assert.deepEqual(events.map(({ method, session }) => [method, session]), [["Page.loadEventFired", undefined], ["Page.frameNavigated", "CHILD1"]]);
+});
+
+test("shows the bot's tab in front over the panel's rectangle and hides it under an overlay", async () => {
+ const { send, panes, posted, electron } = setup();
+ send({ op: "open", browser: "bot:a", partition: PARTITION, egress: 41000, downloads: DOWNLOADS });
+ await tick();
+ send({ op: "create", browser: "bot:a", req: 1, url: "about:blank" });
+ send({ op: "create", browser: "bot:a", req: 2, url: "about:blank", background: true });
+ await tick();
+ const showing = panes.show({ botId: "a", threadId: null, bounds: { x: 300, y: 120, width: 900, height: 700 }, visible: true });
+ const which = posted.find((message) => message.op === "which");
+ assert.deepEqual({ botId: which.botId, threadId: which.threadId }, { botId: "a", threadId: null });
+ send({ op: "resolved", req: which.req, browser: "bot:a" });
+ assert.deepEqual(await showing, { shown: true });
+ const [front, back] = electron.views;
+ assert.equal(front.visible, true);
+ assert.deepEqual(front.bounds, { x: 300, y: 120, width: 900, height: 700 });
+ assert.equal(back.visible, false);
+ assert.equal(electron.window.children.at(-1), front);
+
+ send({ op: "front", browser: "bot:a", tab: "p2" });
+ assert.equal(front.visible, false);
+ assert.equal(back.visible, true);
+
+ assert.deepEqual(await panes.show({ botId: "a", threadId: null, bounds: { x: 300, y: 120, width: 900, height: 700 }, visible: false }), { shown: false });
+ assert.equal(back.visible, false);
+ await assert.rejects(panes.show({ botId: "../a", visible: true }), /invalid/);
+});
+
+test("makes a page's popup another tab of the same profile, with its opener", async () => {
+ const { send, last, electron } = setup();
+ send({ op: "open", browser: "bot:a", partition: PARTITION, egress: 41000, downloads: DOWNLOADS });
+ await tick();
+ send({ op: "create", browser: "bot:a", req: 1, url: "about:blank" });
+ await tick();
+ const opener = electron.views[0].webContents;
+ const answer = opener.openHandler({ url: "https://accounts.example/" });
+ assert.equal(answer.action, "allow");
+ const guest = new EventEmitter();
+ const popup = answer.createWindow({ webContents: guest });
+ assert.equal(popup, guest);
+ await tick();
+ const tab = last("tab");
+ assert.deepEqual({ tab: tab.tab, opener: tab.opener, target: tab.target }, { tab: "p2", opener: "p1", target: "FRAME2" });
+ assert.equal(electron.views[1].options.webContents, guest);
+ assert.equal(electron.views[1].options.webPreferences.partition, PARTITION);
+});
+
+test("tells the server when the person uses a pane, at most four times a second", async () => {
+ const { send, posted, electron, advance } = setup();
+ send({ op: "open", browser: "bot:a", partition: PARTITION, egress: 41000, downloads: DOWNLOADS });
+ await tick();
+ send({ op: "create", browser: "bot:a", req: 1, url: "about:blank" });
+ await tick();
+ const contents = electron.views[0].webContents;
+ contents.emit("input-event", {}, { type: "mouseMove" });
+ contents.emit("input-event", {}, { type: "mouseDown" });
+ contents.emit("input-event", {}, { type: "keyDown" });
+ advance(300);
+ contents.emit("input-event", {}, { type: "char" });
+ const pings = posted.filter((message) => message.op === "input");
+ assert.equal(pings.length, 2);
+ assert.equal(pings[0].tab, "p1");
+});
+
+test("draws a hidden pane for a screenshot, then hides it again", async () => {
+ const { send, last, electron } = setup();
+ send({ op: "open", browser: "bot:a", partition: PARTITION, egress: 41000, downloads: DOWNLOADS });
+ await tick();
+ send({ op: "create", browser: "bot:a", req: 1, url: "about:blank" });
+ await tick();
+ send({ op: "cdp", browser: "bot:a", req: 2, tab: "p1", method: "Page.captureScreenshot", params: {} });
+ await tick();
+ assert.equal(last("answer").result.visibleDuring, true);
+ assert.equal(electron.views[0].visible, false);
+ assert.deepEqual(electron.views[0].bounds, { x: 0, y: 0, width: 1280, height: 800 });
+});
+
+test("closes a profile's views, detaches their debuggers, erases a partition and drops everything for a new server", async () => {
+ const { send, panes, last, electron, posted } = setup();
+ send({ op: "open", browser: "bot:a", partition: PARTITION, egress: 41000, downloads: DOWNLOADS });
+ await tick();
+ send({ op: "create", browser: "bot:a", req: 1, url: "about:blank" });
+ await tick();
+ const [view] = electron.views;
+ send({ op: "close", browser: "bot:a" });
+ assert.equal(view.webContents.closed, true);
+ assert.equal(view.webContents.debugger.isAttached(), false);
+ assert.equal(electron.window.children.length, 0);
+ assert.equal(last("tab-gone").tab, "p1");
+ assert.equal(last("closed").browser, "bot:a");
+ send({ op: "erase", partition: PARTITION });
+ await tick();
+ assert.equal(electron.sessions.get(PARTITION).erased, 1);
+
+ send({ op: "open", browser: "bot:b", partition: PARTITION, egress: 41000, downloads: DOWNLOADS });
+ await tick();
+ send({ op: "create", browser: "bot:b", req: 2, url: "about:blank" });
+ await tick();
+ const next = { postMessage: (message) => posted.push(message) };
+ panes.attach(next);
+ assert.equal(electron.views[1].webContents.closed, true);
+ assert.deepEqual(posted.at(-1), { type: MSG, op: "hello" });
+});
+
+test("a crashed page or a detached debugger is a tab gone", async () => {
+ const { send, last, electron } = setup();
+ send({ op: "open", browser: "bot:a", partition: PARTITION, egress: 41000, downloads: DOWNLOADS });
+ await tick();
+ send({ op: "create", browser: "bot:a", req: 1, url: "about:blank" });
+ await tick();
+ electron.views[0].webContents.emit("render-process-gone", {}, { reason: "crashed" });
+ assert.deepEqual(last("tab-gone"), { type: MSG, op: "tab-gone", browser: "bot:a", tab: "p1", crashed: true });
+});
+
+test("hides the shown pane when the app's page reloads or its renderer crashes", async () => {
+ const { send, panes, posted, electron } = setup();
+ send({ op: "open", browser: "bot:a", partition: PARTITION, egress: 41000, downloads: DOWNLOADS });
+ await tick();
+ send({ op: "create", browser: "bot:a", req: 1, url: "about:blank" });
+ await tick();
+ const showing = panes.show({ botId: "a", threadId: null, bounds: { x: 0, y: 0, width: 800, height: 600 }, visible: true });
+ send({ op: "resolved", req: posted.find((message) => message.op === "which").req, browser: "bot:a" });
+ await showing;
+ assert.equal(electron.views[0].visible, true);
+ electron.window.webContents.emit("did-start-navigation", {}, "http://127.0.0.1/", false, true);
+ assert.equal(electron.views[0].visible, false);
+});
+
+async function opened(options) {
+ const context = setup(options);
+ context.send({ op: "open", browser: "bot:a", partition: PARTITION, egress: 41000, downloads: DOWNLOADS });
+ await tick();
+ context.send({ op: "create", browser: "bot:a", req: 1, url: "about:blank" });
+ await tick();
+ return context;
+}
+
+test("says no window can host a pane while the app window is closed", async () => {
+ const { send, last, electron } = setup();
+ electron.window.destroyed = true;
+ send({ op: "open", browser: "bot:a", partition: PARTITION, egress: 41000, downloads: DOWNLOADS });
+ await tick();
+ assert.deepEqual(last("failed"), { type: MSG, op: "failed", browser: "bot:a", error: "The app window is closed.", reason: "no-window" });
+ assert.equal(electron.sessions.size, 0);
+});
+
+test("keeps a browser to eight tabs, popups included, and says why", async () => {
+ const { send, last, electron } = await opened();
+ for (let req = 2; req <= 8; req++) send({ op: "create", browser: "bot:a", req, url: "about:blank" });
+ await tick();
+ assert.equal(electron.views.length, 8);
+ send({ op: "create", browser: "bot:a", req: 9, url: "about:blank" });
+ await tick();
+ assert.match(last("answer").error.message, /already has 8 tabs open/);
+ assert.deepEqual(electron.views[0].webContents.openHandler({ url: "https://x.example/" }), { action: "deny" });
+});
+
+test("saves every download into the profile's folder without a dialog, reports it, and cancels on request", async () => {
+ const { send, posted, electron } = await opened();
+ const contents = electron.views[0].webContents;
+ const item = Object.assign(new EventEmitter(), {
+ savePath: null, cancelled: false,
+ setSavePath(file) { this.savePath = file; }, cancel() { this.cancelled = true; },
+ getURL: () => "https://example.com/a.csv", getFilename: () => "a.csv", getReceivedBytes: () => 3, getTotalBytes: () => 3,
+ });
+ electron.sessions.get(PARTITION).emit("will-download", {}, item, contents);
+ assert.equal(path.dirname(item.savePath), path.join(DOWNLOADS));
+ item.emit("updated", {}, "progressing");
+ item.emit("done", {}, "completed");
+ const downloads = posted.filter((message) => message.op === "download");
+ assert.deepEqual(downloads.map(({ state }) => state), ["begin", "inProgress", "completed"]);
+ assert.equal(downloads[0].name, "a.csv");
+ assert.equal(downloads[2].path, item.savePath);
+
+ const second = Object.assign(new EventEmitter(), { ...item, savePath: null, cancelled: false, setSavePath(file) { this.savePath = file; }, cancel() { this.cancelled = true; } });
+ electron.sessions.get(PARTITION).emit("will-download", {}, second, contents);
+ send({ op: "cancel-download", browser: "bot:a", guid: posted.filter((message) => message.op === "download").at(-1).guid });
+ assert.equal(second.cancelled, true);
+
+ const stray = Object.assign(new EventEmitter(), { ...item, cancelled: false, setSavePath() { throw new Error("never asked"); }, cancel() { this.cancelled = true; } });
+ electron.sessions.get(PARTITION).emit("will-download", {}, stray, new EventEmitter());
+ assert.equal(stray.cancelled, true);
+});
+
+test("does not count the bot's own input as the person's, should Electron report it", async () => {
+ const { send, posted, electron, advance } = await opened();
+ const contents = electron.views[0].webContents;
+ const debug = contents.debugger;
+ let finish;
+ debug.sendCommand = (method) => (method === "Input.dispatchMouseEvent" ? new Promise((resolve) => { finish = resolve; }) : Promise.resolve({}));
+ send({ op: "cdp", browser: "bot:a", req: 2, tab: "p1", method: "Input.dispatchMouseEvent", params: { type: "mousePressed", x: 1, y: 1 } });
+ contents.emit("input-event", {}, { type: "mouseDown" });
+ finish({});
+ await tick();
+ contents.emit("input-event", {}, { type: "mouseDown" });
+ advance(200);
+ contents.emit("input-event", {}, { type: "mouseDown" });
+ assert.equal(posted.filter((message) => message.op === "input").length, 1);
+});
+
+test("answers a screenshot of a page that never draws with an error instead of waiting for good", async () => {
+ const { send, last, electron } = await opened({ captureMs: 20 });
+ electron.views[0].webContents.neverDraws = true;
+ send({ op: "cdp", browser: "bot:a", req: 2, tab: "p1", method: "Page.captureScreenshot", params: {} });
+ await new Promise((resolve) => setTimeout(resolve, 40));
+ assert.match(last("answer").error.message, /did not draw/);
+ assert.equal(electron.views[0].visible, false);
+});
+
+test("asks again which browser a panel shows: after no answer, when a browser opens, and when the bot's profile changes", async () => {
+ const { send, panes, posted } = setup();
+ const whiches = () => posted.filter((message) => message.op === "which");
+ const area = { x: 0, y: 0, width: 800, height: 600 };
+ const first = panes.show({ botId: "a", threadId: null, profile: null, bounds: area, visible: true });
+ send({ op: "resolved", req: whiches().at(-1).req, browser: null });
+ assert.deepEqual(await first, { shown: false });
+ const again = panes.show({ botId: "a", threadId: null, profile: null, bounds: area, visible: true });
+ assert.equal(whiches().length, 2);
+ send({ op: "resolved", req: whiches().at(-1).req, browser: "bot:a" });
+ await again;
+ send({ op: "open", browser: "bot:a", partition: PARTITION, egress: 41000, downloads: DOWNLOADS });
+ await tick();
+ assert.equal(whiches().length, 3);
+ send({ op: "resolved", req: whiches().at(-1).req, browser: "bot:a" });
+ send({ op: "create", browser: "bot:a", req: 1, url: "about:blank" });
+ await tick();
+ const changed = panes.show({ botId: "a", threadId: null, profile: "work", bounds: area, visible: true });
+ assert.equal(whiches().length, 4);
+ send({ op: "resolved", req: whiches().at(-1).req, browser: "shared:work" });
+ assert.deepEqual(await changed, { shown: false });
+});
+
+test("closes every pane when the app window closes", async () => {
+ const { panes, last, electron } = await opened();
+ panes.closeAll();
+ assert.equal(electron.views[0].webContents.closed, true);
+ assert.equal(last("closed").browser, "bot:a");
+});
diff --git a/electron/browser-pane-wire.d.mts b/electron/browser-pane-wire.d.mts
new file mode 100644
index 0000000000..5dc4d9b858
--- /dev/null
+++ b/electron/browser-pane-wire.d.mts
@@ -0,0 +1,42 @@
+// Types for browser-pane-wire.mjs as the server uses it (server/browser/pane). Keep in step with the implementation.
+type CdpParams = Record<string, unknown>;
+type Base = { type: "openmausbot:browser-pane" };
+
+export type PaneToMain = Base & (
+ | { op: "hello" }
+ /** `egress`: the loopback port of the profile's egress gate; every request of its panes goes through it.
+ * `downloads`: the folder every download of its panes is saved in, never asked of the person. */
+ | { op: "open"; browser: string; partition: string; egress: number; downloads: string }
+ | { op: "cancel-download"; browser: string; guid: string }
+ | { op: "create"; browser: string; req: number; url: string; background?: boolean }
+ | { op: "cdp"; browser: string; req: number; tab: string; method: string; params: CdpParams; session?: string }
+ | { op: "front" | "close-tab"; browser: string; tab: string }
+ | { op: "close"; browser: string }
+ | { op: "erase"; partition: string }
+ | { op: "resolved"; req: number; browser: string | null }
+);
+
+/** `target`: the page's main frame id, which a CDP client takes as its target id. */
+export type PaneToServer = Base & (
+ | { op: "hello" }
+ | { op: "opened"; browser: string; version: string; userAgent: string }
+ /** `reason` "no-window": no app window can host a pane now. */
+ | { op: "failed"; browser: string; error: string; reason?: "no-window" }
+ | { op: "created"; browser: string; req: number; tab: string; target: string; url: string; title: string }
+ | { op: "answer"; browser: string; req: number; result?: CdpParams; error?: { message: string; code?: number } }
+ | { op: "event"; browser: string; tab: string; method: string; params: CdpParams; session?: string }
+ | { op: "tab"; browser: string; tab: string; target: string; url: string; title: string; opener?: string }
+ | { op: "tab-gone"; browser: string; tab: string; crashed?: boolean }
+ | { op: "closed"; browser: string; reason: string }
+ | { op: "input"; browser: string; tab?: string }
+ | { op: "which"; req: number; botId: string; threadId: string | null }
+ | { op: "download"; browser: string; tab: string; guid: string; state: "begin" | "inProgress" | "completed" | "canceled"; url?: string; name?: string; received?: number; total?: number; path?: string }
+);
+
+export declare const PANE_MESSAGE: "openmausbot:browser-pane";
+export declare const PANE_TABS_PER_BROWSER: number;
+export declare const PANE_PARTITION: RegExp;
+export declare function paneMessageToMain(raw: unknown): PaneToMain | null;
+export declare function paneMessageToServer(raw: unknown): PaneToServer | null;
+export declare const PANE_UA_HOSTS: Map<string, "electron">;
+export declare function paneUserAgent(userAgent: string, host?: string, hosts?: ReadonlyMap<string, "electron">): string;
diff --git a/electron/browser-pane-wire.mjs b/electron/browser-pane-wire.mjs
new file mode 100644
index 0000000000..49ca2febae
--- /dev/null
+++ b/electron/browser-pane-wire.mjs
@@ -0,0 +1,84 @@
+// The messages the desktop main process and its own server exchange about the bots' browser panes, over the utility
+// process's parent port. Security: only Electron's main process can post on that port, so the port itself is the
+// authentication; every message is still checked here, on both sides, before anything acts on it.
+export const PANE_MESSAGE = "openmausbot:browser-pane";
+
+/** Tabs one profile's browser may have open, as for a launched Chrome. */
+export const PANE_TABS_PER_BROWSER = 8;
+
+/** A profile's partition: persistent per profile, or in memory with a nonce for a temporary one. */
+export const PANE_PARTITION = /^(?:persist:omb-pane-[0-9a-f]{24}|omb-pane-[0-9a-f]{24}-[0-9a-f]{8})$/;
+const BROWSER = /^(?:bot|shared|temp):[A-Za-z0-9._:@-]{1,200}$/;
+const TAB = /^p[1-9]\d{0,9}$/;
+const SESSION = /^[\w.:-]{1,128}$/;
+const METHOD = /^[A-Z][A-Za-z]*\.[a-z][A-Za-z]*$/;
+const BOT = /^[\w.-]{1,128}$/;
+const GUID = /^[0-9a-f-]{36}$/;
+const DOWNLOAD_STATES = new Set(["begin", "inProgress", "completed", "canceled"]);
+/** An absolute folder or file path, POSIX or Windows, with no parent steps. */
+const ABSOLUTE = /^(?:\/|[A-Za-z]:[\\/])(?!.*(?:^|[\\/])\.\.(?:[\\/]|$))[^\0]{0,4095}$/;
+
+const TO_MAIN = new Set(["hello", "open", "create", "cdp", "front", "close-tab", "close", "erase", "resolved", "cancel-download"]);
+const TO_SERVER = new Set(["hello", "opened", "failed", "created", "answer", "event", "tab", "tab-gone", "closed", "input", "which", "download"]);
+
+const isObject = (value) => Object.prototype.toString.call(value) === "[object Object]";
+const text = (value, pattern) => typeof value === "string" && pattern.test(value);
+const optional = (value, pattern) => value === undefined || text(value, pattern);
+const count = (value) => Number.isSafeInteger(value) && value > 0;
+
+function fieldsValid(message) {
+ const { op } = message;
+ if ("browser" in message && !(op === "resolved" && message.browser === null) && !text(message.browser, BROWSER)) return false;
+ if ("tab" in message && !text(message.tab, TAB)) return false;
+ if ("req" in message && !count(message.req)) return false;
+ if ("session" in message && !optional(message.session, SESSION)) return false;
+ if ("method" in message && !text(message.method, METHOD)) return false;
+ if ("params" in message && !isObject(message.params)) return false;
+ if ("partition" in message && !text(message.partition, PANE_PARTITION)) return false;
+ switch (op) {
+ case "open": return text(message.partition, PANE_PARTITION) && Number.isInteger(message.egress) && message.egress > 0 && message.egress < 65_536 && text(message.downloads, ABSOLUTE);
+ case "failed": return typeof message.error === "string" && (message.reason === undefined || message.reason === "no-window");
+ case "cancel-download": return text(message.guid, GUID);
+ case "download": return text(message.tab, TAB) && text(message.guid, GUID) && DOWNLOAD_STATES.has(message.state)
+ && optional(message.path, ABSOLUTE) && (message.url === undefined || typeof message.url === "string") && (message.name === undefined || typeof message.name === "string")
+ && (message.received === undefined || Number.isFinite(message.received)) && (message.total === undefined || Number.isFinite(message.total));
+ case "erase": return text(message.partition, PANE_PARTITION);
+ case "create": return count(message.req) && typeof message.url === "string" && message.url.length <= 8192;
+ case "cdp": return count(message.req) && text(message.tab, TAB) && text(message.method, METHOD) && isObject(message.params);
+ case "front": case "close-tab": case "tab-gone": return text(message.tab, TAB);
+ case "created": case "tab": return text(message.tab, TAB) && text(message.target, SESSION) && typeof message.url === "string" && typeof message.title === "string" && optional(message.opener, TAB);
+ case "answer": return count(message.req) && (isObject(message.result) || isObject(message.error));
+ case "event": return text(message.tab, TAB) && text(message.method, METHOD) && isObject(message.params);
+ case "which": return count(message.req) && text(message.botId, BOT) && (message.threadId === null || text(message.threadId, BOT));
+ case "resolved": return count(message.req);
+ default: return true;
+ }
+}
+
+function read(raw, ops) {
+ if (!isObject(raw) || raw.type !== PANE_MESSAGE || !ops.has(raw.op)) return null;
+ return fieldsValid(raw) ? raw : null;
+}
+
+/** A message for the main process, or null when it is not one or is malformed. */
+export function paneMessageToMain(raw) {
+ return read(raw, TO_MAIN);
+}
+
+/** A message for the server, or null when it is not one or is malformed. */
+export function paneMessageToServer(raw) {
+ return read(raw, TO_SERVER);
+}
+
+/**
+ * Hosts that get Electron's own user agent instead of the stripped one. Known open risk: sign-in walls (Google's
+ * "this browser may not be secure", Cloudflare Turnstile) judge embedded browsers by it, and which choice passes is not
+ * settled; a host goes here only after a live test in the app.
+ */
+export const PANE_UA_HOSTS = new Map();
+
+/** The user agent a pane sends to `host`: Electron's with the app's tokens taken out, so sites see the Chromium it is. */
+export function paneUserAgent(userAgent, host = "", hosts = PANE_UA_HOSTS) {
+ if (hosts.get(String(host).toLowerCase()) === "electron") return String(userAgent);
+ return String(userAgent).replace(/\s(?:Electron|OpenMausBot|openmausbot)\/\S+/g, "").replace(/\s{2,}/g, " ").trim();
+}
diff --git a/electron/main.mjs b/electron/main.mjs
index cf9dc9c154..4badeee638 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -1,4 +1,4 @@
-import { launchRecord } from "./launch-record-main.mjs"; import { app, autoUpdater as nativeAutoUpdater, BrowserWindow, Tray, WebContentsView, clipboard, desktopCapturer, dialog, globalShortcut, ipcMain, Menu, nativeImage, Notification, net, powerMonitor, powerSaveBlocker, safeStorage, screen, session, shell, systemPreferences, utilityProcess, nativeTheme } from "electron";
+import { launchRecord } from "./launch-record-main.mjs"; import { app, autoUpdater as nativeAutoUpdater, BrowserWindow, Tray, WebContentsView, clipboard, desktopCapturer, dialog, globalShortcut, ipcMain, Menu, nativeImage, Notification, net, powerMonitor, powerSaveBlocker, safeStorage, screen, session, shell, systemPreferences, utilityProcess, nativeTheme } from "electron"; import { createBrowserPanes } from "./browser-pane-main.mjs";
import { createRequire } from "node:module";
import { randomBytes, randomUUID } from "node:crypto";
import fs from "node:fs";
@@ -156,7 +156,7 @@ cloudEntry.fromLaunch(process.argv); const teamLinks = installTeamJoin({ argv: p
let pendingPackageInstallUrl = pendingOrganizationEntry ? null : packageUrlFromCommandLine(process.argv);
let pendingChatLink = pendingOrganizationEntry ? null : chatLinkFromCommandLine(process.argv);
let organizationEntryReady = false;
-let mainWindow = null;
+let mainWindow = null; const browserPanes = createBrowserPanes({ createView: (options) => new WebContentsView(options), fromPartition: (name) => session.fromPartition(name), owner: () => (mainWindow && !mainWindow.isDestroyed() ? mainWindow : null), chromeVersion: process.versions.chrome, log: (line) => slog(line) });
const serverUnavailableWindows = new WeakSet();
let unreadCount = 0;
let unreadOverlayIcon;
@@ -1148,7 +1148,7 @@ async function startServerOn(port, dataDir = runningDataDir ?? startupEnvironmen
proc.on("message", (message) => {
if (!serverSupervisor.isCurrent(proc)) return;
try {
- if (trustedApprovalMode.receive(proc, message)) return;
+ if (browserPanes.receive(proc, message) || trustedApprovalMode.receive(proc, message)) return;
if (managedDesktopRelay.receive(proc, message)) return;
if (orgLibrary?.receive(message)) return;
if (receivePhoneSecretSave(proc, message) || oneHome.receive(proc, message) || tailnetShare.receive(message)) return;
@@ -1160,7 +1160,7 @@ async function startServerOn(port, dataDir = runningDataDir ?? startupEnvironmen
slog(`spawned pid=${proc.pid}`); launchAnalytics.stage("server_spawned"); launchRecord.mark("serverSpawned");
if (!serverSupervisor.isCurrent(proc)) return;
syncDesktopMutationToken(proc); void tailnetShare.attach(proc, port, companionSettings().routes.tailscale);
- syncPhoneSecretKey(proc); grantLocalComputer(proc, (child) => serverSupervisor.isCurrent(child));
+ syncPhoneSecretKey(proc); grantLocalComputer(proc, (child) => serverSupervisor.isCurrent(child)); browserPanes.attach(proc);
});
let exited = false;
proc.once("exit", (code) => {
@@ -1980,7 +1980,7 @@ function createWindow({ deferNavigation = false } = {}) {
applyUnreadBadge(win);
if (restored.maximized && !startupScreen) win.maximize();
win.once("closed", () => {
- if (mainWindow === win) mainWindow = null;
+ if (mainWindow === win) { mainWindow = null; browserPanes.closeAll(); }
});
win.webContents.setWindowOpenHandler(({ url }) => {
@@ -2298,7 +2298,7 @@ ipcMain.handle("desktop-workspace:layout", localOnly("desktop-workspace:layout",
const manager = desktopWorkspaceForEvent(event);
if (!manager) return false;
return manager.layout(items);
-}));
+})); ipcMain.handle("browser-pane:show", localOnly("browser-pane:show", (event, input) => { if (!mainWindow || event.sender !== mainWindow.webContents) throw new Error("The browser pane belongs to the main app window"); return browserPanes.show(input); }));
ipcMain.handle("desktop-workspace:set-interactive", localOnly("desktop-workspace:set-interactive", (event, contextId) => {
const manager = desktopWorkspaceForEvent(event);
if (!manager) return contextId == null;
diff --git a/electron/preload.cjs b/electron/preload.cjs
index a4a9b4ec32..3936b85038 100644
--- a/electron/preload.cjs
+++ b/electron/preload.cjs
@@ -430,6 +430,10 @@ const bridge = {
return () => ipcRenderer.removeListener("desktop-workspace:state", handler);
},
},
+ // This computer's page only: where a bot's Browser panel shows its native browser view.
+ browserPane: {
+ show: (input) => ipcRenderer.invoke("browser-pane:show", input),
+ },
pickFolder: (current) => ipcRenderer.invoke("desktop:pick-folder", current),
exportDiagnostics: () => ipcRenderer.invoke("desktop:export-diagnostics"),
saveFile: (filePath) => invokeWithPlainError("desktop:save-file", filePath),
diff --git a/server/browser/backends.ts b/server/browser/backends.ts
index a5323ad356..e2e7927279 100644
--- a/server/browser/backends.ts
+++ b/server/browser/backends.ts
@@ -10,7 +10,7 @@ import { clearSingleton, staleSingletonLock, type ProcessRegistry } from "./chro
import { languageList } from "./chrome/wrapper.ts";
import { downgradeRefusal, ensureProfile, forgetOpenTabs, markCleanExit, profileDir, profileHash, recordOpenedBy, versionOf, workspaceId } from "./chrome/profile.ts";
-export type BackendKind = "local" | "my-chrome" | "cdp-url";
+export type BackendKind = "local" | "my-chrome" | "cdp-url" | "pane";
export interface BackendCaps {
persistentProfile: boolean;
@@ -43,6 +43,11 @@ export interface OpenedBrowser {
readonly exited: Promise<void>;
/** Chrome's own quit: session restore keeps the tabs and session cookies. */
close(): Promise<void>;
+ /** Where the person uses the page directly: called as they press, type or scroll in it. */
+ onPersonInput?(listener: () => void): () => void;
+ /** 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 };
}
export interface Backend {
diff --git a/server/browser/cdp/actions.ts b/server/browser/cdp/actions.ts
index 5deb7fbfd8..a5a861af65 100644
--- a/server/browser/cdp/actions.ts
+++ b/server/browser/cdp/actions.ts
@@ -116,7 +116,7 @@ async function receivesClick(context: ActionContext, handle: NodeHandle, local:
functionDeclaration: RECEIVES,
arguments: [hitId ? { objectId: hitId } : { value: null }, { value: wantEnabled }],
returnByValue: true,
- });
+ }, { readOnly: true });
if (exceptionDetails || !result.value) return { disabled: false, covering: null };
// A hit in a frame this element hosts lands inside it.
if (!sameFrame && hit.backendNodeId !== handle.backendNodeId) {
@@ -260,14 +260,14 @@ const notEditable = () => new DriverError("not-editable", "The target is not an
async function focusEditable(context: ActionContext, handle: NodeHandle & { ref?: string }): Promise<"text" | "value" | "contenteditable"> {
let editable: { kind: "text" | "value" | "contenteditable" } | null;
try {
- editable = await callOnNode<{ kind: "text" | "value" | "contenteditable" } | null>(context.frames, handle, EDITABLE);
+ editable = await callOnNode<{ kind: "text" | "value" | "contenteditable" } | null>(context.frames, handle, EDITABLE, [], { readOnly: true });
} catch (error) {
if (isGone(error) || (error instanceof DriverError && error.code === "not-found")) throw gone(handle);
throw error;
}
if (!editable) throw notEditable();
await handle.session.send("DOM.focus", { backendNodeId: handle.backendNodeId });
- if (!(await callOnNode<boolean>(context.frames, handle, FOCUSED))) throw notEditable();
+ if (!(await callOnNode<boolean>(context.frames, handle, FOCUSED, [], { readOnly: true }))) throw notEditable();
return editable.kind;
}
@@ -336,7 +336,7 @@ export async function select(context: ActionContext, target: Exclude<Target, Poi
await context.bringToFront();
refuseErrorPage(context);
const handle = await element(context, target);
- const info = await callOnNode<SelectInfo | null>(context.frames, handle, SELECT_INFO).catch((error: unknown) => {
+ const info = await callOnNode<SelectInfo | null>(context.frames, handle, SELECT_INFO, [], { readOnly: true }).catch((error: unknown) => {
if (isGone(error) || (error instanceof DriverError && error.code === "not-found")) throw gone(handle);
throw error;
});
@@ -357,7 +357,7 @@ export async function select(context: ActionContext, target: Exclude<Target, Poi
if (typeable) {
await handle.session.send("DOM.focus", { backendNodeId: handle.backendNodeId });
await context.keyboard.type(option.label);
- const after = await callOnNode<SelectInfo | null>(context.frames, handle, SELECT_INFO);
+ const after = await callOnNode<SelectInfo | null>(context.frames, handle, SELECT_INFO, [], { readOnly: true });
if (after?.value === option.value) return { selected: [option.value] };
}
}
@@ -380,13 +380,13 @@ type CheckState = { kind: "checkbox" | "radio"; checked: boolean | "mixed" } | n
/** Clicks only when the state differs, then confirms the page took it. */
export async function check(context: ActionContext, target: Exclude<Target, Point>, checked = true, options: { timeoutMs?: number } = {}): Promise<{ checked: boolean; changed: boolean }> {
const handle = await element(context, target);
- const state = await callOnNode<CheckState>(context.frames, handle, CHECK_STATE);
+ const state = await callOnNode<CheckState>(context.frames, handle, CHECK_STATE, [], { readOnly: true });
if (!state) throw new DriverError("not-editable", "This element is not a checkbox, radio button or switch.");
if (state.checked === checked) return { checked, changed: false };
if (!checked && state.kind === "radio") throw new DriverError("refused", "A radio button cannot be unchecked; choose another option instead.");
const ref = handle.ref ?? context.refs.refFor(handle);
await click(context, { ref }, options);
- const after = await callOnNode<CheckState>(context.frames, handle, CHECK_STATE);
+ const after = await callOnNode<CheckState>(context.frames, handle, CHECK_STATE, [], { readOnly: true });
if (after?.checked !== checked) throw new DriverError("execution", `Clicking did not ${checked ? "check" : "uncheck"} the element.`);
return { checked, changed: true };
}
@@ -413,7 +413,7 @@ export async function drag(context: ActionContext, from: Target, to: Target, { t
});
await session.send("Input.setInterceptDrags", { enabled: true });
try {
- await valueInWorld(context.frames, sourceFrame, DRAG_PROBE);
+ await valueInWorld(context.frames, sourceFrame, DRAG_PROBE, { readOnly: false });
await context.mouse.move(start.x, start.y);
await context.mouse.down();
// Past Chrome's drag threshold, toward the target.
diff --git a/server/browser/cdp/connection.ts b/server/browser/cdp/connection.ts
index 3b79420778..79d9319f08 100644
--- a/server/browser/cdp/connection.ts
+++ b/server/browser/cdp/connection.ts
@@ -98,7 +98,7 @@ export class CdpConnection {
: undefined;
this.#pending.set(id, { method, session, resolve, reject, timer });
try {
- this.#transport.send(JSON.stringify(message));
+ this.#transport.send(JSON.stringify(message), options.readOnly ? { readOnly: true } : undefined);
} catch (error) {
this.#pending.delete(id);
if (timer) clearTimeout(timer);
diff --git a/server/browser/cdp/evaluate.ts b/server/browser/cdp/evaluate.ts
index 0e76a570da..5b6fdd3e0c 100644
--- a/server/browser/cdp/evaluate.ts
+++ b/server/browser/cdp/evaluate.ts
@@ -124,7 +124,7 @@ export async function callOnNode<T>(
handle: NodeHandle,
fn: string,
args: readonly unknown[] = [],
- { awaitPromise = false }: { awaitPromise?: boolean } = {},
+ { awaitPromise = false, readOnly = false }: { awaitPromise?: boolean; readOnly?: boolean } = {},
): Promise<T> {
return frames.inWorld(handle.frameId, async (session, contextId) => {
const objectId = await resolveInWorld(session, handle.backendNodeId, contextId);
@@ -135,7 +135,7 @@ export async function callOnNode<T>(
arguments: args.map((value) => ({ value })),
returnByValue: true,
awaitPromise,
- });
+ }, { readOnly });
if (result.exceptionDetails) throw new DriverError("execution", exceptionText(result.exceptionDetails));
return valueOf(result.result) as T;
} finally {
@@ -158,7 +158,7 @@ export async function resolveInWorld(session: CdpSession, backendNodeId: number,
/** Runs a function in a frame's isolated world and keeps the result as a remote object (for nodes). */
export async function callInWorld(frames: FrameTree, frameId: string, fn: string, args: readonly unknown[] = []): Promise<{ session: CdpSession; result: RemoteObject }> {
return frames.inWorld(frameId, async (session, contextId) => {
- const found = await session.send<EvaluationResult>("Runtime.evaluate", { expression: "document", contextId, returnByValue: false });
+ const found = await session.send<EvaluationResult>("Runtime.evaluate", { expression: "document", contextId, returnByValue: false }, { readOnly: true });
const documentId = found.result.objectId;
if (!documentId) throw new DriverError("not-found", "The frame has no document.");
try {
@@ -167,7 +167,7 @@ export async function callInWorld(frames: FrameTree, frameId: string, fn: string
functionDeclaration: fn,
arguments: args.map((value) => ({ value })),
returnByValue: false,
- });
+ }, { readOnly: true });
if (result.exceptionDetails) throw new DriverError("execution", exceptionText(result.exceptionDetails));
return { session, result: result.result };
} finally {
@@ -176,10 +176,10 @@ export async function callInWorld(frames: FrameTree, frameId: string, fn: string
});
}
-/** A plain value computed in a frame's isolated world. */
-export async function valueInWorld<T>(frames: FrameTree, frameId: string, expression: string, { awaitPromise = false } = {}): Promise<T> {
+/** A plain value computed in a frame's isolated world; `readOnly` false when the expression changes the page. */
+export async function valueInWorld<T>(frames: FrameTree, frameId: string, expression: string, { awaitPromise = false, readOnly = true } = {}): Promise<T> {
const result = await frames.inWorld(frameId, (session, contextId) =>
- session.send<EvaluationResult>("Runtime.evaluate", { expression, contextId, returnByValue: true, awaitPromise }));
+ session.send<EvaluationResult>("Runtime.evaluate", { expression, contextId, returnByValue: true, awaitPromise }, { readOnly }));
if (result.exceptionDetails) throw new DriverError("execution", exceptionText(result.exceptionDetails));
return valueOf(result.result) as T;
}
diff --git a/server/browser/cdp/files.ts b/server/browser/cdp/files.ts
index 3926ab63e1..f3c05f7c53 100644
--- a/server/browser/cdp/files.ts
+++ b/server/browser/cdp/files.ts
@@ -106,7 +106,7 @@ const FILE_INPUT = `function () {
/** Sets files on one <input type=file>. */
export async function setInputFiles(frames: FrameTree, handle: NodeHandle, paths: readonly string[]): Promise<void> {
checkUploadPaths(paths);
- const input = await callOnNode<{ multiple: boolean; disabled: boolean } | null>(frames, handle, FILE_INPUT);
+ const input = await callOnNode<{ multiple: boolean; disabled: boolean } | null>(frames, handle, FILE_INPUT, [], { readOnly: true });
if (!input) throw new DriverError("not-editable", "That element is not a file input. Pass the <input type=file>'s ref, or click the upload control and answer its picker.");
if (input.disabled) throw new DriverError("not-editable", "That file input is disabled.");
if (paths.length > 1 && !input.multiple) throw new DriverError("refused", "This file input accepts one file.");
diff --git a/server/browser/cdp/navigations.ts b/server/browser/cdp/navigations.ts
index acacd6e2c0..27857aaaaa 100644
--- a/server/browser/cdp/navigations.ts
+++ b/server/browser/cdp/navigations.ts
@@ -47,7 +47,7 @@ export class Navigations {
// stopped past its time: that would stop the page's own scripts.
const yieldMs = Math.max(1, Math.min(2_000, deadline - Date.now()));
await this.#frames.inWorld(this.#frames.mainFrameId, (session, contextId) =>
- session.send("Runtime.evaluate", { expression: AFTER_PAGE_TASKS, contextId, awaitPromise: true, returnByValue: true }, { timeoutMs: yieldMs })).catch(() => {});
+ session.send("Runtime.evaluate", { expression: AFTER_PAGE_TASKS, contextId, awaitPromise: true, returnByValue: true }, { timeoutMs: yieldMs, readOnly: true })).catch(() => {});
if (this.#requested === mark.requested && this.#lifecycle.loaderId === mark.loaderId) return;
const moved = () => this.#lifecycle.loaderId !== mark.loaderId || this.#withinDocument !== mark.withinDocument || this.#stopped !== mark.stopped;
if (!moved()) {
diff --git a/server/browser/cdp/policy.ts b/server/browser/cdp/policy.ts
index d26d1d34dc..475eb01e07 100644
--- a/server/browser/cdp/policy.ts
+++ b/server/browser/cdp/policy.ts
@@ -9,6 +9,8 @@ export type SessionKind = "browser" | "page" | "frame" | "worker" | "other";
export interface SendFlags {
/** A deliberate main-world evaluation: the page can observe it. */
pageWorld?: boolean;
+ /** The call only reads the page; a transport that holds a tab for the person still lets it through. */
+ readOnly?: boolean;
}
const NEVER: readonly RegExp[] = [
diff --git a/server/browser/cdp/snapshot.ts b/server/browser/cdp/snapshot.ts
index 43d41b2848..719ce5b756 100644
--- a/server/browser/cdp/snapshot.ts
+++ b/server/browser/cdp/snapshot.ts
@@ -181,7 +181,7 @@ async function readStyles(frames: FrameTree, items: Item[]): Promise<void> {
functionDeclaration: STYLE_READ,
arguments: present.map((entry) => ({ objectId: entry.objectId })),
returnByValue: true,
- });
+ }, { readOnly: true });
(result.value ?? []).forEach(([pointer, input], i) => {
const item = present[i]!.item;
item.pointer = pointer && !INTERACTIVE.has(item.role);
diff --git a/server/browser/cdp/transport.ts b/server/browser/cdp/transport.ts
index dafc39d895..1938ec2a99 100644
--- a/server/browser/cdp/transport.ts
+++ b/server/browser/cdp/transport.ts
@@ -2,12 +2,17 @@ import type { Readable, Writable } from "node:stream";
/** One CDP connection's bytes: a launched Chrome's pipe, a WebSocket, or the desktop link. */
export interface CdpTransport {
- send(message: string): void;
+ /** `meta` travels beside the message, never on the wire. */
+ send(message: string, meta?: SendMeta): void;
onMessage(listener: (message: string) => void): void;
onClose(listener: (reason: string) => void): void;
close(): void;
}
+export interface SendMeta {
+ readOnly?: boolean;
+}
+
class Listeners {
readonly messages = new Set<(message: string) => void>();
readonly closes = new Set<(reason: string) => void>();
@@ -128,7 +133,7 @@ export interface SentCommand {
/** Records every command as it leaves for the browser, below the driver's own guard. */
export function tracingTransport(inner: CdpTransport, record: (sent: SentCommand) => void): CdpTransport {
return {
- send(message) {
+ send(message, meta) {
try {
const parsed = JSON.parse(message) as { method?: unknown; sessionId?: unknown; params?: unknown };
if (typeof parsed.method === "string") {
@@ -139,7 +144,7 @@ export function tracingTransport(inner: CdpTransport, record: (sent: SentCommand
});
}
} catch {}
- inner.send(message);
+ inner.send(message, meta);
},
onMessage: (listener) => inner.onMessage(listener),
onClose: (listener) => inner.onClose(listener),
diff --git a/server/browser/cdp/wait.ts b/server/browser/cdp/wait.ts
index c7778d3cde..1647b719f0 100644
--- a/server/browser/cdp/wait.ts
+++ b/server/browser/cdp/wait.ts
@@ -137,7 +137,7 @@ async function elementPresent(context: WaitContext, target: { ref?: string; sele
const ref = target.ref ?? (target.selector !== undefined ? parseRef(target.selector) : null);
if (ref) {
try {
- return await callOnNode<boolean>(context.frames, context.refs.resolve(ref), CONNECTED);
+ return await callOnNode<boolean>(context.frames, context.refs.resolve(ref), CONNECTED, [], { readOnly: true });
} catch (error) {
if (error instanceof DriverError && error.code === "stale-ref") throw error;
return false;
diff --git a/server/browser/config.test.ts b/server/browser/config.test.ts
index 3cd5c5935a..8c89fb911b 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 } from "./config.ts";
+import { browserEngineConfigSchema, browserPaneWanted } from "./config.ts";
describe("browser engine proxy configuration", () => {
it("accepts an unauthenticated SOCKS5 endpoint", () => {
@@ -14,3 +14,14 @@ describe("browser engine proxy configuration", () => {
}
});
});
+
+describe("the desktop pane setting", () => {
+ it("is off unless set, and needs the Chrome engine", () => {
+ expect(browserPaneWanted({})).toBe(false);
+ expect(browserPaneWanted({ browserEngine: { surface: "pane" } })).toBe(false);
+ expect(browserPaneWanted({ browserEngine: { engine: "chrome" } })).toBe(false);
+ expect(browserPaneWanted({ browserEngine: { engine: "chrome", surface: "stream" } })).toBe(false);
+ expect(browserPaneWanted({ browserEngine: { engine: "chrome", surface: "pane" } })).toBe(true);
+ expect(browserEngineConfigSchema.safeParse({ surface: "window" }).success).toBe(false);
+ });
+});
diff --git a/server/browser/config.ts b/server/browser/config.ts
index a3fa916d06..c66612b509 100644
--- a/server/browser/config.ts
+++ b/server/browser/config.ts
@@ -26,6 +26,8 @@ export const browserEngineConfigSchema = z.object({
egress: browserEgressConfigSchema.optional(),
/** "chrome" runs the bots' browsers on OpenMausBot's own Chrome driver, an early test; agent-browser is the default. */
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(),
});
export interface BrowserEngineConfig {
@@ -33,8 +35,14 @@ export interface BrowserEngineConfig {
idleTimeoutMinutes?: number;
egress?: BrowserEgressConfig;
engine?: BrowserEngineKind;
+ surface?: "stream" | "pane";
}
export function browserEngineKind(cfg: { browserEngine?: BrowserEngineConfig }): BrowserEngineKind {
return cfg.browserEngine?.engine === "chrome" ? "chrome" : "agent-browser";
}
+
+/** The desktop pane needs the Chrome engine too: it is that engine's browser, shown natively. */
+export function browserPaneWanted(cfg: { browserEngine?: BrowserEngineConfig }): boolean {
+ return browserEngineKind(cfg) === "chrome" && cfg.browserEngine?.surface === "pane";
+}
diff --git a/server/browser/dispatch.ts b/server/browser/dispatch.ts
index 467beac655..9f870de9c9 100644
--- a/server/browser/dispatch.ts
+++ b/server/browser/dispatch.ts
@@ -213,7 +213,7 @@ async function readText(tab: Tab, input: ToolInput<"agent_browser_read">): Promi
let text: string;
if (input.ref !== undefined || input.selector !== undefined) {
const handle = await resolveElement(tab.page.frames, tab.page.refs, input.ref !== undefined ? { ref: input.ref } : { selector: input.selector! });
- text = await callOnNode<string>(tab.page.frames, handle, ELEMENT_TEXT);
+ text = await callOnNode<string>(tab.page.frames, handle, ELEMENT_TEXT, [], { readOnly: true });
} else {
text = await tab.page.visibleText(offset + limit);
}
diff --git a/server/browser/engines.test.ts b/server/browser/engines.test.ts
index 1c07a8adfc..586365eea5 100644
--- a/server/browser/engines.test.ts
+++ b/server/browser/engines.test.ts
@@ -1,4 +1,4 @@
-import { mkdtempSync } from "node:fs";
+import { existsSync, mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -13,7 +13,10 @@ import { removeTempDir } from "../testing/cleanup.ts";
import { ProcessRegistry } from "./chrome/processes.ts";
import { browserRoot } from "./chrome/profile.ts";
import { createBrowserInputLog } from "./input-log.ts";
-import { CHROME_ENGINE, ChromeEngine, chromeTarget, LiveRouter, profileKey, RuntimeRouter, type RuntimeRouterOptions } from "./engines.ts";
+import type { Backend } from "./backends.ts";
+import { PaneBackend } from "./pane/backend.ts";
+import { PaneLink } from "./pane/link.ts";
+import { backendFor, CHROME_ENGINE, ChromeEngine, chromeTarget, LiveRouter, profileKey, RuntimeRouter, type RuntimeRouterOptions } from "./engines.ts";
const AGENT_BROWSER = { command: "/opt/agent-browser", args: ["--session", "s"], env: { AGENT_BROWSER_SESSION: "s" } };
const CHROME = { command: CHROME_ENGINE, args: ["bot:a"], env: {} };
@@ -319,3 +322,39 @@ describe("the new engine's minute", () => {
expect(closeIdle).toHaveBeenCalledTimes(3);
});
});
+
+describe("which backend a profile's browser starts on", () => {
+ const local = { kind: "local" } as Backend;
+ const pane = (available: boolean) => ({ kind: "pane", available }) as unknown as PaneBackend;
+
+ it("stays on the local Chrome unless the pane is wanted and the desktop app shows panes", () => {
+ expect(backendFor(local, undefined)).toBe(local);
+ expect(backendFor(local, { backend: pane(true), wanted: () => false })).toBe(local);
+ expect(backendFor(local, { backend: pane(false), wanted: () => true })).toBe(local);
+ const shown = pane(true);
+ expect(backendFor(local, { backend: shown, wanted: () => true })).toBe(shown);
+ });
+});
+
+describe("deleting a bot's browser on the desktop app, pane off", () => {
+ it("does what it did without the pane: nothing for a profile that never ran, and no partition", async () => {
+ const dataDir = mkdtempSync(join(tmpdir(), "omb-chrome-engine-"));
+ const posted: object[] = [];
+ const link = new PaneLink({ on: () => undefined, postMessage: (message) => posted.push(message) });
+ const value = new ChromeEngine({
+ dataDir, host: "desktop", env: {}, platform: "darwin", egressPort: async () => 0, idleMs: () => 180_000, egressNotice: () => null,
+ pane: { backend: new PaneBackend(link, dataDir, async () => 0), wanted: () => false },
+ });
+ const erase = vi.spyOn(value.service, "erase");
+ try {
+ expect(await value.erase({ kind: "bot", id: "a", partitionId: "" })).toBe(true);
+ expect(await value.erase({ kind: "profile", id: "p", partitionId: "p1" })).toBe(true);
+ expect(erase).not.toHaveBeenCalled();
+ expect(existsSync(join(browserRoot(dataDir), "workspace-id"))).toBe(false);
+ expect(posted).toEqual([{ type: "openmausbot:browser-pane", op: "hello" }]);
+ } finally {
+ await value.close();
+ await removeTempDir(dataDir);
+ }
+ });
+});
diff --git a/server/browser/engines.ts b/server/browser/engines.ts
index 4c90ce99d1..545c7ed1b8 100644
--- a/server/browser/engines.ts
+++ b/server/browser/engines.ts
@@ -8,7 +8,7 @@ import type { BrowserLive } from "../browser-live.ts";
import type { BrowserRuntime, BrowserSpawnSpec } from "../browser-runtime.ts";
import type { StepContext } from "../browser-steps.ts";
import type { FillLoginDeps } from "../login-fill.ts";
-import { LocalBackend } from "./backends.ts";
+import { LocalBackend, type Backend } from "./backends.ts";
import { sandboxDisabled } from "./chrome/host-setup.ts";
import type { HostKind } from "./chrome/flags.ts";
import { ChromeLauncher } from "./chrome/launcher.ts";
@@ -17,6 +17,7 @@ import { browserRoot } from "./chrome/profile.ts";
import { browserLanguage, browserTimeZone, languageList } from "./chrome/wrapper.ts";
import { displayScreen } from "./display.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";
import { BrowserService, type BrowserTarget } from "./service.ts";
import { LiveV1 } from "./viewers/live-v1.ts";
@@ -51,9 +52,16 @@ export interface ChromeEngineOptions {
held?(session: string): boolean;
egressNotice(key: string): string | null;
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 };
log?: (line: string) => void;
}
+/** Each start of a profile's browser picks again, so turning the pane on or off takes effect at the next start. */
+export function backendFor(local: Backend, pane: ChromeEngineOptions["pane"]): Backend {
+ return pane && pane.wanted() && pane.backend.available ? pane.backend : local;
+}
+
/** The new engine: one Chrome launcher (no agent-browser wrapper), the browser service, its live views and its sweep. */
export class ChromeEngine {
readonly launcher: ChromeLauncher;
@@ -93,10 +101,11 @@ export class ChromeEngine {
sandbox,
...(options.log ? { log: options.log } : {}),
});
+ options.pane?.backend.fallBackTo(backend);
const maxRunning = Number(env.OMB_BROWSER_MAX_RUNNING) || MAX_RUNNING[options.host];
this.service = new BrowserService({
dataDir: options.dataDir,
- backend: () => backend,
+ backend: () => backendFor(backend, options.pane),
maxRunning,
idleMs: options.idleMs,
held: options.held,
@@ -160,9 +169,11 @@ export class ChromeEngine {
/** A deleted bot's or profile's browser: stopped, and its folder, downloads and screenshots gone. */
async erase(request: { kind: "bot" | "profile"; id: string; partitionId: string }): Promise<boolean> {
const key = request.kind === "bot" ? `bot:${request.id}` : `shared:${request.partitionId}`;
- if (!this.#everUsed()) return true;
+ const paneUsed = this.#options.pane?.backend.used(key) === true;
+ if (!this.#everUsed() && !paneUsed) return true;
try {
await this.service.erase(key);
+ if (paneUsed) this.#options.pane?.backend.erase(key);
return true;
} catch (error) {
this.#options.log?.(`browser cleanup: could not erase ${key}: ${error instanceof Error ? error.message : String(error)}`);
diff --git a/server/browser/pane/backend.ts b/server/browser/pane/backend.ts
new file mode 100644
index 0000000000..79409fae2f
--- /dev/null
+++ b/server/browser/pane/backend.ts
@@ -0,0 +1,110 @@
+// A profile's browser as panes in the desktop app: real pages the person uses directly, driven by the same CDP driver.
+import { randomBytes } from "node:crypto";
+import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { PANE_TABS_PER_BROWSER } from "../../../electron/browser-pane-wire.mjs";
+import type { Backend, BackendCaps, OpenedBrowser, OpenRequest } from "../backends.ts";
+import { CdpBrowser } from "../cdp/browser.ts";
+import { browserRoot, profileHash, profileKind, workspaceId } from "../chrome/profile.ts";
+import { PaneUnavailable, type OpenedPanes, type PaneLink } from "./link.ts";
+
+const PANE_CAPS: BackendCaps = { persistentProfile: true, window: true, egressGate: true, identityOverride: false, ownsAllTabs: true, downloads: "local", uploads: "path", botPasskeys: false };
+
+/** One empty file per profile whose panes ever opened in this data folder, so deleting a bot touches no partition it never had. */
+function marksDir(dataDir: string): string {
+ return join(browserRoot(dataDir), "panes");
+}
+
+/** Sign-ins are the profile's own and never shared between data folders; a temporary profile's die with the app. */
+export function panePartition(dataDir: string, key: string, nonce = () => randomBytes(4).toString("hex")): string {
+ const hash = profileHash(workspaceId(dataDir), key);
+ return profileKind(key) === "temp" ? `omb-pane-${hash}-${nonce()}` : `persist:omb-pane-${hash}`;
+}
+
+export class PaneBackend implements Backend {
+ readonly kind = "pane" as const;
+ readonly caps = PANE_CAPS;
+ readonly #link: PaneLink;
+ readonly #dataDir: string;
+ readonly #egressPort: (key: string) => Promise<number>;
+ readonly #platform: NodeJS.Platform;
+ #fallback: Backend | null = null;
+
+ /** `egressPort`: the profile's egress gate, which the panes' partition is proxied through as a launched Chrome is. */
+ constructor(link: PaneLink, dataDir: string, egressPort: (key: string) => Promise<number>, platform: NodeJS.Platform = process.platform) {
+ this.#link = link;
+ this.#dataDir = dataDir;
+ this.#egressPort = egressPort;
+ this.#platform = platform;
+ }
+
+ get available(): boolean {
+ return this.#link.available;
+ }
+
+ /** Where a browser starts while no app window can host a pane (the window is closed to the tray). */
+ fallBackTo(backend: Backend): void {
+ this.#fallback = backend;
+ }
+
+ /** Whether this profile's panes ever opened in this data folder; reads only, so a never-used one writes nothing. */
+ used(key: string): boolean {
+ if (profileKind(key) === "temp" || !existsSync(marksDir(this.#dataDir))) return false;
+ return existsSync(join(marksDir(this.#dataDir), profileHash(workspaceId(this.#dataDir), key)));
+ }
+
+ async open(request: OpenRequest): Promise<OpenedBrowser> {
+ const partition = panePartition(this.#dataDir, request.key);
+ let opened: OpenedPanes;
+ try {
+ opened = await this.#link.open(request.key, partition, await this.#egressPort(request.key), request.downloadDir);
+ } catch (error) {
+ if (error instanceof PaneUnavailable && this.#fallback) return this.#fallback.open(request);
+ throw error;
+ }
+ if (profileKind(request.key) !== "temp") {
+ mkdirSync(marksDir(this.#dataDir), { recursive: true, mode: 0o700 });
+ writeFileSync(join(marksDir(this.#dataDir), profileHash(workspaceId(this.#dataDir), request.key)), "");
+ }
+ let browser: CdpBrowser;
+ try {
+ browser = await CdpBrowser.connect(opened.endpoint, { identity: null, headless: false, permissions: false, downloadDir: request.downloadDir, viewport: null, platform: this.#platform, maxPages: PANE_TABS_PER_BROWSER, handleAuth: true });
+ if (browser.pages().length === 0 && browser.settingUp().length === 0) await browser.newPage();
+ } catch (error) {
+ this.#link.close(request.key);
+ throw error;
+ }
+ // What the person did may have changed the page under the bot's refs.
+ const offInput = opened.onPersonInput(() => {
+ for (const page of browser.pages()) page.refs.invalidateAll();
+ });
+ const exited = new Promise<void>((resolve) => { browser.connection.onClose(() => { offInput(); resolve(); }); });
+ return {
+ browser,
+ pageLimit: null,
+ pid: null,
+ version: opened.version,
+ exited,
+ onPersonInput: (listener) => opened.onPersonInput(listener),
+ personControl: {
+ hold: (targetId, held) => {
+ opened.endpoint.hold(targetId, held);
+ if (!held) browser.page(targetId)?.refs.invalidateAll();
+ },
+ owner: (targetId) => opened.endpoint.owner(targetId),
+ },
+ close: async () => {
+ await browser.close();
+ this.#link.close(request.key);
+ },
+ };
+ }
+
+ /** A deleted bot's or profile's pane sign-ins, when its panes ever opened here. */
+ erase(key: string): void {
+ if (!this.used(key)) return;
+ this.#link.erase(panePartition(this.#dataDir, key));
+ rmSync(join(marksDir(this.#dataDir), profileHash(workspaceId(this.#dataDir), key)), { force: true });
+ }
+}
diff --git a/server/browser/pane/endpoint.ts b/server/browser/pane/endpoint.ts
new file mode 100644
index 0000000000..b31e84cd11
--- /dev/null
+++ b/server/browser/pane/endpoint.ts
@@ -0,0 +1,452 @@
+// One profile's desktop panes as one browser-level CDP connection. Each pane is an Electron webContents whose debugger
+// speaks page-level CDP only (no Browser domain, no Target.createTarget): this endpoint answers the browser-level
+// commands itself and asks the main process for tabs, so the CDP driver runs on it unchanged.
+import type { Params } from "../cdp/connection.ts";
+import type { CdpTransport, SendMeta } from "../cdp/transport.ts";
+
+export interface PaneTab {
+ tab: string;
+ /** The page's main frame id: the driver takes it as the target id and the main frame's id. */
+ target: string;
+ url: string;
+ title: string;
+ opener?: string;
+}
+
+/** What the main process does for one profile's panes. */
+export interface PaneChannel {
+ readonly version: string;
+ readonly userAgent: string;
+ create(url: string, background: boolean): Promise<PaneTab>;
+ command(tab: string, method: string, params: Params, session?: string): Promise<Params>;
+ front(tab: string): void;
+ closeTab(tab: string): void;
+ cancelDownload(guid: string): void;
+ close(): void;
+}
+
+/** A download in a pane, as the main process saved it (never through a Save dialog). */
+export interface PaneDownload {
+ tab: string;
+ guid: string;
+ state: "begin" | "inProgress" | "completed" | "canceled";
+ url?: string;
+ name?: string;
+ received?: number;
+ total?: number;
+ path?: string;
+}
+
+export interface PaneEndpointOptions {
+ /** The bot's own input waits until the person has been still this long. */
+ quietMs?: number;
+ /** and never longer than this. */
+ maxHoldMs?: number;
+ /** How long the event re-enabling before a navigation may take. */
+ primeMs?: number;
+}
+
+interface Command {
+ id: number;
+ method: string;
+ params: Params;
+ sessionId?: string;
+ readOnly?: boolean;
+}
+
+interface TabState extends PaneTab {
+ announced: boolean;
+ viewers: Set<string>;
+ casting: Set<string>;
+ /** Commands of the tab's own session go out in order behind a held input. */
+ gate: Promise<void>;
+ /** The person holds the tab: the bot's input is refused until they let go. */
+ held: boolean;
+ lastPerson: number;
+ lastBot: number;
+}
+
+/** Who acted last in a tab, the person holding it counting as the person. */
+export type PaneOwner = "person" | "bot" | null;
+
+export const PERSON_HOLDS_TAB = "The person is using this tab. Wait until they hand it back, then take a fresh snapshot before acting.";
+
+class Refusal extends Error {}
+
+const PAGE_PREFIX = "pane-";
+/** All a held tab lets the bot send, on its page and on its frames: reads, and the setup each new frame needs. */
+const HELD_READS = new Set([
+ "Page.getFrameTree", "Page.getLayoutMetrics", "Page.captureScreenshot", "Page.getNavigationHistory",
+ "DOM.getDocument", "DOM.describeNode", "DOM.resolveNode", "DOM.querySelector", "DOM.getContentQuads", "DOM.getBoxModel",
+ "DOM.getNodeForLocation", "DOM.getFrameOwner", "Accessibility.getFullAXTree", "Accessibility.queryAXTree", "Network.getCookies",
+ "Target.detachFromTarget",
+ // Fronting the held tab itself shows the person the page they hold.
+ "Page.bringToFront",
+]);
+const HELD_SETUP = /^(?:[A-Za-z]+\.(?:enable|disable)$|Page\.(?:setLifecycleEventsEnabled|setInterceptFileChooserDialog|addScriptToEvaluateOnNewDocument|removeScriptToEvaluateOnNewDocument|createIsolatedWorld)$|Emulation\.(?:setFocusEmulationEnabled|setUserAgentOverride)$|Network\.setUserAgentOverride$|Target\.setAutoAttach$|Fetch\.|WebAuthn\.|Runtime\.(?:runIfWaitingForDebugger|releaseObject|releaseObjectGroup)$)/;
+/** Runtime calls change whatever their script changes: only those the driver marked read-only pass a hold. */
+const RUNTIME_CALLS = new Set(["Runtime.evaluate", "Runtime.callFunctionOn"]);
+
+function heldAllows(method: string, readOnly: boolean): boolean {
+ return HELD_READS.has(method) || HELD_SETUP.test(method) || (readOnly && RUNTIME_CALLS.has(method));
+}
+const PRIMED = ["Network.enable", "Page.enable", "Page.setLifecycleEventsEnabled"] as const;
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+export class PaneEndpoint implements CdpTransport {
+ readonly #channel: PaneChannel;
+ readonly #tabs = new Map<string, TabState>();
+ readonly #messages = new Set<(message: string) => void>();
+ readonly #closes = new Set<(reason: string) => void>();
+ readonly #quietMs: number;
+ readonly #maxHoldMs: number;
+ readonly #primeMs: number;
+ #autoAttach = false;
+ #viewerCount = 0;
+ #lastInput = 0;
+ #closed: string | null = null;
+
+ constructor(channel: PaneChannel, tabs: readonly PaneTab[] = [], options: PaneEndpointOptions = {}) {
+ this.#channel = channel;
+ this.#quietMs = options.quietMs ?? 1_000;
+ this.#maxHoldMs = options.maxHoldMs ?? 10_000;
+ this.#primeMs = options.primeMs ?? 1_000;
+ for (const tab of tabs) this.tabOpened(tab);
+ }
+
+ // CdpTransport.
+ send(message: string, meta?: SendMeta): void {
+ if (this.#closed !== null) return;
+ let command: Command;
+ try {
+ command = { ...(JSON.parse(message) as Command), readOnly: meta?.readOnly === true };
+ } catch {
+ return;
+ }
+ void this.#run(command).then(
+ (result) => this.#emit({ id: command.id, result, ...(command.sessionId ? { sessionId: command.sessionId } : {}) }),
+ (error: unknown) => this.#emit({ id: command.id, error: errorOf(error), ...(command.sessionId ? { sessionId: command.sessionId } : {}) }),
+ );
+ }
+
+ onMessage(listener: (message: string) => void): void {
+ this.#messages.add(listener);
+ }
+
+ onClose(listener: (reason: string) => void): void {
+ if (this.#closed !== null) listener(this.#closed);
+ else this.#closes.add(listener);
+ }
+
+ close(): void {
+ this.closed("closed by the driver");
+ }
+
+ // From the main process.
+
+ tabOpened(tab: PaneTab): void {
+ const known = this.#tabs.get(tab.tab);
+ if (known) {
+ known.target = tab.target;
+ known.url = tab.url;
+ known.title = tab.title;
+ this.#event("Target.targetInfoChanged", { targetInfo: this.#info(known) });
+ return;
+ }
+ const state: TabState = { ...tab, announced: false, viewers: new Set(), casting: new Set(), gate: Promise.resolve(), held: false, lastPerson: 0, lastBot: 0 };
+ this.#tabs.set(tab.tab, state);
+ if (this.#autoAttach) this.#announce(state);
+ }
+
+ tabGone(tab: string, crashed = false): void {
+ const state = this.#tabs.get(tab);
+ if (!state) return;
+ this.#tabs.delete(tab);
+ if (crashed) this.#event("Target.targetCrashed", { targetId: state.target, status: "crashed", errorCode: 0 });
+ for (const sessionId of [...state.viewers, ...(state.announced ? [pageSession(tab)] : [])]) {
+ this.#event("Target.detachedFromTarget", { sessionId, targetId: state.target });
+ }
+ this.#event("Target.targetDestroyed", { targetId: state.target });
+ }
+
+ /** A page-level event of one pane's debugger; `session` names a child (an iframe or worker) of that page. */
+ pageEvent(tab: string, method: string, params: Params, session?: string): void {
+ const state = this.#tabs.get(tab);
+ if (!state) return;
+ const page = pageSession(tab);
+ if (session) {
+ this.#event(method, renamed(method, params, page), `${page}:${session}`);
+ return;
+ }
+ if (method === "Target.attachedToTarget" || method === "Target.detachedFromTarget") {
+ if (state.announced) this.#event(method, renamed(method, params, page), page);
+ return;
+ }
+ if (method === "Page.screencastFrame") {
+ for (const viewer of state.casting) this.#event(method, params, viewer);
+ return;
+ }
+ if (state.announced) this.#event(method, params, page);
+ for (const viewer of state.viewers) this.#event(method, params, viewer);
+ }
+
+ /** The person pressed, typed or scrolled in one of these panes (`tab` when the app knows which). */
+ personInput(tab?: string): void {
+ this.#lastInput = Date.now();
+ const state = tab ? this.#tabs.get(tab) : undefined;
+ if (state) state.lastPerson = this.#lastInput;
+ }
+
+ /** A pane's download, as the driver's download tracking hears of one. */
+ download(event: PaneDownload): void {
+ const tab = this.#tabs.get(event.tab);
+ if (event.state === "begin") {
+ this.#event("Browser.downloadWillBegin", { frameId: tab?.target ?? "", guid: event.guid, url: event.url ?? "", suggestedFilename: event.name ?? "" });
+ return;
+ }
+ this.#event("Browser.downloadProgress", {
+ guid: event.guid, receivedBytes: event.received ?? 0, totalBytes: event.total ?? 0, state: event.state, ...(event.path ? { filePath: event.path } : {}),
+ });
+ }
+
+ /** While held, the bot may only read that tab, and may not bring another tab to the front. */
+ hold(targetId: string, held: boolean): void {
+ for (const tab of this.#tabs.values()) if (tab.target === targetId) tab.held = held;
+ }
+
+ owner(targetId: string): PaneOwner {
+ for (const tab of this.#tabs.values()) {
+ if (tab.target !== targetId) continue;
+ if (tab.held || (tab.lastPerson > 0 && tab.lastPerson >= tab.lastBot)) return "person";
+ return tab.lastBot > 0 ? "bot" : null;
+ }
+ return null;
+ }
+
+ closed(reason: string): void {
+ if (this.#closed !== null) return;
+ this.#closed = reason;
+ for (const listener of this.#closes) {
+ try { listener(reason); } catch {}
+ }
+ this.#closes.clear();
+ }
+
+ get tabs(): string[] {
+ return [...this.#tabs.keys()];
+ }
+
+ // Commands.
+
+ async #run(command: Command): Promise<Params> {
+ const params = command.params ?? {};
+ if (!command.sessionId) return this.#browser(command.method, params);
+ const route = this.#route(command.sessionId);
+ if (route.kind !== "viewer" && route.tab.held && !heldAllows(command.method, command.readOnly === true)) throw new Refusal(PERSON_HOLDS_TAB);
+ if (route.kind === "child") return this.#channel.command(route.tab.tab, command.method, unrenamed(command.method, params), route.child);
+ if (route.kind === "viewer") return this.#viewer(route.tab, command.sessionId, command.method, params);
+ return this.#page(route.tab, command.method, params);
+ }
+
+ #route(sessionId: string): { kind: "page" | "viewer"; tab: TabState } | { kind: "child"; tab: TabState; child: string } {
+ const match = /^pane-(p\d+)(?:(~v\d+)|:(.+))?$/.exec(sessionId);
+ const tab = match ? this.#tabs.get(match[1]!) : undefined;
+ if (!match || !tab) throw new Refusal("No session with given id");
+ if (match[3]) return { kind: "child", tab, child: match[3] };
+ if (match[2]) {
+ if (!tab.viewers.has(sessionId)) throw new Refusal("No session with given id");
+ return { kind: "viewer", tab };
+ }
+ return { kind: "page", tab };
+ }
+
+ async #browser(method: string, params: Params): Promise<Params> {
+ switch (method) {
+ case "Target.setDiscoverTargets":
+ return {};
+ case "Target.setAutoAttach":
+ this.#autoAttach = true;
+ for (const tab of this.#tabs.values()) this.#announce(tab);
+ return {};
+ case "Target.getTargets":
+ return { targetInfos: [...this.#tabs.values()].map((tab) => this.#info(tab)) };
+ case "Target.getTargetInfo":
+ return { targetInfo: this.#info(this.#tab(String(params.targetId))) };
+ case "Target.createTarget": {
+ const created = await this.#channel.create(typeof params.url === "string" ? params.url : "about:blank", params.background === true || this.#anyHeld());
+ this.tabOpened(created);
+ return { targetId: created.target };
+ }
+ case "Target.closeTarget": {
+ const tab = this.#tab(String(params.targetId));
+ if (tab.held) throw new Refusal(PERSON_HOLDS_TAB);
+ this.#channel.closeTab(tab.tab);
+ return { success: true };
+ }
+ case "Target.activateTarget": {
+ const tab = this.#tab(String(params.targetId));
+ this.#refuseFront(tab);
+ this.#channel.front(tab.tab);
+ return {};
+ }
+ case "Target.attachToTarget": {
+ const tab = this.#tab(String(params.targetId));
+ const sessionId = `${pageSession(tab.tab)}~v${++this.#viewerCount}`;
+ tab.viewers.add(sessionId);
+ this.#event("Target.attachedToTarget", { sessionId, targetInfo: this.#info(tab), waitingForDebugger: false });
+ return { sessionId };
+ }
+ case "Target.detachFromTarget": {
+ const sessionId = String(params.sessionId);
+ for (const tab of this.#tabs.values()) {
+ if (!tab.viewers.delete(sessionId)) continue;
+ if (tab.casting.delete(sessionId) && tab.casting.size === 0) await this.#channel.command(tab.tab, "Page.stopScreencast", {}).catch(() => undefined);
+ this.#event("Target.detachedFromTarget", { sessionId, targetId: tab.target });
+ }
+ return {};
+ }
+ case "Browser.getVersion":
+ return { protocolVersion: "1.3", product: `Chrome/${this.#channel.version}`, revision: "", userAgent: this.#channel.userAgent, jsVersion: "" };
+ case "Browser.setPermission":
+ case "Browser.resetPermissions":
+ case "Browser.setDownloadBehavior":
+ return {};
+ case "Browser.cancelDownload":
+ this.#channel.cancelDownload(String(params.guid));
+ return {};
+ case "Browser.getWindowForTarget":
+ return { windowId: 1, bounds: {} };
+ case "Browser.getWindowBounds":
+ return { bounds: {} };
+ case "Browser.close":
+ this.#channel.close();
+ return {};
+ default:
+ throw new Refusal(`${method} is not available on a desktop pane.`);
+ }
+ }
+
+ async #page(tab: TabState, method: string, params: Params): Promise<Params> {
+ if (method === "Page.bringToFront") {
+ this.#refuseFront(tab);
+ this.#channel.front(tab.tab);
+ return {};
+ }
+ if (method === "Page.close") {
+ this.#channel.closeTab(tab.tab);
+ return {};
+ }
+ if (method === "Emulation.setDeviceMetricsOverride") throw new Refusal("A desktop pane is sized by the app window.");
+ const ahead = tab.gate;
+ const input = method.startsWith("Input.");
+ if (input) {
+ const released = ahead.then(() => this.#personStill());
+ tab.gate = released;
+ await released;
+ if (tab.held) throw new Refusal(PERSON_HOLDS_TAB);
+ tab.lastBot = Date.now();
+ } else {
+ await ahead;
+ }
+ // Real input follows window focus; a pane the person is not in must still take the bot's keys.
+ if (method === "Page.enable") void this.#channel.command(tab.tab, "Emulation.setFocusEmulationEnabled", { enabled: true }).catch(() => undefined);
+ if (method === "Page.navigate" || method === "Page.reload") await this.#prime(tab.tab);
+ // The person's page outlives this server: a frame paused for it would stay frozen after a server restart.
+ const sent = method === "Target.setAutoAttach" ? { ...params, waitForDebuggerOnStart: false } : params;
+ return this.#channel.command(tab.tab, method, sent);
+ }
+
+ async #viewer(tab: TabState, sessionId: string, method: string, params: Params): Promise<Params> {
+ if (method === "Emulation.setDeviceMetricsOverride") throw new Refusal("A desktop pane is sized by the app window.");
+ if (method === "Page.startScreencast") tab.casting.add(sessionId);
+ if (method === "Page.stopScreencast") {
+ tab.casting.delete(sessionId);
+ if (tab.casting.size > 0) return {};
+ }
+ if (method === "Page.bringToFront") {
+ this.#channel.front(tab.tab);
+ return {};
+ }
+ return this.#channel.command(tab.tab, method, params);
+ }
+
+ /** Electron loses a page's event subscriptions when a navigation swaps its renderer process. */
+ async #prime(tab: string): Promise<void> {
+ const priming = (async () => {
+ for (const method of PRIMED) await this.#channel.command(tab, method, method === "Page.setLifecycleEventsEnabled" ? { enabled: true } : {});
+ })().catch(() => undefined);
+ await Promise.race([priming, sleep(this.#primeMs)]);
+ }
+
+ async #personStill(): Promise<void> {
+ const until = Date.now() + this.#maxHoldMs;
+ for (let wait = this.#lastInput + this.#quietMs - Date.now(); wait > 0 && Date.now() < until; wait = this.#lastInput + this.#quietMs - Date.now()) {
+ await sleep(Math.min(wait, until - Date.now()));
+ }
+ }
+
+ #anyHeld(): boolean {
+ for (const tab of this.#tabs.values()) if (tab.held) return true;
+ return false;
+ }
+
+ /** Bringing a tab to the front while the person holds another would take the page they use away from them. */
+ #refuseFront(tab: TabState): void {
+ for (const other of this.#tabs.values()) if (other.held && other !== tab) throw new Refusal(PERSON_HOLDS_TAB);
+ }
+
+ #tab(targetId: string): TabState {
+ for (const tab of this.#tabs.values()) if (tab.target === targetId) return tab;
+ throw new Refusal("No target with given id found");
+ }
+
+ #info(tab: TabState) {
+ const opener = tab.opener ? this.#tabs.get(tab.opener)?.target : undefined;
+ return { targetId: tab.target, type: "page", url: tab.url, title: tab.title, attached: true, ...(opener ? { openerId: opener } : {}) };
+ }
+
+ #announce(tab: TabState): void {
+ if (tab.announced) return;
+ tab.announced = true;
+ this.#event("Target.attachedToTarget", { sessionId: pageSession(tab.tab), targetInfo: this.#info(tab), waitingForDebugger: false });
+ }
+
+ #event(method: string, params: Params, sessionId?: string): void {
+ this.#emit({ method, params, ...(sessionId ? { sessionId } : {}) });
+ }
+
+ #emit(message: Record<string, unknown>): void {
+ queueMicrotask(() => {
+ if (this.#closed !== null) return;
+ const text = JSON.stringify(message);
+ for (const listener of this.#messages) {
+ try { listener(text); } catch {}
+ }
+ });
+ }
+}
+
+function pageSession(tab: string): string {
+ return `${PAGE_PREFIX}${tab}`;
+}
+
+/** Child session ids are the pane debugger's own: two panes' iframes must never share one on this connection. */
+function renamed(method: string, params: Params, page: string): Params {
+ if ((method === "Target.attachedToTarget" || method === "Target.detachedFromTarget") && typeof params.sessionId === "string") {
+ return { ...params, sessionId: `${page}:${params.sessionId}` };
+ }
+ return params;
+}
+
+function unrenamed(method: string, params: Params): Params {
+ if (method === "Target.detachFromTarget" && typeof params.sessionId === "string") {
+ return { ...params, sessionId: params.sessionId.replace(/^pane-p\d+:/, "") };
+ }
+ return params;
+}
+
+function errorOf(error: unknown): { message: string; code?: number } {
+ if (error instanceof Refusal) return { message: error.message, code: -32000 };
+ const code = (error as { code?: unknown } | null)?.code;
+ return { message: error instanceof Error ? error.message : String(error), ...(typeof code === "number" ? { code } : {}) };
+}
diff --git a/server/browser/pane/link.ts b/server/browser/pane/link.ts
new file mode 100644
index 0000000000..4ad1ee7c39
--- /dev/null
+++ b/server/browser/pane/link.ts
@@ -0,0 +1,242 @@
+// The server's end of the desktop app's pane messages: one PaneEndpoint per profile the main process shows natively.
+import { PANE_MESSAGE, paneMessageToServer, type PaneToMain, type PaneToServer } from "../../../electron/browser-pane-wire.mjs";
+import type { Params } from "../cdp/connection.ts";
+import { PaneEndpoint, type PaneChannel, type PaneEndpointOptions, type PaneTab } from "./endpoint.ts";
+
+/** Electron's utility-process parent port: only the desktop main process can post on it. */
+export interface PanePort {
+ on(event: "message", listener: (event: { data?: unknown }) => void): void;
+ postMessage(message: object): void;
+}
+
+export interface OpenedPanes {
+ readonly endpoint: PaneEndpoint;
+ readonly version: string;
+ onPersonInput(listener: () => void): () => void;
+}
+
+type Outgoing = PaneToMain extends infer M ? M extends unknown ? Omit<M, "type"> : never : never;
+
+interface Pending {
+ browser: string | null;
+ resolve(value: Params | PaneTab): void;
+ reject(error: Error): void;
+ timer: ReturnType<typeof setTimeout>;
+}
+
+export interface PaneLinkOptions extends PaneEndpointOptions {
+ openTimeoutMs?: number;
+ /** A command main never answers fails after this; the driver's own timeouts are usually shorter. */
+ requestTimeoutMs?: number;
+}
+
+interface Open {
+ endpoint: PaneEndpoint;
+ inputs: Set<() => void>;
+}
+
+const OPEN_TIMEOUT_MS = 15_000;
+const REQUEST_TIMEOUT_MS = 120_000;
+
+/** No app window can host a pane now (the window is closed); a launched Chrome can run the browser instead. */
+export class PaneUnavailable extends Error {}
+
+export class PaneProtocolError extends Error {
+ readonly code: number | undefined;
+
+ constructor(message: string, code?: number) {
+ super(message);
+ this.code = code;
+ }
+}
+
+export class PaneLink {
+ readonly #port: PanePort | null;
+ readonly #options: PaneLinkOptions;
+ readonly #browsers = new Map<string, Open>();
+ readonly #opening = new Map<string, { resolve(answer: { version: string; userAgent: string }): void; reject(error: Error): void }>();
+ readonly #pending = new Map<number, Pending>();
+ #resolver: ((botId: string, threadId: string | null) => string | null) | null = null;
+ #ready = false;
+ #next = 0;
+
+ constructor(port: PanePort | null | undefined, options: PaneLinkOptions = {}) {
+ this.#port = port ?? null;
+ this.#options = options;
+ this.#port?.on("message", (event) => {
+ try {
+ const message = paneMessageToServer(event?.data);
+ if (message) this.#receive(message);
+ } catch (error) {
+ console.warn(`browser pane: rejected a message from the app: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ });
+ // The app's own greeting may arrive before this listener exists; asking makes it greet again.
+ this.#post({ op: "hello" });
+ }
+
+ /** True once the desktop app said it shows panes. */
+ get available(): boolean {
+ return this.#ready && this.#port !== null;
+ }
+
+ /** Which profile the panel of a bot (in a conversation) shows; null when it is not a pane. */
+ resolveWith(resolver: (botId: string, threadId: string | null) => string | null): void {
+ this.#resolver = resolver;
+ }
+
+ async open(browser: string, partition: string, egress: number, downloads: string): Promise<OpenedPanes> {
+ if (!this.available) throw new PaneUnavailable("The desktop app does not show browser panes here.");
+ this.close(browser);
+ const answer = await new Promise<{ version: string; userAgent: string }>((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.#opening.delete(browser);
+ // A late answer must not leave panes nobody drives.
+ this.#post({ op: "close", browser });
+ reject(new Error("The desktop app did not open the browser pane in time."));
+ }, this.#options.openTimeoutMs ?? OPEN_TIMEOUT_MS);
+ this.#opening.set(browser, {
+ resolve: (value) => { clearTimeout(timer); resolve(value); },
+ reject: (error) => { clearTimeout(timer); reject(error); },
+ });
+ this.#post({ op: "open", browser, partition, egress, downloads });
+ });
+ const inputs = new Set<() => void>();
+ const channel: PaneChannel = {
+ version: answer.version,
+ userAgent: answer.userAgent,
+ create: (url, background) => this.#request(browser, (req) => ({ op: "create", browser, req, url, ...(background ? { background: true } : {}) })) as Promise<PaneTab>,
+ command: (tab, method, params, session) => this.#request(browser, (req) => ({ op: "cdp", browser, req, tab, method, params, ...(session ? { session } : {}) })) as Promise<Params>,
+ front: (tab) => this.#post({ op: "front", browser, tab }),
+ closeTab: (tab) => this.#post({ op: "close-tab", browser, tab }),
+ cancelDownload: (guid) => this.#post({ op: "cancel-download", browser, guid }),
+ close: () => this.#post({ op: "close", browser }),
+ };
+ const endpoint = new PaneEndpoint(channel, [], this.#options);
+ this.#browsers.set(browser, { endpoint, inputs });
+ endpoint.onClose(() => {
+ if (this.#browsers.get(browser)?.endpoint === endpoint) this.close(browser);
+ });
+ return {
+ endpoint,
+ version: answer.version,
+ onPersonInput: (listener) => {
+ inputs.add(listener);
+ return () => inputs.delete(listener);
+ },
+ };
+ }
+
+ /** Closes every pane of one profile. */
+ close(browser: string): void {
+ const open = this.#browsers.get(browser);
+ if (!open) return;
+ this.#browsers.delete(browser);
+ this.#post({ op: "close", browser });
+ this.#fail(browser, "The browser pane closed.");
+ open.endpoint.closed("the browser pane closed");
+ }
+
+ /** Clears what a profile's partition stored: sign-ins, history, caches. */
+ erase(partition: string): void {
+ if (this.#port) this.#post({ op: "erase", partition });
+ }
+
+ #request(browser: string, message: (req: number) => Outgoing): Promise<Params | PaneTab> {
+ if (!this.#browsers.has(browser)) return Promise.reject(new PaneProtocolError("Target closed"));
+ const req = ++this.#next;
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.#pending.delete(req);
+ reject(new PaneProtocolError("The app did not answer the browser pane in time."));
+ }, this.#options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS);
+ this.#pending.set(req, { browser, resolve: (value) => { clearTimeout(timer); resolve(value); }, reject: (error) => { clearTimeout(timer); reject(error); }, timer });
+ this.#post(message(req));
+ });
+ }
+
+ #fail(browser: string, reason: string): void {
+ for (const [req, pending] of this.#pending) {
+ if (pending.browser !== browser) continue;
+ this.#pending.delete(req);
+ pending.reject(new PaneProtocolError(`Target closed: ${reason}`));
+ }
+ }
+
+ #post(message: Outgoing): void {
+ try {
+ this.#port?.postMessage({ type: PANE_MESSAGE, ...message });
+ } catch (error) {
+ console.warn(`browser pane: could not reach the app: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ }
+
+ #receive(message: PaneToServer): void {
+ switch (message.op) {
+ case "hello":
+ this.#ready = true;
+ for (const browser of this.#browsers.keys()) this.close(browser);
+ return;
+ case "opened":
+ case "failed": {
+ const opening = this.#opening.get(message.browser);
+ this.#opening.delete(message.browser);
+ if (!opening) {
+ if (message.op === "opened" && !this.#browsers.has(message.browser)) this.#post({ op: "close", browser: message.browser });
+ return;
+ }
+ if (message.op === "opened") opening.resolve({ version: message.version, userAgent: message.userAgent });
+ else opening.reject(message.reason === "no-window" ? new PaneUnavailable(message.error) : new Error(message.error));
+ return;
+ }
+ case "created":
+ case "answer": {
+ const pending = this.#pending.get(message.req);
+ if (!pending || pending.browser !== message.browser) return;
+ this.#pending.delete(message.req);
+ if (message.op === "created") pending.resolve({ tab: message.tab, target: message.target, url: message.url, title: message.title });
+ else if (message.error) pending.reject(new PaneProtocolError(String(message.error.message), message.error.code));
+ else pending.resolve(message.result ?? {});
+ return;
+ }
+ case "which": {
+ const browser = this.#resolver?.(message.botId, message.threadId) ?? null;
+ this.#post({ op: "resolved", req: message.req, browser });
+ return;
+ }
+ }
+ const open = this.#browsers.get(message.browser);
+ if (!open) return;
+ switch (message.op) {
+ case "event":
+ open.endpoint.pageEvent(message.tab, message.method, message.params, message.session);
+ return;
+ case "tab":
+ open.endpoint.tabOpened({ tab: message.tab, target: message.target, url: message.url, title: message.title, ...(message.opener ? { opener: message.opener } : {}) });
+ return;
+ case "tab-gone":
+ open.endpoint.tabGone(message.tab, message.crashed === true);
+ return;
+ case "download":
+ open.endpoint.download(message);
+ return;
+ case "input":
+ open.endpoint.personInput(message.tab);
+ for (const listener of open.inputs) {
+ try { listener(); } catch {}
+ }
+ return;
+ case "closed":
+ this.#browsers.delete(message.browser);
+ this.#fail(message.browser, message.reason);
+ open.endpoint.closed(message.reason);
+ return;
+ }
+ }
+}
+
+/** The desktop app's link, on the server it starts as a utility process; null anywhere else. */
+export function desktopPaneLink(managed: boolean): PaneLink | null {
+ const port = (process as NodeJS.Process & { parentPort?: PanePort }).parentPort;
+ return managed && port ? new PaneLink(port) : null;
+}
diff --git a/server/browser/pane/pane.test.ts b/server/browser/pane/pane.test.ts
new file mode 100644
index 0000000000..05b3bc1f61
--- /dev/null
+++ b/server/browser/pane/pane.test.ts
@@ -0,0 +1,387 @@
+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, afterEach, describe, expect, it } from "vitest";
+
+import { PANE_PARTITION } from "../../../electron/browser-pane-wire.mjs";
+import { removeTempDir } from "../../testing/cleanup.ts";
+import { CdpConnection } from "../cdp/connection.ts";
+import { BrowserService } from "../service.ts";
+import { FakeBackend, FakeChrome, type FakeDocument } from "../testing/fake-chrome.ts";
+import { PaneBackend, panePartition } from "./backend.ts";
+import { PaneEndpoint, PERSON_HOLDS_TAB, type PaneChannel } from "./endpoint.ts";
+import { PaneLink } from "./link.ts";
+import { FakeMain } from "./testing/fake-main.ts";
+
+const FORM: FakeDocument = {
+ title: "Sign up",
+ text: "Sign up\nName\nGo",
+ elements: [
+ { role: "heading", name: "Sign up", box: [10, 10, 300, 40] },
+ { role: "textbox", name: "Name", selector: "#name", editable: true, value: "", box: [10, 60, 200, 30] },
+ { role: "button", name: "Go", selector: "#go", box: [10, 100, 80, 30], onClick: (page) => { page.text += "\nHello"; } },
+ ],
+};
+const documents = (url: string): FakeDocument => (url.endsWith("/form") ? FORM : { title: url.split("/").pop() ?? "", text: `page ${url}`, elements: [] });
+const BROWSER_LEVEL = /^(?:Browser\.|Target\.(?:createTarget|closeTarget|getTargets|setDiscoverTargets|attachToTarget|activateTarget))/;
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+const folders: string[] = [];
+const services: BrowserService[] = [];
+afterEach(async () => { await Promise.all(services.splice(0).map((service) => service.closeAll())); });
+afterAll(async () => { for (const folder of folders) await removeTempDir(folder); });
+
+function setup({ quietMs = 1_000, linkOptions = {} }: { quietMs?: number; linkOptions?: ConstructorParameters<typeof PaneLink>[1] } = {}) {
+ const dataDir = mkdtempSync(join(tmpdir(), "omb-browser-pane-"));
+ folders.push(dataDir);
+ const main = new FakeMain(documents);
+ const link = new PaneLink(main, { quietMs, maxHoldMs: 2_000, ...linkOptions });
+ const backend = new PaneBackend(link, dataDir, async () => 41_000, "darwin");
+ const service = new BrowserService({ dataDir, backend: () => backend, maxRunning: 4, idleMs: () => 600_000, takeoverMs: 200 });
+ services.push(service);
+ const target = { session: "bot-a", key: "bot:a" };
+ const call = async (name: string, args: Record<string, unknown> = {}) =>
+ service.agentRpc(target, "tools/call", { name, arguments: args }) as Promise<{ content: Array<{ type: string; text?: string }>; isError?: boolean }>;
+ const text = (result: { content: Array<{ type: string; text?: string }> }) => result.content.map((part) => part.text ?? `[${part.type}]`).join("\n");
+ return { main, link, backend, service, target, call, text, dataDir };
+}
+
+describe("the bots' browser as desktop panes", () => {
+ it("runs the driver's tools on panes that speak page-level CDP only", async () => {
+ const { main, call, text } = setup();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ const opened = text(await call("agent_browser_open", { url: "https://example.com/form" }));
+ expect(opened).toContain("Opened https://example.com/form in t1.");
+ expect(opened).toContain(`textbox "Name" [ref=e1]`);
+ expect(text(await call("agent_browser_fill", { ref: "e1", text: "Ada" }))).toContain("Filled the field.");
+ const clicked = text(await call("agent_browser_click", { ref: "e2" }));
+ expect(clicked).toContain(`Text that appeared on the page: "Hello".`);
+ expect((await call("agent_browser_type", { selector: "#name", text: "b" })).isError).toBeUndefined();
+ expect((await call("agent_browser_press", { key: "Enter" })).isError).toBeUndefined();
+ expect((await call("agent_browser_navigate", { url: "https://example.com/next" })).isError).toBeUndefined();
+ expect(text(await call("agent_browser_snapshot"))).toContain("https://example.com/next");
+ expect(text(await call("agent_browser_screenshot"))).toContain("Screenshot of t1");
+ const page = main.page("p1");
+ expect(page.url).toBe("https://example.com/next");
+ expect(FORM.elements[1]!.value).toBe("Adab");
+ FORM.elements[1]!.value = "";
+ // Nothing browser-level ever reached a pane's own debugger, and only the app was asked to open the tab.
+ expect(main.commands.filter((command) => BROWSER_LEVEL.test(command.method))).toEqual([]);
+ expect(main.toMain.filter((message) => message.op === "create")).toHaveLength(1);
+ expect(main.partitions).toHaveLength(1);
+ expect(main.partitions[0]).toMatch(PANE_PARTITION);
+ expect(main.egress).toEqual([41_000]);
+ });
+
+ it("opens a new tab as another pane and closes every pane with the browser", async () => {
+ const { main, service, call, text } = setup();
+ await call("agent_browser_open", { url: "https://example.com/a" });
+ expect(text(await call("agent_browser_open", { url: "https://example.com/b", tab: "new" }))).toContain("in t2");
+ expect([...main.panes.keys()]).toEqual(["p1", "p2"]);
+ await service.closeAll();
+ expect(main.panes.size).toBe(0);
+ expect(main.toMain.some((message) => message.op === "close")).toBe(true);
+ });
+
+ it("adopts a popup the page opened as a tab with its opener", async () => {
+ const { main, call, text } = setup();
+ await call("agent_browser_open", { url: "https://example.com/a" });
+ await main.popup("p1", "https://accounts.example/sign-in");
+ await sleep(20);
+ const tabs = text(await call("agent_browser_tabs", { action: "list" }));
+ expect(tabs).toContain("accounts.example");
+ });
+
+ it("re-enables page events before each navigation, as a renderer swap drops them", async () => {
+ const { main, call } = setup();
+ await call("agent_browser_open", { url: "https://example.com/a" });
+ main.commands.length = 0;
+ await call("agent_browser_navigate", { url: "https://other.example/b" });
+ const methods = main.commands.map((command) => command.method);
+ const navigate = methods.indexOf("Page.navigate");
+ expect(navigate).toBeGreaterThan(2);
+ expect(methods.slice(navigate - 3, navigate)).toEqual(["Network.enable", "Page.enable", "Page.setLifecycleEventsEnabled"]);
+ });
+
+ it("holds the bot's input while the person uses the page, and drops the bot's refs after", async () => {
+ const { main, call, text } = setup({ quietMs: 300 });
+ await call("agent_browser_open", { url: "https://example.com/form" });
+ main.personInput("bot:a");
+ await sleep(10);
+ const stale = await call("agent_browser_click", { ref: "e2" });
+ expect(stale.isError).toBe(true);
+ expect(text(stale)).toContain("Take a fresh snapshot");
+ main.commands.length = 0;
+ main.personInput("bot:a");
+ await sleep(10);
+ const started = Date.now();
+ expect((await call("agent_browser_click", { selector: "#go" })).isError).toBeUndefined();
+ const input = main.commands.findIndex((command) => command.method.startsWith("Input."));
+ expect(input).toBeGreaterThanOrEqual(0);
+ expect(Date.now() - started).toBeGreaterThanOrEqual(250);
+ });
+
+ it("lets the person hold a tab: the bot's input is refused, its refs drop on release, and the tab says who acted last", async () => {
+ const { main, service, call, text } = setup({ quietMs: 0 });
+ await call("agent_browser_open", { url: "https://example.com/form" });
+ const run = service.profiles()[0]!.run!;
+ const control = run.opened.personControl!;
+ const targetId = run.browser.activePage!.targetId;
+ expect(control.owner(targetId)).toBe(null);
+ control.hold(targetId, true);
+ main.commands.length = 0;
+ expect(control.owner(targetId)).toBe("person");
+ const refused = await call("agent_browser_click", { selector: "#go" });
+ expect(refused.isError).toBe(true);
+ expect(text(refused)).toContain("The person is using this tab.");
+ expect((await call("agent_browser_navigate", { url: "https://example.com/away" })).isError).toBe(true);
+ expect(main.commands.some((command) => command.method.startsWith("Input.") || command.method === "Page.navigate")).toBe(false);
+ control.hold(targetId, false);
+ const stale = await call("agent_browser_click", { ref: "e2" });
+ expect(text(stale)).toContain("Take a fresh snapshot");
+ expect((await call("agent_browser_click", { selector: "#go" })).isError).toBeUndefined();
+ expect(control.owner(targetId)).toBe("bot");
+ main.personInput("bot:a", "p1");
+ await sleep(5);
+ expect(control.owner(targetId)).toBe("person");
+ });
+
+ it("keeps every pane emulating focus, so a pane the person is not in still takes the bot's keys", async () => {
+ const { main, call } = setup();
+ await call("agent_browser_open", { url: "https://example.com/a" });
+ expect(main.commands.filter((command) => command.method === "Emulation.setFocusEmulationEnabled").map((command) => command.params)).toEqual([{ enabled: true }]);
+ });
+
+ it("refuses to emulate a page size on a pane, which the app window sizes", async () => {
+ const { main, call } = setup();
+ await call("agent_browser_open", { url: "https://example.com/a" });
+ const page = [...services[0]!.profiles()][0]!.run!.browser.activePage!;
+ await expect(page.emulateSize({ width: 400, height: 300 }, 1)).rejects.toThrow(/sized by the app window/);
+ expect(main.commands.some((command) => command.method === "Emulation.setDeviceMetricsOverride")).toBe(false);
+ });
+
+ it("fails to open when the app has not said it shows panes", async () => {
+ const dataDir = mkdtempSync(join(tmpdir(), "omb-browser-pane-"));
+ folders.push(dataDir);
+ const silent = { on: () => undefined, postMessage: () => undefined };
+ const link = new PaneLink(silent);
+ expect(link.available).toBe(false);
+ const backend = new PaneBackend(link, dataDir, async () => 41_000);
+ await expect(backend.open({ key: "bot:a", mode: "headless", fresh: false, viewport: { width: 1280, height: 720 }, downloadDir: dataDir })).rejects.toThrow(/does not show browser panes/);
+ expect(new PaneLink(null).available).toBe(false);
+ });
+});
+
+describe("what a held pane lets the bot do", () => {
+ it("reads only: no input, script writes, dialog answers or tab switches on the page or its frames", async () => {
+ const { main, service, call, text } = setup({ quietMs: 0 });
+ await call("agent_browser_open", { url: "https://example.com/form" });
+ await call("agent_browser_open", { url: "https://example.com/other", tab: "new" });
+ const run = service.profiles()[0]!.run!;
+ const [first, second] = run.browser.pages();
+ run.opened.personControl!.hold(first!.targetId, true);
+ main.commands.length = 0;
+ // The person holds t1: the bot may not bring it back or switch the front tab away from them.
+ expect(text(await call("agent_browser_click", { selector: "#go", tab: "t1" }))).toContain("The person is using this tab.");
+ const connection = run.browser.connection;
+ const page = connection.session(first!.session.id!)!;
+ await expect(page.send("Runtime.callFunctionOn", { functionDeclaration: "function () { this.value = 1; }", objectId: "x" })).rejects.toThrow(PERSON_HOLDS_TAB);
+ await expect(page.send("Page.handleJavaScriptDialog", { accept: true })).rejects.toThrow(PERSON_HOLDS_TAB);
+ await expect(page.send("DOM.scrollIntoViewIfNeeded", { backendNodeId: 1 })).rejects.toThrow(PERSON_HOLDS_TAB);
+ await expect(connection.root.send("Target.activateTarget", { targetId: second!.targetId })).rejects.toThrow(PERSON_HOLDS_TAB);
+ await expect(second!.session.send("Page.bringToFront")).rejects.toThrow(PERSON_HOLDS_TAB);
+ // A frame of the held page is held too.
+ main.post({ op: "event", browser: "bot:a", tab: "p1", method: "Target.attachedToTarget", params: { sessionId: "IFRAME1", targetInfo: { targetId: "F", type: "iframe", url: "", title: "" }, waitingForDebugger: false } });
+ await sleep(5);
+ const frame = connection.session("pane-p1:IFRAME1")!;
+ await expect(frame.send("Input.dispatchKeyEvent", { type: "keyDown", key: "a" })).rejects.toThrow(PERSON_HOLDS_TAB);
+ // Reads still run, a script call the driver marks read-only included.
+ expect((await page.send<{ result: { value?: unknown } }>("Runtime.evaluate", { expression: "document.title", contextId: 1, returnByValue: true }, { readOnly: true })).result).toBeDefined();
+ const snapshot = await call("agent_browser_snapshot", { tab: "t1" });
+ expect(snapshot.isError, text(snapshot)).toBeUndefined();
+ expect(main.commands.some((command) => /^(?:Input\.|Page\.handleJavaScriptDialog|DOM\.scrollIntoViewIfNeeded)/.test(command.method))).toBe(false);
+ expect(main.commands.some((command) => command.method === "Runtime.callFunctionOn" && String(command.params.functionDeclaration).includes("this.value = 1"))).toBe(false);
+ expect(main.toMain.filter((message) => message.op === "front").map((message) => (message as { tab: string }).tab)).toEqual(["p1"]);
+ });
+
+ it("opens a bot's new tab behind the one the person holds", async () => {
+ const { main, service, call } = setup({ quietMs: 0 });
+ await call("agent_browser_open", { url: "https://example.com/a" });
+ const run = service.profiles()[0]!.run!;
+ run.opened.personControl!.hold(run.browser.activePage!.targetId, true);
+ await call("agent_browser_open", { url: "https://example.com/b", tab: "new" });
+ expect(main.toMain.filter((message) => message.op === "create").map((message) => (message as { background?: boolean }).background)).toEqual([undefined, true]);
+ });
+});
+
+describe("the pane's downloads", () => {
+ it("are saved to the profile's download folder by the app and tracked as a launched Chrome's are", async () => {
+ const { main, service, call } = setup();
+ await call("agent_browser_open", { url: "https://example.com/a" });
+ const run = service.profiles()[0]!.run!;
+ const folder = main.downloadDirs[0]!;
+ expect(folder).toBe(service.profiles()[0]!.downloadDir);
+ const guid = "0b7c4a52-4f0a-4b8e-9d55-0a1f2b3c4d5e";
+ mkdirSync(folder, { recursive: true });
+ writeFileSync(join(folder, guid), "report");
+ main.post({ op: "download", browser: "bot:a", tab: "p1", guid, state: "begin", url: "https://example.com/report.csv", name: "report.csv" });
+ main.post({ op: "download", browser: "bot:a", tab: "p1", guid, state: "completed", received: 6, total: 6, path: join(folder, guid) });
+ const done = await run.browser.downloads!.finished((download) => download.guid === guid, 2_000);
+ expect(done.state).toBe("completed");
+ expect(done.owner).toBe(run.browser.activePage!.targetId);
+ expect(readFileSync(done.path!, "utf8")).toBe("report");
+ await run.browser.connection.root.send("Browser.cancelDownload", { guid });
+ expect(main.toMain.some((message) => message.op === "cancel-download")).toBe(true);
+ });
+});
+
+describe("when the app cannot host a pane or does not answer", () => {
+ it("starts the browser on the launched Chrome while no app window can host a pane", async () => {
+ const { main, service, backend, call, text } = setup();
+ const fallback = new FakeBackend(() => new FakeChrome({ documents }));
+ backend.fallBackTo(fallback);
+ main.noWindow = true;
+ expect(text(await call("agent_browser_open", { url: "https://example.com/form" }))).toContain("Opened https://example.com/form in t1.");
+ expect(fallback.chromes).toHaveLength(1);
+ expect(main.panes.size).toBe(0);
+ expect(backend.used("bot:a")).toBe(false);
+ expect(service.profiles()[0]!.run).not.toBeNull();
+ });
+
+ it("fails a command the app never answers, and closes panes whose opening answered too late", async () => {
+ const { main, link } = setup({ linkOptions: { requestTimeoutMs: 50, openTimeoutMs: 50 } });
+ await sleep(5);
+ main.openDelayMs = 120;
+ await expect(link.open("bot:late", panePartition(folders.at(-1)!, "bot:late"), 41_000, folders.at(-1)!)).rejects.toThrow(/did not open the browser pane in time/);
+ await sleep(150);
+ expect(main.toMain.filter((message) => message.op === "close" && message.browser === "bot:late").length).toBeGreaterThanOrEqual(2);
+ main.openDelayMs = 0;
+ const opened = await link.open("bot:b", panePartition(folders.at(-1)!, "bot:b"), 41_000, folders.at(-1)!);
+ main.hang = () => true;
+ const connection = new CdpConnection(opened.endpoint, { defaultTimeoutMs: 0 });
+ opened.endpoint.tabOpened({ tab: "p1", target: "F1", url: "about:blank", title: "" });
+ await connection.root.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: false, flatten: true });
+ await expect(connection.session("pane-p1")!.send("Page.getFrameTree")).rejects.toThrow(/did not answer the browser pane in time/);
+ connection.close();
+ });
+});
+
+describe("deleting a bot's browser with the pane", () => {
+ it("clears a partition only for a profile whose panes ever opened here", async () => {
+ const { main, backend, call } = setup();
+ expect(backend.used("bot:a")).toBe(false);
+ await call("agent_browser_open", { url: "https://example.com/a" });
+ expect(backend.used("bot:a")).toBe(true);
+ backend.erase("bot:b");
+ expect(main.toMain.some((message) => message.op === "erase")).toBe(false);
+ backend.erase("bot:a");
+ expect(main.toMain.filter((message) => message.op === "erase")).toEqual([{ type: "openmausbot:browser-pane", op: "erase", partition: main.partitions[0] }]);
+ expect(backend.used("bot:a")).toBe(false);
+ });
+});
+
+describe("the pane partition", () => {
+ it("is per profile and per data folder, and in memory for a temporary profile", async () => {
+ const one = mkdtempSync(join(tmpdir(), "omb-browser-pane-"));
+ const two = mkdtempSync(join(tmpdir(), "omb-browser-pane-"));
+ folders.push(one, two);
+ expect(panePartition(one, "bot:a")).toMatch(/^persist:omb-pane-[0-9a-f]{24}$/);
+ expect(panePartition(one, "bot:a")).toBe(panePartition(one, "bot:a"));
+ expect(panePartition(one, "bot:a")).not.toBe(panePartition(one, "bot:b"));
+ expect(panePartition(one, "bot:a")).not.toBe(panePartition(two, "bot:a"));
+ expect(panePartition(one, "temp:guest-1", () => "0a1b2c3d")).toMatch(/^omb-pane-[0-9a-f]{24}-0a1b2c3d$/);
+ for (const partition of [panePartition(one, "shared:p1"), panePartition(one, "temp:guest-1")]) expect(partition).toMatch(PANE_PARTITION);
+ });
+});
+
+describe("the pane link", () => {
+ it("answers which profile a bot's panel shows, and ignores what is not a pane message", async () => {
+ const main = new FakeMain();
+ const link = new PaneLink(main);
+ link.resolveWith((botId) => (botId === "a" ? `bot:${botId}` : null));
+ await sleep(5);
+ expect(link.available).toBe(true);
+ main.toMain.length = 0;
+ main.post({ op: "which", req: 1, botId: "a", threadId: null });
+ main.post({ op: "which", req: 2, botId: "b", threadId: "t-1" });
+ await sleep(5);
+ expect(main.toMain).toEqual([
+ { type: "openmausbot:browser-pane", op: "resolved", req: 1, browser: "bot:a" },
+ { type: "openmausbot:browser-pane", op: "resolved", req: 2, browser: null },
+ ]);
+ expect(() => main.post({ op: "which", req: 3, botId: "a b", threadId: null })).toThrow(/malformed/);
+ });
+});
+
+describe("the pane endpoint", () => {
+ function channel(sent: Array<{ tab: string; method: string; params: Record<string, unknown>; session?: string }>): PaneChannel {
+ return {
+ version: "146.0.7680.0",
+ userAgent: "Mozilla/5.0 Chrome/146.0.0.0",
+ create: async () => ({ tab: "p9", target: "F9", url: "about:blank", title: "" }),
+ command: async (tab, method, params, session) => { sent.push({ tab, method, params, ...(session ? { session } : {}) }); return {}; },
+ front: () => {},
+ closeTab: () => {},
+ cancelDownload: () => {},
+ close: () => {},
+ };
+ }
+
+ it("keeps two panes' iframe sessions apart and routes each back to its own pane", async () => {
+ const sent: Array<{ tab: string; method: string; params: Record<string, unknown>; session?: string }> = [];
+ const endpoint = new PaneEndpoint(channel(sent), [{ tab: "p1", target: "F1", url: "https://a.test/", title: "A" }, { tab: "p2", target: "F2", url: "https://b.test/", title: "B" }]);
+ const connection = new CdpConnection(endpoint);
+ await connection.root.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true });
+ expect(connection.session("pane-p1")?.kind).toBe("page");
+ for (const tab of ["p1", "p2"]) {
+ endpoint.pageEvent(tab, "Target.attachedToTarget", { sessionId: "F00D", targetInfo: { targetId: "frame", type: "iframe", url: "", title: "" }, waitingForDebugger: false });
+ }
+ await sleep(1);
+ const first = connection.session("pane-p1:F00D");
+ const second = connection.session("pane-p2:F00D");
+ expect(first?.kind).toBe("frame");
+ expect(second?.kind).toBe("frame");
+ await second!.send("Page.getFrameTree");
+ expect(sent.at(-1)).toEqual({ tab: "p2", method: "Page.getFrameTree", params: {}, session: "F00D" });
+ await connection.session("pane-p1")!.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true });
+ expect(sent.at(-1)).toEqual({ tab: "p1", method: "Target.setAutoAttach", params: { autoAttach: true, waitForDebuggerOnStart: false, flatten: true } });
+ const version = await connection.root.send<{ product: string }>("Browser.getVersion");
+ expect(version.product).toBe("Chrome/146.0.7680.0");
+ await expect(connection.root.send("Storage.getCookies", {})).rejects.toThrow(/not available on a desktop pane/);
+ connection.close();
+ });
+
+ it("sends a viewer's screencast frames to that viewer only, and stops the screencast when the last one leaves", async () => {
+ const sent: Array<{ tab: string; method: string; params: Record<string, unknown>; session?: string }> = [];
+ const endpoint = new PaneEndpoint(channel(sent), [{ tab: "p1", target: "F1", url: "https://a.test/", title: "A" }]);
+ const connection = new CdpConnection(endpoint);
+ await connection.root.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true });
+ const { sessionId } = await connection.root.send<{ sessionId: string }>("Target.attachToTarget", { targetId: "F1", flatten: true });
+ const viewer = connection.session(sessionId)!;
+ const frames: string[] = [];
+ viewer.on("Page.screencastFrame", () => frames.push("viewer"));
+ connection.session("pane-p1")!.on("Page.screencastFrame", () => frames.push("page"));
+ await viewer.send("Page.startScreencast", { format: "jpeg" });
+ endpoint.pageEvent("p1", "Page.screencastFrame", { data: "", sessionId: 1, metadata: {} });
+ await sleep(1);
+ expect(frames).toEqual(["viewer"]);
+ await connection.root.send("Target.detachFromTarget", { sessionId });
+ expect(sent.map((command) => command.method)).toEqual(["Page.startScreencast", "Page.stopScreencast"]);
+ connection.close();
+ });
+
+ it("tells the driver a pane is gone, crashed or closed", async () => {
+ const endpoint = new PaneEndpoint(channel([]), [{ tab: "p1", target: "F1", url: "https://a.test/", title: "A" }]);
+ const connection = new CdpConnection(endpoint);
+ const events: string[] = [];
+ for (const method of ["Target.targetCrashed", "Target.detachedFromTarget", "Target.targetDestroyed"]) connection.root.on(method, () => events.push(method));
+ await connection.root.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true });
+ const page = connection.session("pane-p1")!;
+ endpoint.tabGone("p1", true);
+ await sleep(1);
+ expect(events).toEqual(["Target.targetCrashed", "Target.detachedFromTarget", "Target.targetDestroyed"]);
+ expect(page.detached).toBe(true);
+ endpoint.closed("the app window closed");
+ expect(connection.closed).toBe(true);
+ });
+});
diff --git a/server/browser/pane/testing/fake-main.ts b/server/browser/pane/testing/fake-main.ts
new file mode 100644
index 0000000000..6f3065bb26
--- /dev/null
+++ b/server/browser/pane/testing/fake-main.ts
@@ -0,0 +1,180 @@
+// The desktop main process's side of the pane messages, for unit tests: each pane is one FakeChrome page reached only
+// through a page-level session, as an Electron webContents debugger is, and every command a pane got is recorded.
+import { PANE_MESSAGE, paneMessageToMain, paneMessageToServer, type PaneToMain } from "../../../../electron/browser-pane-wire.mjs";
+import { FakeChrome, type FakeDocument, type FakePage } from "../../testing/fake-chrome.ts";
+import type { PanePort } from "../link.ts";
+
+interface FakePane {
+ tab: string;
+ targetId: string;
+ session: string;
+ browser: string;
+}
+
+export interface PaneCommand {
+ tab: string;
+ method: string;
+ params: Record<string, unknown>;
+ session?: string;
+}
+
+export class FakeMain implements PanePort {
+ readonly chrome: FakeChrome;
+ readonly commands: PaneCommand[] = [];
+ readonly toMain: PaneToMain[] = [];
+ readonly partitions: string[] = [];
+ readonly egress: number[] = [];
+ readonly downloadDirs: string[] = [];
+ /** No app window: opening answers that none can host a pane. */
+ noWindow = false;
+ /** Milliseconds before an open is answered. */
+ openDelayMs = 0;
+ /** Commands main never answers. */
+ hang: (command: PaneCommand) => boolean = () => false;
+ readonly panes = new Map<string, FakePane>();
+ /** Answers a pane's command before FakeChrome does; undefined lets it through. */
+ answer: (command: PaneCommand) => Record<string, unknown> | undefined = () => undefined;
+ readonly #listeners = new Set<(event: { data?: unknown }) => void>();
+ readonly #replies = new Map<number, (message: { result?: Record<string, unknown>; error?: { message: string } }) => void>();
+ #id = 1_000;
+ #tab = 0;
+
+ constructor(documents?: (url: string) => FakeDocument) {
+ this.chrome = new FakeChrome({ startUrls: [], ...(documents ? { documents } : {}) });
+ this.chrome.onMessage((text) => this.#fromChrome(JSON.parse(text) as Record<string, unknown>));
+ }
+
+ // PanePort, as the server sees it.
+ on(_event: "message", listener: (event: { data?: unknown }) => void): void {
+ this.#listeners.add(listener);
+ }
+
+ postMessage(message: object): void {
+ const parsed = paneMessageToMain(message);
+ if (!parsed) throw new Error(`the server sent a malformed pane message: ${JSON.stringify(message)}`);
+ this.toMain.push(parsed);
+ void this.#handle(parsed);
+ }
+
+ hello(): void {
+ this.post({ op: "hello" });
+ }
+
+ post(message: Record<string, unknown>): void {
+ const data = { type: PANE_MESSAGE, ...message };
+ if (!paneMessageToServer(data)) throw new Error(`the fake main sent a malformed pane message: ${JSON.stringify(data)}`);
+ queueMicrotask(() => { for (const listener of this.#listeners) listener({ data }); });
+ }
+
+ page(tab: string): FakePage {
+ const pane = this.panes.get(tab);
+ const page = pane && this.chrome.pages.get(pane.targetId);
+ if (!page) throw new Error(`no pane ${tab}`);
+ return page;
+ }
+
+ /** A page opens a popup, as window.open does: main makes it a pane of the same profile. */
+ async popup(opener: string, url: string): Promise<string> {
+ const pane = this.panes.get(opener)!;
+ const created = await this.#open(pane.browser, url);
+ this.post({ op: "tab", browser: pane.browser, tab: created.tab, target: created.targetId, url, title: "", opener });
+ return created.tab;
+ }
+
+ personInput(browser: string, tab?: string): void {
+ this.post({ op: "input", browser, ...(tab ? { tab } : {}) });
+ }
+
+ async #handle(message: PaneToMain): Promise<void> {
+ switch (message.op) {
+ case "hello":
+ this.hello();
+ return;
+ case "open":
+ this.partitions.push(message.partition);
+ this.egress.push(message.egress);
+ this.downloadDirs.push(message.downloads);
+ if (this.openDelayMs) await new Promise((resolve) => setTimeout(resolve, this.openDelayMs));
+ if (this.noWindow) this.post({ op: "failed", browser: message.browser, error: "The app window is closed.", reason: "no-window" });
+ else this.post({ op: "opened", browser: message.browser, version: "146.0.7680.0", userAgent: "Mozilla/5.0 Chrome/146.0.0.0 Safari/537.36" });
+ return;
+ case "create": {
+ const pane = await this.#open(message.browser, message.url);
+ const page = this.chrome.pages.get(pane.targetId)!;
+ this.post({ op: "created", browser: message.browser, req: message.req, tab: pane.tab, target: pane.targetId, url: page.url, title: page.title });
+ return;
+ }
+ case "cdp": {
+ const command = { tab: message.tab, method: message.method, params: message.params, ...(message.session ? { session: message.session } : {}) };
+ this.commands.push(command);
+ if (this.hang(command)) return;
+ const pane = this.panes.get(message.tab);
+ const answered = this.answer(command);
+ if (answered !== undefined) {
+ this.post({ op: "answer", browser: message.browser, req: message.req, result: answered });
+ return;
+ }
+ if (!pane) {
+ this.post({ op: "answer", browser: message.browser, req: message.req, error: { message: "Target closed" } });
+ return;
+ }
+ const reply = await this.#send(message.method, message.params, message.session ?? pane.session);
+ this.post({ op: "answer", browser: message.browser, req: message.req, ...(reply.error ? { error: reply.error } : { result: reply.result ?? {} }) });
+ return;
+ }
+ case "close-tab":
+ await this.#closeTab(message.tab);
+ return;
+ case "close":
+ for (const pane of this.panes.values()) if (pane.browser === message.browser) await this.#closeTab(pane.tab, false);
+ this.post({ op: "closed", browser: message.browser, reason: "closed by the app" });
+ return;
+ default:
+ return;
+ }
+ }
+
+ async #open(browser: string, url: string): Promise<FakePane> {
+ const { result } = await this.#send("Target.createTarget", { url: "about:blank" }, null);
+ const targetId = String(result?.targetId);
+ const attached = await this.#send("Target.attachToTarget", { targetId, flatten: true }, null);
+ const pane = { tab: `p${++this.#tab}`, targetId, session: String(attached.result?.sessionId), browser };
+ this.panes.set(pane.tab, pane);
+ if (url !== "about:blank") await this.#send("Page.navigate", { url }, pane.session);
+ return pane;
+ }
+
+ async #closeTab(tab: string, announce = true): Promise<void> {
+ const pane = this.panes.get(tab);
+ if (!pane) return;
+ this.panes.delete(tab);
+ await this.#send("Target.closeTarget", { targetId: pane.targetId }, null);
+ if (announce) this.post({ op: "tab-gone", browser: pane.browser, tab });
+ }
+
+ #send(method: string, params: Record<string, unknown>, sessionId: string | null): Promise<{ result?: Record<string, unknown>; error?: { message: string } }> {
+ const id = ++this.#id;
+ return new Promise((resolve) => {
+ this.#replies.set(id, resolve);
+ this.chrome.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
+ });
+ }
+
+ #fromChrome(message: Record<string, unknown>): void {
+ if (typeof message.id === "number") {
+ const reply = this.#replies.get(message.id);
+ this.#replies.delete(message.id);
+ reply?.(message as { result?: Record<string, unknown>; error?: { message: string } });
+ return;
+ }
+ if (message.method === "Target.targetInfoChanged") {
+ const info = (message.params as { targetInfo: { targetId: string; url: string; title: string } }).targetInfo;
+ const pane = [...this.panes.values()].find((candidate) => candidate.targetId === info.targetId);
+ if (pane) this.post({ op: "tab", browser: pane.browser, tab: pane.tab, target: pane.targetId, url: info.url, title: info.title });
+ return;
+ }
+ const pane = [...this.panes.values()].find((candidate) => candidate.session === message.sessionId);
+ if (!pane || typeof message.method !== "string") return;
+ this.post({ op: "event", browser: pane.browser, tab: pane.tab, method: message.method, params: message.params ?? {} });
+ }
+}
diff --git a/server/browser/service.ts b/server/browser/service.ts
index 4730ffc17e..6420fb942d 100644
--- a/server/browser/service.ts
+++ b/server/browser/service.ts
@@ -241,6 +241,7 @@ export class BrowserService {
if (profile.tabs.remove(page.targetId)) profile.hub.tabsChanged();
}));
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(); }));
try {
this.#stillWanted(profile, epoch);
await browser.waitForPage(() => true, 15_000);
diff --git a/server/host/browser.ts b/server/host/browser.ts
index fc85cbe23a..fe2273f209 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, type BrowserEngineKind } from "../browser/config.ts";
+import { browserEngineKind, browserPaneWanted, 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";
@@ -47,6 +47,8 @@ import { browserProcessTree } from "../browser-processes.ts";
import { pssBytes } from "../bot-memory-cap.ts";
import { boxMemory } from "../box-memory.ts";
import { CHROME_BROWSER_SYSTEM_PROMPT } from "../browser/prompt.ts";
+import { PaneBackend } from "../browser/pane/backend.ts";
+import { desktopPaneLink } from "../browser/pane/link.ts";
import { passkeyAnnotation } from "../browser/passkey-notice.ts";
import { LentChromeDoors, lentChromeGuidance, type ChromeLender } from "../browser/lent-chrome.ts";
import type { ChromeRoute } from "../device-links.ts";
@@ -166,9 +168,11 @@ export function createBrowserHost(deps: BrowserHostDeps) {
const configured = browserIdleMs(cfg, { cloudHome: Boolean(CLOUD_HOME) });
return idleAfter(configured, Math.min(configured, BROWSER_IDLE_FLOOR_MS), deps.engineMemory?.roomFactor?.() ?? 1);
};
+ const paneLink = desktopPaneLink(DESKTOP_MANAGED);
const chromeEngine = new ChromeEngine({
dataDir: DATA_DIR,
host,
+ ...(paneLink ? { pane: { backend: new PaneBackend(paneLink, DATA_DIR, (key) => browserEgress.open(key)), wanted: () => browserPaneWanted(cfg) } } : {}),
egressPort: (key) => browserEgress.open(key),
egressNotice: (key) => browserEgress.takeNotice(key),
idleMs,
@@ -441,6 +445,13 @@ export function createBrowserHost(deps: BrowserHostDeps) {
const target = profile && profile !== "guest" ? browserProfilePartitionTarget(cfg, profile) : null;
return { session, spec: chromeEngine.spec(session, profileKey(botId + suffix, session, { guest: profile === "guest", partitionId: target ? target.partitionId + suffix : null })) };
}
+ /** The profile a bot's panel shows as desktop panes, or null when its browser is not one. */
+ paneLink?.resolveWith((botId, threadId) => {
+ const bot = store.bot(botId);
+ if (!bot || bot.browser === false || !browserPaneWanted(cfg) || !onChrome(bot.browserProfile)) return null;
+ const { session, spec } = chromeSpec(botId, bot.browserProfile, browserAudience(threadId ?? undefined));
+ return chromeTarget(session, spec)?.key ?? null;
+ });
/** Chrome for the new engine, the installed agent-browser otherwise. */
function browserReady(profile: string | undefined): boolean {
return onChrome(profile) ? chromeEngine.summary().kind === "engine" : browserEngineStatus().kind === "ready";
@@ -693,7 +704,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {
return { binaryPath: engine.binaryPath, session, env: browserSessionSpec(engine.binaryPath, session, profile, await browserEgress.open(session)).env, encryptionKey: browserEngineEncryptionKey() };
}
/** What Settings shows of the engine that runs bots' browsers here; My Chrome stays on agent-browser. */
- function engineSummary<T extends { kind: "engine" | "unavailable"; myChrome: boolean }>(agentBrowser: T): (T | (ReturnType<ChromeEngine["summary"]> & { myChrome: boolean })) & { engine: BrowserEngineKind; noChrome?: true; serverSites?: boolean; proxyConfigured?: boolean; proxySaved?: boolean } {
+ function engineSummary<T extends { kind: "engine" | "unavailable"; myChrome: boolean }>(agentBrowser: T): (T | (ReturnType<ChromeEngine["summary"]> & { myChrome: boolean })) & { engine: BrowserEngineKind; pane?: true; noChrome?: true; serverSites?: boolean; proxyConfigured?: boolean; proxySaved?: boolean } {
const serverSites = sitesSwitch ? { serverSites: cfg.browserEngine?.egress?.localNetwork === true } : {};
const engine = browserEngineKind(cfg);
const proxyValue = cfg.browserEngine?.egress?.proxy;
@@ -701,6 +712,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {
const proxyConfigured = builtInBrowserEnabled(cfg) && !hostedServer && parseSocks5Proxy(proxyValue) !== null;
return {
...(engine === "chrome" ? { ...chromeEngine.summary(), myChrome: agentBrowser.myChrome, ...lentChromeSummary(), engine } : { ...agentBrowser, engine }),
+ ...(paneLink?.available && browserPaneWanted(cfg) ? { pane: true as const } : {}),
...(engine !== "chrome" && agentBrowser.kind === "engine" && chromeLauncher.runsShellForWantOfChrome() ? { noChrome: true as const } : {}),
...serverSites,
...(proxyConfigured ? { proxyConfigured: true } : {}),
diff --git a/src/components/BrowserPanel.pane.dom.test.ts b/src/components/BrowserPanel.pane.dom.test.ts
new file mode 100644
index 0000000000..20e3def4c5
--- /dev/null
+++ b/src/components/BrowserPanel.pane.dom.test.ts
@@ -0,0 +1,92 @@
+// @vitest-environment happy-dom
+// On the desktop app with browserEngine.surface "pane", the panel tells the app where its page area is, and the
+// app's native view hides whenever an overlay covers it; with the setting off the panel never asks.
+import { createElement } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { Bot } from "@/state/store";
+
+const engine: { engine: string; kind: string; pane?: true } = { engine: "chrome", kind: "engine" };
+vi.mock("@/state/store", async (importOriginal) => {
+ const original = await importOriginal<typeof import("@/state/store")>();
+ return { ...original, useStore: () => ({ state: { ...original.initialState, config: { browserEngine: engine } }, dispatch: vi.fn() }) };
+});
+vi.mock("@/lib/page-visible", () => ({ usePageVisible: () => true }));
+vi.mock("@/lib/browser-pip", () => ({ supportsBrowserPictureInPicture: () => false, useBrowserPictureInPicture: () => "" }));
+vi.mock("./browser/StreamSurface", async () => {
+ const { useEffect } = await import("react");
+ return {
+ StreamSurface: (props: { onConnectedChange(next: boolean): void }) => {
+ useEffect(() => { props.onConnectedChange(true); }, []);
+ return null;
+ },
+ };
+});
+vi.mock("./browser/BrowserProfilesManager", () => ({ BrowserProfilesManager: () => null }));
+vi.mock("./browser/MoreMenu", () => ({ MoreMenu: () => null }));
+vi.mock("./browser/PasskeyNotice", () => ({ PasskeyNotice: () => null }));
+
+const { LiveBrowser } = await import("./BrowserPanel");
+
+const bot: Bot = {
+ id: "scout", threadId: "thread-scout", name: "Scout", title: "Researcher", description: "", soul: "",
+ notifications: true, color: "green", unread: false, messages: [],
+ modelSelection: { instanceId: "claude", model: "claude-opus-5-5" },
+};
+const RECT = { left: 300, top: 120, width: 900, height: 700, right: 1200, bottom: 820, x: 300, y: 120, toJSON: () => ({}) };
+const settle = async () => {
+ for (let i = 0; i < 4; i++) await new Promise((resolve) => setTimeout(resolve, 0));
+};
+
+let host: HTMLDivElement;
+let root: Root;
+let show: ReturnType<typeof vi.fn>;
+const pageArea = () => host.querySelector("[data-native-view-host]");
+
+beforeEach(() => {
+ show = vi.fn(async () => ({ shown: true }));
+ (window as unknown as { ogb: unknown }).ogb = { browserPane: { show } };
+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue(RECT as DOMRect);
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+});
+afterEach(() => {
+ flushSync(() => root.unmount());
+ host.remove();
+ delete engine.pane;
+ delete (window as unknown as { ogb?: unknown }).ogb;
+ vi.restoreAllMocks();
+});
+
+describe("the browser panel's native pane", () => {
+ it("never asks the app for a pane while the setting is off", async () => {
+ flushSync(() => root.render(createElement(LiveBrowser, { bot })));
+ await settle();
+ expect(show).not.toHaveBeenCalled();
+ expect(pageArea()).toBeNull();
+ });
+
+ it("shows the pane over the page area once connected, and hides it under an overlay and on leaving", async () => {
+ engine.pane = true;
+ flushSync(() => root.render(createElement(LiveBrowser, { bot })));
+ await settle();
+ expect(pageArea()).not.toBeNull();
+ expect(show).toHaveBeenLastCalledWith({ botId: "scout", threadId: null, profile: null, bounds: { x: 300, y: 120, width: 900, height: 700 }, visible: true });
+
+ const overlay = document.createElement("div");
+ overlay.setAttribute("role", "menu");
+ overlay.style.opacity = "1";
+ document.body.append(overlay);
+ await settle();
+ expect(show.mock.calls.at(-1)?.[0]).toMatchObject({ visible: false });
+ overlay.remove();
+ await settle();
+ expect(show.mock.calls.at(-1)?.[0]).toMatchObject({ visible: true });
+
+ flushSync(() => root.unmount());
+ expect(show.mock.calls.at(-1)?.[0]).toEqual({ botId: "scout", threadId: null, profile: null, bounds: null, visible: false });
+ root = createRoot(host);
+ });
+});
diff --git a/src/components/BrowserPanel.tsx b/src/components/BrowserPanel.tsx
index 41d58a4289..96c07296f4 100644
--- a/src/components/BrowserPanel.tsx
+++ b/src/components/BrowserPanel.tsx
@@ -18,6 +18,7 @@ import { createLiveStreamClient, type LiveResume, type LiveStreamClient } from "
import { BROWSER_HELD_ELSEWHERE } from "../../shared/browser-held";
import { passkeyWallAt } from "../../shared/passkey-wall";
import { browserScope, withBrowserScope } from "@/lib/team-browser";
+import { useNativeViewObscured } from "@/lib/native-view-obscured";
const button = "rounded-md p-1.5 text-ink-secondary hover:bg-inset hover:text-ink disabled:opacity-40 disabled:cursor-not-allowed";
const NO_NAV: BrowserNav = { url: "", loading: false, canGoBack: false, canGoForward: false };
@@ -66,6 +67,7 @@ export function LiveBrowser({ bot, signIn, page }: { bot: Bot; signIn?: BrowserS
const floating = useBrowserPictureInPicture();
const pageVisible = usePageVisible();
const panel = useRef<HTMLDivElement>(null);
+ const pageArea = useRef<HTMLDivElement>(null);
const address = useRef<HTMLInputElement>(null);
const surface = useRef<StreamSurfaceHandle>(null);
const profilesDialog = useRef<HTMLDialogElement>(null);
@@ -288,6 +290,36 @@ export function LiveBrowser({ bot, signIn, page }: { bot: Bot; signIn?: BrowserS
setError("");
}, [shown]);
const typingReady = connected && you;
+ // The desktop app shows this browser natively over the page area; the stream underneath shows through any overlay.
+ const paneMode = stream && state.config?.browserEngine?.pane === true && Boolean(window.ogb?.browserPane);
+ const obscured = useNativeViewObscured(showProfiles || showTyping, paneMode);
+ const paneVisible = paneMode && shown && connected && !asleep && !heldElsewhere && !gone && !starting && !obscured;
+ const paneShown = useRef(paneVisible);
+ const placePane = useRef<() => void>(() => {});
+ paneShown.current = paneVisible;
+ useEffect(() => {
+ const bridge = window.ogb?.browserPane;
+ if (!paneMode || !bridge) return;
+ const threadId = scopedThread ?? null;
+ const profile = bot.browserProfile ?? null;
+ const place = () => {
+ const rect = pageArea.current?.getBoundingClientRect();
+ const bounds = rect && rect.width >= 1 && rect.height >= 1
+ ? { x: Math.round(rect.left), y: Math.round(rect.top), width: Math.round(rect.width), height: Math.round(rect.height) } : null;
+ void bridge.show({ botId: bot.id, threadId, profile, bounds, visible: paneShown.current && bounds !== null }).catch(() => undefined);
+ };
+ placePane.current = place;
+ const observer = new ResizeObserver(place);
+ if (pageArea.current) observer.observe(pageArea.current);
+ window.addEventListener("resize", place);
+ return () => {
+ placePane.current = () => {};
+ observer.disconnect();
+ window.removeEventListener("resize", place);
+ void bridge.show({ botId: bot.id, threadId, profile, bounds: null, visible: false }).catch(() => undefined);
+ };
+ }, [paneMode, bot.id, bot.browserProfile, scopedThread]);
+ useEffect(() => { placePane.current(); }, [paneVisible, paneMode, bot.id, bot.browserProfile, scopedThread]);
const pipSupported = stream && supportsBrowserPictureInPicture();
const passkeyWall = passkeyWallAt(nav.url);
return <div ref={panel} className={maximized
@@ -341,7 +373,7 @@ export function LiveBrowser({ bot, signIn, page }: { bot: Bot; signIn?: BrowserS
{(error || (notReaching && connected)) && <div role="alert" className="flex shrink-0 items-center justify-between gap-2 border-b border-hairline/30 px-3 py-2 text-[12px] text-danger"><span>{notReaching && connected ? t("browser.input.notReaching") : error}</span>{(!connected || notReaching) && <button className="shrink-0 underline" onClick={reconnect}>{t("browser.panel.reconnect")}</button>}</div>}
{takeStatus === "stale" && <div role="status" className="shrink-0 border-b border-hairline/30 px-3 py-1.5 text-[12px] text-accent-text">{t("browser.control.stale", { name: bot.name })}</div>}
{passkeyWall && passkeyDismissed !== nav.url && <PasskeyNotice wall={passkeyWall} botName={bot.name} onDismiss={() => setPasskeyDismissed(nav.url)} />}
- <div className="relative flex min-h-0 flex-1 flex-col bg-inset/40">
+ <div ref={pageArea} {...(paneMode ? { "data-native-view-host": "" } : {})} className="relative flex min-h-0 flex-1 flex-col bg-inset/40">
{shown ? (
<StreamSurface
key={`${attempt}:${stream ? "stream" : "live"}:${bot.browserProfile ?? ""}`}
diff --git a/src/components/LocalVmWorkspace.tsx b/src/components/LocalVmWorkspace.tsx
index a447cf43a6..16ab921dd6 100644
--- a/src/components/LocalVmWorkspace.tsx
+++ b/src/components/LocalVmWorkspace.tsx
@@ -21,7 +21,6 @@ import { t } from "@/lib/i18n";
import { parseComputerHelp, transitionComputerControlLease } from "@/lib/computer-control";
import {
initialLocalVmWorkspaceSlots,
- nativeViewOverlayIntersects,
readyLocalVmViewerUrl,
reconcileLocalVmWorkspaceSlots,
releaseLocalVmWorkspaceControl,
@@ -37,6 +36,7 @@ import { z } from "zod";
import { Select } from "./Select";
import { productName } from "@/lib/brand";
import { randomUuid } from "@/lib/random-uuid";
+import { useNativeViewObscured } from "@/lib/native-view-obscured";
const SLOT_CONTEXTS = ["local-vm-workspace:left", "local-vm-workspace:right"] as const;
@@ -121,105 +121,6 @@ function elementBounds(ref: RefObject<HTMLDivElement | null>): DesktopWorkspaceB
};
}
-const NATIVE_VIEW_OVERLAY_SELECTOR = [
- '[aria-modal="true"]',
- '[role="dialog"]',
- '[role="menu"]',
- "[popover]",
- "[data-native-view-overlay]",
- ".fixed",
- ".absolute",
-].join(",");
-
-/**
- * Electron's native views always paint above the renderer, so any intersecting overlay or popover counts, portals
- * included.
- */
-function rendererOverlayIntersectsNativeView() {
- const hosts = [...document.querySelectorAll<HTMLElement>("[data-native-view-host]")];
- const hostRects = hosts
- .map((host) => host.getBoundingClientRect())
- .filter((rect) => rect.width > 0 && rect.height > 0);
- if (hostRects.length === 0) return false;
-
- const candidates = [...document.querySelectorAll<HTMLElement>(NATIVE_VIEW_OVERLAY_SELECTOR)]
- .filter(
- (candidate) =>
- !hosts.some(
- (host) => candidate === host || candidate.contains(host) || host.contains(candidate),
- ),
- )
- .map((candidate) => {
- const style = window.getComputedStyle(candidate);
- const explicitlyOverlay =
- candidate.matches(
- '[aria-modal="true"], [role="dialog"], [role="menu"], [popover], [data-native-view-overlay]',
- );
- const zIndex = Number.parseInt(style.zIndex, 10);
- return {
- rect: candidate.getBoundingClientRect(),
- explicit: explicitlyOverlay,
- visible:
- style.display !== "none" &&
- style.visibility !== "hidden" &&
- Number(style.opacity) !== 0,
- zIndex: Number.isFinite(zIndex) ? zIndex : null,
- };
- });
- return nativeViewOverlayIntersects(hostRects, candidates);
-}
-
-function useNativeViewObscured(explicit: boolean) {
- const [domOverlay, setDomOverlay] = useState(false);
- useEffect(() => {
- let frame = 0;
- const read = () => setDomOverlay(rendererOverlayIntersectsNativeView());
- const scheduleRead = () => {
- if (frame) return;
- frame = requestAnimationFrame(() => {
- frame = 0;
- read();
- });
- };
- read();
- const observer = new MutationObserver(scheduleRead);
- observer.observe(document.body, {
- subtree: true,
- childList: true,
- attributes: true,
- attributeFilter: ["class", "style", "aria-hidden", "aria-modal", "role", "open", "popover"],
- });
- const resizeObserver = new ResizeObserver(scheduleRead);
- resizeObserver.observe(document.body);
- for (const host of document.querySelectorAll<HTMLElement>("[data-native-view-host]")) {
- resizeObserver.observe(host);
- }
- const overlayEvents = [
- "toggle",
- "animationstart",
- "animationend",
- "transitionstart",
- "transitionend",
- ] as const;
- for (const eventName of overlayEvents) {
- document.addEventListener(eventName, scheduleRead, true);
- }
- window.addEventListener("resize", scheduleRead);
- window.addEventListener("scroll", scheduleRead, true);
- return () => {
- if (frame) cancelAnimationFrame(frame);
- observer.disconnect();
- resizeObserver.disconnect();
- for (const eventName of overlayEvents) {
- document.removeEventListener(eventName, scheduleRead, true);
- }
- window.removeEventListener("resize", scheduleRead);
- window.removeEventListener("scroll", scheduleRead, true);
- };
- }, []);
- return explicit || domOverlay;
-}
-
function statusLabel(status: LocalVmWorkspaceStatus | null, nativeStatus: DesktopWorkspaceState["status"]) {
if (!status) return t("vm.workspace.status.checking");
if (status.container === "missing") return t("vm.workspace.status.missing");
diff --git a/src/lib/native-view-obscured.ts b/src/lib/native-view-obscured.ts
new file mode 100644
index 0000000000..92b73fd019
--- /dev/null
+++ b/src/lib/native-view-obscured.ts
@@ -0,0 +1,106 @@
+import { useEffect, useState } from "react";
+import { nativeViewOverlayIntersects } from "@/lib/local-vm-workspace";
+
+const NATIVE_VIEW_OVERLAY_SELECTOR = [
+ '[aria-modal="true"]',
+ '[role="dialog"]',
+ '[role="menu"]',
+ "[popover]",
+ "[data-native-view-overlay]",
+ ".fixed",
+ ".absolute",
+].join(",");
+
+/**
+ * Electron's native views always paint above the renderer, so any intersecting overlay or popover counts, portals
+ * included.
+ */
+function rendererOverlayIntersectsNativeView() {
+ const hosts = [...document.querySelectorAll<HTMLElement>("[data-native-view-host]")];
+ const hostRects = hosts
+ .map((host) => host.getBoundingClientRect())
+ .filter((rect) => rect.width > 0 && rect.height > 0);
+ if (hostRects.length === 0) return false;
+
+ const candidates = [...document.querySelectorAll<HTMLElement>(NATIVE_VIEW_OVERLAY_SELECTOR)]
+ .filter(
+ (candidate) =>
+ !hosts.some(
+ (host) => candidate === host || candidate.contains(host) || host.contains(candidate),
+ ),
+ )
+ .map((candidate) => {
+ const style = window.getComputedStyle(candidate);
+ const explicitlyOverlay =
+ candidate.matches(
+ '[aria-modal="true"], [role="dialog"], [role="menu"], [popover], [data-native-view-overlay]',
+ );
+ const zIndex = Number.parseInt(style.zIndex, 10);
+ return {
+ rect: candidate.getBoundingClientRect(),
+ explicit: explicitlyOverlay,
+ visible:
+ style.display !== "none" &&
+ style.visibility !== "hidden" &&
+ Number(style.opacity) !== 0,
+ zIndex: Number.isFinite(zIndex) ? zIndex : null,
+ };
+ });
+ return nativeViewOverlayIntersects(hostRects, candidates);
+}
+
+/** `watching` false leaves the page unobserved, for a panel that shows no native view. */
+export function useNativeViewObscured(explicit: boolean, watching = true) {
+ const [domOverlay, setDomOverlay] = useState(false);
+ useEffect(() => {
+ if (!watching) {
+ setDomOverlay(false);
+ return;
+ }
+ let frame = 0;
+ const read = () => setDomOverlay(rendererOverlayIntersectsNativeView());
+ const scheduleRead = () => {
+ if (frame) return;
+ frame = requestAnimationFrame(() => {
+ frame = 0;
+ read();
+ });
+ };
+ read();
+ const observer = new MutationObserver(scheduleRead);
+ observer.observe(document.body, {
+ subtree: true,
+ childList: true,
+ attributes: true,
+ attributeFilter: ["class", "style", "aria-hidden", "aria-modal", "role", "open", "popover"],
+ });
+ const resizeObserver = new ResizeObserver(scheduleRead);
+ resizeObserver.observe(document.body);
+ for (const host of document.querySelectorAll<HTMLElement>("[data-native-view-host]")) {
+ resizeObserver.observe(host);
+ }
+ const overlayEvents = [
+ "toggle",
+ "animationstart",
+ "animationend",
+ "transitionstart",
+ "transitionend",
+ ] as const;
+ for (const eventName of overlayEvents) {
+ document.addEventListener(eventName, scheduleRead, true);
+ }
+ window.addEventListener("resize", scheduleRead);
+ window.addEventListener("scroll", scheduleRead, true);
+ return () => {
+ if (frame) cancelAnimationFrame(frame);
+ observer.disconnect();
+ resizeObserver.disconnect();
+ for (const eventName of overlayEvents) {
+ document.removeEventListener(eventName, scheduleRead, true);
+ }
+ window.removeEventListener("resize", scheduleRead);
+ window.removeEventListener("scroll", scheduleRead, true);
+ };
+ }, [watching]);
+ return explicit || domOverlay;
+}
diff --git a/src/state/config-status.ts b/src/state/config-status.ts
index c93258a67b..0ab9ca5a7c 100644
--- a/src/state/config-status.ts
+++ b/src/state/config-status.ts
@@ -223,6 +223,8 @@ export interface BrowserEngineSummary {
myChromeLendable?: true;
/** browserEngine.engine: "chrome" when the bots' browsers run on OpenMausBot's own Chrome driver. */
engine?: "agent-browser" | "chrome";
+ /** The desktop app shows the Chrome engine's browsers as panes the person uses directly (browserEngine.surface "pane"). */
+ pane?: true;
/** Self-hosted servers only: whether bots' browsers may open this server's own sites and its local network
* (browserEngine.egress.localNetwork, off by default). Absent on the desktop and on MausBot Cloud. */
serverSites?: boolean;
diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.ts
index 2bcf3b3df2..9db439de0e 100644
--- a/src/types/ogb.d.ts
+++ b/src/types/ogb.d.ts
@@ -442,6 +442,11 @@ const __APP_VERSION__: string;
close(contextId?: string): Promise<boolean>;
onState(cb: (state: DesktopWorkspaceState) => void): () => void;
};
+ /** A bot's browser as a native view over its Browser panel (browserEngine.surface "pane"). The main process asks
+ * the server which browser the bot's panel shows; the page never names one. */
+ browserPane?: {
+ show(input: { botId: string; threadId: string | null; profile: string | null; bounds: DesktopWorkspaceBounds | null; visible: boolean }): Promise<{ shown: boolean }>;
+ };
/** Native folder picker; resolves null when the user cancels. */
pickFolder?(current?: string): Promise<string | null>;
/** Writes the redacted diagnostics report to a user-chosen file;