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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion build/maestro/tsdown.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export default defineConfig({
deps: {
neverBundle: ['agent-device/plugins'],
alwaysBundle: [/^@agent-device\//],
onlyBundle: ['yaml', 'undici', 'ipaddr.js', 'pngjs', 'jpeg-js'],
onlyBundle: ['yaml', 'undici', 'ipaddr.js', 'pngjs', 'jpeg-js', 're2js'],
},
inputOptions: {
onLog(level, log, handler) {
Expand Down
3 changes: 2 additions & 1 deletion packages/maestro/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@
"@agent-device/provision-kit": "workspace:*",
"@agent-device/selectors": "workspace:*",
"agent-device": "workspace:*",
"@agent-device/plugins": "workspace:*"
"@agent-device/plugins": "workspace:*",
"re2js": "2.10.0"
},
"scripts": {
"build": "tsdown --config ../../build/maestro/tsdown.config.ts",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import { expect, test } from 'vitest';
import { matchesMaestroTypedSelector } from '../runtime-target-policy.ts';
import { compileMaestroSelector, matchesMaestroTypedSelector } from '../runtime-target-policy.ts';
import type { MaestroFlatSelector } from '../runtime-target-policy.ts';
import type { MaestroSelector } from '../program-ir.ts';
import { makeSnapshot } from './runtime-target-fixtures.ts';

const matches = (
node: Parameters<typeof matchesMaestroTypedSelector>[0],
selector: MaestroFlatSelector,
) => matchesMaestroTypedSelector(node, compileMaestroSelector(selector));

test('typed Maestro text selectors match visible text and state without expression strings', () => {
const node = makeSnapshot([
{
Expand All @@ -14,10 +20,8 @@ test('typed Maestro text selectors match visible text and state without expressi
},
]).nodes[0]!;

expect(
matchesMaestroTypedSelector(node, { text: '^Subtotal.*', enabled: true, selected: true }),
).toBe(true);
expect(matchesMaestroTypedSelector(node, { text: 'Subtotal', selected: false })).toBe(false);
expect(matches(node, { text: '^Subtotal.*', enabled: true, selected: true })).toBe(true);
expect(matches(node, { text: 'Subtotal', selected: false })).toBe(false);
});

test('typed Maestro id and text selectors keep their primary field semantics', () => {
Expand All @@ -30,9 +34,9 @@ test('typed Maestro id and text selectors keep their primary field semantics', (
},
]).nodes[0]!;

expect(matchesMaestroTypedSelector(node, { id: 'checkout-submit' })).toBe(true);
expect(matchesMaestroTypedSelector(node, { text: 'Submit' })).toBe(false);
expect(matchesMaestroTypedSelector(node, { text: '^Submit.*' })).toBe(true);
expect(matches(node, { id: 'checkout-submit' })).toBe(true);
expect(matches(node, { text: 'Submit' })).toBe(false);
expect(matches(node, { text: '^Submit.*' })).toBe(true);
});

test('intersects every field in a compound Maestro selector', () => {
Expand All @@ -47,15 +51,13 @@ test('intersects every field in a compound Maestro selector', () => {
]).nodes[0]!;

expect(
matchesMaestroTypedSelector(node, {
matches(node, {
id: 'checkout-submit',
text: 'Submit order',
enabled: true,
}),
).toBe(true);
expect(matchesMaestroTypedSelector(node, { id: 'checkout-submit', text: 'Cancel order' })).toBe(
false,
);
expect(matches(node, { id: 'checkout-submit', text: 'Cancel order' })).toBe(false);
});

test('treats selector values as full Maestro regex without punctuation inference', () => {
Expand All @@ -67,9 +69,9 @@ test('treats selector values as full Maestro regex without punctuation inference
},
]).nodes[0]!;

expect(matchesMaestroTypedSelector(node, { text: 'item \\d{2} \\[ready' })).toBe(true);
expect(matchesMaestroTypedSelector(node, { text: 'Item 2' })).toBe(false);
expect(matchesMaestroTypedSelector(node, { text: 'Item 22 [ready' })).toBe(true);
expect(matches(node, { text: 'item \\d{2} \\[ready' })).toBe(true);
expect(matches(node, { text: 'Item 2' })).toBe(false);
expect(matches(node, { text: 'Item 22 [ready' })).toBe(true);
});

test('the node-only matcher rejects full selectors at the type boundary', () => {
Expand All @@ -78,7 +80,7 @@ test('the node-only matcher rejects full selectors at the type boundary', () =>

void (() => {
// @ts-expect-error Recursive selectors require snapshot-aware resolution.
matchesMaestroTypedSelector(node, recursiveSelector);
compileMaestroSelector(recursiveSelector);
});
expect(node.label).toBe('Save');
});
93 changes: 88 additions & 5 deletions packages/maestro/src/internal/__tests__/selector-regex.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,70 @@
import { expect, test } from 'vitest';
import { literalFromMaestroRegex, matchesMaestroRegex } from '../selector-regex.ts';
import { compileMaestroRegex, literalFromMaestroRegex } from '../selector-regex.ts';

test('matches Maestro regex as case-insensitive full patterns', () => {
expect(matchesMaestroRegex('Item 22\nready', String.raw`item \d{2}.+ready`)).toBe(true);
expect(matchesMaestroRegex('Item 22 ready later', 'Item 22 ready')).toBe(false);
expect(matchesMaestroRegex('Item [ready', 'item [ready')).toBe(true);
const matches = (value: string, pattern: string) => compileMaestroRegex(pattern)(value);

test.each([
[String.raw`item \d{2}.+ready`, 'Item 22\nready'],
[String.raw`Item \d+`, 'header\nItem 22\nfooter'],
['^item.$', 'ITEM\n'],
['item 2(2|3)', 'Item 22 ready later'],
[String.raw`caf\u00e9`, 'CAFÉ'],
])('maps %s to the JavaScript ^(?:pattern)$ ims result', (pattern, value) => {
expect(matches(value, pattern)).toBe(new RegExp(`^(?:${pattern})$`, 'ims').test(value));
});

test('compares invalid JavaScript patterns and patterns without regex syntax as literals', () => {
expect(matches('Item [ready', 'item [ready')).toBe(true);
const long = 'x'.repeat(1000);
expect(matches(long.toUpperCase(), long)).toBe(true);
expect(matches('y', long)).toBe(false);
});

test('matches a regex-free pattern against one line of multi-line text', () => {
expect(matches('Item 22\nready', 'item 22')).toBe(true);
expect(matches('header\r\nItem 22', 'ITEM 22')).toBe(true);
expect(matches('Item 223\nready', 'item 22')).toBe(false);
});

test.each([
['.*Welcome.*back.*', 'Oh, welcome Ann, glad to have you back!'],
['Welcome( back)?', 'Welcome back'],
['(Sign in|Log in)', 'log in'],
[String.raw`\d+ of \d+`, '3 of 10'],
['.*ready', `${'x'.repeat(10_000)} ready`],
])('matches %s', (pattern, value) => {
expect(matches(value, pattern)).toBe(true);
});

test.each(['(a+)+$', '(a|a)*b'])(
'matches %s over a non-matching input in linear time',
(pattern) => {
const started = performance.now();
expect(matches(`${'a'.repeat(30)}!`, pattern)).toBe(false);
expect(performance.now() - started).toBeLessThan(100);
},
);

test.each([String.raw`(\w+)\1`, '(?=a)a', '(?<=a)b', `${'a'.repeat(256)}.*`])(
'refuses %s with the typed reason',
(pattern) => {
expect(() => compileMaestroRegex(pattern)).toThrowError(
expect.objectContaining({
details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }),
}),
);
},
);

test('reports which limit a refused pattern exceeded', () => {
expect(() => compileMaestroRegex(`${'a'.repeat(300)}.*`)).toThrowError(
expect.objectContaining({
details: expect.objectContaining({ limit: 'pattern_length', patternLength: 302 }),
}),
);
expect(() => compileMaestroRegex('(?=a)a')).toThrowError(
expect.objectContaining({ details: expect.objectContaining({ limit: 'syntax' }) }),
);
});

test('extracts only patterns that are exact literals', () => {
Expand All @@ -13,3 +73,26 @@ test('extracts only patterns that are exact literals', () => {
expect(literalFromMaestroRegex(String.raw`item \d{2}`)).toBeUndefined();
expect(literalFromMaestroRegex('item [ready')).toBe('item [ready');
});

test('anchors on every JavaScript line terminator', () => {
const matches = compileMaestroRegex('^Save$');
for (const terminator of ['\r\n', '\r', '\u2028', '\u2029']) {
expect(matches(`Save${terminator}Now`)).toBe(true);
}
});

test('matches patterns that name a line terminator', () => {
expect(matches('Line 1\r\nLine 2', 'Line 1\r\nLine 2')).toBe(true);
expect(matches('Line 1\r\nLine 2', String.raw`Line 1\r\nLine 2`)).toBe(true);
expect(matches('Header\nLine 1\nLine 2\nFooter', 'Line 1\nLine 2')).toBe(true);
expect(matches('Header\nLine 1\nLine 2x', 'Line 1\nLine 2')).toBe(false);
expect(matches('a
b', String.raw`a
b`)).toBe(true);
expect(matches('a\rb', 'a(\r|x)b')).toBe(true);
});

test('matches whitespace classes against ASCII whitespace only, like Maestro', () => {
expect(matches('Hello World', String.raw`Hello\sWorld`)).toBe(true);
expect(matches('Hello\u00a0World', String.raw`Hello\sWorld`)).toBe(false);
expect(matches('10:30\u202fAM', String.raw`\d+:\d+\sAM`)).toBe(false);
expect(matches('a\u00a0b', String.raw`a\Sb`)).toBe(true);
});
29 changes: 19 additions & 10 deletions packages/maestro/src/internal/facade-execution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@ import {
resolveMaestroReplayStartIndex,
} from './replay-plan.ts';
import type { MaestroReplayPlan } from './replay-plan-types.ts';
import { matchesMaestroTypedSelector } from './runtime-target-policy.ts';
import { compileMaestroSelector, matchesMaestroTypedSelector } from './runtime-target-policy.ts';
import { rankMaestroCandidates } from './runtime-target-ranking.ts';
import { isUnsafeMaestroRegexError } from './selector-regex.ts';

const flowProgram = Symbol('maestroFlowProgram');
const failureCommand = Symbol('maestroFailureCommand');
Expand Down Expand Up @@ -190,10 +191,20 @@ export function collectMaestroFailureSuggestions(
const query = suggestionQuery(failure[failureCommand]);
const platform = failure[failurePlan].platform;
if (!query || (platform !== 'android' && platform !== 'ios')) return [];
return rankMaestroCandidates(snapshot, query.selector, platform).ranked.map((node) => ({
node,
basis: suggestionBasis(query.selector, node),
}));
try {
const textSelector =
query.selector.id === undefined && query.selector.text !== undefined
? compileMaestroSelector({ text: query.selector.text })
: undefined;
return rankMaestroCandidates(snapshot, query.selector, platform).ranked.map((node) => ({
node,
basis: suggestionBasis(query.selector, textSelector, node),
}));
} catch (error) {
// The step already failed on this selector. The report keeps that failure and lists no suggestions.
if (isUnsafeMaestroRegexError(error)) return [];
throw error;
}
}

function createObserver(
Expand Down Expand Up @@ -300,15 +311,13 @@ function suggestionQuery(command: MaestroEngineEvent['command']): SuggestionQuer

function suggestionBasis(
selector: SuggestionQuery['selector'],
textSelector: ReturnType<typeof compileMaestroSelector> | undefined,
node: SnapshotNode,
): 'id' | 'label' | 'other' {
if (selector.id !== undefined) return 'id';
if (
selector.text !== undefined &&
matchesMaestroTypedSelector(
{ ...node, label: undefined, value: undefined },
{ text: selector.text },
)
textSelector &&
matchesMaestroTypedSelector({ ...node, label: undefined, value: undefined }, textSelector)
) {
return 'id';
}
Expand Down
10 changes: 6 additions & 4 deletions packages/maestro/src/internal/runtime-selector-resolution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
selectMaestroPositionMatches,
type MaestroPositionRelation,
} from './runtime-target-position.ts';
import { matchesMaestroTypedSelector } from './runtime-target-policy.ts';
import { compileMaestroSelector, matchesMaestroTypedSelector } from './runtime-target-policy.ts';

export type MaestroSelectorResolution = {
/** Relation-composed matches in snapshot order, before this selector's own index. */
Expand Down Expand Up @@ -166,9 +166,11 @@ function resolveWithoutOwnIndex(
containsDescendants,
...leaf
} = selector;
let matches = hasMaestroLeafSelectorFields(leaf)
? snapshot.nodes.filter((node) => matchesMaestroTypedSelector(node, leaf))
: [...snapshot.nodes];
let matches = [...snapshot.nodes];
if (hasMaestroLeafSelectorFields(leaf)) {
const matcher = compileMaestroSelector(leaf);
matches = matches.filter((node) => matchesMaestroTypedSelector(node, matcher));
}

if (childOf) {
const parentIndexes = new Set(resolve(childOf).indexed.map((node) => node.index));
Expand Down
34 changes: 22 additions & 12 deletions packages/maestro/src/internal/runtime-target-policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,26 @@ export type MaestroFlatSelector = MaestroLeafSelector & {
};
import type { SnapshotNode } from '@agent-device/kernel/snapshot';
import type { SnapshotVisibility } from '@agent-device/contracts/snapshot';
import { matchesMaestroRegex } from './selector-regex.ts';
import { compileMaestroRegex, type MaestroTextMatcher } from './selector-regex.ts';
import { extractNodeText, normalizeText } from './shared.ts';
import { isMaestroNodeVisible } from './snapshot-policy.ts';

export type MaestroRuntimePlatform = 'ios' | 'android';

export type MaestroSelectorMatcher = Omit<MaestroFlatSelector, 'id' | 'text'> & {
id: MaestroTextMatcher | undefined;
text: MaestroTextMatcher | undefined;
};

/** Compiles selector values once before a snapshot scan. */
export function compileMaestroSelector(selector: MaestroFlatSelector): MaestroSelectorMatcher {
return {
...selector,
id: selector.id === undefined ? undefined : compileMaestroSelectorValue(selector.id),
text: selector.text === undefined ? undefined : compileMaestroSelectorValue(selector.text),
};
}

/**
* Match the source-preserving selector IR directly. In particular, this does
* not lower the selector to the legacy `key=value` expression grammar.
Expand All @@ -23,12 +37,10 @@ export type MaestroRuntimePlatform = 'ios' | 'android';
*/
export function matchesMaestroTypedSelector(
node: SnapshotNode,
selector: MaestroFlatSelector,
selector: MaestroSelectorMatcher,
): boolean {
const textTerms = [
selector.id === undefined
? undefined
: matchesMaestroSelectorValue(node.identifier, selector.id),
selector.id?.(node.identifier ?? ''),
selector.text === undefined ? undefined : matchesMaestroVisibleText(node, selector.text),
].filter((matched): matched is boolean => matched !== undefined);
if (textTerms.length === 0 && selector.enabled === undefined && selector.selected === undefined) {
Expand All @@ -55,16 +67,14 @@ export function filterVisibleMaestroMatches(params: {
);
}

function matchesMaestroSelectorValue(value: string | undefined, query: string): boolean {
const text = value ?? '';
const normalizedText = normalizeText(text);
function compileMaestroSelectorValue(query: string): MaestroTextMatcher {
const normalizedQuery = normalizeText(query);
if (normalizedText === normalizedQuery) return true;
return matchesMaestroRegex(text, query);
const matchesRegex = compileMaestroRegex(query);
return (value) => normalizeText(value) === normalizedQuery || matchesRegex(value);
}

function matchesMaestroVisibleText(node: SnapshotNode, query: string): boolean {
function matchesMaestroVisibleText(node: SnapshotNode, matches: MaestroTextMatcher): boolean {
return [node.label, extractNodeText(node), node.identifier]
.filter((value): value is string => Boolean(value))
.some((value) => matchesMaestroSelectorValue(value, query));
.some(matches);
}
Loading
Loading