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
36 changes: 36 additions & 0 deletions packages/command-surface/src/interaction/interactions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { expect, test } from 'vitest';
import { interactionCliReaders, interactionDaemonWriters } from './interactions.ts';
import { selectorCliReaders } from './selectors.ts';
import { AppError } from '@agent-device/kernel/errors';
import { readFillTargetFromPositionals } from '@agent-device/selectors/interaction-positionals';
import type { CliFlags } from '@agent-device/contracts/command';

const BASE_FLAGS: CliFlags = { json: false, help: false, version: false };
Expand Down Expand Up @@ -149,6 +150,41 @@ test('fill --text-stdin refuses a text argument without echoing it', () => {
}
});

test('fill --record-as refuses unreadable targets with the shared decoder refusal and without echoing text', () => {
// fill $REF "pw-secret" --record-as PW with an unset REF, bare ref, unknown key, and non-target words.
for (const [positionals, reason] of [
[['pw-secret'], 'fill_target_missing'],
[['', 'pw-secret'], 'fill_target_missing'],
[['e5', 'pw-secret'], undefined],
[['Email', 'pw-secret'], undefined],
[['button=Email', 'pw-secret'], undefined],
] as const) {
let decoderError: unknown;
try {
readFillTargetFromPositionals([...positionals]);
} catch (error) {
decoderError = error;
}
let caught: unknown;
try {
interactionCliReaders.fill([...positionals], { ...BASE_FLAGS, recordAs: 'PW' });
} catch (error) {
caught = error;
}
expect(caught, positionals.join(' ')).toBeInstanceOf(AppError);
expect(decoderError, positionals.join(' ')).toBeInstanceOf(AppError);
const error = caught as AppError;
const expected = decoderError as AppError;
expect(error.code, positionals.join(' ')).toBe(expected.code);
expect(error.message, positionals.join(' ')).toBe(expected.message);
expect(error.details, positionals.join(' ')).toEqual(expected.details);
expect(error.details?.reason, positionals.join(' ')).toBe(reason);
expect(JSON.stringify({ message: error.message, details: error.details })).not.toMatch(
/pw-secret|Email|\be5\b|\bbutton\b/,
);
}
});

// `find <q> fill ""` is the same clear request through the find grammar (#2063): the empty
// value reaches the typed options, while a missing value is refused at the reader so the typed
// `value: string` contract stays intact.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,16 +56,18 @@ test('parseFillTarget preserves selector text whitespace', () => {
});
});

