diff --git a/packages/command-surface/src/interaction/interactions.test.ts b/packages/command-surface/src/interaction/interactions.test.ts index 6d1afa7c91..0da51a590e 100644 --- a/packages/command-surface/src/interaction/interactions.test.ts +++ b/packages/command-surface/src/interaction/interactions.test.ts @@ -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 }; @@ -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 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. diff --git a/packages/daemon/src/execution/interaction/internal/__tests__/interaction-touch-targets.test.ts b/packages/daemon/src/execution/interaction/internal/__tests__/interaction-touch-targets.test.ts index 2755062fd5..c09f321136 100644 --- a/packages/daemon/src/execution/interaction/internal/__tests__/interaction-touch-targets.test.ts +++ b/packages/daemon/src/execution/interaction/internal/__tests__/interaction-touch-targets.test.ts @@ -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/); } } }); diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-fill.test.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-fill.test.ts index 51ba8c43c7..62e037ed17 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-fill.test.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-fill.test.ts @@ -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'; @@ -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(); diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-fill.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-fill.ts index 6ac5609043..7211700af0 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-fill.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-fill.ts @@ -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 }; } diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-targets.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-targets.ts index b1516cba77..ffb6372942 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-targets.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-targets.ts @@ -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 = { @@ -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, -): 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': { @@ -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 | 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 { diff --git a/packages/selectors/src/interaction-positionals.test.ts b/packages/selectors/src/interaction-positionals.test.ts index 4680cbb188..b3f9ce0e64 100644 --- a/packages/selectors/src/interaction-positionals.test.ts +++ b/packages/selectors/src/interaction-positionals.test.ts @@ -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= 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= 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; + }, ); }); @@ -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), + ); + } +}); diff --git a/packages/selectors/src/interaction-positionals.ts b/packages/selectors/src/interaction-positionals.ts index 95a99642cb..48d46c42d6 100644 --- a/packages/selectors/src/interaction-positionals.ts +++ b/packages/selectors/src/interaction-positionals.ts @@ -55,6 +55,10 @@ export function readInteractionTargetFromPositionals( return readPointTarget(positionals); } +/** + * Decodes `fill` positionals. Any positional may be sensitive text (for example `--record-as` or + * `--text-stdin` when a ref variable expands to nothing), so no refusal quotes a positional. + */ export function readFillTargetFromPositionals(positionals: string[]): DecodedFillTarget { const firstPositional = positionals[0]; if (firstPositional?.startsWith('@')) { @@ -67,10 +71,7 @@ export function readFillTargetFromPositionals(positionals: string[]): DecodedFil }; } if (BARE_SNAPSHOT_REF_PATTERN.test(firstPositional ?? '')) { - throw new AppError( - 'INVALID_ARGS', - `Did you mean "@${firstPositional}"? Snapshot refs need the @ prefix.`, - ); + throw new AppError('INVALID_ARGS', 'Snapshot refs need the @ prefix.'); } const selectorArgs = splitSelectorFromArgs(positionals, { preferTrailingValue: true }); if (selectorArgs) { @@ -88,7 +89,7 @@ export function readFillTargetFromPositionals(positionals: string[]): DecodedFil const pointText = positionals.slice(2); return { kind: 'point', - target: readPointTarget(positionals.slice(0, 2)), + target: readPointTarget(positionals.slice(0, 2), { quotePositionals: false }), text: pointText.length === 0 ? undefined : pointText.join(' '), }; } @@ -113,32 +114,27 @@ function isFillTargetMissing(positionals: string[]): boolean { } 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(' '))}`; + const got = positionals.length === 1 ? 'got one value' : 'got an empty target'; 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 } { +function readPointTarget( + positionals: string[], + options: { quotePositionals?: boolean } = {}, +): { x: number; y: number } { + const quotePositionals = options.quotePositionals ?? true; const firstPositional = positionals[0] ?? ''; const unknownKey = detectUnknownSelectorKeyToken(firstPositional); if (unknownKey) { - // An unquoted multi-word value arrives split across positionals (button=Push Article), so - // fold the trailing tokens back into the suggested value like mergeRestIntoSelectorValue. - // A fully quoted value (button="Push Article") is complete; trailing tokens are not part of it. - const value = hasCompleteQuotedValue(firstPositional) - ? unknownKey.value - : [unknownKey.value, ...positionals.slice(1)].join(' ').trim(); throw new AppError( 'INVALID_ARGS', - formatUnknownSelectorKeyFailure({ key: unknownKey.key, value }), + formatUnknownSelectorKeyFailure(unknownKey, positionals, quotePositionals), ); } const x = Number(positionals[0]); const y = Number(positionals[1]); if (Number.isFinite(x) && Number.isFinite(y)) return { x, y }; - throw new AppError('INVALID_ARGS', formatTargetParseFailure(positionals)); + throw new AppError('INVALID_ARGS', formatTargetParseFailure(positionals, quotePositionals)); } function hasCompleteQuotedValue(token: string): boolean { @@ -148,25 +144,45 @@ function hasCompleteQuotedValue(token: string): boolean { return (first === '"' || first === "'") && valueRaw.endsWith(first); } -function formatUnknownSelectorKeyFailure(unknownKey: { key: string; value: string }): string { - const { key, value } = unknownKey; +function formatUnknownSelectorKeyFailure( + unknownKey: { key: string; value: string }, + positionals: string[], + quotePositionals: boolean, +): string { + const { key } = unknownKey; const supported = SELECTOR_KEY_NAMES.join(', '); + if (!quotePositionals) { + const hint = isRoleHintWord(key) + ? 'Did you mean role= label="..."?' + : 'Did you mean label="..."?'; + return `Unknown selector key. Supported: ${supported}. ${hint}`; + } + // An unquoted multi-word value arrives split across positionals (button=Push Article), so + // fold the trailing tokens back into the suggested value like mergeRestIntoSelectorValue. + // A fully quoted value (button="Push Article") is complete; trailing tokens are not part of it. + const firstPositional = positionals[0] ?? ''; + const value = hasCompleteQuotedValue(firstPositional) + ? unknownKey.value + : [unknownKey.value, ...positionals.slice(1)].join(' ').trim(); const hint = isRoleHintWord(key) ? `Did you mean role=${key} label=${quoteSelectorValue(value)}?` : `Did you mean label=${quoteSelectorValue(value)}?`; return `Unknown selector key "${key}". Supported: ${supported}. ${hint}`; } -function formatTargetParseFailure(positionals: string[]): string { +function formatTargetParseFailure(positionals: string[], quotePositionals: boolean): string { const raw = positionals.filter((part) => part !== undefined).join(' '); if (!raw.trim()) { return 'Missing target. Pass an @ref from snapshot, a selector like text="Sign in", or "x y" coordinates.'; } - const base = `Target "${raw}" is not a @ref, selector, or "x y" point.`; + const base = quotePositionals + ? `Target "${raw}" is not a @ref, selector, or "x y" point.` + : 'Target is not a @ref, selector, or "x y" point.'; if (positionals.some((part) => isSelectorToken(part ?? ''))) { return `${base} Selector values with spaces need quotes, e.g. text="Sign in".`; } - return `${base} To match by visible text, use text=${quoteSelectorValue(raw)} (or label=/id=/role=), or pass an @ref from snapshot.`; + const textExample = quotePositionals ? quoteSelectorValue(raw) : '"..."'; + return `${base} To match by visible text, use text=${textExample} (or label=/id=/role=), or pass an @ref from snapshot.`; } function formatSelectorTrailingArgsFailure( diff --git a/src/__tests__/cli-grammar.test.ts b/src/__tests__/cli-grammar.test.ts index baafb62300..746222d698 100644 --- a/src/__tests__/cli-grammar.test.ts +++ b/src/__tests__/cli-grammar.test.ts @@ -125,7 +125,8 @@ test('bare snapshot refs without @ prefix throw helpful error', () => { () => readInputFromCli('fill', ['e5', 'text'], BASE_FLAGS), (err: any) => { assert.equal(err.code, 'INVALID_ARGS'); - assert.match(err.message, /Did you mean "@e5"\?/); + assert.match(err.message, /Snapshot refs need the @ prefix/); + assert.doesNotMatch(err.message, /\be5\b|\btext\b/); return true; }, );