From 60fa55a81ed371062222489ade92811cfbb4a2cd Mon Sep 17 00:00:00 2001 From: parbez Date: Mon, 23 Nov 2026 12:24:38 +0530 Subject: [PATCH 1/3] fix(cli): name the accepted values when a flag value is refused A refused numeric or enum flag value printed only "Invalid wait: 240000", so agents guessed what the flag meant. The parser now names the accepted range or values ("Expected integer from 100 to 120000.") and returns details.reason flag_value_invalid with the flag and its bounds. Env and config refusals use the same describer, so --fps 500 and AGENT_DEVICE_FPS=500 read alike. --- packages/kernel/src/source-value.test.ts | 8 ++-- packages/kernel/src/source-value.ts | 37 ++++++++------ .../parser/__tests__/args-validation.test.ts | 48 ++++++++++++++++++- src/cli/parser/args.ts | 39 +++++++++++---- website/docs/docs/error-reasons.md | 6 +++ 5 files changed, 107 insertions(+), 31 deletions(-) diff --git a/packages/kernel/src/source-value.test.ts b/packages/kernel/src/source-value.test.ts index 74b5e76cd9..741a206f9b 100644 --- a/packages/kernel/src/source-value.test.ts +++ b/packages/kernel/src/source-value.test.ts @@ -150,12 +150,12 @@ describe('parseSourceValue integers', () => { test('enforces the min bound', () => { expect(parse({ type: 'int', min: 0 }, 0)).toBe(0); - expectInvalidArgs(() => parse({ type: 'int', min: 1 }, 0), 'Must be >= 1'); + expectInvalidArgs(() => parse({ type: 'int', min: 1 }, 0), 'Expected integer >= 1'); }); test('enforces the max bound', () => { expect(parse({ type: 'int', max: 10 }, 10)).toBe(10); - expectInvalidArgs(() => parse({ type: 'int', max: 5 }, 6), 'Must be <= 5'); + expectInvalidArgs(() => parse({ type: 'int', max: 5 }, 6), 'Expected integer <= 5'); }); }); @@ -167,8 +167,8 @@ describe('parseSourceValue numbers', () => { test('rejects non-numeric input and enforces bounds', () => { expectInvalidArgs(() => parse({ type: 'number' }, 'abc'), 'Expected number'); - expectInvalidArgs(() => parse({ type: 'number', min: 0.01 }, 0), 'Must be >= 0.01'); - expectInvalidArgs(() => parse({ type: 'number', max: 1 }, 1.1), 'Must be <= 1'); + expectInvalidArgs(() => parse({ type: 'number', min: 0.01 }, 0), 'Expected number >= 0.01'); + expectInvalidArgs(() => parse({ type: 'number', max: 1 }, 1.1), 'Expected number <= 1'); }); }); diff --git a/packages/kernel/src/source-value.ts b/packages/kernel/src/source-value.ts index d6a0f87d10..75d807603b 100644 --- a/packages/kernel/src/source-value.ts +++ b/packages/kernel/src/source-value.ts @@ -69,34 +69,41 @@ export function parseSourceValue( if (typeof value !== 'string' || !definition.enumValues?.includes(value)) { throw new AppError( 'INVALID_ARGS', - `Invalid value for "${rawKey}" in ${sourceLabel}. Expected one of: ${definition.enumValues?.join(', ')}.`, + `Invalid value for "${rawKey}" in ${sourceLabel}. Expected ${describeAcceptedValues(definition)}.`, ); } return value; } const parsed = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : Number.NaN; - if (!Number.isFinite(parsed) || (definition.type === 'int' && !Number.isInteger(parsed))) { + if ( + !Number.isFinite(parsed) || + (definition.type === 'int' && !Number.isInteger(parsed)) || + (typeof definition.min === 'number' && parsed < definition.min) || + (typeof definition.max === 'number' && parsed > definition.max) + ) { throw new AppError( 'INVALID_ARGS', - `Invalid value for "${rawKey}" in ${sourceLabel}. Expected ${definition.type === 'int' ? 'integer' : 'number'}.`, - ); - } - if (typeof definition.min === 'number' && parsed < definition.min) { - throw new AppError( - 'INVALID_ARGS', - `Invalid value for "${rawKey}" in ${sourceLabel}. Must be >= ${definition.min}.`, - ); - } - if (typeof definition.max === 'number' && parsed > definition.max) { - throw new AppError( - 'INVALID_ARGS', - `Invalid value for "${rawKey}" in ${sourceLabel}. Must be <= ${definition.max}.`, + `Invalid value for "${rawKey}" in ${sourceLabel}. Expected ${describeAcceptedValues(definition)}.`, ); } return parsed; } +/** + * The values an enum or numeric definition accepts, worded the same for a CLI flag, an env var, + * and a config key: `integer from 100 to 120000`, `number >= 0.01`, `one of: auto, socket`. + */ +export function describeAcceptedValues(definition: SourceValueDefinition): string { + if (definition.type === 'enum') return `one of: ${definition.enumValues?.join(', ')}`; + const kind = definition.type === 'int' ? 'integer' : 'number'; + const { min, max } = definition; + if (min !== undefined && max !== undefined) return `${kind} from ${min} to ${max}`; + if (min !== undefined) return `${kind} >= ${min}`; + if (max !== undefined) return `${kind} <= ${max}`; + return kind; +} + function parseBooleanValue(value: unknown, sourceLabel: string, rawKey: string): boolean { if (typeof value === 'boolean') return value; if (typeof value === 'string') { diff --git a/src/cli/parser/__tests__/args-validation.test.ts b/src/cli/parser/__tests__/args-validation.test.ts index e768650d3e..ff0a52750a 100644 --- a/src/cli/parser/__tests__/args-validation.test.ts +++ b/src/cli/parser/__tests__/args-validation.test.ts @@ -28,10 +28,54 @@ test('parseArgs rejects invalid record --fps range', () => { (error) => error instanceof AppError && error.code === 'INVALID_ARGS' && - error.message === 'Invalid fps: 0', + error.message === 'Invalid fps: 0. Expected integer from 1 to 120.', ); }); +test('parseArgs names the accepted values of a refused flag value', () => { + const cases: Array<[string[], Record, string]> = [ + [ + ['open', 'com.example.app', '--wait', '240000'], + { flag: '--wait', min: 100, max: 120000 }, + 'Expected integer from 100 to 120000.', + ], + [ + ['open', 'com.example.app', '--wait=soon'], + { flag: '--wait', min: 100, max: 120000 }, + 'Expected integer from 100 to 120000.', + ], + [ + ['open', 'com.example.app', '--timeout', '0'], + { flag: '--timeout', min: 1, max: undefined }, + 'Expected integer >= 1.', + ], + [ + ['screenshot', './shot.png', '--scale', '2'], + { flag: '--scale', min: 0.01, max: 1 }, + 'Expected number from 0.01 to 1.', + ], + [ + ['snapshot', '--target', 'watch'], + { flag: '--target', allowed: ['mobile', 'tv', 'desktop'] }, + 'Expected one of: mobile, tv, desktop.', + ], + ]; + + for (const [argv, bounds, expected] of cases) { + assert.throws( + () => parseArgs(argv, { strictFlags: true }), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.code, 'INVALID_ARGS'); + assert.deepEqual(error.details, { reason: 'flag_value_invalid', ...bounds }); + assert.ok(error.message.endsWith(expected), error.message); + return true; + }, + `expected ${argv.join(' ')} to be refused with its accepted values`, + ); + } +}); + test('parseArgs refuses a record option the chosen action never reads', () => { const cases: Array<[string[], string]> = [ [ @@ -305,7 +349,7 @@ test('invalid range errors are deterministic', () => { (error) => error instanceof AppError && error.code === 'INVALID_ARGS' && - error.message === 'Invalid depth: -1', + error.message === 'Invalid depth: -1. Expected integer >= 0.', ); }); diff --git a/src/cli/parser/args.ts b/src/cli/parser/args.ts index 98be3602eb..06dfb709b7 100644 --- a/src/cli/parser/args.ts +++ b/src/cli/parser/args.ts @@ -1,5 +1,6 @@ import type { CliFlags } from '@agent-device/contracts/command'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; +import { describeAcceptedValues } from '@agent-device/kernel/source-value'; import { assertCommandPositionalArity, getCommandSchema, @@ -306,7 +307,7 @@ function parseFlagValue( } if (definition.type === 'enum') { if (!definition.enumValues?.includes(value)) { - throw new AppError('INVALID_ARGS', `Invalid ${labelForFlag(token)}: ${value}`); + throw invalidFlagValue(definition, token, value); } return { value, consumeNext: inlineValue === undefined }; } @@ -314,14 +315,12 @@ function parseFlagValue( throw new AppError('INVALID_ARGS', `Flag ${token} requires a value.`); } const parsed = Number(value); - if (!Number.isFinite(parsed)) { - throw new AppError('INVALID_ARGS', `Invalid ${labelForFlag(token)}: ${value}`); - } - if (typeof definition.min === 'number' && parsed < definition.min) { - throw new AppError('INVALID_ARGS', `Invalid ${labelForFlag(token)}: ${value}`); - } - if (typeof definition.max === 'number' && parsed > definition.max) { - throw new AppError('INVALID_ARGS', `Invalid ${labelForFlag(token)}: ${value}`); + if ( + !Number.isFinite(parsed) || + (typeof definition.min === 'number' && parsed < definition.min) || + (typeof definition.max === 'number' && parsed > definition.max) + ) { + throw invalidFlagValue(definition, token, value); } return { value: definition.type === 'int' ? Math.floor(parsed) : parsed, @@ -333,6 +332,26 @@ function labelForFlag(token: string): string { return token.replace(/^-+/, ''); } +/** Why the parser refused a flag value before any command ran. */ +const FLAG_VALUE_REFUSAL_REASONS = { + // The value is not a number, falls outside the flag's range, or is not one of its enum values. + invalid: { reason: 'flag_value_invalid' }, +} as const satisfies ReasonTable<'command flags'>; + +function invalidFlagValue(definition: FlagDefinition, token: string, value: string): AppError { + return new AppError( + 'INVALID_ARGS', + `Invalid ${labelForFlag(token)}: ${value}. Expected ${describeAcceptedValues(definition)}.`, + { + reason: FLAG_VALUE_REFUSAL_REASONS.invalid.reason, + flag: token, + ...(definition.type === 'enum' + ? { allowed: definition.enumValues } + : { min: definition.min, max: definition.max }), + }, + ); +} + function looksLikeFlagToken(value: string): boolean { if (!value.startsWith('-') || value === '-') return false; const [token] = value.startsWith('--') ? splitLongFlag(value) : [value, undefined]; diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index fa20e94c1f..c8ddf90fac 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -544,6 +544,12 @@ These reasons can come from more than one command. | `ARCHIVE_UNSAFE_ENTRY` | The archive holds a link, a special file, or an encrypted entry. | | `ARCHIVE_UNSAFE_PATH` | An archive entry's name is absolute, escaping, or otherwise not one relative path. | +### Command flags + +| Reason | Meaning | +| --- | --- | +| `flag_value_invalid` | The value is not a number, falls outside the flag's range, or is not one of its enum values. | + ### Daemon lifecycle | Reason | Meaning | From f2bada23f01782743274a47b8ec85be475432ec4 Mon Sep 17 00:00:00 2001 From: parbez Date: Mon, 23 Nov 2026 12:26:09 +0530 Subject: [PATCH 2/3] fix(selectors): say fill lost its target when only the text arrived fill $REF "136849" with an unset REF reached the target decoder as one value and was told to use text="136849", which sends the text to the target slot. fill "$REF" "136849" decoded the blank target as x=0 and reported missing text. Both now refuse with details.reason fill_target_missing and say fill needs . One value that holds a selector key, such as label=Sign in, keeps its quoting hint. --- .../src/interaction-positionals.test.ts | 44 +++++++++++++++++++ .../selectors/src/interaction-positionals.ts | 34 +++++++++++++- website/docs/docs/error-reasons.md | 1 + 3 files changed, 78 insertions(+), 1 deletion(-) diff --git a/packages/selectors/src/interaction-positionals.test.ts b/packages/selectors/src/interaction-positionals.test.ts index 56c0cc06dc..1c21a61a16 100644 --- a/packages/selectors/src/interaction-positionals.test.ts +++ b/packages/selectors/src/interaction-positionals.test.ts @@ -1,5 +1,6 @@ import assert from 'node:assert/strict'; import { test } from 'vitest'; +import { AppError } from '@agent-device/kernel/errors'; import { readFillTargetFromPositionals, readInteractionTargetFromPositionals, @@ -107,3 +108,46 @@ test('readFillTargetFromPositionals treats every token after a ref as text', () text: 'good morning', }); }); + +function refusalReason(fn: () => unknown): unknown { + try { + fn(); + } catch (error) { + assert.ok(error instanceof AppError); + assert.equal(error.code, 'INVALID_ARGS'); + return error.details?.reason; + } + assert.fail('expected an INVALID_ARGS refusal'); +} + +test('readFillTargetFromPositionals refuses a fill that received only its text', () => { + // fill $REF "136849" with an unset REF, and fill "$REF" "136849" with an unset REF. + for (const positionals of [['136849'], ['', '136849']]) { + assert.equal( + refusalReason(() => readFillTargetFromPositionals(positionals)), + 'fill_target_missing', + JSON.stringify(positionals), + ); + } +}); + +test('readFillTargetFromPositionals keeps the target diagnostics that are not a missing target', () => { + for (const positionals of [ + [''], + ['button="Submit"'], + ['label=Sign in'], + ['role=button label=Sign in'], + ['label="Sign in'], + ['Email', 'qa@example.com'], + ]) { + assert.equal( + refusalReason(() => readFillTargetFromPositionals(positionals)), + undefined, + JSON.stringify(positionals), + ); + } + assertInvalidArgs( + () => readFillTargetFromPositionals(['label=Sign in']), + 'Selector values with spaces need quotes', + ); +}); diff --git a/packages/selectors/src/interaction-positionals.ts b/packages/selectors/src/interaction-positionals.ts index 3a0d305730..95a99642cb 100644 --- a/packages/selectors/src/interaction-positionals.ts +++ b/packages/selectors/src/interaction-positionals.ts @@ -1,4 +1,4 @@ -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; export function stripAtPrefix(ref: string | undefined): string | undefined { return ref?.startsWith('@') ? ref.slice(1) : ref; @@ -80,6 +80,11 @@ export function readFillTargetFromPositionals(positionals: string[]): DecodedFil text: selectorArgs.rest.length === 0 ? undefined : selectorArgs.rest.join(' '), }; } + if (isFillTargetMissing(positionals)) { + throw new AppError('INVALID_ARGS', formatFillMissingTargetFailure(positionals), { + reason: FILL_TARGET_REFUSAL_REASONS.targetMissing.reason, + }); + } const pointText = positionals.slice(2); return { kind: 'point', @@ -88,6 +93,33 @@ export function readFillTargetFromPositionals(positionals: string[]): DecodedFil }; } +/** Why `fill` refused its positionals before it decoded a target. */ +const FILL_TARGET_REFUSAL_REASONS = { + // Only the text arrived: one value that is no target, or a blank target before the text. + targetMissing: { reason: 'fill_target_missing' }, +} as const satisfies ReasonTable<'fill'>; + +/** + * `fill $REF "136849"` with an unset `REF` reaches here as one value, and `fill "$REF" "136849"` + * as a blank target; either way the caller supplied text but no target. One value that holds a + * selector key (`label=Sign in`) or an unknown key is a malformed target, so its own diagnostic + * stays. + */ +function isFillTargetMissing(positionals: string[]): boolean { + const [target = '', ...rest] = positionals; + if (rest.length > 0) return target.trim() === ''; + if (target.trim() === '' || detectUnknownSelectorKeyToken(target)) return false; + return !target.split(/\s+/).some(isSelectorToken); +} + +function formatFillMissingTargetFailure(positionals: string[]): string { + const got = + positionals.length === 1 + ? `got one value, ${quoteSelectorValue(positionals[0] ?? '')}` + : `got an empty target before ${quoteSelectorValue(positionals.slice(1).join(' '))}`; + return `fill needs but ${got}. If a ref variable expanded to nothing, the target is missing: pass an @ref from snapshot, a selector, or x y coordinates before the text.`; +} + function readPointTarget(positionals: string[]): { x: number; y: number } { const firstPositional = positionals[0] ?? ''; const unknownKey = detectUnknownSelectorKeyToken(firstPositional); diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index c8ddf90fac..08b9359c94 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -106,6 +106,7 @@ Treat a reason that this page does not list as unknown, not as an error in the r | `fill_record_as_requires_armed_recording` | `fill --record-as` needs an armed script recording; open a session with `--save-script` first. | | `fill_text_stdin_unparameterized_recording` | `fill --text-stdin` needs `--record-as` or `--no-record` while a recording is armed, so the stdin text stays out of the script. | | `android_test_ime_rebind_unconfirmed` | The test IME rebind could not be confirmed, so the focused field may have no input session. | +| `fill_target_missing` | Only the text arrived: one value that is no target, or a blank target before the text. | | `fill_text_stdin_tty` | stdin is a terminal, so the command would wait for input no one is piping. | | `fill_text_stdin_too_large` | The piped input passed the byte limit of 64 KiB. | | `fill_text_stdin_empty` | The piped input decoded to an empty string. | From 944f1c74d0aed5b9d217874112a4708f4d6723f1 Mon Sep 17 00:00:00 2001 From: parbez Date: Mon, 23 Nov 2026 12:28:21 +0530 Subject: [PATCH 3/3] fix(gestures): point coordinate drag endpoints at the held pan gesture drag "170 1595" "540 160" reached selector resolution on the device and failed with Invalid selector term "170". The drag payload reader now refuses a number, "x y" or "x,y" endpoint before dispatch and before its timing checks, with details.reason drag_endpoint_is_coordinates. When both endpoints are points and the timing is valid, details.pan and the hint name the gesture pan --hold-ms command that makes the same move. --- .../src/gesture-payload-reader.test.ts | 51 +++++++++++ .../gestures/src/gesture-payload-reader.ts | 85 +++++++++++++++++-- src/commands/schema/cli-help-gestures.ts | 2 +- website/docs/docs/commands.md | 2 +- website/docs/docs/error-reasons.md | 1 + 5 files changed, 132 insertions(+), 9 deletions(-) diff --git a/packages/gestures/src/gesture-payload-reader.test.ts b/packages/gestures/src/gesture-payload-reader.test.ts index 5b5a8a9483..4d3d68fa6d 100644 --- a/packages/gestures/src/gesture-payload-reader.test.ts +++ b/packages/gestures/src/gesture-payload-reader.test.ts @@ -1,6 +1,7 @@ import assert from 'node:assert/strict'; import { test } from 'vitest'; import { readGesturePayload } from './gesture-payload-reader.ts'; +import { AppError } from '@agent-device/kernel/errors'; test('structured gesture input rejects durations outside the planner range', () => { const cases = [ @@ -48,6 +49,56 @@ test('rotate does not accept velocity', () => { }); }); +test('drag refuses coordinate endpoints and carries the held pan that makes the move', () => { + const refusal = (source: string, destination: string, timing: Record = {}) => { + try { + readGesturePayload({ kind: 'drag', source, destination, ...timing }); + } catch (error) { + assert.ok(error instanceof AppError); + assert.equal(error.code, 'INVALID_ARGS'); + const { reason, endpoint, pan } = error.details ?? {}; + return { reason, endpoint, pan }; + } + assert.fail(`expected drag ${source} -> ${destination} to be refused`); + }; + const reason = 'drag_endpoint_is_coordinates'; + + // gesture drag "170 1595" "540 160" 1200 800 600: the pan keeps the hold and the move time. + assert.deepEqual( + refusal('170 1595', '540 160', { sourceHoldMs: 1200, moveMs: 800, destinationHoldMs: 600 }), + { + reason, + endpoint: 'source', + pan: { x: 170, y: 1595, dx: 370, dy: -1435, durationMs: 800, holdMs: 1200 }, + }, + ); + assert.deepEqual(refusal('170,1595', '540,160'), { + reason, + endpoint: 'source', + pan: { x: 170, y: 1595, dx: 370, dy: -1435, durationMs: 500, holdMs: 800 }, + }); + assert.deepEqual(refusal('id="row-1"', '540 160'), { + reason, + endpoint: 'destination', + pan: undefined, + }); + // Unquoted coordinates split into bare numbers, and an invalid moveMs: the endpoints are + // still named, without a pan. + assert.deepEqual( + refusal('170', '1595', { sourceHoldMs: 540, moveMs: 15, destinationHoldMs: 1200 }), + { + reason, + endpoint: 'source', + pan: undefined, + }, + ); + // A selector whose value is a number stays a selector. + assert.equal( + readGesturePayload({ kind: 'drag', source: 'label="170"', destination: '@e2' }).kind, + 'drag', + ); +}); + test('drag requires two non-empty targets and validates each timing phase', () => { for (const input of [ { kind: 'drag', source: '', destination: 'id="drop-target"' }, diff --git a/packages/gestures/src/gesture-payload-reader.ts b/packages/gestures/src/gesture-payload-reader.ts index 7872ceb187..5bbaa379a6 100644 --- a/packages/gestures/src/gesture-payload-reader.ts +++ b/packages/gestures/src/gesture-payload-reader.ts @@ -1,4 +1,4 @@ -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import type { Point } from '@agent-device/kernel/snapshot'; import { GESTURE_KINDS, @@ -220,6 +220,15 @@ function readPanGesturePayload(record: Record): PanGesturePaylo } function readDragGesturePayload(record: Record): DragGesturePayload { + const source = readNonEmptyString(record, 'source'); + const destination = readNonEmptyString(record, 'destination'); + assertDragEndpointsAreTargets(record, source, destination); + return { kind: 'drag', source, destination, ...readDragTiming(record) }; +} + +function readDragTiming( + record: Record, +): Pick { const sourceHoldMs = readOptionalInteger(record, 'sourceHoldMs', { min: 1, max: 10_000 }); const moveMs = readOptionalInteger(record, 'moveMs', { min: 16, max: 10_000 }); const destinationHoldMs = readOptionalInteger(record, 'destinationHoldMs', { @@ -238,13 +247,75 @@ function readDragGesturePayload(record: Record): DragGesturePay `gesture drag total duration must be at most ${GESTURE_DURATION_MAX_MS}`, ); } + return { sourceHoldMs, moveMs, destinationHoldMs }; +} + +/** Why a `gesture` input was refused before planning. */ +const GESTURE_INPUT_REFUSAL_REASONS = { + // A gesture drag endpoint is a number or an "x y" point; drag takes a ref or a selector. + dragEndpointIsCoordinates: { reason: 'drag_endpoint_is_coordinates' }, +} as const satisfies ReasonTable<'gesture'>; + +type HeldPan = { x: number; y: number; dx: number; dy: number; durationMs: number; holdMs: number }; + +/** + * A drag endpoint is a ref or a selector. A number or an "x y" pair is neither and would fail + * later as a malformed selector term, so name the held pan that makes the same move. This runs + * before the timing checks, so a bad timing cannot hide that the endpoints are coordinates. + */ +function assertDragEndpointsAreTargets( + record: Record, + source: string, + destination: string, +): void { + const from = readCoordinateEndpoint(source); + const to = readCoordinateEndpoint(destination); + if (!from && !to) return; + const pan = heldPan(record, from, to); + throw new AppError( + 'INVALID_ARGS', + `gesture drag takes a @ref or selector for source and destination, not coordinates: "${from ? source : destination}".`, + { + reason: GESTURE_INPUT_REFUSAL_REASONS.dragEndpointIsCoordinates.reason, + endpoint: from ? 'source' : 'destination', + ...(pan ? { pan } : {}), + hint: pan + ? `For a coordinate hold-then-drag, use gesture pan ${pan.x} ${pan.y} ${pan.dx} ${pan.dy} ${pan.durationMs} --hold-ms ${pan.holdMs}.${record.destinationHoldMs ? ' gesture pan does not hold at the destination.' : ''}` + : 'For a coordinate hold-then-drag, use gesture pan [durationMs] --hold-ms .', + }, + ); +} + +/** "170", "170 1595", or "170,1595". */ +function readCoordinateEndpoint(token: string): number[] | undefined { + const numbers = token.split(/[\s,]+/).map(Number); + return numbers.length <= 2 && numbers.every(Number.isFinite) ? numbers : undefined; +} + +/** The pan that makes the drag's move, when both endpoints are points and its timing is valid. */ +function heldPan( + record: Record, + from: number[] | undefined, + to: number[] | undefined, +): HeldPan | undefined { + const [x, y] = from ?? []; + const [toX, toY] = to ?? []; + if (x === undefined || y === undefined || toX === undefined || toY === undefined) + return undefined; + let timing: ReturnType; + try { + timing = readDragTiming(record); + } catch (error) { + if (error instanceof AppError) return undefined; + throw error; + } return { - kind: 'drag', - source: readNonEmptyString(record, 'source'), - destination: readNonEmptyString(record, 'destination'), - sourceHoldMs, - moveMs, - destinationHoldMs, + x, + y, + dx: toX - x, + dy: toY - y, + durationMs: timing.moveMs ?? DEFAULT_DRAG_MOVE_MS, + holdMs: timing.sourceHoldMs ?? DEFAULT_DRAG_SOURCE_HOLD_MS, }; } diff --git a/src/commands/schema/cli-help-gestures.ts b/src/commands/schema/cli-help-gestures.ts index fbe1f64f42..3d705ce9dc 100644 --- a/src/commands/schema/cli-help-gestures.ts +++ b/src/commands/schema/cli-help-gestures.ts @@ -35,7 +35,7 @@ Platform quirks: tvOS coordinate pan and fling preserve only the dominant direction as a remote swipe; authored endpoints and duration are not preserved. Gesture planning prefers the active-app frame; a backend without a gesture viewport resolver falls back to the visible snapshot union, which can be less accurate near edges. Rare iOS accessibility gap: a row shown disabled/hittable:false where press reports success but no UI change, or a collapsed composite control with no child refs -- run snapshot -i --json, compute the target center from rects, press x y, then diff snapshot -i. Coordinates are fallback-only; document why you used them. - Drag to reorder or drop: gesture drag @e12 @e40 holds the source (800 ms by default; positional sourceHoldMs overrides it), moves, and releases on the destination. swipe and fling never hold, so they do not start a reorder. + Drag to reorder or drop: gesture drag @e12 @e40 holds the source (800 ms by default; positional sourceHoldMs overrides it), moves, and releases on the destination. Its source and destination are refs or selectors, not coordinates; for a coordinate hold-then-drag, use gesture pan [durationMs] --hold-ms . swipe and fling never hold, so they do not start a reorder. On mobile, after scroll, swipe, or gesture swipe, the next read waits for two captures to agree; web and desktop targets do not wait. A caller whose own polling verifies the screen adds --no-post-gesture-stabilization to skip that wait; a directional scroll then also skips its movement check. macOS: diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 18c5f1cc1c..9398c6c697 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -1223,7 +1223,7 @@ Exact behavior: `agent-device help gesture`. - Touch platforms refuse `hover`; use `longpress` for a hold. For `hover` on the web, see [Web Automation](#web-automation). - `swipe` is a quick throw. `gesture pan` is a deliberate timed drag with one pointer, or two with `--pointer-count 2`. `gesture fling` is a fast directional throw. To update old scripts, see [Rewrite old gesture commands](/docs/migrating-gestures). - `gesture pan --hold-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 and `--hold-ms` work on Android touch devices and iOS/iPadOS only. +- `gesture drag source destination` holds one pointer from a selector or ref to another. It refuses coordinates; for a coordinate drag, use `gesture pan [ms] --hold-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. - `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. diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 08b9359c94..d8993a2575 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -140,6 +140,7 @@ Treat a reason that this page does not list as unknown, not as an error in the r | Reason | Meaning | | --- | --- | +| `drag_endpoint_is_coordinates` | A gesture drag endpoint is a number or an "x y" point; drag takes a ref or a selector. | | `GESTURE_TAP_DUPLICATE_POINT` | Two tap contacts share coordinates, so one contact would press where another already rests. | | `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. |