test('parseFillTarget rejects invalid coordinates instead of treating them as a point', () => {
const parsed = parseFillTarget(['10', 'not-y', 'text']);
test('parseFillTarget rejects invalid coordinates without quoting them', () => {
const parsed = parseFillTarget(['10', 'not-y', 'pw-secret']);

expect(parsed.ok).toBe(false);
if (!parsed.ok) {
expect(parsed.response.ok).toBe(false);
if (!parsed.response.ok) {
expect(parsed.response.error.message).toBe(
'fill requires x y text, @ref text, or selector text',
expect(parsed.response.error.code).toBe('INVALID_ARGS');
expect(parsed.response.error.message).toContain(
'Target is not a @ref, selector, or "x y" point',
);
expect(JSON.stringify(parsed.response.error)).not.toMatch(/not-y|pw-secret/);
}
}
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { test, expect, beforeEach } from 'vitest';
import { attachRefs } from '@agent-device/kernel/snapshot';
import { normalizeError } from '@agent-device/kernel/errors';
import { AppError, 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';
Expand Down Expand Up @@ -224,45 +224,52 @@ test("ADR 0014 blocker-2: a mutating find's internal fill from an expired frame
}
});

test('fill positionals sent straight to the daemon keep the fill_target_missing refusal the CLI reports', async () => {
test('fill positionals sent straight to the daemon keep the refusal readFillTargetFromPositionals 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']]) {
// Missing target (unset REF), bare ref, non-target words, and unknown selector key all get
// the exact decoder refusal without echoing any positional, with or without --record-as / --text-stdin.
const cases = [
[['hunter2'], 'fill_target_missing'],
[['', 'hunter2'], 'fill_target_missing'],
[['e5', 'hunter2'], undefined],
[['Email', 'hunter2'], undefined],
[['button=Email', 'hunter2'], undefined],
[['label=pw secret', 'hunter2'], undefined],
] as const;

for (const [positionals, reason] of cases) {
let cliError: unknown;
try {
readFillTargetFromPositionals(positionals);
readFillTargetFromPositionals([...positionals]);
} catch (error) {
cliError = error;
}
expect(cliError, positionals.join(' ')).toBeInstanceOf(AppError);
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');
for (const flags of [undefined, { recordAs: 'PASSWORD' }, { textStdin: true }]) {
const response = await runInteraction(
sessionStore,
sessionName,
'fill',
[...positionals],
flags,
);
expect(response?.ok).toBe(false);
if (response && !response.ok) {
expect(response.error).toMatchObject({
code: 'INVALID_ARGS',
message: cli.message,
hint: cli.hint,
details: { dispatched: 'no', ...(reason === undefined ? {} : { reason }) },
});
expect(response.error.details?.reason, positionals.join(' ')).toBe(reason);
expect(JSON.stringify(response.error), positionals.join(' ')).not.toMatch(
/hunter2|pw secret|Email|\be5\b|\bbutton\b/,
);
}
}
}
expect(mockFillPoint).not.toHaveBeenCalled();
Expand Down
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 ?? [], params.req.flags);
const parsedTarget = parseFillTarget(params.req.positionals ?? []);
if (!parsedTarget.ok) return { response: parsedTarget.response };
return { session, parsedTarget };
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ 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 @@ -238,15 +236,13 @@ 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[],
flags?: Pick<CommandFlags, 'recordAs' | 'textStdin'>,
): ParsedFillTarget {
export function parseFillTarget(positionals: string[]): ParsedFillTarget {
let decoded: DecodedFillTarget;
try {
decoded = readFillTargetFromPositionals(positionals);
} catch (error) {
return { ok: false, response: fillDecodeFailureResponse(error, flags) };
if (!(error instanceof AppError)) throw error;
return { ok: false, response: { ok: false, error: normalizeError(error) } };
}
switch (decoded.kind) {
case 'ref': {
Expand Down Expand Up @@ -287,26 +283,6 @@ export function parseFillTarget(
}
}

// 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(
result: PressCommandResult | FillCommandResult | LongPressCommandResult,
): Record<string, unknown> {
Expand Down
58 changes: 52 additions & 6 deletions packages/selectors/src/interaction-positionals.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,15 +76,26 @@ test('readInteractionTargetFromPositionals still resolves @refs and valid select
});
});

test('readFillTargetFromPositionals points a role word used as a key at role=/label= too', () => {
test('readFillTargetFromPositionals points an unknown key at role=/label= without quoting positionals', () => {
assertInvalidArgs(
() => readFillTargetFromPositionals(['button="Push Article"', 'hello']),
'Did you mean role=button label="Push Article"?',
() => readFillTargetFromPositionals(['button="Push Article"', 'pw-secret']),
'Did you mean role=<role> label="..."?',
);
// Fill treats the first two positionals as the target; an unquoted split value folds back in.
assertInvalidArgs(
() => readFillTargetFromPositionals(['button=Push', 'Article', 'hello']),
'Did you mean role=button label="Push Article"?',
() => readFillTargetFromPositionals(['button=Push', 'Article', 'pw-secret']),
'Did you mean role=<role> label="..."?',
);
assertInvalidArgs(
() => readFillTargetFromPositionals(['color="red"', 'pw-secret']),
'Did you mean label="..."?',
);
assert.throws(
() => readFillTargetFromPositionals(['color="red"', 'pw-secret']),
(error: unknown) => {
assert.ok(error instanceof Error);
assert.ok(!error.message.includes('role='));
return true;
},
);
});

Expand Down Expand Up @@ -151,3 +162,38 @@ test('readFillTargetFromPositionals keeps the target diagnostics that are not a
'Selector values with spaces need quotes',
);
});

test('readFillTargetFromPositionals quotes no positional in any refusal', () => {
for (const [positionals, reason, expectedFragment] of [
[['pw-secret'], 'fill_target_missing', 'got one value'],
[['', 'pw-secret'], 'fill_target_missing', 'got an empty target'],
[['e5', 'pw-secret'], undefined, 'Snapshot refs need the @ prefix'],
[['button="Push Article"', 'pw-secret'], undefined, 'Unknown selector key'],
[['button=Email', 'pw-secret'], undefined, 'Unknown selector key'],
[['foo=pw-secret'], undefined, 'Unknown selector key'],
[['Email', 'pw-secret'], undefined, 'Target is not a @ref, selector, or "x y" point'],
[['10', 'not-y', 'pw-secret'], undefined, 'Target is not a @ref, selector, or "x y" point'],
[['label=pw secret', 'more-secret'], undefined, 'Selector values with spaces need quotes'],
[[''], undefined, 'Missing target'],
] as const) {
let caught: unknown;
try {
readFillTargetFromPositionals([...positionals]);
} catch (error) {
caught = error;
}
assert.ok(caught instanceof AppError, JSON.stringify(positionals));
assert.equal(caught.code, 'INVALID_ARGS', JSON.stringify(positionals));
assert.equal(caught.details?.reason, reason, JSON.stringify(positionals));
assert.ok(
caught.message.includes(expectedFragment),
`expected ${JSON.stringify(caught.message)} to include ${JSON.stringify(expectedFragment)}`,
);
const serialized = JSON.stringify({ message: caught.message, details: caught.details });
assert.doesNotMatch(
serialized,
/pw-secret|pw secret|more-secret|Push Article|Email|not-y|\be5\b|\bfoo\b|\bbutton\b/,
JSON.stringify(positionals),
);
}
});
Loading
Loading