From 9c38be787ed2484617b46e7cad5b9bcadb773b73 Mon Sep 17 00:00:00 2001 From: parbez Date: Mon, 23 Nov 2026 12:30:24 +0530 Subject: [PATCH] fix(help): answer help selectors with the selector syntax Agents ran help selectors and got Unknown command: selectors plus the full general help, because selector syntax lived in one line of help workflow. help selectors now prints the keys, quoting, alternatives, and matching rules, and the root help, help workflow, and the selectors docs point at it. --- .../__tests__/help-conformance-bench.test.ts | 30 ++++++++++++++ scripts/help-conformance-cases.mjs | 41 +++++++++++++++++++ .../schema/cli-help-first-screen.test.ts | 5 +++ src/commands/schema/cli-help-overview.ts | 1 + src/commands/schema/cli-help-selectors.ts | 28 +++++++++++++ src/commands/schema/cli-help.ts | 5 ++- website/docs/docs/selectors.md | 2 +- 7 files changed, 110 insertions(+), 2 deletions(-) create mode 100644 src/commands/schema/cli-help-selectors.ts diff --git a/scripts/__tests__/help-conformance-bench.test.ts b/scripts/__tests__/help-conformance-bench.test.ts index 0bfe71442c..4ebfbfed7c 100644 --- a/scripts/__tests__/help-conformance-bench.test.ts +++ b/scripts/__tests__/help-conformance-bench.test.ts @@ -6,6 +6,7 @@ import { join } from 'node:path'; import { promisify } from 'node:util'; import { test } from 'vitest'; import { scoreExpectations } from '../help-conformance-case-checks.mjs'; +import { CASES } from '../help-conformance-cases.mjs'; import { validateAgentDeviceCommand } from '../help-conformance-command-validator.ts'; import { opensAndCloses, usesValidationPrep } from '../help-conformance-expectations.mjs'; import { @@ -531,6 +532,35 @@ test('case matchers score parsed tokens so shell quoting does not change results }); }); +test('the selectors case passes a role+label plan and fails a bare role key', async () => { + const testCase = CASES.find(({ id }) => id === 'selectors-role-and-label-in-one-expression'); + assert.ok(testCase); + const score = async (commands: string[]) => + scoreExpectations( + testCase, + commands, + commands.join('\n'), + await validatePlanCommands(commands), + ); + + for (const plan of [ + [`agent-device press 'role=button label="Save"' --settle`, 'agent-device wait text "Saved"'], + ['agent-device click label=Save role=button', 'agent-device find text "Saved" exists'], + ]) { + const checks = await score(plan); + assert.ok( + Object.values(checks).every(Boolean), + `${plan.join(' && ')}: ${JSON.stringify(checks)}`, + ); + } + + const bare = await score(['agent-device press button="Save"', 'agent-device wait text "Saved"']); + assert.equal(bare.noBareRoleKey, false); + assert.equal(bare.pressesRoleAndLabelSelector, false); + const unverified = await score([`agent-device press 'role=button label="Save"'`]); + assert.equal(unverified.verifiesSavedMessage, false); +}); + test('foreground attach grammar accepts both auto-discovery and an explicit known app', async () => { const autoDiscoveryCommand = 'agent-device open --foreground --platform ios'; const explicitTargetCommand = 'agent-device open --foreground --platform ios com.example.app'; diff --git a/scripts/help-conformance-cases.mjs b/scripts/help-conformance-cases.mjs index 92a4a56dbc..5d9bf6dd8a 100644 --- a/scripts/help-conformance-cases.mjs +++ b/scripts/help-conformance-cases.mjs @@ -26,6 +26,20 @@ const RAW_COORDINATE_TARGET = const BARE_REF_TARGET = /(?:^|\n)(?:agent-device\s+)?(?:press|tap|click|fill|longpress)\s+['"]?e\d+\b/i; +// A press or click whose selector is exactly role=button and label=Save, in either order and +// either quoting: one positional ('role=button label="Save"') or two (role=button label=Save). +function isRoleButtonLabelSaveTap(agentCommand) { + if (agentCommand?.command !== 'press' && agentCommand?.command !== 'click') return false; + const terms = agentCommand.positionals + .join(' ') + .replaceAll(/["']/g, '') + .toLowerCase() + .split(/\s+/) + .filter(Boolean) + .sort(); + return terms.length === 2 && terms[0] === 'label=save' && terms[1] === 'role=button'; +} + function quiz(sample, question) { return `Read this previous agent-device output, then plan the next command: @@ -446,6 +460,33 @@ export const CASES = [ ], forbidden: [{ id: 'noRawCoordinateTarget', pattern: RAW_COORDINATE_TARGET }], }, + { + // help selectors owns selector syntax. Only its rules make the plan + // combine role and label in one selector and stay off the bare role key + // (button="Save") the task invites. + id: 'selectors-role-and-label-in-one-expression', + docs: ['--help:first30', 'selectors'], + task: 'On the already-open app, two elements read "Save": a heading and a button. Without a snapshot ref, press the button whose accessibility label is "Save", then verify a "Saved" message appears. Plan commands only.', + expectations: ['validPlanCommands', 'fullPrefix'], + matchers: [ + { + id: 'pressesRoleAndLabelSelector', + test: ({ commandValidation }) => + commandValidation.some(({ agentCommand }) => isRoleButtonLabelSaveTap(agentCommand)), + }, + { + id: 'verifiesSavedMessage', + test: ({ joined, commandValidation }) => + /\bagent-device\s+(?:wait|is|get)\b[^\n]*saved/.test(joined) || + hasFindExists(commandValidation, 'saved'), + }, + ], + forbidden: [ + // Matched against the lowercased canonical plan: button=save, or button="save" when quoted. + { id: 'noBareRoleKey', pattern: /\bbutton=\\?"?save\b/ }, + { id: 'noRawCoordinateTarget', pattern: RAW_COORDINATE_TARGET }, + ], + }, // Next-command quiz cases: captured output (pinned to the real renderer by // scripts/__tests__/help-conformance-sample-outputs.test.ts) plus a task, // scored by regex instead of the named expectation scorers above. diff --git a/src/commands/schema/cli-help-first-screen.test.ts b/src/commands/schema/cli-help-first-screen.test.ts index 7ce012c427..7197ef9640 100644 --- a/src/commands/schema/cli-help-first-screen.test.ts +++ b/src/commands/schema/cli-help-first-screen.test.ts @@ -56,6 +56,11 @@ const FIRST_SCREEN_RULES: Record = { 'iOS transform/pinch/rotate use private XCTest synthesis for a continuous two-finger pan/scale/rotation path; verify app metrics instead of assuming requested values map exactly to recognizer output', '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.', ], + selectors: [ + 'One or more key=value terms separated by spaces. An element must match every term', + 'A role word is not a key: write role=button label="Save", not button="Save"', + 'Text values match the whole field, ignoring case and extra whitespace', + ], tv: [ 'Use this when the target is Android TV (including Fire TV devices on Fire OS over ADB), Apple TV/tvOS, or an Amazon Vega OS TV app running in the Vega Virtual Device (VVD). TV surfaces are focus-first: move focus with remote/D-pad buttons, then activate the focused control', 'Vega OS is driven through the SDK-matched Vega CLI and VDA, not ADB', diff --git a/src/commands/schema/cli-help-overview.ts b/src/commands/schema/cli-help-overview.ts index 560e8c2396..6130d54129 100644 --- a/src/commands/schema/cli-help-overview.ts +++ b/src/commands/schema/cli-help-overview.ts @@ -54,6 +54,7 @@ More commands (exact shapes: agent-device help ): Guides (agent-device help ): workflow full refs, selectors, waits, recovery, and platform limits + selectors key=value syntax, quoting, alternatives, and matching manual-qa / dogfood / accessibility / validate / debugging / scripting / gestures react-native / react-devtools / cdp / tv / web / macos / remote physical-device / ios-system-ui / maestro diff --git a/src/commands/schema/cli-help-selectors.ts b/src/commands/schema/cli-help-selectors.ts new file mode 100644 index 0000000000..b50c7c7196 --- /dev/null +++ b/src/commands/schema/cli-help-selectors.ts @@ -0,0 +1,28 @@ +import { SELECTOR_KEY_NAMES } from '@agent-device/selectors'; + +export const selectorsHelpTopic = { + summary: 'Selector syntax: keys, quoting, alternatives, and matching rules', + body: `agent-device help selectors + +Selector syntax for commands that take a target. press, click, fill, longpress, hover, get, is, wait, scroll --until, and gesture drag accept a selector wherever they accept an @ref; find accepts one as its query. + +Shape: + One or more key=value terms separated by spaces. An element must match every term. Wrap the whole expression in single quotes so the shell passes it as one argument: + agent-device press 'role=button label="Continue"' + agent-device fill 'label="Email" editable=true' "qa@example.com" + agent-device wait 'id="checkout-total"' 5000 + agent-device press 'id="submit" || label="Submit order"' + Keys: ${SELECTOR_KEY_NAMES.join(' ')}. Keys are case-insensitive. + A role word is not a key: write role=button label="Save", not button="Save". No CSS selectors, --selector, or --text. + Quote values with spaces: label="Sign in". Escape a quote inside a value with a backslash: label="Say \\"hi\\"". + || separates alternatives. They are tried left to right, and the first that resolves is used. + +Matching: + id is the identifier (test ID, resource ID, accessibility identifier); label and value are the accessibility label and value; text is the first non-empty of label, value, and identifier; role is the role in brackets in snapshot output (button, text-field, switch). + Text values match the whole field, ignoring case and extra whitespace: label="sign in" matches Sign In, not Sign In Now. For a partial match, use find text "Sign" click. + Boolean keys take true or false, and a bare key means true: visible=false, editable=true, checked. + On Android, id= matches the full resource-id (pkg:id/name for native XML ids); a React Native testID arrives bare (id="login"). + Matches in distinct subtrees make a mutating command fail with AMBIGUOUS_MATCH and a candidate list. Retry with one candidate ref, or narrow the selector with role, id, or longer text. + +Prefer an @ref from the latest snapshot -i, then id/label/role selectors; coordinates are the last resort.`, +} as const; diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 35dd67a9e9..e14c67e636 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -1,4 +1,5 @@ import { gestureHelpTopic } from './cli-help-gestures.ts'; +import { selectorsHelpTopic } from './cli-help-selectors.ts'; import { listCliCommandNames } from '@agent-device/command-registry/catalog'; import { getReplayBackendDeclaration } from '@agent-device/replay-port/replay-backend-declarations'; import { normalizeCliCommandAlias } from '@agent-device/command-registry/cli-command-aliases'; @@ -97,7 +98,7 @@ Snapshots and refs: Truncated preview: snapshot -s @e12 (the current concrete ref), not get text. Missing target: scroll --until . TV/D-pad focus: help tv. Selectors: - id="field-email", label="Allow", role=button label="Search" -- not bare role keys (button="Search"); no CSS selectors/--selector/--text/raw x-y when refs/selectors exist. + id="field-email", label="Allow", role=button label="Search" -- not bare role keys (button="Search"); no CSS selectors/--selector/--text/raw x-y when refs/selectors exist. Full syntax: help selectors. Mutating selector ambiguity: press/click/fill/longpress collapse duplicate accessibility wrappers only when every match is one ancestor-descendant chain resolving to the same actionable node. Matches in distinct subtrees fail with AMBIGUOUS_MATCH and a bounded candidate list; geometry never chooses a winner. Retry one printed candidate ref (pinned to refsGeneration) or narrow the selector with role/id/longer text. Uniqueness-based reads (is except exists/absent, get attrs) share that failure shape. hittable: false on a resolved element does not block dispatch (iOS AX flags are unreliable on deep RN trees); press/fill/click and find focus/type return targetHittable: false plus a hint -- verify or re-target, not a failure. @@ -137,6 +138,7 @@ Escalate: help debugging logs, network, alerts, traces, text-entry help scripting recording, save-script, batch, replay repair help gestures multi-touch gesture shapes/quirks + help selectors selector keys, quoting, alternatives help tv Android TV, tvOS, Vega VVD remote help react-devtools RN components, props/state/hooks, render profiling help react-native RN hazards, Metro/Re.Pack, routing @@ -196,6 +198,7 @@ Recording: Tracing: trace start ./trace.log, trace stop ./trace.log (path is positional, not --path).`, }, gestures: gestureHelpTopic, + selectors: selectorsHelpTopic, tv: { summary: 'Android TV (incl. Fire TV on Fire OS), tvOS, and Vega VVD focus-first remote navigation', diff --git a/website/docs/docs/selectors.md b/website/docs/docs/selectors.md index 0ac141541b..0a9d28a675 100644 --- a/website/docs/docs/selectors.md +++ b/website/docs/docs/selectors.md @@ -74,7 +74,7 @@ Tips: A selector expression is one or more `key=value` terms separated by spaces. An element must match every term. Commands that take a target, such as `press`, `fill`, `longpress`, `get`, `is`, `wait`, and `scroll --until`, accept a selector wherever they accept an `@ref`. `find` accepts one as its -query. +query. `agent-device help selectors` prints this syntax. ```bash agent-device press 'role=button label="Continue"'