diff --git a/docs/adr/0029-daemon-policy.md b/docs/adr/0029-daemon-policy.md index ad185a96f5..09be3c1234 100644 --- a/docs/adr/0029-daemon-policy.md +++ b/docs/adr/0029-daemon-policy.md @@ -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 @@ -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. diff --git a/docs/agents/device-verification.md b/docs/agents/device-verification.md index b11a045861..a3d8d02d36 100644 --- a/docs/agents/device-verification.md +++ b/docs/agents/device-verification.md @@ -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`: diff --git a/packages/client/src/__tests__/index-apps.test.ts b/packages/client/src/__tests__/index-apps.test.ts index a1e947a3b8..62fdca7bd0 100644 --- a/packages/client/src/__tests__/index-apps.test.ts +++ b/packages/client/src/__tests__/index-apps.test.ts @@ -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.']); +}); diff --git a/packages/command-output/src/output/result-serialization.test.ts b/packages/command-output/src/output/result-serialization.test.ts index 91bb7fdd3e..7d8692e551 100644 --- a/packages/command-output/src/output/result-serialization.test.ts +++ b/packages/command-output/src/output/result-serialization.test.ts @@ -1,6 +1,7 @@ import { test } from 'vitest'; import assert from 'node:assert/strict'; import { + serializeCloseResult, serializeInstallFromSourceResult, serializeOpenResult, serializeSessionListEntry, @@ -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' }); +}); diff --git a/packages/command-surface/src/management/app.ts b/packages/command-surface/src/management/app.ts index 9de7aa211a..d09427f1e2 100644 --- a/packages/command-surface/src/management/app.ts +++ b/packages/command-surface/src/management/app.ts @@ -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({ oneOf: [booleanSchema(), stringSchema()], }), diff --git a/packages/contracts/src/device-boot.ts b/packages/contracts/src/device-boot.ts index b69e386736..07e2184377 100644 --- a/packages/contracts/src/device-boot.ts +++ b/packages/contracts/src/device-boot.ts @@ -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 @@ -23,3 +24,42 @@ export type DeviceBootObservation = export type DeviceBootObservationService = Readonly<{ observeBootTimeMs(device: DeviceInfo): Promise; }>; + +/** + * 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; + confirmLaunchedProcessStopped( + device: DeviceInfo, + identity: AndroidEmulatorLaunchIdentity, + ): Promise; +}>; diff --git a/packages/contracts/src/device-readiness-runtime.ts b/packages/contracts/src/device-readiness-runtime.ts index 3271d4c019..06f8c79a42 100644 --- a/packages/contracts/src/device-readiness-runtime.ts +++ b/packages/contracts/src/device-readiness-runtime.ts @@ -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[]; /** @@ -39,6 +42,16 @@ export type DeviceReadinessRuntimeHost = Readonly<{ androidEmulator: Readonly<{ discover(request: DeviceInventoryRequest, signal: AbortSignal): Promise; launch(avdName: string, headless: boolean, bootBudgetMs: number): Promise; + /** + * 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; terminate(pid: number): Promise; }>; }>; diff --git a/packages/contracts/src/replay-test-execution.ts b/packages/contracts/src/replay-test-execution.ts index 75b97aa85d..1e7022c926 100644 --- a/packages/contracts/src/replay-test-execution.ts +++ b/packages/contracts/src/replay-test-execution.ts @@ -187,7 +187,7 @@ export type ReplayTestRunReplay = ( params: ReplayTestRunReplayParams, ) => Promise; -export type ReplayTestCleanupSession = (sessionName: string) => Promise; +export type ReplayTestCleanupSession = (sessionName: string) => Promise; /** * Runs after the attempt settles and before cleanup. Returns a failure outcome when diff --git a/packages/daemon/src/__tests__/support/launched-process-owner-fixture.ts b/packages/daemon/src/__tests__/support/launched-process-owner-fixture.ts new file mode 100644 index 0000000000..292b5de7b7 --- /dev/null +++ b/packages/daemon/src/__tests__/support/launched-process-owner-fixture.ts @@ -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 => { + launchedProcessOwnerAnswers.checks.push({ device, identity }); + return answerForDevice(device, identity); + }, +); + +export const confirmLaunchedProcessStoppedFixture = vi.fn( + async ( + _device: DeviceInfo, + identity: AndroidEmulatorLaunchIdentity, + ): Promise => { + launchedProcessOwnerAnswers.confirmations.push(identity); + return launchedProcessOwnerAnswers.confirmation; + }, +); diff --git a/packages/daemon/src/__tests__/support/lifecycle-operations-spy.ts b/packages/daemon/src/__tests__/support/lifecycle-operations-spy.ts index a86cff82c5..e46c79553c 100644 --- a/packages/daemon/src/__tests__/support/lifecycle-operations-spy.ts +++ b/packages/daemon/src/__tests__/support/lifecycle-operations-spy.ts @@ -14,9 +14,11 @@ import { export function lifecycleOperationsSpy( overrides: Partial = {}, ) { + // 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)), diff --git a/packages/daemon/src/__tests__/support/platform-services-fixture.ts b/packages/daemon/src/__tests__/support/platform-services-fixture.ts index bdcf8773f2..99ca01f310 100644 --- a/packages/daemon/src/__tests__/support/platform-services-fixture.ts +++ b/packages/daemon/src/__tests__/support/platform-services-fixture.ts @@ -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 @@ -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, diff --git a/packages/daemon/src/core/__tests__/daemon-policy.test.ts b/packages/daemon/src/core/__tests__/daemon-policy.test.ts index 7ae94124e5..b081de8644 100644 --- a/packages/daemon/src/core/__tests__/daemon-policy.test.ts +++ b/packages/daemon/src/core/__tests__/daemon-policy.test.ts @@ -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, @@ -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', @@ -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 { @@ -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(); +}); diff --git a/packages/daemon/src/core/daemon-policy.ts b/packages/daemon/src/core/daemon-policy.ts index 81c6357bda..0c79605a13 100644 --- a/packages/daemon/src/core/daemon-policy.ts +++ b/packages/daemon/src/core/daemon-policy.ts @@ -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, }); diff --git a/packages/daemon/src/core/platform-services.ts b/packages/daemon/src/core/platform-services.ts index 2d46422609..b8bbe9793d 100644 --- a/packages/daemon/src/core/platform-services.ts +++ b/packages/daemon/src/core/platform-services.ts @@ -1,5 +1,8 @@ import type { AppleSessionObservation } from '@agent-device/contracts/apple-session-observation'; -import type { DeviceBootObservationService } from '@agent-device/contracts/device-boot'; +import type { + DeviceBootObservationService, + LaunchedDeviceProcessService, +} from '@agent-device/contracts/device-boot'; import type { SessionSurface } from '@agent-device/contracts/session'; import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -11,15 +14,16 @@ export type EnsureLocalDeviceReady = (device: DeviceInfo, signal: AbortSignal) = /** * Root-composed platform services the daemon asks of the host machine for work that binds no - * device runtime, over mechanics the daemon must never name or load itself. The two observation - * members are published contracts types; readiness and open-target classification are signatures - * declared here over neutral types. Device execution is NOT in this port and never + * device runtime, over mechanics the daemon must never name or load itself. The observation and + * launched-process members are published contracts types; readiness and open-target classification + * are signatures declared here over neutral types. Device execution is NOT in this port and never * enters it (ADR 0019): it goes through the request-bound runtime binding * (`RequestExecutionScope.bindDevice`), whose owner facts stay the only admission authority. */ export type DaemonPlatformServices = Readonly<{ appleSessionObservation: AppleSessionObservation; deviceBootObservation: DeviceBootObservationService; + launchedDeviceProcess: LaunchedDeviceProcessService; ensureLocalDeviceReady: EnsureLocalDeviceReady; resolveRequestedOpenSurface(params: { device: DeviceInfo; diff --git a/packages/daemon/src/core/session-state.ts b/packages/daemon/src/core/session-state.ts index b93b1cded9..0a01a1b09a 100644 --- a/packages/daemon/src/core/session-state.ts +++ b/packages/daemon/src/core/session-state.ts @@ -1,3 +1,4 @@ +import type { AndroidEmulatorLaunchIdentity } from '@agent-device/contracts/device-readiness-runtime'; import type { SnapshotDiagnosticsState } from '@agent-device/contracts/capture'; import type { AppLogFailure, AppLogLiveHandle } from '@agent-device/contracts/app-log-runtime'; import type { AudioProbeLiveHandle } from '@agent-device/contracts/audio-probe-runtime'; @@ -173,6 +174,15 @@ export type SessionState = { ownerStartTime: string | null; }; device: DeviceInfo; + /** + * #4162: this session's `open` booted the local simulator or emulator it now holds, so a plain + * `close` stops it and leaves the device as the session found it. Recorded only when device + * selection reports the boot (`selection.bootOccurred`), which never happens for a provider or + * physical target, nor for a device that was already running. The open-state publisher sets it + * through `SessionStore.updateOpenDevice`; changing device identity clears it. Close only reads it. + */ + bootedByOpen?: true; + androidLaunchIdentity?: AndroidEmulatorLaunchIdentity; createdAt: number; surface?: SessionSurface; appBundleId?: string; diff --git a/packages/daemon/src/core/session-store.ts b/packages/daemon/src/core/session-store.ts index 203d1277c2..eb77495296 100644 --- a/packages/daemon/src/core/session-store.ts +++ b/packages/daemon/src/core/session-store.ts @@ -1,3 +1,4 @@ +import type { AndroidEmulatorLaunchIdentity } from '@agent-device/contracts/device-readiness-runtime'; import { resolveSessionDir, resolveSessionAppLogPath, @@ -8,7 +9,12 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; import path from 'node:path'; import fs from 'node:fs'; import { AppError } from '@agent-device/kernel/errors'; -import { devicesOverlap } from '@agent-device/kernel/device'; +import { + devicesOverlap, + deviceIdentity, + sameDeviceIdentity, + type DeviceInfo, +} from '@agent-device/kernel/device'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import type { SessionRef, SessionRuntimeHints, SessionState } from './session-state.ts'; import { recordActionEntry, type RecordActionEntry } from './session-action-recorder.ts'; @@ -418,6 +424,27 @@ export class SessionStore { session.lastActivityAtMs = atMs; } + /** Keep boot ownership and its launch identity together for the same device identity. */ + updateOpenDevice( + ref: SessionRef, + device: DeviceInfo, + bootOccurred: boolean, + androidLaunchIdentity?: AndroidEmulatorLaunchIdentity, + ): void { + const current = this.requireCurrent(ref); + const retainsBoot = sameDeviceIdentity(deviceIdentity(current.device), deviceIdentity(device)); + const ownsBoot = bootOccurred || (retainsBoot && current.bootedByOpen === true); + this.update(ref, { + device, + androidLaunchIdentity: bootOccurred + ? androidLaunchIdentity + : retainsBoot + ? current.androidLaunchIdentity + : undefined, + bootedByOpen: ownsBoot ? true : undefined, + }); + } + /** * Marks a session kept after unconfirmed close effects or a relaunch that failed or was canceled * after dispatch, so daemon idle reap no longer waits on it. A successful reopen clears the mark; diff --git a/packages/daemon/src/core/stopped-local-android-device.ts b/packages/daemon/src/core/stopped-local-android-device.ts index 540e670a19..cf09e69924 100644 --- a/packages/daemon/src/core/stopped-local-android-device.ts +++ b/packages/daemon/src/core/stopped-local-android-device.ts @@ -1,4 +1,5 @@ import type { RuntimeOwnerRef } from '@agent-device/contracts/platform-runtime'; +import type { AndroidEmulatorLaunchIdentity } from '@agent-device/contracts/device-readiness-runtime'; import { ensureReadyUse } from '@agent-device/contracts/platform-runtime-operations'; import type { DeviceInfo } from '@agent-device/kernel/device'; import type { EnvMap } from '@agent-device/kernel/source-value'; @@ -24,6 +25,7 @@ export async function bootStoppedLocalAndroidDevice(params: { flags: Pick; env: EnvMap; deadlineAtMs: number | undefined; + onAndroidEmulatorLaunchIdentity?: (identity: AndroidEmulatorLaunchIdentity) => void; }): Promise { const { device, owner } = params; if (owner.kind !== 'local-family' || device.platform !== 'android' || device.booted === true) { @@ -33,5 +35,6 @@ export async function bootStoppedLocalAndroidDevice(params: { return await readiness.operations.ensureReady({ androidSerialAllowlist: resolveSortedAndroidSerialAllowlist(params.flags, params.env), deadlineAtMs: params.deadlineAtMs, + onAndroidEmulatorLaunchIdentity: params.onAndroidEmulatorLaunchIdentity, }); } diff --git a/packages/daemon/src/server/__tests__/request-router-replay-scope.test.ts b/packages/daemon/src/server/__tests__/request-router-replay-scope.test.ts index afa6929bbe..53a778bb0d 100644 --- a/packages/daemon/src/server/__tests__/request-router-replay-scope.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-replay-scope.test.ts @@ -45,6 +45,11 @@ import { } from '../../__tests__/support/test-device-runtime-gateway.ts'; // Readiness is package-owned; hold the open at the fixture's platform-neutral readiness gate. import { awaitFixtureReadiness } from '../../__tests__/support/application-lifecycle-runtime-fixture.ts'; +import { parseDaemonPolicy } from '@agent-device/daemon-contracts/daemon-policy-file'; +import { acquireDeviceClaim } from '@agent-device/daemon-contracts/device-claims'; +import { platformResourceCleanupFixture } from '../../__tests__/support/platform-resource-cleanup-fixture.ts'; +import { readResponseWarnings } from '@agent-device/kernel/success-text'; +import { toReplayTestAttemptOutcome } from '@agent-device/replay-port/session-test-outcome'; const mockResolveTargetDevice = vi.mocked(getResolveTargetDeviceMock()); const mockAwaitFixtureReadiness = vi.mocked(awaitFixtureReadiness); @@ -60,6 +65,68 @@ beforeEach(() => { mockAwaitFixtureReadiness.mockResolvedValue(undefined); }); +test.each([false, true])( + 'same-session replay close preserves denied-stop warnings (later failure: %s)', + async (laterFailure) => { + const root = mkdtempForTestSync('agent-device-replay-close-policy-'); + const replayPath = path.join(root, 'close.ad'); + fs.writeFileSync(replayPath, laterFailure ? 'close\napp-switcher\n' : 'close\n'); + const sessionStore = makeSessionStore('agent-device-replay-close-policy-'); + const host = createTestHostEnvironment({ + env: { ...process.env, AGENT_DEVICE_CLAIMS_DIR: path.join(root, 'claims') }, + }); + const session = makeIosSession('default', { + bootedByOpen: true, + appBundleId: 'com.example.app', + }); + 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; + sessionStore.publish('default', session); + const cleanup = platformResourceCleanupFixture(); + const handler = createRequestHandler({ + host, + createCommandSurface: testCreateCommandSurface, + logPath: path.join(root, 'daemon.log'), + token: 'test-token', + sessionStore, + leaseRegistry: new LeaseRegistry(), + deviceRuntimeGateway: lifecycleDeviceRuntimeGateway, + deviceInventoryGateways: createTestDeviceInventoryGateways(), + platformResourceCleanup: cleanup, + daemonPolicy: parseDaemonPolicy( + { version: 1, capabilities: { deny: ['device-shutdown'] } }, + path.join(root, 'policy.json'), + ), + trackDownloadableArtifact: () => 'artifact-id', + }); + const response = await handler({ + token: 'test-token', + session: 'default', + command: 'replay', + positionals: [replayPath], + meta: { cwd: root, requestId: 'replay-close-policy', sessionExplicit: true }, + }); + expect(response.ok).toBe(!laterFailure); + const warnings = readResponseWarnings(response.ok ? response.data : response.error.details); + expect(warnings).toEqual([ + "This session's open booted this device and close would stop it, but this daemon's policy denies device-shutdown. The device is still running.", + ]); + expect(toReplayTestAttemptOutcome(response).warnings).toEqual(warnings); + expect(cleanup.retainExecutionHostAfterClose).toHaveBeenCalledWith( + expect.objectContaining({ shutdownRequested: false }), + ); + expect(sessionStore.listRefs()).toHaveLength(0); + }, +); + test('replay runs active-session actions inside the parent request provider scope', async () => { const root = mkdtempForTestSync('agent-device-replay-scope-'); const replayPath = path.join(root, 'flow.ad'); diff --git a/packages/daemon/src/server/request-router.ts b/packages/daemon/src/server/request-router.ts index d1ba73edb8..e539959cb4 100644 --- a/packages/daemon/src/server/request-router.ts +++ b/packages/daemon/src/server/request-router.ts @@ -113,7 +113,10 @@ import type { CreateDaemonCommandSurface } from '@agent-device/contracts/daemon- import type { PlatformResourceCleanup } from '../core/platform-resource-cleanup.ts'; import type { DaemonPlatformServices } from '../core/platform-services.ts'; import type { DaemonProviderCredentials } from '@agent-device/daemon-contracts/provider-credentials'; -import { restrictDeviceInventoryToDaemonPolicy } from '../core/daemon-policy.ts'; +import { + restrictDeviceInventoryToDaemonPolicy, + isDaemonPolicyCapabilityDenied, +} from '../core/daemon-policy.ts'; import type { DaemonPolicy } from '@agent-device/daemon-contracts/daemon-policy-file'; // --------------------------------------------------------------------------- @@ -194,6 +197,8 @@ export function createRequestHandler(deps: RequestRouterDeps): DaemonInvokeFn { daemonPolicy, } = deps; const { sessionStore, leaseRegistry } = deps; + const deviceShutdownDenied = + daemonPolicy !== undefined && isDaemonPolicyCapabilityDenied(daemonPolicy, 'device-shutdown'); const deviceInventoryGateways = daemonPolicy ? restrictDeviceInventoryToDaemonPolicy(deps.deviceInventoryGateways, daemonPolicy) : deps.deviceInventoryGateways; @@ -427,6 +432,7 @@ export function createRequestHandler(deps: RequestRouterDeps): DaemonInvokeFn { androidObservation, createCommandSurface, platformResourceCleanup, + deviceShutdownDenied, bindDevice: lockedScope.bindDevice, platformServices: lockedScope.platformServices, inspectFacts: lockedScope.inspectFacts, diff --git a/packages/daemon/src/sessions/handlers/__tests__/session-replay-command.test.ts b/packages/daemon/src/sessions/handlers/__tests__/session-replay-command.test.ts index ae2d6cd83d..d478b8e2c6 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/session-replay-command.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/session-replay-command.test.ts @@ -21,6 +21,8 @@ import { mockInspectDeviceRuntimeFacts, } from '../../../__tests__/support/handlers/session-command-harness.ts'; import type { EndedLeaseLedger } from '../../../core/request-ended-leases.ts'; +import { lifecycleOperationsSpy } from '../../../__tests__/support/lifecycle-operations-spy.ts'; +import { acquireDeviceClaim } from '@agent-device/daemon-contracts/device-claims'; test('replay test handler threads the complete video owner into the application command', async () => { const root = mkdtempForTestSync('agent-device-replay-handler-video-'); @@ -65,63 +67,91 @@ test('replay test handler threads the complete video owner into the application expect(response.error.message).not.toContain('Screen-recording runtime is not configured'); }); -test('replay test session cleanup reports the lease it ended on the test request', async () => { - const root = mkdtempForTestSync('agent-device-replay-handler-ended-lease-'); - const scriptPath = path.join(root, 'opens.ad'); - fs.writeFileSync(scriptPath, 'context platform=ios\nopen "com.example.app"\n'); - const sessionStore = makeSessionStore(); - const leaseRegistry = new LeaseRegistry(); - const lease = leaseRegistry.allocateLease({ tenantId: 'tenant-a', runId: 'run-1' }); - const endedLeases: EndedLeaseLedger = []; - const wireReq = await withClientReplayScriptSources({ - token: 'token', - session: 'default', - command: 'test', - positionals: [scriptPath], - flags: {}, - meta: { cwd: root, requestId: 'replay-handler-ended-lease' }, - }); - const params: SessionCommandParams = { - host: createTestHostEnvironment(), - createCommandSurface: fakeCreateCommandSurface, - req: { ...wireReq, internal: { endedLeases } }, - sessionName: 'default', - logPath: path.join(root, 'daemon.log'), - sessionStore, - platformServices: daemonPlatformServicesFixture(), - leaseRegistry, - invoke: async (nestedReq) => { - if (nestedReq.command === 'open' && nestedReq.session) { - sessionStore.publish( - nestedReq.session, - makeIosSession(nestedReq.session, { +test.each([false, true])( + 'suite cleanup ends its lease and preserves denied-shutdown policy: %s', + async (shutdownDenied) => { + const root = mkdtempForTestSync('agent-device-replay-handler-ended-lease-'); + const host = createTestHostEnvironment({ + env: { ...process.env, AGENT_DEVICE_CLAIMS_DIR: path.join(root, 'claims') }, + }); + const scriptPath = path.join(root, 'opens.ad'); + fs.writeFileSync(scriptPath, 'context platform=ios\nopen "com.example.app"\n'); + const sessionStore = makeSessionStore(); + const leaseRegistry = new LeaseRegistry(); + const lease = leaseRegistry.allocateLease({ tenantId: 'tenant-a', runId: 'run-1' }); + const endedLeases: EndedLeaseLedger = []; + const { loader, finalizeApplicationClose } = lifecycleOperationsSpy(); + const wireReq = await withClientReplayScriptSources({ + token: 'token', + session: 'default', + command: 'test', + positionals: [scriptPath], + flags: {}, + meta: { cwd: root, requestId: 'replay-handler-ended-lease' }, + }); + const params: SessionCommandParams = { + host, + createCommandSurface: fakeCreateCommandSurface, + req: { + ...wireReq, + internal: { endedLeases }, + }, + deviceShutdownDenied: shutdownDenied, + sessionName: 'default', + logPath: path.join(root, 'daemon.log'), + sessionStore, + platformServices: daemonPlatformServicesFixture(), + leaseRegistry, + invoke: async (nestedReq) => { + if (nestedReq.command === 'open' && nestedReq.session) { + const session = makeIosSession(nestedReq.session, { + bootedByOpen: true, lease: { leaseId: lease.leaseId, tenantId: lease.tenantId, runId: lease.runId }, - }), - ); - } - return { ok: true, data: {} }; - }, - inspectFacts: mockInspectDeviceRuntimeFacts, - bindDevice: mockBindDeviceRuntime, - bindExactDevice: unavailableBindExactDevice, - screenRecordingAdmissionLedger: createScreenRecordingAdmissionLedger(), - requestScope: { - signal: new AbortController().signal, - diagnostics: { emit: () => {} }, - progress: { report: () => {} }, - }, - retainDeviceExecutionLock: async () => {}, - throwIfCanceled: () => {}, - reconcileOrphanedDeviceClaim: async () => ({ - status: 'retained' as const, - reason: 'handler-test' as const, - }), - platformResourceCleanup: platformResourceCleanupFixture(), - }; + }); + const claim = await acquireDeviceClaim({ + env: host.env, + device: session.device, + session: nestedReq.session, + workspace: host.cwd, + stateDir: sessionStore.resolveDaemonStateDir(), + reconcileOrphanedDeviceClaim: async () => ({ status: 'reconciled' }), + }); + if (claim.status !== 'acquired') throw new Error('Expected an owned replay device claim'); + session.deviceClaim = claim.ownership; + sessionStore.publish(nestedReq.session, session); + } + return { ok: true, data: {} }; + }, + inspectFacts: mockInspectDeviceRuntimeFacts, + bindDevice: (device, use) => mockBindDeviceRuntime(device, use, undefined, loader), + bindExactDevice: unavailableBindExactDevice, + screenRecordingAdmissionLedger: createScreenRecordingAdmissionLedger(), + requestScope: { + signal: new AbortController().signal, + diagnostics: { emit: () => {} }, + progress: { report: () => {} }, + }, + retainDeviceExecutionLock: async () => {}, + throwIfCanceled: () => {}, + reconcileOrphanedDeviceClaim: async () => ({ + status: 'retained' as const, + reason: 'handler-test' as const, + }), + platformResourceCleanup: platformResourceCleanupFixture(), + }; - const response = await handleReplayTestCommand(params); + const response = await handleReplayTestCommand(params); - expect(response).toMatchObject({ ok: true }); - expect(endedLeases).toEqual([{ leaseId: lease.leaseId, outcome: 'released' }]); - expect(leaseRegistry.listActiveLeases()).toHaveLength(0); -}); + expect(response).toMatchObject({ ok: true }); + if (response?.ok) { + const tests = response.data?.tests; + if (!Array.isArray(tests)) throw new Error('Expected suite test results'); + expect(tests[0]?.warnings).toEqual(shutdownDenied ? [expect.any(String)] : undefined); + } + expect(endedLeases).toEqual([{ leaseId: lease.leaseId, outcome: 'released' }]); + expect(leaseRegistry.listActiveLeases()).toHaveLength(0); + expect(finalizeApplicationClose).toHaveBeenCalledWith( + expect.objectContaining({ shutdownTarget: !shutdownDenied }), + ); + }, +); diff --git a/packages/daemon/src/sessions/handlers/session-command-input.ts b/packages/daemon/src/sessions/handlers/session-command-input.ts index aa48ff5afa..a99609a278 100644 --- a/packages/daemon/src/sessions/handlers/session-command-input.ts +++ b/packages/daemon/src/sessions/handlers/session-command-input.ts @@ -48,6 +48,7 @@ export type SessionCommandInput = { reconcileOrphanedDeviceClaim: DeviceClaimReconciler; createCommandSurface: CreateDaemonCommandSurface; platformResourceCleanup?: PlatformResourceCleanup; + deviceShutdownDenied?: boolean; }; export type SessionCommandParams = Omit & { diff --git a/packages/daemon/src/sessions/handlers/session-replay-command.ts b/packages/daemon/src/sessions/handlers/session-replay-command.ts index e266b72b86..a14db88ace 100644 --- a/packages/daemon/src/sessions/handlers/session-replay-command.ts +++ b/packages/daemon/src/sessions/handlers/session-replay-command.ts @@ -1,3 +1,4 @@ +import { readResponseWarnings } from '@agent-device/kernel/success-text'; import { resolveSessionTestArtifactsRoot } from '@agent-device/daemon-contracts/session-artifact-paths'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { DaemonPlatformServices } from '../../core/platform-services.ts'; @@ -100,6 +101,7 @@ export const handleReplayTestCommand: SessionCommandHandler = async ({ retainDeviceExecutionLock, throwIfCanceled, platformResourceCleanup, + deviceShutdownDenied, }) => { if (!platformResourceCleanup) { throw new AppError( @@ -155,6 +157,7 @@ export const handleReplayTestCommand: SessionCommandHandler = async ({ bindDevice, platformServices, platformResourceCleanup, + deviceShutdownDenied, }), ...(video ? { video } : {}), }); @@ -311,11 +314,14 @@ type ReplayTestSessionCleanupParams = Readonly<{ platformServices: DaemonPlatformServices; bindDevice?: BindDeviceRuntime; platformResourceCleanup: PlatformResourceCleanup; + deviceShutdownDenied?: boolean; }>; -async function closeReplayTestSession(params: ReplayTestSessionCleanupParams): Promise { +async function closeReplayTestSession( + params: ReplayTestSessionCleanupParams, +): Promise { const { req, sessionName, logPath, sessionStore } = params; - if (!sessionStore.get(sessionName)) return; + if (!sessionStore.get(sessionName)) return []; const closeResponse = await handleSessionCloseCommands({ host: params.host, req: onDelegatingLedger( @@ -326,7 +332,9 @@ async function closeReplayTestSession(params: ReplayTestSessionCleanupParams): P positionals: [], flags: {}, meta: req.meta, - internal: { cleanupIntent: 'suite-owned-test-session' }, + internal: { + cleanupIntent: 'suite-owned-test-session', + }, }, req, ), @@ -339,8 +347,9 @@ async function closeReplayTestSession(params: ReplayTestSessionCleanupParams): P platformServices: params.platformServices, bindDevice: params.bindDevice, platformResourceCleanup: params.platformResourceCleanup, + deviceShutdownDenied: params.deviceShutdownDenied, }); - if (closeResponse.ok) return; + if (closeResponse.ok) return readResponseWarnings(closeResponse.data); throw new AppError(closeResponse.error.code, closeResponse.error.message, { ...(closeResponse.error.details ?? {}), ...(closeResponse.error.hint ? { hint: closeResponse.error.hint } : {}), diff --git a/packages/daemon/src/sessions/handlers/session.ts b/packages/daemon/src/sessions/handlers/session.ts index e3dbd80e07..f065030d9e 100644 --- a/packages/daemon/src/sessions/handlers/session.ts +++ b/packages/daemon/src/sessions/handlers/session.ts @@ -62,6 +62,7 @@ const handleSessionCloseCommandGroup: SessionCommandHandler = (params) => platformServices: params.platformServices, bindDevice: params.bindDevice, platformResourceCleanup: params.platformResourceCleanup, + deviceShutdownDenied: params.deviceShutdownDenied, } satisfies SessionCloseCommandInput); const handleSessionObservabilityCommandGroup: SessionCommandHandler = async ({ @@ -268,5 +269,6 @@ export async function handleSessionCommands( throwIfCanceled, reconcileOrphanedDeviceClaim, platformResourceCleanup, + deviceShutdownDenied: params.deviceShutdownDenied, }); } diff --git a/packages/daemon/src/sessions/request-handler-chain.ts b/packages/daemon/src/sessions/request-handler-chain.ts index 97b6236e15..ca9343ab7d 100644 --- a/packages/daemon/src/sessions/request-handler-chain.ts +++ b/packages/daemon/src/sessions/request-handler-chain.ts @@ -59,6 +59,7 @@ type RequestHandlerChainParams = { androidObservation?: AndroidObservationAdapter; createCommandSurface: CreateDaemonCommandSurface; platformResourceCleanup?: PlatformResourceCleanup; + deviceShutdownDenied?: boolean; bindDevice: BindDeviceRuntime; platformServices: DaemonPlatformServices; inspectFacts: InspectDeviceRuntimeFacts; @@ -206,6 +207,7 @@ async function runSessionHandler( retainDeviceExecutionLock: params.retainDeviceExecutionLock, throwIfCanceled: params.throwIfCanceled, platformResourceCleanup: params.platformResourceCleanup, + deviceShutdownDenied: params.deviceShutdownDenied, }), ); } diff --git a/packages/daemon/src/sessions/session-lifecycle/__tests__/application.test.ts b/packages/daemon/src/sessions/session-lifecycle/__tests__/application.test.ts index 8d7e9aa894..b182be4112 100644 --- a/packages/daemon/src/sessions/session-lifecycle/__tests__/application.test.ts +++ b/packages/daemon/src/sessions/session-lifecycle/__tests__/application.test.ts @@ -61,13 +61,17 @@ function request(command: DaemonRequest['command']): DaemonRequest { }; } -async function run(command: DaemonRequest['command']): Promise { +async function run( + command: DaemonRequest['command'], + deviceShutdownDenied?: boolean, +): Promise { return await handleSessionCommands({ requestScope: platformRequestScopeFixture(), host: createTestHostEnvironment(), createCommandSurface: fakeCreateCommandSurface, platformServices: daemonPlatformServicesFixture(), req: request(command), + deviceShutdownDenied, sessionName: 'default', logPath: '/tmp/agent-device-session-lifecycle-route.log', sessionStore: makeSessionStore('agent-device-session-lifecycle-route-'), @@ -142,31 +146,36 @@ test('open routes only its lifecycle input through its owner', async () => { }); }); -test('close routes only its lifecycle input through its owner', async () => { - const expected: DaemonResponse = { ok: true, data: { session: 'default' } }; - mockHandleSessionCloseCommands.mockImplementationOnce(async () => expected); - - await expect(run('close')).resolves.toEqual(expected); - - const forwarded = mockHandleSessionCloseCommands.mock.calls.at(-1)?.[0]; - expect(Object.keys(forwarded ?? {}).sort()).toEqual( - [ - 'bindDevice', - 'host', - 'inspectFacts', - 'leaseLifecycleProvider', - 'leaseRegistry', - 'logPath', - 'platformResourceCleanup', - 'platformServices', - 'req', - 'sessionName', - 'sessionStore', - ].sort(), - ); - expect(forwarded).toMatchObject({ - req: expect.objectContaining({ command: 'close' }), - sessionName: 'default', - logPath: '/tmp/agent-device-session-lifecycle-route.log', - }); -}); +test.each([true, false])( + 'close routes only its lifecycle input through its owner (shutdown denied: %s)', + async (deviceShutdownDenied) => { + const expected: DaemonResponse = { ok: true, data: { session: 'default' } }; + mockHandleSessionCloseCommands.mockImplementationOnce(async () => expected); + + await expect(run('close', deviceShutdownDenied)).resolves.toEqual(expected); + + const forwarded = mockHandleSessionCloseCommands.mock.calls.at(-1)?.[0]; + expect(Object.keys(forwarded ?? {}).sort()).toEqual( + [ + 'bindDevice', + 'deviceShutdownDenied', + 'host', + 'inspectFacts', + 'leaseLifecycleProvider', + 'leaseRegistry', + 'logPath', + 'platformResourceCleanup', + 'platformServices', + 'req', + 'sessionName', + 'sessionStore', + ].sort(), + ); + expect(forwarded).toMatchObject({ + deviceShutdownDenied, + req: expect.objectContaining({ command: 'close' }), + sessionName: 'default', + logPath: '/tmp/agent-device-session-lifecycle-route.log', + }); + }, +); diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-external-reboot.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-external-reboot.test.ts new file mode 100644 index 0000000000..efe6799f4e --- /dev/null +++ b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-external-reboot.test.ts @@ -0,0 +1,417 @@ +// #4585: plain `close` owes a stop to the PROCESS its own `open` launched, not to whichever process +// answers the serial now. Routed through the session command handler, so claim acquisition, renewal, +// launch-identity recording and close teardown all run against real claim files. What the host says +// about the launched process is answered by the launched-process owner fixture, exactly as the +// composed owner answers it — the process reads themselves are pinned in the Android and +// composition lanes. +import { afterEach, beforeEach, expect, test, vi } from 'vitest'; +import path from 'node:path'; +import * as hostProcess from '@agent-device/host-kit/process'; +import { + bindTestCommandHost, + createTestHostEnvironment, + mkdtempForTestSync, + pinOwnProcessStartTime, +} from '@agent-device/test-kit'; + +vi.mock('@agent-device/device-selection/dispatch-resolve', async (importOriginal) => { + const actual = + await importOriginal(); + const { selectionFromResolveTargetDevice } = + await import('../../../../__tests__/support/device-selection-stub.ts'); + const resolveTargetDevice = vi.fn(); + return { + ...actual, + resolveTargetDevice, + resolveTargetDeviceSelection: vi.fn(selectionFromResolveTargetDevice(resolveTargetDevice)), + }; +}); + +import { + launchedProcessOwnerAnswers as owner, + resetLaunchedProcessOwnerAnswers, +} from '../../../../__tests__/support/launched-process-owner-fixture.ts'; + +/** The identity `open` records for the emulator process it launched. */ +const LAUNCH_IDENTITY = { pid: 4112, startTime: 'launch-start-time' } as const; +import { fakeCreateCommandSurface } from '../../../../__tests__/support/command-surface-fake.ts'; +import { daemonPlatformServicesFixture } from '../../../../__tests__/support/platform-services-fixture.ts'; +import type { CloseApplicationFinalizationInput } from '@agent-device/contracts/application-lifecycle-runtime'; +import { + applicationLifecycleRuntimeFixture, + type LifecycleOperationsLoader, +} from '../../../../__tests__/support/application-lifecycle-runtime-fixture.ts'; +import { + handleSessionCommands, + mockEnsureReadyRuntime, + mockShutdownTargetRuntime, +} from '../../../../__tests__/support/handlers/session-command-harness.ts'; +import { + clearDeviceClaim, + inspectDeviceClaims, +} from '@agent-device/daemon-contracts/device-claims'; +import { SessionStore } from '../../../../core/session-store.ts'; +import { resolveTargetDevice } from '@agent-device/device-selection/dispatch-resolve'; +import type { DeviceInfo } from '@agent-device/kernel/device'; + +pinOwnProcessStartTime(hostProcess); +bindTestCommandHost(); + +const SESSION = 'implicit-shutdown-session'; + +/** The AVD as inventory lists it while stopped: addressed by its AVD name, not booted. */ +const STOPPED_AVD: DeviceInfo = { + platform: 'android', + id: 'pixel-avd', + name: 'Pixel_9_API_37', + kind: 'emulator', + booted: false, +}; + +/** The same emulator once it runs. An outside restart keeps this identity and serial. */ +const BOOTED_EMULATOR: DeviceInfo = { + platform: 'android', + id: 'emulator-5554', + name: 'Pixel_9_API_37', + kind: 'emulator', + booted: true, +}; + +function createRoutedSession() { + const stateDir = mkdtempForTestSync('agent-device-session-close-launch-owner-'); + const env: NodeJS.ProcessEnv = { + ...process.env, + AGENT_DEVICE_CLAIMS_DIR: path.join(stateDir, 'claims'), + }; + const sessionStore = new SessionStore(path.join(stateDir, 'sessions'), { + env, + cwd: process.cwd(), + }); + + async function run(command: { + name: 'open' | 'close'; + flags?: Record; + /** Only a cold open selects a device, and that selection is what boots the stopped AVD. */ + selectsDevice?: boolean; + deviceShutdownDenied?: boolean; + /** A cold open whose readiness never reported the process it launched. */ + omitLaunchIdentity?: boolean; + /** Runs while close dispatches its platform close, before the stop is asked for. */ + duringPlatformClose?: () => void; + }) { + if (command.selectsDevice) { + vi.mocked(resolveTargetDevice).mockResolvedValue(STOPPED_AVD); + mockEnsureReadyRuntime.mockImplementation(async (input) => { + if (!command.omitLaunchIdentity) input.onAndroidEmulatorLaunchIdentity?.(LAUNCH_IDENTITY); + return BOOTED_EMULATOR; + }); + } + // Record the close finalization the daemon asks for, while keeping the fixture's own leaf + // shutdown, so `mockShutdownTargetRuntime` still counts the stop the platform was asked to do. + const finalizeAsks: CloseApplicationFinalizationInput[] = []; + const loader: LifecycleOperationsLoader = async (device, signal, shutdownTarget) => { + const operations = await applicationLifecycleRuntimeFixture(device, signal, shutdownTarget); + const finalizeApplicationClose = operations.finalizeApplicationClose; + return Object.freeze({ + ...operations, + finalizeApplicationClose: async (input) => { + finalizeAsks.push(input); + return await finalizeApplicationClose(input); + }, + ...(command.duringPlatformClose + ? { + closeApplication: async (...args: Parameters) => { + command.duringPlatformClose?.(); + return await operations.closeApplication(...args); + }, + } + : {}), + }); + }; + const response = await handleSessionCommands({ + host: createTestHostEnvironment({ env }), + createCommandSurface: fakeCreateCommandSurface, + platformServices: daemonPlatformServicesFixture(), + sessionStore, + invoke: async () => ({ ok: true, data: {} }), + lifecycleOperationsLoader: loader, + ...(command.deviceShutdownDenied === undefined + ? {} + : { deviceShutdownDenied: command.deviceShutdownDenied }), + req: { + token: 't', + command: command.name, + session: SESSION, + positionals: ['Demo'], + flags: command.flags ?? {}, + }, + sessionName: SESSION, + logPath: path.join(stateDir, 'daemon.log'), + }); + return { response, finalizeAsks }; + } + + /** Claims on disk for this case's device, which a successful close releases with the session. */ + function sessionClaimCount() { + return inspectDeviceClaims({ serial: BOOTED_EMULATOR.id }, env).length; + } + + return { + dropSessionClaim: async () => { + const ownership = sessionStore.get(SESSION)?.deviceClaim; + if (!ownership) throw new Error('expected the session to record its claim'); + await clearDeviceClaim(ownership, env); + }, + run, + sessionClaimCount, + sessionStore, + }; +} + +/** + * Opens a stopped AVD through the cold route and leaves the emulator running on the boot this + * session caused, with the launched process recorded as the host answered for it. + */ +async function openBootedByThisSession(runs: ReturnType) { + const opened = await runs.run({ + name: 'open', + flags: { platform: 'android' }, + selectsDevice: true, + }); + expect(opened.response?.ok).toBe(true); + const session = runs.sessionStore.get(SESSION); + // The boot fact and the identity of the process that caused it are written together, and that + // pair is the only thing close may act on. + expect(session?.bootedByOpen).toBe(true); + expect(session?.androidLaunchIdentity).toEqual(LAUNCH_IDENTITY); +} + +function closeWarningMessages(response: { ok?: unknown; data?: unknown }): unknown { + if (!response.ok) throw new Error('expected a successful close'); + return (response.data as { warnings?: string[] }).warnings; +} + +const PROCESS_CHANGED_WARNING = + "This session's open booted this device, but its emulator process has changed, so close did not request a stop. The device is still running."; +const PROCESS_UNVERIFIED_WARNING = + "This session's open booted this device, but close could not verify its emulator process identity, so it did not request a stop and left the device as it found it."; +const NO_LAUNCH_IDENTITY_WARNING = + "This session's open booted this device, but open recorded no emulator process identity, so close did not request a stop and left the device as it found it."; + +beforeEach(() => { + mockEnsureReadyRuntime.mockReset(); + mockEnsureReadyRuntime.mockResolvedValue(undefined); + resetLaunchedProcessOwnerAnswers(); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +test('plain close stops the emulator this session booted while it still runs that boot', async () => { + const runs = createRoutedSession(); + await openBootedByThisSession(runs); + + const closed = await runs.run({ name: 'close' }); + + expect(closed.response?.ok).toBe(true); + expect(closed.finalizeAsks).toEqual([ + expect.objectContaining({ shutdownTarget: true, retainRunner: false }), + ]); + expect(mockShutdownTargetRuntime).toHaveBeenCalledTimes(1); + expect(closeWarningMessages(closed.response!)).toBeUndefined(); + if (closed.response?.ok) + expect(closed.response.data).toMatchObject({ shutdown: { success: true } }); + // The launched process was asked about once, with the recorded identity, and confirmed as stopped, + // so nothing was escalated; the session is retired with its claim like any successful close. + expect(owner.checks).toEqual([{ device: BOOTED_EMULATOR, identity: LAUNCH_IDENTITY }]); + expect(owner.confirmations).toEqual([LAUNCH_IDENTITY]); + expect(runs.sessionStore.get(SESSION)).toBeUndefined(); + expect(runs.sessionClaimCount()).toBe(0); +}, 30_000); + +test('a replacement that takes the serial during platform close is not stopped', async () => { + const runs = createRoutedSession(); + await openBootedByThisSession(runs); + let platformCloseRan = false; + + // The launched process still runs when close starts. It is replaced while close dispatches its + // platform close, so the one ownership read, taken right before the stop, must see the change. + const closed = await runs.run({ + name: 'close', + duringPlatformClose: () => { + platformCloseRan = true; + expect(owner.checks).toEqual([]); + owner.check = 'changed'; + }, + }); + + expect(platformCloseRan).toBe(true); + expect(closed.response?.ok).toBe(true); + expect(closed.finalizeAsks).toEqual([expect.objectContaining({ shutdownTarget: false })]); + expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); + expect(closeWarningMessages(closed.response!)).toEqual([PROCESS_CHANGED_WARNING]); + expect(owner.checks).toHaveLength(1); + expect(owner.confirmations).toEqual([]); +}, 30_000); + +test('plain close warns when the stop could not be confirmed', async () => { + const runs = createRoutedSession(); + await openBootedByThisSession(runs); + owner.confirmation = 'unconfirmed'; + + const closed = await runs.run({ name: 'close' }); + + expect(closed.response?.ok).toBe(true); + expect(closed.finalizeAsks).toEqual([ + expect.objectContaining({ shutdownTarget: true, retainRunner: false }), + ]); + expect(mockShutdownTargetRuntime).toHaveBeenCalledTimes(1); + // The stop was asked of the device and the owner escalated to the launched process; the caller + // is told that the exit was not confirmed. + expect(closeWarningMessages(closed.response!)).toEqual([ + 'Close asked this device to stop, but could not confirm that its emulator process exited. The device may still be running.', + ]); + expect(owner.confirmations).toEqual([LAUNCH_IDENTITY]); +}); + +test('plain close leaves an emulator rebooted outside the session running and says why', async () => { + const runs = createRoutedSession(); + await openBootedByThisSession(runs); + + // Somebody else's actor kills this emulator and boots the same AVD; the recorded process is gone, + // and the serial is answered by a process this session never launched. + owner.check = 'changed'; + const closed = await runs.run({ name: 'close' }); + + expect(closed.response?.ok).toBe(true); + expect(closed.finalizeAsks).toEqual([ + expect.objectContaining({ shutdownTarget: false, retainRunner: false }), + ]); + expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); + expect(closeWarningMessages(closed.response!)).toEqual([PROCESS_CHANGED_WARNING]); + if (closed.response?.ok) expect(closed.response.data).not.toHaveProperty('shutdown'); + // Close asks about the launched process once, and only as its own decision. + expect(owner.checks).toHaveLength(1); + expect(owner.confirmations).toEqual([]); +}, 30_000); + +test('Quick Boot retains the replacement with the same serial and restored guest uptime', async () => { + const runs = createRoutedSession(); + await openBootedByThisSession(runs); + + // The default quick-boot restore keeps the guest clock and the serial, and the new emulator + // process happens to reuse the pid. Only the process identity separates the two lifetimes, and + // the owner is the one that reads it. + owner.check = 'changed'; + const closed = await runs.run({ name: 'close' }); + + expect(closed.finalizeAsks).toEqual([ + expect.objectContaining({ shutdownTarget: false, retainRunner: false }), + ]); + expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); + expect(closeWarningMessages(closed.response!)).toEqual([PROCESS_CHANGED_WARNING]); +}); + +test('plain close retains the emulator when the host will not answer for the recorded process', async () => { + const runs = createRoutedSession(); + await openBootedByThisSession(runs); + owner.check = 'unverified'; + + const closed = await runs.run({ name: 'close' }); + + expect(closed.response?.ok).toBe(true); + expect(closed.finalizeAsks).toEqual([ + expect.objectContaining({ shutdownTarget: false, retainRunner: false }), + ]); + expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); + expect(closeWarningMessages(closed.response!)).toEqual([PROCESS_UNVERIFIED_WARNING]); + expect(owner.confirmations).toEqual([]); +}, 30_000); + +test('missing launch identity does not acquire ownership from a later process read', async () => { + const runs = createRoutedSession(); + const opened = await runs.run({ + name: 'open', + flags: { platform: 'android' }, + selectsDevice: true, + omitLaunchIdentity: true, + }); + expect(opened.response?.ok).toBe(true); + + const closed = await runs.run({ name: 'close' }); + + expect(closed.finalizeAsks).toEqual([ + expect.objectContaining({ shutdownTarget: false, retainRunner: false }), + ]); + expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); + // Nothing was recorded, so close asks about a process it cannot name, and a stop is never + // confirmed against an identity that does not exist. + expect(owner.checks).toEqual([{ device: BOOTED_EMULATOR, identity: undefined }]); + expect(owner.confirmations).toEqual([]); + expect(closeWarningMessages(closed.response!)).toEqual([NO_LAUNCH_IDENTITY_WARNING]); +}); + +test('close --shutdown stops the device and never asks about the launched process', async () => { + const runs = createRoutedSession(); + await openBootedByThisSession(runs); + owner.check = 'changed'; + owner.confirmation = 'unconfirmed'; + + const closed = await runs.run({ name: 'close', flags: { shutdown: true } }); + + expect(closed.response?.ok).toBe(true); + expect(closed.finalizeAsks).toEqual([ + expect.objectContaining({ shutdownTarget: true, retainRunner: false }), + ]); + expect(mockShutdownTargetRuntime).toHaveBeenCalledTimes(1); + expect(closeWarningMessages(closed.response!)).toBeUndefined(); + // An explicit --shutdown is the user's own command for the device; the launched process neither + // gates it nor gets confirmed afterwards. + expect(owner.checks).toEqual([]); + expect(owner.confirmations).toEqual([]); +}, 30_000); + +test('a policy refusal stays the reported reason and asks nothing of the process owner', async () => { + const runs = createRoutedSession(); + await openBootedByThisSession(runs); + + const closed = await runs.run({ name: 'close', deviceShutdownDenied: true }); + + expect(closed.response?.ok).toBe(true); + expect(closed.finalizeAsks).toEqual([ + expect.objectContaining({ shutdownTarget: false, retainRunner: false }), + ]); + expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); + expect(closeWarningMessages(closed.response!)).toEqual([ + "This session's open booted this device and close would stop it, but this daemon's policy denies device-shutdown. The device is still running.", + ]); + expect(owner.checks).toEqual([]); +}, 30_000); + +test('a lost claim stays the reported reason and asks nothing of the process owner', async () => { + const runs = createRoutedSession(); + await openBootedByThisSession(runs); + await runs.dropSessionClaim(); + + const closed = await runs.run({ name: 'close' }); + + expect(closed.response?.ok).toBe(true); + expect(closed.finalizeAsks).toEqual([ + expect.objectContaining({ shutdownTarget: false, retainRunner: false }), + ]); + expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); + expect(closeWarningMessages(closed.response!)).toEqual([ + "This session's open booted this device, but close could not verify its device claim and did not request a stop.", + ]); + expect(owner.checks).toEqual([]); +}, 30_000); + +test('changing the device serial clears launch ownership', async () => { + const runs = createRoutedSession(); + await openBootedByThisSession(runs); + const ref = runs.sessionStore.lookup(SESSION)!; + runs.sessionStore.updateOpenDevice(ref, { ...BOOTED_EMULATOR, id: 'emulator-5556' }, false); + expect(runs.sessionStore.get(SESSION)?.androidLaunchIdentity).toBeUndefined(); + expect(runs.sessionStore.get(SESSION)?.bootedByOpen).toBeUndefined(); +}); diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-implicit-shutdown.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-implicit-shutdown.test.ts new file mode 100644 index 0000000000..fee57d0bbd --- /dev/null +++ b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-implicit-shutdown.test.ts @@ -0,0 +1,461 @@ +import { daemonPlatformServicesFixture } from '../../../../__tests__/support/platform-services-fixture.ts'; +import { beforeEach, expect, test } from 'vitest'; +import { + sessionCloseShutdownFixture, + type SessionState, +} from './session-close-shutdown.fixtures.ts'; +import { + mkdtempForTestSync, + bindTestCommandHost, + createTestHostEnvironment, +} from '@agent-device/test-kit'; +import { fakeCreateCommandSurface } from '../../../../__tests__/support/command-surface-fake.ts'; +import { lifecycleOperationsSpy } from '../../../../__tests__/support/lifecycle-operations-spy.ts'; +import { platformResourceCleanupFixture } from '../../../../__tests__/support/platform-resource-cleanup-fixture.ts'; +import { + acquireDeviceClaim, + clearDeviceClaim, + inspectDeviceClaims, +} from '@agent-device/daemon-contracts/device-claims'; +import { + launchedProcessOwnerAnswers, + resetLaunchedProcessOwnerAnswers, +} from '../../../../__tests__/support/launched-process-owner-fixture.ts'; + +bindTestCommandHost(); + +const { + AppError, + handleSessionCommands, + makeSession, + makeSessionStore, + mockShutdownTargetRuntime, + noopInvoke, + path, + resetSessionCloseShutdownMocks, +} = sessionCloseShutdownFixture; + +beforeEach(() => { + resetSessionCloseShutdownMocks(); + resetLaunchedProcessOwnerAnswers(); +}); + +const iosSimulator: SessionState['device'] = { + platform: 'apple', + appleOs: 'ios', + id: 'sim-udid-implicit', + name: 'iPhone 15', + kind: 'simulator', + // Selection records the boot from the stopped state, and the session keeps that snapshot. + booted: false, +}; + +const androidEmulator: SessionState['device'] = { + platform: 'android', + id: 'emulator-5554', + name: 'Pixel_9_API_35', + kind: 'emulator', + booted: false, +}; + +/** The process identity a session records for the emulator its own `open` launched. */ +const LAUNCH_IDENTITY = { pid: 4112, startTime: 'launch-start-time' } as const; + +async function closeSession(params: { + sessionName: string; + device: SessionState['device']; + bootedByOpen?: true; + claim?: 'missing' | 'successor'; + flags?: Record; + deviceShutdownDenied?: boolean; + lifecycleOperationsLoader?: Parameters< + typeof handleSessionCommands + >[0]['lifecycleOperationsLoader']; + platformResourceCleanup?: ReturnType; +}) { + const { sessionName, device, bootedByOpen, flags } = params; + const host = createTestHostEnvironment({ + env: { ...process.env, AGENT_DEVICE_CLAIMS_DIR: mkdtempForTestSync('implicit-close-claims-') }, + }); + const sessionStore = makeSessionStore(); + const session = makeSession(sessionName, device); + if (bootedByOpen) session.bootedByOpen = bootedByOpen; + if (device.platform === 'android') session.androidLaunchIdentity = LAUNCH_IDENTITY; + if (bootedByOpen) { + const claimInput = { + env: host.env, + device, + session: sessionName, + workspace: host.cwd, + stateDir: sessionStore.resolveDaemonStateDir(), + reconcileOrphanedDeviceClaim: async () => ({ status: 'reconciled' as const }), + }; + const acquired = await acquireDeviceClaim(claimInput); + if (acquired.status !== 'acquired') throw new Error('Expected an owned device claim'); + session.deviceClaim = acquired.ownership; + if (params.claim === 'missing') { + await clearDeviceClaim(acquired.ownership, host.env); + } + if (params.claim === 'successor') { + const prior = inspectDeviceClaims({}, host.env)[0]?.claim; + if (!prior) throw new Error('Expected the original claim'); + const successor = await acquireDeviceClaim({ + ...claimInput, + session: 'successor-session', + stateDir: path.join(sessionStore.resolveDaemonStateDir(), 'successor-state'), + observeDeviceBoot: { + observeBootTimeMs: async () => ({ observed: true, bootedAtMs: prior.updatedAtMs + 1 }), + }, + }); + expect(successor.status).toBe('acquired'); + } + } + sessionStore.publish(sessionName, session); + const response = await handleSessionCommands({ + host, + createCommandSurface: fakeCreateCommandSurface, + platformServices: daemonPlatformServicesFixture({ + deviceBootObservation: { + observeBootTimeMs: async () => ({ observed: false, reason: 'unobserved' }), + }, + }), + ...(params.lifecycleOperationsLoader + ? { lifecycleOperationsLoader: params.lifecycleOperationsLoader } + : {}), + ...(params.platformResourceCleanup + ? { platformResourceCleanup: params.platformResourceCleanup } + : {}), + deviceShutdownDenied: params.deviceShutdownDenied, + req: { + token: 't', + session: sessionName, + command: 'close', + positionals: [], + flags: flags ?? {}, + }, + sessionName, + logPath: path.join(mkdtempForTestSync('daemon'), 'daemon.log'), + sessionStore, + invoke: noopInvoke, + }); + return { response, sessionStore, claims: inspectDeviceClaims({}, host.env) }; +} + +test.each([ + ['missing', false], + ['missing', true], + ['successor', false], + ['successor', true], +] as const)( + 'plain close cannot stop a boot-owned device when its current claim is %s and policy denial is %s', + async (claim, deviceShutdownDenied) => { + const { loader, finalizeApplicationClose } = lifecycleOperationsSpy(); + const { response, sessionStore, claims } = await closeSession({ + sessionName: 'lost-claim-session', + device: iosSimulator, + bootedByOpen: true, + claim, + deviceShutdownDenied, + lifecycleOperationsLoader: loader, + }); + expect(response?.ok).toBe(true); + if (response?.ok) { + expect(response.data?.warnings).toEqual([ + "This session's open booted this device, but close could not verify its device claim and did not request a stop.", + ]); + } + expect(finalizeApplicationClose).toHaveBeenCalledWith( + expect.objectContaining({ shutdownTarget: false }), + ); + expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); + expect(sessionStore.get('lost-claim-session')).toBeUndefined(); + expect(claims.map((entry) => entry.claim?.session)).toEqual( + claim === 'successor' ? ['successor-session'] : [], + ); + }, +); + +test.each([ + { label: 'iOS simulator', device: iosSimulator }, + { label: 'Android emulator', device: androidEmulator }, +])( + 'plain close stops the $label this session booted and reports it in data.shutdown', + async ({ device }) => { + const { response, sessionStore } = await closeSession({ + sessionName: 'implicit-shutdown-session', + device, + bootedByOpen: true, + }); + + expect(response?.ok).toBe(true); + expect(mockShutdownTargetRuntime).toHaveBeenCalledTimes(1); + expect(sessionStore.get('implicit-shutdown-session')).toBeUndefined(); + if (response?.ok) { + expect(response.data?.session).toBe('implicit-shutdown-session'); + expect(response.data?.shutdown).toEqual({ + success: true, + exitCode: 0, + stdout: '', + stderr: '', + }); + } + // The stop is owed to the launch either way, but only the emulator family has a host process to + // confirm, so the Android close confirms the recorded process and the iOS close does not. + if (device.platform === 'android') + expect(launchedProcessOwnerAnswers.confirmations).toEqual([LAUNCH_IDENTITY]); + else expect(launchedProcessOwnerAnswers.confirmations).toEqual([]); + }, +); + +test.each([ + { label: 'iOS simulator', device: { ...iosSimulator, booted: true } }, + { label: 'Android emulator', device: { ...androidEmulator, booted: true } }, +])( + 'plain close leaves the already-booted $label running and reports no shutdown', + async ({ device }) => { + const { response, sessionStore } = await closeSession({ + sessionName: 'prebooted-session', + device, + }); + + expect(response?.ok).toBe(true); + expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); + expect(sessionStore.get('prebooted-session')).toBeUndefined(); + if (response?.ok) expect(response.data?.shutdown).toBeUndefined(); + }, +); + +test.each([ + { + label: 'a physical iOS device', + device: { + platform: 'apple' as const, + appleOs: 'ios' as const, + id: 'physical-implicit-1', + name: 'My iPhone', + kind: 'device' as const, + booted: false, + }, + }, + { + label: 'a physical Android device', + device: { + platform: 'android' as const, + id: 'R5CT123456A', + name: 'Pixel 9', + kind: 'device' as const, + booted: false, + }, + }, +])( + 'plain close on $label leaves the stop to the platform, which reports none', + async ({ device }) => { + // Selection never records a boot for these kinds. The close may still ask the admitted platform + // to finalize with a stop, and the platform answers with no shutdown result. + const { loader, finalizeApplicationClose } = lifecycleOperationsSpy(); + const { response } = await closeSession({ + sessionName: 'physical-session', + device, + lifecycleOperationsLoader: loader, + }); + + expect(response?.ok).toBe(true); + expect(finalizeApplicationClose).toHaveBeenCalledWith( + expect.objectContaining({ shutdownTarget: false }), + ); + expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); + if (response?.ok) expect(response.data?.shutdown).toBeUndefined(); + }, +); + +test('plain close on a provider-owned session never asks the local-family stop', async () => { + // The boot fact cannot come from a provider selection. Even a record that carries one must not + // route a provider session through the local shutdown capability. + const sessionStore = makeSessionStore(); + const sessionName = 'provider-implicit-session'; + const device: SessionState['device'] = { + platform: 'apple', + appleOs: 'ios', + id: 'limrun:ios:lease-implicit', + name: 'Limrun iOS', + kind: 'simulator', + booted: false, + }; + const session = makeSession(sessionName, device); + session.bootedByOpen = true; + sessionStore.publish(sessionName, session); + const { loader, finalizeApplicationClose } = lifecycleOperationsSpy(); + const facts = sessionCloseShutdownFixture.lifecycleRuntimeFacts(device); + const providerFacts = { + ...facts, + device: { ...facts.device, providerMode: 'provider-runtime' as const }, + }; + sessionCloseShutdownFixture.mockInspectDeviceRuntimeFacts + .mockResolvedValueOnce(providerFacts) + .mockResolvedValueOnce(providerFacts); + sessionCloseShutdownFixture.mockBindDeviceRuntime.mockImplementationOnce( + async (candidate, use) => + await sessionCloseShutdownFixture.narrowDeviceBinding( + { + device: candidate, + owner: sessionCloseShutdownFixture.providerRuntimeOwner('limrun', 'lease-implicit'), + facts: providerFacts, + operations: await loader(candidate), + [Symbol.asyncDispose]: async () => undefined, + }, + use, + ), + ); + + const response = await handleSessionCommands({ + host: createTestHostEnvironment(), + createCommandSurface: fakeCreateCommandSurface, + platformServices: daemonPlatformServicesFixture(), + req: { + token: 't', + session: sessionName, + command: 'close', + positionals: [], + flags: {}, + }, + sessionName, + logPath: path.join(mkdtempForTestSync('daemon'), 'daemon.log'), + sessionStore, + invoke: noopInvoke, + }); + + expect(response?.ok).toBe(true); + expect(finalizeApplicationClose).toHaveBeenCalledWith( + expect.objectContaining({ shutdownTarget: false }), + ); + expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); +}); + +test('plain close on a boot-owned device finalizes without a retained runner and without retention', async () => { + const { loader, finalizeApplicationClose } = lifecycleOperationsSpy(); + const platformResourceCleanup = platformResourceCleanupFixture(); + const { response } = await closeSession({ + sessionName: 'implicit-retain-session', + device: iosSimulator, + bootedByOpen: true, + lifecycleOperationsLoader: loader, + platformResourceCleanup, + }); + + expect(response?.ok).toBe(true); + expect(finalizeApplicationClose).toHaveBeenCalledWith( + expect.objectContaining({ shutdownTarget: true, retainRunner: false }), + ); + expect(platformResourceCleanup.retainExecutionHostAfterClose).toHaveBeenCalledWith( + expect.objectContaining({ device: iosSimulator, shutdownRequested: true }), + ); +}); + +test('close --shutdown keeps asking for the stop on a session that did not boot its device', async () => { + const { loader, finalizeApplicationClose } = lifecycleOperationsSpy(); + const { response } = await closeSession({ + sessionName: 'explicit-shutdown-session', + device: { ...iosSimulator, booted: true }, + flags: { shutdown: true }, + lifecycleOperationsLoader: loader, + }); + + expect(response?.ok).toBe(true); + expect(finalizeApplicationClose).toHaveBeenCalledWith( + expect.objectContaining({ shutdownTarget: true }), + ); +}); + +test('a policy that denies the stop keeps close successful, keeps the runner warm, and reports the kept device', async () => { + // Runtime composition derives this fact from the loaded daemon policy (ADR 0029). The close + // lifecycle reads it BEFORE finalizing, so the refused stop never consumes the runner retention. + const { loader, finalizeApplicationClose } = lifecycleOperationsSpy(); + const platformResourceCleanup = platformResourceCleanupFixture({ + retainExecutionHostAfterClose: () => true, + }); + const { response, sessionStore } = await closeSession({ + sessionName: 'policy-denied-session', + device: iosSimulator, + bootedByOpen: true, + deviceShutdownDenied: true, + lifecycleOperationsLoader: loader, + platformResourceCleanup, + }); + + expect(finalizeApplicationClose).toHaveBeenCalledWith( + expect.objectContaining({ shutdownTarget: false, retainRunner: true }), + ); + // The refused stop never reaches the retention question, so a device kept running still earns + // the warm-runner answer the cleanup gives an ordinary close. + expect(platformResourceCleanup.retainExecutionHostAfterClose).toHaveBeenCalledWith( + expect.objectContaining({ device: iosSimulator, shutdownRequested: false }), + ); + expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); + expect(response?.ok).toBe(true); + expect(sessionStore.get('policy-denied-session')).toBeUndefined(); + if (response?.ok) { + expect(response.data?.session).toBe('policy-denied-session'); + expect(response.data?.shutdown).toBeUndefined(); + expect(response.data?.warnings).toEqual([ + "This session's open booted this device and close would stop it, but this daemon's policy denies device-shutdown. The device is still running.", + ]); + } +}); + +test('a denied policy fact without boot ownership changes nothing', async () => { + const { loader, finalizeApplicationClose } = lifecycleOperationsSpy(); + const { response } = await closeSession({ + sessionName: 'policy-denied-unowned-session', + device: { ...iosSimulator, booted: true }, + deviceShutdownDenied: true, + lifecycleOperationsLoader: loader, + }); + + expect(finalizeApplicationClose).toHaveBeenCalledWith( + expect.objectContaining({ shutdownTarget: false }), + ); + expect(response?.ok).toBe(true); + if (response?.ok) expect(response.data?.warnings).toBeUndefined(); +}); + +test('a failed finalization keeps failing an explicit close --shutdown', async () => { + // The request gate refuses a policy-denied `--shutdown` before the handler (daemon-policy.ts), + // covered there. This is the handler half: whatever the reason, a stop the platform cannot + // complete fails the close with the incomplete-cleanup report — an implicit convenience stop + // would not, which is what the boot-ownership tests above pin. + const shutdownFailed = new AppError('COMMAND_FAILED', 'Emulator refused to shut down.', { + reason: 'shutdown-failed', + retriable: true, + }); + const { loader } = lifecycleOperationsSpy({ + finalizeApplicationClose: async () => { + throw shutdownFailed; + }, + }); + const sessionStore = makeSessionStore(); + const sessionName = 'failed-explicit-shutdown-session'; + const session = makeSession(sessionName, { ...iosSimulator, booted: true }); + sessionStore.publish(sessionName, session); + + await expect( + handleSessionCommands({ + host: createTestHostEnvironment(), + createCommandSurface: fakeCreateCommandSurface, + platformServices: daemonPlatformServicesFixture(), + lifecycleOperationsLoader: loader, + req: { + token: 't', + session: sessionName, + command: 'close', + positionals: [], + flags: { shutdown: true }, + }, + sessionName, + logPath: path.join(mkdtempForTestSync('daemon'), 'daemon.log'), + sessionStore, + invoke: noopInvoke, + }), + ).rejects.toMatchObject({ + details: { reason: 'session_cleanup_incomplete', failedSteps: ['application_lifecycle'] }, + }); +}); diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-open-boot-ownership.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-open-boot-ownership.test.ts new file mode 100644 index 0000000000..d1bef9b8b3 --- /dev/null +++ b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-open-boot-ownership.test.ts @@ -0,0 +1,122 @@ +import path from 'node:path'; +import { expect, test } from 'vitest'; +import { completeOpenCommand } from '../session-open-execution.ts'; +import { openApplicationRuntimeUse } from '@agent-device/contracts/application-lifecycle-runtime-plan'; +import { resolveExistingSessionDeviceSelection } from '@agent-device/device-selection/device-selection-resolver'; +import { mockBindDeviceRuntime } from '../../../../__tests__/support/handlers/session-command-harness.ts'; +import { lifecycleOperationsSpy } from '../../../../__tests__/support/lifecycle-operations-spy.ts'; +import { + makeAndroidEmulator, + makeSession, + makeSessionStore, +} from './session-open-runtime.fixtures.ts'; +import { AppError } from '@agent-device/kernel/errors'; +import { + registerRequestAbort, + markRequestCanceled, + clearRequestAbortRegistration, +} from '@agent-device/host-kit/request'; + +test.each([ + { fails: false, priorBoot: undefined }, + { fails: true, priorBoot: undefined }, + { fails: false, priorBoot: true }, + { fails: true, priorBoot: true }, +] as const)( + 'reopen preserves boot ownership with a stale device snapshot (fails: $fails, owned: $priorBoot)', + async ({ fails, priorBoot }) => { + const store = makeSessionStore(); + const device = { ...makeAndroidEmulator(), booted: false }; + const ref = store.publish('reopen', { + ...makeSession('reopen', device), + bootedByOpen: priorBoot, + }); + const { loader } = lifecycleOperationsSpy({ + openApplication: async () => { + expect(store.requireCurrent(ref).bootedByOpen).toBe(priorBoot); + if (fails) throw new AppError('COMMAND_FAILED', 'Launch rejected'); + return { timing: {} }; + }, + }); + const pending = completeOpenCommand({ + req: { token: 't', command: 'open', positionals: [], session: 'reopen' }, + sessionName: 'reopen', + sessionStore: store, + logPath: path.join(store.host.cwd, 'daemon.log'), + device, + openPositionals: [], + surface: 'app', + runtimeHints: undefined, + existingRef: ref, + selection: resolveExistingSessionDeviceSelection(device), + lifecycle: await mockBindDeviceRuntime(device, openApplicationRuntimeUse, undefined, loader), + }); + if (fails) await expect(pending).rejects.toThrow('Launch rejected'); + else expect((await pending).type).toBe('opened'); + expect(store.requireCurrent(ref).bootedByOpen).toBe(priorBoot); + }, +); + +test.each(['recording', 'launch', 'cancel'] as const)( + 'provisional cold open retains its boot after %s failure', + async (failure) => { + const store = makeSessionStore(); + const device = { ...makeAndroidEmulator(), booted: false }; + const requestId = `provisional-boot-${failure}`; + const registration = registerRequestAbort(requestId); + const { loader } = lifecycleOperationsSpy({ + openApplication: async () => { + if (failure === 'launch') throw new AppError('COMMAND_FAILED', 'Launch rejected'); + markRequestCanceled(requestId); + return { timing: {} }; + }, + }); + try { + const pending = completeOpenCommand({ + req: { + token: 't', + command: 'open', + positionals: [], + session: 'provisional', + meta: { requestId }, + internal: { + openLifecycle: { + beforeDispatch: async () => { + if (failure === 'recording') + return { + ok: false, + error: { code: 'COMMAND_FAILED', message: 'Recording rejected' }, + }; + }, + }, + }, + }, + sessionName: 'provisional', + sessionStore: store, + logPath: path.join(store.host.cwd, 'daemon.log'), + device, + openPositionals: [], + surface: 'app', + runtimeHints: undefined, + selection: { + device, + source: 'local', + reason: 'single-bootable-local', + candidateCount: 1, + bootOccurred: false, + }, + lifecycle: await mockBindDeviceRuntime( + device, + openApplicationRuntimeUse, + undefined, + loader, + ), + }); + if (failure === 'launch') await expect(pending).rejects.toThrow('Launch rejected'); + else expect(await pending).toMatchObject({ type: 'response', response: { ok: false } }); + expect(store.get('provisional')?.bootedByOpen).toBe(true); + } finally { + clearRequestAbortRegistration(registration); + } + }, +); diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-open-state.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-open-state.test.ts index e6ee661111..93c635c80c 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-open-state.test.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-open-state.test.ts @@ -56,3 +56,96 @@ test('a re-open of a session that never armed records nothing', () => { assert.equal(next.scriptPublication, undefined); assert.equal(isSessionRecording(next), false); }); + +// --- #4162: the boot-ownership fact belongs to the open that published it --- +// +// Ownership survives reopens of the same target. A replacement owns only its own boot. + +function firstOpen(bootedByOpen: boolean | undefined) { + const store = makeSessionStore(); + return publishOpenSession({ + req: { token: 't', command: 'open', positionals: [], session: 's' }, + sessionStore: store, + sessionName: 's', + device: IOS_SIMULATOR, + surface: 'app', + bootedByOpen, + }).session; +} + +test('#4162: an open whose selection reported the boot records it on the new session', () => { + assert.equal(firstOpen(true).bootedByOpen, true); +}); + +test.each([false, undefined] as const)( + '#4162: an open whose selection reported no boot records nothing', + (bootedByOpen) => { + assert.equal(firstOpen(bootedByOpen).bootedByOpen, undefined); + }, +); + +const bootOwnershipFacts: readonly (true | undefined)[] = [true, undefined]; + +test.each([false, true])('replacement target owns only its own boot: %s', (replacementBooted) => { + const store = makeSessionStore(); + const existing = makeIosSession('s', { bootedByOpen: true }); + const ref = store.publish(existing.name, existing); + const next = store.requireCurrent( + publishOpenSession({ + req: { token: 't', command: 'open', positionals: [], session: existing.name }, + sessionStore: store, + sessionName: existing.name, + existingRef: ref, + device: { ...IOS_SIMULATOR, id: 'replacement-simulator' }, + surface: 'app', + bootedByOpen: replacementBooted, + }), + ); + assert.equal(next.bootedByOpen, replacementBooted ? true : undefined); +}); + +test.each(bootOwnershipFacts)( + '#4162: a re-open that reports a boot owns the device from then on', + (bootedByOpen) => { + const store = makeSessionStore(); + const existing = makeIosSession('s', bootedByOpen === undefined ? {} : { bootedByOpen }); + const ref = store.publish(existing.name, existing); + + const next = store.requireCurrent( + publishOpenSession({ + req: { token: 't', command: 'open', positionals: [], session: existing.name }, + sessionStore: store, + sessionName: existing.name, + existingRef: ref, + device: IOS_SIMULATOR, + surface: 'app', + bootedByOpen: true, + }), + ); + + assert.equal(next.bootedByOpen, true); + }, +); + +test.each(bootOwnershipFacts)( + '#4162: a re-open that reports no boot leaves the ownership unchanged', + (bootedByOpen) => { + const store = makeSessionStore(); + const existing = makeIosSession('s', bootedByOpen === undefined ? {} : { bootedByOpen }); + const ref = store.publish(existing.name, existing); + + const next = store.requireCurrent( + publishOpenSession({ + req: { token: 't', command: 'open', positionals: [], session: existing.name }, + sessionStore: store, + sessionName: existing.name, + existingRef: ref, + device: IOS_SIMULATOR, + surface: 'app', + bootedByOpen: false, + }), + ); + + assert.equal(next.bootedByOpen, bootedByOpen); + }, +); diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-close-lifecycle-teardown.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-close-lifecycle-teardown.ts index 7617fe4f34..64b23b2ec5 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-close-lifecycle-teardown.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-close-lifecycle-teardown.ts @@ -2,6 +2,13 @@ import type { LeaseRegistry } from '../../../resources/lease-registry.ts'; import { inspectSessionLeaseRetainedOnClose } from '../../lease-lifecycle.ts'; import type { CloseApplicationFinalizationResult } from '@agent-device/contracts/application-lifecycle-runtime'; import type { TargetShutdownResult } from '@agent-device/contracts/device'; +import type { + LaunchedDeviceProcessService, + LaunchedProcessCheck, +} from '@agent-device/contracts/device-boot'; +import type { EnvMap } from '@agent-device/kernel/source-value'; +import { renewDeviceClaim } from '@agent-device/daemon-contracts/device-claims'; +import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import type { DaemonRequest } from '../../../core/daemon-request.ts'; import type { OrdinaryCloseScript } from './session-close-script.ts'; import type { SessionRef, SessionState } from '../../../core/session-state.ts'; @@ -27,16 +34,138 @@ export type PlatformCloseDispatcher = (params: { lifecycle: CloseRuntime | CloseRuntimeWithRuntimeHintClear; }) => Promise; +/** The stop one close owes its device, and the reason it reports when it owes none. */ +type CloseDeviceStopDecision = Readonly<{ + shutdownRequested: boolean; + /** + * #4162: the close owned stopping the device its own `open` booted, and this daemon's policy + * denies `device-shutdown`, so the device stays running. The close itself succeeded. + */ + implicitShutdownDeniedByPolicy: boolean; + implicitShutdownClaimLost: boolean; +}>; + export type SessionCloseTeardownResult = Readonly<{ platformCloseError: unknown; retainExecutionHost: boolean; saveScriptOutcome: OrdinaryCloseScript; shutdownResult?: TargetShutdownResult; shutdownPrepared: boolean; -}>; + /** + * #4585: the process this session's `open` launched is not running the device any more, so whoever + * answers that device address now is somebody else's device and the implicit stop is withheld. The + * close itself succeeded. + */ + implicitShutdownLaunchedProcessGone: boolean; + /** + * #4585: close could not establish whether its own launched process still runs, so it stops + * nothing. This covers the open that recorded no process identity and a host that would not answer + * for the recorded process. + */ + implicitShutdownLaunchedProcessUnverified: boolean; + /** + * The stop was asked for, but the process this session launched was still running when the + * confirmation budget ended and the pid stop could not confirm its exit. + */ + implicitShutdownStopUnconfirmed: boolean; +}> & + Omit; + +/** + * #4162: plain close stops a local virtual device this session's own open booted. The boot fact + * only ever comes from local selection, and the local-family check keeps it off provider paths, + * which release through their lease instead. A policy that denies `device-shutdown` keeps this + * close's own stop from ever being asked: the refusal is decided before the call, so the runner + * retention a kept-running device earns is not spent on a stop that can never happen. + * + * #4585: the stop this session owes is owed to the launch its own open caused, not to whatever + * answers the device address now. This decides only whether a stop is owed. The process behind the + * launch is checked once, later, right before the stop is asked for (`runSessionCloseTeardown`), + * so platform close and hint cleanup cannot open a window in which a replacement takes the serial. + * An explicit `--shutdown` commands the stop whatever the process says, and a lost claim or a + * policy refusal has already decided it without reaching the host. + */ +async function decideDeviceStopOnClose(params: { + env: EnvMap; + explicitShutdown: boolean; + session: SessionState; + localFamily: boolean; + deviceShutdownDenied: boolean; +}): Promise { + const { session } = params; + const implicitShutdown = + !params.explicitShutdown && session.bootedByOpen === true && params.localFamily; + const claimRenewal = implicitShutdown + ? await renewDeviceClaim(session.deviceClaim, params.env) + : undefined; + const implicitShutdownClaimLost = claimRenewal?.status === 'lost'; + const implicitShutdownDeniedByPolicy = + implicitShutdown && !implicitShutdownClaimLost && params.deviceShutdownDenied; + return { + shutdownRequested: + params.explicitShutdown || + (implicitShutdown && !implicitShutdownDeniedByPolicy && claimRenewal?.status === 'renewed'), + implicitShutdownDeniedByPolicy, + implicitShutdownClaimLost, + }; +} + +/** + * Whether the process that launched this session's device still runs it. The owner answers + * `not-applicable` for a device whose family launches no host process, so this never learns which + * families have one, and it passes the recorded identity through as recorded — including its absence, + * which is the answer a launch that recorded nothing gets. + */ +async function checkLaunchedProcessOwnership( + session: SessionState, + launchedProcess: LaunchedDeviceProcessService, +): Promise { + const identity = session.androidLaunchIdentity; + const check = await launchedProcess.checkLaunchedProcess(session.device, identity); + if (check === 'changed' || check === 'unverified') + emitLaunchedProcessMiss( + identity ? `process-check-${check}` : 'open-recorded-no-process', + identity ? { pid: identity.pid } : {}, + ); + return check; +} + +/** + * Step 3 of the implicit stop: the platform asked its device to shut down, so confirm the process + * this session launched actually left. A launch that recorded no process has nothing to confirm, and + * the owner refuses to signal a process that no longer carries the recorded start time. + */ +async function confirmLaunchedProcessStopped( + session: SessionState, + launchedProcess: LaunchedDeviceProcessService, +): Promise { + const identity = session.androidLaunchIdentity; + if (!identity) return false; + if ( + (await launchedProcess.confirmLaunchedProcessStopped(session.device, identity)) !== + 'unconfirmed' + ) + return false; + emitLaunchedProcessMiss('launched-process-stop-unconfirmed', { pid: identity.pid }); + return true; +} + +/** + * The one diagnostic for a session whose close could not settle the state of the process its own + * `open` launched. `step` names the step that decided it, which is the only thing that separates the + * cases the caller reports with the same warning. + */ +function emitLaunchedProcessMiss(step: string, data: Record = {}): void { + emitDiagnostic({ + level: 'warn', + phase: 'launch_process_identity_miss', + data: { step, ...data }, + }); +} /** Runs owned resources, native close, native hint cleanup, and final lifecycle disposal. */ export async function runSessionCloseTeardown(params: { + env: EnvMap; req: DaemonRequest; ref: SessionRef; logPath: string; @@ -54,6 +183,9 @@ export async function runSessionCloseTeardown(params: { platformCloseError: unknown; }): OrdinaryCloseScript; platformResourceCleanup: PlatformResourceCleanup; + deviceShutdownDenied?: boolean; + /** The host process this session's `open` launched, as the root-composed owner answers for it. */ + launchedProcess: LaunchedDeviceProcessService; }): Promise { const { req, @@ -80,9 +212,18 @@ export async function runSessionCloseTeardown(params: { return undefined; } }; + // #4162 + #4585: what this close owes the device, and which reason it reports when it owes nothing. + const deviceStop = await decideDeviceStopOnClose({ + env: params.env, + explicitShutdown: req.flags?.shutdown === true, + session, + localFamily: lifecycle.owner.kind === 'local-family', + deviceShutdownDenied: params.deviceShutdownDenied === true, + }); + const { shutdownRequested, ...stopReasons } = deviceStop; const retainExecutionHost = params.platformResourceCleanup.retainExecutionHostAfterClose({ device: session.device, - shutdownRequested: req.flags?.shutdown === true, + shutdownRequested, hasScreenRecording: Boolean(session.screenRecording), leaseWillEnd: Boolean(session.lease) && @@ -114,6 +255,16 @@ export async function runSessionCloseTeardown(params: { }); }); } + // #4585: the one ownership read, after every other close step and right before the stop is asked + // for. A replacement that took the serial during platform close or hint cleanup is seen here. + // Residual window: the Android stop restores the test IME and waits up to 2.5 s for its flush + // before `adb emu kill`, so a replacement that takes the serial inside that wait is not seen. + const implicitStop = shutdownRequested && req.flags?.shutdown !== true; + const launchedProcess = implicitStop + ? await checkLaunchedProcessOwnership(session, params.launchedProcess) + : 'not-applicable'; + const stopOwed = + shutdownRequested && launchedProcess !== 'changed' && launchedProcess !== 'unverified'; const finalization = await attemptCleanup( 'application_lifecycle', async (): Promise => @@ -122,9 +273,17 @@ export async function runSessionCloseTeardown(params: { surface: session.surface ?? 'app', retainRunner: retainExecutionHost, stateDir: sessionStore.resolveDaemonStateDir(), - shutdownTarget: req.flags?.shutdown === true && lifecycle.owner.kind === 'local-family', + shutdownTarget: stopOwed && lifecycle.owner.kind === 'local-family', })) ?? {}, ); + // The platform has asked the emulator it owns to shut down; this is where this session checks the + // process it launched actually left, because `adb emu kill` answers for the guest, not for the + // host process. An explicit `--shutdown` is the user's own command for the device and is not this + // session's launched process to confirm. + const stopUnconfirmed = + implicitStop && stopOwed + ? await confirmLaunchedProcessStopped(session, params.launchedProcess) + : false; const saveScriptOutcome = repairArmed ? {} : finalizeOrdinaryCloseScript({ req, ref, sessionStore, platformCloseError }); @@ -137,6 +296,10 @@ export async function runSessionCloseTeardown(params: { saveScriptOutcome, shutdownResult: finalization?.shutdown, shutdownPrepared: finalization !== undefined, + ...stopReasons, + implicitShutdownLaunchedProcessGone: launchedProcess === 'changed', + implicitShutdownLaunchedProcessUnverified: launchedProcess === 'unverified', + implicitShutdownStopUnconfirmed: stopUnconfirmed, }; } diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts index 8add840bc0..4caa7af367 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts @@ -1,6 +1,7 @@ import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; import type { DaemonResponse } from '@agent-device/kernel/contracts'; import type { DaemonPlatformServices } from '../../../core/platform-services.ts'; +import type { LaunchedDeviceProcessService } from '@agent-device/contracts/device-boot'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { AppError, normalizeError } from '@agent-device/kernel/errors'; import type { LeaseLifecycleProvider, TargetShutdownResult } from '@agent-device/contracts/device'; @@ -44,6 +45,7 @@ import { type CloseRuntimeWithRuntimeHintClear, type RuntimeHintClearOperation, } from './session-close-runtime-admission.ts'; +import { appendResponseWarning } from './session-open-warnings.ts'; import { closeCleanupError, runSessionCloseTeardown } from './session-close-lifecycle-teardown.ts'; import type { PlatformResourceCleanup } from '../../../core/platform-resource-cleanup.ts'; import { errorResponse } from '@agent-device/kernel/contracts'; @@ -62,6 +64,7 @@ export type SessionCloseCommandInput = Readonly<{ platformServices: DaemonPlatformServices; bindDevice?: BindDeviceRuntime; platformResourceCleanup?: PlatformResourceCleanup; + deviceShutdownDenied?: boolean; }>; function toRepairPlatformCloseFailure(error: unknown): AppError { @@ -355,6 +358,8 @@ export async function handleSessionCloseCommands( clearRuntimeHints: admission.clearRuntimeHints, repairArmed: repair.repairArmed, platformResourceCleanup, + launchedProcess: params.platformServices.launchedDeviceProcess, + deviceShutdownDenied: params.deviceShutdownDenied, }), ); if (closed.kind === 'response') return closed.response; @@ -364,6 +369,11 @@ export async function handleSessionCloseCommands( requestedSaveScript: Boolean(req.flags?.saveScript), shutdownResult: closed.shutdownResult, providerData: closed.providerData, + implicitShutdownDeniedByPolicy: closed.implicitShutdownDeniedByPolicy, + implicitShutdownClaimLost: closed.implicitShutdownClaimLost, + implicitShutdownLaunchedProcessGone: closed.implicitShutdownLaunchedProcessGone, + implicitShutdownLaunchedProcessUnverified: closed.implicitShutdownLaunchedProcessUnverified, + implicitShutdownStopUnconfirmed: closed.implicitShutdownStopUnconfirmed, }); return remoteCloseScriptDelivery(response, closed.remoteScript); } @@ -393,6 +403,13 @@ type SessionCloseFinalization = shutdownResult?: TargetShutdownResult; /** What close delivers for a remote recording, taken from the close-time write (ADR 0016). */ remoteScript?: RemoteCloseScript; + /** #4162: the policy denied the stop this close owed its own boot, so the device kept running. */ + implicitShutdownDeniedByPolicy: boolean; + implicitShutdownClaimLost: boolean; + /** #4585: the device has been rebooted outside this session since its open, so close left it running. */ + implicitShutdownLaunchedProcessGone: boolean; + implicitShutdownLaunchedProcessUnverified: boolean; + implicitShutdownStopUnconfirmed: boolean; }; // Everything between a settled repair decision and a success response: @@ -413,6 +430,9 @@ async function runCloseTeardownAndRelease(params: { clearRuntimeHints?: RuntimeHintClearOperation; repairArmed: boolean; platformResourceCleanup: PlatformResourceCleanup; + deviceShutdownDenied?: boolean; + /** The host process this session's `open` launched, as the root-composed owner answers for it. */ + launchedProcess: LaunchedDeviceProcessService; }): Promise { const { req, @@ -432,7 +452,13 @@ async function runCloseTeardownAndRelease(params: { saveScriptOutcome, shutdownPrepared, shutdownResult, + implicitShutdownDeniedByPolicy, + implicitShutdownClaimLost, + implicitShutdownLaunchedProcessGone, + implicitShutdownLaunchedProcessUnverified, + implicitShutdownStopUnconfirmed, } = await runSessionCloseTeardown({ + env: params.env, leaseRegistry, req, ref, @@ -445,6 +471,8 @@ async function runCloseTeardownAndRelease(params: { dispatchTargetedPlatformClose, finalizeOrdinaryCloseScript, platformResourceCleanup: params.platformResourceCleanup, + deviceShutdownDenied: params.deviceShutdownDenied, + launchedProcess: params.launchedProcess, }); let session = sessionStore.requireCurrent(ref); // Each cleanup report is built where the session's fate is decided, so its diagnostic and hint @@ -491,6 +519,11 @@ async function runCloseTeardownAndRelease(params: { providerData: leaseRelease.providerData, shutdownResult: leaseRelease.shutdownResult ?? shutdownResult, remoteScript: saveScriptOutcome.remote, + implicitShutdownDeniedByPolicy, + implicitShutdownClaimLost, + implicitShutdownLaunchedProcessGone, + implicitShutdownLaunchedProcessUnverified, + implicitShutdownStopUnconfirmed, }; } @@ -500,8 +533,24 @@ function buildCloseSuccessResponse(params: { requestedSaveScript: boolean; shutdownResult: TargetShutdownResult | undefined; providerData: Record | undefined; + implicitShutdownDeniedByPolicy: boolean; + implicitShutdownClaimLost: boolean; + implicitShutdownLaunchedProcessGone: boolean; + implicitShutdownLaunchedProcessUnverified: boolean; + implicitShutdownStopUnconfirmed: boolean; }): DaemonResponse { - const { session, repair, requestedSaveScript, shutdownResult, providerData } = params; + const { + session, + repair, + requestedSaveScript, + shutdownResult, + providerData, + implicitShutdownDeniedByPolicy, + implicitShutdownClaimLost, + implicitShutdownLaunchedProcessGone, + implicitShutdownLaunchedProcessUnverified, + implicitShutdownStopUnconfirmed, + } = params; if (repair.aborted && requestedSaveScript) { return { ok: false, @@ -519,19 +568,50 @@ function buildCloseSuccessResponse(params: { const savedScript = repair.healedScriptPath ? { savedScript: repair.healedScriptPath } : {}; const provider = providerData ? { provider: providerData } : {}; const text = `Closed: ${session.name}`; - if (shutdownResult) { - return { - ok: true, - data: withSuccessText( + const data: Record = shutdownResult + ? withSuccessText( { session: session.name, shutdown: shutdownResult, ...savedScript, ...provider }, text, - ), - }; + ) + : { session: session.name, ...successText(text), ...savedScript, ...provider }; + // #4162: the close owed this device a stop because its own open booted it, but the daemon's + // policy denies `device-shutdown`. The close still succeeded; say plainly what stayed up. + if (implicitShutdownDeniedByPolicy) { + appendResponseWarning( + data, + "This session's open booted this device and close would stop it, but this daemon's policy denies device-shutdown. The device is still running.", + ); } - return { - ok: true, - data: { session: session.name, ...successText(text), ...savedScript, ...provider }, - }; + if (implicitShutdownClaimLost) { + appendResponseWarning( + data, + "This session's open booted this device, but close could not verify its device claim and did not request a stop.", + ); + } + // #4585: the stop this session owed was owed to the emulator process its own open launched. That + // process is gone, so whatever answers the serial now is somebody else's device and stopping it + // would stop a boot this session never caused. Say which device close left running, and why. + if (implicitShutdownLaunchedProcessGone) { + appendResponseWarning( + data, + "This session's open booted this device, but its emulator process has changed, so close did not request a stop. The device is still running.", + ); + } + if (implicitShutdownLaunchedProcessUnverified) { + appendResponseWarning( + data, + session.androidLaunchIdentity + ? "This session's open booted this device, but close could not verify its emulator process identity, so it did not request a stop and left the device as it found it." + : "This session's open booted this device, but open recorded no emulator process identity, so close did not request a stop and left the device as it found it.", + ); + } + if (implicitShutdownStopUnconfirmed) { + appendResponseWarning( + data, + 'Close asked this device to stop, but could not confirm that its emulator process exited. The device may still be running.', + ); + } + return { ok: true, data }; } async function closeAppWithoutEndingSession(params: { diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts index f9dccee84b..6fd957b9d8 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts @@ -1,3 +1,4 @@ +import type { AndroidEmulatorLaunchIdentity } from '@agent-device/contracts/device-readiness-runtime'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { resolveSessionRequestLogPath, @@ -245,6 +246,7 @@ export async function completeOpenCommand(params: { /** The stale claim this open released before taking the device, when there was one. */ tookOverDeviceClaim?: TakenOverDeviceClaim; selection?: DeviceSelectionResult; + androidLaunchIdentity?: AndroidEmulatorLaunchIdentity; }): Promise { const { req, @@ -271,6 +273,10 @@ export async function completeOpenCommand(params: { const shouldRelaunch = req.flags?.relaunch === true; let sessionAppBundleId = appBundleId; const openCommandStartedAtMs = Date.now(); + const preparedSelection = markSelectionBootOccurred( + selection, + lifecycle.owner.kind === 'local-family', + ); const provisionalSession = await prepareOpenDispatchSession({ req, @@ -281,6 +287,8 @@ export async function completeOpenCommand(params: { sessionAppBundleId, appName, existingRef, + bootedByOpen: preparedSelection?.bootOccurred === true, + androidLaunchIdentity: params.androidLaunchIdentity, }); if (provisionalSession.type === 'response') return provisionalSession; const openDispatchRef = provisionalSession.ref; @@ -322,7 +330,6 @@ export async function completeOpenCommand(params: { }); sessionAppBundleId = outcome.appBundleId ?? sessionAppBundleId; const timing: OpenTiming = { ...outcome.timing }; - const preparedSelection = markSelectionBootOccurred(selection); const startupSample = openTarget ? buildStartupPerfSample(openStartedAtMs, openTarget, sessionAppBundleId) : undefined; @@ -397,6 +404,8 @@ export async function completeOpenCommand(params: { appBundleId: sessionAppBundleId, appName, deviceClaim, + bootedByOpen: preparedSelection?.bootOccurred === true, + androidLaunchIdentity: params.androidLaunchIdentity, }); sessionStore.clearCloseEffectsUnconfirmed(nextRef); const nextSession = sessionStore.requireCurrent(nextRef); @@ -430,12 +439,23 @@ async function prepareOpenDispatchSession(params: { sessionAppBundleId: string | undefined; appName: string | undefined; existingRef: SessionRef | undefined; + bootedByOpen: boolean; + androidLaunchIdentity?: AndroidEmulatorLaunchIdentity; }): Promise< { type: 'session'; ref?: SessionRef } | { type: 'response'; response: DaemonResponse } > { const { req, sessionName, sessionStore, existingRef } = params; const beforeDispatch = req.internal?.openLifecycle?.beforeDispatch; - if (!beforeDispatch) return { type: 'session', ref: existingRef }; + if (!beforeDispatch) { + if (existingRef) + sessionStore.updateOpenDevice( + existingRef, + params.device, + params.bootedByOpen, + params.androidLaunchIdentity, + ); + return { type: 'session', ref: existingRef }; + } const ref = publishOpenSession({ req, sessionName, @@ -445,6 +465,8 @@ async function prepareOpenDispatchSession(params: { surface: params.surface, appBundleId: params.sessionAppBundleId, appName: params.appName, + bootedByOpen: params.bootedByOpen, + androidLaunchIdentity: params.androidLaunchIdentity, }); const lifecycleResponse = await beforeDispatch(); if (lifecycleResponse && !lifecycleResponse.ok) @@ -504,6 +526,7 @@ export async function openNewSessionWithDeviceClaim(params: { clearRuntimeHints?: OpenRuntimeHintClearOperation; reconcileOrphanedDeviceClaim: DeviceClaimReconciler; selection?: DeviceSelectionResult; + androidLaunchIdentity?: AndroidEmulatorLaunchIdentity; platformServices: DaemonPlatformServices; }): Promise { const { @@ -603,6 +626,7 @@ export async function openNewSessionWithDeviceClaim(params: { deviceClaim, tookOverDeviceClaim, selection, + androidLaunchIdentity: params.androidLaunchIdentity, }); if (!response.response.ok) await rollbackClaim(); return response; diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-state.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-state.ts index 4108c931e5..4168c76bb2 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-state.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-state.ts @@ -1,7 +1,8 @@ +import type { AndroidEmulatorLaunchIdentity } from '@agent-device/contracts/device-readiness-runtime'; import type { DeviceInfo } from '@agent-device/kernel/device'; import type { SessionSurface } from '@agent-device/contracts/session'; import type { DaemonRequest } from '../../../core/daemon-request.ts'; -import type { SessionRef } from '../../../core/session-state.ts'; +import type { SessionRef, SessionState } from '../../../core/session-state.ts'; import type { SessionStore } from '../../../core/session-store.ts'; import type { DeviceClaimSessionOwnership } from '@agent-device/daemon-contracts/device-claims'; import { clearSessionSnapshot } from '../../../execution/session-snapshot.ts'; @@ -31,6 +32,9 @@ export function publishOpenSession(params: { appBundleId?: string; appName?: string; deviceClaim?: DeviceClaimSessionOwnership; + /** #4162: this open booted the local virtual device, so its plain close owns stopping it. */ + bootedByOpen?: boolean; + androidLaunchIdentity?: AndroidEmulatorLaunchIdentity; }): SessionRef { const { req, @@ -42,11 +46,17 @@ export function publishOpenSession(params: { appBundleId, appName, deviceClaim, + bootedByOpen, } = params; requireOpenSessionAdmission(store, sessionName, existingRef); if (existingRef) { - const session = store.update(existingRef, { + store.updateOpenDevice( + existingRef, device, + bootedByOpen === true, + params.androidLaunchIdentity, + ); + const session = store.update(existingRef, { surface, appBundleId, appName, @@ -56,7 +66,7 @@ export function publishOpenSession(params: { clearSessionSnapshot(session); return store.refresh(existingRef); } - return store.publish(sessionName, { + const draft: SessionState = { name: resolvePublicSessionName(req), sessionScope: req.internal?.resolvedSessionScope ?? resolveSessionScope(req), device, @@ -67,5 +77,9 @@ export function publishOpenSession(params: { actions: [], lease: resolveSessionLeaseForRequest({ req }), deviceClaim, - }); + }; + const ref = store.publish(sessionName, draft); + if (bootedByOpen === true) + store.updateOpenDevice(ref, device, true, params.androidLaunchIdentity); + return store.refresh(ref); } diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-open.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-open.ts index 0b3e7173da..66e01c52af 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-open.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-open.ts @@ -20,6 +20,7 @@ import { requestWebSession } from '../../../core/session-tenant-scope.ts'; import { isWebSession } from '../../web-session-names.ts'; import { resolveOpenTargetDeviceOptions } from '../../../core/open-target-device-resolution.ts'; import { bootStoppedLocalAndroidDevice } from '../../../core/stopped-local-android-device.ts'; +import type { AndroidEmulatorLaunchIdentity } from '@agent-device/contracts/device-readiness-runtime'; import { startupDeadlineAtMs } from '../../startup-deadline.ts'; import { invalidOpenArgs, @@ -42,7 +43,10 @@ import type { InspectDeviceRuntimeFacts, } from '../../../core/request-runtime-binding.ts'; import { admitRuntimeOperations } from '../../../core/runtime-admission.ts'; -import { resolveExistingSessionDeviceSelection } from '@agent-device/device-selection/device-selection-resolver'; +import { + markSelectionBootOccurred, + resolveExistingSessionDeviceSelection, +} from '@agent-device/device-selection/device-selection-resolver'; import { requireRuntimeBinding, requireRuntimeFacts, @@ -321,8 +325,6 @@ async function handleOpenCommand(params: SessionOpenCommandInput): Promise { + androidLaunchIdentity = identity; + }, }); - const selection = booted ? { ...resolved, device: booted } : resolved; + const selection = booted ? { ...markSelectionBootOccurred(resolved), device: booted } : resolved; const device = selection.device; if (booted) { await req.internal?.retainDeviceExecutionLock?.(device.id); @@ -446,6 +453,7 @@ async function handleOpenCommand(params: SessionOpenCommandInput): Promise { diff --git a/packages/device-selection/src/device-selection-resolver.ts b/packages/device-selection/src/device-selection-resolver.ts index 9e9896ad46..3d6713197c 100644 --- a/packages/device-selection/src/device-selection-resolver.ts +++ b/packages/device-selection/src/device-selection-resolver.ts @@ -100,18 +100,22 @@ export function resolveExistingSessionDeviceSelection(device: DeviceInfo): Devic } /** - * Open preparation owns lifecycle effects. Once it succeeds, a local virtual - * target that was stopped at resolution has provided the requested boot event; - * provider and physical targets never claim a daemon-owned boot. + * Classifies the boot obligation for a stopped local virtual target before open dispatch. + * An existing session snapshot does not establish a new boot. */ -export function markSelectionBootOccurred(selection: DeviceSelectionResult): DeviceSelectionResult; +export function markSelectionBootOccurred( + selection: DeviceSelectionResult, + localPreparation?: boolean, +): DeviceSelectionResult; export function markSelectionBootOccurred( selection: DeviceSelectionResult | undefined, + localPreparation?: boolean, ): DeviceSelectionResult | undefined; export function markSelectionBootOccurred( selection: DeviceSelectionResult | undefined, + localPreparation = selection?.source === 'local', ): DeviceSelectionResult | undefined { - if (!selection || selection.source !== 'local') return selection; + if (!selection || !localPreparation || selection.source !== 'local') return selection; const { device } = selection; const bootedByThisOpen = device.booted !== true && (device.kind === 'simulator' || device.kind === 'emulator'); diff --git a/packages/platform-android/src/device-boot-launch.test.ts b/packages/platform-android/src/device-boot-launch.test.ts new file mode 100644 index 0000000000..2c0d9e7ddd --- /dev/null +++ b/packages/platform-android/src/device-boot-launch.test.ts @@ -0,0 +1,133 @@ +import { beforeEach, expect, test, vi } from 'vitest'; + +const mocks = vi.hoisted(() => ({ + readProcessIdentityFacts: vi.fn(), + isProcessAlive: vi.fn(), + waitForProcessExit: vi.fn(), + stopProcessAndConfirmExit: vi.fn(), +})); + +// `processStartTimesDiffer` stays real: the comparison it performs is the rule under test, and the +// process reads are the answers modelled here. +vi.mock('@agent-device/host-kit/process', async (importOriginal) => ({ + ...(await importOriginal()), + readProcessIdentityFacts: mocks.readProcessIdentityFacts, + isProcessAlive: mocks.isProcessAlive, + waitForProcessExit: mocks.waitForProcessExit, + stopProcessAndConfirmExit: mocks.stopProcessAndConfirmExit, +})); + +import { + checkAndroidEmulatorLaunchProcess, + confirmAndroidEmulatorLaunchProcessStopped, + readAndroidEmulatorLaunchStartTime, +} from './device-boot.ts'; + +/** The identity `open` recorded for the emulator process it launched. */ +const IDENTITY = { pid: 4112, startTime: 'launch-start-time' } as const; + +beforeEach(() => { + vi.resetAllMocks(); + mocks.readProcessIdentityFacts.mockResolvedValue({ + startTime: IDENTITY.startTime, + zombie: false, + }); + mocks.isProcessAlive.mockReturnValue(true); + mocks.waitForProcessExit.mockResolvedValue(true); + mocks.stopProcessAndConfirmExit.mockResolvedValue({ status: 'stopped', signal: 'SIGTERM' }); +}); + +test('reads the launch start time the process read answers with', async () => { + expect(await readAndroidEmulatorLaunchStartTime(4242)).toBe(IDENTITY.startTime); + expect(mocks.readProcessIdentityFacts).toHaveBeenCalledExactlyOnceWith(4242, 5_000); +}); + +test('a slow launch start time read is retried once with the full budget', async () => { + mocks.readProcessIdentityFacts + .mockRejectedValueOnce(new Error('ps timed out after 5000ms')) + .mockResolvedValueOnce({ startTime: 'launch', zombie: false }); + expect(await readAndroidEmulatorLaunchStartTime(4242)).toBe('launch'); + expect(mocks.readProcessIdentityFacts.mock.calls).toEqual([ + [4242, 5_000], + [4242, 5_000], + ]); +}); + +test('a zombie launch has no start time and is not read again', async () => { + mocks.readProcessIdentityFacts.mockResolvedValueOnce({ startTime: null, zombie: true }); + expect(await readAndroidEmulatorLaunchStartTime(4242)).toBeNull(); + expect(mocks.readProcessIdentityFacts).toHaveBeenCalledTimes(1); +}); + +test('a launch the host never answers for has no start time after both reads', async () => { + mocks.readProcessIdentityFacts.mockResolvedValue({ startTime: null, zombie: null }); + expect(await readAndroidEmulatorLaunchStartTime(4242)).toBeNull(); + expect(mocks.readProcessIdentityFacts).toHaveBeenCalledTimes(2); +}); + +test('a launched process that still answers with its recorded start time is the same launch', async () => { + expect(await checkAndroidEmulatorLaunchProcess(IDENTITY)).toBe('same'); + // One read, on the ordinary process budget: this answer is on a close's decision path. + expect(mocks.readProcessIdentityFacts).toHaveBeenCalledExactlyOnceWith(4112, 1_000); +}); + +test('a launched process that is gone is a changed launch even though the serial still answers', async () => { + mocks.isProcessAlive.mockReturnValue(false); + expect(await checkAndroidEmulatorLaunchProcess(IDENTITY)).toBe('changed'); +}); + +test('a zombie answering the recorded pid is a changed launch', async () => { + mocks.readProcessIdentityFacts.mockResolvedValueOnce({ + startTime: IDENTITY.startTime, + zombie: true, + }); + expect(await checkAndroidEmulatorLaunchProcess(IDENTITY)).toBe('changed'); +}); + +test('a reused pid carrying a new start time is a changed launch', async () => { + // Quick Boot keeps the serial and the guest clock, so only the lifetime tells the two emulator + // processes apart. + mocks.readProcessIdentityFacts.mockResolvedValueOnce({ + startTime: 'replacement-start-time', + zombie: false, + }); + expect(await checkAndroidEmulatorLaunchProcess(IDENTITY)).toBe('changed'); +}); + +test('a process read that does not answer verifies nothing and stops nothing', async () => { + mocks.readProcessIdentityFacts.mockRejectedValue(new Error('ps timed out after 1000ms')); + expect(await checkAndroidEmulatorLaunchProcess(IDENTITY)).toBe('unverified'); +}); + +test('a start time the host leaves blank verifies nothing rather than matching anything', async () => { + // `processStartTimesDiffer` treats a blank as no evidence, so this must not report `same`. + mocks.readProcessIdentityFacts.mockResolvedValueOnce({ startTime: null, zombie: false }); + expect(await checkAndroidEmulatorLaunchProcess(IDENTITY)).toBe('unverified'); +}); + +test('a launched process that took the emulator shutdown is stopped without a signal', async () => { + expect(await confirmAndroidEmulatorLaunchProcessStopped(IDENTITY)).toBe('stopped'); + expect(mocks.waitForProcessExit).toHaveBeenCalledExactlyOnceWith(4112, 3_000); + expect(mocks.stopProcessAndConfirmExit).not.toHaveBeenCalled(); +}); + +test('a launched process that ignores the emulator shutdown is stopped by its recorded identity', async () => { + mocks.waitForProcessExit.mockResolvedValue(false); + expect(await confirmAndroidEmulatorLaunchProcessStopped(IDENTITY)).toBe('stopped'); + // host-kit signals the pid only while the recorded start time still names it, and the escalation + // stays brief because the graceful kill already had its own budget. + expect(mocks.stopProcessAndConfirmExit).toHaveBeenCalledExactlyOnceWith( + { pid: 4112, identity: { startTime: IDENTITY.startTime } }, + { termTimeoutMs: 1_500, killTimeoutMs: 1_500 }, + ); +}); + +test('a launched process that survives every stop is reported unconfirmed', async () => { + mocks.waitForProcessExit.mockResolvedValue(false); + mocks.stopProcessAndConfirmExit.mockResolvedValue({ + status: 'retained', + reason: 'exit-timeout', + signal: 'SIGKILL', + }); + expect(await confirmAndroidEmulatorLaunchProcessStopped(IDENTITY)).toBe('unconfirmed'); +}); diff --git a/packages/platform-android/src/device-boot.ts b/packages/platform-android/src/device-boot.ts index 81c8b7c642..c71f567f0e 100644 --- a/packages/platform-android/src/device-boot.ts +++ b/packages/platform-android/src/device-boot.ts @@ -1,6 +1,36 @@ -import type { DeviceBootObservation } from '@agent-device/contracts/device-boot'; +import type { + DeviceBootObservation, + 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'; +/** + * Reads the start time of an emulator process this host just launched. One `ps` of that pid gets + * 5 s, and a read that did not answer is tried once more, so a slow host still records the launch. + */ +export async function readAndroidEmulatorLaunchStartTime(pid: number): Promise { + const { readProcessIdentityFacts } = await import('@agent-device/host-kit/process'); + for (let attempt = 1; attempt <= LAUNCH_START_TIME_ATTEMPTS; attempt += 1) { + try { + const facts = await readProcessIdentityFacts(pid, LAUNCH_START_TIME_TIMEOUT_MS); + if (facts.startTime) return facts.startTime; + if (facts.zombie === true) return null; + } catch { + // A timed-out read is retried; the second miss leaves no start time. + } + } + return null; +} + +/** + * Under heavy host load one process-table read took up to 4.2 s, which is why the read that names + * a launch gets 5 s and one retry rather than host-kit's ordinary 1 s process budget. + */ +const LAUNCH_START_TIME_TIMEOUT_MS = 5_000; +const LAUNCH_START_TIME_ATTEMPTS = 2; + /** The probe answers in tens of milliseconds and must not become the reason an `open` waits. */ const BOOT_PROBE_TIMEOUT_MS = 3_000; @@ -36,3 +66,60 @@ async function readUptimeSeconds(device: DeviceInfo): Promise { + const { isProcessAlive, processStartTimesDiffer, readProcessIdentityFacts } = + await import('@agent-device/host-kit/process'); + let facts: Awaited>; + try { + facts = await readProcessIdentityFacts(identity.pid, PROCESS_IDENTITY_TIMEOUT_MS); + } catch { + return 'unverified'; + } + if (!isProcessAlive(identity.pid) || facts.zombie === true) return 'changed'; + if (processStartTimesDiffer(identity.startTime, facts.startTime)) return 'changed'; + return facts.startTime === identity.startTime ? 'same' : 'unverified'; +} + +/** + * Whether the launched emulator process took the shutdown asked of the device through + * `adb emu kill`. It waits only for the process that command addressed to leave, so an emulator that + * exits promptly costs one liveness read. A process that ignores the kill is stopped by pid, and + * host-kit signals that pid only while the recorded start time still names it. + */ +export async function confirmAndroidEmulatorLaunchProcessStopped( + identity: AndroidEmulatorLaunchIdentity, +): Promise { + const { stopProcessAndConfirmExit, waitForProcessExit } = + await import('@agent-device/host-kit/process'); + if (await waitForProcessExit(identity.pid, GRACEFUL_SHUTDOWN_EXIT_CONFIRM_MS)) return 'stopped'; + const stop = await stopProcessAndConfirmExit( + { pid: identity.pid, identity: { startTime: identity.startTime } }, + LAUNCHED_PROCESS_STOP_BUDGET, + ); + return stop.status === 'stopped' ? 'stopped' : 'unconfirmed'; +} + +/** + * Under heavy host load one process-table read took up to 4.2 s. The launch-naming read gets 5 s and + * a retry because losing it loses the launch; this read is on a close's decision path and answers in + * tens of milliseconds, so it gets one ordinary process budget instead. + */ +const PROCESS_IDENTITY_TIMEOUT_MS = 1_000; + +/** + * The graceful `adb emu kill` already had its own 15 s to work. Waiting the same again on a process + * that is demonstrably ignoring it would double what one close may spend, so this confirms the exit + * briefly and then escalates. + */ +const GRACEFUL_SHUTDOWN_EXIT_CONFIRM_MS = 3_000; +const LAUNCHED_PROCESS_STOP_BUDGET = { termTimeoutMs: 1_500, killTimeoutMs: 1_500 } as const; diff --git a/packages/platform-android/src/readiness/runtime.test.ts b/packages/platform-android/src/readiness/runtime.test.ts index 11ed49629c..a5021f222d 100644 --- a/packages/platform-android/src/readiness/runtime.test.ts +++ b/packages/platform-android/src/readiness/runtime.test.ts @@ -146,6 +146,88 @@ test('a launched emulator gets the remaining startup budget for its window watch expect(launch).toHaveBeenCalledWith('Pixel_9', false, 30_000); }); +test('reports a bound launch identity once for the discovered serial', async () => { + let discoveries = 0; + const { host } = timedHost({ + bootCompleted: '1', + discover: () => (++discoveries === 1 ? [stoppedAvd()] : [runningEmulator()]), + }); + const identity = { pid: 4242, startTime: 'start' }; + const bind = vi.fn(async () => identity); + Object.assign(host.deviceReadiness.androidEmulator, { bindLaunchedEmulator: bind }); + const observer = vi.fn(); + const result = await ensureAndroidReady( + host, + stoppedAvd(), + { + headless: true, + onAndroidEmulatorLaunchIdentity: observer, + }, + new AbortController().signal, + ); + expect(bind).toHaveBeenCalledWith(4242, expect.objectContaining({ id: 'emulator-5554' })); + expect(observer).toHaveBeenCalledExactlyOnceWith(identity); + expect(result).toEqual({ ...runningEmulator(), booted: true }); +}); + +test('prebooted and unbound launches do not report an identity', async () => { + const observer = vi.fn(); + const existing = timedHost({ bootCompleted: '1', discover: () => [runningEmulator()] }); + const bind = vi.fn(async () => undefined); + Object.assign(existing.host.deviceReadiness.androidEmulator, { bindLaunchedEmulator: bind }); + await ensureAndroidReady( + existing.host, + stoppedAvd(), + { headless: false, onAndroidEmulatorLaunchIdentity: observer }, + new AbortController().signal, + ); + expect(bind).not.toHaveBeenCalled(); + let discoveries = 0; + const launched = timedHost({ + bootCompleted: '1', + discover: () => (++discoveries === 1 ? [stoppedAvd()] : [runningEmulator()]), + }); + Object.assign(launched.host.deviceReadiness.androidEmulator, { bindLaunchedEmulator: bind }); + await ensureAndroidReady( + launched.host, + stoppedAvd(), + { headless: true, onAndroidEmulatorLaunchIdentity: observer }, + new AbortController().signal, + ); + expect(bind).toHaveBeenCalledOnce(); + expect(observer).not.toHaveBeenCalled(); +}); + +test('abort during binding suppresses the observation and terminates the launched emulator', async () => { + let discoveries = 0; + const { host, terminate } = timedHost({ + bootCompleted: '1', + discover: () => (++discoveries === 1 ? [stoppedAvd()] : [runningEmulator()]), + }); + const controller = new AbortController(); + const reason = new Error('cancel binding'); + Object.assign(host.deviceReadiness.androidEmulator, { + bindLaunchedEmulator: async () => { + controller.abort(reason); + return { pid: 4242, startTime: 'start' }; + }, + }); + const observer = vi.fn(); + await expect( + ensureAndroidReady( + host, + stoppedAvd(), + { + headless: true, + onAndroidEmulatorLaunchIdentity: observer, + }, + controller.signal, + ), + ).rejects.toBe(reason); + expect(observer).not.toHaveBeenCalled(); + expect(terminate).toHaveBeenCalledWith(4242); +}); + test('without a deadline the default 120s boot wait applies', async () => { const { host, elapsed } = timedHost({ bootCompleted: '0', discover: () => [runningEmulator()] }); diff --git a/packages/platform-android/src/readiness/runtime.ts b/packages/platform-android/src/readiness/runtime.ts index 404cb8e83f..17e9b8458d 100644 --- a/packages/platform-android/src/readiness/runtime.ts +++ b/packages/platform-android/src/readiness/runtime.ts @@ -60,7 +60,16 @@ async function ensureEmulatorReady( const refreshed = (await host.deviceReadiness.androidEmulator.discover(request, signal)).find( (candidate) => candidate.id === discovered.id, ); - return { ...(refreshed ?? discovered), name: selected.name, booted: true }; + const ready = { ...(refreshed ?? discovered), name: selected.name, booted: true }; + if (launchedPid !== undefined && input.onAndroidEmulatorLaunchIdentity) { + const identity = await host.deviceReadiness.androidEmulator.bindLaunchedEmulator?.( + launchedPid, + ready, + ); + signal.throwIfAborted(); + if (identity) input.onAndroidEmulatorLaunchIdentity(identity); + } + return ready; } catch (error) { if (launchedPid !== undefined && signal.aborted) { await host.deviceReadiness.androidEmulator.terminate(launchedPid); diff --git a/packages/replay-port/src/daemon-port/command-types.ts b/packages/replay-port/src/daemon-port/command-types.ts index 2d3f586276..620f5b410f 100644 --- a/packages/replay-port/src/daemon-port/command-types.ts +++ b/packages/replay-port/src/daemon-port/command-types.ts @@ -93,7 +93,7 @@ export type ReplayTestVideoOwner = Readonly<{ throwIfCanceled: () => void; }>; -type ReplayTestSessionCleanup = (sessionName: string) => Promise; +type ReplayTestSessionCleanup = (sessionName: string) => Promise; export type ReplayTestCommand = ReplayCommand & Readonly<{ diff --git a/packages/replay-port/src/daemon-port/native-command.ts b/packages/replay-port/src/daemon-port/native-command.ts index e4371b85af..56decfcadb 100644 --- a/packages/replay-port/src/daemon-port/native-command.ts +++ b/packages/replay-port/src/daemon-port/native-command.ts @@ -76,6 +76,7 @@ export async function runReplayCommand(command: ReplayCommand): Promise(); + const warnings: string[] = []; try { resolved = bundle.entry; if (isMaestroYamlPath(resolved) && req.flags?.replayBackend !== 'maestro') { @@ -135,6 +136,7 @@ export async function runReplayCommand(command: ReplayCommand): Promise 0 + ? { details: { ...normalized.details, artifactPaths: [...artifactPaths] } } + : {}), + }, }, + warnings, + ); + } +} + +async function withReplayActionWarnings( + response: DaemonResponse, + warnings: readonly string[], +): Promise { + if (warnings.length === 0) return response; + const { readResponseWarnings } = await import('@agent-device/kernel/success-text'); + if (response.ok) { + return { + ...response, + data: { ...response.data, warnings: [...warnings, ...readResponseWarnings(response.data)] }, }; } + return { + ...response, + error: { + ...response.error, + details: { + ...response.error.details, + warnings: [...warnings, ...readResponseWarnings(response.error.details)], + }, + }, + }; } function completeReplayRun(params: { diff --git a/packages/replay-port/src/daemon-port/session-replay-runtime-engine-adapter.ts b/packages/replay-port/src/daemon-port/session-replay-runtime-engine-adapter.ts index 414884f367..e335ec5437 100644 --- a/packages/replay-port/src/daemon-port/session-replay-runtime-engine-adapter.ts +++ b/packages/replay-port/src/daemon-port/session-replay-runtime-engine-adapter.ts @@ -114,10 +114,11 @@ export function createAdReplayStepRuntime(params: { * the artifacts collected up to that point. */ artifactPaths: Set; + warnings: string[]; onStep: ReplayTestAttemptStepSink | undefined; armSaveScript: () => void; }): { runtime: AdReplayStepRuntime; readLastResponse: () => DaemonResponse | undefined } { - const { ctx, req, artifactPaths, onStep, armSaveScript } = params; + const { ctx, req, artifactPaths, warnings, onStep, armSaveScript } = params; let lastResponse: DaemonResponse | undefined; let lastObservation: DivergenceObservation | undefined; @@ -244,7 +245,11 @@ export function createAdReplayStepRuntime(params: { // `createAdReplayStepRuntime`'s `artifactPaths` parameter. collectReplayActionArtifactPaths(response).forEach((entry) => artifactPaths.add(entry)); const ledger = [...artifactPaths]; - if (response.ok) return { status: 'ok', artifactPaths: ledger }; + if (response.ok) { + const { readResponseWarnings } = await import('@agent-device/kernel/success-text'); + warnings.push(...readResponseWarnings(response.data)); + return { status: 'ok', artifactPaths: ledger }; + } return classifyReplayDispatchFailure(response, guard, ledger); }, diff --git a/packages/replay-test/src/internal/__tests__/session-test-runtime.test.ts b/packages/replay-test/src/internal/__tests__/session-test-runtime.test.ts index f19cb89c77..67eb19ec58 100644 --- a/packages/replay-test/src/internal/__tests__/session-test-runtime.test.ts +++ b/packages/replay-test/src/internal/__tests__/session-test-runtime.test.ts @@ -294,3 +294,63 @@ test('runReplayTestAttempt cleans up without a finalizer and adds no finalizatio expect(result.warnings).toEqual([]); expect(cleanupSession).toHaveBeenCalledWith('default:test:no-finalizer'); }); + +test.each(['passed', 'failed'] as const)( + 'successful cleanup warnings survive a %s attempt', + async (status) => { + const prior: ReplayTestAttemptOutcome = + status === 'passed' + ? PASSED + : { + status: 'failed', + error: { code: 'COMMAND_FAILED', message: 'assertion failed' }, + warnings: ['earlier warning'], + artifactPaths: [], + infrastructure: false, + }; + const result = await runReplayTestAttempt({ + filePath: 'cleanup.ad', + sessionName: 'suite:cleanup', + requestId: 'cleanup-warning', + runReplay: async () => prior, + cleanupSession: async () => ['Device remains running.'], + ...trackCancellation(), + }); + expect(result.status).toBe(status); + expect(result.warnings).toEqual([...prior.warnings, 'Device remains running.']); + }, +); + +test('late cleanup warnings are diagnosed after the timeout result was returned', async () => { + vi.useFakeTimers(); + let finish!: (outcome: ReplayTestAttemptOutcome) => void; + const replay = new Promise((resolve) => { + finish = resolve; + }); + const cleanupSession = vi.fn(async () => + cleanupSession.mock.calls.length > 1 ? ['Device remains running.'] : [], + ); + const emitDiagnostic = vi.fn(); + const attempt = runReplayTestAttempt({ + filePath: 'late.ad', + sessionName: 'suite:late', + requestId: 'late-warning', + timeoutMs: 10, + runReplay: async () => replay, + cleanupSession, + ...trackCancellation(), + emitDiagnostic, + }); + await vi.advanceTimersByTimeAsync(2010); + const result = await attempt; + finish(PASSED); + await vi.waitFor(() => expect(cleanupSession).toHaveBeenCalledTimes(2)); + expect(emitDiagnostic).toHaveBeenCalledWith( + expect.objectContaining({ + level: 'warn', + phase: 'test_late_cleanup_warning', + data: expect.objectContaining({ session: 'suite:late', warning: 'Device remains running.' }), + }), + ); + await expect(attempt).resolves.toBe(result); +}); diff --git a/packages/replay-test/src/internal/session-test-runtime.ts b/packages/replay-test/src/internal/session-test-runtime.ts index 0c8c50ab2d..54047f3fee 100644 --- a/packages/replay-test/src/internal/session-test-runtime.ts +++ b/packages/replay-test/src/internal/session-test-runtime.ts @@ -164,7 +164,9 @@ export async function runReplayTestAttempt( ts: new Date().toISOString(), session: sessionName, }); - await cleanupSession(sessionName); + const cleanupWarnings = await cleanupSession(sessionName); + if (outcome && cleanupWarnings) + for (const warning of cleanupWarnings) outcome = appendReplayTestWarning(outcome, warning); appendReplayTestTimingEvent(tracePath, { type: 'replay_test_cleanup_stop', ts: new Date().toISOString(), @@ -243,7 +245,13 @@ async function cleanupSessionAfterLateReplay(params: { await replayPromise; } finally { try { - await cleanupSession(sessionName); + const warnings = await cleanupSession(sessionName); + for (const warning of warnings ?? []) + emitDiagnostic({ + level: 'warn', + phase: 'test_late_cleanup_warning', + data: { session: sessionName, requestId, warning }, + }); } catch (error) { const appErr = normalizeError(error); emitDiagnostic({ @@ -336,7 +344,7 @@ function markReplayTimeoutCleanupPending( } function appendReplayTestWarning( - outcome: Extract, + outcome: ReplayTestAttemptOutcome, warning: string, ): ReplayTestAttemptOutcome { return { ...outcome, warnings: [...outcome.warnings, warning] }; diff --git a/scripts/__tests__/simulator-skills-contract.test.ts b/scripts/__tests__/simulator-skills-contract.test.ts index f57e6deaf4..1c597e9431 100644 --- a/scripts/__tests__/simulator-skills-contract.test.ts +++ b/scripts/__tests__/simulator-skills-contract.test.ts @@ -37,7 +37,11 @@ const SKILLS = [ id: 'foreground platform open', requiredText: 'agent-device open --platform ios --foreground', }, - { id: 'device shutdown on finish', requiredText: 'agent-device close --shutdown' }, + { + id: 'device shutdown on finish', + requiredText: + 'When you finish, run `agent-device close`. Plain close stops a local simulator your open booted and leaves one that was already running. If the daemon policy denies `device-shutdown`, inspect the warning for the local simulator that stays running. Pass `--shutdown` to explicitly stop a local simulator regardless of boot ownership; a denied explicit stop fails with `UNAUTHORIZED` and `details.reason: DAEMON_POLICY_DENIED`.', + }, ] satisfies Contract[], prohibitions: [ { id: 'version startup probe', forbiddenText: 'agent-device --version' }, @@ -65,7 +69,11 @@ const SKILLS = [ id: 'foreground platform open', requiredText: 'agent-device open --platform android --foreground', }, - { id: 'device shutdown on finish', requiredText: 'agent-device close --shutdown' }, + { + id: 'device shutdown on finish', + requiredText: + 'When you finish, run `agent-device close`. Plain close stops a local emulator your open booted and leaves one that was already running. If the daemon policy denies `device-shutdown`, inspect the warning for the local emulator that stays running. Pass `--shutdown` to explicitly stop a local emulator regardless of boot ownership; a denied explicit stop fails with `UNAUTHORIZED` and `details.reason: DAEMON_POLICY_DENIED`.', + }, ] satisfies Contract[], prohibitions: [ { id: 'version startup probe', forbiddenText: 'agent-device --version' }, diff --git a/scripts/layering/session-state.ts b/scripts/layering/session-state.ts index 137559123f..9df6d2c347 100644 --- a/scripts/layering/session-state.ts +++ b/scripts/layering/session-state.ts @@ -79,7 +79,6 @@ export const SESSION_STATE_FIELD_OWNERS: Readonly = new Set([ 'actions', + // #4162: `SessionStore.updateOpenDevice` binds boot ownership to the current device identity. + // Close only reads the fact; a replacement cannot inherit it. + 'device', + 'bootedByOpen', + // #4585: `SessionStore.updateOpenDevice` records the launch identity of the boot above in the + // same write. Close compares it with the current emulator process before it stops the device. + 'androidLaunchIdentity', // #4237: `close` marks a session it keeps through `SessionStore.markCloseEffectsUnconfirmed`. 'closeEffectsUnconfirmed', 'createdAt', diff --git a/skills/agent-device/SKILL.md b/skills/agent-device/SKILL.md index 603796cd69..924239b0db 100644 --- a/skills/agent-device/SKILL.md +++ b/skills/agent-device/SKILL.md @@ -13,7 +13,7 @@ agent-device open --foreground That starts the session and returns the initial interactive snapshot with `@refs`. -Loop: act with `press|click|fill|longpress ... --settle`, `scroll --settle`, or `back --settle`; continue from the printed diff, verify the named expectation with a read-only command (`wait text "..."`, `is`, or `get`; bare `find` clicks, so check with `find text "..." exists`), then run `agent-device close`, or `agent-device close --shutdown` if your session booted a local simulator or emulator, unless the user asks to keep it running. +Loop: act with `press|click|fill|longpress ... --settle`, `scroll --settle`, or `back --settle`; continue from the printed diff, verify the named expectation with a read-only command (`wait text "..."`, `is`, or `get`; bare `find` clicks, so check with `find text "..." exists`), then run `agent-device close`. Plain close also stops a local simulator or emulator your open booted, and leaves one that was already running; if the daemon policy denies `device-shutdown`, inspect the warning for the local device that stays running. Pass `--shutdown` to explicitly stop a local simulator or emulator regardless of boot ownership; a denied explicit stop fails with `UNAUTHORIZED` and `details.reason: DAEMON_POLICY_DENIED`. When the emulator process its own open launched is gone or cannot be verified, plain close leaves the emulator running and warns. For exploratory QA, read `agent-device help dogfood`; its platform checks run `agent-device audit`. diff --git a/skills/android-emulator/SKILL.md b/skills/android-emulator/SKILL.md index 433f57c9ee..34671fa3ce 100644 --- a/skills/android-emulator/SKILL.md +++ b/skills/android-emulator/SKILL.md @@ -21,7 +21,7 @@ agent-device open --platform android --foreground Follow the initial interactive snapshot and corrective error hints. If the shell reports that `agent-device` is unavailable, stop and ask the user to install it or expose their existing installation on `PATH`. -When you finish, if your session booted the emulator, run `agent-device close --shutdown`, unless the user asks to keep it running. +When you finish, run `agent-device close`. Plain close stops a local emulator your open booted and leaves one that was already running. If the daemon policy denies `device-shutdown`, inspect the warning for the local emulator that stays running. Pass `--shutdown` to explicitly stop a local emulator regardless of boot ownership; a denied explicit stop fails with `UNAUTHORIZED` and `details.reason: DAEMON_POLICY_DENIED`. When the emulator process its own open launched is gone or cannot be verified, plain close leaves the emulator running and warns. Only when the task is specialized or a command shape is unclear, read the relevant version-matched help topic: diff --git a/skills/dogfood/SKILL.md b/skills/dogfood/SKILL.md index cd9b0ec086..912bf16c99 100644 --- a/skills/dogfood/SKILL.md +++ b/skills/dogfood/SKILL.md @@ -22,7 +22,7 @@ Read current CLI guidance: agent-device help dogfood ``` -Loop: open app -> snapshot -i + screenshot -> explore flows -> capture evidence per issue -> close (`close --shutdown` if your session booted a local simulator or emulator, unless the user asks to keep it running). +Loop: open app -> snapshot -i + screenshot -> explore flows -> capture evidence per issue -> close (plain close also stops a local simulator or emulator your open booted unless daemon policy denies `device-shutdown`; inspect warnings for a local device kept running). When the emulator process its own open launched is gone or cannot be verified, plain close leaves the emulator running and warns. On the first screen, and after a screen changes meaningfully, run `agent-device audit` when the target supports snapshots. Report its findings as accessibility findings. diff --git a/skills/ios-simulator/SKILL.md b/skills/ios-simulator/SKILL.md index 9560e21888..99c8931c79 100644 --- a/skills/ios-simulator/SKILL.md +++ b/skills/ios-simulator/SKILL.md @@ -21,7 +21,7 @@ agent-device open --platform ios --foreground Follow the initial interactive snapshot and corrective error hints. If the shell reports that `agent-device` is unavailable, stop and ask the user to install it or expose their existing installation on `PATH`. -When you finish, if your session booted the simulator, run `agent-device close --shutdown`, unless the user asks to keep it running. +When you finish, run `agent-device close`. Plain close stops a local simulator your open booted and leaves one that was already running. If the daemon policy denies `device-shutdown`, inspect the warning for the local simulator that stays running. Pass `--shutdown` to explicitly stop a local simulator regardless of boot ownership; a denied explicit stop fails with `UNAUTHORIZED` and `details.reason: DAEMON_POLICY_DENIED`. Only when the task is specialized or a command shape is unclear, read the relevant version-matched help topic: diff --git a/src/commands/schema/cli-help-workflows.ts b/src/commands/schema/cli-help-workflows.ts index cb5f505691..1943a2a53d 100644 --- a/src/commands/schema/cli-help-workflows.ts +++ b/src/commands/schema/cli-help-workflows.ts @@ -29,7 +29,7 @@ Loop: 4. Treat a settled:true diff as the next observation. Do not add wait stable or another snapshot when the diff already shows the next target or expected result. 5. If --settle prints not settled, follow its hint before the next ref-based action. 6. Verify named expectations with wait text/selector/absent, get, is, find text "..." exists, or the settled diff. Bare find clicks. A bare screenshot/snapshot is not verification for a named expectation. - 7. Close the session when the script ends. If your session booted a local simulator or emulator, use close --shutdown, unless the user asks to keep it running. + 7. Close the session when the script ends. Plain close stops a local simulator or emulator this session's open booted unless daemon policy denies device-shutdown; inspect warnings for a local device kept running. When the emulator process its own open launched is gone or cannot be verified, plain close leaves the emulator running and reports why. A device that was already running keeps running. Command shapes: agent-device open com.example.app --relaunch @@ -339,7 +339,7 @@ Loop: 3. Use snapshot -i and press/fill/click/longpress --settle for UI-driving steps. 4. Use the settled diff as evidence when it shows the changed behavior; otherwise verify with wait/get/is, find text "..." exists, screenshot, logs, network, perf, or trace based on the claim. 5. Record timings, token/output size, screenshots/videos, logs, or perf artifacts only when they answer the validation question. - 6. Close sessions and release leases before finishing. If your session booted a local simulator or emulator, use close --shutdown, unless the user asks to keep it running. + 6. Close sessions and release leases before finishing. Plain close stops a local simulator or emulator this session's open booted unless daemon policy denies device-shutdown; inspect warnings for a local device kept running. When the emulator process its own open launched is gone or cannot be verified, plain close leaves the emulator running and reports why. A device that was already running keeps running. Evidence: CLI/runtime freshness: pnpm build, pnpm clean:daemon, then agent-device --version or the command under test. diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 53f255ac5f..4e7ba8eb25 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -141,7 +141,7 @@ Validation and evidence: React Native: help react-native for Metro/Re.Pack reload, DevTools, RN overlays. JS-only change: metro reload, wait text "Home"; open --relaunch for native reset. -Lifecycle facts (trust these instead of probing): open without --relaunch is idempotent-foreground except native macOS app opens (background); --relaunch restarts it. close keeps a healthy iOS runner warm by default; runners/daemons self-idle after 5 minutes; stale leases self-reclaim. open device claims reclaim other worktrees' warm runners; "already owned by another agent-device daemon" = owner outside claim arbitration. Env vars: help physical-device. +Lifecycle facts (trust these instead of probing): open without --relaunch is idempotent-foreground (native macOS: background); --relaunch restarts it. Plain close can stop its device; rules: help close. iOS can retain warm runners on running devices; runners/daemons self-idle after 5 minutes; stale leases self-reclaim. open reclaims other worktrees' warm runners; "already owned by another agent-device daemon" = outside arbitration. Env vars: help physical-device. Escalate: help manual-qa scripted manual QA @@ -426,7 +426,7 @@ Runner and daemon lifecycle (applies to simulators too): open without --relaunch is idempotent-foreground for an already-running app, except native macOS app opens keep it in the background (help macos); neither restarts the process. open --relaunch restarts the app; on iOS simulators this collapses to one simctl launch --terminate-running-process call instead of a separate terminate-then-launch. If a relaunch leaves an existing session's device effects unconfirmed, close can release its claim; idle shutdown retries cleanup and leaves an unconfirmed claim stale, while embedded runtimes and AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS=0 require close because they do not shut down for idleness. No runner read launches a session app that is not running: snapshot, wait, is, get, a reading find, and an interaction's leading reads (a gesture's viewport read, the capture that resolves a selector click/fill) answer the retriable APP_NOT_RUNNING instead of bare-launching over a launch SpringBoard still holds behind its deep-link confirmation. Only open, activate, and a command that mutates without a leading read bring a stopped app up. - close keeps a healthy iOS simulator XCTest runner warm by default so the next open on that simulator (same udid in the same simulator set) skips the runner build, unless --shutdown was requested, the session was recording, or its device lease ends on close. A lease allocated with retainOnClose can keep the runner between sessions; releasing or expiring that lease stops its runner unless a session outside the lease has taken over the device. A retained runner auto-stops after an idle window (default 5 minutes); set AGENT_DEVICE_IOS_RUNNER_IDLE_STOP_MS to override, or 0 to disable idle stopping. Lease release, expiry, and graceful daemon shutdown still clean up runners they own. Only a ready runner with an observed listener is retained; close retires unfinished prewarm recovery. Losing the retained listener stops that generation, and graceful daemon shutdown stops idle retained runners rather than handing them off without supervision. + close keeps a healthy iOS simulator XCTest runner warm by default so the next open on that simulator (same udid in the same simulator set) skips the runner build, unless the close stopped the device (this session's open booted it, or --shutdown), the session was recording, or its device lease ends on close. A lease allocated with retainOnClose can keep the runner between sessions; releasing or expiring that lease stops its runner unless a session outside the lease has taken over the device. A retained runner auto-stops after an idle window (default 5 minutes); set AGENT_DEVICE_IOS_RUNNER_IDLE_STOP_MS to override, or 0 to disable idle stopping. Lease release, expiry, and graceful daemon shutdown still clean up runners they own. Only a ready runner with an observed listener is retained; close retires unfinished prewarm recovery. Losing the retained listener stops that generation, and graceful daemon shutdown stops idle retained runners rather than handing them off without supervision. Each AGENT_DEVICE_STATE_DIR runs its own daemon. It self-exits after an idle window (default 5 minutes, matching the runner idle-stop default) once it has no open sessions, no in-flight requests, and no active recording; set AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS to override, or 0 to disable idle reap. A client starting a local daemon waits while the daemon process stays alive and keeps publishing startup progress, so an overloaded host makes startup slower, not failed. It stops at a ceiling (default 120 s; set AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS to a positive integer number of milliseconds to override) and names the outcome in error details.reason: startup-exited (the process ended before registering), startup-stalled (alive, no startup progress for a fixed 60 s window the ceiling variable does not change), or startup-ceiling (a startup was still live when the ceiling passed — this client's daemon or another client's; the client stops its own launch and never signals another client's live daemon. Only a progressing own launch outlasts the 60 s stall window, so a ceiling set below 60 s also ends a silent own launch this way). details.phases carries the startup phase timings it observed and details.startupTimeoutMs the effective ceiling. Branch on details.reason, never on the message. The variable is read only when a client must start a daemon: a value that is not a positive integer fails with INVALID_ARGS before the daemon spawns, and a client that only attaches to or reuses a running daemon never reads it. On iOS simulators, open prepares app accessibility before launching an app or URL. If a running app has an empty accessibility tree after an earlier XCTest session, use open --relaunch, then snapshot -i. A preparation failure is logged and does not block launch. @@ -631,7 +631,7 @@ Rules: A busy direct-proxy device error means another agent owns the device until it closes or its inactivity lease expires. Keep the proxy token secret. Anyone with the token can control the proxied daemon. A daemon with AGENT_DEVICE_HTTP_AUTH_HOOK configured treats HTTP requests as remote: host-path install sources are rejected, as are install and reinstall binary paths, push payload files, and xctrace template files; uploaded artifacts remain supported, inline push JSON remains supported, and Maestro runScript, evalScript, and JavaScript conditions are rejected. No-hook local HTTP and socket flows retain their local behavior. - A daemon started with AGENT_DEVICE_DAEMON_POLICY= enforces that policy for every request, including batch steps and replay actions: it can limit which devices are visible and bindable, allow or deny commands (Maestro flows reach the daemon as the runtime command), and deny device-shutdown. A denial is UNAUTHORIZED with details.reason DAEMON_POLICY_DENIED; do not retry it. Use an allowed command or device, or ask the daemon operator to change the policy; a denied capability such as device-shutdown has no allowed alternative. + A daemon started with AGENT_DEVICE_DAEMON_POLICY= enforces that policy for every request, including batch steps and replay actions: it can limit which devices are visible and bindable, allow or deny commands (Maestro flows reach the daemon as the runtime command), and deny device-shutdown. A denial is UNAUTHORIZED with details.reason DAEMON_POLICY_DENIED; do not retry it. Use an allowed command or device, or ask the daemon operator to change the policy; a denied capability such as device-shutdown has no allowed alternative. A plain close skips the denied implicit stop of a local simulator or emulator this session's open booted, succeeds, and reports the kept local device in warnings. Explicit close --shutdown fails with UNAUTHORIZED and details.reason DAEMON_POLICY_DENIED. If local/proxy iOS reports that the runner is already owned by another agent-device daemon after lease admission, retry after the owning session closes or after lease expiry. If the conflict repeats, clean stale daemon state on the machine with simulator access. Do not use --config as a remote profile flag. --config loads CLI defaults; --remote-config selects remote daemon/profile settings. For self-contained scripts, pass the same --remote-config to every operational command, including disconnect; a preceding connect is optional but not required. diff --git a/src/platform-runtime-android-emulator-host.test.ts b/src/platform-runtime-android-emulator-host.test.ts index 051061ca83..f6416af78e 100644 --- a/src/platform-runtime-android-emulator-host.test.ts +++ b/src/platform-runtime-android-emulator-host.test.ts @@ -1,4 +1,14 @@ import { beforeEach, expect, test, vi } from 'vitest'; +import type { DeviceInfo } from '@agent-device/kernel/device'; + +const { readAndroidEmulatorLaunchStartTime } = vi.hoisted(() => ({ + readAndroidEmulatorLaunchStartTime: vi.fn( + async (): Promise => 'Mon Nov 9 10:00:00 2026', + ), +})); +vi.mock('@agent-device/platform-android/device-boot', () => ({ + readAndroidEmulatorLaunchStartTime, +})); const { runCmd, runCmdDetached, runCmdDetachedMonitored, emitDiagnostic } = vi.hoisted(() => ({ runCmd: vi.fn(async (_cmd: string, args: readonly string[]) => ({ @@ -38,6 +48,7 @@ vi.mock('@agent-device/host-kit/process', () => ({ import { createAndroidEmulatorHost } from './platform-runtime-android-emulator-host.ts'; beforeEach(() => { + readAndroidEmulatorLaunchStartTime.mockClear(); runCmd.mockClear(); runCmdDetached.mockClear(); runCmdDetachedMonitored.mockClear(); @@ -45,6 +56,35 @@ beforeEach(() => { stopProcessAndConfirmExit.mockClear(); }); +const emulator: DeviceInfo = { + platform: 'android', + kind: 'emulator', + id: 'emulator-5558', + name: 'Pixel_9', +}; +const launchIdentity = { pid: 4242, startTime: 'Mon Nov 9 10:00:00 2026' }; + +test('binds the launched process to the pid it spawned and the start time it recorded', async () => { + const host = createAndroidEmulatorHost('linux'); + await host.launch('Pixel_9', true, 90_000); + expect(readAndroidEmulatorLaunchStartTime).toHaveBeenCalledWith(4242); + await expect(host.bindLaunchedEmulator!(4242, emulator)).resolves.toEqual(launchIdentity); +}); + +test('binds nothing for a pid this host did not launch', async () => { + const host = createAndroidEmulatorHost('linux'); + await host.launch('Pixel_9', true, 90_000); + await expect(host.bindLaunchedEmulator!(4243, emulator)).resolves.toBeUndefined(); +}); + +test('a launch whose start time could not be read binds nothing', async () => { + readAndroidEmulatorLaunchStartTime.mockResolvedValueOnce(null); + const host = createAndroidEmulatorHost('linux'); + await host.launch('Pixel_9', true, 90_000); + await expect(host.bindLaunchedEmulator!(4242, emulator)).resolves.toBeUndefined(); + expect(emitDiagnostic).not.toHaveBeenCalled(); +}); + test('a windowed macOS launch hands focus back to the app frontmost before launch', async () => { await expect(createAndroidEmulatorHost('darwin').launch('Pixel_9', false, 90_000)).resolves.toBe( 4242, diff --git a/src/platform-runtime-android-emulator-host.ts b/src/platform-runtime-android-emulator-host.ts index 855e1da6fe..c414c1a526 100644 --- a/src/platform-runtime-android-emulator-host.ts +++ b/src/platform-runtime-android-emulator-host.ts @@ -1,11 +1,9 @@ import type { DeviceReadinessRuntimeHost } from '@agent-device/contracts/device-readiness-runtime'; +import { readAndroidEmulatorLaunchStartTime } from '@agent-device/platform-android/device-boot'; import { listLocalDeviceInventory } from '@agent-device/device-selection/device-inventory-context'; import { runCmd, runCmdDetached, runCmdDetachedMonitored } from '@agent-device/host-kit/command'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; -import { - readProcessIdentityFacts, - stopProcessAndConfirmExit, -} from '@agent-device/host-kit/process'; +import { stopProcessAndConfirmExit } from '@agent-device/host-kit/process'; const LSAPPINFO_PID = /"pid"=(\d+)/; const EMULATOR_STOP_BUDGET = { termTimeoutMs: 1_500, killTimeoutMs: 1_500 } as const; @@ -80,11 +78,19 @@ export function createAndroidEmulatorHost( const pid = runCmdDetached('emulator', args); launched.set(pid, { avdName, - startTime: readProcessIdentityFacts(pid).then((facts) => facts.startTime), + startTime: readAndroidEmulatorLaunchStartTime(pid), }); if (frontmostPid !== undefined) returnFocusAfterLaunch(pid, frontmostPid, bootBudgetMs); return pid; }, + bindLaunchedEmulator: async (pid) => { + // Binding is recording what this launch was: the pid this process spawned and when the host + // says it started. Close proves the emulator answering the serial is still that process. + const record = launched.get(pid); + if (!record) return undefined; + const startTime = await record.startTime; + return startTime ? { pid, startTime } : undefined; + }, terminate, }); } diff --git a/src/platform-runtime-daemon-services.ts b/src/platform-runtime-daemon-services.ts index 1a1c13ef4e..02a9bdc6df 100644 --- a/src/platform-runtime-daemon-services.ts +++ b/src/platform-runtime-daemon-services.ts @@ -1,5 +1,5 @@ import { appleSessionObservation } from './platform-runtime-apple-resources.ts'; -import { deviceBootObservation } from './platform-runtime-device-boot.ts'; +import { deviceBootObservation, launchedDeviceProcess } from './platform-runtime-device-boot.ts'; import { ensureLocalPlatformDeviceReady } from './platform-runtime-device-ready.ts'; import { resolveRequestedOpenSurface, @@ -18,6 +18,7 @@ export function createDaemonPlatformServices(): DaemonPlatformServices { return Object.freeze({ appleSessionObservation, deviceBootObservation, + launchedDeviceProcess, ensureLocalDeviceReady: ensureLocalPlatformDeviceReady, resolveRequestedOpenSurface, validateOpenRelaunchTarget, diff --git a/src/platform-runtime-device-boot.test.ts b/src/platform-runtime-device-boot.test.ts index 9e97e858d0..f8fa9a0222 100644 --- a/src/platform-runtime-device-boot.test.ts +++ b/src/platform-runtime-device-boot.test.ts @@ -1,5 +1,9 @@ import { beforeEach, expect, test, vi } from 'vitest'; -import type { DeviceBootObservation } from '@agent-device/contracts/device-boot'; +import type { + DeviceBootObservation, + LaunchedProcessCheck, + LaunchedProcessStopConfirmation, +} from '@agent-device/contracts/device-boot'; const mocks = vi.hoisted(() => ({ observeSimulatorBootTimeMs: vi.fn(async (): Promise => ({ @@ -10,12 +14,19 @@ const mocks = vi.hoisted(() => ({ observed: false, reason: 'unobserved', })), + checkAndroidEmulatorLaunchProcess: vi.fn( + async (): Promise => 'changed' satisfies LaunchedProcessCheck, + ), + confirmAndroidEmulatorLaunchProcessStopped: vi.fn( + async (): Promise => 'unconfirmed', + ), })); vi.mock('@agent-device/platform-apple/simulator-boot', () => mocks); vi.mock('@agent-device/platform-android/device-boot', () => mocks); import { + ANDROID_DEVICE, ANDROID_EMULATOR, IOS_SIMULATOR, IPADOS_SIMULATOR, @@ -24,7 +35,7 @@ import { TVOS_SIMULATOR, VISIONOS_SIMULATOR, } from '@agent-device/test-kit'; -import { deviceBootObservation } from './platform-runtime-device-boot.ts'; +import { deviceBootObservation, launchedDeviceProcess } from './platform-runtime-device-boot.ts'; beforeEach(() => { vi.clearAllMocks(); @@ -68,3 +79,36 @@ test('a device whose family asks no boot question is refused without loading a p expect(mocks.observeSimulatorBootTimeMs).not.toHaveBeenCalled(); expect(mocks.observeAndroidBootTimeMs).not.toHaveBeenCalled(); }); + +const LAUNCH_IDENTITY = { pid: 4112, startTime: 'launch-start-time' } as const; + +test('an Android emulator is the only device whose launch has a process to check', async () => { + // The answer is passed through as the Android owner gave it, so the composition adds no verdict. + expect(await launchedDeviceProcess.checkLaunchedProcess(ANDROID_EMULATOR, LAUNCH_IDENTITY)).toBe( + 'changed', + ); + expect(mocks.checkAndroidEmulatorLaunchProcess).toHaveBeenCalledWith(LAUNCH_IDENTITY); + + await launchedDeviceProcess.confirmLaunchedProcessStopped(ANDROID_EMULATOR, LAUNCH_IDENTITY); + expect(mocks.confirmAndroidEmulatorLaunchProcessStopped).toHaveBeenCalledWith(LAUNCH_IDENTITY); +}); + +test('a device with no host launch process is answered without loading a probe', async () => { + for (const device of [IOS_SIMULATOR, ANDROID_DEVICE, MACOS_DEVICE]) { + expect(await launchedDeviceProcess.checkLaunchedProcess(device, LAUNCH_IDENTITY)).toBe( + 'not-applicable', + ); + expect(await launchedDeviceProcess.confirmLaunchedProcessStopped(device, LAUNCH_IDENTITY)).toBe( + 'stopped', + ); + } + expect(mocks.checkAndroidEmulatorLaunchProcess).not.toHaveBeenCalled(); + expect(mocks.confirmAndroidEmulatorLaunchProcessStopped).not.toHaveBeenCalled(); +}); + +test('an Android launch that recorded no process is refused before the process is read', async () => { + expect(await launchedDeviceProcess.checkLaunchedProcess(ANDROID_EMULATOR, undefined)).toBe( + 'unverified', + ); + expect(mocks.checkAndroidEmulatorLaunchProcess).not.toHaveBeenCalled(); +}); diff --git a/src/platform-runtime-device-boot.ts b/src/platform-runtime-device-boot.ts index aa5f32acf9..ddc1d2f00a 100644 --- a/src/platform-runtime-device-boot.ts +++ b/src/platform-runtime-device-boot.ts @@ -1,7 +1,11 @@ import type { DeviceBootObservation, DeviceBootObservationService, + LaunchedDeviceProcessService, + LaunchedProcessCheck, + LaunchedProcessStopConfirmation, } from '@agent-device/contracts/device-boot'; +import type { AndroidEmulatorLaunchIdentity } from '@agent-device/contracts/device-readiness-runtime'; import { isIosFamily, type DeviceInfo } from '@agent-device/kernel/device'; /** @@ -24,3 +28,36 @@ export const deviceBootObservation: DeviceBootObservationService = Object.freeze return { observed: false, reason: 'unsupported-device' }; }, }); + +/** + * Whether the process that launched a device is still the caller's own launch, and whether it took + * the shutdown the caller asked of the device. Only an Android emulator has a host process this + * machine launches to bring the device up, so every other leaf answers `not-applicable` rather than + * a miss, and the caller stops the device on the platform's answer alone. + */ +export const launchedDeviceProcess: LaunchedDeviceProcessService = Object.freeze({ + async checkLaunchedProcess( + device: DeviceInfo, + identity: AndroidEmulatorLaunchIdentity | undefined, + ): Promise { + if (!isAndroidEmulator(device)) return 'not-applicable'; + if (!identity) return 'unverified'; + const { checkAndroidEmulatorLaunchProcess } = + await import('@agent-device/platform-android/device-boot'); + return await checkAndroidEmulatorLaunchProcess(identity); + }, + async confirmLaunchedProcessStopped( + device: DeviceInfo, + identity: AndroidEmulatorLaunchIdentity, + ): Promise { + if (!isAndroidEmulator(device)) return 'stopped'; + const { confirmAndroidEmulatorLaunchProcessStopped } = + await import('@agent-device/platform-android/device-boot'); + return await confirmAndroidEmulatorLaunchProcessStopped(identity); + }, +}); + +/** The one device kind whose boot this host starts as a process it can later name. */ +function isAndroidEmulator(device: DeviceInfo): boolean { + return device.platform === 'android' && device.kind === 'emulator'; +} diff --git a/test/integration/interaction-contract/daemon-harness.ts b/test/integration/interaction-contract/daemon-harness.ts index 70202b93ea..9ba111fa4d 100644 --- a/test/integration/interaction-contract/daemon-harness.ts +++ b/test/integration/interaction-contract/daemon-harness.ts @@ -1,4 +1,5 @@ import { mkdtempForTestSync } from '@agent-device/test-kit'; +import { onTestFailed } from 'vitest'; import { assertRpcOk } from '../provider-scenarios/assertions.ts'; import { FIRST_SCREEN_NODES, @@ -42,6 +43,32 @@ export async function withIosContractDaemon( run: (daemon: ProviderScenarioHarness, transcript: ProviderScenarioTranscript) => Promise, options: { saveScript?: boolean | string } = {}, ): Promise { + const startedAt = performance.now(); + const timings: Array<{ stage: string; startMs: number; endMs: number }> = []; + let activeStage = 'create'; + let stageStartedAt = startedAt; + const enter = (stage: string) => { + const now = performance.now(); + timings.push({ + stage: activeStage, + startMs: Math.round(stageStartedAt - startedAt), + endMs: Math.round(now - startedAt), + }); + if (timings.length > 8) timings.shift(); + activeStage = stage; + stageStartedAt = now; + }; + onTestFailed(() => { + console.error( + '[interaction-contract-stage]', + JSON.stringify({ + activeStage, + elapsedMs: Math.round(performance.now() - startedAt), + stageStartedMs: Math.round(stageStartedAt - startedAt), + timings, + }), + ); + }); const transcript = createProviderTranscript([ ...Array.from({ length: SETTLING_CAPTURE_READS }, () => runnerSnapshotEntry(FIRST_SCREEN_NODES), @@ -66,13 +93,25 @@ export async function withIosContractDaemon( }); await withProviderScenarioResource( - async () => - await createProviderScenarioHarness({ + async () => { + const daemon = await createProviderScenarioHarness({ appleRunnerProvider: () => appleRunnerProvider, appleToolProvider: () => appleTool.provider, deviceInventoryProvider: async () => [PROVIDER_SCENARIO_IOS_SIMULATOR], env: { AGENT_DEVICE_CLAIMS_DIR: mkdtempForTestSync('interaction-contract-claims-') }, - }), + }); + return { + ...daemon, + callCommand: async (...args: Parameters) => { + enter(args[0]); + return await daemon.callCommand(...args); + }, + close: async () => { + enter('cleanup'); + await daemon.close(); + }, + }; + }, async (daemon) => { const open = await daemon.callCommand('open', [CONTRACT_APP], { platform: 'ios', @@ -82,6 +121,7 @@ export async function withIosContractDaemon( }); assertRpcOk(open); assertRpcOk(await daemon.callCommand('snapshot')); + enter('scenario'); await run(daemon, scenarioTranscript); transcript.assertComplete(); }, diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index c9daba39d8..4923cdb6c9 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -106,6 +106,7 @@ Open apps and links: - iOS simulators: `open` prepares app accessibility before launching an app or URL. If an already-running app has an empty accessibility tree after an earlier XCTest session, run `open --relaunch`, then `snapshot -i`. Preparation failures are logged and do not block launch. Runner cleanup also restores app accessibility after confirmed termination; a runner started by a release before this change is not restored, so relaunch the app with `open --relaunch`. - Android React Native: `open --relaunch` needs an installed package name. Install or reinstall the APK first; `open --relaunch` is rejected. For Metro-backed JS changes, run `metro reload` before reaching for `open --relaunch`. - Android (adb): an intent target such as `open settings` records the package that opened as `appBundleId`. `open settings --relaunch` stops and restarts that app. If the intent matches more than one activity, `--relaunch` fails. +- `close` stops the local Apple simulator or Android emulator that session's `open` booted, and reports it in `data.shutdown` — the same field `close --shutdown` reports. A device that was already running when the session opened keeps running unless you pass `--shutdown`. For an Android emulator, that stop is owed to the emulator process the session's `open` launched, which `close` checks first; when that process is gone or the host cannot answer for it, plain `close` leaves the emulator running and reports why in `warnings`. A daemon whose policy denies `device-shutdown` stops nothing: `close --shutdown` fails with `UNAUTHORIZED` and `error.details.reason: DAEMON_POLICY_DENIED`, and a plain `close` succeeds and says in `warnings` that it left the device running. Plain `close` never stops a physical or provider-owned device. Explicit provider shutdown follows the provider release action; with [Limrun](/docs/limrun), it can delete an instance. - Android (ADB): `close` force-stops the app, then checks for 2 seconds that it has left the foreground, waits up to 10 seconds for the processes it killed to exit, and checks for 2 more that no new process started. If a check window ends first, `close` fails with `details.reason: android-app-close-timeout` and `details.phase` set to `foreground`, `exit`, or `process`; a process that survives the force-stop fails with `exit`, and apps Android restarts at once, such as the launcher, fail with `process`. `open --relaunch` runs the same checks but accepts a new process once the killed ones exit, because Android can restart an app at once for a background client, such as Settings on Android 17. When `pidof` cannot list the app's processes, `close` fails with `details.reason: android-process-probe-unavailable`; if that happens before the force-stop, the app keeps running. - To diagnose an Android foreground-close timeout (`details.phase: foreground`), inspect `details.foregroundObservations` and `details.initialProcessCount` in the JSON error. The observations retain at most the last five probes: `startMs` and `endMs` are milliseconds from the start of the foreground check, `remainingMs` is the budget left when the probe ends, and `result` is `target`, `other`, or `unknown`. The process count is read before force-stop. In the [session request log](/docs/sessions#find-a-sessions-logs-and-artifacts), the `android_close_foreground_fence` diagnostic records this history as `data.observations` with `data.initialProcessCount`. If a foreground probe throws, that diagnostic also retains the history with an `error` result for the failed probe; the command reports the probe failure. - When `close` cannot confirm its cleanup on a session that holds a device claim, it fails and keeps the session and its claim, so the device is not handed on unconfirmed. Run `close` again with the same options to retry the cleanup and release the device, leaving out `--save-script` once the first attempt has published the script. Only `close`, or a successful `open`, is supported on the kept session: other commands work, but the session stays marked, so an idle daemon can still shut it down. If nobody retries, the kept session does not keep the daemon alive: when the daemon has been idle for its idle timeout and shuts down, its shutdown retries the cleanup, and a claim it still cannot confirm goes stale instead of being released. Embedded runtimes and `AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS=0` never shut down for idleness, so there a retried `close` is the only release. diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index f28cd07a67..5c05fb003f 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -316,7 +316,9 @@ AGENT_DEVICE_DAEMON_POLICY=./policy.json agent-device proxy stay denied. Some client-side tools reach the daemon through internal commands: allow `runtime` for Maestro flows, and `install-from-source` for remote installs. - `capabilities.deny: ["device-shutdown"]` blocks `shutdown`, `close --shutdown`, and any other path - that would shut the device down. + that would shut the device down. A plain `close` whose own `open` booted a local simulator or + emulator skips that implicit stop, succeeds, and warns that the local device is still running. + Explicit `close --shutdown` fails with `UNAUTHORIZED` and `details.reason: DAEMON_POLICY_DENIED`. - `leases.require: "macos-app"` (the only accepted value) refuses every request that is not made under a `macos-app` lease or that its allow list does not cover, including requests that name no lease and inventory commands such as `doctor` and `session list`. diff --git a/website/docs/docs/sessions.md b/website/docs/docs/sessions.md index f8540e6caa..6dfd98c7ba 100644 --- a/website/docs/docs/sessions.md +++ b/website/docs/docs/sessions.md @@ -118,18 +118,40 @@ prints the `address` that `--session` accepts. ## Shut down the device on close -Add `--shutdown` to shut down an Apple simulator or Android emulator when you close the session. Use it -in CI and on shared hosts so devices don't keep running after the run: +`close` stops the local simulator or emulator that this session's `open` booted, so the device ends +as the session found it. A device that was already running when you opened it keeps running: + +```bash +agent-device open --platform ios --device iPhone_17_Pro +agent-device close # the simulator this open booted ends shut down +``` + +For an Android emulator, that stop is owed to the emulator process this session's `open` +launched, so `close` checks that process before it asks for the stop. When it is gone, or when the +host cannot answer for it, plain `close` leaves the emulator running and reports why in `warnings`. +Use `close --shutdown` to stop the emulator anyway. + +Add `--shutdown` to explicitly stop a local simulator or emulator regardless of boot ownership. +Physical devices are not stopped. Provider sessions follow the provider's shutdown action. +With [Limrun](./limrun.md), `--shutdown` ends the instance or attachment and can delete an instance +that agent-device created: ```bash agent-device close --shutdown ``` -Without `--shutdown`, `close` can keep a ready, idle iOS simulator runner warm for the next `open` -when its listener connection is still live and the session has no screen recording or device lease. -Unfinished runner startup is stopped. If you shut that simulator down yourself while the runner is -retained, losing its listener connection stops the retained runner. Idle retained runners also stop -when their daemon shuts down gracefully. +When a shutdown result exists, `close` reports it in `data.shutdown`. Check `shutdown.success` to +see whether the stop succeeded. The field is omitted when no shutdown result is returned, including +a plain close of a prebooted device or a policy-skipped implicit stop. If the daemon policy denies `device-shutdown`, `close --shutdown` fails with +`UNAUTHORIZED` and `error.details.reason: DAEMON_POLICY_DENIED`. Plain `close` skips its implicit stop, +succeeds, and reports the local simulator or emulator it left running in `warnings`. + +When the session keeps its device running, `close` can keep a ready, idle iOS simulator runner warm +for the next `open` when its listener connection is still live and the session has no screen +recording or device lease. A close that stops the device stops its runner instead. Unfinished runner +startup is always stopped. If you shut that simulator down yourself while the runner is retained, +losing its listener connection stops the retained runner. Idle retained runners also stop when their +daemon shuts down gracefully. ## Wait for a slow or busy device @@ -229,8 +251,8 @@ xcrun simctl install "$udid" ./App.app never runs unfenced. Add `--wait ` to `open` to queue for the device instead. - The script exits with the command's status, as long as the command is the last line. To run more after it, save `status=$?` and finish with `exit "$status"`. -- The `trap` closes the session whether the command succeeds or fails. Add `--shutdown` to `close` to - shut the simulator or emulator down afterwards. +- The `trap` closes the session whether the command succeeds or fails. That `close` also shuts down a + simulator or emulator the `open` booted; add `--shutdown` to shut down one that was already running. - `open` without an app boots the device if needed and claims it, so the first call on a cold simulator can take minutes. - This is a session claim, not a claim owned by your process. If the shell dies without running its