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-cancel-pending-press.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@e2e-dev/mobile": patch
---

Cancel pending taps, double taps, focus, check and uncheck actions when the step stops waiting for them or the run is interrupted. Input already sent to the device may still finish.
12 changes: 7 additions & 5 deletions docs/mobile.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -769,11 +769,13 @@ message and hint, never `LAUNCH_TIMEOUT`, `ACTION_FAILED`, or
**An action that outlives its timeout.** A tap, fill, key, swipe, or
`back` gets its `timeout` (default `actionTimeout`). If the device doesn't
answer in time, the step fails with `ACTION_FAILED` and isn't retried: the
input may have landed. A `longPress` that holds at least as long as the
time left is refused before it's sent; raise its `timeout`. Snapshots and
screenshots run within the timeout of the call that takes them, so a device
that stops answering fails the step with `ACTION_FAILED` instead of holding
it until the test timeout. `locator.waitFor`, `expect`, and
input may have landed. A pending tap, double tap, focus, check or uncheck is
cancelled when the step stops waiting for it or the run is interrupted. Input
already sent to the device may still finish. A `longPress` that holds at least
as long as the time left is refused before it's sent; raise its `timeout`.
Snapshots and screenshots run within the timeout of the call that takes them,
so a device that stops answering fails the step with `ACTION_FAILED` instead
of holding it until the test timeout. `locator.waitFor`, `expect`, and
`toHaveScreenshot` give their last snapshot extra time, up to their slowest
one so far and within the test timeout, so a screen that shows up during it
still passes. An element that never shows up fails as
Expand Down
9 changes: 7 additions & 2 deletions docs/reference/mobile.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -359,8 +359,13 @@ so a cold boot on CI is never charged against `launchTimeout`.
first attempt, and that device's app is not opened there.

<Note>
agent-device commands take no abort signal, so a timed-out command keeps
running on the device. The next attempt waits for it to settle.
A pending tap, double tap, focus, check or uncheck is cancelled when the step
stops waiting for it or the run is interrupted. This also covers the tap that
dismisses a keyboard tip.

Input already sent to the device may still finish.
Other commands can outlive their caller's timeout; the next attempt waits for
them to finish.
</Note>

#### Capabilities
Expand Down
23 changes: 14 additions & 9 deletions packages/mobile/src/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import type { LocatorActionKind, PointerAction, PointerActionKind, ViewportPoint } from 'e2e/engine';
import type { AgentDeviceClient } from './options.ts';
import { unsupported } from './support.ts';
import { unsupported, type InputBudget } from './support.ts';

