Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions internal/interaction-harness/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -210,3 +210,26 @@ simulator. Skip such a proof on the driver's flag, citing the reason:
The WebKit input command is reached through Playwright's in-process server
object, so it needs a locally launched browser (the default), not `connect()`.
Firefox has no touch input path and no project.

WebKit's touches carry their real dispatch time, so a velocity reaches the
page only as well as the dispatch keeps pace. `play` sends each event at its
scripted time, and never sooner after the one before it than the script spaces
them: a stall stretches one gap instead of sending the events behind it
together. With `{checkPacing: true}`, `play` then reads the `timeStamp`s the
page received and throws `TouchPacingError` where they decide a release: an
event missing, either of the last two move intervals (what a release velocity
reads) more than `TOUCH_PACING_TOLERANCE_MS` (4 ms) off the script, or the
lift `TOUCH_LIFT_STILLNESS_MS` (40 ms) or more after the last move. A
gesture's first moves and its lift reach the page with its own handling time
(a burst after `touchstart`, a lift a frame late), and no release reads them.
On one worker of a loaded machine, 440 gaps over 40 flicks moved at most 4 ms;
under eight workers, 4% of flicks had a gap further off, up to 21 ms. Wrap a
proof whose outcome follows a velocity in
`retakeOnTouchPacing(testInfo, attempt)`:
`attempt` builds the state, plays with `checkPacing` and asserts, and runs once
more only on a `TouchPacingError`, listed as a `touch-retake` annotation; a
second one fails the test with that cause.

A tap that must click uses `driver.tap` in both engines. WebKit synthesises no
click from a scripted touch sequence, so a proof that needs that click skips
with `test.skip(!driver.synthesizesClicks, SCRIPTED_CLICK_SKIP)`.
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,12 @@ import {
watchAnimations,
withFinger,
} from './index';
import {toTouchEvents} from './scripts';
import {
SCRIPTED_CLICK_SKIP,
TOUCH_PACING_TOLERANCE_MS,
TouchPacingError,
} from './touch';

