diff --git a/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/TouchPlanInjector.java b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/TouchPlanInjector.java index ed88b4b117..3748500c09 100644 --- a/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/TouchPlanInjector.java +++ b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/TouchPlanInjector.java @@ -75,7 +75,7 @@ private static void injectEvent( UiAutomation automation, MotionEvent event, boolean waitForDispatch) { try { sleepUntil(event.getEventTime()); - if (!automation.injectInputEvent(event, waitForDispatch)) { + if (!UiAutomationInputDispatcher.inject(automation, event, waitForDispatch)) { throw new IllegalStateException("injectInputEvent returned false"); } } finally { diff --git a/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/UiAutomationInputDispatcher.java b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/UiAutomationInputDispatcher.java new file mode 100644 index 0000000000..791edf083d --- /dev/null +++ b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/UiAutomationInputDispatcher.java @@ -0,0 +1,49 @@ +package com.callstack.agentdevice.snapshothelper; + +import android.app.UiAutomation; +import android.view.InputEvent; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * Dispatches planned input without the framework's global animation synchronization. + * + *

The public two-argument overload waits for global animations before every event. Android's + * three-argument test API separates that policy from synchronous input dispatch, but the SDK stub + * hides the method, so the helper resolves it from the runtime framework. + */ +final class UiAutomationInputDispatcher { + private static volatile Method injectWithoutAnimationWait = findInjectWithoutAnimationWait(); + + private UiAutomationInputDispatcher() {} + + static boolean inject(UiAutomation automation, InputEvent event, boolean waitForDispatch) { + Method method = injectWithoutAnimationWait; + if (method == null) return automation.injectInputEvent(event, waitForDispatch); + try { + return (Boolean) method.invoke(automation, event, waitForDispatch, false); + } catch (IllegalAccessException | IllegalArgumentException error) { + // Older or restricted runtimes retain the public, slower compatibility path. + injectWithoutAnimationWait = null; + return automation.injectInputEvent(event, waitForDispatch); + } catch (InvocationTargetException error) { + rethrowCause(error.getCause()); + throw new AssertionError("Unreachable"); + } + } + + private static Method findInjectWithoutAnimationWait() { + try { + return UiAutomation.class.getMethod( + "injectInputEvent", InputEvent.class, boolean.class, boolean.class); + } catch (NoSuchMethodException | SecurityException error) { + return null; + } + } + + private static void rethrowCause(Throwable cause) { + if (cause instanceof RuntimeException) throw (RuntimeException) cause; + if (cause instanceof Error) throw (Error) cause; + throw new IllegalStateException("UiAutomation input injection failed", cause); + } +} diff --git a/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/PointerEventScheduleTest.java b/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/PointerEventScheduleTest.java index 709886e5d8..8d274add37 100644 --- a/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/PointerEventScheduleTest.java +++ b/android/snapshot-helper/src/test/java/com/callstack/agentdevice/snapshothelper/PointerEventScheduleTest.java @@ -12,6 +12,11 @@ public static void main(String[] args) { "MOVE:1:1:16:true", "MOVE:2:1:32:true", "UP:2:1:32:true"); + assertSteps( + PointerEventSchedule.create(1, new long[] {0, 16}), + "DOWN:0:1:0:true", + "MOVE:1:1:16:true", + "UP:1:1:16:true"); assertSteps( PointerEventSchedule.create(2, new long[] {0, 16, 32}), "DOWN:0:1:0:true", diff --git a/docs/adr/0015-direct-maestro-engine.md b/docs/adr/0015-direct-maestro-engine.md index 039f8cd21b..dd1346cefb 100644 --- a/docs/adr/0015-direct-maestro-engine.md +++ b/docs/adr/0015-direct-maestro-engine.md @@ -125,8 +125,10 @@ primes the next command, so the retry policy does not add another hierarchy read `waitForAnimationToEnd` uses its own screenshot-stability operation, matching upstream's two immediate captures per attempt and 0.005% normalized absolute RGB-difference threshold. These captures explicitly bypass ordinary screenshot stabilization so the command observes the application rather than -recursively waiting on another settling policy. Screenshot stability does not discharge a pending -mutation boundary; a later mutating command still verifies hierarchy stability before dispatch. On iOS, +recursively waiting on another settling policy. After a successful authored visual wait, screenshot +stability discharges the same-generation pending mutation boundary instead of preceding the visual +barrier with a hierarchy capture. Reaching the visual deadline without observing a stable pair leaves +that boundary pending for the next mutating command's hierarchy settle. On iOS, comparison captures use the persistent runner's screenshot surface so both frames come from one warmed transport and avoid simulator screenshot setup between polls. diff --git a/src/compat/maestro/__tests__/daemon-runtime-port-snapshot-source.test.ts b/src/compat/maestro/__tests__/daemon-runtime-port-snapshot-source.test.ts index 54ff5aece6..58e8ec0320 100644 --- a/src/compat/maestro/__tests__/daemon-runtime-port-snapshot-source.test.ts +++ b/src/compat/maestro/__tests__/daemon-runtime-port-snapshot-source.test.ts @@ -124,3 +124,22 @@ test('rejects a deferred stability baseline consumed by another generation', asy 'stability generation 2 does not match 3', ); }); + +test('consumes deferred hierarchy stability after a same-generation visual wait', async () => { + const source = createDaemonMaestroSnapshotSource({ + baseReq: makeBaseRequest({ flags: { platform: 'ios', replayBackend: 'maestro' } }), + invoke: async () => ({ ok: true, data: { nodes: [] } }), + dependencies: makeDependencies(), + platform: 'ios', + }); + + source.requireStability(2); + source.consumeStabilityFromVisualWait({ generation: 2, env: {} }); + + await expect(source.settlePending({ generation: 2, env: {} })).resolves.toBeUndefined(); + + source.requireStability(2); + expect(() => source.consumeStabilityFromVisualWait({ generation: 3, env: {} })).toThrow( + 'stability generation 2 does not match 3', + ); +}); diff --git a/src/compat/maestro/__tests__/daemon-runtime-port.test.ts b/src/compat/maestro/__tests__/daemon-runtime-port.test.ts index 43fb8e3837..bee15d8fa8 100644 --- a/src/compat/maestro/__tests__/daemon-runtime-port.test.ts +++ b/src/compat/maestro/__tests__/daemon-runtime-port.test.ts @@ -541,7 +541,7 @@ test('waitForAnimationToEnd uses two unstabilized screenshot captures', async () platform: 'android', }); - await port.execute({ + const result = await port.execute({ command: { kind: 'waitForAnimationToEnd', source: { line: 2 }, timeout: 0 }, generation: 0, env: {}, @@ -553,6 +553,7 @@ test('waitForAnimationToEnd uses two unstabilized screenshot captures', async () expect( requests.every(({ flags }) => flags?.maestro?.screenshotCaptureBackend === undefined), ).toBe(true); + expect(result).not.toHaveProperty('visualStabilityReached'); }); test('waitForAnimationToEnd uses the persistent runner capture backend on iOS', async () => { @@ -636,5 +637,86 @@ test('waitForAnimationToEnd between two taps does not throw a stability-generati const result = await executeMaestroProgram(program, port); - expect(result).toMatchObject({ executed: 3, skipped: 0 }); + expect(result).toMatchObject({ executed: 3, skipped: 0, generation: 2 }); + expect(requests.map(({ command }) => command)).toEqual([ + 'snapshot', + 'click', + 'screenshot', + 'screenshot', + 'snapshot', + 'click', + ]); +}); + +test('timed-out waitForAnimationToEnd retains the pending hierarchy settle', async () => { + const requests: DaemonRequest[] = []; + const clock = { value: 0 }; + const firstScreenshot = new PNG({ width: 1, height: 1 }); + firstScreenshot.data[3] = 255; + const secondScreenshot = new PNG({ width: 1, height: 1 }); + secondScreenshot.data[0] = 255; + secondScreenshot.data[3] = 255; + const screenshots = [PNG.sync.write(firstScreenshot), PNG.sync.write(secondScreenshot)]; + let screenshotIndex = 0; + const snapshot = makeSnapshot([ + { index: 0, type: 'Application', rect: { x: 0, y: 0, width: 402, height: 874 } }, + { + index: 1, + parentIndex: 0, + type: 'Button', + identifier: 'settings', + label: 'Settings', + rect: { x: 20, y: 40, width: 120, height: 44 }, + }, + { + index: 2, + parentIndex: 0, + type: 'Button', + identifier: 'catalog', + label: 'Catalog', + rect: { x: 20, y: 100, width: 120, height: 44 }, + }, + ]); + + const port = createDaemonMaestroRuntimePort({ + baseReq: makeBaseRequest({ flags: { platform: 'ios', replayBackend: 'maestro' } }), + invoke: async (request) => { + requests.push(request); + if (request.command === 'snapshot') return { ok: true, data: snapshot }; + if (request.command === 'screenshot') { + await fs.promises.writeFile( + request.positionals[0]!, + screenshots[screenshotIndex++ % screenshots.length]!, + ); + } + return { ok: true, data: {} }; + }, + dependencies: makeDependencies(clock), + platform: 'ios', + }); + + const program = parseMaestroProgram( + [ + 'appId: com.callstack.agentdevicelab', + '---', + '- tapOn:', + ' text: Settings', + '- waitForAnimationToEnd: 0', + '- tapOn:', + ' text: Catalog', + ].join('\n'), + ); + + const result = await executeMaestroProgram(program, port); + + expect(result).toMatchObject({ executed: 3, skipped: 0, generation: 2 }); + expect(clock.value).toBe(MAESTRO_OBSERVATION_POLL_MS); + expect(requests.map(({ command }) => command)).toEqual([ + 'snapshot', + 'click', + 'screenshot', + 'screenshot', + 'snapshot', + 'click', + ]); }); diff --git a/src/compat/maestro/__tests__/runtime-port.test.ts b/src/compat/maestro/__tests__/runtime-port.test.ts index 05aa272120..fdfee2162f 100644 --- a/src/compat/maestro/__tests__/runtime-port.test.ts +++ b/src/compat/maestro/__tests__/runtime-port.test.ts @@ -72,7 +72,7 @@ describe('MaestroRuntimePort', () => { expect(result).toEqual({ executed: 12, skipped: 0, - generation: 10, + generation: 9, artifactPaths: ['artifact://checkout.png'], }); expect(calls.map(({ kind }) => kind)).toEqual([ @@ -113,16 +113,16 @@ describe('MaestroRuntimePort', () => { expect(calls[9]).toMatchObject({ kind: 'waitForAnimationToEnd', input: { timeoutMs: 50 }, - generation: 10, + generation: 9, }); expect(calls[11]).toMatchObject({ kind: 'runScript', input: { file: 'setup.js', env: { SEED: 7 } }, - generation: 10, + generation: 9, }); }); - test('describes observation validity after successful waits and scripts', async () => { + test('preserves observation validity after visual waits and scripts', async () => { const waitInvalidation = vi.fn(); const scriptInvalidation = vi.fn(); const operations = makeOperations({ @@ -147,7 +147,7 @@ describe('MaestroRuntimePort', () => { invalidateObservation: scriptInvalidation, }), ).resolves.toEqual({}); - expect(waitInvalidation).toHaveBeenCalledOnce(); + expect(waitInvalidation).not.toHaveBeenCalled(); expect(scriptInvalidation).not.toHaveBeenCalled(); }); diff --git a/src/compat/maestro/__tests__/wait-for-animation-to-end.test.ts b/src/compat/maestro/__tests__/wait-for-animation-to-end.test.ts index d6a5b7b480..1a6f736b47 100644 --- a/src/compat/maestro/__tests__/wait-for-animation-to-end.test.ts +++ b/src/compat/maestro/__tests__/wait-for-animation-to-end.test.ts @@ -9,7 +9,7 @@ test('captures an explicit zero-timeout pair and accepts exactly 0.005% RGB diff let captureCount = 0; let tempRoot: string | undefined; - await waitForMaestroAnimationToEnd({ + const stable = await waitForMaestroAnimationToEnd({ timeoutMs: 0, now: () => 0, capture: async (screenshotPath) => { @@ -18,6 +18,7 @@ test('captures an explicit zero-timeout pair and accepts exactly 0.005% RGB diff }, }); + expect(stable).toBe(true); expect(captureCount).toBe(2); expect(await exists(tempRoot!)).toBe(false); }); @@ -27,7 +28,7 @@ test('retries changed pairs immediately until a matching pair is captured', asyn let captureCount = 0; let tempRoot: string | undefined; - await waitForMaestroAnimationToEnd({ + const stable = await waitForMaestroAnimationToEnd({ timeoutMs: 2, now: () => now, capture: async (screenshotPath) => { @@ -46,6 +47,7 @@ test('retries changed pairs immediately until a matching pair is captured', asyn }, }); + expect(stable).toBe(true); expect(captureCount).toBe(4); expect(await exists(tempRoot!)).toBe(false); }); @@ -55,7 +57,7 @@ test('treats dimension and capture failures as nonmatches before retrying', asyn let captureCount = 0; let tempRoot: string | undefined; - await waitForMaestroAnimationToEnd({ + const stable = await waitForMaestroAnimationToEnd({ timeoutMs: 10, now: () => now, capture: async (screenshotPath) => { @@ -74,10 +76,29 @@ test('treats dimension and capture failures as nonmatches before retrying', asyn }, }); + expect(stable).toBe(true); expect(captureCount).toBe(6); expect(await exists(tempRoot!)).toBe(false); }); +test('reports an expired deadline when no screenshot pair is stable', async () => { + let captureCount = 0; + + const stable = await waitForMaestroAnimationToEnd({ + timeoutMs: 0, + now: () => 0, + capture: async (screenshotPath) => { + await fs.writeFile( + screenshotPath, + makePng(1, 1, [[0, captureCount++ % 2 === 0 ? 0 : 255, 0, 0]]), + ); + }, + }); + + expect(stable).toBe(false); + expect(captureCount).toBe(2); +}); + test('propagates cancellation and cleans temporary screenshots', async () => { const controller = new AbortController(); let captureCount = 0; diff --git a/src/compat/maestro/daemon-runtime-port-observation.ts b/src/compat/maestro/daemon-runtime-port-observation.ts index ea996e8ad8..1a9d666412 100644 --- a/src/compat/maestro/daemon-runtime-port-observation.ts +++ b/src/compat/maestro/daemon-runtime-port-observation.ts @@ -42,6 +42,7 @@ export type MaestroSnapshotSource = { readonly readMetrics: () => Pick; readonly invalidate: (generation: number) => void; readonly requireStability: (generation: number) => void; + readonly consumeStabilityFromVisualWait: (context: MaestroRuntimeReadContext) => void; readonly prime: (generation: number, snapshot: SnapshotState) => void; readonly settlePending: (context: MaestroRuntimeReadContext) => Promise; }; diff --git a/src/compat/maestro/daemon-runtime-port-snapshot-source.ts b/src/compat/maestro/daemon-runtime-port-snapshot-source.ts index b156e00640..e2ac0ba1d0 100644 --- a/src/compat/maestro/daemon-runtime-port-snapshot-source.ts +++ b/src/compat/maestro/daemon-runtime-port-snapshot-source.ts @@ -81,6 +81,19 @@ export function createDaemonMaestroSnapshotSource( invalidatedBaseline = undefined; primed = undefined; }, + consumeStabilityFromVisualWait: (context) => { + if (stabilityRequiredGeneration === undefined) return; + if (stabilityRequiredGeneration !== context.generation) { + throw new AppError( + 'COMMAND_FAILED', + `Maestro stability generation ${stabilityRequiredGeneration} does not match ${context.generation}.`, + ); + } + stabilityRequiredGeneration = undefined; + stabilityBaseline = undefined; + invalidatedBaseline = undefined; + primed = undefined; + }, prime: (generation, snapshot) => { primed = { generation, snapshot }; }, diff --git a/src/compat/maestro/daemon-runtime-port.ts b/src/compat/maestro/daemon-runtime-port.ts index 1e8c68e274..01cb68224c 100644 --- a/src/compat/maestro/daemon-runtime-port.ts +++ b/src/compat/maestro/daemon-runtime-port.ts @@ -284,7 +284,7 @@ function createDaemonMaestroRuntimeParts(options: CreateDaemonMaestroRuntimeOper await invokeMutation({ kind: 'pressKey', key: 'dismiss' }, context, 'deferred'); }, waitForAnimationToEnd: async (input, context) => { - await waitForMaestroAnimationToEnd({ + const visualStabilityReached = await waitForMaestroAnimationToEnd({ timeoutMs: input.timeoutMs ?? MAESTRO_COMPATIBILITY_PRESETS.command.waitForAnimationToEndTimeoutMs, now: options.dependencies.now, @@ -298,6 +298,7 @@ function createDaemonMaestroRuntimeParts(options: CreateDaemonMaestroRuntimeOper }); }, }); + return { visualStabilityReached }; }, takeScreenshot: async (input) => ({ artifactPaths: artifactPathsFromData(await invoke({ kind: 'screenshot', path: input.path })), @@ -373,10 +374,17 @@ export function createDaemonMaestroRuntimePort( const { operations, snapshots, readMetrics } = createDaemonMaestroRuntimeParts(options); return { execute: async (request: MaestroRuntimeRequest): Promise => { - if (maestroCommandRequiresSettledPredecessor(request.command)) { - await snapshots.settlePending(operationContext(request, request.command)); + const context = operationContext(request, request.command); + const visualStabilityBarrier = request.command.kind === 'waitForAnimationToEnd'; + if (maestroCommandRequiresSettledPredecessor(request.command) && !visualStabilityBarrier) { + await snapshots.settlePending(context); } - return await executeMaestroRuntimeCommand(request, operations); + const result = await executeMaestroRuntimeCommand(request, operations); + if (visualStabilityBarrier && result.visualStabilityReached === true) { + snapshots.consumeStabilityFromVisualWait(context); + } + delete result.visualStabilityReached; + return result; }, observe: async (request) => { const observation = await observeMaestroCondition(request, operations); diff --git a/src/compat/maestro/engine-types.ts b/src/compat/maestro/engine-types.ts index c6dc26979c..2e3ad2ea5d 100644 --- a/src/compat/maestro/engine-types.ts +++ b/src/compat/maestro/engine-types.ts @@ -100,6 +100,8 @@ export type MaestroRuntimeResult = { artifactPaths?: string[]; /** Daemon response data for gesture/profile evidence in replay traces. */ data?: Record; + /** Internal completion evidence consumed before the result leaves the daemon runtime port. */ + visualStabilityReached?: boolean; }; export type MaestroRuntimeMetrics = { diff --git a/src/compat/maestro/runtime-port-commands.ts b/src/compat/maestro/runtime-port-commands.ts index 6ddfe7558e..35681ddf22 100644 --- a/src/compat/maestro/runtime-port-commands.ts +++ b/src/compat/maestro/runtime-port-commands.ts @@ -343,7 +343,7 @@ async function executeNavigationCommand( operations.waitForAnimationToEnd, waitForAnimationToEndInput(command), context, - 'invalidate', + 'preserve', ); } } @@ -437,6 +437,9 @@ function resultWithArtifacts( ...optionalOutputEnv(result?.outputEnv), ...optionalArtifactPaths(defaultArtifacts, result?.artifactPaths), ...optionalData(result?.data), + ...(result?.visualStabilityReached === undefined + ? {} + : { visualStabilityReached: result.visualStabilityReached }), }; } diff --git a/src/compat/maestro/runtime-port-types.ts b/src/compat/maestro/runtime-port-types.ts index 36a65fd987..50d1ef64f5 100644 --- a/src/compat/maestro/runtime-port-types.ts +++ b/src/compat/maestro/runtime-port-types.ts @@ -93,6 +93,8 @@ export type MaestroRuntimeOperationResult = { readonly artifactPaths?: readonly string[]; /** Daemon response data surfaced for replay-trace evidence. */ readonly data?: Record; + /** Internal completion evidence consumed by the daemon Maestro port. */ + readonly visualStabilityReached?: boolean; }; export type MaestroRuntimeOperation = ( diff --git a/src/compat/maestro/wait-for-animation-to-end.ts b/src/compat/maestro/wait-for-animation-to-end.ts index d8fc2daa8b..5dc191d8d7 100644 --- a/src/compat/maestro/wait-for-animation-to-end.ts +++ b/src/compat/maestro/wait-for-animation-to-end.ts @@ -20,18 +20,18 @@ export type MaestroAnimationWaitOptions = { */ export async function waitForMaestroAnimationToEnd( options: MaestroAnimationWaitOptions, -): Promise { +): Promise { validateTimeout(options.timeoutMs); throwIfMaestroScreenshotAborted(options.signal); const deadline = options.now() + options.timeoutMs; - await withMaestroScreenshotWorkspace('animation', async (tempRoot) => { + return await withMaestroScreenshotWorkspace('animation', async (tempRoot) => { const firstPath = path.join(tempRoot, 'first.png'); const secondPath = path.join(tempRoot, 'second.png'); while (true) { throwIfMaestroScreenshotAborted(options.signal); - if (await capturePairMatches(options, firstPath, secondPath)) return; - if (options.now() >= deadline) return; + if (await capturePairMatches(options, firstPath, secondPath)) return true; + if (options.now() >= deadline) return false; } }); }