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
2 changes: 1 addition & 1 deletion packages/command-surface/src/management/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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; 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.'),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand Down
26 changes: 24 additions & 2 deletions packages/platform-android/src/app-lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 stopAndroidPackageForRelaunch(device, resolved.value);
if (activity) {
return await openAndroidPackageActivity(
device,
Expand Down Expand Up @@ -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 stopAndroidPackageForRelaunch(device, resolved);
return await runAndroidShell(device, [
'am',
'start',
Expand Down Expand Up @@ -619,6 +619,28 @@ 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<void> {
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,
Expand Down
34 changes: 34 additions & 0 deletions packages/platform-android/src/lifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
3 changes: 3 additions & 0 deletions packages/platform-android/src/lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@ 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);
}
Expand Down
2 changes: 1 addition & 1 deletion website/docs/docs/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <app> --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 <app> --relaunch`.
- Android React Native: `open --relaunch` needs an installed package name. Install or reinstall the APK first; `open <apk|aab> --relaunch` is rejected. For Metro-backed JS changes, run `metro reload` before reaching for `open <app> --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.

Expand Down
Loading