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 @@ -24,14 +24,23 @@ const RECENTS = Buffer.concat([PNG_SIGNATURE, Buffer.from('recents-surface')]);
* runner under a step timeout: the capture would finish after `workMs`, but a forwarded
* `options.timeoutMs` kills it first and returns a failure without writing the image. The
* forwarded timeout of every screenshot call is recorded in `timeouts`.
*
* `staleForegroundReads` replays the observed Home race: the first that many `appstate` reads
* after `home` still name the fixture, the way a read taken while the launcher is being resumed
* does. `Infinity` is a foreground that never leaves the fixture.
*/
function scriptedDevice(options: { script: Record<string, Buffer[]>; workMs: number }): {
function scriptedDevice(options: {
script: Record<string, Buffer[]>;
workMs: number;
staleForegroundReads?: number;
}): {
runCli: LiveRunCli;
timeouts: Record<string, (number | undefined)[]>;
} {
const attempts = new Map<string, number>();
const timeouts: Record<string, (number | undefined)[]> = {};
let foregroundPackage = APP_ID;
let staleForegroundReads = options.staleForegroundReads ?? 0;
const runCli: LiveRunCli = (args, _env, cliOptions): Promise<CliJsonResult> => {
const command = args[0];
if (command === 'home') {
Expand All @@ -53,11 +62,13 @@ function scriptedDevice(options: { script: Record<string, Buffer[]>; workMs: num
});
}
if (command === 'appstate') {
const reported = staleForegroundReads > 0 ? APP_ID : foregroundPackage;
if (staleForegroundReads > 0) staleForegroundReads -= 1;
return Promise.resolve({
status: 0,
stdout: '',
stderr: '',
json: { success: true, data: { package: foregroundPackage } },
json: { success: true, data: { package: reported } },
});
}
if (command === 'screenshot') {
Expand Down Expand Up @@ -238,6 +249,64 @@ test('a wedged capture is cut at the forwarded remaining timeout and the scenari
).toBeGreaterThanOrEqual(homeTimeouts.length);
});

test('the scenario passes while Home keeps the foreground stale for the first reads', async () => {
// The hosted race: `home` answers, and every appstate read taken while WindowManager resumes the
// launcher still names the fixture. One read (the pre-fix route) fails; the wait rides it out.
const device = scriptedDevice({
script: {
'foreground.png': [FOREGROUND],
'home.png': [HOME],
'recents.png': [RECENTS],
},
workMs: 100,
staleForegroundReads: 3,
});
const { context, promise } = runScenarioWithDevice(device);
const result = await settle(promise);

expect(result.status).toBe('fulfilled');
const foregroundReads = context.stepHistory.filter(
(record) => record.commandName === 'appstate' && record.step.startsWith('read Android Home'),
);
expect(foregroundReads.map((record) => record.step)).toEqual([
'read Android Home foreground state (attempt 1)',
'read Android Home foreground state (attempt 2)',
'read Android Home foreground state (attempt 3)',
'read Android Home foreground state (attempt 4)',
]);
expect(context.completedScenarios).toContain('smoke:home-recents-restoration');
});

test('the scenario fails at the deadline when Home never moves the foreground', async () => {
const device = scriptedDevice({
script: {
'foreground.png': [FOREGROUND],
'home.png': [HOME],
'recents.png': [RECENTS],
},
workMs: 100,
staleForegroundReads: Number.POSITIVE_INFINITY,
});
const { context, promise } = runScenarioWithDevice(device);
const result = await settle(promise);

expect(result).toMatchObject({
status: 'rejected',
reason: {
message: expect.stringMatching(
/Android Home never moved the foreground off the fixture package within 30000ms.*foreground read \d+ still reported com\.callstack\.agentdevicelab/s,
),
},
});
// The verdict is the foreground wait's: no Home-surface capture is ever attempted, so the lane
// cannot proceed to pixel comparisons on a foreground the device never confirmed.
expect(
context.stepHistory.filter(
(record) => record.commandName === 'screenshot' && record.step.includes('Home surface'),
),
).toHaveLength(0);
});

test('the scenario fails when Recents never differs from the Home surface', async () => {
const device = scriptedDevice({
script: { 'foreground.png': [FOREGROUND], 'home.png': [HOME], 'recents.png': [HOME] },
Expand Down
13 changes: 10 additions & 3 deletions test/integration/android-emulator-e2e/live-automation-scenario.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import {
} from './live-harness.ts';
import { assertHumanSnapshotCompaction } from './live-snapshot-compaction.ts';
import { waitForSnapshotDiffLines } from './live-snapshot-transition.ts';
import { waitForSurfaceChange } from './live-surface-transition.ts';
import { waitForForegroundLeaves, waitForSurfaceChange } from './live-surface-transition.ts';

const C = PUBLIC_COMMANDS;

Expand Down Expand Up @@ -279,8 +279,15 @@ async function assertHomeAndRecentsRestoration(
const foreground = path.join(context.artifactDir, 'foreground.png');
await capturePng(context, 'capture Android fixture foreground', foreground);
await runStep(context, 'send Android fixture Home', ['home']);
const homeState = await runStep(context, 'read Android Home foreground state', ['appstate']);
assert.notEqual(homeState.json?.data?.package, context.appId, JSON.stringify(homeState.json));
// Home injects one keyevent and answers before WindowManager resumes the launcher, so the first
// appstate read can still name the fixture. The foreground must leave it before pixels are read.
await waitForForegroundLeaves(
context,
runStep,
context.appId,
'read Android Home foreground state',
'Android Home never moved the foreground off the fixture package',
);
const home = path.join(context.artifactDir, 'home.png');
// Home is dispatched before the launcher has drawn, so one capture can still show the fixture.
await waitForSurfaceChange(
Expand Down
181 changes: 179 additions & 2 deletions test/integration/android-emulator-e2e/live-surface-transition.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,14 @@ import { afterEach, beforeEach, expect, test, vi } from 'vitest';

import { mkdtempForTestSync } from '@agent-device/test-kit';

import type { LiveContext } from './live-harness.ts';
import { type SurfaceCapture, waitForSurfaceChange } from './live-surface-transition.ts';
import type { CliJsonResult } from '../cli-json.ts';
import type { AndroidLiveHarness, LiveContext } from './live-harness.ts';
import {
type ForegroundRead,
type SurfaceCapture,
waitForForegroundLeaves,
waitForSurfaceChange,
} from './live-surface-transition.ts';

const CONTEXT = {} as LiveContext;

Expand Down Expand Up @@ -195,3 +201,174 @@ test('a capture that resolves after the deadline is rejected as a late observati
// The final observed image is still kept, even when it arrives late.
expect(fs.readFileSync(outputPath).equals(HOME_SURFACE)).toBe(true);
});

const FIXTURE_PACKAGE = 'com.callstack.agentdevicelab';
const LAUNCHER_PACKAGE = 'com.google.android.apps.nexuslauncher';

type ForegroundStep = { step: string; args: string[]; timeoutMs: number | undefined };

/** A scripted `runStep` answering `appstate` with one package per attempt; an Error is thrown. */
function scriptedForegroundRun(script: (string | Error | undefined)[]): {
runStep: AndroidLiveHarness['runStep'];
steps: ForegroundStep[];
} {
const steps: ForegroundStep[] = [];
const runStep = (
_context: LiveContext,
step: string,
args: string[],
options: { timeoutMs?: number } = {},
) => {
steps.push({ step, args, timeoutMs: options.timeoutMs });
const answer = script[Math.min(steps.length - 1, script.length - 1)]!;
if (answer instanceof Error) return Promise.reject(answer);
return Promise.resolve({
status: 0,
stdout: '',
stderr: '',
json: { success: true, data: answer === undefined ? {} : { package: answer } },
});
};
return { runStep, steps };
}

test('the foreground wait reports the first package that left the expected one', async () => {
const { runStep, steps } = scriptedForegroundRun([
FIXTURE_PACKAGE,
FIXTURE_PACKAGE,
LAUNCHER_PACKAGE,
]);
const settled = await settle(
waitForForegroundLeaves(
CONTEXT,
runStep,
FIXTURE_PACKAGE,
'read foreground state',
'foreground never left the fixture',
),
);

expect(settled.status).toBe('fulfilled');
if (settled.status === 'fulfilled') expect(settled.value).toBe(LAUNCHER_PACKAGE);
expect(steps.map((record) => record.step)).toEqual([
'read foreground state (attempt 1)',
'read foreground state (attempt 2)',
'read foreground state (attempt 3)',
]);
// Each read asks for the foreground package through one bounded appstate step.
for (const record of steps) {
expect(record.args).toEqual(['appstate']);
expect(typeof record.timeoutMs).toBe('number');
expect(record.timeoutMs).toBeGreaterThan(0);
expect(record.timeoutMs).toBeLessThanOrEqual(5_000);
}
});

test('the foreground wait fails at the deadline when the package never changes', async () => {
const { runStep, steps } = scriptedForegroundRun([FIXTURE_PACKAGE]);
const settled = await settle(
waitForForegroundLeaves(
CONTEXT,
runStep,
FIXTURE_PACKAGE,
'read foreground state',
'foreground never left the fixture',
),
);

expect(settled).toMatchObject({
status: 'rejected',
reason: {
message: expect.stringMatching(
/foreground never left the fixture within 30000ms.*foreground read \d+ still reported com\.callstack\.agentdevicelab/s,
),
},
});
// Reads run to the deadline, and the last one is still bounded by the time it has left.
expect(steps.length).toBeGreaterThan(1);
expect(Math.min(...steps.map((record) => record.timeoutMs!))).toBeLessThan(5_000);
});

/** A `runStep` for a wait driven by an injected `read`; any call to it is reported as a failure. */
function unusedRunStep(): { runStep: AndroidLiveHarness['runStep']; calls: string[] } {
const calls: string[] = [];
const runStep = (_context: LiveContext, step: string): Promise<CliJsonResult> => {
calls.push(step);
return Promise.reject(new Error(`runStep should not run: ${step}`));
};
return { runStep: runStep as AndroidLiveHarness['runStep'], calls };
}

test('the foreground wait retries a failed read and reports it at the deadline', async () => {
const unused = unusedRunStep();
const read: ForegroundRead = () => Promise.reject(new Error('appstate: device offline'));
const settled = await settle(
waitForForegroundLeaves(
CONTEXT,
unused.runStep,
FIXTURE_PACKAGE,
'read foreground state',
'foreground never left the fixture',
{ read },
),
);

expect(settled).toMatchObject({
status: 'rejected',
reason: {
message: expect.stringMatching(
/foreground never left the fixture within 30000ms.*device offline/s,
),
},
});
expect(unused.calls).toEqual([]);
});

test('a read that answers no package is retried and reported at the deadline', async () => {
const { runStep } = scriptedForegroundRun([undefined]);
const settled = await settle(
waitForForegroundLeaves(
CONTEXT,
runStep,
FIXTURE_PACKAGE,
'read foreground state',
'foreground never left the fixture',
),
);

expect(settled).toMatchObject({
status: 'rejected',
reason: {
message: expect.stringMatching(
/foreground never left the fixture within 30000ms.*foreground read \d+ reported no package/s,
),
},
});
});

test('a read that resolves after the deadline is a late observation', async () => {
const unused = unusedRunStep();
const read: ForegroundRead = async (_attempt, remainingMs) => {
await new Promise((resolve) => setTimeout(resolve, remainingMs + 500));
return LAUNCHER_PACKAGE;
};
const settled = await settle(
waitForForegroundLeaves(
CONTEXT,
unused.runStep,
FIXTURE_PACKAGE,
'read foreground state',
'foreground never left the fixture',
{ read },
),
);

expect(settled).toMatchObject({
status: 'rejected',
reason: {
message: expect.stringMatching(
/foreground never left the fixture within 30000ms.*resolved after the deadline/s,
),
},
});
});
Loading
Loading