diff --git a/packages/maestro/package.json b/packages/maestro/package.json index e21431628e5..5737d6edcf9 100644 --- a/packages/maestro/package.json +++ b/packages/maestro/package.json @@ -13,7 +13,8 @@ "@agent-device/host-kit": "workspace:*", "@agent-device/kernel": "workspace:*", "@agent-device/provision-kit": "workspace:*", - "@agent-device/selectors": "workspace:*" + "@agent-device/selectors": "workspace:*", + "@eslint-community/regexpp": "4.12.2" }, "exports": { ".": { diff --git a/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-observation-scroll.test.ts b/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-observation-scroll.test.ts index 4d9eb460c61..6bfca5a102a 100644 --- a/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-observation-scroll.test.ts +++ b/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-observation-scroll.test.ts @@ -113,71 +113,95 @@ test('scrolls until the target is fully visible in the screen viewport', async ( expect(result.observation?.identity).toMatch(/^maestro-observation-/); }); -test('uses Maestro swipeFromCenter semantics inside the visible vertical container', async () => { - const requests: MaestroDaemonOperationRequest[] = []; - let snapshots = 0; - const port = createDaemonMaestroRuntimePort({ - ...makeRuntimeEnvelope({ flags: { platform: 'ios', replayBackend: 'maestro' } }), - invoke: async (request) => { - requests.push(request); - if (request.command !== 'snapshot') return { ok: true, data: {} }; - snapshots += 1; - return { - ok: true, - data: { - createdAt: snapshots, - nodes: [ - { index: 0, type: 'Application', rect: { x: 0, y: 0, width: 402, height: 874 } }, - { - index: 1, - parentIndex: 0, - type: 'ScrollView', - rect: { x: 0, y: 100, width: 402, height: 650 }, - }, - ...(snapshots < 3 - ? [] - : [ - { - index: 2, - parentIndex: 1, - type: 'Button', - identifier: 'home-open-form', - rect: { x: 20, y: 600, width: 180, height: 44 }, - }, - ]), - ], - }, - }; - }, - dependencies: makeDependencies(), - platform: 'ios', - }); +test.each([ + { name: 'absent target', undecidable: false, findsTarget: true }, + { name: 'undecidable target', undecidable: true, findsTarget: true }, + { name: 'undecidable target through the deadline', undecidable: true, findsTarget: false }, +])( + 'swipes inside the visible vertical container with an $name', + async ({ undecidable, findsTarget }) => { + const requests: MaestroDaemonOperationRequest[] = []; + let scrolled = false; + const port = createDaemonMaestroRuntimePort({ + ...makeRuntimeEnvelope({ flags: { platform: 'ios', replayBackend: 'maestro' } }), + invoke: async (request) => { + requests.push(request); + if (request.command === 'gesture') scrolled = true; + if (request.command !== 'snapshot') return { ok: true, data: {} }; + return { + ok: true, + data: { + createdAt: 0, + nodes: [ + { index: 0, type: 'Application', rect: { x: 0, y: 0, width: 402, height: 874 } }, + { + index: 1, + parentIndex: 0, + type: 'ScrollView', + rect: { x: 0, y: 100, width: 402, height: 650 }, + }, + ...(scrolled && findsTarget + ? [ + { + index: 2, + parentIndex: 1, + type: 'Button', + label: 'Open form', + rect: { x: 20, y: 600, width: 180, height: 44 }, + }, + ] + : undecidable + ? [ + { + index: 2, + parentIndex: 1, + type: 'Text', + label: 'Terms and conditions\n'.repeat(800), + }, + ] + : []), + ], + }, + }; + }, + dependencies: makeDependencies(), + platform: 'ios', + }); - await port.execute({ - command: { - kind: 'scrollUntilVisible', - source: { line: 2 }, - element: { id: 'home-open-form' }, - direction: 'down', - timeout: 2_000, - }, - generation: 0, - env: {}, - invalidateObservation() {}, - }); + const result = port.execute({ + command: { + kind: 'scrollUntilVisible', + source: { line: 2 }, + element: { text: '.*Open form' }, + direction: 'down', + timeout: 2_000, + }, + generation: 0, + env: {}, + invalidateObservation() {}, + }); - const gesture = requests.find(({ command }) => command === 'gesture'); - expect(gesture).toMatchObject({ - input: { - kind: 'pan', - origin: { x: 201, y: 425 }, - delta: { x: 0, y: -260 }, - durationMs: 601, - }, - dispatch: { gestureViewport: { x: 0, y: 100, width: 402, height: 650 } }, - }); - expect(requests.some(({ command }) => command === 'scroll')).toBe(false); -}); + if (findsTarget) { + await expect(result).resolves.toMatchObject({ observation: { matched: true } }); + } else { + await expect(result).rejects.toMatchObject({ + details: { reason: 'maestro_selector_regex_indeterminate' }, + }); + } + + const gesture = requests.find(({ command }) => command === 'gesture'); + expect(gesture).toMatchObject({ + input: { + kind: 'pan', + origin: { x: 201, y: 425 }, + delta: { x: 0, y: -260 }, + durationMs: 601, + }, + dispatch: { gestureViewport: { x: 0, y: 100, width: 402, height: 650 } }, + }); + expect(requests.some(({ command }) => command === 'scroll')).toBe(false); + }, +); test('ignores a larger scroll container that does not intersect the application viewport', async () => { const requests: MaestroDaemonOperationRequest[] = []; diff --git a/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-observation.test.ts b/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-observation.test.ts index 0874714e215..62f32307f23 100644 --- a/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-observation.test.ts +++ b/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-observation.test.ts @@ -12,6 +12,7 @@ import { maestroSnapshotSignature, observeTypedMaestroCondition, resolveTypedMaestroTarget, + scrollUntilTypedMaestroTarget, waitForTypedSnapshotStability, } from '../daemon-runtime-port-observation.ts'; import { @@ -223,6 +224,124 @@ test('matches iOS Maestro ids on semantic nodes suppressed from interactive pres ).resolves.toMatchObject({ matched: true, visible: true, candidateCount: 1, ref: 'e2' }); }); +test('retries an indeterminate regex observation until a later snapshot has a confirmed match', async () => { + const clock = { value: 0 }; + let captures = 0; + const header = { index: 1, type: 'Text', label: 'Header\n'.repeat(10_000) }; + const root = { index: 0, type: 'Application', rect: { x: 0, y: 0, width: 402, height: 874 } }; + const ready = { + index: 2, + type: 'Text', + label: 'Ready', + rect: { x: 20, y: 40, width: 120, height: 44 }, + }; + + const match = await observeTypedMaestroCondition({ + condition: { kind: 'visible', selector: { text: '.*Ready' } }, + timeoutMs: MAESTRO_OBSERVATION_POLL_MS, + context: { generation: 0, env: {} }, + snapshot: async () => makeSnapshot(captures++ === 0 ? [root, header] : [root, header, ready]), + dependencies: makeDependencies(clock), + platform: 'android', + }); + + expect(match).toMatchObject({ matched: true, visible: true, ref: 'e3' }); + expect(captures).toBe(2); +}); + +test('polls an indeterminate relational selector until its parent appears', async () => { + const clock = { value: 0 }; + let captures = 0; + const root = { index: 0, type: 'Application', rect: { x: 0, y: 0, width: 402, height: 874 } }; + const header = { index: 1, type: 'Text', label: 'Header\n'.repeat(10_000) }; + const parent = { + index: 2, + type: 'Text', + label: 'Ready', + rect: { x: 20, y: 40, width: 120, height: 44 }, + }; + const row = { + index: 3, + parentIndex: 2, + type: 'Text', + identifier: 'row', + rect: { x: 20, y: 90, width: 120, height: 44 }, + }; + + const match = await observeTypedMaestroCondition({ + condition: { kind: 'visible', selector: { id: 'row', childOf: { text: '.*Ready' } } }, + timeoutMs: MAESTRO_OBSERVATION_POLL_MS, + context: { generation: 0, env: {} }, + snapshot: async () => makeSnapshot(captures++ === 0 ? [root, header] : [root, parent, row]), + dependencies: makeDependencies(clock), + platform: 'android', + }); + + expect(match).toMatchObject({ matched: true, visible: true, ref: 'e4' }); + expect(captures).toBe(2); +}); + +test.each([ + { + name: 'oversized multiline label', + selector: { text: '.*Ready' }, + node: { index: 0, type: 'Text', label: 'Header\n'.repeat(10_000) }, + }, + { + name: 'clipped field in a complete snapshot', + selector: { text: 'Order is ready' }, + node: { index: 0, type: 'EditText', label: 'Order is', value: 'Order is', textClipped: true }, + }, +])('does not report notVisible with a $name', async ({ selector, node }) => { + await expect( + observeTypedMaestroCondition({ + condition: { kind: 'notVisible', selector }, + timeoutMs: 0, + context: { generation: 0, env: {} }, + snapshot: async () => ({ ...makeSnapshot([node]), truncated: false }), + dependencies: makeDependencies(), + platform: 'android', + }), + ).rejects.toMatchObject({ + details: { reason: 'maestro_selector_regex_indeterminate' }, + }); +}); + +test('scrolls past an indeterminate snapshot to a confirmed target', async () => { + const clock = { value: 0 }; + let captures = 0; + let scrolls = 0; + const root = { index: 0, type: 'Application', rect: { x: 0, y: 0, width: 402, height: 874 } }; + const header = { index: 1, type: 'Text', label: 'Header\n'.repeat(10_000) }; + const ready = { + index: 2, + type: 'Text', + label: 'Ready', + rect: { x: 20, y: 40, width: 120, height: 44 }, + }; + + const match = await scrollUntilTypedMaestroTarget({ + selector: { text: '.*Ready' }, + direction: 'down', + timeoutMs: MAESTRO_OBSERVATION_POLL_MS, + context: { generation: 0, env: {} }, + snapshot: async () => { + captures += 1; + return makeSnapshot([root, header]); + }, + scroll: async () => { + scrolls += 1; + return makeSnapshot([root, header, ready]); + }, + dependencies: makeDependencies(clock), + platform: 'android', + }); + + expect(match).toMatchObject({ matched: true, visible: true, ref: 'e3' }); + expect(captures).toBe(1); + expect(scrolls).toBe(1); +}); + test('reports iOS Maestro evidence refs in semantic snapshot space after earlier suppression', async () => { const snapshot = makeSnapshot([ { index: 0, type: 'Application', rect: { x: 0, y: 0, width: 402, height: 874 } }, diff --git a/packages/maestro/src/daemon-port/daemon-runtime-port-observation.ts b/packages/maestro/src/daemon-port/daemon-runtime-port-observation.ts index df6e7071427..812a1b43464 100644 --- a/packages/maestro/src/daemon-port/daemon-runtime-port-observation.ts +++ b/packages/maestro/src/daemon-port/daemon-runtime-port-observation.ts @@ -118,6 +118,7 @@ function resolveTargetFromSnapshot(params: { params.platform, { interactiveBounds: params.mode === 'tap', + confirmedUnindexedExistence: params.mode === 'observe', presentation: presentation ? { snapshot: interactiveSnapshot, @@ -137,6 +138,23 @@ function resolveTargetFromSnapshot(params: { ); } +function resolveObservationTarget(params: Parameters[0]): { + match?: MaestroTargetMatch; + indeterminate?: AppError; +} { + try { + return { match: resolveTargetFromSnapshot(params) }; + } catch (error) { + if ( + error instanceof AppError && + error.details?.reason === 'maestro_selector_regex_indeterminate' + ) { + return { indeterminate: error }; + } + throw error; + } +} + export async function observeTypedMaestroCondition(params: { readonly condition: MaestroObservationCondition; readonly timeoutMs: number; @@ -147,20 +165,22 @@ export async function observeTypedMaestroCondition(params: { }): Promise { validateTimeout(params.timeoutMs, 'observation'); let lastMatch: MaestroTargetMatch | undefined; + let lastIndeterminate: AppError | undefined; const conditionDeadline = params.dependencies.now() + params.timeoutMs; while (true) { throwIfAborted(params.context.signal); const snapshot = await captureRetriableMaestroSnapshot(params, conditionDeadline); - const match = resolveTargetFromSnapshot({ + const resolution = resolveObservationTarget({ query: { selector: params.condition.selector }, context: params.context, snapshot, platform: params.platform, mode: 'observe', }); - lastMatch = match; - if (maestroObservationMatches(params.condition, match)) return match; + lastMatch = resolution.match; + lastIndeterminate = resolution.indeterminate; + if (lastMatch && maestroObservationMatches(params.condition, lastMatch)) return lastMatch; if (params.dependencies.now() >= conditionDeadline) break; await sleepWithinDeadline( @@ -172,6 +192,7 @@ export async function observeTypedMaestroCondition(params: { } throwIfAborted(params.context.signal); + if (lastIndeterminate) throw lastIndeterminate; return requireObservationResult(lastMatch); } @@ -188,33 +209,34 @@ export async function scrollUntilTypedMaestroTarget(params: { validateTimeout(params.timeoutMs, 'scrollUntilVisible'); const deadline = params.dependencies.now() + params.timeoutMs; let lastMatch: MaestroTargetMatch | undefined; + let lastIndeterminate: AppError | undefined; let settledSnapshot: SnapshotState | undefined; while (true) { throwIfAborted(params.context.signal); const snapshot = settledSnapshot ?? (await captureRetriableMaestroSnapshot(params, deadline)); settledSnapshot = undefined; - lastMatch = resolveTargetFromSnapshot({ + const resolution = resolveObservationTarget({ query: { selector: params.selector }, context: params.context, snapshot, platform: params.platform, mode: 'observe', }); + lastMatch = resolution.match; + lastIndeterminate = resolution.indeterminate; if ( - lastMatch.visiblePercentage === MAESTRO_RUNTIME_ADAPTER_POLICY.scrollUntilVisiblePercentage + lastMatch?.visiblePercentage === MAESTRO_RUNTIME_ADAPTER_POLICY.scrollUntilVisiblePercentage ) { return lastMatch; } - if (params.dependencies.now() >= deadline) break; - const remaining = deadline - params.dependencies.now(); - if (remaining > 0) { - settledSnapshot = await params.scroll(remaining, snapshot); - } + if (remaining <= 0) break; + settledSnapshot = await params.scroll(remaining, snapshot); } throwIfAborted(params.context.signal); + if (lastIndeterminate) throw lastIndeterminate; return requireObservationResult(lastMatch); } diff --git a/packages/maestro/src/internal/__tests__/facade-execution-failure-suggestions.test.ts b/packages/maestro/src/internal/__tests__/facade-execution-failure-suggestions.test.ts index 852ec9a81f1..f356b97a8bd 100644 --- a/packages/maestro/src/internal/__tests__/facade-execution-failure-suggestions.test.ts +++ b/packages/maestro/src/internal/__tests__/facade-execution-failure-suggestions.test.ts @@ -68,6 +68,15 @@ describe('Maestro failure suggestion queries', () => { expect(suggestions.map(({ node, basis }) => [node.ref, basis])).toEqual([['e1', 'id']]); }); + test('an unsafe failed selector yields no suggestions', async () => { + const suggestions = await suggestionsFor( + ['appId: com.example.app', '---', '- tapOn:', ' id: (a+)+$', ''].join('\n'), + 'android', + [{ ...saveButton, identifier: 'a'.repeat(4096) }], + ); + expect(suggestions).toEqual([]); + }); + test('a coordinate tapOn has no selector to suggest from', async () => { const suggestions = await suggestionsFor( ['appId: com.example.app', '---', '- tapOn:', ' point: 50%,50%', ''].join('\n'), diff --git a/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts b/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts index acec5e12a9e..e51a1837636 100644 --- a/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts +++ b/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts @@ -3,6 +3,8 @@ import type { SnapshotNode } from '@agent-device/kernel/snapshot'; import type { MaestroSelector } from '../program-ir.ts'; import { createMaestroSnapshotResolver } from '../runtime-selector-resolution.ts'; import type { MaestroPositionRelation } from '../runtime-target-position.ts'; +import { matchMaestroCandidatesWithResolver } from '../runtime-target-ranking.ts'; +import { resolveMaestroTargetFromSnapshot } from '../runtime-targets.ts'; import { makeSnapshot } from './runtime-target-fixtures.ts'; test('computes recursive selector sets once per snapshot instead of once per candidate', () => { @@ -55,6 +57,299 @@ test('rejects cyclic selector graphs explicitly', () => { expect(() => resolver.resolve(selector)).toThrow(/cannot contain cycles/); }); +test('matches a complete interior multiline span before ordered target selection', () => { + const snapshot = makeSnapshot([ + { index: 0, label: 'prefix\nstart\nmiddle\nend\nsuffix' }, + { index: 1, label: 'start\nend' }, + ]); + const resolver = createMaestroSnapshotResolver(snapshot); + + expect( + resolver.resolve({ text: 'start.*end', index: 0 }).indexed.map((node) => node.index), + ).toEqual([0]); +}); + +test('a nonmatching multiline node does not prevent a later confirmed selector match', () => { + const resolver = createMaestroSnapshotResolver( + makeSnapshot([ + { index: 0, label: 'Welcome back\nPlease log in' }, + { index: 1, label: 'Sign in' }, + ]), + ); + expect(resolver.resolve({ text: '.*Sign in.*' }).matches.map((node) => node.index)).toEqual([1]); +}); + +test('action resolution ignores an unrelated multiline value within the regex length limit', () => { + const terms = 'Please read the terms and conditions before continuing to checkout.\n'; + const resolver = createMaestroSnapshotResolver( + makeSnapshot([ + { index: 0, label: terms.repeat(45) }, + { index: 1, label: 'Sign in' }, + ]), + ); + + const match = resolver.resolve({ text: 'Sign (in|up).*' }); + expect(match.matches.map((node) => node.index)).toEqual([1]); +}); + +test('action resolution skips line starts that share only the first literal character', () => { + const snapshot = makeSnapshot([ + { index: 0, label: 'Shipping info\n'.repeat(800) }, + { index: 1, label: 'Sign in', rect: { x: 0, y: 0, width: 40, height: 20 } }, + ]); + + expect( + resolveMaestroTargetFromSnapshot(snapshot, { selector: { text: 'Sign (in|up).*' } }, 'android'), + ).toMatchObject({ ok: true, node: { index: 1 } }); +}); + +test('an exact long selector checks every candidate before refusing regex execution', () => { + const pattern = `Total: 12.5 ${'x'.repeat(300)}`; + const resolver = createMaestroSnapshotResolver( + makeSnapshot([ + { index: 0, label: `${pattern} extra` }, + { index: 1, label: ` ${pattern} ` }, + ]), + ); + expect(resolver.resolve({ text: pattern }).matches.map((node) => node.index)).toEqual([1]); + expect(() => resolver.resolve({ text: `${pattern} missing` })).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); +}); + +test('a long pattern requires one candidate to satisfy every selector field', () => { + const pattern = `Total: 12.5 ${'x'.repeat(300)}`; + const resolver = createMaestroSnapshotResolver( + makeSnapshot([ + { index: 0, label: pattern, enabled: false }, + { index: 1, label: `${pattern} extra`, enabled: true }, + ]), + ); + expect(() => resolver.resolve({ text: pattern, enabled: true })).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); +}); + +test('a long pattern requires an exact match within the selected parent', () => { + const pattern = `Total: 12.5 ${'x'.repeat(300)}`; + const resolver = createMaestroSnapshotResolver( + makeSnapshot([ + { index: 0, identifier: 'summary' }, + { index: 1, label: pattern, parentIndex: 0 }, + { index: 2, identifier: 'details' }, + { index: 3, label: `${pattern} extra`, parentIndex: 2 }, + { index: 4, identifier: 'empty' }, + ]), + ); + + expect( + resolver + .resolve({ text: pattern, childOf: { id: 'summary' } }) + .matches.map((node) => node.index), + ).toEqual([1]); + expect(resolver.resolve({ text: pattern, childOf: { id: 'empty' } }).matches).toEqual([]); + expect(() => resolver.resolve({ text: pattern, childOf: { id: 'details' } })).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); +}); + +test('an empty relation scope skips later relations with uncertain matches', () => { + const resolver = createMaestroSnapshotResolver( + makeSnapshot([ + { index: 0, identifier: 'empty' }, + { index: 1, identifier: 'orders' }, + { index: 2, label: 'Order pending', textClipped: true, parentIndex: 1 }, + ]), + ); + const uncertain = { text: 'Order.*ready' }; + + expect(resolver.resolve({ childOf: { id: 'empty' }, containsChild: uncertain }).matches).toEqual( + [], + ); + expect(resolver.resolve({ containsDescendants: [{ id: 'missing' }, uncertain] }).matches).toEqual( + [], + ); + expect(resolver.resolve({ containsDescendants: [uncertain, { id: 'missing' }] }).matches).toEqual( + [], + ); + expect(() => resolver.resolve({ containsChild: uncertain })).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); +}); + +test('ranking reuses the parent result after a definite relation miss', () => { + const childOf = { text: 'Summary' }; + const computed: MaestroSelector[] = []; + const resolver = createMaestroSnapshotResolver( + makeSnapshot([ + { index: 0, label: 'Summ', textClipped: true }, + { index: 1, identifier: 'row', parentIndex: 0 }, + ]), + { onSelectorComputed: (selector) => computed.push(selector) }, + ); + + expect( + matchMaestroCandidatesWithResolver({ childOf, containsChild: { id: 'missing' } }, resolver) + .matches, + ).toEqual([]); + expect(computed.filter((selector) => selector === childOf)).toHaveLength(1); +}); + +test('a definite leaf ID miss discards uncertainty from an otherwise viable relation', () => { + const snapshot = makeSnapshot([ + { index: 0, label: 'Summ', textClipped: true }, + { index: 1, identifier: 'row', parentIndex: 0 }, + ]); + const childOf = { text: 'Summary' }; + + expect( + resolveMaestroTargetFromSnapshot(snapshot, { selector: { id: 'missing', childOf } }, 'android'), + ).toMatchObject({ + ok: false, + failureReason: 'selector-did-not-match', + evidence: { matched: false }, + }); + expect(() => + resolveMaestroTargetFromSnapshot(snapshot, { selector: { id: 'row', childOf } }, 'android'), + ).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); +}); + +test.each(['containsChild', 'containsDescendants'] as const)( + '%s only retains uncertainty in the subtree with the clipped source', + (relation) => { + const resolver = createMaestroSnapshotResolver( + makeSnapshot([ + { index: 0, identifier: 'summary' }, + { index: 1, label: 'Ready', parentIndex: 0 }, + { index: 2, identifier: 'archive' }, + { index: 3, label: 'Rea', textClipped: true, parentIndex: 2 }, + ]), + ); + const nested = { text: 'Ready' }; + const scope = + relation === 'containsChild' ? { containsChild: nested } : { containsDescendants: [nested] }; + + expect(resolver.resolve({ id: 'summary', ...scope }).matches.map((node) => node.index)).toEqual( + [0], + ); + expect(() => resolver.resolve({ id: 'archive', ...scope })).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); + }, +); + +test('nested indexed relations retain only possible selections in their scope', () => { + const rect = (y: number) => ({ x: 0, y, width: 40, height: 20 }); + const resolver = createMaestroSnapshotResolver( + makeSnapshot([ + { index: 0, label: 'Summary', rect: rect(0) }, + { index: 1, identifier: 'confirmed', parentIndex: 0, rect: rect(20) }, + { index: 2, label: 'Summ', textClipped: true, rect: rect(100) }, + { index: 3, identifier: 'possible', parentIndex: 2, rect: rect(120) }, + ]), + ); + + expect( + resolver.resolve({ childOf: { text: 'Summary', index: 0 } }).matches.map((node) => node.index), + ).toEqual([1]); + expect( + resolver.resolve({ id: 'confirmed', childOf: { text: 'Summary', index: 1 } }).matches, + ).toEqual([]); + expect(() => + resolver.resolve({ id: 'possible', childOf: { text: 'Summary', index: 1 } }), + ).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); +}); + +test('positional uncertainty only reaches candidates on the applicable side', () => { + const rect = (y: number) => ({ x: 0, y, width: 40, height: 20 }); + const resolver = createMaestroSnapshotResolver( + makeSnapshot([ + { index: 0, label: 'Summ', textClipped: true, rect: rect(100) }, + { index: 1, identifier: 'above', rect: rect(20) }, + { index: 2, identifier: 'below', rect: rect(150) }, + ]), + ); + const below = { text: 'Summary' }; + + expect(resolver.resolve({ id: 'above', below }).matches).toEqual([]); + expect(() => resolver.resolve({ id: 'below', below })).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); +}); + +test('clipped field text leaves matching uncertain while complete fields still decide', () => { + const resolver = createMaestroSnapshotResolver({ + ...makeSnapshot([ + { + index: 0, + label: 'Order is', + value: 'Order is', + identifier: 'order-status', + contentDescription: 'Order status', + textClipped: true, + enabled: false, + }, + ]), + truncated: false, + }); + + for (const text of ['Order is ready', 'Order is']) { + expect(() => resolver.resolve({ text })).toThrow( + expect.objectContaining({ + details: { reason: 'maestro_selector_regex_indeterminate', retriable: false }, + }), + ); + } + expect(resolver.resolve({ text: 'Order status' }).matches.map((node) => node.index)).toEqual([0]); + expect(resolver.resolve({ text: 'order-status' }).matches.map((node) => node.index)).toEqual([0]); + expect(resolver.resolve({ id: 'order-status' }).matches.map((node) => node.index)).toEqual([0]); + expect(resolver.resolve({ text: 'Order is ready', enabled: true }).matches).toEqual([]); +}); + +test('a confirmed unindexed match wins over uncertainty but an index still refuses', () => { + const snapshot = makeSnapshot([ + { index: 0, label: 'Header\n'.repeat(10_000) }, + { index: 1, label: 'Ready' }, + { index: 2, label: 'Header\n'.repeat(10_000), identifier: 'Ready' }, + ]); + const resolver = createMaestroSnapshotResolver( + snapshot, + {}, + { confirmedUnindexedExistence: true }, + ); + expect(resolver.resolve({ text: '.*Ready' }).matches.map((node) => node.index)).toEqual([1, 2]); + expect(() => resolver.resolve({ text: '.*Ready', index: 0 })).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); + expect(() => createMaestroSnapshotResolver(snapshot).resolve({ text: '.*Ready' })).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); +}); + test('resolves containment through array-offset parent links with non-contiguous indexes', () => { const snapshot = makeSnapshot([ { index: 10, identifier: 'container' }, diff --git a/packages/maestro/src/internal/__tests__/runtime-target-policy.test.ts b/packages/maestro/src/internal/__tests__/runtime-target-policy.test.ts index e2a5972c4d3..664e4071c4d 100644 --- a/packages/maestro/src/internal/__tests__/runtime-target-policy.test.ts +++ b/packages/maestro/src/internal/__tests__/runtime-target-policy.test.ts @@ -58,18 +58,18 @@ test('intersects every field in a compound Maestro selector', () => { ); }); -test('treats selector values as full Maestro regex without punctuation inference', () => { +test('treats admitted selector values as full Maestro regex without punctuation inference', () => { const node = makeSnapshot([ { index: 1, type: 'TextView', - label: 'Item 22 [ready', + label: 'Item 22 ready', }, ]).nodes[0]!; - expect(matchesMaestroTypedSelector(node, { text: 'item \\d{2} \\[ready' })).toBe(true); + expect(matchesMaestroTypedSelector(node, { text: 'item \\d\\d ready' })).toBe(true); expect(matchesMaestroTypedSelector(node, { text: 'Item 2' })).toBe(false); - expect(matchesMaestroTypedSelector(node, { text: 'Item 22 [ready' })).toBe(true); + expect(matchesMaestroTypedSelector(node, { text: 'Item 22 ready' })).toBe(true); }); test('the node-only matcher rejects full selectors at the type boundary', () => { @@ -82,3 +82,12 @@ test('the node-only matcher rejects full selectors at the type boundary', () => }); expect(node.label).toBe('Save'); }); + +test('typed selectors validate even when node text equals the unsafe pattern', () => { + const node = makeSnapshot([{ index: 1, label: 'a*a*' }]).nodes[0]!; + expect(() => matchesMaestroTypedSelector(node, { text: 'a*a*' })).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); +}); diff --git a/packages/maestro/src/internal/__tests__/runtime-targets-typed.test.ts b/packages/maestro/src/internal/__tests__/runtime-targets-typed.test.ts index 457bc2afb35..460b6f53490 100644 --- a/packages/maestro/src/internal/__tests__/runtime-targets-typed.test.ts +++ b/packages/maestro/src/internal/__tests__/runtime-targets-typed.test.ts @@ -180,6 +180,53 @@ test('reports matched-but-invisible targets with a typed no-visible-match reason }); }); +test('a hidden confirmed match cannot hide uncertainty in a visible observation candidate', () => { + const snapshot = makeSnapshot([ + { index: 0, type: 'Application', rect: { x: 0, y: 0, width: 320, height: 640 } }, + { + index: 1, + parentIndex: 0, + label: 'Ready', + rect: { x: 16, y: 20, width: 120, height: 44 }, + visibleToUser: false, + }, + { + index: 2, + parentIndex: 0, + label: 'Header\n'.repeat(10_000), + rect: { x: 16, y: 80, width: 120, height: 44 }, + }, + ]); + + expect(() => + resolveMaestroTargetFromSnapshot(snapshot, { selector: { text: '.*Ready' } }, 'android', { + confirmedUnindexedExistence: true, + }), + ).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); + + const visibleMatch = makeSnapshot([ + snapshot.nodes[0]!, + { ...snapshot.nodes[1]!, visibleToUser: true }, + snapshot.nodes[2]!, + ]); + expect( + resolveMaestroTargetFromSnapshot(visibleMatch, { selector: { text: '.*Ready' } }, 'android', { + confirmedUnindexedExistence: true, + }), + ).toMatchObject({ ok: true, node: { index: 1 } }); + expect(() => + resolveMaestroTargetFromSnapshot(visibleMatch, { selector: { text: '.*Ready' } }, 'android'), + ).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); +}); + test('keeps Maestro-visible app content matchable while a React Native overlay is present', () => { const snapshot = makeSnapshot([ { diff --git a/packages/maestro/src/internal/__tests__/selector-regex.test.ts b/packages/maestro/src/internal/__tests__/selector-regex.test.ts index ef53e98949b..b9cb0cc53c1 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -1,10 +1,106 @@ -import { expect, test } from 'vitest'; +import { RegExpParser } from '@eslint-community/regexpp'; +import { expect, test, vi } from 'vitest'; import { literalFromMaestroRegex, matchesMaestroRegex } from '../selector-regex.ts'; test('matches Maestro regex as case-insensitive full patterns', () => { + expect(matchesMaestroRegex('Item 22\nready', String.raw`item \d\d.+ready`)).toBe(true); 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); + expect(matchesMaestroRegex('Item \\', 'item \\')).toBe(true); + expect(matchesMaestroRegex('Sign in', '.*Sign in.*')).toBe(true); + expect(matchesMaestroRegex('candidate-low', 'candidate-(low|high)')).toBe(true); + expect(matchesMaestroRegex('item 22', String.raw`item [0-9]+`)).toBe(true); + expect(matchesMaestroRegex('Item 22 ready', String.raw`Item \d+\s+ready`)).toBe(true); + expect(matchesMaestroRegex('Item 8', String.raw`Item \8`)).toBe(true); + expect(matchesMaestroRegex('aaab', '(a+)b')).toBe(true); + expect(matchesMaestroRegex('aaabbb', '(a+)b+')).toBe(true); + expect(matchesMaestroRegex('AB12', '[A-Z]+[0-9]+')).toBe(true); + expect(matchesMaestroRegex('aa12', String.raw`a+\d+`)).toBe(true); + expect(matchesMaestroRegex('ab12', String.raw`[a-z]+\d+`)).toBe(true); + expect(matchesMaestroRegex('12kg', String.raw`\d+(kg|lb)`)).toBe(true); + expect(matchesMaestroRegex('Status\nReady\nDetails', 'Ready')).toBe(true); +}); + +test.each([ + '(a+)+', + '(a|aa)+', + '(?:(?:a|aa))*', + '(?:(?:a|ab)(?:c|bc))*', + 'a*a*', + 'a*b*a*', + '(a*)(a*)b', + '(?:aa)+a+b', + 'a{10001}', + 'a{10001,}', + 'a+(?:|a)a+b', + 'a+(?=a)a+b', + 'a+(?:a*)b', + '(?:a+)a+b', + '(a+){2}', + String.raw`(a+)\1`, + '(a|aa)(a|aa)(a|aa)(a|aa)(a|aa)(a|aa)', +])('refuses a backtracking Maestro selector pattern %s', (pattern) => { + expect(() => matchesMaestroRegex(`${'a'.repeat(4096)}X`, pattern)).toThrow( + expect.objectContaining({ + code: 'INVALID_ARGS', + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); +}); + +test('refuses a nullable separator before matching a maximum-length node value', () => { + expect(() => matchesMaestroRegex(`${'a'.repeat(8191)}X`, 'a+(?:|a)a+b')).toThrow( + expect.objectContaining({ + code: 'INVALID_ARGS', + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); +}); + +test('refuses overlapping grouped repetitions before a long node value runs', () => { + const value = `${'a\n'.repeat(4096)}X`; + expect(() => matchesMaestroRegex(value, '(a*)(a*)b')).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); +}); + +test('ordered wildcard literals retain Maestro full and multiline matching', () => { + for (const [value, pattern, expected] of [ + ['xxaYYb', '.*a.*b', true], + ['a\nZZ', '.*a.*b', false], + ['a\nb', '.*a.*b', true], + ['Order\nconfirmed', '.*Order.*confirmed.*', true], + ['xYyZz', '.*x.*y.*z', true], + ['Å\nβ', '.*å.*β', true], + ['a\r\nb', '.*a.*b', true], + ['a\u2028b', '.*a.*b', true], + ['ababa', '.*aba', true], + ['aababa', '.*a.*aba', true], + ['a.b\nc', String.raw`.*a\.b.*c`, true], + ['aX\nbYc', 'a.*b.*c', true], + ['xaX\nbYc', 'a.*b.*c', false], + ['a\nbX', '.*a.*b', false], + ['a'.repeat(8192) + 'b', '.*a.*b', true], + ['a'.repeat(8192) + 'X', '.*a.*b', false], + ] as const) { + expect(matchesMaestroRegex(value, pattern)).toBe(expected); + } +}); + +test('ordered wildcard work exhaustion remains indeterminate', () => { + const pattern = `.*${'a'.repeat(99)}b.*c`; + expect(() => matchesMaestroRegex('a'.repeat(11_000), pattern)).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); + expect(() => matchesMaestroRegex('x'.repeat(1_000_001), 'a.*b.*c')).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); }); test('extracts only patterns that are exact literals', () => { @@ -12,4 +108,134 @@ test('extracts only patterns that are exact literals', () => { expect(literalFromMaestroRegex(String.raw`price\.usd`)).toBe('price.usd'); expect(literalFromMaestroRegex(String.raw`item \d{2}`)).toBeUndefined(); expect(literalFromMaestroRegex('item [ready')).toBe('item [ready'); + expect(literalFromMaestroRegex('a'.repeat(8193))).toBe('a'.repeat(8193)); + expect(literalFromMaestroRegex(`${'a'.repeat(8193)}*`)).toBeUndefined(); +}); + +test('long device labels retain literal and bounded regex matches', () => { + expect(matchesMaestroRegex('a'.repeat(8193), 'item')).toBe(false); + expect(matchesMaestroRegex('a'.repeat(8193), 'a'.repeat(8193))).toBe(true); + expect(matchesMaestroRegex(`Status\n${'A'.repeat(8193)}\nDetails`, 'a'.repeat(8193))).toBe(true); + expect(matchesMaestroRegex(`Status\n${'A'.repeat(8192)}X\nDetails`, 'a'.repeat(8193))).toBe( + false, + ); + expect(matchesMaestroRegex(`Details: ${'x'.repeat(8300)} End`, 'Details: x+ End')).toBe(true); + expect(matchesMaestroRegex('item', 'item')).toBe(true); +}); + +test('a long regex-shaped selector matches exact text without executing its regex', () => { + const pattern = `Total: 12.5 ${'x'.repeat(300)}`; + expect(matchesMaestroRegex(` total: 12.5 ${'x'.repeat(300)} `, pattern)).toBe(true); + expect(() => matchesMaestroRegex(`${pattern} more`, pattern)).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); +}); + +test('multiline regex matches whole values and individual lines without retrying every suffix', () => { + expect(matchesMaestroRegex('start\nmiddle\nend', 'start.*end')).toBe(true); + expect(matchesMaestroRegex('before\nReady\nafter', 'Ready')).toBe(true); + expect(matchesMaestroRegex('before\nReady\nafter', '.*Ready.*')).toBe(true); + expect(matchesMaestroRegex('prefix\nstart\nmiddle\nend\nsuffix', 'start.*end')).toBe(true); + const wholeValuePastRestartBudget = `start${'\ndetails'.repeat(150)}\nend`; + expect(wholeValuePastRestartBudget.length).toBe(1209); + expect(matchesMaestroRegex(wholeValuePastRestartBudget, 'start.*end')).toBe(true); + for (const pattern of ['.*Sign in.*', 'Sign.*', 'Item .', String.raw`Hello\s+World`]) { + expect(matchesMaestroRegex('Welcome back\nPlease log in', pattern)).toBe(false); + } + expect(matchesMaestroRegex('x\nx', '[^x]+')).toBe(false); + expect(matchesMaestroRegex('a\n'.repeat(192_000), 'a+Z')).toBe(false); + expect(() => matchesMaestroRegex('a\n'.repeat(192_000), '.*Z')).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); +}); + +test('invalid regex syntax uses whole-value literal equality', () => { + expect(matchesMaestroRegex('[', '[')).toBe(true); + expect(matchesMaestroRegex('prefix\n[\nsuffix', '[')).toBe(false); +}); + +test('dense multiline values skip starts that cannot match the leading literal', () => { + const entries = 'Log\n'.repeat(1_500); + expect(matchesMaestroRegex(`${entries}order\nready`, 'Order.*ready')).toBe(true); + expect(matchesMaestroRegex(`${entries}Log\nclosed`, 'Order.*ready')).toBe(false); +}); + +test('dense multiline values retain complete-line matches when span search exceeds its work limit', () => { + const entries = `Log\n${'Order pending\n'.repeat(900)}`; + expect(matchesMaestroRegex(`${entries}Order ready`, 'Order.*ready')).toBe(true); + expect(() => matchesMaestroRegex(`${entries}Order\nready`, 'Order.*ready')).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); +}); + +test('CR and LF each provide a multiline anchor boundary', () => { + expect(matchesMaestroRegex('one\r\ntwo', '^$')).toBe(true); + expect(matchesMaestroRegex('one\rtwo', '^two$')).toBe(true); + expect(matchesMaestroRegex('one\ntwo', '^two$')).toBe(true); +}); + +test('escaped brackets and braces match literal node text', () => { + expect(matchesMaestroRegex('a(b', String.raw`a\(b`)).toBe(true); + expect(matchesMaestroRegex('price {2}', String.raw`price \{2\}`)).toBe(true); + expect(matchesMaestroRegex('price 22', String.raw`price {2}`)).toBe(false); +}); + +test('literal matches preserve text before safe regex-shaped patterns use regex semantics', () => { + expect(matchesMaestroRegex(' Save now ', 'save now')).toBe(true); + expect(matchesMaestroRegex('a'.repeat(257), 'a'.repeat(257))).toBe(true); + expect(() => matchesMaestroRegex('a*a*', 'a*a*')).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); + expect(matchesMaestroRegex('Item 22 [ready', 'Item 22 [ready')).toBe(true); + expect(matchesMaestroRegex('Terms | Privacy', 'Terms | Privacy')).toBe(true); + expect(matchesMaestroRegex('(a|b)', '(a|b)')).toBe(true); + expect(matchesMaestroRegex('Terms ', 'Terms | Privacy')).toBe(true); + expect(matchesMaestroRegex('a'.repeat(8193), 'a+')).toBe(true); + expect(matchesMaestroRegex('a'.repeat(8193), 'a'.repeat(8193))).toBe(true); + expect(matchesMaestroRegex('a'.repeat(256), 'a'.repeat(257))).toBe(false); + expect(() => matchesMaestroRegex('a'.repeat(8193), `${'a'.repeat(8193)}*`)).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); + expect(() => matchesMaestroRegex('a'.repeat(256), `(${`a`.repeat(255)})`)).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); +}); + +test('reuses a parsed selector pattern across node values', () => { + const parse = vi.spyOn(RegExpParser.prototype, 'parsePattern'); + try { + expect(matchesMaestroRegex('memoized-123', 'memoized-[0-9]+')).toBe(true); + expect(matchesMaestroRegex('memoized-abc', 'memoized-[0-9]+')).toBe(false); + expect(parse).toHaveBeenCalledTimes(1); + } finally { + parse.mockRestore(); + } +}); + +test('reports a parser failure through the typed selector reason', () => { + const parse = vi.spyOn(RegExpParser.prototype, 'parsePattern').mockImplementationOnce(() => { + throw new SyntaxError('unsupported parser syntax'); + }); + try { + expect(() => matchesMaestroRegex('parser-error-123', 'parser-error-[0-9]+')).toThrow( + expect.objectContaining({ + code: 'INVALID_ARGS', + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); + } finally { + parse.mockRestore(); + } }); diff --git a/packages/maestro/src/internal/engine-context.ts b/packages/maestro/src/internal/engine-context.ts index 2cd000efe74..c869754115c 100644 --- a/packages/maestro/src/internal/engine-context.ts +++ b/packages/maestro/src/internal/engine-context.ts @@ -140,8 +140,7 @@ function resolveValue( } function assertNoUnsupportedInterpolation(value: string): void { - const interpolation = /\$\{[^{}]*\}/g; - for (const match of value.matchAll(interpolation)) { + for (const match of value.matchAll(/\$\{[^{}]*\}/g)) { if (isMaestroPlatformExpression(match[0])) continue; throw new AppError( 'INVALID_ARGS', diff --git a/packages/maestro/src/internal/facade-execution.ts b/packages/maestro/src/internal/facade-execution.ts index 7295fde20c8..bdb734a01ad 100644 --- a/packages/maestro/src/internal/facade-execution.ts +++ b/packages/maestro/src/internal/facade-execution.ts @@ -1,5 +1,6 @@ import path from 'node:path'; import { isDeepLinkTarget } from '@agent-device/contracts/command'; +import { AppError } from '@agent-device/kernel/errors'; import type { SessionRuntimeHints } from '@agent-device/kernel/contracts'; import type { SnapshotNode } from '@agent-device/kernel/snapshot'; import type { SnapshotState } from '@agent-device/contracts/snapshot-model'; @@ -28,6 +29,7 @@ import { import type { MaestroReplayPlan } from './replay-plan-types.ts'; import { matchesMaestroTypedSelector } from './runtime-target-policy.ts'; import { rankMaestroCandidates } from './runtime-target-ranking.ts'; +import { MAESTRO_SELECTOR_REGEX_REASONS } from './selector-regex.ts'; const flowProgram = Symbol('maestroFlowProgram'); const failureCommand = Symbol('maestroFailureCommand'); @@ -190,10 +192,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 { + return rankMaestroCandidates(snapshot, query.selector, platform).ranked.map((node) => ({ + node, + basis: suggestionBasis(query.selector, node), + })); + } catch (error) { + if ( + error instanceof AppError && + (error.details?.reason === MAESTRO_SELECTOR_REGEX_REASONS.unsafe.reason || + error.details?.reason === MAESTRO_SELECTOR_REGEX_REASONS.indeterminate.reason) + ) + return []; + throw error; + } } function createObserver( @@ -306,7 +318,7 @@ function suggestionBasis( if ( selector.text !== undefined && matchesMaestroTypedSelector( - { ...node, label: undefined, value: undefined }, + { ...node, label: undefined, value: undefined, textClipped: undefined }, { text: selector.text }, ) ) { diff --git a/packages/maestro/src/internal/runtime-port-geometry.ts b/packages/maestro/src/internal/runtime-port-geometry.ts index 59b6edf2b22..76ccdfa6557 100644 --- a/packages/maestro/src/internal/runtime-port-geometry.ts +++ b/packages/maestro/src/internal/runtime-port-geometry.ts @@ -25,6 +25,7 @@ import { } from './runtime-target-policy.ts'; import { createMaestroResolver } from './runtime-target-ranking.ts'; import { resolveMaestroClickability } from './runtime-clickability.ts'; +import { MAESTRO_SELECTOR_REGEX_REASONS } from './selector-regex.ts'; import type { MaestroResolutionProbe } from './runtime-selector-resolution.ts'; import type { MaestroRuntimeOperations, @@ -96,10 +97,19 @@ function selectMaestroScrollableViewport( const candidateByIndex = new Map( candidates.map((candidate) => [candidate.node.index, candidate]), ); - for (const target of resolver.resolve(selector).indexed) { - const container = findScrollContainer(target, visibility.nodeByIndex); - const candidate = container ? candidateByIndex.get(container.index) : undefined; - if (candidate) return candidate.viewport; + try { + for (const target of resolver.resolve(selector).indexed) { + const container = findScrollContainer(target, visibility.nodeByIndex); + const candidate = container ? candidateByIndex.get(container.index) : undefined; + if (candidate) return candidate.viewport; + } + } catch (error) { + if ( + !(error instanceof AppError) || + error.details?.reason !== MAESTRO_SELECTOR_REGEX_REASONS.indeterminate.reason + ) { + throw error; + } } return candidates.sort(compareViewportAreaDescending)[0]?.viewport; } diff --git a/packages/maestro/src/internal/runtime-selector-resolution.ts b/packages/maestro/src/internal/runtime-selector-resolution.ts index c4b14cb9039..9c6d63182de 100644 --- a/packages/maestro/src/internal/runtime-selector-resolution.ts +++ b/packages/maestro/src/internal/runtime-selector-resolution.ts @@ -8,16 +8,25 @@ import type { SnapshotState } from '@agent-device/contracts/snapshot-model'; import type { MaestroSelector } from './program-ir.ts'; import { hasMaestroLeafSelectorFields } from './selector-relations.ts'; import { + createMaestroPositionUncertainty, selectMaestroPositionMatches, type MaestroPositionRelation, } from './runtime-target-position.ts'; -import { matchesMaestroTypedSelector } from './runtime-target-policy.ts'; +import { matchesMaestroTypedSelector, type MaestroFlatSelector } from './runtime-target-policy.ts'; +import { + createMaestroSelectorIndeterminateError, + MAESTRO_SELECTOR_REGEX_REASONS, + matchesMaestroRegex, + requiresExactMaestroRegexMatch, +} from './selector-regex.ts'; export type MaestroSelectorResolution = { /** Relation-composed matches in snapshot order, before this selector's own index. */ readonly matches: SnapshotNode[]; /** Matches after applying this selector's own index or no-index ordering policy. */ readonly indexed: SnapshotNode[]; + readonly parentMatched: boolean; + readonly uncertain?: AppError; }; export type MaestroResolutionProbe = { @@ -31,6 +40,7 @@ export type MaestroResolutionProbe = { export type MaestroResolutionOptions = { orderUnindexed?: (matches: readonly SnapshotNode[]) => SnapshotNode[]; + confirmedUnindexedExistence?: boolean; }; export type MaestroSnapshotResolver = { @@ -39,9 +49,18 @@ export type MaestroSnapshotResolver = { resolvePosition(relation: MaestroPositionRelation, anchor: MaestroSelector): SnapshotNode[]; }; +type UncertainNodes = ReadonlySet; +type CandidateMatch = boolean | 'uncertain'; +type RelationMatch = (node: SnapshotNode) => CandidateMatch; +type SelectorEntry = Omit & { + uncertainNodes?: UncertainNodes; + uncertainIndexed?: UncertainNodes; +}; + type MaestroPositionResolution = { ordered: SnapshotNode[]; - candidateIndexes: ReadonlySet; + match: RelationMatch; + uncertain: boolean; }; /** Resolve a recursive selector graph once for one immutable snapshot. */ @@ -52,7 +71,7 @@ export function createMaestroSnapshotResolver( ): MaestroSnapshotResolver { const visibility = createSnapshotVisibility(snapshot.nodes, probe); probe.onVisibilityContextCreated?.(); - const selectorCache = new WeakMap(); + const selectorCache = new WeakMap(); const resolving = new WeakSet(); const ancestorIndexesByNode = new WeakMap>(); const positionCaches = new Map< @@ -91,10 +110,16 @@ export function createMaestroSnapshotResolver( const cached = cache.get(anchor); if (cached) return cached; probe.onPositionComputed?.(relation, anchor); - const ordered = selectMaestroPositionMatches(snapshot.nodes, relation, resolve(anchor).indexed); - const resolution = { + const { indexed, uncertainIndexed } = resolveEntry(anchor); + const ordered = selectMaestroPositionMatches(snapshot.nodes, relation, indexed); + const candidateIndexes = new Set(ordered.map((node) => node.index)); + const uncertainAtPosition = + uncertainIndexed && createMaestroPositionUncertainty(relation, uncertainIndexed); + const resolution: MaestroPositionResolution = { ordered, - candidateIndexes: new Set(ordered.map((node) => node.index)), + match: (node) => + candidateIndexes.has(node.index) || (uncertainAtPosition?.(node) ? 'uncertain' : false), + uncertain: uncertainIndexed !== undefined, }; cache.set(anchor, resolution); return resolution; @@ -103,58 +128,75 @@ export function createMaestroSnapshotResolver( const resolvePosition = ( relation: MaestroPositionRelation, anchor: MaestroSelector, - ): SnapshotNode[] => resolvePositionEntry(relation, anchor).ordered; - - const resolvePositionIndexes = ( - relation: MaestroPositionRelation, - anchor: MaestroSelector, - ): ReadonlySet => resolvePositionEntry(relation, anchor).candidateIndexes; + ): SnapshotNode[] => { + const { ordered, uncertain } = resolvePositionEntry(relation, anchor); + if (uncertain) throw createMaestroSelectorIndeterminateError(); + return ordered; + }; - const resolve = (selector: MaestroSelector): MaestroSelectorResolution => { + const resolveEntry = (selector: MaestroSelector): SelectorEntry => { const cached = selectorCache.get(selector); if (cached) return cached; if (resolving.has(selector)) { throw new AppError('INVALID_ARGS', 'Maestro selector relations cannot contain cycles.'); } resolving.add(selector); - probe.onSelectorComputed?.(selector); try { - const matches = resolveWithoutOwnIndex( + probe.onSelectorComputed?.(selector); + const { matches, possible, uncertainNodes, parentMatched } = resolveWithoutOwnIndex( snapshot, selector, parentOf, ancestorIndexes, - resolve, - resolvePositionIndexes, + resolveEntry, + resolvePositionEntry, ); - const resolution = { - matches, - indexed: selectMaestroIndexedMatches(matches, selector.index, options.orderUnindexed), - }; - selectorCache.set(selector, resolution); - return resolution; + const selection = + possible && uncertainNodes && selector.index !== undefined + ? selectPossiblyIndexedMatches(possible, uncertainNodes, selector.index) + : { + indexed: selectMaestroIndexedMatches(matches, selector.index, options.orderUnindexed), + uncertainIndexed: uncertainNodes, + }; + const entry = { matches, uncertainNodes, parentMatched, ...selection }; + selectorCache.set(selector, entry); + return entry; } finally { resolving.delete(selector); } }; + const resolve = (selector: MaestroSelector): MaestroSelectorResolution => { + const { matches, indexed, parentMatched, uncertainNodes } = resolveEntry(selector); + const uncertain = uncertainNodes && createMaestroSelectorIndeterminateError(); + if ( + uncertain && + (!options.confirmedUnindexedExistence || selector.index !== undefined || !matches.length) + ) { + throw uncertain; + } + return { matches, indexed, parentMatched, ...(uncertain ? { uncertain } : {}) }; + }; + return { visibility, resolve, resolvePosition }; } -type ResolveSelector = (selector: MaestroSelector) => MaestroSelectorResolution; -type ResolvePositionIndexes = ( - relation: MaestroPositionRelation, - anchor: MaestroSelector, -) => ReadonlySet; - function resolveWithoutOwnIndex( snapshot: SnapshotState, selector: MaestroSelector, parentOf: (node: SnapshotNode) => SnapshotNode | undefined, ancestorIndexes: (node: SnapshotNode) => ReadonlySet, - resolve: ResolveSelector, - resolvePositionIndexes: ResolvePositionIndexes, -): SnapshotNode[] { + resolve: (selector: MaestroSelector) => SelectorEntry, + resolvePosition: ( + relation: MaestroPositionRelation, + anchor: MaestroSelector, + ) => MaestroPositionResolution, +): { + matches: SnapshotNode[]; + possible?: SnapshotNode[]; + uncertainNodes?: UncertainNodes; + parentMatched: boolean; +} { const { index: _index, childOf, @@ -166,40 +208,117 @@ function resolveWithoutOwnIndex( containsDescendants, ...leaf } = selector; - let matches = hasMaestroLeafSelectorFields(leaf) - ? snapshot.nodes.filter((node) => matchesMaestroTypedSelector(node, leaf)) - : [...snapshot.nodes]; - + let narrowed: SnapshotNode[] | undefined; + let uncertainNodes: Set | undefined; + let parentMatched = true; + const narrow = (resolveFilter: () => RelationMatch): void => { + if (narrowed?.length === 0) return; + const match = resolveFilter(); + narrowed = (narrowed ?? snapshot.nodes).filter((node) => { + const result = match(node); + if (result === false) uncertainNodes?.delete(node); + if (result === 'uncertain') (uncertainNodes ??= new Set()).add(node); + return result !== false; + }); + }; if (childOf) { - const parentIndexes = new Set(resolve(childOf).indexed.map((node) => node.index)); - matches = matches.filter((node) => setsIntersect(ancestorIndexes(node), parentIndexes)); + narrow(() => { + const { indexed, uncertainIndexed } = resolve(childOf); + parentMatched = indexed.length > 0 || uncertainIndexed !== undefined; + const parentIndexes = new Set(indexed.map((node) => node.index)); + const possibleParents = new Set(); + for (const node of uncertainIndexed ?? []) possibleParents.add(node.index); + return (node) => { + const ancestors = ancestorIndexes(node); + return ( + setsIntersect(ancestors, parentIndexes) || + (setsIntersect(ancestors, possibleParents) ? 'uncertain' : false) + ); + }; + }); } if (containsChild) { - const matchedParentIndexes = new Set( - resolve(containsChild) - .indexed.map(parentOf) - .filter((node): node is SnapshotNode => node !== undefined) - .map((node) => node.index), - ); - matches = matches.filter((node) => matchedParentIndexes.has(node.index)); + narrow(() => { + const { indexed, uncertainIndexed } = resolve(containsChild); + const parents = new Set(indexed.map((node) => parentOf(node)?.index)); + const possibleParents = new Set(); + for (const node of uncertainIndexed ?? []) possibleParents.add(parentOf(node)?.index); + return (node) => + parents.has(node.index) || (possibleParents.has(node.index) ? 'uncertain' : false); + }); } - if (containsDescendants) { - const containingAncestorSets = containsDescendants.map((nested) => - collectContainingAncestorIndexes(resolve(nested).indexed, ancestorIndexes), - ); - matches = matches.filter((node) => - containingAncestorSets.every((indexes) => indexes.has(node.index)), - ); + for (const nested of containsDescendants ?? []) { + narrow(() => { + const { indexed, uncertainIndexed } = resolve(nested); + const indexes = collectContainingAncestorIndexes(indexed, ancestorIndexes); + const possibleAncestors = collectContainingAncestorIndexes( + uncertainIndexed ?? [], + ancestorIndexes, + ); + return (node) => + indexes.has(node.index) || (possibleAncestors.has(node.index) ? 'uncertain' : false); + }); } for (const [relation, anchor] of positionalSelectors(selector)) { - const relatedIndexes = resolvePositionIndexes(relation, anchor); - matches = matches.filter((node) => relatedIndexes.has(node.index)); + narrow(() => resolvePosition(relation, anchor).match); + } + return { + ...resolveLeafMatches(narrowed ?? snapshot.nodes, leaf, uncertainNodes), + parentMatched, + }; +} + +function resolveLeafMatches( + scope: readonly SnapshotNode[], + leaf: MaestroFlatSelector, + uncertainNodes: Set | undefined, +): Omit, 'parentMatched'> { + if (scope.length === 0) return { matches: [] }; + const hasLeaf = hasMaestroLeafSelectorFields(leaf); + let leafMatched = false; + const possible = scope.filter((node) => { + const result = hasLeaf ? matchLeaf(node, leaf) : true; + if (result === false) { + uncertainNodes?.delete(node); + return false; + } + if (result === true) leafMatched = true; + if (result === 'uncertain') (uncertainNodes ??= new Set()).add(node); + return true; + }); + if (!leafMatched) { + const longPattern = [leaf.id, leaf.text].find( + (pattern) => pattern !== undefined && requiresExactMaestroRegexMatch(pattern), + ); + if (longPattern !== undefined) matchesMaestroRegex('', longPattern); + } + const unresolved = uncertainNodes; + if (!unresolved?.size) return { matches: possible }; + return { + matches: possible.filter((node) => !unresolved.has(node)), + possible, + uncertainNodes: unresolved, + }; +} + +function matchLeaf(node: SnapshotNode, leaf: MaestroFlatSelector): CandidateMatch { + try { + return matchesMaestroTypedSelector(node, leaf); + } catch (error) { + if (!isIndeterminateRegexError(error)) throw error; + return 'uncertain'; } - return matches; +} + +function isIndeterminateRegexError(error: unknown): error is AppError { + return ( + error instanceof AppError && + error.details?.reason === MAESTRO_SELECTOR_REGEX_REASONS.indeterminate.reason + ); } function collectContainingAncestorIndexes( - nodes: readonly SnapshotNode[], + nodes: Iterable, ancestorIndexes: (node: SnapshotNode) => ReadonlySet, ): Set { const containingIndexes = new Set(); @@ -210,7 +329,9 @@ function collectContainingAncestorIndexes( } function setsIntersect(left: ReadonlySet, right: ReadonlySet): boolean { - for (const value of left) if (right.has(value)) return true; + if (right.size) { + for (const value of left) if (right.has(value)) return true; + } return false; } @@ -235,6 +356,29 @@ function selectMaestroIndexedMatches( return selected ? [selected] : []; } +function selectPossiblyIndexedMatches( + nodes: readonly SnapshotNode[], + uncertain: UncertainNodes, + index: number | string, +): Pick { + const desiredIndex = resolveMaestroSelectorIndex(index); + const possible = new Set(); + let definiteBefore = 0; + let uncertainBefore = 0; + const ordered = sortMaestroMatchesForIndex(nodes); + for (const node of ordered) { + if (definiteBefore > desiredIndex) break; + const isUncertain = uncertain.has(node); + if (definiteBefore + uncertainBefore >= desiredIndex) { + if (!isUncertain && uncertainBefore === 0) return { indexed: [node] }; + possible.add(node); + } + if (isUncertain) uncertainBefore += 1; + else definiteBefore += 1; + } + return { indexed: [], ...(possible.size ? { uncertainIndexed: possible } : {}) }; +} + export function selectMaestroIndexedNode( matches: readonly SnapshotNode[], index: number | string | undefined, diff --git a/packages/maestro/src/internal/runtime-target-policy.ts b/packages/maestro/src/internal/runtime-target-policy.ts index bc025276802..87dd8211eef 100644 --- a/packages/maestro/src/internal/runtime-target-policy.ts +++ b/packages/maestro/src/internal/runtime-target-policy.ts @@ -1,13 +1,18 @@ +import { AppError } from '@agent-device/kernel/errors'; +import type { SnapshotNode } from '@agent-device/kernel/snapshot'; +import type { SnapshotVisibility } from '@agent-device/contracts/snapshot'; import type { MaestroLeafSelector, MaestroRelationalSelectorFields } from './program-ir.ts'; +import { + createMaestroSelectorIndeterminateError, + MAESTRO_SELECTOR_REGEX_REASONS, + matchesMaestroRegex, +} from './selector-regex.ts'; +import { extractNodeText } from './shared.ts'; +import { isMaestroNodeVisible } from './snapshot-policy.ts'; export type MaestroFlatSelector = MaestroLeafSelector & { [Key in keyof MaestroRelationalSelectorFields]?: never; }; -import type { SnapshotNode } from '@agent-device/kernel/snapshot'; -import type { SnapshotVisibility } from '@agent-device/contracts/snapshot'; -import { matchesMaestroRegex } from './selector-regex.ts'; -import { extractNodeText, normalizeText } from './shared.ts'; -import { isMaestroNodeVisible } from './snapshot-policy.ts'; export type MaestroRuntimePlatform = 'ios' | 'android'; @@ -28,13 +33,13 @@ export function matchesMaestroTypedSelector( const textTerms = [ selector.id === undefined ? undefined - : matchesMaestroSelectorValue(node.identifier, selector.id), + : tryMatchMaestroSelectorValue(node.identifier, selector.id), selector.text === undefined ? undefined : matchesMaestroVisibleText(node, selector.text), - ].filter((matched): matched is boolean => matched !== undefined); + ].filter((matched): matched is boolean | AppError => matched !== undefined); if (textTerms.length === 0 && selector.enabled === undefined && selector.selected === undefined) { return false; } - if (textTerms.some((matched) => !matched)) return false; + if (textTerms.includes(false)) return false; if (selector.enabled !== undefined && Boolean(node.enabled !== false) !== selector.enabled) { return false; @@ -42,6 +47,8 @@ export function matchesMaestroTypedSelector( if (selector.selected !== undefined && Boolean(node.selected === true) !== selector.selected) { return false; } + const uncertain = textTerms.find((term): term is AppError => term instanceof AppError); + if (uncertain) throw uncertain; return true; } @@ -55,16 +62,38 @@ export function filterVisibleMaestroMatches(params: { ); } -function matchesMaestroSelectorValue(value: string | undefined, query: string): boolean { - const text = value ?? ''; - const normalizedText = normalizeText(text); - const normalizedQuery = normalizeText(query); - if (normalizedText === normalizedQuery) return true; - return matchesMaestroRegex(text, query); +function tryMatchMaestroSelectorValue( + value: string | undefined, + query: string, +): boolean | AppError { + try { + return matchesMaestroRegex(value ?? '', query, true); + } catch (error) { + if ( + error instanceof AppError && + error.details?.reason === MAESTRO_SELECTOR_REGEX_REASONS.indeterminate.reason + ) { + return error; + } + throw error; + } } -function matchesMaestroVisibleText(node: SnapshotNode, query: string): boolean { - return [node.label, extractNodeText(node), node.identifier] - .filter((value): value is string => Boolean(value)) - .some((value) => matchesMaestroSelectorValue(value, query)); +function matchesMaestroVisibleText(node: SnapshotNode, query: string): boolean | AppError { + const values = node.textClipped + ? [node.contentDescription ?? (node.text === '' ? node.label : undefined), node.identifier] + : [node.label, extractNodeText(node), node.identifier]; + let uncertain: AppError | undefined; + for (const value of new Set(values)) { + if (!value) continue; + const result = tryMatchMaestroSelectorValue(value, query); + if (result === true) return true; + if (result instanceof AppError) uncertain ??= result; + } + if (node.textClipped) { + // Validate the pattern even when the clipped prefix is the only available text. + matchesMaestroRegex('', query, true); + return uncertain ?? createMaestroSelectorIndeterminateError(); + } + return uncertain ?? false; } diff --git a/packages/maestro/src/internal/runtime-target-position.ts b/packages/maestro/src/internal/runtime-target-position.ts index 478d9717d82..99092ae3ee6 100644 --- a/packages/maestro/src/internal/runtime-target-position.ts +++ b/packages/maestro/src/internal/runtime-target-position.ts @@ -69,3 +69,16 @@ function isFiniteRect(rect: Rect | undefined): rect is Rect { function centerCoordinate(origin: number, size: number): number { return origin + Math.trunc(size / 2); } + +export function createMaestroPositionUncertainty( + relation: MaestroPositionRelation, + anchors: Iterable, +): ((node: SnapshotNode) => boolean) | undefined { + let extreme: Rect | undefined; + for (const { rect } of anchors) { + if (isFiniteRect(rect) && (!extreme || qualifies(relation, extreme, rect))) extreme = rect; + } + if (!extreme) return undefined; + const anchor = extreme; + return (node) => isFiniteRect(node.rect) && qualifies(relation, node.rect, anchor); +} diff --git a/packages/maestro/src/internal/runtime-target-ranking.ts b/packages/maestro/src/internal/runtime-target-ranking.ts index 56619125d38..5edc0f63124 100644 --- a/packages/maestro/src/internal/runtime-target-ranking.ts +++ b/packages/maestro/src/internal/runtime-target-ranking.ts @@ -1,4 +1,5 @@ import type { Rect, SnapshotNode } from '@agent-device/kernel/snapshot'; +import type { AppError } from '@agent-device/kernel/errors'; import type { SnapshotState } from '@agent-device/contracts/snapshot-model'; import { isPositiveFiniteRect } from '@agent-device/kernel/rect'; import { normalizeType, type SnapshotVisibility } from '@agent-device/contracts/snapshot'; @@ -27,18 +28,28 @@ export type MaestroRankedCandidates = { readonly ranked: SnapshotNode[]; readonly parentMatched: boolean; readonly clickability: MaestroClickabilityDecision; + readonly uncertain?: AppError; }; -export type MaestroCandidateMatches = Pick; +export type MaestroCandidateMatches = Pick< + MaestroRankedCandidates, + 'matches' | 'parentMatched' | 'uncertain' +>; export function rankMaestroCandidates( snapshot: SnapshotState, selector: MaestroSelector, platform: MaestroRuntimePlatform, probe: MaestroResolutionProbe = {}, + confirmedUnindexedExistence = false, ): MaestroRankedCandidates { const clickability = resolveMaestroClickability(snapshot, platform); - const resolver = createMaestroResolver(snapshot, clickability, probe); + const resolver = createMaestroResolver( + snapshot, + clickability, + probe, + confirmedUnindexedExistence, + ); const scoped = matchMaestroCandidatesWithResolver(selector, resolver); const visible = filterVisibleMaestroMatches({ visibility: resolver.visibility, @@ -63,23 +74,25 @@ export function matchMaestroCandidatesWithResolver( selector: MaestroSelector, resolver: MaestroSnapshotResolver, ): MaestroCandidateMatches { - const matches = resolver.resolve(selector).matches; - const parentMatched = - selector.childOf === undefined || resolver.resolve(selector.childOf).indexed.length > 0; - return { matches, parentMatched }; + const { matches, parentMatched, uncertain } = resolver.resolve(selector); + return { matches, parentMatched, ...(uncertain ? { uncertain } : {}) }; } export function createMaestroResolver( snapshot: SnapshotState, clickability: MaestroClickabilityDecision | undefined, probe: MaestroResolutionProbe = {}, + confirmedUnindexedExistence = false, ): MaestroSnapshotResolver { return createMaestroSnapshotResolver( snapshot, probe, clickability - ? { orderUnindexed: (matches) => orderMaestroClickableFirst(matches, clickability) } - : {}, + ? { + orderUnindexed: (matches) => orderMaestroClickableFirst(matches, clickability), + confirmedUnindexedExistence, + } + : { confirmedUnindexedExistence }, ); } diff --git a/packages/maestro/src/internal/runtime-targets.ts b/packages/maestro/src/internal/runtime-targets.ts index c904bbb5062..9462b5f3975 100644 --- a/packages/maestro/src/internal/runtime-targets.ts +++ b/packages/maestro/src/internal/runtime-targets.ts @@ -43,6 +43,8 @@ type MaestroInteractivePresentation = { presentedIndexesBySourceIndex: ReadonlyMap; }; +type PresentedNodeLookup = ReturnType; + export type MaestroTargetResolution = | { ok: true; @@ -66,15 +68,20 @@ export function resolveMaestroTargetFromSnapshot( options: { interactiveBounds?: boolean; presentation?: MaestroInteractivePresentation; + confirmedUnindexedExistence?: boolean; } = {}, ): MaestroTargetResolution { const presentedNodes = platform === 'ios' && options.presentation ? createPresentedNodeLookup(options.presentation) : undefined; - const candidates = presentedNodes - ? rankPresentedMaestroCandidates(snapshot, query, presentedNodes) - : rankMaestroCandidates(snapshot, query.selector, platform); + const candidates = rankTargetCandidates( + snapshot, + query, + platform, + presentedNodes, + options.confirmedUnindexedExistence, + ); if (!candidates.parentMatched) { return { ok: false, @@ -89,6 +96,7 @@ export function resolveMaestroTargetFromSnapshot( : selectMaestroSnapshotMatch(rankedMatches, query.selector.index)?.node; const evidence = buildMaestroTargetEvidence(query, matches, rankedMatches, target); if (!target) { + if (candidates.uncertain) throw candidates.uncertain; return failedTargetResolution(query, matches, rankedMatches, evidence); } const presentedTarget = presentedNodes @@ -99,6 +107,7 @@ export function resolveMaestroTargetFromSnapshot( ? (presentedTarget?.rect ?? semanticRect) : (semanticRect ?? presentedTarget?.rect); if (!rect) { + if (candidates.uncertain) throw candidates.uncertain; return { ok: false, message: 'Maestro target did not provide usable geometry.', @@ -112,17 +121,55 @@ export function resolveMaestroTargetFromSnapshot( node: target, rect, matches: rankedMatches.length, - dispatchCandidates: - platform === 'ios' && - query.allowAtomicSelectorDispatch && - !hasMaestroRecursiveRelations(query.selector) && - presentedNodes - ? countInteractionDispatchCandidates(semanticRect, rankedMatches, presentedTarget) - : 0, + dispatchCandidates: atomicDispatchCandidates( + platform, + query, + presentedNodes, + semanticRect, + rankedMatches, + presentedTarget, + ), evidence, }; } +function rankTargetCandidates( + snapshot: SnapshotState, + query: MaestroSnapshotTargetQuery, + platform: MaestroRuntimePlatform, + presentedNodes: PresentedNodeLookup | undefined, + confirmedUnindexedExistence: boolean | undefined, +): MaestroRankedCandidates { + if (presentedNodes) { + return rankPresentedMaestroCandidates( + snapshot, + query, + presentedNodes, + confirmedUnindexedExistence, + ); + } + return rankMaestroCandidates(snapshot, query.selector, platform, {}, confirmedUnindexedExistence); +} + +function atomicDispatchCandidates( + platform: MaestroRuntimePlatform, + query: MaestroSnapshotTargetQuery, + presentedNodes: PresentedNodeLookup | undefined, + semanticRect: Rect | undefined, + rankedMatches: SnapshotNode[], + presentedTarget: { node: SnapshotNode; rect: Rect } | null, +): number { + if ( + platform !== 'ios' || + !query.allowAtomicSelectorDispatch || + hasMaestroRecursiveRelations(query.selector) || + !presentedNodes + ) { + return 0; + } + return countInteractionDispatchCandidates(semanticRect, rankedMatches, presentedTarget); +} + export const hasMaestroRecursiveRelations = hasRecursiveRelations; function createPresentedNodeLookup(presentation: MaestroInteractivePresentation): { @@ -156,12 +203,16 @@ function rankPresentedMaestroCandidates( snapshot: SnapshotState, query: MaestroSnapshotTargetQuery, presentedNodes: ReturnType, + confirmedUnindexedExistence = false, ): MaestroRankedCandidates { const clickability = resolveMaestroClickability(snapshot, 'ios'); const resolver = createMaestroSnapshotResolver( snapshot, {}, - { orderUnindexed: (matches) => orderMaestroClickableFirst(matches, clickability) }, + { + orderUnindexed: (matches) => orderMaestroClickableFirst(matches, clickability), + confirmedUnindexedExistence, + }, ); const scoped = matchMaestroCandidatesWithResolver(query.selector, resolver); const visible = scoped.matches.filter(presentedNodes.isVisible); diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index b03d0982561..ed20aa4e919 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -1,20 +1,446 @@ +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; +import { RegExpParser, visitRegExpAST, type AST } from '@eslint-community/regexpp'; +import { normalizeText } from './shared.ts'; + +export const MAESTRO_SELECTOR_REGEX_REASONS = { + // The selector pattern uses constructs that the bounded matcher cannot safely execute. + unsafe: { reason: 'maestro_selector_regex_unsafe' }, + // Incomplete snapshot text or the matching work limit prevents a definite selector result. + indeterminate: { reason: 'maestro_selector_regex_indeterminate' }, +} as const satisfies ReasonTable<'maestro selector regex'>; + const REGEX_SYNTAX = new Set(String.raw`^$\.*+?()[]{}|`); +const MAX_PATTERN_LENGTH = 256; +const MAX_COUNTED_REPETITION = 10_000; +const MAX_CACHED_PATTERNS = 128; +const MAX_PATTERN_PATHS = 32; +const MAX_MULTILINE_VALUE_LENGTH = 16_384; +const MAX_MULTILINE_WORK = 4_000_000; +const MAX_ORDERED_WORK = 1_000_000; +const parser = new RegExpParser(); +type RegexElement = AST.Alternative['elements'][number]; +type LiteralMatcher = { literal: string; wholeOnly: boolean; lineRegex?: RegExp }; +type GenericMatcher = { + regex: RegExp; + multilineRegex: RegExp; + canSpanLines: boolean; + initialLiteral?: RegExp; +}; +type Matcher = LiteralMatcher | { runs: RegExp[] } | GenericMatcher; +const matcherCache = new Map(); + +export function requiresExactMaestroRegexMatch(pattern: string): boolean { + return pattern.length > MAX_PATTERN_LENGTH && hasRegexSyntax(pattern); +} + +/** + * Returns a match or throws AppError with `maestro_selector_regex_unsafe` or + * `maestro_selector_regex_indeterminate`. + */ +export function matchesMaestroRegex( + value: string, + pattern: string, + deferLongPatternRefusal = false, +): boolean { + if (requiresExactMaestroRegexMatch(pattern)) { + if (normalizeText(value) === normalizeText(pattern)) return true; + if (deferLongPatternRefusal) return false; + unsafeMaestroRegex(); + } + const matcher = matcherForPattern(pattern); + if ('literal' in matcher) return matchesLiteral(value, matcher); + if (normalizeText(value) === normalizeText(pattern)) return true; + if ('runs' in matcher) return matchesOrderedRuns(value, pattern, matcher.runs); + return matchesGenericRegex(value, matcher); +} + +function matchesGenericRegex(value: string, matcher: GenericMatcher): boolean { + if (!hasLineTerminator(value)) return matcher.regex.test(value); + if (value.length <= MAX_MULTILINE_VALUE_LENGTH) { + if (!matcher.canSpanLines || withinMultilineWorkLimit(value, matcher.initialLiteral)) { + return matcher.multilineRegex.test(value); + } + if (matcher.regex.test(value)) return true; + } + if (matchesAnyLine(value, matcher.regex)) return true; + if (matcher.canSpanLines) throw createMaestroSelectorIndeterminateError(); + return false; +} + +function matchesLiteral(value: string, matcher: LiteralMatcher): boolean { + if (normalizeText(value) === normalizeText(matcher.literal)) return true; + if (matcher.wholeOnly) return false; + if (matcher.literal.length > MAX_PATTERN_LENGTH) { + return matchesLongLiteralLine(value, matcher.literal); + } + matcher.lineRegex ??= new RegExp( + `^(?:${matcher.literal.replaceAll(/[\\^$.*+?()[\]{}|]/g, String.raw`\$&`)})$`, + 'im', + ); + return matcher.lineRegex.test(value); +} + +function matchesLongLiteralLine(value: string, literal: string): boolean { + const text = value.toLowerCase(); + const query = literal.toLowerCase(); + const fallbacks = literalPrefixFallbacks(query); + let matched = 0; + for (let index = 0; index < text.length; index += 1) { + while (matched > 0 && text[index] !== query[matched]) matched = fallbacks[matched - 1]!; + if (text[index] === query[matched]) matched += 1; + if (matched !== query.length) continue; + const start = index + 1 - matched; + const before = start === 0 || isLineTerminator(text[start - 1]); + const after = index + 1 === text.length || isLineTerminator(text[index + 1]); + if (before && after) return true; + matched = fallbacks[matched - 1]!; + } + return false; +} + +function literalPrefixFallbacks(query: string): Uint32Array { + const fallbacks = new Uint32Array(query.length); + let matched = 0; + for (let index = 1; index < query.length; index += 1) { + while (matched > 0 && query[index] !== query[matched]) matched = fallbacks[matched - 1]!; + if (query[index] === query[matched]) matched += 1; + fallbacks[index] = matched; + } + return fallbacks; +} + +function isLineTerminator(character: string | undefined): boolean { + return ( + character === '\n' || character === '\r' || character === '\u2028' || character === '\u2029' + ); +} + +function hasLineTerminator(value: string): boolean { + return /[\n\r\u2028\u2029]/.test(value); +} + +function withinMultilineWorkLimit(value: string, initialLiteral?: RegExp): boolean { + // With the multiline start anchor, each line boundary can restart a scan of the remaining suffix. + let work = value.length; + for (let index = 0; index < value.length; index += 1) { + if (!isLineTerminator(value[index])) continue; + if (initialLiteral) { + initialLiteral.lastIndex = index + 1; + if (!initialLiteral.test(value)) continue; + } + work += value.length - index - 1; + if (work > MAX_MULTILINE_WORK) return false; + } + return true; +} + +function matchesAnyLine(value: string, regex: RegExp): boolean { + let start = 0; + for (let index = 0; index < value.length; index += 1) { + if (!isLineTerminator(value[index])) continue; + if (regex.test(value.slice(start, index))) return true; + start = index + 1; + } + return regex.test(value.slice(start)); +} + +function matchesOrderedRuns(value: string, pattern: string, runs: RegExp[]): boolean { + let cursor = 0; + let work = 0; + for (const [index, run] of runs.entries()) { + const needsLineStart = index === 0 && !pattern.startsWith('.*'); + const needsLineEnd = index === runs.length - 1 && !pattern.endsWith('.*'); + let start = cursor; + for (; start <= value.length; start += 1) { + if ((work += 1 + run.source.length) > MAX_ORDERED_WORK) { + throw createMaestroSelectorIndeterminateError(); + } + const end = orderedRunEnd(value, run, start, needsLineStart, needsLineEnd); + if (end === undefined) continue; + cursor = end; + break; + } + if (start > value.length) return false; + } + return true; +} + +function orderedRunEnd( + value: string, + run: RegExp, + start: number, + needsLineStart: boolean, + needsLineEnd: boolean, +): number | undefined { + if (needsLineStart && !atLineStart(value, start)) return undefined; + run.lastIndex = start; + if (!run.test(value)) return undefined; + const end = run.lastIndex; + return needsLineEnd && !atLineEnd(value, end) ? undefined : end; +} + +function atLineStart(value: string, index: number): boolean { + return index === 0 || isLineTerminator(value[index - 1]); +} + +function atLineEnd(value: string, index: number): boolean { + return index === value.length || isLineTerminator(value[index]); +} + +function matcherForPattern(pattern: string): Matcher { + const cached = matcherCache.get(pattern); + if (cached) return cached; + const literal = literalFromMaestroRegex(pattern); + let matcher: Matcher; + if (literal !== undefined) { + let wholeOnly = false; + try { + new RegExp(pattern); + } catch { + wholeOnly = true; + } + matcher = { literal, wholeOnly }; + } else { + if (pattern.length > MAX_PATTERN_LENGTH) unsafeMaestroRegex(); + const bounded = assertBoundedMaestroPattern(pattern); + try { + matcher = + 'runs' in bounded + ? bounded + : { + regex: new RegExp(`^(?:${pattern})$`, 'is'), + multilineRegex: new RegExp(`^(?:${pattern})$`, 'ims'), + ...bounded, + }; + } catch { + unsafeMaestroRegex(); + } + } + if (matcherCache.size >= MAX_CACHED_PATTERNS) { + matcherCache.delete(matcherCache.keys().next().value!); + } + matcherCache.set(pattern, matcher); + return matcher; +} -export function matchesMaestroRegex(value: string, pattern: string): boolean { +function assertBoundedMaestroPattern( + pattern: string, +): Pick | { runs: RegExp[] } { + let parsed: AST.Pattern; try { - return new RegExp(`^(?:${pattern})$`, 'ims').test(value); + parsed = parser.parsePattern(pattern); } catch { - return value.toLocaleLowerCase() === pattern.toLocaleLowerCase(); + unsafeMaestroRegex(); + } + let ambiguousGroups = 0; + const countAlternatives = (count: number): void => { + if (count > 1 && ++ambiguousGroups > 4) unsafeMaestroRegex(); + }; + visitRegExpAST(parsed, { + onBackreferenceEnter: unsafeMaestroRegex, + onAssertionEnter(node) { + if ('alternatives' in node) unsafeMaestroRegex(); + }, + onGroupEnter(node) { + countAlternatives(node.alternatives.length); + }, + onCapturingGroupEnter(node) { + countAlternatives(node.alternatives.length); + }, + onQuantifierEnter(node) { + if ( + node.min > MAX_COUNTED_REPETITION || + (Number.isFinite(node.max) && node.max > MAX_COUNTED_REPETITION) + ) { + unsafeMaestroRegex(); + } + visitRegExpAST(node.element, { + onGroupEnter(group) { + if (group.alternatives.length > 1) unsafeMaestroRegex(); + }, + onCapturingGroupEnter(group) { + if (group.alternatives.length > 1) unsafeMaestroRegex(); + }, + onQuantifierEnter: unsafeMaestroRegex, + }); + }, + }); + const ordered = orderedLiteralRuns(parsed); + if (ordered) return { runs: ordered }; + for (const alternative of parsed.alternatives) { + for (const path of expandedPaths(alternative.elements)) assertDisjointQuantifiers(path); + } + let initialLiteral = ''; + if (parsed.alternatives.length === 1) { + for (const element of parsed.alternatives[0]!.elements) { + if (element.type !== 'Character') break; + initialLiteral += element.raw; + } + } + return { + canSpanLines: parsed.alternatives.some((alternative) => + alternative.elements.some(elementCanSpanLines), + ), + ...(initialLiteral ? { initialLiteral: new RegExp(initialLiteral, 'iy') } : {}), + }; +} + +function orderedLiteralRuns(pattern: AST.Pattern): RegExp[] | undefined { + if (pattern.alternatives.length !== 1) return undefined; + const elements = pattern.alternatives[0]!.elements; + const wildcard = (element: RegexElement): boolean => + element.type === 'Quantifier' && + element.element.type === 'CharacterSet' && + element.element.kind === 'any' && + element.min === 0 && + element.max === Infinity && + element.greedy; + if (elements.filter(wildcard).length < 2) return undefined; + if (elements.some((element) => element.type !== 'Character' && !wildcard(element))) { + return undefined; + } + return pattern.raw + .split('.*') + .filter(Boolean) + .map((source) => new RegExp(source, 'iy')); +} + +function elementCanSpanLines(element: RegexElement): boolean { + if (element.type === 'Assertion') return false; + if (element.type === 'Quantifier') return elementCanSpanLines(element.element); + if (element.type === 'Group' || element.type === 'CapturingGroup') { + return element.alternatives.some((alternative) => + alternative.elements.some(elementCanSpanLines), + ); + } + const atom = new RegExp(`^(?:${element.raw})$`, 'is'); + return ['\n', '\r', '\u2028', '\u2029'].some((character) => atom.test(character)); +} + +function expandedPaths(elements: AST.Alternative['elements']): RegexElement[][] { + let paths: RegexElement[][] = [[]]; + for (const element of elements) { + paths = appendElement(paths, element); + } + return paths; +} + +function appendElement(paths: RegexElement[][], element: RegexElement): RegexElement[][] { + const isGroup = element.type === 'Group' || element.type === 'CapturingGroup'; + const branches = isGroup + ? element.alternatives.flatMap((alternative) => expandedPaths(alternative.elements)) + : [[element]]; + const next: RegexElement[][] = []; + for (const prefix of paths) { + for (const branch of branches) { + if (isGroup) assertSafeGroupAfterQuantifier(prefix.at(-1), branch); + next.push([...prefix, ...branch]); + if (next.length > MAX_PATTERN_PATHS) unsafeMaestroRegex(); + } + } + return next; +} + +function assertSafeGroupAfterQuantifier( + previous: RegexElement | undefined, + branch: RegexElement[], +) { + if (previous?.type !== 'Quantifier' || previous.max === previous.min) return; + const first = branch.find((element) => element.type !== 'Assertion'); + if (!first || (first.type === 'Quantifier' && first.min === 0)) unsafeMaestroRegex(); + const atom = first.type === 'Quantifier' ? first.element : first; + if (!quantifiedAtomsAreDisjoint(previous.element, atom)) unsafeMaestroRegex(); +} + +function assertDisjointQuantifiers(path: RegexElement[]): void { + const quantifiers = path.flatMap((element, index) => + element.type === 'Quantifier' && element.max > element.min ? [{ element, index }] : [], + ); + for (let left = 0; left < quantifiers.length; left += 1) { + for (let right = left + 1; right < quantifiers.length; right += 1) { + const later = quantifiers[right]!; + if (later.index === path.length - 1 && isTrailingWildcard(later.element)) continue; + if (!quantifiedAtomsAreDisjoint(quantifiers[left]!.element.element, later.element.element)) { + unsafeMaestroRegex(); + } + } + } +} + +function isTrailingWildcard(quantifier: AST.Quantifier): boolean { + return quantifier.element.raw === '.' && quantifier.max === Infinity && quantifier.min <= 1; +} + +function quantifiedAtomsAreDisjoint( + left: AST.QuantifiableElement, + right: AST.QuantifiableElement, +): boolean { + if ( + left.type === 'Group' || + left.type === 'CapturingGroup' || + right.type === 'Group' || + right.type === 'CapturingGroup' + ) { + return false; + } + if (!isAsciiOnly(left) && !isAsciiOnly(right)) return false; + const leftMatcher = new RegExp(`^(?:${left.raw})$`, 'is'); + const rightMatcher = new RegExp(`^(?:${right.raw})$`, 'is'); + for (let codePoint = 0; codePoint < 128; codePoint += 1) { + const character = String.fromCharCode(codePoint); + if (leftMatcher.test(character) && rightMatcher.test(character)) return false; + } + return true; +} + +function isAsciiOnly(element: AST.QuantifiableElement): boolean { + if (element.type === 'Character') return element.value < 128; + if (element.type === 'CharacterSet') { + return (element.kind === 'digit' || element.kind === 'word') && !element.negate; } + if (element.type !== 'CharacterClass' || element.negate) return false; + return element.elements.every((part) => { + if (part.type === 'Character') return part.value < 128; + if (part.type === 'CharacterClassRange') return part.max.value < 128; + return part.type === 'CharacterSet' && isAsciiOnly(part); + }); +} + +function unsafeMaestroRegex(): never { + throw new AppError('INVALID_ARGS', 'Maestro selector regular expression is too complex.', { + reason: MAESTRO_SELECTOR_REGEX_REASONS.unsafe.reason, + retriable: false, + }); +} + +export function createMaestroSelectorIndeterminateError(): AppError { + return new AppError('UNSUPPORTED_OPERATION', 'Maestro could not decide the selector match.', { + reason: MAESTRO_SELECTOR_REGEX_REASONS.indeterminate.reason, + retriable: false, + }); } export function literalFromMaestroRegex(pattern: string): string | undefined { + if (pattern.length > MAX_PATTERN_LENGTH) { + return hasRegexSyntax(pattern) ? undefined : pattern; + } try { new RegExp(pattern); } catch { return pattern; } + return literalFromEscapedPattern(pattern); +} + +function hasRegexSyntax(pattern: string): boolean { + for (const character of pattern) { + if (REGEX_SYNTAX.has(character)) return true; + } + return false; +} + +function literalFromEscapedPattern(pattern: string): string | undefined { let literal = ''; for (let index = 0; index < pattern.length; index += 1) { const character = pattern[index]!; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 311e223d79e..26c5fca09e6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -737,6 +737,9 @@ importers: '@agent-device/selectors': specifier: workspace:* version: link:../selectors + '@eslint-community/regexpp': + specifier: 4.12.2 + version: 4.12.2 devDependencies: undici: specifier: 7.30.1 diff --git a/scripts/__tests__/package-closure-audit.test.ts b/scripts/__tests__/package-closure-audit.test.ts index 4f2742eb26e..b91c790d268 100644 --- a/scripts/__tests__/package-closure-audit.test.ts +++ b/scripts/__tests__/package-closure-audit.test.ts @@ -17,7 +17,70 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { afterEach, test } from 'vitest'; -import { auditDependencyClosure, type PackedManifest } from '../lib/shipped-imports.ts'; +import { + auditDependencyClosure, + assertBundledWorkspaceDependencies, + bundledWorkspaceDependencyNames, + type PackedManifest, +} from '../lib/shipped-imports.ts'; + +test('bundled workspace proof includes package devDependencies', () => { + const names = bundledWorkspaceDependencyNames( + new Map([ + [ + 'packages/maestro/package.json', + JSON.stringify({ + dependencies: { + '@eslint-community/regexpp': '4.12.2', + '@agent-device/kernel': 'workspace:*', + }, + devDependencies: { + '@limrun/api': '^0.69.1', + '@eslint-community/regexpp': 'workspace:*', + 'test-only': '1.0.0', + }, + }), + ], + ]), + new Set(['@eslint-community/regexpp', '@limrun/api', '@agent-device/kernel']), + ); + assert.deepEqual([...names].sort(), ['@eslint-community/regexpp', '@limrun/api']); + assert.throws( + () => + assertBundledWorkspaceDependencies( + names, + new Set(['@eslint-community/regexpp@4.12.2 (MIT)']), + new Map(), + ), + /does not attribute rendered @limrun\/api modules/, + ); +}); + +test('a bundled workspace dependency needs rendered notice attribution', () => { + assert.throws( + () => assertBundledWorkspaceDependencies(new Set(['regexpp']), new Set(), new Map()), + /does not attribute rendered regexpp modules/, + ); + assert.doesNotThrow(() => + assertBundledWorkspaceDependencies( + new Set(['regexpp']), + new Set(['regexpp@4.12.2 (MIT)']), + new Map(), + ), + ); +}); + +test('a bundled workspace dependency cannot retain a shipped runtime import', () => { + assert.throws( + () => + assertBundledWorkspaceDependencies( + new Set(['regexpp']), + new Set(['regexpp@4.12.2 (MIT)']), + new Map([['regexpp', ['dist/cli.js']]]), + ), + /still imports regexpp at runtime/, + ); +}); const tempRoots: string[] = []; diff --git a/scripts/bundled-dependency-names.ts b/scripts/bundled-dependency-names.ts new file mode 100644 index 00000000000..ee400e548f0 --- /dev/null +++ b/scripts/bundled-dependency-names.ts @@ -0,0 +1,33 @@ +export const bundledDependencyNames = [ + '@eslint-community/regexpp', + '@limrun/api', + '@limrun/xdelta3-wasm', + '@xmldom/xmldom', + 'agent-base', + 'b4a', + 'debug', + 'events-universal', + 'eventsource-client', + 'eventsource-parser', + 'fast-fifo', + 'has-flag', + 'https-proxy-agent', + 'ignore', + 'ipaddr.js', + 'jpeg-js', + 'ms', + 'pend', + 'plist', + 'pngjs', + 'proxy-from-env', + 'streamx', + 'supports-color', + 'tar-stream', + 'text-decoder', + 'undici', + 'undici-types', + 'ws', + 'xmlbuilder', + 'yaml', + 'yauzl', +]; diff --git a/scripts/check-package.ts b/scripts/check-package.ts index 0bb72f67331..0e5684313b8 100644 --- a/scripts/check-package.ts +++ b/scripts/check-package.ts @@ -9,7 +9,8 @@ * 1. `publint` — packaging metadata against the packed tarball (exports/bin/types conditions). * 2. `attw` — declaration resolution for the module systems this package supports. * 3. runtime dependency closure — every bare specifier the shipped files import is a Node builtin - * or a declared `dependencies` entry, and every declared entry is actually imported. + * or a declared `dependencies` entry, every declared entry is imported, and every bundled + * workspace dependency is attributed in the packed artifact without a runtime import. * 4. every `exports` subpath imports, and the `bin` runs, from outside the workspace. * 5. the installed tree carries no daemon source, which is what lets an installed * client treat its version as the whole of its code identity (#2458). @@ -28,11 +29,17 @@ import os from 'node:os'; import path from 'node:path'; import { auditDependencyClosure, + assertBundledWorkspaceDependencies, + bundledWorkspaceDependencyNames, type PackedManifest as PackedDependencies, } from './lib/shipped-imports.ts'; import { assertInstalledSnapshotBridge } from './size-report-install.mjs'; +import { readLicenseNotices } from './size-report-package-notices.mjs'; +import { bundledDependencyNames } from './bundled-dependency-names.ts'; +import { listTrackedPackageManifests } from './layering/tracked-sources.ts'; import { assertBundledLicenseNotices, + BUNDLED_LICENSE_NOTICES_PATH, parseNpmPackOutput, type NpmPackEntry, } from './size-report-package.mjs'; @@ -282,6 +289,30 @@ try { ) as PackedManifest; const importedBy = auditDependencyClosure(installedRoot, manifest); step(`Verified the dependency closure: ${[...importedBy.keys()].sort().join(', ')}.`); + // R11 permits a workspace runtime dependency to be absent from the root manifest only when + // tsdown bundles it. The notices plugin attributes only modules rendered into the artifact. + // Check attribution for every bundled external dependency declared in the workspace. + const bundled = new Set(bundledDependencyNames); + const bundledWorkspaceDependencies = bundledWorkspaceDependencyNames( + new Map( + listTrackedPackageManifests(repoRoot).map((file) => [ + file, + fs.readFileSync(path.join(repoRoot, file), 'utf8'), + ]), + ), + bundled, + ); + const notices = readLicenseNotices( + fs.readFileSync(path.join(installedRoot, BUNDLED_LICENSE_NOTICES_PATH), 'utf8'), + ); + assertBundledWorkspaceDependencies( + bundledWorkspaceDependencies, + new Set(notices.attributions.map(({ label }) => label)), + importedBy, + ); + step( + `Confirmed ${bundledWorkspaceDependencies.size} bundled workspace dependencies are attributed.`, + ); importEveryExport(manifest); smokeTestBin(installedRoot, manifest); } catch (error) { diff --git a/scripts/layering/package-boundaries.test.ts b/scripts/layering/package-boundaries.test.ts index 8b255939b37..8144d39b9ff 100644 --- a/scripts/layering/package-boundaries.test.ts +++ b/scripts/layering/package-boundaries.test.ts @@ -8,6 +8,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { test } from 'node:test'; +import { bundledDependencyNames } from '../bundled-dependency-names.ts'; import { listSourceFiles } from './check.ts'; import { readNamedExports, readReExportSources } from './facade-exports.ts'; import { @@ -881,13 +882,22 @@ test('the real tree parses, declares, and passes R11', () => { '@agent-device/platform-android', ]); const rootExternalDependencies = rootExternalDependencyRanges(repoRoot); + const bundled = new Set(bundledDependencyNames); for (const pkg of packages) { for (const [name, range] of pkg.externalDependencies) { - assert.equal( - rootExternalDependencies.get(name), - range, - `${pkg.name} external dependency ${name} must match the root dependency range`, - ); + if (bundled.has(name)) { + assert.equal( + rootExternalDependencies.has(name), + false, + `${pkg.name} bundled dependency ${name} must not ship as a root runtime dependency`, + ); + } else { + assert.equal( + rootExternalDependencies.get(name), + range, + `${pkg.name} externalized dependency ${name} must match the root runtime range`, + ); + } } } const xmlPackage = packages.find((pkg) => pkg.name === '@agent-device/xml'); diff --git a/scripts/lib/shipped-imports.ts b/scripts/lib/shipped-imports.ts index 6acf2b83abb..7c59a1fb8a2 100644 --- a/scripts/lib/shipped-imports.ts +++ b/scripts/lib/shipped-imports.ts @@ -59,6 +59,42 @@ export type PackedManifest = { peerDependencies?: Record; }; +/** Bundled external dependencies declared by tracked workspace package manifests. */ +export function bundledWorkspaceDependencyNames( + manifests: ReadonlyMap, + bundledNames: ReadonlySet, +): Set { + const names = new Set(); + for (const source of manifests.values()) { + const manifest = JSON.parse(source) as { + dependencies?: Record; + devDependencies?: Record; + }; + for (const field of [manifest.dependencies, manifest.devDependencies]) { + for (const [name, range] of Object.entries(field ?? {})) { + if (bundledNames.has(name) && !range.startsWith('workspace:')) names.add(name); + } + } + } + return names; +} + +/** Prove that bundled workspace dependencies are attributed in the packed code. */ +export function assertBundledWorkspaceDependencies( + names: ReadonlySet, + attributionLabels: ReadonlySet, + importedBy: ReadonlyMap, +): void { + for (const name of names) { + if (![...attributionLabels].some((label) => label.startsWith(`${name}@`))) { + throw new Error(`The packed bundle does not attribute rendered ${name} modules.`); + } + if (importedBy.has(name)) { + throw new Error(`The packed bundle still imports ${name} at runtime.`); + } + } +} + /** Every file extension the package ships that Node can resolve a specifier from. */ const SHIPPED_SOURCE = /\.(?:m?js|cjs|d\.ts)$/; diff --git a/scripts/size-report-package.d.mts b/scripts/size-report-package.d.mts index 2056499a205..48b1afc91f8 100644 --- a/scripts/size-report-package.d.mts +++ b/scripts/size-report-package.d.mts @@ -2,6 +2,7 @@ // it is not in the typechecked program). TypeScript resolves this file when a checked module // imports `./size-report-package.mjs`; keep it in step with the exports there. export const DOCUMENTED_PACK_STUBS: readonly string[]; +export const BUNDLED_LICENSE_NOTICES_PATH: string; export function readMacosHelperTestTargets(manifestSource: string): string[]; export type NpmPackEntry = Readonly<{ path: string; size: number }>; export function assertBundledLicenseNotices( diff --git a/scripts/size-report-package.mjs b/scripts/size-report-package.mjs index f873a1c5575..a56fe2932fe 100644 --- a/scripts/size-report-package.mjs +++ b/scripts/size-report-package.mjs @@ -75,7 +75,7 @@ export function collectNpmPack(root) { * The notices asset a packed tree ships, and the build output it comes from. One path keeps the * manifest check and the content check naming the same file. */ -const BUNDLED_LICENSE_NOTICES_PATH = 'dist/src/THIRD_PARTY_NOTICES.txt'; +export const BUNDLED_LICENSE_NOTICES_PATH = 'dist/src/THIRD_PARTY_NOTICES.txt'; function describeUnresolvedAttribution(attribution) { return ( diff --git a/test/repo-guards/maestro-regex-owner.test.ts b/test/repo-guards/maestro-regex-owner.test.ts new file mode 100644 index 00000000000..dcac5bbf322 --- /dev/null +++ b/test/repo-guards/maestro-regex-owner.test.ts @@ -0,0 +1,229 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { parseSync } from 'oxc-parser'; +import { test } from 'vitest'; + +const SOURCE_ROOT = path.join( + path.dirname(fileURLToPath(import.meta.url)), + '../../packages/maestro/src', +); +const REGEX_OWNER = path.join(SOURCE_ROOT, 'internal/selector-regex.ts'); + +function sourceFiles(directory: string): string[] { + return fs.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { + if (entry.name === '__tests__' || entry.name === 'test-utils') return []; + const entryPath = path.join(directory, entry.name); + if (entry.isDirectory()) return sourceFiles(entryPath); + if (!entry.name.endsWith('.ts') || entry.name.endsWith('.test.ts')) return []; + return [entryPath]; + }); +} + +function regexBypassViolations(source: string, filePath: string): string[] { + const parsed = parseSync(filePath, source); + assert.deepEqual(parsed.errors, []); + const violations: string[] = []; + type Node = { + type?: string; + name?: string; + value?: unknown; + regex?: unknown; + start?: number; + callee?: Node; + id?: Node; + init?: Node; + left?: Node; + object?: Node; + property?: Node; + arguments?: Node[]; + body?: Node[]; + declarations?: Node[]; + params?: Node[]; + [key: string]: unknown; + }; + type Scope = { parent?: Scope; bindings: Map }; + function calledName(callee: Node | undefined): unknown { + if (callee?.type === 'Identifier') return callee.name; + if (callee?.type === 'MemberExpression') return callee.property?.name ?? callee.property?.value; + return undefined; + } + function binding(scope: Scope, name: string): boolean | undefined { + for (let current: Scope | undefined = scope; current; current = current.parent) { + if (current.bindings.has(name)) return current.bindings.get(name); + } + return undefined; + } + function isRegexReference(node: Node | undefined, scope: Scope): boolean { + if (node?.type === 'MemberExpression') { + return ( + node.object?.type === 'Identifier' && + node.object.name === 'globalThis' && + binding(scope, 'globalThis') === undefined && + calledName(node) === 'RegExp' + ); + } + if (node?.type !== 'Identifier' || !node.name) return false; + return binding(scope, node.name) ?? node.name === 'RegExp'; + } + function bindPattern(node: Node | undefined, scope: Scope): void { + if (!node) return; + if (node.type === 'Identifier' && node.name) { + scope.bindings.set(node.name, false); + return; + } + for (const child of patternChildren(node)) bindPattern(child, scope); + } + function patternChildren(node: Node): Node[] { + if (node.type === 'Property') return [node.value as Node]; + if (node.type === 'RestElement') return [node.argument as Node]; + if (node.type === 'AssignmentPattern') return [node.left as Node]; + if (node.type !== 'ObjectPattern' && node.type !== 'ArrayPattern') return []; + return Object.values(node).flatMap((child) => (Array.isArray(child) ? (child as Node[]) : [])); + } + function blockScope(node: Node, parent: Scope): Scope { + const scope: Scope = { parent, bindings: new Map() }; + for (const statement of node.body ?? []) declareStatement(statement, scope); + for (const statement of node.body ?? []) bindRegexAliases(statement, scope); + return scope; + } + function declareStatement(statement: Node, scope: Scope): void { + if (statement.type === 'VariableDeclaration') { + for (const declaration of statement.declarations ?? []) bindPattern(declaration.id, scope); + } else if (statement.type === 'FunctionDeclaration' || statement.type === 'ClassDeclaration') { + bindPattern(statement.id, scope); + } + } + function bindRegexAliases(statement: Node, scope: Scope): void { + if (statement.type !== 'VariableDeclaration') return; + for (const declaration of statement.declarations ?? []) { + if (declaration.id?.type === 'Identifier' && isRegexReference(declaration.init, scope)) { + scope.bindings.set(declaration.id.name!, true); + } + } + } + function isRegexBypass(node: Node, scope: Scope): boolean { + if (node.type !== 'NewExpression' && node.type !== 'CallExpression') return false; + if (isRegexReference(node.callee, scope)) return true; + return node.type === 'CallExpression' && isIndirectRegexCall(node, scope); + } + function isIndirectRegexCall(node: Node, scope: Scope): boolean { + const name = calledName(node.callee); + if (node.callee?.type !== 'MemberExpression') return false; + if ((name === 'call' || name === 'apply') && isRegexReference(node.callee.object, scope)) { + return true; + } + if (name === 'construct' && node.callee.object?.name === 'Reflect') { + return ( + binding(scope, 'Reflect') === undefined && isRegexReference(node.arguments?.[0], scope) + ); + } + return ( + (name === 'match' || name === 'matchAll' || name === 'search') && + node.arguments?.[0]?.regex === undefined + ); + } + function scopeForNode(node: Node, scope: Scope): Scope { + switch (node.type) { + case 'Program': + case 'BlockStatement': + return blockScope(node, scope); + case 'FunctionDeclaration': + case 'FunctionExpression': + case 'ArrowFunctionExpression': + return functionScope(node, scope); + case 'CatchClause': { + const local: Scope = { parent: scope, bindings: new Map() }; + bindPattern(node.param as Node, local); + return local; + } + case 'ForStatement': + case 'ForOfStatement': + case 'ForInStatement': + return loopScope(node, scope); + default: + return scope; + } + } + function functionScope(node: Node, parent: Scope): Scope { + const scope: Scope = { parent, bindings: new Map() }; + bindPattern(node.id, scope); + for (const parameter of node.params ?? []) bindPattern(parameter, scope); + return scope; + } + function loopScope(node: Node, parent: Scope): Scope { + const scope: Scope = { parent, bindings: new Map() }; + const declaration = node.type === 'ForStatement' ? node.init : node.left; + if (declaration?.type === 'VariableDeclaration') { + for (const item of declaration.declarations ?? []) bindPattern(item.id, scope); + bindRegexAliases(declaration, scope); + } + return scope; + } + function visit(value: unknown, scope: Scope): void { + if (!value || typeof value !== 'object') return; + if (Array.isArray(value)) { + for (const item of value) visit(item, scope); + return; + } + const node = value as Node; + const local = scopeForNode(node, scope); + if (isRegexBypass(node, local)) { + const line = source.slice(0, node.start).split('\n').length; + violations.push(`${path.relative(SOURCE_ROOT, filePath)}:${line}`); + } + for (const child of Object.values(node)) visit(child, local); + } + visit(parsed.program, { bindings: new Map() }); + return violations; +} + +test('Maestro regex construction stays behind the bounded selector owner', () => { + const files = sourceFiles(SOURCE_ROOT).filter((file) => file !== REGEX_OWNER); + assert.ok(files.length > 0, 'guard must scan Maestro production files'); + assert.deepEqual( + files.flatMap((file) => regexBypassViolations(fs.readFileSync(file, 'utf8'), file)), + [], + 'Route authored selector patterns through internal/selector-regex.ts.', + ); +}); + +test('Maestro regex guard catches direct and implicit construction', () => { + const source = [ + 'new RegExp(query)', + 'RegExp(query)', + 'value.match(query)', + 'value.matchAll(query)', + 'value.search(query)', + "value['match'](query)", + 'const R = RegExp; new R(query)', + 'Reflect.construct(RegExp, [query])', + 'RegExp.call(null, query)', + 'RegExp.apply(null, [query])', + 'for (const R = RegExp; ; ) new R(query)', + 'globalThis.RegExp(query)', + "new globalThis['RegExp'](query)", + ].join(';'); + assert.equal(regexBypassViolations(source, 'fixture.ts').length, 13); + assert.deepEqual(regexBypassViolations('value.matchAll(/fixed/g)', 'fixture.ts'), []); + assert.deepEqual( + regexBypassViolations('const R = RegExp; function use(R) { new R(query) }', 'fixture.ts'), + [], + ); + assert.deepEqual( + regexBypassViolations( + 'function use() { const RegExp = make(); new RegExp(query) }', + 'fixture.ts', + ), + [], + ); + assert.deepEqual( + regexBypassViolations('const R = RegExp; for (const R of values) new R(query)', 'fixture.ts'), + [], + ); + assert.deepEqual( + regexBypassViolations('function use(globalThis) { globalThis.RegExp(query) }', 'fixture.ts'), + [], + ); +}); diff --git a/tsdown.config.ts b/tsdown.config.ts index 5412d1a2040..dc699f86194 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -1,4 +1,5 @@ import { buildEntries } from './scripts/build-entries.ts'; +import { bundledDependencyNames } from './scripts/bundled-dependency-names.ts'; import fs from 'node:fs'; import { defineConfig, type TsdownPluginOption } from 'tsdown'; import { bundledLicenseNotices } from './scripts/lib/bundled-license-notices.ts'; @@ -86,38 +87,7 @@ export default defineConfig({ entry: buildEntries, deps: { alwaysBundle: [/^@agent-device\//], - onlyBundle: [ - '@limrun/api', - '@limrun/xdelta3-wasm', - '@xmldom/xmldom', - 'agent-base', - 'b4a', - 'debug', - 'events-universal', - 'eventsource-client', - 'eventsource-parser', - 'fast-fifo', - 'has-flag', - 'https-proxy-agent', - 'ignore', - 'ipaddr.js', - 'jpeg-js', - 'ms', - 'pend', - 'plist', - 'pngjs', - 'proxy-from-env', - 'streamx', - 'supports-color', - 'tar-stream', - 'text-decoder', - 'undici', - 'undici-types', - 'ws', - 'xmlbuilder', - 'yaml', - 'yauzl', - ], + onlyBundle: bundledDependencyNames, // The Limrun SDK is dev-bundled, so a published install has no `@limrun/api` to resolve: // the limrun facade declares the session and runtime types consumers may use. dts: { diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index e3a89daa61d..c3986928c93 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -881,6 +881,13 @@ These reasons can come from more than one command. | `event_creation_failed` | macOS could not create the keyboard or mouse event to post. | | `missing_button` | No button on the alert fits the requested accept or dismiss. | +### Maestro selector regex + +| Reason | Meaning | +| --- | --- | +| `maestro_selector_regex_unsafe` | The selector pattern uses constructs that the bounded matcher cannot safely execute. | +| `maestro_selector_regex_indeterminate` | Incomplete snapshot text or the matching work limit prevents a definite selector result. | + ### Metro reload | Reason | Meaning | diff --git a/website/docs/docs/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index fdf4e5d7606..0407be9d5bd 100644 --- a/website/docs/docs/run-maestro-flows.md +++ b/website/docs/docs/run-maestro-flows.md @@ -30,6 +30,11 @@ Keep the target binding, such as `--platform ios`, on the `replay` or `test` com ## Boundaries +- Selector `id` and `text`: + - Supported matches: exact text, one line of a multiline value for plain literals, and safe regular expressions over complete spans between line boundaries. Safe patterns can use groups, alternatives, character classes, counted or disjoint repetitions, and ordered literal runs separated by greedy `.*`. Invalid regex syntax uses whole-value literal equality. + - Multiline regex matching has a work limit and scans values up to 16,384 characters for spans across lines. Individual lines can still match. Counted repetitions cannot exceed 10,000, and a pattern can contain at most four ambiguous groups. When there are candidates to check, a regex pattern over 256 characters requires one node to satisfy every selector field, including an exact normalized text match for that pattern. + - Refusals: backreferences, lookahead or lookbehind, overlapping repetitions, and quantified groups containing alternatives or repetitions fail with `maestro_selector_regex_unsafe`. A pattern that exceeds the limits also fails with this reason. + - Selection uses a definite match for an unindexed observation even if another node's match is undecidable. A clipped Android field can leave a text match undecidable even when the snapshot tree is complete. An action or indexed selector fails with `maestro_selector_regex_indeterminate` if an undecidable match could change the chosen target. `scrollUntilVisible` continues scrolling and reports the error if its last snapshot is still undecidable at the deadline. - Permissions: every entry is one `settings permission` call, applied in order with `all` first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so `location: inuse` and `location: never` mean `allow` and `deny` there, while `location: always` and `photos: limited` are Apple-only and fail. On iOS simulators, `grant`, `deny`, or `reset` on `notifications` returns `ios-notification-permission-unsupported`. Answer the notification prompt with the CLI command `alert accept` or `alert dismiss`, which this Maestro subset does not include. For `all`, `simctl privacy` determines which services the runtime can change, and current runtimes leave notifications untouched. - Runtime: iOS and Android only; `launchApp.clearState` and standalone `clearState` support Android and iOS simulators, launch arguments are Apple-only (a map-form argument key gains a leading `-` unless its value is a boolean, as in Maestro), and other standalone device utility/state commands are unsupported. - Expressions: `evalScript` and condition `true:` fields (`runFlow.when` and `repeat.while` share one evaluator) are evaluated as JavaScript (flow `env` and prior `output` leaves are string-typed); a `true:` field that is a boolean, a `maestro.platform` comparison, or plain literal text after `${VAR}` lookups is decided without JavaScript, with the `assertTrue` falsy table for literal text. Other fields stay literal or `${VAR}` lookup-only — `assertTrue` supports literals and bare lookups, and other expression-shaped payloads fail loud.