From c9da502b850fcb182934d9d8574cf2a6fb5e8bb2 Mon Sep 17 00:00:00 2001 From: xiatiandeairen Date: Wed, 18 Nov 2026 16:18:48 +0400 Subject: [PATCH 1/4] fix(find): reject ambiguous find get text and get attrs A find value read binds one node, so it now shares the mutating find contract from #1625: several matches fail with AMBIGUOUS_MATCH and the candidate list unless --first or --last picks one. The capture is no longer scoped to the first match, the daemon forwards --first/--last to the read-only runtime, and the printed candidates follow the strict-read issuance rule. exists, wait, and list keep their semantics. Fixes #4685 --- .../__tests__/selector-read-policy.test.ts | 35 ++++++++--- .../runtime/selector-read-find-list.test.ts | 28 +++++++++ .../interaction/runtime/selector-read.ts | 63 +++++++++++++++---- .../contracts/src/daemon-command-surface.ts | 3 + .../internal/find-match-resolution.ts | 14 +---- .../src/execution/selector-match-errors.ts | 26 ++++---- ...elector-runtime-ambiguity-issuance.test.ts | 45 ++++++++++++- .../selector-runtime-find-read-only.test.ts | 34 ++++++++++ .../daemon/src/execution/selector-runtime.ts | 11 +++- .../daemon/src/execution/session-snapshot.ts | 5 +- packages/selectors/src/index.ts | 4 ++ packages/selectors/src/internal/find.ts | 26 ++++++++ .../src/internal/resolution-policy.ts | 8 ++- .../selectors/src/selector-pipeline-policy.ts | 7 ++- src/commands/schema/cli-help.ts | 2 +- website/docs/docs/selectors.md | 8 ++- 16 files changed, 260 insertions(+), 59 deletions(-) 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..eef693c6ca 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,38 @@ 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: each picks its end of the candidate set. + 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, FIRST_MATCH_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, DISAMBIGUATED_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..6d9982a820 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,30 @@ 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'); +}); 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..ee7bb0e306 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, @@ -14,6 +16,7 @@ import { 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 +60,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 +123,13 @@ export const findCommand: RuntimeCommand> { + const { matched } = await captureFindMatches(runtime, options, locator); + return { + kind: 'list', + matches: matched.map((node) => ({ ...refAddress(node), node })), + }; +} + +/** + * `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. Presence (`exists`, `wait`) stays first-match. + */ +async function findValueReadMatch( + runtime: AgentDeviceRuntime, + options: FindReadCommandOptions, + locator: FindLocator, +): Promise<{ capture: CapturedSnapshot; match: SnapshotNode }> { + const { capture, matched } = await captureFindMatches(runtime, options, locator); + 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 }; +} + +/** Every match on one stored capture: the candidate set `list` returns and a value read narrows. */ +async function captureFindMatches( + runtime: AgentDeviceRuntime, + options: FindReadCommandOptions, + locator: FindLocator, +): Promise<{ capture: CapturedSnapshot; matched: SnapshotNode[] }> { 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. + // 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(), @@ -260,10 +304,7 @@ async function listFindMatches( { platform: runtime.backend.platform }, ).list?.matchedNodes ?? []) : findBestMatchesByLocator(capture.snapshot.nodes, locator, options.query, {}).matches; - return { - kind: 'list', - matches: matched.map((node) => ({ ...refAddress(node), node })), - }; + return { capture, matched }; } /** 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-resolution.ts b/packages/daemon/src/execution/interaction/internal/find-match-resolution.ts index e32b20559f..59124d4b28 100644 --- a/packages/daemon/src/execution/interaction/internal/find-match-resolution.ts +++ b/packages/daemon/src/execution/interaction/internal/find-match-resolution.ts @@ -1,6 +1,7 @@ import type { DaemonResponse } from '@agent-device/kernel/contracts'; import { findBestMatchesByLocator, + narrowFindMatches, type FindLocator, type SelectorResolutionPolicy, } from '@agent-device/selectors'; @@ -64,11 +65,11 @@ export function resolveFindMatch(params: { // 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 +81,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/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..b25862a466 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` — presence is the question. */ readAny: { ambiguity: 'first-match', requireRect: false, @@ -86,7 +86,9 @@ export const SELECTOR_RESOLUTION_POLICIES = { }, /** * `find list` — the inspection surface: every match is the ANSWER, so the - * candidate set stays whole and nothing needs a tap point. + * candidate set stays whole and nothing needs a tap point. Find's value reads + * (`get text`/`get attrs`, #4685) take the same set and, like mutating find, + * reject several matches unless `--first`/`--last` narrows them. */ readList: { ambiguity: 'reject-candidates', diff --git a/packages/selectors/src/selector-pipeline-policy.ts b/packages/selectors/src/selector-pipeline-policy.ts index 8233fbd627..4f4fa16224 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`. */ readAny: { resolution: SELECTOR_RESOLUTION_POLICIES.readAny, occlusion: 'ignore', @@ -176,7 +176,10 @@ export const SELECTOR_PIPELINE_POLICIES = { promotion: 'none', poll: WAIT_POLL_BUDGET, }, - /** `find list`: enumerate matches; never narrows, never acts. */ + /** + * `find list`: enumerate matches; never narrows, never acts. `find get text|attrs` reads + * the same set and refuses several matches unless `--first`/`--last` picks one (#4685). + */ readList: { resolution: SELECTOR_RESOLUTION_POLICIES.readList, occlusion: 'ignore', 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 From 1953103db7f9ebd9ff5e04318f2fe1ae9fded789 Mon Sep 17 00:00:00 2001 From: xiatiandeairen Date: Thu, 19 Nov 2026 10:09:38 +0400 Subject: [PATCH 2/4] fix(find): bind value reads to the same candidate set as mutating find find get text|attrs counted the raw match list, while mutating find first drops the root interaction container and prefers on-screen matches. On the same tree the two could disagree: a read refused or read the app root where a click bound one element, and --first/--last picked by document order instead of find's ranking. findOneNodeCandidates in @agent-device/selectors now builds the rooted, on-screen-preferred, ranked candidate list, and both resolveFindMatch and findValueReadMatch count and narrow it. preferOnscreenMatches moves from the daemon into the same module. --- .../__tests__/selector-read-policy.test.ts | 7 ++- .../runtime/selector-read-find-list.test.ts | 54 ++++++++++++++++ .../interaction/runtime/selector-read.ts | 43 ++++++++----- .../internal/find-match-resolution.ts | 32 ++-------- packages/selectors/package.json | 4 ++ .../src/find-candidates.test.ts} | 2 +- .../src/find-candidates.ts} | 63 ++++++++++++++----- .../src/internal/resolution-policy.ts | 11 ++-- .../selectors/src/selector-pipeline-policy.ts | 9 +-- scripts/layering/package-boundaries.test.ts | 1 + 10 files changed, 150 insertions(+), 76 deletions(-) rename packages/{daemon/src/execution/interaction/internal/__tests__/find-match-ranking.test.ts => selectors/src/find-candidates.test.ts} (98%) rename packages/{daemon/src/execution/interaction/internal/find-match-ranking.ts => selectors/src/find-candidates.ts} (52%) 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 eef693c6ca..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 @@ -313,21 +313,22 @@ test('find get attrs refuses the ambiguity exists tolerates on the same tree (#4 assert.equal(error.code, 'AMBIGUOUS_MATCH'); assert.equal((error.details as { matches?: number } | undefined)?.matches, 2); - // `--first`/`--last` are the explicit opt-in: each picks its end of the candidate set. + // `--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(first.kind === 'attrs' ? first.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, DISAMBIGUATED_REF); + assert.equal(last.kind === 'attrs' ? last.ref : undefined, FIRST_MATCH_REF); // Presence keeps the readAny row: an ambiguous screen still answers `found: true`. const exists = await device.selectors.find({ 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 6d9982a820..80c0e6b99c 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 @@ -94,3 +94,57 @@ test('runtime find get text refuses several text matches unless --first or --las }); 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'); +}); 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 ee7bb0e306..24edd74df1 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/selector-read.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/selector-read.ts @@ -14,6 +14,7 @@ import { type SelectorPipelineHooks, } from '@agent-device/selectors/selector-pipeline'; import { SELECTOR_PIPELINE_POLICIES } from '@agent-device/selectors/selector-pipeline-policy'; +import { findOneNodeCandidates } from '@agent-device/selectors/find-candidates'; 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'; @@ -248,7 +249,16 @@ async function listFindMatches( options: FindReadCommandOptions, locator: FindLocator, ): Promise> { - const { matched } = await captureFindMatches(runtime, options, locator); + const selectorExpression = parseFindSelectorExpression(locator, options.query); + const capture = await captureFindCandidates(runtime, options); + const matched = selectorExpression + ? (listSelectorPipelineMatches( + SELECTOR_PIPELINE_POLICIES.readList, + capture.snapshot.nodes, + selectorExpression, + { platform: runtime.backend.platform }, + ).list?.matchedNodes ?? []) + : findBestMatchesByLocator(capture.snapshot.nodes, locator, options.query, {}).matches; return { kind: 'list', matches: matched.map((node) => ({ ...refAddress(node), node })), @@ -258,14 +268,23 @@ 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. Presence (`exists`, `wait`) stays first-match. + * `--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, matched } = await captureFindMatches(runtime, options, locator); + const capture = await captureFindCandidates(runtime, options); + const matched = findOneNodeCandidates({ + 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); @@ -279,13 +298,11 @@ async function findValueReadMatch( return { capture, match: narrowed }; } -/** Every match on one stored capture: the candidate set `list` returns and a value read narrows. */ -async function captureFindMatches( +/** One stored, unscoped capture: `list` and the value reads both need every match in it. */ +async function captureFindCandidates( runtime: AgentDeviceRuntime, options: FindReadCommandOptions, - locator: FindLocator, -): Promise<{ capture: CapturedSnapshot; matched: SnapshotNode[] }> { - const selectorExpression = parseFindSelectorExpression(locator, options.query); +): 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. @@ -296,15 +313,7 @@ async function captureFindMatches( if (isSparseSnapshotQualityVerdict(capture.snapshot.snapshotQuality)) { throw sparseSelectorSnapshotError(capture.snapshot.snapshotQuality); } - const matched = selectorExpression - ? (listSelectorPipelineMatches( - SELECTOR_PIPELINE_POLICIES.readList, - capture.snapshot.nodes, - selectorExpression, - { platform: runtime.backend.platform }, - ).list?.matchedNodes ?? []) - : findBestMatchesByLocator(capture.snapshot.nodes, locator, options.query, {}).matches; - return { capture, matched }; + return capture; } /** 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 59124d4b28..fb48dd1067 100644 --- a/packages/daemon/src/execution/interaction/internal/find-match-resolution.ts +++ b/packages/daemon/src/execution/interaction/internal/find-match-resolution.ts @@ -1,15 +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/find-candidates'; 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'; @@ -34,31 +31,12 @@ 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. - 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); + // explicitly opts into positional narrowing. `find get text|attrs` + // counts the same candidate set (#4685). + const policy = SELECTOR_PIPELINE_POLICIES.findAct.resolution; + let matches = findOneNodeCandidates({ nodes, locator, query, selectorExpression, platform }); if (matches.length > 1) { // The row says candidates reject unless the caller narrowed explicitly; diff --git a/packages/selectors/package.json b/packages/selectors/package.json index 4a3d25ceff..7b0ab00a51 100644 --- a/packages/selectors/package.json +++ b/packages/selectors/package.json @@ -52,6 +52,10 @@ "types": "./src/interaction-positionals.ts", "default": "./src/interaction-positionals.ts" }, + "./find-candidates": { + "types": "./src/find-candidates.ts", + "default": "./src/find-candidates.ts" + }, "./interaction-targeting": { "types": "./src/interaction-targeting.ts", "default": "./src/interaction-targeting.ts" diff --git a/packages/daemon/src/execution/interaction/internal/__tests__/find-match-ranking.test.ts b/packages/selectors/src/find-candidates.test.ts similarity index 98% rename from packages/daemon/src/execution/interaction/internal/__tests__/find-match-ranking.test.ts rename to packages/selectors/src/find-candidates.test.ts index 97d457ccd2..8338dde6aa 100644 --- a/packages/daemon/src/execution/interaction/internal/__tests__/find-match-ranking.test.ts +++ b/packages/selectors/src/find-candidates.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 './find-candidates.ts'; const VIEWPORT = { x: 0, y: 0, width: 390, height: 844 }; const DUPLICATE_MATCH_COUNT = 32; diff --git a/packages/daemon/src/execution/interaction/internal/find-match-ranking.ts b/packages/selectors/src/find-candidates.ts similarity index 52% rename from packages/daemon/src/execution/interaction/internal/find-match-ranking.ts rename to packages/selectors/src/find-candidates.ts index 7e58ade95f..bd34a56a37 100644 --- a/packages/daemon/src/execution/interaction/internal/find-match-ranking.ts +++ b/packages/selectors/src/find-candidates.ts @@ -1,22 +1,51 @@ -import { centerOfRect } from '@agent-device/kernel/snapshot'; -import { type SnapshotState } from '@agent-device/contracts/snapshot-model'; +import { centerOfRect, type SnapshotNode } from '@agent-device/kernel/snapshot'; +import { + findBestMatchesByLocator, + type FindLocator, + type SelectorMatchOptions, +} from '@agent-device/selectors'; import { createActionableTouchResolver, isRootInteractionContainer, resolveActionableTouchResolution, -} from '@agent-device/selectors/interaction-targeting'; +} from './interaction-targeting.ts'; +import { listSelectorPipelineMatches } from './selector-pipeline.ts'; +import { SELECTOR_PIPELINE_POLICIES } from './selector-pipeline-policy.ts'; + +/** + * 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. + */ +export function findOneNodeCandidates(params: { + nodes: SnapshotNode[]; + locator: FindLocator; + query: string; + selectorExpression: string | null; + platform: SelectorMatchOptions['platform']; +}): SnapshotNode[] { + const { nodes, locator, query, selectorExpression, platform } = params; + const pipeline = SELECTOR_PIPELINE_POLICIES.findAct; + 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); +} /** - * 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 + * 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: SnapshotState['nodes'], - nodes: SnapshotState['nodes'], -): SnapshotState['nodes'] { + matches: SnapshotNode[], + nodes: SnapshotNode[], +): SnapshotNode[] { const viewport = nodes[0]?.rect; if (!viewport) return matches; const onscreen = matches.filter((node) => { @@ -35,10 +64,10 @@ export function preferOnscreenMatches( } function rankInteractiveMatches( - matches: SnapshotState['nodes'], - nodes: SnapshotState['nodes'], + matches: SnapshotNode[], + nodes: SnapshotNode[], resolveTouch: ReturnType, -): SnapshotState['nodes'] { +): SnapshotNode[] { return matches .map((node, index) => ({ node, @@ -53,8 +82,8 @@ function rankInteractiveMatches( } function interactiveMatchScore( - node: SnapshotState['nodes'][number], - nodes: SnapshotState['nodes'], + node: SnapshotNode, + nodes: SnapshotNode[], resolveTouch: ReturnType, ): number { const resolution = resolveTouch(node); @@ -67,7 +96,7 @@ function interactiveMatchScore( function resolvedTouchScore( resolution: ReturnType, - root: SnapshotState['nodes'][number] | undefined, + root: SnapshotNode | undefined, ): number { if (!resolution.node.rect) return 0; if (resolution.reason === 'semantic-target' || resolution.reason === 'same-rect-descendant') { @@ -82,6 +111,6 @@ function resolvedTouchScore( return 0; } -function rectArea(node: SnapshotState['nodes'][number]): number { +function rectArea(node: SnapshotNode): number { return node.rect ? node.rect.width * node.rect.height : Number.POSITIVE_INFINITY; } diff --git a/packages/selectors/src/internal/resolution-policy.ts b/packages/selectors/src/internal/resolution-policy.ts index b25862a466..d985c37a24 100644 --- a/packages/selectors/src/internal/resolution-policy.ts +++ b/packages/selectors/src/internal/resolution-policy.ts @@ -69,7 +69,7 @@ export const SELECTOR_RESOLUTION_POLICIES = { ambiguity: 'fail-closed', requireRect: false, }, - /** `exists`/`absent` and `find exists` — presence is the question. */ + /** `exists`/`absent` and `find exists|wait` — presence is the question. */ readAny: { ambiguity: 'first-match', requireRect: false, @@ -79,16 +79,17 @@ export const SELECTOR_RESOLUTION_POLICIES = { ambiguity: 'first-match', requireRect: false, }, - /** Mutating `find` (#1625): candidates reject unless explicitly narrowed. */ + /** + * Mutating `find` (#1625) and its value reads (`get text`/`get attrs`, #4685): + * candidates reject unless explicitly narrowed. + */ findAct: { ambiguity: 'reject-candidates', requireRect: true, }, /** * `find list` — the inspection surface: every match is the ANSWER, so the - * candidate set stays whole and nothing needs a tap point. Find's value reads - * (`get text`/`get attrs`, #4685) take the same set and, like mutating find, - * reject several matches unless `--first`/`--last` narrows them. + * candidate set stays whole and nothing needs a tap point. */ readList: { ambiguity: 'reject-candidates', diff --git a/packages/selectors/src/selector-pipeline-policy.ts b/packages/selectors/src/selector-pipeline-policy.ts index 4f4fa16224..ce74a06b21 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 exists`. */ + /** `is exists`/`absent` and `find exists|wait`. */ readAny: { resolution: SELECTOR_RESOLUTION_POLICIES.readAny, occlusion: 'ignore', @@ -176,16 +176,13 @@ export const SELECTOR_PIPELINE_POLICIES = { promotion: 'none', poll: WAIT_POLL_BUDGET, }, - /** - * `find list`: enumerate matches; never narrows, never acts. `find get text|attrs` reads - * the same set and refuses several matches unless `--first`/`--last` picks one (#4685). - */ + /** `find list`: enumerate matches; never narrows, never acts. */ readList: { resolution: SELECTOR_RESOLUTION_POLICIES.readList, occlusion: 'ignore', }, /** - * Mutating `find` (#1625). `offscreen: 'ignore'` is deliberate for the ranking (`preferOnscreen + * Mutating `find` (#1625) and its value reads (#4685, 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 diff --git a/scripts/layering/package-boundaries.test.ts b/scripts/layering/package-boundaries.test.ts index e1c99c20a7..d238d6a1e2 100644 --- a/scripts/layering/package-boundaries.test.ts +++ b/scripts/layering/package-boundaries.test.ts @@ -778,6 +778,7 @@ test('the real tree parses, declares, and passes R11', () => { '@agent-device/selectors/absence-observation-resolution', '@agent-device/selectors/ast', '@agent-device/selectors/engine', + '@agent-device/selectors/find-candidates', '@agent-device/selectors/interaction-action', '@agent-device/selectors/interaction-error', '@agent-device/selectors/interaction-positionals', From b7ec11ed58a42a27c8cf2723fa31a6a6b3459e77 Mon Sep 17 00:00:00 2001 From: xiatiandeairen Date: Thu, 19 Nov 2026 12:30:43 +0400 Subject: [PATCH 3/4] fix(find): keep the shared find candidate set out of a new eager module The eager-closure budget rejected find-candidates.ts: as a new subpath it added a module to command-runtime's closure, and its static edge to the selectors entry made it evaluate 67 modules where the ranking code it replaced evaluated 15. preferOnscreenMatches and its ranking helpers now live in interaction-targeting, whose functions they already called, and findOneNodeCandidates lives in selector-pipeline, which both callers already import. Callers pass the findAct row, typed to that row, so selector-pipeline does not pull in the policy table. The ranking test is renamed for its module. Rollback: reverting this commit restores find-candidates.ts, its ./find-candidates export and the package-boundaries entry; the eager closure budget then fails again until the module is re-homed. --- .../interaction/runtime/selector-read.ts | 3 +- .../internal/find-match-resolution.ts | 14 ++- packages/selectors/package.json | 4 - packages/selectors/src/find-candidates.ts | 116 ------------------ ...nteraction-targeting-find-ranking.test.ts} | 2 +- .../selectors/src/interaction-targeting.ts | 80 +++++++++++- packages/selectors/src/selector-pipeline.ts | 30 +++++ scripts/layering/package-boundaries.test.ts | 1 - 8 files changed, 123 insertions(+), 127 deletions(-) delete mode 100644 packages/selectors/src/find-candidates.ts rename packages/selectors/src/{find-candidates.test.ts => interaction-targeting-find-ranking.test.ts} (98%) 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 24edd74df1..78ab29f2f9 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/selector-read.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/selector-read.ts @@ -12,9 +12,9 @@ import { listSelectorPipelineMatches, resolveSelectorPipeline, type SelectorPipelineHooks, + findOneNodeCandidates, } from '@agent-device/selectors/selector-pipeline'; import { SELECTOR_PIPELINE_POLICIES } from '@agent-device/selectors/selector-pipeline-policy'; -import { findOneNodeCandidates } from '@agent-device/selectors/find-candidates'; 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'; @@ -279,6 +279,7 @@ async function findValueReadMatch( ): Promise<{ capture: CapturedSnapshot; match: SnapshotNode }> { const capture = await captureFindCandidates(runtime, options); const matched = findOneNodeCandidates({ + pipeline: SELECTOR_PIPELINE_POLICIES.findAct, nodes: capture.snapshot.nodes, locator, query: options.query, 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 fb48dd1067..08789c8375 100644 --- a/packages/daemon/src/execution/interaction/internal/find-match-resolution.ts +++ b/packages/daemon/src/execution/interaction/internal/find-match-resolution.ts @@ -4,7 +4,7 @@ import { type FindLocator, type SelectorResolutionPolicy, } from '@agent-device/selectors'; -import { findOneNodeCandidates } from '@agent-device/selectors/find-candidates'; +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 type { DaemonRequest } from '../../../core/daemon-request.ts'; @@ -35,8 +35,16 @@ export function resolveFindMatch(params: { // contract — multiple matches reject with candidates unless --first/--last // explicitly opts into positional narrowing. `find get text|attrs` // counts the same candidate set (#4685). - const policy = SELECTOR_PIPELINE_POLICIES.findAct.resolution; - let matches = findOneNodeCandidates({ nodes, locator, query, selectorExpression, platform }); + const pipeline = SELECTOR_PIPELINE_POLICIES.findAct; + const policy = pipeline.resolution; + let matches = findOneNodeCandidates({ + pipeline, + nodes, + locator, + query, + selectorExpression, + platform, + }); if (matches.length > 1) { // The row says candidates reject unless the caller narrowed explicitly; diff --git a/packages/selectors/package.json b/packages/selectors/package.json index 7b0ab00a51..4a3d25ceff 100644 --- a/packages/selectors/package.json +++ b/packages/selectors/package.json @@ -52,10 +52,6 @@ "types": "./src/interaction-positionals.ts", "default": "./src/interaction-positionals.ts" }, - "./find-candidates": { - "types": "./src/find-candidates.ts", - "default": "./src/find-candidates.ts" - }, "./interaction-targeting": { "types": "./src/interaction-targeting.ts", "default": "./src/interaction-targeting.ts" diff --git a/packages/selectors/src/find-candidates.ts b/packages/selectors/src/find-candidates.ts deleted file mode 100644 index bd34a56a37..0000000000 --- a/packages/selectors/src/find-candidates.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { centerOfRect, type SnapshotNode } from '@agent-device/kernel/snapshot'; -import { - findBestMatchesByLocator, - type FindLocator, - type SelectorMatchOptions, -} from '@agent-device/selectors'; -import { - createActionableTouchResolver, - isRootInteractionContainer, - resolveActionableTouchResolution, -} from './interaction-targeting.ts'; -import { listSelectorPipelineMatches } from './selector-pipeline.ts'; -import { SELECTOR_PIPELINE_POLICIES } from './selector-pipeline-policy.ts'; - -/** - * 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. - */ -export function findOneNodeCandidates(params: { - nodes: SnapshotNode[]; - locator: FindLocator; - query: string; - selectorExpression: string | null; - platform: SelectorMatchOptions['platform']; -}): SnapshotNode[] { - const { nodes, locator, query, selectorExpression, platform } = params; - const pipeline = SELECTOR_PIPELINE_POLICIES.findAct; - 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); -} - -/** - * 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/find-candidates.test.ts b/packages/selectors/src/interaction-targeting-find-ranking.test.ts similarity index 98% rename from packages/selectors/src/find-candidates.test.ts rename to packages/selectors/src/interaction-targeting-find-ranking.test.ts index 8338dde6aa..10da736e4e 100644 --- a/packages/selectors/src/find-candidates.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-candidates.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/selector-pipeline.ts b/packages/selectors/src/selector-pipeline.ts index edb800f11f..dd335b696b 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,29 @@ 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. The caller passes the `findAct` 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']; + 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/scripts/layering/package-boundaries.test.ts b/scripts/layering/package-boundaries.test.ts index d238d6a1e2..e1c99c20a7 100644 --- a/scripts/layering/package-boundaries.test.ts +++ b/scripts/layering/package-boundaries.test.ts @@ -778,7 +778,6 @@ test('the real tree parses, declares, and passes R11', () => { '@agent-device/selectors/absence-observation-resolution', '@agent-device/selectors/ast', '@agent-device/selectors/engine', - '@agent-device/selectors/find-candidates', '@agent-device/selectors/interaction-action', '@agent-device/selectors/interaction-error', '@agent-device/selectors/interaction-positionals', From 4efbb210c866e442cb7a0e6b7514fd67fe253add Mon Sep 17 00:00:00 2001 From: xiatiandeairen Date: Sun, 22 Nov 2026 16:20:19 +0400 Subject: [PATCH 4/4] fix(find): keep rectless and ref-less matches in find value reads findValueReadMatch passed the findAct row, which requires a rect and a ref, so on web `find "" get text` refused a node that `find list`, `wait text` and `snapshot` all show. Add a findRead row (reject-candidates, requireRect: false, occlusion ignore) and let findOneNodeCandidates take either row, so reads and taps still share root exclusion and on-screen ranking while addressability comes from the action's row. --- .../runtime/selector-read-find-list.test.ts | 22 +++++++++++++++++++ .../interaction/runtime/selector-read.ts | 2 +- .../src/internal/resolution-policy.ts | 13 +++++++---- .../selectors/src/selector-pipeline-policy.ts | 15 ++++++++++++- packages/selectors/src/selector-pipeline.ts | 8 ++++--- 5 files changed, 51 insertions(+), 9 deletions(-) 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 80c0e6b99c..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 @@ -148,3 +148,25 @@ test('runtime find get text binds the onscreen match over an offscreen duplicate }); 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 78ab29f2f9..e4d2b33b21 100644 --- a/packages/command-runtime/src/commands/interaction/runtime/selector-read.ts +++ b/packages/command-runtime/src/commands/interaction/runtime/selector-read.ts @@ -279,7 +279,7 @@ async function findValueReadMatch( ): Promise<{ capture: CapturedSnapshot; match: SnapshotNode }> { const capture = await captureFindCandidates(runtime, options); const matched = findOneNodeCandidates({ - pipeline: SELECTOR_PIPELINE_POLICIES.findAct, + pipeline: SELECTOR_PIPELINE_POLICIES.findRead, nodes: capture.snapshot.nodes, locator, query: options.query, diff --git a/packages/selectors/src/internal/resolution-policy.ts b/packages/selectors/src/internal/resolution-policy.ts index d985c37a24..3e31e6d427 100644 --- a/packages/selectors/src/internal/resolution-policy.ts +++ b/packages/selectors/src/internal/resolution-policy.ts @@ -79,14 +79,19 @@ export const SELECTOR_RESOLUTION_POLICIES = { ambiguity: 'first-match', requireRect: false, }, - /** - * Mutating `find` (#1625) and its value reads (`get text`/`get attrs`, #4685): - * candidates reject unless explicitly narrowed. - */ + /** Mutating `find` (#1625): candidates reject unless explicitly narrowed. */ findAct: { 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 ce74a06b21..a6dd5631e2 100644 --- a/packages/selectors/src/selector-pipeline-policy.ts +++ b/packages/selectors/src/selector-pipeline-policy.ts @@ -182,7 +182,7 @@ export const SELECTOR_PIPELINE_POLICIES = { occlusion: 'ignore', }, /** - * Mutating `find` (#1625) and its value reads (#4685, through `findOneNodeCandidates`). `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 dd335b696b..7998bb29a4 100644 --- a/packages/selectors/src/selector-pipeline.ts +++ b/packages/selectors/src/selector-pipeline.ts @@ -388,11 +388,13 @@ export function selectorPollBudget(policy: SelectorPipelinePolicy): WaitPollBudg * 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. The caller passes the `findAct` row, - * which the type pins, so this module stays clear of the policy table's eager import closure. + * 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']; + pipeline: (typeof SELECTOR_PIPELINE_POLICIES)['findAct' | 'findRead']; nodes: SnapshotNode[]; locator: FindLocator; query: string;