From 453cb766c7bb783fbf22027984d38803240c1dd3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 16:29:26 +0100 Subject: [PATCH 01/10] feat(close): stop a simulator or emulator the session's own open booted Squashed rebase of #4539 onto the rewritten 0.22 (91d36280f5). The content equals 29cb52b790 except for conflict adaptations: the interaction-contract harness keeps main's single settling read, and two tests pass main's new cache argument before the lifecycle loader. --- docs/adr/0029-daemon-policy.md | 3 + docs/agents/device-verification.md | 8 +- .../client/src/__tests__/index-apps.test.ts | 10 + .../src/output/result-serialization.test.ts | 15 + .../command-surface/src/management/app.ts | 6 +- .../src/application-lifecycle-runtime.ts | 6 + packages/contracts/src/device-boot.ts | 8 + .../contracts/src/device-readiness-runtime.ts | 7 + .../contracts/src/device-shutdown-runtime.ts | 24 +- .../contracts/src/replay-test-execution.ts | 2 +- .../support/lifecycle-operations-spy.ts | 4 +- .../support/platform-services-fixture.ts | 3 + .../src/core/__tests__/daemon-policy.test.ts | 42 +- packages/daemon/src/core/daemon-policy.ts | 9 +- packages/daemon/src/core/platform-services.ts | 7 +- packages/daemon/src/core/session-state.ts | 10 + packages/daemon/src/core/session-store.ts | 29 +- .../src/core/stopped-local-android-device.ts | 3 + ...uest-router-bounded-claim-recovery.test.ts | 1 + .../request-router-replay-scope.test.ts | 67 +++ packages/daemon/src/server/request-router.ts | 8 +- .../__tests__/session-replay-command.test.ts | 144 +++-- .../handlers/session-command-input.ts | 1 + .../handlers/session-replay-command.ts | 17 +- .../daemon/src/sessions/handlers/session.ts | 2 + .../src/sessions/request-handler-chain.ts | 2 + .../__tests__/application.test.ts | 67 ++- .../session-close-external-reboot.test.ts | 536 ++++++++++++++++++ .../session-close-implicit-shutdown.test.ts | 447 +++++++++++++++ .../session-open-boot-ownership.test.ts | 122 ++++ .../__tests__/session-open-state.test.ts | 93 +++ .../session-close-lifecycle-teardown.ts | 114 +++- .../internal/session-close.ts | 88 ++- .../internal/session-open-execution.ts | 28 +- .../internal/session-open-state.ts | 22 +- .../internal/session-open.ts | 18 +- .../device-selection-resolver.test.ts | 10 + .../src/device-selection-resolver.ts | 14 +- .../src/device-boot-generation.test.ts | 66 +++ packages/platform-android/src/device-boot.ts | 46 ++ .../platform-android/src/lifecycle.test.ts | 26 +- packages/platform-android/src/lifecycle.ts | 14 +- .../src/readiness/runtime.test.ts | 82 +++ .../platform-android/src/readiness/runtime.ts | 11 +- .../src/shutdown/runtime.test.ts | 42 ++ .../platform-android/src/shutdown/runtime.ts | 29 +- .../src/daemon-port/command-types.ts | 2 +- .../src/daemon-port/native-command.ts | 84 ++- .../session-replay-runtime-engine-adapter.ts | 9 +- .../__tests__/session-test-runtime.test.ts | 60 ++ .../src/internal/session-test-runtime.ts | 14 +- .../simulator-skills-contract.test.ts | 12 +- scripts/layering/session-state.ts | 8 +- skills/agent-device/SKILL.md | 2 +- skills/android-emulator/SKILL.md | 2 +- skills/dogfood/SKILL.md | 2 +- skills/ios-simulator/SKILL.md | 2 +- src/commands/schema/cli-help-workflows.ts | 4 +- src/commands/schema/cli-help.ts | 6 +- ...form-runtime-android-emulator-host.test.ts | 38 ++ src/platform-runtime-android-emulator-host.ts | 16 + src/platform-runtime-device-boot.test.ts | 33 ++ src/platform-runtime-device-boot.ts | 44 +- ...tform-runtime-device-shutdown-host.test.ts | 14 + src/platform-runtime-device-shutdown-host.ts | 15 +- .../interaction-contract/daemon-harness.ts | 46 +- website/docs/docs/commands.md | 1 + website/docs/docs/remote-proxy.md | 4 +- website/docs/docs/sessions.md | 41 +- 69 files changed, 2549 insertions(+), 223 deletions(-) create mode 100644 packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-external-reboot.test.ts create mode 100644 packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-implicit-shutdown.test.ts create mode 100644 packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-open-boot-ownership.test.ts create mode 100644 packages/platform-android/src/device-boot-generation.test.ts 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..6be3963cba 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 an Android emulator process changed or cannot be verified, plain close leaves it 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/application-lifecycle-runtime.ts b/packages/contracts/src/application-lifecycle-runtime.ts index b1e01d7e76..c8c579a7f7 100644 --- a/packages/contracts/src/application-lifecycle-runtime.ts +++ b/packages/contracts/src/application-lifecycle-runtime.ts @@ -1,3 +1,7 @@ +import type { + AndroidShutdownVerification, + AndroidShutdownRetained, +} from './device-shutdown-runtime.ts'; import type { RuntimeOperationName } from './runtime-operation-names.ts'; import type { RuntimeOperationFact } from './platform-runtime.ts'; import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -271,10 +275,12 @@ export type CloseApplicationFinalizationInput = Readonly<{ daemonShutdown?: boolean; /** `close --shutdown` is an admitted close finalization effect, never a daemon fallback. */ shutdownTarget?: boolean; + verifyAndroidShutdown?: AndroidShutdownVerification; }>; export type CloseApplicationFinalizationResult = Readonly<{ shutdown?: TargetShutdownResult; + androidShutdownRetained?: AndroidShutdownRetained['retained']; }>; export type PrepareAppleRunnerInput = Readonly<{ diff --git a/packages/contracts/src/device-boot.ts b/packages/contracts/src/device-boot.ts index b69e386736..347bd15e72 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,10 @@ export type DeviceBootObservation = export type DeviceBootObservationService = Readonly<{ observeBootTimeMs(device: DeviceInfo): Promise; }>; + +export type DeviceShutdownGenerationService = Readonly<{ + assessShutdownGeneration( + device: DeviceInfo, + expected: AndroidEmulatorLaunchIdentity | undefined, + ): Promise<'same' | 'changed' | 'unobserved' | 'not-applicable'>; +}>; diff --git a/packages/contracts/src/device-readiness-runtime.ts b/packages/contracts/src/device-readiness-runtime.ts index 3271d4c019..bc3f602c78 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,10 @@ export type DeviceReadinessRuntimeHost = Readonly<{ androidEmulator: Readonly<{ discover(request: DeviceInventoryRequest, signal: AbortSignal): Promise; launch(avdName: string, headless: boolean, bootBudgetMs: number): Promise; + bindLaunchedEmulator?( + pid: number, + device: DeviceInfo, + ): Promise; terminate(pid: number): Promise; }>; }>; diff --git a/packages/contracts/src/device-shutdown-runtime.ts b/packages/contracts/src/device-shutdown-runtime.ts index 9791971257..fe257e06ea 100644 --- a/packages/contracts/src/device-shutdown-runtime.ts +++ b/packages/contracts/src/device-shutdown-runtime.ts @@ -2,6 +2,17 @@ import type { DeviceInfo } from '@agent-device/kernel/device'; import type { AppleToolHost, HostCommandRunner } from './platform-runtime-host.ts'; import type { TargetShutdownResult } from './target-shutdown-contract.ts'; +export type AndroidShutdownVerification = () => Promise<'same' | 'changed' | 'unobserved'>; +export type AndroidShutdownRetained = Readonly<{ retained: 'changed' | 'unobserved' }>; +export type AndroidShutdownTarget = { + (device: DeviceInfo, signal: AbortSignal): Promise; + ( + device: DeviceInfo, + signal: AbortSignal, + verify: AndroidShutdownVerification, + ): Promise; +}; + export type DeviceShutdownRuntimeOperations = Readonly<{ shutdownTarget( input: Readonly<{ @@ -32,17 +43,18 @@ export type DeviceShutdownRuntimeLoaders = Readonly<{ apple: ( dependencies: Pick, ) => Promise; - android: ( - dependencies: Pick, - ) => Promise; + android: (dependencies: Pick) => Promise< + Readonly<{ + canShutdownTarget(device: DeviceInfo): boolean; + shutdownTarget: AndroidShutdownTarget; + }> + >; }>; export type DeviceShutdownRuntimeHost = Readonly<{ apple: Readonly<{ shutdownTarget(device: DeviceInfo, signal: AbortSignal): Promise; }>; - android: Readonly<{ - shutdownTarget(device: DeviceInfo, signal: AbortSignal): Promise; - }>; + android: Readonly<{ shutdownTarget: AndroidShutdownTarget }>; close?: DeviceShutdownCloseCapability; }>; 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/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..a68b9d16a6 100644 --- a/packages/daemon/src/__tests__/support/platform-services-fixture.ts +++ b/packages/daemon/src/__tests__/support/platform-services-fixture.ts @@ -6,6 +6,8 @@ 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'; +const assessShutdownGenerationFixture = async () => 'not-applicable' as const; + /** * 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 @@ -26,6 +28,7 @@ export function daemonPlatformServicesFixture( }), deviceBootObservation: Object.freeze({ observeBootTimeMs: observeBootTimeMsFixture, + assessShutdownGeneration: assessShutdownGenerationFixture, }), ensureLocalDeviceReady: ensureLocalDeviceReadyFixture, resolveRequestedOpenSurface: resolveRequestedOpenSurfaceFixture, 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..56e1d47ee6 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, + DeviceShutdownGenerationService, +} from '@agent-device/contracts/device-boot'; import type { SessionSurface } from '@agent-device/contracts/session'; import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -19,7 +22,7 @@ export type EnsureLocalDeviceReady = (device: DeviceInfo, signal: AbortSignal) = */ export type DaemonPlatformServices = Readonly<{ appleSessionObservation: AppleSessionObservation; - deviceBootObservation: DeviceBootObservationService; + deviceBootObservation: DeviceBootObservationService & DeviceShutdownGenerationService; 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-bounded-claim-recovery.test.ts b/packages/daemon/src/server/__tests__/request-router-bounded-claim-recovery.test.ts index b5440b72fc..9ce74f8973 100644 --- a/packages/daemon/src/server/__tests__/request-router-bounded-claim-recovery.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-bounded-claim-recovery.test.ts @@ -143,6 +143,7 @@ function route( ? {} : { deviceBootObservation: { + assessShutdownGeneration: async () => 'not-applicable' as const, observeBootTimeMs: async () => ({ observed: true as const, bootedAtMs: options.bootedAtMs!, 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..db0ca8fda1 --- /dev/null +++ b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-external-reboot.test.ts @@ -0,0 +1,536 @@ +// #4585: plain `close` owes a stop to the boot its own `open` caused, not to whichever boot the +// device is running now. Routed through the session command handler, so claim acquisition, renewal, +// boot stamping and close teardown all run against real claim files. +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 { fakeCreateCommandSurface } from '../../../../__tests__/support/command-surface-fake.ts'; +import { daemonPlatformServicesFixture } from '../../../../__tests__/support/platform-services-fixture.ts'; +import { + handleSessionCommands, + mockEnsureReadyRuntime, + mockShutdownTargetRuntime, +} from '../../../../__tests__/support/handlers/session-command-harness.ts'; +import { + applicationLifecycleRuntimeFixture, + type LifecycleOperationsLoader, +} from '../../../../__tests__/support/application-lifecycle-runtime-fixture.ts'; +import { + acquireDeviceClaim, + clearDeviceClaim, + inspectDeviceClaims, +} from '@agent-device/daemon-contracts/device-claims'; +import type { DeviceBootObservation } from '@agent-device/contracts/device-boot'; +import type { DaemonPlatformServices } from '../../../../core/platform-services.ts'; +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(); + +/** The clock every case runs on, so a boot epoch is a named instant rather than an elapsed guess. */ +const CLOCK_START_MS = Date.UTC(2026, 0, 15, 10, 0, 0); +/** How far after the cold open a case places the emulator's next boot, and how long it has been up. */ +const LATER_BOOT_DELAY_MS = 60_000; +const LATER_BOOT_UPTIME_MS = 45_000; +/** How long before a case's own boot a prior session's claim was taken. */ +const PRIOR_CLAIM_GAP_MS = 30 * 60_000; + +const SESSION = 'implicit-shutdown-session'; +const OWN_GENERATION = { pid: 1234, startTime: 'original' }; +const NEXT_GENERATION = { pid: 1234, startTime: 'replacement' }; + +/** The boot epoch of an emulator restarted outside the session: past, and later than the open's. */ +const LATER_BOOT_MS = CLOCK_START_MS + LATER_BOOT_DELAY_MS - LATER_BOOT_UPTIME_MS; +const REBOOTED: DeviceBootObservation = { observed: true, bootedAtMs: LATER_BOOT_MS }; + +/** 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_35', + kind: 'emulator', + booted: false, +}; + +/** The same emulator once it runs. An outside reboot keeps this identity and serial. */ +const BOOTED_EMULATOR: DeviceInfo = { + platform: 'android', + id: 'emulator-5554', + name: 'Pixel_9_API_35', + kind: 'emulator', + booted: true, +}; + +function createRoutedSession( + observeBootTimeMs?: (device: DeviceInfo) => Promise, +) { + const stateDir = mkdtempForTestSync('agent-device-session-close-reboot-'); + const env: NodeJS.ProcessEnv = { + ...process.env, + AGENT_DEVICE_CLAIMS_DIR: path.join(stateDir, 'claims'), + }; + // The platform port supplies the emulator's observed boot time. + const boot: { current: DeviceBootObservation } = { + current: { observed: false, reason: 'unobserved' }, + }; + let bootAsks = 0; + const generation: { current: typeof OWN_GENERATION | undefined } = { current: OWN_GENERATION }; + let generationAsks = 0; + const platformServices = daemonPlatformServicesFixture({ + deviceBootObservation: { + assessShutdownGeneration: async (_device, expected) => { + if (!expected) return 'unobserved'; + generationAsks += 1; + if (observeBootTimeMs) throw new Error('unavailable'); + const current = boot.current === REBOOTED ? NEXT_GENERATION : generation.current; + return !current + ? 'unobserved' + : current.pid === expected.pid && current.startTime === expected.startTime + ? 'same' + : 'changed'; + }, + observeBootTimeMs: async (device: DeviceInfo): Promise => { + bootAsks += 1; + return (await observeBootTimeMs?.(device)) ?? boot.current; + }, + }, + }) as unknown as DaemonPlatformServices; + 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; + beforeAppOpen?(): void; + deviceShutdownDenied?: boolean; + omitLaunchIdentity?: boolean; + beforeFinalization?(): void; + }) { + if (command.selectsDevice) { + vi.mocked(resolveTargetDevice).mockResolvedValue(STOPPED_AVD); + mockEnsureReadyRuntime.mockImplementation(async (input) => { + if (!command.omitLaunchIdentity) input.onAndroidEmulatorLaunchIdentity?.(OWN_GENERATION); + return BOOTED_EMULATOR; + }); + } + // Plain close is recorded at the lifecycle port the close dispatches, and the leaf + // `shutdownTarget` stays the harness's own, so `mockShutdownTargetRuntime` counts the stop the + // platform was actually asked to perform. + const finalizeAsks: Array> = []; + const loader: LifecycleOperationsLoader = async (device, signal, shutdownTarget) => { + const operations = await applicationLifecycleRuntimeFixture(device, signal, shutdownTarget); + const finalizeApplicationClose = operations.finalizeApplicationClose; + return Object.freeze({ + ...operations, + openApplication: async (input) => { + command.beforeAppOpen?.(); + return await operations.openApplication(input); + }, + finalizeApplicationClose: async (input) => { + finalizeAsks.push({ + shutdownTarget: input.shutdownTarget === true, + retainRunner: input.retainRunner === true, + }); + command.beforeFinalization?.(); + if (input.verifyAndroidShutdown) { + const result = await input.verifyAndroidShutdown(); + if (result !== 'same') return { androidShutdownRetained: result }; + } + return await finalizeApplicationClose(input); + }, + }); + }; + const response = await handleSessionCommands({ + host: createTestHostEnvironment({ env }), + createCommandSurface: fakeCreateCommandSurface, + platformServices, + 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 }; + } + + function sessionClaim() { + const claim = inspectDeviceClaims({ serial: BOOTED_EMULATOR.id }, env)[0]?.claim; + if (!claim) throw new Error('expected the session to hold its claim'); + return claim; + } + + /** 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; + } + + /** + * Leaves a claim on disk for this device, taken by the same session name, workspace and daemon. + * That is the shape a session inherits when a previous one ended without clearing its claim, and + * the acquisition that follows renews that claim rather than taking a new one. + */ + async function plantPriorClaim() { + const acquired = await acquireDeviceClaim({ + device: BOOTED_EMULATOR, + session: SESSION, + workspace: process.cwd(), + stateDir: sessionStore.resolveDaemonStateDir(), + env, + reconcileOrphanedDeviceClaim: async () => ({ status: 'reconciled' as const }), + }); + if (acquired.status !== 'acquired') throw new Error('expected to plant a prior claim'); + } + + return { + boot, + generation, + generationAsks: () => generationAsks, + /** Asks the boot-observation service answered, so a case can prove the device was not probed. */ + bootAsks: () => bootAsks, + dropSessionClaim: async () => { + const ownership = sessionStore.get(SESSION)?.deviceClaim; + if (!ownership) throw new Error('expected the session to record its claim'); + await clearDeviceClaim(ownership, env); + }, + plantPriorClaim, + run, + sessionClaim, + sessionClaimCount, + sessionStore, + }; +} + +/** + * Opens a stopped AVD through the cold route and leaves the emulator running on the boot this + * session caused. The clock stays fake so a case can name a later boot instead of waiting one out. + */ +async function openBootedByThisSession( + runs: ReturnType, + beforeAppOpen?: () => void, +) { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(CLOCK_START_MS); + const opened = await runs.run({ + name: 'open', + flags: { platform: 'android' }, + selectsDevice: true, + beforeAppOpen, + }); + expect(opened.response?.ok).toBe(true); + const session = runs.sessionStore.get(SESSION); + // The boot fact and the launch identity of the boot it describes are written together, and that + // pair is the only thing close may compare against the running emulator. + expect(session?.bootedByOpen).toBe(true); + expect(session?.androidLaunchIdentity).toEqual(OWN_GENERATION); + return CLOCK_START_MS; +} + +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; +} + +beforeEach(() => { + mockEnsureReadyRuntime.mockReset(); + mockEnsureReadyRuntime.mockResolvedValue(undefined); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +test('plain close leaves an emulator rebooted outside the session running and says why', async () => { + const runs = createRoutedSession(); + await openBootedByThisSession(runs); + + // An outside actor restarts the emulator between two session commands. A reopen then proves the + // session cannot recover the boot fact from what it owns: the reopen boots nothing, and its own + // claim renewal vouches for the running device, so only the observed boot separates the boots. + vi.advanceTimersByTime(LATER_BOOT_DELAY_MS); + runs.boot.current = REBOOTED; + const ref = runs.sessionStore.lookup(SESSION); + expect(ref).toBeDefined(); + runs.sessionStore.updateOpenDevice(ref!, { ...BOOTED_EMULATOR, booted: false }, false); + const reopened = await runs.run({ name: 'open', flags: { platform: 'android' } }); + expect(reopened.response?.ok).toBe(true); + expect(mockEnsureReadyRuntime).toHaveBeenCalledTimes(1); + expect(runs.sessionClaim().updatedAtMs).toBeGreaterThanOrEqual(LATER_BOOT_MS); + // The reopen claims the running device as its own, yet keeps the launch identity of the boot it + // caused. That is what separates this session's boot from the outside one, and no claim timestamp + // can do it: renewal restamps `updatedAtMs` to vouch for the reboot, and `createdAtMs` can + // predate either. + expect(runs.sessionStore.get(SESSION)?.androidLaunchIdentity).toEqual(OWN_GENERATION); + // Open and reopen settle their claims from the record alone, so neither has probed the device. + expect(runs.bootAsks()).toBe(0); + + const closed = await runs.run({ name: 'close' }); + + expect(closed.response?.ok).toBe(true); + expect(closed.finalizeAsks).toEqual([{ shutdownTarget: false, retainRunner: false }]); + expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); + expect(closeWarningMessages(closed.response!)).toEqual([ + "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 (closed.response?.ok) expect(closed.response.data).not.toHaveProperty('shutdown'); + // Close asks the device once, and only once: the implicit stop's own decision. + expect(runs.generationAsks()).toBe(1); +}, 30_000); + +test('plain close leaves an emulator rebooted outside the session running without any reopen', async () => { + const runs = createRoutedSession(); + await openBootedByThisSession(runs); + + runs.boot.current = REBOOTED; + const closed = await runs.run({ name: 'close' }); + + expect(closed.response?.ok).toBe(true); + expect(closed.finalizeAsks).toEqual([{ shutdownTarget: false, retainRunner: false }]); + expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); + expect(closeWarningMessages(closed.response!)).toHaveLength(1); +}, 30_000); + +test('plain close keeps a reboot that raced the first application launch', async () => { + const runs = createRoutedSession(); + await openBootedByThisSession(runs, () => { + vi.advanceTimersByTime(LATER_BOOT_DELAY_MS); + runs.boot.current = REBOOTED; + }); + + const closed = await runs.run({ name: 'close' }); + + expect(closed.response?.ok).toBe(true); + expect(closed.finalizeAsks[0]?.shutdownTarget).toBe(false); + expect(closeWarningMessages(closed.response!)).toHaveLength(1); +}); + +test('plain close stops the emulator this session booted while it still runs that boot', async () => { + const runs = createRoutedSession(); + const ownBootMs = await openBootedByThisSession(runs); + expect(ownBootMs).toBe(CLOCK_START_MS); + + // Same case except the boot the device reports: the one this session caused. + runs.boot.current = { observed: true, bootedAtMs: ownBootMs }; + const closed = await runs.run({ name: 'close' }); + + expect(closed.response?.ok).toBe(true); + expect(closed.finalizeAsks).toEqual([{ shutdownTarget: true, retainRunner: false }]); + expect(mockShutdownTargetRuntime).toHaveBeenCalledTimes(1); + expect(closeWarningMessages(closed.response!)).toBeUndefined(); +}, 30_000); + +test('plain close retains the emulator when its host generation is unavailable', async () => { + const runs = createRoutedSession(); + await openBootedByThisSession(runs); + + runs.generation.current = undefined; + const closed = await runs.run({ name: 'close' }); + + expect(closed.response?.ok).toBe(true); + expect(closed.finalizeAsks).toEqual([{ shutdownTarget: false, retainRunner: false }]); + expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); + expect(closeWarningMessages(closed.response!)).toHaveLength(1); +}, 30_000); + +test('plain close stops the emulator its own open booted even when the claim long predates that boot', async () => { + const runs = createRoutedSession(); + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(CLOCK_START_MS); + // A previous session of this same name, workspace and daemon left its claim behind, so this + // session's open renews that claim instead of taking a new one. Its creation time belongs to the + // earlier session and describes nothing about the boot about to happen. + await runs.plantPriorClaim(); + vi.advanceTimersByTime(PRIOR_CLAIM_GAP_MS); + + const ownBootMs = CLOCK_START_MS + PRIOR_CLAIM_GAP_MS; + const opened = await runs.run({ + name: 'open', + flags: { platform: 'android' }, + selectsDevice: true, + }); + expect(opened.response?.ok).toBe(true); + expect(runs.sessionStore.get(SESSION)?.bootedByOpen).toBe(true); + expect(runs.sessionClaim().createdAtMs).toBe(CLOCK_START_MS); + + // The emulator reports the boot THIS open caused, which is what an uptime probe answers. + runs.boot.current = { observed: true, bootedAtMs: ownBootMs }; + const closed = await runs.run({ name: 'close' }); + + // The session still owns the boot the device is running, so it still owes the stop. + expect(closed.response?.ok).toBe(true); + expect(closed.finalizeAsks).toEqual([{ shutdownTarget: true, retainRunner: false }]); + expect(mockShutdownTargetRuntime).toHaveBeenCalledTimes(1); + expect(closeWarningMessages(closed.response!)).toBeUndefined(); +}, 30_000); + +test('close --shutdown stops a rebooted emulator and asks the device nothing', async () => { + const runs = createRoutedSession(); + await openBootedByThisSession(runs); + runs.boot.current = REBOOTED; + const asksAfterOpen = runs.generationAsks(); + + const closed = await runs.run({ name: 'close', flags: { shutdown: true } }); + + expect(closed.response?.ok).toBe(true); + expect(closed.finalizeAsks).toEqual([{ shutdownTarget: true, retainRunner: false }]); + expect(mockShutdownTargetRuntime).toHaveBeenCalledTimes(1); + expect(runs.generationAsks()).toBe(asksAfterOpen); + expect(closeWarningMessages(closed.response!)).toBeUndefined(); +}, 30_000); + +test('a failed generation probe keeps the emulator running', async () => { + const runs = createRoutedSession((device) => + Promise.reject(new Error(`adb is gone: ${device.id}`)), + ); + await openBootedByThisSession(runs); + + const closed = await runs.run({ name: 'close' }); + + expect(closed.response?.ok).toBe(true); + expect(closed.finalizeAsks).toEqual([{ shutdownTarget: false, retainRunner: false }]); + expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); + expect(closeWarningMessages(closed.response!)).toHaveLength(1); +}, 30_000); + +test('close reaches no device or session step when it asks the boot observation', async () => { + const runs = createRoutedSession(); + await openBootedByThisSession(runs); + runs.boot.current = REBOOTED; + + const closed = await runs.run({ name: 'close' }); + + // The probe is the close's first step and the only one it adds: the lifecycle ask sees the + // decision it produced, and the session is retired as any successful close retires it. + expect(closed.finalizeAsks).toEqual([{ shutdownTarget: false, retainRunner: false }]); + expect(runs.generationAsks()).toBe(1); + expect(runs.sessionStore.get(SESSION)).toBeUndefined(); + expect(runs.sessionClaimCount()).toBe(0); +}, 30_000); + +test('a policy refusal stays the reported reason when the emulator was rebooted as well', async () => { + const runs = createRoutedSession(); + await openBootedByThisSession(runs); + runs.boot.current = REBOOTED; + const asksBeforeClose = runs.generationAsks(); + + const closed = await runs.run({ name: 'close', deviceShutdownDenied: true }); + + expect(closed.response?.ok).toBe(true); + expect(closed.finalizeAsks).toEqual([{ 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(runs.generationAsks()).toBe(asksBeforeClose); +}, 30_000); + +test('a lost claim stays the reported reason when the emulator was rebooted as well', async () => { + const runs = createRoutedSession(); + await openBootedByThisSession(runs); + runs.boot.current = REBOOTED; + await runs.dropSessionClaim(); + const asksBeforeClose = runs.generationAsks(); + + const closed = await runs.run({ name: 'close' }); + + expect(closed.response?.ok).toBe(true); + expect(closed.finalizeAsks).toEqual([{ 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.", + ]); + // Losing the claim settles the stop without reaching the device, so the reboot adds nothing. + expect(runs.generationAsks()).toBe(asksBeforeClose); +}, 30_000); + +test('Quick Boot retains the replacement with the same serial and restored guest uptime', async () => { + const runs = createRoutedSession(); + await openBootedByThisSession(runs); + runs.boot.current = { observed: true, bootedAtMs: CLOCK_START_MS - 80_000 }; + runs.generation.current = NEXT_GENERATION; + const closed = await runs.run({ name: 'close' }); + expect(closed.finalizeAsks[0]?.shutdownTarget).toBe(false); + expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); + expect(closeWarningMessages(closed.response!)).toHaveLength(1); +}); + +test('missing launch identity does not acquire ownership from a later observation', 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[0]?.shutdownTarget).toBe(false); + expect(runs.generationAsks()).toBe(0); + expect(closeWarningMessages(closed.response!)).toHaveLength(1); +}); + +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(); +}); + +test.each(['changed', 'unobserved'] as const)( + 'close reports %s when generation changes during cleanup', + async (outcome) => { + const runs = createRoutedSession(); + await openBootedByThisSession(runs); + const closed = await runs.run({ + name: 'close', + beforeFinalization: () => { + runs.generation.current = outcome === 'changed' ? NEXT_GENERATION : undefined; + }, + }); + expect(closed.response?.ok).toBe(true); + expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); + expect(closeWarningMessages(closed.response!)).toEqual([ + outcome === 'changed' + ? "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." + : "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.", + ]); + if (closed.response?.ok) expect(closed.response.data).not.toHaveProperty('shutdown'); + }, +); 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..37b42bdd5f --- /dev/null +++ b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-implicit-shutdown.test.ts @@ -0,0 +1,447 @@ +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'; + +bindTestCommandHost(); + +const { + AppError, + handleSessionCommands, + makeSession, + makeSessionStore, + mockShutdownTargetRuntime, + noopInvoke, + path, + resetSessionCloseShutdownMocks, +} = sessionCloseShutdownFixture; + +beforeEach(resetSessionCloseShutdownMocks); + +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, +}; + +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; + session.androidLaunchIdentity = { pid: 42, startTime: 'start' }; + 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' }), + assessShutdownGeneration: async () => 'same' as const, + }, + }), + ...(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: '', + }); + } + }, +); + +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..b176440c8d 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,9 @@ 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 { DeviceShutdownGenerationService } 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 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 +30,89 @@ 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; + /** + * #4585: the close owned stopping the device its own `open` booted, but the device has been + * through a boot this session never described since that open, so the running device is not the + * one this session started and the implicit stop is withheld. The close itself succeeded. + */ + implicitShutdownDeviceRebooted: boolean; + implicitShutdownGenerationUnobserved: boolean; +}>; + export type SessionCloseTeardownResult = Readonly<{ platformCloseError: unknown; retainExecutionHost: boolean; saveScriptOutcome: OrdinaryCloseScript; shutdownResult?: TargetShutdownResult; shutdownPrepared: 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: a stop this session owes its own open is a stop owed to the boot that open caused, so the + * the Android host generation is checked only once the stop is otherwise owed. An + * explicit `--shutdown` commands the stop whatever the device says, and a lost claim or a policy + * refusal has already decided it without reaching the device. Each reason is reported as itself and + * in this order: what settled the stop first is the only reason close can honestly give. + */ +async function decideDeviceStopOnClose(params: { + env: EnvMap; + explicitShutdown: boolean; + session: SessionState; + localFamily: boolean; + deviceShutdownDenied: boolean; + observeDeviceBoot: DeviceShutdownGenerationService; +}): 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; + const generation = + implicitShutdown && !implicitShutdownDeniedByPolicy && claimRenewal?.status === 'renewed' + ? await params.observeDeviceBoot + .assessShutdownGeneration(session.device, session.androidLaunchIdentity) + .catch(() => 'unobserved' as const) + : 'not-applicable'; + const implicitShutdownDeviceRebooted = generation === 'changed'; + const implicitShutdownGenerationUnobserved = generation === 'unobserved'; + return { + shutdownRequested: + params.explicitShutdown || + (implicitShutdown && + !implicitShutdownDeniedByPolicy && + !implicitShutdownDeviceRebooted && + !implicitShutdownGenerationUnobserved && + claimRenewal?.status === 'renewed'), + implicitShutdownDeniedByPolicy, + implicitShutdownClaimLost, + implicitShutdownDeviceRebooted, + implicitShutdownGenerationUnobserved, + }; +} /** 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 +130,8 @@ export async function runSessionCloseTeardown(params: { platformCloseError: unknown; }): OrdinaryCloseScript; platformResourceCleanup: PlatformResourceCleanup; + deviceShutdownDenied?: boolean; + observeDeviceBoot: DeviceShutdownGenerationService; }): Promise { const { req, @@ -80,9 +158,20 @@ 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, + observeDeviceBoot: params.observeDeviceBoot, + }); + const { shutdownRequested, ...stopReasons } = deviceStop; + const expectedAndroidLaunchIdentity = session.androidLaunchIdentity; const retainExecutionHost = params.platformResourceCleanup.retainExecutionHostAfterClose({ device: session.device, - shutdownRequested: req.flags?.shutdown === true, + shutdownRequested, hasScreenRecording: Boolean(session.screenRecording), leaseWillEnd: Boolean(session.lease) && @@ -122,7 +211,19 @@ 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: shutdownRequested && lifecycle.owner.kind === 'local-family', + ...(shutdownRequested && req.flags?.shutdown !== true + ? { + verifyAndroidShutdown: async () => { + const generation = await params.observeDeviceBoot + .assessShutdownGeneration(session.device, expectedAndroidLaunchIdentity) + .catch(() => 'unobserved' as const); + return generation === 'same' || generation === 'changed' + ? generation + : ('unobserved' as const); + }, + } + : {}), })) ?? {}, ); const saveScriptOutcome = repairArmed @@ -137,6 +238,13 @@ export async function runSessionCloseTeardown(params: { saveScriptOutcome, shutdownResult: finalization?.shutdown, shutdownPrepared: finalization !== undefined, + ...stopReasons, + implicitShutdownDeviceRebooted: + stopReasons.implicitShutdownDeviceRebooted || + finalization?.androidShutdownRetained === 'changed', + implicitShutdownGenerationUnobserved: + stopReasons.implicitShutdownGenerationUnobserved || + finalization?.androidShutdownRetained === 'unobserved', }; } 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..6881f713dd 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 { DeviceShutdownGenerationService } 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, + observeDeviceBoot: params.platformServices.deviceBootObservation, + deviceShutdownDenied: params.deviceShutdownDenied, }), ); if (closed.kind === 'response') return closed.response; @@ -364,6 +369,10 @@ export async function handleSessionCloseCommands( requestedSaveScript: Boolean(req.flags?.saveScript), shutdownResult: closed.shutdownResult, providerData: closed.providerData, + implicitShutdownDeniedByPolicy: closed.implicitShutdownDeniedByPolicy, + implicitShutdownClaimLost: closed.implicitShutdownClaimLost, + implicitShutdownDeviceRebooted: closed.implicitShutdownDeviceRebooted, + implicitShutdownGenerationUnobserved: closed.implicitShutdownGenerationUnobserved, }); return remoteCloseScriptDelivery(response, closed.remoteScript); } @@ -393,6 +402,12 @@ 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. */ + implicitShutdownDeviceRebooted: boolean; + implicitShutdownGenerationUnobserved: boolean; }; // Everything between a settled repair decision and a success response: @@ -413,6 +428,9 @@ async function runCloseTeardownAndRelease(params: { clearRuntimeHints?: RuntimeHintClearOperation; repairArmed: boolean; platformResourceCleanup: PlatformResourceCleanup; + deviceShutdownDenied?: boolean; + /** Boot observation for the implicit stop's #4585 check, forwarded to the teardown. */ + observeDeviceBoot: DeviceShutdownGenerationService; }): Promise { const { req, @@ -432,7 +450,12 @@ async function runCloseTeardownAndRelease(params: { saveScriptOutcome, shutdownPrepared, shutdownResult, + implicitShutdownDeniedByPolicy, + implicitShutdownClaimLost, + implicitShutdownDeviceRebooted, + implicitShutdownGenerationUnobserved, } = await runSessionCloseTeardown({ + env: params.env, leaseRegistry, req, ref, @@ -445,6 +468,8 @@ async function runCloseTeardownAndRelease(params: { dispatchTargetedPlatformClose, finalizeOrdinaryCloseScript, platformResourceCleanup: params.platformResourceCleanup, + deviceShutdownDenied: params.deviceShutdownDenied, + observeDeviceBoot: params.observeDeviceBoot, }); let session = sessionStore.requireCurrent(ref); // Each cleanup report is built where the session's fate is decided, so its diagnostic and hint @@ -491,6 +516,10 @@ async function runCloseTeardownAndRelease(params: { providerData: leaseRelease.providerData, shutdownResult: leaseRelease.shutdownResult ?? shutdownResult, remoteScript: saveScriptOutcome.remote, + implicitShutdownDeniedByPolicy, + implicitShutdownClaimLost, + implicitShutdownDeviceRebooted, + implicitShutdownGenerationUnobserved, }; } @@ -500,8 +529,22 @@ function buildCloseSuccessResponse(params: { requestedSaveScript: boolean; shutdownResult: TargetShutdownResult | undefined; providerData: Record | undefined; + implicitShutdownDeniedByPolicy: boolean; + implicitShutdownClaimLost: boolean; + implicitShutdownDeviceRebooted: boolean; + implicitShutdownGenerationUnobserved: boolean; }): DaemonResponse { - const { session, repair, requestedSaveScript, shutdownResult, providerData } = params; + const { + session, + repair, + requestedSaveScript, + shutdownResult, + providerData, + implicitShutdownDeniedByPolicy, + implicitShutdownClaimLost, + implicitShutdownDeviceRebooted, + implicitShutdownGenerationUnobserved, + } = params; if (repair.aborted && requestedSaveScript) { return { ok: false, @@ -519,19 +562,42 @@ 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 a stop owed to the boot its own open caused. The device + // has since been through a boot this session never described, so stopping it now would stop + // someone else's device. Say which device close left running, and why. + if (implicitShutdownDeviceRebooted) { + 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 (implicitShutdownGenerationUnobserved) { + appendResponseWarning( + data, + "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.", + ); + } + 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-generation.test.ts b/packages/platform-android/src/device-boot-generation.test.ts new file mode 100644 index 0000000000..14e6a22cc9 --- /dev/null +++ b/packages/platform-android/src/device-boot-generation.test.ts @@ -0,0 +1,66 @@ +import { beforeEach, expect, test, vi } from 'vitest'; +import type { DeviceInfo } from '@agent-device/kernel/device'; + +const mocks = vi.hoisted(() => ({ + runCmd: vi.fn(), + readProcessIdentityFacts: vi.fn(), +})); +vi.mock('@agent-device/host-kit/command', () => ({ runCmd: mocks.runCmd })); +vi.mock('@agent-device/host-kit/process', () => ({ + readProcessIdentityFacts: mocks.readProcessIdentityFacts, + hostPlatform: () => 'darwin', +})); + +import { observeAndroidEmulatorGeneration } from './device-boot.ts'; + +const device: DeviceInfo = { + platform: 'android', + kind: 'emulator', + id: 'emulator-5558', + name: 'Pixel', +}; + +beforeEach(() => { + vi.resetAllMocks(); + // The real macOS shape for an emulator listening on IPv4 and IPv6: one process, two sockets. + mocks.runCmd.mockResolvedValue({ exitCode: 0, stdout: 'p42\nf31\nf32\n', stderr: '' }); + mocks.readProcessIdentityFacts.mockResolvedValue({ startTime: 'start', zombie: false }); +}); + +test('observes only the listener on the admitted console port', async () => { + expect(await observeAndroidEmulatorGeneration(device)).toEqual({ pid: 42, startTime: 'start' }); + expect(mocks.runCmd).toHaveBeenCalledWith( + 'lsof', + ['-nP', '-iTCP:5558', '-sTCP:LISTEN', '-Fp'], + expect.anything(), + ); +}); + +test('ambiguous listeners and missing process identity remain unknown', async () => { + mocks.runCmd.mockResolvedValueOnce({ exitCode: 0, stdout: 'p42\nf31\np43\nf32\n', stderr: '' }); + expect(await observeAndroidEmulatorGeneration(device)).toBeUndefined(); + expect(mocks.readProcessIdentityFacts).not.toHaveBeenCalled(); + mocks.readProcessIdentityFacts.mockResolvedValueOnce({ startTime: null, zombie: false }); + expect(await observeAndroidEmulatorGeneration(device)).toBeUndefined(); +}); + +test('one process with a single listening socket is observed', async () => { + mocks.runCmd.mockResolvedValueOnce({ exitCode: 0, stdout: 'p42\nf31\n', stderr: '' }); + expect(await observeAndroidEmulatorGeneration(device)).toEqual({ pid: 42, startTime: 'start' }); +}); + +test('no listener or a malformed pid remains unknown', async () => { + mocks.runCmd.mockResolvedValueOnce({ exitCode: 0, stdout: '', stderr: '' }); + expect(await observeAndroidEmulatorGeneration(device)).toBeUndefined(); + mocks.runCmd.mockResolvedValueOnce({ exitCode: 0, stdout: 'p0\nf31\n', stderr: '' }); + expect(await observeAndroidEmulatorGeneration(device)).toBeUndefined(); + expect(mocks.readProcessIdentityFacts).not.toHaveBeenCalled(); +}); + +test('physical and malformed targets do not inspect host processes', async () => { + expect(await observeAndroidEmulatorGeneration({ ...device, kind: 'device' })).toBeUndefined(); + expect( + await observeAndroidEmulatorGeneration({ ...device, id: 'emulator-5558:other' }), + ).toBeUndefined(); + expect(mocks.runCmd).not.toHaveBeenCalled(); +}); diff --git a/packages/platform-android/src/device-boot.ts b/packages/platform-android/src/device-boot.ts index 81c8b7c642..4673b4e210 100644 --- a/packages/platform-android/src/device-boot.ts +++ b/packages/platform-android/src/device-boot.ts @@ -1,6 +1,52 @@ import type { DeviceBootObservation } from '@agent-device/contracts/device-boot'; +import type { AndroidEmulatorLaunchIdentity } from '@agent-device/contracts/device-readiness-runtime'; import type { DeviceInfo } from '@agent-device/kernel/device'; +/** Observe the process listening on the ADB emulator console port without contacting it. */ +export async function observeAndroidEmulatorGeneration( + device: DeviceInfo, +): Promise { + if (device.platform !== 'android' || device.kind !== 'emulator') return undefined; + const match = /^emulator-(\d+)$/.exec(device.id); + const port = Number(match?.[1]); + if (!match || !Number.isInteger(port) || port < 1 || port > 65535) return undefined; + try { + const { hostPlatform, readProcessIdentityFacts } = + await import('@agent-device/host-kit/process'); + if (hostPlatform() !== 'darwin' && hostPlatform() !== 'linux') return undefined; + const { runCmd } = await import('@agent-device/host-kit/command'); + const result = await runCmd('lsof', ['-nP', `-iTCP:${port}`, '-sTCP:LISTEN', '-Fp'], { + allowFailure: true, + timeoutMs: BOOT_PROBE_TIMEOUT_MS, + }); + if (result.exitCode !== 0) return undefined; + const pid = soleListenerPid(result.stdout); + if (pid === undefined) return undefined; + const facts = await readProcessIdentityFacts(pid, BOOT_PROBE_TIMEOUT_MS); + if (!facts.startTime || facts.zombie !== false) return undefined; + return { pid, startTime: facts.startTime }; + } catch { + return undefined; + } +} + +/** + * `lsof -F p` prints one `p` line per process and one `f` line per listening socket, so an + * emulator that listens on IPv4 and IPv6 prints `p`, `f`, `f`. The listener counts + * only when every socket belongs to one process. + */ +function soleListenerPid(stdout: string): number | undefined { + const pids = new Set(); + for (const line of stdout.split(/\r?\n/)) { + if (line.startsWith('p')) pids.add(line.slice(1)); + } + if (pids.size !== 1) return undefined; + const [value] = pids; + if (!/^[1-9]\d*$/.test(value ?? '')) return undefined; + const pid = Number(value); + return Number.isSafeInteger(pid) ? pid : undefined; +} + /** The probe answers in tens of milliseconds and must not become the reason an `open` waits. */ const BOOT_PROBE_TIMEOUT_MS = 3_000; diff --git a/packages/platform-android/src/lifecycle.test.ts b/packages/platform-android/src/lifecycle.test.ts index 8ec48f2a55..af6347dd3d 100644 --- a/packages/platform-android/src/lifecycle.test.ts +++ b/packages/platform-android/src/lifecycle.test.ts @@ -58,7 +58,7 @@ function createLifecycle( device: DeviceInfo, input: Readonly<{ stateDir: string; shutdownTarget: boolean; signal: AbortSignal }>, ) => Promise; - shutdownTarget?: () => Promise; + shutdownTarget?: (...args: unknown[]) => Promise; close?: Interactor['close']; }> = {}, ): LifecycleFixture { @@ -95,7 +95,8 @@ function createLifecycle( }, deviceShutdown: { android: { - shutdownTarget: async () => await (params.shutdownTarget?.() ?? Promise.resolve(undefined)), + shutdownTarget: async (...args: unknown[]) => + await (params.shutdownTarget?.(...args) ?? Promise.resolve(undefined)), }, }, androidApplications: { @@ -478,6 +479,27 @@ test('close --shutdown restores the keyboard and only then kills the emulator (# expect(result.shutdown).toMatchObject({ success: true }); }); +test('finalization forwards verification after restoring IME and returns retention', async () => { + const events: string[] = []; + const verify = async () => 'changed' as const; + const { lifecycle } = createLifecycle({ + restoreTestIme: async () => { + events.push('restore'); + }, + shutdownTarget: async (_device, _signal, received) => { + events.push('shutdown'); + expect(received).toBe(verify); + return { retained: await (received as typeof verify)() }; + }, + }); + await expect( + lifecycle.finalizeApplicationClose( + finalizationInput({ shutdownTarget: true, verifyAndroidShutdown: verify }), + ), + ).resolves.toEqual({ androidShutdownRetained: 'changed' }); + expect(events).toEqual(['restore', 'shutdown']); +}); + test('close --shutdown is ignored for a physical Android device', async () => { const shutdownTarget = vi.fn(async () => ({ success: true, diff --git a/packages/platform-android/src/lifecycle.ts b/packages/platform-android/src/lifecycle.ts index 029288658a..2bc41bdfd6 100644 --- a/packages/platform-android/src/lifecycle.ts +++ b/packages/platform-android/src/lifecycle.ts @@ -92,9 +92,19 @@ export function bindAndroidApplicationLifecycle( }); const shutdown = input.shutdownTarget && device.kind === 'emulator' - ? await host.deviceShutdown.android.shutdownTarget(device, signal) + ? input.verifyAndroidShutdown + ? await host.deviceShutdown.android.shutdownTarget( + device, + signal, + input.verifyAndroidShutdown, + ) + : await host.deviceShutdown.android.shutdownTarget(device, signal) : undefined; - return shutdown === undefined ? {} : { shutdown }; + return shutdown === undefined + ? {} + : 'retained' in shutdown + ? { androidShutdownRetained: shutdown.retained } + : { shutdown }; }, prepareAppleRunner: unavailable, configureProviderPortReverse: unavailable, 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/platform-android/src/shutdown/runtime.test.ts b/packages/platform-android/src/shutdown/runtime.test.ts index 3baf1973b8..c4d76e10f8 100644 --- a/packages/platform-android/src/shutdown/runtime.test.ts +++ b/packages/platform-android/src/shutdown/runtime.test.ts @@ -68,6 +68,48 @@ test('an active emulator shuts down through the owning adb command', async () => ); }); +test.each(['changed', 'unobserved'] as const)( + 'retains an emulator whose generation is %s after the IME wait', + async (outcome) => { + const device = androidDevice(); + seedRestoreMark(device.id, 0); + const settling = deferred(); + sleep.mockImplementationOnce(() => settling.promise); + let generation: 'same' | 'changed' | 'unobserved' = 'same'; + const verify = vi.fn(async () => generation); + const pending = createAndroidShutdownRuntime({ commands }).shutdownTarget( + device, + signal(), + verify, + ); + await drainMicrotasks(); + expect(verify).not.toHaveBeenCalled(); + generation = outcome; + settling.resolve(); + await expect(pending).resolves.toEqual({ retained: outcome }); + expect(run).not.toHaveBeenCalled(); + }, +); + +test('a verified generation reaches the shutdown command', async () => { + const verify = vi.fn(async () => 'same' as const); + await expect( + createAndroidShutdownRuntime({ commands }).shutdownTarget(androidDevice(), signal(), verify), + ).resolves.toEqual(success()); + expect(verify).toHaveBeenCalledOnce(); + expect(run).toHaveBeenCalledOnce(); +}); + +test('a failed generation verification retains the emulator', async () => { + const verify = async (): Promise<'same'> => { + throw new Error('probe failed'); + }; + await expect( + createAndroidShutdownRuntime({ commands }).shutdownTarget(androidDevice(), signal(), verify), + ).resolves.toEqual({ retained: 'unobserved' }); + expect(run).not.toHaveBeenCalled(); +}); + test('only Android emulators are available', () => { expect(canShutdownTarget(androidDevice())).toBe(true); expect(canShutdownTarget({ ...androidDevice(), kind: 'device' })).toBe(false); diff --git a/packages/platform-android/src/shutdown/runtime.ts b/packages/platform-android/src/shutdown/runtime.ts index bf0a8acf60..06cdc48815 100644 --- a/packages/platform-android/src/shutdown/runtime.ts +++ b/packages/platform-android/src/shutdown/runtime.ts @@ -1,4 +1,8 @@ -import type { DeviceShutdownRuntimeDependencies } from '@agent-device/contracts/device-shutdown-runtime'; +import type { + AndroidShutdownTarget, + AndroidShutdownVerification, + DeviceShutdownRuntimeDependencies, +} from '@agent-device/contracts/device-shutdown-runtime'; import type { TargetShutdownResult } from '@agent-device/contracts/device'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { normalizeError } from '@agent-device/kernel/errors'; @@ -8,7 +12,7 @@ const SHUTDOWN_TIMEOUT_MS = 15_000; export type AndroidShutdownRuntime = Readonly<{ canShutdownTarget(device: DeviceInfo): boolean; - shutdownTarget(device: DeviceInfo, signal: AbortSignal): Promise; + shutdownTarget: AndroidShutdownTarget; }>; export function createAndroidShutdownRuntime( @@ -16,8 +20,17 @@ export function createAndroidShutdownRuntime( ): AndroidShutdownRuntime { return Object.freeze({ canShutdownTarget, - shutdownTarget: async (device, signal) => - await shutdownAndroidTarget(dependencies.commands, device, signal), + shutdownTarget: (async ( + device: DeviceInfo, + signal: AbortSignal, + verify?: AndroidShutdownVerification, + ) => + await shutdownAndroidTarget( + dependencies.commands, + device, + signal, + verify, + )) as AndroidShutdownTarget, }); } @@ -29,7 +42,8 @@ async function shutdownAndroidTarget( commands: DeviceShutdownRuntimeDependencies['commands'], device: DeviceInfo, signal: AbortSignal, -): Promise { + verify?: AndroidShutdownVerification, +): Promise { if (device.booted === false) return stoppedTargetSuccess(); signal.throwIfAborted(); @@ -40,6 +54,11 @@ async function shutdownAndroidTarget( // inside the window, and the timestamp stays for the retry to wait out the remainder. await awaitTestImeFlushWindow(device.id, signal); signal.throwIfAborted(); + if (verify) { + const generation = await verify().catch(() => 'unobserved' as const); + signal.throwIfAborted(); + if (generation !== 'same') return { retained: generation }; + } try { const result = await commands.run( { 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..5a2ce8bbff 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`. If an Android emulator reports a later boot, plain close leaves it 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..7fd0ba3634 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`. If an Android emulator reports a later boot, plain close leaves it 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..a3300dc49c 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). If an Android emulator reports a later boot, plain close leaves it 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..cd62557e9b 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. If a local Android emulator process changed or cannot be verified, plain close leaves it 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. If a local Android emulator process changed or cannot be verified, plain close leaves it 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..cb1db4dd5a 100644 --- a/src/platform-runtime-android-emulator-host.test.ts +++ b/src/platform-runtime-android-emulator-host.test.ts @@ -1,4 +1,10 @@ import { beforeEach, expect, test, vi } from 'vitest'; +import type { DeviceInfo } from '@agent-device/kernel/device'; + +const { observeAndroidEmulatorGeneration } = vi.hoisted(() => ({ + observeAndroidEmulatorGeneration: vi.fn(), +})); +vi.mock('@agent-device/platform-android/device-boot', () => ({ observeAndroidEmulatorGeneration })); const { runCmd, runCmdDetached, runCmdDetachedMonitored, emitDiagnostic } = vi.hoisted(() => ({ runCmd: vi.fn(async (_cmd: string, args: readonly string[]) => ({ @@ -38,6 +44,7 @@ vi.mock('@agent-device/host-kit/process', () => ({ import { createAndroidEmulatorHost } from './platform-runtime-android-emulator-host.ts'; beforeEach(() => { + observeAndroidEmulatorGeneration.mockReset(); runCmd.mockClear(); runCmdDetached.mockClear(); runCmdDetachedMonitored.mockClear(); @@ -45,6 +52,37 @@ 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 only when both serial observations match its recorded identity', async () => { + const host = createAndroidEmulatorHost('linux'); + await host.launch('Pixel_9', true, 90_000); + observeAndroidEmulatorGeneration.mockResolvedValue(launchIdentity); + await expect(host.bindLaunchedEmulator!(4242, emulator)).resolves.toEqual(launchIdentity); + expect(observeAndroidEmulatorGeneration).toHaveBeenCalledTimes(2); + expect(observeAndroidEmulatorGeneration).toHaveBeenCalledWith(emulator); +}); + +test('does not bind an unrelated listener, reused pid, or unavailable observation', async () => { + const host = createAndroidEmulatorHost('linux'); + await host.launch('Pixel_9', true, 90_000); + observeAndroidEmulatorGeneration.mockResolvedValueOnce({ ...launchIdentity, pid: 4243 }); + await expect(host.bindLaunchedEmulator!(4242, emulator)).resolves.toBeUndefined(); + observeAndroidEmulatorGeneration + .mockResolvedValueOnce(launchIdentity) + .mockResolvedValueOnce({ ...launchIdentity, startTime: 'new' }); + await expect(host.bindLaunchedEmulator!(4242, emulator)).resolves.toBeUndefined(); + observeAndroidEmulatorGeneration.mockResolvedValueOnce(undefined); + await expect(host.bindLaunchedEmulator!(4242, emulator)).resolves.toBeUndefined(); + await expect(host.bindLaunchedEmulator!(4243, emulator)).resolves.toBeUndefined(); +}); + 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..52e9b74453 100644 --- a/src/platform-runtime-android-emulator-host.ts +++ b/src/platform-runtime-android-emulator-host.ts @@ -1,4 +1,5 @@ import type { DeviceReadinessRuntimeHost } from '@agent-device/contracts/device-readiness-runtime'; +import { observeAndroidEmulatorGeneration } 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'; @@ -85,6 +86,21 @@ export function createAndroidEmulatorHost( if (frontmostPid !== undefined) returnFocusAfterLaunch(pid, frontmostPid, bootBudgetMs); return pid; }, + bindLaunchedEmulator: async (pid, device) => { + const record = launched.get(pid); + if (!record) return undefined; + try { + const startTime = await record.startTime; + if (!startTime) return undefined; + const first = await observeAndroidEmulatorGeneration(device); + if (first?.pid !== pid || first.startTime !== startTime) return undefined; + const second = await observeAndroidEmulatorGeneration(device); + if (second?.pid !== pid || second.startTime !== startTime) return undefined; + return { pid, startTime }; + } catch { + return undefined; + } + }, terminate, }); } diff --git a/src/platform-runtime-device-boot.test.ts b/src/platform-runtime-device-boot.test.ts index 9e97e858d0..8a0a84f91b 100644 --- a/src/platform-runtime-device-boot.test.ts +++ b/src/platform-runtime-device-boot.test.ts @@ -10,6 +10,9 @@ const mocks = vi.hoisted(() => ({ observed: false, reason: 'unobserved', })), + observeAndroidEmulatorGeneration: vi.fn( + async (): Promise<{ pid: number; startTime: string } | undefined> => undefined, + ), })); vi.mock('@agent-device/platform-apple/simulator-boot', () => mocks); @@ -30,6 +33,36 @@ beforeEach(() => { vi.clearAllMocks(); }); +test('generation is reported only when two serial observations agree', async () => { + const identity = { pid: 42, startTime: 'start' }; + mocks.observeAndroidEmulatorGeneration.mockResolvedValue(identity); + expect(await deviceBootObservation.assessShutdownGeneration(ANDROID_EMULATOR, identity)).toBe( + 'same', + ); + mocks.observeAndroidEmulatorGeneration + .mockResolvedValueOnce(identity) + .mockResolvedValueOnce({ ...identity, startTime: 'replacement' }); + expect(await deviceBootObservation.assessShutdownGeneration(ANDROID_EMULATOR, identity)).toBe( + 'unobserved', + ); + mocks.observeAndroidEmulatorGeneration.mockResolvedValue({ pid: 43, startTime: 'replacement' }); + expect(await deviceBootObservation.assessShutdownGeneration(ANDROID_EMULATOR, identity)).toBe( + 'changed', + ); + expect(await deviceBootObservation.assessShutdownGeneration(LINUX_DEVICE, identity)).toBe( + 'not-applicable', + ); + expect( + await deviceBootObservation.assessShutdownGeneration( + { ...ANDROID_EMULATOR, kind: 'device' }, + identity, + ), + ).toBe('not-applicable'); + expect(await deviceBootObservation.assessShutdownGeneration(ANDROID_EMULATOR, undefined)).toBe( + 'unobserved', + ); +}); + test('an iOS Simulator is answered by the Apple probe alone', async () => { expect(await deviceBootObservation.observeBootTimeMs(IOS_SIMULATOR)).toEqual({ observed: true, diff --git a/src/platform-runtime-device-boot.ts b/src/platform-runtime-device-boot.ts index aa5f32acf9..c9c47efca3 100644 --- a/src/platform-runtime-device-boot.ts +++ b/src/platform-runtime-device-boot.ts @@ -1,6 +1,7 @@ import type { DeviceBootObservation, DeviceBootObservationService, + DeviceShutdownGenerationService, } from '@agent-device/contracts/device-boot'; import { isIosFamily, type DeviceInfo } from '@agent-device/kernel/device'; @@ -9,18 +10,33 @@ import { isIosFamily, type DeviceInfo } from '@agent-device/kernel/device'; * family owns the device. Families that answer no boot question for a leaf report * `unsupported-device`, so a caller never branches on platform to decide what an answer means. */ -export const deviceBootObservation: DeviceBootObservationService = Object.freeze({ - async observeBootTimeMs(device: DeviceInfo): Promise { - if (isIosFamily(device) && device.kind === 'simulator') { - const { observeSimulatorBootTimeMs } = - await import('@agent-device/platform-apple/simulator-boot'); - return await observeSimulatorBootTimeMs(device); - } - if (device.platform === 'android') { - const { observeAndroidBootTimeMs } = +export const deviceBootObservation: DeviceBootObservationService & DeviceShutdownGenerationService = + Object.freeze({ + async assessShutdownGeneration(device, expected) { + if (device.platform !== 'android' || device.kind !== 'emulator') return 'not-applicable'; + if (!expected) return 'unobserved'; + const { observeAndroidEmulatorGeneration } = await import('@agent-device/platform-android/device-boot'); - return await observeAndroidBootTimeMs(device); - } - return { observed: false, reason: 'unsupported-device' }; - }, -}); + const first = await observeAndroidEmulatorGeneration(device); + if (!first) return 'unobserved'; + const second = await observeAndroidEmulatorGeneration(device); + if (!second || second.pid !== first.pid || second.startTime !== first.startTime) + return 'unobserved'; + return first.pid === expected.pid && first.startTime === expected.startTime + ? 'same' + : 'changed'; + }, + async observeBootTimeMs(device: DeviceInfo): Promise { + if (isIosFamily(device) && device.kind === 'simulator') { + const { observeSimulatorBootTimeMs } = + await import('@agent-device/platform-apple/simulator-boot'); + return await observeSimulatorBootTimeMs(device); + } + if (device.platform === 'android') { + const { observeAndroidBootTimeMs } = + await import('@agent-device/platform-android/device-boot'); + return await observeAndroidBootTimeMs(device); + } + return { observed: false, reason: 'unsupported-device' }; + }, + }); diff --git a/src/platform-runtime-device-shutdown-host.test.ts b/src/platform-runtime-device-shutdown-host.test.ts index 11dd688acc..a9fe34f4f0 100644 --- a/src/platform-runtime-device-shutdown-host.test.ts +++ b/src/platform-runtime-device-shutdown-host.test.ts @@ -57,6 +57,20 @@ test('Android shutdown uses the owning package capability', async () => { expect(shutdownLoaders.android).toHaveBeenCalledOnce(); }); +test('Android host forwards the shutdown verifier to the runtime', async () => { + const device: DeviceInfo = { + platform: 'android', + id: 'emulator-5554', + name: 'Pixel', + kind: 'emulator', + booted: true, + }; + const verify = async () => 'same' as const; + const abortSignal = signal(); + await shutdownHost().android.shutdownTarget(device, abortSignal, verify); + expect(androidShutdown).toHaveBeenCalledWith(device, abortSignal, verify); +}); + test('a shutdown guard refuses every shutdown path before the owner runtime loads', async () => { const denied = new Error('policy denies device-shutdown'); const host = shutdownHost(() => { diff --git a/src/platform-runtime-device-shutdown-host.ts b/src/platform-runtime-device-shutdown-host.ts index b85351203a..148d484c64 100644 --- a/src/platform-runtime-device-shutdown-host.ts +++ b/src/platform-runtime-device-shutdown-host.ts @@ -1,5 +1,7 @@ import type { DeviceInfo } from '@agent-device/kernel/device'; import type { + AndroidShutdownTarget, + AndroidShutdownVerification, DeviceShutdownCloseCapability, DeviceShutdownRuntimeDependencies, DeviceShutdownRuntimeHost, @@ -35,10 +37,17 @@ export function createDeviceShutdownRuntimeHost( }, }); const android = Object.freeze({ - shutdownTarget: async (device: DeviceInfo, signal: AbortSignal) => { + shutdownTarget: (async ( + device: DeviceInfo, + signal: AbortSignal, + verify?: AndroidShutdownVerification, + ) => { assertShutdownAllowed(); - return await (await loadAndroid()).shutdownTarget(device, signal); - }, + const runtime = await loadAndroid(); + return verify + ? await runtime.shutdownTarget(device, signal, verify) + : await runtime.shutdownTarget(device, signal); + }) as AndroidShutdownTarget, }); const close: DeviceShutdownCloseCapability = Object.freeze({ canShutdownTarget: async (device) => await canShutdownTarget(device, loadApple, loadAndroid), 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..c1b1c08dc5 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`. When an Android emulator process changed or cannot be verified, plain `close` leaves it running and reports why in `warnings`. The check needs a macOS or Linux host with `lsof`; elsewhere, plain `close` leaves a booted Android emulator running, so use `close --shutdown`. 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..d68cad1c76 100644 --- a/website/docs/docs/sessions.md +++ b/website/docs/docs/sessions.md @@ -118,18 +118,41 @@ 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 +``` + +If a local Android emulator process changed or cannot be verified, +plain `close` leaves it running and reports why in `warnings`. +The check reads the emulator's host process with `lsof`, so it needs a macOS or Linux host with +`lsof` installed. On other hosts, plain `close` leaves a booted Android emulator running and warns; +use `close --shutdown` to stop it. + +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 +252,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 From fa4159853659b5184812dd10481f9250001f66a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 16:31:18 +0100 Subject: [PATCH 02/10] fix(close): read the emulator console listener without blocking calls and retry a slow read Under heavy host load one lsof read took 1.7-4.2 s against a 3 s budget, so the launch identity read as unobserved and close kept an emulator it should stop. Use lsof -b -w -t, give each read 5 s, and retry once when a read times out or fails. A clean no-listener answer is final. --- .../src/device-boot-generation.test.ts | 49 +++++++++----- packages/platform-android/src/device-boot.ts | 67 +++++++++++++------ 2 files changed, 80 insertions(+), 36 deletions(-) diff --git a/packages/platform-android/src/device-boot-generation.test.ts b/packages/platform-android/src/device-boot-generation.test.ts index 14e6a22cc9..152972605b 100644 --- a/packages/platform-android/src/device-boot-generation.test.ts +++ b/packages/platform-android/src/device-boot-generation.test.ts @@ -22,41 +22,58 @@ const device: DeviceInfo = { beforeEach(() => { vi.resetAllMocks(); - // The real macOS shape for an emulator listening on IPv4 and IPv6: one process, two sockets. - mocks.runCmd.mockResolvedValue({ exitCode: 0, stdout: 'p42\nf31\nf32\n', stderr: '' }); + // `lsof -b -w -t` prints the listening process id once, even for IPv4 and IPv6 sockets. + mocks.runCmd.mockResolvedValue({ exitCode: 0, stdout: '42\n', stderr: '' }); mocks.readProcessIdentityFacts.mockResolvedValue({ startTime: 'start', zombie: false }); }); -test('observes only the listener on the admitted console port', async () => { +const slowRead = () => Promise.reject(new Error('lsof timed out after 5000ms')); + +test('observes only the listener on the admitted console port without blocking kernel calls', async () => { expect(await observeAndroidEmulatorGeneration(device)).toEqual({ pid: 42, startTime: 'start' }); expect(mocks.runCmd).toHaveBeenCalledWith( 'lsof', - ['-nP', '-iTCP:5558', '-sTCP:LISTEN', '-Fp'], - expect.anything(), + ['-b', '-w', '-t', '-nP', '-iTCP:5558', '-sTCP:LISTEN'], + expect.objectContaining({ allowFailure: true, timeoutMs: 5_000 }), ); }); -test('ambiguous listeners and missing process identity remain unknown', async () => { - mocks.runCmd.mockResolvedValueOnce({ exitCode: 0, stdout: 'p42\nf31\np43\nf32\n', stderr: '' }); - expect(await observeAndroidEmulatorGeneration(device)).toBeUndefined(); - expect(mocks.readProcessIdentityFacts).not.toHaveBeenCalled(); - mocks.readProcessIdentityFacts.mockResolvedValueOnce({ startTime: null, zombie: false }); - expect(await observeAndroidEmulatorGeneration(device)).toBeUndefined(); +test('a slow listener read is retried once and still observes the identity', async () => { + mocks.runCmd.mockImplementationOnce(slowRead); + expect(await observeAndroidEmulatorGeneration(device)).toEqual({ pid: 42, startTime: 'start' }); + expect(mocks.runCmd).toHaveBeenCalledTimes(2); }); -test('one process with a single listening socket is observed', async () => { - mocks.runCmd.mockResolvedValueOnce({ exitCode: 0, stdout: 'p42\nf31\n', stderr: '' }); +test('a slow process identity read is retried once', async () => { + mocks.readProcessIdentityFacts.mockResolvedValueOnce({ startTime: null, zombie: null }); expect(await observeAndroidEmulatorGeneration(device)).toEqual({ pid: 42, startTime: 'start' }); + expect(mocks.runCmd).toHaveBeenCalledTimes(2); }); -test('no listener or a malformed pid remains unknown', async () => { - mocks.runCmd.mockResolvedValueOnce({ exitCode: 0, stdout: '', stderr: '' }); +test('two slow reads remain unknown', async () => { + mocks.runCmd.mockImplementation(slowRead); expect(await observeAndroidEmulatorGeneration(device)).toBeUndefined(); - mocks.runCmd.mockResolvedValueOnce({ exitCode: 0, stdout: 'p0\nf31\n', stderr: '' }); + expect(mocks.runCmd).toHaveBeenCalledTimes(2); +}); + +test('no listener answers at once without a retry', async () => { + mocks.runCmd.mockResolvedValueOnce({ exitCode: 1, stdout: '', stderr: '' }); expect(await observeAndroidEmulatorGeneration(device)).toBeUndefined(); + expect(mocks.runCmd).toHaveBeenCalledTimes(1); expect(mocks.readProcessIdentityFacts).not.toHaveBeenCalled(); }); +test('ambiguous listeners, a malformed pid and a zombie remain unknown without a retry', async () => { + mocks.runCmd.mockResolvedValueOnce({ exitCode: 0, stdout: '42\n43\n', stderr: '' }); + expect(await observeAndroidEmulatorGeneration(device)).toBeUndefined(); + mocks.runCmd.mockResolvedValueOnce({ exitCode: 0, stdout: '0\n', stderr: '' }); + expect(await observeAndroidEmulatorGeneration(device)).toBeUndefined(); + expect(mocks.readProcessIdentityFacts).not.toHaveBeenCalled(); + mocks.readProcessIdentityFacts.mockResolvedValueOnce({ startTime: 'start', zombie: true }); + expect(await observeAndroidEmulatorGeneration(device)).toBeUndefined(); + expect(mocks.runCmd).toHaveBeenCalledTimes(3); +}); + test('physical and malformed targets do not inspect host processes', async () => { expect(await observeAndroidEmulatorGeneration({ ...device, kind: 'device' })).toBeUndefined(); expect( diff --git a/packages/platform-android/src/device-boot.ts b/packages/platform-android/src/device-boot.ts index 4673b4e210..3425a49a72 100644 --- a/packages/platform-android/src/device-boot.ts +++ b/packages/platform-android/src/device-boot.ts @@ -10,36 +10,56 @@ export async function observeAndroidEmulatorGeneration( const match = /^emulator-(\d+)$/.exec(device.id); const port = Number(match?.[1]); if (!match || !Number.isInteger(port) || port < 1 || port > 65535) return undefined; + for (let attempt = 1; attempt <= LISTENER_PROBE_ATTEMPTS; attempt += 1) { + const reading = await readConsoleListener(port); + if (reading.kind === 'identity') return reading.identity; + if (reading.kind === 'absent') return undefined; + } + return undefined; +} + +type ConsoleListenerReading = + | { kind: 'identity'; identity: AndroidEmulatorLaunchIdentity } + /** The host answered: no single process listens on the port. A retry cannot change it. */ + | { kind: 'absent' } + /** The host did not answer in time or a read failed. A retry can still observe the listener. */ + | { kind: 'unread' }; + +/** + * `lsof -b -w -t` prints only process ids, one per line, skips kernel calls that can block under + * load (`-b`) and suppresses the warnings that `-b` causes (`-w`). It exits 1 with no output when + * nothing listens. An emulator listens on IPv4 and IPv6 from one process, so its id prints once. + */ +async function readConsoleListener(port: number): Promise { try { const { hostPlatform, readProcessIdentityFacts } = await import('@agent-device/host-kit/process'); - if (hostPlatform() !== 'darwin' && hostPlatform() !== 'linux') return undefined; + if (hostPlatform() !== 'darwin' && hostPlatform() !== 'linux') return { kind: 'absent' }; const { runCmd } = await import('@agent-device/host-kit/command'); - const result = await runCmd('lsof', ['-nP', `-iTCP:${port}`, '-sTCP:LISTEN', '-Fp'], { - allowFailure: true, - timeoutMs: BOOT_PROBE_TIMEOUT_MS, - }); - if (result.exitCode !== 0) return undefined; + const result = await runCmd( + 'lsof', + ['-b', '-w', '-t', '-nP', `-iTCP:${port}`, '-sTCP:LISTEN'], + { allowFailure: true, timeoutMs: LISTENER_PROBE_TIMEOUT_MS }, + ); + if (result.exitCode !== 0) return { kind: 'absent' }; const pid = soleListenerPid(result.stdout); - if (pid === undefined) return undefined; - const facts = await readProcessIdentityFacts(pid, BOOT_PROBE_TIMEOUT_MS); - if (!facts.startTime || facts.zombie !== false) return undefined; - return { pid, startTime: facts.startTime }; + if (pid === undefined) return { kind: 'absent' }; + const facts = await readProcessIdentityFacts(pid, LISTENER_PROBE_TIMEOUT_MS); + if (facts.zombie === true) return { kind: 'absent' }; + if (!facts.startTime || facts.zombie !== false) return { kind: 'unread' }; + return { kind: 'identity', identity: { pid, startTime: facts.startTime } }; } catch { - return undefined; + return { kind: 'unread' }; } } -/** - * `lsof -F p` prints one `p` line per process and one `f` line per listening socket, so an - * emulator that listens on IPv4 and IPv6 prints `p`, `f`, `f`. The listener counts - * only when every socket belongs to one process. - */ function soleListenerPid(stdout: string): number | undefined { - const pids = new Set(); - for (const line of stdout.split(/\r?\n/)) { - if (line.startsWith('p')) pids.add(line.slice(1)); - } + const pids = new Set( + stdout + .split(/\r?\n/) + .map((line) => line.trim()) + .filter((line) => line.length > 0), + ); if (pids.size !== 1) return undefined; const [value] = pids; if (!/^[1-9]\d*$/.test(value ?? '')) return undefined; @@ -47,6 +67,13 @@ function soleListenerPid(stdout: string): number | undefined { return Number.isSafeInteger(pid) ? pid : undefined; } +/** + * Under heavy host load one listener read took up to 4.2 s. Each attempt gets 5 s, and a read that + * did not answer is tried once more, so a slow host still binds and verifies the launch identity. + */ +const LISTENER_PROBE_TIMEOUT_MS = 5_000; +const LISTENER_PROBE_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; From 8a61133b1ba268ba2b433bd56a2af283805489ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 17:02:32 +0100 Subject: [PATCH 03/10] fix(close): bound the launch identity probe and keep -b off Linux lsof Open and close each run two agreeing observations, and each observation could take two 5 s reads, so the probe could add 20 s per step. The pair now shares one 10 s deadline that also caps each lsof and ps read. Linux lsof finds sockets through /proc, and -b can stop the port filter matching there, so -b and -w apply only on macOS. --- .../src/device-boot-generation.test.ts | 31 ++++++++++++++- packages/platform-android/src/device-boot.ts | 39 ++++++++++++++----- ...form-runtime-android-emulator-host.test.ts | 14 ++++++- src/platform-runtime-android-emulator-host.ts | 11 ++++-- src/platform-runtime-device-boot.test.ts | 6 +++ src/platform-runtime-device-boot.ts | 8 ++-- 6 files changed, 91 insertions(+), 18 deletions(-) diff --git a/packages/platform-android/src/device-boot-generation.test.ts b/packages/platform-android/src/device-boot-generation.test.ts index 152972605b..adebbcb043 100644 --- a/packages/platform-android/src/device-boot-generation.test.ts +++ b/packages/platform-android/src/device-boot-generation.test.ts @@ -4,11 +4,12 @@ import type { DeviceInfo } from '@agent-device/kernel/device'; const mocks = vi.hoisted(() => ({ runCmd: vi.fn(), readProcessIdentityFacts: vi.fn(), + hostPlatform: vi.fn(), })); vi.mock('@agent-device/host-kit/command', () => ({ runCmd: mocks.runCmd })); vi.mock('@agent-device/host-kit/process', () => ({ readProcessIdentityFacts: mocks.readProcessIdentityFacts, - hostPlatform: () => 'darwin', + hostPlatform: mocks.hostPlatform, })); import { observeAndroidEmulatorGeneration } from './device-boot.ts'; @@ -25,6 +26,7 @@ beforeEach(() => { // `lsof -b -w -t` prints the listening process id once, even for IPv4 and IPv6 sockets. mocks.runCmd.mockResolvedValue({ exitCode: 0, stdout: '42\n', stderr: '' }); mocks.readProcessIdentityFacts.mockResolvedValue({ startTime: 'start', zombie: false }); + mocks.hostPlatform.mockReturnValue('darwin'); }); const slowRead = () => Promise.reject(new Error('lsof timed out after 5000ms')); @@ -81,3 +83,30 @@ test('physical and malformed targets do not inspect host processes', async () => ).toBeUndefined(); expect(mocks.runCmd).not.toHaveBeenCalled(); }); + +test('Linux reads the listener without -b, which can stop the port filter matching through /proc', async () => { + mocks.hostPlatform.mockReturnValue('linux'); + expect(await observeAndroidEmulatorGeneration(device)).toEqual({ pid: 42, startTime: 'start' }); + expect(mocks.runCmd).toHaveBeenCalledWith( + 'lsof', + ['-t', '-nP', '-iTCP:5558', '-sTCP:LISTEN'], + expect.objectContaining({ timeoutMs: 5_000 }), + ); +}); + +test('a shared deadline caps each read and stops reads once it is spent', async () => { + const remaining = [3_000, 0]; + const deadline = { + remainingMs: () => remaining.shift() ?? 0, + elapsedMs: () => 0, + isExpired: () => false, + }; + mocks.runCmd.mockImplementationOnce(slowRead); + expect(await observeAndroidEmulatorGeneration(device, { deadline })).toBeUndefined(); + expect(mocks.runCmd).toHaveBeenCalledTimes(1); + expect(mocks.runCmd).toHaveBeenCalledWith( + 'lsof', + expect.any(Array), + expect.objectContaining({ timeoutMs: 3_000 }), + ); +}); diff --git a/packages/platform-android/src/device-boot.ts b/packages/platform-android/src/device-boot.ts index 3425a49a72..7b9ec7ba07 100644 --- a/packages/platform-android/src/device-boot.ts +++ b/packages/platform-android/src/device-boot.ts @@ -1,17 +1,27 @@ import type { DeviceBootObservation } 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 type { DeadlineClock } from '@agent-device/host-kit/retry'; -/** Observe the process listening on the ADB emulator console port without contacting it. */ +/** + * Observe the process listening on the ADB emulator console port without contacting it. A caller + * that observes more than once passes one deadline, so all reads share one bounded budget. + */ export async function observeAndroidEmulatorGeneration( device: DeviceInfo, + options: { deadline?: DeadlineClock } = {}, ): Promise { if (device.platform !== 'android' || device.kind !== 'emulator') return undefined; const match = /^emulator-(\d+)$/.exec(device.id); const port = Number(match?.[1]); if (!match || !Number.isInteger(port) || port < 1 || port > 65535) return undefined; for (let attempt = 1; attempt <= LISTENER_PROBE_ATTEMPTS; attempt += 1) { - const reading = await readConsoleListener(port); + const budgetMs = Math.min( + LISTENER_PROBE_TIMEOUT_MS, + options.deadline?.remainingMs() ?? LISTENER_PROBE_TIMEOUT_MS, + ); + if (budgetMs <= 0) return undefined; + const reading = await readConsoleListener(port, budgetMs); if (reading.kind === 'identity') return reading.identity; if (reading.kind === 'absent') return undefined; } @@ -26,25 +36,30 @@ type ConsoleListenerReading = | { kind: 'unread' }; /** - * `lsof -b -w -t` prints only process ids, one per line, skips kernel calls that can block under - * load (`-b`) and suppresses the warnings that `-b` causes (`-w`). It exits 1 with no output when - * nothing listens. An emulator listens on IPv4 and IPv6 from one process, so its id prints once. + * `lsof -t` prints only process ids, one per line, and exits 1 with no output when nothing listens. + * An emulator listens on IPv4 and IPv6 from one process, so its id prints once. On macOS, `-b` + * skips kernel calls that can block under load, and `-w` suppresses the warnings it causes. Linux + * lsof finds sockets through /proc, and `-b` can stop the port filter from matching there. */ -async function readConsoleListener(port: number): Promise { +async function readConsoleListener( + port: number, + budgetMs: number, +): Promise { try { const { hostPlatform, readProcessIdentityFacts } = await import('@agent-device/host-kit/process'); if (hostPlatform() !== 'darwin' && hostPlatform() !== 'linux') return { kind: 'absent' }; const { runCmd } = await import('@agent-device/host-kit/command'); + const nonBlocking = hostPlatform() === 'darwin' ? ['-b', '-w'] : []; const result = await runCmd( 'lsof', - ['-b', '-w', '-t', '-nP', `-iTCP:${port}`, '-sTCP:LISTEN'], - { allowFailure: true, timeoutMs: LISTENER_PROBE_TIMEOUT_MS }, + [...nonBlocking, '-t', '-nP', `-iTCP:${port}`, '-sTCP:LISTEN'], + { allowFailure: true, timeoutMs: budgetMs }, ); if (result.exitCode !== 0) return { kind: 'absent' }; const pid = soleListenerPid(result.stdout); if (pid === undefined) return { kind: 'absent' }; - const facts = await readProcessIdentityFacts(pid, LISTENER_PROBE_TIMEOUT_MS); + const facts = await readProcessIdentityFacts(pid, budgetMs); if (facts.zombie === true) return { kind: 'absent' }; if (!facts.startTime || facts.zombie !== false) return { kind: 'unread' }; return { kind: 'identity', identity: { pid, startTime: facts.startTime } }; @@ -74,6 +89,12 @@ function soleListenerPid(stdout: string): number | undefined { const LISTENER_PROBE_TIMEOUT_MS = 5_000; const LISTENER_PROBE_ATTEMPTS = 2; +/** + * One budget for the two agreeing observations that bind or verify a launch identity. Open and + * close each spend at most this long on the probe. + */ +export const ANDROID_EMULATOR_GENERATION_BUDGET_MS = 10_000; + /** The probe answers in tens of milliseconds and must not become the reason an `open` waits. */ const BOOT_PROBE_TIMEOUT_MS = 3_000; diff --git a/src/platform-runtime-android-emulator-host.test.ts b/src/platform-runtime-android-emulator-host.test.ts index cb1db4dd5a..12bbfbc1cb 100644 --- a/src/platform-runtime-android-emulator-host.test.ts +++ b/src/platform-runtime-android-emulator-host.test.ts @@ -4,7 +4,10 @@ import type { DeviceInfo } from '@agent-device/kernel/device'; const { observeAndroidEmulatorGeneration } = vi.hoisted(() => ({ observeAndroidEmulatorGeneration: vi.fn(), })); -vi.mock('@agent-device/platform-android/device-boot', () => ({ observeAndroidEmulatorGeneration })); +vi.mock('@agent-device/platform-android/device-boot', () => ({ + ANDROID_EMULATOR_GENERATION_BUDGET_MS: 10_000, + observeAndroidEmulatorGeneration, +})); const { runCmd, runCmdDetached, runCmdDetachedMonitored, emitDiagnostic } = vi.hoisted(() => ({ runCmd: vi.fn(async (_cmd: string, args: readonly string[]) => ({ @@ -66,7 +69,14 @@ test('binds the launched process only when both serial observations match its re observeAndroidEmulatorGeneration.mockResolvedValue(launchIdentity); await expect(host.bindLaunchedEmulator!(4242, emulator)).resolves.toEqual(launchIdentity); expect(observeAndroidEmulatorGeneration).toHaveBeenCalledTimes(2); - expect(observeAndroidEmulatorGeneration).toHaveBeenCalledWith(emulator); + expect(observeAndroidEmulatorGeneration).toHaveBeenCalledWith(emulator, { + deadline: expect.any(Object), + }); + // Both observations share one deadline, so the pair is bounded together. + const calls = observeAndroidEmulatorGeneration.mock.calls as unknown as Array< + [unknown, { deadline: unknown }] + >; + expect(calls[1]?.[1].deadline).toBe(calls[0]?.[1].deadline); }); test('does not bind an unrelated listener, reused pid, or unavailable observation', async () => { diff --git a/src/platform-runtime-android-emulator-host.ts b/src/platform-runtime-android-emulator-host.ts index 52e9b74453..32ef3e9e71 100644 --- a/src/platform-runtime-android-emulator-host.ts +++ b/src/platform-runtime-android-emulator-host.ts @@ -1,5 +1,9 @@ import type { DeviceReadinessRuntimeHost } from '@agent-device/contracts/device-readiness-runtime'; -import { observeAndroidEmulatorGeneration } from '@agent-device/platform-android/device-boot'; +import { + ANDROID_EMULATOR_GENERATION_BUDGET_MS, + observeAndroidEmulatorGeneration, +} from '@agent-device/platform-android/device-boot'; +import { Deadline } from '@agent-device/host-kit/retry'; 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'; @@ -92,9 +96,10 @@ export function createAndroidEmulatorHost( try { const startTime = await record.startTime; if (!startTime) return undefined; - const first = await observeAndroidEmulatorGeneration(device); + const deadline = Deadline.fromTimeoutMs(ANDROID_EMULATOR_GENERATION_BUDGET_MS); + const first = await observeAndroidEmulatorGeneration(device, { deadline }); if (first?.pid !== pid || first.startTime !== startTime) return undefined; - const second = await observeAndroidEmulatorGeneration(device); + const second = await observeAndroidEmulatorGeneration(device, { deadline }); if (second?.pid !== pid || second.startTime !== startTime) return undefined; return { pid, startTime }; } catch { diff --git a/src/platform-runtime-device-boot.test.ts b/src/platform-runtime-device-boot.test.ts index 8a0a84f91b..bb9ba1d24e 100644 --- a/src/platform-runtime-device-boot.test.ts +++ b/src/platform-runtime-device-boot.test.ts @@ -10,6 +10,7 @@ const mocks = vi.hoisted(() => ({ observed: false, reason: 'unobserved', })), + ANDROID_EMULATOR_GENERATION_BUDGET_MS: 10_000, observeAndroidEmulatorGeneration: vi.fn( async (): Promise<{ pid: number; startTime: string } | undefined> => undefined, ), @@ -39,6 +40,11 @@ test('generation is reported only when two serial observations agree', async () expect(await deviceBootObservation.assessShutdownGeneration(ANDROID_EMULATOR, identity)).toBe( 'same', ); + // The two agreeing reads share one deadline, so a slow host cannot double the budget. + const calls = mocks.observeAndroidEmulatorGeneration.mock.calls as unknown as Array< + [unknown, { deadline: unknown }] + >; + expect(calls[1]?.[1].deadline).toBe(calls[0]?.[1].deadline); mocks.observeAndroidEmulatorGeneration .mockResolvedValueOnce(identity) .mockResolvedValueOnce({ ...identity, startTime: 'replacement' }); diff --git a/src/platform-runtime-device-boot.ts b/src/platform-runtime-device-boot.ts index c9c47efca3..e571157e0b 100644 --- a/src/platform-runtime-device-boot.ts +++ b/src/platform-runtime-device-boot.ts @@ -15,11 +15,13 @@ export const deviceBootObservation: DeviceBootObservationService & DeviceShutdow async assessShutdownGeneration(device, expected) { if (device.platform !== 'android' || device.kind !== 'emulator') return 'not-applicable'; if (!expected) return 'unobserved'; - const { observeAndroidEmulatorGeneration } = + const { ANDROID_EMULATOR_GENERATION_BUDGET_MS, observeAndroidEmulatorGeneration } = await import('@agent-device/platform-android/device-boot'); - const first = await observeAndroidEmulatorGeneration(device); + const { Deadline } = await import('@agent-device/host-kit/retry'); + const deadline = Deadline.fromTimeoutMs(ANDROID_EMULATOR_GENERATION_BUDGET_MS); + const first = await observeAndroidEmulatorGeneration(device, { deadline }); if (!first) return 'unobserved'; - const second = await observeAndroidEmulatorGeneration(device); + const second = await observeAndroidEmulatorGeneration(device, { deadline }); if (!second || second.pid !== first.pid || second.startTime !== first.startTime) return 'unobserved'; return first.pid === expected.pid && first.startTime === expected.startTime From 9f0602e47fa9b0fc2c06e89a6b0bcbe3a0128091 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 17:24:57 +0100 Subject: [PATCH 04/10] fix(close): retry the launch start time read and name each identity miss Open read the launched emulator's start time with the 1 s ps default, so one slow ps left no launch identity and cold stop failed safe under load. The read now uses the listener probe's 5 s budget and one retry. Each observation reports why it produced no identity; open logs android_launch_identity_unbound and close logs android_launch_identity_unobserved with the step and the read that missed. The close warning now says when open recorded no identity. --- .../session-close-external-reboot.test.ts | 4 +- .../internal/session-close.ts | 4 +- packages/platform-android/src/device-boot.ts | 87 +++++++++++++++---- ...form-runtime-android-emulator-host.test.ts | 61 +++++++++---- src/platform-runtime-android-emulator-host.ts | 34 +++++--- src/platform-runtime-device-boot.test.ts | 38 ++++++-- src/platform-runtime-device-boot.ts | 30 +++++-- 7 files changed, 194 insertions(+), 64 deletions(-) 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 index db0ca8fda1..b50eb19f71 100644 --- 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 @@ -501,7 +501,9 @@ test('missing launch identity does not acquire ownership from a later observatio const closed = await runs.run({ name: 'close' }); expect(closed.finalizeAsks[0]?.shutdownTarget).toBe(false); expect(runs.generationAsks()).toBe(0); - expect(closeWarningMessages(closed.response!)).toHaveLength(1); + expect(closeWarningMessages(closed.response!)).toEqual([ + "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.", + ]); }); test('changing the device serial clears launch ownership', async () => { 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 6881f713dd..432342fc38 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts @@ -594,7 +594,9 @@ function buildCloseSuccessResponse(params: { if (implicitShutdownGenerationUnobserved) { appendResponseWarning( data, - "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.", + 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.", ); } return { ok: true, data }; diff --git a/packages/platform-android/src/device-boot.ts b/packages/platform-android/src/device-boot.ts index 7b9ec7ba07..e1c11e2fa0 100644 --- a/packages/platform-android/src/device-boot.ts +++ b/packages/platform-android/src/device-boot.ts @@ -3,6 +3,19 @@ import type { AndroidEmulatorLaunchIdentity } from '@agent-device/contracts/devi import type { DeviceInfo } from '@agent-device/kernel/device'; import type { DeadlineClock } from '@agent-device/host-kit/retry'; +/** Why one observation of the emulator console listener produced no identity. */ +export type AndroidEmulatorGenerationMiss = + | 'no-listener' + | 'ambiguous-listener' + | 'zombie-listener' + | 'listener-read-timeout' + | 'process-read-timeout' + | 'deadline-spent'; + +export type AndroidEmulatorGenerationReading = + | Readonly<{ identity: AndroidEmulatorLaunchIdentity }> + | Readonly<{ miss: AndroidEmulatorGenerationMiss }>; + /** * Observe the process listening on the ADB emulator console port without contacting it. A caller * that observes more than once passes one deadline, so all reads share one bounded budget. @@ -11,29 +24,58 @@ export async function observeAndroidEmulatorGeneration( device: DeviceInfo, options: { deadline?: DeadlineClock } = {}, ): Promise { - if (device.platform !== 'android' || device.kind !== 'emulator') return undefined; + const reading = await inspectAndroidEmulatorGeneration(device, options); + return 'identity' in reading ? reading.identity : undefined; +} + +/** {@link observeAndroidEmulatorGeneration} with the reason a read produced no identity. */ +export async function inspectAndroidEmulatorGeneration( + device: DeviceInfo, + options: { deadline?: DeadlineClock } = {}, +): Promise { + if (device.platform !== 'android' || device.kind !== 'emulator') return { miss: 'no-listener' }; const match = /^emulator-(\d+)$/.exec(device.id); const port = Number(match?.[1]); - if (!match || !Number.isInteger(port) || port < 1 || port > 65535) return undefined; + if (!match || !Number.isInteger(port) || port < 1 || port > 65535) return { miss: 'no-listener' }; + let last: AndroidEmulatorGenerationMiss = 'deadline-spent'; for (let attempt = 1; attempt <= LISTENER_PROBE_ATTEMPTS; attempt += 1) { const budgetMs = Math.min( LISTENER_PROBE_TIMEOUT_MS, options.deadline?.remainingMs() ?? LISTENER_PROBE_TIMEOUT_MS, ); - if (budgetMs <= 0) return undefined; + if (budgetMs <= 0) return { miss: last }; const reading = await readConsoleListener(port, budgetMs); - if (reading.kind === 'identity') return reading.identity; - if (reading.kind === 'absent') return undefined; + if (reading.kind === 'identity') return { identity: reading.identity }; + if (reading.kind === 'absent') return { miss: reading.miss }; + last = reading.miss; + } + return { miss: last }; +} + +/** + * Read the start time of an emulator process this host just launched. It uses the same budget and + * retry as the console listener read, so a slow `ps` under load still records the launch identity. + */ +export async function readAndroidEmulatorLaunchStartTime(pid: number): Promise { + const { readProcessIdentityFacts } = await import('@agent-device/host-kit/process'); + for (let attempt = 1; attempt <= LISTENER_PROBE_ATTEMPTS; attempt += 1) { + try { + const facts = await readProcessIdentityFacts(pid, LISTENER_PROBE_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 undefined; + return null; } type ConsoleListenerReading = | { kind: 'identity'; identity: AndroidEmulatorLaunchIdentity } - /** The host answered: no single process listens on the port. A retry cannot change it. */ - | { kind: 'absent' } + /** The host answered: no single live process listens on the port. A retry cannot change it. */ + | { kind: 'absent'; miss: 'no-listener' | 'ambiguous-listener' | 'zombie-listener' } /** The host did not answer in time or a read failed. A retry can still observe the listener. */ - | { kind: 'unread' }; + | { kind: 'unread'; miss: 'listener-read-timeout' | 'process-read-timeout' }; /** * `lsof -t` prints only process ids, one per line, and exits 1 with no output when nothing listens. @@ -45,10 +87,12 @@ async function readConsoleListener( port: number, budgetMs: number, ): Promise { + const { hostPlatform, readProcessIdentityFacts } = await import('@agent-device/host-kit/process'); + if (hostPlatform() !== 'darwin' && hostPlatform() !== 'linux') { + return { kind: 'absent', miss: 'no-listener' }; + } + let stdout: string; try { - const { hostPlatform, readProcessIdentityFacts } = - await import('@agent-device/host-kit/process'); - if (hostPlatform() !== 'darwin' && hostPlatform() !== 'linux') return { kind: 'absent' }; const { runCmd } = await import('@agent-device/host-kit/command'); const nonBlocking = hostPlatform() === 'darwin' ? ['-b', '-w'] : []; const result = await runCmd( @@ -56,15 +100,22 @@ async function readConsoleListener( [...nonBlocking, '-t', '-nP', `-iTCP:${port}`, '-sTCP:LISTEN'], { allowFailure: true, timeoutMs: budgetMs }, ); - if (result.exitCode !== 0) return { kind: 'absent' }; - const pid = soleListenerPid(result.stdout); - if (pid === undefined) return { kind: 'absent' }; + if (result.exitCode !== 0) return { kind: 'absent', miss: 'no-listener' }; + stdout = result.stdout; + } catch { + return { kind: 'unread', miss: 'listener-read-timeout' }; + } + const pid = soleListenerPid(stdout); + if (pid === undefined) return { kind: 'absent', miss: 'ambiguous-listener' }; + try { const facts = await readProcessIdentityFacts(pid, budgetMs); - if (facts.zombie === true) return { kind: 'absent' }; - if (!facts.startTime || facts.zombie !== false) return { kind: 'unread' }; + if (facts.zombie === true) return { kind: 'absent', miss: 'zombie-listener' }; + if (!facts.startTime || facts.zombie !== false) { + return { kind: 'unread', miss: 'process-read-timeout' }; + } return { kind: 'identity', identity: { pid, startTime: facts.startTime } }; } catch { - return { kind: 'unread' }; + return { kind: 'unread', miss: 'process-read-timeout' }; } } diff --git a/src/platform-runtime-android-emulator-host.test.ts b/src/platform-runtime-android-emulator-host.test.ts index 12bbfbc1cb..3a88e8d934 100644 --- a/src/platform-runtime-android-emulator-host.test.ts +++ b/src/platform-runtime-android-emulator-host.test.ts @@ -1,12 +1,16 @@ import { beforeEach, expect, test, vi } from 'vitest'; import type { DeviceInfo } from '@agent-device/kernel/device'; -const { observeAndroidEmulatorGeneration } = vi.hoisted(() => ({ - observeAndroidEmulatorGeneration: vi.fn(), +const { inspectAndroidEmulatorGeneration, readAndroidEmulatorLaunchStartTime } = vi.hoisted(() => ({ + inspectAndroidEmulatorGeneration: vi.fn(), + readAndroidEmulatorLaunchStartTime: vi.fn( + async (): Promise => 'Mon Nov 9 10:00:00 2026', + ), })); vi.mock('@agent-device/platform-android/device-boot', () => ({ ANDROID_EMULATOR_GENERATION_BUDGET_MS: 10_000, - observeAndroidEmulatorGeneration, + inspectAndroidEmulatorGeneration, + readAndroidEmulatorLaunchStartTime, })); const { runCmd, runCmdDetached, runCmdDetachedMonitored, emitDiagnostic } = vi.hoisted(() => ({ @@ -47,7 +51,8 @@ vi.mock('@agent-device/host-kit/process', () => ({ import { createAndroidEmulatorHost } from './platform-runtime-android-emulator-host.ts'; beforeEach(() => { - observeAndroidEmulatorGeneration.mockReset(); + inspectAndroidEmulatorGeneration.mockReset(); + readAndroidEmulatorLaunchStartTime.mockClear(); runCmd.mockClear(); runCmdDetached.mockClear(); runCmdDetachedMonitored.mockClear(); @@ -66,31 +71,55 @@ const launchIdentity = { pid: 4242, startTime: 'Mon Nov 9 10:00:00 2026' }; test('binds the launched process only when both serial observations match its recorded identity', async () => { const host = createAndroidEmulatorHost('linux'); await host.launch('Pixel_9', true, 90_000); - observeAndroidEmulatorGeneration.mockResolvedValue(launchIdentity); + expect(readAndroidEmulatorLaunchStartTime).toHaveBeenCalledWith(4242); + inspectAndroidEmulatorGeneration.mockResolvedValue({ identity: launchIdentity }); await expect(host.bindLaunchedEmulator!(4242, emulator)).resolves.toEqual(launchIdentity); - expect(observeAndroidEmulatorGeneration).toHaveBeenCalledTimes(2); - expect(observeAndroidEmulatorGeneration).toHaveBeenCalledWith(emulator, { - deadline: expect.any(Object), - }); + expect(inspectAndroidEmulatorGeneration).toHaveBeenCalledTimes(2); // Both observations share one deadline, so the pair is bounded together. - const calls = observeAndroidEmulatorGeneration.mock.calls as unknown as Array< + const calls = inspectAndroidEmulatorGeneration.mock.calls as unknown as Array< [unknown, { deadline: unknown }] >; + expect(calls[0]?.[1].deadline).toBeDefined(); expect(calls[1]?.[1].deadline).toBe(calls[0]?.[1].deadline); }); -test('does not bind an unrelated listener, reused pid, or unavailable observation', async () => { +test('does not bind an unrelated listener, reused pid, or unavailable observation, and names the miss', async () => { const host = createAndroidEmulatorHost('linux'); await host.launch('Pixel_9', true, 90_000); - observeAndroidEmulatorGeneration.mockResolvedValueOnce({ ...launchIdentity, pid: 4243 }); + inspectAndroidEmulatorGeneration.mockResolvedValueOnce({ + identity: { ...launchIdentity, pid: 4243 }, + }); await expect(host.bindLaunchedEmulator!(4242, emulator)).resolves.toBeUndefined(); - observeAndroidEmulatorGeneration - .mockResolvedValueOnce(launchIdentity) - .mockResolvedValueOnce({ ...launchIdentity, startTime: 'new' }); + inspectAndroidEmulatorGeneration + .mockResolvedValueOnce({ identity: launchIdentity }) + .mockResolvedValueOnce({ identity: { ...launchIdentity, startTime: 'new' } }); await expect(host.bindLaunchedEmulator!(4242, emulator)).resolves.toBeUndefined(); - observeAndroidEmulatorGeneration.mockResolvedValueOnce(undefined); + inspectAndroidEmulatorGeneration.mockResolvedValueOnce({ miss: 'listener-read-timeout' }); await expect(host.bindLaunchedEmulator!(4242, emulator)).resolves.toBeUndefined(); await expect(host.bindLaunchedEmulator!(4243, emulator)).resolves.toBeUndefined(); + const causes = emitDiagnostic.mock.calls + .map(([event]) => event as { phase: string; data: { step: string; cause: string } }) + .filter((event) => event.phase === 'android_launch_identity_unbound') + .map((event) => `${event.data.step}:${event.data.cause}`); + expect(causes).toEqual([ + 'bind:first-launch-mismatch', + 'bind:second-launch-mismatch', + 'bind:first-listener-read-timeout', + ]); +}); + +test('a launch whose start time could not be read binds nothing and says so', 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(inspectAndroidEmulatorGeneration).not.toHaveBeenCalled(); + expect(emitDiagnostic).toHaveBeenCalledWith( + expect.objectContaining({ + phase: 'android_launch_identity_unbound', + data: expect.objectContaining({ step: 'bind', cause: 'launch-start-time-unread' }), + }), + ); }); test('a windowed macOS launch hands focus back to the app frontmost before launch', async () => { diff --git a/src/platform-runtime-android-emulator-host.ts b/src/platform-runtime-android-emulator-host.ts index 32ef3e9e71..3ce4155c27 100644 --- a/src/platform-runtime-android-emulator-host.ts +++ b/src/platform-runtime-android-emulator-host.ts @@ -1,16 +1,14 @@ import type { DeviceReadinessRuntimeHost } from '@agent-device/contracts/device-readiness-runtime'; import { ANDROID_EMULATOR_GENERATION_BUDGET_MS, - observeAndroidEmulatorGeneration, + inspectAndroidEmulatorGeneration, + readAndroidEmulatorLaunchStartTime, } from '@agent-device/platform-android/device-boot'; import { Deadline } from '@agent-device/host-kit/retry'; 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; @@ -85,7 +83,7 @@ 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; @@ -93,17 +91,29 @@ export function createAndroidEmulatorHost( bindLaunchedEmulator: async (pid, device) => { const record = launched.get(pid); if (!record) return undefined; + const unbound = (cause: string) => { + // Close reads this as "open recorded no identity", so the miss is named where it happened. + emitDiagnostic({ + level: 'warn', + phase: 'android_launch_identity_unbound', + data: { step: 'bind', cause, pid, serial: device.id }, + }); + return undefined; + }; try { const startTime = await record.startTime; - if (!startTime) return undefined; + if (!startTime) return unbound('launch-start-time-unread'); const deadline = Deadline.fromTimeoutMs(ANDROID_EMULATOR_GENERATION_BUDGET_MS); - const first = await observeAndroidEmulatorGeneration(device, { deadline }); - if (first?.pid !== pid || first.startTime !== startTime) return undefined; - const second = await observeAndroidEmulatorGeneration(device, { deadline }); - if (second?.pid !== pid || second.startTime !== startTime) return undefined; + for (const read of ['first', 'second'] as const) { + const reading = await inspectAndroidEmulatorGeneration(device, { deadline }); + if (!('identity' in reading)) return unbound(`${read}-${reading.miss}`); + if (reading.identity.pid !== pid || reading.identity.startTime !== startTime) { + return unbound(`${read}-launch-mismatch`); + } + } return { pid, startTime }; } catch { - return undefined; + return unbound('bind-failed'); } }, terminate, diff --git a/src/platform-runtime-device-boot.test.ts b/src/platform-runtime-device-boot.test.ts index bb9ba1d24e..4254748021 100644 --- a/src/platform-runtime-device-boot.test.ts +++ b/src/platform-runtime-device-boot.test.ts @@ -11,13 +11,17 @@ const mocks = vi.hoisted(() => ({ reason: 'unobserved', })), ANDROID_EMULATOR_GENERATION_BUDGET_MS: 10_000, - observeAndroidEmulatorGeneration: vi.fn( - async (): Promise<{ pid: number; startTime: string } | undefined> => undefined, + inspectAndroidEmulatorGeneration: vi.fn( + async (): Promise<{ identity: { pid: number; startTime: string } } | { miss: string }> => ({ + miss: 'no-listener', + }), ), + emitDiagnostic: vi.fn(), })); vi.mock('@agent-device/platform-apple/simulator-boot', () => mocks); vi.mock('@agent-device/platform-android/device-boot', () => mocks); +vi.mock('@agent-device/host-kit/diagnostics', () => ({ emitDiagnostic: mocks.emitDiagnostic })); import { ANDROID_EMULATOR, @@ -36,22 +40,24 @@ beforeEach(() => { test('generation is reported only when two serial observations agree', async () => { const identity = { pid: 42, startTime: 'start' }; - mocks.observeAndroidEmulatorGeneration.mockResolvedValue(identity); + mocks.inspectAndroidEmulatorGeneration.mockResolvedValue({ identity }); expect(await deviceBootObservation.assessShutdownGeneration(ANDROID_EMULATOR, identity)).toBe( 'same', ); // The two agreeing reads share one deadline, so a slow host cannot double the budget. - const calls = mocks.observeAndroidEmulatorGeneration.mock.calls as unknown as Array< + const calls = mocks.inspectAndroidEmulatorGeneration.mock.calls as unknown as Array< [unknown, { deadline: unknown }] >; expect(calls[1]?.[1].deadline).toBe(calls[0]?.[1].deadline); - mocks.observeAndroidEmulatorGeneration - .mockResolvedValueOnce(identity) - .mockResolvedValueOnce({ ...identity, startTime: 'replacement' }); + mocks.inspectAndroidEmulatorGeneration + .mockResolvedValueOnce({ identity }) + .mockResolvedValueOnce({ identity: { ...identity, startTime: 'replacement' } }); expect(await deviceBootObservation.assessShutdownGeneration(ANDROID_EMULATOR, identity)).toBe( 'unobserved', ); - mocks.observeAndroidEmulatorGeneration.mockResolvedValue({ pid: 43, startTime: 'replacement' }); + mocks.inspectAndroidEmulatorGeneration.mockResolvedValue({ + identity: { pid: 43, startTime: 'replacement' }, + }); expect(await deviceBootObservation.assessShutdownGeneration(ANDROID_EMULATOR, identity)).toBe( 'changed', ); @@ -69,6 +75,22 @@ test('generation is reported only when two serial observations agree', async () ); }); +test('an unverified close names the step and the read that missed', async () => { + const identity = { pid: 42, startTime: 'start' }; + mocks.inspectAndroidEmulatorGeneration + .mockResolvedValueOnce({ identity }) + .mockResolvedValueOnce({ miss: 'process-read-timeout' }); + expect(await deviceBootObservation.assessShutdownGeneration(ANDROID_EMULATOR, identity)).toBe( + 'unobserved', + ); + await deviceBootObservation.assessShutdownGeneration(ANDROID_EMULATOR, undefined); + const causes = mocks.emitDiagnostic.mock.calls + .map(([event]) => event as { phase: string; data: { step: string; cause: string } }) + .filter((event) => event.phase === 'android_launch_identity_unobserved') + .map((event) => `${event.data.step}:${event.data.cause}`); + expect(causes).toEqual(['assess:second-process-read-timeout', 'assess:unbound-at-open']); +}); + test('an iOS Simulator is answered by the Apple probe alone', async () => { expect(await deviceBootObservation.observeBootTimeMs(IOS_SIMULATOR)).toEqual({ observed: true, diff --git a/src/platform-runtime-device-boot.ts b/src/platform-runtime-device-boot.ts index e571157e0b..c3313d8006 100644 --- a/src/platform-runtime-device-boot.ts +++ b/src/platform-runtime-device-boot.ts @@ -4,6 +4,7 @@ import type { DeviceShutdownGenerationService, } from '@agent-device/contracts/device-boot'; import { isIosFamily, type DeviceInfo } from '@agent-device/kernel/device'; +import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; /** * The single answer to "when did this device's current boot begin?", assembled from whichever @@ -14,17 +15,30 @@ export const deviceBootObservation: DeviceBootObservationService & DeviceShutdow Object.freeze({ async assessShutdownGeneration(device, expected) { if (device.platform !== 'android' || device.kind !== 'emulator') return 'not-applicable'; - if (!expected) return 'unobserved'; - const { ANDROID_EMULATOR_GENERATION_BUDGET_MS, observeAndroidEmulatorGeneration } = + const unobserved = (cause: string) => { + emitDiagnostic({ + level: 'warn', + phase: 'android_launch_identity_unobserved', + data: { step: 'assess', cause, serial: device.id }, + }); + return 'unobserved' as const; + }; + if (!expected) return unobserved('unbound-at-open'); + const { ANDROID_EMULATOR_GENERATION_BUDGET_MS, inspectAndroidEmulatorGeneration } = await import('@agent-device/platform-android/device-boot'); const { Deadline } = await import('@agent-device/host-kit/retry'); const deadline = Deadline.fromTimeoutMs(ANDROID_EMULATOR_GENERATION_BUDGET_MS); - const first = await observeAndroidEmulatorGeneration(device, { deadline }); - if (!first) return 'unobserved'; - const second = await observeAndroidEmulatorGeneration(device, { deadline }); - if (!second || second.pid !== first.pid || second.startTime !== first.startTime) - return 'unobserved'; - return first.pid === expected.pid && first.startTime === expected.startTime + const first = await inspectAndroidEmulatorGeneration(device, { deadline }); + if (!('identity' in first)) return unobserved(`first-${first.miss}`); + const second = await inspectAndroidEmulatorGeneration(device, { deadline }); + if (!('identity' in second)) return unobserved(`second-${second.miss}`); + if ( + second.identity.pid !== first.identity.pid || + second.identity.startTime !== first.identity.startTime + ) { + return unobserved('reads-disagree'); + } + return first.identity.pid === expected.pid && first.identity.startTime === expected.startTime ? 'same' : 'changed'; }, From 041b199a1c8bda4038b8203da7127b2d2df8a4be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 17:59:25 +0100 Subject: [PATCH 05/10] refactor(close): drop the identity-only probe export Every caller now reads the miss reason through inspectAndroidEmulatorGeneration. --- .../src/device-boot-generation.test.ts | 9 ++++++++- packages/platform-android/src/device-boot.ts | 14 +++----------- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/packages/platform-android/src/device-boot-generation.test.ts b/packages/platform-android/src/device-boot-generation.test.ts index adebbcb043..27c2eea79c 100644 --- a/packages/platform-android/src/device-boot-generation.test.ts +++ b/packages/platform-android/src/device-boot-generation.test.ts @@ -12,7 +12,14 @@ vi.mock('@agent-device/host-kit/process', () => ({ hostPlatform: mocks.hostPlatform, })); -import { observeAndroidEmulatorGeneration } from './device-boot.ts'; +import { inspectAndroidEmulatorGeneration } from './device-boot.ts'; + +const observeAndroidEmulatorGeneration = async ( + ...args: Parameters +) => { + const reading = await inspectAndroidEmulatorGeneration(...args); + return 'identity' in reading ? reading.identity : undefined; +}; const device: DeviceInfo = { platform: 'android', diff --git a/packages/platform-android/src/device-boot.ts b/packages/platform-android/src/device-boot.ts index e1c11e2fa0..ffc3bd3df6 100644 --- a/packages/platform-android/src/device-boot.ts +++ b/packages/platform-android/src/device-boot.ts @@ -17,18 +17,10 @@ export type AndroidEmulatorGenerationReading = | Readonly<{ miss: AndroidEmulatorGenerationMiss }>; /** - * Observe the process listening on the ADB emulator console port without contacting it. A caller - * that observes more than once passes one deadline, so all reads share one bounded budget. + * Observe the process listening on the ADB emulator console port without contacting it, with the + * reason a read produced no identity. A caller that observes more than once passes one deadline, + * so all reads share one bounded budget. */ -export async function observeAndroidEmulatorGeneration( - device: DeviceInfo, - options: { deadline?: DeadlineClock } = {}, -): Promise { - const reading = await inspectAndroidEmulatorGeneration(device, options); - return 'identity' in reading ? reading.identity : undefined; -} - -/** {@link observeAndroidEmulatorGeneration} with the reason a read produced no identity. */ export async function inspectAndroidEmulatorGeneration( device: DeviceInfo, options: { deadline?: DeadlineClock } = {}, From 059757d7eadb9ba8b592de0bc5fbb030b8df091f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 19:00:20 +0100 Subject: [PATCH 06/10] test(close): cover the launch start time retry and keep ps inside the deadline Cover the retried 5 s launch start time read and the zombie case. The ps read after lsof now gets only what the shared deadline still has, so one slow attempt stays inside the 10 s pair budget. --- .../src/device-boot-generation.test.ts | 36 ++++++++++++++++++- packages/platform-android/src/device-boot.ts | 8 +++-- 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/packages/platform-android/src/device-boot-generation.test.ts b/packages/platform-android/src/device-boot-generation.test.ts index 27c2eea79c..5eec8d0873 100644 --- a/packages/platform-android/src/device-boot-generation.test.ts +++ b/packages/platform-android/src/device-boot-generation.test.ts @@ -12,7 +12,10 @@ vi.mock('@agent-device/host-kit/process', () => ({ hostPlatform: mocks.hostPlatform, })); -import { inspectAndroidEmulatorGeneration } from './device-boot.ts'; +import { + inspectAndroidEmulatorGeneration, + readAndroidEmulatorLaunchStartTime, +} from './device-boot.ts'; const observeAndroidEmulatorGeneration = async ( ...args: Parameters @@ -117,3 +120,34 @@ test('a shared deadline caps each read and stops reads once it is spent', async expect.objectContaining({ timeoutMs: 3_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('the process read gets only what the shared deadline still has', async () => { + const remaining = [5_000, 1_200]; + const deadline = { + remainingMs: () => remaining.shift() ?? 0, + elapsedMs: () => 0, + isExpired: () => false, + }; + expect(await observeAndroidEmulatorGeneration(device, { deadline })).toEqual({ + pid: 42, + startTime: 'start', + }); + expect(mocks.readProcessIdentityFacts).toHaveBeenCalledWith(42, 1_200); +}); diff --git a/packages/platform-android/src/device-boot.ts b/packages/platform-android/src/device-boot.ts index ffc3bd3df6..46621622fc 100644 --- a/packages/platform-android/src/device-boot.ts +++ b/packages/platform-android/src/device-boot.ts @@ -36,7 +36,7 @@ export async function inspectAndroidEmulatorGeneration( options.deadline?.remainingMs() ?? LISTENER_PROBE_TIMEOUT_MS, ); if (budgetMs <= 0) return { miss: last }; - const reading = await readConsoleListener(port, budgetMs); + const reading = await readConsoleListener(port, budgetMs, options.deadline); if (reading.kind === 'identity') return { identity: reading.identity }; if (reading.kind === 'absent') return { miss: reading.miss }; last = reading.miss; @@ -78,6 +78,7 @@ type ConsoleListenerReading = async function readConsoleListener( port: number, budgetMs: number, + deadline: DeadlineClock | undefined, ): Promise { const { hostPlatform, readProcessIdentityFacts } = await import('@agent-device/host-kit/process'); if (hostPlatform() !== 'darwin' && hostPlatform() !== 'linux') { @@ -99,8 +100,11 @@ async function readConsoleListener( } const pid = soleListenerPid(stdout); if (pid === undefined) return { kind: 'absent', miss: 'ambiguous-listener' }; + // The ps read gets only what the shared deadline still has, so lsof and ps together stay inside it. + const processBudgetMs = Math.min(budgetMs, deadline?.remainingMs() ?? budgetMs); + if (processBudgetMs <= 0) return { kind: 'unread', miss: 'process-read-timeout' }; try { - const facts = await readProcessIdentityFacts(pid, budgetMs); + const facts = await readProcessIdentityFacts(pid, processBudgetMs); if (facts.zombie === true) return { kind: 'absent', miss: 'zombie-listener' }; if (!facts.startTime || facts.zombie !== false) { return { kind: 'unread', miss: 'process-read-timeout' }; From 026bfb7af7b21827e575a758a17cbdbfdd1510ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 22:55:42 +0100 Subject: [PATCH 07/10] refactor(android): verify the launched emulator process on close Plain close now owns the emulator process its own `open` launched, instead of probing which emulator generation owns the console. `open` records `{ pid, startTime }`; close reads the host facts for that pid once, keeps the device when the process is gone, changed, or unverifiable, and stops the recorded process when the emulator console kill does not take. Removes the `lsof` console-listener generation probe, the `DeviceShutdownGenerationService` wiring, and the `generation` field that platform runtimes no longer answer for. --- .../command-surface/src/management/app.ts | 2 +- .../src/application-lifecycle-runtime.ts | 6 - packages/contracts/src/device-boot.ts | 8 - .../contracts/src/device-readiness-runtime.ts | 6 + .../contracts/src/device-shutdown-runtime.ts | 24 +- .../launched-emulator-process-fixture.ts | 96 ++++ .../support/platform-services-fixture.ts | 3 - packages/daemon/src/core/platform-services.ts | 7 +- ...uest-router-bounded-claim-recovery.test.ts | 1 - .../session-close-external-reboot.test.ts | 432 ++++++------------ .../session-close-implicit-shutdown.test.ts | 28 +- .../session-close-emulator-process.ts | 63 +++ .../session-close-lifecycle-teardown.ts | 126 +++-- .../internal/session-close.ts | 39 +- .../src/device-boot-generation.test.ts | 153 ------- .../src/device-boot-launch.test.ts | 43 ++ packages/platform-android/src/device-boot.ts | 132 +----- .../platform-android/src/lifecycle.test.ts | 26 +- packages/platform-android/src/lifecycle.ts | 14 +- .../src/shutdown/runtime.test.ts | 42 -- .../platform-android/src/shutdown/runtime.ts | 29 +- skills/agent-device/SKILL.md | 2 +- skills/android-emulator/SKILL.md | 2 +- skills/dogfood/SKILL.md | 2 +- src/commands/schema/cli-help-workflows.ts | 4 +- ...form-runtime-android-emulator-host.test.ts | 47 +- src/platform-runtime-android-emulator-host.ts | 37 +- src/platform-runtime-device-boot.test.ts | 61 --- src/platform-runtime-device-boot.ts | 60 +-- ...tform-runtime-device-shutdown-host.test.ts | 14 - src/platform-runtime-device-shutdown-host.ts | 15 +- website/docs/docs/commands.md | 2 +- website/docs/docs/sessions.md | 9 +- 33 files changed, 539 insertions(+), 996 deletions(-) create mode 100644 packages/daemon/src/__tests__/support/launched-emulator-process-fixture.ts create mode 100644 packages/daemon/src/sessions/session-lifecycle/internal/session-close-emulator-process.ts delete mode 100644 packages/platform-android/src/device-boot-generation.test.ts create mode 100644 packages/platform-android/src/device-boot-launch.test.ts diff --git a/packages/command-surface/src/management/app.ts b/packages/command-surface/src/management/app.ts index 6be3963cba..d09427f1e2 100644 --- a/packages/command-surface/src/management/app.ts +++ b/packages/command-surface/src/management/app.ts @@ -95,7 +95,7 @@ const openCommandMetadata = defineFieldCommandMetadata( const closeCommandMetadata = defineFieldCommandMetadata( 'close', - "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 an Android emulator process changed or cannot be verified, plain close leaves it 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.", + "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( diff --git a/packages/contracts/src/application-lifecycle-runtime.ts b/packages/contracts/src/application-lifecycle-runtime.ts index c8c579a7f7..b1e01d7e76 100644 --- a/packages/contracts/src/application-lifecycle-runtime.ts +++ b/packages/contracts/src/application-lifecycle-runtime.ts @@ -1,7 +1,3 @@ -import type { - AndroidShutdownVerification, - AndroidShutdownRetained, -} from './device-shutdown-runtime.ts'; import type { RuntimeOperationName } from './runtime-operation-names.ts'; import type { RuntimeOperationFact } from './platform-runtime.ts'; import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -275,12 +271,10 @@ export type CloseApplicationFinalizationInput = Readonly<{ daemonShutdown?: boolean; /** `close --shutdown` is an admitted close finalization effect, never a daemon fallback. */ shutdownTarget?: boolean; - verifyAndroidShutdown?: AndroidShutdownVerification; }>; export type CloseApplicationFinalizationResult = Readonly<{ shutdown?: TargetShutdownResult; - androidShutdownRetained?: AndroidShutdownRetained['retained']; }>; export type PrepareAppleRunnerInput = Readonly<{ diff --git a/packages/contracts/src/device-boot.ts b/packages/contracts/src/device-boot.ts index 347bd15e72..b69e386736 100644 --- a/packages/contracts/src/device-boot.ts +++ b/packages/contracts/src/device-boot.ts @@ -1,5 +1,4 @@ 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 @@ -24,10 +23,3 @@ export type DeviceBootObservation = export type DeviceBootObservationService = Readonly<{ observeBootTimeMs(device: DeviceInfo): Promise; }>; - -export type DeviceShutdownGenerationService = Readonly<{ - assessShutdownGeneration( - device: DeviceInfo, - expected: AndroidEmulatorLaunchIdentity | undefined, - ): Promise<'same' | 'changed' | 'unobserved' | 'not-applicable'>; -}>; diff --git a/packages/contracts/src/device-readiness-runtime.ts b/packages/contracts/src/device-readiness-runtime.ts index bc3f602c78..06f8c79a42 100644 --- a/packages/contracts/src/device-readiness-runtime.ts +++ b/packages/contracts/src/device-readiness-runtime.ts @@ -42,6 +42,12 @@ 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, diff --git a/packages/contracts/src/device-shutdown-runtime.ts b/packages/contracts/src/device-shutdown-runtime.ts index fe257e06ea..9791971257 100644 --- a/packages/contracts/src/device-shutdown-runtime.ts +++ b/packages/contracts/src/device-shutdown-runtime.ts @@ -2,17 +2,6 @@ import type { DeviceInfo } from '@agent-device/kernel/device'; import type { AppleToolHost, HostCommandRunner } from './platform-runtime-host.ts'; import type { TargetShutdownResult } from './target-shutdown-contract.ts'; -export type AndroidShutdownVerification = () => Promise<'same' | 'changed' | 'unobserved'>; -export type AndroidShutdownRetained = Readonly<{ retained: 'changed' | 'unobserved' }>; -export type AndroidShutdownTarget = { - (device: DeviceInfo, signal: AbortSignal): Promise; - ( - device: DeviceInfo, - signal: AbortSignal, - verify: AndroidShutdownVerification, - ): Promise; -}; - export type DeviceShutdownRuntimeOperations = Readonly<{ shutdownTarget( input: Readonly<{ @@ -43,18 +32,17 @@ export type DeviceShutdownRuntimeLoaders = Readonly<{ apple: ( dependencies: Pick, ) => Promise; - android: (dependencies: Pick) => Promise< - Readonly<{ - canShutdownTarget(device: DeviceInfo): boolean; - shutdownTarget: AndroidShutdownTarget; - }> - >; + android: ( + dependencies: Pick, + ) => Promise; }>; export type DeviceShutdownRuntimeHost = Readonly<{ apple: Readonly<{ shutdownTarget(device: DeviceInfo, signal: AbortSignal): Promise; }>; - android: Readonly<{ shutdownTarget: AndroidShutdownTarget }>; + android: Readonly<{ + shutdownTarget(device: DeviceInfo, signal: AbortSignal): Promise; + }>; close?: DeviceShutdownCloseCapability; }>; diff --git a/packages/daemon/src/__tests__/support/launched-emulator-process-fixture.ts b/packages/daemon/src/__tests__/support/launched-emulator-process-fixture.ts new file mode 100644 index 0000000000..b63e383187 --- /dev/null +++ b/packages/daemon/src/__tests__/support/launched-emulator-process-fixture.ts @@ -0,0 +1,96 @@ +import type * as HostProcessModule from '@agent-device/host-kit/process'; + +/** + * How the host answers for the emulator process a test session's `open` launched, so a close suite + * can name which answer the launched-process rule gets without touching the real process table. + * Cases use the pid named here rather than an arbitrary one: a fabricated pid would be signalled for + * real if a rule ever aimed a stop at the wrong process, so the seams below answer for this pid only + * and delegate every other pid to the real host. + */ +export type LaunchedEmulatorProcess = { + /** The pid `open` recorded for the emulator it launched. */ + pid: number; + /** The start time `open` recorded for that pid. */ + startTime: string; + /** Whether `kill(pid, 0)` still finds it. */ + alive: boolean; + /** Whether the host shows it as a zombie: still answered for, already terminated. */ + zombie: boolean; + /** The live start time the host reports for it, which may contradict the recorded one. */ + liveStartTime: string; + /** Whether the host refuses to answer for the pid at all. */ + unreadable: boolean; + /** Whether the process took the `adb emu kill` the close asked for. */ + exitsOnKill: boolean; + /** How many times the close read this pid's identity facts. */ + factReads: number; + /** Every pid a stop escalated to, with the identity it carried. */ + signalAttempts: Array<{ pid: number; startTime?: string }>; +}; + +const DEFAULTS = { + pid: 4112, + startTime: 'launch-start-time', + alive: true, + zombie: false, + liveStartTime: 'launch-start-time', + unreadable: false, + exitsOnKill: true, +} as const; + +/** + * The one model the suite's host answers are read from, shared by the mocked module and the cases. + * A case sets the fields it cares about; `resetLaunchedEmulatorProcess` returns it before the next. + */ +export const launchedEmulatorProcess: LaunchedEmulatorProcess = { + ...DEFAULTS, + factReads: 0, + signalAttempts: [], +}; + +/** Returns the model to a live launched process that takes the kill, before each case. */ +export function resetLaunchedEmulatorProcess(): void { + Object.assign(launchedEmulatorProcess, DEFAULTS, { factReads: 0 }); + launchedEmulatorProcess.signalAttempts.length = 0; +} + +/** + * The `@agent-device/host-kit/process` answers a close suite needs, over the model above. Only the + * four reads a close makes about another process are answered this way, and only for the launched + * pid; the real host keeps answering every other question. + */ +export function launchedEmulatorProcessHost( + actual: typeof HostProcessModule, +): typeof HostProcessModule { + const isLaunched = (pid: number) => pid === launchedEmulatorProcess.pid; + return { + ...actual, + isProcessAlive: (pid: number) => + isLaunched(pid) ? launchedEmulatorProcess.alive : actual.isProcessAlive(pid), + readProcessIdentityFacts: async (pid: number, timeoutMs?: number) => { + if (!isLaunched(pid)) return await actual.readProcessIdentityFacts(pid, timeoutMs); + launchedEmulatorProcess.factReads += 1; + if (launchedEmulatorProcess.unreadable) throw new Error('ps timed out after 1000ms'); + return { + startTime: launchedEmulatorProcess.liveStartTime, + command: '/sdk/emulator/emulator -avd Pixel_9_API_37', + zombie: launchedEmulatorProcess.zombie, + }; + }, + waitForProcessExit: async (pid: number, timeoutMs: number) => + isLaunched(pid) + ? !launchedEmulatorProcess.alive || launchedEmulatorProcess.exitsOnKill + : await actual.waitForProcessExit(pid, timeoutMs), + stopProcessAndConfirmExit: async ( + target: HostProcessModule.ProcessStopTarget, + budget: HostProcessModule.ProcessStopBudget, + ) => { + if (!isLaunched(target.pid)) return await actual.stopProcessAndConfirmExit(target, budget); + launchedEmulatorProcess.signalAttempts.push({ + pid: target.pid, + startTime: target.identity.startTime, + }); + return { status: 'stopped', signal: 'SIGTERM' } as const; + }, + }; +} diff --git a/packages/daemon/src/__tests__/support/platform-services-fixture.ts b/packages/daemon/src/__tests__/support/platform-services-fixture.ts index a68b9d16a6..bdcf8773f2 100644 --- a/packages/daemon/src/__tests__/support/platform-services-fixture.ts +++ b/packages/daemon/src/__tests__/support/platform-services-fixture.ts @@ -6,8 +6,6 @@ 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'; -const assessShutdownGenerationFixture = async () => 'not-applicable' as const; - /** * 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 @@ -28,7 +26,6 @@ export function daemonPlatformServicesFixture( }), deviceBootObservation: Object.freeze({ observeBootTimeMs: observeBootTimeMsFixture, - assessShutdownGeneration: assessShutdownGenerationFixture, }), ensureLocalDeviceReady: ensureLocalDeviceReadyFixture, resolveRequestedOpenSurface: resolveRequestedOpenSurfaceFixture, diff --git a/packages/daemon/src/core/platform-services.ts b/packages/daemon/src/core/platform-services.ts index 56e1d47ee6..2d46422609 100644 --- a/packages/daemon/src/core/platform-services.ts +++ b/packages/daemon/src/core/platform-services.ts @@ -1,8 +1,5 @@ import type { AppleSessionObservation } from '@agent-device/contracts/apple-session-observation'; -import type { - DeviceBootObservationService, - DeviceShutdownGenerationService, -} from '@agent-device/contracts/device-boot'; +import type { DeviceBootObservationService } from '@agent-device/contracts/device-boot'; import type { SessionSurface } from '@agent-device/contracts/session'; import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -22,7 +19,7 @@ export type EnsureLocalDeviceReady = (device: DeviceInfo, signal: AbortSignal) = */ export type DaemonPlatformServices = Readonly<{ appleSessionObservation: AppleSessionObservation; - deviceBootObservation: DeviceBootObservationService & DeviceShutdownGenerationService; + deviceBootObservation: DeviceBootObservationService; ensureLocalDeviceReady: EnsureLocalDeviceReady; resolveRequestedOpenSurface(params: { device: DeviceInfo; diff --git a/packages/daemon/src/server/__tests__/request-router-bounded-claim-recovery.test.ts b/packages/daemon/src/server/__tests__/request-router-bounded-claim-recovery.test.ts index 9ce74f8973..b5440b72fc 100644 --- a/packages/daemon/src/server/__tests__/request-router-bounded-claim-recovery.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-bounded-claim-recovery.test.ts @@ -143,7 +143,6 @@ function route( ? {} : { deviceBootObservation: { - assessShutdownGeneration: async () => 'not-applicable' as const, observeBootTimeMs: async () => ({ observed: true as const, bootedAtMs: options.bootedAtMs!, 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 index b50eb19f71..20a462a838 100644 --- 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 @@ -1,6 +1,7 @@ -// #4585: plain `close` owes a stop to the boot its own `open` caused, not to whichever boot the -// device is running now. Routed through the session command handler, so claim acquisition, renewal, -// boot stamping and close teardown all run against real claim files. +// #4585: plain `close` owes a stop to the emulator 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, and the +// only host fact close reads about the launched process is the `ps` of the recorded pid. import { afterEach, beforeEach, expect, test, vi } from 'vitest'; import path from 'node:path'; import * as hostProcess from '@agent-device/host-kit/process'; @@ -24,24 +25,39 @@ vi.mock('@agent-device/device-selection/dispatch-resolve', async (importOriginal }; }); +// The host's answers about the emulator process `open` launched are modelled so no case signals or +// waits on a real process. `launchedEmulatorProcess()` is that model. +vi.mock('@agent-device/host-kit/process', async (importOriginal) => { + const { launchedEmulatorProcessHost } = + await import('../../../../__tests__/support/launched-emulator-process-fixture.ts'); + return launchedEmulatorProcessHost( + await importOriginal(), + ); +}); + +import { + launchedEmulatorProcess as launched, + resetLaunchedEmulatorProcess, +} from '../../../../__tests__/support/launched-emulator-process-fixture.ts'; + +/** The identity `open` records for the emulator process it launched, as the model answers for it. */ +const launchedEmulatorIdentity = () => ({ pid: launched.pid, startTime: launched.startTime }); 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 { - applicationLifecycleRuntimeFixture, - type LifecycleOperationsLoader, -} from '../../../../__tests__/support/application-lifecycle-runtime-fixture.ts'; -import { - acquireDeviceClaim, clearDeviceClaim, inspectDeviceClaims, } from '@agent-device/daemon-contracts/device-claims'; -import type { DeviceBootObservation } from '@agent-device/contracts/device-boot'; -import type { DaemonPlatformServices } from '../../../../core/platform-services.ts'; import { SessionStore } from '../../../../core/session-store.ts'; import { resolveTargetDevice } from '@agent-device/device-selection/dispatch-resolve'; import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -49,74 +65,32 @@ import type { DeviceInfo } from '@agent-device/kernel/device'; pinOwnProcessStartTime(hostProcess); bindTestCommandHost(); -/** The clock every case runs on, so a boot epoch is a named instant rather than an elapsed guess. */ -const CLOCK_START_MS = Date.UTC(2026, 0, 15, 10, 0, 0); -/** How far after the cold open a case places the emulator's next boot, and how long it has been up. */ -const LATER_BOOT_DELAY_MS = 60_000; -const LATER_BOOT_UPTIME_MS = 45_000; -/** How long before a case's own boot a prior session's claim was taken. */ -const PRIOR_CLAIM_GAP_MS = 30 * 60_000; - const SESSION = 'implicit-shutdown-session'; -const OWN_GENERATION = { pid: 1234, startTime: 'original' }; -const NEXT_GENERATION = { pid: 1234, startTime: 'replacement' }; - -/** The boot epoch of an emulator restarted outside the session: past, and later than the open's. */ -const LATER_BOOT_MS = CLOCK_START_MS + LATER_BOOT_DELAY_MS - LATER_BOOT_UPTIME_MS; -const REBOOTED: DeviceBootObservation = { observed: true, bootedAtMs: LATER_BOOT_MS }; /** 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_35', + name: 'Pixel_9_API_37', kind: 'emulator', booted: false, }; -/** The same emulator once it runs. An outside reboot keeps this identity and serial. */ +/** 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_35', + name: 'Pixel_9_API_37', kind: 'emulator', booted: true, }; -function createRoutedSession( - observeBootTimeMs?: (device: DeviceInfo) => Promise, -) { - const stateDir = mkdtempForTestSync('agent-device-session-close-reboot-'); +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'), }; - // The platform port supplies the emulator's observed boot time. - const boot: { current: DeviceBootObservation } = { - current: { observed: false, reason: 'unobserved' }, - }; - let bootAsks = 0; - const generation: { current: typeof OWN_GENERATION | undefined } = { current: OWN_GENERATION }; - let generationAsks = 0; - const platformServices = daemonPlatformServicesFixture({ - deviceBootObservation: { - assessShutdownGeneration: async (_device, expected) => { - if (!expected) return 'unobserved'; - generationAsks += 1; - if (observeBootTimeMs) throw new Error('unavailable'); - const current = boot.current === REBOOTED ? NEXT_GENERATION : generation.current; - return !current - ? 'unobserved' - : current.pid === expected.pid && current.startTime === expected.startTime - ? 'same' - : 'changed'; - }, - observeBootTimeMs: async (device: DeviceInfo): Promise => { - bootAsks += 1; - return (await observeBootTimeMs?.(device)) ?? boot.current; - }, - }, - }) as unknown as DaemonPlatformServices; const sessionStore = new SessionStore(path.join(stateDir, 'sessions'), { env, cwd: process.cwd(), @@ -127,41 +101,28 @@ function createRoutedSession( flags?: Record; /** Only a cold open selects a device, and that selection is what boots the stopped AVD. */ selectsDevice?: boolean; - beforeAppOpen?(): void; deviceShutdownDenied?: boolean; + /** A cold open whose readiness never reported the process it launched. */ omitLaunchIdentity?: boolean; - beforeFinalization?(): void; }) { if (command.selectsDevice) { vi.mocked(resolveTargetDevice).mockResolvedValue(STOPPED_AVD); mockEnsureReadyRuntime.mockImplementation(async (input) => { - if (!command.omitLaunchIdentity) input.onAndroidEmulatorLaunchIdentity?.(OWN_GENERATION); + if (!command.omitLaunchIdentity) + input.onAndroidEmulatorLaunchIdentity?.(launchedEmulatorIdentity()); return BOOTED_EMULATOR; }); } - // Plain close is recorded at the lifecycle port the close dispatches, and the leaf - // `shutdownTarget` stays the harness's own, so `mockShutdownTargetRuntime` counts the stop the - // platform was actually asked to perform. - const finalizeAsks: Array> = []; + // 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, - openApplication: async (input) => { - command.beforeAppOpen?.(); - return await operations.openApplication(input); - }, finalizeApplicationClose: async (input) => { - finalizeAsks.push({ - shutdownTarget: input.shutdownTarget === true, - retainRunner: input.retainRunner === true, - }); - command.beforeFinalization?.(); - if (input.verifyAndroidShutdown) { - const result = await input.verifyAndroidShutdown(); - if (result !== 'same') return { androidShutdownRetained: result }; - } + finalizeAsks.push(input); return await finalizeApplicationClose(input); }, }); @@ -169,7 +130,7 @@ function createRoutedSession( const response = await handleSessionCommands({ host: createTestHostEnvironment({ env }), createCommandSurface: fakeCreateCommandSurface, - platformServices, + platformServices: daemonPlatformServicesFixture(), sessionStore, invoke: async () => ({ ok: true, data: {} }), lifecycleOperationsLoader: loader, @@ -189,48 +150,18 @@ function createRoutedSession( return { response, finalizeAsks }; } - function sessionClaim() { - const claim = inspectDeviceClaims({ serial: BOOTED_EMULATOR.id }, env)[0]?.claim; - if (!claim) throw new Error('expected the session to hold its claim'); - return claim; - } - /** 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; } - /** - * Leaves a claim on disk for this device, taken by the same session name, workspace and daemon. - * That is the shape a session inherits when a previous one ended without clearing its claim, and - * the acquisition that follows renews that claim rather than taking a new one. - */ - async function plantPriorClaim() { - const acquired = await acquireDeviceClaim({ - device: BOOTED_EMULATOR, - session: SESSION, - workspace: process.cwd(), - stateDir: sessionStore.resolveDaemonStateDir(), - env, - reconcileOrphanedDeviceClaim: async () => ({ status: 'reconciled' as const }), - }); - if (acquired.status !== 'acquired') throw new Error('expected to plant a prior claim'); - } - return { - boot, - generation, - generationAsks: () => generationAsks, - /** Asks the boot-observation service answered, so a case can prove the device was not probed. */ - bootAsks: () => bootAsks, dropSessionClaim: async () => { const ownership = sessionStore.get(SESSION)?.deviceClaim; if (!ownership) throw new Error('expected the session to record its claim'); await clearDeviceClaim(ownership, env); }, - plantPriorClaim, run, - sessionClaim, sessionClaimCount, sessionStore, }; @@ -238,27 +169,20 @@ function createRoutedSession( /** * Opens a stopped AVD through the cold route and leaves the emulator running on the boot this - * session caused. The clock stays fake so a case can name a later boot instead of waiting one out. + * session caused, with the launched process recorded as the host answers for it. */ -async function openBootedByThisSession( - runs: ReturnType, - beforeAppOpen?: () => void, -) { - vi.useFakeTimers({ toFake: ['Date'] }); - vi.setSystemTime(CLOCK_START_MS); +async function openBootedByThisSession(runs: ReturnType) { const opened = await runs.run({ name: 'open', flags: { platform: 'android' }, selectsDevice: true, - beforeAppOpen, }); expect(opened.response?.ok).toBe(true); const session = runs.sessionStore.get(SESSION); - // The boot fact and the launch identity of the boot it describes are written together, and that - // pair is the only thing close may compare against the running emulator. + // 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(OWN_GENERATION); - return CLOCK_START_MS; + expect(session?.androidLaunchIdentity).toEqual(launchedEmulatorIdentity()); } function closeWarningMessages(response: { ok?: unknown; data?: unknown }): unknown { @@ -266,246 +190,198 @@ function closeWarningMessages(response: { ok?: unknown; data?: unknown }): unkno 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); + resetLaunchedEmulatorProcess(); }); afterEach(() => { vi.useRealTimers(); }); -test('plain close leaves an emulator rebooted outside the session running and says why', async () => { +test('plain close stops the emulator this session booted while it still runs that boot', async () => { const runs = createRoutedSession(); await openBootedByThisSession(runs); - // An outside actor restarts the emulator between two session commands. A reopen then proves the - // session cannot recover the boot fact from what it owns: the reopen boots nothing, and its own - // claim renewal vouches for the running device, so only the observed boot separates the boots. - vi.advanceTimersByTime(LATER_BOOT_DELAY_MS); - runs.boot.current = REBOOTED; - const ref = runs.sessionStore.lookup(SESSION); - expect(ref).toBeDefined(); - runs.sessionStore.updateOpenDevice(ref!, { ...BOOTED_EMULATOR, booted: false }, false); - const reopened = await runs.run({ name: 'open', flags: { platform: 'android' } }); - expect(reopened.response?.ok).toBe(true); - expect(mockEnsureReadyRuntime).toHaveBeenCalledTimes(1); - expect(runs.sessionClaim().updatedAtMs).toBeGreaterThanOrEqual(LATER_BOOT_MS); - // The reopen claims the running device as its own, yet keeps the launch identity of the boot it - // caused. That is what separates this session's boot from the outside one, and no claim timestamp - // can do it: renewal restamps `updatedAtMs` to vouch for the reboot, and `createdAtMs` can - // predate either. - expect(runs.sessionStore.get(SESSION)?.androidLaunchIdentity).toEqual(OWN_GENERATION); - // Open and reopen settle their claims from the record alone, so neither has probed the device. - expect(runs.bootAsks()).toBe(0); - const closed = await runs.run({ name: 'close' }); expect(closed.response?.ok).toBe(true); - expect(closed.finalizeAsks).toEqual([{ shutdownTarget: false, retainRunner: false }]); - expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); - expect(closeWarningMessages(closed.response!)).toEqual([ - "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.", + expect(closed.finalizeAsks).toEqual([ + expect.objectContaining({ shutdownTarget: true, retainRunner: false }), ]); - if (closed.response?.ok) expect(closed.response.data).not.toHaveProperty('shutdown'); - // Close asks the device once, and only once: the implicit stop's own decision. - expect(runs.generationAsks()).toBe(1); + expect(mockShutdownTargetRuntime).toHaveBeenCalledTimes(1); + expect(closeWarningMessages(closed.response!)).toBeUndefined(); + if (closed.response?.ok) + expect(closed.response.data).toMatchObject({ shutdown: { success: true } }); + // The launched process took the shutdown it was asked for, so nothing was ever signalled by pid, + // and the session is retired with its claim like any successful close. + expect(launched.signalAttempts).toEqual([]); + expect(runs.sessionStore.get(SESSION)).toBeUndefined(); + expect(runs.sessionClaimCount()).toBe(0); }, 30_000); -test('plain close leaves an emulator rebooted outside the session running without any reopen', async () => { +test('plain close stops the launched process itself when it ignores the emulator console kill', async () => { const runs = createRoutedSession(); await openBootedByThisSession(runs); + launched.exitsOnKill = false; - runs.boot.current = REBOOTED; const closed = await runs.run({ name: 'close' }); expect(closed.response?.ok).toBe(true); - expect(closed.finalizeAsks).toEqual([{ shutdownTarget: false, retainRunner: false }]); + expect(mockShutdownTargetRuntime).toHaveBeenCalledTimes(1); + expect(closeWarningMessages(closed.response!)).toBeUndefined(); + // The escalation aims only at the process this session launched, with the identity open recorded, + // which is what host-kit requires before it signals anything. + expect(launched.signalAttempts).toEqual([{ pid: launched.pid, startTime: launched.startTime }]); +}); + +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. + launched.alive = false; + 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!)).toHaveLength(1); + expect(closeWarningMessages(closed.response!)).toEqual([PROCESS_CHANGED_WARNING]); + if (closed.response?.ok) expect(closed.response.data).not.toHaveProperty('shutdown'); + // Close reads the launched process once, and only as its own decision. + expect(launched.factReads).toBe(1); }, 30_000); -test('plain close keeps a reboot that raced the first application launch', async () => { +test('Quick Boot retains the replacement with the same serial and restored guest uptime', async () => { const runs = createRoutedSession(); - await openBootedByThisSession(runs, () => { - vi.advanceTimersByTime(LATER_BOOT_DELAY_MS); - runs.boot.current = REBOOTED; - }); + 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 start time separates the two lifetimes. + launched.liveStartTime = 'replacement-start-time'; const closed = await runs.run({ name: 'close' }); - expect(closed.response?.ok).toBe(true); - expect(closed.finalizeAsks[0]?.shutdownTarget).toBe(false); - expect(closeWarningMessages(closed.response!)).toHaveLength(1); + 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 stops the emulator this session booted while it still runs that boot', async () => { +test('plain close leaves the emulator running when a zombie answers the recorded pid', async () => { const runs = createRoutedSession(); - const ownBootMs = await openBootedByThisSession(runs); - expect(ownBootMs).toBe(CLOCK_START_MS); + await openBootedByThisSession(runs); + launched.zombie = true; - // Same case except the boot the device reports: the one this session caused. - runs.boot.current = { observed: true, bootedAtMs: ownBootMs }; const closed = await runs.run({ name: 'close' }); - expect(closed.response?.ok).toBe(true); - expect(closed.finalizeAsks).toEqual([{ shutdownTarget: true, retainRunner: false }]); - expect(mockShutdownTargetRuntime).toHaveBeenCalledTimes(1); - expect(closeWarningMessages(closed.response!)).toBeUndefined(); -}, 30_000); + 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 its host generation is unavailable', async () => { +test('plain close retains the emulator when the host will not answer for the recorded pid', async () => { const runs = createRoutedSession(); await openBootedByThisSession(runs); + launched.unreadable = true; - runs.generation.current = undefined; const closed = await runs.run({ name: 'close' }); expect(closed.response?.ok).toBe(true); - expect(closed.finalizeAsks).toEqual([{ shutdownTarget: false, retainRunner: false }]); + expect(closed.finalizeAsks).toEqual([ + expect.objectContaining({ shutdownTarget: false, retainRunner: false }), + ]); expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); - expect(closeWarningMessages(closed.response!)).toHaveLength(1); + expect(closeWarningMessages(closed.response!)).toEqual([PROCESS_UNVERIFIED_WARNING]); + expect(launched.signalAttempts).toEqual([]); }, 30_000); -test('plain close stops the emulator its own open booted even when the claim long predates that boot', async () => { +test('missing launch identity does not acquire ownership from a later process read', async () => { const runs = createRoutedSession(); - vi.useFakeTimers({ toFake: ['Date'] }); - vi.setSystemTime(CLOCK_START_MS); - // A previous session of this same name, workspace and daemon left its claim behind, so this - // session's open renews that claim instead of taking a new one. Its creation time belongs to the - // earlier session and describes nothing about the boot about to happen. - await runs.plantPriorClaim(); - vi.advanceTimersByTime(PRIOR_CLAIM_GAP_MS); - - const ownBootMs = CLOCK_START_MS + PRIOR_CLAIM_GAP_MS; const opened = await runs.run({ name: 'open', flags: { platform: 'android' }, selectsDevice: true, + omitLaunchIdentity: true, }); expect(opened.response?.ok).toBe(true); - expect(runs.sessionStore.get(SESSION)?.bootedByOpen).toBe(true); - expect(runs.sessionClaim().createdAtMs).toBe(CLOCK_START_MS); - // The emulator reports the boot THIS open caused, which is what an uptime probe answers. - runs.boot.current = { observed: true, bootedAtMs: ownBootMs }; const closed = await runs.run({ name: 'close' }); - // The session still owns the boot the device is running, so it still owes the stop. - expect(closed.response?.ok).toBe(true); - expect(closed.finalizeAsks).toEqual([{ shutdownTarget: true, retainRunner: false }]); - expect(mockShutdownTargetRuntime).toHaveBeenCalledTimes(1); - expect(closeWarningMessages(closed.response!)).toBeUndefined(); -}, 30_000); + expect(closed.finalizeAsks).toEqual([ + expect.objectContaining({ shutdownTarget: false, retainRunner: false }), + ]); + expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); + // Nothing was recorded, so close has no pid to read and asks the host nothing. + expect(launched.factReads).toBe(0); + expect(closeWarningMessages(closed.response!)).toEqual([NO_LAUNCH_IDENTITY_WARNING]); +}); -test('close --shutdown stops a rebooted emulator and asks the device nothing', async () => { +test('close --shutdown stops the device and never signals the launched process', async () => { const runs = createRoutedSession(); await openBootedByThisSession(runs); - runs.boot.current = REBOOTED; - const asksAfterOpen = runs.generationAsks(); + launched.alive = false; + launched.exitsOnKill = false; const closed = await runs.run({ name: 'close', flags: { shutdown: true } }); expect(closed.response?.ok).toBe(true); - expect(closed.finalizeAsks).toEqual([{ shutdownTarget: true, retainRunner: false }]); + expect(closed.finalizeAsks).toEqual([ + expect.objectContaining({ shutdownTarget: true, retainRunner: false }), + ]); expect(mockShutdownTargetRuntime).toHaveBeenCalledTimes(1); - expect(runs.generationAsks()).toBe(asksAfterOpen); expect(closeWarningMessages(closed.response!)).toBeUndefined(); + expect(launched.signalAttempts).toEqual([]); }, 30_000); -test('a failed generation probe keeps the emulator running', async () => { - const runs = createRoutedSession((device) => - Promise.reject(new Error(`adb is gone: ${device.id}`)), - ); - await openBootedByThisSession(runs); - - const closed = await runs.run({ name: 'close' }); - - expect(closed.response?.ok).toBe(true); - expect(closed.finalizeAsks).toEqual([{ shutdownTarget: false, retainRunner: false }]); - expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); - expect(closeWarningMessages(closed.response!)).toHaveLength(1); -}, 30_000); - -test('close reaches no device or session step when it asks the boot observation', async () => { - const runs = createRoutedSession(); - await openBootedByThisSession(runs); - runs.boot.current = REBOOTED; - - const closed = await runs.run({ name: 'close' }); - - // The probe is the close's first step and the only one it adds: the lifecycle ask sees the - // decision it produced, and the session is retired as any successful close retires it. - expect(closed.finalizeAsks).toEqual([{ shutdownTarget: false, retainRunner: false }]); - expect(runs.generationAsks()).toBe(1); - expect(runs.sessionStore.get(SESSION)).toBeUndefined(); - expect(runs.sessionClaimCount()).toBe(0); -}, 30_000); - -test('a policy refusal stays the reported reason when the emulator was rebooted as well', async () => { +test('a policy refusal stays the reported reason and reads no process', async () => { const runs = createRoutedSession(); await openBootedByThisSession(runs); - runs.boot.current = REBOOTED; - const asksBeforeClose = runs.generationAsks(); const closed = await runs.run({ name: 'close', deviceShutdownDenied: true }); expect(closed.response?.ok).toBe(true); - expect(closed.finalizeAsks).toEqual([{ shutdownTarget: false, retainRunner: false }]); + 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(runs.generationAsks()).toBe(asksBeforeClose); + expect(launched.factReads).toBe(0); }, 30_000); -test('a lost claim stays the reported reason when the emulator was rebooted as well', async () => { +test('a lost claim stays the reported reason and reads no process', async () => { const runs = createRoutedSession(); await openBootedByThisSession(runs); - runs.boot.current = REBOOTED; await runs.dropSessionClaim(); - const asksBeforeClose = runs.generationAsks(); const closed = await runs.run({ name: 'close' }); expect(closed.response?.ok).toBe(true); - expect(closed.finalizeAsks).toEqual([{ shutdownTarget: false, retainRunner: false }]); + 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.", ]); - // Losing the claim settles the stop without reaching the device, so the reboot adds nothing. - expect(runs.generationAsks()).toBe(asksBeforeClose); + expect(launched.factReads).toBe(0); }, 30_000); -test('Quick Boot retains the replacement with the same serial and restored guest uptime', async () => { - const runs = createRoutedSession(); - await openBootedByThisSession(runs); - runs.boot.current = { observed: true, bootedAtMs: CLOCK_START_MS - 80_000 }; - runs.generation.current = NEXT_GENERATION; - const closed = await runs.run({ name: 'close' }); - expect(closed.finalizeAsks[0]?.shutdownTarget).toBe(false); - expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); - expect(closeWarningMessages(closed.response!)).toHaveLength(1); -}); - -test('missing launch identity does not acquire ownership from a later observation', 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[0]?.shutdownTarget).toBe(false); - expect(runs.generationAsks()).toBe(0); - expect(closeWarningMessages(closed.response!)).toEqual([ - "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.", - ]); -}); - test('changing the device serial clears launch ownership', async () => { const runs = createRoutedSession(); await openBootedByThisSession(runs); @@ -514,25 +390,3 @@ test('changing the device serial clears launch ownership', async () => { expect(runs.sessionStore.get(SESSION)?.androidLaunchIdentity).toBeUndefined(); expect(runs.sessionStore.get(SESSION)?.bootedByOpen).toBeUndefined(); }); - -test.each(['changed', 'unobserved'] as const)( - 'close reports %s when generation changes during cleanup', - async (outcome) => { - const runs = createRoutedSession(); - await openBootedByThisSession(runs); - const closed = await runs.run({ - name: 'close', - beforeFinalization: () => { - runs.generation.current = outcome === 'changed' ? NEXT_GENERATION : undefined; - }, - }); - expect(closed.response?.ok).toBe(true); - expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); - expect(closeWarningMessages(closed.response!)).toEqual([ - outcome === 'changed' - ? "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." - : "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.", - ]); - if (closed.response?.ok) expect(closed.response.data).not.toHaveProperty('shutdown'); - }, -); 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 index 37b42bdd5f..8f964a9ec5 100644 --- 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 @@ -1,5 +1,5 @@ import { daemonPlatformServicesFixture } from '../../../../__tests__/support/platform-services-fixture.ts'; -import { beforeEach, expect, test } from 'vitest'; +import { beforeEach, expect, test, vi } from 'vitest'; import { sessionCloseShutdownFixture, type SessionState, @@ -17,6 +17,20 @@ import { clearDeviceClaim, inspectDeviceClaims, } from '@agent-device/daemon-contracts/device-claims'; +import { + launchedEmulatorProcess, + resetLaunchedEmulatorProcess, +} from '../../../../__tests__/support/launched-emulator-process-fixture.ts'; + +// The host's answers about the emulator process an `open` launched are modelled, so an Android case +// can settle its close without touching the real process table. +vi.mock('@agent-device/host-kit/process', async (importOriginal) => { + const { launchedEmulatorProcessHost } = + await import('../../../../__tests__/support/launched-emulator-process-fixture.ts'); + return launchedEmulatorProcessHost( + await importOriginal(), + ); +}); bindTestCommandHost(); @@ -31,7 +45,10 @@ const { resetSessionCloseShutdownMocks, } = sessionCloseShutdownFixture; -beforeEach(resetSessionCloseShutdownMocks); +beforeEach(() => { + resetSessionCloseShutdownMocks(); + resetLaunchedEmulatorProcess(); +}); const iosSimulator: SessionState['device'] = { platform: 'apple', @@ -70,7 +87,11 @@ async function closeSession(params: { const sessionStore = makeSessionStore(); const session = makeSession(sessionName, device); if (bootedByOpen) session.bootedByOpen = bootedByOpen; - session.androidLaunchIdentity = { pid: 42, startTime: 'start' }; + if (device.platform === 'android') + session.androidLaunchIdentity = { + pid: launchedEmulatorProcess.pid, + startTime: launchedEmulatorProcess.startTime, + }; if (bootedByOpen) { const claimInput = { env: host.env, @@ -107,7 +128,6 @@ async function closeSession(params: { platformServices: daemonPlatformServicesFixture({ deviceBootObservation: { observeBootTimeMs: async () => ({ observed: false, reason: 'unobserved' }), - assessShutdownGeneration: async () => 'same' as const, }, }), ...(params.lifecycleOperationsLoader diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-close-emulator-process.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-close-emulator-process.ts new file mode 100644 index 0000000000..775a9b4824 --- /dev/null +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-close-emulator-process.ts @@ -0,0 +1,63 @@ +// #4585: a plain `close` owes a stop to the boot its own `open` caused, and on Android the host +// half of that boot is one emulator process this daemon launched and recorded. This module is the +// one owner of the rule that names that process: read it, and stop nothing else. +import type { AndroidEmulatorLaunchIdentity } from '@agent-device/contracts/device-readiness-runtime'; +import { + isProcessAlive, + processStartTimesDiffer, + readProcessIdentityFacts, + stopProcessAndConfirmExit, + waitForProcessExit, +} from '@agent-device/host-kit/process'; + +/** + * What the host says about the launched emulator process, read once immediately before a stop. + * `same` is the only answer that lets the stop proceed: `changed` is positive evidence that the + * recorded process is gone, so whoever answers the serial now is not this session's launch, and + * `unverified` means the host could not name the live process at all. + */ +export type AndroidEmulatorProcessCheck = 'same' | 'changed' | 'unverified'; + +/** + * {@link AndroidEmulatorProcessCheck} for one recorded launch, from one `ps` of the recorded pid. + * Liveness is read separately from the start time because a reaped process leaves no `ps` row, and + * only `kill(pid, 0)` tells that apart from a `ps` read that failed. + */ +export async function checkAndroidEmulatorProcess( + identity: AndroidEmulatorLaunchIdentity, +): Promise { + let facts: Awaited>; + try { + facts = await readProcessIdentityFacts(identity.pid); + } 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 process took the shutdown it was asked for 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 confirmAndroidEmulatorProcessStopped( + identity: AndroidEmulatorLaunchIdentity, +): Promise<'stopped' | 'unconfirmed'> { + 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'; +} + +/** + * 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/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 b176440c8d..c9bcc769a0 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,13 +2,18 @@ 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 { DeviceShutdownGenerationService } 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'; import { SessionStore } from '../../../core/session-store.ts'; +import { + checkAndroidEmulatorProcess, + confirmAndroidEmulatorProcessStopped, + type AndroidEmulatorProcessCheck, +} from './session-close-emulator-process.ts'; import { cleanupRetainedMaterializedPathsForSession } from '../../materialized-path-registry.ts'; import { reportSessionCleanupFailures, @@ -40,12 +45,17 @@ type CloseDeviceStopDecision = Readonly<{ implicitShutdownDeniedByPolicy: boolean; implicitShutdownClaimLost: boolean; /** - * #4585: the close owned stopping the device its own `open` booted, but the device has been - * through a boot this session never described since that open, so the running device is not the - * one this session started and the implicit stop is withheld. The close itself succeeded. + * #4585: the emulator process this session's `open` launched is not running any more, so whoever + * answers that serial 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 emulator 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 pid. */ - implicitShutdownDeviceRebooted: boolean; - implicitShutdownGenerationUnobserved: boolean; + implicitShutdownLaunchedProcessUnverified: boolean; }>; export type SessionCloseTeardownResult = Readonly<{ @@ -64,11 +74,12 @@ export type SessionCloseTeardownResult = Readonly<{ * 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: a stop this session owes its own open is a stop owed to the boot that open caused, so the - * the Android host generation is checked only once the stop is otherwise owed. An - * explicit `--shutdown` commands the stop whatever the device says, and a lost claim or a policy - * refusal has already decided it without reaching the device. Each reason is reported as itself and - * in this order: what settled the stop first is the only reason close can honestly give. + * #4585: on Android, the stop this session owes is owed to the emulator PROCESS its own open + * launched, not to whatever answers that serial now, so the recorded process is checked once, right + * before the stop is asked for. 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. Each + * reason is reported as itself and in this order: what settled the stop first is the only reason + * close can honestly give. */ async function decideDeviceStopOnClose(params: { env: EnvMap; @@ -76,7 +87,6 @@ async function decideDeviceStopOnClose(params: { session: SessionState; localFamily: boolean; deviceShutdownDenied: boolean; - observeDeviceBoot: DeviceShutdownGenerationService; }): Promise { const { session } = params; const implicitShutdown = @@ -87,29 +97,74 @@ async function decideDeviceStopOnClose(params: { const implicitShutdownClaimLost = claimRenewal?.status === 'lost'; const implicitShutdownDeniedByPolicy = implicitShutdown && !implicitShutdownClaimLost && params.deviceShutdownDenied; - const generation = + const launchedProcess = implicitShutdown && !implicitShutdownDeniedByPolicy && claimRenewal?.status === 'renewed' - ? await params.observeDeviceBoot - .assessShutdownGeneration(session.device, session.androidLaunchIdentity) - .catch(() => 'unobserved' as const) + ? await checkLaunchedAndroidEmulatorProcess(session) : 'not-applicable'; - const implicitShutdownDeviceRebooted = generation === 'changed'; - const implicitShutdownGenerationUnobserved = generation === 'unobserved'; + const implicitShutdownLaunchedProcessGone = launchedProcess === 'changed'; + const implicitShutdownLaunchedProcessUnverified = launchedProcess === 'unverified'; return { shutdownRequested: params.explicitShutdown || (implicitShutdown && !implicitShutdownDeniedByPolicy && - !implicitShutdownDeviceRebooted && - !implicitShutdownGenerationUnobserved && + !implicitShutdownLaunchedProcessGone && + !implicitShutdownLaunchedProcessUnverified && claimRenewal?.status === 'renewed'), implicitShutdownDeniedByPolicy, implicitShutdownClaimLost, - implicitShutdownDeviceRebooted, - implicitShutdownGenerationUnobserved, + implicitShutdownLaunchedProcessGone, + implicitShutdownLaunchedProcessUnverified, }; } +/** + * Whether the emulator process this session's open launched still runs the device it booted. Only + * the Android emulator has a host process this daemon launched to check; every other device is + * stopped by the platform answer alone, so this reports `not-applicable` rather than a miss. + */ +async function checkLaunchedAndroidEmulatorProcess( + session: SessionState, +): Promise { + if (session.device.platform !== 'android' || session.device.kind !== 'emulator') + return 'not-applicable'; + const identity = session.androidLaunchIdentity; + if (!identity) { + emitAndroidLaunchIdentityMiss('open-recorded-no-process'); + return 'unverified'; + } + const check = await checkAndroidEmulatorProcess(identity); + if (check !== 'same') + emitAndroidLaunchIdentityMiss(`process-check-${check}`, { pid: identity.pid }); + return check; +} + +/** + * Step 3 of the implicit Android stop: the platform asked the emulator to shut itself down through + * `adb emu kill`, so confirm the process this session launched actually left. One that ignores the + * kill is stopped by pid, and host-kit refuses a pid that no longer carries the recorded start time. + */ +async function confirmLaunchedAndroidEmulatorStopped(session: SessionState): Promise { + if (session.device.platform !== 'android' || session.device.kind !== 'emulator') return; + const identity = session.androidLaunchIdentity; + if (!identity) return; + if ((await confirmAndroidEmulatorProcessStopped(identity)) === 'unconfirmed') + emitAndroidLaunchIdentityMiss('launched-process-stop-unconfirmed', { pid: identity.pid }); +} + +/** + * The one diagnostic for a session whose close could not settle the state of the emulator 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 emitAndroidLaunchIdentityMiss(step: string, data: Record = {}): void { + emitDiagnostic({ + level: 'warn', + phase: 'android_launch_identity_miss', + data: { step, ...data }, + }); +} + /** Runs owned resources, native close, native hint cleanup, and final lifecycle disposal. */ export async function runSessionCloseTeardown(params: { env: EnvMap; @@ -131,7 +186,6 @@ export async function runSessionCloseTeardown(params: { }): OrdinaryCloseScript; platformResourceCleanup: PlatformResourceCleanup; deviceShutdownDenied?: boolean; - observeDeviceBoot: DeviceShutdownGenerationService; }): Promise { const { req, @@ -165,10 +219,8 @@ export async function runSessionCloseTeardown(params: { session, localFamily: lifecycle.owner.kind === 'local-family', deviceShutdownDenied: params.deviceShutdownDenied === true, - observeDeviceBoot: params.observeDeviceBoot, }); const { shutdownRequested, ...stopReasons } = deviceStop; - const expectedAndroidLaunchIdentity = session.androidLaunchIdentity; const retainExecutionHost = params.platformResourceCleanup.retainExecutionHostAfterClose({ device: session.device, shutdownRequested, @@ -212,20 +264,14 @@ export async function runSessionCloseTeardown(params: { retainRunner: retainExecutionHost, stateDir: sessionStore.resolveDaemonStateDir(), shutdownTarget: shutdownRequested && lifecycle.owner.kind === 'local-family', - ...(shutdownRequested && req.flags?.shutdown !== true - ? { - verifyAndroidShutdown: async () => { - const generation = await params.observeDeviceBoot - .assessShutdownGeneration(session.device, expectedAndroidLaunchIdentity) - .catch(() => 'unobserved' as const); - return generation === 'same' || generation === 'changed' - ? generation - : ('unobserved' as const); - }, - } - : {}), })) ?? {}, ); + // 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. + if (shutdownRequested && req.flags?.shutdown !== true) + await confirmLaunchedAndroidEmulatorStopped(session); const saveScriptOutcome = repairArmed ? {} : finalizeOrdinaryCloseScript({ req, ref, sessionStore, platformCloseError }); @@ -239,12 +285,6 @@ export async function runSessionCloseTeardown(params: { shutdownResult: finalization?.shutdown, shutdownPrepared: finalization !== undefined, ...stopReasons, - implicitShutdownDeviceRebooted: - stopReasons.implicitShutdownDeviceRebooted || - finalization?.androidShutdownRetained === 'changed', - implicitShutdownGenerationUnobserved: - stopReasons.implicitShutdownGenerationUnobserved || - finalization?.androidShutdownRetained === 'unobserved', }; } 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 432342fc38..d12366fb42 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts @@ -1,7 +1,6 @@ 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 { DeviceShutdownGenerationService } 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'; @@ -358,7 +357,6 @@ export async function handleSessionCloseCommands( clearRuntimeHints: admission.clearRuntimeHints, repairArmed: repair.repairArmed, platformResourceCleanup, - observeDeviceBoot: params.platformServices.deviceBootObservation, deviceShutdownDenied: params.deviceShutdownDenied, }), ); @@ -371,8 +369,8 @@ export async function handleSessionCloseCommands( providerData: closed.providerData, implicitShutdownDeniedByPolicy: closed.implicitShutdownDeniedByPolicy, implicitShutdownClaimLost: closed.implicitShutdownClaimLost, - implicitShutdownDeviceRebooted: closed.implicitShutdownDeviceRebooted, - implicitShutdownGenerationUnobserved: closed.implicitShutdownGenerationUnobserved, + implicitShutdownLaunchedProcessGone: closed.implicitShutdownLaunchedProcessGone, + implicitShutdownLaunchedProcessUnverified: closed.implicitShutdownLaunchedProcessUnverified, }); return remoteCloseScriptDelivery(response, closed.remoteScript); } @@ -406,8 +404,8 @@ type SessionCloseFinalization = implicitShutdownDeniedByPolicy: boolean; implicitShutdownClaimLost: boolean; /** #4585: the device has been rebooted outside this session since its open, so close left it running. */ - implicitShutdownDeviceRebooted: boolean; - implicitShutdownGenerationUnobserved: boolean; + implicitShutdownLaunchedProcessGone: boolean; + implicitShutdownLaunchedProcessUnverified: boolean; }; // Everything between a settled repair decision and a success response: @@ -429,8 +427,6 @@ async function runCloseTeardownAndRelease(params: { repairArmed: boolean; platformResourceCleanup: PlatformResourceCleanup; deviceShutdownDenied?: boolean; - /** Boot observation for the implicit stop's #4585 check, forwarded to the teardown. */ - observeDeviceBoot: DeviceShutdownGenerationService; }): Promise { const { req, @@ -452,8 +448,8 @@ async function runCloseTeardownAndRelease(params: { shutdownResult, implicitShutdownDeniedByPolicy, implicitShutdownClaimLost, - implicitShutdownDeviceRebooted, - implicitShutdownGenerationUnobserved, + implicitShutdownLaunchedProcessGone, + implicitShutdownLaunchedProcessUnverified, } = await runSessionCloseTeardown({ env: params.env, leaseRegistry, @@ -469,7 +465,6 @@ async function runCloseTeardownAndRelease(params: { finalizeOrdinaryCloseScript, platformResourceCleanup: params.platformResourceCleanup, deviceShutdownDenied: params.deviceShutdownDenied, - observeDeviceBoot: params.observeDeviceBoot, }); let session = sessionStore.requireCurrent(ref); // Each cleanup report is built where the session's fate is decided, so its diagnostic and hint @@ -518,8 +513,8 @@ async function runCloseTeardownAndRelease(params: { remoteScript: saveScriptOutcome.remote, implicitShutdownDeniedByPolicy, implicitShutdownClaimLost, - implicitShutdownDeviceRebooted, - implicitShutdownGenerationUnobserved, + implicitShutdownLaunchedProcessGone, + implicitShutdownLaunchedProcessUnverified, }; } @@ -531,8 +526,8 @@ function buildCloseSuccessResponse(params: { providerData: Record | undefined; implicitShutdownDeniedByPolicy: boolean; implicitShutdownClaimLost: boolean; - implicitShutdownDeviceRebooted: boolean; - implicitShutdownGenerationUnobserved: boolean; + implicitShutdownLaunchedProcessGone: boolean; + implicitShutdownLaunchedProcessUnverified: boolean; }): DaemonResponse { const { session, @@ -542,8 +537,8 @@ function buildCloseSuccessResponse(params: { providerData, implicitShutdownDeniedByPolicy, implicitShutdownClaimLost, - implicitShutdownDeviceRebooted, - implicitShutdownGenerationUnobserved, + implicitShutdownLaunchedProcessGone, + implicitShutdownLaunchedProcessUnverified, } = params; if (repair.aborted && requestedSaveScript) { return { @@ -582,16 +577,16 @@ function buildCloseSuccessResponse(params: { "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 a stop owed to the boot its own open caused. The device - // has since been through a boot this session never described, so stopping it now would stop - // someone else's device. Say which device close left running, and why. - if (implicitShutdownDeviceRebooted) { + // #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 (implicitShutdownGenerationUnobserved) { + if (implicitShutdownLaunchedProcessUnverified) { appendResponseWarning( data, session.androidLaunchIdentity diff --git a/packages/platform-android/src/device-boot-generation.test.ts b/packages/platform-android/src/device-boot-generation.test.ts deleted file mode 100644 index 5eec8d0873..0000000000 --- a/packages/platform-android/src/device-boot-generation.test.ts +++ /dev/null @@ -1,153 +0,0 @@ -import { beforeEach, expect, test, vi } from 'vitest'; -import type { DeviceInfo } from '@agent-device/kernel/device'; - -const mocks = vi.hoisted(() => ({ - runCmd: vi.fn(), - readProcessIdentityFacts: vi.fn(), - hostPlatform: vi.fn(), -})); -vi.mock('@agent-device/host-kit/command', () => ({ runCmd: mocks.runCmd })); -vi.mock('@agent-device/host-kit/process', () => ({ - readProcessIdentityFacts: mocks.readProcessIdentityFacts, - hostPlatform: mocks.hostPlatform, -})); - -import { - inspectAndroidEmulatorGeneration, - readAndroidEmulatorLaunchStartTime, -} from './device-boot.ts'; - -const observeAndroidEmulatorGeneration = async ( - ...args: Parameters -) => { - const reading = await inspectAndroidEmulatorGeneration(...args); - return 'identity' in reading ? reading.identity : undefined; -}; - -const device: DeviceInfo = { - platform: 'android', - kind: 'emulator', - id: 'emulator-5558', - name: 'Pixel', -}; - -beforeEach(() => { - vi.resetAllMocks(); - // `lsof -b -w -t` prints the listening process id once, even for IPv4 and IPv6 sockets. - mocks.runCmd.mockResolvedValue({ exitCode: 0, stdout: '42\n', stderr: '' }); - mocks.readProcessIdentityFacts.mockResolvedValue({ startTime: 'start', zombie: false }); - mocks.hostPlatform.mockReturnValue('darwin'); -}); - -const slowRead = () => Promise.reject(new Error('lsof timed out after 5000ms')); - -test('observes only the listener on the admitted console port without blocking kernel calls', async () => { - expect(await observeAndroidEmulatorGeneration(device)).toEqual({ pid: 42, startTime: 'start' }); - expect(mocks.runCmd).toHaveBeenCalledWith( - 'lsof', - ['-b', '-w', '-t', '-nP', '-iTCP:5558', '-sTCP:LISTEN'], - expect.objectContaining({ allowFailure: true, timeoutMs: 5_000 }), - ); -}); - -test('a slow listener read is retried once and still observes the identity', async () => { - mocks.runCmd.mockImplementationOnce(slowRead); - expect(await observeAndroidEmulatorGeneration(device)).toEqual({ pid: 42, startTime: 'start' }); - expect(mocks.runCmd).toHaveBeenCalledTimes(2); -}); - -test('a slow process identity read is retried once', async () => { - mocks.readProcessIdentityFacts.mockResolvedValueOnce({ startTime: null, zombie: null }); - expect(await observeAndroidEmulatorGeneration(device)).toEqual({ pid: 42, startTime: 'start' }); - expect(mocks.runCmd).toHaveBeenCalledTimes(2); -}); - -test('two slow reads remain unknown', async () => { - mocks.runCmd.mockImplementation(slowRead); - expect(await observeAndroidEmulatorGeneration(device)).toBeUndefined(); - expect(mocks.runCmd).toHaveBeenCalledTimes(2); -}); - -test('no listener answers at once without a retry', async () => { - mocks.runCmd.mockResolvedValueOnce({ exitCode: 1, stdout: '', stderr: '' }); - expect(await observeAndroidEmulatorGeneration(device)).toBeUndefined(); - expect(mocks.runCmd).toHaveBeenCalledTimes(1); - expect(mocks.readProcessIdentityFacts).not.toHaveBeenCalled(); -}); - -test('ambiguous listeners, a malformed pid and a zombie remain unknown without a retry', async () => { - mocks.runCmd.mockResolvedValueOnce({ exitCode: 0, stdout: '42\n43\n', stderr: '' }); - expect(await observeAndroidEmulatorGeneration(device)).toBeUndefined(); - mocks.runCmd.mockResolvedValueOnce({ exitCode: 0, stdout: '0\n', stderr: '' }); - expect(await observeAndroidEmulatorGeneration(device)).toBeUndefined(); - expect(mocks.readProcessIdentityFacts).not.toHaveBeenCalled(); - mocks.readProcessIdentityFacts.mockResolvedValueOnce({ startTime: 'start', zombie: true }); - expect(await observeAndroidEmulatorGeneration(device)).toBeUndefined(); - expect(mocks.runCmd).toHaveBeenCalledTimes(3); -}); - -test('physical and malformed targets do not inspect host processes', async () => { - expect(await observeAndroidEmulatorGeneration({ ...device, kind: 'device' })).toBeUndefined(); - expect( - await observeAndroidEmulatorGeneration({ ...device, id: 'emulator-5558:other' }), - ).toBeUndefined(); - expect(mocks.runCmd).not.toHaveBeenCalled(); -}); - -test('Linux reads the listener without -b, which can stop the port filter matching through /proc', async () => { - mocks.hostPlatform.mockReturnValue('linux'); - expect(await observeAndroidEmulatorGeneration(device)).toEqual({ pid: 42, startTime: 'start' }); - expect(mocks.runCmd).toHaveBeenCalledWith( - 'lsof', - ['-t', '-nP', '-iTCP:5558', '-sTCP:LISTEN'], - expect.objectContaining({ timeoutMs: 5_000 }), - ); -}); - -test('a shared deadline caps each read and stops reads once it is spent', async () => { - const remaining = [3_000, 0]; - const deadline = { - remainingMs: () => remaining.shift() ?? 0, - elapsedMs: () => 0, - isExpired: () => false, - }; - mocks.runCmd.mockImplementationOnce(slowRead); - expect(await observeAndroidEmulatorGeneration(device, { deadline })).toBeUndefined(); - expect(mocks.runCmd).toHaveBeenCalledTimes(1); - expect(mocks.runCmd).toHaveBeenCalledWith( - 'lsof', - expect.any(Array), - expect.objectContaining({ timeoutMs: 3_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('the process read gets only what the shared deadline still has', async () => { - const remaining = [5_000, 1_200]; - const deadline = { - remainingMs: () => remaining.shift() ?? 0, - elapsedMs: () => 0, - isExpired: () => false, - }; - expect(await observeAndroidEmulatorGeneration(device, { deadline })).toEqual({ - pid: 42, - startTime: 'start', - }); - expect(mocks.readProcessIdentityFacts).toHaveBeenCalledWith(42, 1_200); -}); 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..ebb3a22950 --- /dev/null +++ b/packages/platform-android/src/device-boot-launch.test.ts @@ -0,0 +1,43 @@ +import { beforeEach, expect, test, vi } from 'vitest'; + +const mocks = vi.hoisted(() => ({ + readProcessIdentityFacts: vi.fn(), +})); +vi.mock('@agent-device/host-kit/process', () => ({ + readProcessIdentityFacts: mocks.readProcessIdentityFacts, +})); + +import { readAndroidEmulatorLaunchStartTime } from './device-boot.ts'; + +beforeEach(() => { + vi.resetAllMocks(); + mocks.readProcessIdentityFacts.mockResolvedValue({ startTime: 'start', zombie: false }); +}); + +test('reads the launch start time the process read answers with', async () => { + expect(await readAndroidEmulatorLaunchStartTime(4242)).toBe('start'); + 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); +}); diff --git a/packages/platform-android/src/device-boot.ts b/packages/platform-android/src/device-boot.ts index 46621622fc..e3c41286df 100644 --- a/packages/platform-android/src/device-boot.ts +++ b/packages/platform-android/src/device-boot.ts @@ -1,58 +1,15 @@ import type { DeviceBootObservation } 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 type { DeadlineClock } from '@agent-device/host-kit/retry'; - -/** Why one observation of the emulator console listener produced no identity. */ -export type AndroidEmulatorGenerationMiss = - | 'no-listener' - | 'ambiguous-listener' - | 'zombie-listener' - | 'listener-read-timeout' - | 'process-read-timeout' - | 'deadline-spent'; - -export type AndroidEmulatorGenerationReading = - | Readonly<{ identity: AndroidEmulatorLaunchIdentity }> - | Readonly<{ miss: AndroidEmulatorGenerationMiss }>; - -/** - * Observe the process listening on the ADB emulator console port without contacting it, with the - * reason a read produced no identity. A caller that observes more than once passes one deadline, - * so all reads share one bounded budget. - */ -export async function inspectAndroidEmulatorGeneration( - device: DeviceInfo, - options: { deadline?: DeadlineClock } = {}, -): Promise { - if (device.platform !== 'android' || device.kind !== 'emulator') return { miss: 'no-listener' }; - const match = /^emulator-(\d+)$/.exec(device.id); - const port = Number(match?.[1]); - if (!match || !Number.isInteger(port) || port < 1 || port > 65535) return { miss: 'no-listener' }; - let last: AndroidEmulatorGenerationMiss = 'deadline-spent'; - for (let attempt = 1; attempt <= LISTENER_PROBE_ATTEMPTS; attempt += 1) { - const budgetMs = Math.min( - LISTENER_PROBE_TIMEOUT_MS, - options.deadline?.remainingMs() ?? LISTENER_PROBE_TIMEOUT_MS, - ); - if (budgetMs <= 0) return { miss: last }; - const reading = await readConsoleListener(port, budgetMs, options.deadline); - if (reading.kind === 'identity') return { identity: reading.identity }; - if (reading.kind === 'absent') return { miss: reading.miss }; - last = reading.miss; - } - return { miss: last }; -} /** - * Read the start time of an emulator process this host just launched. It uses the same budget and - * retry as the console listener read, so a slow `ps` under load still records the launch identity. + * 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 <= LISTENER_PROBE_ATTEMPTS; attempt += 1) { + for (let attempt = 1; attempt <= LAUNCH_START_TIME_ATTEMPTS; attempt += 1) { try { - const facts = await readProcessIdentityFacts(pid, LISTENER_PROBE_TIMEOUT_MS); + const facts = await readProcessIdentityFacts(pid, LAUNCH_START_TIME_TIMEOUT_MS); if (facts.startTime) return facts.startTime; if (facts.zombie === true) return null; } catch { @@ -62,85 +19,12 @@ export async function readAndroidEmulatorLaunchStartTime(pid: number): Promise { - const { hostPlatform, readProcessIdentityFacts } = await import('@agent-device/host-kit/process'); - if (hostPlatform() !== 'darwin' && hostPlatform() !== 'linux') { - return { kind: 'absent', miss: 'no-listener' }; - } - let stdout: string; - try { - const { runCmd } = await import('@agent-device/host-kit/command'); - const nonBlocking = hostPlatform() === 'darwin' ? ['-b', '-w'] : []; - const result = await runCmd( - 'lsof', - [...nonBlocking, '-t', '-nP', `-iTCP:${port}`, '-sTCP:LISTEN'], - { allowFailure: true, timeoutMs: budgetMs }, - ); - if (result.exitCode !== 0) return { kind: 'absent', miss: 'no-listener' }; - stdout = result.stdout; - } catch { - return { kind: 'unread', miss: 'listener-read-timeout' }; - } - const pid = soleListenerPid(stdout); - if (pid === undefined) return { kind: 'absent', miss: 'ambiguous-listener' }; - // The ps read gets only what the shared deadline still has, so lsof and ps together stay inside it. - const processBudgetMs = Math.min(budgetMs, deadline?.remainingMs() ?? budgetMs); - if (processBudgetMs <= 0) return { kind: 'unread', miss: 'process-read-timeout' }; - try { - const facts = await readProcessIdentityFacts(pid, processBudgetMs); - if (facts.zombie === true) return { kind: 'absent', miss: 'zombie-listener' }; - if (!facts.startTime || facts.zombie !== false) { - return { kind: 'unread', miss: 'process-read-timeout' }; - } - return { kind: 'identity', identity: { pid, startTime: facts.startTime } }; - } catch { - return { kind: 'unread', miss: 'process-read-timeout' }; - } -} - -function soleListenerPid(stdout: string): number | undefined { - const pids = new Set( - stdout - .split(/\r?\n/) - .map((line) => line.trim()) - .filter((line) => line.length > 0), - ); - if (pids.size !== 1) return undefined; - const [value] = pids; - if (!/^[1-9]\d*$/.test(value ?? '')) return undefined; - const pid = Number(value); - return Number.isSafeInteger(pid) ? pid : undefined; -} - -/** - * Under heavy host load one listener read took up to 4.2 s. Each attempt gets 5 s, and a read that - * did not answer is tried once more, so a slow host still binds and verifies the launch identity. - */ -const LISTENER_PROBE_TIMEOUT_MS = 5_000; -const LISTENER_PROBE_ATTEMPTS = 2; - /** - * One budget for the two agreeing observations that bind or verify a launch identity. Open and - * close each spend at most this long on the probe. + * 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. */ -export const ANDROID_EMULATOR_GENERATION_BUDGET_MS = 10_000; +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; diff --git a/packages/platform-android/src/lifecycle.test.ts b/packages/platform-android/src/lifecycle.test.ts index af6347dd3d..8ec48f2a55 100644 --- a/packages/platform-android/src/lifecycle.test.ts +++ b/packages/platform-android/src/lifecycle.test.ts @@ -58,7 +58,7 @@ function createLifecycle( device: DeviceInfo, input: Readonly<{ stateDir: string; shutdownTarget: boolean; signal: AbortSignal }>, ) => Promise; - shutdownTarget?: (...args: unknown[]) => Promise; + shutdownTarget?: () => Promise; close?: Interactor['close']; }> = {}, ): LifecycleFixture { @@ -95,8 +95,7 @@ function createLifecycle( }, deviceShutdown: { android: { - shutdownTarget: async (...args: unknown[]) => - await (params.shutdownTarget?.(...args) ?? Promise.resolve(undefined)), + shutdownTarget: async () => await (params.shutdownTarget?.() ?? Promise.resolve(undefined)), }, }, androidApplications: { @@ -479,27 +478,6 @@ test('close --shutdown restores the keyboard and only then kills the emulator (# expect(result.shutdown).toMatchObject({ success: true }); }); -test('finalization forwards verification after restoring IME and returns retention', async () => { - const events: string[] = []; - const verify = async () => 'changed' as const; - const { lifecycle } = createLifecycle({ - restoreTestIme: async () => { - events.push('restore'); - }, - shutdownTarget: async (_device, _signal, received) => { - events.push('shutdown'); - expect(received).toBe(verify); - return { retained: await (received as typeof verify)() }; - }, - }); - await expect( - lifecycle.finalizeApplicationClose( - finalizationInput({ shutdownTarget: true, verifyAndroidShutdown: verify }), - ), - ).resolves.toEqual({ androidShutdownRetained: 'changed' }); - expect(events).toEqual(['restore', 'shutdown']); -}); - test('close --shutdown is ignored for a physical Android device', async () => { const shutdownTarget = vi.fn(async () => ({ success: true, diff --git a/packages/platform-android/src/lifecycle.ts b/packages/platform-android/src/lifecycle.ts index 2bc41bdfd6..029288658a 100644 --- a/packages/platform-android/src/lifecycle.ts +++ b/packages/platform-android/src/lifecycle.ts @@ -92,19 +92,9 @@ export function bindAndroidApplicationLifecycle( }); const shutdown = input.shutdownTarget && device.kind === 'emulator' - ? input.verifyAndroidShutdown - ? await host.deviceShutdown.android.shutdownTarget( - device, - signal, - input.verifyAndroidShutdown, - ) - : await host.deviceShutdown.android.shutdownTarget(device, signal) + ? await host.deviceShutdown.android.shutdownTarget(device, signal) : undefined; - return shutdown === undefined - ? {} - : 'retained' in shutdown - ? { androidShutdownRetained: shutdown.retained } - : { shutdown }; + return shutdown === undefined ? {} : { shutdown }; }, prepareAppleRunner: unavailable, configureProviderPortReverse: unavailable, diff --git a/packages/platform-android/src/shutdown/runtime.test.ts b/packages/platform-android/src/shutdown/runtime.test.ts index c4d76e10f8..3baf1973b8 100644 --- a/packages/platform-android/src/shutdown/runtime.test.ts +++ b/packages/platform-android/src/shutdown/runtime.test.ts @@ -68,48 +68,6 @@ test('an active emulator shuts down through the owning adb command', async () => ); }); -test.each(['changed', 'unobserved'] as const)( - 'retains an emulator whose generation is %s after the IME wait', - async (outcome) => { - const device = androidDevice(); - seedRestoreMark(device.id, 0); - const settling = deferred(); - sleep.mockImplementationOnce(() => settling.promise); - let generation: 'same' | 'changed' | 'unobserved' = 'same'; - const verify = vi.fn(async () => generation); - const pending = createAndroidShutdownRuntime({ commands }).shutdownTarget( - device, - signal(), - verify, - ); - await drainMicrotasks(); - expect(verify).not.toHaveBeenCalled(); - generation = outcome; - settling.resolve(); - await expect(pending).resolves.toEqual({ retained: outcome }); - expect(run).not.toHaveBeenCalled(); - }, -); - -test('a verified generation reaches the shutdown command', async () => { - const verify = vi.fn(async () => 'same' as const); - await expect( - createAndroidShutdownRuntime({ commands }).shutdownTarget(androidDevice(), signal(), verify), - ).resolves.toEqual(success()); - expect(verify).toHaveBeenCalledOnce(); - expect(run).toHaveBeenCalledOnce(); -}); - -test('a failed generation verification retains the emulator', async () => { - const verify = async (): Promise<'same'> => { - throw new Error('probe failed'); - }; - await expect( - createAndroidShutdownRuntime({ commands }).shutdownTarget(androidDevice(), signal(), verify), - ).resolves.toEqual({ retained: 'unobserved' }); - expect(run).not.toHaveBeenCalled(); -}); - test('only Android emulators are available', () => { expect(canShutdownTarget(androidDevice())).toBe(true); expect(canShutdownTarget({ ...androidDevice(), kind: 'device' })).toBe(false); diff --git a/packages/platform-android/src/shutdown/runtime.ts b/packages/platform-android/src/shutdown/runtime.ts index 06cdc48815..bf0a8acf60 100644 --- a/packages/platform-android/src/shutdown/runtime.ts +++ b/packages/platform-android/src/shutdown/runtime.ts @@ -1,8 +1,4 @@ -import type { - AndroidShutdownTarget, - AndroidShutdownVerification, - DeviceShutdownRuntimeDependencies, -} from '@agent-device/contracts/device-shutdown-runtime'; +import type { DeviceShutdownRuntimeDependencies } from '@agent-device/contracts/device-shutdown-runtime'; import type { TargetShutdownResult } from '@agent-device/contracts/device'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { normalizeError } from '@agent-device/kernel/errors'; @@ -12,7 +8,7 @@ const SHUTDOWN_TIMEOUT_MS = 15_000; export type AndroidShutdownRuntime = Readonly<{ canShutdownTarget(device: DeviceInfo): boolean; - shutdownTarget: AndroidShutdownTarget; + shutdownTarget(device: DeviceInfo, signal: AbortSignal): Promise; }>; export function createAndroidShutdownRuntime( @@ -20,17 +16,8 @@ export function createAndroidShutdownRuntime( ): AndroidShutdownRuntime { return Object.freeze({ canShutdownTarget, - shutdownTarget: (async ( - device: DeviceInfo, - signal: AbortSignal, - verify?: AndroidShutdownVerification, - ) => - await shutdownAndroidTarget( - dependencies.commands, - device, - signal, - verify, - )) as AndroidShutdownTarget, + shutdownTarget: async (device, signal) => + await shutdownAndroidTarget(dependencies.commands, device, signal), }); } @@ -42,8 +29,7 @@ async function shutdownAndroidTarget( commands: DeviceShutdownRuntimeDependencies['commands'], device: DeviceInfo, signal: AbortSignal, - verify?: AndroidShutdownVerification, -): Promise { +): Promise { if (device.booted === false) return stoppedTargetSuccess(); signal.throwIfAborted(); @@ -54,11 +40,6 @@ async function shutdownAndroidTarget( // inside the window, and the timestamp stays for the retry to wait out the remainder. await awaitTestImeFlushWindow(device.id, signal); signal.throwIfAborted(); - if (verify) { - const generation = await verify().catch(() => 'unobserved' as const); - signal.throwIfAborted(); - if (generation !== 'same') return { retained: generation }; - } try { const result = await commands.run( { diff --git a/skills/agent-device/SKILL.md b/skills/agent-device/SKILL.md index 5a2ce8bbff..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`. 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`. If an Android emulator reports a later boot, plain close leaves it running and warns. +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 7fd0ba3634..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, 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`. If an Android emulator reports a later boot, plain close leaves it running and warns. +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 a3300dc49c..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 (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). If an Android emulator reports a later boot, plain close leaves it running and warns. +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/src/commands/schema/cli-help-workflows.ts b/src/commands/schema/cli-help-workflows.ts index cd62557e9b..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. 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. If a local Android emulator process changed or cannot be verified, plain close leaves it running and reports why. A device that was already running keeps 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. 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. If a local Android emulator process changed or cannot be verified, plain close leaves it running and reports why. A device that was already running keeps 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/platform-runtime-android-emulator-host.test.ts b/src/platform-runtime-android-emulator-host.test.ts index 3a88e8d934..f6416af78e 100644 --- a/src/platform-runtime-android-emulator-host.test.ts +++ b/src/platform-runtime-android-emulator-host.test.ts @@ -1,15 +1,12 @@ import { beforeEach, expect, test, vi } from 'vitest'; import type { DeviceInfo } from '@agent-device/kernel/device'; -const { inspectAndroidEmulatorGeneration, readAndroidEmulatorLaunchStartTime } = vi.hoisted(() => ({ - inspectAndroidEmulatorGeneration: vi.fn(), +const { readAndroidEmulatorLaunchStartTime } = vi.hoisted(() => ({ readAndroidEmulatorLaunchStartTime: vi.fn( async (): Promise => 'Mon Nov 9 10:00:00 2026', ), })); vi.mock('@agent-device/platform-android/device-boot', () => ({ - ANDROID_EMULATOR_GENERATION_BUDGET_MS: 10_000, - inspectAndroidEmulatorGeneration, readAndroidEmulatorLaunchStartTime, })); @@ -51,7 +48,6 @@ vi.mock('@agent-device/host-kit/process', () => ({ import { createAndroidEmulatorHost } from './platform-runtime-android-emulator-host.ts'; beforeEach(() => { - inspectAndroidEmulatorGeneration.mockReset(); readAndroidEmulatorLaunchStartTime.mockClear(); runCmd.mockClear(); runCmdDetached.mockClear(); @@ -68,58 +64,25 @@ const emulator: DeviceInfo = { }; const launchIdentity = { pid: 4242, startTime: 'Mon Nov 9 10:00:00 2026' }; -test('binds the launched process only when both serial observations match its recorded identity', async () => { +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); - inspectAndroidEmulatorGeneration.mockResolvedValue({ identity: launchIdentity }); await expect(host.bindLaunchedEmulator!(4242, emulator)).resolves.toEqual(launchIdentity); - expect(inspectAndroidEmulatorGeneration).toHaveBeenCalledTimes(2); - // Both observations share one deadline, so the pair is bounded together. - const calls = inspectAndroidEmulatorGeneration.mock.calls as unknown as Array< - [unknown, { deadline: unknown }] - >; - expect(calls[0]?.[1].deadline).toBeDefined(); - expect(calls[1]?.[1].deadline).toBe(calls[0]?.[1].deadline); }); -test('does not bind an unrelated listener, reused pid, or unavailable observation, and names the miss', async () => { +test('binds nothing for a pid this host did not launch', async () => { const host = createAndroidEmulatorHost('linux'); await host.launch('Pixel_9', true, 90_000); - inspectAndroidEmulatorGeneration.mockResolvedValueOnce({ - identity: { ...launchIdentity, pid: 4243 }, - }); - await expect(host.bindLaunchedEmulator!(4242, emulator)).resolves.toBeUndefined(); - inspectAndroidEmulatorGeneration - .mockResolvedValueOnce({ identity: launchIdentity }) - .mockResolvedValueOnce({ identity: { ...launchIdentity, startTime: 'new' } }); - await expect(host.bindLaunchedEmulator!(4242, emulator)).resolves.toBeUndefined(); - inspectAndroidEmulatorGeneration.mockResolvedValueOnce({ miss: 'listener-read-timeout' }); - await expect(host.bindLaunchedEmulator!(4242, emulator)).resolves.toBeUndefined(); await expect(host.bindLaunchedEmulator!(4243, emulator)).resolves.toBeUndefined(); - const causes = emitDiagnostic.mock.calls - .map(([event]) => event as { phase: string; data: { step: string; cause: string } }) - .filter((event) => event.phase === 'android_launch_identity_unbound') - .map((event) => `${event.data.step}:${event.data.cause}`); - expect(causes).toEqual([ - 'bind:first-launch-mismatch', - 'bind:second-launch-mismatch', - 'bind:first-listener-read-timeout', - ]); }); -test('a launch whose start time could not be read binds nothing and says so', async () => { +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(inspectAndroidEmulatorGeneration).not.toHaveBeenCalled(); - expect(emitDiagnostic).toHaveBeenCalledWith( - expect.objectContaining({ - phase: 'android_launch_identity_unbound', - data: expect.objectContaining({ step: 'bind', cause: 'launch-start-time-unread' }), - }), - ); + expect(emitDiagnostic).not.toHaveBeenCalled(); }); test('a windowed macOS launch hands focus back to the app frontmost before launch', async () => { diff --git a/src/platform-runtime-android-emulator-host.ts b/src/platform-runtime-android-emulator-host.ts index 3ce4155c27..c414c1a526 100644 --- a/src/platform-runtime-android-emulator-host.ts +++ b/src/platform-runtime-android-emulator-host.ts @@ -1,10 +1,5 @@ import type { DeviceReadinessRuntimeHost } from '@agent-device/contracts/device-readiness-runtime'; -import { - ANDROID_EMULATOR_GENERATION_BUDGET_MS, - inspectAndroidEmulatorGeneration, - readAndroidEmulatorLaunchStartTime, -} from '@agent-device/platform-android/device-boot'; -import { Deadline } from '@agent-device/host-kit/retry'; +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'; @@ -88,33 +83,13 @@ export function createAndroidEmulatorHost( if (frontmostPid !== undefined) returnFocusAfterLaunch(pid, frontmostPid, bootBudgetMs); return pid; }, - bindLaunchedEmulator: async (pid, device) => { + 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 unbound = (cause: string) => { - // Close reads this as "open recorded no identity", so the miss is named where it happened. - emitDiagnostic({ - level: 'warn', - phase: 'android_launch_identity_unbound', - data: { step: 'bind', cause, pid, serial: device.id }, - }); - return undefined; - }; - try { - const startTime = await record.startTime; - if (!startTime) return unbound('launch-start-time-unread'); - const deadline = Deadline.fromTimeoutMs(ANDROID_EMULATOR_GENERATION_BUDGET_MS); - for (const read of ['first', 'second'] as const) { - const reading = await inspectAndroidEmulatorGeneration(device, { deadline }); - if (!('identity' in reading)) return unbound(`${read}-${reading.miss}`); - if (reading.identity.pid !== pid || reading.identity.startTime !== startTime) { - return unbound(`${read}-launch-mismatch`); - } - } - return { pid, startTime }; - } catch { - return unbound('bind-failed'); - } + const startTime = await record.startTime; + return startTime ? { pid, startTime } : undefined; }, terminate, }); diff --git a/src/platform-runtime-device-boot.test.ts b/src/platform-runtime-device-boot.test.ts index 4254748021..9e97e858d0 100644 --- a/src/platform-runtime-device-boot.test.ts +++ b/src/platform-runtime-device-boot.test.ts @@ -10,18 +10,10 @@ const mocks = vi.hoisted(() => ({ observed: false, reason: 'unobserved', })), - ANDROID_EMULATOR_GENERATION_BUDGET_MS: 10_000, - inspectAndroidEmulatorGeneration: vi.fn( - async (): Promise<{ identity: { pid: number; startTime: string } } | { miss: string }> => ({ - miss: 'no-listener', - }), - ), - emitDiagnostic: vi.fn(), })); vi.mock('@agent-device/platform-apple/simulator-boot', () => mocks); vi.mock('@agent-device/platform-android/device-boot', () => mocks); -vi.mock('@agent-device/host-kit/diagnostics', () => ({ emitDiagnostic: mocks.emitDiagnostic })); import { ANDROID_EMULATOR, @@ -38,59 +30,6 @@ beforeEach(() => { vi.clearAllMocks(); }); -test('generation is reported only when two serial observations agree', async () => { - const identity = { pid: 42, startTime: 'start' }; - mocks.inspectAndroidEmulatorGeneration.mockResolvedValue({ identity }); - expect(await deviceBootObservation.assessShutdownGeneration(ANDROID_EMULATOR, identity)).toBe( - 'same', - ); - // The two agreeing reads share one deadline, so a slow host cannot double the budget. - const calls = mocks.inspectAndroidEmulatorGeneration.mock.calls as unknown as Array< - [unknown, { deadline: unknown }] - >; - expect(calls[1]?.[1].deadline).toBe(calls[0]?.[1].deadline); - mocks.inspectAndroidEmulatorGeneration - .mockResolvedValueOnce({ identity }) - .mockResolvedValueOnce({ identity: { ...identity, startTime: 'replacement' } }); - expect(await deviceBootObservation.assessShutdownGeneration(ANDROID_EMULATOR, identity)).toBe( - 'unobserved', - ); - mocks.inspectAndroidEmulatorGeneration.mockResolvedValue({ - identity: { pid: 43, startTime: 'replacement' }, - }); - expect(await deviceBootObservation.assessShutdownGeneration(ANDROID_EMULATOR, identity)).toBe( - 'changed', - ); - expect(await deviceBootObservation.assessShutdownGeneration(LINUX_DEVICE, identity)).toBe( - 'not-applicable', - ); - expect( - await deviceBootObservation.assessShutdownGeneration( - { ...ANDROID_EMULATOR, kind: 'device' }, - identity, - ), - ).toBe('not-applicable'); - expect(await deviceBootObservation.assessShutdownGeneration(ANDROID_EMULATOR, undefined)).toBe( - 'unobserved', - ); -}); - -test('an unverified close names the step and the read that missed', async () => { - const identity = { pid: 42, startTime: 'start' }; - mocks.inspectAndroidEmulatorGeneration - .mockResolvedValueOnce({ identity }) - .mockResolvedValueOnce({ miss: 'process-read-timeout' }); - expect(await deviceBootObservation.assessShutdownGeneration(ANDROID_EMULATOR, identity)).toBe( - 'unobserved', - ); - await deviceBootObservation.assessShutdownGeneration(ANDROID_EMULATOR, undefined); - const causes = mocks.emitDiagnostic.mock.calls - .map(([event]) => event as { phase: string; data: { step: string; cause: string } }) - .filter((event) => event.phase === 'android_launch_identity_unobserved') - .map((event) => `${event.data.step}:${event.data.cause}`); - expect(causes).toEqual(['assess:second-process-read-timeout', 'assess:unbound-at-open']); -}); - test('an iOS Simulator is answered by the Apple probe alone', async () => { expect(await deviceBootObservation.observeBootTimeMs(IOS_SIMULATOR)).toEqual({ observed: true, diff --git a/src/platform-runtime-device-boot.ts b/src/platform-runtime-device-boot.ts index c3313d8006..aa5f32acf9 100644 --- a/src/platform-runtime-device-boot.ts +++ b/src/platform-runtime-device-boot.ts @@ -1,58 +1,26 @@ import type { DeviceBootObservation, DeviceBootObservationService, - DeviceShutdownGenerationService, } from '@agent-device/contracts/device-boot'; import { isIosFamily, type DeviceInfo } from '@agent-device/kernel/device'; -import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; /** * The single answer to "when did this device's current boot begin?", assembled from whichever * family owns the device. Families that answer no boot question for a leaf report * `unsupported-device`, so a caller never branches on platform to decide what an answer means. */ -export const deviceBootObservation: DeviceBootObservationService & DeviceShutdownGenerationService = - Object.freeze({ - async assessShutdownGeneration(device, expected) { - if (device.platform !== 'android' || device.kind !== 'emulator') return 'not-applicable'; - const unobserved = (cause: string) => { - emitDiagnostic({ - level: 'warn', - phase: 'android_launch_identity_unobserved', - data: { step: 'assess', cause, serial: device.id }, - }); - return 'unobserved' as const; - }; - if (!expected) return unobserved('unbound-at-open'); - const { ANDROID_EMULATOR_GENERATION_BUDGET_MS, inspectAndroidEmulatorGeneration } = +export const deviceBootObservation: DeviceBootObservationService = Object.freeze({ + async observeBootTimeMs(device: DeviceInfo): Promise { + if (isIosFamily(device) && device.kind === 'simulator') { + const { observeSimulatorBootTimeMs } = + await import('@agent-device/platform-apple/simulator-boot'); + return await observeSimulatorBootTimeMs(device); + } + if (device.platform === 'android') { + const { observeAndroidBootTimeMs } = await import('@agent-device/platform-android/device-boot'); - const { Deadline } = await import('@agent-device/host-kit/retry'); - const deadline = Deadline.fromTimeoutMs(ANDROID_EMULATOR_GENERATION_BUDGET_MS); - const first = await inspectAndroidEmulatorGeneration(device, { deadline }); - if (!('identity' in first)) return unobserved(`first-${first.miss}`); - const second = await inspectAndroidEmulatorGeneration(device, { deadline }); - if (!('identity' in second)) return unobserved(`second-${second.miss}`); - if ( - second.identity.pid !== first.identity.pid || - second.identity.startTime !== first.identity.startTime - ) { - return unobserved('reads-disagree'); - } - return first.identity.pid === expected.pid && first.identity.startTime === expected.startTime - ? 'same' - : 'changed'; - }, - async observeBootTimeMs(device: DeviceInfo): Promise { - if (isIosFamily(device) && device.kind === 'simulator') { - const { observeSimulatorBootTimeMs } = - await import('@agent-device/platform-apple/simulator-boot'); - return await observeSimulatorBootTimeMs(device); - } - if (device.platform === 'android') { - const { observeAndroidBootTimeMs } = - await import('@agent-device/platform-android/device-boot'); - return await observeAndroidBootTimeMs(device); - } - return { observed: false, reason: 'unsupported-device' }; - }, - }); + return await observeAndroidBootTimeMs(device); + } + return { observed: false, reason: 'unsupported-device' }; + }, +}); diff --git a/src/platform-runtime-device-shutdown-host.test.ts b/src/platform-runtime-device-shutdown-host.test.ts index a9fe34f4f0..11dd688acc 100644 --- a/src/platform-runtime-device-shutdown-host.test.ts +++ b/src/platform-runtime-device-shutdown-host.test.ts @@ -57,20 +57,6 @@ test('Android shutdown uses the owning package capability', async () => { expect(shutdownLoaders.android).toHaveBeenCalledOnce(); }); -test('Android host forwards the shutdown verifier to the runtime', async () => { - const device: DeviceInfo = { - platform: 'android', - id: 'emulator-5554', - name: 'Pixel', - kind: 'emulator', - booted: true, - }; - const verify = async () => 'same' as const; - const abortSignal = signal(); - await shutdownHost().android.shutdownTarget(device, abortSignal, verify); - expect(androidShutdown).toHaveBeenCalledWith(device, abortSignal, verify); -}); - test('a shutdown guard refuses every shutdown path before the owner runtime loads', async () => { const denied = new Error('policy denies device-shutdown'); const host = shutdownHost(() => { diff --git a/src/platform-runtime-device-shutdown-host.ts b/src/platform-runtime-device-shutdown-host.ts index 148d484c64..b85351203a 100644 --- a/src/platform-runtime-device-shutdown-host.ts +++ b/src/platform-runtime-device-shutdown-host.ts @@ -1,7 +1,5 @@ import type { DeviceInfo } from '@agent-device/kernel/device'; import type { - AndroidShutdownTarget, - AndroidShutdownVerification, DeviceShutdownCloseCapability, DeviceShutdownRuntimeDependencies, DeviceShutdownRuntimeHost, @@ -37,17 +35,10 @@ export function createDeviceShutdownRuntimeHost( }, }); const android = Object.freeze({ - shutdownTarget: (async ( - device: DeviceInfo, - signal: AbortSignal, - verify?: AndroidShutdownVerification, - ) => { + shutdownTarget: async (device: DeviceInfo, signal: AbortSignal) => { assertShutdownAllowed(); - const runtime = await loadAndroid(); - return verify - ? await runtime.shutdownTarget(device, signal, verify) - : await runtime.shutdownTarget(device, signal); - }) as AndroidShutdownTarget, + return await (await loadAndroid()).shutdownTarget(device, signal); + }, }); const close: DeviceShutdownCloseCapability = Object.freeze({ canShutdownTarget: async (device) => await canShutdownTarget(device, loadApple, loadAndroid), diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index c1b1c08dc5..4923cdb6c9 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -106,7 +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`. When an Android emulator process changed or cannot be verified, plain `close` leaves it running and reports why in `warnings`. The check needs a macOS or Linux host with `lsof`; elsewhere, plain `close` leaves a booted Android emulator running, so use `close --shutdown`. 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. +- `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/sessions.md b/website/docs/docs/sessions.md index d68cad1c76..6dfd98c7ba 100644 --- a/website/docs/docs/sessions.md +++ b/website/docs/docs/sessions.md @@ -126,11 +126,10 @@ agent-device open --platform ios --device iPhone_17_Pro agent-device close # the simulator this open booted ends shut down ``` -If a local Android emulator process changed or cannot be verified, -plain `close` leaves it running and reports why in `warnings`. -The check reads the emulator's host process with `lsof`, so it needs a macOS or Linux host with -`lsof` installed. On other hosts, plain `close` leaves a booted Android emulator running and warns; -use `close --shutdown` to stop it. +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. From 00f70c241d59adb51e6494b149a607f83b26d7c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 19 Nov 2026 23:24:46 +0100 Subject: [PATCH 08/10] refactor(close): ask the root-composed owner about the launched process MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `check:layering` rejects the previous shape: R65 keeps the daemon's close orchestration from selecting a concrete platform, and the launched-emulator check did exactly that. The rule moves to where R65 points — a published `LaunchedDeviceProcessService` composed at the root, answered by the Android family and `not-applicable` for every device that launches no host process. The process reads themselves (one `ps`, liveness, and the pid escalation with the recorded start time) now live in `@agent-device/platform-android/device-boot` beside the launch that records the identity, which is where the timeout and escalation budgets belong. --- packages/contracts/src/device-boot.ts | 39 ++++++ .../launched-emulator-process-fixture.ts | 96 --------------- .../support/launched-process-owner-fixture.ts | 75 +++++++++++ .../support/platform-services-fixture.ts | 9 +- packages/daemon/src/core/platform-services.ts | 12 +- .../session-close-external-reboot.test.ts | 116 ++++++++---------- .../session-close-implicit-shutdown.test.ts | 34 +++-- .../session-close-emulator-process.ts | 63 ---------- .../session-close-lifecycle-teardown.ts | 97 ++++++++------- .../internal/session-close.ts | 5 + .../src/device-boot-launch.test.ts | 98 ++++++++++++++- packages/platform-android/src/device-boot.ts | 64 +++++++++- src/platform-runtime-daemon-services.ts | 3 +- src/platform-runtime-device-boot.test.ts | 48 +++++++- src/platform-runtime-device-boot.ts | 37 ++++++ 15 files changed, 495 insertions(+), 301 deletions(-) delete mode 100644 packages/daemon/src/__tests__/support/launched-emulator-process-fixture.ts create mode 100644 packages/daemon/src/__tests__/support/launched-process-owner-fixture.ts delete mode 100644 packages/daemon/src/sessions/session-lifecycle/internal/session-close-emulator-process.ts diff --git a/packages/contracts/src/device-boot.ts b/packages/contracts/src/device-boot.ts index b69e386736..41791763e7 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,41 @@ 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, a pid, or a process tool. + * + * 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/daemon/src/__tests__/support/launched-emulator-process-fixture.ts b/packages/daemon/src/__tests__/support/launched-emulator-process-fixture.ts deleted file mode 100644 index b63e383187..0000000000 --- a/packages/daemon/src/__tests__/support/launched-emulator-process-fixture.ts +++ /dev/null @@ -1,96 +0,0 @@ -import type * as HostProcessModule from '@agent-device/host-kit/process'; - -/** - * How the host answers for the emulator process a test session's `open` launched, so a close suite - * can name which answer the launched-process rule gets without touching the real process table. - * Cases use the pid named here rather than an arbitrary one: a fabricated pid would be signalled for - * real if a rule ever aimed a stop at the wrong process, so the seams below answer for this pid only - * and delegate every other pid to the real host. - */ -export type LaunchedEmulatorProcess = { - /** The pid `open` recorded for the emulator it launched. */ - pid: number; - /** The start time `open` recorded for that pid. */ - startTime: string; - /** Whether `kill(pid, 0)` still finds it. */ - alive: boolean; - /** Whether the host shows it as a zombie: still answered for, already terminated. */ - zombie: boolean; - /** The live start time the host reports for it, which may contradict the recorded one. */ - liveStartTime: string; - /** Whether the host refuses to answer for the pid at all. */ - unreadable: boolean; - /** Whether the process took the `adb emu kill` the close asked for. */ - exitsOnKill: boolean; - /** How many times the close read this pid's identity facts. */ - factReads: number; - /** Every pid a stop escalated to, with the identity it carried. */ - signalAttempts: Array<{ pid: number; startTime?: string }>; -}; - -const DEFAULTS = { - pid: 4112, - startTime: 'launch-start-time', - alive: true, - zombie: false, - liveStartTime: 'launch-start-time', - unreadable: false, - exitsOnKill: true, -} as const; - -/** - * The one model the suite's host answers are read from, shared by the mocked module and the cases. - * A case sets the fields it cares about; `resetLaunchedEmulatorProcess` returns it before the next. - */ -export const launchedEmulatorProcess: LaunchedEmulatorProcess = { - ...DEFAULTS, - factReads: 0, - signalAttempts: [], -}; - -/** Returns the model to a live launched process that takes the kill, before each case. */ -export function resetLaunchedEmulatorProcess(): void { - Object.assign(launchedEmulatorProcess, DEFAULTS, { factReads: 0 }); - launchedEmulatorProcess.signalAttempts.length = 0; -} - -/** - * The `@agent-device/host-kit/process` answers a close suite needs, over the model above. Only the - * four reads a close makes about another process are answered this way, and only for the launched - * pid; the real host keeps answering every other question. - */ -export function launchedEmulatorProcessHost( - actual: typeof HostProcessModule, -): typeof HostProcessModule { - const isLaunched = (pid: number) => pid === launchedEmulatorProcess.pid; - return { - ...actual, - isProcessAlive: (pid: number) => - isLaunched(pid) ? launchedEmulatorProcess.alive : actual.isProcessAlive(pid), - readProcessIdentityFacts: async (pid: number, timeoutMs?: number) => { - if (!isLaunched(pid)) return await actual.readProcessIdentityFacts(pid, timeoutMs); - launchedEmulatorProcess.factReads += 1; - if (launchedEmulatorProcess.unreadable) throw new Error('ps timed out after 1000ms'); - return { - startTime: launchedEmulatorProcess.liveStartTime, - command: '/sdk/emulator/emulator -avd Pixel_9_API_37', - zombie: launchedEmulatorProcess.zombie, - }; - }, - waitForProcessExit: async (pid: number, timeoutMs: number) => - isLaunched(pid) - ? !launchedEmulatorProcess.alive || launchedEmulatorProcess.exitsOnKill - : await actual.waitForProcessExit(pid, timeoutMs), - stopProcessAndConfirmExit: async ( - target: HostProcessModule.ProcessStopTarget, - budget: HostProcessModule.ProcessStopBudget, - ) => { - if (!isLaunched(target.pid)) return await actual.stopProcessAndConfirmExit(target, budget); - launchedEmulatorProcess.signalAttempts.push({ - pid: target.pid, - startTime: target.identity.startTime, - }); - return { status: 'stopped', signal: 'SIGTERM' } as const; - }, - }; -} 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/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/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/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 index 20a462a838..39ec954e29 100644 --- 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 @@ -1,7 +1,9 @@ -// #4585: plain `close` owes a stop to the emulator 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, and the -// only host fact close reads about the launched process is the `ps` of the recorded pid. +// #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'; @@ -25,23 +27,13 @@ vi.mock('@agent-device/device-selection/dispatch-resolve', async (importOriginal }; }); -// The host's answers about the emulator process `open` launched are modelled so no case signals or -// waits on a real process. `launchedEmulatorProcess()` is that model. -vi.mock('@agent-device/host-kit/process', async (importOriginal) => { - const { launchedEmulatorProcessHost } = - await import('../../../../__tests__/support/launched-emulator-process-fixture.ts'); - return launchedEmulatorProcessHost( - await importOriginal(), - ); -}); - import { - launchedEmulatorProcess as launched, - resetLaunchedEmulatorProcess, -} from '../../../../__tests__/support/launched-emulator-process-fixture.ts'; + launchedProcessOwnerAnswers as owner, + resetLaunchedProcessOwnerAnswers, +} from '../../../../__tests__/support/launched-process-owner-fixture.ts'; -/** The identity `open` records for the emulator process it launched, as the model answers for it. */ -const launchedEmulatorIdentity = () => ({ pid: launched.pid, startTime: launched.startTime }); +/** 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'; @@ -108,8 +100,7 @@ function createRoutedSession() { if (command.selectsDevice) { vi.mocked(resolveTargetDevice).mockResolvedValue(STOPPED_AVD); mockEnsureReadyRuntime.mockImplementation(async (input) => { - if (!command.omitLaunchIdentity) - input.onAndroidEmulatorLaunchIdentity?.(launchedEmulatorIdentity()); + if (!command.omitLaunchIdentity) input.onAndroidEmulatorLaunchIdentity?.(LAUNCH_IDENTITY); return BOOTED_EMULATOR; }); } @@ -169,7 +160,7 @@ function createRoutedSession() { /** * 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 answers for it. + * session caused, with the launched process recorded as the host answered for it. */ async function openBootedByThisSession(runs: ReturnType) { const opened = await runs.run({ @@ -182,7 +173,7 @@ async function openBootedByThisSession(runs: ReturnType { mockEnsureReadyRuntime.mockReset(); mockEnsureReadyRuntime.mockResolvedValue(undefined); - resetLaunchedEmulatorProcess(); + resetLaunchedProcessOwnerAnswers(); }); afterEach(() => { @@ -221,26 +212,30 @@ test('plain close stops the emulator this session booted while it still runs tha expect(closeWarningMessages(closed.response!)).toBeUndefined(); if (closed.response?.ok) expect(closed.response.data).toMatchObject({ shutdown: { success: true } }); - // The launched process took the shutdown it was asked for, so nothing was ever signalled by pid, - // and the session is retired with its claim like any successful close. - expect(launched.signalAttempts).toEqual([]); + // 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('plain close stops the launched process itself when it ignores the emulator console kill', async () => { +test('plain close succeeds without saying more when the stop could not be confirmed', async () => { const runs = createRoutedSession(); await openBootedByThisSession(runs); - launched.exitsOnKill = false; + 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 launched process was escalated by the owner; an + // unconfirmed exit is the owner's diagnostic, not a close the caller has to act on. expect(closeWarningMessages(closed.response!)).toBeUndefined(); - // The escalation aims only at the process this session launched, with the identity open recorded, - // which is what host-kit requires before it signals anything. - expect(launched.signalAttempts).toEqual([{ pid: launched.pid, startTime: launched.startTime }]); + expect(owner.confirmations).toEqual([LAUNCH_IDENTITY]); }); test('plain close leaves an emulator rebooted outside the session running and says why', async () => { @@ -249,7 +244,7 @@ test('plain close leaves an emulator rebooted outside the session running and sa // 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. - launched.alive = false; + owner.check = 'changed'; const closed = await runs.run({ name: 'close' }); expect(closed.response?.ok).toBe(true); @@ -259,8 +254,9 @@ test('plain close leaves an emulator rebooted outside the session running and sa expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); expect(closeWarningMessages(closed.response!)).toEqual([PROCESS_CHANGED_WARNING]); if (closed.response?.ok) expect(closed.response.data).not.toHaveProperty('shutdown'); - // Close reads the launched process once, and only as its own decision. - expect(launched.factReads).toBe(1); + // 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 () => { @@ -268,22 +264,9 @@ test('Quick Boot retains the replacement with the same serial and restored guest 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 start time separates the two lifetimes. - launched.liveStartTime = 'replacement-start-time'; - 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 leaves the emulator running when a zombie answers the recorded pid', async () => { - const runs = createRoutedSession(); - await openBootedByThisSession(runs); - launched.zombie = true; - + // 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([ @@ -293,10 +276,10 @@ test('plain close leaves the emulator running when a zombie answers the recorded expect(closeWarningMessages(closed.response!)).toEqual([PROCESS_CHANGED_WARNING]); }); -test('plain close retains the emulator when the host will not answer for the recorded pid', async () => { +test('plain close retains the emulator when the host will not answer for the recorded process', async () => { const runs = createRoutedSession(); await openBootedByThisSession(runs); - launched.unreadable = true; + owner.check = 'unverified'; const closed = await runs.run({ name: 'close' }); @@ -306,7 +289,7 @@ test('plain close retains the emulator when the host will not answer for the rec ]); expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); expect(closeWarningMessages(closed.response!)).toEqual([PROCESS_UNVERIFIED_WARNING]); - expect(launched.signalAttempts).toEqual([]); + expect(owner.confirmations).toEqual([]); }, 30_000); test('missing launch identity does not acquire ownership from a later process read', async () => { @@ -325,16 +308,18 @@ test('missing launch identity does not acquire ownership from a later process re expect.objectContaining({ shutdownTarget: false, retainRunner: false }), ]); expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); - // Nothing was recorded, so close has no pid to read and asks the host nothing. - expect(launched.factReads).toBe(0); + // 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 signals the launched process', async () => { +test('close --shutdown stops the device and never asks about the launched process', async () => { const runs = createRoutedSession(); await openBootedByThisSession(runs); - launched.alive = false; - launched.exitsOnKill = false; + owner.check = 'changed'; + owner.confirmation = 'unconfirmed'; const closed = await runs.run({ name: 'close', flags: { shutdown: true } }); @@ -344,10 +329,13 @@ test('close --shutdown stops the device and never signals the launched process', ]); expect(mockShutdownTargetRuntime).toHaveBeenCalledTimes(1); expect(closeWarningMessages(closed.response!)).toBeUndefined(); - expect(launched.signalAttempts).toEqual([]); + // 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 reads no process', async () => { +test('a policy refusal stays the reported reason and asks nothing of the process owner', async () => { const runs = createRoutedSession(); await openBootedByThisSession(runs); @@ -361,10 +349,10 @@ test('a policy refusal stays the reported reason and reads no process', async () 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(launched.factReads).toBe(0); + expect(owner.checks).toEqual([]); }, 30_000); -test('a lost claim stays the reported reason and reads no process', async () => { +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(); @@ -379,7 +367,7 @@ test('a lost claim stays the reported reason and reads no process', async () => 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(launched.factReads).toBe(0); + expect(owner.checks).toEqual([]); }, 30_000); test('changing the device serial clears launch ownership', async () => { 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 index 8f964a9ec5..fee57d0bbd 100644 --- 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 @@ -1,5 +1,5 @@ import { daemonPlatformServicesFixture } from '../../../../__tests__/support/platform-services-fixture.ts'; -import { beforeEach, expect, test, vi } from 'vitest'; +import { beforeEach, expect, test } from 'vitest'; import { sessionCloseShutdownFixture, type SessionState, @@ -18,19 +18,9 @@ import { inspectDeviceClaims, } from '@agent-device/daemon-contracts/device-claims'; import { - launchedEmulatorProcess, - resetLaunchedEmulatorProcess, -} from '../../../../__tests__/support/launched-emulator-process-fixture.ts'; - -// The host's answers about the emulator process an `open` launched are modelled, so an Android case -// can settle its close without touching the real process table. -vi.mock('@agent-device/host-kit/process', async (importOriginal) => { - const { launchedEmulatorProcessHost } = - await import('../../../../__tests__/support/launched-emulator-process-fixture.ts'); - return launchedEmulatorProcessHost( - await importOriginal(), - ); -}); + launchedProcessOwnerAnswers, + resetLaunchedProcessOwnerAnswers, +} from '../../../../__tests__/support/launched-process-owner-fixture.ts'; bindTestCommandHost(); @@ -47,7 +37,7 @@ const { beforeEach(() => { resetSessionCloseShutdownMocks(); - resetLaunchedEmulatorProcess(); + resetLaunchedProcessOwnerAnswers(); }); const iosSimulator: SessionState['device'] = { @@ -68,6 +58,9 @@ const androidEmulator: SessionState['device'] = { 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']; @@ -87,11 +80,7 @@ async function closeSession(params: { const sessionStore = makeSessionStore(); const session = makeSession(sessionName, device); if (bootedByOpen) session.bootedByOpen = bootedByOpen; - if (device.platform === 'android') - session.androidLaunchIdentity = { - pid: launchedEmulatorProcess.pid, - startTime: launchedEmulatorProcess.startTime, - }; + if (device.platform === 'android') session.androidLaunchIdentity = LAUNCH_IDENTITY; if (bootedByOpen) { const claimInput = { env: host.env, @@ -210,6 +199,11 @@ test.each([ 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([]); }, ); diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-close-emulator-process.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-close-emulator-process.ts deleted file mode 100644 index 775a9b4824..0000000000 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-close-emulator-process.ts +++ /dev/null @@ -1,63 +0,0 @@ -// #4585: a plain `close` owes a stop to the boot its own `open` caused, and on Android the host -// half of that boot is one emulator process this daemon launched and recorded. This module is the -// one owner of the rule that names that process: read it, and stop nothing else. -import type { AndroidEmulatorLaunchIdentity } from '@agent-device/contracts/device-readiness-runtime'; -import { - isProcessAlive, - processStartTimesDiffer, - readProcessIdentityFacts, - stopProcessAndConfirmExit, - waitForProcessExit, -} from '@agent-device/host-kit/process'; - -/** - * What the host says about the launched emulator process, read once immediately before a stop. - * `same` is the only answer that lets the stop proceed: `changed` is positive evidence that the - * recorded process is gone, so whoever answers the serial now is not this session's launch, and - * `unverified` means the host could not name the live process at all. - */ -export type AndroidEmulatorProcessCheck = 'same' | 'changed' | 'unverified'; - -/** - * {@link AndroidEmulatorProcessCheck} for one recorded launch, from one `ps` of the recorded pid. - * Liveness is read separately from the start time because a reaped process leaves no `ps` row, and - * only `kill(pid, 0)` tells that apart from a `ps` read that failed. - */ -export async function checkAndroidEmulatorProcess( - identity: AndroidEmulatorLaunchIdentity, -): Promise { - let facts: Awaited>; - try { - facts = await readProcessIdentityFacts(identity.pid); - } 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 process took the shutdown it was asked for 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 confirmAndroidEmulatorProcessStopped( - identity: AndroidEmulatorLaunchIdentity, -): Promise<'stopped' | 'unconfirmed'> { - 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'; -} - -/** - * 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/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 c9bcc769a0..69309aab23 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,10 @@ 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'; @@ -9,11 +13,6 @@ 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'; import { SessionStore } from '../../../core/session-store.ts'; -import { - checkAndroidEmulatorProcess, - confirmAndroidEmulatorProcessStopped, - type AndroidEmulatorProcessCheck, -} from './session-close-emulator-process.ts'; import { cleanupRetainedMaterializedPathsForSession } from '../../materialized-path-registry.ts'; import { reportSessionCleanupFailures, @@ -45,15 +44,15 @@ type CloseDeviceStopDecision = Readonly<{ implicitShutdownDeniedByPolicy: boolean; implicitShutdownClaimLost: boolean; /** - * #4585: the emulator process this session's `open` launched is not running any more, so whoever - * answers that serial now is somebody else's device and the implicit stop is withheld. The close - * itself succeeded. + * #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 emulator 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 pid. + * #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; }>; @@ -74,12 +73,12 @@ export type SessionCloseTeardownResult = Readonly<{ * 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: on Android, the stop this session owes is owed to the emulator PROCESS its own open - * launched, not to whatever answers that serial now, so the recorded process is checked once, right - * before the stop is asked for. 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. Each - * reason is reported as itself and in this order: what settled the stop first is the only reason - * close can honestly give. + * #4585: the stop this session owes is owed to the launch its own open caused, not to whatever + * answers the device address now, so the process behind that launch is checked once, right before + * the stop is asked for, through the root-composed owner that knows which devices have one. 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. Each reason is reported as itself and + * in this order: what settled the stop first is the only reason close can honestly give. */ async function decideDeviceStopOnClose(params: { env: EnvMap; @@ -87,6 +86,7 @@ async function decideDeviceStopOnClose(params: { session: SessionState; localFamily: boolean; deviceShutdownDenied: boolean; + launchedProcess: LaunchedDeviceProcessService; }): Promise { const { session } = params; const implicitShutdown = @@ -99,7 +99,7 @@ async function decideDeviceStopOnClose(params: { implicitShutdown && !implicitShutdownClaimLost && params.deviceShutdownDenied; const launchedProcess = implicitShutdown && !implicitShutdownDeniedByPolicy && claimRenewal?.status === 'renewed' - ? await checkLaunchedAndroidEmulatorProcess(session) + ? await checkLaunchedProcessOwnership(session, params.launchedProcess) : 'not-applicable'; const implicitShutdownLaunchedProcessGone = launchedProcess === 'changed'; const implicitShutdownLaunchedProcessUnverified = launchedProcess === 'unverified'; @@ -119,48 +119,52 @@ async function decideDeviceStopOnClose(params: { } /** - * Whether the emulator process this session's open launched still runs the device it booted. Only - * the Android emulator has a host process this daemon launched to check; every other device is - * stopped by the platform answer alone, so this reports `not-applicable` rather than a miss. + * 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 checkLaunchedAndroidEmulatorProcess( +async function checkLaunchedProcessOwnership( session: SessionState, -): Promise { - if (session.device.platform !== 'android' || session.device.kind !== 'emulator') - return 'not-applicable'; + launchedProcess: LaunchedDeviceProcessService, +): Promise { const identity = session.androidLaunchIdentity; - if (!identity) { - emitAndroidLaunchIdentityMiss('open-recorded-no-process'); - return 'unverified'; - } - const check = await checkAndroidEmulatorProcess(identity); - if (check !== 'same') - emitAndroidLaunchIdentityMiss(`process-check-${check}`, { pid: identity.pid }); + 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 Android stop: the platform asked the emulator to shut itself down through - * `adb emu kill`, so confirm the process this session launched actually left. One that ignores the - * kill is stopped by pid, and host-kit refuses a pid that no longer carries the recorded start time. + * 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 confirmLaunchedAndroidEmulatorStopped(session: SessionState): Promise { - if (session.device.platform !== 'android' || session.device.kind !== 'emulator') return; +async function confirmLaunchedProcessStopped( + session: SessionState, + launchedProcess: LaunchedDeviceProcessService, +): Promise { const identity = session.androidLaunchIdentity; if (!identity) return; - if ((await confirmAndroidEmulatorProcessStopped(identity)) === 'unconfirmed') - emitAndroidLaunchIdentityMiss('launched-process-stop-unconfirmed', { pid: identity.pid }); + if ( + (await launchedProcess.confirmLaunchedProcessStopped(session.device, identity)) === + 'unconfirmed' + ) + emitLaunchedProcessMiss('launched-process-stop-unconfirmed', { pid: identity.pid }); } /** - * The one diagnostic for a session whose close could not settle the state of the emulator 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. + * 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 emitAndroidLaunchIdentityMiss(step: string, data: Record = {}): void { +function emitLaunchedProcessMiss(step: string, data: Record = {}): void { emitDiagnostic({ level: 'warn', - phase: 'android_launch_identity_miss', + phase: 'launch_process_identity_miss', data: { step, ...data }, }); } @@ -186,6 +190,8 @@ export async function runSessionCloseTeardown(params: { }): 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, @@ -219,6 +225,7 @@ export async function runSessionCloseTeardown(params: { session, localFamily: lifecycle.owner.kind === 'local-family', deviceShutdownDenied: params.deviceShutdownDenied === true, + launchedProcess: params.launchedProcess, }); const { shutdownRequested, ...stopReasons } = deviceStop; const retainExecutionHost = params.platformResourceCleanup.retainExecutionHostAfterClose({ @@ -271,7 +278,7 @@ export async function runSessionCloseTeardown(params: { // host process. An explicit `--shutdown` is the user's own command for the device and is not this // session's launched process to confirm. if (shutdownRequested && req.flags?.shutdown !== true) - await confirmLaunchedAndroidEmulatorStopped(session); + await confirmLaunchedProcessStopped(session, params.launchedProcess); const saveScriptOutcome = repairArmed ? {} : finalizeOrdinaryCloseScript({ req, ref, sessionStore, platformCloseError }); 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 d12366fb42..4cd08079bf 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'; @@ -357,6 +358,7 @@ export async function handleSessionCloseCommands( clearRuntimeHints: admission.clearRuntimeHints, repairArmed: repair.repairArmed, platformResourceCleanup, + launchedProcess: params.platformServices.launchedDeviceProcess, deviceShutdownDenied: params.deviceShutdownDenied, }), ); @@ -427,6 +429,8 @@ async function runCloseTeardownAndRelease(params: { 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, @@ -465,6 +469,7 @@ async function runCloseTeardownAndRelease(params: { 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 diff --git a/packages/platform-android/src/device-boot-launch.test.ts b/packages/platform-android/src/device-boot-launch.test.ts index ebb3a22950..2c0d9e7ddd 100644 --- a/packages/platform-android/src/device-boot-launch.test.ts +++ b/packages/platform-android/src/device-boot-launch.test.ts @@ -2,20 +2,43 @@ import { beforeEach, expect, test, vi } from 'vitest'; const mocks = vi.hoisted(() => ({ readProcessIdentityFacts: vi.fn(), + isProcessAlive: vi.fn(), + waitForProcessExit: vi.fn(), + stopProcessAndConfirmExit: vi.fn(), })); -vi.mock('@agent-device/host-kit/process', () => ({ + +// `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 { readAndroidEmulatorLaunchStartTime } from './device-boot.ts'; +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: 'start', zombie: false }); + 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('start'); + expect(await readAndroidEmulatorLaunchStartTime(4242)).toBe(IDENTITY.startTime); expect(mocks.readProcessIdentityFacts).toHaveBeenCalledExactlyOnceWith(4242, 5_000); }); @@ -41,3 +64,70 @@ test('a launch the host never answers for has no start time after both reads', a 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 e3c41286df..c71f567f0e 100644 --- a/packages/platform-android/src/device-boot.ts +++ b/packages/platform-android/src/device-boot.ts @@ -1,4 +1,9 @@ -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'; /** @@ -61,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/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'; +} From 76b0043980601c3a8f1ea516c6e1d7d26fb213e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 20 Nov 2026 09:08:59 +0100 Subject: [PATCH 09/10] fix(close): read launched-process ownership right before the stop The ownership read ran when close decided the stop, up to about 12 s before adb emu kill, so a replacement that took the serial during platform close or hint cleanup could be stopped. The single read now runs just before finalizeApplicationClose, and shutdownTarget is passed only when the launched process still matches. Close also warns when it could not confirm that the process exited. --- packages/contracts/src/device-boot.ts | 3 +- .../session-close-external-reboot.test.ts | 45 ++++++++++++-- .../session-close-lifecycle-teardown.ts | 62 +++++++++++-------- .../internal/session-close.ts | 12 ++++ 4 files changed, 90 insertions(+), 32 deletions(-) diff --git a/packages/contracts/src/device-boot.ts b/packages/contracts/src/device-boot.ts index 41791763e7..07e2184377 100644 --- a/packages/contracts/src/device-boot.ts +++ b/packages/contracts/src/device-boot.ts @@ -46,7 +46,8 @@ 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, a pid, or a process tool. + * 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 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 index 39ec954e29..efe6799f4e 100644 --- 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 @@ -96,6 +96,8 @@ function createRoutedSession() { 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); @@ -116,6 +118,14 @@ function createRoutedSession() { finalizeAsks.push(input); return await finalizeApplicationClose(input); }, + ...(command.duringPlatformClose + ? { + closeApplication: async (...args: Parameters) => { + command.duringPlatformClose?.(); + return await operations.closeApplication(...args); + }, + } + : {}), }); }; const response = await handleSessionCommands({ @@ -220,7 +230,32 @@ test('plain close stops the emulator this session booted while it still runs tha expect(runs.sessionClaimCount()).toBe(0); }, 30_000); -test('plain close succeeds without saying more when the stop could not be confirmed', async () => { +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'; @@ -232,9 +267,11 @@ test('plain close succeeds without saying more when the stop could not be confir expect.objectContaining({ shutdownTarget: true, retainRunner: false }), ]); expect(mockShutdownTargetRuntime).toHaveBeenCalledTimes(1); - // The stop was asked of the device and the launched process was escalated by the owner; an - // unconfirmed exit is the owner's diagnostic, not a close the caller has to act on. - expect(closeWarningMessages(closed.response!)).toBeUndefined(); + // 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]); }); 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 69309aab23..895e56ea8a 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 @@ -63,6 +63,11 @@ export type SessionCloseTeardownResult = Readonly<{ saveScriptOutcome: OrdinaryCloseScript; shutdownResult?: TargetShutdownResult; shutdownPrepared: 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; @@ -74,11 +79,11 @@ export type SessionCloseTeardownResult = Readonly<{ * 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, so the process behind that launch is checked once, right before - * the stop is asked for, through the root-composed owner that knows which devices have one. 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. Each reason is reported as itself and - * in this order: what settled the stop first is the only reason close can honestly give. + * 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; @@ -86,7 +91,6 @@ async function decideDeviceStopOnClose(params: { session: SessionState; localFamily: boolean; deviceShutdownDenied: boolean; - launchedProcess: LaunchedDeviceProcessService; }): Promise { const { session } = params; const implicitShutdown = @@ -97,24 +101,14 @@ async function decideDeviceStopOnClose(params: { const implicitShutdownClaimLost = claimRenewal?.status === 'lost'; const implicitShutdownDeniedByPolicy = implicitShutdown && !implicitShutdownClaimLost && params.deviceShutdownDenied; - const launchedProcess = - implicitShutdown && !implicitShutdownDeniedByPolicy && claimRenewal?.status === 'renewed' - ? await checkLaunchedProcessOwnership(session, params.launchedProcess) - : 'not-applicable'; - const implicitShutdownLaunchedProcessGone = launchedProcess === 'changed'; - const implicitShutdownLaunchedProcessUnverified = launchedProcess === 'unverified'; return { shutdownRequested: params.explicitShutdown || - (implicitShutdown && - !implicitShutdownDeniedByPolicy && - !implicitShutdownLaunchedProcessGone && - !implicitShutdownLaunchedProcessUnverified && - claimRenewal?.status === 'renewed'), + (implicitShutdown && !implicitShutdownDeniedByPolicy && claimRenewal?.status === 'renewed'), implicitShutdownDeniedByPolicy, implicitShutdownClaimLost, - implicitShutdownLaunchedProcessGone, - implicitShutdownLaunchedProcessUnverified, + implicitShutdownLaunchedProcessGone: false, + implicitShutdownLaunchedProcessUnverified: false, }; } @@ -146,14 +140,16 @@ async function checkLaunchedProcessOwnership( async function confirmLaunchedProcessStopped( session: SessionState, launchedProcess: LaunchedDeviceProcessService, -): Promise { +): Promise { const identity = session.androidLaunchIdentity; - if (!identity) return; + if (!identity) return false; if ( - (await launchedProcess.confirmLaunchedProcessStopped(session.device, identity)) === + (await launchedProcess.confirmLaunchedProcessStopped(session.device, identity)) !== 'unconfirmed' ) - emitLaunchedProcessMiss('launched-process-stop-unconfirmed', { pid: identity.pid }); + return false; + emitLaunchedProcessMiss('launched-process-stop-unconfirmed', { pid: identity.pid }); + return true; } /** @@ -225,7 +221,6 @@ export async function runSessionCloseTeardown(params: { session, localFamily: lifecycle.owner.kind === 'local-family', deviceShutdownDenied: params.deviceShutdownDenied === true, - launchedProcess: params.launchedProcess, }); const { shutdownRequested, ...stopReasons } = deviceStop; const retainExecutionHost = params.platformResourceCleanup.retainExecutionHostAfterClose({ @@ -262,6 +257,14 @@ 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. + 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 => @@ -270,15 +273,17 @@ export async function runSessionCloseTeardown(params: { surface: session.surface ?? 'app', retainRunner: retainExecutionHost, stateDir: sessionStore.resolveDaemonStateDir(), - shutdownTarget: shutdownRequested && 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. - if (shutdownRequested && req.flags?.shutdown !== true) - await confirmLaunchedProcessStopped(session, params.launchedProcess); + const stopUnconfirmed = + implicitStop && stopOwed + ? await confirmLaunchedProcessStopped(session, params.launchedProcess) + : false; const saveScriptOutcome = repairArmed ? {} : finalizeOrdinaryCloseScript({ req, ref, sessionStore, platformCloseError }); @@ -292,6 +297,9 @@ export async function runSessionCloseTeardown(params: { 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 4cd08079bf..4caa7af367 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts @@ -373,6 +373,7 @@ export async function handleSessionCloseCommands( implicitShutdownClaimLost: closed.implicitShutdownClaimLost, implicitShutdownLaunchedProcessGone: closed.implicitShutdownLaunchedProcessGone, implicitShutdownLaunchedProcessUnverified: closed.implicitShutdownLaunchedProcessUnverified, + implicitShutdownStopUnconfirmed: closed.implicitShutdownStopUnconfirmed, }); return remoteCloseScriptDelivery(response, closed.remoteScript); } @@ -408,6 +409,7 @@ type SessionCloseFinalization = /** #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: @@ -454,6 +456,7 @@ async function runCloseTeardownAndRelease(params: { implicitShutdownClaimLost, implicitShutdownLaunchedProcessGone, implicitShutdownLaunchedProcessUnverified, + implicitShutdownStopUnconfirmed, } = await runSessionCloseTeardown({ env: params.env, leaseRegistry, @@ -520,6 +523,7 @@ async function runCloseTeardownAndRelease(params: { implicitShutdownClaimLost, implicitShutdownLaunchedProcessGone, implicitShutdownLaunchedProcessUnverified, + implicitShutdownStopUnconfirmed, }; } @@ -533,6 +537,7 @@ function buildCloseSuccessResponse(params: { implicitShutdownClaimLost: boolean; implicitShutdownLaunchedProcessGone: boolean; implicitShutdownLaunchedProcessUnverified: boolean; + implicitShutdownStopUnconfirmed: boolean; }): DaemonResponse { const { session, @@ -544,6 +549,7 @@ function buildCloseSuccessResponse(params: { implicitShutdownClaimLost, implicitShutdownLaunchedProcessGone, implicitShutdownLaunchedProcessUnverified, + implicitShutdownStopUnconfirmed, } = params; if (repair.aborted && requestedSaveScript) { return { @@ -599,6 +605,12 @@ function buildCloseSuccessResponse(params: { : "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 }; } From 696e453f33ca5872fdc52ca9c8f941ca67d1e7e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 20 Nov 2026 10:02:10 +0100 Subject: [PATCH 10/10] refactor(close): keep launched-process outcomes on the teardown result The decide step no longer reads the launched process, so the two outcomes live only on the teardown result. The teardown comment states the residual window inside the Android stop's IME flush wait. --- .../session-close-lifecycle-teardown.ts | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) 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 895e56ea8a..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 @@ -43,6 +43,14 @@ type CloseDeviceStopDecision = Readonly<{ */ 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 @@ -55,14 +63,6 @@ type CloseDeviceStopDecision = Readonly<{ * for the recorded process. */ implicitShutdownLaunchedProcessUnverified: boolean; -}>; - -export type SessionCloseTeardownResult = Readonly<{ - platformCloseError: unknown; - retainExecutionHost: boolean; - saveScriptOutcome: OrdinaryCloseScript; - shutdownResult?: TargetShutdownResult; - shutdownPrepared: 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. @@ -107,8 +107,6 @@ async function decideDeviceStopOnClose(params: { (implicitShutdown && !implicitShutdownDeniedByPolicy && claimRenewal?.status === 'renewed'), implicitShutdownDeniedByPolicy, implicitShutdownClaimLost, - implicitShutdownLaunchedProcessGone: false, - implicitShutdownLaunchedProcessUnverified: false, }; } @@ -259,6 +257,8 @@ 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)