From 3815e72359be181c37d1866a251831132825e22d Mon Sep 17 00:00:00 2001 From: Monarch Maisuriya Date: Wed, 18 Nov 2026 11:17:31 +0530 Subject: [PATCH] fix(desktop): refuse browser screenshots with no painted pixels (#9807) Viewport and full-page browser screenshots wait for a frame with non-transparent pixels. When the page does not paint within the existing capture budget, the tool returns screenshot_no_frame. Fixes #9810. Co-authored-by: monarchmaisuriya Co-authored-by: Claude Opus 5.5 --- docs/browser-capture-harness.md | 5 +- .../features/browser-automation/ipc.test.ts | 24 +++++++ .../src/features/browser-automation/ipc.ts | 8 ++- .../browser-automation/service.test.ts | 67 +++++++++++++++++++ .../features/browser-automation/service.ts | 26 ++++++- 5 files changed, 126 insertions(+), 4 deletions(-) diff --git a/docs/browser-capture-harness.md b/docs/browser-capture-harness.md index f760fafa6..0458356b2 100644 --- a/docs/browser-capture-harness.md +++ b/docs/browser-capture-harness.md @@ -117,7 +117,10 @@ There is no renderer prep/restore handshake or lifetime background-throttling ov Screenshot capture temporarily enables frame production inside the shared serialized queue, restores the previous throttling policy on success or failure, and retains a 5-second capture budget. The browser tool takes one viewport frame through Electron's frame subscription and releases the -subscription on completion or cancellation. A resized resident guest can produce fresh pixels +subscription on completion or cancellation. Guest pages have a transparent base background, so a page +that has painted nothing yet (a dev server hiding `body` until its JS boots) produces frames where +every pixel is transparent. Both screenshot paths skip those frames and return `screenshot_no_frame` +when the capture budget expires without a painted one. A resized resident guest can produce fresh pixels while `capturePage()` leaves its surface-copy request pending; waiting for animation frames or retrying the copy does not repair that state. Full-page screenshots retain the CDP path with layout metrics and screenshot clip. diff --git a/packages/desktop/src/features/browser-automation/ipc.test.ts b/packages/desktop/src/features/browser-automation/ipc.test.ts index 427e86e1b..2ea5f599c 100644 --- a/packages/desktop/src/features/browser-automation/ipc.test.ts +++ b/packages/desktop/src/features/browser-automation/ipc.test.ts @@ -4,6 +4,8 @@ import { adaptWebContents, HostSnapshotEngineRegistry } from "./ipc.js"; import type { IsolatedKeyboardInputEvent } from "./trusted-input.js"; class FakeImage implements TabImage { + public constructor(private readonly alpha = 255) {} + public toPNG(): Uint8Array { return new Uint8Array([137, 80, 78, 71]); } @@ -11,6 +13,10 @@ class FakeImage implements TabImage { public getSize(): { width: number; height: number } { return { width: 640, height: 480 }; } + + public toBitmap(): Uint8Array { + return new Uint8Array([0, 0, 0, 0, 10, 20, 30, this.alpha]); + } } class FakeDebugger { @@ -268,6 +274,24 @@ describe("browser automation IPC adapter", () => { expect(contents.endedFrameSubscriptions).toBe(1); }); + test("skips frames with no painted pixels and captures the first painted frame", async () => { + const contents = new FakeWebContents(2004); + const tab = adaptWebContents(contents); + const controller = new AbortController(); + const capture = tab.captureFrame(controller.signal); + const unpainted = new FakeImage(0); + const painted = new FakeImage(255); + + contents.frameListener?.(unpainted); + expect(contents.frameListener).not.toBeNull(); + contents.frameListener?.(painted); + + expect(await capture).toBe(painted); + expect(contents.frameListener).toBeNull(); + controller.abort(); + expect(contents.endedFrameSubscriptions).toBe(1); + }); + test("cancels a pending frame subscription when the capture budget expires", async () => { const contents = new FakeWebContents(2001); const tab = adaptWebContents(contents); diff --git a/packages/desktop/src/features/browser-automation/ipc.ts b/packages/desktop/src/features/browser-automation/ipc.ts index 18e5b8454..5932ccd0b 100644 --- a/packages/desktop/src/features/browser-automation/ipc.ts +++ b/packages/desktop/src/features/browser-automation/ipc.ts @@ -1,4 +1,4 @@ -import { ipcMain } from "electron"; +import { ipcMain, nativeImage } from "electron"; import { BrowserAutomationExecuteRequestSchema } from "@getpaseo/protocol/browser-automation/rpc-schemas"; import type { BrowserAutomationConsoleLogEntry, @@ -15,7 +15,7 @@ import { promptShimInstallScript, promptShimRestoreScript, } from "./dialog-handling.js"; -import { BrowserTabClosedError, executeAutomationCommand } from "./service.js"; +import { BrowserTabClosedError, executeAutomationCommand, hasPaintedPixels } from "./service.js"; import { BrowserSnapshotEngine } from "./snapshot-engine.js"; import { listRegisteredPaseoBrowserIds, @@ -133,6 +133,7 @@ export function adaptWebContents(contents: BrowserAutomationWebContents): TabCon goForward: () => contents.goForward(), reload: () => contents.reload(), captureFrame: (signal) => captureViewportFrame(contents, signal), + decodePng: (png) => nativeImage.createFromBuffer(Buffer.from(png)), invalidate: () => contents.invalidate(), withFrameProduction: async (capture) => { const previous = contents.getBackgroundThrottling(); @@ -182,6 +183,9 @@ function captureViewportFrame( // A resized resident guest can paint while capturePage's surface-copy // request remains pending. Subscribe to its rendered frames instead. contents.beginFrameSubscription(false, (image) => { + // Keep the subscription open until the page has painted; the capture + // budget turns a page that never paints into screenshot_no_frame. + if (!hasPaintedPixels(image)) return; stop(); resolve(image); }); diff --git a/packages/desktop/src/features/browser-automation/service.test.ts b/packages/desktop/src/features/browser-automation/service.test.ts index d793e138b..5f892bbe5 100644 --- a/packages/desktop/src/features/browser-automation/service.test.ts +++ b/packages/desktop/src/features/browser-automation/service.test.ts @@ -22,6 +22,7 @@ class FakeImage implements TabImage { public constructor( private readonly bytes = new Uint8Array([137, 80, 78, 71, 1, 2, 3]), private readonly size = { width: 640, height: 480 }, + private readonly alpha = 255, ) {} public toPNG(): Uint8Array { @@ -31,8 +32,14 @@ class FakeImage implements TabImage { public getSize(): { width: number; height: number } { return this.size; } + + public toBitmap(): Uint8Array { + return new Uint8Array([0, 0, 0, 0, 10, 20, 30, this.alpha]); + } } +const UNPAINTED_FULL_PAGE_PNG = "unpaintedPng"; + class FakeTab implements TabContents { public withFrameProduction(capture: () => Promise): Promise { return capture(); @@ -77,6 +84,7 @@ class FakeTab implements TabContents { public fullPageScreenshotThrows = false; public fullPageScreenshotErrorMessage = "UnknownVizError"; public fullPageCaptureFailuresBeforeSuccess = 0; + public fullPageUnpaintedCapturesBeforePainted = 0; public layoutMetrics = { cssLayoutViewport: { clientWidth: 390, clientHeight: 844 }, cssContentSize: { width: 390, height: 1200 }, @@ -191,6 +199,11 @@ class FakeTab implements TabContents { this.actions.push("invalidate"); } + public decodePng(png: Uint8Array): TabImage { + const unpainted = Buffer.from(png).equals(Buffer.from(UNPAINTED_FULL_PAGE_PNG, "base64")); + return new FakeImage(png, { width: 390, height: 1200 }, unpainted ? 0 : 255); + } + public getConsoleMessages(): BrowserAutomationConsoleLogEntry[] { return this.consoleMessages; } @@ -218,6 +231,10 @@ class FakeTab implements TabContents { if (this.fullPageScreenshotThrows) { throw new Error(this.fullPageScreenshotErrorMessage); } + if (this.fullPageUnpaintedCapturesBeforePainted > 0) { + this.fullPageUnpaintedCapturesBeforePainted -= 1; + return { data: UNPAINTED_FULL_PAGE_PNG }; + } return { data: this.fullPageScreenshotData }; } if (command === "Runtime.evaluate") { @@ -2035,6 +2052,56 @@ describe("executeAutomationCommand", () => { } }); + test("screenshot with fullPage waits for a CDP image with painted pixels", async () => { + vi.useFakeTimers(); + try { + const browser = new BrowserAutomationHarness(); + browser.tab.fullPageUnpaintedCapturesBeforePainted = 1; + + const resultPromise = browser.execute({ + command: "screenshot", + args: { browserId: BROWSER_A, fullPage: true }, + }); + await vi.advanceTimersByTimeAsync(200); + + await expect(resultPromise).resolves.toMatchObject({ + ok: true, + result: { command: "screenshot", dataBase64: "fullPagePng" }, + }); + expect( + browser.tab.debugCommands.filter((entry) => entry.command === "Page.captureScreenshot"), + ).toHaveLength(2); + } finally { + vi.useRealTimers(); + } + }); + + test("screenshot with fullPage returns no-frame when the page never paints", async () => { + vi.useFakeTimers(); + try { + const browser = new BrowserAutomationHarness(); + browser.tab.fullPageUnpaintedCapturesBeforePainted = Number.POSITIVE_INFINITY; + + const resultPromise = browser.execute({ + command: "screenshot", + args: { browserId: BROWSER_A, fullPage: true }, + }); + await vi.advanceTimersByTimeAsync(5_000); + + await expect(resultPromise).resolves.toEqual({ + requestId: "req-screenshot", + ok: false, + error: { + code: "screenshot_no_frame", + message: "The tab has not painted yet. Retry the screenshot.", + retryable: true, + }, + }); + } finally { + vi.useRealTimers(); + } + }); + test("screenshot with fullPage surfaces ordinary CDP capture errors", async () => { const browser = new BrowserAutomationHarness(); browser.tab.fullPageScreenshotThrows = true; diff --git a/packages/desktop/src/features/browser-automation/service.ts b/packages/desktop/src/features/browser-automation/service.ts index 34a01ed07..5f038dd45 100644 --- a/packages/desktop/src/features/browser-automation/service.ts +++ b/packages/desktop/src/features/browser-automation/service.ts @@ -36,6 +36,7 @@ export interface TabContents { goForward(): void; reload(): void; captureFrame(signal: AbortSignal): Promise; + decodePng(png: Uint8Array): TabImage; invalidate(): void; withFrameProduction(capture: () => Promise): Promise; sendInputEvent(event: IsolatedKeyboardInputEvent): void; @@ -52,6 +53,22 @@ export interface TabContents { export interface TabImage { toPNG(): Uint8Array; getSize(): { width: number; height: number }; + // Raw 32-bit pixels. Alpha is the fourth byte of each pixel in BGRA and RGBA order alike. + toBitmap(): Uint8Array; +} + +// Electron guest pages have a transparent base background, so a page that has +// painted nothing yet (for example a dev server hiding body until its JS boots) +// yields a frame where every pixel is transparent. That frame is not a +// screenshot of the page. +export function hasPaintedPixels(image: TabImage): boolean { + const bitmap = image.toBitmap(); + for (let alpha = 3; alpha < bitmap.length; alpha += 4) { + if (bitmap[alpha] !== 0) { + return true; + } + } + return false; } export interface BrowserRegistry { @@ -1348,11 +1365,18 @@ async function executeFullPageScreenshot( const metrics = await getCdpLayoutMetrics(target.contents); width = metrics.contentWidth; height = metrics.contentHeight; - return (await sendDebugCommand("Page.captureScreenshot", { + const result = (await sendDebugCommand("Page.captureScreenshot", { format: "png", captureBeyondViewport: true, clip: { x: 0, y: 0, width, height, scale: 1 }, })) as CdpCaptureScreenshotResult; + if ( + result.data && + !hasPaintedPixels(target.contents.decodePng(Buffer.from(result.data, "base64"))) + ) { + throw new Error("Page.captureScreenshot returned no painted frame"); + } + return result; }); } catch (error) { if (isScreenshotNoFrameError(error)) {