An open source design system that's fully customizable and agent ready
TypeScript
test(interaction-harness): name a touch's wait apart from its listeners (#10589)
Christopher Chedeauc590f9bba57c
diff --git a/internal/interaction-harness/src/harness.interaction.browser.spec.ts b/internal/interaction-harness/src/harness.interaction.browser.spec.tsindex f593d0465e..c8b79cbd1a 100644--- a/internal/interaction-harness/src/harness.interaction.browser.spec.ts+++ b/internal/interaction-harness/src/harness.interaction.browser.spec.ts@@ -119,6 +119,7 @@ import {toTouchEvents,touchDriver,trackBrightness,+ TouchPacingError,TouchPageStallError,touchStoryboard,TouchLiftStallError,@@ -430,6 +431,139 @@ test.describe('touch input', () => {expect(played.at(-1)?.release).toBeDefined();});+ test("a page task that holds the main thread before an event changes a paced flick's release, and the error names the wait, not the page's listeners", async ({+ page,+ browserName,+ }) => {+ test.skip(+ browserName !== 'webkit',+ 'only WebKit stamps a touch when it arrives; Chromium carries the scripted times',+ );+ // Each pointer move queues a 60 ms task, as a component's timer can. The+ // listeners themselves return at once, and the next move waits for the+ // task before they begin. The driver comes first, so its mark does too.+ const driver = await touchDriver(page);+ await page.route('http://task-stalling-page.test/', route =>+ route.fulfill({+ contentType: 'text/html',+ body: '<!doctype html><body style="margin:0;height:3000px;touch-action:none"><script>addEventListener("pointermove",()=>{setTimeout(()=>{const end=performance.now()+60;while(performance.now()<end){}},0)});</script>',+ }),+ );+ await page.goto('http://task-stalling-page.test/');+ const outcome = await driver+ .play(+ drag({x: 200, y: 400}, {x: 200, y: 300}, {durationMs: 100, hz: 60}),+ {pacing: 'spacing'},+ )+ .then(+ () => 'resolved',+ (error: unknown) => error,+ );+ expect(outcome).toBeInstanceOf(TouchPacingError);+ expect(String(outcome)).toMatch(+ /an event waited \d+ ms for the main thread before the page's listeners began/,+ );+ });++ test("a page's own window capture listener counts as the page's listeners when the driver is created before the page loads", async ({+ page,+ browserName,+ }) => {+ test.skip(+ browserName !== 'webkit',+ 'only WebKit stamps a touch when it arrives; Chromium carries the scripted times',+ );+ // The driver marks when the page's listeners begin with a window capture+ // listener of its own, added here before the page's scripts. So it runs+ // before the page's, which the page adds at load on the window's capture+ // phase and which holds each pointer move 60 ms.+ const driver = await touchDriver(page);+ await page.route('http://capture-stalling-page.test/', route =>+ route.fulfill({+ contentType: 'text/html',+ body: '<!doctype html><body style="margin:0;height:3000px;touch-action:none"><script>addEventListener("pointermove",()=>{const end=performance.now()+60;while(performance.now()<end){}},{capture:true});</script>',+ }),+ );+ await page.goto('http://capture-stalling-page.test/');+ const outcome = await driver+ .play(+ drag({x: 200, y: 400}, {x: 200, y: 300}, {durationMs: 100, hz: 60}),+ {pacing: 'spacing'},+ )+ .then(+ () => 'resolved',+ (error: unknown) => error,+ );+ expect(outcome).toBeInstanceOf(TouchPageStallError);+ expect(String(outcome)).toMatch(+ /the page's own touch and pointer listeners took \d+ ms/,+ );+ });++ test("a page's window capture listener added before a driver created after load still counts as the page's listeners, as a gesture host's does", async ({+ page,+ browserName,+ }) => {+ test.skip(+ browserName !== 'webkit',+ 'only WebKit stamps a touch when it arrives; Chromium carries the scripted times',+ );+ // The page adds its window capture listener at load, as a gesture host+ // does at mount, and the driver comes after. Its mark then runs after+ // that listener, so the hold counts from the event's stamp, as before.+ await page.route('http://late-driver-page.test/', route =>+ route.fulfill({+ contentType: 'text/html',+ body: '<!doctype html><body style="margin:0;height:3000px;touch-action:none"><script>addEventListener("pointermove",()=>{const end=performance.now()+60;while(performance.now()<end){}},{capture:true});</script>',+ }),+ );+ await page.goto('http://late-driver-page.test/');+ const driver = await touchDriver(page);+ const outcome = await driver+ .play(+ drag({x: 200, y: 400}, {x: 200, y: 300}, {durationMs: 100, hz: 60}),+ {pacing: 'spacing'},+ )+ .then(+ () => 'resolved',+ (error: unknown) => error,+ );+ expect(outcome).toBeInstanceOf(TouchPageStallError);+ expect(String(outcome)).toMatch(+ /the page's own touch and pointer listeners took \d+ ms/,+ );+ });++ test("a page set by setContent after the driver keeps the old reading: its window capture listener counts as the page's listeners", async ({+ page,+ browserName,+ }) => {+ test.skip(+ browserName !== 'webkit',+ 'only WebKit stamps a touch when it arrives; Chromium carries the scripted times',+ );+ // The driver's mark runs first on the blank page it navigates to.+ // setContent then reopens that document, which drops the mark's listener+ // and keeps the mark, and the new page adds its own capture listener.+ const driver = await touchDriver(page);+ await page.goto('about:blank');+ await page.setContent(+ '<!doctype html><body style="margin:0;height:3000px;touch-action:none"><script>addEventListener("pointermove",()=>{const end=performance.now()+60;while(performance.now()<end){}},{capture:true});</script>',+ );+ const outcome = await driver+ .play(+ drag({x: 200, y: 400}, {x: 200, y: 300}, {durationMs: 100, hz: 60}),+ {pacing: 'spacing'},+ )+ .then(+ () => 'resolved',+ (error: unknown) => error,+ );+ expect(outcome).toBeInstanceOf(TouchPageStallError);+ expect(String(outcome)).toMatch(+ /the page's own touch and pointer listeners took \d+ ms/,+ );+ });test("a page whose touch listener holds its main thread changes a paced flick's release itself: TouchPageStallError, never the runner's", async ({page,browserName,diff --git a/internal/interaction-harness/src/touch.pacing.test.ts b/internal/interaction-harness/src/touch.pacing.test.tsindex 15d2b83b2a..9f93402653 100644--- a/internal/interaction-harness/src/touch.pacing.test.ts+++ b/internal/interaction-harness/src/touch.pacing.test.ts@@ -321,6 +321,29 @@ describe("touchPacingFault on a paced play's arrivals", () => {);expect(touchPacingFault(FLICK, stalled, TOLERANCE)?.heldByPage).toBeNull();});++ it("counts a listener's time from when it began, so an event's wait for the main thread before it is named as a wait, not the page's listeners", () => {+ // The fourth event waited 28 ms for the main thread, then its listeners+ // ran 2 ms: its successor reaches the page 46 ms after it.+ const arrivals = at([0, 16, 32, 48, 94, 110, 126]);+ const waited = arrivals.map((a, i) =>+ i === 3 ? {...a, startedAt: a.stamp + 28, handledAt: a.stamp + 30} : a,+ );+ const fault = touchPacingFault(FLICK, waited, TOLERANCE);+ expect(fault?.heldByPage).toBeNull();+ expect(fault?.waited).toEqual({gapMs: 46, waitMs: 28});+ expect(String(new TouchPacingError(fault!))).toMatch(+ /an event waited 28 ms for the main thread before the page's listeners began, so the next reached it 46 ms later: another page task held the thread, or the runner starved it/,+ );+ // Its listeners began at once and ran 30 ms: the page's.+ const listened = arrivals.map((a, i) =>+ i === 3 ? {...a, startedAt: a.stamp, handledAt: a.stamp + 30} : a,+ );+ expect(touchPacingFault(FLICK, listened, TOLERANCE)?.heldByPage).toEqual({+ gapMs: 46,+ handlingMs: 30,+ });+ });});describe("the release a paced play's page reads, as Core's velocity tracker reads it", () => {diff --git a/internal/interaction-harness/src/touch.ts b/internal/interaction-harness/src/touch.tsindex 580c145fcd..02c3ececf3 100644--- a/internal/interaction-harness/src/touch.ts+++ b/internal/interaction-harness/src/touch.ts@@ -51,7 +51,12 @@ import {type TouchEventStep,type TouchScript,} from './scripts';-import {armInputRun, HELD_BACK_MS, type InputRun} from './webInput';+import {+ armInputRun,+ HELD_BACK_MS,+ installInputStart,+ type InputRun,+} from './webInput';export type Engine = 'chromium' | 'webkit';@@ -366,6 +371,11 @@ export interface TouchArrival {* NaN unseen.*/readonly handledAt: number;+ /**+ * When the page's listeners began on the step's first event, NaN unseen.+ * Before it, the step waited for the main thread.+ */+ readonly startedAt?: number;}/** Where the release a paced play's page read strays from the script's. */@@ -403,6 +413,15 @@ export interface TouchPacingFault {* dispatch can deliver a gesture's timing then.*/readonly frameGapMs?: number | null;+ /**+ * The widest gap that an event's wait for the main thread accounts for,+ * when the listeners alone do not, or null. The wait ends when the page's+ * listeners begin. Another page task, or a starved runner, held the event.+ */+ readonly waited?: {+ readonly gapMs: number;+ readonly waitMs: number;+ } | null;}/** The lifting finger's release, read from the page's stamps and the script's. */@@ -653,19 +672,43 @@ export function touchPacingFault(const gapsMs = span.map(i => arrivals[i].stamp - arrivals[i - 1].stamp);const scriptedGapsMs = span.map(i => steps[i].t - steps[i - 1].t);let heldByPage: TouchPacingFault['heldByPage'] = null;+ let waited: TouchPacingFault['waited'] = null;span.forEach((i, k) => {+ const holds = (ms: number) =>+ Number.isFinite(ms) &&+ ms > scriptedGapsMs[k] &&+ ms + HELD_BACK_MS >= gapsMs[k] - scriptedGapsMs[k];// The event before held this one back, or this step's own pointer- // listeners held its touch event (a lift read at its touchend).- const before = arrivals[i - 1].handledAt - arrivals[i - 1].stamp;- const own =- arrivals[i].stamp - (arrivals[i].firstStamp ?? arrivals[i].stamp);- for (const handlingMs of [before, own]) {- const held =- Number.isFinite(handlingMs) &&- handlingMs > scriptedGapsMs[k] &&- handlingMs + HELD_BACK_MS >= gapsMs[k] - scriptedGapsMs[k];- if (held && (heldByPage == null || handlingMs > heldByPage.handlingMs)) {- heldByPage = {gapMs: gapsMs[k], handlingMs};+ // listeners held its touch event (a lift read at its touchend). Each runs+ // from a stamp to the end of the listeners. The part before the+ // listeners began is a wait for the main thread, not listener time.+ const terms = [+ [+ arrivals[i - 1].stamp,+ arrivals[i - 1].startedAt,+ arrivals[i - 1].handledAt,+ ],+ [+ arrivals[i].firstStamp ?? arrivals[i].stamp,+ arrivals[i].startedAt,+ arrivals[i].stamp,+ ],+ ] as const;+ for (const [from, began, to] of terms) {+ const totalMs = to - from;+ const handlingMs =+ began != null && Number.isFinite(began)+ ? to - Math.max(began, from)+ : totalMs;+ if (holds(handlingMs)) {+ if (heldByPage == null || handlingMs > heldByPage.handlingMs) {+ heldByPage = {gapMs: gapsMs[k], handlingMs};+ }+ } else if (holds(totalMs)) {+ const waitMs = totalMs - handlingMs;+ if (waited == null || waitMs > waited.waitMs) {+ waited = {gapMs: gapsMs[k], waitMs};+ }}}});@@ -677,6 +720,7 @@ export function touchPacingFault(gapsMs,scriptedGapsMs,heldByPage,+ waited,threshold: boundaries.holdMs,holdMs: hold ?? undefined,};@@ -697,6 +741,7 @@ export function touchPacingFault(gapsMs,scriptedGapsMs,heldByPage,+ waited,threshold: strays ? undefined : releaseBound,};}@@ -754,14 +799,16 @@ function describeReading(fault: TouchPacingFault): string {}/**- * A paced play's page read a release that is not the script's, and its own- * touch and pointer listeners did not hold the events back: a dispatch stalled before- * the page. The runner failed, not the component under test.+ * A paced play's page read a release that is not the script's. Its own touch+ * and pointer listeners did not hold the events back: a dispatch stalled+ * before the page. When an event waited for the main thread before the page's+ * listeners began, the error says how long. Another page task, or a starved+ * runner, held it there.*/export class TouchPacingError extends Error {constructor(readonly fault: TouchPacingFault) {super(- `touchDriver: ${describeFault(fault)}: a dispatch stalled before the page`,+ `touchDriver: ${describeFault(fault)}: ${fault.waited == null ? 'a dispatch stalled before the page' : `an event waited ${fault.waited.waitMs.toFixed(0)} ms for the main thread before the page's listeners began, so the next reached it ${fault.waited.gapMs.toFixed(0)} ms later: another page task held the thread, or the runner starved it`}`,);this.name = 'TouchPacingError';}@@ -771,9 +818,11 @@ export class TouchPacingError extends Error {* A paced play's page read a release that is not the script's, and its own* touch and pointer listeners held an event back. They were still handling* the event before, and WebKit dispatches the next touch only once the page- * is free. The handling time is page wall time, which on a starved runner- * includes the page's wait for a CPU. Judge a page stall from a run with CI's- * CPU limits: there it is the proof's own failure.+ * is free. The handling time runs from when the listeners began, so a wait+ * for the main thread before them is not counted. It is page wall time,+ * which on a starved runner includes a listener's wait for a CPU. Judge a+ * page stall from a run with CI's CPU limits: there it is the proof's own+ * failure.*/export class TouchPageStallError extends Error {constructor(@@ -1123,16 +1172,19 @@ export function touchArrivalsFrom(record: {readonly pointerTypes: readonly string[];readonly stamps: readonly number[];readonly handledAt: readonly number[];+ readonly receivedAt?: readonly number[];}): TouchArrival[] {const arrivals: TouchArrival[] = [];let stamp = Number.POSITIVE_INFINITY;let handledAt = Number.NaN;+ let startedAt = Number.POSITIVE_INFINITY;record.eventTypes.forEach((type, i) => {// A mouse's or a pen's pointer event is not this play's.if (!type.startsWith('touch') && record.pointerTypes[i] !== 'touch') {return;}stamp = Math.min(stamp, record.stamps[i]);+ startedAt = Math.min(startedAt, record.receivedAt?.[i] ?? Number.NaN);const mark = record.handledAt[i];if (Number.isFinite(mark)) {handledAt = Number.isNaN(handledAt) ? mark : Math.max(handledAt, mark);@@ -1142,9 +1194,13 @@ export function touchArrivalsFrom(record: {stamp: type === 'touchstart' ? record.stamps[i] : stamp,firstStamp: stamp,handledAt,+ ...(record.receivedAt == null+ ? {}+ : {startedAt: Number.isFinite(startedAt) ? startedAt : Number.NaN}),});stamp = Number.POSITIVE_INFINITY;handledAt = Number.NaN;+ startedAt = Number.POSITIVE_INFINITY;}});return arrivals;@@ -1203,6 +1259,11 @@ function touchArrivalProbe(page: Page): TouchArrivalProbe {pointerTypes: recorded.pointerTypes.slice(),stamps: recorded.stamps.slice(),handledAt: recorded.handledAt.slice(),+ // Only a mark added before the page's scripts comes before every+ // page listener. Without it, the hold counts from the stamp.+ ...(recorded.startsFirst+ ? {receivedAt: recorded.receivedAt.slice()}+ : {}),};});await run.dispose();@@ -1222,6 +1283,7 @@ function touchArrivalProbe(page: Page): TouchArrivalProbe {async function webkitDriver(page: Page): Promise<TouchDriver> {const session = webkitPageSession(page);+ await installInputStart(page, TOUCH_TYPES);// WebKit's command takes integer CSS px and applies the event's phase to// every point it lists: a start lists only the fingers that land (listing a// finger already down presses it again), an end only the fingers that liftdiff --git a/internal/interaction-harness/src/webInput.ts b/internal/interaction-harness/src/webInput.tsindex ffa78950d1..9437579ce4 100644--- a/internal/interaction-harness/src/webInput.ts+++ b/internal/interaction-harness/src/webInput.ts@@ -382,6 +382,12 @@ export interface InputRun {stamps: number[];/** When the page's first listener received each event. */receivedAt: number[];+ /**+ * True while every event of the run carries the mark `installInputStart`+ * added before the page's scripts. Then `receivedAt` comes before every+ * page listener.+ */+ startsFirst: boolean;/*** When the page's own listeners had finished with each event, NaN until* seen. An event whose propagation the page stops is marked by a task@@ -402,11 +408,39 @@ export interface InputRun {stop: () => void;}+/**+ * Marks when the page's listeners begin on each trusted event of `types`,+ * with a passive window capture listener. Added before the page's scripts, it+ * runs before every page listener, a window capture one included, and+ * `armInputRun` uses its mark. A page already loaded gets it too. There it+ * runs after the window capture listeners the page added at load, such as a+ * gesture host's, so its mark is not used.+ */+export async function installInputStart(+ page: Page,+ types: readonly string[],+): Promise<void> {+ const script = (first: boolean) => `(() => {+ if (window.__harnessInputStart) return;+ const starts = new WeakMap();+ window.__harnessInputStart = {starts, first: ${first}};+ for (const type of ${JSON.stringify([...types])}) {+ window.addEventListener(type, event => {+ if (event.isTrusted && !starts.has(event)) starts.set(event, performance.now());+ }, {capture: true, passive: true});+ }+})()`;+ await page.addInitScript(script(true));+ await page.evaluate(script(false));+}+/*** Arms two passive listeners on the window before a run is dispatched. A* capture listener stamps each trusted event of `types` before the page's* own listeners. A bubble listener, after them, notes when the page has- * finished with the event. The wheel and touch drivers share it.+ * finished with the event. The wheel and touch drivers share it. Where+ * `installInputStart` marked, before the page's scripts, when the page's+ * listeners began on an event, that mark is the event's `receivedAt`.*/export function armInputRun(page: Page,@@ -420,10 +454,19 @@ export function armInputRun(// A message runs as a task of its own, after the dispatch that queued// it: it marks an event whose bubble listener never ran.const channel = new MessageChannel();+ const mark = (+ window as unknown as {+ __harnessInputStart?: {+ starts: WeakMap<Event, number>;+ first: boolean;+ };+ }+ ).__harnessInputStart;const run = {types: [...eventTypes],stamps: [] as number[],receivedAt: [] as number[],+ startsFirst: mark?.first === true,handledAt: [] as number[],eventTypes: [] as string[],pointerTypes: [] as string[],@@ -457,7 +500,13 @@ export function armInputRun(const i = run.stamps.length;index.set(event, i);run.stamps.push(event.timeStamp);- run.receivedAt.push(performance.now());+ const markedAt = run.startsFirst ? mark?.starts.get(event) : undefined;+ // A page that reopens its document drops the mark's listener but+ // keeps the mark. Its events go unmarked, and the run reads as before.+ if (markedAt == null) {+ run.startsFirst = false;+ }+ run.receivedAt.push(markedAt ?? performance.now());run.handledAt.push(Number.NaN);run.eventTypes.push(event.type);run.pointerTypes.push(