Skip to content

webview: size the Chrome page viewport with a device metrics override instead of the window - #39090

Closed
robobun wants to merge 1 commit into
mainfrom
farm/cccb64d5/webview-chrome-initial-viewport
Closed

robobun wants to merge 1 commit into
mainfrom
farm/cccb64d5/webview-chrome-initial-viewport

Conversation

@robobun

@robobun robobun commented Aug 15, 2026

Copy link
Copy Markdown
Collaborator

Problem

  • new Bun.WebView({ backend: "chrome", width: W, height: H }) gives a page whose innerHeight is H - 87 on full Chrome/Chromium (what CI installs, and what find_chrome prefers over the Playwright headless shell); innerWidth is W. Screenshots come out W x (H - 87) too. With google-chrome-stable 151 here: 400x300 requested, {w: 400, h: 213} reported, PNG 400x213. Only await view.resize(W, H) makes the viewport exact.
  • Cause: CDP::Ops::navigate (src/runtime/webview/ChromeBackend.cpp, first-navigate branch) passed width/height to Target.createTarget, and nothing else sized the page. Those parameters size the window. chrome-headless-shell gives the page the whole window, so it looked right there; full Chrome's headless mode keeps ~87px of the window for its (invisible) browser UI and clamps the window to a minimum size (500px wide here), so the page was short of the requested size.
  • Same window sizing also broke small views outright: a view shorter than Chrome's minimum window height came up with a 0x0 or visibilityState === "hidden" page (no frames: rAF never fires, screenshot() never resolves), and scroll(), which fires its wheel event at (width / 2, height / 2) of the constructor size, hit nothing. The same happens in backend.url (WebSocket) mode.

Fix

  • Transport::handleResponse, Target.attachToTarget arm: as soon as the page session exists, send Emulation.setDeviceMetricsOverride with the view's m_width/m_height (fire-and-forget, like Runtime.enable), ahead of Page.enable and the first Page.navigate. CDP handles a session's commands in order, so the override is in place before the navigation starts; the override is session state and persists across later navigations. resize() now builds the identical command through the same deviceMetricsOverride() helper, so construction and resize() agree by construction.
  • Target.createTarget no longer passes width/height; the window stays at Chrome's default size. newWindow: true stays: without it, each new view opens as a tab of the existing window and the already-open views become hidden background tabs.
  • Why this is right: the documented contract (ConstructorOptions.width/height, docs/runtime/webview.mdx) is the viewport size, and the device metrics override is the CDP mechanism for that; it is what resize() already used and what puppeteer and playwright send for every new page. The window size is the wrong knob: it is flavour dependent (headless shell vs full Chrome), clamped, and can produce a hidden page, while Chrome renders, screenshots and maps input for an emulated viewport of any size independently of the window (verified from 300x40 up to 2000x1500 in a default 800x600 window).
  • Observable side effect: outerWidth/outerHeight now report Chrome's default window size instead of tracking the requested size (same as puppeteer); in backend.url mode the new window opens at Chrome's default size with the W x H viewport inside it.
  • Tests, test/js/bun/webview/webview-chrome.test.ts ("Viewport size" section): viewport and screenshot dimensions equal the constructor size before any resize() and survive a second navigation; the url constructor option gets the same size; two views attached to one Chrome each get their own size; a 300x60 view renders and scroll() works; a 1600x1200 view (bigger than the default window) reports, screenshots and receives a far-corner click() at full size. Without the src change these five fail on full Chrome (h: 153 for 240, h: 1113 for 1200, 500x153 for 300x60, ...), with it the file passes (57 tests), five runs of the new tests in a row were stable, and the WebSocket transport was checked by hand against a Chrome started with --remote-debugging-port (exact before/after numbers in the details below). On chrome-headless-shell the new tests pass with or without the fix, since there the window and the page happen to coincide.
  • Test-only: the file now passes --no-sandbox when running as root (Chrome refuses to start as root without it, crbug.com/638180), which is how the suite runs inside containers; before this every Chrome test in the file failed there (45 of 52). Non-root runs, i.e. CI, are unaffected. Whether the runtime itself should do something for root users (Playwright disables the sandbox by default, puppeteer leaves it to the caller; today the user only sees "Chrome exited") is a separate question this PR does not take a position on.

Background

  • CDP (Chrome DevTools Protocol) is the JSON command protocol the Chrome backend drives Chrome with. A target is a tab; attaching to it yields a session id that page-level commands (Page.*, Emulation.*, Input.*) are addressed with. Commands sent on one session are processed in order. The first navigate() on a view runs the attach chain Target.createTarget -> Target.attachToTarget -> Page.enable -> Page.navigate, each step issued from the previous reply in Transport::handleResponse; view.resize() and every later operation talk to the session directly.
  • Emulation.setDeviceMetricsOverride makes the page lay out, paint and hit-test as if its viewport were exactly the given CSS size, whatever the window is; it is per session and survives navigations. Target.createTarget's width/height size the browser window the tab is created in.
  • chrome-headless-shell is the stripped headless binary Playwright/puppeteer download; "full Chrome" (google-chrome-stable, chromium) run with --headless keeps a simulated browser window, including the space its UI would occupy and its minimum window size, even though nothing is drawn. Bun's find_chrome prefers full Chrome from $PATH, and CI's bootstrap installs it.
