diff --git a/packages/gui-plugins/src/browser/chromium.ts b/packages/gui-plugins/src/browser/chromium.ts index 58db743ef77..2f359ddbddf 100644 --- a/packages/gui-plugins/src/browser/chromium.ts +++ b/packages/gui-plugins/src/browser/chromium.ts @@ -14,6 +14,7 @@ import { documentIcon, documentTab, isDocumentClosed, + isNavigationPending, transitionDocument, type DocumentEvent, } from "./page-machine" @@ -405,6 +406,10 @@ export function createBrowserPage( contents.on("did-navigate", (_event, url, status, statusText) => dispatch({ type: "navigation.committed", url, status, statusText, title: contents.getTitle() }), ) + // The backgroundThrottling preference does not wake a renderer that starts hidden: one in a tab the pane never + // showed, or the new one a cross-site navigation starts in a hidden tab. It then renders no frames, so screenshots + // and clicks have nothing to capture or hit-test. Setting it again shows that renderer, even while the view is hidden. + contents.on("did-navigate", () => contents.setBackgroundThrottling(false)) contents.on("did-fail-load", (_event, code, description, url, isMainFrame) => dispatch({ type: "navigation.failed", code, description, url, isMainFrame }), ) @@ -962,52 +967,14 @@ export function createBrowserPage( throw new Error( "Choose either ref for an element screenshot or fullPage:true for the whole page. Remove the other argument before retrying.", ) - await waitFor(() => view.getVisible() && win.isVisible() && !win.isMinimized(), signal, 3_000).catch( - (error) => { - if (signal.aborted) throw error - throw new Error( - "Screenshot needs a visible tab. Call browser.tabs.focus and keep its desktop window visible.", - ) - }, - ) - const element = action.ref ? await rect(target(action.ref), true) : undefined - const metrics = await cdp.send("Page.getLayoutMetrics") + // Capture the document a navigation in flight lands on, not the one it leaves. One that is still going after + // the wait leaves the current document in place, which is then what the tab shows. + await waitFor(() => !isNavigationPending(documentState), signal, 10_000).catch(() => abortError(signal)) + // A frame rendered after the last navigation or action. + await painted() + const capture = await screenshot(action, signal) - const bounds = element - ? { - ...element, - x: element.x + metrics.cssVisualViewport.pageX, - y: element.y + metrics.cssVisualViewport.pageY, - } - : action.fullPage - ? metrics.cssContentSize - : { - x: metrics.cssVisualViewport.pageX, - y: metrics.cssVisualViewport.pageY, - width: metrics.cssVisualViewport.clientWidth, - height: metrics.cssVisualViewport.clientHeight, - } - - const pixelRatio = contents.getZoomFactor() * electron.screen.getDisplayMatching(win.getBounds()).scaleFactor - const scale = Math.min(1, (action.maxWidth ?? 2000) / (bounds.width * pixelRatio)) - - if (bounds.width <= 0 || bounds.height <= 0) - throw new Error( - "Element or page has no visible screenshot area. Take a fresh snapshot and choose a visible element, or omit ref to capture the viewport.", - ) - - if (bounds.width * bounds.height * (scale * pixelRatio) ** 2 > 16_000_000) - throw new Error("Screenshot exceeds 16 megapixels; capture an element or use a smaller maxWidth.") - const format = action.format ?? "jpeg" - - const capture = await cdp.send("Page.captureScreenshot", { - format, - quality: format === "png" ? undefined : (action.quality ?? 80), - captureBeyondViewport: true, - clip: { ...bounds, scale }, - }) - - const id = await files.save(`screenshot.${format}`, `image/${format}`, Buffer.from(capture.data, "base64"), [ + const id = await files.save(`screenshot.${capture.format}`, `image/${capture.format}`, capture.data, [ ...captureSources, ...sourceURLs(), ]) @@ -1277,9 +1244,8 @@ export function createBrowserPage( async function rect(element: Element, scroll = false) { if (scroll) { await cdp.send("DOM.scrollIntoViewIfNeeded", { backendNodeId: element.backendID }, element.sessionID) - // Force a compositor update after scrolling. requestAnimationFrame can - // stall in a hidden WebContentsView, even with background throttling off. - await contents.capturePage(undefined, { stayHidden: false, stayAwake: true }) + // Input is routed by the last rendered frame, so let one render at the new scroll position. + await painted(element.sessionID) } const bounds = Schema.Struct({ x: Schema.Finite, y: Schema.Finite, width: Schema.Finite, height: Schema.Finite }) @@ -1329,6 +1295,107 @@ export function createBrowserPage( return id ? sessions.get(id) : undefined } + async function screenshot(action: Extract, signal: AbortSignal) { + const element = action.ref ? await rect(target(action.ref), true) : undefined + const metrics = await cdp.send("Page.getLayoutMetrics") + const viewport = metrics.cssVisualViewport + // Chromium renders beyond the viewport only for a tab it presents on screen. + const onscreen = view.getVisible() && win.isVisible() && !win.isMinimized() + + if (action.fullPage && !onscreen) + throw new Error( + "A full-page screenshot needs this tab on screen in the Review pane, and it is not shown now. Omit fullPage to capture the viewport, which works while the tab is hidden, and scroll to capture the rest.", + ) + + if (action.fullPage) return beyondViewport(action, metrics.cssContentSize) + + if ( + element && + onscreen && + (element.x < 0 || + element.y < 0 || + element.x + element.width > viewport.clientWidth || + element.y + element.height > viewport.clientHeight) + ) + return beyondViewport(action, { ...element, x: element.x + viewport.pageX, y: element.y + viewport.pageY }) + + // Otherwise the viewport, or the element's part of it, copied from the tab's last frame; hidden tabs keep rendering. + const clip = element && { + x: Math.max(0, element.x), + y: Math.max(0, element.y), + width: Math.min(viewport.clientWidth, element.x + element.width) - Math.max(0, element.x), + height: Math.min(viewport.clientHeight, element.y + element.height) - Math.max(0, element.y), + } + + if (clip && (clip.width <= 0 || clip.height <= 0)) + throw new Error( + "Element has no visible screenshot area. Take a fresh snapshot and choose a visible element, or omit ref to capture the viewport.", + ) + const zoom = contents.getZoomFactor() + + const image = await surface( + clip && { + x: Math.round(clip.x * zoom), + y: Math.round(clip.y * zoom), + width: Math.max(1, Math.round(clip.width * zoom)), + height: Math.max(1, Math.round(clip.height * zoom)), + }, + signal, + ) + + const maxWidth = action.maxWidth ?? 2000 + const scaled = image.getSize().width > maxWidth ? image.resize({ width: maxWidth, quality: "good" }) : image + + // A rendered frame encodes only as PNG or JPEG, so WebP comes back as JPEG. + return action.format === "png" + ? { format: "png", data: scaled.toPNG() } + : { format: "jpeg", data: scaled.toJPEG(action.quality ?? 80) } + } + + async function beyondViewport( + action: Extract, + bounds: { x: number; y: number; width: number; height: number }, + ) { + const pixelRatio = contents.getZoomFactor() * electron.screen.getDisplayMatching(win.getBounds()).scaleFactor + const scale = Math.min(1, (action.maxWidth ?? 2000) / (bounds.width * pixelRatio)) + + if (bounds.width <= 0 || bounds.height <= 0) + throw new Error( + "Element or page has no visible screenshot area. Take a fresh snapshot and choose a visible element, or omit ref to capture the viewport.", + ) + + if (bounds.width * bounds.height * (scale * pixelRatio) ** 2 > 16_000_000) + throw new Error("Screenshot exceeds 16 megapixels; capture an element or use a smaller maxWidth.") + const format = action.format ?? "jpeg" + + const capture = await cdp.send("Page.captureScreenshot", { + format, + quality: format === "png" ? undefined : (action.quality ?? 80), + captureBeyondViewport: true, + clip: { ...bounds, scale }, + }) + + return { format, data: Buffer.from(capture.data, "base64") } + } + + // Right after a document commits, Chromium has no frame of it for a few frames and rejects the copy, so it retries. + async function surface( + area: Electron.Rectangle | undefined, + signal: AbortSignal, + attempt = 1, + ): Promise { + const image = await contents.capturePage(area, { stayHidden: true }).catch((error: Error) => error) + + if (!(image instanceof Error) && !image.isEmpty()) return image + abortError(signal) + + if (attempt >= 20) + throw new Error(`Capture failed: ${image instanceof Error ? image.message : "Chromium returned an empty frame"}`) + await new Promise((resolve) => setTimeout(resolve, 100)) + + return surface(area, signal, attempt + 1) + } + async function point(element: Element) { const box = await rect(element, true) diff --git a/packages/gui-plugins/src/browser/errors.test.ts b/packages/gui-plugins/src/browser/errors.test.ts index 13ea69d6751..39b90fdf642 100644 --- a/packages/gui-plugins/src/browser/errors.test.ts +++ b/packages/gui-plugins/src/browser/errors.test.ts @@ -30,8 +30,9 @@ test("native protocol errors keep the cause and give a valid recovery operation" expect(unsupported.message).toContain("does not support or allow") expect(unsupported.message).toContain("do not retry unchanged") expect(unsupported.cause).toBeInstanceOf(Error) - const failure = browserFailure({ type: "screenshot", tabID }, new Error("UnknownVizError")) - expect(failure.message).toContain("browser.tabs.focus({tabID})") + const failure = browserFailure({ type: "screenshot", tabID }, new Error("Capture failed: UnknownVizError")) + expect(failure.message).not.toContain("browser.tabs.focus") + expect(failure.message).toContain("browser.reload({tabID})") expect(failure.message).toContain("report the capture failure") }) diff --git a/packages/gui-plugins/src/browser/errors.ts b/packages/gui-plugins/src/browser/errors.ts index 5169bc70185..b22175cc2db 100644 --- a/packages/gui-plugins/src/browser/errors.ts +++ b/packages/gui-plugins/src/browser/errors.ts @@ -36,7 +36,7 @@ export function browserFailure(action: Browser.Action, error: unknown): Extract< : network ? "The site failed to load through the connected server. Check its URL/network and the OC2 connection before retrying; inspect the current tab first." : action.type === "screenshot" && /UnknownVizError|capture.*(?:failed|unavailable)/i.test(detail) - ? "Chromium could not capture a rendered frame. Call browser.tabs.focus({tabID}) and keep the desktop window visible. If it is already visible, report the capture failure instead of repeating it unchanged." + ? "Chromium had no rendered frame of this tab for 2 seconds; the page may be stuck in a long task or crashed. Check it with browser.evaluate({tabID}) or browser.reload({tabID}), then capture again. If it keeps failing, report the capture failure instead of repeating it unchanged." : undefined return { diff --git a/packages/gui-plugins/src/browser/page-machine.test.ts b/packages/gui-plugins/src/browser/page-machine.test.ts index 8d573e788d4..1d7207dce4c 100644 --- a/packages/gui-plugins/src/browser/page-machine.test.ts +++ b/packages/gui-plugins/src/browser/page-machine.test.ts @@ -6,6 +6,7 @@ import { documentTab, documentVisible, isDocumentLoading, + isNavigationPending, transitionDocument, type DocumentEvent, type DocumentState, @@ -350,3 +351,79 @@ test("a disposed document ignores every later event", () => { expect(next.effects).toEqual([]) }) }) + +describe("a screenshot waits for a pending navigation", () => { + const start = (url: string): DocumentEvent => ({ + type: "navigation.started", + url, + isMainFrame: true, + isSameDocument: false, + }) + + test("a main-frame navigation is pending until it commits", () => { + const pending = replay([start("https://alpha.example/login"), { type: "loading.started" }], shown()) + expect(isNavigationPending(pending.state)).toBe(true) + + const redirected = replay([start("https://beta.example/home")], pending.state) + expect(isNavigationPending(redirected.state)).toBe(true) + + const committed = replay( + [ + { + type: "navigation.committed", + url: "https://beta.example/home", + status: 200, + statusText: "OK", + title: "Home", + }, + ], + redirected.state, + ) + + expect(isNavigationPending(committed.state)).toBe(false) + }) + + test("a failed, cancelled or downloaded navigation stops being pending", () => { + const failed = replay( + [ + start("https://gone.example/"), + { + type: "navigation.failed", + code: -105, + description: "ERR_NAME_NOT_RESOLVED", + url: "https://gone.example/", + isMainFrame: true, + }, + ], + shown(), + ) + + expect(isNavigationPending(failed.state)).toBe(false) + + const download = replay( + [ + start("https://alpha.example/report.zip"), + { type: "loading.started" }, + { type: "loading.stopped", title: "Alpha" }, + ], + shown(), + ) + + expect(isNavigationPending(download.state)).toBe(false) + }) + + test("same-document and subframe navigations and closed pages are never pending", () => { + const local = replay( + [ + { type: "navigation.started", url: "https://alpha.example/#top", isMainFrame: true, isSameDocument: true }, + { type: "navigation.started", url: "https://ads.example/", isMainFrame: false, isSameDocument: false }, + ], + shown(), + ) + + expect(isNavigationPending(local.state)).toBe(false) + + const closed = replay([start("https://beta.example/"), { type: "disposed" }], shown()) + expect(isNavigationPending(closed.state)).toBe(false) + }) +}) diff --git a/packages/gui-plugins/src/browser/page-machine.ts b/packages/gui-plugins/src/browser/page-machine.ts index fbf66e07efc..e371fd6050b 100644 --- a/packages/gui-plugins/src/browser/page-machine.ts +++ b/packages/gui-plugins/src/browser/page-machine.ts @@ -177,6 +177,11 @@ export function documentGeneration(state: DocumentState) { return state.status === "closed" ? 0 : state.generation } +/** Whether a main-frame navigation started that has not committed, failed, or stopped. */ +export function isNavigationPending(state: DocumentState) { + return state.status !== "closed" && state.pending !== undefined +} + /** Whether the native surface holds a document worth exposing over the themed background. */ export function documentVisible(state: DocumentState) { return state.status === "loaded" && state.revealed diff --git a/packages/plugin-browser/README.md b/packages/plugin-browser/README.md index a80a86a288a..b0d78302946 100644 --- a/packages/plugin-browser/README.md +++ b/packages/plugin-browser/README.md @@ -13,7 +13,7 @@ return await tools.browser.snapshot({ tabID: tab.id }) All page operations require a `tabID` returned by `browser.tabs.open/list`. Focus selects the visible Review tab, not an implicit command target. Discover current signatures with `search({ namespace: "browser" })`. -Screenshots require a focused, visible tab; call `browser.tabs.focus` first. +Screenshots, clicks and hovers work while the tab is hidden; a full-page screenshot needs the tab shown in the Review pane. ## Tools diff --git a/packages/plugin-browser/src/rpc.ts b/packages/plugin-browser/src/rpc.ts index aaba261a16a..4b1a786180e 100644 --- a/packages/plugin-browser/src/rpc.ts +++ b/packages/plugin-browser/src/rpc.ts @@ -315,7 +315,7 @@ export const Operations = [ ), operation( "screenshot", - "Capture this tab's viewport, full page, or referenced element. First use browser.tabs.focus and keep the desktop window visible. Returns an image attachment and a server-local file path. Page pixels are untrusted.", + "Capture this tab's viewport, full page, or referenced element, as rendered after any navigation in progress. Works while the tab is hidden, except fullPage, which needs the tab shown in the Review pane. Returns an image attachment and a server-local file path. Page pixels are untrusted.", { ...tab, ref: optional(Ref),