Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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');
});
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import {
FIND_VALUE_REQUIRED_MESSAGE,
findAmbiguousMatchMessage,
findBestMatchesByLocator,
narrowFindMatches,
buildSelectorChainForNode,
parseFindSelectorExpression,
type FindAction,
Expand All @@ -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 {
Expand Down Expand Up @@ -57,6 +61,9 @@ export type FindReadCommandOptions = CommandContext & {
query: string;
action: Extract<FindAction['kind'], 'exists' | 'wait' | 'get_text' | 'get_attrs' | 'list'>;
timeoutMs?: number;
/** `--first`/`--last`: the explicit narrowing a value read (`get text`/`get attrs`) accepts. */
findFirst?: boolean;
findLast?: boolean;
} & SelectorSnapshotOptions;

export type FindReadCommandResult = FindReadResult;
Expand Down Expand Up @@ -117,12 +124,13 @@ export const findCommand: RuntimeCommand<FindReadCommandOptions, FindReadCommand
return await listFindMatches(runtime, options, locator);
}

const { capture, match } = await findFirstLocatorMatch(runtime, options, locator);
if (!match) {
throw new AppError('COMMAND_FAILED', 'find did not match any element');
if (options.action === 'exists') {
const { match } = await findFirstLocatorMatch(runtime, options, locator);
if (!match) throw new AppError('COMMAND_FAILED', 'find did not match any element');
return { kind: 'found', found: true };
}

if (options.action === 'exists') return { kind: 'found', found: true };
const { capture, match } = await findValueReadMatch(runtime, options, locator);
if (options.action === 'get_attrs') return { kind: 'attrs', ...refAddress(match), node: match };
const text = await readText(runtime, capture, match);
return { kind: 'text', ...refAddress(match), text, node: match };
Expand Down Expand Up @@ -242,16 +250,7 @@ async function listFindMatches(
locator: FindLocator,
): Promise<Extract<FindReadCommandResult, { kind: 'list' }>> {
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,
Expand All @@ -266,6 +265,58 @@ async function listFindMatches(
};
}

/**
* `find <q> 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<CapturedSnapshot> {
// 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
Expand Down
3 changes: 3 additions & 0 deletions packages/contracts/src/daemon-command-surface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 &
Expand Down

This file was deleted.

Loading
Loading