Skip to content

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

Browser pane: fixes from five live runs, and the person's hold on a pane tab

milind-soni2e34319da781
diff --git a/electron/browser-pane-capture.mjs b/electron/browser-pane-capture.mjs
new file mode 100644
index 0000000000..f9c3c6ead2
--- /dev/null
+++ b/electron/browser-pane-capture.mjs
@@ -0,0 +1,65 @@
+// A screenshot of a pane whose window does not draw: the parking window, which is never shown, or an app window that is
+// minimised or hidden. Chromium draws no frame for it, so CDP's Page.captureScreenshot would wait for good. Electron's
+// capturePage makes the page draw while it captures (a hidden window's page counts as visible while a capture is under
+// way), and its picture is shaped as CDP's answer would be: the same pixels for the same clip and scale, whatever the
+// scale factor of the screen the window is on.
+
+/** How long the page gets to draw a fresh frame once a capture has made it visible. */
+export const FRESH_FRAME_MS = 50;
+
+/** How long the page's own ratio is waited for. */
+const RATIO_READ_MS = 500;
+
+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+/** Whether `win` draws its views now: not when minimised or hidden. */
+export function windowDraws(win) {
+ if (!win || win.isDestroyed?.()) return false;
+ if (win.isMinimized?.()) return false;
+ return win.isVisible?.() !== false;
+}
+
+/**
+ * The page's own device pixel ratio, which CDP draws at and the driver divides its clip's scale by; the window's
+ * screen may have another. Read from the page, else from the layout metrics' device and CSS widths.
+ */
+async function pageRatio(contents, css, device) {
+ // A page under a dialog answers no script: the metrics answer then.
+ const read = await Promise.race([
+ contents.debugger.sendCommand("Runtime.evaluate", { expression: "window.devicePixelRatio", returnByValue: true }).catch(() => null),
+ sleep(RATIO_READ_MS).then(() => null),
+ ]);
+ const value = Number(read?.result?.value);
+ if (value > 0) return value;
+ return css > 0 && device > 0 ? device / css : 1;
+}
+
+/** CDP's Page.captureScreenshot answer, `{ data }` in base64, for a pane that is not drawing. */
+export async function captureUndrawn(contents, params = {}, { wait = sleep } = {}) {
+ if (params.captureBeyondViewport) throw new Error("A whole-page screenshot needs the browser shown in the app window. Take a screenshot of the visible part instead.");
+ const metrics = await contents.debugger.sendCommand("Page.getLayoutMetrics");
+ const view = metrics?.cssVisualViewport ?? {};
+ const css = Number(view.clientWidth);
+ const ratio = await pageRatio(contents, css, Number(metrics?.visualViewport?.clientWidth));
+ const clip = params.clip;
+ const region = clip
+ ? { x: Math.round(clip.x - (view.pageX ?? 0)), y: Math.round(clip.y - (view.pageY ?? 0)), width: Math.max(1, Math.round(clip.width)), height: Math.max(1, Math.round(clip.height)) }
+ : css > 0 && Number(view.clientHeight) > 0 ? { x: 0, y: 0, width: Math.round(css), height: Math.round(Number(view.clientHeight)) } : null;
+ const rect = clip ? region : undefined;
+ // The first capture makes the page visible and may hold the frame it drew before; the page then draws a fresh one.
+ await contents.capturePage(rect);
+ contents.invalidate?.();
+ await wait(FRESH_FRAME_MS);
+ let image = await contents.capturePage(rect);
+ if (image.isEmpty()) throw new Error("The page did not draw, so no screenshot was taken.");
+ if (region) {
+ const scale = clip && Number(clip.scale) > 0 ? Number(clip.scale) : 1;
+ const width = Math.max(1, Math.round(region.width * scale * ratio));
+ const height = Math.max(1, Math.round(region.height * scale * ratio));
+ const size = image.getSize();
+ if (size.width !== width || size.height !== height) image = image.resize({ width, height, quality: "good" });
+ }
+ const jpeg = params.format === "jpeg";
+ const bytes = jpeg ? image.toJPEG(Math.min(100, Math.max(1, Math.round(Number(params.quality) || 80)))) : image.toPNG();
+ return { data: bytes.toString("base64") };
+}
diff --git a/electron/browser-pane-capture.node-test.mjs b/electron/browser-pane-capture.node-test.mjs
new file mode 100644
index 0000000000..cb9939df9b
--- /dev/null
+++ b/electron/browser-pane-capture.node-test.mjs
@@ -0,0 +1,84 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { captureUndrawn, windowDraws } from "./browser-pane-capture.mjs";
+
+function fakeImage(width, height, label, calls) {
+ return {
+ label,
+ isEmpty: () => width === 0,
+ getSize: () => ({ width, height }),
+ resize(size) { calls.push(["resize", size]); return fakeImage(size.width, size.height, label, calls); },
+ toPNG: () => Buffer.from(`png ${width}x${height} ${label}`),
+ toJPEG: (quality) => Buffer.from(`jpeg ${width}x${height} q${quality} ${label}`),
+ };
+}
+
+/**
+ * A pane whose page is 365x576 CSS px at the page's device pixel ratio `pageRatio`, in a window on a screen of scale
+ * `screen`: capturePage gives screen pixels. The first capture holds the frame drawn before the bot's action.
+ */
+function fakeContents({ pageRatio = 1, screen = 1, empty = false, unreadable = false } = {}) {
+ const calls = [];
+ let captures = 0;
+ return {
+ calls,
+ debugger: {
+ async sendCommand(method) {
+ calls.push([method]);
+ if (method === "Runtime.evaluate") {
+ if (unreadable) throw new Error("A JavaScript dialog is open on the page");
+ return { result: { type: "number", value: pageRatio } };
+ }
+ return { cssVisualViewport: { pageX: 0, pageY: 400, clientWidth: 365, clientHeight: 576 }, visualViewport: { clientWidth: 365 * pageRatio, clientHeight: 576 * pageRatio } };
+ },
+ },
+ invalidate() { calls.push(["invalidate"]); },
+ async capturePage(rect) {
+ calls.push(["capturePage", rect]);
+ captures++;
+ const width = rect ? rect.width : 365;
+ const height = rect ? rect.height : 576;
+ return fakeImage(empty ? 0 : width * screen, height * screen, captures === 1 ? "before" : "fresh", calls);
+ },
+ };
+}
+
+const text = (answer) => Buffer.from(answer.data, "base64").toString();
+const now = { wait: async () => {} };
+
+test("draws the viewport as CDP would, at the page's ratio whatever the window's screen, from a fresh frame", async () => {
+ for (const [pageRatio, screen, expected] of [[1, 1, "365x576"], [2, 2, "730x1152"], [2, 1, "730x1152"], [1, 2, "365x576"]]) {
+ const contents = fakeContents({ pageRatio, screen });
+ assert.equal(text(await captureUndrawn(contents, {}, now)), `png ${expected} fresh`, `page ${pageRatio}, screen ${screen}`);
+ assert.deepEqual(contents.calls.map(([name]) => name).filter((name) => name === "capturePage" || name === "invalidate"), ["capturePage", "invalidate", "capturePage"]);
+ }
+});
+
+test("takes the driver's clip in page coordinates at its scale: one picture pixel per CSS pixel, at either screen scale", async () => {
+ // The driver asks for scale 1/ratio so the picture has one pixel per CSS pixel.
+ for (const [pageRatio, screen] of [[1, 1], [2, 2], [2, 1], [1, 2]]) {
+ const contents = fakeContents({ pageRatio, screen });
+ const answer = await captureUndrawn(contents, { format: "jpeg", quality: 80, clip: { x: 0, y: 400, width: 365, height: 576, scale: 1 / pageRatio } }, now);
+ assert.equal(text(answer), "jpeg 365x576 q80 fresh", `page ${pageRatio}, screen ${screen}`);
+ assert.deepEqual(contents.calls.find(([name]) => name === "capturePage"), ["capturePage", { x: 0, y: 0, width: 365, height: 576 }]);
+ }
+});
+
+test("falls back on the layout metrics for the page's ratio where the page cannot be read", async () => {
+ const contents = fakeContents({ pageRatio: 2, screen: 1, unreadable: true });
+ assert.equal(text(await captureUndrawn(contents, { clip: { x: 0, y: 400, width: 365, height: 576, scale: 0.5 } }, now)), "png 365x576 fresh");
+});
+
+test("refuses a whole-page capture and says when nothing was drawn", async () => {
+ await assert.rejects(captureUndrawn(fakeContents(), { captureBeyondViewport: true }, now), /whole-page/);
+ await assert.rejects(captureUndrawn(fakeContents({ empty: true }), {}, now), /did not draw/);
+});
+
+test("knows a minimised or hidden window draws nothing", () => {
+ const win = (minimised, visible) => ({ isDestroyed: () => false, isMinimized: () => minimised, isVisible: () => visible });
+ assert.equal(windowDraws(win(false, true)), true);
+ assert.equal(windowDraws(win(true, true)), false);
+ assert.equal(windowDraws(win(false, false)), false);
+ assert.equal(windowDraws(null), false);
+});
diff --git a/electron/browser-pane-dialogs.mjs b/electron/browser-pane-dialogs.mjs
new file mode 100644
index 0000000000..d80418a5a5
--- /dev/null
+++ b/electron/browser-pane-dialogs.mjs
@@ -0,0 +1,82 @@
+// A pane page's alert, confirm and prompt: never a native box. Chromium reports each dialog over CDP
+// (Page.javascriptDialogOpening) and takes the answer there (Page.handleJavaScriptDialog), from the bot's dialog tool or
+// the panel's dialog card; Electron would also draw its own message box, which stays after CDP answered.
+//
+// Adapted from anomalyco/opencode@5ca87b9 packages/gui-plugins/src/browser/page-prompts.ts (takeDialogs,
+// RESTORE_PROMPT), MIT License, Copyright (c) 2025 opencode (full text in third_party/opencode/LICENSE). Modified: the
+// open state comes from the pane's own CDP events.
+
+/** How long a dialog CDP never reported may hold the page before it is dismissed, as a dismissed box would be. */
+export const UNREPORTED_DIALOG_MS = 2_000;
+
+/**
+ * Gives a top-level document Chromium's own `prompt` back. Electron replaces it in every main frame with one that throws
+ * ("prompt() is not supported", Electron 43); a frame Electron does not set up keeps the original, and calling it for
+ * this window opens this window's dialog, which CDP reports like alert and confirm. It runs in the page's own world:
+ * the one script the pane adds there, so a page's prompt works as in Chrome.
+ */
+export const RESTORE_PROMPT = `(() => {
+ if (window !== window.top) return
+ let native
+ const prompt = function prompt(message, value) {
+ if (!native) {
+ const root = document.body ?? document.documentElement
+ if (!root) return null
+ const frame = document.createElement("iframe")
+ frame.hidden = true
+ root.append(frame)
+ native = frame.contentWindow.prompt
+ frame.remove()
+ }
+ return Reflect.apply(native, window, arguments)
+ }
+ Object.defineProperty(window, "prompt", { value: prompt, writable: true, configurable: true, enumerable: true })
+})()`;
+
+/**
+ * Takes Electron's `-run-dialog` (its message box) on `contents`, an Electron internal (lib/browser/api/web-contents.ts,
+ * `(info, callback)`): the page's dialog then waits only for CDP's answer. `opened()` says whether CDP reported it.
+ */
+export function takeDialogs(contents, { opened, warn = () => {}, delayMs = UNREPORTED_DIALOG_MS, setTimer = setTimeout }) {
+ const events = contents;
+ const held = new Set();
+ if (events.listenerCount("-run-dialog") === 0) warn("Electron has no -run-dialog listener on a pane; its own dialog box may still show.");
+ const run = (info, last) => {
+ const callback = [last, info].find((value) => typeof value === "function");
+ if (!callback) {
+ warn("Electron's -run-dialog passed no callback; the dialog is left to CDP.");
+ return;
+ }
+ held.add(callback);
+ // The page never waits on a dialog nobody can see: one CDP never reported is dismissed.
+ setTimer(() => {
+ if (held.has(callback) && !opened()) {
+ held.delete(callback);
+ callback(false, "");
+ }
+ }, delayMs);
+ };
+ const release = () => {
+ for (const callback of held) callback(false, "");
+ held.clear();
+ };
+ events.removeAllListeners("-run-dialog");
+ events.on("-run-dialog", run);
+ events.on("-cancel-dialogs", release);
+ return {
+ /** CDP reported the dialog closed: whoever answered it, its callback is spent. */
+ closed: () => held.clear(),
+ /** Whether a page waits on a dialog here. */
+ get waiting() {
+ return held.size > 0;
+ },
+ /** Dismisses every dialog a page waits on, as a dismissed box would be. */
+ dismiss: release,
+ dispose: () => {
+ release();
+ if (contents.isDestroyed?.()) return;
+ events.off("-run-dialog", run);
+ events.off("-cancel-dialogs", release);
+ },
+ };
+}
diff --git a/electron/browser-pane-dialogs.node-test.mjs b/electron/browser-pane-dialogs.node-test.mjs
new file mode 100644
index 0000000000..0e44bce37d
--- /dev/null
+++ b/electron/browser-pane-dialogs.node-test.mjs
@@ -0,0 +1,75 @@
+import assert from "node:assert/strict";
+import { EventEmitter } from "node:events";
+import test from "node:test";
+
+import { RESTORE_PROMPT, takeDialogs } from "./browser-pane-dialogs.mjs";
+
+function page() {
+ const contents = Object.assign(new EventEmitter(), { isDestroyed: () => false });
+ let boxes = 0;
+ // Electron's own listener: its native message box.
+ contents.on("-run-dialog", () => { boxes++; });
+ return { contents, boxes: () => boxes };
+}
+
+test("never draws Electron's own box: the dialog waits for CDP's answer, from the bot or the panel", () => {
+ const { contents, boxes } = page();
+ const timers = [];
+ let opened = false;
+ const dialogs = takeDialogs(contents, { opened: () => opened, setTimer: (run) => timers.push(run) });
+ const answers = [];
+ contents.emit("-run-dialog", { dialogType: "confirm", messageText: "Delete?" }, (ok, text) => answers.push([ok, text]));
+ opened = true;
+ for (const run of timers) run();
+ assert.equal(boxes(), 0);
+ // CDP answered (Page.handleJavaScriptDialog); Electron's callback is spent, never called again.
+ dialogs.closed();
+ assert.deepEqual(answers, []);
+});
+
+test("dismisses a dialog CDP never reported, so the page never waits on one nobody sees", () => {
+ const { contents } = page();
+ const timers = [];
+ takeDialogs(contents, { opened: () => false, setTimer: (run, ms) => timers.push([run, ms]) });
+ const answers = [];
+ contents.emit("-run-dialog", { dialogType: "alert" }, (ok, text) => answers.push([ok, text]));
+ assert.equal(timers[0][1], 2_000);
+ timers[0][0]();
+ assert.deepEqual(answers, [[false, ""]]);
+});
+
+test("lets go of every held dialog when Electron cancels them or the pane closes", () => {
+ const { contents } = page();
+ const dialogs = takeDialogs(contents, { opened: () => true, setTimer: () => {} });
+ const answers = [];
+ contents.emit("-run-dialog", {}, (ok) => answers.push(ok));
+ contents.emit("-cancel-dialogs");
+ contents.emit("-run-dialog", {}, (ok) => answers.push(ok));
+ dialogs.dispose();
+ assert.deepEqual(answers, [false, false]);
+ assert.equal(contents.listenerCount("-run-dialog"), 0);
+});
+
+test("says so when this Electron has no dialog event to take", () => {
+ const contents = Object.assign(new EventEmitter(), { isDestroyed: () => false });
+ const warnings = [];
+ takeDialogs(contents, { opened: () => false, warn: (line) => warnings.push(line), setTimer: () => {} });
+ assert.equal(warnings.length, 1);
+});
+
+test("gives a top page Chromium's own prompt back, and leaves frames alone", () => {
+ assert.match(RESTORE_PROMPT, /window !== window\.top/);
+ assert.match(RESTORE_PROMPT, /contentWindow\.prompt/);
+});
+
+test("dismisses the dialog a page waits on when asked, as a dismissed box would be", () => {
+ const { contents } = page();
+ const dialogs = takeDialogs(contents, { opened: () => true, setTimer: () => {} });
+ const answers = [];
+ assert.equal(dialogs.waiting, false);
+ contents.emit("-run-dialog", { dialogType: "alert" }, (ok, text) => answers.push([ok, text]));
+ assert.equal(dialogs.waiting, true);
+ dialogs.dismiss();
+ assert.deepEqual(answers, [[false, ""]]);
+ assert.equal(dialogs.waiting, false);
+});
diff --git a/electron/browser-pane-input.mjs b/electron/browser-pane-input.mjs
new file mode 100644
index 0000000000..3a0be10464
--- /dev/null
+++ b/electron/browser-pane-input.mjs
@@ -0,0 +1,81 @@
+// Telling the bot's own input apart from the person's in a pane. Electron reports every CDP Input.dispatch* as an
+// input-event too (measured on Electron 43: within 0-6 ms, before the command answers), so each command the bot sends
+// registers the events it will cause, and only those are taken as the bot's: by type, count and, for the mouse,
+// position. A registration ends a few milliseconds after its command answers; a wheel's scroll gestures, later.
+
+/** Slack after a command answers, for an event Electron reports late. */
+export const ECHO_SLACK_MS = 8;
+/**
+ * One dispatched wheel is reported as exactly two mouseWheel events and a gestureScrollBegin, Update and End (measured
+ * on Electron 43: 50 wheels for 25 dispatched, every one at most 1 ms after the command answered). Electron's wheel
+ * events carry no point, so they are matched by count and time: once both of a bot's wheels are seen, the next is the
+ * person's. Known residual: a person's wheel within this long after a bot scroll, before the bot's second wheel
+ * arrives, counts as the bot's.
+ */
+export const SCROLL_SLACK_MS = 20;
+const SCROLL_GESTURES = ["gestureScrollBegin", "gestureScrollUpdate", "gestureScrollEnd", "gestureFlingStart", "gestureFlingCancel"];
+/** How far apart a dispatched point and its reported event may be, in CSS pixels. */
+const POSITION_SLACK = 2;
+
+const MOUSE = { mousePressed: "mouseDown", mouseReleased: "mouseUp", mouseMoved: "mouseMove" };
+const TOUCH = { touchStart: "touchStart", touchMove: "touchMove", touchEnd: "touchEnd", touchCancel: "touchCancel" };
+
+/** The input-events one CDP input command causes in the page it is sent to. */
+export function echoesOf(method, params) {
+ const p = params ?? {};
+ if (method === "Input.dispatchMouseEvent") {
+ if (p.type === "mouseWheel") {
+ return [
+ { types: ["mouseWheel"], slack: SCROLL_SLACK_MS }, { types: ["mouseWheel"], slack: SCROLL_SLACK_MS },
+ { types: ["gestureScrollBegin"], slack: SCROLL_SLACK_MS }, { types: ["gestureScrollEnd"], slack: SCROLL_SLACK_MS },
+ { types: ["gestureScrollUpdate", "gestureFlingStart", "gestureFlingCancel"], any: true, slack: SCROLL_SLACK_MS },
+ ];
+ }
+ const type = MOUSE[p.type];
+ return type ? [{ types: [type], x: Number(p.x), y: Number(p.y) }] : [];
+ }
+ if (method === "Input.dispatchKeyEvent") {
+ if (p.type === "keyDown") return [{ types: ["keyDown", "rawKeyDown"] }, ...(typeof p.text === "string" && p.text ? [{ types: ["char"] }] : [])];
+ if (p.type === "rawKeyDown") return [{ types: ["rawKeyDown"] }];
+ if (p.type === "char") return [{ types: ["char"] }];
+ if (p.type === "keyUp") return [{ types: ["keyUp"] }];
+ return [];
+ }
+ // Text the bot inserts reaches the page as characters, as many as it holds, or as none (an IME commit).
+ if (method === "Input.insertText") return [{ types: ["char"], any: true }];
+ // A touch can become a tap or a scroll as the page sees it.
+ if (method === "Input.dispatchTouchEvent") return TOUCH[p.type] ? [{ types: [TOUCH[p.type]], any: true }, { types: [...SCROLL_GESTURES, "gestureTapDown", "gestureShowPress", "gestureTap", "gestureTapCancel"], any: true, slack: SCROLL_SLACK_MS }] : [];
+ return [];
+}
+
+export function createEchoes(now = Date.now) {
+ let pending = [];
+ return {
+ /** The events a command about to be sent will cause; call the returned function when it answers. */
+ expect(method, params) {
+ const added = echoesOf(method, params).map((echo) => ({ ...echo, until: Infinity }));
+ pending.push(...added);
+ return () => {
+ const at = now();
+ for (const echo of added) echo.until = at + (echo.slack ?? ECHO_SLACK_MS);
+ };
+ },
+ /** True when an input-event is one the bot's command caused; it is then used up. */
+ take(input) {
+ const at = now();
+ pending = pending.filter((echo) => echo.until >= at);
+ const placed = (echo) => echo.x === undefined || !Number.isFinite(echo.x) || !Number.isFinite(input.x)
+ || (Math.abs(echo.x - input.x) <= POSITION_SLACK && Math.abs(echo.y - input.y) <= POSITION_SLACK);
+ let index = pending.findIndex((echo) => echo.types.includes(input?.type) && placed(echo));
+ // Should Electron report the point in other units, an event of the type while its command still runs is the bot's.
+ if (index < 0) index = pending.findIndex((echo) => echo.types.includes(input?.type) && echo.until === Infinity);
+ if (index < 0) return false;
+ if (!pending[index].any) pending.splice(index, 1);
+ return true;
+ },
+ /** Whether any command of the bot's is still waiting for its answer. */
+ get inFlight() {
+ return pending.some((echo) => echo.until === Infinity);
+ },
+ };
+}
diff --git a/electron/browser-pane-input.node-test.mjs b/electron/browser-pane-input.node-test.mjs
new file mode 100644
index 0000000000..03d4c98c9c
--- /dev/null
+++ b/electron/browser-pane-input.node-test.mjs
@@ -0,0 +1,100 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { createEchoes, echoesOf } from "./browser-pane-input.mjs";
+
+test("the bot's own click and keys are its own, and a person's key right after is the person's", () => {
+ let clock = 1000;
+ const echoes = createEchoes(() => clock);
+ const done = echoes.expect("Input.dispatchMouseEvent", { type: "mousePressed", x: 40, y: 60 });
+ assert.equal(echoes.take({ type: "mouseDown", x: 40, y: 60 }), true);
+ // A second press during the bot's command is not the bot's: one command, one event.
+ assert.equal(echoes.take({ type: "mouseDown", x: 300, y: 300 }), false);
+ done();
+ clock += 3;
+ const release = echoes.expect("Input.dispatchMouseEvent", { type: "mouseReleased", x: 40, y: 60 });
+ release();
+ // The measured cases: a person's key 22 ms and 102 ms after the bot's mouseUp.
+ clock += 22;
+ assert.equal(echoes.take({ type: "keyDown" }), false);
+ clock += 80;
+ assert.equal(echoes.take({ type: "rawKeyDown" }), false);
+});
+
+test("a key the bot types is used up once, its character too, and nothing is left for later", () => {
+ let clock = 0;
+ const echoes = createEchoes(() => clock);
+ const done = echoes.expect("Input.dispatchKeyEvent", { type: "keyDown", key: "a", text: "a" });
+ assert.equal(echoes.take({ type: "rawKeyDown" }), true);
+ assert.equal(echoes.take({ type: "char" }), true);
+ assert.equal(echoes.take({ type: "char" }), false);
+ done();
+ clock += 20;
+ assert.equal(echoes.take({ type: "keyDown" }), false);
+ assert.equal(echoes.inFlight, false);
+});
+
+test("an event in other units still counts as the bot's while its command runs, never after", () => {
+ let clock = 0;
+ const echoes = createEchoes(() => clock);
+ const done = echoes.expect("Input.dispatchMouseEvent", { type: "mousePressed", x: 40, y: 60 });
+ assert.equal(echoes.take({ type: "mouseDown", x: 80, y: 120 }), true);
+ done();
+ const again = echoes.expect("Input.dispatchMouseEvent", { type: "mousePressed", x: 40, y: 60 });
+ again();
+ clock += 1;
+ assert.equal(echoes.take({ type: "mouseDown", x: 80, y: 120 }), false);
+});
+
+test("names what each command causes", () => {
+ assert.deepEqual(echoesOf("Input.dispatchMouseEvent", { type: "mouseMoved", x: 1, y: 2 }), [{ types: ["mouseMove"], x: 1, y: 2 }]);
+ assert.deepEqual(echoesOf("Input.insertText", { text: "hello" }), [{ types: ["char"], any: true }]);
+ assert.deepEqual(echoesOf("Runtime.evaluate", {}), []);
+});
+
+test("a bot's wheel is its own with everything Electron reports for it, and a person's scroll after is the person's", () => {
+ let clock = 0;
+ const echoes = createEchoes(() => clock);
+ const done = echoes.expect("Input.dispatchMouseEvent", { type: "mouseWheel", x: 200, y: 300, deltaX: 0, deltaY: 400 });
+ // Measured on Electron 43: two mouseWheel events and the scroll gesture, its end at most 1 ms after the answer.
+ for (const type of ["mouseWheel", "mouseWheel", "gestureScrollBegin", "gestureScrollUpdate"]) assert.equal(echoes.take({ type, x: 200, y: 300 }), true, type);
+ clock += 4;
+ done();
+ clock += 1;
+ assert.equal(echoes.take({ type: "gestureScrollUpdate" }), true);
+ assert.equal(echoes.take({ type: "gestureScrollEnd" }), true);
+ clock += 400;
+ assert.equal(echoes.take({ type: "mouseWheel", x: 10, y: 10 }), false);
+ assert.equal(echoes.take({ type: "gestureScrollBegin" }), false);
+});
+
+test("a person's wheel once the bot's two wheels are in is the person's, though within the window", () => {
+ let clock = 0;
+ const echoes = createEchoes(() => clock);
+ const done = echoes.expect("Input.dispatchMouseEvent", { type: "mouseWheel", x: 200, y: 300, deltaX: 0, deltaY: 400 });
+ // Electron 43's wheel events carry no point.
+ for (const type of ["mouseWheel", "gestureScrollBegin", "gestureScrollUpdate"]) assert.equal(echoes.take({ type }), true, type);
+ done();
+ clock += 1;
+ assert.equal(echoes.take({ type: "mouseWheel" }), true);
+ assert.equal(echoes.take({ type: "gestureScrollEnd" }), true);
+ clock += 2;
+ assert.equal(echoes.take({ type: "mouseWheel" }), false);
+});
+
+test("the window is 20 ms: within it a person's wheel before the bot's second one counts as the bot's, after it the person's", () => {
+ let clock = 0;
+ const echoes = createEchoes(() => clock);
+ const done = echoes.expect("Input.dispatchMouseEvent", { type: "mouseWheel", x: 200, y: 300, deltaX: 0, deltaY: 400 });
+ assert.equal(echoes.take({ type: "mouseWheel" }), true);
+ done();
+ clock += 15;
+ assert.equal(echoes.take({ type: "mouseWheel" }), true);
+ const again = echoes.expect("Input.dispatchMouseEvent", { type: "mouseWheel", x: 200, y: 300, deltaX: 0, deltaY: 400 });
+ assert.equal(echoes.take({ type: "mouseWheel" }), true);
+ again();
+ clock += 25;
+ // The bot's second wheel never came in time: a person's wheel 25 ms after is the person's.
+ assert.equal(echoes.take({ type: "mouseWheel" }), false);
+ assert.equal(echoes.take({ type: "gestureScrollBegin" }), false);
+});
diff --git a/electron/browser-pane-main.mjs b/electron/browser-pane-main.mjs
index f4795ce66e..4a04ef48e0 100644
--- a/electron/browser-pane-main.mjs
+++ b/electron/browser-pane-main.mjs
@@ -8,16 +8,20 @@ import path from "node:path";
import desktopWorkspace from "./desktop-workspace.cjs";
import { paneBaseUserAgent, paneIdentityMode, paneRequestUserAgent, paneTabUserAgent } from "./browser-pane-identity.mjs";
import { PANE_MESSAGE, PANE_PARTITION, PANE_TABS_PER_BROWSER, paneMessageToMain } from "./browser-pane-wire.mjs";
+import { RESTORE_PROMPT, takeDialogs } from "./browser-pane-dialogs.mjs";
+import { createEchoes } from "./browser-pane-input.mjs";
+import { createDialogGate } from "./browser-pane-under-dialog.mjs";
+import { captureUndrawn, windowDraws } from "./browser-pane-capture.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;
/** A window.open this soon after the person's own press or key, with Chromium's user gesture, is the person's. */
const GESTURE_MS = 1_000;
const POPUP_SIZE = { width: 520, height: 680 };
+/** Commands that leave the page: an open dialog would hold them for good, as the page cannot unload under it. */
+const LEAVING = new Set(["Page.navigate", "Page.reload", "Page.navigateToHistoryEntry", "Page.close"]);
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. */
@@ -44,10 +48,13 @@ const samePanel = (a, b) => a.botId === b.botId && a.threadId === b.threadId &&
/**
* `createView(options)`: a WebContentsView. `createPopup(options)`: a BrowserWindow, for a sign-in popup the person
- * opened. `fromPartition(name)`: Electron's session. `owner()`: the app window or null. `chromeVersion`:
- * process.versions.chrome.
+ * opened. `createParking()`: a BrowserWindow never shown, which holds the panes while the app window is closed, so a
+ * bot's pages, sign-ins and its one cookie jar live on; only while `keepsRunning()`, as a window that stays would keep
+ * the app from quitting when its last window closes, and never once `quitting()`, as a window made then cancels the quit.
+ * `fromPartition(name)`: Electron's session. `owner()`: the app window
+ * or null. `chromeVersion`: process.versions.chrome.
*/
-export function createBrowserPanes({ createView, createPopup = null, fromPartition, owner, chromeVersion, log = () => {}, now = Date.now, captureMs = CAPTURE_MS }) {
+export function createBrowserPanes({ createView, createPopup = null, createParking = null, keepsRunning = () => false, quitting = () => false, fromPartition, owner, chromeVersion, log = () => {}, now = Date.now, captureMs = CAPTURE_MS }) {
const browsers = new Map();
const configured = new Set();
/** Per partition: Electron's own UA, read before this module changed it, and the identity mode in force. */
@@ -61,6 +68,33 @@ export function createBrowserPanes({ createView, createPopup = null, fromPartiti
let requests = 0;
let asks = 0;
let panel = NO_PANEL;
+ let parking = null;
+ /** Chromium's own client hints of this app's Chromium, read once from a pane. */
+ let hints = null;
+
+ /** Where panes live: the app window, or the parking window while there is none. */
+ function host() {
+ const win = owner();
+ if (win && !win.isDestroyed()) return win;
+ if (!createParking || !keepsRunning() || quitting()) return null;
+ if (!parking || parking.isDestroyed()) {
+ try {
+ parking = createParking();
+ } catch (error) {
+ log(`browser pane: could not keep panes without a window: ${error?.message ?? error}`);
+ parking = null;
+ }
+ }
+ return parking;
+ }
+
+ /** Moves a pane's view into `target`; a view sits in one window at a time. */
+ function place(entry, target) {
+ if (entry.popup || !target || entry.window === target) return;
+ try { if (entry.window && !entry.window.isDestroyed()) entry.window.contentView.removeChildView(entry.view); } catch {}
+ target.contentView.addChildView(entry.view);
+ entry.window = target;
+ }
const post = (message) => {
try {
@@ -126,14 +160,16 @@ export function createBrowserPanes({ createView, createPopup = null, fromPartiti
function layout() {
const win = owner();
+ const shownIn = win && !win.isDestroyed() ? win : null;
for (const [key, browser] of browsers) {
for (const [tab, entry] of browser.tabs) {
if (entry.popup) continue;
- const visible = Boolean(panel.wanted && panel.bounds && panel.browser === key && browser.active === tab);
+ const visible = Boolean(shownIn && 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);
+ if (entry.window !== shownIn) place(entry, shownIn);
+ else if (!entry.visible) shownIn.contentView.addChildView(entry.view);
}
entry.view.setVisible(visible);
} catch (error) {
@@ -146,11 +182,12 @@ export function createBrowserPanes({ createView, createPopup = null, fromPartiti
/**
* 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.
+ * frame that never comes. A hidden pane is shown for the capture with all but one pixel past the window's corner; one
+ * in a window that draws nothing (parked, minimised or hidden) is captured with captureUndrawn instead.
*/
function paintHold(entry) {
- const win = owner();
- if (entry.visible || !win || win.isDestroyed()) return () => {};
+ const win = entry.window;
+ if (entry.visible || entry.popup || !win || win.isDestroyed() || win === parking) 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 });
@@ -163,7 +200,6 @@ export function createBrowserPanes({ createView, createPopup = null, fromPartiti
}
function ping(key, entry) {
- if (entry.botInputs > 0 || now() - entry.botInputAt < BOT_INPUT_ECHO_MS) return;
entry.personAt = now();
const last = pings.get(key);
if (last !== undefined && last.tab === entry.tab && now() - last.at < PING_MS) return;
@@ -176,6 +212,48 @@ export function createBrowserPanes({ createView, createPopup = null, fromPartiti
return String(frameTree.frame.id);
}
+ /**
+ * Chromium leaves the client hints out of a navigation's request once a session's user agent is overridden without
+ * them (measured on Electron 43: page fetches had them, the document request had none). So each pane also gets its
+ * user agent through CDP with Chromium's own metadata, read once from a pane's about:blank: the brands and versions a
+ * page reads, never invented ones.
+ */
+ async function clientHints(contents) {
+ if (hints) return hints;
+ const { result } = await contents.debugger.sendCommand("Runtime.evaluate", {
+ expression: "navigator.userAgentData.getHighEntropyValues(['architecture','bitness','model','platformVersion','fullVersionList','wow64','formFactors']).then((v) => ({ ...v, brands: navigator.userAgentData.brands, mobile: navigator.userAgentData.mobile, platform: navigator.userAgentData.platform }))",
+ awaitPromise: true,
+ returnByValue: true,
+ });
+ const value = result?.value;
+ if (!isObject(value) || !Array.isArray(value.brands)) return null;
+ hints = {
+ brands: value.brands, fullVersionList: value.fullVersionList ?? value.brands, platform: String(value.platform ?? ""), platformVersion: String(value.platformVersion ?? ""),
+ architecture: String(value.architecture ?? ""), model: String(value.model ?? ""), mobile: value.mobile === true, bitness: String(value.bitness ?? ""), wow64: value.wow64 === true,
+ ...(Array.isArray(value.formFactors) ? { formFactors: value.formFactors } : {}),
+ };
+ return hints;
+ }
+
+ async function presentAs(entry, userAgent) {
+ const metadata = await clientHints(entry.contents).catch(() => null);
+ if (!metadata) return;
+ await entry.contents.debugger.sendCommand("Emulation.setUserAgentOverride", { userAgent, userAgentMetadata: metadata }).catch(() => undefined);
+ }
+
+ function tabAgent(browser, url) {
+ const identity = identities.get(browser.partition);
+ return identity ? paneTabUserAgent(identity.electron, identity.mode, url) : null;
+ }
+
+ /** What every pane gets before the server sees it: prompt back, and its identity with Chromium's own hints. */
+ async function prepare(browser, entry) {
+ await entry.contents.debugger.sendCommand("Page.addScriptToEvaluateOnNewDocument", { source: RESTORE_PROMPT, runImmediately: true }).catch(() => undefined);
+ const agent = tabAgent(browser, entry.contents.getURL());
+ entry.agent = agent;
+ if (agent) await presentAs(entry, agent);
+ }
+
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 } : {}) });
@@ -184,22 +262,24 @@ export function createBrowserPanes({ createView, createPopup = null, fromPartiti
/** Why no tab can open in this browser now, or null. */
function tabRefusal(key) {
const browser = browsers.get(key);
- const win = owner();
+ const win = host();
if (!browser) return "Target closed";
- if (!win || win.isDestroyed()) return "The app window is closed.";
+ if (!win || win.isDestroyed()) return "No app window can hold a browser pane now.";
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 webPreferences(browser) {
- return { partition: browser.partition, sandbox: true, contextIsolation: true, nodeIntegration: false, webviewTag: false, backgroundThrottling: false, safeDialogs: true };
+ // devTools off: DevTools would take the debugger from the bot (one client per webContents), and opening it once lost
+ // the passkey fail-fast for good. CDP and debugger.attach still work with it off (measured on Electron 43).
+ return { partition: browser.partition, sandbox: true, contextIsolation: true, nodeIntegration: false, webviewTag: false, backgroundThrottling: false, safeDialogs: true, devTools: false };
}
/** A sign-in popup the person's own click opened: Chromium's user gesture, the person's input, no bot input. */
function personOpened(entry, url) {
const report = entry.windowOpen;
return Boolean(report && report.userGesture && report.url === url && now() - report.at < GESTURE_MS)
- && now() - entry.personAt < GESTURE_MS && entry.botInputs === 0 && now() - entry.botInputAt >= GESTURE_MS;
+ && now() - entry.personAt < GESTURE_MS && !entry.echoes.inFlight && now() - entry.botInputAt >= GESTURE_MS;
}
/**
@@ -219,7 +299,7 @@ export function createBrowserPanes({ createView, createPopup = null, fromPartiti
createWindow: (options) => {
const child = createTab(key, { adopt: options?.webContents, opener: entry.tab, windowed: true });
entry.popupChild = child.tab;
- void targetOf(child.contents).then((target) => { child.target = target; info(key, child); }, () => removeTab(key, child.tab));
+ void prepare(browsers.get(key), child).then(() => targetOf(child.contents)).then((target) => { child.target = target; info(key, child); }, () => removeTab(key, child.tab));
return child.contents;
},
};
@@ -228,7 +308,7 @@ export function createBrowserPanes({ createView, createPopup = null, fromPartiti
action: "allow",
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));
+ void prepare(browsers.get(key), popup).then(() => targetOf(popup.contents)).then((target) => { popup.target = target; info(key, popup); }, () => removeTab(key, popup.tab));
return popup.contents;
},
};
@@ -238,7 +318,7 @@ export function createBrowserPanes({ createView, createPopup = null, fromPartiti
const refusal = tabRefusal(key);
if (refusal) throw new Error(refusal);
const browser = browsers.get(key);
- const win = owner();
+ const win = host();
let view = null;
let popup = null;
if (windowed) {
@@ -251,26 +331,43 @@ export function createBrowserPanes({ createView, createPopup = null, fromPartiti
}
const contents = (popup ?? 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, popup, contents, window: win, target: null, visible: false, botInputs: 0, botInputAt: -Infinity, personAt: -Infinity, windowOpen: null, ...(opener ? { opener } : {}) };
+ const entry = {
+ tab: `p${++tabCount}`, view, popup, contents, window: null, target: null, visible: false, echoes: createEchoes(now), botInputAt: -Infinity,
+ personAt: -Infinity, windowOpen: null, agent: null, ...(opener ? { opener } : {}),
+ gate: createDialogGate({ apply: (method, params) => contents.debugger.sendCommand(method, params) }),
+ };
+ entry.dialogs = takeDialogs(contents, { opened: () => entry.gate.open, warn: log });
contents.debugger.attach("1.3");
browser.tabs.set(entry.tab, entry);
contents.debugger.on("message", (_event, method, params, sessionId) => {
if (method === "Page.windowOpen" && !sessionId && isObject(params)) entry.windowOpen = { url: String(params.url), userGesture: params.userGesture === true, at: now() };
+ if (method === "Page.javascriptDialogOpening") entry.gate.opened();
+ if (method === "Page.javascriptDialogClosed") {
+ entry.gate.closed();
+ entry.dialogs.closed();
+ }
post({ op: "event", browser: key, tab: entry.tab, method, params: isObject(params) ? params : {}, ...(sessionId ? { session: sessionId } : {}) });
});
// Sites with a rule of their own see it in the page's navigator.userAgent too.
contents.on("did-start-navigation", (_event, url, isInPlace, isMainFrame) => {
if (!isMainFrame || isInPlace) return;
- const identity = identities.get(browser.partition);
- if (identity) contents.setUserAgent(paneTabUserAgent(identity.electron, identity.mode, url));
+ // A page that leaves has no dialog open, should CDP's close event have gone missing.
+ if (entry.gate.open) entry.gate.closed();
+ const agent = tabAgent(browser, url);
+ if (agent && agent !== entry.agent) {
+ entry.agent = agent;
+ contents.setUserAgent(agent);
+ void presentAs(entry, agent);
+ }
});
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.on("input-event", (_event, input) => {
+ if (entry.echoes.take(input)) return;
+ if (PERSON_INPUT.has(input?.type)) ping(key, entry);
+ });
contents.setWindowOpenHandler((details) => openPopup(key, entry, details));
if (popup) {
// The person sees whose page this is, whatever its title says.
@@ -283,6 +380,7 @@ export function createBrowserPanes({ createView, createPopup = null, fromPartiti
view.setBounds({ x: 0, y: 0, ...size() });
view.setVisible(false);
win.contentView.addChildView(view);
+ entry.window = win;
if (!background) browser.active = entry.tab;
}
layout();
@@ -301,6 +399,7 @@ export function createBrowserPanes({ createView, createPopup = null, fromPartiti
try { entry.view.setVisible(false); } catch {}
try { if (!entry.window.isDestroyed()) entry.window.contentView.removeChildView(entry.view); } catch {}
}
+ try { entry.dialogs.dispose(); } 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 } : {}) });
@@ -320,7 +419,7 @@ export function createBrowserPanes({ createView, createPopup = null, fromPartiti
}
async function open(message) {
- const win = owner();
+ const win = host();
if (!win || win.isDestroyed()) {
post({ op: "failed", browser: message.browser, error: "The app window is closed.", reason: "no-window" });
return;
@@ -355,6 +454,9 @@ export function createBrowserPanes({ createView, createPopup = null, fromPartiti
async function create(message) {
try {
const entry = createTab(message.browser, { background: message.background === true });
+ // A webContents that never loaded a document answers no debugger command (Electron 43): load one first.
+ await entry.contents.loadURL("about:blank").catch(() => undefined);
+ await prepare(browsers.get(message.browser), entry);
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: "" });
@@ -371,11 +473,15 @@ export function createBrowserPanes({ createView, createPopup = null, fromPartiti
}
const capture = message.method === "Page.captureScreenshot" && !message.session;
const input = message.method.startsWith("Input.");
- const release = capture ? paintHold(entry) : () => {};
- if (input) entry.botInputs++;
+ // A pane in a window that draws nothing (the parking window, a minimised or hidden app window) is captured the way
+ // a hidden window's page can be.
+ const undrawn = capture && !entry.popup && ((Boolean(parking) && entry.window === parking) || !windowDraws(entry.window));
+ const release = capture && !undrawn ? paintHold(entry) : () => {};
+ const answered = input ? entry.echoes.expect(message.method, message.params) : null;
let timer;
try {
- const sent = entry.contents.debugger.sendCommand(message.method, message.params, message.session);
+ if (LEAVING.has(message.method) && !message.session) await dismissDialog(entry);
+ const sent = entry.gate.run(message.method, message.params, () => (undrawn ? captureUndrawn(entry.contents, message.params) : 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);
@@ -386,13 +492,19 @@ export function createBrowserPanes({ createView, createPopup = null, fromPartiti
} finally {
clearTimeout(timer);
if (input) {
- entry.botInputs--;
+ answered?.();
entry.botInputAt = now();
}
release();
}
}
+ /** The bot leaves the page: a dialog it left open is dismissed first, and CDP reports it closed. */
+ async function dismissDialog(entry) {
+ if (entry.gate.open) await entry.contents.debugger.sendCommand("Page.handleJavaScriptDialog", { accept: false }).catch(() => undefined);
+ else if (entry.dialogs.waiting) entry.dialogs.dismiss();
+ }
+
function handle(message) {
switch (message.op) {
case "hello":
@@ -429,7 +541,8 @@ export function createBrowserPanes({ createView, createPopup = null, fromPartiti
case "set-cookies": return void setCookies(message);
case "cookie-sources-result":
case "cookie-import-result":
- case "cookie-offer-result": {
+ case "cookie-offer-result":
+ case "hold-result": {
const answer = asking.get(message.req);
asking.delete(message.req);
answer?.(message);
@@ -554,8 +667,62 @@ export function createBrowserPanes({ createView, createPopup = null, fromPartiti
return answer.result;
},
+ /**
+ * The person takes the tab the Browser panel of `botId` shows from the bot (`held`), or hands it back. The server
+ * checks the tab is that panel's; the answer says whether the tab is now held.
+ */
+ async hold(input) {
+ if (!isObject(input) || typeof input.botId !== "string" || !BOT.test(input.botId) || typeof input.held !== "boolean") throw new Error("Browser pane input is invalid");
+ const threadId = typeof input.threadId === "string" && BOT.test(input.threadId) ? input.threadId : null;
+ const browser = samePanel({ botId: input.botId, threadId, profile: panel.profile }, panel) ? panel.browser : null;
+ const tab = browser ? browsers.get(browser)?.active : null;
+ if (!tab) return { held: false };
+ const answer = await askServer("hold", { botId: input.botId, threadId, browser, tab, held: input.held }, { held: false }, RESOLVE_MS * 2);
+ return { held: answer.held };
+ },
+
+ /** Every pane closes, and the parking window with them: the app is quitting or its server is gone. */
closeAll() {
for (const key of browsers.keys()) closeBrowser(key);
+ try { if (parking && !parking.isDestroyed()) parking.destroy(); } catch {}
+ parking = null;
+ },
+
+ /**
+ * The app window closed: its panes move to the parking window and keep running, pages, sign-ins and all, so a bot
+ * goes on in the same browser. A pane Electron already destroyed with the window is a tab gone, as its own event
+ * reports; the profile's partition, and so its sign-ins, stay either way.
+ */
+ windowClosed(win) {
+ panel = NO_PANEL;
+ // Nobody is left at the window a hold was taken from: the bot may go on.
+ if (server) post({ op: "let-go" });
+ if (quitting()) {
+ this.closeAll();
+ return;
+ }
+ // No pane in that window: nothing to keep, and so no window to make.
+ const kept = [...browsers.values()].some((browser) => [...browser.tabs.values()].some((entry) => !entry.popup && entry.window === win));
+ if (!kept) return;
+ const target = host();
+ if (!target) {
+ this.closeAll();
+ return;
+ }
+ for (const browser of browsers.values()) {
+ for (const entry of browser.tabs.values()) {
+ if (entry.popup || entry.window !== win) continue;
+ entry.visible = false;
+ if (!target || entry.contents.isDestroyed()) continue;
+ try {
+ entry.view.setVisible(false);
+ target.contentView.addChildView(entry.view);
+ entry.window = target;
+ } catch (error) {
+ log(`browser pane: could not keep a pane without its window: ${error?.message ?? error}`);
+ }
+ }
+ }
},
};
}
diff --git a/electron/browser-pane-main.node-test.mjs b/electron/browser-pane-main.node-test.mjs
index 7bcd9f34d8..41610dab10 100644
--- a/electron/browser-pane-main.node-test.mjs
+++ b/electron/browser-pane-main.node-test.mjs
@@ -10,7 +10,7 @@ const MSG = "openmausbot:browser-pane";
const DOWNLOADS = "/tmp/omb-pane-downloads";
const tick = () => new Promise((resolve) => setImmediate(resolve));
-function fakeElectron() {
+function fakeElectron(hints = null) {
const views = [];
const sessions = new Map();
const window = {
@@ -29,7 +29,8 @@ function fakeElectron() {
const sent = [];
const contents = Object.assign(options.webContents ?? new EventEmitter(), {
url: "about:blank",
- loaded: [],
+ // A guest Electron made for a popup loads its own document.
+ loaded: options.webContents ? ["(popup)"] : [],
closed: false,
openHandler: null,
webrtc: null,
@@ -44,6 +45,8 @@ function fakeElectron() {
closeDevTools() { this.devtoolsClosed++; },
agent: null,
setUserAgent(agent) { this.agent = agent; },
+ captured: 0,
+ async capturePage() { this.captured++; return { isEmpty: () => false, getSize: () => ({ width: 2, height: 2 }), toPNG: () => Buffer.from("parked"), toJPEG: () => Buffer.from("parked") }; },
});
let attached = false;
contents.debugger = Object.assign(debuggerEvents, {
@@ -53,7 +56,10 @@ function fakeElectron() {
isAttached: () => attached,
async sendCommand(method, params, sessionId) {
sent.push({ method, params, sessionId });
+ // Electron 43: a webContents that never loaded a document answers no debugger command.
+ if (!contents.loaded.length) return new Promise(() => {});
if (method === "Page.getFrameTree") return { frameTree: { frame: { id: `FRAME${views.length}` } } };
+ if (method === "Runtime.evaluate" && hints) return { result: { value: hints } };
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 {};
@@ -98,11 +104,29 @@ function fakeElectron() {
return { views, sessions, window, createView, createPopup, popups, fromPartition };
}
-function setup({ captureMs } = {}) {
- const electron = fakeElectron();
+function fakeWindow() {
+ const window = {
+ destroyed: false,
+ children: [],
+ isDestroyed() { return this.destroyed; },
+ destroy() { this.destroyed = true; },
+ contentView: {
+ addChildView(view) { window.children = window.children.filter((child) => child !== view).concat(view); },
+ removeChildView(view) { window.children = window.children.filter((child) => child !== view); },
+ },
+ };
+ return window;
+}
+
+function setup({ captureMs, keepsRunning = false, hints = null, quitting = () => false } = {}) {
+ const electron = fakeElectron(hints);
let clock = 0;
const logged = [];
- const panes = createBrowserPanes({ createView: electron.createView, createPopup: electron.createPopup, fromPartition: electron.fromPartition, owner: () => (electron.window.destroyed ? null : electron.window), chromeVersion: "146.0.7680.0", now: () => clock, log: (line) => logged.push(line), ...(captureMs ? { captureMs } : {}) });
+ const parkings = [];
+ const createParking = () => { const window = fakeWindow(); parkings.push(window); return window; };
+ electron.windowsMade = () => parkings.length + electron.popups.length + electron.views.length;
+ const panes = createBrowserPanes({ createView: electron.createView, createPopup: electron.createPopup, createParking, keepsRunning: () => keepsRunning, quitting, fromPartition: electron.fromPartition, owner: () => (electron.window.destroyed ? null : electron.window), chromeVersion: "146.0.7680.0", now: () => clock, log: (line) => logged.push(line), ...(captureMs ? { captureMs } : {}) });
+ electron.parkings = parkings;
const posted = [];
const server = { postMessage: (message) => posted.push(message) };
panes.attach(server);
@@ -186,9 +210,11 @@ test("creates a sandboxed view per tab, attaches its debugger and relays its CDP
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.options.webPreferences.devTools, false);
+ assert.deepEqual(view.webContents.loaded, ["about:blank", "https://example.com/"]);
+ const order = view.webContents.debugger.sent.map((command) => command.method);
+ assert.deepEqual(order.slice(0, 3), ["Page.addScriptToEvaluateOnNewDocument", "Runtime.evaluate", "Page.getFrameTree"]);
+ assert.equal(view.webContents.debugger.sent[0].params.worldName, undefined);
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);
@@ -550,3 +576,286 @@ test("takes an import request only from the app window's own top page", () => {
assert.throws(() => fromAppWindow({ sender: { mainFrame }, senderFrame: mainFrame }, window), /main app window/);
assert.throws(() => fromAppWindow({ sender: window.webContents, senderFrame: mainFrame }, null), /main app window/);
});
+
+async function openedWith(options) {
+ const context = setup(options);
+ context.send({ op: "open", browser: "bot:a", partition: PARTITION, egress: 41000, downloads: DOWNLOADS, identity: "native" });
+ await tick();
+ context.send({ op: "create", browser: "bot:a", req: 1, url: "about:blank" });
+ await tick();
+ await tick();
+ return context;
+}
+
+test("gives each pane its user agent with Chromium's own client hints, so navigations and fetches carry the same", async () => {
+ const hints = { brands: [{ brand: "Not;A=Brand", version: "8" }, { brand: "Chromium", version: "150" }], mobile: false, platform: "macOS", platformVersion: "15.6.0", architecture: "arm", bitness: "64", model: "", wow64: false, fullVersionList: [{ brand: "Chromium", version: "150.0.7871.250" }] };
+ const { electron } = await openedWith({ hints });
+ const contents = electron.views[0].webContents;
+ const override = contents.debugger.sent.find((command) => command.method === "Emulation.setUserAgentOverride");
+ assert.equal(override.params.userAgent, "Mozilla/5.0 (Macintosh) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.7680.0 Electron/43.7.9 Safari/537.36");
+ assert.deepEqual(override.params.userAgentMetadata.brands, hints.brands);
+ assert.equal(override.params.userAgentMetadata.platformVersion, "15.6.0");
+ // A site with a whole-tab rule gets its user agent with the same hints.
+ contents.emit("did-start-navigation", {}, "https://www.chase.com/", false, true);
+ await tick();
+ const overrides = contents.debugger.sent.filter((command) => command.method === "Emulation.setUserAgentOverride");
+ assert.equal(overrides.length, 2);
+ assert.equal(overrides[1].params.userAgent, "Mozilla/5.0 (Macintosh) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.7680.0 Safari/537.36");
+ assert.deepEqual(overrides[1].params.userAgentMetadata, overrides[0].params.userAgentMetadata);
+});
+
+test("keeps the panes running in a window never shown while the app window is closed, where the app keeps running", async () => {
+ const { electron, panes, posted } = await openedWith({ keepsRunning: true });
+ const [view] = electron.views;
+ electron.window.destroyed = true;
+ panes.windowClosed(electron.window);
+ assert.equal(electron.parkings.length, 1);
+ assert.equal(electron.parkings[0].children[0], view);
+ assert.equal(view.webContents.closed, false);
+ assert.equal(posted.some((message) => message.op === "closed"), false);
+});
+
+test("closes the panes with the window where the app quits with its last window", async () => {
+ const { electron, panes, last } = await openedWith({ keepsRunning: false });
+ electron.window.destroyed = true;
+ panes.windowClosed(electron.window);
+ assert.equal(electron.parkings.length, 0);
+ assert.equal(electron.views[0].webContents.closed, true);
+ assert.equal(last("closed").browser, "bot:a");
+});
+
+test("a person's key right after the bot's click is the person's; the bot's own echo is not", async () => {
+ const { send, posted, electron, advance } = await openedWith();
+ advance(5_000);
+ const contents = electron.views[0].webContents;
+ let finish;
+ contents.debugger.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: 10, y: 20 } });
+ contents.emit("input-event", {}, { type: "mouseDown", x: 10, y: 20 });
+ finish({});
+ await tick();
+ advance(22);
+ contents.emit("input-event", {}, { type: "keyDown" });
+ const pings = posted.filter((message) => message.op === "input");
+ assert.equal(pings.length, 1);
+});
+
+test("asks the server to hold the tab the panel shows, and lets every hold go when the window closes", async () => {
+ const { electron, panes, send, posted } = await openedWith({ keepsRunning: true });
+ // No panel shows this bot: there is no tab to hold.
+ assert.deepEqual(await panes.hold({ botId: "a", threadId: null, held: true }), { held: false });
+ 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;
+ const held = panes.hold({ botId: "a", threadId: null, held: true });
+ const asked = posted.at(-1);
+ assert.deepEqual({ op: asked.op, botId: asked.botId, threadId: asked.threadId, browser: asked.browser, tab: asked.tab, held: asked.held }, { op: "hold", botId: "a", threadId: null, browser: "bot:a", tab: "p1", held: true });
+ send({ op: "hold-result", req: asked.req, held: true });
+ assert.deepEqual(await held, { held: true });
+ await assert.rejects(panes.hold({ botId: "a", threadId: null, held: "yes" }), /invalid/);
+ electron.window.destroyed = true;
+ panes.windowClosed(electron.window);
+ assert.equal(posted.some((message) => message.op === "let-go"), true);
+});
+
+test("quits with the pane setting off: no pane was ever opened, so closing the window makes no window", () => {
+ let quitting = false;
+ const { electron, panes } = setup({ keepsRunning: true, quitting: () => quitting });
+ electron.window.destroyed = true;
+ panes.windowClosed(electron.window);
+ quitting = true;
+ panes.closeAll();
+ panes.windowClosed(electron.window);
+ assert.equal(electron.windowsMade(), 0);
+});
+
+test("quits with panes open: the panes close with the window and nothing is parked", async () => {
+ let quitting = false;
+ const { electron, panes, last } = await openedWith({ keepsRunning: true, quitting: () => quitting });
+ quitting = true;
+ panes.closeAll();
+ electron.window.destroyed = true;
+ panes.windowClosed(electron.window);
+ assert.equal(electron.parkings.length, 0);
+ assert.equal(electron.views[0].webContents.closed, true);
+ assert.equal(last("closed").browser, "bot:a");
+});
+
+test("quits with panes parked: the parking window is destroyed with them", async () => {
+ let quitting = false;
+ const { electron, panes } = await openedWith({ keepsRunning: true, quitting: () => quitting });
+ electron.window.destroyed = true;
+ panes.windowClosed(electron.window);
+ assert.equal(electron.parkings.length, 1);
+ quitting = true;
+ panes.closeAll();
+ assert.equal(electron.parkings[0].destroyed, true);
+ assert.equal(electron.views[0].webContents.closed, true);
+ assert.equal(electron.parkings.length, 1);
+});
+
+test("a window closed as the app quits never parks: the quit is not cancelled by a new window", async () => {
+ let quitting = false;
+ const { electron, panes } = await openedWith({ keepsRunning: true, quitting: () => quitting });
+ quitting = true;
+ electron.window.destroyed = true;
+ panes.windowClosed(electron.window);
+ assert.equal(electron.parkings.length, 0);
+ assert.equal(electron.views[0].webContents.closed, true);
+});
+
+test("a bot's scroll never reads as the person's", async () => {
+ const { send, posted, electron, advance } = await openedWith();
+ advance(5_000);
+ const contents = electron.views[0].webContents;
+ let finish;
+ contents.debugger.sendCommand = (method) => (method === "Input.dispatchMouseEvent" ? new Promise((resolve) => { finish = resolve; }) : Promise.resolve({}));
+ for (let scroll = 0; scroll < 25; scroll++) {
+ send({ op: "cdp", browser: "bot:a", req: 10 + scroll, tab: "p1", method: "Input.dispatchMouseEvent", params: { type: "mouseWheel", x: 200, y: 300, deltaX: 0, deltaY: 400 } });
+ for (const type of ["mouseWheel", "mouseWheel", "gestureScrollBegin", "gestureScrollUpdate"]) contents.emit("input-event", {}, { type, x: 200, y: 300 });
+ finish({});
+ await tick();
+ // Measured: every echo at most 1 ms after the answer.
+ advance(1);
+ contents.emit("input-event", {}, { type: "gestureScrollEnd", x: 200, y: 300 });
+ advance(1_000);
+ }
+ assert.equal(posted.filter((message) => message.op === "input").length, 0);
+ contents.emit("input-event", {}, { type: "mouseWheel", x: 20, y: 30 });
+ assert.equal(posted.filter((message) => message.op === "input").length, 1);
+});
+
+test("takes a parked pane's screenshot although its window never draws", async () => {
+ const { electron, panes, send, last } = await openedWith({ keepsRunning: true });
+ const contents = electron.views[0].webContents;
+ contents.neverDraws = true;
+ electron.window.destroyed = true;
+ panes.windowClosed(electron.window);
+ send({ op: "cdp", browser: "bot:a", req: 7, tab: "p1", method: "Page.captureScreenshot", params: { format: "png" } });
+ await new Promise((resolve) => setTimeout(resolve, 120));
+ assert.deepEqual(last("answer").result, { data: Buffer.from("parked").toString("base64") });
+ // One capture to make the page draw, one of the fresh frame.
+ assert.equal(contents.captured, 2);
+ // Nothing was shown for it.
+ assert.notEqual(electron.views[0].visible, true);
+});
+
+test("the bot leaving a page dismisses the alert it left open first, so the navigation is never held", async () => {
+ const { electron, send, last } = await openedWith();
+ const contents = electron.views[0].webContents;
+ const answers = [];
+ contents.emit("-run-dialog", { dialogType: "alert", messageText: "Hi" }, (ok) => answers.push(ok));
+ contents.debugger.emit("message", {}, "Page.javascriptDialogOpening", { type: "alert", message: "Hi" });
+ contents.debugger.sent.length = 0;
+ send({ op: "cdp", browser: "bot:a", req: 9, tab: "p1", method: "Page.navigate", params: { url: "https://example.com/next" } });
+ await tick();
+ await tick();
+ assert.deepEqual(contents.debugger.sent.map((command) => command.method), ["Page.handleJavaScriptDialog", "Page.navigate"]);
+ assert.deepEqual(contents.debugger.sent[0].params, { accept: false });
+ assert.equal(last("answer").req, 9);
+ // CDP closed it, and Electron's own callback is spent with it.
+ contents.debugger.emit("message", {}, "Page.javascriptDialogClosed", {});
+ assert.deepEqual(answers, []);
+ // One CDP never reported is let go as a dismissed box.
+ contents.emit("-run-dialog", { dialogType: "alert", messageText: "Again" }, (ok) => answers.push(ok));
+ contents.debugger.sent.length = 0;
+ send({ op: "cdp", browser: "bot:a", req: 10, tab: "p1", method: "Page.reload", params: {} });
+ await tick();
+ await tick();
+ assert.deepEqual(answers, [false]);
+ assert.deepEqual(contents.debugger.sent.map((command) => command.method), ["Page.reload"]);
+});
+
+test("a dialog that opens under the bot's click and its page read never holds them: both are answered at once", async () => {
+ const { electron, send, posted } = await openedWith();
+ const contents = electron.views[0].webContents;
+ const original = contents.debugger.sendCommand.bind(contents.debugger);
+ // Electron holds input and scripts while the page's alert is up; the answer to the dialog goes through.
+ contents.debugger.sendCommand = (method, params, session) => (/^(?:Input\.|Runtime\.)/.test(method) ? new Promise(() => {}) : original(method, params, session));
+ const answer = (req) => posted.find((message) => message.op === "answer" && message.req === req);
+ // The order seen live: the click's release, the driver's read of the page, then the alert opening.
+ send({ op: "cdp", browser: "bot:a", req: 20, tab: "p1", method: "Input.dispatchMouseEvent", params: { type: "mouseReleased", x: 10, y: 10, button: "left", clickCount: 1 } });
+ send({ op: "cdp", browser: "bot:a", req: 21, tab: "p1", method: "Runtime.callFunctionOn", params: { functionDeclaration: "function () { return document.title; }", objectId: "o" } });
+ await tick();
+ assert.equal(answer(20), undefined);
+ assert.equal(answer(21), undefined);
+ contents.debugger.emit("message", {}, "Page.javascriptDialogOpening", { type: "alert", message: "hello alert" });
+ await tick();
+ assert.deepEqual(answer(20).result, {});
+ assert.match(answer(21).error.message, /dialog is open/);
+ // A read sent while it is open is answered at once too, and the dialog's own answer is never held.
+ send({ op: "cdp", browser: "bot:a", req: 22, tab: "p1", method: "Runtime.evaluate", params: { expression: "1" } });
+ send({ op: "cdp", browser: "bot:a", req: 23, tab: "p1", method: "Page.handleJavaScriptDialog", params: { accept: false } });
+ await tick();
+ await tick();
+ assert.match(answer(22).error.message, /dialog is open/);
+ assert.deepEqual(answer(23).result, {});
+ // The driver's other reads of the page are answered too, not held for the link's timeout.
+ for (const [req, method] of [[24, "DOM.getBoxModel"], [25, "Accessibility.getFullAXTree"], [26, "Page.getLayoutMetrics"]]) {
+ send({ op: "cdp", browser: "bot:a", req, tab: "p1", method, params: {} });
+ await tick();
+ assert.match(answer(req).error.message, /dialog is open/, method);
+ }
+ // Leaving the page clears it, should the close event go missing.
+ contents.emit("did-start-navigation", {}, "https://example.com/next", false, true);
+ contents.debugger.sendCommand = original;
+ send({ op: "cdp", browser: "bot:a", req: 27, tab: "p1", method: "Runtime.evaluate", params: { expression: "1" } });
+ await tick();
+ await tick();
+ assert.deepEqual(answer(27).result, {});
+});
+
+test("takes a screenshot of a pane whose app window is minimised or hidden as it does a parked one", async () => {
+ const { electron, send, last } = await openedWith();
+ const contents = electron.views[0].webContents;
+ contents.neverDraws = true;
+ for (const [state, req] of [[{ isMinimized: () => true, isVisible: () => true }, 30], [{ isMinimized: () => false, isVisible: () => false }, 31]]) {
+ Object.assign(electron.window, state);
+ contents.captured = 0;
+ send({ op: "cdp", browser: "bot:a", req, tab: "p1", method: "Page.captureScreenshot", params: { format: "png" } });
+ await new Promise((resolve) => setTimeout(resolve, 120));
+ assert.deepEqual(last("answer").result, { data: Buffer.from("parked").toString("base64") });
+ assert.equal(contents.captured, 2);
+ }
+});
+
+test("a turn's preview tick under an open alert never holds the bot's navigate: the live wire's order", async () => {
+ const { electron, send, posted } = await openedWith();
+ const contents = electron.views[0].webContents;
+ const original = contents.debugger.sendCommand.bind(contents.debugger);
+ let open = false;
+ // Under the alert the page answers no screencast change, script, read or capture.
+ contents.debugger.sendCommand = (method, params, session) => {
+ if (method === "Page.handleJavaScriptDialog") open = false;
+ return open && !/^(?:Page\.(?:handleJavaScriptDialog|navigate)|Page\.getNavigationHistory)/.test(method) ? new Promise(() => {}) : original(method, params, session);
+ };
+ const answer = (req) => posted.find((message) => message.op === "answer" && message.req === req);
+ send({ op: "cdp", browser: "bot:a", req: 40, tab: "p1", method: "Input.dispatchMouseEvent", params: { type: "mouseReleased", x: 44, y: 97, button: "left", clickCount: 1 } });
+ open = true;
+ contents.debugger.emit("message", {}, "Page.javascriptDialogOpening", { type: "alert", message: "hello alert" });
+ // The preview tick: pause the panel's screencast, capture, resume.
+ send({ op: "cdp", browser: "bot:a", req: 41, tab: "p1", method: "Page.stopScreencast", params: {} });
+ send({ op: "cdp", browser: "bot:a", req: 42, tab: "p1", method: "Page.getLayoutMetrics", params: {} });
+ send({ op: "cdp", browser: "bot:a", req: 43, tab: "p1", method: "Page.captureScreenshot", params: { format: "jpeg" } });
+ send({ op: "cdp", browser: "bot:a", req: 44, tab: "p1", method: "Page.stopScreencast", params: {} });
+ send({ op: "cdp", browser: "bot:a", req: 45, tab: "p1", method: "Page.startScreencast", params: { format: "jpeg", quality: 70, maxWidth: 730, maxHeight: 1156 } });
+ await tick();
+ await tick();
+ assert.deepEqual(answer(40).result, {});
+ assert.deepEqual(answer(41).result, {});
+ assert.match(answer(42).error.message, /dialog is open/);
+ assert.match(answer(43).error.message, /dialog is open/);
+ assert.deepEqual(answer(44).result, {});
+ assert.deepEqual(answer(45).result, {});
+ // Then the bot navigates: the alert is dismissed, the page leaves, and the screencast the panel wanted starts again.
+ contents.debugger.sent.length = 0;
+ send({ op: "cdp", browser: "bot:a", req: 46, tab: "p1", method: "Page.navigate", params: { url: "https://example.com/next" } });
+ await tick();
+ contents.debugger.emit("message", {}, "Page.javascriptDialogClosed", { result: false });
+ await tick();
+ await tick();
+ assert.ok(answer(46).result);
+ const methods = contents.debugger.sent.map((command) => command.method);
+ assert.deepEqual(methods.slice(0, 2), ["Page.handleJavaScriptDialog", "Page.navigate"]);
+ assert.ok(methods.includes("Page.startScreencast"));
+});
diff --git a/electron/browser-pane-under-dialog.mjs b/electron/browser-pane-under-dialog.mjs
new file mode 100644
index 0000000000..5d2f8802dc
--- /dev/null
+++ b/electron/browser-pane-under-dialog.mjs
@@ -0,0 +1,82 @@
+// A pane's commands while its page has a JavaScript dialog open. The page's renderer waits on the dialog, so anything it
+// must answer (a script, a DOM or accessibility read, input, a screenshot, the screencast) would wait until the dialog
+// closes, and the bot's next call would queue behind it (measured on Electron 43: a turn's preview tick under an open
+// alert held the bot's navigate until the link's timeout). Nothing a pane forwards may sit unanswered in front of the
+// dialog's dismissal: each command is answered by the browser, settled at once, or settled after a short grace.
+
+export const DIALOG_HOLDS = "A JavaScript dialog is open on the page; it holds this until it is answered.";
+/** How long a command of no known kind may wait under an open dialog before it is settled with DIALOG_HOLDS. */
+export const DIALOG_GRACE_MS = 1_000;
+
+/** Answered by the browser itself, so a dialog never holds them; a navigation dismisses the dialog first. */
+const BROWSER = /^(?:Page\.(?:handleJavaScriptDialog|getNavigationHistory|navigate|reload|navigateToHistoryEntry|close|bringToFront)$|Fetch\.|Target\.|Browser\.)/;
+/** Answered by the page's renderer, which the dialog holds. */
+const PAGE = /^(?:Input\.|Runtime\.(?:evaluate|callFunctionOn|awaitPromise|getProperties)$|DOM\.(?!enable$|disable$)|Accessibility\.(?:getFullAXTree|getPartialAXTree|queryAXTree)$|Page\.(?:getLayoutMetrics|captureScreenshot)$)/;
+const SCREENCAST = /^Page\.(?:startScreencast|stopScreencast|screencastFrameAck)$/;
+
+/** Which kind of command `method` is under an open dialog. */
+export function underDialogKind(method) {
+ if (BROWSER.test(method)) return "browser";
+ if (SCREENCAST.test(method)) return "screencast";
+ if (PAGE.test(method)) return method.startsWith("Input.") ? "input" : "page";
+ return "other";
+}
+
+/**
+ * One pane's gate. `run(method, params, send)` answers a command: `send()` sends it to the page. `opened()` and
+ * `closed()` follow CDP's dialog events. A screencast started or stopped under the dialog is answered at once and
+ * applied once it closes, through `apply(method, params)`.
+ */
+export function createDialogGate({ apply, graceMs = DIALOG_GRACE_MS, setTimer = setTimeout, clearTimer = clearTimeout }) {
+ let open = false;
+ /** The screencast state wanted while the dialog was open: start parameters, null to stop, undefined for none. */
+ let cast;
+ const pending = new Set();
+ return {
+ get open() {
+ return open;
+ },
+ opened() {
+ open = true;
+ for (const item of pending) item.underDialog();
+ },
+ closed() {
+ open = false;
+ for (const item of pending) clearTimer(item.timer);
+ if (cast === undefined) return;
+ const wanted = cast;
+ cast = undefined;
+ void Promise.resolve(wanted ? apply("Page.startScreencast", wanted) : apply("Page.stopScreencast", {})).catch(() => undefined);
+ },
+ run(method, params, send) {
+ const kind = underDialogKind(method);
+ if (open) {
+ if (kind === "screencast") {
+ if (method !== "Page.screencastFrameAck") cast = method === "Page.startScreencast" ? params ?? {} : null;
+ return Promise.resolve({});
+ }
+ if (kind === "page" || kind === "input") return Promise.reject(new Error(DIALOG_HOLDS));
+ }
+ const sent = send();
+ if (kind === "browser") return sent;
+ sent.catch(() => undefined);
+ return new Promise((resolve, reject) => {
+ const item = {
+ timer: undefined,
+ underDialog() {
+ // Input was delivered and the screencast is the browser's own to restart; a read waits on the dialog.
+ if (kind === "input" || kind === "screencast") resolve({});
+ else if (kind === "page") reject(new Error(DIALOG_HOLDS));
+ else item.timer = setTimer(() => reject(new Error(DIALOG_HOLDS)), graceMs);
+ },
+ };
+ pending.add(item);
+ if (open) item.underDialog();
+ sent.then(resolve, reject).finally(() => {
+ pending.delete(item);
+ clearTimer(item.timer);
+ });
+ });
+ },
+ };
+}
diff --git a/electron/browser-pane-under-dialog.node-test.mjs b/electron/browser-pane-under-dialog.node-test.mjs
new file mode 100644
index 0000000000..eafefb8c6a
--- /dev/null
+++ b/electron/browser-pane-under-dialog.node-test.mjs
@@ -0,0 +1,60 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { createDialogGate, DIALOG_HOLDS, underDialogKind } from "./browser-pane-under-dialog.mjs";
+
+const never = () => new Promise(() => {});
+const tick = () => new Promise((resolve) => setImmediate(resolve));
+const outcome = (promise) => promise.then((value) => ({ value }), (error) => ({ error: error.message }));
+
+function gate() {
+ const applied = [];
+ const timers = [];
+ const g = createDialogGate({ apply: async (method, params) => { applied.push([method, params]); }, setTimer: (run, ms) => { timers.push({ run, ms }); return timers.length; }, clearTimer: () => {} });
+ return { g, applied, timers };
+}
+
+test("names every kind the pane forwards", () => {
+ for (const [method, kind] of [
+ ["Page.handleJavaScriptDialog", "browser"], ["Page.navigate", "browser"], ["Page.getNavigationHistory", "browser"], ["Fetch.continueRequest", "browser"], ["Target.attachToTarget", "browser"],
+ ["Page.startScreencast", "screencast"], ["Page.stopScreencast", "screencast"], ["Page.screencastFrameAck", "screencast"],
+ ["Input.dispatchMouseEvent", "input"], ["Runtime.callFunctionOn", "page"], ["DOM.getContentQuads", "page"], ["Accessibility.getFullAXTree", "page"], ["Page.getLayoutMetrics", "page"], ["Page.captureScreenshot", "page"],
+ ["Page.createIsolatedWorld", "other"], ["Network.enable", "other"], ["DOM.enable", "other"],
+ ]) assert.equal(underDialogKind(method), kind, method);
+});
+
+test("settles what was under way when a dialog opens: input as delivered, the screencast at once, a read with the dialog's error, the rest after a grace", async () => {
+ const { g, timers } = gate();
+ const click = outcome(g.run("Input.dispatchMouseEvent", {}, never));
+ const cast = outcome(g.run("Page.stopScreencast", {}, never));
+ const read = outcome(g.run("Runtime.callFunctionOn", {}, never));
+ const world = outcome(g.run("Page.createIsolatedWorld", {}, never));
+ const history = g.run("Page.getNavigationHistory", {}, async () => ({ entries: [] }));
+ g.opened();
+ assert.deepEqual(await click, { value: {} });
+ assert.deepEqual(await cast, { value: {} });
+ assert.deepEqual(await read, { error: DIALOG_HOLDS });
+ assert.equal(timers.length, 1);
+ assert.equal(timers[0].ms, 1_000);
+ timers[0].run();
+ assert.deepEqual(await world, { error: DIALOG_HOLDS });
+ assert.deepEqual(await history, { entries: [] });
+});
+
+test("while a dialog is open: reads and input refused at once, the screencast's wanted state kept and applied once it closes", async () => {
+ const { g, applied } = gate();
+ g.opened();
+ const sent = [];
+ const send = (method) => () => { sent.push(method); return never(); };
+ assert.deepEqual(await outcome(g.run("Page.captureScreenshot", {}, send("Page.captureScreenshot"))), { error: DIALOG_HOLDS });
+ assert.deepEqual(await outcome(g.run("Input.dispatchKeyEvent", {}, send("Input.dispatchKeyEvent"))), { error: DIALOG_HOLDS });
+ assert.deepEqual(await g.run("Page.stopScreencast", {}, send("Page.stopScreencast")), {});
+ assert.deepEqual(await g.run("Page.startScreencast", { format: "jpeg", maxWidth: 730 }, send("Page.startScreencast")), {});
+ assert.deepEqual(sent, []);
+ // The dialog's own answer always goes through.
+ assert.deepEqual(await g.run("Page.handleJavaScriptDialog", { accept: false }, async () => ({})), {});
+ g.closed();
+ await tick();
+ assert.deepEqual(applied, [["Page.startScreencast", { format: "jpeg", maxWidth: 730 }]]);
+ assert.equal(g.open, false);
+});
diff --git a/electron/browser-pane-wire.d.mts b/electron/browser-pane-wire.d.mts
index 715f95ca5c..b74d50b078 100644
--- a/electron/browser-pane-wire.d.mts
+++ b/electron/browser-pane-wire.d.mts
@@ -20,6 +20,7 @@ export type PaneToMain = Base & (
| { op: "cookie-sources-result"; req: number; sources: CookieSource[] }
| { op: "cookie-import-result"; req: number; result: CookieImportResult }
| { op: "cookie-offer-result"; req: number; offered: boolean; reason?: string }
+ | { op: "hold-result"; req: number; held: boolean }
);
/** Electron's cookies.set details. */
@@ -66,6 +67,9 @@ export type PaneToServer = Base & (
| { op: "cookie-sources"; req: number }
| { op: "cookie-offer"; req: number; botId: string; threadId: string | null; site: string }
| { op: "cookie-import"; req: number; botId: string; threadId: string | null; site: string; source: string; profile: string }
+ /** The person takes the tab the panel shows from the bot, or hands it back; every hold ends when the window goes. */
+ | { op: "hold"; req: number; botId: string; threadId: string | null; browser: string; tab: string; held: boolean }
+ | { op: "let-go" }
| { op: "download"; browser: string; tab: string; guid: string; state: "begin" | "inProgress" | "completed" | "canceled"; url?: string; name?: string; received?: number; total?: number; path?: string }
);
diff --git a/electron/browser-pane-wire.mjs b/electron/browser-pane-wire.mjs
index 0c6b025465..ebcc57de15 100644
--- a/electron/browser-pane-wire.mjs
+++ b/electron/browser-pane-wire.mjs
@@ -24,8 +24,8 @@ const SAME_SITE = new Set(["unspecified", "no_restriction", "lax", "strict"]);
const COOKIE_BYTES = 4096;
const MAX_COOKIES = 2000;
-const TO_MAIN = new Set(["hello", "open", "create", "cdp", "front", "close-tab", "close", "erase", "resolved", "cancel-download", "set-cookies", "cookie-sources-result", "cookie-import-result", "cookie-offer-result"]);
-const TO_SERVER = new Set(["hello", "opened", "failed", "created", "answer", "event", "tab", "tab-gone", "closed", "input", "which", "download", "cookies-set", "cookie-sources", "cookie-import", "cookie-offer"]);
+const TO_MAIN = new Set(["hello", "open", "create", "cdp", "front", "close-tab", "close", "erase", "resolved", "cancel-download", "set-cookies", "cookie-sources-result", "cookie-import-result", "cookie-offer-result", "hold-result"]);
+const TO_SERVER = new Set(["hello", "opened", "failed", "created", "answer", "event", "tab", "tab-gone", "closed", "input", "which", "download", "cookies-set", "cookie-sources", "cookie-import", "cookie-offer", "hold", "let-go"]);
const isObject = (value) => Object.prototype.toString.call(value) === "[object Object]";
const text = (value, pattern) => typeof value === "string" && pattern.test(value);
@@ -82,6 +82,9 @@ function fieldsValid(message) {
return count(message.req) && text(message.botId, BOT) && (message.threadId === null || text(message.threadId, BOT)) && short(message.site, 2048)
&& (message.op === "cookie-offer" || (text(message.source, SOURCE) && short(message.profile, 512) && message.profile.length > 0));
case "cookie-import-result": return count(message.req) && isObject(message.result) && typeof message.result.ok === "boolean";
+ case "hold": return count(message.req) && text(message.botId, BOT) && (message.threadId === null || text(message.threadId, BOT)) && text(message.browser, BROWSER) && text(message.tab, TAB) && typeof message.held === "boolean";
+ case "hold-result": return count(message.req) && typeof message.held === "boolean";
+ case "let-go": return true;
case "cookie-offer-result": return count(message.req) && typeof message.offered === "boolean" && (message.reason === undefined || short(message.reason, 32));
default: return true;
}
diff --git a/electron/main.mjs b/electron/main.mjs
index b1abbb5848..74d3a376a4 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -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; const browserPanes = createBrowserPanes({ createView: (options) => new WebContentsView(options), createPopup: (options) => new BrowserWindow(options), fromPartition: (name) => session.fromPartition(name), owner: () => (mainWindow && !mainWindow.isDestroyed() ? mainWindow : null), chromeVersion: process.versions.chrome, log: (line) => slog(line) });
+let mainWindow = null; const browserPanes = createBrowserPanes({ createView: (options) => new WebContentsView(options), createPopup: (options) => new BrowserWindow(options), createParking: () => new BrowserWindow({ show: false, width: 1280, height: 800, skipTaskbar: true, webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false } }), keepsRunning: () => process.platform === "darwin" || hiddenStart || alwaysOnHome.on(), quitting: () => desktopShutdownStarted, 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;
@@ -1127,7 +1127,7 @@ async function startServerOn(port, dataDir = runningDataDir ?? startupEnvironmen
OMB_CREDENTIAL_STORE: credentialStoreUnavailable ? "unavailable" : "ok",
...workspaceCredentialEnv(secureCredentials),
});
- delete childEnv.OMB_BROWSER_CONNECTION;
+ delete childEnv.OMB_BROWSER_CONNECTION; if (app.isPackaged) delete childEnv.OMB_TEST_COOKIE_KEY; // a live test's fixture key; never a packaged app's
delete childEnv.OMB_SERVER_COMPILE_CACHE;
if (compileCacheDir) childEnv.OMB_SERVER_COMPILE_CACHE = compileCacheDir;
slog(`fork ${entry} port=${port}`); launchRecord.mark("serverForked");
@@ -1980,7 +1980,7 @@ function createWindow({ deferNavigation = false } = {}) {
applyUnreadBadge(win);
if (restored.maximized && !startupScreen) win.maximize();
win.once("closed", () => {
- if (mainWindow === win) { mainWindow = null; browserPanes.closeAll(); }
+ if (mainWindow === win) { mainWindow = null; browserPanes.windowClosed(win); }
});
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("browser-cookies:sources", localOnly("browser-cookies:sources", (event) => { fromAppWindow(event, mainWindow); return browserPanes.cookieSources(); })); ipcMain.handle("browser-cookies:offer", localOnly("browser-cookies:offer", (event, input) => { fromAppWindow(event, mainWindow); return browserPanes.cookieOffer(input); })); ipcMain.handle("browser-cookies:import", localOnly("browser-cookies:import", (event, input) => { fromAppWindow(event, mainWindow); return browserPanes.importCookies(input); }));
+})); 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("browser-pane:hold", localOnly("browser-pane:hold", (event, input) => { fromAppWindow(event, mainWindow); return browserPanes.hold(input); })); ipcMain.handle("browser-cookies:sources", localOnly("browser-cookies:sources", (event) => { fromAppWindow(event, mainWindow); return browserPanes.cookieSources(); })); ipcMain.handle("browser-cookies:offer", localOnly("browser-cookies:offer", (event, input) => { fromAppWindow(event, mainWindow); return browserPanes.cookieOffer(input); })); ipcMain.handle("browser-cookies:import", localOnly("browser-cookies:import", (event, input) => { fromAppWindow(event, mainWindow); return browserPanes.importCookies(input); }));
ipcMain.handle("desktop-workspace:set-interactive", localOnly("desktop-workspace:set-interactive", (event, contextId) => {
const manager = desktopWorkspaceForEvent(event);
if (!manager) return contextId == null;
@@ -3067,7 +3067,7 @@ process.once("SIGINT", requestSignalQuit);
process.once("SIGTERM", requestSignalQuit);
app.on("before-quit", (e) => {
- talk.close();
+ talk.close(); browserPanes.closeAll();
desktopShutdownStarted = true;
startupScreen?.dispose();
companyBackupSchedule?.close();
diff --git a/electron/preload.cjs b/electron/preload.cjs
index ebba5b43f1..7423575891 100644
--- a/electron/preload.cjs
+++ b/electron/preload.cjs
@@ -433,6 +433,7 @@ const bridge = {
// 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),
+ hold: (input) => ipcRenderer.invoke("browser-pane:hold", input),
},
// This computer's page only: a site's sign-in from the person's own browsers into a bot's, which they start themselves.
browserCookies: {
diff --git a/electron/preload.node-test.mjs b/electron/preload.node-test.mjs
index c98fd9ac07..f2c01d109d 100644
--- a/electron/preload.node-test.mjs
+++ b/electron/preload.node-test.mjs
@@ -182,3 +182,10 @@ test("a Cloud link arriving before React subscriptions is delivered exactly once
assert.deepEqual(calls, ["cloud"], "later subscriptions must not reopen Settings");
late();
});
+
+test("the browser pane bridge asks main over its own channels with only the panel's input", async () => {
+ const before = invocations.length;
+ const input = { botId: "a", threadId: null, held: true };
+ await exposed.api.browserPane.hold(input);
+ assert.deepEqual(invocations.slice(before), [["browser-pane:hold", input]]);
+});
diff --git a/server/browser/backends.ts b/server/browser/backends.ts
index 09093d27bd..bbb1268b15 100644
--- a/server/browser/backends.ts
+++ b/server/browser/backends.ts
@@ -58,8 +58,8 @@ export interface OpenedBrowser {
/** 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; held(targetId: string): boolean };
+ * release), says who acted last in it, whether it holds a tab, and whether the person holds any tab. */
+ personControl?: { hold(targetId: string, held: boolean): void; owner(targetId: string): "person" | "bot" | null; held(targetId: string): boolean; holding(): boolean };
/** The private display its window is on, which a person sees as a remote desktop; absent when it runs headless. */
readonly display?: DesktopDisplay | null;
}
diff --git a/server/browser/cookies/cookies.test.ts b/server/browser/cookies/cookies.test.ts
index cd207bc638..e6b85035be 100644
--- a/server/browser/cookies/cookies.test.ts
+++ b/server/browser/cookies/cookies.test.ts
@@ -1,5 +1,5 @@
import { randomBytes } from "node:crypto";
-import { chmodSync, mkdirSync, mkdtempSync, readdirSync, writeFileSync } from "node:fs";
+import { chmodSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, afterEach, describe, expect, it, vi } from "vitest";
@@ -8,7 +8,7 @@ import { removeTempDir } from "../../testing/cleanup.ts";
import { importCookies, type CookieSink } from "./importer.ts";
import { googleCookie, importSite, writable, type WritableCookie } from "./policy.ts";
import { decryptChromium, deriveCbcKey, readChromium } from "./readers.ts";
-import { chromiumKey, firefoxProfiles, listSources, locate, systemKeyStore } from "./sources.ts";
+import { chromiumKey, firefoxProfiles, keyStoreFor, listSources, locate, systemKeyStore, TEST_COOKIE_KEY_ENV } from "./sources.ts";
import { binaryCookies, chromiumDatabase, fakeKeys, firefoxProfile, fixtureFiles, gcmValue, localState } from "./testing/fixtures.ts";
const folders: string[] = [];
@@ -277,6 +277,21 @@ describe("the cookies a bot's browser can take", () => {
});
describe("the system key stores", () => {
+ it("answer a live test's fixture password without ever calling a system tool, and only where it is set", async () => {
+ const calls: string[] = [];
+ const run = async (command: string) => { calls.push(command); return "system\n"; };
+ const fixture = keyStoreFor({ [TEST_COOKIE_KEY_ENV]: "fixture-password" }, run);
+ expect(await fixture.macPassword("Chrome Safe Storage", "Chrome")).toBe("fixture-password");
+ expect(await fixture.linuxPassword("chrome")).toBe("fixture-password");
+ await expect(fixture.windowsUnprotect(Buffer.from("blob"))).rejects.toThrow(/DPAPI/);
+ expect(calls).toEqual([]);
+ expect(await keyStoreFor({}, run).macPassword("Chrome Safe Storage", "Chrome")).toBe("system\n");
+ expect(calls).toEqual(["/usr/bin/security"]);
+ // The packaged app never hands the fixture key to its server.
+ const main = readFileSync(new URL("../../../electron/main.mjs", import.meta.url), "utf8");
+ expect(main).toContain(`if (app.isPackaged) delete childEnv.${TEST_COOKIE_KEY_ENV};`);
+ });
+
it("ask each system's own tool by its absolute path, with nothing from a caller in a shell", async () => {
const calls: Array<[string, readonly string[], string | undefined]> = [];
const run = async (command: string, args: readonly string[], input?: string) => {
diff --git a/server/browser/cookies/sources.ts b/server/browser/cookies/sources.ts
index 4c2985d98b..464d19da0e 100644
--- a/server/browser/cookies/sources.ts
+++ b/server/browser/cookies/sources.ts
@@ -280,6 +280,23 @@ export function systemKeyStore(env: BrowserFiles["env"], run: Run = runProgram):
};
}
+/** Live tests set it to a fixture profile's Safe Storage password; the packaged app never passes it to its server. */
+export const TEST_COOKIE_KEY_ENV = "OMB_TEST_COOKIE_KEY";
+
+/**
+ * The key store an import uses: the system's, or, for a live test of a fixture profile, one that answers every
+ * Chromium browser's password with `OMB_TEST_COOKIE_KEY` and never reaches the Keychain, DPAPI or a keyring.
+ */
+export function keyStoreFor(env: BrowserFiles["env"], run: Run = runProgram): KeyStore {
+ const fixture = env[TEST_COOKIE_KEY_ENV];
+ if (fixture === undefined || fixture === "") return systemKeyStore(env, run);
+ return {
+ macPassword: async () => fixture,
+ windowsUnprotect: async () => { throw new Error("A test key store unwraps no DPAPI blob."); },
+ linuxPassword: async () => fixture,
+ };
+}
+
/** This computer as the person's own account sees it: only ever read once the person asked for an import. */
export function systemFiles(): BrowserFiles {
return {
diff --git a/server/browser/dispatch.ts b/server/browser/dispatch.ts
index 6f1d6a5129..88c65da55f 100644
--- a/server/browser/dispatch.ts
+++ b/server/browser/dispatch.ts
@@ -60,6 +60,8 @@ export interface ToolContext {
secretOnPage(tab: Tab): Promise<boolean>;
saveScreenshot(data: Buffer, pageUrl: string): string;
downloads(): Download[];
+ /** Whether the person holds a tab of this browser in the app: the bot's tabs then stay behind theirs. */
+ personHolds?(): boolean;
}
/** A typed address with its scheme: a bare host means https, loopback http. */
@@ -145,6 +147,17 @@ function signInWait(tab: Tab, url: string, prompt: { origin: string; realm: stri
return `${tab.id} is waiting at ${sanitizeUrl(url) || url}: the site asks for a user name and password (HTTP sign-in for ${prompt.origin}${prompt.realm ? `, "${prompt.realm.slice(0, 100)}"` : ""}). The person watching this browser can answer it, and the page loads once they do; agent_browser_status shows the prompt until then. Do not try to answer it yourself.`;
}
+/**
+ * Leaving a page with its alert, confirm or prompt open dismisses it first, as the page cannot unload under it; the
+ * bot is told. A beforeunload is the navigation's own and is accepted there.
+ */
+async function leaving(tab: Tab): Promise<string | null> {
+ const dialog = tab.page.dialogs.pending;
+ if (!dialog || dialog.type === "beforeunload") return null;
+ await tab.page.dialogs.answer({ accept: false });
+ return `Dismissed the page's open ${dialog.type} dialog ${JSON.stringify(dialog.message.slice(0, 300))} to leave the page.`;
+}
+
/** A dialog the action opened ends its answer: nothing else runs on the tab until it is answered. */
function dialogNote(tab: Tab): string | null {
const dialog = tab.page.dialogs.pending;
@@ -268,13 +281,14 @@ export async function executeTool(context: ToolContext, call: ToolCall): Promise
const tab = existing ?? await context.control.agent(null, () => context.openTab());
return context.control.agent(tab, async () => {
await tab.page.bringToFront();
+ const dismissed = address ? await leaving(tab) : null;
const opened = address ? await tab.page.navigate(address, { readiness: "load", timeoutMs: remaining(context) }) : null;
if (opened?.signInPrompt) return textResult(signInWait(tab, opened.url, opened.signInPrompt));
const lead = opened
? `Opened ${sanitizeUrl(opened.url) || opened.url} in ${tab.id}${opened.status && opened.status >= 400 ? `; the site answered HTTP ${opened.status}` : ""}.`
: `${tab.id} is open at ${sanitizeUrl(tab.page.url()) || tab.page.url()}.`;
const snapshot = await snapshotResult(context, tab);
- return withParts(textResult(lead, "Page observed after navigation. Its refs are current, so act on them without another snapshot. Check this result for redirects, sign-in requirements or page errors before reporting task success:"), ...snapshot.content.map((part) => (part.type === "text" ? part.text : null)), dialogNote(tab));
+ return withParts(textResult(dismissed ? `${dismissed} ${lead}` : lead, "Page observed after navigation. Its refs are current, so act on them without another snapshot. Check this result for redirects, sign-in requirements or page errors before reporting task success:"), ...snapshot.content.map((part) => (part.type === "text" ? part.text : null)), dialogNote(tab));
});
}
case "agent_browser_navigate": {
@@ -283,11 +297,12 @@ export async function executeTool(context: ToolContext, call: ToolCall): Promise
if ((url === undefined) === (action === undefined)) return errorResult("Pass url or action (back, forward or reload), not both.");
return act(context, tab, async () => {
const options = { readiness, timeoutMs: remaining(context) };
+ const dismissed = await leaving(tab);
const result = url !== undefined
? await tab.page.navigate(agentUrl(url), options)
: action === "back" ? await tab.page.back(options) : action === "forward" ? await tab.page.forward(options) : await tab.page.reload(options);
if (result.signInPrompt) return textResult(signInWait(tab, result.url, result.signInPrompt));
- return textResult(`${tab.id} is now at ${sanitizeUrl(result.url) || result.url}${result.status && result.status >= 400 ? ` (HTTP ${result.status})` : ""}. Refs from earlier snapshots do not apply to it; take a snapshot before acting on refs.`);
+ return textResult(`${dismissed ? `${dismissed} ` : ""}${tab.id} is now at ${sanitizeUrl(result.url) || result.url}${result.status && result.status >= 400 ? ` (HTTP ${result.status})` : ""}. Refs from earlier snapshots do not apply to it; take a snapshot before acting on refs.`);
});
}
case "agent_browser_snapshot": {
@@ -303,8 +318,10 @@ export async function executeTool(context: ToolContext, call: ToolCall): Promise
const read = readsDuringHold(call) && heldRead(context, tab);
return act(context, tab, async () => {
if (!read) await tab.page.bringToFront();
- if (call.input.url !== undefined && call.input.url.trim() !== "") await tab.page.navigate(agentUrl(call.input.url), { readiness: "load", timeoutMs: remaining(context) });
- return textResult(`${pageLabel(describe(tab))}\n${await readText(tab, call.input)}`);
+ const going = call.input.url !== undefined && call.input.url.trim() !== "";
+ const dismissed = going ? await leaving(tab) : null;
+ if (going) await tab.page.navigate(agentUrl(call.input.url!), { readiness: "load", timeoutMs: remaining(context) });
+ return textResult(`${dismissed ? `${dismissed}\n` : ""}${pageLabel(describe(tab))}\n${await readText(tab, call.input)}`);
}, { read });
}
case "agent_browser_screenshot": {
@@ -446,12 +463,14 @@ export async function executeTool(context: ToolContext, call: ToolCall): Promise
return act(context, tab, async () => {
await tab.page.bringToFront();
if (address) await tab.page.navigate(address, { readiness: "load", timeoutMs: remaining(context) });
- return textResult(`Opened ${tab.id} at ${sanitizeUrl(tab.page.url()) || tab.page.url()}. It is in front; take a snapshot to act on it.`);
+ const where = context.personHolds?.() ? "It opened behind the tab the person is using" : "It is in front";
+ return textResult(`Opened ${tab.id} at ${sanitizeUrl(tab.page.url()) || tab.page.url()}. ${where}; take a snapshot to act on it.`);
});
}
if (!which) return errorResult(`Pass tab for ${action}.`);
const tab = tabOf(context, which);
if (action === "close") return context.control.agent(null, async () => { await context.closeTab(tab); return textResult(`Closed ${tab.id}.`); });
+ if (context.personHolds?.()) return errorResult(`The person is using a tab of this browser, so ${tab.id} stays behind it. Act on ${tab.id} by passing tab, or wait until they hand the tab back.`);
return context.control.agent(tab, async () => {
await tab.page.bringToFront();
return textResult(`${tab.id} is in front: ${pageLabel(describe(tab))}. Take a snapshot to act on it.`);
diff --git a/server/browser/engines.ts b/server/browser/engines.ts
index bcb5dada65..7cc773298b 100644
--- a/server/browser/engines.ts
+++ b/server/browser/engines.ts
@@ -207,7 +207,7 @@ export class ChromeEngine {
if (this.#timer) clearInterval(this.#timer);
this.#timer = null;
this.live.closeAll();
- this.stream.closeAll();
+ this.stream.closeAll({ stopping: true });
this.desktop.closeAll();
await this.service.closeAll();
await this.displays.closeAll();
@@ -423,6 +423,11 @@ export class LiveRouter {
return chromeTarget(session, spec) ? this.#chrome.service.answerFileChooser(session, owner, chooserId, paths) : Promise.resolve(false);
}
+ /** The person takes a tab of a desktop pane from the bot, or hands it back; null where there is no such pane tab. */
+ hold({ session, spec }: SessionSpec, tab: string, held: boolean): string | null {
+ return chromeTarget(session, spec) ? this.#chrome.service.holdTab(session, tab, held) : null;
+ }
+
download({ session, spec }: SessionSpec, id: string): Download | undefined {
return chromeTarget(session, spec) ? this.#chrome.service.download(session, id) : undefined;
}
@@ -431,7 +436,8 @@ export class LiveRouter {
closeForSession(session: string): void { this.#chrome.live.closeForSession(session); this.#chrome.stream.closeForSession(session); this.#chrome.desktop.closeForSession(session); this.#old.closeForSession(session); }
closeForOwner(owner: string): void { this.#chrome.live.closeForOwner(owner); this.#chrome.stream.closeForOwner(owner); this.#chrome.desktop.closeForOwner(owner); this.#old.closeForOwner(owner); }
closeForBot(botId: string): void { this.#chrome.live.closeForBot(botId); this.#chrome.stream.closeForBot(botId); this.#chrome.desktop.closeForBot(botId); this.#old.closeForBot(botId); }
- closeAll(): void { this.#chrome.live.closeAll(); this.#chrome.stream.closeAll(); this.#chrome.desktop.closeAll(); this.#old.closeAll(); }
+ /** `stopping`: the server is stopping, and the panels' streams reconnect to the one that starts next. */
+ closeAll({ stopping = false }: { stopping?: boolean } = {}): void { this.#chrome.live.closeAll(); this.#chrome.stream.closeAll({ stopping }); this.#chrome.desktop.closeAll(); this.#old.closeAll(); }
/** Who may see what changed: every v2 or desktop view that no longer shows its browser to a person allowed to see it closes now. */
recheck(): void { this.#chrome.stream.recheck(); this.#chrome.desktop.recheck(); }
}
diff --git a/server/browser/pane/backend.ts b/server/browser/pane/backend.ts
index faaf05471e..01190a819c 100644
--- a/server/browser/pane/backend.ts
+++ b/server/browser/pane/backend.ts
@@ -84,7 +84,9 @@ export class PaneBackend implements Backend {
const offInput = opened.onPersonInput(() => {
for (const page of browser.pages()) page.refs.invalidateAll();
});
- const exited = new Promise<void>((resolve) => { browser.connection.onClose(() => { offInput(); resolve(); }); });
+ // A tab the person hands back may have changed under the bot's refs.
+ const offHold = opened.endpoint.onHold((targetId, held) => { if (!held) browser.page(targetId)?.refs.invalidateAll(); });
+ const exited = new Promise<void>((resolve) => { browser.connection.onClose(() => { offInput(); offHold(); resolve(); }); });
return {
browser,
pageLimit: null,
@@ -95,12 +97,10 @@ export class PaneBackend implements Backend {
onSiteRefusal: (listener) => opened.endpoint.onRefusal(listener),
onPersonInput: (listener) => opened.onPersonInput(listener),
personControl: {
- hold: (targetId, held) => {
- opened.endpoint.hold(targetId, held);
- if (!held) browser.page(targetId)?.refs.invalidateAll();
- },
+ hold: (targetId, held) => opened.endpoint.hold(targetId, held),
owner: (targetId) => opened.endpoint.owner(targetId),
held: (targetId) => opened.endpoint.held(targetId),
+ holding: () => opened.endpoint.holding(),
},
close: async () => {
await browser.close();
diff --git a/server/browser/pane/endpoint.ts b/server/browser/pane/endpoint.ts
index d82baa5016..b3d3122235 100644
--- a/server/browser/pane/endpoint.ts
+++ b/server/browser/pane/endpoint.ts
@@ -106,6 +106,7 @@ export class PaneEndpoint implements CdpTransport {
readonly #maxHoldMs: number;
readonly #primeMs: number;
readonly #refusals = new Set<(refusal: SiteRefusal) => void>();
+ readonly #holds = new Set<(targetId: string, held: boolean) => void>();
#autoAttach = false;
#viewerCount = 0;
#lastInput = 0;
@@ -238,7 +239,38 @@ export class PaneEndpoint implements CdpTransport {
/** 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;
+ for (const tab of this.#tabs.values()) if (tab.target === targetId) this.#setHeld(tab, held);
+ }
+
+ /** `hold` by the app's own name for the tab; the tab's target, or null when it is not one of these panes. */
+ holdTab(tab: string, held: boolean): string | null {
+ const state = this.#tabs.get(tab);
+ if (!state) return null;
+ this.#setHeld(state, held);
+ return state.target;
+ }
+
+ /** Every hold ends: the app window the person held them from has gone. */
+ releaseAll(): void {
+ for (const tab of this.#tabs.values()) if (tab.held) this.#setHeld(tab, false);
+ }
+
+ /** Called as a tab is held or handed back. */
+ onHold(listener: (targetId: string, held: boolean) => void): () => void {
+ this.#holds.add(listener);
+ return () => this.#holds.delete(listener);
+ }
+
+ #setHeld(tab: TabState, held: boolean): void {
+ tab.held = held;
+ for (const listener of this.#holds) {
+ try { listener(tab.target, held); } catch {}
+ }
+ }
+
+ /** Whether the person holds any tab: the bot's tabs then stay behind it. */
+ holding(): boolean {
+ return this.#anyHeld();
}
/** The person holds this tab now. */
@@ -361,9 +393,9 @@ export class PaneEndpoint implements CdpTransport {
}
async #page(tab: TabState, method: string, params: Params): Promise<Params> {
+ // The driver fronts a page before it navigates; while the person holds another tab, the page loads behind it.
if (method === "Page.bringToFront") {
- this.#refuseFront(tab);
- this.#channel.front(tab.tab);
+ if (!this.#heldOtherThan(tab)) this.#channel.front(tab.tab);
return {};
}
if (method === "Page.close") {
@@ -371,6 +403,8 @@ export class PaneEndpoint implements CdpTransport {
return {};
}
if (method === "Emulation.setDeviceMetricsOverride") throw new Refusal("A desktop pane is sized by the app window.");
+ // An answer to the page's dialog waits on nothing: what is under way on the page may be waiting on that dialog.
+ if (method === "Page.handleJavaScriptDialog") return this.#channel.command(tab.tab, method, params);
const ahead = tab.gate;
const input = method.startsWith("Input.");
if (input) {
@@ -430,9 +464,14 @@ export class PaneEndpoint implements CdpTransport {
return false;
}
+ #heldOtherThan(tab: TabState): boolean {
+ for (const other of this.#tabs.values()) if (other.held && other !== tab) 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);
+ if (this.#heldOtherThan(tab)) throw new Refusal(PERSON_HOLDS_TAB);
}
#tab(targetId: string): TabState {
diff --git a/server/browser/pane/link.ts b/server/browser/pane/link.ts
index 112eef1f0f..6173de28fe 100644
--- a/server/browser/pane/link.ts
+++ b/server/browser/pane/link.ts
@@ -255,6 +255,17 @@ export class PaneLink {
void this.#answer(message.req, async () => ({ op: "cookie-import-result", req: message.req, result: await this.#cookies!.import(message) }),
() => ({ op: "cookie-import-result", req: message.req, result: { ok: false, reason: "unreadable" } }));
return;
+ case "hold": {
+ // The tab must be one of the browser this server shows for that bot and conversation.
+ const shown = this.#resolver?.(message.botId, message.threadId) ?? null;
+ const shownOpen = shown === message.browser ? this.#browsers.get(shown) : undefined;
+ const target = shownOpen?.endpoint.holdTab(message.tab, message.held) ?? null;
+ this.#post({ op: "hold-result", req: message.req, held: target !== null && message.held });
+ return;
+ }
+ case "let-go":
+ for (const open of this.#browsers.values()) open.endpoint.releaseAll();
+ return;
}
const open = this.#browsers.get(message.browser);
if (!open) return;
diff --git a/server/browser/pane/pane.test.ts b/server/browser/pane/pane.test.ts
index 5bbe09789c..4aa248977f 100644
--- a/server/browser/pane/pane.test.ts
+++ b/server/browser/pane/pane.test.ts
@@ -147,6 +147,93 @@ describe("the bots' browser as desktop panes", () => {
expect(control.owner(targetId)).toBe("person");
});
+ it("takes a hold from the app's panel only for the tab that panel shows, and ends every hold when the window goes", async () => {
+ const { main, link, service, call, text } = setup({ quietMs: 0 });
+ link.resolveWith((botId) => (botId === "a" ? "bot:a" : null));
+ await call("agent_browser_open", { url: "https://example.com/form" });
+ const control = service.profiles()[0]!.run!.opened.personControl!;
+ const answered = async (fields: Record<string, unknown>) => {
+ const req = 900 + main.toMain.length;
+ main.post({ op: "hold", req, threadId: null, tab: "p1", ...fields });
+ await sleep(5);
+ return main.toMain.find((message) => message.op === "hold-result" && (message as { req: number }).req === req) as { held: boolean } | undefined;
+ };
+ // Another bot's panel cannot hold this browser's tab.
+ expect(await answered({ botId: "b", browser: "bot:a", held: true })).toMatchObject({ held: false });
+ expect(control.holding()).toBe(false);
+ expect(await answered({ botId: "a", browser: "bot:a", held: true })).toMatchObject({ held: true });
+ expect(text(await call("agent_browser_click", { selector: "#go" }))).toContain("The person is using this tab.");
+ main.post({ op: "let-go" });
+ await sleep(5);
+ expect(control.holding()).toBe(false);
+ expect((await call("agent_browser_click", { selector: "#go" })).isError).toBeUndefined();
+ });
+
+ it("holds the tab the HTTP route names, not the bot's active one", async () => {
+ const { service, target, call, text } = setup({ quietMs: 0 });
+ await call("agent_browser_open", { url: "https://example.com/form" });
+ expect(service.holdTab(target.session, "t1", true)).toBe("t1");
+ expect(text(await call("agent_browser_click", { selector: "#go" }))).toContain("The person is using this tab.");
+ // The bot's tab opened behind the person's is the bot's active one; the person's hold stays on theirs.
+ await call("agent_browser_tabs", { action: "new" });
+ expect(text(await call("agent_browser_click", { selector: "#go", tab: "t1" }))).toContain("The person is using this tab.");
+ expect(service.holdTab(target.session, "t1", false)).toBe("t1");
+ expect(text(await call("agent_browser_click", { ref: "e2", tab: "t1" }))).toContain("Take a fresh snapshot");
+ expect(service.holdTab(target.session, "t9", true)).toBe(null);
+ expect(service.holdTab("no-such-session", "t1", true)).toBe(null);
+ });
+
+ it("answers the page's dialog at once, never behind input waiting for the person to finish", async () => {
+ const { main, service, call } = setup({ quietMs: 1_500 });
+ await call("agent_browser_open", { url: "https://example.com/form" });
+ const page = service.profiles()[0]!.run!.browser.activePage!;
+ main.personInput("bot:a", "p1");
+ await sleep(5);
+ void page.session.send("Input.dispatchKeyEvent", { type: "keyDown", key: "a" }).catch(() => undefined);
+ main.commands.length = 0;
+ const started = Date.now();
+ await page.session.send("Page.handleJavaScriptDialog", { accept: false });
+ expect(Date.now() - started).toBeLessThan(500);
+ expect(main.commands.map((command) => command.method)).toEqual(["Page.handleJavaScriptDialog"]);
+ });
+
+ it("never holds the bot's navigate behind a turn's preview of a page under an alert, with the panel watching", async () => {
+ const { main, service, target, call, text } = setup({ quietMs: 0 });
+ await call("agent_browser_open", { url: "https://example.com/form" });
+ const viewer = await service.attachViewer(target, { owner: "local-owner", canOperate: true, maxWidth: 730, maxHeight: 1156 }, (output) => { if (output.type === "frame") output.ack(); });
+ await sleep(20);
+ main.post({ op: "event", browser: "bot:a", tab: "p1", method: "Page.javascriptDialogOpening", params: { type: "alert", message: "hello alert", url: "https://example.com/form" } });
+ await sleep(5);
+ // Under the alert the page answers no screencast change, script, read or capture, as Electron's did live.
+ let open = true;
+ main.hang = (command) => {
+ if (command.method === "Page.handleJavaScriptDialog") open = false;
+ return open && /^(?:Page\.(?:startScreencast|stopScreencast|getLayoutMetrics|captureScreenshot)|Runtime\.|DOM\.|Accessibility\.)/.test(command.method);
+ };
+ const preview = service.previewFrame("bot-a").then(() => "pictured", (error: Error) => error.message);
+ const started = Date.now();
+ const result = await call("agent_browser_open", { url: "https://example.com/next" });
+ expect(Date.now() - started).toBeLessThan(2_000);
+ expect(text(result)).toContain("Dismissed the page's open alert dialog");
+ expect(await preview).toMatch(/dialog/);
+ await viewer.close();
+ });
+
+ it("dismisses the alert a page left open when the bot navigates away, and says so", async () => {
+ const { main, call, text } = setup({ quietMs: 0 });
+ await call("agent_browser_open", { url: "https://example.com/form" });
+ main.post({ op: "event", browser: "bot:a", tab: "p1", method: "Page.javascriptDialogOpening", params: { type: "alert", message: "Saved!", url: "https://example.com/form" } });
+ await sleep(5);
+ main.commands.length = 0;
+ const result = await call("agent_browser_navigate", { url: "https://example.com/next" });
+ expect(result.isError, text(result)).toBeUndefined();
+ expect(text(result)).toContain(`Dismissed the page's open alert dialog "Saved!" to leave the page.`);
+ const methods = main.commands.map((command) => command.method);
+ expect(methods.indexOf("Page.handleJavaScriptDialog")).toBeGreaterThanOrEqual(0);
+ expect(methods.indexOf("Page.handleJavaScriptDialog")).toBeLessThan(methods.indexOf("Page.navigate"));
+ expect(main.commands.find((command) => command.method === "Page.handleJavaScriptDialog")!.params).toEqual({ accept: false });
+ });
+
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" });
@@ -190,7 +277,8 @@ describe("what a held pane lets the bot do", () => {
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);
+ // The driver's own fronting before a navigation leaves the page behind the person's.
+ await second!.session.send("Page.bringToFront");
// 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);
@@ -221,13 +309,23 @@ describe("what a held pane lets the bot do", () => {
expect(main.commands).toEqual([]);
});
- it("opens a bot's new tab behind the one the person holds", async () => {
- const { main, service, call } = setup({ quietMs: 0 });
+ it("opens a bot's new tab behind the one the person holds, and says so", async () => {
+ const { main, service, call, text } = 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" });
+ const held = run.browser.activePage!.targetId;
+ run.opened.personControl!.hold(held, true);
+ const opened = await call("agent_browser_open", { url: "https://example.com/b", tab: "new" });
+ expect(opened.isError, text(opened)).toBeUndefined();
expect(main.toMain.filter((message) => message.op === "create").map((message) => (message as { background?: boolean }).background)).toEqual([undefined, true]);
+ expect(main.commands.some((command) => command.tab === "p2" && command.method === "Page.navigate")).toBe(true);
+ const listed = text(await call("agent_browser_tabs", { action: "new", url: "https://example.com/c" }));
+ expect(listed).toContain("behind the tab the person is using");
+ expect(listed).not.toContain("in front");
+ expect(text(await call("agent_browser_tabs", { action: "switch", tab: "t2" }))).toContain("stays behind it");
+ expect(main.toMain.filter((message) => message.op === "front").map((message) => (message as { tab: string }).tab).filter((tab) => tab !== "p1")).toEqual([]);
+ run.opened.personControl!.hold(held, false);
+ expect(text(await call("agent_browser_tabs", { action: "new" }))).toContain("It is in front");
});
});
diff --git a/server/browser/service.ts b/server/browser/service.ts
index fb628087d7..76de8fcb01 100644
--- a/server/browser/service.ts
+++ b/server/browser/service.ts
@@ -530,6 +530,7 @@ export class BrowserService {
secretOnPage: (tab) => this.#holds.refuses(profile.session, async () => tab.page.url(), tab.page.targetId),
saveScreenshot: (data, pageUrl) => this.#saveScreenshot(profile, data, pageUrl),
downloads: () => run.browser.downloads?.list() ?? [],
+ personHolds: () => run.opened.personControl?.holding() ?? false,
};
}
@@ -608,7 +609,10 @@ export class BrowserService {
if (!profile || !tab) throw new Error("the browser has no open page to picture");
if (profile.control.agents > 0 || this.#lanes.held(profile.key)) throw new Error("The browser is busy with an agent action.");
if (profile.control.owner !== null) throw new Error("a person holds the browser");
+ // A page under a dialog answers no screencast pause or capture, and the bot's next call would wait behind this one.
+ if (tab.page.dialogs.pending) throw new Error("a dialog is open on the page");
return profile.control.agent(tab, async () => {
+ if (tab.page.dialogs.pending) throw new Error("a dialog is open on the page");
if (await tab.page.secrets.present(tab.page.frames)) throw new Error("a filled secret is on the page");
const shot = await profile.hub.paused(tab, () => tab.page.screenshot({ format: "jpeg", quality: 80 }));
return { png: shot.data.toString("base64"), format: "jpeg" as const };
@@ -694,6 +698,19 @@ export class BrowserService {
return this.#bySession(session)?.hub.answerFileChooser(owner, chooserId, paths) ?? Promise.resolve(false);
}
+ /**
+ * The person takes `tab` of this session's desktop pane from the bot, or hands it back. It is named, since the bot's
+ * active tab can be one opened behind the person's. The tab held, or null where there is no such pane tab.
+ */
+ holdTab(session: string, tab: string, held: boolean): string | null {
+ const profile = this.#bySession(session);
+ const control = profile?.run?.opened.personControl;
+ const chosen = profile?.tabs.get(tab);
+ if (!control || !chosen) return null;
+ control.hold(chosen.page.targetId, held);
+ return chosen.id;
+ }
+
/** A file this session's browser finished downloading. */
download(session: string, id: string): Download | undefined {
const download = this.#bySession(session)?.run?.browser.downloads?.list().find((candidate) => candidate.id === id);
diff --git a/server/browser/viewers/core.ts b/server/browser/viewers/core.ts
index e60007fb02..e7160ab7d3 100644
--- a/server/browser/viewers/core.ts
+++ b/server/browser/viewers/core.ts
@@ -24,7 +24,7 @@ import type { HoldLimits } from "../hold.ts";
import type { Tab } from "../tabs.ts";
import { ACCEPT_OF, chooseOption, cursorAt, editableAt, selectAt, type SelectPopup } from "./popups.ts";
import { DrawnView, type FrameMetadata } from "./drawn-view.ts";
-import { ViewerHold } from "./hold.ts";
+import { ViewerHold } from "./hold.ts"; import { covered } from "./cover.ts";
import { fitsScreen, MIN_WINDOW_WIDTH, requestedSize, VIEWPORT_PRESETS, viewportFor, ZOOM_LIMITS, zoomedLayout, type ViewportSetting } from "./viewport.ts";
/** Chromium keeps three frames unacknowledged, so acking 100 ms after arrival caps a viewer near 30 fps. */
@@ -533,7 +533,7 @@ export class ViewerHub {
await this.host.running();
if (viewer.closed) return viewer;
await this.#hold.carryOn(viewer);
- await viewer.hide(this.#hold.hides(viewer));
+ await viewer.hide(this.#hold.hides(viewer) || covered(viewer));
void this.#resizeForViewers().catch(() => undefined);
viewer.push(this.controlFor(viewer));
viewer.push({ type: "viewport", ...(this.#shown ?? { ...zoomedLayout(this.viewport(), this.zoom), zoom: this.zoom }), setting: this.setting });
@@ -589,7 +589,7 @@ export class ViewerHub {
broadcastControl(): void {
for (const viewer of this.viewers) {
- void viewer.hide(this.#hold.hides(viewer));
+ void viewer.hide(this.#hold.hides(viewer) || covered(viewer));
viewer.push(this.controlFor(viewer));
}
void this.offerFileChooser();
diff --git a/server/browser/viewers/cover.test.ts b/server/browser/viewers/cover.test.ts
new file mode 100644
index 0000000000..1b53b03306
--- /dev/null
+++ b/server/browser/viewers/cover.test.ts
@@ -0,0 +1,94 @@
+import { mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, afterEach, describe, expect, it } from "vitest";
+
+import { removeTempDir } from "../../testing/cleanup.ts";
+import { BrowserService } from "../service.ts";
+import { FakeBackend, FakeChrome } from "../testing/fake-chrome.ts";
+import type { ViewerOutput } from "./core.ts";
+import { coverView, covered } from "./cover.ts";
+
+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); });
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+async function setup() {
+ const dataDir = mkdtempSync(join(tmpdir(), "omb-cover-"));
+ folders.push(dataDir);
+ const backend = new FakeBackend(() => new FakeChrome({ documents: () => ({ title: "Page", text: "hello", elements: [] }) }));
+ 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" };
+ await service.agentRpc(target, "tools/call", { name: "agent_browser_open", arguments: { url: "https://example.com/" } });
+ const watch = async (owner = "local-owner") => {
+ const outputs: ViewerOutput[] = [];
+ const viewer = await service.attachViewer(target, { owner, canOperate: true, maxWidth: 1280, maxHeight: 800 }, (output) => {
+ outputs.push(output);
+ if (output.type === "frame") output.ack();
+ });
+ return { viewer, outputs };
+ };
+ const sent = (method: string) => backend.chrome.sent.filter((command) => command.method === method).length;
+ return { service, watch, sent, backend };
+}
+
+describe("a view the desktop app covers with its native view", () => {
+ it("runs no screencast and takes no stills while covered, and starts again with a still once uncovered", async () => {
+ const { watch, sent, service } = await setup();
+ const { viewer } = await watch();
+ await sleep(20);
+ const stops = sent("Page.stopScreencast");
+ await coverView(viewer, true, false);
+ expect(covered(viewer)).toBe(true);
+ expect(sent("Page.stopScreencast")).toBe(stops + 1);
+ const starts = sent("Page.startScreencast");
+ const stills = sent("Page.captureScreenshot");
+ // Control changes, page changes and the bot's own work do not bring the frames back.
+ await viewer.input({ type: "resize", width: 1100, height: 700 });
+ await service.agentRpc({ session: "bot-a", key: "bot:a" }, "tools/call", { name: "agent_browser_navigate", arguments: { url: "https://example.com/next" } });
+ await viewer.pushStill();
+ await sleep(300);
+ expect(sent("Page.startScreencast")).toBe(starts);
+ expect(sent("Page.captureScreenshot")).toBe(stills);
+ await coverView(viewer, false, false);
+ expect(sent("Page.startScreencast")).toBeGreaterThan(starts);
+ expect(sent("Page.captureScreenshot")).toBeGreaterThan(stills);
+ });
+
+ it("takes a turn's preview picture without restarting a covered view's screencast", async () => {
+ const { watch, sent, service } = await setup();
+ const { viewer } = await watch();
+ await coverView(viewer, true, false);
+ const starts = sent("Page.startScreencast");
+ const shots = sent("Page.captureScreenshot");
+ // The chat's preview of a bot's turn, every few seconds while it runs.
+ await service.previewFrame("bot-a");
+ await service.previewFrame("bot-a");
+ await sleep(20);
+ expect(sent("Page.captureScreenshot")).toBe(shots + 2);
+ expect(sent("Page.startScreencast")).toBe(starts);
+ });
+
+ it("stays hidden while another person holds the browser, though the app's view hides", async () => {
+ const { watch, sent } = await setup();
+ const { viewer } = await watch();
+ await coverView(viewer, true, false);
+ const starts = sent("Page.startScreencast");
+ await coverView(viewer, false, true);
+ expect(sent("Page.startScreencast")).toBe(starts);
+ });
+
+ it("leaves another device's view its own frames", async () => {
+ const { watch, sent } = await setup();
+ const { viewer } = await watch();
+ await coverView(viewer, true, false);
+ const starts = sent("Page.startScreencast");
+ const phone = await watch("phone-session");
+ await sleep(20);
+ expect(sent("Page.startScreencast")).toBe(starts + 1);
+ expect(covered(phone.viewer)).toBe(false);
+ });
+});
diff --git a/server/browser/viewers/cover.ts b/server/browser/viewers/cover.ts
new file mode 100644
index 0000000000..5fa481e510
--- /dev/null
+++ b/server/browser/viewers/cover.ts
@@ -0,0 +1,21 @@
+// Views the desktop app covers with its own native view of the same browser. The person sees the page itself there, so
+// such a view takes no frames, neither a screencast nor stills, until the native view hides again (an overlay, the
+// panel's dialog card, the app window closing). Every other view of the browser, a phone's or another device's, runs
+// its own screencast and is not affected.
+
+const coveredViews = new WeakSet<object>();
+
+/** Whether the desktop app shows its native view over this one. */
+export function covered(viewer: object): boolean {
+ return coveredViews.has(viewer);
+}
+
+/**
+ * The desktop app showed (`on`) or hid its native view over `viewer`. `heldElsewhere` says whether another person's
+ * hold hides the view anyway; the view hides for either reason and shows again, with a still, once neither applies.
+ */
+export function coverView(viewer: { hide(hidden: boolean): Promise<void> }, on: boolean, heldElsewhere: boolean): Promise<void> {
+ if (on) coveredViews.add(viewer);
+ else coveredViews.delete(viewer);
+ return viewer.hide(on || heldElsewhere);
+}
diff --git a/server/browser/viewers/stream-v2.ts b/server/browser/viewers/stream-v2.ts
index 148152a8b8..8831febf21 100644
--- a/server/browser/viewers/stream-v2.ts
+++ b/server/browser/viewers/stream-v2.ts
@@ -15,6 +15,7 @@ import { hostSetupOf } from "../chrome/host-setup.ts";
import { browserInputLog } from "../input-log.ts";
import type { BrowserService, BrowserTarget } from "../service.ts";
import { FRAME_CAP_LIMITS, type Viewer, type ViewerOptions, type ViewerOutput } from "./core.ts";
+import { coverView } from "./cover.ts";
import { requestedSize } from "./viewport.ts";
import { displayUrl } from "./live-v1.ts";
@@ -109,6 +110,8 @@ class StreamSession {
closing = false;
#early: unknown[] = [];
#restarting = false;
+ /** Another person's hold hides this view, as its last control message said. */
+ #heldElsewhere = false;
constructor(request: StreamRequest, ws: WebSocket) {
this.request = request;
@@ -144,6 +147,7 @@ class StreamSession {
this.close(STREAM_CLOSE.reconnect, "reconnect", { dropped: true });
return;
}
+ if (output.type === "control") this.#heldElsewhere = output.held && !output.owned;
const message = wireMessage(output);
if (!message) return;
const text = JSON.stringify(message);
@@ -190,10 +194,16 @@ class StreamSession {
}
#input(message: unknown, service: BrowserService): void {
- if ((message as { type?: unknown } | null)?.type === "restart") {
+ const type = (message as { type?: unknown } | null)?.type;
+ if (type === "restart") {
void this.#restart(service);
return;
}
+ // The desktop app shows its native view of this browser over the panel, or hides it again.
+ if (type === "covered") {
+ if (this.viewer) void coverView(this.viewer, (message as { covered?: unknown }).covered === true, this.#heldElsewhere).catch(() => undefined);
+ return;
+ }
void this.viewer?.input(message);
}
@@ -324,7 +334,11 @@ export class StreamV2 {
closeForSession(session: string): void { this.#closeWhere((request) => request.target.session === session); }
closeForOwner(owner: string): void { this.#closeWhere((request) => request.owner === owner); }
closeForBot(botId: string): void { this.#closeWhere((request) => request.botId === botId); }
- closeAll(): void { this.#closeWhere(() => true); }
+ /** Every view closes: for good, or, as the server stops (`stopping`), with the close that has panels reconnect. */
+ closeAll({ stopping = false }: { stopping?: boolean } = {}): void {
+ if (!stopping) return this.#closeWhere(() => true);
+ for (const session of this.#sessions) session.close(STREAM_CLOSE.reconnect, "The server is restarting.");
+ }
/** Closes now every view the 5 s recheck would close. */
recheck(): void { for (const session of this.#sessions) if (!session.request.isCurrent()) session.close(STREAM_CLOSE.gone, GONE); }
diff --git a/server/host/browser.ts b/server/host/browser.ts
index 89996845b4..d83f2407d5 100644
--- a/server/host/browser.ts
+++ b/server/host/browser.ts
@@ -50,7 +50,7 @@ import { CHROME_BROWSER_SYSTEM_PROMPT } from "../browser/prompt.ts";
import { PaneBackend } from "../browser/pane/backend.ts";
import { desktopPaneLink } from "../browser/pane/link.ts";
import { cookieRequests } from "../browser/cookies/requests.ts";
-import { systemFiles, systemKeyStore } from "../browser/cookies/sources.ts";
+import { keyStoreFor, systemFiles } from "../browser/cookies/sources.ts";
import { sweep as sweepCookieCopies } from "../browser/cookies/snapshot.ts";
import { passkeyAnnotation } from "../browser/passkey-notice.ts";
import { LentChromeDoors, lentChromeGuidance, type ChromeLender } from "../browser/lent-chrome.ts";
@@ -463,7 +463,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {
if (paneLink) void sweepCookieCopies(cookieScratch);
paneLink?.answerCookieRequests(cookieRequests({
files: systemFiles,
- keys: () => systemKeyStore(process.env),
+ keys: () => keyStoreFor(process.env),
scratch: cookieScratch,
destination: (botId, threadId) => {
const bot = store.bot(botId);
diff --git a/server/index.ts b/server/index.ts
index c6b91e8738..3fdaa3b787 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -15237,7 +15237,7 @@ const gracefulShutdown = createGracefulShutdown({
sharedComputers.close(); deviceLinks.close(); stopCloudTeamPolicy(); stopCloudTeamRoster();
phones.close();
sharedComputerControl.close();
- browserLive.closeAll();
+ browserLive.closeAll({ stopping: true });
desktopViewer.closeAll();
upgrades.close();
for (const idle of localVmIdles.values()) idle.cancel();
diff --git a/server/routes/browser-viewers.test.ts b/server/routes/browser-viewers.test.ts
index 8e4b7df0a2..b0df6011d1 100644
--- a/server/routes/browser-viewers.test.ts
+++ b/server/routes/browser-viewers.test.ts
@@ -77,11 +77,13 @@ afterEach(async () => {
for (const folder of folders.splice(0)) await removeTempDir(folder);
});
-async function serve({ attach, current = () => true, download, audience = () => "team", action = async () => ({ ok: true }), inputLog, desktopView = true }: {
+async function serve({ attach, current = () => true, download, audience = () => "team", action = async () => ({ ok: true }), inputLog, desktopView = true, hold = () => null, authorize = async () => null }: {
desktopView?: boolean;
attach?: (options: ViewerOptions, push: (output: ViewerOutput) => void) => Promise<Viewer>;
current?: () => boolean;
download?: (id: string) => Download | undefined;
+ hold?: (tab: string, held: boolean) => string | null;
+ authorize?: BrowserViewerRouteDeps["authorize"];
audience?: (threadId: string | null) => Audience | null;
action?: (body: unknown) => Promise<unknown>;
inputLog?: BrowserInputLog;
@@ -133,13 +135,14 @@ async function serve({ attach, current = () => true, download, audience = () =>
return chooser === "chooser-1";
},
download: (_browser, id) => download?.(id),
+ hold: (_browser, tab, held) => hold(tab, held),
},
audience: (_auth, threadId) => audience(threadId),
browser: async (botId, opened) => {
fixture.opened.push(opened);
return botId === "pepper" ? { botId, session: "bot-pepper", spec: { command: "omb-cdp", args: ["bot:pepper"], env: {} } } : { status: 404, error: "no such bot" };
},
- authorize: async () => null,
+ authorize,
current: (_botId, _session, _auth, checked) => { fixture.checked.push(checked); return current(); },
restartRefusal: () => null,
...(inputLog ? { inputLog } : {}),
@@ -243,6 +246,39 @@ describe("the v2 stream", () => {
socket.close();
});
+ it("pauses a view the desktop app covers with its native view, unless another person's hold already hides it", async () => {
+ const hides: boolean[] = [];
+ const fixture = await serve({
+ attach: async (_options, push) => {
+ push({ type: "control", canOperate: true, controller: "unclaimed", held: false, owned: false, controlling: false, stale: false, generation: 1, dialog: null });
+ return { id: "viewer", input: async (message: unknown) => { fixture.inputs.push(message); }, hide: async (hidden: boolean) => { hides.push(hidden); }, close: async () => {} } as unknown as Viewer;
+ },
+ });
+ const socket = new WebSocket(`ws://${fixture.origin}/api/bots/pepper/browser/stream`);
+ await new Promise((resolve) => socket.addEventListener("message", resolve, { once: true }));
+ socket.send(JSON.stringify({ type: "covered", covered: true }));
+ socket.send(JSON.stringify({ type: "covered", covered: false }));
+ await until(() => hides.length === 2);
+ socket.close();
+ expect(hides).toEqual([true, false]);
+ // The covered message is the stream's own: it never reaches the page as input.
+ expect(fixture.inputs).toEqual([]);
+ });
+
+ it("closes every view for good when told to, and with a reconnect as the server stops", async () => {
+ const closes: number[] = [];
+ for (const stopping of [false, true]) {
+ const fixture = await serve();
+ const socket = new WebSocket(`ws://${fixture.origin}/api/bots/pepper/browser/stream`);
+ await new Promise((resolve) => socket.addEventListener("open", resolve, { once: true }));
+ await until(() => fixture.attachments.length === 1);
+ const closed = new Promise<number>((resolve) => socket.addEventListener("close", (event) => resolve(event.code)));
+ fixture.stream.closeAll({ stopping });
+ closes.push(await closed);
+ }
+ expect(closes).toEqual([4404, 1012]);
+ });
+
it("refuses an upgrade from another origin, and a plain request, before attaching a viewer", async () => {
const fixture = await serve();
const refused = await new Promise<number>((resolve) => {
@@ -559,3 +595,40 @@ describe("the desktop view", () => {
expect(fixture.desktops).toEqual([]);
});
});
+
+describe("the person's hold on a desktop pane tab", () => {
+ const post = (fixture: Fixture, body: unknown, path = "/api/bots/pepper/browser/hold") =>
+ fetch(`http://${fixture.origin}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
+
+ it("takes the tab named, and hands it back", async () => {
+ const holds: Array<[string, boolean]> = [];
+ const fixture = await serve({ hold: (tab, held) => { holds.push([tab, held]); return tab; } });
+ const taken = await post(fixture, { held: true, tab: "t1" });
+ expect(taken.status).toBe(200);
+ expect(await taken.json()).toEqual({ tab: "t1", held: true });
+ expect((await post(fixture, { held: false, tab: "t2" })).status).toBe(200);
+ expect(holds).toEqual([["t1", true], ["t2", false]]);
+ });
+
+ it("is checked as a view of the browser is: who may see it, a fresh sign-in, the browser still current", async () => {
+ const holds: unknown[] = [];
+ const hold = (tab: string) => { holds.push(tab); return tab; };
+ const body = { held: true, tab: "t1" };
+ expect((await post(await serve({ hold, audience: () => null }), body)).status).toBe(404);
+ expect((await post(await serve({ hold, authorize: async () => ({ status: 403, error: "Sign in again." }) }), body)).status).toBe(403);
+ expect((await post(await serve({ hold, current: () => false }), body)).status).toBe(409);
+ expect((await post(await serve({ hold }), body, "/api/bots/other/browser/hold")).status).toBe(404);
+ expect(holds).toEqual([]);
+ });
+
+ it("refuses a malformed request, and a browser that is not a desktop pane", async () => {
+ const fixture = await serve();
+ expect((await post(fixture, { held: "yes", tab: "t1" })).status).toBe(400);
+ expect((await post(fixture, { held: true, tab: "p1" })).status).toBe(400);
+ expect((await post(fixture, { held: true })).status).toBe(400);
+ expect((await fetch(`http://${fixture.origin}/api/bots/pepper/browser/hold`)).status).toBe(405);
+ const refused = await post(fixture, { held: true, tab: "t1" });
+ expect(refused.status).toBe(409);
+ expect((await refused.json() as { error: string }).error).toContain("desktop app");
+ });
+});
diff --git a/server/routes/browser-viewers.ts b/server/routes/browser-viewers.ts
index b08542311b..c72cdb7175 100644
--- a/server/routes/browser-viewers.ts
+++ b/server/routes/browser-viewers.ts
@@ -2,8 +2,9 @@
// phone apps speak, and its contract is frozen. v2 (GET …/browser/stream, a WebSocket) is the desktop panel's and the
// web UI's, on the new engine only: a page's file picker is answered by POST …/browser/upload and a finished download
// is fetched from GET …/browser/download/:id. GET …/browser/desktop (a WebSocket) is the remote-desktop view of a browser
-// whose window is on a private display, beside the v2 stream. Never mix login frames into the general events feed, which
-// every device reads.
+// whose window is on a private display, beside the v2 stream. In the desktop app, POST …/browser/hold takes a pane tab,
+// named by its id, from the bot or hands it back. Never mix login frames into the general events feed, which every device
+// reads.
import { createReadStream, rmSync } from "node:fs";
import type { IncomingMessage } from "node:http";
import { dirname, join } from "node:path";
@@ -25,6 +26,8 @@ const LIVE = /^\/api\/bots\/([\w-]+)\/browser\/(live|action)$/;
const STREAM = /^\/api\/bots\/([\w-]+)\/browser\/(stream|desktop)$/;
const UPLOAD = /^\/api\/bots\/([\w-]+)\/browser\/upload$/;
const DOWNLOAD = /^\/api\/bots\/([\w-]+)\/browser\/download\/([\w-]{1,64})$/;
+const HOLD = /^\/api\/bots\/([\w-]+)\/browser\/hold$/;
+const TAB_ID = /^t\d{1,9}$/;
const CHOOSER = /^[\w-]{1,64}$/;
const UPLOAD_MAX_FILES = 20;
const PICKER_CLOSED = "The page's file picker is no longer open.";
@@ -34,7 +37,7 @@ type Failure = { status: number; error: string };
export interface BrowserViewerRouteDeps {
upgrades: Upgrades;
- viewers: Pick<LiveRouter, "open" | "action" | "stream" | "desktop" | "fileChooserOffered" | "answerFileChooser" | "download">;
+ viewers: Pick<LiveRouter, "open" | "action" | "stream" | "desktop" | "fileChooserOffered" | "answerFileChooser" | "download"> & Partial<Pick<LiveRouter, "hold">>;
/** Who is watching, as a hold of the browser knows them: every view and device of one person shares their hold. */
person(auth: RequestAuth): string;
/** Whose browser of the bot this person's view shows (`threadId` names the conversation they look at); null when
@@ -115,7 +118,8 @@ export function createBrowserViewerRoutes(deps: BrowserViewerRouteDeps): RouteHa
const stream = live ? null : STREAM.exec(path);
const upload = live || stream ? null : UPLOAD.exec(path);
const download = live || stream || upload ? null : DOWNLOAD.exec(path);
- const botId = (live ?? stream ?? upload ?? download)?.[1];
+ const hold = live || stream || upload || download ? null : HOLD.exec(path);
+ const botId = (live ?? stream ?? upload ?? download ?? hold)?.[1];
if (!botId) return PASS;
res.setHeader("cache-control", "no-store");
const pending = stream ? deps.upgrades.pending(req) : undefined;
@@ -198,6 +202,16 @@ export function createBrowserViewerRoutes(deps: BrowserViewerRouteDeps): RouteHa
return;
}
+ if (hold) {
+ if (method !== "POST") return json(res, 405, { error: "method not allowed" });
+ const body = await readBody(req, 1_024);
+ if (typeof body?.held !== "boolean" || typeof body.tab !== "string" || !TAB_ID.test(body.tab)) return json(res, 400, { error: "Pass held and the tab, as t1." });
+ if (!isCurrent()) return json(res, 409, { error: "This browser session changed. Reopen the browser panel." });
+ const tab = deps.viewers.hold?.(browser, body.tab, body.held) ?? null;
+ if (!tab) return json(res, 409, { error: "Only a browser shown in the desktop app's panel can be held." });
+ return json(res, 200, { tab, held: body.held });
+ }
+
if (upload) {
if (method !== "POST") return json(res, 405, { error: "method not allowed" });
const chooser = url.searchParams.get("chooser") ?? "";
diff --git a/src/components/BrowserPanel.pane.dom.test.ts b/src/components/BrowserPanel.pane.dom.test.ts
index 20e3def4c5..44a40e3383 100644
--- a/src/components/BrowserPanel.pane.dom.test.ts
+++ b/src/components/BrowserPanel.pane.dom.test.ts
@@ -1,7 +1,7 @@
// @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 { act, 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";
@@ -14,11 +14,17 @@ vi.mock("@/state/store", async (importOriginal) => {
});
vi.mock("@/lib/page-visible", () => ({ usePageVisible: () => true }));
vi.mock("@/lib/browser-pip", () => ({ supportsBrowserPictureInPicture: () => false, useBrowserPictureInPicture: () => "" }));
+const streamed = vi.hoisted(() => [] as unknown[]);
+const surface = vi.hoisted(() => ({ props: null as null | { onConnectedChange(next: boolean): void; onMessage?(message: Record<string, unknown>): void } }));
vi.mock("./browser/StreamSurface", async () => {
const { useEffect } = await import("react");
return {
- StreamSurface: (props: { onConnectedChange(next: boolean): void }) => {
- useEffect(() => { props.onConnectedChange(true); }, []);
+ StreamSurface: (props: { onConnectedChange(next: boolean): void; onClient?(client: unknown): void; onMessage?(message: Record<string, unknown>): void }) => {
+ surface.props = props;
+ useEffect(() => {
+ props.onClient?.({ send: (message: unknown) => { streamed.push(message); return true; }, stop: () => {} });
+ props.onConnectedChange(true);
+ }, []);
return null;
},
};
@@ -89,4 +95,49 @@ describe("the browser panel's native pane", () => {
expect(show.mock.calls.at(-1)?.[0]).toEqual({ botId: "scout", threadId: null, profile: null, bounds: null, visible: false });
root = createRoot(host);
});
+
+ it("stops the stream's frames while the app shows the pane, and has them again once it hides", async () => {
+ engine.pane = true;
+ streamed.length = 0;
+ flushSync(() => root.render(createElement(LiveBrowser, { bot })));
+ await settle();
+ const covers = () => streamed.filter((message) => (message as { type?: string }).type === "covered").map((message) => (message as { covered: boolean }).covered);
+ await vi.waitFor(() => expect(covers().at(-1)).toBe(true));
+ const overlay = document.createElement("div");
+ overlay.setAttribute("role", "menu");
+ overlay.style.opacity = "1";
+ document.body.append(overlay);
+ await vi.waitFor(() => expect(covers().at(-1)).toBe(false));
+ overlay.remove();
+ await vi.waitFor(() => expect(covers().at(-1)).toBe(true));
+ });
+
+ it("keeps the frames where the app did not show the pane", async () => {
+ engine.pane = true;
+ streamed.length = 0;
+ show.mockImplementation(async () => ({ shown: false }));
+ flushSync(() => root.render(createElement(LiveBrowser, { bot })));
+ await settle();
+ expect(streamed.some((message) => (message as { type?: string; covered?: boolean }).type === "covered" && (message as { covered: boolean }).covered)).toBe(false);
+ });
+
+ it("shows the pane again by itself after its server restarts and the stream reconnects", async () => {
+ engine.pane = true;
+ flushSync(() => root.render(createElement(LiveBrowser, { bot })));
+ await settle();
+ expect(show.mock.calls.at(-1)?.[0]).toMatchObject({ visible: true });
+ // The server restarts: the stream drops and reconnects, the new server says its browser is starting, and the
+ // covered view draws no frame; then the browser lists its tab.
+ await act(async () => surface.props!.onConnectedChange(false));
+ await settle();
+ expect(show.mock.calls.at(-1)?.[0]).toMatchObject({ visible: false });
+ await act(async () => { surface.props!.onConnectedChange(true); surface.props!.onMessage?.({ type: "starting" }); });
+ await settle();
+ expect(show.mock.calls.at(-1)?.[0]).toMatchObject({ visible: false });
+ const asked = show.mock.calls.length;
+ await act(async () => surface.props!.onMessage?.({ type: "tabs", tabs: [{ tabId: "t1", title: "", url: "about:blank", active: true }] }));
+ await settle();
+ expect(show.mock.calls.length).toBeGreaterThan(asked);
+ expect(show.mock.calls.at(-1)?.[0]).toMatchObject({ visible: true });
+ });
});
diff --git a/src/components/BrowserPanel.test.ts b/src/components/BrowserPanel.test.ts
index 6dd4f03756..49eb21890b 100644
--- a/src/components/BrowserPanel.test.ts
+++ b/src/components/BrowserPanel.test.ts
@@ -130,6 +130,24 @@ describe("the browser panel's connection", () => {
expect(host.querySelector("[data-browser-transport]")!.getAttribute("data-browser-transport")).toBe("live");
});
+ it("reconnects by itself, on the stream, when its server restarts, and shows no Reconnect", async () => {
+ const socket = await streaming();
+ const before = FakeSocket.instances.length;
+ // The server stops: it closes the view with the reconnect code, then refuses while it starts again.
+ await act(async () => socket.dispatchEvent(Object.assign(new Event("close"), { code: 1012, reason: "The server is restarting." })));
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 600)); });
+ expect(FakeSocket.instances.length).toBe(before + 1);
+ await act(async () => FakeSocket.instances.at(-1)!.refuse());
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 1_100)); });
+ const next = FakeSocket.instances.at(-1)!;
+ expect(next).not.toBe(socket);
+ expect(button("Reconnect")).toBeUndefined();
+ expect(host.querySelector("[data-browser-transport]")!.getAttribute("data-browser-transport")).toBe("stream");
+ await act(async () => { next.open(); next.control("agent"); next.message(new ArrayBuffer(8)); });
+ await flush();
+ expect(button("Reconnect")).toBeUndefined();
+ });
+
it("says the browser is starting until its first frame arrives", async () => {
await render();
const socket = FakeSocket.instances.at(-1)!;
diff --git a/src/components/BrowserPanel.tsx b/src/components/BrowserPanel.tsx
index 0221971879..861f913bc7 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 { followBounds } from "@/lib/follow-bounds";
import { useNativeViewObscured } from "@/lib/native-view-obscured";
import { CookieImportDialog, cookieImportAvailable, siteOfAddress } from "./browser/CookieImportDialog";
@@ -318,33 +319,45 @@ export function LiveBrowser({ bot, signIn, page }: { bot: Bot; signIn?: BrowserS
const profile = state.config?.browserProfiles?.find((candidate) => candidate.id === bot.browserProfile);
const importable = cookieImportAvailable(state.config) && bot.browserProfile !== "guest"
&& !(profile?.browser === "chrome" && state.config?.browserEngine?.myChrome === true);
- const paneVisible = paneMode && shown && connected && !asleep && !heldElsewhere && !gone && !starting && !obscured;
+ // A page's alert, confirm or prompt is answered in the panel's own card, under where the native pane would be.
+ const paneVisible = paneMode && shown && connected && !asleep && !heldElsewhere && !gone && !starting && !obscured && !control?.dialog;
const paneShown = useRef(paneVisible);
const placePane = useRef<() => void>(() => {});
+ // While the app shows the pane, the stream underneath sends no frames; it resumes as soon as the pane hides.
+ const [paneUp, setPaneUp] = useState(false);
+ const covered = paneVisible && paneUp;
+ const coveredSent = useRef(false);
+ useEffect(() => {
+ if (!stream || (!covered && !coveredSent.current)) return;
+ clientRef.current?.send({ type: "covered", covered });
+ coveredSent.current = covered;
+ }, [stream, covered, connected]);
paneShown.current = paneVisible;
useEffect(() => {
const bridge = window.ogb?.browserPane;
if (!paneMode || !bridge) return;
const threadId = scopedThread ?? null;
const profile = bot.browserProfile ?? null;
+ let placed = 0;
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);
+ const visible = paneShown.current && bounds !== null;
+ const asked = ++placed;
+ void bridge.show({ botId: bot.id, threadId, profile, bounds, visible }).then((answer) => { if (asked === placed) setPaneUp(visible && answer?.shown === true); }, () => { if (asked === placed) setPaneUp(false); });
};
placePane.current = place;
- const observer = new ResizeObserver(place);
- if (pageArea.current) observer.observe(pageArea.current);
- window.addEventListener("resize", place);
+ const stop = pageArea.current ? followBounds(pageArea.current, place) : () => {};
return () => {
placePane.current = () => {};
- observer.disconnect();
- window.removeEventListener("resize", place);
+ stop();
+ setPaneUp(false);
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]);
+ // A pane the app makes after the panel asked (as after a server restart) is shown once its tab is listed.
+ useEffect(() => { placePane.current(); }, [paneVisible, paneMode, bot.id, bot.browserProfile, scopedThread, tabs]);
const pipSupported = stream && supportsBrowserPictureInPicture();
const passkeyWall = passkeyWallAt(nav.url);
return <div ref={panel} className={maximized
diff --git a/src/lib/browser-stream-client.test.ts b/src/lib/browser-stream-client.test.ts
index 16f8f6d435..3e5eb9e1bb 100644
--- a/src/lib/browser-stream-client.test.ts
+++ b/src/lib/browser-stream-client.test.ts
@@ -221,6 +221,94 @@ describe("preview stream downloads, uploads and messages", () => {
expect(onUnauthorized).toHaveBeenCalledOnce();
});
+ it("waits out its server restarting, refused before open for a while, then takes a lasting refusal as unauthorized", () => {
+ vi.useFakeTimers();
+ const onConnectedChange = vi.fn();
+ const onUnauthorized = vi.fn();
+ createPreviewStreamClient(target, events({ onConnectedChange, onUnauthorized }));
+ FakeSocket.current.closeWith(1006, "");
+ for (let attempt = 0; attempt < 3; attempt++) {
+ vi.advanceTimersByTime(10_000);
+ FakeSocket.current.closeWith(1006, "", false);
+ }
+ expect(onUnauthorized).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(10_000);
+ FakeSocket.current.dispatchEvent(new Event("open"));
+ expect(onConnectedChange.mock.calls).toEqual([[true], [false], [true]]);
+ // Connected again: a server that then keeps refusing is a refusal after its restart allowance.
+ FakeSocket.current.dispatchEvent(Object.assign(new Event("close"), { code: 1006, reason: "" }));
+ for (let attempt = 0; attempt < 8; attempt++) {
+ vi.advanceTimersByTime(10_000);
+ FakeSocket.current.closeWith(1006, "", false);
+ }
+ expect(onUnauthorized).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(10_000);
+ FakeSocket.current.closeWith(1006, "", false);
+ expect(onUnauthorized).toHaveBeenCalledOnce();
+ vi.useRealTimers();
+ });
+
+ it("reconnects by itself when a connected stream drops as its server restarts, however the socket closed", () => {
+ for (const code of [1012, 1006, 1001]) {
+ vi.useFakeTimers();
+ const onConnectedChange = vi.fn();
+ const onUnauthorized = vi.fn();
+ const onGone = vi.fn();
+ createPreviewStreamClient(target, events({ onConnectedChange, onUnauthorized, onGone }));
+ const first = FakeSocket.current;
+ first.control(agent);
+ first.closeWith(code, "");
+ // The server is down for a moment: its refusals before open are waited out.
+ for (let attempt = 0; attempt < 3; attempt++) {
+ vi.advanceTimersByTime(10_000);
+ FakeSocket.current.closeWith(1006, "", false);
+ }
+ vi.advanceTimersByTime(10_000);
+ expect(FakeSocket.current).not.toBe(first);
+ FakeSocket.current.dispatchEvent(new Event("open"));
+ expect(onConnectedChange.mock.calls).toEqual([[true], [false], [true]]);
+ expect(onUnauthorized).not.toHaveBeenCalled();
+ expect(onGone).not.toHaveBeenCalled();
+ vi.useRealTimers();
+ }
+ });
+
+ it("still stops at once on a real refusal after it was connected", () => {
+ for (const code of [1008, 4401]) {
+ vi.useFakeTimers();
+ const onUnauthorized = vi.fn();
+ createPreviewStreamClient(target, events({ onUnauthorized }));
+ const first = FakeSocket.current;
+ first.closeWith(code, "");
+ vi.advanceTimersByTime(20_000);
+ expect(FakeSocket.current).toBe(first);
+ expect(onUnauthorized).toHaveBeenCalledOnce();
+ vi.useRealTimers();
+ }
+ });
+
+ it("tells each new socket the app's native view covers it, as each is a new view on the server", () => {
+ vi.useFakeTimers();
+ const client = createPreviewStreamClient(target, events());
+ const first = FakeSocket.current;
+ first.control(agent);
+ expect(client.send({ type: "covered", covered: true })).toBe(true);
+ expect(first.sent).toContain(JSON.stringify({ type: "covered", covered: true }));
+ first.closeWith(1012, "reconnect");
+ vi.advanceTimersByTime(500);
+ const second = FakeSocket.current;
+ expect(second).not.toBe(first);
+ second.dispatchEvent(new Event("open"));
+ second.control(agent);
+ expect(second.sent).toContain(JSON.stringify({ type: "covered", covered: true }));
+ client.send({ type: "covered", covered: false });
+ second.closeWith(1012, "reconnect");
+ vi.advanceTimersByTime(1_000);
+ FakeSocket.current.control(agent);
+ expect(FakeSocket.current.sent.some((sent) => sent.includes("covered"))).toBe(false);
+ vi.useRealTimers();
+ });
+
it("reconnects after the browser restarted, with the newest size and frame cap the viewer asked for", () => {
vi.useFakeTimers();
const onConnectedChange = vi.fn();
diff --git a/src/lib/browser-stream-client.ts b/src/lib/browser-stream-client.ts
index 3a5deb63d4..8680230aaa 100644
--- a/src/lib/browser-stream-client.ts
+++ b/src/lib/browser-stream-client.ts
@@ -5,6 +5,9 @@
import { t } from "./i18n";
+/** Refusals before open a client that was connected takes as its server restarting: about 45 s with the backoff. */
+const RESTART_RETRIES = 8;
+
/** The browser's host cannot run Chrome until it is set up; the close reason names the fix. */
export const PREVIEW_STREAM_HOST_SETUP_CLOSE_CODE = 4503;
export const PREVIEW_STREAM_TAB_GONE_CODE = 4404;
@@ -109,6 +112,8 @@ export type PreviewStreamInput =
/** The installed extensions, for the Extensions menu; an extension's own page opens by its id only. */
| { readonly type: "extensions" }
| { readonly type: "openExtension"; readonly id: string }
+ /** The desktop app shows its native view of this browser over the panel: no frames are needed until it hides. */
+ | { readonly type: "covered"; readonly covered: boolean }
| {
readonly type: "mouse";
readonly action: "move" | "down" | "up";
@@ -282,7 +287,7 @@ export interface PreviewStreamClient {
/** A viewer that may operate sizes the page while it watches, and may restart or wake it; the person holding the browser
* hands it back from any of their views; everything else needs control. */
const allowed = (input: PreviewStreamInput, control: PreviewStreamControl): boolean =>
- input.type === "takeControl" || input.type === "resize" || input.type === "frameCap" || input.type === "restart" || input.type === "wake"
+ input.type === "takeControl" || input.type === "resize" || input.type === "frameCap" || input.type === "restart" || input.type === "wake" || input.type === "covered"
|| (input.type === "releaseControl" && control.owned === true) || control.controller === "you";
const ACK_MESSAGE = JSON.stringify({ type: "ack" });
@@ -292,6 +297,7 @@ export function createPreviewStreamClient(
): PreviewStreamClient {
let cap = { width: target.maxWidth, height: target.maxHeight };
let size = target.width !== undefined && target.height !== undefined ? { width: target.width, height: target.height } : null;
+ let covered = false;
const streamUrl = () => {
const query = new URLSearchParams({
maxWidth: String(Math.max(1, Math.round(cap.width))),
@@ -308,6 +314,9 @@ export function createPreviewStreamClient(
let socket: WebSocket | null = null;
let retryTimer: ReturnType<typeof setTimeout> | null = null;
let failures = 0;
+ /** A socket of this client opened once: a later refusal before open is the server restarting, for a while. */
+ let everOpened = false;
+ let unreachable = 0;
let control: PreviewStreamControl | null = null;
let fileChooser: string | null = null;
@@ -321,6 +330,8 @@ export function createPreviewStreamClient(
ws.addEventListener("open", () => {
if (socket !== ws) return;
opened = true;
+ everOpened = true;
+ unreachable = 0;
events.onConnectedChange(true);
});
ws.addEventListener("message", (event) => {
@@ -436,6 +447,8 @@ export function createPreviewStreamClient(
// A size or cap the viewer asked for while this socket was opening reaches the server now.
if (first && canOperate && cap !== opening.cap) ws.send(JSON.stringify({ type: "frameCap", maxWidth: cap.width, maxHeight: cap.height }));
if (first && canOperate && size && size !== opening.size) ws.send(JSON.stringify({ type: "resize", ...size }));
+ // Each socket is a new view on the server, which starts uncovered.
+ if (first && canOperate && covered) ws.send(JSON.stringify({ type: "covered", covered: true }));
events.onControl?.(nextControl);
} else if (typeof type === "string") {
events.onMessage?.(message as Record<string, unknown>);
@@ -458,8 +471,10 @@ export function createPreviewStreamClient(
events.onHostSetup?.(decodeHostSetup(event.reason));
return;
}
- // Rejected upgrades surface as 1006 before open for both cookies and tickets.
- if (event.code === 1008 || event.code === 4401 || (!opened && event.code === 1006)) {
+ // Rejected upgrades surface as 1006 before open for both cookies and tickets; so does a server that is restarting,
+ // which a client that was connected waits out before taking it as a refusal.
+ const restarting = !opened && event.code === 1006 && everOpened && ++unreachable <= RESTART_RETRIES;
+ if (event.code === 1008 || event.code === 4401 || (!opened && event.code === 1006 && !restarting)) {
stopped = true;
events.onUnauthorized();
return;
@@ -475,6 +490,7 @@ export function createPreviewStreamClient(
send: (input) => {
if (input.type === "resize") size = { width: input.width, height: input.height };
else if (input.type === "frameCap") cap = { width: input.maxWidth, height: input.maxHeight };
+ else if (input.type === "covered") covered = input.covered;
if (socket?.readyState !== WebSocket.OPEN) return false;
if (!control?.canOperate) return false;
if (!allowed(input, control)) return false;
diff --git a/src/lib/follow-bounds.dom.test.ts b/src/lib/follow-bounds.dom.test.ts
new file mode 100644
index 0000000000..2700ddde1c
--- /dev/null
+++ b/src/lib/follow-bounds.dom.test.ts
@@ -0,0 +1,61 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { followBounds } from "./follow-bounds";
+
+let box = { left: 300, top: 120, width: 900, height: 700 };
+let element: HTMLDivElement;
+let stop: () => void;
+const frames = async (count: number) => { for (let i = 0; i < count; i++) await new Promise((resolve) => requestAnimationFrame(() => resolve(undefined))); };
+
+beforeEach(() => {
+ box = { left: 300, top: 120, width: 900, height: 700 };
+ element = document.createElement("div");
+ document.body.append(element);
+ vi.spyOn(element, "getBoundingClientRect").mockImplementation(() => ({ ...box, right: box.left + box.width, bottom: box.top + box.height, x: box.left, y: box.top, toJSON: () => ({}) }) as DOMRect);
+});
+afterEach(() => {
+ stop?.();
+ element.remove();
+ vi.restoreAllMocks();
+});
+
+describe("following a box a native view sits over", () => {
+ it("follows every frame of a sidebar sliding, which moves the box without resizing it", async () => {
+ const seen: number[] = [];
+ stop = followBounds(element, () => seen.push(element.getBoundingClientRect().left));
+ document.body.dispatchEvent(new Event("transitionrun", { bubbles: true }));
+ for (const left of [280, 240, 180, 120, 80]) {
+ box = { ...box, left };
+ await frames(1);
+ }
+ document.body.dispatchEvent(new Event("transitionend", { bubbles: true }));
+ await frames(6);
+ expect(seen).toEqual([280, 240, 180, 120, 80]);
+ });
+
+ it("goes quiet once the box keeps still, and wakes on a page change", async () => {
+ const moved = vi.fn();
+ stop = followBounds(element, moved);
+ const raf = vi.spyOn(window, "requestAnimationFrame");
+ await frames(8);
+ raf.mockClear();
+ await new Promise((resolve) => setTimeout(resolve, 60));
+ expect(raf.mock.calls.length).toBe(0);
+ expect(moved).not.toHaveBeenCalled();
+ box = { ...box, top: 40 };
+ document.body.className = "maximized";
+ await frames(4);
+ expect(moved).toHaveBeenCalledTimes(1);
+ });
+
+ it("stops following when stopped", async () => {
+ const moved = vi.fn();
+ stop = followBounds(element, moved);
+ stop();
+ document.body.dispatchEvent(new Event("transitionrun", { bubbles: true }));
+ box = { ...box, left: 10 };
+ await frames(3);
+ expect(moved).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/lib/follow-bounds.ts b/src/lib/follow-bounds.ts
new file mode 100644
index 0000000000..190224cdee
--- /dev/null
+++ b/src/lib/follow-bounds.ts
@@ -0,0 +1,69 @@
+/** Frames a box must keep still before following it stops. */
+const SETTLE_FRAMES = 3;
+/** A transition or animation that never reports its end stops being followed after this long. */
+const MAX_FOLLOW_MS = 5_000;
+
+const STARTS = ["transitionrun", "transitionstart", "animationstart"] as const;
+const ENDS = ["transitionend", "transitioncancel", "animationend", "animationcancel"] as const;
+
+/**
+ * Calls `moved` whenever `element`'s box changes: on resize, scroll, a page change, and on every frame while a
+ * transition or animation runs anywhere on the page, since a sliding sidebar moves a box without resizing it. A native
+ * view placed over the box follows it this way. Returns the function that stops following.
+ */
+export function followBounds(element: HTMLElement, moved: () => void): () => void {
+ let frame = 0;
+ let last = "";
+ let still = 0;
+ let running = 0;
+ let runningUntil = 0;
+ const box = () => {
+ const rect = element.getBoundingClientRect();
+ return `${Math.round(rect.left)},${Math.round(rect.top)},${Math.round(rect.width)},${Math.round(rect.height)}`;
+ };
+ const tick = () => {
+ frame = 0;
+ const now = box();
+ if (now !== last) {
+ last = now;
+ still = 0;
+ moved();
+ } else {
+ still += 1;
+ }
+ if (running > 0 && performance.now() > runningUntil) running = 0;
+ if (running > 0 || still < SETTLE_FRAMES) frame = requestAnimationFrame(tick);
+ };
+ const watch = () => {
+ still = 0;
+ if (!frame) frame = requestAnimationFrame(tick);
+ };
+ const started = () => {
+ running += 1;
+ runningUntil = performance.now() + MAX_FOLLOW_MS;
+ watch();
+ };
+ const ended = () => {
+ running = Math.max(0, running - 1);
+ watch();
+ };
+ last = box();
+ const resizes = new ResizeObserver(watch);
+ resizes.observe(element);
+ resizes.observe(document.documentElement);
+ const changes = new MutationObserver(watch);
+ changes.observe(document.body, { subtree: true, childList: true, attributes: true, attributeFilter: ["class", "style", "hidden", "open"] });
+ for (const name of STARTS) document.addEventListener(name, started, true);
+ for (const name of ENDS) document.addEventListener(name, ended, true);
+ window.addEventListener("resize", watch);
+ window.addEventListener("scroll", watch, true);
+ return () => {
+ if (frame) cancelAnimationFrame(frame);
+ resizes.disconnect();
+ changes.disconnect();
+ for (const name of STARTS) document.removeEventListener(name, started, true);
+ for (const name of ENDS) document.removeEventListener(name, ended, true);
+ window.removeEventListener("resize", watch);
+ window.removeEventListener("scroll", watch, true);
+ };
+}
diff --git a/src/lib/local-vm-workspace.ts b/src/lib/local-vm-workspace.ts
index 916b1593c6..b4beb9ab88 100644
--- a/src/lib/local-vm-workspace.ts
+++ b/src/lib/local-vm-workspace.ts
@@ -50,6 +50,8 @@ export interface NativeViewOverlayCandidate {
explicit: boolean;
visible: boolean;
zIndex: number | null;
+ /** Whether the candidate paints above the host where they meet; undefined where the page cannot tell. */
+ above?: boolean;
}
/** Native views paint above renderer content, so hide them only under a visible overlay. */
@@ -65,6 +67,7 @@ export function nativeViewOverlayIntersects(
return candidates.some(
(candidate) =>
candidate.visible &&
+ candidate.above !== false &&
candidate.rect.width > 0 &&
candidate.rect.height > 0 &&
(candidate.explicit || (candidate.zIndex !== null && candidate.zIndex >= 10)) &&
diff --git a/src/lib/native-view-obscured.dom.test.ts b/src/lib/native-view-obscured.dom.test.ts
new file mode 100644
index 0000000000..f25ef3880c
--- /dev/null
+++ b/src/lib/native-view-obscured.dom.test.ts
@@ -0,0 +1,113 @@
+// @vitest-environment happy-dom
+import { createElement } from "react";
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { nativeViewOverlayIntersects } from "./local-vm-workspace";
+import { useNativeViewObscured } from "./native-view-obscured";
+
+const rect = (left: number, top: number, width: number, height: number) => ({ left, top, width, height, right: left + width, bottom: top + height, x: left, y: top, toJSON: () => ({}) }) as DOMRect;
+
+let root: Root;
+let mount: HTMLDivElement;
+let seen: boolean[];
+const boxes = new Map<Element, DOMRect>();
+let topmost: (x: number, y: number) => Element | null;
+
+function Probe() {
+ seen.push(useNativeViewObscured(false));
+ return null;
+}
+const settle = async () => { await act(async () => { for (let i = 0; i < 3; i++) await new Promise((resolve) => setTimeout(resolve, 20)); }); };
+
+beforeEach(() => {
+ seen = [];
+ boxes.clear();
+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) { return boxes.get(this) ?? rect(0, 0, 0, 0); });
+ topmost = () => null;
+ (document as unknown as { elementFromPoint: (x: number, y: number) => Element | null }).elementFromPoint = (x, y) => topmost(x, y);
+ mount = document.createElement("div");
+ document.body.append(mount);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ document.body.innerHTML = "";
+ vi.restoreAllMocks();
+});
+
+async function page(html: string) {
+ document.body.insertAdjacentHTML("afterbegin", html);
+ const host = document.querySelector("[data-native-view-host]")!;
+ boxes.set(host, rect(0, 80, 1280, 740));
+ root = createRoot(mount);
+ return host;
+}
+
+describe("what hides a native view", () => {
+ it("not the closed menus of the panel's own toolbar", async () => {
+ await page(`<div class="toolbar"><details><summary>Menu</summary><div class="absolute z-40" role="menu" style="opacity:1">items</div></details></div><div data-native-view-host></div>`);
+ const menu = document.querySelector('[role="menu"]') as HTMLElement;
+ boxes.set(menu, rect(1000, 60, 224, 300));
+ topmost = () => menu;
+ await act(async () => root.render(createElement(Probe)));
+ await settle();
+ expect(seen.at(-1)).toBe(false);
+ });
+
+ it("an open menu that paints over it", async () => {
+ await page(`<div data-native-view-host></div><div class="absolute z-40" role="menu" style="opacity:1">items</div>`);
+ const menu = document.querySelector('[role="menu"]') as HTMLElement;
+ boxes.set(menu, rect(1000, 60, 224, 300));
+ menu.checkVisibility = () => true;
+ topmost = (x, y) => (x >= 1000 && y <= 360 ? menu : document.querySelector("[data-native-view-host]"));
+ await act(async () => root.render(createElement(Probe)));
+ await settle();
+ expect(seen.at(-1)).toBe(true);
+ });
+
+ it("not the sidebar and the bars under a maximised panel", async () => {
+ await page(`<aside class="absolute z-20" style="opacity:1">sidebar</aside><div class="fixed inset-0 z-50"><div data-native-view-host><span id="page"></span></div></div>`);
+ const sidebar = document.querySelector("aside") as HTMLElement;
+ boxes.set(sidebar, rect(0, 28, 280, 792));
+ sidebar.checkVisibility = () => true;
+ topmost = () => document.getElementById("page");
+ await act(async () => root.render(createElement(Probe)));
+ await settle();
+ expect(seen.at(-1)).toBe(false);
+ });
+});
+
+describe("the Local VM view's rule", () => {
+ it("still hides under a visible explicit overlay, or a z-indexed one, where the page cannot hit-test", () => {
+ const host = rect(0, 0, 500, 500);
+ const over = rect(100, 100, 50, 50);
+ expect(nativeViewOverlayIntersects([host], [{ rect: over, explicit: true, visible: true, zIndex: null }])).toBe(true);
+ expect(nativeViewOverlayIntersects([host], [{ rect: over, explicit: false, visible: true, zIndex: 20 }])).toBe(true);
+ expect(nativeViewOverlayIntersects([host], [{ rect: over, explicit: true, visible: false, zIndex: null }])).toBe(false);
+ expect(nativeViewOverlayIntersects([host], [{ rect: over, explicit: true, visible: true, zIndex: null, above: false }])).toBe(false);
+ });
+});
+
+describe("where the page cannot hit-test", () => {
+ it("keeps the rectangle rule for an overlay that takes no pointer events, as a toast", async () => {
+ await page(`<div data-native-view-host></div><div class="fixed z-50" role="dialog" style="opacity:1; pointer-events:none">Saved</div>`);
+ const toast = document.querySelector('[role="dialog"]') as HTMLElement;
+ boxes.set(toast, rect(900, 700, 300, 60));
+ topmost = () => document.querySelector("[data-native-view-host]");
+ await act(async () => root.render(createElement(Probe)));
+ await settle();
+ expect(seen.at(-1)).toBe(true);
+ });
+
+ it("keeps the rectangle rule", async () => {
+ await page(`<div data-native-view-host></div><div class="absolute z-40" role="menu" style="opacity:1">items</div>`);
+ const menu = document.querySelector('[role="menu"]') as HTMLElement;
+ boxes.set(menu, rect(1000, 60, 224, 300));
+ menu.checkVisibility = () => true;
+ topmost = () => null;
+ await act(async () => root.render(createElement(Probe)));
+ await settle();
+ expect(seen.at(-1)).toBe(true);
+ });
+});
diff --git a/src/lib/native-view-obscured.ts b/src/lib/native-view-obscured.ts
index 92b73fd019..f21f666a06 100644
--- a/src/lib/native-view-obscured.ts
+++ b/src/lib/native-view-obscured.ts
@@ -11,9 +11,44 @@ const NATIVE_VIEW_OVERLAY_SELECTOR = [
".absolute",
].join(",");
+/** Rendered at all: a closed <details>' content, display:none, visibility:hidden or opacity 0 is not. */
+function rendered(candidate: HTMLElement, style: CSSStyleDeclaration): boolean {
+ const closed = candidate.closest("details:not([open])");
+ if (closed && !candidate.closest("summary")?.parentElement?.isSameNode(closed)) return false;
+ if (typeof candidate.checkVisibility === "function") return candidate.checkVisibility({ opacityProperty: true, visibilityProperty: true });
+ return style.display !== "none" && style.visibility !== "hidden" && Number(style.opacity) !== 0;
+}
+
+/**
+ * Whether `candidate` paints above the native view's host where their rectangles meet: the topmost element at a few
+ * points of the overlap is the candidate or inside it. A sidebar under a maximised panel meets its rectangle but paints
+ * below it. Undefined where the page cannot hit-test there: no point answered (off screen or without layout), or the
+ * candidate takes no pointer events, which hit-testing passes through though it paints.
+ */
+function paintsAbove(candidate: HTMLElement, style: CSSStyleDeclaration, rect: DOMRect, hosts: readonly DOMRect[]): boolean | undefined {
+ if (typeof document.elementFromPoint !== "function" || style.pointerEvents === "none") return undefined;
+ let tested = false;
+ for (const host of hosts) {
+ const left = Math.max(rect.left, host.left);
+ const right = Math.min(rect.right, host.right);
+ const top = Math.max(rect.top, host.top);
+ const bottom = Math.min(rect.bottom, host.bottom);
+ if (left >= right || top >= bottom) continue;
+ const inset = (from: number, to: number, at: number) => from + Math.min(Math.max(1, (to - from) * at), to - from - 0.5);
+ const points = [[0.5, 0.5], [0.1, 0.1], [0.9, 0.1], [0.1, 0.9], [0.9, 0.9]].map(([x, y]) => [inset(left, right, x!), inset(top, bottom, y!)] as const);
+ for (const [x, y] of points) {
+ const hit = document.elementFromPoint(x, y);
+ if (!hit) continue;
+ tested = true;
+ if (hit === candidate || candidate.contains(hit)) return true;
+ }
+ }
+ return tested ? false : undefined;
+}
+
/**
- * Electron's native views always paint above the renderer, so any intersecting overlay or popover counts, portals
- * included.
+ * Electron's native views always paint above the renderer, so an overlay or popover that paints above the view's host
+ * where they meet counts, portals included.
*/
function rendererOverlayIntersectsNativeView() {
const hosts = [...document.querySelectorAll<HTMLElement>("[data-native-view-host]")];
@@ -36,14 +71,15 @@ function rendererOverlayIntersectsNativeView() {
'[aria-modal="true"], [role="dialog"], [role="menu"], [popover], [data-native-view-overlay]',
);
const zIndex = Number.parseInt(style.zIndex, 10);
+ const rect = candidate.getBoundingClientRect();
+ const visible = rendered(candidate, style);
+ const above = visible ? paintsAbove(candidate, style, rect, hostRects) : false;
return {
- rect: candidate.getBoundingClientRect(),
+ rect,
explicit: explicitlyOverlay,
- visible:
- style.display !== "none" &&
- style.visibility !== "hidden" &&
- Number(style.opacity) !== 0,
+ visible,
zIndex: Number.isFinite(zIndex) ? zIndex : null,
+ ...(above === undefined ? {} : { above }),
};
});
return nativeViewOverlayIntersects(hostRects, candidates);
diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.ts
index 73acc9eb8d..bb1893f79f 100644
--- a/src/types/ogb.d.ts
+++ b/src/types/ogb.d.ts
@@ -457,6 +457,9 @@ const __APP_VERSION__: string;
* 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 }>;
+ /** The person takes the tab the panel shows from the bot (`held`), or hands it back; the bot may only read a
+ * held tab. Every hold ends when the window closes. */
+ hold(input: { botId: string; threadId: string | null; held: boolean }): Promise<{ held: boolean }>;
};
/** A site's sign-in from the person's own browsers into a bot's browser, which the person starts. Counts and a
* reason code come back, never a cookie. `offer` says whether a site can be imported for a bot (Google never). */