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
3 changes: 3 additions & 0 deletions docs/adr/0029-daemon-policy.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## Status

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).

## Rules at a glance

Expand All @@ -21,6 +22,8 @@ Accepted (2026-09-29). Amended (2026-11-04): `devices.allow` admits web session
- **Capability gate:** the device-shutdown host capability refuses shutdown from every command.
The only exception permits Apple readiness to roll back a Simulator boot started and then canceled by the same request.
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 `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`.
They never expose the policy's host path.
Expand Down
8 changes: 5 additions & 3 deletions docs/agents/device-verification.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,11 @@ A failed command can look like a fast success. Before you record its time, check

## Ownership and cleanup

Use one session for each purpose. For more isolation, use a separate `--state-dir` under `/private/tmp`.
Close each session that you opened manually, including failed attempts, with its original session, platform, UDID, and state directory.
If your session booted a local simulator or emulator, add `--shutdown`, unless the user asks to keep it running.
Use one session per purpose. For isolation, set `--state-dir` under `/private/tmp`.
Close every session you opened, even after failure. Reuse its session, platform, UDID, and state directory.
Use plain `close` for a local device your `open` booted.
If policy denies `device-shutdown`, read the warning.
Keep prebooted devices running unless the user requests shutdown.

For `DEVICE_IN_USE`:

Expand Down
10 changes: 10 additions & 0 deletions packages/client/src/__tests__/index-apps.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -462,3 +462,13 @@ test('apps.installFromSource forwards GitHub Actions artifact sources unchanged'
artifactId: 1234567890,
});
});

test.each(['apps', 'sessions'] as const)('%s.close preserves response warnings', async (api) => {
const setup = createClientTransport(async (req) => {
assert.equal(req.command, 'close');
return { ok: true, data: { session: 'qa', warnings: ['Device remains running.', 42] } };
});
const client = createAgentDeviceClient(setup.config, { transport: setup.transport });
const result = await client[api].close({ session: 'qa' });
assert.deepEqual(result.warnings, ['Device remains running.']);
});
15 changes: 15 additions & 0 deletions packages/command-output/src/output/result-serialization.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { test } from 'vitest';
import assert from 'node:assert/strict';
import {
serializeCloseResult,
serializeInstallFromSourceResult,
serializeOpenResult,
serializeSessionListEntry,
Expand Down Expand Up @@ -237,3 +238,17 @@ test('serializeInstallFromSourceResult uses install-family package naming', () =
message: 'Installed: Demo',
});
});

