Skip to content

webview: navigate/reload/goBack/goForward accept { waitUntil, timeout } - #30645

Closed
robobun wants to merge 5 commits into
mainfrom
farm/46eec509/webview-navigate-waituntil-timeout
Closed

robobun wants to merge 5 commits into
mainfrom
farm/46eec509/webview-navigate-waituntil-timeout

Conversation

@robobun

@robobun robobun commented May 13, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • await view.navigate(url) settles only on Page.loadEventFired. A page that keeps a subresource open (SSE, a hung <img>) never fires load, so the await hangs.
  • There is no timeout. Playwright and Puppeteer expose both options on goto().

Fix

  • navigate, reload, goBack, goForward take { waitUntil: "load" | "domcontentloaded", timeout } (defaults "load", 30000 ms, 0 disables). WebKit: "domcontentloaded" degrades to "load" (no DCL delegate hook).
  • Chrome: the attach chain enables Page.lifecycleEvent. A "domcontentloaded" wait settles when the event's frameId and loaderId match the main frame's last Page.frameNavigated; replayed and subframe events never match. "load" still uses Page.loadEventFired.
  • Timeout: JSWebView::armNavTimeout schedules a WTF::RunLoop::dispatchAfter closure keyed by {viewId, generation}. Settling the Navigate slot bumps m_navGeneration, so a late timer does nothing. Navigate-slot Pending entries carry their generation, so a stale reply cannot settle a retry.
  • Verified: test/js/bun/webview/webview-navigate-options.test.ts (new, mock CDP, 8 tests, no Chrome) and 5 real-Chrome tests in webview-chrome.test.ts (all 63 pass). Also the rest of test/js/bun/webview/ and bun-types.test.ts.

Background

  • JSWebView holds one pending promise per slot (m_pendingNavigate, ...). The Chrome backend maps each CDP command id to a Pending { method, slot, viewId } entry and settles that slot on reply.
  • CDP Page.lifecycleEvent reports DOMContentLoaded, load, networkIdle per frame and loaderId (one per document load). Enabling it replays the current document's events, hence the loaderId match.
  • WTF::RunLoop::dispatchAfter is WebKit's delayed dispatch, backed by WTFTimer on bun's event loop. The timer has no cancel handle; the generation counter is the cancel.
Notes

History. Opened 2026-05-13, all CI lanes green on build #54352, closed by the stale bot on 2026-09-02, reopened and rebased onto main@6f27257 the same day. The rebase had one conflict: JSWebViewConstructor.cpp now marks the constructor's navigate promise handled (#40992). Both are kept: markAsHandled() and timeoutMs=0 for the constructor's initial navigate. The generation bump moved into a shared takeSlot helper so rejectSlotAsHandled (close(), browser death) also invalidates an armed timer.

Real Chrome. Chrome refuses to start as root without --no-sandbox, so on a root container run the real-Chrome files with BUN_CHROME_PATH pointing at a wrapper script that adds the flag. The mock tests need nothing.

Mock transport. webview-navigate-options.test.ts drives the connect-mode transport with a Bun.serve WebSocket that speaks CDP. fake-chrome-fixture.ts (pipe mode) exists on main for the spawn path. Both fakes stay: the ws mock is the only CI coverage of connect mode, and the lifecycle scenarios (DCL-only, silent, stale load) are per-test behaviours that would need several new fixture flags.

Gate. With src/ at base, webview-navigate-options.test.ts fails 7 of 8 (the default-load test passes). With the fix, 8 of 8.

