diff --git a/test/integration/android-emulator-e2e/live-automation-scenario.test.ts b/test/integration/android-emulator-e2e/live-automation-scenario.test.ts index a22f7c85b9..cc700b44b4 100644 --- a/test/integration/android-emulator-e2e/live-automation-scenario.test.ts +++ b/test/integration/android-emulator-e2e/live-automation-scenario.test.ts @@ -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; workMs: number }): { +function scriptedDevice(options: { + script: Record; + workMs: number; + staleForegroundReads?: number; +}): { runCli: LiveRunCli; timeouts: Record; } { const attempts = new Map(); const timeouts: Record = {}; let foregroundPackage = APP_ID; + let staleForegroundReads = options.staleForegroundReads ?? 0; const runCli: LiveRunCli = (args, _env, cliOptions): Promise => { const command = args[0]; if (command === 'home') { @@ -53,11 +62,13 @@ function scriptedDevice(options: { script: Record; 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') { @@ -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] }, diff --git a/test/integration/android-emulator-e2e/live-automation-scenario.ts b/test/integration/android-emulator-e2e/live-automation-scenario.ts index 477b522827..a99b85d96f 100644 --- a/test/integration/android-emulator-e2e/live-automation-scenario.ts +++ b/test/integration/android-emulator-e2e/live-automation-scenario.ts @@ -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; @@ -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( diff --git a/test/integration/android-emulator-e2e/live-surface-transition.test.ts b/test/integration/android-emulator-e2e/live-surface-transition.test.ts index 5962d185ce..9a5afeee19 100644 --- a/test/integration/android-emulator-e2e/live-surface-transition.test.ts +++ b/test/integration/android-emulator-e2e/live-surface-transition.test.ts @@ -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; @@ -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 => { + 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, + ), + }, + }); +}); diff --git a/test/integration/android-emulator-e2e/live-surface-transition.ts b/test/integration/android-emulator-e2e/live-surface-transition.ts index 4174b94694..d0ccdbd666 100644 --- a/test/integration/android-emulator-e2e/live-surface-transition.ts +++ b/test/integration/android-emulator-e2e/live-surface-transition.ts @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; import { capturePng as defaultPngCapture, filesDiffer } from './live-assertions.ts'; -import type { LiveContext } from './live-harness.ts'; +import type { AndroidLiveHarness, LiveContext } from './live-harness.ts'; import type { RunStepOptions } from '../live-device-e2e/runtime.ts'; // One launcher capture took 6.7 s on a hosted emulator, and 8.0 s behind an abandoned one: a @@ -12,6 +12,12 @@ const SURFACE_CAPTURE_TIMEOUT_MS = 15_000; const SURFACE_TRANSITION_TIMEOUT_MS = 2 * SURFACE_CAPTURE_TIMEOUT_MS; const SURFACE_TRANSITION_POLL_MS = 250; +// Every hosted foreground read after Home answered in 193–443 ms and still named the fixture, +// while the launcher was resumed about 1.5 s after the keyevent. The wait shares the surface +// transition's deadline so a foreground verdict can never arrive before a pixel verdict would; +// one read is capped well below it because an `appstate` read is a dumpsys, not a capture. +const FOREGROUND_READ_TIMEOUT_MS = 5_000; + /** A PNG capture step: `screenshot --scale 0.5` with harness step options. */ export type PngCapture = ( context: LiveContext, @@ -105,3 +111,65 @@ function defaultCapture( timeoutMs: Math.min(remainingMs, SURFACE_CAPTURE_TIMEOUT_MS), }); } + +/** + * Reads one `appstate` foreground answer and returns its foreground package, or `undefined` when + * the read answered nothing. Only a package the device actually names is reported. + */ +export type ForegroundRead = (attempt: number, remainingMs: number) => Promise; + +/** + * Waits until the device's reported foreground package leaves `expectedPackage`, and returns the + * first different answer. `home` injects one keyevent and answers when the injection lands, before + * WindowManager has resumed the launcher: every hosted failure read the fixture 90–530 ms after + * the command finished while the launcher was resumed about 1.5 s after it. Each read is bounded + * below the wait's deadline, a read that resolves after the deadline is rejected as a late + * observation, and the wait fails at the deadline with the last observation if the foreground + * never leaves the package. + */ +export async function waitForForegroundLeaves( + context: LiveContext, + runStep: AndroidLiveHarness['runStep'], + expectedPackage: string, + readStep: string, + failure: string, + options: { read?: ForegroundRead } = {}, +): Promise { + const read: ForegroundRead = + options.read ?? + (async (attempt, remainingMs) => { + const result = await runStep(context, `${readStep} (attempt ${attempt})`, ['appstate'], { + allowFailure: true, + timeoutMs: Math.min(remainingMs, FOREGROUND_READ_TIMEOUT_MS), + }); + const packageName: unknown = result.json?.data?.package; + return typeof packageName === 'string' && packageName.length > 0 ? packageName : undefined; + }); + const deadline = Date.now() + SURFACE_TRANSITION_TIMEOUT_MS; + let lastObservation = 'no foreground read finished'; + let attempt = 0; + for ( + let remaining = SURFACE_TRANSITION_TIMEOUT_MS; + remaining > 0; + remaining = deadline - Date.now() + ) { + attempt += 1; + try { + const packageName = await read(attempt, remaining); + if (Date.now() >= deadline) { + lastObservation = `foreground read ${attempt} resolved after the deadline`; + } else if (packageName === undefined) { + lastObservation = `foreground read ${attempt} reported no package`; + } else if (packageName !== expectedPackage) { + return packageName; + } else { + lastObservation = `foreground read ${attempt} still reported ${packageName}`; + } + } catch (error) { + lastObservation = `foreground read ${attempt} failed: ${error instanceof Error ? error.message : String(error)}`; + } + const pause = Math.min(SURFACE_TRANSITION_POLL_MS, deadline - Date.now()); + if (pause > 0) await new Promise((resolve) => setTimeout(resolve, pause)); + } + assert.fail(`${failure} within ${SURFACE_TRANSITION_TIMEOUT_MS}ms (${lastObservation})`); +}