From 26a4a248cc3f3a2d5a9493b3968ee47f7de7937d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 00:08:04 +0100 Subject: [PATCH 1/3] fix(android): stop the emulator a failed cold boot left unowned An open that boots a stopped Android emulator stops that launch when the open fails (#4764). A failure inside the boot was outside that rule: readiness terminated the process it launched only when the request was canceled, so a boot that failed for another reason left an emulator running with no session to own it, and no later close ever learned to stop it (#4847). Readiness now decides per failure reason at the owner that holds the launched pid. A refusal that spent the startup budget keeps booting, which is what the --timeout contract and the existing tests promise, and a canceled request keeps terminating its launch. Every other failure after the launch returned a pid stops that process and rethrows its own error: the host could not record the launch, a boot probe failed inside the budget, or discovery went wrong. A terminate that itself throws records a diagnostic naming the boot failure it answers rather than replacing that failure. An emulator that was already running is still never stopped, and the daemon's open orchestration gains no second stop path. commands.md and the open help said a boot that failed before the emulator was ready left it as it is; both now state the final rule. --- .../command-surface/src/management/app.ts | 2 +- .../src/readiness/runtime.test.ts | 147 +++++++++++++++++- .../platform-android/src/readiness/runtime.ts | 52 ++++++- website/docs/docs/commands.md | 2 +- 4 files changed, 194 insertions(+), 9 deletions(-) diff --git a/packages/command-surface/src/management/app.ts b/packages/command-surface/src/management/app.ts index a67f3c46ec..9a4a2e12e7 100644 --- a/packages/command-surface/src/management/app.ts +++ b/packages/command-surface/src/management/app.ts @@ -219,7 +219,7 @@ export const openCommandFacet = defineCommandFacet({ summary: 'Open an app, deep link or URL, save replays', searchHint: 'relaunch', cliDetail: - 'Use --platform to bind URL/deep-link opens to the target platform. For local or Limrun iOS simulator initial stdout/stderr, put --launch-console on this open command, for example agent-device open "Agent Device Tester" --platform ios --launch-console artifacts/launch-console.log. Expo Go/dev-client shells accept host + URL, for example agent-device open "Expo Go" exp://127.0.0.1:8081 --platform ios. macOS also supports --surface app|frontmost-app|desktop|menubar. --metro-host/--metro-port/--bundle-url choose the app\'s Metro server and save that address for later metro reload calls in the same session. A fresh open without Metro hints clears an older same-name binding; close also clears it. --launch-url supplies the app\'s launch URL; it does not select the reload server. On an iOS simulator without --launch-url, open connects a detected Expo development client through its expo-development-client URL. The app must declare a single exp+ scheme that no other installed app owns. If detection is inconclusive, the app opens normally. Bare React Native apps receive their server settings before launch. On an iOS simulator, when --launch-url raises an "Open in ?" prompt that keeps open from seeing the app, open accepts it if the URL scheme belongs to the session app (data.launchConfirmation: "accepted"); if the scheme belongs to another installed app, the prompt stays on screen and open fails with details.reason launch_confirmation_foreign_app; if the scheme owner cannot be resolved because no single installed app owns it or the lookup failed, the prompt stays on screen and open returns with data.launchConfirmation: "unanswered", launchConfirmationReason url-owner-unresolved, and a warning; a prompt that is seen but not recognized is reported the same way with launchConfirmationReason alert-unrecognized and its own warning; for url-owner-unresolved, answer the prompt with alert accept; for alert-unrecognized, read the alert with alert get first, because it can be the app\'s own alert (such as a permission prompt) rather than the launch confirmation, and answer with alert accept only when it is the launch confirmation; when agent-device cannot read whether a prompt is up at all (the alert read, the accept, or the runner itself failed, including after a re-hand of the URL), open stays green, reports no launchConfirmation plus data.launchConfirmationProbeFailure naming the failed step (alert-read, alert-accept, or runner), and appends a warning that says to check with alert get. The prompt is read whenever open cannot see the app afterwards, including on a slow host where the app\'s target discovery fails on its own deadline. When an accept leaves the app provably not running, open hands the same URL over once more and reads again; still not running, it fails with details.reason launch_confirmation_unanswered. When the runner reports its main-thread timeout for the accept and the prompt is still up, open presses Open again, but only when the time the open request has left covers a whole press and the read that checks it. A recognized prompt still visible after a failed accept, or once that time is gone, also fails with this reason, even if the app is running behind it; answer it with alert accept or alert dismiss. A simulator openurl that CoreSimulator never answers fails within 20s with details.reason ios-simulator-openurl-timeout. The prompt is recognized by the OS\'s own wording of its title and buttons in the Simulator\'s preferred languages; when the runner cannot read that wording, the prompt stays on screen as alert-unrecognized. A prompt that appears after open has already seen the app is not answered; use alert accept. A device another session is holding refuses at once; add --wait to block up to that budget for it and only then fail with DEVICE_IN_USE naming the owning session. An open that fails after a stopped Android emulator it launched finishes booting tries to stop that emulator within 3s; read error.details.failedOpenEmulatorCleanup for the outcome (stopped, kept_running, not_confirmed) and failedOpenEmulatorCleanupReason for why it was kept. The emulator keeps running when daemon policy denies device-shutdown (daemon-policy-denied), when another session or claim took it or was in the middle of taking it (device-in-use), when it was already running, or when the boot timed out or failed before ready.', + 'Use --platform to bind URL/deep-link opens to the target platform. For local or Limrun iOS simulator initial stdout/stderr, put --launch-console on this open command, for example agent-device open "Agent Device Tester" --platform ios --launch-console artifacts/launch-console.log. Expo Go/dev-client shells accept host + URL, for example agent-device open "Expo Go" exp://127.0.0.1:8081 --platform ios. macOS also supports --surface app|frontmost-app|desktop|menubar. --metro-host/--metro-port/--bundle-url choose the app\'s Metro server and save that address for later metro reload calls in the same session. A fresh open without Metro hints clears an older same-name binding; close also clears it. --launch-url supplies the app\'s launch URL; it does not select the reload server. On an iOS simulator without --launch-url, open connects a detected Expo development client through its expo-development-client URL. The app must declare a single exp+ scheme that no other installed app owns. If detection is inconclusive, the app opens normally. Bare React Native apps receive their server settings before launch. On an iOS simulator, when --launch-url raises an "Open in ?" prompt that keeps open from seeing the app, open accepts it if the URL scheme belongs to the session app (data.launchConfirmation: "accepted"); if the scheme belongs to another installed app, the prompt stays on screen and open fails with details.reason launch_confirmation_foreign_app; if the scheme owner cannot be resolved because no single installed app owns it or the lookup failed, the prompt stays on screen and open returns with data.launchConfirmation: "unanswered", launchConfirmationReason url-owner-unresolved, and a warning; a prompt that is seen but not recognized is reported the same way with launchConfirmationReason alert-unrecognized and its own warning; for url-owner-unresolved, answer the prompt with alert accept; for alert-unrecognized, read the alert with alert get first, because it can be the app\'s own alert (such as a permission prompt) rather than the launch confirmation, and answer with alert accept only when it is the launch confirmation; when agent-device cannot read whether a prompt is up at all (the alert read, the accept, or the runner itself failed, including after a re-hand of the URL), open stays green, reports no launchConfirmation plus data.launchConfirmationProbeFailure naming the failed step (alert-read, alert-accept, or runner), and appends a warning that says to check with alert get. The prompt is read whenever open cannot see the app afterwards, including on a slow host where the app\'s target discovery fails on its own deadline. When an accept leaves the app provably not running, open hands the same URL over once more and reads again; still not running, it fails with details.reason launch_confirmation_unanswered. When the runner reports its main-thread timeout for the accept and the prompt is still up, open presses Open again, but only when the time the open request has left covers a whole press and the read that checks it. A recognized prompt still visible after a failed accept, or once that time is gone, also fails with this reason, even if the app is running behind it; answer it with alert accept or alert dismiss. A simulator openurl that CoreSimulator never answers fails within 20s with details.reason ios-simulator-openurl-timeout. The prompt is recognized by the OS\'s own wording of its title and buttons in the Simulator\'s preferred languages; when the runner cannot read that wording, the prompt stays on screen as alert-unrecognized. A prompt that appears after open has already seen the app is not answered; use alert accept. A device another session is holding refuses at once; add --wait to block up to that budget for it and only then fail with DEVICE_IN_USE naming the owning session. An open that fails after a stopped Android emulator it launched stops that emulator within 3s, so none is left with no session to own it; after the emulator was booted, read error.details.failedOpenEmulatorCleanup (stopped, kept_running, not_confirmed) and failedOpenEmulatorCleanupReason for what happened (daemon-policy-denied, or device-in-use when another session or claim took it or was taking it). Before the emulator is ready, the reason for the failure decides: a boot that ran out --timeout keeps booting, and any other failure, including a cancellation, stops the process it launched. An emulator that was already running is never stopped.', mcpDetail: "metroHost, metroPort, and bundleUrl choose the app's Metro server and save its address for later reloads. launchUrl selects the app's launch URL and does not select the reload server. A fresh open without Metro hints clears an older same-name binding; close also clears it.", }, diff --git a/packages/platform-android/src/readiness/runtime.test.ts b/packages/platform-android/src/readiness/runtime.test.ts index 151998a497..297ee52782 100644 --- a/packages/platform-android/src/readiness/runtime.test.ts +++ b/packages/platform-android/src/readiness/runtime.test.ts @@ -2,6 +2,10 @@ import { expect, test, vi } from 'vitest'; import type { PlatformRuntimeHost } from '@agent-device/contracts/platform-runtime-operations'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { AppError } from '@agent-device/kernel/errors'; +import { + countDiagnosticEventsByPhase, + withDiagnosticsScope, +} from '@agent-device/host-kit/diagnostics'; import { ensureAndroidReady } from './runtime.ts'; test('cancellation interrupts Android boot polling and terminates the emulator launched by the request', async () => { @@ -243,15 +247,24 @@ test('without a deadline the default 120s boot wait applies', async () => { type ProbeResult = { stdout: string; stderr: string; exitCode: number }; -/** A host whose boot probe replays the given results in order, then keeps returning the last one. */ -function probeHost(sequence: readonly (ProbeResult | Error)[]) { +/** + * A host whose boot probe replays the given results in order, then keeps returning the last one. + * With `launched`, the first inventory answer is a stopped AVD, so the flow launches one (pid 4242) + * and every later answer shows it running: that is when the probe results decide. + */ +function probeHost( + sequence: readonly (ProbeResult | Error)[], + options: Readonly<{ launched?: boolean }> = {}, +) { let now = 1_000; + let discoveries = 0; const queue = [...sequence]; const run = vi.fn(async () => { const next = queue.length > 1 ? queue.shift() : queue[0]; if (next instanceof Error) throw next; return next as ProbeResult; }); + const terminate = vi.fn(async () => {}); const host = { commands: { which: async () => 'tool', run }, toolchains: { prepare: async () => {} }, @@ -263,13 +276,14 @@ function probeHost(sequence: readonly (ProbeResult | Error)[]) { }, deviceReadiness: { androidEmulator: { - discover: async () => [runningEmulator()], + discover: async () => + options.launched === true && ++discoveries === 1 ? [stoppedAvd()] : [runningEmulator()], launch: async () => 4242, - terminate: async () => {}, + terminate, }, }, } as unknown as PlatformRuntimeHost; - return { host, run, elapsed: () => now - 1_000 }; + return { host, run, terminate, elapsed: () => now - 1_000 }; } const BOOTED_PROBE: ProbeResult = { stdout: '1\n', stderr: '', exitCode: 0 }; @@ -523,6 +537,129 @@ test('a thrown offline wording without typed details does not retry, proving tex expect(run).toHaveBeenCalledTimes(1); }); +// Each case below decides what happens to an emulator this request launched (pid 4242) when its +// boot fails: a failure with the startup budget still unspent stops it, a spent budget does not, +// and an emulator that was already running is never this request's to stop. +test('a launch the host could not record stops the emulator and keeps the recording failure', async () => { + let discoveries = 0; + const { host, terminate } = timedHost({ + bootCompleted: '1', + discover: () => (++discoveries === 1 ? [stoppedAvd()] : [runningEmulator()]), + }); + const bindFailure = new AppError('COMMAND_FAILED', 'host refused to record the launch'); + Object.assign(host.deviceReadiness.androidEmulator, { + bindLaunchedEmulator: async () => { + throw bindFailure; + }, + }); + + await expect( + ensureAndroidReady( + host, + stoppedAvd(), + { headless: true, deadlineAtMs: 30_000, onAndroidEmulatorLaunch: vi.fn() }, + new AbortController().signal, + ), + ).rejects.toBe(bindFailure); + expect(terminate).toHaveBeenCalledWith(4242); +}); + +test('a boot probe that fails inside the budget stops the launched emulator', async () => { + const { host, terminate, run } = probeHost( + [{ stdout: '', stderr: 'error: closed', exitCode: 1 }], + { launched: true }, + ); + + await expect( + ensureAndroidReady( + host, + stoppedAvd(), + { headless: true, deadlineAtMs: 30_000 }, + new AbortController().signal, + ), + ).rejects.toMatchObject({ details: { reason: 'BOOT_COMMAND_FAILED' } }); + expect(run).toHaveBeenCalledTimes(1); + expect(terminate).toHaveBeenCalledWith(4242); +}); + +test('discovery that goes wrong after the launch stops the launched emulator', async () => { + let discoveries = 0; + const discoveryFailure = new AppError('COMMAND_FAILED', 'adb devices failed'); + const { host, terminate } = timedHost({ + bootCompleted: '1', + discover: () => { + discoveries += 1; + if (discoveries === 1) return [stoppedAvd()]; + if (discoveries === 2) return [runningEmulator()]; + throw discoveryFailure; + }, + }); + + await expect( + ensureAndroidReady( + host, + stoppedAvd(), + { headless: true, deadlineAtMs: 30_000 }, + new AbortController().signal, + ), + ).rejects.toBe(discoveryFailure); + expect(terminate).toHaveBeenCalledWith(4242); +}); + +test('a boot probe that spends the startup budget leaves the launched emulator booting', async () => { + const { host, terminate } = probeHost([], { launched: true }); + // The probe uses the last of the budget before it fails: the clock passes the deadline. + Object.assign(host.commands, { + run: async () => { + await host.clock.sleep(10_000); + throw new AppError('COMMAND_FAILED', 'adb timed out after 10000ms', { timeoutMs: 10_000 }); + }, + }); + + await expect( + ensureAndroidReady( + host, + stoppedAvd(), + { headless: true, deadlineAtMs: 5_000 }, + new AbortController().signal, + ), + ).rejects.toMatchObject({ details: { reason: 'ANDROID_BOOT_TIMEOUT' } }); + expect(terminate).not.toHaveBeenCalled(); +}); + +test('an emulator that was already running is not stopped when its boot probe fails', async () => { + const { host, terminate } = probeHost([{ stdout: '', stderr: 'error: closed', exitCode: 1 }]); + + await expect( + ensureAndroidReady( + host, + runningEmulator(), + { headless: false, deadlineAtMs: 30_000 }, + new AbortController().signal, + ), + ).rejects.toMatchObject({ details: { reason: 'BOOT_COMMAND_FAILED' } }); + expect(terminate).not.toHaveBeenCalled(); +}); + +test('a host that refuses the stop still reports the boot failure and records the refusal', async () => { + await withDiagnosticsScope({ command: 'open' }, async () => { + const { host, terminate } = probeHost([{ stdout: '', stderr: 'error: closed', exitCode: 1 }], { + launched: true, + }); + terminate.mockRejectedValue(new Error('pid 4242 is not this host')); + + await expect( + ensureAndroidReady( + host, + stoppedAvd(), + { headless: true, deadlineAtMs: 30_000 }, + new AbortController().signal, + ), + ).rejects.toMatchObject({ details: { reason: 'BOOT_COMMAND_FAILED' } }); + expect(countDiagnosticEventsByPhase(['android_emulator_launch_terminate_failed'])).toBe(1); + }); +}); + function stoppedAvd(): DeviceInfo { return { platform: 'android', diff --git a/packages/platform-android/src/readiness/runtime.ts b/packages/platform-android/src/readiness/runtime.ts index a03b197dfe..b8c2426e81 100644 --- a/packages/platform-android/src/readiness/runtime.ts +++ b/packages/platform-android/src/readiness/runtime.ts @@ -13,6 +13,7 @@ export type AndroidReadinessHost = Pick< import type { DeviceInfo } from '@agent-device/kernel/device'; import { deviceShellArgv } from '@agent-device/kernel/device-shell'; import { AppError, asAppError } from '@agent-device/kernel/errors'; +import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { bootFailureHint } from '@agent-device/provision-kit/boot-diagnostics'; import { androidAdbResultError, attachAdbFailureHint } from '../adb-executor.ts'; import { @@ -79,14 +80,61 @@ async function ensureEmulatorReady( } return ready; } catch (error) { - if (launchedPid !== undefined && signal.aborted) { - await host.deviceReadiness.androidEmulator.terminate(launchedPid); + if (launchedPid !== undefined && !keepsBootAfterFailure(host, error, deadlineAtMs, signal)) { + // This request's launch has no boot left to wait for: it goes with the failure, so no + // emulator is left running with no session to own it (#4847). + await terminateLaunch(host, launchedPid, error); } signal.throwIfAborted(); throw error; } } +/** + * Whether a failed boot leaves its emulator booting, and so leaves this request's launch running. + * A canceled request always answers stopped — the abort owner owns that decision. Otherwise only a + * failure that spent the startup budget keeps booting: each poller throws {@link bootTimeoutError} + * once `clock.now()` passes `deadlineAtMs`, and a boot probe that fails at or past that same + * deadline reports its own spent budget rather than `BOOT_TIMEOUT_REASON` (see + * `buildAndroidBootError`). Every other refusal — the host could not record the launch, a probe + * failed inside the budget, discovery went wrong — has no boot left to wait for. + */ +function keepsBootAfterFailure( + host: AndroidReadinessHost, + error: unknown, + deadlineAtMs: number, + signal: AbortSignal, +): boolean { + if (signal.aborted) return false; + return ( + host.clock.now() >= deadlineAtMs || asAppError(error).details?.reason === BOOT_TIMEOUT_REASON + ); +} + +/** + * Stops the process this request launched, and never replaces the failure that caused the stop: a + * host that refuses to signal reports a diagnostic naming that failure instead. + */ +async function terminateLaunch( + host: AndroidReadinessHost, + launchedPid: number, + bootFailure: unknown, +): Promise { + try { + await host.deviceReadiness.androidEmulator.terminate(launchedPid); + } catch (error) { + emitDiagnostic({ + level: 'warn', + phase: 'android_emulator_launch_terminate_failed', + data: { + pid: launchedPid, + error: error instanceof Error ? error.message : String(error), + bootFailure: bootFailure instanceof Error ? bootFailure.message : String(bootFailure), + }, + }); + } +} + async function prepareAndroidEmulatorToolchain(host: AndroidReadinessHost): Promise { await host.toolchains.prepare('android'); if (!(await host.commands.which('adb'))) { diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index ab6f3e0a5c..05437f1e0c 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -122,7 +122,7 @@ Device claims and the daemon: Open apps and links: - `open [app|url] [url]` boots the selected device when needed and opens the target in a session. `open ` opens deep links on Android and iOS, and `open ` opens a deep link in that app on iOS. Only a boot this `open` performed gives a later plain `close` the right to stop the device. See [Desktop targets](#desktop-targets) for macOS activation behavior. -- An `open` that launches a stopped Android emulator and then fails without publishing a session stops that emulator, so no unowned emulator is left running: a later `close` never learns the failed `open` booted it. The stop itself takes at most 3 seconds after the failure. The failed open's own error stays the reported error and carries `error.details.failedOpenEmulatorCleanup`: `stopped`, `kept_running` with `failedOpenEmulatorCleanupReason` (`daemon-policy-denied` when [daemon policy](/docs/remote-proxy#restrict-what-clients-can-do) denies `device-shutdown`, `device-in-use` when another session or claim took the booted device, or is in the middle of taking it, `no-process-identity` when the launch's start time could not be read), or `not_confirmed`. An emulator that was already running is never stopped. This rule covers failures after the boot completes: a boot that ran out its `--timeout`, or that failed before the emulator was ready, leaves the emulator as it is, as above; only a canceled boot stops the emulator it launched. +- An `open` that launches a stopped Android emulator and then fails without publishing a session stops that emulator, so no unowned emulator is left running: a later `close` never learns the failed `open` booted it. The stop itself takes at most 3 seconds after the failure. The failed open's own error stays the reported error and carries `error.details.failedOpenEmulatorCleanup`: `stopped`, `kept_running` with `failedOpenEmulatorCleanupReason` (`daemon-policy-denied` when [daemon policy](/docs/remote-proxy#restrict-what-clients-can-do) denies `device-shutdown`, `device-in-use` when another session or claim took the booted device, or is in the middle of taking it, `no-process-identity` when the launch's start time could not be read), or `not_confirmed`. An emulator that was already running is never stopped. While the emulator is still booting, the failure's reason decides instead and no `failedOpenEmulatorCleanup` is reported: a boot that ran out its `--timeout` leaves the emulator booting, as above, a canceled boot stops the process it launched, and any other failure before the emulator is ready, such as a boot probe that failed inside the budget or device discovery that went wrong, stops that process because it launched it. - Remote daemons refuse `file:` URLs in `open` targets and launch URLs with reason `REMOTE_HOST_INPUT_DENIED`. Serve local web content over HTTP(S) instead. - On iOS devices, `http(s)://` URLs open in Safari when no app is active. Custom-scheme URLs need an active app in the session. - Local iOS simulator: after `open` launches an app and the backend reports that launch (local iOS simulators do; other devices and backends skip the wait, so their first capture can still show a launch screen), the first capture in the session polls for the app's first screen for up to 10 seconds. A capture that starts before the 10 seconds end still completes and is judged. This includes the initial snapshot of `open --foreground`. A tree counts as the first screen when, besides the app root, it shows a labeled element that is not text, such as a button, or two different texts, and two reads in a row agree. An unlabeled splash image, an empty view, a busy indicator, or a single status line such as Expo's "Bundling 91%…" does not count, however long it stays unchanged. An app whose first screen is a single line of text, or has no labeled element at all, such as a game canvas, waits the full 10 seconds; to skip the wait, pass `--no-post-gesture-stabilization` to `open` (see [Scroll](#scroll) for the other ways to set it) and poll the screen yourself. If the wait runs out, the snapshot returns what it read with a warning: `postGestureOutcome.kind: "loading"` when it still showed no first screen, or `"unsettled"` when a first screen was there but kept changing. Run `snapshot -i` again, or `wait text `, before you act on it. From c58a5822038fcd3592b5187c9ddd5f53e2209bc9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 00:17:31 +0100 Subject: [PATCH 2/3] fix(android): gate the launched emulator's stop with the shutdown policy (#4847) `terminate` is the one teardown a launched emulator's own host can perform, and it was the one shutdown no policy was asked about: `assertShutdownAllowed` guarded only `deviceShutdown`. A daemon that denies `device-shutdown` therefore SIGTERM'd the emulator a failed boot had launched, and a canceled boot had signaled it the same way before this. Pass that assertion to the host that owns the launch and ask it before anything else. A denied daemon now leaves its launch running and the caller keeps the failure that asked: readiness already records a diagnostic when `terminate` throws, and the open reports its own boot error. The keep-decision now reads the boot's phase rather than the clock, so a step after a finished boot cannot read as a spent budget: only a boot-wait poller that ran out that budget keeps its launch. The rule belongs to booting, not to `open`, so `commands.md` says so. --- docs/adr/0029-daemon-policy.md | 2 + .../contracts/src/device-readiness-runtime.ts | 5 +++ .../src/readiness/runtime.test.ts | 34 +++++++++++++++- .../platform-android/src/readiness/runtime.ts | 30 +++++++------- ...form-runtime-android-emulator-host.test.ts | 40 +++++++++++++++++++ src/platform-runtime-android-emulator-host.ts | 5 +++ src/platform-runtime-operation-host.ts | 2 +- website/docs/docs/commands.md | 2 +- 8 files changed, 103 insertions(+), 17 deletions(-) diff --git a/docs/adr/0029-daemon-policy.md b/docs/adr/0029-daemon-policy.md index e5f5be46b8..301ad21bfe 100644 --- a/docs/adr/0029-daemon-policy.md +++ b/docs/adr/0029-daemon-policy.md @@ -5,6 +5,7 @@ Accepted (2026-09-29). Amended (2026-11-04): `devices.allow` admits web session devices like app devices (ADR 0037). Amended (2026-11-14): plain close skips a denied implicit stop of a local simulator or emulator that this session's `open` booted (#4162). Amended (2026-11-20): a failed `open` stops the emulator its own host launched, and a denied `device-shutdown` keeps that launch running and reports why (#4764). +Amended (2026-11-21): the capability gate covers every host that can tear down a launched Android emulator process, not only the shutdown capability, so readiness keeps its launch when policy denies `device-shutdown` (#4863). ## Rules at a glance @@ -25,6 +26,7 @@ Amended (2026-11-20): a failed `open` stops the emulator its own host launched, That Simulator was not previously running. A plain close of a local simulator or emulator booted by this session's `open` skips the denied implicit stop, succeeds, and reports the kept local device. A failed `open` that launched a stopped emulator and published no session stops that launch through the launched-process owner, and asks nothing of the host when policy denies `device-shutdown`: the emulator stays running and the open's error reports `kept_running` with `failedOpenEmulatorCleanupReason: 'daemon-policy-denied'`. + The host that launched an Android emulator applies this gate to its own terminate of that process, whichever request asked, so a boot that failed and a canceled boot both keep their launch running under a denied policy and report their own failure. A `close --shutdown` the caller asked for fails like any other denied request. 4. Denials use `UNAUTHORIZED`, `details.reason: 'DAEMON_POLICY_DENIED'`, `retriable: false`, a hint, and the policy digest. They include `rule`: `command`, `device`, `capability`, or `lease`. diff --git a/packages/contracts/src/device-readiness-runtime.ts b/packages/contracts/src/device-readiness-runtime.ts index 3f5de9ea73..35a0c6a92d 100644 --- a/packages/contracts/src/device-readiness-runtime.ts +++ b/packages/contracts/src/device-readiness-runtime.ts @@ -58,6 +58,11 @@ export type DeviceReadinessRuntimeHost = Readonly<{ pid: number, device: DeviceInfo, ): Promise; + /** + * Stops the emulator process this host's `launch` of `pid` started, and throws without signaling + * when the daemon's policy denies `device-shutdown`. A caller that must not lose its own failure + * catches that refusal: the launch stays running. + */ terminate(pid: number): Promise; }>; }>; diff --git a/packages/platform-android/src/readiness/runtime.test.ts b/packages/platform-android/src/readiness/runtime.test.ts index 297ee52782..b730a42a89 100644 --- a/packages/platform-android/src/readiness/runtime.test.ts +++ b/packages/platform-android/src/readiness/runtime.test.ts @@ -623,10 +623,42 @@ test('a boot probe that spends the startup budget leaves the launched emulator b { headless: true, deadlineAtMs: 5_000 }, new AbortController().signal, ), - ).rejects.toMatchObject({ details: { reason: 'ANDROID_BOOT_TIMEOUT' } }); + ).rejects.toMatchObject({ + details: { reason: 'ANDROID_BOOT_TIMEOUT', bootBudgetSpent: true }, + }); expect(terminate).not.toHaveBeenCalled(); }); +test('a step that fails after the boot is done stops the launched emulator past the deadline', async () => { + let discoveries = 0; + const lateFailure = new AppError('COMMAND_FAILED', 'adb devices failed'); + const { host, terminate } = timedHost({ + bootCompleted: '1', + discover: () => { + discoveries += 1; + if (discoveries === 1) return [stoppedAvd()]; + // The boot is over; this refresh is the step after it, and it fails once the clock is past + // the startup deadline. A spent budget keeps an emulator that is still coming up, and this one + // is already up, so the launch is this request's to stop. + if (discoveries === 2) { + host.clock.sleep(60_000); + throw lateFailure; + } + return [runningEmulator()]; + }, + }); + + await expect( + ensureAndroidReady( + host, + stoppedAvd(), + { headless: true, deadlineAtMs: 30_000 }, + new AbortController().signal, + ), + ).rejects.toBe(lateFailure); + expect(terminate).toHaveBeenCalledWith(4242); +}); + test('an emulator that was already running is not stopped when its boot probe fails', async () => { const { host, terminate } = probeHost([{ stdout: '', stderr: 'error: closed', exitCode: 1 }]); diff --git a/packages/platform-android/src/readiness/runtime.ts b/packages/platform-android/src/readiness/runtime.ts index b8c2426e81..70a1a1eae6 100644 --- a/packages/platform-android/src/readiness/runtime.ts +++ b/packages/platform-android/src/readiness/runtime.ts @@ -61,11 +61,15 @@ async function ensureEmulatorReady( input.headless, deadlineAtMs - host.clock.now(), ); + // Where the boot got to, so a failure after the emulator answered tells a spent boot budget + // apart from a late step that failed on its own. + let bootWaitDone = false; try { const discovered = existing ?? (await waitForDiscovery(host, selected.name, request, input.serial, deadlineAtMs, signal)); await waitForBoot(host, discovered.id, deadlineAtMs, signal); + bootWaitDone = true; const refreshed = (await host.deviceReadiness.androidEmulator.discover(request, signal)).find( (candidate) => candidate.id === discovered.id, ); @@ -80,7 +84,7 @@ async function ensureEmulatorReady( } return ready; } catch (error) { - if (launchedPid !== undefined && !keepsBootAfterFailure(host, error, deadlineAtMs, signal)) { + if (launchedPid !== undefined && !keepsBootAfterFailure(error, bootWaitDone, signal)) { // This request's launch has no boot left to wait for: it goes with the failure, so no // emulator is left running with no session to own it (#4847). await terminateLaunch(host, launchedPid, error); @@ -92,28 +96,23 @@ async function ensureEmulatorReady( /** * Whether a failed boot leaves its emulator booting, and so leaves this request's launch running. - * A canceled request always answers stopped — the abort owner owns that decision. Otherwise only a - * failure that spent the startup budget keeps booting: each poller throws {@link bootTimeoutError} - * once `clock.now()` passes `deadlineAtMs`, and a boot probe that fails at or past that same - * deadline reports its own spent budget rather than `BOOT_TIMEOUT_REASON` (see - * `buildAndroidBootError`). Every other refusal — the host could not record the launch, a probe - * failed inside the budget, discovery went wrong — has no boot left to wait for. + * Only a boot-wait poller that ran out the startup budget answers yes; a canceled request always + * answers no — the abort owner owns that decision. */ function keepsBootAfterFailure( - host: AndroidReadinessHost, error: unknown, - deadlineAtMs: number, + bootWaitDone: boolean, signal: AbortSignal, ): boolean { if (signal.aborted) return false; - return ( - host.clock.now() >= deadlineAtMs || asAppError(error).details?.reason === BOOT_TIMEOUT_REASON - ); + if (bootWaitDone) return false; + const details = asAppError(error).details; + return details?.reason === BOOT_TIMEOUT_REASON || details?.bootBudgetSpent === true; } /** - * Stops the process this request launched, and never replaces the failure that caused the stop: a - * host that refuses to signal reports a diagnostic naming that failure instead. + * Stops this request's launch, keeping the failure that caused the stop: a refused stop, such as a + * denied `device-shutdown` policy, is recorded beside that failure, never in its place. */ async function terminateLaunch( host: AndroidReadinessHost, @@ -269,6 +268,9 @@ function throwBootProbeFailure( hint: bootFailureHint(reason), ...(failure.details ?? {}), reason, + // Says this probe's own failure ended a boot whose budget ran out, which is what separates it + // from a probe that failed with booting still ahead of it. + ...(budgetSpent ? { bootBudgetSpent: true } : {}), }; throw buildAndroidBootError(failure, reason, budgetSpent, details); } diff --git a/src/platform-runtime-android-emulator-host.test.ts b/src/platform-runtime-android-emulator-host.test.ts index f6416af78e..af9f12f5b8 100644 --- a/src/platform-runtime-android-emulator-host.test.ts +++ b/src/platform-runtime-android-emulator-host.test.ts @@ -182,6 +182,46 @@ test('terminate signals nothing for a pid this host did not launch', async () => expect(stopProcessAndConfirmExit).toHaveBeenCalledOnce(); }); +test('a denied device-shutdown policy keeps the launched emulator and signals nothing', async () => { + const denied = Object.assign(new Error('DAEMON_POLICY_DENIED'), { + details: { reason: 'DAEMON_POLICY_DENIED' }, + }); + const assertShutdownAllowed = vi.fn(() => { + throw denied; + }); + const host = createAndroidEmulatorHost('linux', assertShutdownAllowed); + await host.launch('Pixel_9', true, 90_000); + + // The policy is the first thing asked, so a denied daemon never reaches the process table or a + // signal: the emulator this host launched keeps running (#4863 review). + await expect(host.terminate(4242)).rejects.toBe(denied); + expect(assertShutdownAllowed).toHaveBeenCalledOnce(); + expect(stopProcessAndConfirmExit).not.toHaveBeenCalled(); +}); + +test('a denied device-shutdown policy is asked before the pid is looked up', async () => { + const assertShutdownAllowed = vi.fn(() => { + throw new Error('DAEMON_POLICY_DENIED'); + }); + const host = createAndroidEmulatorHost('linux', assertShutdownAllowed); + + await expect(host.terminate(5151)).rejects.toThrow('DAEMON_POLICY_DENIED'); + expect(emitDiagnostic).not.toHaveBeenCalledWith( + expect.objectContaining({ phase: 'android_emulator_terminate_unrecorded_pid' }), + ); +}); + +test('an allowed daemon stops the emulator with the gate asked first', async () => { + const assertShutdownAllowed = vi.fn(); + const host = createAndroidEmulatorHost('linux', assertShutdownAllowed); + await host.launch('Pixel_9', true, 90_000); + + await host.terminate(4242); + + expect(assertShutdownAllowed).toHaveBeenCalledOnce(); + expect(stopProcessAndConfirmExit).toHaveBeenCalledOnce(); +}); + test('a terminate that could not prove the exit keeps the launch for a retry', async () => { const host = createAndroidEmulatorHost('linux'); await host.launch('Pixel_9', true, 90_000); diff --git a/src/platform-runtime-android-emulator-host.ts b/src/platform-runtime-android-emulator-host.ts index c414c1a526..49ac23d2d5 100644 --- a/src/platform-runtime-android-emulator-host.ts +++ b/src/platform-runtime-android-emulator-host.ts @@ -33,10 +33,15 @@ function run(argv) { export function createAndroidEmulatorHost( hostPlatform: NodeJS.Platform = process.platform, + /** ADR 0029: the daemon policy's last line against a shutdown, whichever command asks. */ + assertShutdownAllowed: () => void = () => {}, ): DeviceReadinessRuntimeHost['androidEmulator'] { // What each launch recorded about its emulator, so terminate signals only that process. const launched = new Map }>(); const terminate = async (pid: number): Promise => { + // Asked of a launched emulator, a teardown is a shutdown: the policy is consulted before the + // process table is read, so a denied daemon leaves this launch running. + assertShutdownAllowed(); const record = launched.get(pid); if (!record) { // Nothing names this pid as an emulator this host started, so nothing is signaled. diff --git a/src/platform-runtime-operation-host.ts b/src/platform-runtime-operation-host.ts index 2ba2bdeb92..bb9641c9dc 100644 --- a/src/platform-runtime-operation-host.ts +++ b/src/platform-runtime-operation-host.ts @@ -120,7 +120,7 @@ export function createPlatformRuntimeHost(options: { deviceReadiness: Object.freeze({ applePhysical: createApplePhysicalReadinessHost(), appleAutomation: createAppleAutomationKeepHotHost(), - androidEmulator: createAndroidEmulatorHost(), + androidEmulator: createAndroidEmulatorHost(process.platform, options.assertShutdownAllowed), }), deviceShutdown: createDeviceShutdownRuntimeHost( { appleTools, commands }, diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 05437f1e0c..de2aee7c5c 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -122,7 +122,7 @@ Device claims and the daemon: Open apps and links: - `open [app|url] [url]` boots the selected device when needed and opens the target in a session. `open ` opens deep links on Android and iOS, and `open ` opens a deep link in that app on iOS. Only a boot this `open` performed gives a later plain `close` the right to stop the device. See [Desktop targets](#desktop-targets) for macOS activation behavior. -- An `open` that launches a stopped Android emulator and then fails without publishing a session stops that emulator, so no unowned emulator is left running: a later `close` never learns the failed `open` booted it. The stop itself takes at most 3 seconds after the failure. The failed open's own error stays the reported error and carries `error.details.failedOpenEmulatorCleanup`: `stopped`, `kept_running` with `failedOpenEmulatorCleanupReason` (`daemon-policy-denied` when [daemon policy](/docs/remote-proxy#restrict-what-clients-can-do) denies `device-shutdown`, `device-in-use` when another session or claim took the booted device, or is in the middle of taking it, `no-process-identity` when the launch's start time could not be read), or `not_confirmed`. An emulator that was already running is never stopped. While the emulator is still booting, the failure's reason decides instead and no `failedOpenEmulatorCleanup` is reported: a boot that ran out its `--timeout` leaves the emulator booting, as above, a canceled boot stops the process it launched, and any other failure before the emulator is ready, such as a boot probe that failed inside the budget or device discovery that went wrong, stops that process because it launched it. +- An `open` that launches a stopped Android emulator and then fails without publishing a session stops that emulator, so no unowned emulator is left running: a later `close` never learns the failed `open` booted it. The stop itself takes at most 3 seconds after the failure. The failed open's own error stays the reported error and carries `error.details.failedOpenEmulatorCleanup`: `stopped`, `kept_running` with `failedOpenEmulatorCleanupReason` (`daemon-policy-denied` when [daemon policy](/docs/remote-proxy#restrict-what-clients-can-do) denies `device-shutdown`, `device-in-use` when another session or claim took the booted device, or is in the middle of taking it, `no-process-identity` when the launch's start time could not be read), or `not_confirmed`. An emulator that was already running is never stopped. While the emulator is still booting, the failure's reason decides instead and no `failedOpenEmulatorCleanup` is reported: a boot that ran out its `--timeout` leaves the emulator booting, as above, a canceled boot stops the process it launched, and any other failure before the emulator is ready, such as a boot probe that failed inside the budget or device discovery that went wrong, stops that process because it launched it. A boot failure on a daemon whose policy denies `device-shutdown` leaves that process running too. That boot-time rule belongs to booting itself, so `boot` and app deployment follow it the same way. - Remote daemons refuse `file:` URLs in `open` targets and launch URLs with reason `REMOTE_HOST_INPUT_DENIED`. Serve local web content over HTTP(S) instead. - On iOS devices, `http(s)://` URLs open in Safari when no app is active. Custom-scheme URLs need an active app in the session. - Local iOS simulator: after `open` launches an app and the backend reports that launch (local iOS simulators do; other devices and backends skip the wait, so their first capture can still show a launch screen), the first capture in the session polls for the app's first screen for up to 10 seconds. A capture that starts before the 10 seconds end still completes and is judged. This includes the initial snapshot of `open --foreground`. A tree counts as the first screen when, besides the app root, it shows a labeled element that is not text, such as a button, or two different texts, and two reads in a row agree. An unlabeled splash image, an empty view, a busy indicator, or a single status line such as Expo's "Bundling 91%…" does not count, however long it stays unchanged. An app whose first screen is a single line of text, or has no labeled element at all, such as a game canvas, waits the full 10 seconds; to skip the wait, pass `--no-post-gesture-stabilization` to `open` (see [Scroll](#scroll) for the other ways to set it) and poll the screen yourself. If the wait runs out, the snapshot returns what it read with a warning: `postGestureOutcome.kind: "loading"` when it still showed no first screen, or `"unsettled"` when a first screen was there but kept changing. Run `snapshot -i` again, or `wait text `, before you act on it. From 8bf0b9a8188dcda7db80f5c74f782112798e1a5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 00:30:27 +0100 Subject: [PATCH 3/3] docs(open): say a denied device-shutdown policy keeps a failed boot's emulator running --- packages/command-surface/src/management/app.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/command-surface/src/management/app.ts b/packages/command-surface/src/management/app.ts index 9a4a2e12e7..fe6ad59aee 100644 --- a/packages/command-surface/src/management/app.ts +++ b/packages/command-surface/src/management/app.ts @@ -219,7 +219,7 @@ export const openCommandFacet = defineCommandFacet({ summary: 'Open an app, deep link or URL, save replays', searchHint: 'relaunch', cliDetail: - 'Use --platform to bind URL/deep-link opens to the target platform. For local or Limrun iOS simulator initial stdout/stderr, put --launch-console on this open command, for example agent-device open "Agent Device Tester" --platform ios --launch-console artifacts/launch-console.log. Expo Go/dev-client shells accept host + URL, for example agent-device open "Expo Go" exp://127.0.0.1:8081 --platform ios. macOS also supports --surface app|frontmost-app|desktop|menubar. --metro-host/--metro-port/--bundle-url choose the app\'s Metro server and save that address for later metro reload calls in the same session. A fresh open without Metro hints clears an older same-name binding; close also clears it. --launch-url supplies the app\'s launch URL; it does not select the reload server. On an iOS simulator without --launch-url, open connects a detected Expo development client through its expo-development-client URL. The app must declare a single exp+ scheme that no other installed app owns. If detection is inconclusive, the app opens normally. Bare React Native apps receive their server settings before launch. On an iOS simulator, when --launch-url raises an "Open in ?" prompt that keeps open from seeing the app, open accepts it if the URL scheme belongs to the session app (data.launchConfirmation: "accepted"); if the scheme belongs to another installed app, the prompt stays on screen and open fails with details.reason launch_confirmation_foreign_app; if the scheme owner cannot be resolved because no single installed app owns it or the lookup failed, the prompt stays on screen and open returns with data.launchConfirmation: "unanswered", launchConfirmationReason url-owner-unresolved, and a warning; a prompt that is seen but not recognized is reported the same way with launchConfirmationReason alert-unrecognized and its own warning; for url-owner-unresolved, answer the prompt with alert accept; for alert-unrecognized, read the alert with alert get first, because it can be the app\'s own alert (such as a permission prompt) rather than the launch confirmation, and answer with alert accept only when it is the launch confirmation; when agent-device cannot read whether a prompt is up at all (the alert read, the accept, or the runner itself failed, including after a re-hand of the URL), open stays green, reports no launchConfirmation plus data.launchConfirmationProbeFailure naming the failed step (alert-read, alert-accept, or runner), and appends a warning that says to check with alert get. The prompt is read whenever open cannot see the app afterwards, including on a slow host where the app\'s target discovery fails on its own deadline. When an accept leaves the app provably not running, open hands the same URL over once more and reads again; still not running, it fails with details.reason launch_confirmation_unanswered. When the runner reports its main-thread timeout for the accept and the prompt is still up, open presses Open again, but only when the time the open request has left covers a whole press and the read that checks it. A recognized prompt still visible after a failed accept, or once that time is gone, also fails with this reason, even if the app is running behind it; answer it with alert accept or alert dismiss. A simulator openurl that CoreSimulator never answers fails within 20s with details.reason ios-simulator-openurl-timeout. The prompt is recognized by the OS\'s own wording of its title and buttons in the Simulator\'s preferred languages; when the runner cannot read that wording, the prompt stays on screen as alert-unrecognized. A prompt that appears after open has already seen the app is not answered; use alert accept. A device another session is holding refuses at once; add --wait to block up to that budget for it and only then fail with DEVICE_IN_USE naming the owning session. An open that fails after a stopped Android emulator it launched stops that emulator within 3s, so none is left with no session to own it; after the emulator was booted, read error.details.failedOpenEmulatorCleanup (stopped, kept_running, not_confirmed) and failedOpenEmulatorCleanupReason for what happened (daemon-policy-denied, or device-in-use when another session or claim took it or was taking it). Before the emulator is ready, the reason for the failure decides: a boot that ran out --timeout keeps booting, and any other failure, including a cancellation, stops the process it launched. An emulator that was already running is never stopped.', + 'Use --platform to bind URL/deep-link opens to the target platform. For local or Limrun iOS simulator initial stdout/stderr, put --launch-console on this open command, for example agent-device open "Agent Device Tester" --platform ios --launch-console artifacts/launch-console.log. Expo Go/dev-client shells accept host + URL, for example agent-device open "Expo Go" exp://127.0.0.1:8081 --platform ios. macOS also supports --surface app|frontmost-app|desktop|menubar. --metro-host/--metro-port/--bundle-url choose the app\'s Metro server and save that address for later metro reload calls in the same session. A fresh open without Metro hints clears an older same-name binding; close also clears it. --launch-url supplies the app\'s launch URL; it does not select the reload server. On an iOS simulator without --launch-url, open connects a detected Expo development client through its expo-development-client URL. The app must declare a single exp+ scheme that no other installed app owns. If detection is inconclusive, the app opens normally. Bare React Native apps receive their server settings before launch. On an iOS simulator, when --launch-url raises an "Open in ?" prompt that keeps open from seeing the app, open accepts it if the URL scheme belongs to the session app (data.launchConfirmation: "accepted"); if the scheme belongs to another installed app, the prompt stays on screen and open fails with details.reason launch_confirmation_foreign_app; if the scheme owner cannot be resolved because no single installed app owns it or the lookup failed, the prompt stays on screen and open returns with data.launchConfirmation: "unanswered", launchConfirmationReason url-owner-unresolved, and a warning; a prompt that is seen but not recognized is reported the same way with launchConfirmationReason alert-unrecognized and its own warning; for url-owner-unresolved, answer the prompt with alert accept; for alert-unrecognized, read the alert with alert get first, because it can be the app\'s own alert (such as a permission prompt) rather than the launch confirmation, and answer with alert accept only when it is the launch confirmation; when agent-device cannot read whether a prompt is up at all (the alert read, the accept, or the runner itself failed, including after a re-hand of the URL), open stays green, reports no launchConfirmation plus data.launchConfirmationProbeFailure naming the failed step (alert-read, alert-accept, or runner), and appends a warning that says to check with alert get. The prompt is read whenever open cannot see the app afterwards, including on a slow host where the app\'s target discovery fails on its own deadline. When an accept leaves the app provably not running, open hands the same URL over once more and reads again; still not running, it fails with details.reason launch_confirmation_unanswered. When the runner reports its main-thread timeout for the accept and the prompt is still up, open presses Open again, but only when the time the open request has left covers a whole press and the read that checks it. A recognized prompt still visible after a failed accept, or once that time is gone, also fails with this reason, even if the app is running behind it; answer it with alert accept or alert dismiss. A simulator openurl that CoreSimulator never answers fails within 20s with details.reason ios-simulator-openurl-timeout. The prompt is recognized by the OS\'s own wording of its title and buttons in the Simulator\'s preferred languages; when the runner cannot read that wording, the prompt stays on screen as alert-unrecognized. A prompt that appears after open has already seen the app is not answered; use alert accept. A device another session is holding refuses at once; add --wait to block up to that budget for it and only then fail with DEVICE_IN_USE naming the owning session. An open that fails after a stopped Android emulator it launched stops that emulator within 3s, so none is left with no session to own it; after the emulator was booted, read error.details.failedOpenEmulatorCleanup (stopped, kept_running, not_confirmed) and failedOpenEmulatorCleanupReason for what happened (daemon-policy-denied, or device-in-use when another session or claim took it or was taking it). Before the emulator is ready, the reason for the failure decides: a boot that ran out --timeout keeps booting, and any other failure, including a cancellation, stops the process it launched. Under a daemon policy that denies device-shutdown, a failed or canceled boot leaves the launched emulator running, and only the android_emulator_launch_terminate_failed diagnostic records it. An emulator that was already running is never stopped.', mcpDetail: "metroHost, metroPort, and bundleUrl choose the app's Metro server and save its address for later reloads. launchUrl selects the app's launch URL and does not select the reload server. A fresh open without Metro hints clears an older same-name binding; close also clears it.", },