Probe numbers (google-chrome-stable 151.0.7922.137, Debian 13)

Released bun, pipe transport (backend: { type: "chrome", url: false }), innerWidth x innerHeight / PNG IHDR after navigate():

requested 200x120 -> inner 200x33,   outer 500x120, png 200x33
requested 400x300 -> inner 400x213,  outer 500x300, png 400x213
requested 800x600 -> inner 800x513,  outer 800x600, png 800x513
requested 300x60  -> inner 0x0 / 500x73 / 500x153 (varies per run)
requested 300x40  -> inner 780x493; scroll() never resolved

Released bun vs this branch, WebSocket transport (backend: { type: "chrome", url: "ws://..." } against a Chrome started with --remote-debugging-port=0):

            released            this branch
320x240     320x153 / png same  320x240 / png 320x240
300x60      500x153 / png same  300x60  / png 300x60
1600x1200   1600x1113 / same    1600x1200 / png 1600x1200

This branch, pipe transport, per size: innerWidth x innerHeight, outerWidth x outerHeight, whether rAF fires, PNG size, scrollY after scroll(0, 100):

300x40    -> 300x40    outer 780x580 visible, raf ok, png 300x40,    scrolled 100
300x60    -> 300x60    outer 780x580 visible, raf ok, png 300x60,    scrolled 100
320x240   -> 320x240   outer 780x580 visible, raf ok, png 320x240,   scrolled 100
1600x1200 -> 1600x1200 outer 780x580 visible, raf ok, png 1600x1200, scrolled 100
2000x1500 -> 2000x1500 outer 780x580 visible, raf ok, png 2000x1500, scrolled 100

Raw CDP check of newWindow with three targets left open (override 320x240 / 400x300 / 500x350): without newWindow the first two report visibilityState "hidden" and rAF stops firing in them; with newWindow: true all three stay visible.

…sion attaches

The Chrome backend passed the constructor's width/height to
Target.createTarget, which sizes the window rather than the page. With
chrome-headless-shell the page gets the whole window, but full Chrome's
headless mode keeps about 87px of it for its invisible browser UI and
clamps small windows to a minimum size, so innerHeight and screenshots
were shorter than requested until the first resize().

Send Emulation.setDeviceMetricsOverride (the same command resize() uses)
as soon as Target.attachToTarget returns, before Page.enable and the
first Page.navigate. The override persists across navigations. Stop
sizing the window from createTarget: windows below Chrome's minimum
size came up hidden (0x0, no frames), and the override sizes the
viewport independently of the window anyway.

The chrome test file now passes --no-sandbox when running as root,
which Chrome requires; previously every test in it failed in that
environment.
@coderabbitai

coderabbitai Bot commented Aug 15, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@robobun, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 4 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: c4316ab7-2ca9-4f58-9d46-38aea1dd6886

📥 Commits

Reviewing files that changed from the base of the PR and between 88a6398 and 2b9be43.

📒 Files selected for processing (3)
  • src/runtime/webview/ChromeBackend.cpp
  • src/runtime/webview/JSWebView.h
  • test/js/bun/webview/webview-chrome.test.ts

Comment @coderabbitai help to get the list of available commands.

@robobun

robobun commented Aug 15, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 12:13 PM PT - Aug 15th, 2026