test('serializeCloseResult preserves warnings and omits an empty warning channel', () => {
const result = { session: 'qa', identifiers: { session: 'qa' } };
assert.deepEqual(serializeCloseResult({ ...result, warnings: ['Device remains running.'] }), {
session: 'qa',
message: 'Closed: qa',
warnings: ['Device remains running.'],
});
assert.deepEqual(serializeCloseResult({ ...result, warnings: [] }), {
session: 'qa',
message: 'Closed: qa',
});
assert.deepEqual(serializeCloseResult(result), { session: 'qa', message: 'Closed: qa' });
});
6 changes: 4 additions & 2 deletions packages/command-surface/src/management/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,10 +95,12 @@ const openCommandMetadata = defineFieldCommandMetadata(

const closeCommandMetadata = defineFieldCommandMetadata(
'close',
'Close the named app, or close the active session app when app is omitted. The shutdown option also stops the session simulator or emulator where supported; close alone never stops the device. Android ADB close fails with android-app-close-timeout if the app stays foreground past 2s, a killed process does not exit within 10s, or a new process runs past 2s; a relaunching open accepts that new process. For foreground timeouts, JSON details include foregroundObservations and initialProcessCount; the android_close_foreground_fence request diagnostic retains the last five probe results and timings, including when a probe throws. It fails with android-process-probe-unavailable when adb pidof cannot list the app processes; if that happens before the force-stop, the app keeps running. If close cannot confirm its cleanup on a session that holds a device claim, the session and its claim stay. A repeated close retries cleanup with the same options, except that save-script must be omitted after publication.',
"Close the named app, or close the active session app when app is omitted. When this session's open booted a local simulator or emulator, close stops it too, leaving the device as the session found it; a device that was already running keeps running. When the emulator process its own open launched is gone or cannot be verified, plain close leaves the emulator running and warns. Pass shutdown to explicitly stop a local simulator or emulator regardless of boot ownership. A daemon whose policy denies device-shutdown skips the implicit stop on plain close, which succeeds with a warning that the local device stays running. Explicit close with shutdown fails with UNAUTHORIZED and details.reason DAEMON_POLICY_DENIED. 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. For foreground timeouts, JSON details include foregroundObservations and initialProcessCount; the android_close_foreground_fence request diagnostic retains the last five probe results and timings, including when a probe throws. It fails with android-process-probe-unavailable when adb pidof cannot list the app processes; if that happens before the force-stop, the app keeps running. If close cannot confirm its cleanup on a session that holds a device claim, the session and its claim stay. A repeated close retries cleanup with the same options, except that save-script must be omitted after publication.",
{
app: stringField('Optional app to close.'),
shutdown: booleanField('Shutdown the session/device where supported.'),
shutdown: booleanField(
'Shutdown the session/device where supported, even one this session did not boot.',
),
saveScript: jsonSchemaField<boolean | string>({
oneOf: [booleanSchema(), stringSchema()],
}),
Expand Down
40 changes: 40 additions & 0 deletions packages/contracts/src/device-boot.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { DeviceInfo } from '@agent-device/kernel/device';
import type { AndroidEmulatorLaunchIdentity } from './device-readiness-runtime.ts';

/**
* Why a device owner could not name the start of its current boot. `unobserved` covers every
Expand All @@ -23,3 +24,42 @@ export type DeviceBootObservation =
export type DeviceBootObservationService = Readonly<{
observeBootTimeMs(device: DeviceInfo): Promise<DeviceBootObservation>;
}>;

/**
* What the host says about the process that launched a device, read once immediately before a stop
* is asked for. `same` is the only answer that lets the stop proceed: `changed` is positive evidence
* that the recorded process is gone, so whoever answers the device address now is not the launch the
* caller caused, and `unverified` establishes nothing — the host refused to answer for the recorded
* process, or the caller recorded none. `not-applicable` is the answer for a device whose owner
* launches no host process, so the caller never has to know which owner answered.
*/
export type LaunchedProcessCheck = 'not-applicable' | 'same' | 'changed' | 'unverified';

/**
* Whether the process behind a launch took the shutdown asked of the device. `stopped` covers the
* process that exited on its own and the one that had to be stopped by pid; `unconfirmed` means it
* still runs after every stop the host was allowed to make.
*/
export type LaunchedProcessStopConfirmation = 'stopped' | 'unconfirmed';

/**
* The host half of a device boot: the one process this machine started to bring the device up.
* Owners answer for the device kinds that launch a host process and report `not-applicable` for
* every other leaf, so neutral orchestration can ask "is this still the launch I caused?" and "did
* it stop?" without naming a platform or a process tool. The caller passes the recorded launch
* identity (its pid and start time) through unchanged.
*
* Both members are bounded probes on the caller's decision path, so each stays well below the
* operation it precedes, and an unanswered probe leaves that operation as cautious as it was before
* the probe existed.
*/
export type LaunchedDeviceProcessService = Readonly<{
checkLaunchedProcess(
device: DeviceInfo,
identity: AndroidEmulatorLaunchIdentity | undefined,
): Promise<LaunchedProcessCheck>;
confirmLaunchedProcessStopped(
device: DeviceInfo,
identity: AndroidEmulatorLaunchIdentity,
): Promise<LaunchedProcessStopConfirmation>;
}>;
13 changes: 13 additions & 0 deletions packages/contracts/src/device-readiness-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import type { DeviceInventoryRequest } from './device-inventory.ts';
/** Typed `details.reason` every platform reports when the boot deadline expires. */
export const BOOT_TIMEOUT_REASON = 'boot_timeout';

export type AndroidEmulatorLaunchIdentity = Readonly<{ pid: number; startTime: string }>;

export type EnsureReadyInput = Readonly<{
onAndroidEmulatorLaunchIdentity?: (identity: AndroidEmulatorLaunchIdentity) => void;
serial?: string;
androidSerialAllowlist?: readonly string[];
/**
Expand Down Expand Up @@ -39,6 +42,16 @@ export type DeviceReadinessRuntimeHost = Readonly<{
androidEmulator: Readonly<{
discover(request: DeviceInventoryRequest, signal: AbortSignal): Promise<readonly DeviceInfo[]>;
launch(avdName: string, headless: boolean, bootBudgetMs: number): Promise<number>;
/**
* What this host's `launch` of `pid` recorded about the emulator process it started, or nothing
* when that launch is unknown here or its start time could not be read. The caller records it
* beside the serial the launch came up on, so a later stop can prove the running emulator is
* still that process.
*/
bindLaunchedEmulator?(
pid: number,
device: DeviceInfo,
): Promise<AndroidEmulatorLaunchIdentity | undefined>;
terminate(pid: number): Promise<void>;
}>;
}>;
2 changes: 1 addition & 1 deletion packages/contracts/src/replay-test-execution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ export type ReplayTestRunReplay = (
params: ReplayTestRunReplayParams,
) => Promise<ReplayTestAttemptOutcome>;

export type ReplayTestCleanupSession = (sessionName: string) => Promise<void>;
export type ReplayTestCleanupSession = (sessionName: string) => Promise<readonly string[] | void>;

/**
* Runs after the attempt settles and before cleanup. Returns a failure outcome when
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import type {
LaunchedProcessCheck,
LaunchedProcessStopConfirmation,
} from '@agent-device/contracts/device-boot';
import type { AndroidEmulatorLaunchIdentity } from '@agent-device/contracts/device-readiness-runtime';
import type { DeviceInfo } from '@agent-device/kernel/device';
import { vi } from 'vitest';

/**
* How the root-composed launched-process owner answers, so a close suite can name what the host said
* about the process its session launched without touching the real process table. Cases set the
* fields they care about and assert the close's branching on the answer; the process reads behind
* each answer, and what the composed owner really does per device kind, are pinned in the Android and
* composition lanes.
*/
export type LaunchedProcessOwnerAnswers = {
/** What the owner answers for its device kind when the recorded launch is still itself. */
check: LaunchedProcessCheck;
/** What the owner answers once a stop was asked for. */
confirmation: LaunchedProcessStopConfirmation;
/** Every check that was asked, in order, with what it was asked about. */
checks: Array<{ device: DeviceInfo; identity: AndroidEmulatorLaunchIdentity | undefined }>;
/** Every stop confirmation that was asked, in order. */
confirmations: AndroidEmulatorLaunchIdentity[];
};

/** The one model the two seams below answer from, shared by the fixture and the cases. */
export const launchedProcessOwnerAnswers: LaunchedProcessOwnerAnswers = {
check: 'same',
confirmation: 'stopped',
checks: [],
confirmations: [],
};

/** Returns the owner to a live, unchanged launched process that takes its stop, before each case. */
export function resetLaunchedProcessOwnerAnswers(): void {
launchedProcessOwnerAnswers.check = 'same';
launchedProcessOwnerAnswers.confirmation = 'stopped';
launchedProcessOwnerAnswers.checks.length = 0;
launchedProcessOwnerAnswers.confirmations.length = 0;
}

/**
* The double's one stated rule: an Android emulator is the device whose boot this host starts as a
* process it can later name, and a launch that recorded no identity has nothing to verify. Every
* other device answers `not-applicable`, so the caller stops it on the platform's answer alone.
*/
function answerForDevice(
device: DeviceInfo,
identity: AndroidEmulatorLaunchIdentity | undefined,
): LaunchedProcessCheck {
if (device.platform !== 'android' || device.kind !== 'emulator') return 'not-applicable';
return identity ? launchedProcessOwnerAnswers.check : 'unverified';
}

/** The launched-process answers over the model above, as stable module-level members. */
export const checkLaunchedProcessFixture = vi.fn(
async (
device: DeviceInfo,
identity: AndroidEmulatorLaunchIdentity | undefined,
): Promise<LaunchedProcessCheck> => {
launchedProcessOwnerAnswers.checks.push({ device, identity });
return answerForDevice(device, identity);
},
);

export const confirmLaunchedProcessStoppedFixture = vi.fn(
async (
_device: DeviceInfo,
identity: AndroidEmulatorLaunchIdentity,
): Promise<LaunchedProcessStopConfirmation> => {
launchedProcessOwnerAnswers.confirmations.push(identity);
return launchedProcessOwnerAnswers.confirmation;
},
);
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@ import {
export function lifecycleOperationsSpy(
overrides: Partial<ApplicationLifecycleRuntimeOperations> = {},
) {
// The returned handle is always the spy the loader installs, so a suite reads its calls whichever
// way it built the case. A supplied implementation becomes that spy's behaviour.
const finalizeApplicationClose = vi.fn<
ApplicationLifecycleRuntimeOperations['finalizeApplicationClose']
>(async () => ({}));
>(overrides.finalizeApplicationClose ?? (async () => ({})));
const loader: LifecycleOperationsLoader = async (device, signal, shutdownTarget) =>
Object.freeze({
...(await applicationLifecycleRuntimeFixture(device, signal, shutdownTarget)),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import type { SessionSurface } from '@agent-device/contracts/session';
import type { DeviceBootObservation } from '@agent-device/contracts/device-boot';
import type { DaemonPlatformServices } from '../../core/platform-services.ts';
import { unavailableDeviceRuntimeGateway } from './unavailable-device-runtime-gateway.ts';

import {
checkLaunchedProcessFixture,
confirmLaunchedProcessStoppedFixture,
} from './launched-process-owner-fixture.ts';
/**
* The `DaemonPlatformServices` port as the daemon suites answer it: every member is a plain
* `vi.fn` spy with a canned answer, never a re-implementation of a root platform rule. A suite
Expand All @@ -27,6 +30,10 @@ export function daemonPlatformServicesFixture(
deviceBootObservation: Object.freeze({
observeBootTimeMs: observeBootTimeMsFixture,
}),
launchedDeviceProcess: Object.freeze({
checkLaunchedProcess: checkLaunchedProcessFixture,
confirmLaunchedProcessStopped: confirmLaunchedProcessStoppedFixture,
}),
ensureLocalDeviceReady: ensureLocalDeviceReadyFixture,
resolveRequestedOpenSurface: resolveRequestedOpenSurfaceFixture,
validateOpenRelaunchTarget: validateOpenRelaunchTargetFixture,
Expand Down
42 changes: 39 additions & 3 deletions packages/daemon/src/core/__tests__/daemon-policy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { createTestDeviceInventoryGateways } from '@agent-device/device-selectio
import { makeIosSession } from '../../__tests__/support/session-factories.ts';
import { makeSessionStore } from '../../__tests__/support/store-factory.ts';
import { parseDaemonPolicy } from '@agent-device/daemon-contracts/daemon-policy-file';
import { acquireDeviceClaim } from '@agent-device/daemon-contracts/device-claims';
import {
assertDaemonPolicyAdmitsRequest,
restrictDeviceInventoryToDaemonPolicy,
Expand Down Expand Up @@ -52,14 +53,24 @@ function makeHandler(
inventory?: readonly DeviceInfo[];
providerInventory?: readonly DeviceInfo[];
leaseRegistry?: LeaseRegistry;
bootedByOpen?: true;
} = {},
) {
const sessionStore = makeSessionStore('agent-device-daemon-policy-');
sessionStore.publish('default', makeIosSession('default', { appBundleId: 'com.example.app' }));
const host = createTestHostEnvironment({
env: { ...process.env, AGENT_DEVICE_CLAIMS_DIR: mkdtempForTestSync('policy-claims-') },
});
sessionStore.publish(
'default',
makeIosSession('default', {
appBundleId: 'com.example.app',
bootedByOpen: options.bootedByOpen,
}),
);
const bind = vi.fn(lifecycleDeviceRuntimeGateway.bind);
const inspectFacts = vi.fn(lifecycleDeviceRuntimeGateway.inspectFacts);
const handler = createRequestHandler({
host: createTestHostEnvironment(),
host,
createCommandSurface: fakeCreateCommandSurface,
logPath: path.join(mkdtempForTestSync('daemon-policy'), 'daemon.log'),
token: 'test-token',
Expand All @@ -81,7 +92,7 @@ function makeHandler(
hostDiagnostics: hostDiagnosticsFixture(),
daemonPolicy,
});
return { handler, bind, inspectFacts };
return { handler, bind, inspectFacts, sessionStore, host };
}

function request(command: string, extra: Partial<DaemonRequest> = {}): DaemonRequest {
Expand Down Expand Up @@ -491,3 +502,28 @@ test('a policy that allows one web session device admits that session only, neve
expectPolicyDenied(await handler(openWeb(denied)), 'device');
}
});

test('plain close uses the loaded policy dependency and releases a boot-owned session without shutdown', async () => {
const { handler, sessionStore, host } = makeHandler(
policy({ capabilities: { deny: ['device-shutdown'] } }),
{ bootedByOpen: true },
);
const session = sessionStore.get('default')!;
const claim = await acquireDeviceClaim({
env: host.env,
device: session.device,
session: 'default',
workspace: host.cwd,
stateDir: sessionStore.resolveDaemonStateDir(),
reconcileOrphanedDeviceClaim: async () => ({ status: 'reconciled' as const }),
});
if (claim.status !== 'acquired') throw new Error('Expected an owned device claim');
session.deviceClaim = claim.ownership;
const response = await handler(request('close'));
expect(response).toMatchObject({
ok: true,
data: { warnings: [expect.stringContaining('device-shutdown')] },
});
if (response.ok) expect(response.data?.shutdown).toBeUndefined();
expect(sessionStore.get('default')).toBeUndefined();
});
9 changes: 8 additions & 1 deletion packages/daemon/src/core/daemon-policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,11 +92,18 @@ export function assertDaemonPolicyAdmitsDevice(policy: DaemonPolicy, device: Dev
});
}

export function isDaemonPolicyCapabilityDenied(
policy: DaemonPolicy,
capability: DaemonPolicyCapability,
): boolean {
return policy.deniedCapabilities.has(capability);
}

export function assertDaemonPolicyAllowsCapability(
policy: DaemonPolicy,
capability: DaemonPolicyCapability,
): void {
if (!policy.deniedCapabilities.has(capability)) return;
if (!isDaemonPolicyCapabilityDenied(policy, capability)) return;
throw policyDenied(policy, 'capability', `This daemon's policy denies ${capability}.`, {
capability,
});
Expand Down
Loading
Loading