diff --git a/.changeset/mobile-cancel-pending-press.md b/.changeset/mobile-cancel-pending-press.md new file mode 100644 index 0000000000..f84dd0037b --- /dev/null +++ b/.changeset/mobile-cancel-pending-press.md @@ -0,0 +1,5 @@ +--- +"@e2e-dev/mobile": patch +--- + +Cancel pending taps, double taps, focus, check and uncheck actions when the step stops waiting for them or the run is interrupted. Input already sent to the device may still finish. diff --git a/docs/mobile.mdx b/docs/mobile.mdx index a3085a5cc7..4e7c5bfbc2 100644 --- a/docs/mobile.mdx +++ b/docs/mobile.mdx @@ -769,11 +769,13 @@ message and hint, never `LAUNCH_TIMEOUT`, `ACTION_FAILED`, or **An action that outlives its timeout.** A tap, fill, key, swipe, or `back` gets its `timeout` (default `actionTimeout`). If the device doesn't answer in time, the step fails with `ACTION_FAILED` and isn't retried: the -input may have landed. A `longPress` that holds at least as long as the -time left is refused before it's sent; raise its `timeout`. Snapshots and -screenshots run within the timeout of the call that takes them, so a device -that stops answering fails the step with `ACTION_FAILED` instead of holding -it until the test timeout. `locator.waitFor`, `expect`, and +input may have landed. A pending tap, double tap, focus, check or uncheck is +cancelled when the step stops waiting for it or the run is interrupted. Input +already sent to the device may still finish. A `longPress` that holds at least +as long as the time left is refused before it's sent; raise its `timeout`. +Snapshots and screenshots run within the timeout of the call that takes them, +so a device that stops answering fails the step with `ACTION_FAILED` instead +of holding it until the test timeout. `locator.waitFor`, `expect`, and `toHaveScreenshot` give their last snapshot extra time, up to their slowest one so far and within the test timeout, so a screen that shows up during it still passes. An element that never shows up fails as diff --git a/docs/reference/mobile.mdx b/docs/reference/mobile.mdx index 71d9efc64d..c7496c14b3 100644 --- a/docs/reference/mobile.mdx +++ b/docs/reference/mobile.mdx @@ -359,8 +359,13 @@ so a cold boot on CI is never charged against `launchTimeout`. first attempt, and that device's app is not opened there. -agent-device commands take no abort signal, so a timed-out command keeps -running on the device. The next attempt waits for it to settle. +A pending tap, double tap, focus, check or uncheck is cancelled when the step +stops waiting for it or the run is interrupted. This also covers the tap that +dismisses a keyboard tip. + +Input already sent to the device may still finish. +Other commands can outlive their caller's timeout; the next attempt waits for +them to finish. #### Capabilities diff --git a/packages/mobile/src/actions.ts b/packages/mobile/src/actions.ts index a585e654d8..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,27 +63,32 @@ export function pointerInteraction( action: PointerAction, settle: Record, stabilization: Record, + input: InputBudget, ): Promise { const at = { x: point.x, y: point.y }; switch (action.kind) { case 'tap': - return client.interactions.press({ ...at, ...settle }); + return input.press(client, { ...at, ...settle }); case 'doubleTap': - return client.interactions.press({ ...at, count: 2, ...settle }); + return input.press(client, { ...at, count: 2, ...settle }); case 'longPress': - return client.interactions.longPress({ ...at, ...settle, durationMs: action.durationMs ?? DEFAULT_LONG_PRESS_MS }); + return input.send( + () => client.interactions.longPress({ ...at, ...settle, durationMs: action.durationMs ?? DEFAULT_LONG_PRESS_MS }), + action.durationMs ?? DEFAULT_LONG_PRESS_MS, + ); case 'swipeTo': { const to = { x: action.target.x, y: action.target.y }; - if (action.durationMs !== undefined) { - return client.interactions.pan({ + const durationMs = action.durationMs; + if (durationMs !== undefined) { + return input.send(() => client.interactions.pan({ x: at.x, y: at.y, dx: to.x - at.x, dy: to.y - at.y, - durationMs: action.durationMs, - }); + durationMs, + }), durationMs); } - return client.interactions.swipe({ from: at, to, ...stabilization }); + return input.send(() => client.interactions.swipe({ from: at, to, ...stabilization })); } case 'secondaryTap': case 'hover': diff --git a/packages/mobile/src/device.ts b/packages/mobile/src/device.ts index fadce6e459..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)); + 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 0cfbbc8fa5..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)), - locate: (expression, operation) => surface.locate(expression, operation, surface.inputBudget('locate', operation.timeoutMs)), - perform: (ref, action, operation) => surface.perform(ref, action, operation, surface.inputBudget(action.kind, operation.timeoutMs)), + observe: (operation, options) => surface.observe(operation, options, surface.inputBudget('observe', operation)), + locate: (expression, operation) => surface.locate(expression, operation, surface.inputBudget('locate', operation)), + perform: (ref, action, operation) => surface.perform(ref, action, operation, surface.inputBudget(action.kind, operation)), actions: DEVICE_ACTIONS, - performAt: (point, action, operation) => surface.performAt(point, action, operation, surface.inputBudget(action.kind, operation.timeoutMs)), + performAt: (point, action, operation) => surface.performAt(point, action, operation, surface.inputBudget(action.kind, operation)), pointerActions: DEVICE_POINTER_ACTIONS, keyboard: { - type: (text, keyboardOptions, operation) => surface.typeText(text, keyboardOptions, operation, surface.inputBudget('type', operation.timeoutMs)), - press: (key, operation) => surface.pressFocusedKey(key, operation, surface.inputBudget('press', operation.timeoutMs)), - dismiss: (operation) => surface.dismissKeyboard(operation.signal, surface.inputBudget('keyboard dismiss', operation.timeoutMs)), + type: (text, keyboardOptions, operation) => surface.typeText(text, keyboardOptions, operation, surface.inputBudget('type', operation)), + press: (key, operation) => surface.pressFocusedKey(key, operation, surface.inputBudget('press', operation)), + dismiss: (operation) => surface.dismissKeyboard(operation.signal, surface.inputBudget('keyboard dismiss', operation)), }, validateApp: (app, info) => validateApp(app, info, surface.options.platform), // No `open`: a device app has no URL to open, so the runner serves // `app.open()` with `restart`, the fresh launch of the pinned app, which // is also the device's "recreate the context". session: { - back: (operation) => surface.back(operation, surface.inputBudget('back', operation.timeoutMs)), + back: (operation) => surface.back(operation, surface.inputBudget('back', operation)), restart: (operation) => surface.restart(operation), reset: (operation) => surface.reset(operation), }, artifacts: { - screenshot: (label, operation) => surface.screenshot(label, operation, surface.inputBudget('screenshot', operation.timeoutMs)), + screenshot: (label, operation) => surface.screenshot(label, operation, surface.inputBudget('screenshot', operation)), startVideo: (operation) => surface.startVideo(operation), stopVideo: (operation) => surface.stopVideo(operation), }, diff --git a/packages/mobile/src/support.ts b/packages/mobile/src/support.ts index 19f75da9c6..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; @@ -35,18 +36,27 @@ export class InputBudget { private sent = false; /** - * `track` keeps the device command itself in flight, past a timeout that - * abandons it, until it settles. The callers' own tracking settles with the - * race, so this is the registration the next attempt waits on. + * `track` keeps the SDK request in flight, past a timeout that abandons + * it, until its promise settles. Cancellation can settle that promise + * before already accepted native work ends. */ constructor( private readonly label: string, timeoutMs: number, private readonly track: (pending: Promise) => Promise, + private readonly signal: AbortSignal, ) { this.endsAt = Date.now() + timeoutMs; } + /** + * Press requests receive caller cancellation and are cancelled when this + * wait expires, including its existing acknowledgement allowance. + */ + press(client: AgentDeviceClient, options: PressOptions): Promise { + 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,7 +65,7 @@ export class InputBudget { * it is refused unsent. An input that does not answer in time may have * landed, so it is `ACTION_MAY_HAVE_COMMITTED` and the runner never repeats it. */ - send(dispatch: () => Promise, holdMs = 0): Promise { + send(dispatch: (signal: AbortSignal) => Promise, holdMs = 0): Promise { const remaining = this.remainingMs(); if (remaining <= 0) return Promise.reject(this.spent()); if (holdMs >= remaining) { @@ -67,9 +77,15 @@ export class InputBudget { ), ); } - const pending = this.track(dispatch()); + const answerMs = Math.max(remaining, MIN_ANSWER_MS); + const deadline = new AbortController(); + const requestSignal = AbortSignal.any([this.signal, deadline.signal]); + const pending = this.track(dispatch(requestSignal)); this.sent = true; - return withTimeout(pending, Math.max(remaining, MIN_ANSWER_MS), () => this.maybeCommitted()); + return withTimeout(pending, answerMs, () => { + deadline.abort(); + return this.maybeCommitted(); + }); } /** diff --git a/packages/mobile/src/surface.ts b/packages/mobile/src/surface.ts index d749021aaa..a9b4181629 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>(); @@ -573,9 +572,9 @@ export class AgentDeviceSurface { return result; } - /** The budget one operation runs under; its device commands stay in flight until they settle. */ - inputBudget(label: string, timeoutMs: number): InputBudget { - return new InputBudget(label, timeoutMs, (pending) => this.track(pending)); + /** The budget and cancellation signal shared by one operation's inputs. */ + inputBudget(label: string, operation: Pick): InputBudget { + return new InputBudget(label, operation.timeoutMs, (pending) => this.track(pending), operation.signal); } /** Registers one device command as in flight until it settles. */ @@ -1456,16 +1455,16 @@ export class AgentDeviceSurface { } switch (action.kind) { case 'tap': - return input.send(() => client.interactions.press({ ...this.actionTarget(target, true), ...settle })); + return input.press(client, { ...this.actionTarget(target, true), ...settle }); case 'focus': // A touch surface focuses by tapping, and a tap on anything but an // editable field activates it; focus is offered for fields only. if (target.node.role !== 'textbox') { throw unsupported(`agent-device can only focus editable fields; node ${target.id} is ${target.node.role ?? 'unknown'}`); } - return input.send(() => client.interactions.press({ ...this.actionTarget(target), ...settle })); + return input.press(client, { ...this.actionTarget(target), ...settle }); case 'doubleTap': - return input.send(() => client.interactions.press({ ...this.actionTarget(target), count: 2, ...settle })); + return input.press(client, { ...this.actionTarget(target), count: 2, ...settle }); case 'longPress': return input.send( () => client.interactions.longPress({ ...this.actionTarget(target), ...settle, durationMs: action.durationMs ?? DEFAULT_LONG_PRESS_MS }), @@ -1490,7 +1489,7 @@ export class AgentDeviceSurface { throw unsupported(`agent-device cannot read whether node ${target.id} is checked; tap it instead`); } if (checked === wanted) return undefined; - return input.send(() => client.interactions.press({ ...this.actionTarget(target, true), ...settle })); + return input.press(client, { ...this.actionTarget(target, true), ...settle }); } case 'press': return this.pressKey(client, target, action.key, settle, input); @@ -1553,7 +1552,7 @@ export class AgentDeviceSurface { // A key reaches the field through the soft keyboard, which is up only // while the field holds focus. if (entry.node.role === 'textbox' && entry.node.states?.focused !== true) { - await input.send(() => client.interactions.press({ ...this.actionTarget(entry), ...settle })); + await input.press(client, { ...this.actionTarget(entry), ...settle }); } if (enter) return input.send(() => client.command.keyboard({ action: 'enter' })); return input.send(() => client.interactions.type({ text: parsed.key.kind === 'char' ? parsed.key.char : ' ' })); @@ -1567,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(() => pointerInteraction(client, point, action, settle, gestureStabilization(operation)), holdMs), operation.signal); + await this.command(`${action.kind} at point`, (client) => pointerInteraction(client, point, action, settle, gestureStabilization(operation), input), operation.signal); if (action.kind === 'swipeTo') this.noteGesture(operation); this.markAction(before); } @@ -1697,7 +1695,7 @@ export class AgentDeviceSurface { const tipTop = tip.rect.y; const button = nodes.find((node) => node.label === 'Continue' && node.rect !== undefined && node.rect.y > tipTop); if (button?.rect === undefined) return raw; - await this.command('keyboard.dismiss', (client) => input.send(() => client.interactions.press(centreOf(button.rect!))), signal); + await this.command('keyboard.dismiss', (client) => input.press(client, centreOf(button.rect!)), signal); return await this.snapshot(signal, false, input); } 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 edcf91afe6..742a11c541 100644 --- a/packages/mobile/tests/unit/engine.test.ts +++ b/packages/mobile/tests/unit/engine.test.ts @@ -1342,6 +1342,9 @@ describe('perform', () => { ['interactions.scroll', { direction: 'up', settle: true, settleQuietMs: 150 }], ['interactions.drag', { source: '@e4', destination: '@e3' }], ]); + const presses = h.fake.calls.filter((call) => call.method === 'interactions.press'); + expect(presses).not.toHaveLength(0); + expect(presses.every((call) => call.signal instanceof AbortSignal)).toBe(true); }); it.each(['Enter', 'a'])('sends %s to a focused field without tapping it first', async (key) => { @@ -1921,6 +1924,9 @@ describe('device fixture', () => { await device.dismissKeyboard(); expect(h.fake.methods().slice(before)).toEqual(['command.keyboard', 'capture.snapshot', 'interactions.press', 'capture.snapshot']); expect(h.fake.lastArgs('interactions.press')).toEqual({ x: 195, y: 722 }); + const presses = h.fake.calls.filter((call) => call.method === 'interactions.press'); + expect(presses).not.toHaveLength(0); + expect(presses.every((call) => call.signal instanceof AbortSignal)).toBe(true); }); it('leaves any other refusal to the caller', async () => { @@ -3353,7 +3359,7 @@ describe('deterministic actions', () => { const search = await observed(h, 'Search'); if (action === 'Enter') await h.engine.perform!(search.ref, { kind: 'press', key: 'Enter' }, test()); else if (action === 'focused Enter') await h.engine.keyboard!.press('Enter', test()); - else await h.surface.dismissKeyboard(test().signal, h.surface.inputBudget('keyboard dismiss', test().timeoutMs)); + else await h.surface.dismissKeyboard(test().signal, h.surface.inputBudget('keyboard dismiss', test())); h.fake.respond('capture.snapshot', () => ({ ...SETTINGS_SNAPSHOT, keyboard: { kind: 'absent' } })); const stale = await observed(h, 'About'); h.fake.respond('capture.snapshot', () => ({ @@ -3441,6 +3447,9 @@ describe('deterministic actions', () => { const about = await observed(h, 'About'); await h.engine.perform!(about.ref, { kind: 'tap' }, { ...operation(), origin: 'agent' }); expect(h.fake.lastArgs('interactions.press')).toEqual({ ref: '@e4', settle: true, settleQuietMs: 150 }); + const presses = h.fake.calls.filter((call) => call.method === 'interactions.press'); + expect(presses).not.toHaveLength(0); + expect(presses.every((call) => call.signal instanceof AbortSignal)).toBe(true); }); it('skips the post-gesture stabilization wait for a test swipe and scroll, and keeps it for the agent', async () => { 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..134341b860 --- /dev/null +++ b/packages/mobile/tests/unit/input-cancellation.test.ts @@ -0,0 +1,79 @@ +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 { 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', '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; + let markFinished!: () => void; + 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(); + 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: 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; + 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); + 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 !== 'input deadline') controller.abort(); + await rejected; + // The external request resumes after the operation has already ended. + releaseRequest(); + await finished; + expect(delivered).toBe(0); + } finally { + releaseRequest(); + await engine.dispose!({ signal: new AbortController().signal, timeoutMs: 1000 }); + 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..fa99568c56 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' }); @@ -101,4 +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' }); + } + 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.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 }); + } + }); });