/**
* The action kinds a device honors, declared so the harness offers exactly
Expand Down Expand Up @@ -63,27 +63,32 @@ export function pointerInteraction(
action: PointerAction,
settle: Record<string, unknown>,
stabilization: Record<string, unknown>,
input: InputBudget,
): Promise<unknown> {
const at = { x: point.x, y: point.y };
switch (action.kind) {
case 'tap':
return client.interactions.press({ ...at, ...settle });
return input.press(client, { ...at, ...settle });
case 'doubleTap':
return client.interactions.press({ ...at, count: 2, ...settle });
return input.press(client, { ...at, count: 2, ...settle });
case 'longPress':
return client.interactions.longPress({ ...at, ...settle, durationMs: action.durationMs ?? DEFAULT_LONG_PRESS_MS });
return input.send(
() => client.interactions.longPress({ ...at, ...settle, durationMs: action.durationMs ?? DEFAULT_LONG_PRESS_MS }),
action.durationMs ?? DEFAULT_LONG_PRESS_MS,
);
case 'swipeTo': {
const to = { x: action.target.x, y: action.target.y };
if (action.durationMs !== undefined) {
return client.interactions.pan({
const durationMs = action.durationMs;
if (durationMs !== undefined) {
return input.send(() => client.interactions.pan({
x: at.x,
y: at.y,
dx: to.x - at.x,
dy: to.y - at.y,
durationMs: action.durationMs,
});
durationMs,
}), durationMs);
}
return client.interactions.swipe({ from: at, to, ...stabilization });
return input.send(() => client.interactions.swipe({ from: at, to, ...stabilization }));
}
case 'secondaryTap':
case 'hover':
Expand Down
2 changes: 1 addition & 1 deletion packages/mobile/src/device.ts
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ export function createDeviceFixture(surface: AgentDeviceSurface, context: Engine
await surface.screenCommand('device.alert', (client) => client.command.alert({ ...surface.selection(), action }), context.signal);
},
async dismissKeyboard() {
await surface.dismissKeyboard(context.signal, surface.inputBudget('device.dismissKeyboard', context.timeouts.action));
await surface.dismissKeyboard(context.signal, surface.inputBudget('device.dismissKeyboard', { timeoutMs: context.timeouts.action, signal: context.signal }));
},
async clipboard() {
const result = await surface.command(
Expand Down
18 changes: 9 additions & 9 deletions packages/mobile/src/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,28 +34,28 @@ export function buildEngine(surface: AgentDeviceSurface): EngineHandle {
dispose: (context) => surface.dispose(context),
// The harness signal does not abort at an operation's budget, so each
// operation enforces its own; see InputBudget in support.ts.
observe: (operation, options) => surface.observe(operation, options, surface.inputBudget('observe', operation.timeoutMs)),
locate: (expression, operation) => surface.locate(expression, operation, surface.inputBudget('locate', operation.timeoutMs)),
perform: (ref, action, operation) => surface.perform(ref, action, operation, surface.inputBudget(action.kind, operation.timeoutMs)),
observe: (operation, options) => surface.observe(operation, options, surface.inputBudget('observe', operation)),
locate: (expression, operation) => surface.locate(expression, operation, surface.inputBudget('locate', operation)),
perform: (ref, action, operation) => surface.perform(ref, action, operation, surface.inputBudget(action.kind, operation)),
actions: DEVICE_ACTIONS,
performAt: (point, action, operation) => surface.performAt(point, action, operation, surface.inputBudget(action.kind, operation.timeoutMs)),
performAt: (point, action, operation) => surface.performAt(point, action, operation, surface.inputBudget(action.kind, operation)),
pointerActions: DEVICE_POINTER_ACTIONS,
keyboard: {
type: (text, keyboardOptions, operation) => surface.typeText(text, keyboardOptions, operation, surface.inputBudget('type', operation.timeoutMs)),
press: (key, operation) => surface.pressFocusedKey(key, operation, surface.inputBudget('press', operation.timeoutMs)),
dismiss: (operation) => surface.dismissKeyboard(operation.signal, surface.inputBudget('keyboard dismiss', operation.timeoutMs)),
type: (text, keyboardOptions, operation) => surface.typeText(text, keyboardOptions, operation, surface.inputBudget('type', operation)),
press: (key, operation) => surface.pressFocusedKey(key, operation, surface.inputBudget('press', operation)),
dismiss: (operation) => surface.dismissKeyboard(operation.signal, surface.inputBudget('keyboard dismiss', operation)),
},
validateApp: (app, info) => validateApp(app, info, surface.options.platform),
// No `open`: a device app has no URL to open, so the runner serves
// `app.open()` with `restart`, the fresh launch of the pinned app, which
// is also the device's "recreate the context".
session: {
back: (operation) => surface.back(operation, surface.inputBudget('back', operation.timeoutMs)),
back: (operation) => surface.back(operation, surface.inputBudget('back', operation)),
restart: (operation) => surface.restart(operation),
reset: (operation) => surface.reset(operation),
},
artifacts: {
screenshot: (label, operation) => surface.screenshot(label, operation, surface.inputBudget('screenshot', operation.timeoutMs)),
screenshot: (label, operation) => surface.screenshot(label, operation, surface.inputBudget('screenshot', operation)),
startVideo: (operation) => surface.startVideo(operation),
stopVideo: (operation) => surface.stopVideo(operation),
},
Expand Down
30 changes: 23 additions & 7 deletions packages/mobile/src/support.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
/** Shared helpers for the agent-device engine: error constructors, filenames, PNG headers, gestures, the screen location and size. */

