Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .changeset/mobile-skip-post-gesture-stabilization.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@e2e-dev/mobile": patch
---

Send `postGestureStabilization: false` with a test's own swipe and scroll, so an agent-device release that accepts the option stops holding the next read for up to 3.5 s after a gesture the test then checks with `expect`. The first action on a control within 2 s of such a gesture re-reads the control until two reads agree on where it is, so a tap does not land on a list still coasting and get swallowed. The agent's gestures keep the wait. agent-device 0.21.36 ignores the option, so the speedup waits for a release that has it; until then the re-read adds one snapshot to the first action after a test's swipe or scroll.
6 changes: 4 additions & 2 deletions packages/mobile/src/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ export const DEVICE_POINTER_ACTIONS: readonly PointerActionKind[] = ['tap', 'dou
/**
* Issues one pointer action at a screen point in logical pixels. `settle` is
* the device's quiet-wait options, spread onto the interaction as the node
* actions do. A double tap is two presses (`count: 2`), as it is on a node:
* actions do; `stabilization` is the post-gesture option a swipe carries.
* A double tap is two presses (`count: 2`), as it is on a node:
* agent-device's own double-tap gesture reaches a React Native `Pressable`
* on iOS as one press, while two presses in a row land about 285 ms apart.
* The kinds outside `DEVICE_POINTER_ACTIONS` never arrive: the harness
Expand All @@ -61,6 +62,7 @@ export function pointerInteraction(
point: ViewportPoint,
action: PointerAction,
settle: Record<string, unknown>,
stabilization: Record<string, unknown>,
): Promise<unknown> {
const at = { x: point.x, y: point.y };
switch (action.kind) {
Expand All @@ -81,7 +83,7 @@ export function pointerInteraction(
durationMs: action.durationMs,
});
}
return client.interactions.swipe({ from: at, to });
return client.interactions.swipe({ from: at, to, ...stabilization });
}
case 'secondaryTap':
case 'hover':
Expand Down
84 changes: 81 additions & 3 deletions packages/mobile/src/surface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,17 @@ interface NodeBinding {
*/
const DEFAULT_TRANSITION_MS = 500;

/**
* How long after a test's swipe or scroll skipped agent-device's stabilization
* wait the next action on a control first confirms the control stopped moving.
* A list still coasting swallows a tap to stop itself, so the press would
* report success and change nothing.
*/
const GESTURE_STEADY_MS = 2_000;

/** Pause between the reads that confirm a control stopped moving after a gesture. */
const GESTURE_STEADY_POLL_MS = 100;

/** How one screenshot is taken. */
interface ScreenshotCapture {
/** The status bar in a fixed state (time, battery, signal), for a screenshot compared against a stored one (`comparable`). */
Expand Down Expand Up @@ -320,6 +331,14 @@ function sleep(ms: number, signal: AbortSignal): Promise<void> {
/** What agent-device is told about settling after an action. */
type SettleOptions = { readonly settle: true; readonly settleQuietMs: number } | Record<never, never>;

/**
* Whether agent-device holds the next read after a scroll or swipe until the
* tree stops moving. A test's gesture opts out: its `expect` polls the screen
* itself, and agent-device otherwise waits up to 3.5 s for a swipe that left
* the tree unchanged. An agent keeps the wait, since it reads the screen next.
*/
type GestureStabilizationOptions = { readonly postGestureStabilization: false } | Record<never, never>;

const DEFAULT_SETTLE_QUIET_MS = 150;

/** Every option `mobile()` takes, kept equal to `MobileOptions` by the compiler. */
Expand Down Expand Up @@ -386,6 +405,17 @@ function transitionMs(transition: MobileOptions['transition']): number {
return budget;
}

/** The stabilization wait a gesture carries: none for a test's own step, agent-device's default for the agent. */
function gestureStabilization(operation: OperationContext): GestureStabilizationOptions {
return operation.origin === 'test' ? { postGestureStabilization: false } : {};
Comment thread
kdy1 marked this conversation as resolved.
Resolved
}

/** True when two bounds are the same; a control without bounds has nothing to compare, so it counts as unmoved. */
function sameBounds(a: NodeBinding['node']['rect'], b: NodeBinding['node']['rect']): boolean {
if (a === undefined || b === undefined) return true;
return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
}

/** Resolves the `settle` option: the default window, a custom one, or no wait at all. */
function settleOptions(settle: MobileOptions['settle']): SettleOptions {
if (settle === false) return {};
Expand Down Expand Up @@ -453,6 +483,8 @@ export class AgentDeviceSurface {
readonly settleOptions: SettleOptions;
/** When this surface last acted on the device (an input or an app launch); the screen may be in transition for a while after. */
private lastActionAt = 0;
/** When a test's swipe or scroll last went out without agent-device's stabilization wait; 0 when nothing is pending. */
private skippedStabilizationAt = 0;
/** The screen as last projected before that action, to tell controls that were already there from ones that came with it. */
private screenBeforeAction: ProjectedScreen | undefined;
/** The most recent projection of the screen, from any observe or locate. */
Expand Down Expand Up @@ -1297,6 +1329,38 @@ export class AgentDeviceSurface {
return true;
}

/** Records that a test's gesture skipped the stabilization wait, so the next action on a control checks it stopped moving. */
private noteGesture(operation: OperationContext): void {
if (operation.origin === 'test') this.skippedStabilizationAt = Date.now();
}

/**
* After a gesture that skipped the stabilization wait, re-reads the control
* until two reads agree on where it is, so an action does not land on a list
* still coasting. Costs one extra snapshot when the screen already rests,
* and nothing once GESTURE_STEADY_MS has passed. An input action keeps the
* checks `relocated` makes on every read, and the poll never outlasts the
* action's budget.
*/
private async steadied(entry: NodeBinding, operation: OperationContext, budget: InputBudget, input: boolean): Promise<NodeBinding> {
const deadline = this.skippedStabilizationAt + GESTURE_STEADY_MS;
if (this.skippedStabilizationAt === 0 || Date.now() >= deadline) return entry;
let current = entry;
for (;;) {
const next = await this.relocated(current, operation, budget, input);
const steady = sameBounds(current.node.rect, next.node.rect);
Comment thread
kdy1 marked this conversation as resolved.
Resolved
current = next;
if (steady || Date.now() >= deadline) break;
if (budget.remainingMs() <= GESTURE_STEADY_POLL_MS) {
throw new EngineError('OPERATION_TIMEOUT', 'the control kept moving until the action budget ran out', { retryable: false });
}
await sleep(GESTURE_STEADY_POLL_MS, operation.signal);
if (operation.signal.aborted) throw new EngineError('CANCELLED', 'gesture wait cancelled', { retryable: false });
}
this.skippedStabilizationAt = 0;
return current;
}

/** Refreshes a control after a transition wait, keeping the binding when no wait was needed. */
private async settled(entry: NodeBinding, operation: OperationContext, budget: InputBudget): Promise<NodeBinding> {
if (await this.waitForTransition(entry, operation, budget)) return this.relocated(entry, operation, budget);
Expand Down Expand Up @@ -1354,7 +1418,13 @@ export class AgentDeviceSurface {
if (action.kind !== 'swipe') throw notActionable(`the screen root takes swipe only, not ${action.kind}; act on a node`);
if (deterministic) await this.waitOutTransition(operation, input);
const before = this.latestScreen;
await this.command('swipe', (client) => input.send(() => client.interactions.scroll({ direction: action.direction, ...settle })), operation.signal);
const stabilization = gestureStabilization(operation);
await this.command(
'swipe',
(client) => input.send(() => client.interactions.scroll({ direction: action.direction, ...settle, ...stabilization })),
operation.signal,
);
this.noteGesture(operation);
this.markAction(before);
return;
}
Expand All @@ -1380,6 +1450,10 @@ export class AgentDeviceSurface {
} else if (deterministic) {
target = await this.settled(entry, operation, input);
}
if (deterministic) {
target = await this.steadied(target, operation, input, filling);
if (filling && !target.takesText) throw refuseFill(target);
}
switch (action.kind) {
case 'tap':
return input.send(() => client.interactions.press({ ...this.actionTarget(target, true), ...settle }));
Expand Down Expand Up @@ -1423,7 +1497,10 @@ export class AgentDeviceSurface {
case 'swipe': {
const rect = target.node.rect;
if (rect === undefined) throw notActionable(`node ${target.id} has no bounds to swipe within`);
return input.send(() => client.interactions.swipe(swipeWithin(rect, action.direction, action.momentum)));
const stabilization = gestureStabilization(operation);
const sent = await input.send(() => client.interactions.swipe({ ...swipeWithin(rect, action.direction, action.momentum), ...stabilization }));
this.noteGesture(operation);
return sent;
}
case 'dragTo': {
// A test locates the drop target in a capture of its own, after the
Expand Down Expand Up @@ -1491,7 +1568,8 @@ export class AgentDeviceSurface {
const settle = operation.origin === 'test' ? {} : this.settleOptions;
const before = this.latestScreen;
const holdMs = action.kind === 'longPress' ? (action.durationMs ?? DEFAULT_LONG_PRESS_MS) : action.kind === 'swipeTo' ? action.durationMs : undefined;
await this.command(`${action.kind} at point`, (client) => input.send(() => pointerInteraction(client, point, action, settle), holdMs), operation.signal);
await this.command(`${action.kind} at point`, (client) => input.send(() => pointerInteraction(client, point, action, settle, gestureStabilization(operation)), holdMs), operation.signal);
if (action.kind === 'swipeTo') this.noteGesture(operation);
this.markAction(before);
}

Expand Down
128 changes: 125 additions & 3 deletions packages/mobile/tests/unit/engine.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -498,7 +498,7 @@ describe('lifecycle', () => {
const step: OperationContext = { ...operation(), origin: 'test' };
const slowScreen = await screenRootOf(slow);
await slow.engine.perform!(slowScreen.ref, { kind: 'swipe', direction: 'up', momentum: 'slow' }, step);
expect(slow.fake.lastArgs('interactions.scroll')).toEqual({ direction: 'up' });
expect(slow.fake.lastArgs('interactions.scroll')).toEqual({ direction: 'up', postGestureStabilization: false });

expect(() => harness({ settle: -1 })).toThrow(/non-negative integer/);
expect(() => harness({ settle: 1.5 })).toThrow(/non-negative integer/);
Expand Down Expand Up @@ -1941,7 +1941,7 @@ describe('device fixture', () => {
await h.engine.perform!(screen.ref, { kind: 'swipe', direction: 'down' }, { ...operation(), origin: 'test' });

expect(Date.now() - dismissedAt).toBe(120);
expect(h.fake.lastArgs('interactions.scroll')).toEqual({ direction: 'down' });
expect(h.fake.lastArgs('interactions.scroll')).toEqual({ direction: 'down', postGestureStabilization: false });
});

it('counts a back, home, alert, keyboard, rotation, or fold as an action, so a control that arrives with it waits out the transition budget', async () => {
Expand Down Expand Up @@ -3424,7 +3424,7 @@ describe('deterministic actions', () => {
await h.engine.performAt!({ x: 10, y: 20 }, { kind: 'longPress' }, test());
expect(h.fake.lastArgs('interactions.longPress')).toEqual({ x: 10, y: 20, durationMs: 1000 });
await h.engine.performAt!({ x: 10, y: 20 }, { kind: 'swipeTo', target: { x: 10, y: 300 } }, test());
expect(h.fake.lastArgs('interactions.swipe')).toEqual({ from: { x: 10, y: 20 }, to: { x: 10, y: 300 } });
expect(h.fake.lastArgs('interactions.swipe')).toEqual({ from: { x: 10, y: 20 }, to: { x: 10, y: 300 }, postGestureStabilization: false });
await h.engine.performAt!({ x: 10, y: 20 }, { kind: 'swipeTo', target: { x: 10, y: 300 }, durationMs: 400 }, test());
expect(h.fake.lastArgs('interactions.pan')).toEqual({ x: 10, y: 20, dx: 0, dy: 280, durationMs: 400 });
expect(h.engine.pointerActions).toEqual(['tap', 'doubleTap', 'longPress', 'swipeTo']);
Expand All @@ -3434,6 +3434,128 @@ describe('deterministic actions', () => {
expect(h.fake.lastArgs('interactions.press')).toEqual({ ref: '@e4', settle: true, settleQuietMs: 150 });
});

it('skips the post-gesture stabilization wait for a test swipe and scroll, and keeps it for the agent', async () => {
const h = harness({ settle: false });
await openAttempt(h);
await sleep(0);
const root = await screenRootOf(h);
const scroller = await observed(h, 'Scroller');
const step = test();
const agent: OperationContext = { ...operation(), origin: 'agent' };

await h.engine.perform!(root.ref, { kind: 'swipe', direction: 'down' }, step);
expect(h.fake.lastArgs('interactions.scroll')).toEqual({ direction: 'down', postGestureStabilization: false });
await h.engine.perform!(scroller.ref, { kind: 'swipe', direction: 'down' }, step);
expect(h.fake.lastArgs('interactions.swipe')).toEqual({
from: expect.any(Object),
to: expect.any(Object),
postGestureStabilization: false,
});

await h.engine.perform!(root.ref, { kind: 'swipe', direction: 'down' }, agent);
expect(h.fake.lastArgs('interactions.scroll')).toEqual({ direction: 'down' });
await h.engine.perform!(scroller.ref, { kind: 'swipe', direction: 'down' }, agent);
expect(h.fake.lastArgs('interactions.swipe')).toEqual({ from: expect.any(Object), to: expect.any(Object) });
});

it('re-reads a control until it rests before a test acts on it after a gesture that skipped the stabilization wait', async () => {
autoAdvanceTimers();
const h = harness({ settle: false, transition: 0 });
await openAttempt(h);
await sleep(0);
const root = await screenRootOf(h);
const about = await observed(h, 'About');
let reads = 0;
h.fake.respond('capture.snapshot', () => {
reads += 1;
const y = reads === 1 ? 150 : 180;
return { ...SETTINGS_SNAPSHOT, nodes: SETTINGS_NODES.map((node) => (node.ref === '@e4' ? { ...node, rect: { ...node.rect!, y } } : node)) };
});

await h.engine.perform!(root.ref, { kind: 'swipe', direction: 'down' }, test());
await h.engine.perform!(about.ref, { kind: 'tap' }, test());
// Two reads while the control still moved, one more to see it rest.
expect(reads).toBe(3);
expect(h.fake.methods().slice(-2)).toEqual(['capture.snapshot', 'interactions.press']);

reads = 10;
await h.engine.perform!(about.ref, { kind: 'tap' }, test());
expect(reads).toBe(10);
});

it('keeps the input checks on every re-read, so a field that turned disabled after a gesture is never filled', async () => {
autoAdvanceTimers();
const h = harness({ settle: false, transition: 0 });
await openAttempt(h);
await sleep(0);
const root = await screenRootOf(h);
const search = await observed(h, 'Search');
let reads = 0;
h.fake.respond('capture.snapshot', () => {
reads += 1;
const field = reads === 1 ? {} : { enabled: false };
return { ...SETTINGS_SNAPSHOT, nodes: SETTINGS_NODES.map((node) => (node.ref === '@e7' ? { ...node, ...field, rect: { ...node.rect!, y: 220 + reads * 10 } } : node)) };
});

await h.engine.perform!(root.ref, { kind: 'swipe', direction: 'down' }, test());
await expect(h.engine.perform!(search.ref, { kind: 'fill', value: 'blue', sensitive: false }, test())).rejects.toMatchObject({
code: 'NODE_STALE',
retryable: true,
});
expect(h.fake.methods()).not.toContain('interactions.fill');
});

it('stops re-reading a moving control once the action budget cannot fit another poll, and sends nothing', async () => {
autoAdvanceTimers();
const h = harness({ settle: false, transition: 0 });
await openAttempt(h);
await sleep(0);
const root = await screenRootOf(h);
const about = await observed(h, 'About');
let reads = 0;
h.fake.respond('capture.snapshot', () => {
reads += 1;
return { ...SETTINGS_SNAPSHOT, nodes: SETTINGS_NODES.map((node) => (node.ref === '@e4' ? { ...node, rect: { ...node.rect!, y: 120 + reads * 10 } } : node)) };
});

await h.engine.perform!(root.ref, { kind: 'swipe', direction: 'down' }, test());
await expect(h.engine.perform!(about.ref, { kind: 'tap' }, { ...test(), timeoutMs: 150 })).rejects.toMatchObject({ code: 'OPERATION_TIMEOUT' });
expect(h.fake.methods()).not.toContain('interactions.press');
});

it('re-reads a control before a node swipe too, so the swipe starts from where the control rests', async () => {
autoAdvanceTimers();
const h = harness({ settle: false, transition: 0 });
await openAttempt(h);
await sleep(0);
const root = await screenRootOf(h);
const scroller = await observed(h, 'Scroller');
let reads = 0;
h.fake.respond('capture.snapshot', () => {
reads += 1;
return { ...SETTINGS_SNAPSHOT, nodes: SETTINGS_NODES.map((node) => (node.ref === '@e10' ? { ...node, rect: { ...node.rect!, y: 350 } } : node)) };
});

await h.engine.perform!(root.ref, { kind: 'swipe', direction: 'down' }, test());
await h.engine.perform!(scroller.ref, { kind: 'swipe', direction: 'down' }, test());
// The control moved from y 320 to 350 after the gesture, then rested.
expect(reads).toBe(2);
expect(h.fake.lastArgs('interactions.swipe')).toMatchObject({ from: { y: expect.any(Number) } });
});

it('does not re-read a control after a gesture when the agent made it', async () => {
const h = harness({ settle: false, transition: 0 });
await openAttempt(h);
await sleep(0);
const root = await screenRootOf(h);
const about = await observed(h, 'About');
const agent: OperationContext = { ...operation(), origin: 'agent' };
const before = h.fake.methods().filter((m) => m === 'capture.snapshot').length;
await h.engine.perform!(root.ref, { kind: 'swipe', direction: 'down' }, agent);
await h.engine.perform!(about.ref, { kind: 'tap' }, agent);
expect(h.fake.methods().filter((m) => m === 'capture.snapshot')).toHaveLength(before);
});

it('does not dispatch an action whose transition wait was cancelled', async () => {
const h = harness({ transition: 300 });
await openAttempt(h);
Expand Down
Loading