Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(browser): bound every CDP tool call, not just screenshots

liuzixiangc7dc831c1bb3
diff --git a/apps/desktop/electron/main/browser-host.ts b/apps/desktop/electron/main/browser-host.ts
index 268859db2..e31ba2f13 100644
--- a/apps/desktop/electron/main/browser-host.ts
+++ b/apps/desktop/electron/main/browser-host.ts
@@ -8,7 +8,7 @@ import { join } from "node:path";
export const BROWSER_PLUGIN_ID = "pi.browser";
export const BROWSER_VIEW_ID = "browser";
const BROWSER_REVEAL_TIMEOUT_MS = 5_000;
-const BROWSER_SCREENSHOT_TIMEOUT_MS = 30_000;
+const BROWSER_CDP_TIMEOUT_MS = 30_000;
export type BrowserRect = {
x: number;
@@ -92,29 +92,47 @@ type BrowserPage = {
navigating: boolean;
};
+/**
+ * Bound any CDP round trip on the guest. A page that opens a native dialog
+ * or runs a busy loop never answers `debugger.sendCommand`, and neither the
+ * CDP layer nor the RPC timeout table bounds it (#1611) — without this the
+ * agent's browser tool call hangs forever. On timeout the whole debugger
+ * session is detached as recovery, which also drops previously created
+ * snapshot uids; the tool result explains the timeout so the agent can
+ * re-snapshot.
+ */
+function withCdpDeadline<T>(
+ page: BrowserPage,
+ wc: WebContents,
+ run: () => Promise<T>,
+ label: string,
+): Promise<T> {
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+ const timedOut = new Promise<never>((_resolve, reject) => {
+ timeout = setTimeout(() => {
+ const error = Object.assign(
+ new Error(`browser ${label} timed out after ${BROWSER_CDP_TIMEOUT_MS}ms`),
+ { code: "TIMEOUT" },
+ );
+ reject(error);
+ try {
+ page.cdp.detach(wc);
+ } catch {
+ // Preserve the timeout result if the guest is already shutting down.
+ }
+ }, BROWSER_CDP_TIMEOUT_MS);
+ });
+ return Promise.race([Promise.resolve().then(run), timedOut])
+ .finally(() => { if (timeout) clearTimeout(timeout); });
+}
+
function captureScreenshotWithDeadline<T>(
page: BrowserPage,
capture: (wc: WebContents) => Promise<T>,
): Promise<T> {
- return page.pane.captureScreenshot((wc) => {
- let timeout: ReturnType<typeof setTimeout> | undefined;
- const timedOut = new Promise<never>((_resolve, reject) => {
- timeout = setTimeout(() => {
- const error = Object.assign(
- new Error(`browser screenshot timed out after ${BROWSER_SCREENSHOT_TIMEOUT_MS}ms`),
- { code: "TIMEOUT" },
- );
- reject(error);
- try {
- page.cdp.detach(wc);
- } catch {
- // Preserve the timeout result if the guest is already shutting down.
- }
- }, BROWSER_SCREENSHOT_TIMEOUT_MS);
- });
- return Promise.race([Promise.resolve().then(() => capture(wc)), timedOut])
- .finally(() => { if (timeout) clearTimeout(timeout); });
- });
+ return page.pane.captureScreenshot((wc) =>
+ withCdpDeadline(page, wc, () => capture(wc), "screenshot"),
+ );
}
/** Host-owned pages, keyed by conversation and resource tab. */
@@ -451,7 +469,9 @@ export class BrowserHost {
}
async snapshot(): Promise<{ tree: string; url: string; title: string }> {
- return this.currentPage().cdp.snapshot(this.requireWebContents());
+ const page = this.currentPage();
+ const wc = this.requireWebContents();
+ return withCdpDeadline(page, wc, () => page.cdp.snapshot(wc), "snapshot");
}
async screenshot(input: { fullPage?: boolean } = {}, sessionId?: string): Promise<{ mimeType: string; data: string; path?: string }> {
@@ -467,9 +487,21 @@ export class BrowserHost {
} catch { return shot; }
}
- async click(uid: string): Promise<void> { await this.currentPage().cdp.click(this.requireWebContents(), uid); }
- async fill(uid: string, text: string): Promise<void> { await this.currentPage().cdp.fill(this.requireWebContents(), uid, text); }
- async evaluate(expression: string): Promise<unknown> { return this.currentPage().cdp.evaluate(this.requireWebContents(), expression); }
+ async click(uid: string): Promise<void> {
+ const page = this.currentPage();
+ const wc = this.requireWebContents();
+ return withCdpDeadline(page, wc, () => page.cdp.click(wc, uid), "click");
+ }
+ async fill(uid: string, text: string): Promise<void> {
+ const page = this.currentPage();
+ const wc = this.requireWebContents();
+ return withCdpDeadline(page, wc, () => page.cdp.fill(wc, uid, text), "fill");
+ }
+ async evaluate(expression: string): Promise<unknown> {
+ const page = this.currentPage();
+ const wc = this.requireWebContents();
+ return withCdpDeadline(page, wc, () => page.cdp.evaluate(wc, expression), "evaluate");
+ }
console(limit?: number): { messages: ReturnType<BrowserCdp["console"]> } {
this.assertBrowserViewVisible();
if (!this.active?.started) return { messages: [] };
@@ -479,10 +511,11 @@ export class BrowserHost {
}
async cdpCommand(method: string, params?: unknown): Promise<unknown> {
const page = this.currentPage();
+ const wc = this.requireWebContents();
if (method === "Page.captureScreenshot") {
- return captureScreenshotWithDeadline(page, (wc) => page.cdp.send(wc, method, params));
+ return captureScreenshotWithDeadline(page, (view) => page.cdp.send(view, method, params));
}
- return page.cdp.send(this.requireWebContents(), method, params);
+ return withCdpDeadline(page, wc, () => page.cdp.send(wc, method, params), `cdp ${method}`);
}
/** The renderer-created resource tab is the preview's only navigation owner. */
diff --git a/apps/desktop/test/browser-cdp-deadline.test.mjs b/apps/desktop/test/browser-cdp-deadline.test.mjs
new file mode 100644
index 000000000..373efcc09
--- /dev/null
+++ b/apps/desktop/test/browser-cdp-deadline.test.mjs
@@ -0,0 +1,146 @@
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+// The CDP layer is a controllable stub; browser-host.ts itself is real.
+register(new URL("./helpers/browser-cdp-stub-hook.mjs", import.meta.url).href);
+const { BrowserHost } = await import("../electron/main/browser-host.ts");
+const { BrowserCdp } = await import("./helpers/browser-cdp-stub.mjs");
+
+const settled = () => new Promise(setImmediate);
+function deferred() {
+ let resolve;
+ const promise = new Promise((done) => { resolve = done; });
+ return { promise, resolve };
+}
+
+// Manual fake clock over setTimeout: the deadline handlers arm real timers,
+// so tests advance 30 seconds without waiting.
+function fakeClock(t) {
+ const pending = new Map();
+ let now = 0;
+ let seq = 0;
+ t.mock.method(globalThis, "setTimeout", (callback, delay) => {
+ seq += 1;
+ pending.set(seq, { callback, at: now + (delay ?? 0) });
+ return { id: seq, ref() {}, unref() {}, hasRef: () => true };
+ });
+ t.mock.method(globalThis, "clearTimeout", (handle) => {
+ pending.delete(handle?.id);
+ });
+ return {
+ advance(ms) {
+ now += ms;
+ for (const [id, job] of [...pending.entries()]) {
+ if (job.at <= now) {
+ pending.delete(id);
+ try { job.callback(); } catch { /* unrelated boot timers may fail late */ }
+ }
+ }
+ },
+ };
+}
+
+function harness() {
+ const roots = [], loads = [];
+ const createPane = (onState) => {
+ let state = null;
+ const wc = { isDestroyed: () => false };
+ const pane = {
+ visible: false, disposed: false,
+ setWindow: () => {}, setBounds: () => {},
+ setVisible(value) { this.visible = value; },
+ getState: () => state,
+ getWebContents: () => wc,
+ webContents: wc,
+ invalidateNavigation: () => {},
+ captureScreenshot: (run) => run(wc),
+ navigateAndWait(target) {
+ const done = deferred();
+ loads.push({ target, pane, finish() {
+ state = { url: target, title: target, isLoading: false, canGoBack: false, canGoForward: false };
+ onState(state); done.resolve(state);
+ }, fail: () => done.resolve(null) });
+ return done.promise;
+ },
+ dispose() { this.visible = false; this.disposed = true; },
+ };
+ return pane;
+ };
+ const host = new BrowserHost({
+ createPane, isPluginLoaded: () => true,
+ getFileRoot(sessionId) {
+ const done = deferred(); roots.push({ sessionId, ...done }); return done.promise;
+ },
+ onState: () => {},
+ onRevealView: () => {},
+ });
+ host.setChromeSurface({
+ pluginId: "pi.browser", viewId: "browser", visible: true,
+ bounds: { x: 100, y: 20, width: 400, height: 600 },
+ });
+ host.setGuestHole("pi.browser", { x: 0, y: 30, width: 400, height: 570 });
+ return { host, roots, loads };
+}
+
+async function open(h, sessionId, tabId, url) {
+ h.host.setChromeSession(sessionId, tabId, url);
+ h.roots.at(-1).resolve(`/projects/${sessionId}`);
+ await settled(); h.loads.at(-1).finish(); await settled();
+}
+
+test("a hung snapshot is rejected by the deadline and detaches the debugger session", async (t) => {
+ const clock = fakeClock(t);
+ const h = harness();
+ await open(h, "A", "one", "a.html");
+ const cdp = BrowserCdp.current;
+ cdp.hang.add("snapshot");
+
+ const pending = assert.rejects(h.host.snapshot(), /browser snapshot timed out/);
+ clock.advance(30_000);
+ await pending;
+ assert.equal(cdp.detached.length, 1, "timeout recovery detaches the debugger session");
+});
+
+test("click, fill and evaluate share the same deadline", async (t) => {
+ const clock = fakeClock(t);
+ const h = harness();
+ await open(h, "A", "one", "a.html");
+ BrowserCdp.current.hang.add("click").add("fill").add("evaluate");
+
+ const clickPending = assert.rejects(h.host.click("uid-1"), /browser click timed out/);
+ const fillPending = assert.rejects(h.host.fill("uid-1", "text"), /browser fill timed out/);
+ const evaluatePending = assert.rejects(h.host.evaluate("1+1"), /browser evaluate timed out/);
+ clock.advance(30_000);
+ await Promise.all([clickPending, fillPending, evaluatePending]);
+});
+
+test("an allow-listed cdpCommand other than screenshots is deadline-bounded too", async (t) => {
+ const clock = fakeClock(t);
+ const h = harness();
+ await open(h, "A", "one", "a.html");
+ BrowserCdp.current.hang.add("Runtime.evaluate");
+
+ const pending = assert.rejects(
+ h.host.cdpCommand("Runtime.evaluate", { expression: "1" }),
+ /browser cdp Runtime\.evaluate timed out/,
+ );
+ clock.advance(30_000);
+ await pending;
+});
+
+test("calls that finish in time are unaffected by the deadline", async (t) => {
+ const clock = fakeClock(t);
+ const h = harness();
+ await open(h, "A", "one", "a.html");
+
+ const snapshot = await h.host.snapshot();
+ assert.equal(snapshot.tree, "fixture-tree");
+ const evaluated = await h.host.evaluate("1+1");
+ assert.deepEqual(evaluated, { expression: "1+1" });
+ const cdp = await h.host.cdpCommand("Page.getLayoutMetrics", {});
+ assert.equal(cdp.method, "Page.getLayoutMetrics");
+ // Advancing well past the deadline must fire nothing: the timers were cleared.
+ clock.advance(60_000);
+ assert.deepEqual(BrowserCdp.current.detached, []);
+});
diff --git a/apps/desktop/test/helpers/browser-cdp-stub-hook.mjs b/apps/desktop/test/helpers/browser-cdp-stub-hook.mjs
new file mode 100644
index 000000000..89f345c86
--- /dev/null
+++ b/apps/desktop/test/helpers/browser-cdp-stub-hook.mjs
@@ -0,0 +1,18 @@
+/**
+ * Module hooks for importing browser-host.ts under `node --test` with the
+ * CDP layer replaced: specifiers ending in `browser-cdp` resolve to the
+ * controllable stub, everything else defers to the repo's ts-import-hooks.
+ *
+ * Register with:
+ * register(new URL("./browser-cdp-stub-hook.mjs", import.meta.url).href);
+ */
+import { resolve as resolveTypeScriptSibling } from "./ts-import-hooks.mjs";
+
+const stub = new URL("./browser-cdp-stub.mjs", import.meta.url).href;
+
+export async function resolve(specifier, context, next) {
+ if (specifier === "./browser-cdp") {
+ return next(stub, { ...context, parentURL: undefined });
+ }
+ return resolveTypeScriptSibling(specifier, context, next);
+}
diff --git a/apps/desktop/test/helpers/browser-cdp-stub.mjs b/apps/desktop/test/helpers/browser-cdp-stub.mjs
new file mode 100644
index 000000000..f03a9804e
--- /dev/null
+++ b/apps/desktop/test/helpers/browser-cdp-stub.mjs
@@ -0,0 +1,61 @@
+/**
+ * Controllable stand-in for `./browser-cdp`, loaded in place of the real
+ * module by helpers/browser-cdp-stub-hook.mjs. Tests install per-method
+ * behavior: methods named in `hang` never settle (the "page opened a native
+ * dialog" case), everything else resolves with a fixture value. Every call
+ * is recorded, and `detached` collects the WebContents the deadline handler
+ * detached.
+ */
+export class BrowserCdp {
+ static current = null;
+
+ constructor() {
+ this.hang = new Set();
+ this.calls = [];
+ this.detached = [];
+ BrowserCdp.current = this;
+ }
+
+ run(method, result) {
+ this.calls.push(method);
+ if (this.hang.has(method)) return new Promise(() => {});
+ return Promise.resolve(result);
+ }
+
+ snapshot() {
+ return this.run("snapshot", { tree: "fixture-tree", url: "fixture://page", title: "Fixture" });
+ }
+
+ screenshot(_wc, input) {
+ return this.run("screenshot", { mimeType: "image/jpeg", data: `shot:${JSON.stringify(input ?? {})}` });
+ }
+
+ click(_wc, uid) {
+ return this.run("click", { uid });
+ }
+
+ fill(_wc, uid, text) {
+ return this.run("fill", { uid, text });
+ }
+
+ evaluate(_wc, expression) {
+ return this.run("evaluate", { expression });
+ }
+
+ send(_wc, method, params) {
+ return this.run(method, { method, params });
+ }
+
+ attach() {
+ this.calls.push("attach");
+ }
+
+ detach(wc) {
+ this.calls.push("detach");
+ this.detached.push(wc);
+ }
+
+ console() {
+ return [];
+ }
+}