import type { CaptureScreenshotResult } from 'agent-device';
import type { CaptureScreenshotResult, PressOptions } from 'agent-device';
import { EngineError, withTimeout, type Momentum, type ScrollDirection, type ViewportSize } from 'e2e/engine';
import type { AgentDeviceClient } from './options.ts';

export interface Point {
readonly x: number;
Expand Down Expand Up @@ -35,18 +36,27 @@ export class InputBudget {
private sent = false;

/**
* `track` keeps the device command itself in flight, past a timeout that
* abandons it, until it settles. The callers' own tracking settles with the
* race, so this is the registration the next attempt waits on.
* `track` keeps the SDK request in flight, past a timeout that abandons
* it, until its promise settles. Cancellation can settle that promise
* before already accepted native work ends.
*/
constructor(
private readonly label: string,
timeoutMs: number,
private readonly track: <T>(pending: Promise<T>) => Promise<T>,
private readonly signal: AbortSignal,
) {
this.endsAt = Date.now() + timeoutMs;
}

/**
* Press requests receive caller cancellation and are cancelled when this
* wait expires, including its existing acknowledgement allowance.
*/
press(client: AgentDeviceClient, options: PressOptions): Promise<unknown> {
return this.send((signal) => client.interactions.press({ ...options, signal }));
}

/**
* Sends one input with what is left of the budget. With none left it sends
* nothing: `OPERATION_TIMEOUT`, or `ACTION_MAY_HAVE_COMMITTED` once an
Expand All @@ -55,7 +65,7 @@ export class InputBudget {
* it is refused unsent. An input that does not answer in time may have
* landed, so it is `ACTION_MAY_HAVE_COMMITTED` and the runner never repeats it.
*/
send<T>(dispatch: () => Promise<T>, holdMs = 0): Promise<T> {
send<T>(dispatch: (signal: AbortSignal) => Promise<T>, holdMs = 0): Promise<T> {
const remaining = this.remainingMs();
if (remaining <= 0) return Promise.reject(this.spent());
if (holdMs >= remaining) {
Expand All @@ -67,9 +77,15 @@ export class InputBudget {
),
);
}
const pending = this.track(dispatch());
const answerMs = Math.max(remaining, MIN_ANSWER_MS);
const deadline = new AbortController();
const requestSignal = AbortSignal.any([this.signal, deadline.signal]);
Comment thread
shamilovtim marked this conversation as resolved.
Resolved
const pending = this.track(dispatch(requestSignal));
this.sent = true;
return withTimeout(pending, Math.max(remaining, MIN_ANSWER_MS), () => this.maybeCommitted());
return withTimeout(pending, answerMs, () => {
deadline.abort();
return this.maybeCommitted();
});
}

/**
Expand Down
28 changes: 13 additions & 15 deletions packages/mobile/src/surface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -470,10 +470,9 @@ export class AgentDeviceSurface {
/** How this worker's device records through its provider: set in init when the pool's provider records and the slot rides one of its leases. */
private leaseRecorder: LeaseRecorder | undefined;
/**
* Commands still running on the device. agent-device takes no abort
* signal, so a cancelled or timed-out call is only abandoned by its
* caller; it keeps executing. The next attempt waits for these to settle
* before it opens anything, so a ghost tap can never land in a retry.
* SDK requests still pending, including uncancelled commands abandoned
* by their caller. Cancelled press promises can settle before native
* work ends; agent-device owns its bounded drain and device-request ordering.
Comment thread
shamilovtim marked this conversation as resolved.
Resolved
*/
private readonly inflight = new Set<Promise<unknown>>();

Expand Down Expand Up @@ -573,9 +572,9 @@ export class AgentDeviceSurface {
return result;
}

/** The budget one operation runs under; its device commands stay in flight until they settle. */
inputBudget(label: string, timeoutMs: number): InputBudget {
return new InputBudget(label, timeoutMs, (pending) => this.track(pending));
/** The budget and cancellation signal shared by one operation's inputs. */
inputBudget(label: string, operation: Pick<OperationContext, 'timeoutMs' | 'signal'>): InputBudget {
return new InputBudget(label, operation.timeoutMs, (pending) => this.track(pending), operation.signal);
}

/** Registers one device command as in flight until it settles. */
Expand Down Expand Up @@ -1456,16 +1455,16 @@ export class AgentDeviceSurface {
}
switch (action.kind) {
case 'tap':
return input.send(() => client.interactions.press({ ...this.actionTarget(target, true), ...settle }));
return input.press(client, { ...this.actionTarget(target, true), ...settle });
case 'focus':
// A touch surface focuses by tapping, and a tap on anything but an
// editable field activates it; focus is offered for fields only.
if (target.node.role !== 'textbox') {
throw unsupported(`agent-device can only focus editable fields; node ${target.id} is ${target.node.role ?? 'unknown'}`);
}
return input.send(() => client.interactions.press({ ...this.actionTarget(target), ...settle }));
return input.press(client, { ...this.actionTarget(target), ...settle });
case 'doubleTap':
return input.send(() => client.interactions.press({ ...this.actionTarget(target), count: 2, ...settle }));
return input.press(client, { ...this.actionTarget(target), count: 2, ...settle });
case 'longPress':
return input.send(
() => client.interactions.longPress({ ...this.actionTarget(target), ...settle, durationMs: action.durationMs ?? DEFAULT_LONG_PRESS_MS }),
Expand All @@ -1490,7 +1489,7 @@ export class AgentDeviceSurface {
throw unsupported(`agent-device cannot read whether node ${target.id} is checked; tap it instead`);
}
if (checked === wanted) return undefined;
return input.send(() => client.interactions.press({ ...this.actionTarget(target, true), ...settle }));
return input.press(client, { ...this.actionTarget(target, true), ...settle });
}
case 'press':
return this.pressKey(client, target, action.key, settle, input);
Expand Down Expand Up @@ -1553,7 +1552,7 @@ export class AgentDeviceSurface {
// A key reaches the field through the soft keyboard, which is up only
// while the field holds focus.
if (entry.node.role === 'textbox' && entry.node.states?.focused !== true) {
await input.send(() => client.interactions.press({ ...this.actionTarget(entry), ...settle }));
await input.press(client, { ...this.actionTarget(entry), ...settle });
}
if (enter) return input.send(() => client.command.keyboard({ action: 'enter' }));
return input.send(() => client.interactions.type({ text: parsed.key.kind === 'char' ? parsed.key.char : ' ' }));
Expand All @@ -1567,8 +1566,7 @@ export class AgentDeviceSurface {
async performAt(point: ViewportPoint, action: PointerAction, operation: OperationContext, input: InputBudget): Promise<void> {
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, gestureStabilization(operation)), holdMs), operation.signal);
await this.command(`${action.kind} at point`, (client) => pointerInteraction(client, point, action, settle, gestureStabilization(operation), input), operation.signal);
if (action.kind === 'swipeTo') this.noteGesture(operation);
this.markAction(before);
}
Expand Down Expand Up @@ -1697,7 +1695,7 @@ export class AgentDeviceSurface {
const tipTop = tip.rect.y;
const button = nodes.find((node) => node.label === 'Continue' && node.rect !== undefined && node.rect.y > tipTop);
if (button?.rect === undefined) return raw;
await this.command('keyboard.dismiss', (client) => input.send(() => client.interactions.press(centreOf(button.rect!))), signal);
await this.command('keyboard.dismiss', (client) => input.press(client, centreOf(button.rect!)), signal);
return await this.snapshot(signal, false, input);
}

Expand Down
8 changes: 7 additions & 1 deletion packages/mobile/tests/helpers/fake-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export type Responder = (args: unknown) => unknown;
export interface RecordedCall {
readonly method: string;
readonly args: unknown;
readonly signal?: AbortSignal;
}

export interface FakeClient {
Expand All @@ -38,7 +39,12 @@ export function createFakeClient(initial: Readonly<Record<string, Responder>> =
},
apply: (_target, _self, args: unknown[]) => {
const method = path.join('.');
calls.push({ method, args: args[0] });
const argument = args[0];
const options = typeof argument === 'object' && argument !== null && 'signal' in argument
? argument as Record<string, unknown>
: undefined;
const { signal, ...recordedArgs } = options ?? {};
calls.push({ method, args: options === undefined ? argument : recordedArgs, ...(signal instanceof AbortSignal ? { signal } : {}) });
const responder = responders.get(method);
return Promise.resolve().then(() => (responder === undefined ? {} : responder(args[0])));
},
Expand Down
11 changes: 10 additions & 1 deletion packages/mobile/tests/unit/engine.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1342,6 +1342,9 @@ describe('perform', () => {
['interactions.scroll', { direction: 'up', settle: true, settleQuietMs: 150 }],
['interactions.drag', { source: '@e4', destination: '@e3' }],
]);
const presses = h.fake.calls.filter((call) => call.method === 'interactions.press');
expect(presses).not.toHaveLength(0);
expect(presses.every((call) => call.signal instanceof AbortSignal)).toBe(true);
});

it.each(['Enter', 'a'])('sends %s to a focused field without tapping it first', async (key) => {
Expand Down Expand Up @@ -1921,6 +1924,9 @@ describe('device fixture', () => {
await device.dismissKeyboard();
expect(h.fake.methods().slice(before)).toEqual(['command.keyboard', 'capture.snapshot', 'interactions.press', 'capture.snapshot']);
expect(h.fake.lastArgs('interactions.press')).toEqual({ x: 195, y: 722 });
const presses = h.fake.calls.filter((call) => call.method === 'interactions.press');
expect(presses).not.toHaveLength(0);
expect(presses.every((call) => call.signal instanceof AbortSignal)).toBe(true);
});

it('leaves any other refusal to the caller', async () => {
Expand Down Expand Up @@ -3353,7 +3359,7 @@ describe('deterministic actions', () => {
const search = await observed(h, 'Search');
if (action === 'Enter') await h.engine.perform!(search.ref, { kind: 'press', key: 'Enter' }, test());
else if (action === 'focused Enter') await h.engine.keyboard!.press('Enter', test());
else await h.surface.dismissKeyboard(test().signal, h.surface.inputBudget('keyboard dismiss', test().timeoutMs));
else await h.surface.dismissKeyboard(test().signal, h.surface.inputBudget('keyboard dismiss', test()));
h.fake.respond('capture.snapshot', () => ({ ...SETTINGS_SNAPSHOT, keyboard: { kind: 'absent' } }));
const stale = await observed(h, 'About');
h.fake.respond('capture.snapshot', () => ({
Expand Down Expand Up @@ -3441,6 +3447,9 @@ describe('deterministic actions', () => {
const about = await observed(h, 'About');
await h.engine.perform!(about.ref, { kind: 'tap' }, { ...operation(), origin: 'agent' });
expect(h.fake.lastArgs('interactions.press')).toEqual({ ref: '@e4', settle: true, settleQuietMs: 150 });
const presses = h.fake.calls.filter((call) => call.method === 'interactions.press');
expect(presses).not.toHaveLength(0);
expect(presses.every((call) => call.signal instanceof AbortSignal)).toBe(true);
});

it('skips the post-gesture stabilization wait for a test swipe and scroll, and keeps it for the agent', async () => {
Expand Down
Loading
Loading