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
2 changes: 2 additions & 0 deletions packages/ad-script/docs/target-annotation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
},
Expand Down
Original file line number Diff line number Diff line change
@@ -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> = {}): SessionAction {
return { ts: Date.now(), command: 'click', positionals: [], flags: {}, ...overrides };
}

function writeAndParse(
writer: SessionScriptWriter,
session: Parameters<SessionScriptWriter['write']>[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]);
});
3 changes: 2 additions & 1 deletion packages/daemon/src/core/session-script-writer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"']),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
7 changes: 6 additions & 1 deletion packages/selectors/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -78,6 +82,7 @@ export {
parseFindSelectorExpression,
projectSelectorExpression,
readSimpleSelectorTarget,
recordedSelectorExpression,
readSelectorAlternatives,
readReplaySelectorDisplayValue,
readSelectorExpression,
Expand Down
17 changes: 17 additions & 0 deletions packages/selectors/src/internal/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/commands/schema/cli-help.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ Script paths are the caller's:
Script line grammar:
A .ad line is <command> [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 <selector>, 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:
Expand Down
2 changes: 1 addition & 1 deletion website/docs/docs/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <scale> [x] [y]`, `gesture rotate <degrees> [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.
Expand Down
2 changes: 2 additions & 0 deletions website/docs/docs/replay-e2e.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ By default, the script goes to:
~/.agent-device/sessions/<session>-<timestamp>.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
Expand Down
Loading