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 <monarchmaisuriya7600@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
871c714b46
commit
3815e72359
5 files changed
+126
-4
No files matched your search
@@ -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.
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
@@ -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<T>(capture: () => Promise<T>): Promise<T> {
|
||||
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;
|
||||
|
||||
@@ -36,6 +36,7 @@ export interface TabContents {
|
||||
goForward(): void;
|
||||
reload(): void;
|
||||
captureFrame(signal: AbortSignal): Promise<TabImage>;
|
||||
decodePng(png: Uint8Array): TabImage;
|
||||
invalidate(): void;
|
||||
withFrameProduction<T>(capture: () => Promise<T>): Promise<T>;
|
||||
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)) {
|
||||
|
||||
Reference in new issue
Block a user