🔄 @robobun, the build for your commit 2b9be431 (Build #98209) was cancelled — waiting for the next build...

@robobun

robobun commented Aug 15, 2026

Copy link
Copy Markdown
Collaborator Author

Status: reproduced and fixed; waiting on CI and review.

  • Reproduced with the released bun (1.4.0-canary.1) and google-chrome-stable 151 on Linux: new Bun.WebView({ backend: { type: "chrome", url: false }, width: 400, height: 300 }) reports {w: 400, h: 213} for innerWidth/innerHeight after navigate(), and screenshot() is a 400x213 PNG. Same in backend.url (WebSocket) mode.
  • With this branch both are 400x300; test/js/bun/webview/webview-chrome.test.ts passes (57 tests), and its five new "Viewport size" tests fail on main's src on full Chrome.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reviewed this PR and didn't find any bugs. The fix is well-scoped — it moves the initial viewport sizing onto the same Emulation.setDeviceMetricsOverride path resize() already used, via a shared helper, and the tests cover the variant matrix (constructor, url option, multi-view, sub-minimum and over-default sizes). Because it changes user-visible behaviour (outerWidth/outerHeight and the visible window size in backend.url connect mode no longer track the requested size), a maintainer sign-off on that tradeoff would still be worthwhile.

What was reviewed

  • The fire-and-forget send(0, deviceMetricsOverride(...)) in the TargetAttachToTarget arm follows the existing Runtime.enable pattern; CDP session ordering guarantees it lands before Page.navigate.
  • resize() sets m_width/m_height before calling the helper, so reading them from view instead of the parameters is equivalent.
  • --no-sandbox is root-only and threaded through every subprocess test via chromeJson; the sibling webview-chrome-ws.test.ts was checked and does not spawn Chrome itself, so it does not need the same flag.
Extended reasoning...

Overview

This PR fixes Bun.WebView({ backend: "chrome", width, height }) so the page viewport actually matches the requested size on full Chrome/Chromium. Previously the constructor passed width/height to Target.createTarget, which sizes the window; full Chrome's headless mode reserves ~87px of the window for invisible browser UI and clamps to a minimum window size, so innerHeight and screenshots came out short (and tiny views could come up hidden entirely). The fix sends Emulation.setDeviceMetricsOverride as soon as the page session attaches — the same command resize() already used — and drops the window sizing from createTarget. resize() now shares a deviceMetricsOverride() helper so the two paths cannot drift. JSWebView.h changes are comment-only. The test file gains five viewport-size tests plus a root-only --no-sandbox flag threaded through every backend construction (in-process and subprocess).

Security risks

None. No untrusted input parsing, no auth/crypto/permissions. --no-sandbox is passed to Chrome only in the test file and only when process.getuid?.() === 0; CI runs as non-root so is unaffected, and the runtime's own spawn path is untouched.

Level of scrutiny

Moderate. The C++ change is small (~30 net lines) and follows existing patterns exactly — send(0, ...) for an untracked fire-and-forget matches Runtime.enable, and the WS-queue draining logic already treats id==0 as always-send. The interesting part is the behavioural tradeoff: outerWidth/outerHeight now report Chrome's default window size, and in backend.url connect mode (attaching to the user's visible Chrome) new windows open at Chrome's default size with the emulated viewport inside. The PR argues, with probe numbers and by reference to puppeteer/playwright, that this is the correct reading of the documented "viewport size" contract and that the previous behaviour was simply broken. I agree, but it is a user-visible API behaviour change that a maintainer should confirm.

Other factors

The PR description also explicitly leaves open whether the runtime (not just the tests) should pass --no-sandbox for root users, noting Playwright and puppeteer differ. That is out of scope here but flagged for a maintainer to note. No prior reviewer comments; no CODEOWNERS entry for src/runtime/webview/. The new tests use await using, drain subprocess pipes with Promise.all, rAF-poll instead of sleep, and assert exact viewport/PNG dimensions — they meet the repo's test-quality bar.

@robobun

robobun commented Aug 15, 2026

Copy link
Copy Markdown
Collaborator Author

Re the review above: agreed that the outerWidth/outerHeight change and the default-size window in backend.url mode are the one deliberate behaviour change here. Both are listed under "Observable side effect" in the Fix section so whoever merges can weigh them; keeping Target.createTarget's width/height in addition to the override would preserve outerWidth/outerHeight for sizes above Chrome's minimums, but would keep the hidden 0x0 window for sizes below them (the 300x60 / 300x40 probes in the description), which is why this PR drops it.

@robobun

robobun commented Sep 10, 2026

Copy link
Copy Markdown
Collaborator Author

This PR also fixes a screenshot() hang with several small Chrome views.

Repro (Linux, google-chrome-stable 153, bun 1.4.3 and main at 4ff9193):

const backend = { type: "chrome", url: false };
const server = Bun.serve({ port: 0, fetch: () => new Response("<body style='background:#fa0'>x</body>", { headers: { "content-type": "text/html" } }) });
const views = [0, 1, 2].map(() => new Bun.WebView({ backend, width: 80, height: 60 }));
await Promise.all(views.map((v, i) => v.navigate(`http://127.0.0.1:${server.port}/?${i}`)));
for (const [i, v] of views.entries()) {
  console.log(i, await v.evaluate("JSON.stringify({ vs: document.visibilityState, w: innerWidth, h: innerHeight })"));
  console.log(i, (await v.screenshot()).size); // stays pending for views 1 and 2
}

On main, view 0 reports {"vs":"hidden","w":780,"h":493} and its capture answers. Views 1 and 2 report {"vs":"visible","w":0,"h":0}. Chrome never answers Page.captureScreenshot for them, because a 0x0 page produces no frame. The screenshot() promise stays pending, and each later call throws Invalid state: a screenshot() is already pending. The cause is the window sizing that this PR removes: an 80x60 window is below full Chrome's minimum height, so the page gets no area. The same three views at 400x300 all capture fine on main.

With this branch merged into current main (it merges cleanly), all three views report {"vs":"visible","w":80,"h":60} and every capture answers. I also checked 3 views at 1x1 and at 300x40, and 4 views at 16x8.

The failures on build #98209 are not related to this diff (test/bake/deinitialization.test.ts on Windows, and install test flakes).

@robobun

robobun commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as stale: this PR conflicts with main, and its last commit is from 2026-08-15.

The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR.

@robobun robobun closed this Nov 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant