From 7fff7a63ef92a8082ae48aa547466fa7c0c2686e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 12 Nov 2026 18:45:40 +0100 Subject: [PATCH 1/3] fix(android): let open --relaunch accept a package Android restarts at once On Android 17 a provider or broadcast client restarts Settings right after am force-stop, so the relaunch close fence saw a new process and refused with android-app-close-timeout (phase process). A relaunch needs only the processes that ran before the stop to exit; the launch that follows reuses the new one. close keeps refusing a restarted process. Fixes #4482 Co-Authored-By: Claude Opus 5.5 --- .../command-surface/src/management/app.ts | 2 +- .../src/__tests__/app-lifecycle-close.test.ts | 34 +++++++++++++++++++ .../platform-android/src/app-lifecycle.ts | 28 ++++++++++++--- .../platform-android/src/lifecycle.test.ts | 34 +++++++++++++++++++ packages/platform-android/src/lifecycle.ts | 3 ++ website/docs/docs/commands.md | 2 +- 6 files changed, 96 insertions(+), 7 deletions(-) diff --git a/packages/command-surface/src/management/app.ts b/packages/command-surface/src/management/app.ts index 90ac292b1f..8a1122d3fa 100644 --- a/packages/command-surface/src/management/app.ts +++ b/packages/command-surface/src/management/app.ts @@ -93,7 +93,7 @@ const openCommandMetadata = defineFieldCommandMetadata( const closeCommandMetadata = defineFieldCommandMetadata( 'close', - 'Close the named app, or close the active session app when app is omitted. If the session booted a local simulator or emulator, add shutdown when you finish, unless the user asks to keep it running; 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. 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; run close again with the same options to retry the cleanup, leaving out save-script once the script is published.', + 'Close the named app, or close the active session app when app is omitted. If the session booted a local simulator or emulator, add shutdown when you finish, unless the user asks to keep it running; 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; open --relaunch 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; run close again with the same options to retry the cleanup, leaving out save-script once the script is published.', { 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 1db9710c50..4671aa6c9a 100644 --- a/packages/platform-android/src/__tests__/app-lifecycle-close.test.ts +++ b/packages/platform-android/src/__tests__/app-lifecycle-close.test.ts @@ -330,6 +330,40 @@ test('openAndroidApp refuses to relaunch a package whose stop fence expires', as } }); +test('openAndroidApp relaunches a package that Android restarts right after the stop', async () => { + vi.useFakeTimers(); + const calls: (readonly string[])[] = []; + let pidofReads = 0; + try { + await withAndroidAdbProvider( + { + exec: async (args) => { + calls.push(args); + const stdout = + args[1] === 'pidof' + ? pidofReads++ === 0 + ? '12345\n' + : '67890\n' + : args[1] === 'dumpsys' + ? 'mCurrentFocus=Window{42 u0 com.android.launcher/.Launcher}\n' + : ''; + return { stdout, stderr: '', exitCode: 0 }; + }, + }, + { serial: ANDROID_EMULATOR.id }, + async () => { + await Promise.all([ + openAndroidApp(ANDROID_EMULATOR, 'com.example.app', { terminateRunningApp: true }), + vi.runAllTimersAsync(), + ]); + }, + ); + assert.equal(calls.filter((args) => args[2] === 'start').length, 1); + } finally { + vi.useRealTimers(); + } +}); + test.each([ [9_999, true, 4], [10_000, false, 2], diff --git a/packages/platform-android/src/app-lifecycle.ts b/packages/platform-android/src/app-lifecycle.ts index 62fce2c599..8c8601d50f 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 stopAndroidPackage(device, resolved.value); + if (options.terminateRunningApp) await stopAndroidPackage(device, resolved.value, 'relaunch'); 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 stopAndroidPackage(device, resolved); + if (options.terminateRunningApp) await stopAndroidPackage(device, resolved, 'relaunch'); return await runAndroidShell(device, [ 'am', 'start', @@ -616,7 +616,20 @@ export async function openAndroidDevice(device: DeviceInfo): Promise { } export async function closeAndroidApp(device: DeviceInfo, app: string): Promise { - await stopAndroidPackage(device, await resolveAndroidPackageToEnd(device, app, 'Close')); + await stopAndroidPackage(device, await resolveAndroidPackageToEnd(device, app, 'Close'), 'close'); +} + +/** + * A close that stopped every process that ran before it, but saw the package start again. A relaunch + * accepts this: Android can restart a package at once for a provider or broadcast client (Settings + * on Android 17), and the launch that follows reuses that new process. + */ +export function isAndroidPackageRestartedAfterClose(error: unknown): boolean { + return ( + error instanceof AppError && + error.details?.reason === 'android-app-close-timeout' && + error.details.phase === 'process' + ); } async function resolveAndroidPackageToEnd( @@ -632,7 +645,11 @@ async function resolveAndroidPackageToEnd( return resolved.value; } -async function stopAndroidPackage(device: DeviceInfo, packageName: string): Promise { +async function stopAndroidPackage( + device: DeviceInfo, + packageName: string, + purpose: 'close' | 'relaunch', +): Promise { const killed = await readAndroidPackagePids( device, packageName, @@ -643,7 +660,8 @@ async function stopAndroidPackage(device: DeviceInfo, packageName: string): Prom } await runAndroidShell(device, ['am', 'force-stop', packageName]); const expired = await waitForAndroidPackageStopped(device, packageName, killed); - if (expired) throw androidCloseTimeoutError(packageName, expired); + if (!expired || (purpose === 'relaunch' && expired === 'process')) return; + throw androidCloseTimeoutError(packageName, expired); } /** diff --git a/packages/platform-android/src/lifecycle.test.ts b/packages/platform-android/src/lifecycle.test.ts index 2584ad67cf..dc70a2b659 100644 --- a/packages/platform-android/src/lifecycle.test.ts +++ b/packages/platform-android/src/lifecycle.test.ts @@ -193,6 +193,40 @@ test('relaunch refuses to open or observe after the Android exit close fence exp expect(calls).toEqual(['close:com.example.app']); }); +test('relaunch opens after the stopped package restarts with a new process', async () => { + vi.useFakeTimers(); + bindAndroidAdbHostStub({}); + const { calls, lifecycle } = createLifecycle({ + close: async (app) => await closeAndroidApp(device, app), + }); + let pidofReads = 0; + await withAndroidAdbProvider( + { + exec: async (args) => ({ + stdout: + args[1] === 'pidof' + ? // The first read precedes am force-stop; Android restarts the package right after it. + pidofReads++ === 0 + ? '12345\n' + : '67890\n' + : args[1] === 'dumpsys' + ? 'mCurrentFocus=Window{43 u0 com.android.launcher/.Launcher}\n' + : '', + stderr: '', + exitCode: 0, + }), + }, + { serial: device.id }, + async () => { + await Promise.all([ + lifecycle.openApplication(openInput({ relaunch: true })), + vi.runAllTimersAsync(), + ]); + }, + ); + expect(calls.slice(0, 2)).toEqual(['close:com.example.app', 'open:com.example.app']); +}); + test('preserves a runtime launch URL duration after the admitted Android follow-up open', async () => { const { calls, lifecycle } = createLifecycle(); vi.spyOn(Date, 'now') diff --git a/packages/platform-android/src/lifecycle.ts b/packages/platform-android/src/lifecycle.ts index e3c8595784..4cd51b556c 100644 --- a/packages/platform-android/src/lifecycle.ts +++ b/packages/platform-android/src/lifecycle.ts @@ -116,6 +116,9 @@ async function openAndroidApplication( device: binding.device, interactor: await binding.resolveInteractor(input.execution, relaunchOwner), positionals: [relaunchOwner], + }).catch(async (error: unknown) => { + const { isAndroidPackageRestartedAfterClose } = await import('./app-lifecycle.ts'); + if (!isAndroidPackageRestartedAfterClose(error)) throw error; }); timing.relaunchCloseDurationMs = elapsed(closeStartedAtMs); } diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 034da43e81..2ae8e5892b 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -104,7 +104,7 @@ Open apps and links: - 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`. 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, 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. - 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. From 14c49027a6c8aa6f5210885e065e39daa4835674 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 12 Nov 2026 18:58:36 +0100 Subject: [PATCH 2/3] fix(android): skip the process fence on relaunch instead of reading its expiry Address review: a process-fence expiry can be a slow probe, not a proven restart. A relaunch needs only the foreground and exit fences, so the in-open stop no longer runs the process fence, and the owner close accepts a refusal from that fence alone. The close description no longer carries CLI syntax, which MCP tool descriptions reject. Co-Authored-By: Claude Opus 5.5 --- packages/command-surface/src/management/app.ts | 2 +- packages/platform-android/src/app-lifecycle.ts | 16 +++++++++------- packages/platform-android/src/lifecycle.ts | 4 ++-- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/packages/command-surface/src/management/app.ts b/packages/command-surface/src/management/app.ts index 8a1122d3fa..a6c35de193 100644 --- a/packages/command-surface/src/management/app.ts +++ b/packages/command-surface/src/management/app.ts @@ -93,7 +93,7 @@ const openCommandMetadata = defineFieldCommandMetadata( const closeCommandMetadata = defineFieldCommandMetadata( 'close', - 'Close the named app, or close the active session app when app is omitted. If the session booted a local simulator or emulator, add shutdown when you finish, unless the user asks to keep it running; 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; open --relaunch 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; run close again with the same options to retry the cleanup, leaving out save-script once the script is published.', + 'Close the named app, or close the active session app when app is omitted. If the session booted a local simulator or emulator, add shutdown when you finish, unless the user asks to keep it running; 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; run close again with the same options to retry the cleanup, leaving out save-script once the script is published.', { app: stringField('Optional app to close.'), shutdown: booleanField('Shutdown the session/device where supported.'), diff --git a/packages/platform-android/src/app-lifecycle.ts b/packages/platform-android/src/app-lifecycle.ts index 8c8601d50f..ec403c94bf 100644 --- a/packages/platform-android/src/app-lifecycle.ts +++ b/packages/platform-android/src/app-lifecycle.ts @@ -620,11 +620,11 @@ export async function closeAndroidApp(device: DeviceInfo, app: string): Promise< } /** - * A close that stopped every process that ran before it, but saw the package start again. A relaunch - * accepts this: Android can restart a package at once for a provider or broadcast client (Settings - * on Android 17), and the launch that follows reuses that new process. + * 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 isAndroidPackageRestartedAfterClose(error: unknown): boolean { +export function passedAndroidRelaunchStopFences(error: unknown): boolean { return ( error instanceof AppError && error.details?.reason === 'android-app-close-timeout' && @@ -659,9 +659,8 @@ async function stopAndroidPackage( throw androidPidofUnavailableError(packageName); } await runAndroidShell(device, ['am', 'force-stop', packageName]); - const expired = await waitForAndroidPackageStopped(device, packageName, killed); - if (!expired || (purpose === 'relaunch' && expired === 'process')) return; - throw androidCloseTimeoutError(packageName, expired); + const expired = await waitForAndroidPackageStopped(device, packageName, killed, purpose); + if (expired) throw androidCloseTimeoutError(packageName, expired); } /** @@ -725,9 +724,12 @@ async function waitForAndroidPackageStopped( device: DeviceInfo, packageName: string, killed: ReadonlySet, + purpose: 'close' | 'relaunch', ): Promise { if (!(await waitForAndroidPackageNotForeground(device, packageName))) return 'foreground'; if (!(await waitForAndroidKilledProcessesExit(device, packageName, killed))) return 'exit'; + // See passedAndroidRelaunchStopFences: a relaunch needs no process fence. + if (purpose === 'relaunch') return undefined; if (!(await waitForAndroidPackageProcessGone(device, packageName))) return 'process'; return undefined; } diff --git a/packages/platform-android/src/lifecycle.ts b/packages/platform-android/src/lifecycle.ts index 4cd51b556c..89cd085bff 100644 --- a/packages/platform-android/src/lifecycle.ts +++ b/packages/platform-android/src/lifecycle.ts @@ -117,8 +117,8 @@ async function openAndroidApplication( interactor: await binding.resolveInteractor(input.execution, relaunchOwner), positionals: [relaunchOwner], }).catch(async (error: unknown) => { - const { isAndroidPackageRestartedAfterClose } = await import('./app-lifecycle.ts'); - if (!isAndroidPackageRestartedAfterClose(error)) throw error; + const { passedAndroidRelaunchStopFences } = await import('./app-lifecycle.ts'); + if (!passedAndroidRelaunchStopFences(error)) throw error; }); timing.relaunchCloseDurationMs = elapsed(closeStartedAtMs); } From 753e5a2bd77172cc48b9ae67aea806c5e4038204 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 12 Nov 2026 21:40:31 +0100 Subject: [PATCH 3/3] refactor(android): one relaunch rule for both relaunch routes Address review: the in-open stops skipped the process fence through a purpose parameter while the owner close caught its refusal. Both routes now catch a refusal from the process fence alone through passedAndroidRelaunchStopFences. Co-Authored-By: Claude Opus 5.5 --- .../platform-android/src/app-lifecycle.ts | 26 ++++++++++--------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/packages/platform-android/src/app-lifecycle.ts b/packages/platform-android/src/app-lifecycle.ts index ec403c94bf..fb959c6049 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 stopAndroidPackage(device, resolved.value, 'relaunch'); + if (options.terminateRunningApp) await stopAndroidPackageForRelaunch(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 stopAndroidPackage(device, resolved, 'relaunch'); + if (options.terminateRunningApp) await stopAndroidPackageForRelaunch(device, resolved); return await runAndroidShell(device, [ 'am', 'start', @@ -616,7 +616,16 @@ export async function openAndroidDevice(device: DeviceInfo): Promise { } export async function closeAndroidApp(device: DeviceInfo, app: string): Promise { - await stopAndroidPackage(device, await resolveAndroidPackageToEnd(device, app, 'Close'), 'close'); + 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; + }); } /** @@ -645,11 +654,7 @@ async function resolveAndroidPackageToEnd( return resolved.value; } -async function stopAndroidPackage( - device: DeviceInfo, - packageName: string, - purpose: 'close' | 'relaunch', -): Promise { +async function stopAndroidPackage(device: DeviceInfo, packageName: string): Promise { const killed = await readAndroidPackagePids( device, packageName, @@ -659,7 +664,7 @@ async function stopAndroidPackage( throw androidPidofUnavailableError(packageName); } await runAndroidShell(device, ['am', 'force-stop', packageName]); - const expired = await waitForAndroidPackageStopped(device, packageName, killed, purpose); + const expired = await waitForAndroidPackageStopped(device, packageName, killed); if (expired) throw androidCloseTimeoutError(packageName, expired); } @@ -724,12 +729,9 @@ async function waitForAndroidPackageStopped( device: DeviceInfo, packageName: string, killed: ReadonlySet, - purpose: 'close' | 'relaunch', ): Promise { if (!(await waitForAndroidPackageNotForeground(device, packageName))) return 'foreground'; if (!(await waitForAndroidKilledProcessesExit(device, packageName, killed))) return 'exit'; - // See passedAndroidRelaunchStopFences: a relaunch needs no process fence. - if (purpose === 'relaunch') return undefined; if (!(await waitForAndroidPackageProcessGone(device, packageName))) return 'process'; return undefined; }