From e31a26e761910fab7cfab8865c710cb1e6602642 Mon Sep 17 00:00:00 2001 From: Tim Shamilov Date: Tue, 10 Nov 2026 19:10:03 -0500 Subject: [PATCH 01/10] fix(mobile): cancel pending press requests at the input deadline --- .changeset/mobile-cancel-pending-press.md | 5 ++ docs/mobile.mdx | 3 +- packages/mobile/src/actions.ts | 5 +- packages/mobile/src/support.ts | 23 ++++++- packages/mobile/src/surface.ts | 18 +++--- packages/mobile/tests/unit/engine.test.ts | 62 +++++++++---------- .../tests/unit/input-cancellation.test.ts | 62 +++++++++++++++++++ 7 files changed, 132 insertions(+), 46 deletions(-) create mode 100644 .changeset/mobile-cancel-pending-press.md create mode 100644 packages/mobile/tests/unit/input-cancellation.test.ts diff --git a/.changeset/mobile-cancel-pending-press.md b/.changeset/mobile-cancel-pending-press.md new file mode 100644 index 0000000000..0a097d37ce --- /dev/null +++ b/.changeset/mobile-cancel-pending-press.md @@ -0,0 +1,5 @@ +--- +"@e2e-dev/mobile": patch +--- + +Cancel pending agent-device press requests when their caller is interrupted or their input budget expires. A press waiting for native readiness can no longer dispatch after the step has ended. Inputs that already dispatched keep their existing possibly-committed timeout behavior. diff --git a/docs/mobile.mdx b/docs/mobile.mdx index a3085a5cc7..940bf6e84f 100644 --- a/docs/mobile.mdx +++ b/docs/mobile.mdx @@ -769,7 +769,8 @@ 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 +input may have landed. Presses still waiting for native readiness are +cancelled at their timeout or on interruption. 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 diff --git a/packages/mobile/src/actions.ts b/packages/mobile/src/actions.ts index a585e654d8..92ccdcf119 100644 --- a/packages/mobile/src/actions.ts +++ b/packages/mobile/src/actions.ts @@ -63,13 +63,14 @@ export function pointerInteraction( action: PointerAction, settle: Record, stabilization: Record, + signal: AbortSignal, ): Promise { const at = { x: point.x, y: point.y }; switch (action.kind) { case 'tap': - return client.interactions.press({ ...at, ...settle }); + return client.interactions.press({ ...at, ...settle, signal }); case 'doubleTap': - return client.interactions.press({ ...at, count: 2, ...settle }); + return client.interactions.press({ ...at, count: 2, ...settle, signal }); case 'longPress': return client.interactions.longPress({ ...at, ...settle, durationMs: action.durationMs ?? DEFAULT_LONG_PRESS_MS }); case 'swipeTo': { diff --git a/packages/mobile/src/support.ts b/packages/mobile/src/support.ts index 19f75da9c6..77f34e7895 100644 --- a/packages/mobile/src/support.ts +++ b/packages/mobile/src/support.ts @@ -54,8 +54,10 @@ export class InputBudget { * at least as long as the budget left could only be cut off mid-gesture, so * 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. + * Press requests also receive the deadline and caller cancellation through + * the SDK signal, so readiness polling cannot dispatch after either ends. */ - send(dispatch: () => Promise, holdMs = 0): Promise { + send(dispatch: (signal: AbortSignal) => Promise, holdMs = 0, signal?: AbortSignal): Promise { const remaining = this.remainingMs(); if (remaining <= 0) return Promise.reject(this.spent()); if (holdMs >= remaining) { @@ -67,9 +69,24 @@ export class InputBudget { ), ); } - const pending = this.track(dispatch()); + if (signal?.aborted) return Promise.reject(cancelled(`${this.label} cancelled before it was sent`)); + const answerMs = Math.max(remaining, MIN_ANSWER_MS); + const deadline = new AbortController(); + // The answer allowance must not extend a pending press's dispatch deadline. + const timer = setTimeout(() => deadline.abort(), Math.ceil(remaining)); + const requestSignal = signal === undefined ? deadline.signal : AbortSignal.any([signal, deadline.signal]); + let pending: Promise; + try { + pending = this.track(dispatch(requestSignal)); + } catch (cause) { + clearTimeout(timer); + throw cause; + } this.sent = true; - return withTimeout(pending, Math.max(remaining, MIN_ANSWER_MS), () => this.maybeCommitted()); + return withTimeout(pending, answerMs, () => this.maybeCommitted()).catch((cause: unknown) => { + if (deadline.signal.aborted && signal?.aborted !== true) throw this.maybeCommitted(); + throw cause; + }).finally(() => clearTimeout(timer)); } /** diff --git a/packages/mobile/src/surface.ts b/packages/mobile/src/surface.ts index d749021aaa..1d178dc3fb 100644 --- a/packages/mobile/src/surface.ts +++ b/packages/mobile/src/surface.ts @@ -1456,16 +1456,16 @@ export class AgentDeviceSurface { } switch (action.kind) { case 'tap': - return input.send(() => client.interactions.press({ ...this.actionTarget(target, true), ...settle })); + return input.send((signal) => client.interactions.press({ ...this.actionTarget(target, true), ...settle, signal }), 0, operation.signal); 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.send((signal) => client.interactions.press({ ...this.actionTarget(target), ...settle, signal }), 0, operation.signal); case 'doubleTap': - return input.send(() => client.interactions.press({ ...this.actionTarget(target), count: 2, ...settle })); + return input.send((signal) => client.interactions.press({ ...this.actionTarget(target), count: 2, ...settle, signal }), 0, operation.signal); case 'longPress': return input.send( () => client.interactions.longPress({ ...this.actionTarget(target), ...settle, durationMs: action.durationMs ?? DEFAULT_LONG_PRESS_MS }), @@ -1490,10 +1490,10 @@ 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.send((signal) => client.interactions.press({ ...this.actionTarget(target, true), ...settle, signal }), 0, operation.signal); } case 'press': - return this.pressKey(client, target, action.key, settle, input); + return this.pressKey(client, target, action.key, settle, input, operation.signal); case 'swipe': { const rect = target.node.rect; if (rect === undefined) throw notActionable(`node ${target.id} has no bounds to swipe within`); @@ -1536,7 +1536,7 @@ export class AgentDeviceSurface { * modifiers and the other named keys (`Escape`, `Tab`, `Backspace`, the * arrows) have nothing to land on and are refused. */ - private async pressKey(client: AgentDeviceClient, entry: NodeBinding, key: string, settle: SettleOptions, input: InputBudget): Promise { + private async pressKey(client: AgentDeviceClient, entry: NodeBinding, key: string, settle: SettleOptions, input: InputBudget, signal: AbortSignal): Promise { const parsed = parseKey(key); if (parsed === undefined) { throw unsupported( @@ -1553,7 +1553,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.send((requestSignal) => client.interactions.press({ ...this.actionTarget(entry), ...settle, signal: requestSignal }), 0, signal); } if (enter) return input.send(() => client.command.keyboard({ action: 'enter' })); return input.send(() => client.interactions.type({ text: parsed.key.kind === 'char' ? parsed.key.char : ' ' })); @@ -1568,7 +1568,7 @@ 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, gestureStabilization(operation)), holdMs), operation.signal); + await this.command(`${action.kind} at point`, (client) => input.send((signal) => pointerInteraction(client, point, action, settle, gestureStabilization(operation), signal), holdMs, operation.signal), operation.signal); if (action.kind === 'swipeTo') this.noteGesture(operation); this.markAction(before); } @@ -1697,7 +1697,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.send((requestSignal) => client.interactions.press({ ...centreOf(button.rect!), signal: requestSignal }), 0, signal), signal); return await this.snapshot(signal, false, input); } diff --git a/packages/mobile/tests/unit/engine.test.ts b/packages/mobile/tests/unit/engine.test.ts index edcf91afe6..c080ff3b6c 100644 --- a/packages/mobile/tests/unit/engine.test.ts +++ b/packages/mobile/tests/unit/engine.test.ts @@ -490,13 +490,13 @@ describe('lifecycle', () => { await openAttempt(slow); const node = await observed(slow, 'About'); await slow.engine.perform!(node.ref, { kind: 'tap' }, operation()); - expect(slow.fake.lastArgs('interactions.press')).toEqual({ ref: '@e4', settle: true, settleQuietMs: 600 }); + expect(slow.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), ref: '@e4', settle: true, settleQuietMs: 600 }); const none = harness({ settle: false }); await openAttempt(none); const target = await observed(none, 'About'); await none.engine.perform!(target.ref, { kind: 'tap' }, operation()); - expect(none.fake.lastArgs('interactions.press')).toEqual({ ref: '@e4' }); + expect(none.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), ref: '@e4' }); await none.engine.session!.back!(operation()); expect(none.fake.lastArgs('command.back')).toEqual({}); const screen = await screenRootOf(none); @@ -1175,8 +1175,8 @@ describe('location', () => { await h.engine.perform!(back!.ref, { kind: 'tap' }, operation()); await h.engine.perform!(about.ref, { kind: 'tap' }, operation()); expect(h.fake.calls.filter((call) => call.method === 'interactions.press').map((call) => call.args)).toEqual([ - { ref: '@e3', settle: true, settleQuietMs: 150 }, - { ref: '@e4', settle: true, settleQuietMs: 150 }, + { signal: expect.any(AbortSignal), ref: '@e3', settle: true, settleQuietMs: 150 }, + { signal: expect.any(AbortSignal), ref: '@e4', settle: true, settleQuietMs: 150 }, ]); }); @@ -1317,25 +1317,25 @@ describe('perform', () => { await h.engine.perform!(root.ref, { kind: 'swipe', direction: 'up', momentum: 'fast' }, op); await h.engine.perform!(about!.ref, { kind: 'dragTo', target: back!.ref }, op); expect(h.fake.calls.slice(before).map((call) => [call.method, call.args])).toEqual([ - ['interactions.press', { ref: '@e4', settle: true, settleQuietMs: 150 }], - ['interactions.press', { ref: '@e4', count: 2, settle: true, settleQuietMs: 150 }], + ['interactions.press', { signal: expect.any(AbortSignal), ref: '@e4', settle: true, settleQuietMs: 150 }], + ['interactions.press', { signal: expect.any(AbortSignal), ref: '@e4', count: 2, settle: true, settleQuietMs: 150 }], ['interactions.longPress', { ref: '@e4', settle: true, settleQuietMs: 150, durationMs: 900 }], // No duration named: the engine's one-second hold, past a Pressable's delayLongPress. ['interactions.longPress', { ref: '@e4', settle: true, settleQuietMs: 150, durationMs: 1000 }], - ['interactions.press', { ref: '@e7', settle: true, settleQuietMs: 150 }], + ['interactions.press', { signal: expect.any(AbortSignal), ref: '@e7', settle: true, settleQuietMs: 150 }], ['interactions.hover', { ref: '@e4' }], ['capture.snapshot', { interactiveOnly: false }], ['interactions.fill', { ref: '@e7', text: 'blue', settle: true, settleQuietMs: 150 }], ['capture.snapshot', { interactiveOnly: false }], ['interactions.fill', { ref: '@e7', text: '', settle: true, settleQuietMs: 150 }], - ['interactions.press', { ref: '@e6', settle: true, settleQuietMs: 150 }], + ['interactions.press', { signal: expect.any(AbortSignal), ref: '@e6', settle: true, settleQuietMs: 150 }], // Enter reaches the field through the soft keyboard, so the unfocused field is tapped first. - ['interactions.press', { ref: '@e7', settle: true, settleQuietMs: 150 }], + ['interactions.press', { signal: expect.any(AbortSignal), ref: '@e7', settle: true, settleQuietMs: 150 }], ['command.keyboard', { action: 'enter' }], - ['interactions.press', { ref: '@e7', settle: true, settleQuietMs: 150 }], + ['interactions.press', { signal: expect.any(AbortSignal), ref: '@e7', settle: true, settleQuietMs: 150 }], ['interactions.type', { text: 'a' }], // Space is typed like a character, the unfocused field tapped first. - ['interactions.press', { ref: '@e7', settle: true, settleQuietMs: 150 }], + ['interactions.press', { signal: expect.any(AbortSignal), ref: '@e7', settle: true, settleQuietMs: 150 }], ['interactions.type', { text: ' ' }], ['interactions.swipe', { from: { x: 195, y: 620 }, to: { x: 195, y: 420 } }], // The root swipe is the viewport swipe: agent-device's whole-screen scroll at its default amount, settled like a tap. @@ -1384,10 +1384,10 @@ describe('perform', () => { ); await h.engine.perform!(located!.ref, { kind: 'uncheck' }, operation()); expect(h.fake.calls.slice(before).filter((call) => call.method === 'interactions.press').map((call) => call.args)).toEqual([ - { ref: '@e4', settle: true, settleQuietMs: 150 }, - { ref: '@e4', settle: true, settleQuietMs: 150 }, - { ref: '@e5', settle: true, settleQuietMs: 150 }, - { ref: '@e4', settle: true, settleQuietMs: 150 }, + { signal: expect.any(AbortSignal), ref: '@e4', settle: true, settleQuietMs: 150 }, + { signal: expect.any(AbortSignal), ref: '@e4', settle: true, settleQuietMs: 150 }, + { signal: expect.any(AbortSignal), ref: '@e5', settle: true, settleQuietMs: 150 }, + { signal: expect.any(AbortSignal), ref: '@e4', settle: true, settleQuietMs: 150 }, ]); }); @@ -1920,7 +1920,7 @@ describe('device fixture', () => { const before = h.fake.calls.length; 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 }); + expect(h.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), x: 195, y: 722 }); }); it('leaves any other refusal to the caller', async () => { @@ -1982,7 +1982,7 @@ describe('device fixture', () => { const submit = await observed(h, 'Submit'); await h.engine.perform!(submit.ref, { kind: 'tap' }, { ...operation(), origin: 'test' }); expect(Date.now() - startedAt).toBeGreaterThanOrEqual(100); - expect(h.fake.lastArgs('interactions.press')).toEqual({ ref: '@e11' }); + expect(h.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), ref: '@e11' }); } // A read leaves the budget alone: the clipboard changes no screen. await device.clipboard(); @@ -2531,8 +2531,8 @@ describe('snapshot generations', () => { await h.engine.perform!(toggle!.ref, { kind: 'check' }, op); await h.engine.perform!(about!.ref, { kind: 'dragTo', target: back!.ref }, op); expect(h.fake.calls.slice(before).map((call) => [call.method, call.args])).toEqual([ - ['interactions.press', { ref: '@e4~s7', settle: true, settleQuietMs: 150 }], - ['interactions.press', { ref: '@e6~s7', settle: true, settleQuietMs: 150 }], + ['interactions.press', { signal: expect.any(AbortSignal), ref: '@e4~s7', settle: true, settleQuietMs: 150 }], + ['interactions.press', { signal: expect.any(AbortSignal), ref: '@e6~s7', settle: true, settleQuietMs: 150 }], ['interactions.drag', { source: '@e4~s7', destination: '@e3~s7' }], ]); }); @@ -2566,7 +2566,7 @@ describe('snapshot generations', () => { const step: OperationContext = { ...operation(), origin: 'test' }; const about = await observed(h, 'About'); await h.engine.perform!(about.ref, { kind: 'tap' }, step); - expect(h.fake.lastArgs('interactions.press')).toEqual({ ref: '@e4~s8' }); + expect(h.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), ref: '@e4~s8' }); }); it('drags from a source found again after a transition to a target located before it', async () => { @@ -3214,13 +3214,13 @@ describe('deterministic actions', () => { * transition budget. An upper bound on wall-clock time says the same only * on an idle machine. */ - async function tapsAtOnce(h: Harness, node: SemanticNode, expected: unknown): Promise { + async function tapsAtOnce(h: Harness, node: SemanticNode, expected: Record): Promise { vi.setTimerTickMode('manual'); try { const pending = h.engine.perform!(node.ref, { kind: 'tap' }, test()); await new Promise((resolve) => setImmediate(resolve)); expect(vi.getTimerCount()).toBe(0); - expect(h.fake.lastArgs('interactions.press')).toEqual(expected); + expect(h.fake.lastArgs('interactions.press')).toEqual({ ...expected, signal: expect.any(AbortSignal) }); await pending; } finally { vi.setTimerTickMode('nextTimerAsync'); @@ -3255,7 +3255,7 @@ describe('deterministic actions', () => { const submit = await observed(h, 'Submit'); await h.engine.perform!(submit.ref, { kind: 'tap' }, test()); expect(Date.now() - startedAt).toBeGreaterThanOrEqual(100); - expect(h.fake.lastArgs('interactions.press')).toEqual({ ref: '@e11' }); + expect(h.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), ref: '@e11' }); }); it('acts on a control that came with the last action where a fresh snapshot lists it once the budget has passed', async () => { @@ -3276,7 +3276,7 @@ describe('deterministic actions', () => { const inFlight = await observed(h, 'Submit'); h.fake.respond('capture.snapshot', () => submit(600, '@e42')); await h.engine.perform!(inFlight.ref, { kind: 'tap' }, test()); - expect(h.fake.lastArgs('interactions.press')).toEqual({ ref: '@e42' }); + expect(h.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), ref: '@e42' }); // A missing control must be resolved again before any input is dispatched. h.fake.respond('capture.snapshot', () => SETTINGS_SNAPSHOT); @@ -3313,7 +3313,7 @@ describe('deterministic actions', () => { expect(h.fake.methods().filter((method) => method === 'interactions.press')).toHaveLength(presses); await h.engine.perform!((await observed(h, 'Chat')).ref, { kind: 'tap' }, test()); - expect(h.fake.lastArgs('interactions.press')).toEqual({ ref: '@e12' }); + expect(h.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), ref: '@e12' }); }); it.each( @@ -3342,7 +3342,7 @@ describe('deterministic actions', () => { ? { ...node, ref: '@e42', rect: { x: 0, y: 200, width: 390, height: 44 } } : node), })); await h.engine.perform!(stale.ref, { kind: 'tap' }, test()); - expect(h.fake.lastArgs('interactions.press')).toEqual({ ref: '@e42' }); + expect(h.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), ref: '@e42' }); }); it.each(['Enter', 'focused Enter', 'dismiss'] as const)('reobserves after %s hides the keyboard before the control moves', async action => { @@ -3362,7 +3362,7 @@ describe('deterministic actions', () => { ? { ...node, ref: '@e42', rect: { x: 0, y: 200, width: 390, height: 44 } } : node), })); await h.engine.perform!(stale.ref, { kind: 'tap' }, test()); - expect(h.fake.lastArgs('interactions.press')).toEqual({ ref: '@e42' }); + expect(h.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), ref: '@e42' }); }); it.each(['type', 'fill', 'clear'] as const)('keeps unchanged controls immediate after %s when keyboard state is unchanged', async action => { @@ -3394,7 +3394,7 @@ describe('deterministic actions', () => { nodes: [...SETTINGS_NODES, add('@e20', 200), { ...add('@e21', 610), index: 11 }], })); await h.engine.perform!(arriving.ref, { kind: 'tap' }, test()); - expect(h.fake.lastArgs('interactions.press')).toEqual({ ref: '@e21' }); + expect(h.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), ref: '@e21' }); }); it('gives a control that moved with the last action the budget too, and skips it once the budget has elapsed', async () => { @@ -3425,9 +3425,9 @@ describe('deterministic actions', () => { await h.engine.session!.back!(test()); expect(h.fake.lastArgs('command.back')).toEqual({}); await h.engine.performAt!({ x: 10, y: 20 }, { kind: 'tap' }, test()); - expect(h.fake.lastArgs('interactions.press')).toEqual({ x: 10, y: 20 }); + expect(h.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), x: 10, y: 20 }); await h.engine.performAt!({ x: 10, y: 20 }, { kind: 'doubleTap' }, test()); - expect(h.fake.lastArgs('interactions.press')).toEqual({ x: 10, y: 20, count: 2 }); + expect(h.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), x: 10, y: 20, count: 2 }); await h.engine.performAt!({ x: 10, y: 20 }, { kind: 'longPress', durationMs: 700 }, test()); expect(h.fake.lastArgs('interactions.longPress')).toEqual({ x: 10, y: 20, durationMs: 700 }); await h.engine.performAt!({ x: 10, y: 20 }, { kind: 'longPress' }, test()); @@ -3440,7 +3440,7 @@ 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 }); + expect(h.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), 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 () => { diff --git a/packages/mobile/tests/unit/input-cancellation.test.ts b/packages/mobile/tests/unit/input-cancellation.test.ts new file mode 100644 index 0000000000..8ce640b803 --- /dev/null +++ b/packages/mobile/tests/unit/input-cancellation.test.ts @@ -0,0 +1,62 @@ +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { createAgentDeviceClient } from 'agent-device'; +import { expect, it } from 'vitest'; +import type { OperationContext } from 'e2e/engine'; +import { buildEngine } from '../../src/engine.ts'; +import { AgentDeviceSurface } from '../../src/surface.ts'; +import { SETTINGS_SNAPSHOT } from '../helpers/fake-client.ts'; +import { boot } from '../helpers/harness.ts'; + +it.each(['caller abort', 'input deadline'] as const)('cancels a press waiting for readiness at the SDK boundary after %s', async (reason) => { + const stateDir = mkdtempSync(path.join(tmpdir(), 'e2e-input-cancel-')); + let releaseReady!: () => void; + let markStarted!: () => void; + let markFinished!: () => void; + const ready = new Promise((resolve) => { releaseReady = resolve; }); + const started = new Promise((resolve) => { markStarted = resolve; }); + const finished = new Promise((resolve) => { markFinished = resolve; }); + const controller = new AbortController(); + let delivered = 0; + const client = createAgentDeviceClient({ session: 'input-cancel', stateDir }, { + transport: async (request, context) => { + if (request.command === 'snapshot') return { ok: true, data: SETTINGS_SNAPSHOT }; + if (request.command === 'open') return { ok: true, data: { appName: 'Settings', appBundleId: 'com.apple.Preferences' } }; + if (request.command === 'press') { + markStarted(); + await ready; + if (context?.signal?.aborted !== true) delivered += 1; + markFinished(); + } + return { ok: true, data: {} }; + }, + }); + const engine = buildEngine(new AgentDeviceSurface({ platform: 'ios', transition: 0, settle: false }, () => client)); + const operation: OperationContext = { signal: controller.signal, timeoutMs: reason === 'input deadline' ? 100 : 30000, runId: 'run', attemptId: 'a1', origin: 'test' }; + try { + await boot({ engine, app: { bundleId: 'Settings' } }); + await engine.session!.restart!(operation); + const [target] = await engine.locate!({ kind: 'query', query: { kind: 'testId', value: { kind: 'string', value: 'ABOUT', exact: true } } }, operation); + expect(target).toBeDefined(); + const pressing = engine.perform!(target!.ref, { kind: 'tap' }, operation); + const rejected = expect(pressing).rejects.toMatchObject({ code: reason === 'caller abort' ? 'CANCELLED' : 'ACTION_MAY_HAVE_COMMITTED' }); + await started; + if (reason === 'caller abort') controller.abort(); + // Readiness arrives after the input deadline, within the existing 250 ms answer allowance. + const readinessTimer = reason === 'input deadline' ? setTimeout(releaseReady, 180) : undefined; + try { + await rejected; + } finally { + clearTimeout(readinessTimer); + } + // The external control becomes ready after the operation has already ended. + releaseReady(); + await finished; + expect(delivered).toBe(0); + } finally { + releaseReady(); + await engine.dispose!({ signal: new AbortController().signal, timeoutMs: 1000 }); + rmSync(stateDir, { recursive: true, force: true }); + } +}); From 31ceef35325ffbc14ef02cc1fd0893baf4e0b4c0 Mon Sep 17 00:00:00 2001 From: Tim Shamilov Date: Tue, 10 Nov 2026 19:21:38 -0500 Subject: [PATCH 02/10] fix(mobile): preserve response grace when cancelling presses --- .changeset/mobile-cancel-pending-press.md | 2 +- docs/mobile.mdx | 6 ++-- packages/mobile/src/support.ts | 27 +++++++-------- .../tests/unit/input-cancellation.test.ts | 34 +++++++++++++++---- 4 files changed, 44 insertions(+), 25 deletions(-) diff --git a/.changeset/mobile-cancel-pending-press.md b/.changeset/mobile-cancel-pending-press.md index 0a097d37ce..35c3c30a4f 100644 --- a/.changeset/mobile-cancel-pending-press.md +++ b/.changeset/mobile-cancel-pending-press.md @@ -2,4 +2,4 @@ "@e2e-dev/mobile": patch --- -Cancel pending agent-device press requests when their caller is interrupted or their input budget expires. A press waiting for native readiness can no longer dispatch after the step has ended. Inputs that already dispatched keep their existing possibly-committed timeout behavior. +Cancel pending agent-device press requests when their caller is interrupted or the adapter stops waiting for a response. This stops native readiness polling after a failed step while preserving the existing minimum 250 ms acknowledgement allowance and possibly-committed timeout behavior. diff --git a/docs/mobile.mdx b/docs/mobile.mdx index 940bf6e84f..f869fa59e8 100644 --- a/docs/mobile.mdx +++ b/docs/mobile.mdx @@ -769,8 +769,10 @@ 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. Presses still waiting for native readiness are -cancelled at their timeout or on interruption. A `longPress` that holds at least as long as the +input may have landed. Press requests are cancelled when the adapter stops +waiting, including its minimum 250 ms acknowledgement allowance, or on interruption. +This stops native readiness polling for an input that has not dispatched. +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 diff --git a/packages/mobile/src/support.ts b/packages/mobile/src/support.ts index 77f34e7895..51726bfd8b 100644 --- a/packages/mobile/src/support.ts +++ b/packages/mobile/src/support.ts @@ -1,6 +1,6 @@ /** 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 { isAgentDeviceError, type CaptureScreenshotResult } from 'agent-device'; import { EngineError, withTimeout, type Momentum, type ScrollDirection, type ViewportSize } from 'e2e/engine'; export interface Point { @@ -54,8 +54,8 @@ export class InputBudget { * at least as long as the budget left could only be cut off mid-gesture, so * 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. - * Press requests also receive the deadline and caller cancellation through - * the SDK signal, so readiness polling cannot dispatch after either ends. + * Press requests receive caller cancellation and are cancelled when this + * wait expires, including its existing acknowledgement allowance. */ send(dispatch: (signal: AbortSignal) => Promise, holdMs = 0, signal?: AbortSignal): Promise { const remaining = this.remainingMs(); @@ -72,21 +72,18 @@ export class InputBudget { if (signal?.aborted) return Promise.reject(cancelled(`${this.label} cancelled before it was sent`)); const answerMs = Math.max(remaining, MIN_ANSWER_MS); const deadline = new AbortController(); - // The answer allowance must not extend a pending press's dispatch deadline. - const timer = setTimeout(() => deadline.abort(), Math.ceil(remaining)); const requestSignal = signal === undefined ? deadline.signal : AbortSignal.any([signal, deadline.signal]); - let pending: Promise; - try { - pending = this.track(dispatch(requestSignal)); - } catch (cause) { - clearTimeout(timer); - throw cause; - } + const pending = this.track(dispatch(requestSignal)); this.sent = true; - return withTimeout(pending, answerMs, () => this.maybeCommitted()).catch((cause: unknown) => { - if (deadline.signal.aborted && signal?.aborted !== true) throw this.maybeCommitted(); + return withTimeout(pending, answerMs, () => { + deadline.abort(); + return this.maybeCommitted(); + }).catch((cause: unknown) => { + if (deadline.signal.aborted && signal?.aborted !== true && isAgentDeviceError(cause) && cause.details?.reason === 'request_canceled') { + throw this.maybeCommitted(); + } throw cause; - }).finally(() => clearTimeout(timer)); + }); } /** diff --git a/packages/mobile/tests/unit/input-cancellation.test.ts b/packages/mobile/tests/unit/input-cancellation.test.ts index 8ce640b803..5d2b8c9272 100644 --- a/packages/mobile/tests/unit/input-cancellation.test.ts +++ b/packages/mobile/tests/unit/input-cancellation.test.ts @@ -6,6 +6,7 @@ import { expect, it } from 'vitest'; import type { OperationContext } from 'e2e/engine'; import { buildEngine } from '../../src/engine.ts'; import { AgentDeviceSurface } from '../../src/surface.ts'; +import { InputBudget } from '../../src/support.ts'; import { SETTINGS_SNAPSHOT } from '../helpers/fake-client.ts'; import { boot } from '../helpers/harness.ts'; @@ -43,13 +44,7 @@ it.each(['caller abort', 'input deadline'] as const)('cancels a press waiting fo const rejected = expect(pressing).rejects.toMatchObject({ code: reason === 'caller abort' ? 'CANCELLED' : 'ACTION_MAY_HAVE_COMMITTED' }); await started; if (reason === 'caller abort') controller.abort(); - // Readiness arrives after the input deadline, within the existing 250 ms answer allowance. - const readinessTimer = reason === 'input deadline' ? setTimeout(releaseReady, 180) : undefined; - try { - await rejected; - } finally { - clearTimeout(readinessTimer); - } + await rejected; // The external control becomes ready after the operation has already ended. releaseReady(); await finished; @@ -60,3 +55,28 @@ it.each(['caller abort', 'input deadline'] as const)('cancels a press waiting fo rmSync(stateDir, { recursive: true, force: true }); } }); + +it.each(['press', 'type'] as const)('preserves the acknowledgement allowance for %s at the SDK boundary', async (command) => { + const stateDir = mkdtempSync(path.join(tmpdir(), 'e2e-input-ack-')); + let delivered = 0; + const client = createAgentDeviceClient({ session: 'input-ack', stateDir }, { + transport: async (request) => { + delivered += 1; + await new Promise((resolve) => setTimeout(resolve, 180)); + return request.command === 'type' + ? { ok: false, error: { code: 'UNSUPPORTED_OPERATION', message: 'Typing is unavailable' } } + : { ok: true, data: {} }; + }, + }); + const budget = new InputBudget(command, 100, (pending) => pending); + try { + if (command === 'press') { + await expect(budget.send((signal) => client.interactions.press({ x: 20, y: 20, signal }), 0, new AbortController().signal)).resolves.toBeDefined(); + } else { + await expect(budget.send(() => client.interactions.type({ text: 'hello' }))).rejects.toMatchObject({ code: 'UNSUPPORTED_OPERATION', message: 'Typing is unavailable' }); + } + expect(delivered).toBe(1); + } finally { + rmSync(stateDir, { recursive: true, force: true }); + } +}); From c282cf9099c907adf581872d0cf57e74b70719ac Mon Sep 17 00:00:00 2001 From: Tim Shamilov Date: Wed, 11 Nov 2026 00:03:33 -0500 Subject: [PATCH 03/10] fix(mobile): share cancellation across an operation --- .changeset/mobile-cancel-pending-press.md | 2 +- docs/mobile.mdx | 6 +- packages/mobile/src/device.ts | 2 +- packages/mobile/src/engine.ts | 18 ++-- packages/mobile/src/support.ts | 19 ++-- packages/mobile/src/surface.ts | 24 ++--- packages/mobile/tests/helpers/fake-client.ts | 8 +- packages/mobile/tests/unit/engine.test.ts | 64 ++++++------- .../tests/unit/input-cancellation.test.ts | 40 ++------- packages/mobile/tests/unit/support.test.ts | 89 ++++++++++++++++--- 10 files changed, 158 insertions(+), 114 deletions(-) diff --git a/.changeset/mobile-cancel-pending-press.md b/.changeset/mobile-cancel-pending-press.md index 35c3c30a4f..48e41e5b1a 100644 --- a/.changeset/mobile-cancel-pending-press.md +++ b/.changeset/mobile-cancel-pending-press.md @@ -2,4 +2,4 @@ "@e2e-dev/mobile": patch --- -Cancel pending agent-device press requests when their caller is interrupted or the adapter stops waiting for a response. This stops native readiness polling after a failed step while preserving the existing minimum 250 ms acknowledgement allowance and possibly-committed timeout behavior. +Cancel pending taps, double taps, focus and check actions when their timeout expires or the run is interrupted. Input already sent to the device may still finish. diff --git a/docs/mobile.mdx b/docs/mobile.mdx index f869fa59e8..634b0bf09f 100644 --- a/docs/mobile.mdx +++ b/docs/mobile.mdx @@ -769,9 +769,9 @@ 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. Press requests are cancelled when the adapter stops -waiting, including its minimum 250 ms acknowledgement allowance, or on interruption. -This stops native readiness polling for an input that has not dispatched. +input may have landed. A pending tap, double tap, focus or check is cancelled +when its timeout expires 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 diff --git a/packages/mobile/src/device.ts b/packages/mobile/src/device.ts index fadce6e459..2fa5d5a341 100644 --- a/packages/mobile/src/device.ts +++ b/packages/mobile/src/device.ts @@ -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', context.timeouts.action, context.signal)); }, async clipboard() { const result = await surface.command( diff --git a/packages/mobile/src/engine.ts b/packages/mobile/src/engine.ts index 0cfbbc8fa5..e8051b1505 100644 --- a/packages/mobile/src/engine.ts +++ b/packages/mobile/src/engine.ts @@ -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.timeoutMs, operation.signal)), + locate: (expression, operation) => surface.locate(expression, operation, surface.inputBudget('locate', operation.timeoutMs, operation.signal)), + perform: (ref, action, operation) => surface.perform(ref, action, operation, surface.inputBudget(action.kind, operation.timeoutMs, operation.signal)), 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.timeoutMs, operation.signal)), 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.timeoutMs, operation.signal)), + press: (key, operation) => surface.pressFocusedKey(key, operation, surface.inputBudget('press', operation.timeoutMs, operation.signal)), + dismiss: (operation) => surface.dismissKeyboard(operation.signal, surface.inputBudget('keyboard dismiss', operation.timeoutMs, operation.signal)), }, 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.timeoutMs, operation.signal)), 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.timeoutMs, operation.signal)), startVideo: (operation) => surface.startVideo(operation), stopVideo: (operation) => surface.stopVideo(operation), }, diff --git a/packages/mobile/src/support.ts b/packages/mobile/src/support.ts index 51726bfd8b..fe81096df6 100644 --- a/packages/mobile/src/support.ts +++ b/packages/mobile/src/support.ts @@ -1,6 +1,6 @@ /** Shared helpers for the agent-device engine: error constructors, filenames, PNG headers, gestures, the screen location and size. */ -import { isAgentDeviceError, type CaptureScreenshotResult } from 'agent-device'; +import type { CaptureScreenshotResult } from 'agent-device'; import { EngineError, withTimeout, type Momentum, type ScrollDirection, type ViewportSize } from 'e2e/engine'; export interface Point { @@ -35,14 +35,15 @@ 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: (pending: Promise) => Promise, + private readonly signal: AbortSignal, ) { this.endsAt = Date.now() + timeoutMs; } @@ -57,7 +58,7 @@ export class InputBudget { * Press requests receive caller cancellation and are cancelled when this * wait expires, including its existing acknowledgement allowance. */ - send(dispatch: (signal: AbortSignal) => Promise, holdMs = 0, signal?: AbortSignal): Promise { + send(dispatch: (signal: AbortSignal) => Promise, holdMs = 0): Promise { const remaining = this.remainingMs(); if (remaining <= 0) return Promise.reject(this.spent()); if (holdMs >= remaining) { @@ -69,20 +70,14 @@ export class InputBudget { ), ); } - if (signal?.aborted) return Promise.reject(cancelled(`${this.label} cancelled before it was sent`)); const answerMs = Math.max(remaining, MIN_ANSWER_MS); const deadline = new AbortController(); - const requestSignal = signal === undefined ? deadline.signal : AbortSignal.any([signal, deadline.signal]); + const requestSignal = AbortSignal.any([this.signal, deadline.signal]); const pending = this.track(dispatch(requestSignal)); this.sent = true; return withTimeout(pending, answerMs, () => { deadline.abort(); return this.maybeCommitted(); - }).catch((cause: unknown) => { - if (deadline.signal.aborted && signal?.aborted !== true && isAgentDeviceError(cause) && cause.details?.reason === 'request_canceled') { - throw this.maybeCommitted(); - } - throw cause; }); } diff --git a/packages/mobile/src/surface.ts b/packages/mobile/src/surface.ts index 1d178dc3fb..8942abdaec 100644 --- a/packages/mobile/src/surface.ts +++ b/packages/mobile/src/surface.ts @@ -573,9 +573,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, timeoutMs: number, signal: AbortSignal): InputBudget { + return new InputBudget(label, timeoutMs, (pending) => this.track(pending), signal); } /** Registers one device command as in flight until it settles. */ @@ -1456,16 +1456,16 @@ export class AgentDeviceSurface { } switch (action.kind) { case 'tap': - return input.send((signal) => client.interactions.press({ ...this.actionTarget(target, true), ...settle, signal }), 0, operation.signal); + return input.send((signal) => client.interactions.press({ ...this.actionTarget(target, true), ...settle, signal })); 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((signal) => client.interactions.press({ ...this.actionTarget(target), ...settle, signal }), 0, operation.signal); + return input.send((signal) => client.interactions.press({ ...this.actionTarget(target), ...settle, signal })); case 'doubleTap': - return input.send((signal) => client.interactions.press({ ...this.actionTarget(target), count: 2, ...settle, signal }), 0, operation.signal); + return input.send((signal) => client.interactions.press({ ...this.actionTarget(target), count: 2, ...settle, signal })); case 'longPress': return input.send( () => client.interactions.longPress({ ...this.actionTarget(target), ...settle, durationMs: action.durationMs ?? DEFAULT_LONG_PRESS_MS }), @@ -1490,10 +1490,10 @@ 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((signal) => client.interactions.press({ ...this.actionTarget(target, true), ...settle, signal }), 0, operation.signal); + return input.send((signal) => client.interactions.press({ ...this.actionTarget(target, true), ...settle, signal })); } case 'press': - return this.pressKey(client, target, action.key, settle, input, operation.signal); + return this.pressKey(client, target, action.key, settle, input); case 'swipe': { const rect = target.node.rect; if (rect === undefined) throw notActionable(`node ${target.id} has no bounds to swipe within`); @@ -1536,7 +1536,7 @@ export class AgentDeviceSurface { * modifiers and the other named keys (`Escape`, `Tab`, `Backspace`, the * arrows) have nothing to land on and are refused. */ - private async pressKey(client: AgentDeviceClient, entry: NodeBinding, key: string, settle: SettleOptions, input: InputBudget, signal: AbortSignal): Promise { + private async pressKey(client: AgentDeviceClient, entry: NodeBinding, key: string, settle: SettleOptions, input: InputBudget): Promise { const parsed = parseKey(key); if (parsed === undefined) { throw unsupported( @@ -1553,7 +1553,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((requestSignal) => client.interactions.press({ ...this.actionTarget(entry), ...settle, signal: requestSignal }), 0, signal); + await input.send((requestSignal) => client.interactions.press({ ...this.actionTarget(entry), ...settle, signal: requestSignal })); } if (enter) return input.send(() => client.command.keyboard({ action: 'enter' })); return input.send(() => client.interactions.type({ text: parsed.key.kind === 'char' ? parsed.key.char : ' ' })); @@ -1568,7 +1568,7 @@ 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((signal) => pointerInteraction(client, point, action, settle, gestureStabilization(operation), signal), holdMs, operation.signal), operation.signal); + await this.command(`${action.kind} at point`, (client) => input.send((signal) => pointerInteraction(client, point, action, settle, gestureStabilization(operation), signal), holdMs), operation.signal); if (action.kind === 'swipeTo') this.noteGesture(operation); this.markAction(before); } @@ -1697,7 +1697,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((requestSignal) => client.interactions.press({ ...centreOf(button.rect!), signal: requestSignal }), 0, signal), signal); + await this.command('keyboard.dismiss', (client) => input.send((requestSignal) => client.interactions.press({ ...centreOf(button.rect!), signal: requestSignal })), signal); return await this.snapshot(signal, false, input); } diff --git a/packages/mobile/tests/helpers/fake-client.ts b/packages/mobile/tests/helpers/fake-client.ts index d91a3260e2..b65e387720 100644 --- a/packages/mobile/tests/helpers/fake-client.ts +++ b/packages/mobile/tests/helpers/fake-client.ts @@ -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 { @@ -38,7 +39,12 @@ export function createFakeClient(initial: Readonly> = }, 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 + : 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]))); }, diff --git a/packages/mobile/tests/unit/engine.test.ts b/packages/mobile/tests/unit/engine.test.ts index c080ff3b6c..50c5cd3c79 100644 --- a/packages/mobile/tests/unit/engine.test.ts +++ b/packages/mobile/tests/unit/engine.test.ts @@ -490,13 +490,13 @@ describe('lifecycle', () => { await openAttempt(slow); const node = await observed(slow, 'About'); await slow.engine.perform!(node.ref, { kind: 'tap' }, operation()); - expect(slow.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), ref: '@e4', settle: true, settleQuietMs: 600 }); + expect(slow.fake.lastArgs('interactions.press')).toEqual({ ref: '@e4', settle: true, settleQuietMs: 600 }); const none = harness({ settle: false }); await openAttempt(none); const target = await observed(none, 'About'); await none.engine.perform!(target.ref, { kind: 'tap' }, operation()); - expect(none.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), ref: '@e4' }); + expect(none.fake.lastArgs('interactions.press')).toEqual({ ref: '@e4' }); await none.engine.session!.back!(operation()); expect(none.fake.lastArgs('command.back')).toEqual({}); const screen = await screenRootOf(none); @@ -1175,8 +1175,8 @@ describe('location', () => { await h.engine.perform!(back!.ref, { kind: 'tap' }, operation()); await h.engine.perform!(about.ref, { kind: 'tap' }, operation()); expect(h.fake.calls.filter((call) => call.method === 'interactions.press').map((call) => call.args)).toEqual([ - { signal: expect.any(AbortSignal), ref: '@e3', settle: true, settleQuietMs: 150 }, - { signal: expect.any(AbortSignal), ref: '@e4', settle: true, settleQuietMs: 150 }, + { ref: '@e3', settle: true, settleQuietMs: 150 }, + { ref: '@e4', settle: true, settleQuietMs: 150 }, ]); }); @@ -1317,25 +1317,25 @@ describe('perform', () => { await h.engine.perform!(root.ref, { kind: 'swipe', direction: 'up', momentum: 'fast' }, op); await h.engine.perform!(about!.ref, { kind: 'dragTo', target: back!.ref }, op); expect(h.fake.calls.slice(before).map((call) => [call.method, call.args])).toEqual([ - ['interactions.press', { signal: expect.any(AbortSignal), ref: '@e4', settle: true, settleQuietMs: 150 }], - ['interactions.press', { signal: expect.any(AbortSignal), ref: '@e4', count: 2, settle: true, settleQuietMs: 150 }], + ['interactions.press', { ref: '@e4', settle: true, settleQuietMs: 150 }], + ['interactions.press', { ref: '@e4', count: 2, settle: true, settleQuietMs: 150 }], ['interactions.longPress', { ref: '@e4', settle: true, settleQuietMs: 150, durationMs: 900 }], // No duration named: the engine's one-second hold, past a Pressable's delayLongPress. ['interactions.longPress', { ref: '@e4', settle: true, settleQuietMs: 150, durationMs: 1000 }], - ['interactions.press', { signal: expect.any(AbortSignal), ref: '@e7', settle: true, settleQuietMs: 150 }], + ['interactions.press', { ref: '@e7', settle: true, settleQuietMs: 150 }], ['interactions.hover', { ref: '@e4' }], ['capture.snapshot', { interactiveOnly: false }], ['interactions.fill', { ref: '@e7', text: 'blue', settle: true, settleQuietMs: 150 }], ['capture.snapshot', { interactiveOnly: false }], ['interactions.fill', { ref: '@e7', text: '', settle: true, settleQuietMs: 150 }], - ['interactions.press', { signal: expect.any(AbortSignal), ref: '@e6', settle: true, settleQuietMs: 150 }], + ['interactions.press', { ref: '@e6', settle: true, settleQuietMs: 150 }], // Enter reaches the field through the soft keyboard, so the unfocused field is tapped first. - ['interactions.press', { signal: expect.any(AbortSignal), ref: '@e7', settle: true, settleQuietMs: 150 }], + ['interactions.press', { ref: '@e7', settle: true, settleQuietMs: 150 }], ['command.keyboard', { action: 'enter' }], - ['interactions.press', { signal: expect.any(AbortSignal), ref: '@e7', settle: true, settleQuietMs: 150 }], + ['interactions.press', { ref: '@e7', settle: true, settleQuietMs: 150 }], ['interactions.type', { text: 'a' }], // Space is typed like a character, the unfocused field tapped first. - ['interactions.press', { signal: expect.any(AbortSignal), ref: '@e7', settle: true, settleQuietMs: 150 }], + ['interactions.press', { ref: '@e7', settle: true, settleQuietMs: 150 }], ['interactions.type', { text: ' ' }], ['interactions.swipe', { from: { x: 195, y: 620 }, to: { x: 195, y: 420 } }], // The root swipe is the viewport swipe: agent-device's whole-screen scroll at its default amount, settled like a tap. @@ -1384,10 +1384,10 @@ describe('perform', () => { ); await h.engine.perform!(located!.ref, { kind: 'uncheck' }, operation()); expect(h.fake.calls.slice(before).filter((call) => call.method === 'interactions.press').map((call) => call.args)).toEqual([ - { signal: expect.any(AbortSignal), ref: '@e4', settle: true, settleQuietMs: 150 }, - { signal: expect.any(AbortSignal), ref: '@e4', settle: true, settleQuietMs: 150 }, - { signal: expect.any(AbortSignal), ref: '@e5', settle: true, settleQuietMs: 150 }, - { signal: expect.any(AbortSignal), ref: '@e4', settle: true, settleQuietMs: 150 }, + { ref: '@e4', settle: true, settleQuietMs: 150 }, + { ref: '@e4', settle: true, settleQuietMs: 150 }, + { ref: '@e5', settle: true, settleQuietMs: 150 }, + { ref: '@e4', settle: true, settleQuietMs: 150 }, ]); }); @@ -1920,7 +1920,7 @@ describe('device fixture', () => { const before = h.fake.calls.length; 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({ signal: expect.any(AbortSignal), x: 195, y: 722 }); + expect(h.fake.lastArgs('interactions.press')).toEqual({ x: 195, y: 722 }); }); it('leaves any other refusal to the caller', async () => { @@ -1982,7 +1982,7 @@ describe('device fixture', () => { const submit = await observed(h, 'Submit'); await h.engine.perform!(submit.ref, { kind: 'tap' }, { ...operation(), origin: 'test' }); expect(Date.now() - startedAt).toBeGreaterThanOrEqual(100); - expect(h.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), ref: '@e11' }); + expect(h.fake.lastArgs('interactions.press')).toEqual({ ref: '@e11' }); } // A read leaves the budget alone: the clipboard changes no screen. await device.clipboard(); @@ -2531,8 +2531,8 @@ describe('snapshot generations', () => { await h.engine.perform!(toggle!.ref, { kind: 'check' }, op); await h.engine.perform!(about!.ref, { kind: 'dragTo', target: back!.ref }, op); expect(h.fake.calls.slice(before).map((call) => [call.method, call.args])).toEqual([ - ['interactions.press', { signal: expect.any(AbortSignal), ref: '@e4~s7', settle: true, settleQuietMs: 150 }], - ['interactions.press', { signal: expect.any(AbortSignal), ref: '@e6~s7', settle: true, settleQuietMs: 150 }], + ['interactions.press', { ref: '@e4~s7', settle: true, settleQuietMs: 150 }], + ['interactions.press', { ref: '@e6~s7', settle: true, settleQuietMs: 150 }], ['interactions.drag', { source: '@e4~s7', destination: '@e3~s7' }], ]); }); @@ -2566,7 +2566,7 @@ describe('snapshot generations', () => { const step: OperationContext = { ...operation(), origin: 'test' }; const about = await observed(h, 'About'); await h.engine.perform!(about.ref, { kind: 'tap' }, step); - expect(h.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), ref: '@e4~s8' }); + expect(h.fake.lastArgs('interactions.press')).toEqual({ ref: '@e4~s8' }); }); it('drags from a source found again after a transition to a target located before it', async () => { @@ -3214,13 +3214,13 @@ describe('deterministic actions', () => { * transition budget. An upper bound on wall-clock time says the same only * on an idle machine. */ - async function tapsAtOnce(h: Harness, node: SemanticNode, expected: Record): Promise { + async function tapsAtOnce(h: Harness, node: SemanticNode, expected: unknown): Promise { vi.setTimerTickMode('manual'); try { const pending = h.engine.perform!(node.ref, { kind: 'tap' }, test()); await new Promise((resolve) => setImmediate(resolve)); expect(vi.getTimerCount()).toBe(0); - expect(h.fake.lastArgs('interactions.press')).toEqual({ ...expected, signal: expect.any(AbortSignal) }); + expect(h.fake.lastArgs('interactions.press')).toEqual(expected); await pending; } finally { vi.setTimerTickMode('nextTimerAsync'); @@ -3255,7 +3255,7 @@ describe('deterministic actions', () => { const submit = await observed(h, 'Submit'); await h.engine.perform!(submit.ref, { kind: 'tap' }, test()); expect(Date.now() - startedAt).toBeGreaterThanOrEqual(100); - expect(h.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), ref: '@e11' }); + expect(h.fake.lastArgs('interactions.press')).toEqual({ ref: '@e11' }); }); it('acts on a control that came with the last action where a fresh snapshot lists it once the budget has passed', async () => { @@ -3276,7 +3276,7 @@ describe('deterministic actions', () => { const inFlight = await observed(h, 'Submit'); h.fake.respond('capture.snapshot', () => submit(600, '@e42')); await h.engine.perform!(inFlight.ref, { kind: 'tap' }, test()); - expect(h.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), ref: '@e42' }); + expect(h.fake.lastArgs('interactions.press')).toEqual({ ref: '@e42' }); // A missing control must be resolved again before any input is dispatched. h.fake.respond('capture.snapshot', () => SETTINGS_SNAPSHOT); @@ -3313,7 +3313,7 @@ describe('deterministic actions', () => { expect(h.fake.methods().filter((method) => method === 'interactions.press')).toHaveLength(presses); await h.engine.perform!((await observed(h, 'Chat')).ref, { kind: 'tap' }, test()); - expect(h.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), ref: '@e12' }); + expect(h.fake.lastArgs('interactions.press')).toEqual({ ref: '@e12' }); }); it.each( @@ -3342,7 +3342,7 @@ describe('deterministic actions', () => { ? { ...node, ref: '@e42', rect: { x: 0, y: 200, width: 390, height: 44 } } : node), })); await h.engine.perform!(stale.ref, { kind: 'tap' }, test()); - expect(h.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), ref: '@e42' }); + expect(h.fake.lastArgs('interactions.press')).toEqual({ ref: '@e42' }); }); it.each(['Enter', 'focused Enter', 'dismiss'] as const)('reobserves after %s hides the keyboard before the control moves', async action => { @@ -3353,7 +3353,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().timeoutMs, test().signal)); h.fake.respond('capture.snapshot', () => ({ ...SETTINGS_SNAPSHOT, keyboard: { kind: 'absent' } })); const stale = await observed(h, 'About'); h.fake.respond('capture.snapshot', () => ({ @@ -3362,7 +3362,7 @@ describe('deterministic actions', () => { ? { ...node, ref: '@e42', rect: { x: 0, y: 200, width: 390, height: 44 } } : node), })); await h.engine.perform!(stale.ref, { kind: 'tap' }, test()); - expect(h.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), ref: '@e42' }); + expect(h.fake.lastArgs('interactions.press')).toEqual({ ref: '@e42' }); }); it.each(['type', 'fill', 'clear'] as const)('keeps unchanged controls immediate after %s when keyboard state is unchanged', async action => { @@ -3394,7 +3394,7 @@ describe('deterministic actions', () => { nodes: [...SETTINGS_NODES, add('@e20', 200), { ...add('@e21', 610), index: 11 }], })); await h.engine.perform!(arriving.ref, { kind: 'tap' }, test()); - expect(h.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), ref: '@e21' }); + expect(h.fake.lastArgs('interactions.press')).toEqual({ ref: '@e21' }); }); it('gives a control that moved with the last action the budget too, and skips it once the budget has elapsed', async () => { @@ -3425,9 +3425,9 @@ describe('deterministic actions', () => { await h.engine.session!.back!(test()); expect(h.fake.lastArgs('command.back')).toEqual({}); await h.engine.performAt!({ x: 10, y: 20 }, { kind: 'tap' }, test()); - expect(h.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), x: 10, y: 20 }); + expect(h.fake.lastArgs('interactions.press')).toEqual({ x: 10, y: 20 }); await h.engine.performAt!({ x: 10, y: 20 }, { kind: 'doubleTap' }, test()); - expect(h.fake.lastArgs('interactions.press')).toEqual({ signal: expect.any(AbortSignal), x: 10, y: 20, count: 2 }); + expect(h.fake.lastArgs('interactions.press')).toEqual({ x: 10, y: 20, count: 2 }); await h.engine.performAt!({ x: 10, y: 20 }, { kind: 'longPress', durationMs: 700 }, test()); expect(h.fake.lastArgs('interactions.longPress')).toEqual({ x: 10, y: 20, durationMs: 700 }); await h.engine.performAt!({ x: 10, y: 20 }, { kind: 'longPress' }, test()); @@ -3440,7 +3440,7 @@ 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({ signal: expect.any(AbortSignal), ref: '@e4', settle: true, settleQuietMs: 150 }); + 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 () => { diff --git a/packages/mobile/tests/unit/input-cancellation.test.ts b/packages/mobile/tests/unit/input-cancellation.test.ts index 5d2b8c9272..e1a1eb2da0 100644 --- a/packages/mobile/tests/unit/input-cancellation.test.ts +++ b/packages/mobile/tests/unit/input-cancellation.test.ts @@ -6,16 +6,15 @@ import { expect, it } from 'vitest'; import type { OperationContext } from 'e2e/engine'; import { buildEngine } from '../../src/engine.ts'; import { AgentDeviceSurface } from '../../src/surface.ts'; -import { InputBudget } from '../../src/support.ts'; import { SETTINGS_SNAPSHOT } from '../helpers/fake-client.ts'; import { boot } from '../helpers/harness.ts'; -it.each(['caller abort', 'input deadline'] as const)('cancels a press waiting for readiness at the SDK boundary after %s', async (reason) => { +it.each(['caller abort', 'input deadline'] as const)('cancels a pending press at the SDK boundary after %s', async (reason) => { const stateDir = mkdtempSync(path.join(tmpdir(), 'e2e-input-cancel-')); - let releaseReady!: () => void; + let releaseRequest!: () => void; let markStarted!: () => void; let markFinished!: () => void; - const ready = new Promise((resolve) => { releaseReady = resolve; }); + const pendingRequest = new Promise((resolve) => { releaseRequest = resolve; }); const started = new Promise((resolve) => { markStarted = resolve; }); const finished = new Promise((resolve) => { markFinished = resolve; }); const controller = new AbortController(); @@ -26,7 +25,7 @@ it.each(['caller abort', 'input deadline'] as const)('cancels a press waiting fo if (request.command === 'open') return { ok: true, data: { appName: 'Settings', appBundleId: 'com.apple.Preferences' } }; if (request.command === 'press') { markStarted(); - await ready; + await pendingRequest; if (context?.signal?.aborted !== true) delivered += 1; markFinished(); } @@ -45,38 +44,13 @@ it.each(['caller abort', 'input deadline'] as const)('cancels a press waiting fo await started; if (reason === 'caller abort') controller.abort(); await rejected; - // The external control becomes ready after the operation has already ended. - releaseReady(); + // The external request resumes after the operation has already ended. + releaseRequest(); await finished; expect(delivered).toBe(0); } finally { - releaseReady(); + releaseRequest(); await engine.dispose!({ signal: new AbortController().signal, timeoutMs: 1000 }); rmSync(stateDir, { recursive: true, force: true }); } }); - -it.each(['press', 'type'] as const)('preserves the acknowledgement allowance for %s at the SDK boundary', async (command) => { - const stateDir = mkdtempSync(path.join(tmpdir(), 'e2e-input-ack-')); - let delivered = 0; - const client = createAgentDeviceClient({ session: 'input-ack', stateDir }, { - transport: async (request) => { - delivered += 1; - await new Promise((resolve) => setTimeout(resolve, 180)); - return request.command === 'type' - ? { ok: false, error: { code: 'UNSUPPORTED_OPERATION', message: 'Typing is unavailable' } } - : { ok: true, data: {} }; - }, - }); - const budget = new InputBudget(command, 100, (pending) => pending); - try { - if (command === 'press') { - await expect(budget.send((signal) => client.interactions.press({ x: 20, y: 20, signal }), 0, new AbortController().signal)).resolves.toBeDefined(); - } else { - await expect(budget.send(() => client.interactions.type({ text: 'hello' }))).rejects.toMatchObject({ code: 'UNSUPPORTED_OPERATION', message: 'Typing is unavailable' }); - } - expect(delivered).toBe(1); - } finally { - rmSync(stateDir, { recursive: true, force: true }); - } -}); diff --git a/packages/mobile/tests/unit/support.test.ts b/packages/mobile/tests/unit/support.test.ts index 683ad42794..31ad904d09 100644 --- a/packages/mobile/tests/unit/support.test.ts +++ b/packages/mobile/tests/unit/support.test.ts @@ -1,3 +1,7 @@ +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { createAgentDeviceClient } from 'agent-device'; import { describe, expect, it, vi } from 'vitest'; import { InputBudget, sanitizeFilename, screenLocation, swipeWithin } from '../../src/support.ts'; @@ -6,29 +10,29 @@ describe('support helpers', () => { const hung = () => new Promise(() => undefined); vi.useFakeTimers(); try { - const cut = new InputBudget('tap', 300, (pending) => pending).send(hung); + const cut = new InputBudget('tap', 300, (pending) => pending, new AbortController().signal).send(hung); const committed = expect(cut).rejects.toMatchObject({ code: 'ACTION_MAY_HAVE_COMMITTED' }); await vi.advanceTimersByTimeAsync(300); await committed; // Sent with almost nothing left, a tap still gets time to answer. - const late = new InputBudget('tap', 10, (pending) => pending).send(() => new Promise((resolve) => setTimeout(() => resolve('tapped'), 200))); + const late = new InputBudget('tap', 10, (pending) => pending, new AbortController().signal).send(() => new Promise((resolve) => setTimeout(() => resolve('tapped'), 200))); await vi.advanceTimersByTimeAsync(200); await expect(late).resolves.toBe('tapped'); // A spent budget sends nothing; after an input went out, the next one is refused as possibly committed. - const spent = new InputBudget('tap', 100, (pending) => pending); + const spent = new InputBudget('tap', 100, (pending) => pending, new AbortController().signal); await vi.advanceTimersByTimeAsync(100); let dispatched = false; await expect(spent.send(async () => (dispatched = true))).rejects.toMatchObject({ code: 'OPERATION_TIMEOUT', message: 'tap timed out before it was sent' }); expect(dispatched).toBe(false); - const twoStep = new InputBudget('press', 100, (pending) => pending); + const twoStep = new InputBudget('press', 100, (pending) => pending, new AbortController().signal); await twoStep.send(async () => undefined); await vi.advanceTimersByTimeAsync(100); await expect(twoStep.send(async () => undefined)).rejects.toMatchObject({ code: 'ACTION_MAY_HAVE_COMMITTED' }); // A command that throws before it is sent does not count as sent. - const refused = new InputBudget('press', 100, (pending) => pending); + const refused = new InputBudget('press', 100, (pending) => pending, new AbortController().signal); expect(() => refused.send(() => { throw new Error('no target'); })).toThrow('no target'); @@ -37,7 +41,7 @@ describe('support helpers', () => { // A hold the budget cannot cover is refused unsent, with the reason. let held = false; - await expect(new InputBudget('longPress', 2_000, (pending) => pending).send(async () => (held = true), 3_000)).rejects.toMatchObject({ + await expect(new InputBudget('longPress', 2_000, (pending) => pending, new AbortController().signal).send(async () => (held = true), 3_000)).rejects.toMatchObject({ code: 'NOT_ACTIONABLE', message: expect.stringMatching(/^longPress holds for 3000 ms, but only 2000 ms of its timeout are left/), }); @@ -52,19 +56,19 @@ describe('support helpers', () => { const hung = () => new Promise(() => undefined); vi.useFakeTimers(); try { - await expect(new InputBudget('snapshot', 300, (pending) => pending).read(async () => 'tree')).resolves.toBe('tree'); + await expect(new InputBudget('snapshot', 300, (pending) => pending, new AbortController().signal).read(async () => 'tree')).resolves.toBe('tree'); - const cut = new InputBudget('snapshot', 200, (pending) => pending).read(hung); + const cut = new InputBudget('snapshot', 200, (pending) => pending, new AbortController().signal).read(hung); const timedOut = expect(cut).rejects.toMatchObject({ code: 'OPERATION_TIMEOUT', message: 'snapshot timed out before the device answered' }); await vi.advanceTimersByTimeAsync(200); await timedOut; - const spent = new InputBudget('snapshot', 100, (pending) => pending); + const spent = new InputBudget('snapshot', 100, (pending) => pending, new AbortController().signal); await vi.advanceTimersByTimeAsync(100); await expect(spent.read(async () => 'late')).rejects.toMatchObject({ code: 'OPERATION_TIMEOUT', message: 'snapshot timed out before it was sent' }); // After a swipe went out, a read that does not answer must not let a replay send the swipe again. - const dismissal = new InputBudget('keyboard dismiss', 300, (pending) => pending); + const dismissal = new InputBudget('keyboard dismiss', 300, (pending) => pending, new AbortController().signal); await dismissal.send(async () => undefined); const after = dismissal.read(hung); const committed = expect(after).rejects.toMatchObject({ code: 'ACTION_MAY_HAVE_COMMITTED' }); @@ -102,3 +106,68 @@ describe('support helpers', () => { expect(sanitizeFilename('x'.repeat(100))).toHaveLength(64); }); }); + +it.each(['press', 'type'] as const)('preserves the acknowledgement allowance for %s at the SDK boundary', async (command) => { + const stateDir = mkdtempSync(path.join(tmpdir(), 'e2e-input-ack-')); + let delivered = 0; + const client = createAgentDeviceClient({ session: 'input-ack', stateDir }, { + transport: async (request) => { + delivered += 1; + await new Promise((resolve) => setTimeout(resolve, 180)); + return request.command === 'type' + ? { ok: false, error: { code: 'UNSUPPORTED_OPERATION', message: 'Typing is unavailable' } } + : { ok: true, data: {} }; + }, + }); + const budget = new InputBudget(command, 100, (pending) => pending, new AbortController().signal); + try { + if (command === 'press') { + await expect(budget.send((signal) => client.interactions.press({ x: 20, y: 20, signal }))).resolves.toBeDefined(); + } else { + await expect(budget.send((signal) => client.interactions.type({ text: 'hello', signal }))).rejects.toMatchObject({ code: 'UNSUPPORTED_OPERATION', message: 'Typing is unavailable' }); + } + expect(delivered).toBe(1); + } finally { + rmSync(stateDir, { recursive: true, force: true }); + } +}); + +it('keeps caller cancellation on later inputs from the same operation', async () => { + const stateDir = mkdtempSync(path.join(tmpdir(), 'e2e-input-operation-cancel-')); + const controller = new AbortController(); + let release!: () => void; + let markStarted!: () => void; + let markFinished!: () => void; + const held = new Promise((resolve) => { release = resolve; }); + const started = new Promise((resolve) => { markStarted = resolve; }); + const finished = new Promise((resolve) => { markFinished = resolve; }); + let requests = 0; + let delivered = 0; + const client = createAgentDeviceClient({ session: 'operation-cancel', stateDir }, { + transport: async (_request, context) => { + requests += 1; + if (requests === 2) { + markStarted(); + await held; + } + if (context?.signal?.aborted !== true) delivered += 1; + if (requests === 2) markFinished(); + return { ok: true, data: {} }; + }, + }); + const budget = new InputBudget('tap', 30000, (pending) => pending, controller.signal); + try { + await budget.send((signal) => client.interactions.press({ x: 20, y: 20, signal })); + const second = budget.send((signal) => client.interactions.press({ x: 30, y: 30, signal })); + const canceled = expect(second).rejects.toMatchObject({ details: { reason: 'request_canceled' } }); + await started; + controller.abort(); + await canceled; + release(); + await finished; + expect(delivered).toBe(1); + } finally { + release(); + rmSync(stateDir, { recursive: true, force: true }); + } +}); From 9dc33e80fc2545e2af56519fc780590259472b77 Mon Sep 17 00:00:00 2001 From: Tim Shamilov Date: Wed, 11 Nov 2026 00:38:02 -0500 Subject: [PATCH 04/10] docs(mobile): clarify pending request tracking --- packages/mobile/src/surface.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/mobile/src/surface.ts b/packages/mobile/src/surface.ts index 8942abdaec..8184291263 100644 --- a/packages/mobile/src/surface.ts +++ b/packages/mobile/src/surface.ts @@ -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. */ private readonly inflight = new Set>(); From ac80493b14d137628782d72aca07fcc4fb8b32e6 Mon Sep 17 00:00:00 2001 From: Tim Shamilov Date: Wed, 11 Nov 2026 01:32:16 -0500 Subject: [PATCH 05/10] docs(mobile): scope cancellation in the reference --- docs/reference/mobile.mdx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/reference/mobile.mdx b/docs/reference/mobile.mdx index 71d9efc64d..b932c564f9 100644 --- a/docs/reference/mobile.mdx +++ b/docs/reference/mobile.mdx @@ -359,8 +359,10 @@ so a cold boot on CI is never charged against `launchTimeout`. first attempt, and that device's app is not opened there. -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 or check is cancelled when its timeout expires +or the run is interrupted. Input already sent to the device may still finish. +Other commands can outlive their caller's timeout; the next attempt waits for +their SDK requests to settle. #### Capabilities From 1c15ae1d766200566df4aa4e8fc0f1650a7b4969 Mon Sep 17 00:00:00 2001 From: Tim Shamilov Date: Wed, 11 Nov 2026 01:39:32 -0500 Subject: [PATCH 06/10] docs(mobile): include all cancellable press paths --- docs/mobile.mdx | 2 +- docs/reference/mobile.mdx | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/mobile.mdx b/docs/mobile.mdx index 634b0bf09f..0456812ed3 100644 --- a/docs/mobile.mdx +++ b/docs/mobile.mdx @@ -769,7 +769,7 @@ 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 pending tap, double tap, focus or check is cancelled +input may have landed. A pending tap, double tap, focus, check or uncheck is cancelled when its timeout expires or the run is interrupted. Input already sent to the device may still finish. A `longPress` that holds at least as long as the diff --git a/docs/reference/mobile.mdx b/docs/reference/mobile.mdx index b932c564f9..797e4bea53 100644 --- a/docs/reference/mobile.mdx +++ b/docs/reference/mobile.mdx @@ -359,8 +359,11 @@ so a cold boot on CI is never charged against `launchTimeout`. first attempt, and that device's app is not opened there. -A pending tap, double tap, focus or check is cancelled when its timeout expires -or the run is interrupted. Input already sent to the device may still finish. +A pending tap, double tap, focus, check or uncheck is cancelled when its timeout +expires 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 their SDK requests to settle. From a4f0be54b13af13c3e0507b22830d98ad95bf2b4 Mon Sep 17 00:00:00 2001 From: Tim Shamilov Date: Wed, 11 Nov 2026 01:46:02 -0500 Subject: [PATCH 07/10] docs(mobile): include uncheck in the release note --- .changeset/mobile-cancel-pending-press.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/mobile-cancel-pending-press.md b/.changeset/mobile-cancel-pending-press.md index 48e41e5b1a..4f9e762570 100644 --- a/.changeset/mobile-cancel-pending-press.md +++ b/.changeset/mobile-cancel-pending-press.md @@ -2,4 +2,4 @@ "@e2e-dev/mobile": patch --- -Cancel pending taps, double taps, focus and check actions when their timeout expires or the run is interrupted. Input already sent to the device may still finish. +Cancel pending taps, double taps, focus, check and uncheck actions when their timeout expires or the run is interrupted. Input already sent to the device may still finish. From e15c05852c35de4067f691d0776629fb207c4d0c Mon Sep 17 00:00:00 2001 From: Tim Shamilov Date: Wed, 11 Nov 2026 10:56:04 -0500 Subject: [PATCH 08/10] fix(mobile): centralize cancellable press dispatch --- docs/reference/mobile.mdx | 2 +- packages/mobile/src/actions.ts | 24 +++++++++++++--------- packages/mobile/src/device.ts | 2 +- packages/mobile/src/engine.ts | 18 ++++++++-------- packages/mobile/src/support.ts | 13 +++++++++--- packages/mobile/src/surface.ts | 19 ++++++++--------- packages/mobile/tests/unit/engine.test.ts | 2 +- packages/mobile/tests/unit/support.test.ts | 6 +++--- 8 files changed, 48 insertions(+), 38 deletions(-) diff --git a/docs/reference/mobile.mdx b/docs/reference/mobile.mdx index 797e4bea53..9a4286e8fb 100644 --- a/docs/reference/mobile.mdx +++ b/docs/reference/mobile.mdx @@ -365,7 +365,7 @@ keyboard tip. Input already sent to the device may still finish. Other commands can outlive their caller's timeout; the next attempt waits for -their SDK requests to settle. +them to finish. #### Capabilities diff --git a/packages/mobile/src/actions.ts b/packages/mobile/src/actions.ts index 92ccdcf119..d28fa6a0c2 100644 --- a/packages/mobile/src/actions.ts +++ b/packages/mobile/src/actions.ts @@ -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 @@ -63,28 +63,32 @@ export function pointerInteraction( action: PointerAction, settle: Record, stabilization: Record, - signal: AbortSignal, + input: InputBudget, ): Promise { const at = { x: point.x, y: point.y }; switch (action.kind) { case 'tap': - return client.interactions.press({ ...at, ...settle, signal }); + return input.press(client, { ...at, ...settle }); case 'doubleTap': - return client.interactions.press({ ...at, count: 2, ...settle, signal }); + 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': diff --git a/packages/mobile/src/device.ts b/packages/mobile/src/device.ts index 2fa5d5a341..8f18ecb75c 100644 --- a/packages/mobile/src/device.ts +++ b/packages/mobile/src/device.ts @@ -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, context.signal)); + await surface.dismissKeyboard(context.signal, surface.inputBudget('device.dismissKeyboard', { timeoutMs: context.timeouts.action, signal: context.signal })); }, async clipboard() { const result = await surface.command( diff --git a/packages/mobile/src/engine.ts b/packages/mobile/src/engine.ts index e8051b1505..eb4892bf21 100644 --- a/packages/mobile/src/engine.ts +++ b/packages/mobile/src/engine.ts @@ -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, operation.signal)), - locate: (expression, operation) => surface.locate(expression, operation, surface.inputBudget('locate', operation.timeoutMs, operation.signal)), - perform: (ref, action, operation) => surface.perform(ref, action, operation, surface.inputBudget(action.kind, operation.timeoutMs, operation.signal)), + 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, operation.signal)), + 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, operation.signal)), - press: (key, operation) => surface.pressFocusedKey(key, operation, surface.inputBudget('press', operation.timeoutMs, operation.signal)), - dismiss: (operation) => surface.dismissKeyboard(operation.signal, surface.inputBudget('keyboard dismiss', operation.timeoutMs, operation.signal)), + 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, operation.signal)), + 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, operation.signal)), + screenshot: (label, operation) => surface.screenshot(label, operation, surface.inputBudget('screenshot', operation)), startVideo: (operation) => surface.startVideo(operation), stopVideo: (operation) => surface.stopVideo(operation), }, diff --git a/packages/mobile/src/support.ts b/packages/mobile/src/support.ts index fe81096df6..87697ff80e 100644 --- a/packages/mobile/src/support.ts +++ b/packages/mobile/src/support.ts @@ -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; @@ -48,6 +49,14 @@ export class InputBudget { 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 { + 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 @@ -55,8 +64,6 @@ export class InputBudget { * at least as long as the budget left could only be cut off mid-gesture, so * 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. - * Press requests receive caller cancellation and are cancelled when this - * wait expires, including its existing acknowledgement allowance. */ send(dispatch: (signal: AbortSignal) => Promise, holdMs = 0): Promise { const remaining = this.remainingMs(); diff --git a/packages/mobile/src/surface.ts b/packages/mobile/src/surface.ts index 8184291263..a9b4181629 100644 --- a/packages/mobile/src/surface.ts +++ b/packages/mobile/src/surface.ts @@ -573,8 +573,8 @@ export class AgentDeviceSurface { } /** The budget and cancellation signal shared by one operation's inputs. */ - inputBudget(label: string, timeoutMs: number, signal: AbortSignal): InputBudget { - return new InputBudget(label, timeoutMs, (pending) => this.track(pending), signal); + inputBudget(label: string, operation: Pick): InputBudget { + return new InputBudget(label, operation.timeoutMs, (pending) => this.track(pending), operation.signal); } /** Registers one device command as in flight until it settles. */ @@ -1455,16 +1455,16 @@ export class AgentDeviceSurface { } switch (action.kind) { case 'tap': - return input.send((signal) => client.interactions.press({ ...this.actionTarget(target, true), ...settle, signal })); + 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((signal) => client.interactions.press({ ...this.actionTarget(target), ...settle, signal })); + return input.press(client, { ...this.actionTarget(target), ...settle }); case 'doubleTap': - return input.send((signal) => client.interactions.press({ ...this.actionTarget(target), count: 2, ...settle, signal })); + 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 }), @@ -1489,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((signal) => client.interactions.press({ ...this.actionTarget(target, true), ...settle, signal })); + return input.press(client, { ...this.actionTarget(target, true), ...settle }); } case 'press': return this.pressKey(client, target, action.key, settle, input); @@ -1552,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((requestSignal) => client.interactions.press({ ...this.actionTarget(entry), ...settle, signal: requestSignal })); + 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 : ' ' })); @@ -1566,8 +1566,7 @@ export class AgentDeviceSurface { async performAt(point: ViewportPoint, action: PointerAction, operation: OperationContext, input: InputBudget): Promise { 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((signal) => pointerInteraction(client, point, action, settle, gestureStabilization(operation), signal), 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); } @@ -1696,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((requestSignal) => client.interactions.press({ ...centreOf(button.rect!), signal: requestSignal })), signal); + await this.command('keyboard.dismiss', (client) => input.press(client, centreOf(button.rect!)), signal); return await this.snapshot(signal, false, input); } diff --git a/packages/mobile/tests/unit/engine.test.ts b/packages/mobile/tests/unit/engine.test.ts index 50c5cd3c79..fdaff0a5fe 100644 --- a/packages/mobile/tests/unit/engine.test.ts +++ b/packages/mobile/tests/unit/engine.test.ts @@ -3353,7 +3353,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, test().signal)); + 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', () => ({ diff --git a/packages/mobile/tests/unit/support.test.ts b/packages/mobile/tests/unit/support.test.ts index 31ad904d09..b7871d2a64 100644 --- a/packages/mobile/tests/unit/support.test.ts +++ b/packages/mobile/tests/unit/support.test.ts @@ -122,7 +122,7 @@ it.each(['press', 'type'] as const)('preserves the acknowledgement allowance for const budget = new InputBudget(command, 100, (pending) => pending, new AbortController().signal); try { if (command === 'press') { - await expect(budget.send((signal) => client.interactions.press({ x: 20, y: 20, signal }))).resolves.toBeDefined(); + await expect(budget.press(client, { x: 20, y: 20 })).resolves.toBeDefined(); } else { await expect(budget.send((signal) => client.interactions.type({ text: 'hello', signal }))).rejects.toMatchObject({ code: 'UNSUPPORTED_OPERATION', message: 'Typing is unavailable' }); } @@ -157,8 +157,8 @@ it('keeps caller cancellation on later inputs from the same operation', async () }); const budget = new InputBudget('tap', 30000, (pending) => pending, controller.signal); try { - await budget.send((signal) => client.interactions.press({ x: 20, y: 20, signal })); - const second = budget.send((signal) => client.interactions.press({ x: 30, y: 30, signal })); + await budget.press(client, { x: 20, y: 20 }); + const second = budget.press(client, { x: 30, y: 30 }); const canceled = expect(second).rejects.toMatchObject({ details: { reason: 'request_canceled' } }); await started; controller.abort(); From d45a6e1551629f0f2dd165b739d6970a059febeb Mon Sep 17 00:00:00 2001 From: Tim Shamilov Date: Wed, 11 Nov 2026 12:51:46 -0500 Subject: [PATCH 09/10] test(mobile): cover signals at every press dispatch path --- packages/mobile/tests/unit/engine.test.ts | 3 ++ .../tests/unit/input-cancellation.test.ts | 39 +++++++++++++++---- 2 files changed, 34 insertions(+), 8 deletions(-) diff --git a/packages/mobile/tests/unit/engine.test.ts b/packages/mobile/tests/unit/engine.test.ts index fdaff0a5fe..7598528818 100644 --- a/packages/mobile/tests/unit/engine.test.ts +++ b/packages/mobile/tests/unit/engine.test.ts @@ -1342,6 +1342,7 @@ describe('perform', () => { ['interactions.scroll', { direction: 'up', settle: true, settleQuietMs: 150 }], ['interactions.drag', { source: '@e4', destination: '@e3' }], ]); + expect(h.fake.calls.filter((call) => call.method === 'interactions.press').every((call) => call.signal instanceof AbortSignal)).toBe(true); }); it.each(['Enter', 'a'])('sends %s to a focused field without tapping it first', async (key) => { @@ -1921,6 +1922,7 @@ 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 }); + expect(h.fake.calls.filter((call) => call.method === 'interactions.press').every((call) => call.signal instanceof AbortSignal)).toBe(true); }); it('leaves any other refusal to the caller', async () => { @@ -3441,6 +3443,7 @@ 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 }); + expect(h.fake.calls.filter((call) => call.method === 'interactions.press').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 () => { diff --git a/packages/mobile/tests/unit/input-cancellation.test.ts b/packages/mobile/tests/unit/input-cancellation.test.ts index e1a1eb2da0..134341b860 100644 --- a/packages/mobile/tests/unit/input-cancellation.test.ts +++ b/packages/mobile/tests/unit/input-cancellation.test.ts @@ -3,13 +3,14 @@ import { tmpdir } from 'node:os'; import path from 'node:path'; import { createAgentDeviceClient } from 'agent-device'; import { expect, it } from 'vitest'; -import type { OperationContext } from 'e2e/engine'; +import type { EngineFixtureContext, OperationContext } from 'e2e/engine'; +import type { Device } from '../../src/device.ts'; import { buildEngine } from '../../src/engine.ts'; import { AgentDeviceSurface } from '../../src/surface.ts'; import { SETTINGS_SNAPSHOT } from '../helpers/fake-client.ts'; import { boot } from '../helpers/harness.ts'; -it.each(['caller abort', 'input deadline'] as const)('cancels a pending press at the SDK boundary after %s', async (reason) => { +it.each(['caller abort', 'input deadline', 'device fixture abort'] as const)('cancels a pending press at the SDK boundary after %s', async (reason) => { const stateDir = mkdtempSync(path.join(tmpdir(), 'e2e-input-cancel-')); let releaseRequest!: () => void; let markStarted!: () => void; @@ -19,10 +20,22 @@ it.each(['caller abort', 'input deadline'] as const)('cancels a pending press at const finished = new Promise((resolve) => { markFinished = resolve; }); const controller = new AbortController(); let delivered = 0; + const snapshot = reason === 'device fixture abort' + ? { + ...SETTINGS_SNAPSHOT, + nodes: [ + ...SETTINGS_SNAPSHOT.nodes, + { ref: '@e30', index: 10, parentIndex: 0, depth: 1, type: 'static-text', label: 'Speed up your typing by sliding your finger across the letters to compose a word.', rect: { x: 20, y: 600, width: 350, height: 60 } }, + { ref: '@e31', index: 11, parentIndex: 0, depth: 1, type: 'button', label: 'Continue', rect: { x: 95, y: 700, width: 200, height: 44 } }, + ], + keyboard: { kind: 'visible', frame: { x: 0, y: 583, width: 390, height: 261 } }, + } + : SETTINGS_SNAPSHOT; const client = createAgentDeviceClient({ session: 'input-cancel', stateDir }, { transport: async (request, context) => { - if (request.command === 'snapshot') return { ok: true, data: SETTINGS_SNAPSHOT }; + if (request.command === 'snapshot') return { ok: true, data: snapshot }; if (request.command === 'open') return { ok: true, data: { appName: 'Settings', appBundleId: 'com.apple.Preferences' } }; + if (request.command === 'keyboard') return { ok: false, error: { code: 'UNSUPPORTED_OPERATION', message: 'The keyboard has no dismiss key' } }; if (request.command === 'press') { markStarted(); await pendingRequest; @@ -37,12 +50,22 @@ it.each(['caller abort', 'input deadline'] as const)('cancels a pending press at try { await boot({ engine, app: { bundleId: 'Settings' } }); await engine.session!.restart!(operation); - const [target] = await engine.locate!({ kind: 'query', query: { kind: 'testId', value: { kind: 'string', value: 'ABOUT', exact: true } } }, operation); - expect(target).toBeDefined(); - const pressing = engine.perform!(target!.ref, { kind: 'tap' }, operation); - const rejected = expect(pressing).rejects.toMatchObject({ code: reason === 'caller abort' ? 'CANCELLED' : 'ACTION_MAY_HAVE_COMMITTED' }); + let pressing: Promise; + if (reason === 'device fixture abort') { + const device = engine.fixtures!['device']!({ + fixture: (_name: string, value: object) => value, + signal: controller.signal, + timeouts: { action: 30_000 }, + } as unknown as EngineFixtureContext) as Device; + pressing = device.dismissKeyboard(); + } else { + const [target] = await engine.locate!({ kind: 'query', query: { kind: 'testId', value: { kind: 'string', value: 'ABOUT', exact: true } } }, operation); + expect(target).toBeDefined(); + pressing = engine.perform!(target!.ref, { kind: 'tap' }, operation); + } + const rejected = expect(pressing).rejects.toMatchObject({ code: reason === 'input deadline' ? 'ACTION_MAY_HAVE_COMMITTED' : 'CANCELLED' }); await started; - if (reason === 'caller abort') controller.abort(); + if (reason !== 'input deadline') controller.abort(); await rejected; // The external request resumes after the operation has already ended. releaseRequest(); From 66957b62067bfd5cb02b1b5abc4c1885e1df3f6c Mon Sep 17 00:00:00 2001 From: Tim Shamilov Date: Fri, 13 Nov 2026 01:42:42 -0500 Subject: [PATCH 10/10] docs(mobile): clarify press cancellation and tighten checks --- .changeset/mobile-cancel-pending-press.md | 2 +- docs/mobile.mdx | 15 ++- docs/reference/mobile.mdx | 6 +- packages/mobile/tests/unit/engine.test.ts | 12 +- packages/mobile/tests/unit/support.test.ts | 122 ++++++++++----------- 5 files changed, 81 insertions(+), 76 deletions(-) diff --git a/.changeset/mobile-cancel-pending-press.md b/.changeset/mobile-cancel-pending-press.md index 4f9e762570..f84dd0037b 100644 --- a/.changeset/mobile-cancel-pending-press.md +++ b/.changeset/mobile-cancel-pending-press.md @@ -2,4 +2,4 @@ "@e2e-dev/mobile": patch --- -Cancel pending taps, double taps, focus, check and uncheck actions when their timeout expires or the run is interrupted. Input already sent to the device may still finish. +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. diff --git a/docs/mobile.mdx b/docs/mobile.mdx index 0456812ed3..4e7c5bfbc2 100644 --- a/docs/mobile.mdx +++ b/docs/mobile.mdx @@ -769,14 +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 pending tap, double tap, focus, check or uncheck is cancelled -when its timeout expires 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 +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 diff --git a/docs/reference/mobile.mdx b/docs/reference/mobile.mdx index 9a4286e8fb..c7496c14b3 100644 --- a/docs/reference/mobile.mdx +++ b/docs/reference/mobile.mdx @@ -359,9 +359,9 @@ so a cold boot on CI is never charged against `launchTimeout`. first attempt, and that device's app is not opened there. -A pending tap, double tap, focus, check or uncheck is cancelled when its timeout -expires or the run is interrupted. This also covers the tap that dismisses a -keyboard tip. +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 diff --git a/packages/mobile/tests/unit/engine.test.ts b/packages/mobile/tests/unit/engine.test.ts index 7598528818..742a11c541 100644 --- a/packages/mobile/tests/unit/engine.test.ts +++ b/packages/mobile/tests/unit/engine.test.ts @@ -1342,7 +1342,9 @@ describe('perform', () => { ['interactions.scroll', { direction: 'up', settle: true, settleQuietMs: 150 }], ['interactions.drag', { source: '@e4', destination: '@e3' }], ]); - expect(h.fake.calls.filter((call) => call.method === 'interactions.press').every((call) => call.signal instanceof AbortSignal)).toBe(true); + 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) => { @@ -1922,7 +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 }); - expect(h.fake.calls.filter((call) => call.method === 'interactions.press').every((call) => call.signal instanceof AbortSignal)).toBe(true); + 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 () => { @@ -3443,7 +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 }); - expect(h.fake.calls.filter((call) => call.method === 'interactions.press').every((call) => call.signal instanceof AbortSignal)).toBe(true); + 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 () => { diff --git a/packages/mobile/tests/unit/support.test.ts b/packages/mobile/tests/unit/support.test.ts index b7871d2a64..fa99568c56 100644 --- a/packages/mobile/tests/unit/support.test.ts +++ b/packages/mobile/tests/unit/support.test.ts @@ -105,69 +105,69 @@ describe('support helpers', () => { expect(sanitizeFilename('')).toBe('artifact'); expect(sanitizeFilename('x'.repeat(100))).toHaveLength(64); }); -}); -it.each(['press', 'type'] as const)('preserves the acknowledgement allowance for %s at the SDK boundary', async (command) => { - const stateDir = mkdtempSync(path.join(tmpdir(), 'e2e-input-ack-')); - let delivered = 0; - const client = createAgentDeviceClient({ session: 'input-ack', stateDir }, { - transport: async (request) => { - delivered += 1; - await new Promise((resolve) => setTimeout(resolve, 180)); - return request.command === 'type' - ? { ok: false, error: { code: 'UNSUPPORTED_OPERATION', message: 'Typing is unavailable' } } - : { ok: true, data: {} }; - }, - }); - const budget = new InputBudget(command, 100, (pending) => pending, new AbortController().signal); - try { - if (command === 'press') { - await expect(budget.press(client, { x: 20, y: 20 })).resolves.toBeDefined(); - } else { - await expect(budget.send((signal) => client.interactions.type({ text: 'hello', signal }))).rejects.toMatchObject({ code: 'UNSUPPORTED_OPERATION', message: 'Typing is unavailable' }); + it.each(['press', 'type'] as const)('preserves the acknowledgement allowance for %s at the SDK boundary', async (command) => { + const stateDir = mkdtempSync(path.join(tmpdir(), 'e2e-input-ack-')); + let delivered = 0; + const client = createAgentDeviceClient({ session: 'input-ack', stateDir }, { + transport: async (request) => { + delivered += 1; + await new Promise((resolve) => setTimeout(resolve, 180)); + return request.command === 'type' + ? { ok: false, error: { code: 'UNSUPPORTED_OPERATION', message: 'Typing is unavailable' } } + : { ok: true, data: {} }; + }, + }); + const budget = new InputBudget(command, 100, (pending) => pending, new AbortController().signal); + try { + if (command === 'press') { + await expect(budget.press(client, { x: 20, y: 20 })).resolves.toBeDefined(); + } else { + await expect(budget.send((signal) => client.interactions.type({ text: 'hello', signal }))).rejects.toMatchObject({ code: 'UNSUPPORTED_OPERATION', message: 'Typing is unavailable' }); + } + expect(delivered).toBe(1); + } finally { + rmSync(stateDir, { recursive: true, force: true }); } - expect(delivered).toBe(1); - } finally { - rmSync(stateDir, { recursive: true, force: true }); - } -}); + }); -it('keeps caller cancellation on later inputs from the same operation', async () => { - const stateDir = mkdtempSync(path.join(tmpdir(), 'e2e-input-operation-cancel-')); - const controller = new AbortController(); - let release!: () => void; - let markStarted!: () => void; - let markFinished!: () => void; - const held = new Promise((resolve) => { release = resolve; }); - const started = new Promise((resolve) => { markStarted = resolve; }); - const finished = new Promise((resolve) => { markFinished = resolve; }); - let requests = 0; - let delivered = 0; - const client = createAgentDeviceClient({ session: 'operation-cancel', stateDir }, { - transport: async (_request, context) => { - requests += 1; - if (requests === 2) { - markStarted(); - await held; - } - if (context?.signal?.aborted !== true) delivered += 1; - if (requests === 2) markFinished(); - return { ok: true, data: {} }; - }, + it('keeps caller cancellation on later inputs from the same operation', async () => { + const stateDir = mkdtempSync(path.join(tmpdir(), 'e2e-input-operation-cancel-')); + const controller = new AbortController(); + let release!: () => void; + let markStarted!: () => void; + let markFinished!: () => void; + const held = new Promise((resolve) => { release = resolve; }); + const started = new Promise((resolve) => { markStarted = resolve; }); + const finished = new Promise((resolve) => { markFinished = resolve; }); + let requests = 0; + let delivered = 0; + const client = createAgentDeviceClient({ session: 'operation-cancel', stateDir }, { + transport: async (_request, context) => { + requests += 1; + if (requests === 2) { + markStarted(); + await held; + } + if (context?.signal?.aborted !== true) delivered += 1; + if (requests === 2) markFinished(); + return { ok: true, data: {} }; + }, + }); + const budget = new InputBudget('tap', 30000, (pending) => pending, controller.signal); + try { + await budget.press(client, { x: 20, y: 20 }); + const second = budget.press(client, { x: 30, y: 30 }); + const canceled = expect(second).rejects.toMatchObject({ details: { reason: 'request_canceled' } }); + await started; + controller.abort(); + await canceled; + release(); + await finished; + expect(delivered).toBe(1); + } finally { + release(); + rmSync(stateDir, { recursive: true, force: true }); + } }); - const budget = new InputBudget('tap', 30000, (pending) => pending, controller.signal); - try { - await budget.press(client, { x: 20, y: 20 }); - const second = budget.press(client, { x: 30, y: 30 }); - const canceled = expect(second).rejects.toMatchObject({ details: { reason: 'request_canceled' } }); - await started; - controller.abort(); - await canceled; - release(); - await finished; - expect(delivered).toBe(1); - } finally { - release(); - rmSync(stateDir, { recursive: true, force: true }); - } });