diff --git a/packages/command-runtime/src/commands/interaction/runtime/__tests__/selector-read-policy.test.ts b/packages/command-runtime/src/commands/interaction/runtime/__tests__/selector-read-policy.test.ts index fd3705b461..0bfa5f5967 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/__tests__/selector-read-policy.test.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/__tests__/selector-read-policy.test.ts @@ -298,23 +298,39 @@ test('is exists tolerates the ambiguity its sibling predicates refuse (readAny r assert.equal(result.matches, 2); }); -test('find takes the document-order head on the same tree (readAny row)', async () => { +test('find get attrs refuses the ambiguity exists tolerates on the same tree (#4685)', async () => { const device = createSelectorDevice(ambiguousSelectorReadSnapshot()); - // `get_attrs`, not `exists`: WHICH node the row selected has to be - // observable, or the assertion cannot separate `readAny` from the - // disambiguating row — `found: true` holds either way while the selection - // silently moves to the tiebreak winner (#1715 review). - const attrs = await device.selectors.find({ + // A value read binds one node, so it shares the mutating find's contract (#1625): the candidate + // set refuses instead of the document-order head answering silently. + const error = await device.selectors + .find({ session: 'default', query: AMBIGUOUS_SELECTOR, action: 'get_attrs' }) + .then( + () => null, + (error: unknown) => error, + ); + assert.ok(error instanceof AppError, 'find get attrs must refuse rather than take a duplicate'); + assert.equal(error.code, 'AMBIGUOUS_MATCH'); + assert.equal((error.details as { matches?: number } | undefined)?.matches, 2); + + // `--first`/`--last` are the explicit opt-in. They pick an end of mutating find's ranked + // candidate set, not of document order, so the smaller tiebreak winner ranks first. + const first = await device.selectors.find({ session: 'default', query: AMBIGUOUS_SELECTOR, action: 'get_attrs', + findFirst: true, }); - assert.equal(attrs.kind, 'attrs'); - assert.equal(attrs.kind === 'attrs' ? attrs.ref : undefined, FIRST_MATCH_REF); + assert.equal(first.kind === 'attrs' ? first.ref : undefined, DISAMBIGUATED_REF); + const last = await device.selectors.find({ + session: 'default', + query: AMBIGUOUS_SELECTOR, + action: 'get_attrs', + findLast: true, + }); + assert.equal(last.kind === 'attrs' ? last.ref : undefined, FIRST_MATCH_REF); - // The presence contract rides the same resolution, so a row that refuses an - // ambiguous screen would fail here rather than answering `found: true`. + // Presence keeps the readAny row: an ambiguous screen still answers `found: true`. const exists = await device.selectors.find({ session: 'default', query: AMBIGUOUS_SELECTOR, diff --git a/packages/command-runtime/src/commands/interaction/runtime/selector-read-find-list.test.ts b/packages/command-runtime/src/commands/interaction/runtime/selector-read-find-list.test.ts index 6ca1d51a5b..6e8ac6f45c 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/selector-read-find-list.test.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/selector-read-find-list.test.ts @@ -1,5 +1,6 @@ import assert from 'node:assert/strict'; import { test } from 'vitest'; +import { AppError, readElementMatchCandidateRefs } from '@agent-device/kernel/errors'; import { makeSnapshotState } from '@agent-device/selectors/snapshot-geometry-fixtures'; import { createSelectorDevice } from './__tests__/test-utils/index.ts'; @@ -66,3 +67,106 @@ test('runtime find list on a unique match still lists instead of acting', async ['@e2'], ); }); + +// #4685: a text-locator value read sees every match (its capture is not scoped to the first one) +// and shares the mutating find's refusal, so `get text` cannot silently read one of several rows. +test('runtime find get text refuses several text matches unless --first or --last picks one', async () => { + const device = createSelectorDevice( + makeSnapshotState([APPLICATION, followButton(1, 0), followButton(2, 90), followButton(3, 180)]), + ); + + const error = await device.selectors + .find({ session: 'default', locator: 'text', query: 'Follow', action: 'get_text' }) + .then( + () => null, + (error: unknown) => error, + ); + assert.ok(error instanceof AppError); + assert.equal(error.code, 'AMBIGUOUS_MATCH'); + assert.deepEqual(readElementMatchCandidateRefs(error.details), ['e2', 'e3', 'e4']); + + const last = await device.selectors.find({ + session: 'default', + locator: 'text', + query: 'Follow', + action: 'get_text', + findLast: true, + }); + assert.equal(last.kind === 'text' ? last.ref : undefined, '@e4'); +}); + +// #4685 review: a value read counts the candidate set mutating find binds (`findOneNodeCandidates`), +// so a read and a click on the same query never bind different nodes. +test('runtime find get text never counts the application root that click excludes', async () => { + const device = createSelectorDevice( + makeSnapshotState([ + { ...APPLICATION, label: 'Settings' }, + { + index: 1, + parentIndex: 0, + type: 'Button', + label: 'Settings', + hittable: true, + rect: { x: 0, y: 100, width: 80, height: 40 }, + }, + ]), + ); + + const read = await device.selectors.find({ + session: 'default', + locator: 'label', + query: 'Settings', + action: 'get_text', + }); + assert.equal(read.kind === 'text' ? read.ref : undefined, '@e2'); +}); + +test('runtime find get text binds the onscreen match over an offscreen duplicate', async () => { + const device = createSelectorDevice( + makeSnapshotState([ + APPLICATION, + followButton(1, 0), + { ...followButton(2, 0), rect: { x: 0, y: 2400, width: 80, height: 40 } }, + ]), + ); + + const read = await device.selectors.find({ + session: 'default', + locator: 'text', + query: 'Follow', + action: 'get_text', + }); + assert.equal(read.kind === 'text' ? read.ref : undefined, '@e2'); + + // The offscreen twin is not a candidate, so --last cannot reach it by document order. + const last = await device.selectors.find({ + session: 'default', + locator: 'text', + query: 'Follow', + action: 'get_text', + findLast: true, + }); + assert.equal(last.kind === 'text' ? last.ref : undefined, '@e2'); +}); + +// #4699 review: on a producer that issues its own refs (web, agent-browser), a static text line it +// left unaddressed has no ref and no rect. A value read only reports text, so it must still find +// that node, as `find list`, `wait text` and `snapshot` do. +test('runtime find get text reads a ref-less, rectless text node', async () => { + const [root, total] = makeSnapshotState([ + APPLICATION, + { index: 1, parentIndex: 0, type: 'StaticText', label: 'Order total $42.00' }, + ]).nodes; + const { ref: _unissued, ...refless } = total!; + assert.equal(refless.rect, undefined); + const device = createSelectorDevice({ nodes: [root!, refless], createdAt: Date.now() }); + + const read = await device.selectors.find({ + session: 'default', + locator: 'text', + query: 'Order total', + action: 'get_text', + }); + assert.equal(read.kind, 'text'); + assert.equal(read.kind === 'text' ? read.text : undefined, 'Order total $42.00'); +}); diff --git a/packages/command-runtime/src/commands/interaction/runtime/selector-read.ts b/packages/command-runtime/src/commands/interaction/runtime/selector-read.ts index 2e392007eb..e4d2b33b21 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/selector-read.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/selector-read.ts @@ -1,6 +1,8 @@ import { FIND_VALUE_REQUIRED_MESSAGE, + findAmbiguousMatchMessage, findBestMatchesByLocator, + narrowFindMatches, buildSelectorChainForNode, parseFindSelectorExpression, type FindAction, @@ -10,10 +12,12 @@ import { listSelectorPipelineMatches, resolveSelectorPipeline, type SelectorPipelineHooks, + findOneNodeCandidates, } from '@agent-device/selectors/selector-pipeline'; import { SELECTOR_PIPELINE_POLICIES } from '@agent-device/selectors/selector-pipeline-policy'; import type { SnapshotNode } from '@agent-device/kernel/snapshot'; import { isSparseSnapshotQualityVerdict } from '@agent-device/capture-kit/snapshot-quality-verdict'; +import { elementMatchCandidateDetails } from '@agent-device/capture-kit/snapshot-lines'; import type { AgentDeviceRuntime, CommandContext } from '@agent-device/contracts/runtime-contract'; import { AppError } from '@agent-device/kernel/errors'; import type { @@ -57,6 +61,9 @@ export type FindReadCommandOptions = CommandContext & { query: string; action: Extract; timeoutMs?: number; + /** `--first`/`--last`: the explicit narrowing a value read (`get text`/`get attrs`) accepts. */ + findFirst?: boolean; + findLast?: boolean; } & SelectorSnapshotOptions; export type FindReadCommandResult = FindReadResult; @@ -117,12 +124,13 @@ export const findCommand: RuntimeCommand> { const selectorExpression = parseFindSelectorExpression(locator, options.query); - // Deliberately UNSCOPED: findSnapshotScope narrows the capture to the first - // label match, which is exactly wrong for an action whose purpose is to show - // every match. - const capture = await captureSelectorSnapshot(runtime, options, { - updateSession: true, - ...deriveSelectorCapturePolicy(), - }); - if (isSparseSnapshotQualityVerdict(capture.snapshot.snapshotQuality)) { - throw sparseSelectorSnapshotError(capture.snapshot.snapshotQuality); - } + const capture = await captureFindCandidates(runtime, options); const matched = selectorExpression ? (listSelectorPipelineMatches( SELECTOR_PIPELINE_POLICIES.readList, @@ -266,6 +265,58 @@ async function listFindMatches( }; } +/** + * `find get text|attrs` (#4685): a value read binds ONE node, so it shares the mutating find's + * ambiguity contract (#1625) — several matches refuse with the candidate list unless `--first` or + * `--last` picks one. It counts and narrows `findOneNodeCandidates`, the set mutating find binds, so + * a read and a tap on the same query bind the same node. Presence (`exists`, `wait`) stays + * first-match. + */ +async function findValueReadMatch( + runtime: AgentDeviceRuntime, + options: FindReadCommandOptions, + locator: FindLocator, +): Promise<{ capture: CapturedSnapshot; match: SnapshotNode }> { + const capture = await captureFindCandidates(runtime, options); + const matched = findOneNodeCandidates({ + pipeline: SELECTOR_PIPELINE_POLICIES.findRead, + nodes: capture.snapshot.nodes, + locator, + query: options.query, + selectorExpression: parseFindSelectorExpression(locator, options.query), + platform: runtime.backend.platform, + }); + if (matched.length === 0) throw new AppError('COMMAND_FAILED', 'find did not match any element'); + if (matched.length === 1) return { capture, match: matched[0]! }; + const narrowed = narrowFindMatches(matched, options); + if (!narrowed) { + throw new AppError( + 'AMBIGUOUS_MATCH', + findAmbiguousMatchMessage(matched.length, locator, options.query), + { locator, query: options.query, ...elementMatchCandidateDetails(matched) }, + ); + } + return { capture, match: narrowed }; +} + +/** One stored, unscoped capture: `list` and the value reads both need every match in it. */ +async function captureFindCandidates( + runtime: AgentDeviceRuntime, + options: FindReadCommandOptions, +): Promise { + // CONSERVATIVE: Deliberately UNSCOPED. findSnapshotScope narrows the capture to the first label + // match's subtree, which hides every other match, so neither a list nor an ambiguity check could + // see them. Revisit only if scoped capture can keep every matching subtree. + const capture = await captureSelectorSnapshot(runtime, options, { + updateSession: true, + ...deriveSelectorCapturePolicy(), + }); + if (isSparseSnapshotQualityVerdict(capture.snapshot.snapshotQuality)) { + throw sparseSelectorSnapshotError(capture.snapshot.snapshotQuality); + } + return capture; +} + /** * The address an agent acts on, when this node has one. Where the capture's producer mints its own * refs (`backend-issued`, web) a node it left unaddressed carries none, and listing one would offer diff --git a/packages/contracts/src/daemon-command-surface.ts b/packages/contracts/src/daemon-command-surface.ts index 7c8eaf744c..ecdd3b9235 100644 --- a/packages/contracts/src/daemon-command-surface.ts +++ b/packages/contracts/src/daemon-command-surface.ts @@ -113,6 +113,9 @@ export type DaemonFindOptions = CommandContext & query: string; action: 'exists' | 'wait' | 'get_text' | 'get_attrs' | 'list'; timeoutMs?: number; + /** `--first`/`--last`: narrow an ambiguous `get text`/`get attrs` by position. */ + findFirst?: boolean; + findLast?: boolean; }>; export type DaemonGetOptions = CommandContext & diff --git a/packages/daemon/src/execution/interaction/internal/find-match-ranking.ts b/packages/daemon/src/execution/interaction/internal/find-match-ranking.ts deleted file mode 100644 index 7e58ade95f..0000000000 --- a/packages/daemon/src/execution/interaction/internal/find-match-ranking.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { centerOfRect } from '@agent-device/kernel/snapshot'; -import { type SnapshotState } from '@agent-device/contracts/snapshot-model'; -import { - createActionableTouchResolver, - isRootInteractionContainer, - resolveActionableTouchResolution, -} from '@agent-device/selectors/interaction-targeting'; - -/** - * How `find` orders the candidates its locator matched, before the ambiguity - * contract in `find-match-resolution.ts` either refuses them or narrows with - * `--first`/`--last`. Ordering is a separate question from matching: it asks - * which candidate an agent most plausibly meant to touch, using the same - * actionability policy the interaction itself will run. - */ -export function preferOnscreenMatches( - matches: SnapshotState['nodes'], - nodes: SnapshotState['nodes'], -): SnapshotState['nodes'] { - const viewport = nodes[0]?.rect; - if (!viewport) return matches; - const onscreen = matches.filter((node) => { - if (!node.rect) return false; - const center = centerOfRect(node.rect); - return ( - center.x >= viewport.x && - center.x <= viewport.x + viewport.width && - center.y >= viewport.y && - center.y <= viewport.y + viewport.height - ); - }); - const preferred = onscreen.length > 0 ? onscreen : matches; - if (preferred.length < 2) return preferred; - return rankInteractiveMatches(preferred, nodes, createActionableTouchResolver(nodes)); -} - -function rankInteractiveMatches( - matches: SnapshotState['nodes'], - nodes: SnapshotState['nodes'], - resolveTouch: ReturnType, -): SnapshotState['nodes'] { - return matches - .map((node, index) => ({ - node, - index, - score: interactiveMatchScore(node, nodes, resolveTouch), - })) - .sort((left, right) => { - if (right.score !== left.score) return right.score - left.score; - return rectArea(left.node) - rectArea(right.node) || left.index - right.index; - }) - .map((entry) => entry.node); -} - -function interactiveMatchScore( - node: SnapshotState['nodes'][number], - nodes: SnapshotState['nodes'], - resolveTouch: ReturnType, -): number { - const resolution = resolveTouch(node); - if (resolution.reason === 'covered') return 0; - const resolved = resolvedTouchScore(resolution, nodes[0]); - if (resolved > 0) return resolved; - if (node.hittable && node.rect && !isRootInteractionContainer(node, nodes[0])) return 3; - return node.rect ? 1 : 0; -} - -function resolvedTouchScore( - resolution: ReturnType, - root: SnapshotState['nodes'][number] | undefined, -): number { - if (!resolution.node.rect) return 0; - if (resolution.reason === 'semantic-target' || resolution.reason === 'same-rect-descendant') { - return 4; - } - if ( - resolution.reason === 'hittable-ancestor' && - !isRootInteractionContainer(resolution.node, root) - ) { - return 2; - } - return 0; -} - -function rectArea(node: SnapshotState['nodes'][number]): number { - return node.rect ? node.rect.width * node.rect.height : Number.POSITIVE_INFINITY; -} diff --git a/packages/daemon/src/execution/interaction/internal/find-match-resolution.ts b/packages/daemon/src/execution/interaction/internal/find-match-resolution.ts index e32b20559f..08789c8375 100644 --- a/packages/daemon/src/execution/interaction/internal/find-match-resolution.ts +++ b/packages/daemon/src/execution/interaction/internal/find-match-resolution.ts @@ -1,14 +1,12 @@ import type { DaemonResponse } from '@agent-device/kernel/contracts'; import { - findBestMatchesByLocator, + narrowFindMatches, type FindLocator, type SelectorResolutionPolicy, } from '@agent-device/selectors'; -import { listSelectorPipelineMatches } from '@agent-device/selectors/selector-pipeline'; +import { findOneNodeCandidates } from '@agent-device/selectors/selector-pipeline'; import { SELECTOR_PIPELINE_POLICIES } from '@agent-device/selectors/selector-pipeline-policy'; import type { SnapshotState } from '@agent-device/contracts/snapshot-model'; -import { isRootInteractionContainer } from '@agent-device/selectors/interaction-targeting'; -import { preferOnscreenMatches } from './find-match-ranking.ts'; import type { DaemonRequest } from '../../../core/daemon-request.ts'; import type { SessionState } from '../../../core/session-state.ts'; import { buildAmbiguousMatchError } from '../../selector-match-errors.ts'; @@ -33,42 +31,31 @@ export function resolveFindMatch(params: { platform: SessionState['device']['platform']; }): FindMatchResult { const { nodes, locator, query, selectorExpression, flags, platform } = params; - const pipeline = SELECTOR_PIPELINE_POLICIES.findAct; - const rooted = nodes.filter((node) => !isRootInteractionContainer(node, nodes[0])); // #1625: selector-shaped and text-shaped queries share ONE ambiguity // contract — multiple matches reject with candidates unless --first/--last - // explicitly opts into positional narrowing. Selectors used to take the - // first match silently, which was exactly the mis-binding path the error's - // own recovery advice ("use a selector") pointed agents at. + // explicitly opts into positional narrowing. `find get text|attrs` + // counts the same candidate set (#4685). + const pipeline = SELECTOR_PIPELINE_POLICIES.findAct; const policy = pipeline.resolution; - let matches: SnapshotState['nodes']; - if (selectorExpression) { - // The `reject-candidates` door: the row's candidacy stage runs inside, and - // the whole candidate set comes back for find to rank and narrow. - matches = - listSelectorPipelineMatches(pipeline, rooted, selectorExpression, { platform }).list - ?.matchedNodes ?? []; - } else { - // Fuzzy text scoring, not a selector chain: this branch brings its own - // matcher and reads the row's rect requirement. The row still governs the - // target it produces — occlusion and promotion run on it below, in the - // same node stages the selector branch reaches. - matches = findBestMatchesByLocator(rooted, locator, query, { - requireRect: policy.requireRect, - }).matches; - } - matches = preferOnscreenMatches(matches, nodes); + let matches = findOneNodeCandidates({ + pipeline, + nodes, + locator, + query, + selectorExpression, + platform, + }); if (matches.length > 1) { // The row says candidates reject unless the caller narrowed explicitly; // assert that rather than assuming, so a future row edit cannot silently // turn this into first-match. assertRejectsCandidates(policy); - const narrowed = narrowMultipleMatches(matches, flags); + const narrowed = narrowFindMatches(matches, flags); if (!narrowed) { return { ok: false, response: buildAmbiguousMatchError(matches, locator, query) }; } - matches = narrowed; + matches = [narrowed]; } const node = matches[0] ?? null; @@ -80,12 +67,3 @@ export function resolveFindMatch(params: { } return { ok: true, node }; } - -function narrowMultipleMatches( - matches: SnapshotState['nodes'], - flags: DaemonRequest['flags'], -): SnapshotState['nodes'] | null { - if (flags?.findFirst) return [matches[0]!]; - if (flags?.findLast) return [matches.at(-1)!]; - return null; -} diff --git a/packages/daemon/src/execution/selector-match-errors.ts b/packages/daemon/src/execution/selector-match-errors.ts index cb6df8c1da..bbadc40157 100644 --- a/packages/daemon/src/execution/selector-match-errors.ts +++ b/packages/daemon/src/execution/selector-match-errors.ts @@ -1,20 +1,13 @@ import type { DaemonResponse } from '@agent-device/kernel/contracts'; -import type { FindLocator } from '@agent-device/selectors'; +import { findAmbiguousMatchMessage, type FindLocator } from '@agent-device/selectors'; import type { SnapshotState } from '@agent-device/contracts/snapshot-model'; import { elementMatchCandidateDetails } from '@agent-device/capture-kit/snapshot-lines'; import { errorResponse } from '@agent-device/kernel/contracts'; -// #1597: an agent reading an ambiguous-match error must be able to act on the -// right @ref immediately, without a follow-up snapshot round trip. Candidate -// lines reuse the exact snapshot-line renderer (`formatSnapshotLine`) so a -// candidate reads identically to its row in `snapshot -i` output: ref, role, -// label/identifier. The cap lives in the one builder that fills the disclosure -// (`elementMatchCandidateDetails`), beside the renderer — `matches` (the true -// total) is what a -// "+N more" marker is computed from at render time by the surface owners. -// Exported as find's locator AMBIGUOUS_MATCH producer so the help-benchmark -// sample parity test renders the exact error this handler returns; a message -// change here fails that gate instead of drifting past it. +// The acting find's AMBIGUOUS_MATCH response: the shared message (`findAmbiguousMatchMessage`), the +// #1597 candidates, and the acting route's `dispatched: no`. Exported so the help-benchmark sample +// parity test renders the exact error this handler returns; a message change here fails that gate +// instead of drifting past it. export function buildAmbiguousMatchError( matches: SnapshotState['nodes'], locator: FindLocator, @@ -22,8 +15,13 @@ export function buildAmbiguousMatchError( ): DaemonResponse { return errorResponse( 'AMBIGUOUS_MATCH', - `find matched ${matches.length} elements for ${locator} "${query}". Use a more specific locator or selector.`, - { locator, query, ...elementMatchCandidateDetails(matches), dispatched: 'no' }, + findAmbiguousMatchMessage(matches.length, locator, query), + { + locator, + query, + ...elementMatchCandidateDetails(matches), + dispatched: 'no', + }, ); } diff --git a/packages/daemon/src/execution/selector-runtime-ambiguity-issuance.test.ts b/packages/daemon/src/execution/selector-runtime-ambiguity-issuance.test.ts index cd37558a1c..58be6aca2d 100644 --- a/packages/daemon/src/execution/selector-runtime-ambiguity-issuance.test.ts +++ b/packages/daemon/src/execution/selector-runtime-ambiguity-issuance.test.ts @@ -6,7 +6,7 @@ import { makeSessionStore } from '../__tests__/support/store-factory.ts'; import { selectorCaptureFixture } from '../__tests__/support/selector-capture-fixture.ts'; import { refFrameScope, refFrameState } from '../core/ref-frame.ts'; import type { DaemonRequest } from '../index.ts'; -import { dispatchIsViaRuntime } from './selector-runtime.ts'; +import { dispatchFindReadOnlyViaRuntime, dispatchIsViaRuntime } from './selector-runtime.ts'; import { IOS_SIMULATOR } from '@agent-device/test-kit'; import { getRuntimeBindings, @@ -37,6 +37,16 @@ const testCreateCommandSurface = createTouchCommandSurface({ ); throw ambiguousIsError(); }, + find: async ({ session, requestId, signal }) => { + await config.backend.captureSnapshot?.( + { session, requestId, signal: signal ?? config.signal }, + { includeRects: true }, + ); + throw new AppError('AMBIGUOUS_MATCH', 'find matched 2 elements for any "Deploy"', { + matches: 2, + candidates: ['@e2 [button] "Deploy"', '@e3 [button] "Deploy"'], + }); + }, }, }), }); @@ -332,3 +342,36 @@ test('an ambiguous press issues its printed candidates from its own capture', as // Nothing was tapped: the refusal preceded dispatch. expect(mockTapPoint).not.toHaveBeenCalled(); }); + +// #4685: an ambiguous `find get text` prints candidates minted from its own full capture, so it +// owes the same issuance as `is`: pinned candidates and a frame holding exactly them. +test('an ambiguous find get text issues its printed candidates', async () => { + const sessionStore = makeSessionStore(); + const sessionName = 'find-read-ambiguity-issuance'; + const session = makeStaleRefSession(sessionName); + session.device = IOS_SIMULATOR; + sessionStore.publish(sessionName, session); + + const fixture = selectorCaptureFixture({ snapshot: () => ambiguousFullCapture() }); + const response = await dispatchFindReadOnlyViaRuntime({ + createCommandSurface: testCreateCommandSurface, + platformServices: daemonPlatformServicesFixture(), + req: { + token: 't', + session: sessionName, + command: 'find', + positionals: ['Deploy', 'get', 'text'], + flags: {}, + }, + sessionName, + sessionStore, + inspectFacts: fixture.inspectFacts, + bindDevice: fixture.bindDevice, + }); + + if (!response || response.ok) throw new Error('expected the ambiguity refusal'); + expect(response.error.code).toBe('AMBIGUOUS_MATCH'); + expect(typeof response.error.details?.refsGeneration).toBe('number'); + expect(refFrameState(session)).toBe('active'); + expect([...refFrameScope(session)].sort()).toEqual(['e2', 'e3']); +}); diff --git a/packages/daemon/src/execution/selector-runtime-find-read-only.test.ts b/packages/daemon/src/execution/selector-runtime-find-read-only.test.ts index 8638c7c0e4..904261890d 100644 --- a/packages/daemon/src/execution/selector-runtime-find-read-only.test.ts +++ b/packages/daemon/src/execution/selector-runtime-find-read-only.test.ts @@ -240,3 +240,37 @@ test('read-only find while recording is intentionally deferred from target-v1 ev // an explicit deferral, not an accident. expect(recordedAction?.targetEvidence).toBeUndefined(); }); + +// #4685: `--first`/`--last` are the only narrowing an ambiguous `find get text|attrs` accepts, so +// the read-only route has to hand them to the command family rather than drop them. +test('read-only find forwards --first and --last to the command family', async () => { + const sessionStore = makeSessionStore(); + const sessionName = 'default'; + sessionStore.publish(sessionName, makeAuthoringSession(sessionName)); + const seen: DaemonFindOptions[] = []; + const createCommandSurface = commandSurfaceWithMembers(() => ({ + selectors: { + find: async (options: DaemonFindOptions) => { + seen.push(options); + return { kind: 'found' as const, found: true as const }; + }, + }, + })); + + for (const flags of [{ findFirst: true }, { findLast: true }]) { + const response = await invokeFindHandler({ + createCommandSurface, + sessionName, + sessionStore, + positionals: ['dup', 'get', 'text'], + flags, + invoke: async () => ({ ok: true, data: {} }), + }); + expect(response?.ok).toBe(true); + } + + expect(seen.map(({ findFirst, findLast }) => ({ findFirst, findLast }))).toEqual([ + { findFirst: true, findLast: undefined }, + { findFirst: undefined, findLast: true }, + ]); +}); diff --git a/packages/daemon/src/execution/selector-runtime.ts b/packages/daemon/src/execution/selector-runtime.ts index ec6d459664..d97f768ef1 100644 --- a/packages/daemon/src/execution/selector-runtime.ts +++ b/packages/daemon/src/execution/selector-runtime.ts @@ -64,6 +64,13 @@ export async function dispatchFindReadOnlyViaRuntime( }); if (!resolvedRuntime.ok) return resolvedRuntime.response; + // #4685: an ambiguous `get text|attrs` prints candidate refs from the capture it just stored, so it + // follows the strict reads' issuance rule rather than printing refs the frame cannot honor. + const candidateIssuance = { + ref: resolvedRuntime.ref, + sessionStore: params.sessionStore, + consumed: params.consumedSnapshot, + }; const response = await toDaemonResponse(async () => { const result = await resolvedRuntime.runtime.selectors.find({ session: params.sessionName, @@ -72,6 +79,8 @@ export async function dispatchFindReadOnlyViaRuntime( query: parsed.query, action, timeoutMs: parsed.timeoutMs, + findFirst: req.flags?.findFirst, + findLast: req.flags?.findLast, }); recordIfSession( params.sessionStore, @@ -107,7 +116,7 @@ export async function dispatchFindReadOnlyViaRuntime( } } return data; - }); + }, candidateIssuance); // The consumed capture was just stored on the session: when it is an occluding system surface, // both found and not-found outcomes must disclose that app content is occluded. return withCaptureDisclosures({ diff --git a/packages/daemon/src/execution/session-snapshot.ts b/packages/daemon/src/execution/session-snapshot.ts index 6500935eaf..48039e7893 100644 --- a/packages/daemon/src/execution/session-snapshot.ts +++ b/packages/daemon/src/execution/session-snapshot.ts @@ -148,9 +148,10 @@ export function issueSettleRefs( * candidate `@ref`s must be able to ISSUE them, and issuance is only ever * valid against the tree the session's generation describes. The routes that * owe that contract run their error through here — the acting touch runtime - * (`press`/`click`/`fill`) and the strict-read dispatches (`is`, `get attrs`) + * (`press`/`click`/`fill`) and the strict-read dispatches (`is`, `get attrs`, + * and find's value reads `get text`/`get attrs`) * — so the rule has one implementation beside the partial-frame primitive it - * wraps, exactly like {@link issueSettleRefs}. The `find` refusals + * wraps, exactly like {@link issueSettleRefs}. The mutating `find` refusals * (`buildAmbiguousMatchError`, `buildNestedTextFieldsError`) deliberately do * NOT consume this rule: the first predates it (#1597), neither prints a * `refsGeneration`, and both route the caller to narrow the locator; unlike diff --git a/packages/selectors/src/index.ts b/packages/selectors/src/index.ts index 0a27c616d3..71c814d75d 100644 --- a/packages/selectors/src/index.ts +++ b/packages/selectors/src/index.ts @@ -26,9 +26,11 @@ import { import { selectorFailureHint, STALE_REF_HINT } from './internal/resolve.ts'; import { matchesWaitText } from './internal/node.ts'; import { + findAmbiguousMatchMessage, findBestMatchesByLocator, checkFindArgs, isReadOnlyFindAction, + narrowFindMatches, normalizeFindActionToken, parseFindArgs, parseFindSelectorExpression, @@ -65,8 +67,10 @@ export { checkWaitText, detectUnknownSelectorKeyToken, evaluateIsPredicate, + findAmbiguousMatchMessage, findBestMatchesByLocator, isReadOnlyFindAction, + narrowFindMatches, normalizeFindActionToken, isRoleHintWord, isSelectorToken, diff --git a/packages/daemon/src/execution/interaction/internal/__tests__/find-match-ranking.test.ts b/packages/selectors/src/interaction-targeting-find-ranking.test.ts similarity index 98% rename from packages/daemon/src/execution/interaction/internal/__tests__/find-match-ranking.test.ts rename to packages/selectors/src/interaction-targeting-find-ranking.test.ts index 97d457ccd2..10da736e4e 100644 --- a/packages/daemon/src/execution/interaction/internal/__tests__/find-match-ranking.test.ts +++ b/packages/selectors/src/interaction-targeting-find-ranking.test.ts @@ -3,7 +3,7 @@ import { test } from 'vitest'; import type { RawSnapshotNode } from '@agent-device/kernel/snapshot'; import type { SnapshotState } from '@agent-device/contracts/snapshot-model'; import { makeSnapshotState } from '@agent-device/selectors/snapshot-geometry-fixtures'; -import { preferOnscreenMatches } from '../find-match-ranking.ts'; +import { preferOnscreenMatches } from './interaction-targeting.ts'; const VIEWPORT = { x: 0, y: 0, width: 390, height: 844 }; const DUPLICATE_MATCH_COUNT = 32; diff --git a/packages/selectors/src/interaction-targeting.ts b/packages/selectors/src/interaction-targeting.ts index 66f79b872c..67721609e5 100644 --- a/packages/selectors/src/interaction-targeting.ts +++ b/packages/selectors/src/interaction-targeting.ts @@ -1,4 +1,4 @@ -import type { Rect, SnapshotNode } from '@agent-device/kernel/snapshot'; +import { centerOfRect, type Rect, type SnapshotNode } from '@agent-device/kernel/snapshot'; import { findNearestAncestor, findSnapshotAncestor, @@ -450,3 +450,81 @@ export function isNestedTouchControl(nodes: readonly SnapshotNode[], node: Snaps return encloses && larger; }); } + +/** + * How `find` orders the candidates its locator matched. Ordering is a separate question from + * matching: it asks which candidate an agent most plausibly meant to touch, using the same + * actionability policy the interaction itself will run. + */ +export function preferOnscreenMatches( + matches: SnapshotNode[], + nodes: SnapshotNode[], +): SnapshotNode[] { + const viewport = nodes[0]?.rect; + if (!viewport) return matches; + const onscreen = matches.filter((node) => { + if (!node.rect) return false; + const center = centerOfRect(node.rect); + return ( + center.x >= viewport.x && + center.x <= viewport.x + viewport.width && + center.y >= viewport.y && + center.y <= viewport.y + viewport.height + ); + }); + const preferred = onscreen.length > 0 ? onscreen : matches; + if (preferred.length < 2) return preferred; + return rankInteractiveMatches(preferred, nodes, createActionableTouchResolver(nodes)); +} + +function rankInteractiveMatches( + matches: SnapshotNode[], + nodes: SnapshotNode[], + resolveTouch: ReturnType, +): SnapshotNode[] { + return matches + .map((node, index) => ({ + node, + index, + score: interactiveMatchScore(node, nodes, resolveTouch), + })) + .sort((left, right) => { + if (right.score !== left.score) return right.score - left.score; + return rectArea(left.node) - rectArea(right.node) || left.index - right.index; + }) + .map((entry) => entry.node); +} + +function interactiveMatchScore( + node: SnapshotNode, + nodes: SnapshotNode[], + resolveTouch: ReturnType, +): number { + const resolution = resolveTouch(node); + if (resolution.reason === 'covered') return 0; + const resolved = resolvedTouchScore(resolution, nodes[0]); + if (resolved > 0) return resolved; + if (node.hittable && node.rect && !isRootInteractionContainer(node, nodes[0])) return 3; + return node.rect ? 1 : 0; +} + +function resolvedTouchScore( + resolution: ReturnType, + root: SnapshotNode | undefined, +): number { + if (!resolution.node.rect) return 0; + if (resolution.reason === 'semantic-target' || resolution.reason === 'same-rect-descendant') { + return 4; + } + if ( + resolution.reason === 'hittable-ancestor' && + !isRootInteractionContainer(resolution.node, root) + ) { + return 2; + } + return 0; +} + +function rectArea(node: SnapshotNode): number { + return node.rect ? node.rect.width * node.rect.height : Number.POSITIVE_INFINITY; +} diff --git a/packages/selectors/src/internal/find.ts b/packages/selectors/src/internal/find.ts index c731345e9a..7c9258d440 100644 --- a/packages/selectors/src/internal/find.ts +++ b/packages/selectors/src/internal/find.ts @@ -57,6 +57,32 @@ export function isReadOnlyFindAction(action: FindAction['kind']): action is Read ); } +/** + * #1625's ambiguity contract for every `find` action that binds one node: mutating actions and the + * value reads (`get text`, `get attrs`, #4685). Several matches refuse unless `--first`/`--last` + * picks one by position; `exists`, `wait`, and `list` never call this. + */ +export function narrowFindMatches( + matches: readonly SnapshotNode[], + flags: { findFirst?: boolean; findLast?: boolean } | undefined, +): SnapshotNode | undefined { + if (flags?.findFirst) return matches[0]; + if (flags?.findLast) return matches.at(-1); + return undefined; +} + +/** + * The one AMBIGUOUS_MATCH message every `find` refusal prints (#1597); each route attaches the + * candidate list (`elementMatchCandidateDetails`) and its own dispatch disclosure. + */ +export function findAmbiguousMatchMessage( + count: number, + locator: FindLocator, + query: string, +): string { + return `find matched ${count} elements for ${locator} "${query}". Use a more specific locator or selector.`; +} + export type FindMatchOptions = { requireRect?: boolean; }; diff --git a/packages/selectors/src/internal/resolution-policy.ts b/packages/selectors/src/internal/resolution-policy.ts index 776f5b9fd5..3e31e6d427 100644 --- a/packages/selectors/src/internal/resolution-policy.ts +++ b/packages/selectors/src/internal/resolution-policy.ts @@ -17,7 +17,7 @@ import type { SelectorResolutionOptions } from './public-resolution-types.ts'; * guesses when it resolves to the control; the pipeline applies that * structural collapse after this door refuses (#2498). * - `first-match` — any match count accepted, first wins (existence reads and - * the wait loop, where presence is the question). + * the wait loop, where presence is the question; never a read that returns a value). * - `reject-candidates` — multiple matches stay visible to the caller, which * either proves structural equivalence (acting targets) or rejects with a * candidate list (#1625's mutating-find contract). It is not reducible to @@ -69,7 +69,7 @@ export const SELECTOR_RESOLUTION_POLICIES = { ambiguity: 'fail-closed', requireRect: false, }, - /** `exists`/`absent` and find's read-only actions — presence is the question. */ + /** `exists`/`absent` and `find exists|wait` — presence is the question. */ readAny: { ambiguity: 'first-match', requireRect: false, @@ -84,6 +84,14 @@ export const SELECTOR_RESOLUTION_POLICIES = { ambiguity: 'reject-candidates', requireRect: true, }, + /** + * `find get text|attrs` (#4685): the same ambiguity contract as `findAct`, but a read needs + * no tap point, so a node without a rect or ref (web static text) is still a candidate. + */ + findRead: { + ambiguity: 'reject-candidates', + requireRect: false, + }, /** * `find list` — the inspection surface: every match is the ANSWER, so the * candidate set stays whole and nothing needs a tap point. diff --git a/packages/selectors/src/selector-pipeline-policy.ts b/packages/selectors/src/selector-pipeline-policy.ts index 8233fbd627..a6dd5631e2 100644 --- a/packages/selectors/src/selector-pipeline-policy.ts +++ b/packages/selectors/src/selector-pipeline-policy.ts @@ -152,7 +152,7 @@ export const SELECTOR_PIPELINE_POLICIES = { promotion: 'none', poll: 'none', }, - /** `is exists`/`absent` and find's read-only actions. */ + /** `is exists`/`absent` and `find exists|wait`. */ readAny: { resolution: SELECTOR_RESOLUTION_POLICIES.readAny, occlusion: 'ignore', @@ -182,7 +182,7 @@ export const SELECTOR_PIPELINE_POLICIES = { occlusion: 'ignore', }, /** - * Mutating `find` (#1625). `offscreen: 'ignore'` is deliberate for the ranking (`preferOnscreen + * Mutating `find` (#1625), through `findOneNodeCandidates`. `offscreen: 'ignore'` is deliberate for the ranking (`preferOnscreen * Matches` prefers an on-screen twin rather than refusing an off-screen one), and each action then * decides what to do with the winner: click/fill hand it to the acting leaf, while focus/type * dispatch a point themselves, which is why ADR 0011 classifies this row's stages per action on @@ -195,6 +195,19 @@ export const SELECTOR_PIPELINE_POLICIES = { promotion: 'hittable-ancestor-below-root', poll: 'none', }, + /** + * `find get text|attrs` (#4685), through `findOneNodeCandidates`: it shares `findAct`'s + * candidate rule (root excluded, on-screen first, several matches refuse) so a read and a tap on + * one query bind the same node. A read neither taps nor waits, so a node without a rect or ref + * stays a candidate and occlusion does not matter. + */ + findRead: { + resolution: SELECTOR_RESOLUTION_POLICIES.findRead, + occlusion: 'ignore', + offscreen: 'ignore', + promotion: 'none', + poll: 'none', + }, /** `screenshot --crop-on`: crops the capture to the resolved node's frame. */ cropTarget: { resolution: SELECTOR_RESOLUTION_POLICIES.cropTarget, diff --git a/packages/selectors/src/selector-pipeline.ts b/packages/selectors/src/selector-pipeline.ts index edb800f11f..7998bb29a4 100644 --- a/packages/selectors/src/selector-pipeline.ts +++ b/packages/selectors/src/selector-pipeline.ts @@ -4,6 +4,7 @@ import { type SnapshotNode, } from '@agent-device/kernel/snapshot'; import type { + FindLocator, SelectorChainMatchList, SelectorMatchOptions, SelectorResolution, @@ -16,11 +17,14 @@ import { isSnapshotNodeInteractionBlocked } from '@agent-device/capture-kit/snap import { classifyActionableTouchCandidates, isRootInteractionContainer, + preferOnscreenMatches, resolveActionableTouchResolution, resolveElementReportedTwice, } from './interaction-targeting.ts'; +import { findBestMatchesByLocator } from './internal/find.ts'; import type { ActingPipelinePolicy, + SELECTOR_PIPELINE_POLICIES, CandidateSetPipelinePolicy, SelectorListPolicy, SelectorPipelinePolicy, @@ -379,3 +383,31 @@ export function selectorPollBudget(policy: SelectorPipelinePolicy): WaitPollBudg } return policy.poll; } + +/** + * The candidate set of every `find` action that binds one node: mutating actions and the value + * reads (`get text`, `get attrs`). The root interaction container is never a candidate, and + * on-screen matches rank first. Callers count this list and narrow it with `narrowFindMatches`, + * so a read and a tap on the same query bind the same node. Which nodes are addressable comes from + * the action's row: `findAct` for click/fill/focus/type, `findRead` for get text/attrs. The caller + * passes the row, which the type pins, so this module stays clear of the policy table's eager import + * closure. + */ +export function findOneNodeCandidates(params: { + pipeline: (typeof SELECTOR_PIPELINE_POLICIES)['findAct' | 'findRead']; + nodes: SnapshotNode[]; + locator: FindLocator; + query: string; + selectorExpression: string | null; + platform: SelectorMatchOptions['platform']; +}): SnapshotNode[] { + const { pipeline, nodes, locator, query, selectorExpression, platform } = params; + const rooted = nodes.filter((node) => !isRootInteractionContainer(node, nodes[0])); + const matches = selectorExpression + ? (listSelectorPipelineMatches(pipeline, rooted, selectorExpression, { platform }).list + ?.matchedNodes ?? []) + : findBestMatchesByLocator(rooted, locator, query, { + requireRect: pipeline.resolution.requireRect, + }).matches; + return preferOnscreenMatches(matches, nodes); +} diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 5d0092ef6f..e75b3e9e6f 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -99,7 +99,7 @@ Snapshots and refs: 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. - 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. + 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, find get text/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 return targetHittable: false plus a hint -- verify or re-target, not a failure. Text entry: diff --git a/website/docs/docs/selectors.md b/website/docs/docs/selectors.md index ebbde6e5b4..3038bd46f3 100644 --- a/website/docs/docs/selectors.md +++ b/website/docs/docs/selectors.md @@ -39,13 +39,15 @@ Actions: matches before you act. `find` has no `longpress` or `swipe` action; run `list`, then run the gesture on the ref you picked, for example `longpress @e14`. -When more than one element matches, the mutating actions (`click`, `focus`, `fill`, `type`) reject -the query and list the candidates. This applies to text queries and selector expressions alike. -Read-only actions (`exists`, `wait`, `get`) use the first match, and `list` returns every match. Add `--first` or `--last` to pick a match by +When more than one element matches, the actions that bind one element (`click`, `focus`, `fill`, +`type`, `get text`, `get attrs`) reject the query and list the candidates. This applies to text +queries and selector expressions alike. `exists` and `wait` only ask whether something matches, so +they accept any match, and `list` returns every match. Add `--first` or `--last` to pick a match by position instead. ```bash agent-device find "Follow" click --first +agent-device find "Follow" get text --last ``` A read-only `find` that prints a ref (`get text`, `get attrs`, `list`) publishes only the refs it