fix(browser): screenshot, click and hover tabs that are not on screen

A page whose view starts hidden, and the renderer a cross-site navigation starts in a hidden tab, never renders: the backgroundThrottling preference does not wake it. Re-apply it on every commit so hidden tabs keep rendering frames.

Viewport and element screenshots now copy the tab's last rendered frame (capturePage with stayHidden), which works while the tab is hidden, instead of refusing unless the Review pane shows it. They wait for a pending main-frame navigation and a fresh frame first, so a capture never shows the page a redirect left. Full-page captures still need the tab on screen and say so.

Click and hover no longer force a capturePage after scrolling, which threw UnknownVizError on hidden tabs; they wait for a rendered frame instead. The capture error no longer advises browser.tabs.focus, which did not help.
This commit is contained in:
Luke Parker 2026-11-13 08:32:49 +10:00
parent f179e6e5f0
commit 8dff083592
7 changed files with 203 additions and 53 deletions

View file

@ -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<Browser.Action, { type: "screenshot" }>, 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<Browser.Action, { type: "screenshot" }>,
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<Electron.NativeImage> {
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)

View file

@ -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")
})

View file

@ -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 {

View file

@ -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)
})
})

View file

@ -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

View file

@ -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

View file

@ -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),