diff --git a/packages/command-surface/src/management/app.ts b/packages/command-surface/src/management/app.ts index 77bba7d068..bbfdabbac0 100644 --- a/packages/command-surface/src/management/app.ts +++ b/packages/command-surface/src/management/app.ts @@ -95,7 +95,7 @@ const openCommandMetadata = defineFieldCommandMetadata( const closeCommandMetadata = defineFieldCommandMetadata( 'close', - 'Close the named app, or close the active session app when app is omitted. The shutdown option also stops the session simulator or emulator where supported; close alone never stops the device. Android ADB close fails with android-app-close-timeout if the app stays foreground past 2s, a killed process does not exit within 10s, or a new process runs past 2s; a relaunching open accepts that new process. It fails with android-process-probe-unavailable when adb pidof cannot list the app processes; if that happens before the force-stop, the app keeps running. If close cannot confirm its cleanup on a session that holds a device claim, the session and its claim stay. A repeated close retries cleanup with the same options, except that save-script must be omitted after publication.', + 'Close the named app, or close the active session app when app is omitted. The shutdown option also stops the session simulator or emulator where supported; close alone never stops the device. Android ADB close fails with android-app-close-timeout if the app stays foreground past 2s or a killed process does not exit within 10s; a new process that Android starts afterwards does not fail it. It fails with android-process-probe-unavailable when adb pidof cannot list the app processes; if that happens before the force-stop, the app keeps running. If close cannot confirm its cleanup on a session that holds a device claim, the session and its claim stay. A repeated close retries cleanup with the same options, except that save-script must be omitted after publication.', { app: stringField('Optional app to close.'), shutdown: booleanField('Shutdown the session/device where supported.'), diff --git a/packages/platform-android/src/__tests__/app-lifecycle-close.test.ts b/packages/platform-android/src/__tests__/app-lifecycle-close.test.ts index 4671aa6c9a..6d62e34d20 100644 --- a/packages/platform-android/src/__tests__/app-lifecycle-close.test.ts +++ b/packages/platform-android/src/__tests__/app-lifecycle-close.test.ts @@ -50,8 +50,7 @@ test('closeAndroidApp waits until package is no longer foreground', async () => ['shell', 'am', 'force-stop', 'com.example.app'], ['shell', 'dumpsys', 'window', 'windows'], ['shell', 'dumpsys', 'window', 'windows'], - ['shell', 'pidof', 'com.example.app'], - ['shell', 'pidof', 'com.example.app'], + ['shell', 'dumpsys', 'window', 'windows'], ]); }); @@ -92,8 +91,7 @@ test('closeAndroidApp returns after force-stop when package is already not foreg ['shell', 'pidof', 'com.example.app'], ['shell', 'am', 'force-stop', 'com.example.app'], ['shell', 'dumpsys', 'window', 'windows'], - ['shell', 'pidof', 'com.example.app'], - ['shell', 'pidof', 'com.example.app'], + ['shell', 'dumpsys', 'window', 'windows'], ]); }); @@ -142,12 +140,11 @@ test('closeAndroidApp waits until package process exits after force-stop', async ['shell', 'dumpsys', 'window', 'windows'], ['shell', 'pidof', 'com.example.app'], ['shell', 'pidof', 'com.example.app'], - ['shell', 'pidof', 'com.example.app'], - ['shell', 'pidof', 'com.example.app'], + ['shell', 'dumpsys', 'window', 'windows'], ]); }); -test('closeAndroidApp waits past the process fence for a killed process that exits slowly', async () => { +test('closeAndroidApp waits past 2s for a killed process that exits slowly', async () => { vi.useFakeTimers(); vi.setSystemTime(0); try { @@ -184,7 +181,6 @@ test('closeAndroidApp waits past the process fence for a killed process that exi test.each([ ['foreground', 2_000, 1], ['exit', 10_000, 201], - ['process', 2_000, 42], ] as const)( 'closeAndroidApp refuses an exhausted %s fence', async (phase, timeoutMs, pidofCalls) => { @@ -195,10 +191,12 @@ test.each([ { exec: async (args) => { calls.push(args); - const killed = calls.filter((call) => call[1] === 'am').length === 0; + const stopped = calls.some((call) => call[1] === 'am'); const stdout = args[1] === 'pidof' - ? `${killed || phase !== 'process' ? '12345' : '67890'}\n` + ? phase === 'exit' || !stopped + ? '12345\n' + : '' : args[1] === 'dumpsys' ? `mCurrentFocus=Window{42 u0 ${phase === 'foreground' ? 'com.example.app/.MainActivity' : 'com.android.launcher/.Launcher'}}\n` : ''; @@ -233,31 +231,19 @@ test.each([ ); test.each([ - ['foreground', 1, 1_999, true, 3], - ['foreground', 1, 2_000, false, 1], - ['foreground', 1, 2_001, false, 1], - ['process', 1, 1_849, true, 3], - ['process', 1, 1_850, false, 2], - ['process', 1, 2_000, false, 2], - ['process', 1, 2_001, false, 2], - ['process', 2, 1_999, true, 3], - ['process', 2, 2_000, false, 3], - ['process', 2, 2_001, false, 3], + [1_999, true], + [2_000, false], + [2_001, false], ] as const)( - 'closeAndroidApp admits %s probe %i completing at %ims only within its fence (success=%s)', - async (phase, probe, completionMs, succeeds, expectedProcessPolls) => { + 'closeAndroidApp admits a foreground probe completing at %ims only within its fence (success=%s)', + async (completionMs, succeeds) => { vi.useFakeTimers(); vi.setSystemTime(0); - let processPolls = 0; try { await withAndroidAdbProvider( { exec: async (args) => { - if (args[1] === 'pidof') processPolls += 1; - if ( - (phase === 'foreground' && args[1] === 'dumpsys') || - (phase === 'process' && args[1] === 'pidof' && processPolls === probe + 1) - ) { + if (args[1] === 'dumpsys') { await new Promise((resolve) => setTimeout(resolve, completionMs - Date.now())); } return { @@ -280,7 +266,7 @@ test.each([ assert.equal(error.code, 'COMMAND_FAILED'); assert.deepEqual(error.details, { reason: 'android-app-close-timeout', - phase, + phase: 'foreground', packageName: 'com.example.app', timeoutMs: 2_000, }); @@ -289,7 +275,6 @@ test.each([ await Promise.all([result, vi.runAllTimersAsync()]); }, ); - assert.equal(processPolls, expectedProcessPolls); } finally { vi.useRealTimers(); } @@ -365,7 +350,7 @@ test('openAndroidApp relaunches a package that Android restarts right after the }); test.each([ - [9_999, true, 4], + [9_999, true, 2], [10_000, false, 2], [10_001, false, 2], ] as const)( @@ -420,7 +405,7 @@ test.each([ }, ); -test('closeAndroidApp refuses a new process that outlives the killed one', async () => { +test('closeAndroidApp accepts a new process once the killed ones have exited', async () => { vi.useFakeTimers(); vi.setSystemTime(0); const calls: (readonly string[])[] = []; @@ -429,8 +414,10 @@ test('closeAndroidApp refuses a new process that outlives the killed one', async { exec: async (args) => { calls.push(args); - const killed = calls.some((call) => call[1] === 'am'); - const pids = !killed ? '12345' : Date.now() < 500 ? '12345 67890' : '67890'; + // Android starts a new Settings process (67890) for a background client after the stop and + // keeps it, while the process that ran before the close (12345) exits within 500ms. + const stopped = calls.some((call) => call[1] === 'am'); + const pids = !stopped ? '12345' : Date.now() < 500 ? '12345 67890' : '67890'; return { stdout: args[1] === 'dumpsys' @@ -444,13 +431,51 @@ test('closeAndroidApp refuses a new process that outlives the killed one', async }, }, { serial: ANDROID_EMULATOR.id }, + async () => { + await Promise.all([ + closeAndroidApp(ANDROID_EMULATOR, 'com.example.app'), + vi.runAllTimersAsync(), + ]); + }, + ); + assert.equal(calls.at(-1)?.[1], 'dumpsys', 'the foreground check ran last'); + assert.ok(Date.now() < 2_000, 'a new process is not waited out'); + } finally { + vi.useRealTimers(); + } +}); + +test('closeAndroidApp refuses a new process that is foreground once the killed ones have exited', async () => { + vi.useFakeTimers(); + vi.setSystemTime(0); + try { + await withAndroidAdbProvider( + { + exec: async (args) => { + const focus = + Date.now() < 100 ? 'com.android.launcher/.Launcher' : 'com.example.app/.MainActivity'; + return { + stdout: + args[1] === 'dumpsys' + ? `mCurrentFocus=Window{43 u0 ${focus}}\n` + : args[1] === 'pidof' + ? Date.now() < 100 + ? '12345\n' + : '67890\n' + : '', + stderr: '', + exitCode: 0, + }; + }, + }, + { serial: ANDROID_EMULATOR.id }, async () => { const rejection = assert.rejects( closeAndroidApp(ANDROID_EMULATOR, 'com.example.app'), (error: unknown) => error instanceof AppError && error.details?.reason === 'android-app-close-timeout' && - error.details?.phase === 'process', + error.details?.phase === 'foreground', ); await Promise.all([rejection, vi.runAllTimersAsync()]); }, diff --git a/packages/platform-android/src/app-lifecycle.ts b/packages/platform-android/src/app-lifecycle.ts index fb959c6049..9976a09ef6 100644 --- a/packages/platform-android/src/app-lifecycle.ts +++ b/packages/platform-android/src/app-lifecycle.ts @@ -220,7 +220,7 @@ async function startAndroidApp( if (resolved.type === 'intent') { return await openAndroidIntent(device, resolved.value, options); } - if (options.terminateRunningApp) await stopAndroidPackageForRelaunch(device, resolved.value); + if (options.terminateRunningApp) await stopAndroidPackage(device, resolved.value); if (activity) { return await openAndroidPackageActivity( device, @@ -357,7 +357,7 @@ async function openAndroidAppBoundDeepLink( } await ensureAndroidLocalhostReverse(device, deepLinkUrl); const resolved = await requireAndroidPackageForOpen(device, app, 'app-bound open'); - if (options.terminateRunningApp) await stopAndroidPackageForRelaunch(device, resolved); + if (options.terminateRunningApp) await stopAndroidPackage(device, resolved); return await runAndroidShell(device, [ 'am', 'start', @@ -619,28 +619,6 @@ export async function closeAndroidApp(device: DeviceInfo, app: string): Promise< await stopAndroidPackage(device, await resolveAndroidPackageToEnd(device, app, 'Close')); } -async function stopAndroidPackageForRelaunch( - device: DeviceInfo, - packageName: string, -): Promise { - await stopAndroidPackage(device, packageName).catch((error: unknown) => { - if (!passedAndroidRelaunchStopFences(error)) throw error; - }); -} - -/** - * A close refused only by its process fence, which runs after the foreground and exit fences passed. - * That is all a relaunch needs: the processes that ran before the stop are gone, and Android can - * restart a package at once for a provider or broadcast client (Settings on Android 17). - */ -export function passedAndroidRelaunchStopFences(error: unknown): boolean { - return ( - error instanceof AppError && - error.details?.reason === 'android-app-close-timeout' && - error.details.phase === 'process' - ); -} - async function resolveAndroidPackageToEnd( device: DeviceInfo, app: string, @@ -719,11 +697,13 @@ function androidPidofUnavailableError(packageName: string): AppError { }); } -type AndroidStopFencePhase = 'foreground' | 'exit' | 'process'; +type AndroidStopFencePhase = 'foreground' | 'exit'; /** * The fence that expired before the package stopped, or undefined once it stopped. `killed` holds - * the pids that ran before `am force-stop`; any other pid afterwards is a new process. + * the pids that ran before `am force-stop`. The package has stopped once none of them runs and the + * package is not foreground. A new pid that is not foreground is a process Android started on its + * own, for a provider or broadcast client (Settings on Android 17), not the app the close ended. */ async function waitForAndroidPackageStopped( device: DeviceInfo, @@ -732,7 +712,8 @@ async function waitForAndroidPackageStopped( ): Promise { if (!(await waitForAndroidPackageNotForeground(device, packageName))) return 'foreground'; if (!(await waitForAndroidKilledProcessesExit(device, packageName, killed))) return 'exit'; - if (!(await waitForAndroidPackageProcessGone(device, packageName))) return 'process'; + // Read again last: a relaunch that is on screen once the killed processes exit still fails. + if (!(await waitForAndroidPackageNotForeground(device, packageName))) return 'foreground'; return undefined; } @@ -748,10 +729,6 @@ const ANDROID_CLOSE_TIMEOUTS: Record< message: 'process that ran before close did not exit', timeoutMs: ANDROID_CLOSE_KILLED_EXIT_TIMEOUT_MS, }, - process: { - message: 'process remained running after close', - timeoutMs: ANDROID_CLOSE_PROCESS_TIMEOUT_MS, - }, }; function androidCloseTimeoutError(packageName: string, phase: AndroidStopFencePhase): AppError { diff --git a/packages/platform-android/src/lifecycle.ts b/packages/platform-android/src/lifecycle.ts index 029288658a..a23016ae3d 100644 --- a/packages/platform-android/src/lifecycle.ts +++ b/packages/platform-android/src/lifecycle.ts @@ -115,9 +115,6 @@ async function openAndroidApplication( device: binding.device, interactor: await binding.resolveInteractor(input.execution, relaunchOwner), positionals: [relaunchOwner], - }).catch(async (error: unknown) => { - const { passedAndroidRelaunchStopFences } = await import('./app-lifecycle.ts'); - if (!passedAndroidRelaunchStopFences(error)) throw error; }); timing.relaunchCloseDurationMs = elapsed(closeStartedAtMs); } diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index bbe92401c3..73d6b90095 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -262,7 +262,7 @@ Exact behavior: `agent-device help close`. - iOS simulators: `open` prepares app accessibility before launching an app or URL. If an already-running app has an empty accessibility tree after an earlier XCTest session, run `open --relaunch`, then `snapshot -i`. Preparation failures are logged and do not block launch. Runner cleanup also restores app accessibility after confirmed termination; a runner started by a release before this change is not restored, so relaunch the app with `open --relaunch`. - Android React Native: `open --relaunch` needs an installed package name. Install or reinstall the APK first; `open --relaunch` is rejected. For Metro-backed JS changes, run `metro reload` before reaching for `open --relaunch`. - Android (adb): an intent target such as `open settings` records the package that opened as `appBundleId`. `open settings --relaunch` stops and restarts that app. If the intent matches more than one activity, `--relaunch` fails. -- Android (ADB): `close` force-stops the app, then checks for 2 seconds that it has left the foreground, waits up to 10 seconds for the processes it killed to exit, and checks for 2 more that no new process started. If a check window ends first, `close` fails with `details.reason: android-app-close-timeout` and `details.phase` set to `foreground`, `exit`, or `process`; a process that survives the force-stop fails with `exit`, and apps Android restarts at once, such as the launcher, fail with `process`. `open --relaunch` runs the same checks but accepts a new process once the killed ones exit, because Android can restart an app at once for a background client, such as Settings on Android 17. When `pidof` cannot list the app's processes, `close` fails with `details.reason: android-process-probe-unavailable`; if that happens before the force-stop, the app keeps running. +- Android (ADB): `close` force-stops the app, then checks for 2 seconds that it has left the foreground and waits up to 10 seconds for the processes it killed to exit. If a check window ends first, `close` fails with `details.reason: android-app-close-timeout` and `details.phase` set to `foreground` or `exit`; a process that survives the force-stop fails with `exit`. A new process that Android starts after the stop does not fail `close` or `open --relaunch`, because Android can restart an app at once for a background client, such as Settings on Android 17. When `pidof` cannot list the app's processes, `close` fails with `details.reason: android-process-probe-unavailable`; if that happens before the force-stop, the app keeps running. - When `close` cannot confirm its cleanup on a session that holds a device claim, it fails and keeps the session and its claim, so the device is not handed on unconfirmed. Run `close` again with the same options to retry the cleanup and release the device, leaving out `--save-script` once the first attempt has published the script. Only `close`, or a successful `open`, is supported on the kept session: other commands work, but the session stays marked, so an idle daemon can still shut it down. If nobody retries, the kept session does not keep the daemon alive: when the daemon has been idle for its idle timeout and shuts down, its shutdown retries the cleanup, and a claim it still cannot confirm goes stale instead of being released. Embedded runtimes and `AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS=0` never shut down for idleness, so there a retried `close` is the only release. - If `open --relaunch` leaves an existing session's device effects unconfirmed, the session and claim remain available for `close`, but idle shutdown can retry cleanup and leave an unconfirmed claim stale; embedded runtimes and `AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS=0` do not shut down for idleness, so use `close` to release the claim.