From e406386d6c187190c16b927b78c5030f5de2cfb8 Mon Sep 17 00:00:00 2001 From: Vivek Date: Tue, 18 Aug 2026 11:17:05 +0530 Subject: [PATCH 1/3] chore: add guarded on-device levers to A/B the iOS back-swipe blank #1410 moved the history push ahead of the DOM mutation and merged with its iOS acceptance criterion openly unmet, because the gesture preview exists only on a real iPhone. The blank survived there, so the assumption behind that fix is still untested: that WebKit binds the back-forward snapshot synchronously at the pushState call. If it instead captures the compositing surface when the didSameDocumentNavigation IPC lands in the UI process, that happens after the whole push-swap-scroll task, and reordering inside the task changes nothing the device can see. Rather than guess again, ship the two candidate timings behind default-off levers and let the device choose, which is the method that finally isolated #610. ?raf and ?raf2 hand WebKit one or two frames to paint the outgoing page between the push and the swap; ?scrolllast defers the scroll-to-top past the frame to isolate the clamp from the swap. The yield sits in fetchAndApply rather than at the four commit points inside applySwap, because applySwap is synchronous and cannot await. The thunk is one-shot, so firing it in the caller covers whichever commit point the swap reaches and leaves that call a no-op, which is the same ordering at every one of them rather than at a chosen few. --- .../core/src/router-client/diagnostics.js | 45 +++++ .../core/src/router-client/fetch-apply.js | 83 +++++++-- .../browser/nav-swipe-ab-levers.test.js | 159 ++++++++++++++++++ .../core/test/routing/router-client.test.js | 69 ++++++++ website/app/layout.ts | 16 ++ 5 files changed, 357 insertions(+), 15 deletions(-) create mode 100644 packages/core/test/routing/browser/nav-swipe-ab-levers.test.js diff --git a/packages/core/src/router-client/diagnostics.js b/packages/core/src/router-client/diagnostics.js index 52912afb4..66067c887 100644 --- a/packages/core/src/router-client/diagnostics.js +++ b/packages/core/src/router-client/diagnostics.js @@ -339,6 +339,51 @@ export function warnIfSmoothScrollOnHtml() { ); } +/** + * #1428 diagnostic, TEMPORARY. Reads a guarded paint-timing lever an app sets + * on `window.__webjsDiag` (e.g. `{ raf: true }`) so the iOS back-swipe blank + * can be A/B'd on a real device. Default off, so the production nav path is + * byte-for-byte unchanged when nothing sets the object. + * + * The same shape as the #637 levers that isolated #610, and for the same + * reason: the symptom exists only on a real iPhone, where no harness we have + * can see it, so the only way to tell a candidate fix from a guess is to ship + * both behaviours behind a flag and let the device choose. + * + * @param {string} name + * @returns {boolean} + */ +export function diagFlag(name) { + try { return !!(typeof window !== 'undefined' && window.__webjsDiag && window.__webjsDiag[name]); } + catch { return false; } +} + +/** + * #1428 diagnostic, TEMPORARY. Resolve after `frames` animation frames, or + * `null` when there is no `requestAnimationFrame` to wait on (the unit runner's + * DOM shim), so a caller can `await` it unconditionally. + * + * Why a frame and not a microtask: the thing being tested is whether WebKit has + * COMPOSITED the outgoing page before it captures the back-forward snapshot. A + * microtask runs inside the same task and paints nothing, so only a frame + * boundary can tell the two hypotheses apart. + * + * @param {number} frames + * @returns {Promise | null} + */ +export function diagFrameYield(frames) { + if (typeof requestAnimationFrame !== 'function') return null; + return new Promise((resolve) => { + let left = frames; + const step = () => { + left -= 1; + if (left <= 0) resolve(undefined); + else requestAnimationFrame(step); + }; + requestAnimationFrame(step); + }); +} + /** * Nav-in-flight signalling. The router can expose `data-navigating` on * so an app may style a loading indicator with `html[data-navigating] { … }`. diff --git a/packages/core/src/router-client/fetch-apply.js b/packages/core/src/router-client/fetch-apply.js index 57d4a1797..88cef68a6 100644 --- a/packages/core/src/router-client/fetch-apply.js +++ b/packages/core/src/router-client/fetch-apply.js @@ -10,7 +10,7 @@ import { markStale, parseTagHeader } from '../action-cache-client.js'; import { renderStream } from '../webjs-stream.js'; import { buildHaveHeader } from './boundaries.js'; import { STREAM_MIME } from './constants.js'; -import { warnIfSmoothScrollOnHtml } from './diagnostics.js'; +import { diagFlag, diagFrameYield, warnIfSmoothScrollOnHtml } from './diagnostics.js'; import { restoreOptimistic } from './dom-differ.js'; import { parseHTML } from './dom-parse.js'; import { clearFrameBusy, markFrameBusy } from './frames.js'; @@ -307,6 +307,43 @@ export async function fetchAndApply(href, frameId, recordHistory, optimisticStat } : null; + // #1428 diagnostic, TEMPORARY (default off, so an app that sets nothing runs + // the path above byte for byte). #1410 put the push ahead of the mutation and + // the blank SURVIVED on a real iPhone, which leaves exactly one assumption + // behind that fix untested: that WebKit binds the gesture snapshot + // synchronously, at the `pushState` call. If it instead captures the + // compositing surface when the `didSameDocumentNavigation` IPC lands in the + // UI process, that happens only after this whole task (push, swap, + // scroll-to-top) has run, so reordering WITHIN the task changes nothing the + // device can see, and the fix would need a composited frame instead. These + // levers test that by handing WebKit a frame to paint the OUTGOING page + // between the push and the swap. + // + // The yield sits HERE rather than at the four commit points inside + // `applySwap` because that function is synchronous and cannot await. The + // thunk is one-shot, so calling it here fires the push for whichever commit + // point the swap goes on to reach and leaves that call a no-op, which is the + // same ordering at every one of them rather than at a chosen few. Tied to + // `recordHistoryNow` being non-null so the background paths (a revalidation, + // a refresh, the popstate restore) are untouched: they record no entry, so + // there is no snapshot to compose, and delaying them would move a second + // variable in a run that is trying to isolate one. + const diagFrames = diagFlag('raf2') ? 2 : diagFlag('raf') ? 1 : 0; + if (diagFrames && recordHistoryNow) { + recordHistoryNow(); + const painted = diagFrameYield(diagFrames); + if (painted) await painted; + // The yield reopens the supersede window the guard above just closed, so + // re-check rather than swapping in a document a newer navigation has + // already moved past. The push has landed by now and is not rolled back: + // the newer navigation pushes its own entry over it, and this is a + // diagnostic that only runs when a device A/B has opted in. + if (myToken !== currentNavigationToken) { + if (streamCtx && streamCtx.reader) { try { streamCtx.reader.cancel(); } catch { /* ignore */ } } + return { ok: false, status: respStatus, aborted: true, applied: false }; + } + } + const disposition = applySwap(doc, frameId, !!revalidating, finalUrl, incomingBuild, incomingSrc, refresh, recordHistoryNow); // `'none'` means applySwap returned WITHOUT committing anything: the frame the // response was for is missing, or it degraded to a hard navigation (an @@ -341,21 +378,37 @@ export async function fetchAndApply(href, frameId, recordHistory, optimisticStat // restoration themselves before dispatching popstate, so // leaving scroll alone preserves the browser-native UX. if (recordHistory) { - // Use the final URL (after any server-side redirect) so hash - // anchors point at the document we actually rendered. - const url = new URL(finalUrl); - if (url.hash) { - const t = document.getElementById(url.hash.slice(1)); - // A hash anchor is the one nav scroll we DON'T force instant: a - // `#section` link is exactly where an app's `scroll-behavior: smooth` - // is wanted, and native browsers animate it too. - if (t) t.scrollIntoView(); - else { warnIfSmoothScrollOnHtml(); window.scrollTo({ left: 0, top: 0, behavior: 'instant' }); } + const applyNavScroll = () => { + // Use the final URL (after any server-side redirect) so hash + // anchors point at the document we actually rendered. + const url = new URL(finalUrl); + if (url.hash) { + const t = document.getElementById(url.hash.slice(1)); + // A hash anchor is the one nav scroll we DON'T force instant: a + // `#section` link is exactly where an app's `scroll-behavior: smooth` + // is wanted, and native browsers animate it too. + if (t) t.scrollIntoView(); + else { warnIfSmoothScrollOnHtml(); window.scrollTo({ left: 0, top: 0, behavior: 'instant' }); } + } else { + // Scroll-to-top on a forward nav. behavior:'instant' so an app-level + // `scroll-behavior: smooth` does not animate it (match native nav). + warnIfSmoothScrollOnHtml(); + window.scrollTo({ left: 0, top: 0, behavior: 'instant' }); + } + }; + // #1428 diagnostic, TEMPORARY (default off). Isolates the CLAMP from the + // swap. The scroll-to-top runs in the same task as the push and the + // mutation, so if WebKit composes its snapshot from a later frame it reads + // an offset of 0 against the destination, and neither the #1410 ordering + // nor a frame yield would change that. Deferring the scroll past the frame + // says whether the offset is the part that matters. Extracted to a thunk so + // both paths run identical code and the run compares one variable. + if (diagFlag('scrolllast')) { + const painted = diagFrameYield(1); + if (painted) painted.then(applyNavScroll); + else applyNavScroll(); } else { - // Scroll-to-top on a forward nav. behavior:'instant' so an app-level - // `scroll-behavior: smooth` does not animate it (match native nav). - warnIfSmoothScrollOnHtml(); - window.scrollTo({ left: 0, top: 0, behavior: 'instant' }); + applyNavScroll(); } } diff --git a/packages/core/test/routing/browser/nav-swipe-ab-levers.test.js b/packages/core/test/routing/browser/nav-swipe-ab-levers.test.js new file mode 100644 index 000000000..867ea1e3e --- /dev/null +++ b/packages/core/test/routing/browser/nav-swipe-ab-levers.test.js @@ -0,0 +1,159 @@ +/** + * Real-browser test for #1428: the guarded paint-timing levers that let a real + * iPhone decide what actually fixes the back-swipe blank. + * + * #1410 moved the `pushState` ahead of the DOM mutation and the blank survived + * on-device, which leaves one assumption behind that fix untested: that WebKit + * binds the back-forward gesture snapshot synchronously, at the `pushState` + * call. If it instead captures the compositing surface when the + * `didSameDocumentNavigation` IPC lands in the UI process, that happens after + * the whole push-swap-scroll task has run, and reordering inside that task + * changes nothing a device can see. + * + * The gesture preview is iOS-only and cannot be asserted anywhere but a real + * iPhone. What CAN be asserted in any browser is the thing the levers change: + * whether a FRAME BOUNDARY falls between the push and the mutation. That is the + * whole mechanism under test, so it is what these pin, in both directions. + * + * The default direction matters as much as the lever direction. These sit on + * the live navigation path, so an app that opts into nothing must run exactly + * the timing it ran before, and only a test that fails when the lever leaks can + * say so. + */ +import { enableClientRouter, navigate } from '../../../src/router-client.js'; + +import { assert } from '../../../../../test/browser-assert.js'; +import { installNavGuard } from '../../../../../test/browser-nav-guard.js'; + +const OUTGOING_SENTINEL = 'outgoing-page-1428'; +const INCOMING_SENTINEL = 'incoming-page-1428'; +const SCROLL_TO = 800; + +suite('Client router: back-swipe A/B levers (#1428)', () => { + let origFetch, origPushState, navGuard, origHref, observer, seq, pushes; + + /** @param {Record | null} levers */ + function setup(levers) { + origHref = location.href; + enableClientRouter(); + navGuard = installNavGuard(); + + if (levers) window.__webjsDiag = levers; + else delete window.__webjsDiag; + + // A genuinely TALL outgoing document against a SHORT destination, the shape + // the defect was measured on: the engine really clamps the offset, so the + // #1410 guarantee is being re-checked against real layout rather than a + // stub. + document.body.innerHTML = + `${OUTGOING_SENTINEL}
`; + window.scrollTo({ left: 0, top: SCROLL_TO, behavior: 'instant' }); + + // One ordered trace of the three events the levers reorder. `frame` is + // requested from INSIDE the push wrapper, so it is queued ahead of any + // frame the router itself requests afterwards and therefore fires first + // within that frame. That ordering is what makes `frame` before `mutate` + // mean "the router waited for a frame" rather than "some frame elapsed". + seq = []; + pushes = []; + origPushState = history.pushState; + history.pushState = function (...args) { + seq.push('push'); + pushes.push({ text: document.body.textContent || '', scrollY: window.scrollY }); + requestAnimationFrame(() => seq.push('frame')); + return origPushState.apply(this, args); + }; + + // A MutationObserver callback is a microtask, so a synchronous swap records + // `mutate` before the next frame can run, which is exactly the distinction + // being drawn. + observer = new MutationObserver(() => { + if (!seq.includes('mutate')) seq.push('mutate'); + }); + observer.observe(document.body, { childList: true, subtree: true }); + + origFetch = window.fetch; + window.fetch = () => Promise.resolve(new Response( + '' + + `${INCOMING_SENTINEL}`, + { headers: { 'content-type': 'text/html', 'x-webjs-build': '' } }, + )); + } + + function teardown() { + if (observer) observer.disconnect(); + window.fetch = origFetch; + history.pushState = origPushState; + delete window.__webjsDiag; + if (navGuard) navGuard.remove(); + document.body.innerHTML = ''; + window.scrollTo({ left: 0, top: 0, behavior: 'instant' }); + history.replaceState(null, '', origHref); + } + + /** Let any pending frame callback land, so the trace is complete. */ + function settleFrames() { + return new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => r(undefined)))); + } + + test('default: no lever set, so the swap still happens in the push\'s own task', async () => { + setup(null); + try { + await navigate(location.origin + '/swipe-ab-default'); + await settleFrames(); + + assert.equal(navGuard.hardNavigations.length, 0, + `the swap must not degrade here (fallbacks: ${JSON.stringify(navGuard.fallbacks)})`); + assert.deepEqual(seq, ['push', 'mutate', 'frame'], + `with no lever the mutation lands before any frame boundary (got ${JSON.stringify(seq)})`); + } finally { teardown(); } + }); + + test('?raf: a frame boundary falls between the push and the mutation', async () => { + setup({ raf: true }); + try { + await navigate(location.origin + '/swipe-ab-raf'); + await settleFrames(); + + assert.equal(navGuard.hardNavigations.length, 0, + `the swap must not degrade here (fallbacks: ${JSON.stringify(navGuard.fallbacks)})`); + assert.deepEqual(seq, ['push', 'frame', 'mutate'], + `the lever must paint a frame between the push and the swap (got ${JSON.stringify(seq)})`); + } finally { teardown(); } + }); + + test('?raf2: same ordering, and the entry is still recorded exactly once', async () => { + setup({ raf2: true }); + try { + await navigate(location.origin + '/swipe-ab-raf2'); + await settleFrames(); + + assert.deepEqual(seq, ['push', 'frame', 'mutate'], + `the double-frame lever must also swap after a frame (got ${JSON.stringify(seq)})`); + // The lever calls the one-shot thunk itself and `applySwap` calls it + // again at its commit point, so the guard is the only thing between this + // and a duplicated history entry. + assert.equal(pushes.length, 1, 'exactly one pushState per navigation under the lever'); + } finally { teardown(); } + }); + + test('?raf: the #1410 guarantee survives, the outgoing page is still live at the push', async () => { + setup({ raf: true }); + try { + await navigate(location.origin + '/swipe-ab-raf-state'); + await settleFrames(); + + assert.equal(pushes.length, 1, 'the navigation recorded exactly one history entry'); + const at = pushes[0]; + // The lever moves the push EARLIER (ahead of the yield), so what #1410 + // pinned has to still hold: a lever that fixed the frame timing by + // sacrificing the recorded state would be a regression wearing a fix. + assert.ok(at.text.includes(OUTGOING_SENTINEL), + 'the outgoing page is still in the DOM at the pushState call'); + assert.ok(!at.text.includes(INCOMING_SENTINEL), + 'the incoming page has NOT been swapped in yet at the pushState call'); + assert.ok(at.scrollY >= SCROLL_TO - 5, + `the outgoing scroll offset is still live at the pushState call (expected about ${SCROLL_TO}, got ${at.scrollY})`); + } finally { teardown(); } + }); +}); diff --git a/packages/core/test/routing/router-client.test.js b/packages/core/test/routing/router-client.test.js index 422f91da2..973e1ecf7 100644 --- a/packages/core/test/routing/router-client.test.js +++ b/packages/core/test/routing/router-client.test.js @@ -29,6 +29,7 @@ import { parseHTML } from 'linkedom'; // does not trip the auto-enable the barrel's dynamic import exists to defer. import { cacheKey } from '../../src/router-client/snapshot-cache.js'; import { prefetchEvict } from '../../src/router-client/prefetch.js'; +import { diagFlag, diagFrameYield } from '../../src/router-client/diagnostics.js'; let _collect, _plan, _keyOf, _diffEl, _reconcile, _addNewHead, _merge, _isNonHtmlPath, navigate, @@ -5220,6 +5221,74 @@ test('applySwap: the history callback fires BEFORE the DOM mutation (#1406)', () } }); +/* -------------------------------------------------------------------------- + * #1428: the on-device A/B levers for the back-swipe blank. + * + * #1410 shipped the ordering fix with its iOS acceptance criterion openly + * unmet, and the blank survived on a real iPhone, so one assumption behind it + * is still untested: that WebKit binds the gesture snapshot synchronously at + * the `pushState` call rather than from a later composited frame. The levers + * exist to let a device decide, and the thing to pin here is that they are + * INERT unless an app opts in, since they sit on the live navigation path. + * ------------------------------------------------------------------------ */ + +test('diagFlag: false when the app sets nothing, so the nav path is untouched (#1428)', () => { + const saved = globalThis.window ? globalThis.window.__webjsDiag : undefined; + try { + if (globalThis.window) delete globalThis.window.__webjsDiag; + assert.equal(diagFlag('raf'), false, 'no diag object means no lever'); + assert.equal(diagFlag('raf2'), false); + assert.equal(diagFlag('scrolllast'), false); + } finally { + if (globalThis.window && saved !== undefined) globalThis.window.__webjsDiag = saved; + } +}); + +test('diagFlag: reads the lever an app opted into, and only that one (#1428)', () => { + const saved = globalThis.window ? globalThis.window.__webjsDiag : undefined; + try { + globalThis.window.__webjsDiag = { raf: true, raf2: false, scrolllast: false }; + assert.equal(diagFlag('raf'), true, 'the opted-in lever reads true'); + assert.equal(diagFlag('raf2'), false, 'a sibling lever stays off'); + // An unknown name must not throw its way onto the navigation path. + assert.equal(diagFlag('nope'), false, 'an unknown lever is simply off'); + } finally { + if (globalThis.window) { + if (saved === undefined) delete globalThis.window.__webjsDiag; + else globalThis.window.__webjsDiag = saved; + } + } +}); + +test('diagFrameYield: null without requestAnimationFrame, so the caller degrades (#1428)', () => { + const saved = globalThis.requestAnimationFrame; + try { + // The unit runner's DOM shim has no rAF, which is the case the call sites + // guard with `if (painted) await painted`. A promise that never resolves + // here would hang a navigation rather than skip a diagnostic. + delete globalThis.requestAnimationFrame; + assert.equal(diagFrameYield(1), null, 'no rAF means nothing to await'); + } finally { + if (saved !== undefined) globalThis.requestAnimationFrame = saved; + } +}); + +test('diagFrameYield: waits the requested number of frames (#1428)', async () => { + const saved = globalThis.requestAnimationFrame; + try { + let frames = 0; + globalThis.requestAnimationFrame = (fn) => { frames += 1; queueMicrotask(fn); return frames; }; + await diagFrameYield(2); + // Two frames, not one: `?raf2` exists because a single rAF can still land + // before the commit WebKit needs, and the double-rAF is the standard + // after-next-paint idiom. + assert.equal(frames, 2, 'the double-frame lever really waits two frames'); + } finally { + if (saved === undefined) delete globalThis.requestAnimationFrame; + else globalThis.requestAnimationFrame = saved; + } +}); + test('applySwap: a frame-missing response commits nothing, so it records no history (#1406)', () => { const savedBody = globalThis.document.body.innerHTML; const savedLocation = globalThis.location; diff --git a/website/app/layout.ts b/website/app/layout.ts index 610d177a4..cdadc5f92 100644 --- a/website/app/layout.ts +++ b/website/app/layout.ts @@ -195,6 +195,22 @@ export default function RootLayout({ children }: LayoutProps) { if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', measure); else measure(); })(); + // #1428, TEMPORARY: capture the back-swipe A/B levers off the query + // string into window.__webjsDiag, so a real iPhone can compare the + // candidate paint timings against the current one. Captured ONCE here + // rather than read per navigation, because the flag is gone from the URL + // the moment the first soft nav replaces it, and the run needs the lever + // to hold for the whole session. Inline and in the head so it lands + // before the router boots (a module script is deferred). Removed with + // the levers once the device has answered. + (function(){ + try { + var p = new URLSearchParams(location.search); + if (p.has('raf') || p.has('raf2') || p.has('scrolllast')) { + window.__webjsDiag = { raf: p.has('raf'), raf2: p.has('raf2'), scrolllast: p.has('scrolllast') }; + } + } catch (_) {} + })(); From 374ee586fdc54c01a167405478d6f348cc0a0155 Mon Sep 17 00:00:00 2001 From: Vivek Date: Tue, 18 Aug 2026 11:47:19 +0530 Subject: [PATCH 2/3] fix: guard the deferred back-swipe scroll on the navigation token The ?scrolllast lever defers the scroll-to-top by a frame, which puts it outside the navigation's own task. A newer navigation can start in that frame, and the deferred callback would then scroll ITS page: worst on the hash branch, where scrollIntoView hunts the old URL's anchor in the new document and lands somewhere arbitrary if that id happens to exist. The synchronous path cannot do this, so the lever was adding a failure mode rather than isolating one, and a diagnostic that exists to measure scroll behaviour must not write scroll into a page it has nothing to do with. --- .../core/src/router-client/fetch-apply.js | 10 ++++- .../browser/nav-swipe-ab-levers.test.js | 43 +++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/packages/core/src/router-client/fetch-apply.js b/packages/core/src/router-client/fetch-apply.js index 88cef68a6..f6ab799a1 100644 --- a/packages/core/src/router-client/fetch-apply.js +++ b/packages/core/src/router-client/fetch-apply.js @@ -405,7 +405,15 @@ export async function fetchAndApply(href, frameId, recordHistory, optimisticStat // both paths run identical code and the run compares one variable. if (diagFlag('scrolllast')) { const painted = diagFrameYield(1); - if (painted) painted.then(applyNavScroll); + // Guarded on the nav token, because deferring the scroll puts it outside + // this navigation's own task: a newer navigation can start in that frame, + // and then this would scroll ITS page. The synchronous path cannot do + // that, so an unguarded `.then` would be the lever writing scroll into a + // page it has nothing to do with. Worst on the hash branch, where + // `scrollIntoView` would hunt this URL's anchor in the new document and + // land somewhere arbitrary if the id happens to exist. A diagnostic + // measuring scroll behaviour cannot afford to move scroll on its own. + if (painted) painted.then(() => { if (myToken === currentNavigationToken) applyNavScroll(); }); else applyNavScroll(); } else { applyNavScroll(); diff --git a/packages/core/test/routing/browser/nav-swipe-ab-levers.test.js b/packages/core/test/routing/browser/nav-swipe-ab-levers.test.js index 867ea1e3e..c774759e3 100644 --- a/packages/core/test/routing/browser/nav-swipe-ab-levers.test.js +++ b/packages/core/test/routing/browser/nav-swipe-ab-levers.test.js @@ -137,6 +137,49 @@ suite('Client router: back-swipe A/B levers (#1428)', () => { } finally { teardown(); } }); + test('?scrolllast: the scroll-to-top lands after a frame, not in the swap\'s task', async () => { + setup({ scrolllast: true }); + const scrolls = []; + const origScrollTo = window.scrollTo; + try { + // Recorded rather than suppressed: the lever is about WHEN the write + // happens, so the write still has to happen. + window.scrollTo = function (...args) { scrolls.push(seq.slice()); return origScrollTo.apply(this, args); }; + await navigate(location.origin + '/swipe-ab-scrolllast'); + const beforeFrame = scrolls.length; + await settleFrames(); + + assert.equal(beforeFrame, 0, + `the deferred scroll must not have run yet when the navigation resolved (ran ${beforeFrame} times)`); + assert.equal(scrolls.length, 1, 'the scroll still runs, one frame later'); + assert.ok(scrolls[0].includes('frame'), + `the scroll landed after a frame boundary (trace at the write: ${JSON.stringify(scrolls[0])})`); + } finally { window.scrollTo = origScrollTo; teardown(); } + }); + + test('?scrolllast: a superseded navigation does not scroll the page that replaced it', async () => { + setup({ scrolllast: true }); + const scrolls = []; + const origScrollTo = window.scrollTo; + try { + window.scrollTo = function (...args) { scrolls.push('scroll'); return origScrollTo.apply(this, args); }; + await navigate(location.origin + '/swipe-ab-superseded'); + + // Start a second navigation inside the deferred scroll's frame gap. Its + // fetch never settles, so it bumps the nav token and then does nothing + // else, which isolates the guard from anything the newer navigation + // would itself have done to scroll. + window.fetch = () => new Promise(() => {}); + navigate(location.origin + '/swipe-ab-superseder'); + await settleFrames(); + + // Without the token guard the first navigation's scroll fires here, into + // a document a newer navigation already owns. + assert.equal(scrolls.length, 0, + 'the superseded navigation abandoned its deferred scroll'); + } finally { window.scrollTo = origScrollTo; teardown(); } + }); + test('?raf: the #1410 guarantee survives, the outgoing page is still live at the push', async () => { setup({ raf: true }); try { From cf5519c02171c1a8797f7ff34d9db5a04a6144dd Mon Sep 17 00:00:00 2001 From: Vivek Date: Tue, 18 Aug 2026 11:59:27 +0530 Subject: [PATCH 3/3] test: abort the superseding navigation instead of leaving it in flight The supersede assertion drove its second navigation with a fetch that never settled, which left a navigation in flight for the rest of the page's life holding the router's token and its own frame state. Under the full browser suite that leak reded an unrelated file, the #1310 back-restore residue assertion, on Firefox, while both files passed in isolation and while the branch's own file passed everywhere. Rejecting with an AbortError settles the navigation down the path the router already takes for a superseded one, so the assertion observes the same thing with nothing left running. Full browser suite green twice at this commit, against a baseline that was green before the file was added. --- .../browser/nav-swipe-ab-levers.test.js | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/packages/core/test/routing/browser/nav-swipe-ab-levers.test.js b/packages/core/test/routing/browser/nav-swipe-ab-levers.test.js index c774759e3..fd4eb9622 100644 --- a/packages/core/test/routing/browser/nav-swipe-ab-levers.test.js +++ b/packages/core/test/routing/browser/nav-swipe-ab-levers.test.js @@ -165,13 +165,23 @@ suite('Client router: back-swipe A/B levers (#1428)', () => { window.scrollTo = function (...args) { scrolls.push('scroll'); return origScrollTo.apply(this, args); }; await navigate(location.origin + '/swipe-ab-superseded'); - // Start a second navigation inside the deferred scroll's frame gap. Its - // fetch never settles, so it bumps the nav token and then does nothing - // else, which isolates the guard from anything the newer navigation - // would itself have done to scroll. - window.fetch = () => new Promise(() => {}); - navigate(location.origin + '/swipe-ab-superseder'); + // Start a second navigation inside the deferred scroll's frame gap. It + // bumps the nav token and then does nothing else, which isolates the + // guard from anything the newer navigation would itself have done to + // scroll. + // + // Aborted rather than left pending. A fetch that never settles leaves a + // navigation in flight for the rest of the page's life, holding the + // router's token and its own frame state, and a test that never cleans + // that up is a leak looking for somewhere to surface. An AbortError is + // the shape the router already treats as a superseded navigation, so it + // settles down the path it would take in production. + let abortPending; + window.fetch = () => new Promise((_, reject) => { abortPending = reject; }); + const superseder = navigate(location.origin + '/swipe-ab-superseder'); await settleFrames(); + if (abortPending) abortPending(new DOMException('aborted', 'AbortError')); + await superseder.catch(() => {}); // Without the token guard the first navigation's scroll fires here, into // a document a newer navigation already owns.