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,5 +1,7 @@
import { test, expect, beforeEach } from 'vitest';
import { attachRefs } from '@agent-device/kernel/snapshot';
import { normalizeError } from '@agent-device/kernel/errors';
import { readFillTargetFromPositionals } from '@agent-device/selectors/interaction-positionals';
import { makeSessionStore } from '../../../__tests__/support/store-factory.ts';
import { activateCompleteRefFrame, expireRefFrame } from '../../../core/ref-frame.ts';
import { STALE_SNAPSHOT_REFS_WARNING } from '../../session-snapshot.ts';
Expand Down Expand Up @@ -221,3 +223,47 @@ test("ADR 0014 blocker-2: a mutating find's internal fill from an expired frame
expect(internal.data?.warning).toBeUndefined();
}
});

test('fill positionals sent straight to the daemon keep the fill_target_missing refusal the CLI reports', async () => {
const sessionStore = makeSessionStore();
const sessionName = 'fill-target-missing';
sessionStore.publish(sessionName, makeSession(sessionName));

// fill $REF "136849" with an unset REF, and fill "$REF" "136849" with an unset REF.
for (const positionals of [['136849'], ['', '136849']]) {
let cliError: unknown;
try {
readFillTargetFromPositionals(positionals);
} catch (error) {
cliError = error;
}
const cli = normalizeError(cliError);
const response = await runInteraction(sessionStore, sessionName, 'fill', positionals);
expect(response?.ok).toBe(false);
if (response && !response.ok) {
expect(response.error).toMatchObject({
code: 'INVALID_ARGS',
message: cli.message,
hint: cli.hint,
details: { reason: 'fill_target_missing', dispatched: 'no' },
});
}
}
expect(mockFillPoint).not.toHaveBeenCalled();
});

