diff --git a/packages/ad-script/docs/target-annotation.md b/packages/ad-script/docs/target-annotation.md index b771718301..ede208622b 100644 --- a/packages/ad-script/docs/target-annotation.md +++ b/packages/ad-script/docs/target-annotation.md @@ -94,6 +94,8 @@ An id may identify the target and lead its selector chain only if it is unique i The writer counts matches for the id independently of ancestry. If multiple nodes carry that id, the writer demotes it to role+label, as for an unrecorded id. The rule uses capture-time uniqueness, not an `android:id/*` namespace heuristic. +A unique id is the whole recorded selector expression, with no `||` alternatives. +An alternative after it could bind only a node without that id, and verification refuses that node. ## Identity-empty pressed containers diff --git a/packages/command-runtime/src/commands/interaction/runtime/gestures.test.ts b/packages/command-runtime/src/commands/interaction/runtime/gestures.test.ts index 4237243b83..42ede142b0 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/gestures.test.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/gestures.test.ts @@ -63,8 +63,8 @@ test('runtime drag resolves generic selector endpoints before one continuous poi offsetMs: 1_500, point: { x: 290, y: 440 }, }); - assert.equal(result.recording?.sourceSelector?.split(' || ')[0], 'id="drag-source"'); - assert.equal(result.recording?.destinationSelector?.split(' || ')[0], 'id="drop-target"'); + assert.equal(result.recording?.sourceSelector, 'id="drag-source"'); + assert.equal(result.recording?.destinationSelector, 'id="drop-target"'); assert.deepEqual(result.targets?.source.resolution, { source: 'runtime', phase: 'pre-action', diff --git a/packages/command-runtime/src/commands/interaction/runtime/gestures.ts b/packages/command-runtime/src/commands/interaction/runtime/gestures.ts index 9e8c2ae7a8..7f71f8d894 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/gestures.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/gestures.ts @@ -12,6 +12,7 @@ import { singlePointerPlanEndpoints, } from '@agent-device/contracts/gesture-plan'; import { AppError } from '@agent-device/kernel/errors'; +import { recordedSelectorExpression } from '@agent-device/selectors'; import { SELECTOR_PIPELINE_POLICIES } from '@agent-device/selectors/selector-pipeline-policy'; import type { Point, Rect, SnapshotNode } from '@agent-device/kernel/snapshot'; import type { AgentDeviceRuntime, CommandContext } from '@agent-device/contracts/runtime-contract'; @@ -301,8 +302,8 @@ function dragRecordingDetails( } function selectorExpression(target: ResolvedInteractionTarget): string | undefined { - return 'selectorChain' in target && target.selectorChain?.length - ? target.selectorChain.join(' || ') + return 'selectorChain' in target && target.selectorChain + ? recordedSelectorExpression(target.selectorChain) : undefined; } diff --git a/packages/daemon/src/__tests__/support/touch-command-surface-fake.ts b/packages/daemon/src/__tests__/support/touch-command-surface-fake.ts index f8083fd155..428150b45b 100644 --- a/packages/daemon/src/__tests__/support/touch-command-surface-fake.ts +++ b/packages/daemon/src/__tests__/support/touch-command-surface-fake.ts @@ -33,7 +33,7 @@ import type { } from '@agent-device/kernel/snapshot'; import type { SnapshotState } from '@agent-device/contracts/snapshot-model'; import { extractReadableText } from '@agent-device/capture-kit/text-surface'; -import { buildSelectorChainForNode } from '@agent-device/selectors'; +import { buildSelectorChainForNode, recordedSelectorExpression } from '@agent-device/selectors'; import { fakeCreateCommandSurface } from './command-surface-fake.ts'; import { captureAndStoreSnapshot, @@ -326,8 +326,8 @@ async function dragOrInert( destination: { selectorChain: destinationTarget.selectorChain, resolution: exact }, }, recording: { - sourceSelector: sourceTarget.selectorChain.join(' || '), - destinationSelector: destinationTarget.selectorChain.join(' || '), + sourceSelector: recordedSelectorExpression(sourceTarget.selectorChain), + destinationSelector: recordedSelectorExpression(destinationTarget.selectorChain), sourceTarget, destinationTarget, }, diff --git a/packages/daemon/src/core/__tests__/session-script-writer-recorded-selector.test.ts b/packages/daemon/src/core/__tests__/session-script-writer-recorded-selector.test.ts new file mode 100644 index 0000000000..0c6fedc6c2 --- /dev/null +++ b/packages/daemon/src/core/__tests__/session-script-writer-recorded-selector.test.ts @@ -0,0 +1,58 @@ +import type { SessionAction } from '@agent-device/contracts/session'; +import { test, expect } from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; +import { SessionScriptWriter } from '../session-script-writer.ts'; +import { makeAuthoringSession } from '../../__tests__/support/session-factories.ts'; +import { parseReplayScriptDetailed } from '@agent-device/ad-script'; +import type { SnapshotNode } from '@agent-device/kernel/snapshot'; +import { buildSelectorChainForNode } from '@agent-device/selectors'; +import { createLiveTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; + +const hostCwd = createLiveTestHostEnvironment().cwd; + +function action(overrides: Partial = {}): SessionAction { + return { ts: Date.now(), command: 'click', positionals: [], flags: {}, ...overrides }; +} + +function writeAndParse( + writer: SessionScriptWriter, + session: Parameters[0], +) { + const result = writer.write(session); + if (!result.written) throw new Error('expected the script to be written'); + const script = fs.readFileSync(result.path, 'utf8'); + return { script, parsed: parseReplayScriptDetailed(script) }; +} + +function row(index: number, label: string, identifier?: string): SnapshotNode { + return { index, ref: `e${index}`, type: 'Button', label, ...(identifier ? { identifier } : {}) }; +} + +test.each([ + { + name: 'a record-time-unique id writes only the id selector', + nodes: [row(0, 'Wi-Fi', 'wifi'), row(1, 'Bluetooth', 'bluetooth')], + expected: 'id="wifi"', + }, + { + name: 'a shared id is demoted and the role/label chain stays', + nodes: [row(0, 'Wi-Fi', 'android:id/title'), row(1, 'Bluetooth', 'android:id/title')], + expected: 'role="button" label="Wi-Fi" || label="Wi-Fi"', + }, + { + name: 'a node without an id keeps the role/label chain', + nodes: [row(0, 'Wi-Fi'), row(1, 'Bluetooth')], + expected: 'role="button" label="Wi-Fi" || label="Wi-Fi"', + }, +])('$name', ({ nodes, expected }) => { + const root = mkdtempForTestSync('agent-device-script-writer-recorded-selector-'); + const writer = new SessionScriptWriter(path.join(root, 'sessions'), hostCwd); + const selectorChain = buildSelectorChainForNode(nodes[0]!, 'android', { action: 'click', nodes }); + const session = makeAuthoringSession('default', { + actions: [action({ command: 'press', positionals: ['@e0'], result: { selectorChain } })], + }); + + const { parsed } = writeAndParse(writer, session); + expect(parsed.actions[0]?.positionals).toEqual([expected]); +}); diff --git a/packages/daemon/src/core/session-script-writer.ts b/packages/daemon/src/core/session-script-writer.ts index f9db9e3dcb..cbad5bba6b 100644 --- a/packages/daemon/src/core/session-script-writer.ts +++ b/packages/daemon/src/core/session-script-writer.ts @@ -6,6 +6,7 @@ import { publicPlatformString } from '@agent-device/kernel/device'; import { dragGesturePayloadFromPositionals } from '@agent-device/contracts/gesture-normalization'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { AppError } from '@agent-device/kernel/errors'; +import { recordedSelectorExpression } from '@agent-device/selectors'; import { inferFillText, appendScriptSeriesFlags, @@ -431,7 +432,7 @@ function readSelectorChainExpression(action: SessionAction): string | undefined action.result.selectorChain.every((entry) => typeof entry === 'string') ? (action.result.selectorChain as string[]) : []; - return selectorChain.length > 0 ? selectorChain.join(' || ') : undefined; + return recordedSelectorExpression(selectorChain); } function isSelectorTargetingCommand(command: string): boolean { diff --git a/packages/daemon/src/execution/interaction/internal/interaction-gesture-drag.test.ts b/packages/daemon/src/execution/interaction/internal/interaction-gesture-drag.test.ts index b8315a8f12..0f79cdf2e2 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-gesture-drag.test.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-gesture-drag.test.ts @@ -128,8 +128,8 @@ test('recorded ref drag dispatches once and stores portable selectors with both const recorded = session.actions[0]; expect(recorded?.positionals?.[0]).toBe('drag'); - expect(recorded?.positionals?.[1]?.split(' || ')[0]).toBe('id="drag-source"'); - expect(recorded?.positionals?.[2]?.split(' || ')[0]).toBe('id="drop-target"'); + expect(recorded?.positionals?.[1]).toBe('id="drag-source"'); + expect(recorded?.positionals?.[2]).toBe('id="drop-target"'); expect(recorded?.positionals?.slice(3)).toEqual(['700', '600', '200']); expect(recorded?.result).toMatchObject({ selectorChain: expect.arrayContaining(['id="drag-source"']), diff --git a/packages/daemon/src/execution/interaction/internal/interaction-ios-tap-outcome.test.ts b/packages/daemon/src/execution/interaction/internal/interaction-ios-tap-outcome.test.ts index cc0ba7aebd..190da96aaa 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-ios-tap-outcome.test.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-ios-tap-outcome.test.ts @@ -810,9 +810,7 @@ test('corroborated runtime taps retain target evidence through save and replay', if (!written.written) return; const savedScript = fs.readFileSync(written.path, 'utf8'); expect(savedScript).toContain('# agent-device:target-v1'); - expect(savedScript).toContain( - String.raw`click "id=\"unfollow\" || role=\"button\" label=\"Unfollow\" || label=\"Unfollow\""`, - ); + expect(savedScript).toContain(`${String.raw`click "id=\"unfollow\""`}\n`); recording = false; const replaySessionName = 'ios-replayed-tap'; diff --git a/packages/selectors/src/index.ts b/packages/selectors/src/index.ts index 0a27c616d3..2be5fe49f1 100644 --- a/packages/selectors/src/index.ts +++ b/packages/selectors/src/index.ts @@ -7,7 +7,11 @@ import { IS_TEXT_VALUE_REQUIRED_MESSAGE, SELECTOR_EXPRESSION_REQUIRED_MESSAGE, } from './internal/arguments.ts'; -import { buildSelectorChainForNode, normalizeSelectorText } from './internal/build.ts'; +import { + buildSelectorChainForNode, + normalizeSelectorText, + recordedSelectorExpression, +} from './internal/build.ts'; import { detectUnknownSelectorKeyToken, isRoleHintWord, @@ -78,6 +82,7 @@ export { parseFindSelectorExpression, projectSelectorExpression, readSimpleSelectorTarget, + recordedSelectorExpression, readSelectorAlternatives, readReplaySelectorDisplayValue, readSelectorExpression, diff --git a/packages/selectors/src/internal/build.ts b/packages/selectors/src/internal/build.ts index f1fe435bc1..f39e1e615a 100644 --- a/packages/selectors/src/internal/build.ts +++ b/packages/selectors/src/internal/build.ts @@ -2,6 +2,7 @@ import { uniqueStrings } from '@agent-device/kernel/collections'; import type { Platform, PublicPlatform } from '@agent-device/kernel/device'; import type { SnapshotNode } from '@agent-device/kernel/snapshot'; import { isNodeVisible } from './node.ts'; +import { tryParseSelectorChain } from './parse.ts'; import { extractNodeText, normalizeType } from '@agent-device/contracts/snapshot'; import { idMatchCountInTree, readNodeLocalIdentity } from '@agent-device/ad-script'; @@ -68,6 +69,22 @@ export function buildSelectorChainForNode( return deduped; } +/** + * The selector expression a recorded step writes for a chain from + * `buildSelectorChainForNode`. A leading id passed `selectableId`'s + * record-time uniqueness check, so it is the whole expression: a fallback + * after it could only re-bind a node without that id, which `target-v1` + * verification refuses. Any other chain keeps its ` || ` alternatives. + */ +export function recordedSelectorExpression(chain: readonly string[]): string | undefined { + const [first] = chain; + if (first === undefined) return undefined; + const leading = tryParseSelectorChain(first)?.selectors; + const isLoneId = + leading?.length === 1 && leading[0]?.terms.length === 1 && leading[0].terms[0]?.key === 'id'; + return isLoneId ? first : chain.join(' || '); +} + /** * ADR 0012 decision 3 amendment (#1269): an id may lead the selector chain * only when it uniquely denotes the node in the record-time tree it was diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 5d0092ef6f..c8935f3428 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -159,6 +159,7 @@ Script paths are the caller's: Script line grammar: A .ad line is [positional...] [flag...]. Whitespace splits tokens; a token quoted with " or ' is one argument, and single quotes keep a double quote literal, exactly as at the shell (press 'id="far"' is one selector). Values in double quotes are JSON strings (escape \\\\, \\", \\t, \\n). Values in single quotes are literal, as at the shell: a backslash keeps its own character and the only escape is \\' for an apostrophe. A script carries only the flags declared for that command and marked recorded, so the script form of a step matches the CLI form: scroll down --until 'id="x"', wait 'label="Sign in"' --raw. CLI-only spellings and per-request options are not part of a step: --settle, --verify, scroll --pixels/--duration-ms, and the device-selection flags (--platform, --serial, --device) are the common ones a script does not carry. Reaching an off-screen target is viewport-independent in a script the same way it is at the CLI: write scroll down --until , not a fixed scroll amount that passes on one screen size and fails on another. + A recorded element step writes its target as a selector. An id unique on the recorded screen is written alone (press 'id="submit"'); otherwise it writes alternatives such as role+label and label, joined with || (press 'role="button" label="Submit" || label="Submit"'). press/click/longpress resolve their target once. Before interacting with a loading screen, add an explicit landmark wait: wait 'label="Continue"' 5000, then press 'label="Continue"'. Reusable open-to-destination scripts: diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 4ed3299301..7e8dd460b4 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -568,7 +568,7 @@ agent-device wait 'id="field-phone" value="00 062 91 77"' - `longpress` is supported on iOS and Android. `hover` is web only: it moves the pointer over a target without pressing so hover-gated UI appears, and `--settle` returns what it revealed. Touch platforms reject it; use `longpress` for the hold gesture. - `swipe` is a quick, fixed-duration throw. `gesture pan x y dx dy [durationMs]` is a deliberate timed drag with one pointer, or two with `--pointer-count 2`. Repeated swipes allow at most 200 repetitions, 10000ms pauses, and 60000ms in total. - `gesture fling up|down|left|right x y [distance]` is a fast directional throw. Neither `swipe` nor `gesture fling` takes a duration, and `gesture rotate` takes no velocity; see [Rewrite old gesture commands](/docs/migrating-gestures) to update old scripts. -- `gesture drag source destination [sourceHoldMs] [moveMs] [destinationHoldMs]` holds one pointer down from source to destination. Endpoints are selectors or refs, resolved before dispatch and recorded as selector chains. Defaults are 800, 500, and 0ms, capped at 10000ms in total. It works on Android touch devices and iOS/iPadOS; other backends refuse it before touching the screen. +- `gesture drag source destination [sourceHoldMs] [moveMs] [destinationHoldMs]` holds one pointer down from source to destination. Endpoints are selectors or refs, resolved before dispatch and recorded as selectors, the same way as other recorded steps. Defaults are 800, 500, and 0ms, capped at 10000ms in total. It works on Android touch devices and iOS/iPadOS; other backends refuse it before touching the screen. - `gesture pinch [x] [y]`, `gesture rotate [x] [y]` (the sign sets direction), `gesture transform x y dx dy scale degrees [durationMs]`, and two-finger `gesture pan` work in Android, iOS, and iPadOS app sessions, on simulators and physical devices. On Apple they use the XCTest runner, so iOS sessions reached through a WebDriver provider refuse them. One-finger `gesture pan` works wherever coordinate drags do. A path that does not fit the viewport fails before injection instead of being clamped. Use `orientation` to rotate the device. - `gesture tap x1 y1 x2 y2 [... x5 y5]` touches 2 to 5 distinct points and holds them for `--hold-ms` (default 50ms, at least 16ms) before lifting. `--count` repeats the same contacts up to 200 times with `--pause-ms` between repetitions; the series must fit in 60000ms, counting about 500ms of overhead per repetition. It works in Android and iOS/iPadOS app sessions; WebDriver providers refuse it unless they declare `tapGesture` support. On iOS the contacts touch down and lift together; on Android they touch down up to 8ms apart and lift 8ms apart in reverse order. Three or more fingers can trigger iOS system gestures such as undo, so verify app state afterwards. Use `press` for one finger. - Cancelled `gesture` and `swipe` requests return `COMMAND_FAILED` with `details.reason=request_canceled` and record no action. Repetition pauses are interruptible. diff --git a/website/docs/docs/replay-e2e.md b/website/docs/docs/replay-e2e.md index 8272cb269a..1c18665556 100644 --- a/website/docs/docs/replay-e2e.md +++ b/website/docs/docs/replay-e2e.md @@ -64,6 +64,8 @@ By default, the script goes to: ~/.agent-device/sessions/-.ad ``` +Each recorded element step writes its target as a selector. When the element's id is unique on the recorded screen, the step writes only that id, for example `press 'id="submit"'`. Otherwise, it writes alternatives such as role and label, joined with `||`, for example `press 'role="button" label="Submit" || label="Submit"'`. + To choose the output file, pass a path to `--save-script`: ```bash