An open source design system that's fully customizable and agent ready
TypeScript
test(interaction-harness): hold a lift until a time after the thaw (#10352)
Christopher Chedeau2301991251a8
diff --git a/internal/interaction-harness/README.md b/internal/interaction-harness/README.mdindex b78cb5535b..598a36cc3e 100644--- a/internal/interaction-harness/README.md+++ b/internal/interaction-harness/README.md@@ -410,6 +410,8 @@ instead, and the proof acts at an instant of the scene's own time.predicate holds, and rejects after its timeout.- `advanceFrozenPage(page, ms)` moves the page's clock and every heldanimation on together by `ms`; timers and frame callbacks stay held.+- `holdInputUntil(page, {afterResumeMs})` makes the page handle its next lift+ late, after the thaw, while the scene runs (below).While frozen, every animation in the document is paused where it stands (WebAnimations, CSS animations and transitions), and so is any the page starts@@ -447,6 +449,31 @@ the headless shell (300 ms into a pause the timeline had advanced 300 ms and acompositor animation 45 px), and its `advance` policy cannot return to realtime: it fast-forwards whenever the page is idle.+### Input the page handles late++A frozen page handles input at once. A proof that needs a late handling, with+the compositor still moving, cannot freeze through the input. A held run resumes+only at the first frame after the thaw, and a block before that frame holds the+screen too. `holdInputUntil(page, {afterResumeMs})`, called before the thaw,+holds the next lift instead (`pointerup` or `touchend`; `on` names others). The+install's window capture listener runs first in the input's task and keeps the+main thread busy until `afterResumeMs` after that first frame. Send the input+once `resumed()` resolves. `landed()` then gives when the input arrived, when it+was due, and when the page let it through. The event keeps its own `timeStamp`,+earlier than its handling, as on a busy page. An input that arrives more than a+frame late, before that first frame, or while the page is frozen again, rejects+`landed()` with `LiftPlacementError` and the numbers. The page cannot hold back+an input it has not received, and a hold before the frame would stop the screen.+Choose `afterResumeMs` above the runner's time from `resumed()` to the input's+arrival. Under load, that round trip is what makes a hold late. The page lets+the input through at its time, or at its arrival if that came later within the+frame. On a starved runner it can be later still, by as long as its main thread+did not run: `landed()` gives that as `stalledMs`.++`navigator.scheduling.isInputPending()` cannot gate a lift. In Playwright's+Chromium 149 it reports a queued mouse press or key at once, but never a touch+sent with `Input.dispatchTouchEvent`. WebKit has no `isInputPending`.+## Engine limits (measured with Playwright 1.61)| | Chromium 149 | WebKit 26.5 (Linux build) |diff --git a/internal/interaction-harness/src/freeze.ts b/internal/interaction-harness/src/freeze.tsindex b6dc55144f..7708cdaee4 100644--- a/internal/interaction-harness/src/freeze.ts+++ b/internal/interaction-harness/src/freeze.ts@@ -7,6 +7,7 @@* `freezePageWhen` and `advanceFrozenPage`. Stop a scene (its animations,* frames, timeouts and every time it reads), step it by its own clock, and* start it again. An interval skips its ticks while frozen.+ * `holdInputUntil` makes the page handle an input late while the scene runs.* @position Input timed by the scene, not by the test process: a proof freezes* the scene where it wants to act, acts, and thaws. The README's "Page* freeze" section says what a freeze holds and why it lives in script.@@ -139,8 +140,41 @@ const FREEZE_SCRIPT = `(() => {// page listener for that input, in the input's own task.const ARMABLE = ['pointerdown', 'pointermove', 'pointerup', 'pointercancel', 'touchstart', 'touchmove', 'touchend', 'touchcancel', 'mousedown', 'mousemove', 'mouseup', 'click', 'keydown', 'keyup', 'wheel', 'scroll'];const armed = new Set();+ // An input held until its time (holdInputUntil), one at a time. The page+ // then handles it late, its main thread busy, while the compositor runs on.+ const ONE_FRAME_MS = 1000 / 60;+ let inputHold = null;+ let holds = 0;+ const placeHeld = type => {+ const held = inputHold;+ held.type = type;+ const arrived = rawNow();+ held.arrivedAt = now(arrived);+ // Before the first frame drawn unfrozen, the held runs have not resumed:+ // a block there would stop the screen too.+ if (held.resumeAt == null) { held.outcome = 'early'; return; }+ // Frozen again, the page's clock and the screen stand still.+ if (state.frozenAt != null) { held.outcome = 'frozen'; return; }+ // An input the page has not received cannot be held back.+ if (held.arrivedAt > held.intended + ONE_FRAME_MS) { held.outcome = 'late'; return; }+ // Unfrozen, the page's clock is the real one less a constant: nothing can+ // freeze the page while this task runs.+ let last = arrived;+ // The longest gap between two reads: time the main thread did not run.+ let stalled = 0;+ while (last - state.offset < held.intended) {+ // the page's main thread is busy+ const read = rawNow();+ stalled = Math.max(stalled, read - last);+ last = read;+ }+ held.stalledMs = stalled;+ held.releasedAt = last - state.offset;+ held.outcome = 'placed';+ };for (const type of ARMABLE) {window.addEventListener(type, () => {+ if (inputHold != null && inputHold.outcome == null && inputHold.types.includes(type)) placeHeld(type);if (!armed.delete(type)) return;window.__harnessFreeze.freeze();if (window.__harnessTimerGate) window.__harnessTimerGate.freeze(true);@@ -158,6 +192,27 @@ const FREEZE_SCRIPT = `(() => {}armed.add(type);},+ // Holds the next input of these types until afterMs past the first frame+ // the page draws unfrozen.+ holdInput(types, afterMs) {+ for (const type of types) {+ if (!ARMABLE.includes(type)) {+ throw new Error('holdInputUntil: a hold takes only ' + ARMABLE.join(', ') + '; got ' + type);+ }+ }+ holds += 1;+ const held = {id: holds, types, afterMs, resumeAt: null, intended: null, arrivedAt: null, releasedAt: null, stalledMs: null, type: null, outcome: null};+ inputHold = held;+ const tick = time => {+ if (inputHold !== held || held.outcome != null) return;+ if (state.frozenAt != null) { nativeFrame(tick); return; }+ held.resumeAt = now(time);+ held.intended = held.resumeAt + afterMs;+ };+ nativeFrame(tick);+ return held.id;+ },+ get held() { return inputHold == null ? null : Object.assign({}, inputHold); },get frozen() { return state.frozenAt != null; },// The frozen span so far. Once thawed, a page time plus it is real time.get offset() { return state.offset; },@@ -390,3 +445,195 @@ export async function thawPage(page: Page): Promise<void> {w.__harnessTimerGate?.thaw();});}++/**+ * An input that `holdInputUntil` could not hold to its time. It reached the+ * page more than a frame after its time, before the first frame after the+ * thaw, or while the page was frozen again. The proof would then read another+ * instant than the one it set. Always a red, with the numbers; never a pass.+ */+export class LiftPlacementError extends Error {+ constructor(+ message: string,+ /** The page times the error is read from, ms. */+ readonly numbers: Readonly<Record<string, number | null>>,+ ) {+ super(message);+ this.name = 'LiftPlacementError';+ }+}++/** A held input's times on the page's clock, ms. */+export interface HeldInput {+ /** The event type the hold caught first. */+ readonly type: string;+ /** The first frame the page drew unfrozen after the call. */+ readonly resumeMs: number;+ /** When the page was to handle the input: `resumeMs + afterResumeMs`. */+ readonly intendedMs: number;+ /** When the input reached the page. */+ readonly arrivedMs: number;+ /** When the hold let the page's own listeners run. */+ readonly releasedMs: number;+ /**+ * The longest time the page's main thread did not run during the hold. The+ * page lets the input through at its time, or at its arrival if that came+ * later. On a starved runner it can be up to this much later still.+ */+ readonly stalledMs: number;+}++export interface InputHold {+ /**+ * Resolves with `resumeMs`, once the page has drawn its first frame+ * unfrozen. Send the input after it.+ */+ resumed(options?: {timeout?: number}): Promise<number>;+ /**+ * Resolves once the hold has let the input through. Rejects with+ * `LiftPlacementError` when the input came too late or too early to hold.+ */+ landed(options?: {timeout?: number}): Promise<HeldInput>;+}++interface HoldState {+ id: number;+ afterMs: number;+ resumeAt: number | null;+ intended: number | null;+ arrivedAt: number | null;+ releasedAt: number | null;+ stalledMs: number | null;+ type: string | null;+ outcome: 'early' | 'frozen' | 'late' | 'placed' | null;+}++/**+ * Makes the page handle its next lift late, at a time of the scene's clock,+ * while the compositor keeps the scene moving. A frozen page handles input at+ * once, so a freeze alone cannot do this.+ *+ * Call it before the thaw. The hold counts from the first frame the page then+ * draws unfrozen, where the held runs resume. Send the input after+ * `resumed()`. The install's window capture listener catches the first+ * `pointerup` or `touchend` (or the types in `on`) before any page listener.+ * It keeps the main thread busy until `afterResumeMs` after that frame, and+ * then lets the page's listeners run. The event keeps its own `timeStamp`,+ * earlier than its handling, as on a busy page.+ * Choose `afterResumeMs` above the runner's time from `resumed()` to the+ * input's arrival. Under load, that round trip makes a hold late.+ * Needs `installPageFreeze` before the page loads.+ */+export async function holdInputUntil(+ page: Page,+ {+ afterResumeMs,+ on = ['pointerup', 'touchend'],+ }: {afterResumeMs: number; on?: readonly string[]},+): Promise<InputHold> {+ if (!Number.isFinite(afterResumeMs) || afterResumeMs <= 0) {+ throw new Error(+ `holdInputUntil: afterResumeMs must be a positive number of ms, got ${afterResumeMs}`,+ );+ }+ const id = await page.evaluate(+ ([types, ms]) => {+ const w = window as unknown as {+ __harnessFreeze?: {+ holdInput?: (types: readonly string[], ms: number) => number;+ };+ };+ if (w.__harnessFreeze?.holdInput == null) {+ throw new Error(+ 'holdInputUntil: call installPageFreeze before the page loads',+ );+ }+ return w.__harnessFreeze.holdInput(types, ms);+ },+ [on, afterResumeMs] as const,+ );+ // Waits on the real frames: the page's own stand still while it is frozen.+ const waitFor = (field: 'resumeAt' | 'outcome', timeout: number) =>+ page.evaluate(+ ([key, wait, holdId]) =>+ new Promise<HoldState>((resolve, reject) => {+ const freeze = (+ window as unknown as {+ __harnessFreeze: {+ held: HoldState | null;+ frame: (callback: () => void) => number;+ realNow: () => number;+ };+ }+ ).__harnessFreeze;+ const deadline = freeze.realNow() + wait;+ const tick = () => {+ const held = freeze.held;+ // One hold at a time: a later call replaces this one, whose+ // handle would otherwise read the later hold.+ if (held?.id !== holdId) {+ reject(+ new Error(+ 'holdInputUntil: a later holdInputUntil replaced this hold',+ ),+ );+ } else if (held[key] != null) {+ resolve(held);+ } else if (freeze.realNow() > deadline) {+ reject(+ new Error(+ key === 'resumeAt'+ ? `holdInputUntil: the page drew no frame unfrozen within ${wait} ms`+ : `holdInputUntil: no held input reached the page within ${wait} ms`,+ ),+ );+ } else {+ freeze.frame(tick);+ }+ };+ tick();+ }),+ [field, timeout, id] as const,+ );+ return {+ async resumed({timeout = 5_000} = {}) {+ return (await waitFor('resumeAt', timeout)).resumeAt as number;+ },+ async landed({timeout = 5_000} = {}) {+ const held = await waitFor('outcome', timeout);+ const numbers = {+ resumeMs: held.resumeAt,+ intendedMs: held.intended,+ arrivedMs: held.arrivedAt,+ releasedMs: held.releasedAt,+ };+ if (held.outcome === 'early') {+ throw new LiftPlacementError(+ `holdInputUntil: the ${held.type} reached the page before its first frame after the thaw, where the held runs resume. A hold there would stop the screen too: send the input after resumed()`,+ numbers,+ );+ }+ if (held.outcome === 'frozen') {+ throw new LiftPlacementError(+ `holdInputUntil: the ${held.type} reached the page while it was frozen again after the thaw. A hold then would stop the screen too: thaw before the input comes`,+ numbers,+ );+ }+ if (held.outcome === 'late') {+ const lateMs = (held.arrivedAt ?? 0) - (held.intended ?? 0);+ throw new LiftPlacementError(+ `holdInputUntil: the ${held.type} reached the page ${lateMs.toFixed(1)} ms after its time (${held.afterMs} ms after the first frame after the thaw), more than a frame: the page cannot hold back an input it has not received`,+ numbers,+ );+ }+ return {+ type: held.type as string,+ resumeMs: held.resumeAt as number,+ intendedMs: held.intended as number,+ arrivedMs: held.arrivedAt as number,+ releasedMs: held.releasedAt as number,+ stalledMs: held.stalledMs as number,+ };+ },+ };+}diff --git a/internal/interaction-harness/src/harness.interaction.browser.spec.ts b/internal/interaction-harness/src/harness.interaction.browser.spec.tsindex 9ebfef041b..b3c017dcfc 100644--- a/internal/interaction-harness/src/harness.interaction.browser.spec.ts+++ b/internal/interaction-harness/src/harness.interaction.browser.spec.ts@@ -80,11 +80,13 @@ import {freezeTimers,HARNESS_READ,holdAnimations,+ holdInputUntil,installInputLog,type InputRecord,installLongTaskLog,installPageFreeze,installTimerGate,+ LiftPlacementError,markElement,merge,parseTransform,@@ -5628,6 +5630,141 @@ test.describe('page freeze', () => {expect(elapsed - (thawed.now - frozen.now)).toBeGreaterThan(250);});+ test("a held lift reaches the page early, and its handling waits for its time after the thaw: the page's own listener runs then", async ({+ page,+ }) => {+ await installPageFreeze(page);+ await freezeFixture(page);+ await installTimerGate(page);+ const driver = await touchDriver(page);+ // The page's own lift listener, added after the install's.+ await page.evaluate(() => {+ const w = window as unknown as {liftHandledAt?: number};+ addEventListener(+ 'pointerup',+ () => {+ w.liftHandledAt ??= performance.now();+ },+ {capture: true, passive: true},+ );+ });+ await freezePage(page);+ const hold = await holdInputUntil(page, {afterResumeMs: 200});+ await thawPage(page);+ const resumeMs = await hold.resumed();+ await driver.play([+ {t: 0, fingers: [{id: 0, x: 20, y: 60}]},+ {t: 30, fingers: []},+ ]);+ const held = await hold.landed();+ expect(held.resumeMs).toBe(resumeMs);+ expect(held.intendedMs).toBeCloseTo(resumeMs + 200, 6);+ // It reached the page after the first frame and before its time...+ expect(held.arrivedMs).toBeGreaterThan(resumeMs);+ expect(held.arrivedMs).toBeLessThan(held.intendedMs);+ // ...and the page handled it at its time, late only by as long as its+ // main thread did not run (a floating-point margin).+ expect(held.releasedMs).toBeGreaterThanOrEqual(held.intendedMs);+ expect(held.releasedMs - held.intendedMs).toBeLessThanOrEqual(+ held.stalledMs + 1e-6,+ );+ const handledAt = await page.evaluate(+ () => (window as unknown as {liftHandledAt?: number}).liftHandledAt,+ );+ expect(handledAt).toBeGreaterThanOrEqual(held.intendedMs);+ // A hold takes a positive time and only the inputs the install listens for.+ await expect(holdInputUntil(page, {afterResumeMs: 0})).rejects.toThrow(+ /positive number/,+ );+ await expect(+ holdInputUntil(page, {afterResumeMs: 50, on: ['focus']}),+ ).rejects.toThrow(/takes only/);+ // One hold at a time: a later hold replaces an earlier one, whose handle+ // then fails by name.+ const earlier = await holdInputUntil(page, {afterResumeMs: 50});+ await holdInputUntil(page, {afterResumeMs: 50});+ await expect(earlier.resumed()).rejects.toThrow(/replaced this hold/);+ await expect(earlier.landed()).rejects.toThrow(/replaced this hold/);+ });++ test('a lift that reaches the page more than a frame after its time fails by name, with the numbers', async ({+ page,+ }) => {+ await installPageFreeze(page);+ await freezeFixture(page);+ await installTimerGate(page);+ const driver = await touchDriver(page);+ await freezePage(page);+ const hold = await holdInputUntil(page, {afterResumeMs: 20});+ await thawPage(page);+ await hold.resumed();+ // Sent well after its time: the page cannot hold back what it has not had.+ await page.waitForTimeout(200);+ await driver.play([+ {t: 0, fingers: [{id: 0, x: 20, y: 60}]},+ {t: 30, fingers: []},+ ]);+ const error = await hold.landed().catch((caught: unknown) => caught);+ expect(error).toBeInstanceOf(LiftPlacementError);+ const {numbers, message} = error as LiftPlacementError;+ expect(message).toMatch(/ms after its time/);+ expect(+ (numbers.arrivedMs ?? 0) - (numbers.intendedMs ?? 0),+ ).toBeGreaterThan(1000 / 60);+ });++ test('a lift that reaches the page before its first frame after the thaw fails by name', async ({+ page,+ }) => {+ await installPageFreeze(page);+ await freezeFixture(page);+ await installTimerGate(page);+ const driver = await touchDriver(page);+ await freezePage(page);+ const hold = await holdInputUntil(page, {afterResumeMs: 50});+ // Still frozen: the page has drawn no frame unfrozen, so no held run has+ // resumed.+ await driver.play([+ {t: 0, fingers: [{id: 0, x: 20, y: 60}]},+ {t: 30, fingers: []},+ ]);+ const error = await hold.landed().catch((caught: unknown) => caught);+ expect(error).toBeInstanceOf(LiftPlacementError);+ expect((error as Error).message).toMatch(+ /before its first frame after the thaw/,+ );+ await thawPage(page);+ });++ test('a lift that reaches the page while it is frozen again after the thaw fails by name, and the page still answers', async ({+ page,+ }) => {+ await installPageFreeze(page);+ await freezeFixture(page);+ await installTimerGate(page);+ const driver = await touchDriver(page);+ await freezePage(page);+ const hold = await holdInputUntil(page, {afterResumeMs: 200});+ await thawPage(page);+ await hold.resumed();+ // Frozen again before the lift: the page's clock stands still.+ await freezePage(page);+ await driver.play([+ {t: 0, fingers: [{id: 0, x: 20, y: 60}]},+ {t: 30, fingers: []},+ ]);+ const error = await hold.landed().catch((caught: unknown) => caught);+ expect(error).toBeInstanceOf(LiftPlacementError);+ expect((error as Error).message).toMatch(/while it was frozen again/);+ // The hold did not keep the page busy: it answers within a second.+ const answered = await Promise.race([+ page.evaluate(() => true),+ new Promise<boolean>(resolve => setTimeout(() => resolve(false), 1_000)),+ ]);+ expect(answered).toBe(true);+ await thawPage(page);+ });+test("a freeze armed on an input lands before the page's own listeners for it, so a slow handler's run is held at its start", async ({page,}) => {