Skip to content

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

fix(browser): preserve the latest viewport after screenshot capture

AR3074f68894726c0
diff --git a/apps/desktop/electron/main/browser-host.ts b/apps/desktop/electron/main/browser-host.ts
index e3aa94e9a..918a1b44a 100644
--- a/apps/desktop/electron/main/browser-host.ts
+++ b/apps/desktop/electron/main/browser-host.ts
@@ -302,7 +302,7 @@ export class BrowserHost {
async screenshot(input: { fullPage?: boolean } = {}, sessionId?: string): Promise<{ mimeType: string; data: string; path?: string }> {
const page = this.currentPage();
- const shot = await page.cdp.screenshot(this.requireWebContents(), input);
+ const shot = await page.pane.captureScreenshot((wc) => page.cdp.screenshot(wc, input));
const scratch = this.deps.getScratchDir?.(sessionId ?? page.sessionId);
if (!scratch) return shot;
try {
@@ -322,7 +322,13 @@ export class BrowserHost {
void this.active.cdp.attach(wc);
return { messages: this.active.cdp.console(limit) };
}
- async cdpCommand(method: string, params?: unknown): Promise<unknown> { return this.currentPage().cdp.send(this.requireWebContents(), method, params); }
+ async cdpCommand(method: string, params?: unknown): Promise<unknown> {
+ const page = this.currentPage();
+ if (method === "Page.captureScreenshot") {
+ return page.pane.captureScreenshot((wc) => page.cdp.send(wc, method, params));
+ }
+ return page.cdp.send(this.requireWebContents(), method, params);
+ }
/** The renderer-created resource tab is the preview's only navigation owner. */
async previewWorkspaceFile(_sessionId: string, _path: string, _root: string): Promise<{ ok: true } | { ok: false; content: string }> {
diff --git a/apps/desktop/electron/main/browser-view.ts b/apps/desktop/electron/main/browser-view.ts
index 0c885d1d5..38dd8c2e1 100644
--- a/apps/desktop/electron/main/browser-view.ts
+++ b/apps/desktop/electron/main/browser-view.ts
@@ -1,4 +1,4 @@
-import { shell, WebContentsView, type BrowserWindow } from "electron";
+import { shell, WebContentsView, type BrowserWindow, type WebContents } from "electron";
import { realpathSync, statSync, watch, type FSWatcher } from "node:fs";
import { dirname, isAbsolute, resolve, sep } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
@@ -95,6 +95,8 @@ export class BrowserPane {
private window: BrowserWindow | null = null;
private visible = false;
private bounds = { x: 0, y: 0, width: 0, height: 0 };
+ private capturing = false;
+ private captureTail: Promise<void> = Promise.resolve();
private onState: (state: BrowserState) => void;
private fileRoot: string | null = null;
private watcher: FSWatcher | null = null;
@@ -149,6 +151,29 @@ export class BrowserPane {
return wc;
}
+ /** Serialize captures with native resizing on this page only. */
+ captureScreenshot<T>(capture: (wc: WebContents) => Promise<T>): Promise<T> {
+ // Pin the guest before queueing so a closed/recreated page cannot receive
+ // a screenshot requested for its predecessor.
+ const wc = this.getWebContents();
+ const task = this.captureTail.then(async () => {
+ if (!wc || wc.isDestroyed() || this.getWebContents() !== wc) {
+ throw Object.assign(new Error("browser guest is not available"), { code: "UNAVAILABLE" });
+ }
+ this.capturing = true;
+ try {
+ return await capture(wc);
+ } finally {
+ this.capturing = false;
+ this.applyBounds();
+ }
+ });
+ // The caller still receives capture errors; a failure must not block the
+ // next independent capture.
+ this.captureTail = task.then(() => undefined, () => undefined);
+ return task;
+ }
+
/**
* Stop native WebContents events from publishing state for the document
* that belonged to the previous session. The next completed managed
@@ -280,7 +305,15 @@ export class BrowserPane {
height: Math.max(0, Math.round(Number(bounds.height) || 0)),
};
this.bounds = safe;
- if (this.view && this.visible) this.view.setBounds(safe);
+ this.applyBounds();
+ }
+
+ private applyBounds(): void {
+ // Chromium restores capture-time viewport metrics on completion. Keep
+ // native bounds unchanged meanwhile, then apply the latest requested size.
+ if (this.view && this.visible && !this.capturing && !this.view.webContents.isDestroyed()) {
+ this.view.setBounds(this.bounds);
+ }
}
setVisible(visible: boolean): void {
@@ -329,7 +362,7 @@ export class BrowserPane {
if (!this.window.contentView.children.includes(this.view)) {
this.window.contentView.addChildView(this.view);
}
- this.view.setBounds(this.bounds);
+ this.applyBounds();
}
private detach(): void {
diff --git a/apps/desktop/test/browser-capture-resize.test.mjs b/apps/desktop/test/browser-capture-resize.test.mjs
new file mode 100644
index 000000000..84684e89d
--- /dev/null
+++ b/apps/desktop/test/browser-capture-resize.test.mjs
@@ -0,0 +1,167 @@
+import assert from "node:assert/strict";
+import { once } from "node:events";
+import { register, registerHooks } from "node:module";
+import test from "node:test";
+
+// Only Electron is replaced: exercise the production Host, Pane and CDP path.
+// Chromium restores the viewport saved when capture starts, even if a native
+// bounds update arrives before capture finishes.
+const electron = `data:text/javascript,${encodeURIComponent(`
+ import { EventEmitter } from "node:events";
+ export const shell = {};
+ export class WebContentsView {
+ static instances = [];
+ constructor() {
+ const wc = Object.assign(new EventEmitter(), {
+ id: WebContentsView.instances.length + 1,
+ url: "", destroyed: false, viewport: { width: 0, height: 0 },
+ captures: [],
+ async loadURL(url) {
+ this.emit("did-start-navigation", {}, url, false, true);
+ this.url = url;
+ this.emit("did-navigate", {}, url);
+ },
+ getURL() { return this.url; },
+ getTitle: () => "fixture", isLoading: () => false,
+ isDestroyed() { return this.destroyed; },
+ close() { this.destroyed = true; },
+ navigationHistory: { canGoBack: () => false, canGoForward: () => false },
+ setWindowOpenHandler: () => {},
+ session: { setPermissionRequestHandler: () => {} },
+ });
+ wc.debugger = Object.assign(new EventEmitter(), {
+ attached: false,
+ isAttached() { return this.attached; },
+ attach() { this.attached = true; },
+ detach() { this.attached = false; },
+ async sendCommand(method, params) {
+ if (method === "Page.getLayoutMetrics") {
+ return { cssContentSize: { width: wc.viewport.width, height: 6000 } };
+ }
+ if (method !== "Page.captureScreenshot") return {};
+ const savedViewport = { ...wc.viewport };
+ let resolve, reject;
+ const pending = new Promise((yes, no) => { resolve = yes; reject = no; });
+ wc.captures.push({ params, resolve, reject });
+ wc.emit("capture-start");
+ try {
+ await pending;
+ return { data: "fixture-image" };
+ } finally { wc.viewport = savedViewport; }
+ },
+ });
+ this.webContents = wc;
+ WebContentsView.instances.push(this);
+ }
+ setBounds(bounds) {
+ this.bounds = { ...bounds };
+ this.webContents.viewport = { width: bounds.width, height: bounds.height };
+ }
+ setVisible() {}
+ }
+`)}`;
+registerHooks({ resolve(specifier, context, next) {
+ return specifier === "electron" ? { url: electron, shortCircuit: true } : next(specifier, context);
+} });
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+const { BrowserHost } = await import("../electron/main/browser-host.ts");
+const { BrowserPane } = await import("../electron/main/browser-view.ts");
+const { WebContentsView } = await import("electron");
+
+async function harness(t) {
+ const host = new BrowserHost({
+ createPane: (onState, onOpenUrl) => new BrowserPane(onState, onOpenUrl),
+ isPluginLoaded: () => true, getFileRoot: async () => null, onState: () => {},
+ });
+ const children = [];
+ host.setWindow({ isDestroyed: () => false, contentView: {
+ children,
+ addChildView(view) { children.push(view); },
+ removeChildView(view) { children.splice(children.indexOf(view), 1); },
+ } });
+ host.setChromeSurface({ pluginId: "pi.browser", viewId: "browser", visible: true,
+ bounds: { x: 0, y: 0, width: 1200, height: 900 } });
+ const resize = (width, height) => host.setGuestHole("pi.browser", { x: 0, y: 0, width, height });
+ resize(800, 500);
+ host.setChromeSession("session", "first");
+ await host.navigate({ url: "https://fixture.invalid/first" }, "session");
+ t.after(() => host.dispose());
+ return { host, resize, wc: WebContentsView.instances.at(-1).webContents };
+}
+
+for (const raw of [false, true]) {
+ test(`${raw ? "raw CDP" : "browser screenshot"} restores the latest panel size`, async (t) => {
+ const { host, resize, wc } = await harness(t);
+ const started = once(wc, "capture-start");
+ const request = raw
+ ? host.cdpCommand("Page.captureScreenshot", { format: "png" })
+ : host.screenshot({ fullPage: true });
+ await started;
+ resize(910, 590);
+ resize(960, 620);
+ wc.captures[0].resolve();
+ await request;
+ assert.deepEqual(wc.viewport, { width: 960, height: 620 });
+ assert.equal(wc.captures.length, 1, "resizing must not repeat the screenshot");
+ });
+}
+
+test("a failed capture releases resizing and does not poison the next capture", async (t) => {
+ const { host, resize, wc } = await harness(t);
+ const started = once(wc, "capture-start");
+ const failed = assert.rejects(host.screenshot(), /fixture capture failure/);
+ await started;
+ resize(940, 600);
+ wc.captures[0].reject(new Error("fixture capture failure"));
+ await failed;
+ assert.deepEqual(wc.viewport, { width: 940, height: 600 });
+ const nextStarted = once(wc, "capture-start");
+ const next = host.screenshot();
+ await nextStarted;
+ wc.captures[1].resolve();
+ assert.equal((await next).data, "fixture-image");
+});
+
+test("overlapping capture APIs serialize per page, not across sibling tabs", async (t) => {
+ const { host, resize, wc } = await harness(t);
+ const started = once(wc, "capture-start");
+ const first = host.screenshot();
+ await started;
+ const nextStarted = once(wc, "capture-start");
+ const next = host.cdpCommand("Page.captureScreenshot", { format: "png" });
+ host.setChromeSession("session", "second");
+ await host.navigate({ url: "https://fixture.invalid/second" }, "session");
+ const sibling = WebContentsView.instances.at(-1).webContents;
+ const siblingStarted = once(sibling, "capture-start");
+ const siblingShot = host.screenshot();
+ await siblingStarted;
+ assert.equal(wc.captures.length, 1, "the first page must not capture concurrently");
+ sibling.captures[0].resolve();
+ await siblingShot;
+ wc.captures[0].resolve();
+ await first;
+ await nextStarted;
+ assert.equal(wc.captures.length, 2, "queued capture must retain its original page");
+ host.setChromeSession("session", "first");
+ resize(920, 610);
+ wc.captures[1].resolve();
+ await next;
+ assert.deepEqual(wc.viewport, { width: 920, height: 610 });
+ assert.equal(sibling.captures.length, 1);
+});
+
+test("closing a tab rejects its queued capture without capturing a replacement", async (t) => {
+ const { host, wc } = await harness(t);
+ const started = once(wc, "capture-start");
+ const first = host.screenshot();
+ await started;
+ const queued = assert.rejects(host.screenshot(), /browser guest is not available/);
+ host.closeTab("session", "first");
+ host.setChromeSession("session", "replacement");
+ await host.navigate({ url: "https://fixture.invalid/replacement" }, "session");
+ wc.captures[0].resolve();
+ await first;
+ await queued;
+ assert.equal(wc.captures.length, 1);
+ assert.equal(WebContentsView.instances.at(-1).webContents.captures.length, 0);
+});
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index b2646cc9c..422889915 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -1206,6 +1206,13 @@ entirely inside the plugin's isolated page:
the divider restores the default 360px width, clamped by the same live
minimum and three-column budget, so a reset never breaches the MainChat
floor.
+- Browser capture and resize: screenshots and raw `Page.captureScreenshot`
+ calls serialize per retained browser page. While a capture is in flight,
+ the page retains the latest requested bounds without changing its native
+ viewport. Capture completion or failure applies those bounds if the page
+ is visible; a hidden page receives them when shown again. Queued captures
+ stay on their original page and fail if that guest was closed. Other pages
+ remain independent, and resizing never triggers an extra screenshot.
- Persistence: all session contexts are renderer runtime state only. On app
startup, open state, tabs, active-tab selection, file requests, and Browser
resources reset; only the committed preferred `{width}` remains in
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index be11b1497..2b496f9a1 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -4364,6 +4364,24 @@ identify the platform validation still needed.
- **Milestone**: M5
- **Status**: Draft (manual)
+#### E2E-BROWSER-capture-resize: Capture completion preserves the latest viewport
+
+- **Preconditions**: Isolated Electron profile and a local responsive page
+ taller than the visible browser viewport. No provider account is needed.
+- **Steps**: Start a full-page screenshot, then resize the browser hole twice
+ before Chromium completes it. Repeat while alternating larger and smaller
+ sizes and through raw `Page.captureScreenshot`. Queue overlapping captures,
+ change resource tabs, fail a capture, and close a tab with a queued capture.
+- **Expected**: The completed capture does not restore a stale viewport. The
+ page's `innerWidth`/`innerHeight` match the latest requested bounds. Captures
+ on one page serialize without blocking a sibling page. Failed capture
+ releases resize handling. Closing a page cannot redirect its queued capture
+ to another page. No screenshot is repeated to repair layout.
+- **Status**: Native Electron capture/resize path automated by
+ `node scripts/e2e-browser-capture-resize.mjs` (artifacts retained). The
+ production Host/Pane/CDP service paths for failure, queueing and tab closure
+ are covered by `apps/desktop/test/browser-capture-resize.test.mjs`.
+
#### E2E-BROWSER-session-preview-race: Session switching does not expose a stale preview
- **Preconditions**: Two sessions have distinct HTML previews; their Browser
diff --git a/scripts/e2e-browser-capture-resize.mjs b/scripts/e2e-browser-capture-resize.mjs
new file mode 100644
index 000000000..6a41735f0
--- /dev/null
+++ b/scripts/e2e-browser-capture-resize.mjs
@@ -0,0 +1,40 @@
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { mkdtempSync } from "node:fs";
+import { createRequire } from "node:module";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { resolveElectronBinary } from "./e2e/boot.mjs";
+
+const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
+// Reuse compatible installed dependencies without importing their app source.
+const dependencyRoot = process.env.E2E_DEPENDENCY_ROOT || root;
+const require = createRequire(join(dependencyRoot, "packages/agent-runtime/package.json"));
+const { build } = require("esbuild");
+const { electronBinary } = resolveElectronBinary(dependencyRoot);
+const artifacts = mkdtempSync(join(tmpdir(), "pi-browser-capture-resize-"));
+const main = join(artifacts, "main.cjs");
+await build({
+ entryPoints: [join(root, "scripts/e2e/browser-capture-resize.ts")],
+ outfile: main, bundle: true, platform: "node", format: "cjs", external: ["electron"],
+});
+const env = { ...process.env, BROWSER_CAPTURE_ARTIFACT_DIR: artifacts };
+delete env.ELECTRON_RUN_AS_NODE;
+const child = spawn(electronBinary, [main], { env, stdio: ["ignore", "pipe", "pipe"] });
+let output = "";
+for (const stream of [child.stdout, child.stderr]) {
+ stream.on("data", (data) => { output += data; });
+}
+const timeout = setTimeout(() => child.kill(), 45_000);
+let code;
+try {
+ code = await new Promise((resolve, reject) => {
+ child.once("error", reject);
+ child.once("close", resolve);
+ });
+} finally { clearTimeout(timeout); }
+console.log(`Browser capture artifacts retained at ${artifacts}`);
+console.log(output.trim());
+assert.equal(code, 0, "native browser capture/resize regression failed");
+assert.match(output, /BROWSER_CAPTURE_RESIZE {"ok":true/);
diff --git a/scripts/e2e/browser-capture-resize.ts b/scripts/e2e/browser-capture-resize.ts
new file mode 100644
index 000000000..62323883a
--- /dev/null
+++ b/scripts/e2e/browser-capture-resize.ts
@@ -0,0 +1,105 @@
+import assert from "node:assert/strict";
+import { once } from "node:events";
+import { writeFileSync } from "node:fs";
+import { createServer } from "node:http";
+import { join } from "node:path";
+import { app, BrowserWindow } from "electron";
+import { BrowserHost } from "../../apps/desktop/electron/main/browser-host";
+import { BrowserPane } from "../../apps/desktop/electron/main/browser-view";
+
+const artifactDir = process.env.BROWSER_CAPTURE_ARTIFACT_DIR;
+if (!artifactDir) throw new Error("BROWSER_CAPTURE_ARTIFACT_DIR is required");
+app.setPath("userData", join(artifactDir, "profile"));
+
+async function probe(artifactDir: string) {
+ const server = createServer((_request, response) => {
+ response.setHeader("Content-Type", "text/html; charset=utf-8");
+ response.end(`<!doctype html><style>
+ body{margin:0;font:24px sans-serif;background:#eee}
+ header{padding:20px;background:#222;color:white}
+ main{height:6000px;background:linear-gradient(#ddd,#57a)}
+ .grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:20px}
+ article{padding:24px;background:white;border:1px solid #888}
+ </style><header>Browser viewport resize regression</header><main><div class="grid">
+ ${Array.from({ length: 12 }, (_, i) => `<article>Card ${i + 1}</article>`).join("")}
+ </div></main>`);
+ });
+ server.listen(0, "127.0.0.1");
+ await once(server, "listening");
+ const address = server.address();
+ assert(address && typeof address !== "string");
+ const window = new BrowserWindow({ width: 1100, height: 750, show: true });
+ const panes: BrowserPane[] = [];
+ const host = new BrowserHost({
+ createPane: (onState, onOpenUrl) => {
+ const pane = new BrowserPane(onState, onOpenUrl);
+ panes.push(pane);
+ return pane;
+ },
+ isPluginLoaded: () => true, getFileRoot: async () => null, onState: () => {},
+ });
+ try {
+ await window.loadURL("about:blank");
+ host.setWindow(window);
+ host.setChromeSurface({ pluginId: "pi.browser", viewId: "browser", visible: true,
+ bounds: { x: 0, y: 0, width: 1000, height: 700 } });
+ const resize = (width: number, height: number) => {
+ host.setGuestHole("pi.browser", { x: 0, y: 0, width, height });
+ };
+ resize(800, 500);
+ host.setChromeSession("capture-regression", "page");
+ await host.navigate({ url: `http://127.0.0.1:${address.port}` }, "capture-regression");
+ const wc = panes[0].getWebContents();
+ assert(wc);
+ const frame = () => wc.executeJavaScript(
+ "new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))",
+ );
+ await frame();
+ const originalSend = wc.debugger.sendCommand.bind(wc.debugger);
+ let resizeDuringCapture: { width: number; height: number } | undefined;
+ // Synchronize a real native bounds change with Chromium's in-flight
+ // screenshot, rather than relying on a machine-speed-dependent timer.
+ wc.debugger.sendCommand = (method, params, sessionId) => {
+ const pending = originalSend(method, params, sessionId);
+ if (method === "Page.captureScreenshot" && resizeDuringCapture) {
+ const size = resizeDuringCapture;
+ resizeDuringCapture = undefined;
+ resize(size.width - 20, size.height - 20);
+ resize(size.width, size.height);
+ }
+ return pending;
+ };
+ const results = [];
+ for (let i = 0; i < 12; i++) {
+ const expected = i % 2 ? { width: 820, height: 510 } : { width: 960, height: 620 };
+ resizeDuringCapture = expected;
+ const raw = i >= 6;
+ if (raw) {
+ await host.cdpCommand("Page.captureScreenshot", { format: "png",
+ captureBeyondViewport: true, clip: { x: 0, y: 0, width: 800, height: 6000, scale: 1 } });
+ } else {
+ await host.screenshot({ fullPage: true });
+ }
+ await frame();
+ const actual: unknown = await wc.executeJavaScript("({width: innerWidth, height: innerHeight})");
+ results.push({ entry: raw ? "raw-cdp" : "screenshot", expected, actual });
+ }
+ wc.debugger.sendCommand = originalSend;
+ const image = await wc.capturePage();
+ assert(!image.isEmpty(), "native guest screenshot is empty");
+ writeFileSync(join(artifactDir, "browser-viewport.png"), image.toPNG());
+ const report = { electron: process.versions.electron, chrome: process.versions.chrome, results };
+ writeFileSync(join(artifactDir, "results.json"), JSON.stringify(report, null, 2));
+ for (const row of results) assert.deepEqual(row.actual, row.expected, row.entry);
+ console.log(`BROWSER_CAPTURE_RESIZE ${JSON.stringify({ ok: true, ...report })}`);
+ } finally {
+ host.dispose();
+ window.destroy();
+ server.close();
+ }
+}
+
+app.whenReady().then(() => probe(artifactDir)).then(
+ () => app.exit(0),
+ (error: unknown) => { console.error(error); app.exit(1); },
+);