test('a sensitive fill that received only its text keeps fill_target_missing without echoing the text', async () => {
const sessionStore = makeSessionStore();
const sessionName = 'fill-target-missing-sensitive';
sessionStore.publish(sessionName, makeSession(sessionName));

for (const flags of [{ textStdin: true }, { recordAs: 'PASSWORD' }]) {
const response = await runInteraction(sessionStore, sessionName, 'fill', ['hunter2'], flags);
expect(response?.ok).toBe(false);
if (response && !response.ok) {
expect(response.error.details?.reason).toBe('fill_target_missing');
expect(JSON.stringify(response.error)).not.toContain('hunter2');
}
}
expect(mockFillPoint).not.toHaveBeenCalled();
});
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ function readFillTarget(
if (!session) return { response: noActiveSessionError() };
const unsupportedSurfaceResponse = unsupportedMacOsDesktopSurfaceInteraction(session, 'fill');
if (unsupportedSurfaceResponse) return { response: unsupportedSurfaceResponse };
const parsedTarget = parseFillTarget(params.req.positionals ?? []);
const parsedTarget = parseFillTarget(params.req.positionals ?? [], params.req.flags);
if (!parsedTarget.ok) return { response: parsedTarget.response };
return { session, parsedTarget };
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ import {
import { parseCoordinateTarget } from './interaction-targeting.ts';
import { parseVersionedRefPositional } from '../../ref-positionals.ts';
import { errorResponse } from '@agent-device/kernel/contracts';
import { AppError, normalizeError } from '@agent-device/kernel/errors';
import { isSensitiveFillText } from '@agent-device/ad-script';
import type { CommandFlags } from '@agent-device/contracts/command';

/** What a decoded touch target carries: the target plus optional ref-plan provenance. */
type ParsedTouchTargetOk = {
Expand Down Expand Up @@ -226,16 +229,15 @@ function missingFillTextResponse(place: 'ref' | 'coordinates' | 'selector'): Par
* see {@link DecodedFillTarget}); this layer adds only what the wire owns: versioned-ref
* admission, the selector whitespace rule, and the daemon error responses.
*/
export function parseFillTarget(positionals: string[]): ParsedFillTarget {
const decoded = decodeFillTarget(positionals);
if (!decoded) {
return {
ok: false,
response: errorResponse(
'INVALID_ARGS',
'fill requires x y text, @ref text, or selector text',
),
};
export function parseFillTarget(
positionals: string[],
flags?: Pick<CommandFlags, 'recordAs' | 'textStdin'>,
): ParsedFillTarget {
let decoded: DecodedFillTarget;
try {
decoded = readFillTargetFromPositionals(positionals);
} catch (error) {
return { ok: false, response: fillDecodeFailureResponse(error, flags) };
}
switch (decoded.kind) {
case 'ref': {
Expand Down Expand Up @@ -276,14 +278,24 @@ export function parseFillTarget(positionals: string[]): ParsedFillTarget {
}
}

// A decode failure only means "no recognizable target shape" — fold it into this handler's
// uniform INVALID_ARGS response.
function decodeFillTarget(positionals: string[]): DecodedFillTarget | null {
try {
return readFillTargetFromPositionals(positionals);
} catch {
return null;
// A refusal with a typed reason, such as `fill_target_missing`, keeps that reason. Every other
// decode failure folds into this handler's uniform INVALID_ARGS response.
function fillDecodeFailureResponse(
error: unknown,
flags: Pick<CommandFlags, 'recordAs' | 'textStdin'> | undefined,
): DaemonResponse {
if (!(error instanceof AppError) || typeof error.details?.reason !== 'string') {
return errorResponse('INVALID_ARGS', 'fill requires x y text, @ref text, or selector text');
}
// The decoder quotes the positionals, and a sensitive fill's positional may be the text itself.
const refusal = isSensitiveFillText(flags)
? new AppError(
'INVALID_ARGS',
'fill could not read a target before the text. Pass an @ref from snapshot, a selector, or x y coordinates.',
{ reason: error.details.reason },
)
: error;
return { ok: false, error: normalizeError(refusal) };
}

export function interactionResultExtra(
Expand Down
9 changes: 9 additions & 0 deletions packages/gestures/src/gesture-payload-reader.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,15 @@ test('drag refuses coordinate endpoints and carries the held pan that makes the
readGesturePayload({ kind: 'drag', source: 'label="170"', destination: '@e2' }).kind,
'drag',
);
// An empty or blank segment is no coordinate, so these are left to the selector checks.
for (const endpoint of [',', '170,', '170 , ']) {
assert.equal(
readGesturePayload({ kind: 'drag', source: endpoint, destination: '@e2' }).kind,
'drag',
endpoint,
);
}
assert.deepEqual(refusal('170,', '540 160'), { reason, endpoint: 'destination', pan: undefined });
});

test('drag requires two non-empty targets and validates each timing phase', () => {
Expand Down
8 changes: 5 additions & 3 deletions packages/gestures/src/gesture-payload-reader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -300,10 +300,12 @@ function assertDragEndpointsAreTargets(
);
}

/** "170", "170 1595", or "170,1595". */
/** "170", "170 1595", or "170,1595". An empty segment, as in "," or "170,", is no number. */
function readCoordinateEndpoint(token: string): number[] | undefined {
const numbers = token.split(/[\s,]+/).map(Number);
return numbers.length <= 2 && numbers.every(Number.isFinite) ? numbers : undefined;
const segments = token.split(/[\s,]+/);
if (segments.length > 2 || segments.includes('')) return undefined;
const numbers = segments.map(Number);
return numbers.every(Number.isFinite) ? numbers : undefined;
}

/** The pan that makes the drag's move, when both endpoints are points and its timing is valid. */
Expand Down
5 changes: 3 additions & 2 deletions packages/kernel/src/source-value.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,9 @@ export function parseSourceValue(
}

/**
* 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`.
* The values an enum or numeric definition accepts, as an env var or a config key reads them:
* `integer from 100 to 120000`, `number >= 0.01`, `one of: auto, socket`. A CLI int flag floors a
* fraction instead of refusing it, so its parser words the bounds as a number rounded down.
*/
export function describeAcceptedValues(definition: SourceValueDefinition): string {
if (definition.type === 'enum') return `one of: ${definition.enumValues?.join(', ')}`;
Expand Down
18 changes: 12 additions & 6 deletions src/cli/parser/__tests__/args-validation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ test('parseArgs rejects invalid record --fps range', () => {
(error) =>
error instanceof AppError &&
error.code === 'INVALID_ARGS' &&
error.message === 'Invalid fps: 0. Expected integer from 1 to 120.',
error.message ===
'Invalid fps: 0. Expected number from 1 to 120 (rounded down to an integer).',
);
});

Expand All @@ -37,17 +38,17 @@ test('parseArgs names the accepted values of a refused flag value', () => {
[
['open', 'com.example.app', '--wait', '240000'],
{ flag: '--wait', min: 100, max: 120000 },
'Expected integer from 100 to 120000.',
'Expected number from 100 to 120000 (rounded down to an integer).',
],
[
['open', 'com.example.app', '--wait=soon'],
{ flag: '--wait', min: 100, max: 120000 },
'Expected integer from 100 to 120000.',
'Expected number from 100 to 120000 (rounded down to an integer).',
],
[
['open', 'com.example.app', '--timeout', '0'],
['open', 'com.example.app', '--timeout', '0.5'],
{ flag: '--timeout', min: 1, max: undefined },
'Expected integer >= 1.',
'Expected number >= 1 (rounded down to an integer).',
],
[
['screenshot', './shot.png', '--scale', '2'],
Expand Down Expand Up @@ -76,6 +77,11 @@ test('parseArgs names the accepted values of a refused flag value', () => {
}
});

test('parseArgs floors an in-range fractional value of an integer flag', () => {
const parsed = parseArgs(['open', 'com.example.app', '--timeout', '1.5'], { strictFlags: true });
assert.equal(parsed.flags.timeoutMs, 1);
});

test('parseArgs refuses a record option the chosen action never reads', () => {
const cases: Array<[string[], string]> = [
[
Expand Down Expand Up @@ -349,7 +355,7 @@ test('invalid range errors are deterministic', () => {
(error) =>
error instanceof AppError &&
error.code === 'INVALID_ARGS' &&
error.message === 'Invalid depth: -1. Expected integer >= 0.',
error.message === 'Invalid depth: -1. Expected number >= 0 (rounded down to an integer).',
);
});

Expand Down
7 changes: 6 additions & 1 deletion src/cli/parser/args.ts
Original file line number Diff line number Diff line change
Expand Up @@ -339,9 +339,14 @@ const FLAG_VALUE_REFUSAL_REASONS = {
} as const satisfies ReasonTable<'command flags'>;

function invalidFlagValue(definition: FlagDefinition, token: string, value: string): AppError {
// An int flag takes any number in range and floors it, so `--timeout 1.5` is accepted.
const accepted =
definition.type === 'int'
? `${describeAcceptedValues({ ...definition, type: 'number' })} (rounded down to an integer)`
: describeAcceptedValues(definition);
return new AppError(
'INVALID_ARGS',
`Invalid ${labelForFlag(token)}: ${value}. Expected ${describeAcceptedValues(definition)}.`,
`Invalid ${labelForFlag(token)}: ${value}. Expected ${accepted}.`,
{
reason: FLAG_VALUE_REFUSAL_REASONS.invalid.reason,
flag: token,
Expand Down
Loading