const FIXTURE = `<!doctype html><meta name=viewport content="width=device-width,initial-scale=1">
<style>
Expand Down Expand Up @@ -267,6 +273,81 @@ test.describe('touch input', () => {
),
).toBe(2);
});

test('a scripted tap clicks where the driver says it does, and driver.tap clicks in both engines', async ({
page,
}) => {
await page.route('http://tap.test/', route =>
route.fulfill({
contentType: 'text/html',
body: `<!doctype html><meta name=viewport content="width=device-width,initial-scale=1"><body style="margin:0"><button id=b style="position:absolute;left:40px;top:40px;width:200px;height:80px">tap</button><script>window.__order=[];for(const type of ['touchstart','touchend','click'])b.addEventListener(type,()=>window.__order.push(type));</script>`,
}),
);
await page.goto('http://tap.test/');
const order = () =>
page.evaluate(() =>
(window as unknown as {__order: string[]}).__order.slice(),
);
const driver = await touchDriver(page);

await driver.play(tap({x: 140, y: 80}));
await driver.tap({x: 140, y: 80});
// driver.tap's click comes last, and a click of the scripted tap, if it
// gets one, before driver.tap's touchstart: no wait on the clock.
await expect
.poll(async () => {
const events = await order();
return events.lastIndexOf('click') > events.lastIndexOf('touchstart');
})
.toBe(true);
const events = await order();
const second = events.indexOf('touchstart', 1);
expect(events.slice(0, second)).toEqual(
driver.synthesizesClicks
? ['touchstart', 'touchend', 'click']
: ['touchstart', 'touchend'],
);
expect(events.slice(second)).toEqual(['touchstart', 'touchend', 'click']);
expect(SCRIPTED_CLICK_SKIP).toContain('driver.tap');
});

test('a gesture the page receives off its pacing throws TouchPacingError where the page times touches by their arrival', async ({
page,
}) => {
await fixture(page);
const driver = await touchDriver(page);
const script = flick(
{x: 160, y: 200},
{velocity: {x: 0, y: -1500}, durationMs: 96, hz: 120},
);
// The driver stalls 40 ms before the last move, as a dispatch does on a
// loaded runner: the interval a release velocity reads stretches.
const count = toTouchEvents(script).length;
const played = driver.play(script, {
checkPacing: true,
onEvent: async (_, index) => {
if (index === count - 3) {
await new Promise(r => setTimeout(r, 40));
}
},
});
if (driver.scriptedTimestamps) {
// Chromium: the page sees the script's stamps whatever the dispatch.
expect((await played).length).toBeGreaterThan(4);
return;
}
const error = await played.then(
() => null,
(thrown: unknown) => thrown,
);
expect(error).toBeInstanceOf(TouchPacingError);
const {scriptedGaps, receivedGaps} = error as TouchPacingError;
expect(receivedGaps).toHaveLength(scriptedGaps.length);
// The stall stretches the interval ending at the last move.
expect(receivedGaps[count - 3] - scriptedGaps[count - 3]).toBeGreaterThan(
TOUCH_PACING_TOLERANCE_MS,
);
});
});

test.describe('frame evidence', () => {
Expand Down
173 changes: 173 additions & 0 deletions internal/interaction-harness/src/touch.pacing.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.

/**
* @file touch.pacing.test.ts
* @input Touch scripts from ./scripts and synthetic page timestamps (no
* browser)
* @output The driver's pacing: after a stalled dispatch the events behind it
* keep their scripted gaps rather than leaving together; a gesture the page
* received off its pacing where a release reads it (its last two move
* intervals, its lift) fails `checkTouchPacing` with its gaps named; and
* `retakeOnTouchPacing` re-takes only such a gesture, once, listing it.
* @position Unit test of ./touch's pacing; the browser proof of the same
* behavior through WebKit's real input is in
* harness.interaction.browser.spec.ts.
*/

import {describe, expect, it} from 'vitest';
import {drag} from './scripts';
import {
checkTouchPacing,
playSteps,
retakeOnTouchPacing,
TOUCH_LIFT_STILLNESS_MS,
TOUCH_PACING_TOLERANCE_MS,
TouchPacingError,
} from './touch';

describe('playSteps', () => {
it('keeps the scripted gaps after a stalled dispatch instead of sending the events behind it together', async () => {
// A drag of six moves 12 ms apart; the third dispatch stalls 40 ms.
const script = drag(
{x: 0, y: 0},
{x: 0, y: 60},
{durationMs: 72, hz: 1000 / 12},
);
const sentAt: number[] = [];
let index = 0;
const played = await playSteps(
script,
{},
async () => {
sentAt.push(performance.now());
if (index === 2) {
await new Promise(resolve => setTimeout(resolve, 40));
}
index += 1;
},
t => t,
);
const scriptedGaps = played.slice(1).map((p, i) => p.t - played[i].t);
const sentGaps = sentAt.slice(1).map((t, i) => t - sentAt[i]);
// The stalled event's own gap stretches; every later one is at least
// its scripted gap (less a millisecond of timer slack), never a burst.
for (let i = 3; i < sentGaps.length; i += 1) {
expect(sentGaps[i], `gap ${i + 1}`).toBeGreaterThanOrEqual(
scriptedGaps[i] - 1,
);
}
expect(sentGaps[2]).toBeGreaterThanOrEqual(40);

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.

Node can resolve setTimeout(…, 40) up to about 1 ms early by performance.now(): repeating this case 120 times gave a stalled gap under 40 ms three times (minimum 39.31 ms), which would turn the required test check red with no cause in the code. The same 1 ms slack the later gaps get keeps the case red on the old scheduling, whose later gaps measure about 0 ms:

expect(sentGaps[2]).toBeGreaterThanOrEqual(39);

});
});

describe('checkTouchPacing', () => {
// A flick as the driver plays it: a touch-down, ten moves 8 ms apart, and
// the lift 2.1 ms after the last move.
const steps = [
{t: 0, type: 'touchStart'},
...Array.from({length: 10}, (_, i) => ({
t: 8 * (i + 1),
type: 'touchMove',
})),
{t: 82.1, type: 'touchEnd'},
];
/** Page timestamps from the gaps between them. */
const at = (gaps: readonly number[]) =>
gaps.reduce<number[]>(
(times, gap) => [...times, times[times.length - 1] + gap],
[1000],
);

it("passes the page's own handling in a gesture's first moves and its lift: a burst after the touch-down, a lift a frame late", () => {
// What WebKit delivered for a BottomSheet flick on an idle worker.
expect(() =>
checkTouchPacing(steps, at([4, 11, 3, 8, 8, 8, 8, 8, 8, 8, 9])),
).not.toThrow();
});

it('fails a stall and the burst behind it in the move intervals a release velocity reads, naming both gap lists', () => {
const received = at([8, 8, 8, 8, 8, 8, 8, 29, 2, 1, 2]);
expect(() => checkTouchPacing(steps, received)).toThrow(TouchPacingError);
try {
checkTouchPacing(steps, received);
} catch (error) {
const pacing = error as TouchPacingError;
expect(pacing.message).toMatch(
/the move interval ending at event 10, which a release velocity reads, is 6\.0 ms off/,
);
expect(pacing.receivedGaps).toEqual([8, 8, 8, 8, 8, 8, 8, 29, 2, 1, 2]);
expect(pacing.scriptedGaps.slice(0, 10)).toEqual(Array(10).fill(8));
}
// The same stall earlier, with the last two intervals on pace: the
// release reads the script's velocity.
expect(() =>
checkTouchPacing(steps, at([8, 8, 29, 2, 1, 2, 8, 8, 8, 8, 2])),
).not.toThrow();
});

it(`fails a lift that reaches the page ${TOUCH_LIFT_STILLNESS_MS} ms or more after the last move, where a release reads as still`, () => {
expect(() =>
checkTouchPacing(steps, at([8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 45])),
).toThrow(/the lift came 45\.0 ms after the last move/);
});

it('fails a gesture with an event missing, unless the touched element left the document', () => {
const received = at([8, 8, 8, 8]);
expect(() => checkTouchPacing(steps, received)).toThrow(
/5 touch events arrived for 12 dispatched/,
);
expect(() =>
checkTouchPacing(steps, received, {partial: true}),
).not.toThrow();
});

it('holds the tolerance it states', () => {
expect(TOUCH_PACING_TOLERANCE_MS).toBe(4);
});
});

describe('retakeOnTouchPacing', () => {
const offPace = () => new TouchPacingError('gap 4 is 21.0 ms off', [8], [29]);

it('re-takes a gesture received off pace once, and fails red when the second attempt is off pace too', async () => {
const info = {annotations: [] as {type: string; description?: string}[]};
const attempts: number[] = [];
await expect(
retakeOnTouchPacing(info, async n => {
attempts.push(n);
throw offPace();
}),
).rejects.toThrow(TouchPacingError);
expect(attempts).toEqual([1, 2]);
expect(info.annotations.map(a => a.type)).toEqual(['touch-retake']);
});

it('never re-takes a product failure after input that arrived on pace', async () => {
const info = {annotations: [] as {type: string; description?: string}[]};
const attempts: number[] = [];
await expect(
retakeOnTouchPacing(info, async n => {
attempts.push(n);
throw new Error('the sheet rested on full, expected half');
}),
).rejects.toThrow('the sheet rested on full, expected half');
expect(attempts).toEqual([1]);
expect(info.annotations).toEqual([]);
});

it('passes on a good second attempt after a bad first one, and lists the re-take', async () => {
const info = {annotations: [] as {type: string; description?: string}[]};
const value = await retakeOnTouchPacing(info, async n => {
if (n === 1) {
throw offPace();
}
return 'rested on half';
});
expect(value).toBe('rested on half');
expect(info.annotations).toHaveLength(1);
expect(info.annotations[0]).toMatchObject({
type: 'touch-retake',
description: expect.stringMatching(/off its scripted pacing/),
});
});
});
Loading