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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
6 changes: 4 additions & 2 deletions docs/adr/0015-direct-maestro-engine.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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',
);
});
86 changes: 84 additions & 2 deletions src/compat/maestro/__tests__/daemon-runtime-port.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {},
Expand All @@ -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 () => {
Expand Down Expand Up @@ -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',
]);
});
10 changes: 5 additions & 5 deletions src/compat/maestro/__tests__/runtime-port.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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([
Expand Down Expand Up @@ -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({
Expand All @@ -147,7 +147,7 @@ describe('MaestroRuntimePort', () => {
invalidateObservation: scriptInvalidation,
}),
).resolves.toEqual({});
expect(waitInvalidation).toHaveBeenCalledOnce();
expect(waitInvalidation).not.toHaveBeenCalled();
expect(scriptInvalidation).not.toHaveBeenCalled();
});

Expand Down
27 changes: 24 additions & 3 deletions src/compat/maestro/__tests__/wait-for-animation-to-end.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand All @@ -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);
});
Expand All @@ -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) => {
Expand All @@ -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);
});
Expand All @@ -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) => {
Expand All @@ -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;
Expand Down
1 change: 1 addition & 0 deletions src/compat/maestro/daemon-runtime-port-observation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export type MaestroSnapshotSource = {
readonly readMetrics: () => Pick<MaestroRuntimeMetrics, 'hierarchyCaptures'>;
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<void>;
};
Expand Down
13 changes: 13 additions & 0 deletions src/compat/maestro/daemon-runtime-port-snapshot-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
},
Expand Down
16 changes: 12 additions & 4 deletions src/compat/maestro/daemon-runtime-port.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -298,6 +298,7 @@ function createDaemonMaestroRuntimeParts(options: CreateDaemonMaestroRuntimeOper
});
},
});
return { visualStabilityReached };
},
takeScreenshot: async (input) => ({
artifactPaths: artifactPathsFromData(await invoke({ kind: 'screenshot', path: input.path })),
Expand Down Expand Up @@ -373,10 +374,17 @@ export function createDaemonMaestroRuntimePort(
const { operations, snapshots, readMetrics } = createDaemonMaestroRuntimeParts(options);
return {
execute: async (request: MaestroRuntimeRequest): Promise<MaestroRuntimeResult> => {
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);
Expand Down
2 changes: 2 additions & 0 deletions src/compat/maestro/engine-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ export type MaestroRuntimeResult = {
artifactPaths?: string[];
/** Daemon response data for gesture/profile evidence in replay traces. */
data?: Record<string, unknown>;
/** Internal completion evidence consumed before the result leaves the daemon runtime port. */
visualStabilityReached?: boolean;
};

export type MaestroRuntimeMetrics = {
Expand Down
Loading
Loading