Deferred, needs a maintainer's scope call.

  • WebKit timeout does not reset the host's m_navPending. After a timeout the next navigate() rejects with "navigation already pending". Needs a new Op::CancelNavigate IPC message. view.close() works.
  • A stale Page.frameNavigated can re-arm the event gate in the sub-millisecond window where the timeout fires as the old navigation commits and the user retries in .catch(). Needs the expected loaderId from the Page.navigate reply (Playwright's LifecycleWatcher), which Page.reload and navigateToHistoryEntry do not return.
  • A stale Target.attachToTarget reply does not close its tab (one round trip after createTarget set m_targetId). Needs targetId carried in Pending. webview: close the tab created by a Target.createTarget that was in flight at close() #39075 covers the close() side of this.
  • goBack/goForward do not set m_loading = true; reload() does.
  • view.title no longer refreshes on page-initiated navigations. view.url still does through frameNavigated.

no test proof · iteration 0 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/bun/webview/webview-chrome.test.ts

@robobun
robobun requested a review from alii as a code owner May 13, 2026 23:15
@coderabbitai

coderabbitai Bot commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

WebView navigation methods accept optional waitUntil and timeout options; lifecycle events (DOMContentLoaded or load) drive promise settlement, parent-side timeouts can reject navigations, and Chrome backend matches lifecycle events to committed frame/loader IDs.

Changes

WebView Navigation with waitUntil and Timeout Support

Layer / File(s) Summary
Navigation Options Contract and Type Definitions
packages/bun-types/bun.d.ts, src/runtime/webview/JSWebView.h
WebView.NavigateOptions interface with waitUntil and timeout. NavWaitUntil enum and JSWebView fields (m_navWaitUntil, m_navGeneration, m_frameId, m_loaderId) added; method signatures updated to accept these parameters.
Promise Settlement and Timeout Mechanism
src/runtime/webview/JSWebView.cpp
Implements generation-gated timeout arming (armNavTimeout, beginChromeNavigation) and dispatchAfter-based timeout rejection; settleSlot increments m_navGeneration to invalidate stale timers.
Chrome Backend Lifecycle Event Handling
src/runtime/webview/ChromeBackend.cpp
Enables Page.lifecycleEvent, records committed main-frame frameId/loaderId, matches lifecycle events to the pending navigation, and centralizes title-fetch via chainTitle() for settlement.
JavaScript API Binding, Parsing, and Constructor Wiring
src/runtime/webview/JSWebViewPrototype.cpp, src/runtime/webview/JSWebViewConstructor.cpp, packages/bun-types/bun.d.ts
Adds parseNavOptions (defaults waitUntil to "load"), updates WebView.prototype.navigate/goBack/goForward/reload to accept optional options and forward parsed waitUntil/timeout to native methods, and makes constructor initial navigations use NavWaitUntil::Load with timeoutMs=0.
Chrome Backend Integration Tests
test/js/bun/webview/webview-chrome.test.ts
Adds tests covering navigate/reload behavior with waitUntil and timeout against the Chrome backend, including hanging subresource scenarios and option validation.
Mock CDP Tests with Full Lifecycle Coverage
test/js/bun/webview/webview-navigate-options.test.ts
Subprocess-isolated mock CDP server tests that exercise DOMContentLoaded vs load settling, silent/timeouts, stale-event and stale-timer regressions, back-to-back navigate behavior, and synchronous option validation error cases.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the primary API change: WebView navigation methods now accept waitUntil and timeout options.
Description check ✅ Passed The description explains the problem, implementation, backend differences, timeout behavior, tests, verification results, and deferred issues. It does not use the exact template headings, but it provi…
Full details: Description check

Explanation

The description explains the problem, implementation, backend differences, timeout behavior, tests, verification results, and deferred issues. It does not use the exact template headings, but it provides the required information and is substantially complete.


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

@robobun

robobun commented May 13, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 7:28 PM PT - Sep 1st, 2026

✅ @robobun, your commit 3ad225378c07995dd376e62f8d32f1dd3f3d2079 passed in Build #109172! 🎉


🧪   To try this PR locally:

bunx bun-pr 30645

That installs a local version of the PR into your bun-30645 executable, so you can run:

bun-30645 --bun

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/runtime/webview/JSWebView.cpp`:
- Around line 320-359: The comment says timeouts are armed for symmetry but in
JSWebView::goBack, JSWebView::goForward, and JSWebView::reload the WK_DISPATCH
path returns directly so armNavTimeout(g, timeoutMs) is never called; either
update the comment to state WebKit doesn't arm the timeout, or change the
WK_DISPATCH branches to mirror navigate by saving the promise, calling
armNavTimeout(g, timeoutMs), then returning that promise (i.e., follow
navigate's pattern) so behavior matches the comment; reference the WK_DISPATCH
macro, armNavTimeout, and the navigate implementation when making the change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 82a744d8-3bde-42f2-ae9d-10dca0d6447d

📥 Commits

Reviewing files that changed from the base of the PR and between b9c757b and a6d1fe0.

📒 Files selected for processing (8)
  • packages/bun-types/bun.d.ts
  • src/runtime/webview/ChromeBackend.cpp
  • src/runtime/webview/JSWebView.cpp
  • src/runtime/webview/JSWebView.h
  • src/runtime/webview/JSWebViewConstructor.cpp
  • src/runtime/webview/JSWebViewPrototype.cpp
  • test/js/bun/webview/webview-chrome.test.ts
  • test/js/bun/webview/webview-navigate-options.test.ts

Comment thread src/runtime/webview/JSWebView.cpp Resolved
Comment thread src/runtime/webview/ChromeBackend.cpp Resolved
Comment thread packages/bun-types/bun.d.ts Resolved
Comment thread src/runtime/webview/JSWebView.cpp Resolved

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/runtime/webview/JSWebViewPrototype.cpp`:
- Around line 243-255: The code currently coerces non-number JS values for
options.timeout via toNumber(); change it to reject any non-number (except
undefined) the same way waitUntil does: after retrieving t (from o->get(...,
"timeout")), if t.isUndefined() skip, otherwise require t.isNumber() and if not
call Bun::ERR::INVALID_ARG_VALUE (using "options.timeout"_s and t) and return
false; then call t.toNumber(g), check RETURN_IF_EXCEPTION, validate finiteness
and non-negativity, and clamp into timeout as before.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 5a93f631-b47b-421c-b2f8-d91884de81cd

📥 Commits

Reviewing files that changed from the base of the PR and between a6d1fe0 and 2092e2f.

📒 Files selected for processing (6)
  • packages/bun-types/bun.d.ts
  • src/runtime/webview/ChromeBackend.cpp
  • src/runtime/webview/JSWebView.cpp
  • src/runtime/webview/JSWebViewConstructor.cpp
  • src/runtime/webview/JSWebViewPrototype.cpp
  • test/js/bun/webview/webview-navigate-options.test.ts

Comment thread src/runtime/webview/ChromeBackend.cpp Resolved
Comment thread src/runtime/webview/JSWebView.cpp Resolved

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/runtime/webview/ChromeBackend.cpp`:
- Around line 1204-1206: The branch handling the "Page.loadEventFired" event
must not clear view->m_loading for a stale/cleared loader; modify the check so
m_loading is only set to false when the current loader is still active (e.g.,
require that view->m_loaderId is non-empty or otherwise matches the event's
loader id) before clearing m_loading and calling chainTitle; update the
Page.loadEventFired handling in ChromeBackend.cpp to gate setting
view->m_loading = false behind the loader-id validity check (and then call
chainTitle() only as before when view->m_pendingNavigate is true).

In `@src/runtime/webview/JSWebView.cpp`:
- Around line 348-377: The Chrome branches for JSWebView::reload and
JSWebView::goBack/JSWebView::goForward must set the view loading flag the same
way navigate() does: set m_loading (or call the same setter navigate() uses) to
true when beginning a Chrome navigation (i.e. before calling
CDP::Ops::reload/goBack/goForward and before armNavTimeout), and for the
history-path that queries Page.getNavigationHistory ensure you set m_loading =
true when the history response confirms there is an entry to traverse to; this
will keep view.loading in sync with in-flight Chrome reload/history navigations.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 5482aa6a-e445-4dee-a7d2-5086baecfde9

📥 Commits

Reviewing files that changed from the base of the PR and between 2092e2f and b52522d.

📒 Files selected for processing (4)
  • src/runtime/webview/ChromeBackend.cpp
  • src/runtime/webview/JSWebView.cpp
  • src/runtime/webview/JSWebViewConstructor.cpp
  • test/js/bun/webview/webview-navigate-options.test.ts

Comment thread src/runtime/webview/ChromeBackend.cpp Resolved
Comment thread src/runtime/webview/JSWebView.cpp Resolved
@robobun

robobun commented May 14, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: reopened 2026-09-02, rebased onto main, waiting on CI and a maintainer

The stale bot closed this PR after 90 days without a maintainer response. Reopened, squashed, and rebased onto main@6f27257 as 74c1c44. The feature is still absent on main. Two follow-up commits (b5e1ffe, 55ea54b) cut every comment this PR adds under src/ to one line, for the comment-length check; no code change.

Reproduction

  • webview-navigate-options.test.ts drives the connect-mode transport with a mock CDP WebSocket. With src/ at base it fails 7 of 8 (the default-load test passes). With the fix, 8 of 8.
  • Real Chrome (now available here): all 63 tests in webview-chrome.test.ts pass, including the five this PR adds. Chrome needs --no-sandbox when run as root, so the real-Chrome files run with BUN_CHROME_PATH pointing at a wrapper that adds the flag.
  • Also green: the rest of test/js/bun/webview/ (32 pass, 62 skip on Linux, 6 todo) and test/integration/bun-types/bun-types.test.ts.

Rebase notes

PR: #30645

Comment thread src/runtime/webview/ChromeBackend.cpp Resolved
Comment thread src/runtime/webview/ChromeBackend.cpp Resolved
Comment thread src/runtime/webview/ChromeBackend.cpp Resolved
Comment thread src/runtime/webview/ChromeBackend.cpp Resolved
Comment thread src/runtime/webview/ChromeBackend.cpp Resolved
Comment thread src/runtime/webview/JSWebView.cpp Resolved
@github-actions

github-actions Bot commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Closing this PR because it has been inactive for more than 90 days.

@github-actions github-actions Bot closed this Sep 2, 2026
`waitUntil: "load" | "domcontentloaded"` (default "load") picks the
milestone that settles the returned promise. `timeout` (default 30000
ms, 0 disables it) rejects the promise with "Navigation timeout of
<n>ms exceeded".

Chrome backend: Page.setLifecycleEventsEnabled is sent once per
session. Page.lifecycleEvent settles a "domcontentloaded" wait when
the main frame's loaderId (captured from Page.frameNavigated) reaches
DOMContentLoaded or load. Page.loadEventFired keeps settling "load".
A generation counter on the view invalidates the timeout timer once
the Navigate slot settles, including the close() path through
rejectSlotAsHandled. Every Navigate-slot CDP response carries the
generation it was sent under, so a reply for a timed-out navigation
cannot settle a later retry; a stale Target.createTarget reply closes
the tab it created.

WebKit backend: accepts the options. "domcontentloaded" behaves like
"load" (no separate delegate hook). The timeout applies.

Types: add WebView.NavigateOptions. Rename back()/forward() to the
runtime's goBack()/goForward().
@robobun robobun reopened this Sep 2, 2026
Comment thread src/runtime/webview/ChromeBackend.cpp Resolved
Comment thread src/runtime/webview/ChromeBackend.cpp Resolved
Comment thread src/runtime/webview/ChromeBackend.cpp Resolved
Comment thread src/runtime/webview/ChromeBackend.cpp Resolved
Comment thread src/runtime/webview/ChromeBackend.cpp Resolved
Comment thread src/runtime/webview/ChromeBackend.cpp Resolved
Comment thread src/runtime/webview/ChromeBackend.cpp Resolved
Comment thread src/runtime/webview/ChromeBackend.cpp Resolved
Comment thread src/runtime/webview/JSWebView.cpp Resolved
Comment thread src/runtime/webview/JSWebView.cpp Resolved
Comment thread src/runtime/webview/JSWebView.cpp Resolved
Comment thread src/runtime/webview/JSWebView.cpp Resolved
Comment thread src/runtime/webview/JSWebView.cpp Resolved
Comment thread src/runtime/webview/JSWebView.cpp Resolved
Comment thread src/runtime/webview/JSWebView.cpp Resolved
Comment thread src/runtime/webview/JSWebView.h Resolved
Comment thread src/runtime/webview/JSWebView.h Resolved
Comment thread src/runtime/webview/JSWebView.h Resolved
Comment thread src/runtime/webview/JSWebView.h Resolved
Comment thread src/runtime/webview/JSWebView.h Resolved

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

Additional findings (outside the current diff — GitHub can't attach inline comments there):

  • 🔴 src/runtime/webview/ChromeBackend.cpp:1230 — view.title no longer updates after page-initiated navigations (link click, window.location=, meta refresh): on base, Page.loadEventFired chained a PageTitle fetch unconditionally so "the PageTitle handler settles a no-op and m_title still updates"; the new view->m_pendingNavigate guard skips chainTitle() when no user navigate is pending, leaving m_title stale forever. Fix: drop the m_pendingNavigate gate and rely on navGen — an idle chainTitle() stamps the current generation, and any later navigate() bumps it via beginChromeNavigation(), so the stale response is already dropped at the entry.navGen != view->m_navGeneration check.

    Extended reasoning...

    Base (11a2e2c) Page.loadEventFired handler: view->m_loading = false; then unconditionally enqueues Method::PageTitle; its response handler at line 842 writes view->m_title and settle() no-ops when the Navigate slot is empty — the base comment explicitly documents this: "If no navigate is pending (uninitiated navigation, redirect), the PageTitle handler settles a no-op and m_title still updates." After this PR, line 1230 is if (view->m_pendingNavigate && !view->m_navTitleChained) chainTitle();. Scenario: await view.navigate(pageA) resolves (settleSlot clears m_pendingNavigate); the page then does location.href = pageB. Chrome emits Page.frameNavigated (sets m_loaderId, updates m_url) and Page.loadEventFired; m_loaderId is non-empty so m_loading=false runs, but m_pendingNavigate is null so chainTitle() is skipped and view->m_title still holds pageA's title. m_title is written nowhere else in ChromeBackend.cpp. The comment justifies the guard as preventing an idle PageTitle from racing a later navigate(), but that race is already closed by the…

    Verification: normal — this is a regression against base. Base (11a2e2c) Page.loadEventFired handler, lines 1119-1123: ```cpp if (method.size() == 19 && memcmp(method.data(), "Page.loadEventFired", 19) == 0) { view->m_loading = false; uint32_t tid = nextId(); m_pending.add(tid, Pending { Method::PageTitle, PendingSlot::Navigate, view->m_viewId }); send(tid, Command(tid,… | normal —…

The loadEventFired handler gated the title fetch on a pending
navigate(), so a link click or location.href left m_title stale. Drop
the gate: the fetch's navGen entry already protects a later navigate()
from the stale reply, and the settle is a no-op when no navigate is
pending. Reset the per-document dedupe flag on each main-frame commit
so consecutive page-initiated navigations each fetch once.
@robobun

robobun commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

Confirmed, fixed in 0718511. The loadEventFired handler gated chainTitle() on m_pendingNavigate, so a page-initiated navigation left view.title stale. The gate is gone: the navGen stamp on the PageTitle entry already drops a reply that races a later navigate(), and the settle is a no-op when no navigate is pending. The gate removal alone was not enough: m_navTitleChained stayed set after a completed navigate(), so frameNavigated now resets it on each main-frame commit. A new mock-CDP test drives two consecutive page-initiated navigations. It fails before the fix (title stays stale) and passes after.

Comment thread src/runtime/webview/ChromeBackend.cpp Resolved
A first-navigate timeout that fired between the Target.attachToTarget
reply and the Page.enable reply made the stale-generation gate drop the
Page.enable reply. That reply handler was the only sender of
Runtime.enable and Page.setLifecycleEventsEnabled, so the session lost
console events and waitUntil:'domcontentloaded' forever. Send both
fire-and-forget commands from the attach handler, next to Page.enable.
The dropped reply now only skips the timed-out Page.navigate.
Comment thread src/runtime/webview/ChromeBackend.cpp Resolved
@robobun

robobun commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

Confirmed, fixed in 3ad2253. The PageEnable reply handler was the only sender of Runtime.enable and Page.setLifecycleEventsEnabled, so a first-navigate timeout that fired mid-attach dropped that reply at the stale gate and the session permanently lost console and lifecycle events. Both fire-and-forget commands now go out from the Target.attachToTarget handler, next to Page.enable. The dropped reply then only skips the timed-out Page.navigate, which is the correct cost. New mock-CDP test: the mock holds the Page.enable reply for 2s and only emits lifecycleEvent if it received setLifecycleEventsEnabled. It fails before the fix (the second navigate with waitUntil:'domcontentloaded' times out) and passes after. Full file: 10/10.

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

Code review found no issues

No high-confidence issues detected in this change.

@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-09-02.

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