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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import {
FIND_NO_MATCH_HINT,
FIND_NO_MATCH_MESSAGE,
FIND_VALUE_REQUIRED_MESSAGE,
findBestMatchesByLocator,
buildSelectorChainForNode,
Expand Down Expand Up @@ -119,7 +121,9 @@ export const findCommand: RuntimeCommand<FindReadCommandOptions, FindReadCommand

const { capture, match } = await findFirstLocatorMatch(runtime, options, locator);
if (!match) {
throw new AppError('COMMAND_FAILED', 'find did not match any element');
throw new AppError('COMMAND_FAILED', FIND_NO_MATCH_MESSAGE, {
hint: FIND_NO_MATCH_HINT,
});
}

if (options.action === 'exists') return { kind: 'found', found: true };
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import type { DaemonResponse } from '@agent-device/kernel/contracts';
import {
FIND_NO_MATCH_HINT,
FIND_NO_MATCH_MESSAGE,
findBestMatchesByLocator,
type FindAction,
type FindLocator,
Expand All @@ -15,8 +17,6 @@ import type { SessionState } from '../../../core/session-state.ts';
import { buildAmbiguousMatchError } from '../../selector-match-errors.ts';
import { errorResponse } from '@agent-device/kernel/contracts';

const FIND_NO_MATCH_HINT =
'Run snapshot -i to see current elements and refs, or scroll first if the element may be off-screen.';
// A bare `find <text>` is this action, so an agent that meant a lookup learns the read form here.
const FIND_CLICK_NO_MATCH_HINT = `${FIND_NO_MATCH_HINT} This find clicks its match; to look an element up without acting on it, use find text "..." exists.`;

Expand Down Expand Up @@ -84,7 +84,7 @@ export function resolveFindMatch(params: {
ok: false,
// Nothing was dispatched: a bare `find` defaults to click, which would otherwise read as a
// mutation that may have reached the device.
response: errorResponse('COMMAND_FAILED', 'find did not match any element', {
response: errorResponse('COMMAND_FAILED', FIND_NO_MATCH_MESSAGE, {
dispatched: 'no',
hint: action === 'click' ? FIND_CLICK_NO_MATCH_HINT : FIND_NO_MATCH_HINT,
}),
Expand Down
51 changes: 51 additions & 0 deletions packages/gestures/src/gesture-plan-viewport.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,47 @@ describe('viewport-aware multi-touch geometry', () => {
}
});

test('an out-of-bounds refusal names the viewport and the first point outside it', () => {
const inset = { x: 0, y: 47, width: 390, height: 750 };
for (const [viewport, point, frame, named] of [
[PORTRAIT, { x: 0, y: 100 }, /the 390x844 viewport$/, '(0, 100)'],
[inset, { x: 100, y: 10 }, /the 390x750 viewport at \(0, 47\)$/, '(100, 10)'],
[PORTRAIT, { x: 391.23456, y: 100 }, /the 390x844 viewport$/, '(391.23, 100)'],
] as const) {
const error = captureError(() =>
buildGesturePlan(
{
intent: 'tap',
points: [{ x: 100, y: 200 }, point],
},
viewport,
),
);
assert.ok(isErrorWithReason(error, 'INVALID_ARGS', 'GESTURE_TRAJECTORY_OUT_OF_BOUNDS'));
assert.ok(error.message.includes(`point ${named} `), error.message);
assert.match(error.message, frame);
assert.deepEqual(error.details?.viewport, viewport);
// The message rounds; the details keep the exact sample.
assert.deepEqual(error.details?.sample, { offsetMs: 0, point });
assert.match(String(error.details?.hint), /snapshot/);
}
});

test('a pinch too small for the viewport names the viewport but no point', () => {
const error = captureError(() =>
buildGesturePlan(
{ intent: 'pinch', origin: { x: 20, y: 20 }, scale: 2 },
{ x: 0, y: 0, width: 40, height: 40 },
),
);
assert.ok(isErrorWithReason(error, 'INVALID_ARGS', 'GESTURE_TRAJECTORY_OUT_OF_BOUNDS'));
assert.match(error.message, /the 40x40 viewport$/);
assert.doesNotMatch(error.message, /point/);
assert.equal(error.details?.minimumReliableSpan, 48);
assert.equal(error.details?.sample, undefined);
assert.doesNotMatch(String(error.details?.hint), /snapshot/);
});

test('positive and negative translation choose geometry that keeps the full path in bounds', () => {
for (const delta of [
{ x: 80, y: 40 },
Expand Down Expand Up @@ -186,6 +227,16 @@ describe('gesture planning never synthesizes an out-of-bounds point', () => {
});
});

function captureError(build: () => unknown): AppError {
try {
build();
} catch (error) {
assert.ok(error instanceof AppError, `unexpected error type: ${String(error)}`);
return error;
}
assert.fail('expected the gesture plan to be refused');
}

function buildTransformPlan(durationMs: number) {
return requireTwoPointerPlan(
buildGesturePlan(
Expand Down
3 changes: 2 additions & 1 deletion packages/gestures/src/gesture-plan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ const GESTURE_PLAN_REFUSAL_REASONS = {
pathInvalidTimeline: { reason: 'GESTURE_PATH_INVALID_TIMELINE' },
// A trajectory sample carries a non-finite coordinate.
trajectoryNonFinite: { reason: 'GESTURE_TRAJECTORY_NON_FINITE' },
// A trajectory sample leaves the viewport, so the contact would press outside the screen.
// A trajectory sample leaves the viewport, so the contact would press outside the screen, or a
// two-finger path cannot keep its contacts the minimum span apart inside it.
trajectoryOutOfBounds: { reason: 'GESTURE_TRAJECTORY_OUT_OF_BOUNDS' },
} as const satisfies ReasonTable<'gesture'>;
const GESTURE_FLING_DEFAULT_DISTANCE = 180;
Expand Down
4 changes: 4 additions & 0 deletions packages/selectors/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ import {
parseFindArgs,
parseFindSelectorExpression,
FIND_LOCATORS,
FIND_NO_MATCH_HINT,
FIND_NO_MATCH_MESSAGE,
FIND_VALUE_REQUIRED_MESSAGE,
UNSUPPORTED_FIND_ACTION_HINT,
} from './internal/find.ts';
Expand Down Expand Up @@ -96,6 +98,8 @@ export {

export {
FIND_LOCATORS,
FIND_NO_MATCH_HINT,
FIND_NO_MATCH_MESSAGE,
FIND_VALUE_REQUIRED_MESSAGE,
IS_PREDICATE_USAGE_HINT,
IS_TEXT_VALUE_REQUIRED_MESSAGE,
Expand Down
5 changes: 5 additions & 0 deletions packages/selectors/src/internal/find.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,11 @@ export type ParsedFindArgs = {
/** Shared by `checkFindArgs` and `findCommand`, which validates already-parsed options. */
export const FIND_VALUE_REQUIRED_MESSAGE = 'find requires a value';

/** Shared by the acting and read-only `find` no-match refusals, so their wording cannot drift. */
export const FIND_NO_MATCH_MESSAGE = 'find did not match any element';
export const FIND_NO_MATCH_HINT =
'Run snapshot -i to see current elements and refs, or scroll first if the element may be off-screen.';

/**
* Shared by both `Unsupported find action` throw sites (this file's raw-token
* parser and `packages/command-surface/src/interaction/selectors.ts`'s typed CLI reader) so
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import assert from 'node:assert/strict';
import { test } from 'vitest';
import type { InteractionGuarantee } from '@agent-device/contracts/interaction-guarantees';
import { FIND_NO_MATCH_HINT } from '@agent-device/selectors';
import { KEYBOARD_COVERED_BAND_RECT, keyboardCoveredTabBarSnapshot } from '@agent-device/test-kit';
import { assertRpcError, assertRpcOk } from '../provider-scenarios/assertions.ts';
import { PARALLEL_PROVIDER_SCENARIO_TIMEOUT_MS } from '../provider-scenarios/test-timeouts.ts';
Expand Down Expand Up @@ -775,6 +776,7 @@ test(
runnerSnapshotEntry(twinFormTree()),
runnerSnapshotEntry(KEYBOARD_TREE),
runnerSnapshotEntry(KEYBOARD_TREE),
runnerSnapshotEntry(KEYBOARD_TREE),
],
async (daemon) => {
const ambiguous = assertRpcError(
Expand All @@ -789,16 +791,28 @@ test(
]);

// A bare find is a click. Click and focus share resolveFindMatch, so this row also pins the
// click no-match: neither sends anything.
for (const args of [['label', 'Nowhere', 'focus'], ['Nowhere']]) {
// click no-match: neither sends anything. The read-only `exists` row takes the selector
// runtime instead and must refuse the same way. Only the click hint points at the read form.
const noMatchHints: unknown[] = [];
for (const args of [
['label', 'Nowhere', 'focus'],
['Nowhere'],
['label', 'Nowhere', 'exists'],
]) {
const noMatch = assertRpcError(
await daemon.callCommand('find', args),
500,
'COMMAND_FAILED',
/find did not match any element/,
);
assert.equal(readErrorDetails(noMatch).dispatched, 'no');
noMatchHints.push(noMatch.hint);
}
const [focusHint, clickHint, existsHint] = noMatchHints;
assert.equal(focusHint, FIND_NO_MATCH_HINT);
assert.equal(existsHint, FIND_NO_MATCH_HINT);
assert.ok(typeof clickHint === 'string' && clickHint.startsWith(FIND_NO_MATCH_HINT));
assert.match(clickHint, /find text "\.\.\." exists/);
},
);
},
Expand Down
14 changes: 14 additions & 0 deletions test/integration/provider-scenarios/android-find.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { ANDROID_IME_HELPER_FIXTURE_ARTIFACT } from '../../../src/__tests__/test
import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from '../../../src/__tests__/test-utils/android-snapshot-helper.ts';
import type { AndroidAdbProvider } from '@agent-device/platform-android/mechanics';
import { WAIT_REASONS } from '@agent-device/contracts/wait';
import { FIND_NO_MATCH_HINT } from '@agent-device/selectors';
import { arrayEqual, assertCommandCall, assertRpcOk } from './assertions.ts';
import { androidSettingsXml, androidSnapshotHelperOutput } from './android-world.ts';
import {
Expand Down Expand Up @@ -74,6 +75,19 @@ test('Provider-backed integration Android find flow covers refs, wait, ambiguity
});
assert.equal(exists.found, true);

// The read-only no-match gets the acting route's recovery hint, without the click-only advice
// to switch to a lookup.
for (const args of [
['label', 'Nowhere', 'exists'],
['label', 'Nowhere', 'get', 'text'],
['label', 'Nowhere', 'get', 'attrs'],
]) {
const noMatch = (await daemon.callCommand('find', args, selection)).json?.error?.data;
assert.equal(noMatch?.code, 'COMMAND_FAILED', args.join(' '));
assert.equal(noMatch?.details?.dispatched, 'no', args.join(' '));
assert.equal(noMatch?.hint, FIND_NO_MATCH_HINT, args.join(' '));
}

const pressFoundRef = await client.interactions.press({ ref: attrsPinnedRef, ...selection });
assert.equal(pressFoundRef.x, 88);
assert.equal(pressFoundRef.y, 151);
Expand Down
3 changes: 2 additions & 1 deletion website/docs/docs/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -1260,7 +1260,7 @@ Exact behavior: `agent-device help gesture`.
- `gesture pan --hold-ms <ms>` holds one pointer before it moves, for drag handles that expose no element and so no ref, such as reorder grips.
- `gesture drag source destination` holds one pointer from a selector or ref to another. It refuses coordinates; for a coordinate drag, use `gesture pan <x> <y> <dx> <dy> [ms] --hold-ms <ms>`. It and `--hold-ms` work on Android touch devices and iOS/iPadOS only.
- `gesture pinch`, `gesture rotate`, `gesture transform`, and two-finger `gesture pan` work in Android, iOS, and iPadOS app sessions. iOS sessions through a WebDriver provider refuse them. A path that does not fit the viewport fails instead of being clamped. Use `orientation` to rotate the device.
- `swipe` and `gesture` coordinates use the units `snapshot` reports: points on Apple platforms, not screenshot pixels. A gesture that leaves the viewport fails with `GESTURE_TRAJECTORY_OUT_OF_BOUNDS`, and the message names the viewport size and the first point outside it.
- `swipe` and `gesture` coordinates use the units `snapshot` reports: points on Apple platforms, not screenshot pixels. A gesture that leaves the viewport fails with `GESTURE_TRAJECTORY_OUT_OF_BOUNDS`, and the message names the viewport size and the first point outside it. A `gesture pinch`, `rotate`, `transform`, or two-finger `pan` that cannot keep its fingers far enough apart in the viewport fails the same way, and its message names only the viewport.
- `gesture tap` touches 2 to 5 points at once in Android and iOS/iPadOS app sessions. WebDriver providers refuse it unless they declare `tapGesture` support. Three or more fingers can trigger iOS system gestures such as undo, so verify app state afterwards. Use `press` for one finger.
- On iOS, a long press, scroll, or swipe that fails with `synthesized_gesture_not_dispatched` sent nothing, so a retry is safe. `synthesized_gesture_outcome_unknown` means it may have run; check the screen first.
- On iOS, a one-finger `gesture pan` can cross into the keyboard area. Use it for an intended drag where the app supports interactive keyboard dismissal.
Expand Down Expand Up @@ -1326,6 +1326,7 @@ An Apple runner that returns `COMMAND_ALREADY_FINISHED` cannot replay that comma
- `malformed_request`: fix the client that built the request; resending it unchanged fails the same way.
- `remote_daemon_unavailable`: the remote daemon did not answer its health check. Make it reachable, or clear `--daemon-base-url` or `AGENT_DEVICE_DAEMON_BASE_URL`. For a saved `connect` connection, run `disconnect` to return to the local daemon.
- `webdriver_route_unsupported`: the device cloud's driver does not implement the route. The limit is the driver, not the device.
- `find` with no match (`COMMAND_FAILED`, no reason): no `find` action ran. Run `snapshot -i` to see the current elements, or scroll first if the element may be off-screen.

iOS runner refusals carry a typed `error.details.reason` too:

Expand Down
2 changes: 1 addition & 1 deletion website/docs/docs/error-reasons.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ Treat a reason that this page does not list as unknown, not as an error in the r
| `GESTURE_PATH_TOO_SHORT` | The gesture path has fewer usable samples than any recognizable motion needs. |
| `GESTURE_PATH_INVALID_TIMELINE` | The path's sample timeline is not ordered and finite, so no clock can play it back. |
| `GESTURE_TRAJECTORY_NON_FINITE` | A trajectory sample carries a non-finite coordinate. |
| `GESTURE_TRAJECTORY_OUT_OF_BOUNDS` | A trajectory sample leaves the viewport, so the contact would press outside the screen. |
| `GESTURE_TRAJECTORY_OUT_OF_BOUNDS` | A trajectory sample leaves the viewport, so the contact would press outside the screen, or a two-finger path cannot keep its contacts the minimum span apart inside it. |

### `install-from-source`

Expand Down
Loading