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
51 changes: 51 additions & 0 deletions packages/gestures/src/gesture-payload-reader.test.ts
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 { 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 = [
Expand Down Expand Up @@ -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<string, number> = {}) => {
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"' },
Expand Down
85 changes: 78 additions & 7 deletions packages/gestures/src/gesture-payload-reader.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -220,6 +220,15 @@ function readPanGesturePayload(record: Record<string, unknown>): PanGesturePaylo
}

function readDragGesturePayload(record: Record<string, unknown>): 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<string, unknown>,
): Pick<DragGesturePayload, 'sourceHoldMs' | 'moveMs' | 'destinationHoldMs'> {
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', {
Expand All @@ -238,13 +247,75 @@ function readDragGesturePayload(record: Record<string, unknown>): 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<string, unknown>,
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 <x> <y> <dx> <dy> [durationMs] --hold-ms <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<string, unknown>,
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<typeof readDragTiming>;
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,
};
}

Expand Down
8 changes: 4 additions & 4 deletions packages/kernel/src/source-value.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
});

Expand All @@ -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');
});
});

Expand Down
37 changes: 22 additions & 15 deletions packages/kernel/src/source-value.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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') {
Expand Down
44 changes: 44 additions & 0 deletions packages/selectors/src/interaction-positionals.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import assert from 'node:assert/strict';
import { test } from 'vitest';
import { AppError } from '@agent-device/kernel/errors';
import {
readFillTargetFromPositionals,
readInteractionTargetFromPositionals,
Expand Down Expand Up @@ -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',
);
});
34 changes: 33 additions & 1 deletion packages/selectors/src/interaction-positionals.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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',
Expand All @@ -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 <target> <text> 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);
Expand Down
Loading
Loading