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: 2 additions & 0 deletions docs/adr/0029-daemon-policy.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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`.
Expand Down
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 @@ -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 <path> 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+<slug> 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 <App>?" 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 <ms> 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 <path> 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+<slug> 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 <App>?" 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 <ms> 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.",
},
Expand Down
5 changes: 5 additions & 0 deletions packages/contracts/src/device-readiness-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@ export type DeviceReadinessRuntimeHost = Readonly<{
pid: number,
device: DeviceInfo,
): Promise<AndroidEmulatorLaunchIdentity | undefined>;
/**
* 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<void>;
}>;
}>;
179 changes: 174 additions & 5 deletions packages/platform-android/src/readiness/runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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 () => {} },
Expand All @@ -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 };
Expand Down Expand Up @@ -523,6 +537,161 @@ 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', 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 }]);

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',
Expand Down
Loading
Loading