diff --git a/.changeset/close-stops-its-own-boot.md b/.changeset/close-stops-its-own-boot.md new file mode 100644 index 0000000000..fd0370ebce --- /dev/null +++ b/.changeset/close-stops-its-own-boot.md @@ -0,0 +1,7 @@ +--- +'agent-device': minor +--- + +Plain `close` now stops the local simulator or emulator that its own session `open` booted, so a session leaves the device as it found it. A device that was already running when the session opened keeps running, and physical and provider-owned devices are never stopped this way. The stop is reported in `data.shutdown`, the same field `close --shutdown` reports. + +This is a default change. `close --shutdown` keeps its meaning and still stops a device the session did not boot. A daemon policy that denies `device-shutdown` blocks both stops: there, `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. A close that stops a device no longer keeps that simulator's iOS runner warm for the next `open`. 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 5bb55728a1..9c05333831 100644 --- a/docs/agents/device-verification.md +++ b/docs/agents/device-verification.md @@ -31,7 +31,9 @@ A failed command can look like a fast success. Before you record the time of a c 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. +If this session's `open` booted a local simulator or emulator, use plain `close`. +If daemon policy denies `device-shutdown`, inspect the warning. +If a local device was already running, leave it 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/client/src/index.ts b/packages/client/src/index.ts index c03bb9c1ce..37c27640fd 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -267,10 +267,12 @@ export function createAgentDeviceClient( const session = resolveRequestSession(options); try { const data = await executeCommand>('close', options); + const warnings = readResponseWarnings(data); return { session, shutdown: normalizeTargetShutdownResult(data.shutdown), provider: asOptionalRecord(data.provider), + ...(warnings.length > 0 ? { warnings } : {}), savedScript: readOptionalString(data, 'savedScript'), identifiers: { session }, }; @@ -375,10 +377,12 @@ export function createAgentDeviceClient( close: async (options: AppCloseOptions = {}) => { const session = resolveRequestSession(options); const data = await executeCommand>('close', options); + const warnings = readResponseWarnings(data); return { session, closedApp: options.app, shutdown: normalizeTargetShutdownResult(data.shutdown), + ...(warnings.length > 0 ? { warnings } : {}), savedScript: readOptionalString(data, 'savedScript'), identifiers: { session }, }; 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-output/src/output/result-serialization.ts b/packages/command-output/src/output/result-serialization.ts index 1c07c1211d..c05bbedf47 100644 --- a/packages/command-output/src/output/result-serialization.ts +++ b/packages/command-output/src/output/result-serialization.ts @@ -177,6 +177,7 @@ export function serializeCloseResult( return { session: result.session, ...(result.shutdown ? { shutdown: result.shutdown } : {}), + ...(result.warnings?.length ? { warnings: result.warnings } : {}), ...('provider' in result && result.provider ? { provider: result.provider } : {}), ...successText( [ diff --git a/packages/command-surface/src/management/app.ts b/packages/command-surface/src/management/app.ts index 659b12319c..b7ee909810 100644 --- a/packages/command-surface/src/management/app.ts +++ b/packages/command-surface/src/management/app.ts @@ -93,10 +93,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. 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. 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. 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/client-app.ts b/packages/contracts/src/client-app.ts index a462387ed7..48ea4c495f 100644 --- a/packages/contracts/src/client-app.ts +++ b/packages/contracts/src/client-app.ts @@ -155,6 +155,11 @@ export type AppCloseResult = { session: string; closedApp?: string; shutdown?: TargetShutdownResult; + /** + * #4162: disclosure carried on the close response, e.g. the policy-refused stop of a device + * this session's own open booted. The close still succeeded; the warning says what stayed up. + */ + warnings?: string[]; /** * #1258: absolute path of the committed session/healed script when this close * published one (`close --save-script`, or a repair-armed session's finalize) diff --git a/packages/contracts/src/client-session.ts b/packages/contracts/src/client-session.ts index 22e2e91be2..9ce10d61cf 100644 --- a/packages/contracts/src/client-session.ts +++ b/packages/contracts/src/client-session.ts @@ -8,6 +8,11 @@ export type SessionCloseResult = { session: string; shutdown?: TargetShutdownResult; provider?: CloudProviderSessionResult; + /** + * #4162: disclosure carried on the close response, e.g. the policy-refused stop of a device + * this session's own open booted. The close still succeeded; the warning says what stayed up. + */ + warnings?: string[]; /** * #1258: absolute path of the committed session/healed script when this close * published one (`close --save-script`, or a repair-armed session's finalize) 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/core/__tests__/daemon-policy.test.ts b/packages/daemon/src/core/__tests__/daemon-policy.test.ts index 7ae94124e5..4469de8921 100644 --- a/packages/daemon/src/core/__tests__/daemon-policy.test.ts +++ b/packages/daemon/src/core/__tests__/daemon-policy.test.ts @@ -52,10 +52,17 @@ 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' })); + 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({ @@ -81,7 +88,7 @@ function makeHandler( hostDiagnostics: hostDiagnosticsFixture(), daemonPolicy, }); - return { handler, bind, inspectFacts }; + return { handler, bind, inspectFacts, sessionStore }; } function request(command: string, extra: Partial = {}): DaemonRequest { @@ -491,3 +498,17 @@ 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 } = makeHandler( + policy({ capabilities: { deny: ['device-shutdown'] } }), + { bootedByOpen: true }, + ); + 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/session-state.ts b/packages/daemon/src/core/session-state.ts index 439ddaf3d4..5a117da67b 100644 --- a/packages/daemon/src/core/session-state.ts +++ b/packages/daemon/src/core/session-state.ts @@ -171,6 +171,14 @@ 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; 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 bd83252834..a7f0c4e2cd 100644 --- a/packages/daemon/src/core/session-store.ts +++ b/packages/daemon/src/core/session-store.ts @@ -8,7 +8,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'; @@ -409,6 +414,16 @@ export class SessionStore { session.lastActivityAtMs = atMs; } + /** Carries boot ownership across reopens of the same device, never onto a replacement. */ + updateOpenDevice(ref: SessionRef, device: DeviceInfo, bootOccurred: boolean): void { + const current = this.requireCurrent(ref); + const retainsBoot = sameDeviceIdentity(deviceIdentity(current.device), deviceIdentity(device)); + this.update(ref, { + device, + bootedByOpen: bootOccurred || (retainsBoot && current.bootedByOpen) ? 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/server/__tests__/request-router-replay-scope.test.ts b/packages/daemon/src/server/__tests__/request-router-replay-scope.test.ts index afa6929bbe..a8fdb049ef 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,10 @@ 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 { 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 +64,54 @@ 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-'); + sessionStore.publish( + 'default', + makeIosSession('default', { bootedByOpen: true, appBundleId: 'com.example.app' }), + ); + const cleanup = platformResourceCleanupFixture(); + const handler = createRequestHandler({ + host: createTestHostEnvironment(), + 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 3cac1975ff..5df64d776f 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; @@ -414,6 +419,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..e9808f2c65 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, 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 a0a60750ea..7d8b70bf5b 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 8d41c4f193..e47e956af9 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'; @@ -73,6 +74,7 @@ export const handleReplayTestCommand: SessionCommandHandler = async ({ retainDeviceExecutionLock, throwIfCanceled, platformResourceCleanup, + deviceShutdownDenied, }) => { if (!platformResourceCleanup) { throw new AppError( @@ -122,6 +124,7 @@ export const handleReplayTestCommand: SessionCommandHandler = async ({ bindDevice, platformServices, platformResourceCleanup, + deviceShutdownDenied, }), ...(video ? { video } : {}), }); @@ -210,11 +213,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( @@ -225,7 +231,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, ), @@ -238,8 +246,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 bc5f36a645..20b14d7d82 100644 --- a/packages/daemon/src/sessions/session-lifecycle/__tests__/application.test.ts +++ b/packages/daemon/src/sessions/session-lifecycle/__tests__/application.test.ts @@ -60,12 +60,16 @@ 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({ 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-'), @@ -140,31 +144,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-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..dba902f84f --- /dev/null +++ b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-implicit-shutdown.test.ts @@ -0,0 +1,426 @@ +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, + 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; + if (bootedByOpen && params.claim !== 'missing') { + 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 === '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(), + ...(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', 'successor'] as const)( + 'plain close cannot stop a boot-owned device when its current claim is %s', + async (claim) => { + const { loader, finalizeApplicationClose } = lifecycleOperationsSpy(); + const { response, sessionStore, claims } = await closeSession({ + sessionName: 'lost-claim-session', + device: iosSimulator, + bootedByOpen: true, + claim, + lifecycleOperationsLoader: loader, + }); + expect(response?.ok).toBe(true); + 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..3e73816857 --- /dev/null +++ b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-open-boot-ownership.test.ts @@ -0,0 +1,109 @@ +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([false, true])( + 'a prepared cold reopen owns its boot before dispatch (fails: %s)', + async (fails) => { + const store = makeSessionStore(); + const device = { ...makeAndroidEmulator(), booted: false }; + const ref = store.publish('reopen', makeSession('reopen', device)); + const { loader } = lifecycleOperationsSpy({ + openApplication: async () => { + expect(store.requireCurrent(ref).bootedByOpen).toBe(true); + 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, loader), + }); + if (fails) await expect(pending).rejects.toThrow('Launch rejected'); + else expect((await pending).type).toBe('opened'); + expect(store.requireCurrent(ref).bootedByOpen).toBe(true); + }, +); + +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, 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 8a663bc6d4..2c4b9cd1b5 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,8 @@ 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 { 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 { SessionRef, SessionState } from '../../../core/session-state.ts'; import { SessionStore } from '../../../core/session-store.ts'; @@ -32,10 +34,16 @@ export type SessionCloseTeardownResult = Readonly<{ saveScriptError?: Error; shutdownResult?: TargetShutdownResult; shutdownPrepared: 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; }>; /** 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; @@ -53,6 +61,7 @@ export async function runSessionCloseTeardown(params: { platformCloseError: unknown; }): Error | undefined; platformResourceCleanup: PlatformResourceCleanup; + deviceShutdownDenied?: boolean; }): Promise { const { req, @@ -79,9 +88,24 @@ export async function runSessionCloseTeardown(params: { return undefined; } }; + // #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. + const explicitShutdown = req.flags?.shutdown === true; + const bootOwnedLocalStop = + session.bootedByOpen === true && lifecycle.owner.kind === 'local-family'; + const implicitShutdown = !explicitShutdown && bootOwnedLocalStop; + const implicitShutdownDeniedByPolicy = implicitShutdown && params.deviceShutdownDenied === true; + const shutdownRequested = + explicitShutdown || + (implicitShutdown && + !implicitShutdownDeniedByPolicy && + (await renewDeviceClaim(session.deviceClaim, params.env)).status === 'renewed'); const retainExecutionHost = params.platformResourceCleanup.retainExecutionHostAfterClose({ device: session.device, - shutdownRequested: req.flags?.shutdown === true, + shutdownRequested, hasScreenRecording: Boolean(session.screenRecording), leaseWillEnd: Boolean(session.lease) && @@ -121,7 +145,7 @@ 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', })) ?? {}, ); const saveScriptError = repairArmed @@ -136,6 +160,7 @@ export async function runSessionCloseTeardown(params: { saveScriptError, shutdownResult: finalization?.shutdown, shutdownPrepared: finalization !== undefined, + implicitShutdownDeniedByPolicy, }; } 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 ba8459ee6e..fa52911ea5 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts @@ -40,6 +40,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'; @@ -58,6 +59,7 @@ export type SessionCloseCommandInput = Readonly<{ platformServices: DaemonPlatformServices; bindDevice?: BindDeviceRuntime; platformResourceCleanup?: PlatformResourceCleanup; + deviceShutdownDenied?: boolean; }>; function toRepairPlatformCloseFailure(error: unknown): AppError { @@ -351,6 +353,7 @@ export async function handleSessionCloseCommands( clearRuntimeHints: admission.clearRuntimeHints, repairArmed: repair.repairArmed, platformResourceCleanup, + deviceShutdownDenied: params.deviceShutdownDenied, }), ); if (closed.kind === 'response') return closed.response; @@ -360,6 +363,7 @@ export async function handleSessionCloseCommands( requestedSaveScript: Boolean(req.flags?.saveScript), shutdownResult: closed.shutdownResult, providerData: closed.providerData, + implicitShutdownDeniedByPolicy: closed.implicitShutdownDeniedByPolicy, }); } @@ -386,6 +390,8 @@ type SessionCloseFinalization = kind: 'closed'; providerData?: Record; shutdownResult?: TargetShutdownResult; + /** #4162: the policy denied the stop this close owed its own boot, so the device kept running. */ + implicitShutdownDeniedByPolicy: boolean; }; // Everything between a settled repair decision and a success response: @@ -406,6 +412,7 @@ async function runCloseTeardownAndRelease(params: { clearRuntimeHints?: RuntimeHintClearOperation; repairArmed: boolean; platformResourceCleanup: PlatformResourceCleanup; + deviceShutdownDenied?: boolean; }): Promise { const { req, @@ -425,7 +432,9 @@ async function runCloseTeardownAndRelease(params: { saveScriptError, shutdownPrepared, shutdownResult, + implicitShutdownDeniedByPolicy, } = await runSessionCloseTeardown({ + env: params.env, leaseRegistry, req, ref, @@ -438,6 +447,7 @@ async function runCloseTeardownAndRelease(params: { dispatchTargetedPlatformClose, finalizeOrdinaryCloseScript, platformResourceCleanup: params.platformResourceCleanup, + deviceShutdownDenied: params.deviceShutdownDenied, }); let session = sessionStore.requireCurrent(ref); // Each cleanup report is built where the session's fate is decided, so its diagnostic and hint @@ -483,6 +493,7 @@ async function runCloseTeardownAndRelease(params: { kind: 'closed', providerData: leaseRelease.providerData, shutdownResult: leaseRelease.shutdownResult ?? shutdownResult, + implicitShutdownDeniedByPolicy, }; } @@ -492,8 +503,16 @@ function buildCloseSuccessResponse(params: { requestedSaveScript: boolean; shutdownResult: TargetShutdownResult | undefined; providerData: Record | undefined; + implicitShutdownDeniedByPolicy: boolean; }): DaemonResponse { - const { session, repair, requestedSaveScript, shutdownResult, providerData } = params; + const { + session, + repair, + requestedSaveScript, + shutdownResult, + providerData, + implicitShutdownDeniedByPolicy, + } = params; if (repair.aborted && requestedSaveScript) { return { ok: false, @@ -511,19 +530,21 @@ 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 }, - }; + 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 977911dfe1..6ae1ba2935 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 @@ -267,6 +267,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, @@ -277,6 +281,7 @@ export async function completeOpenCommand(params: { sessionAppBundleId, appName, existingRef, + bootedByOpen: preparedSelection?.bootOccurred === true, }); if (provisionalSession.type === 'response') return provisionalSession; const openDispatchRef = provisionalSession.ref; @@ -321,7 +326,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; @@ -396,6 +400,7 @@ export async function completeOpenCommand(params: { appBundleId: sessionAppBundleId, appName, deviceClaim, + bootedByOpen: preparedSelection?.bootOccurred === true, }); sessionStore.clearCloseEffectsUnconfirmed(nextRef); const nextSession = sessionStore.requireCurrent(nextRef); @@ -428,12 +433,16 @@ async function prepareOpenDispatchSession(params: { sessionAppBundleId: string | undefined; appName: string | undefined; existingRef: SessionRef | undefined; + bootedByOpen: boolean; }): 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); + return { type: 'session', ref: existingRef }; + } const ref = publishOpenSession({ req, sessionName, @@ -443,6 +452,7 @@ async function prepareOpenDispatchSession(params: { surface: params.surface, appBundleId: params.sessionAppBundleId, appName: params.appName, + bootedByOpen: params.bootedByOpen, }); const lifecycleResponse = await beforeDispatch(); if (lifecycleResponse && !lifecycleResponse.ok) 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..25e485d535 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,7 @@ 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 +31,8 @@ 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; }): SessionRef { const { req, @@ -42,11 +44,12 @@ export function publishOpenSession(params: { appBundleId, appName, deviceClaim, + bootedByOpen, } = params; requireOpenSessionAdmission(store, sessionName, existingRef); if (existingRef) { + store.updateOpenDevice(existingRef, device, bootedByOpen === true); const session = store.update(existingRef, { - device, surface, appBundleId, appName, @@ -56,7 +59,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 +70,8 @@ export function publishOpenSession(params: { actions: [], lease: resolveSessionLeaseForRequest({ req }), deviceClaim, - }); + }; + const ref = store.publish(sessionName, draft); + if (bootedByOpen === true) store.updateOpenDevice(ref, device, true); + 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 019ece1434..8594a7fcb5 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-open.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-open.ts @@ -42,7 +42,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, @@ -406,7 +409,8 @@ 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..a6781cbb45 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. + * Provider and physical targets never claim a daemon-owned 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 === 'provider') return selection; const { device } = selection; const bootedByThisOpen = device.booted !== true && (device.kind === 'simulator' || device.kind === 'emulator'); 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 607ae8e22a..eee9e1d843 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') { @@ -133,6 +134,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 ab8719ed49..804ecc4af9 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 @@ -111,10 +111,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; @@ -241,7 +242,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 fa1f8ec1d3..589662c177 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 ecdf22b2fa..ed9b89fa0c 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/packages/replay-test/src/internal/session-test-types.ts b/packages/replay-test/src/internal/session-test-types.ts index a7dfe1ca44..43358c4f4c 100644 --- a/packages/replay-test/src/internal/session-test-types.ts +++ b/packages/replay-test/src/internal/session-test-types.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/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..586aff494d 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', // #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 96f7649726..90eee9cb21 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`. Reaching an off-screen target is one command, not a scroll-and-check loop: `scroll down --until ` scrolls until that element is on screen, and `scroll bottom` runs to the end of the content. Repeated bare `scroll down` calls are the slow way to find something. diff --git a/skills/android-emulator/SKILL.md b/skills/android-emulator/SKILL.md index 433f57c9ee..4207fb88a8 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`. 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 972ac8874d..ccc61e5cba 100644 --- a/skills/dogfood/SKILL.md +++ b/skills/dogfood/SKILL.md @@ -22,6 +22,6 @@ 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). Target app is required; infer platform or ask. Findings must come from runtime behavior, not source reads. Let `help dogfood` provide exact report shape, evidence commands, and current workflow guidance. 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 beac717dfe..20954c000a 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. A device that was already running keeps running. Command shapes: agent-device open com.example.app --relaunch @@ -285,7 +285,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. 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 98929c16eb..ae35049442 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -129,7 +129,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 @@ -411,7 +411,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. @@ -614,7 +614,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/website/docs/docs/commands.md b/website/docs/docs/commands.md index 888e4b04fe..3fcdba4e25 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -105,6 +105,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`. 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. - 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. - If `open --relaunch` leaves an existing session's device effects unconfirmed, the session and claim remain available for `close`, but idle shutdown can retry cleanup and leave an unconfirmed claim stale; embedded runtimes and `AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS=0` do not shut down for idleness, so use `close` to release the claim. diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index b8b920091c..671e90dc0d 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -284,7 +284,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..ae092e89bd 100644 --- a/website/docs/docs/sessions.md +++ b/website/docs/docs/sessions.md @@ -118,18 +118,35 @@ 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 +``` + +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 +246,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