Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(browser): keep preview placement responsive during capture
AR307722d2fa37c26
diff --git a/apps/desktop/electron/main/browser-view.ts b/apps/desktop/electron/main/browser-view.tsindex 38dd8c2e1..cc98c82d8 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, type WebContents } from "electron";+import { shell, View, 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";@@ -8,8 +8,8 @@ import { isAllowedHttpUrl, parseAllowedExternalUrl } from "./safe-open-external"/*** Work panel embedded preview browser (D100, ADR 0019).*- * A single WebContentsView owned by the main process, attached to the main- * window and positioned from renderer-measured bounds. The renderer is the+ * A single WebContentsView owned by the main process, clipped by a native+ * presentation View positioned from renderer-measured bounds. The renderer is the* visibility authority: it hides the view whenever the browser tab is not* the active panel surface or a blocking overlay opens (the view always* composites above renderer content).@@ -92,6 +92,7 @@ export function resolveLocalFile(raw: string, root: string | null): string | nulexport class BrowserPane {private view: WebContentsView | null = null;+ private surface: View | null = null;private window: BrowserWindow | null = null;private visible = false;private bounds = { x: 0, y: 0, width: 0, height: 0 };@@ -309,23 +310,26 @@ export class BrowserPane {}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);+ // Move and clip the presentation surface immediately, even while Chromium+ // pins its capture-time viewport. A pending screenshot must not leave the+ // guest over the conversation when the window or work panel moves.+ this.surface?.setBounds(this.bounds);+ if (this.view && this.visible && !this.capturing && this.getWebContents()) {+ this.view.setBounds({ x: 0, y: 0, width: this.bounds.width, height: this.bounds.height });}}setVisible(visible: boolean): void {this.visible = visible;if (!this.view) return;+ this.surface?.setVisible(visible);this.view.setVisible?.(visible);if (visible) this.attach();else this.detach();}openExternal(): void {- const url = this.view?.webContents.getURL();+ const url = this.getWebContents()?.getURL();if (!url) return;const allowed = parseAllowedExternalUrl(url);if (allowed) {@@ -346,30 +350,33 @@ export class BrowserPane {this.clearLiveReload();this.detach();if (this.view) {- this.view.webContents.close();+ const wc = this.getWebContents();+ this.surface?.removeChildView(this.view);this.view = null;+ this.surface = null;+ wc?.close();}}private attach(): void {- if (!this.window || this.window.isDestroyed() || !this.view) return;+ if (!this.window || this.window.isDestroyed() || !this.surface) return;const children = this.window.contentView.children;// The guest hole sits on top of plugin chrome. Re-adding a plugin view// after this pane is attached would cover the guest unless we keep it last.- if (children.includes(this.view) && children[children.length - 1] !== this.view) {- this.window.contentView.removeChildView(this.view);+ if (children.includes(this.surface) && children[children.length - 1] !== this.surface) {+ this.window.contentView.removeChildView(this.surface);}- if (!this.window.contentView.children.includes(this.view)) {- this.window.contentView.addChildView(this.view);+ if (!this.window.contentView.children.includes(this.surface)) {+ this.window.contentView.addChildView(this.surface);}this.applyBounds();}private detach(): void {- if (!this.window || this.window.isDestroyed() || !this.view) return;+ if (!this.window || this.window.isDestroyed() || !this.surface) return;const children = this.window.contentView.children;- if (children.includes(this.view)) {- this.window.contentView.removeChildView(this.view);+ if (children.includes(this.surface)) {+ this.window.contentView.removeChildView(this.surface);}}@@ -417,7 +424,9 @@ export class BrowserPane {}private ensureView(): WebContentsView {- if (this.view && !this.view.webContents.isDestroyed()) return this.view;+ if (this.view && this.getWebContents()) return this.view;+ this.detach();+ if (this.view) this.surface?.removeChildView(this.view);const view = new WebContentsView({webPreferences: {sandbox: true,@@ -427,6 +436,11 @@ export class BrowserPane {partition: PARTITION,},});+ const surface = new View();+ surface.addChildView(view);+ surface.setVisible(this.visible);+ surface.setBounds(this.bounds);+ this.surface = surface;const wc = view.webContents;wc.setWindowOpenHandler(({ url }) => {const allowed = parseAllowedExternalUrl(url);diff --git a/apps/desktop/test/browser-capture-resize.test.mjs b/apps/desktop/test/browser-capture-resize.test.mjsindex 84684e89d..d0fd1e44d 100644--- a/apps/desktop/test/browser-capture-resize.test.mjs+++ b/apps/desktop/test/browser-capture-resize.test.mjs@@ -9,9 +9,21 @@ import test from "node:test";const electron = `data:text/javascript,${encodeURIComponent(`import { EventEmitter } from "node:events";export const shell = {};- export class WebContentsView {+ export class View {+ children = [];+ parent = null;+ visible = true;+ bounds = { x: 0, y: 0, width: 0, height: 0 };+ addChildView(view) { this.children.push(view); view.parent = this; }+ removeChildView(view) { this.children.splice(this.children.indexOf(view), 1); view.parent = null; }+ setBounds(bounds) { this.bounds = { ...bounds }; }+ getBounds() { return { ...this.bounds }; }+ setVisible(visible) { this.visible = visible; }+ }+ export class WebContentsView extends View {static instances = [];constructor() {+ super();const wc = Object.assign(new EventEmitter(), {id: WebContentsView.instances.length + 1,url: "", destroyed: false, viewport: { width: 0, height: 0 },@@ -24,7 +36,11 @@ const electron = `data:text/javascript,${encodeURIComponent(`getURL() { return this.url; },getTitle: () => "fixture", isLoading: () => false,isDestroyed() { return this.destroyed; },- close() { this.destroyed = true; },+ close() {+ if (this.destroyed) throw new Error("guest already destroyed");+ this.destroyed = true;+ this.emit("destroyed");+ },navigationHistory: { canGoBack: () => false, canGoForward: () => false },setWindowOpenHandler: () => {},session: { setPermissionRequestHandler: () => {} },@@ -51,13 +67,13 @@ const electron = `data:text/javascript,${encodeURIComponent(`},});this.webContents = wc;+ wc.once("destroyed", () => { this.webContents = undefined; });WebContentsView.instances.push(this);}setBounds(bounds) {this.bounds = { ...bounds };this.webContents.viewport = { width: bounds.width, height: bounds.height };}- setVisible() {}}`)}`;registerHooks({ resolve(specifier, context, next) {@@ -86,7 +102,41 @@ async function harness(t) {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 };+ return { host, resize, children, view: WebContentsView.instances.at(-1), wc: WebContentsView.instances.at(-1).webContents };+}++function paintedBounds(view) {+ const own = view.getBounds();+ if (!view.parent) return own;+ const parent = view.parent.getBounds();+ return {+ x: parent.x + own.x, y: parent.y + own.y,+ width: Math.min(own.width, parent.width - own.x),+ height: Math.min(own.height, parent.height - own.y),+ };+}++for (const raw of [false, true]) {+ test(`${raw ? "raw CDP" : "browser screenshot"} stays inside the relocated panel before capture finishes`, async (t) => {+ const { host, wc, view } = await harness(t);+ const started = once(wc, "capture-start");+ const capture = raw+ ? host.cdpCommand("Page.captureScreenshot", { format: "png" })+ : host.screenshot({ fullPage: true });+ await started;+ // A maximize/restore can move the panel while the tool's screenshot is+ // still pending. The content must never remain above the conversation.+ const relocated = { x: 1100, y: 42, width: 620, height: 430 };+ host.setChromeSurface({ pluginId: "pi.browser", viewId: "browser", visible: true, bounds: relocated });+ host.setGuestHole("pi.browser", { x: 0, y: 0, width: 620, height: 430 });+ const during = paintedBounds(view);+ assert.deepEqual(wc.viewport, { width: 800, height: 500 }, "capture viewport remains stable");+ wc.captures[0].resolve();+ await capture;+ assert.deepEqual(during, relocated, "move and clip the native guest before awaiting capture");+ assert.deepEqual(paintedBounds(view), relocated);+ assert.deepEqual(wc.viewport, { width: 620, height: 430 });+ });}for (const raw of [false, true]) {@@ -165,3 +215,59 @@ test("closing a tab rejects its queued capture without capturing a replacement",assert.equal(wc.captures.length, 1);assert.equal(WebContentsView.instances.at(-1).webContents.captures.length, 0);});++test("hiding and restoring a captured page keeps its presentation isolated from sibling tabs", async (t) => {+ const { host, children, view, wc } = await harness(t);+ const surface = view.parent;+ const started = once(wc, "capture-start");+ const capture = host.screenshot();+ await started;+ host.setChromeSession("session", "second");+ await host.navigate({ url: "https://fixture.invalid/second" }, "session");+ assert(!children.includes(surface));+ assert.equal(surface.visible, false);+ const relocated = { x: 960, y: 70, width: 530, height: 400 };+ host.setChromeSurface({ pluginId: "pi.browser", viewId: "browser", visible: true, bounds: relocated });+ host.setGuestHole("pi.browser", { x: 0, y: 0, width: 530, height: 400 });+ host.setChromeSession("session", "first");+ assert.deepEqual(paintedBounds(view), relocated);+ assert.equal(surface.visible, true);+ assert.equal(children.at(-1), surface);+ wc.captures[0].resolve();+ await capture;+ assert.deepEqual(wc.viewport, { width: 530, height: 400 });+ host.closeTab("session", "first");+ assert(!children.includes(surface));+ assert.equal(surface.children.length, 0);+ assert.equal(wc.destroyed, true);+});++test("a destroyed native guest can be resized, replaced and disposed safely", async (t) => {+ const { host, resize, wc, view, children } = await harness(t);+ const previousSurface = view.parent;+ wc.close();+ assert.equal(view.webContents, undefined, "Electron clears a destroyed guest handle");+ resize(930, 620);+ await host.navigate({ url: "https://fixture.invalid/recreated" }, "session");+ const replacement = WebContentsView.instances.at(-1);+ assert.notEqual(replacement, view);+ assert(!children.includes(previousSurface));+ assert.equal(children.length, 1);+ assert.deepEqual(replacement.webContents.viewport, { width: 930, height: 620 });+ replacement.webContents.close();+ host.dispose();+ host.dispose();+ assert.equal(children.length, 0);+});++test("capture completion after native guest destruction preserves the original capture result", async (t) => {+ const { host, resize, wc } = await harness(t);+ const started = once(wc, "capture-start");+ const capture = host.screenshot();+ await started;+ wc.close();+ resize(900, 620);+ wc.captures[0].resolve();+ assert.equal((await capture).data, "fixture-image");+ host.dispose();+});diff --git a/apps/desktop/test/browser-pane-navigation.test.mjs b/apps/desktop/test/browser-pane-navigation.test.mjsindex 13d576d72..766e75c9a 100644--- a/apps/desktop/test/browser-pane-navigation.test.mjs+++ b/apps/desktop/test/browser-pane-navigation.test.mjs@@ -11,6 +11,13 @@ import { pathToFileURL } from "node:url";const electron = `data:text/javascript,${encodeURIComponent(`import { EventEmitter } from "node:events";export const shell = {};+ export class View {+ children = [];+ addChildView(view) { this.children.push(view); }+ removeChildView(view) { this.children.splice(this.children.indexOf(view), 1); }+ setVisible() {}+ setBounds() {}+ }export class WebContentsView {static instances = [];constructor() {diff --git a/scripts/e2e/browser-capture-resize.ts b/scripts/e2e/browser-capture-resize.tsindex 62323883a..3b2bd18bc 100644--- a/scripts/e2e/browser-capture-resize.ts+++ b/scripts/e2e/browser-capture-resize.ts@@ -1,17 +1,20 @@import assert from "node:assert/strict";import { once } from "node:events";-import { writeFileSync } from "node:fs";+import { appendFileSync, writeFileSync } from "node:fs";import { createServer } from "node:http";import { join } from "node:path";-import { app, BrowserWindow } from "electron";+import { app, BrowserWindow, desktopCapturer, WebContentsView, type View } from "electron";import { BrowserHost } from "../../apps/desktop/electron/main/browser-host";import { BrowserPane } from "../../apps/desktop/electron/main/browser-view";+import { checkBrowserPaneLifecycle } from "./browser-pane-lifecycle";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"));+const stage = (value: string) => appendFileSync(join(artifactDir, "progress.log"), `${value}\n`);async function probe(artifactDir: string) {+ stage("app-ready");const server = createServer((_request, response) => {response.setHeader("Content-Type", "text/html; charset=utf-8");response.end(`<!doctype html><style>@@ -28,7 +31,7 @@ async function probe(artifactDir: string) {await once(server, "listening");const address = server.address();assert(address && typeof address !== "string");- const window = new BrowserWindow({ width: 1100, height: 750, show: true });+ const window = new BrowserWindow({ width: 1100, height: 750, show: true, alwaysOnTop: true });const panes: BrowserPane[] = [];const host = new BrowserHost({createPane: (onState, onOpenUrl) => {@@ -39,7 +42,15 @@ async function probe(artifactDir: string) {isPluginLoaded: () => true, getFileRoot: async () => null, onState: () => {},});try {- await window.loadURL("about:blank");+ await window.loadURL(`data:text/html,${encodeURIComponent(`<!doctype html>+ <style>body{margin:0;background:#202024;color:white;font:20px sans-serif}+ header{height:44px;padding-left:24px;display:flex;align-items:center}+ main{padding:24px}#panel{position:fixed;right:0;top:44px;bottom:0;width:44%;background:#121217}+ #toolbar{height:36px;background:#343440;padding-left:16px;display:flex;align-items:center}+ </style><header>PI browser window transition regression</header>+ <main>Conversation stays visible and clickable.</main>+ <section id=panel><div id=toolbar>Local HTML preview</div></section>`)}`);+ stage("shell-loaded");host.setWindow(window);host.setChromeSurface({ pluginId: "pi.browser", viewId: "browser", visible: true,bounds: { x: 0, y: 0, width: 1000, height: 700 } });@@ -49,12 +60,17 @@ async function probe(artifactDir: string) {resize(800, 500);host.setChromeSession("capture-regression", "page");await host.navigate({ url: `http://127.0.0.1:${address.port}` }, "capture-regression");+ stage("guest-loaded");const wc = panes[0].getWebContents();assert(wc);+ window.moveTop();+ window.focus();+ wc.setBackgroundThrottling(false);const frame = () => wc.executeJavaScript("new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))",);await frame();+ stage("guest-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@@ -71,6 +87,7 @@ async function probe(artifactDir: string) {};const results = [];for (let i = 0; i < 12; i++) {+ stage(`capture-${i}`);const expected = i % 2 ? { width: 820, height: 510 } : { width: 960, height: 620 };resizeDuringCapture = expected;const raw = i >= 6;@@ -85,21 +102,119 @@ async function probe(artifactDir: string) {results.push({ entry: raw ? "raw-cdp" : "screenshot", expected, actual });}wc.debugger.sendCommand = originalSend;+ const presentation = (views: readonly View[]): { view: View; parents: View[] } | undefined => {+ for (const view of views) {+ if (view instanceof WebContentsView && view.webContents === wc) return { view, parents: [] };+ const child = presentation(view.children);+ if (child) return { view: child.view, parents: [view, ...child.parents] };+ }+ return undefined;+ };+ const measuredPanel = async () => {+ const rect: { x: number; y: number; width: number; height: number } =+ await window.webContents.executeJavaScript(`new Promise(resolve => requestAnimationFrame(() => {+ const {x,y,width,height} = document.querySelector('#panel').getBoundingClientRect();+ resolve({x:Math.round(x), y:Math.round(y), width:Math.round(width), height:Math.round(height)});+ }))`);+ host.setChromeSurface({ pluginId: "pi.browser", viewId: "browser", visible: true, bounds: rect });+ const hole = { x: 0, y: 36, width: rect.width, height: rect.height - 36 };+ host.setGuestHole("pi.browser", hole);+ return { x: rect.x, y: rect.y + hole.y, width: hole.width, height: hole.height };+ };+ await measuredPanel();+ await frame();+ const transitions = [];+ const nativeScreenshots: string[] = [];+ const nativeScreenshot = async (name: string) => {+ // OS-wide capture enumerates unrelated desktop windows and can block on+ // unavailable WGC sources. Keep visual collection explicit; native guest+ // placement and viewport assertions always run.+ if (process.env.BROWSER_CAPTURE_NATIVE_SCREENSHOTS !== "1") return;+ const sources = await desktopCapturer.getSources({ types: ["window"], thumbnailSize: { width: 2600, height: 1500 } });+ const source = sources.find((source) => source.id === window.getMediaSourceId());+ assert(source, "test window native capture source");+ assert(!source.thumbnail.isEmpty(), "native window capture is empty");+ writeFileSync(join(artifactDir, name), source.thumbnail.toPNG());+ nativeScreenshots.push(name);+ };+ for (const mode of ["maximize", "restore", "fullscreen", "leave-fullscreen"] as const) {+ stage(mode);+ const before: { width: number; height: number } = await wc.executeJavaScript(+ "({width: innerWidth, height: innerHeight})",+ );+ let release!: () => void;+ let entered!: () => void;+ const gate = new Promise<void>((resolve) => { release = resolve; });+ const started = new Promise<void>((resolve) => { entered = resolve; });+ wc.debugger.sendCommand = (method, params, sessionId) => {+ const response = originalSend(method, params, sessionId);+ if (method !== "Page.captureScreenshot") return response;+ entered();+ return Promise.all([response, gate]).then(([result]) => result);+ };+ const capture = host.screenshot({ fullPage: true });+ await started;+ try {+ const event = mode === "maximize" ? "maximize" : mode === "restore" ? "unmaximize"+ : mode === "fullscreen" ? "enter-full-screen" : "leave-full-screen";+ const changed = once(window, event);+ if (mode === "maximize") window.maximize();+ else if (mode === "restore") window.unmaximize();+ else window.setFullScreen(mode === "fullscreen");+ await changed;+ const expected = await measuredPanel();+ const surface = presentation(window.contentView.children);+ assert(surface, "browser guest must remain attached");+ let actual = surface.view.getBounds();+ for (const parent of [...surface.parents].reverse()) {+ const bounds = parent.getBounds();+ actual = { x: bounds.x + actual.x, y: bounds.y + actual.y,+ width: Math.min(actual.width, bounds.width - actual.x),+ height: Math.min(actual.height, bounds.height - actual.y) };+ }+ const viewport: unknown = await wc.executeJavaScript(+ "({width: innerWidth, height: innerHeight})",+ );+ await nativeScreenshot(`native-${mode}-during.png`);+ // During expansion the old captured viewport can be smaller than the+ // new panel, but it must be in the right place and never exceed it.+ assert.equal(actual.x, expected.x, `${mode}: guest x during capture`);+ assert.equal(actual.y, expected.y, `${mode}: guest y during capture`);+ assert(actual.width <= expected.width && actual.height <= expected.height, `${mode}: clip to panel`);+ assert.deepEqual(viewport, before, `${mode}: preserve capture viewport`);+ transitions.push({ mode, expected, during: actual, viewport });+ } finally {+ release();+ await capture;+ wc.debugger.sendCommand = originalSend;+ }+ await frame();+ const expected = await measuredPanel();+ // Native bounds updates reach the guest renderer asynchronously. Wait+ // after the final measured layout has been applied, not before it.+ await frame();+ const restored: unknown = await wc.executeJavaScript(+ "({width: innerWidth, height: innerHeight})",+ );+ assert.deepEqual(restored, { width: expected.width, height: expected.height }, `${mode}: final viewport`);+ await nativeScreenshot(`native-${mode}-after.png`);+ }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 };+ const lifecycle = await checkBrowserPaneLifecycle(host, panes, window, `http://127.0.0.1:${address.port}`, stage);+ const report = { electron: process.versions.electron, chrome: process.versions.chrome, results, transitions, lifecycle, nativeScreenshots };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();+ if (!window.isDestroyed()) window.destroy();server.close();}}app.whenReady().then(() => probe(artifactDir)).then(() => app.exit(0),- (error: unknown) => { console.error(error); app.exit(1); },+ (error: unknown) => { stage(String(error)); console.error(error); app.exit(1); },);diff --git a/scripts/e2e/browser-pane-lifecycle.ts b/scripts/e2e/browser-pane-lifecycle.tsnew file mode 100644index 000000000..92d88950d--- /dev/null+++ b/scripts/e2e/browser-pane-lifecycle.ts@@ -0,0 +1,168 @@+import assert from "node:assert/strict";+import { once } from "node:events";+import { WebContentsView, type BrowserWindow, type View } from "electron";+import type { BrowserHost, BrowserRect } from "../../apps/desktop/electron/main/browser-host";+import type { BrowserPane } from "../../apps/desktop/electron/main/browser-view";++/** Additional native regressions for the container introduced around each guest. */+export async function checkBrowserPaneLifecycle(+ host: BrowserHost, panes: BrowserPane[], window: BrowserWindow, url: string,+ stage: (name: string) => void,+): Promise<string[]> {+ const passed: string[] = [];+ const rect = { x: 570, y: 90, width: 420, height: 490 };+ const show = (bounds: BrowserRect = rect) => {+ host.setChromeSurface({ pluginId: "pi.browser", viewId: "browser", visible: true, bounds });+ host.setGuestHole("pi.browser", { x: 0, y: 0, width: bounds.width, height: bounds.height });+ };+ const attached = () => {+ const result: number[] = [];+ const visit = (views: readonly View[]) => {+ for (const view of views) {+ if (!view.getVisible()) continue;+ if (view instanceof WebContentsView) result.push(view.webContents.id);+ visit(view.children);+ }+ };+ visit(window.contentView.children);+ return result;+ };+ const viewport = (pane: BrowserPane) => {+ const wc = pane.getWebContents();+ assert(wc);+ return wc.executeJavaScript(+ "new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve({width:innerWidth,height:innerHeight}))))",+ );+ };+ const hold = async (pane: BrowserPane, raw = false) => {+ const wc = pane.getWebContents();+ assert(wc);+ const original = wc.debugger.sendCommand.bind(wc.debugger);+ let release!: () => void;+ let fail!: (error: Error) => void;+ let entered!: () => void;+ const started = new Promise<void>((resolve) => { entered = resolve; });+ const gate = new Promise<void>((resolve, reject) => { release = resolve; fail = reject; });+ let count = 0;+ wc.debugger.sendCommand = (method, params, sessionId) => {+ const response = original(method, params, sessionId);+ if (method !== "Page.captureScreenshot") return response;+ count++;+ // Hold delivery of a real completed Chromium capture. Detaching before+ // Chromium has produced its frame would test platform capture liveness+ // rather than the pane's pending-completion lifecycle.+ return response.then(async result => { entered(); await gate; return result; });+ };+ const result = (raw+ ? host.cdpCommand("Page.captureScreenshot", { format: "png" })+ : host.screenshot({ fullPage: true })+ ).then(value => ({ value, error: undefined }), error => ({ value: undefined, error }));+ await started;+ return { release, fail, result, count: () => count, restore: () => { wc.debugger.sendCommand = original; } };+ };++ stage("lifecycle-queue");+ show();+ host.setChromeSession("lifecycle", "first");+ await host.navigate({ url }, "lifecycle");+ const first = panes.at(-1)!;+ const firstWc = first.getWebContents();+ assert(firstWc);+ const initial = await viewport(first);+ const capture = await hold(first);+ try {+ const queued = host.cdpCommand("Page.captureScreenshot", { format: "png" });+ host.setChromeSession("lifecycle", "second");+ await host.navigate({ url: url + "/second" }, "lifecycle");+ const second = panes.at(-1)!;+ assert.deepEqual(attached(), [second.getWebContents()!.id]);+ await host.screenshot();+ assert.equal(capture.count(), 1, "other pages do not start a queued capture");+ host.setChromeSession("another-session", "third");+ await host.navigate({ url: url + "/third" }, "another-session");+ assert.deepEqual(attached(), [panes.at(-1)!.getWebContents()!.id]);+ host.setChromeSession("lifecycle", "first");+ show({ x: 680, y: 110, width: 300, height: 360 });+ assert.deepEqual(attached(), [firstWc.id]);+ assert.deepEqual(await viewport(first), initial);+ capture.release();+ assert.equal((await capture.result).error, undefined);+ await queued;+ assert.equal(capture.count(), 2);+ assert.deepEqual(await viewport(first), { width: 300, height: 360 });+ passed.push("native queued captures, independent sibling/session pages and restored bounds");+ } finally { capture.release(); await capture.result; capture.restore(); }++ stage("lifecycle-hidden");+ const hidden = await hold(first, true);+ try {+ host.setChromeSurface(null);+ assert.deepEqual(attached(), [], "blocking overlays hide the presentation and guest");+ hidden.release();+ assert.equal((await hidden.result).error, undefined);+ assert.deepEqual(attached(), [], "capture completion must not expose a hidden page");+ show();+ assert.deepEqual(attached(), [firstWc.id]);+ assert.deepEqual(await viewport(first), { width: rect.width, height: rect.height });+ passed.push("native overlay hide, hidden completion and reshow");+ } finally { hidden.release(); await hidden.result; hidden.restore(); }++ stage("lifecycle-failure");+ const failed = await hold(first);+ try {+ show({ ...rect, x: 510, width: 480 });+ const failure = new Error("controlled screenshot failure");+ failed.fail(failure);+ assert.equal((await failed.result).error, failure);+ assert.deepEqual(await viewport(first), { width: 480, height: rect.height });+ } finally { failed.release(); await failed.result; failed.restore(); }+ await host.screenshot();+ passed.push("native failed capture restores bounds and next capture works");++ stage("lifecycle-close-tab");+ const closing = await hold(first);+ try {+ const rejected = assert.rejects(host.screenshot(), /browser guest is not available/);+ const destroyed = once(firstWc, "destroyed");+ host.closeTab("lifecycle", "first");+ await destroyed;+ assert(firstWc.isDestroyed());+ assert.deepEqual(attached(), []);+ host.setChromeSession("lifecycle", "replacement");+ await host.navigate({ url: url + "/replacement" }, "lifecycle");+ closing.release();+ await closing.result;+ await rejected;+ assert.equal(closing.count(), 1);+ await host.screenshot();+ passed.push("native tab close destroys guest, cancels queued capture and leaves replacement usable");+ } finally { closing.release(); await closing.result; }++ stage("lifecycle-recreate");+ const live = panes.at(-1)!;+ const liveWc = live.getWebContents();+ assert(liveWc);+ const closed = once(liveWc, "destroyed");+ liveWc.close();+ await closed;+ host.setChromeSession("lifecycle", "replacement");+ await host.navigate({ url: url + "/recreated" }, "lifecycle");+ assert.notEqual(live.getWebContents()!.id, liveWc.id);+ assert.deepEqual(attached(), [live.getWebContents()!.id]);+ assert.equal(window.contentView.children.length, 1, "destroyed guest must not leave an orphan container");+ await host.screenshot();+ passed.push("native destroyed guest can be recreated without an orphan container");++ stage("lifecycle-close-window");+ const closingWindow = await hold(live);+ try {+ window.destroy();+ host.setWindow(null);+ closingWindow.release();+ await closingWindow.result;+ assert(live.getWebContents() === null);+ host.dispose();+ passed.push("native window close during capture disposes safely and repeatedly");+ } finally { closingWindow.release(); await closingWindow.result; }+ return passed;+}