From 637a24501b1795ea4c9305d203e355f84c86150b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 20 Nov 2026 23:02:54 +0100 Subject: [PATCH 1/2] fix(close): stop an Apple simulator only on its open's own boot proof MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Plain `close` stopped an Apple simulator whenever the pre-open inventory snapshot said the device was stopped, which is an inference about a moment before the boot, not a fact about the boot (#4791). Anything else could have booted the simulator in that window — a concurrent `xcrun simctl boot`, another workspace, a person at the machine — and closing the session then shut down a boot the session never caused. The stop now requires positive proof from the step that could have performed it: the readiness call the open makes reports whether its own `simctl boot` started the boot, and only that answer gives the session a boot to stop. `open`'s preparation accepts an optional boot report and the Apple lifecycle forwards readiness's answer into it, so the port's other implementers are unchanged. Readiness answers on every exit: performed when it issued the boot, `already-booted` when the memo hit or the listing found the Simulator up or CoreSimulator refused the boot, and `no-boot-attempt` for macOS and physical devices. An owner that boots the device through a step outside its preparation, which is the daemon's Android emulator launch, answers nothing, so Android keeps its existing launched-process ownership. `resolveSessionBootOwnership` in contracts turns the pair of answers into the ownership the session records, and `SessionStore.updateOpenDevice` writes it beside `bootedByOpen` in the same store-owned write. A disproved re-open cannot take back a boot an earlier open of the same device proved, so the reason is recorded only alongside the ownership it refused. When the inference is refused, plain `close` keeps the simulator running and names `boot-owner-unverified` in `warnings`, so a kept-running device is never silent. `close --shutdown` still commands the stop without asking the ownership question, and an open that proved its boot still stops the device as before. --- .../command-surface/src/management/app.ts | 2 +- .../src/application-lifecycle-runtime.ts | 9 + packages/contracts/src/device-boot.ts | 52 ++++++ .../support/boot-ownership-fixtures.ts | 11 ++ packages/daemon/src/core/session-state.ts | 8 + packages/daemon/src/core/session-store.ts | 11 +- .../session-replay-command-capture.test.ts | 2 + .../session-close-external-reboot.test.ts | 7 +- .../session-close-foreign-boot.test.ts | 174 ++++++++++++++++++ .../__tests__/session-open-state.test.ts | 67 ++++++- .../session-close-lifecycle-teardown.ts | 10 + .../internal/session-close.ts | 17 ++ .../internal/session-open-execution.ts | 25 ++- .../internal/session-open-prepare.ts | 10 + .../internal/session-open-state.ts | 18 +- .../internal/session-open.ts | 1 + packages/platform-apple/src/core/simctl.ts | 14 ++ packages/platform-apple/src/core/simulator.ts | 12 +- packages/platform-apple/src/lifecycle.ts | 3 + .../src/readiness/runtime.test.ts | 73 ++++++++ .../platform-apple/src/readiness/runtime.ts | 44 ++++- scripts/layering/session-state.ts | 3 + .../runner-refusal-reason-docs.test.ts | 5 + website/docs/docs/commands.md | 4 +- website/docs/docs/sessions.md | 4 + 25 files changed, 546 insertions(+), 40 deletions(-) create mode 100644 packages/daemon/src/__tests__/support/boot-ownership-fixtures.ts create mode 100644 packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-foreign-boot.test.ts diff --git a/packages/command-surface/src/management/app.ts b/packages/command-surface/src/management/app.ts index 22a99e7d59..a67f3c46ec 100644 --- a/packages/command-surface/src/management/app.ts +++ b/packages/command-surface/src/management/app.ts @@ -95,7 +95,7 @@ const openCommandMetadata = defineFieldCommandMetadata( const closeCommandMetadata = defineFieldCommandMetadata( 'close', - "Close the named app, or close the active session app when app is omitted. When this session's open booted a local simulator or emulator, close stops it too, leaving the device as the session found it; a device that was already running keeps running. When the emulator process its own open launched is gone or cannot be verified, plain close leaves the emulator running and warns. Pass shutdown to explicitly stop a local simulator or emulator regardless of boot ownership. A daemon whose policy denies device-shutdown skips the implicit stop on plain close, which succeeds with a warning that the local device stays running. Explicit close with shutdown fails with UNAUTHORIZED and details.reason DAEMON_POLICY_DENIED. Android ADB close fails with android-app-close-timeout if the app stays foreground past 2s, a killed process does not exit within 10s, or a new process runs past 2s; a relaunching open accepts that new process. For foreground timeouts, JSON details include foregroundObservations and initialProcessCount; the android_close_foreground_fence request diagnostic retains the last five probe results and timings, including when a probe throws. It fails with android-process-probe-unavailable when adb pidof cannot list the app processes; if that happens before the force-stop, the app keeps running. If close cannot confirm its cleanup on a session that holds a device claim, the session and its claim stay. A repeated close retries cleanup with the same options, except that save-script must be omitted after publication.", + "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. For an Apple simulator, the proof that open booted it is that open's own boot step performed the boot; when something else booted it first, plain close leaves the simulator running and warns with boot-owner-unverified. When the emulator process its own open launched is gone or cannot be verified, plain close leaves the emulator running and warns. Pass shutdown to explicitly stop a local simulator or emulator regardless of boot ownership. A daemon whose policy denies device-shutdown skips the implicit stop on plain close, which succeeds with a warning that the local device stays running. Explicit close with shutdown fails with UNAUTHORIZED and details.reason DAEMON_POLICY_DENIED. Android ADB close fails with android-app-close-timeout if the app stays foreground past 2s, a killed process does not exit within 10s, or a new process runs past 2s; a relaunching open accepts that new process. For foreground timeouts, JSON details include foregroundObservations and initialProcessCount; the android_close_foreground_fence request diagnostic retains the last five probe results and timings, including when a probe throws. It fails with android-process-probe-unavailable when adb pidof cannot list the app processes; if that happens before the force-stop, the app keeps running. If close cannot confirm its cleanup on a session that holds a device claim, the session and its claim stay. A repeated close retries cleanup with the same options, except that save-script must be omitted after publication.", { app: stringField('Optional app to close.'), shutdown: booleanField( diff --git a/packages/contracts/src/application-lifecycle-runtime.ts b/packages/contracts/src/application-lifecycle-runtime.ts index b1e01d7e76..69b066a866 100644 --- a/packages/contracts/src/application-lifecycle-runtime.ts +++ b/packages/contracts/src/application-lifecycle-runtime.ts @@ -6,6 +6,7 @@ import type { RunnerLogicalLeaseContext } from './runner-lease-context.ts'; import type { SessionSurface } from './session-surface.ts'; import type { ProviderPortReverseOptions } from './provider-device-runtime.ts'; import type { TargetShutdownResult } from './target-shutdown-contract.ts'; +import type { DeviceBootPerformance } from './device-boot.ts'; /** * A deliberately neutral runtime-hint payload. Daemon policy owns parsing and @@ -84,6 +85,14 @@ export type OpenApplicationPreparationInput = Readonly<{ surface: SessionSurface; prewarmRunnerOnColdBoot: boolean; execution: ApplicationLifecycleExecution; + /** + * #4791: an owner whose preparation contains the step that could boot the device reports what that + * step did with its own call: `performed: true` is positive proof this open booted the device, and + * a `performed: false` answer is positive proof it did not, whatever an earlier inventory snapshot + * said. An owner that performs no boot step in its preparation answers nothing — answering for a + * boot made elsewhere would misreport this call. + */ + onBootPerformance?: (performance: DeviceBootPerformance) => void; }>; /** diff --git a/packages/contracts/src/device-boot.ts b/packages/contracts/src/device-boot.ts index 87378e42f7..c48848a5e9 100644 --- a/packages/contracts/src/device-boot.ts +++ b/packages/contracts/src/device-boot.ts @@ -79,6 +79,58 @@ export type LaunchedDeviceProcessService = Readonly<{ ): Promise; }>; +/** + * What the boot step of an `open` reports about its OWN call. Boot ownership needs positive proof, so + * an owner that started the boot reports `performed: true`, and an owner that found the device already + * up reports that too — `already-booted` is the tool's own answer for a device that was up before the + * call, `no-boot-attempt` is the answer when readiness settled the device without reaching a boot. An + * owner whose readiness step reports nothing leaves the port unset rather than guessing. + */ +export type DeviceBootPerformance = + | Readonly<{ performed: true }> + | Readonly<{ performed: false; reason: 'already-booted' | 'no-boot-attempt' }>; + +/** + * The warning token plain `close` publishes when the platform answered its own boot step with "this + * call did not boot the device", so the session has no boot of its own to stop and whatever is running + * belongs to somebody else. Callers read a member; none writes a literal. + */ +export const CLOSE_BOOT_OWNER_UNVERIFIED_REASONS = { + bootOwnerUnverified: 'boot-owner-unverified', +} as const satisfies Record; + +/** + * Whether a session's `open` owns stopping the device it holds, and whether it must say why not. + * + * #4791: a boot the platform reports performing is positive proof, so it owns the boot whatever the + * snapshot said. A device-selection snapshot only says the device was STOPPED when the open looked at + * it, which is not proof the open booted it: anything else could have booted it in the meantime, and + * nothing about booting a simulator claims the device. So when the platform answers that its own boot + * step did not boot the device, the session owns no stop and reports the inference it refused. An + * owner whose open boots the device through some step of its own, outside the preparation that reports + * (the daemon's Android emulator launch), reports nothing, which leaves the snapshot inference in + * charge for that family. + */ +export type CloseBootOwnership = Readonly<{ + ownsBoot: boolean; + bootOwnerUnverified: boolean; +}>; + +export function resolveSessionBootOwnership( + input: Readonly<{ + /** Device selection's inference: the pre-open snapshot said this stopped local device needed a boot. */ + inferredFromSnapshot: boolean; + /** What the platform's own boot step reported about its call, when that owner reports at all. */ + bootPerformance: DeviceBootPerformance | undefined; + }>, +): CloseBootOwnership { + const disprovesSnapshot = input.bootPerformance?.performed === false; + return { + ownsBoot: input.inferredFromSnapshot && !disprovesSnapshot, + bootOwnerUnverified: input.inferredFromSnapshot && disprovesSnapshot, + }; +} + /** * The `details.failedOpenEmulatorCleanupReason` values a failed open publishes, from the owner of * this outcome. Callers read a member; none writes a literal. diff --git a/packages/daemon/src/__tests__/support/boot-ownership-fixtures.ts b/packages/daemon/src/__tests__/support/boot-ownership-fixtures.ts new file mode 100644 index 0000000000..79fee1ad26 --- /dev/null +++ b/packages/daemon/src/__tests__/support/boot-ownership-fixtures.ts @@ -0,0 +1,11 @@ +import type { CloseBootOwnership } from '@agent-device/contracts/device-boot'; + +/** + * The boot-ownership pair an `open` records when it proved nothing about the device's boot: it owns no + * stop, and it disproved nothing. Suites that are not about boot ownership pass this instead of + * inventing one of their own, so a new field of the pair cannot be quietly defaulted away. + */ +export const NO_BOOT_PROOF: CloseBootOwnership = { + ownsBoot: false, + bootOwnerUnverified: false, +}; diff --git a/packages/daemon/src/core/session-state.ts b/packages/daemon/src/core/session-state.ts index 0a01a1b09a..c53dc8138e 100644 --- a/packages/daemon/src/core/session-state.ts +++ b/packages/daemon/src/core/session-state.ts @@ -182,6 +182,14 @@ export type SessionState = { * through `SessionStore.updateOpenDevice`; changing device identity clears it. Close only reads it. */ bootedByOpen?: true; + /** + * #4791: this session's `open` inferred a boot from a pre-open snapshot that said the device was + * stopped, and the platform then answered its own boot step with "this call did not boot it". The + * session therefore owns no stop, and a plain `close` reports in `warnings` that it left the device + * running rather than stopping a boot it never caused. Recorded and cleared by the same + * `SessionStore.updateOpenDevice` write as `bootedByOpen`; close only reads it. + */ + bootOwnerUnverified?: true; androidLaunchIdentity?: AndroidEmulatorLaunchIdentity; createdAt: number; surface?: SessionSurface; diff --git a/packages/daemon/src/core/session-store.ts b/packages/daemon/src/core/session-store.ts index eb77495296..27796cad07 100644 --- a/packages/daemon/src/core/session-store.ts +++ b/packages/daemon/src/core/session-store.ts @@ -1,4 +1,5 @@ import type { AndroidEmulatorLaunchIdentity } from '@agent-device/contracts/device-readiness-runtime'; +import type { CloseBootOwnership } from '@agent-device/contracts/device-boot'; import { resolveSessionDir, resolveSessionAppLogPath, @@ -428,20 +429,24 @@ export class SessionStore { updateOpenDevice( ref: SessionRef, device: DeviceInfo, - bootOccurred: boolean, + bootOwnership: CloseBootOwnership, androidLaunchIdentity?: AndroidEmulatorLaunchIdentity, ): void { const current = this.requireCurrent(ref); const retainsBoot = sameDeviceIdentity(deviceIdentity(current.device), deviceIdentity(device)); - const ownsBoot = bootOccurred || (retainsBoot && current.bootedByOpen === true); + const ownsBoot = bootOwnership.ownsBoot || (retainsBoot && current.bootedByOpen === true); this.update(ref, { device, - androidLaunchIdentity: bootOccurred + androidLaunchIdentity: bootOwnership.ownsBoot ? androidLaunchIdentity : retainsBoot ? current.androidLaunchIdentity : undefined, bootedByOpen: ownsBoot ? true : undefined, + // #4791: the reason is reported only alongside the ownership it refused. A re-open that disproves + // its OWN boot cannot erase a boot an earlier open of this same device proved and #4162 keeps, so + // that close stops on the preserved proof and says nothing. + bootOwnerUnverified: !ownsBoot && bootOwnership.bootOwnerUnverified ? true : undefined, }); } diff --git a/packages/daemon/src/sessions/handlers/session-replay-command-capture.test.ts b/packages/daemon/src/sessions/handlers/session-replay-command-capture.test.ts index 1cba1d6d48..6ee29afea9 100644 --- a/packages/daemon/src/sessions/handlers/session-replay-command-capture.test.ts +++ b/packages/daemon/src/sessions/handlers/session-replay-command-capture.test.ts @@ -31,6 +31,7 @@ import { } from '../../__tests__/support/legacy-snapshot-capture-fixture.ts'; import { captureSnapshotWithInteractor } from '../../core/snapshot-interactor-capture.ts'; import { daemonPlatformServicesFixture } from '../../__tests__/support/platform-services-fixture.ts'; +import { NO_BOOT_PROOF } from '../../__tests__/support/boot-ownership-fixtures.ts'; import { selectorCaptureFixture } from '../../__tests__/support/selector-capture-fixture.ts'; import { SAVE_ANNOTATION, @@ -185,6 +186,7 @@ test.each(['close and reopen', 'open with refreshed device'])( device: closes ? initial.session.device : { ...initial.session.device }, surface: 'app', appBundleId: initial.session.appBundleId, + bootOwnership: NO_BOOT_PROOF, }); } return { ok: true, data: {} }; diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-external-reboot.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-external-reboot.test.ts index 572f1a23ff..9e1932b2e2 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-external-reboot.test.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-external-reboot.test.ts @@ -52,6 +52,7 @@ import { inspectDeviceClaims, } from '@agent-device/daemon-contracts/device-claims'; import { SessionStore } from '../../../../core/session-store.ts'; +import { NO_BOOT_PROOF } from '../../../../__tests__/support/boot-ownership-fixtures.ts'; import { resolveTargetDevice } from '@agent-device/device-selection/dispatch-resolve'; import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -460,7 +461,11 @@ test('changing the device serial clears launch ownership', async () => { const runs = createRoutedSession(); await openBootedByThisSession(runs); const ref = runs.sessionStore.lookup(SESSION)!; - runs.sessionStore.updateOpenDevice(ref, { ...BOOTED_EMULATOR, id: 'emulator-5556' }, false); + runs.sessionStore.updateOpenDevice( + ref, + { ...BOOTED_EMULATOR, id: 'emulator-5556' }, + NO_BOOT_PROOF, + ); expect(runs.sessionStore.get(SESSION)?.androidLaunchIdentity).toBeUndefined(); expect(runs.sessionStore.get(SESSION)?.bootedByOpen).toBeUndefined(); }); diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-foreign-boot.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-foreign-boot.test.ts new file mode 100644 index 0000000000..93ef193a09 --- /dev/null +++ b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-foreign-boot.test.ts @@ -0,0 +1,174 @@ +// #4791: plain `close` stops an Apple simulator only when open has positive proof that its OWN boot +// step performed the boot. The pre-open snapshot says only that the device was stopped when the open +// looked at it, so anything else could have booted it in the meantime — a concurrent `simctl boot`, +// another workspace, a person at the machine. Routed through the session command handler, so +// selection, readiness, claim acquisition, boot-ownership recording and close teardown all run for +// real. The platform's own boot report is answered by the lifecycle fixture at the port, exactly as +// the Apple readiness step answers it; the readiness mechanics themselves are pinned in the platform +// package's own suite. +import { beforeEach, expect, test, vi } from 'vitest'; +import path from 'node:path'; +import * as hostProcess from '@agent-device/host-kit/process'; +import { + bindTestCommandHost, + createTestHostEnvironment, + mkdtempForTestSync, + pinOwnProcessStartTime, +} from '@agent-device/test-kit'; + +vi.mock('@agent-device/device-selection/dispatch-resolve', async (importOriginal) => { + const actual = + await importOriginal(); + const { selectionFromResolveTargetDevice } = + await import('../../../../__tests__/support/device-selection-stub.ts'); + const resolveTargetDevice = vi.fn(); + return { + ...actual, + resolveTargetDevice, + resolveTargetDeviceSelection: vi.fn(selectionFromResolveTargetDevice(resolveTargetDevice)), + }; +}); + +import { fakeCreateCommandSurface } from '../../../../__tests__/support/command-surface-fake.ts'; +import { daemonPlatformServicesFixture } from '../../../../__tests__/support/platform-services-fixture.ts'; +import type { DeviceBootPerformance } from '@agent-device/contracts/device-boot'; +import { CLOSE_BOOT_OWNER_UNVERIFIED_REASONS } from '@agent-device/contracts/device-boot'; +import { + applicationLifecycleRuntimeFixture, + type LifecycleOperationsLoader, +} from '../../../../__tests__/support/application-lifecycle-runtime-fixture.ts'; +import { + handleSessionCommands, + mockShutdownTargetRuntime, +} from '../../../../__tests__/support/handlers/session-command-harness.ts'; +import { inspectDeviceClaims } from '@agent-device/daemon-contracts/device-claims'; +import { SessionStore } from '../../../../core/session-store.ts'; +import { resolveTargetDevice } from '@agent-device/device-selection/dispatch-resolve'; +import type { DeviceInfo } from '@agent-device/kernel/device'; + +pinOwnProcessStartTime(hostProcess); +bindTestCommandHost(); + +const SESSION = 'foreign-boot-session'; + +/** The simulator as inventory lists it while shut down, which is all the open's snapshot ever sees. */ +const STOPPED_SIMULATOR: DeviceInfo = { + platform: 'apple', + appleOs: 'ios', + id: 'sim-udid-4791', + name: 'iPhone 17 Pro', + kind: 'simulator', + booted: false, +}; + +/** The same simulator once it runs, which is what the open binds and the session holds. */ +const BOOTED_SIMULATOR: DeviceInfo = { ...STOPPED_SIMULATOR, booted: true }; + +function createRoutedSession() { + const stateDir = mkdtempForTestSync('agent-device-session-close-foreign-boot-'); + const env: NodeJS.ProcessEnv = { + ...process.env, + AGENT_DEVICE_CLAIMS_DIR: path.join(stateDir, 'claims'), + }; + const sessionStore = new SessionStore(path.join(stateDir, 'sessions'), { + env, + cwd: process.cwd(), + }); + + async function run(command: { + name: 'open' | 'close'; + flags?: Record; + /** What the platform's own boot step reports about the open's preparation call. */ + bootPerformance?: DeviceBootPerformance; + }) { + if (command.name === 'open') { + // Selection sees a shut-down simulator, which is the inference #4791 refuses to act on alone. + vi.mocked(resolveTargetDevice).mockResolvedValue(STOPPED_SIMULATOR); + } + const loader: LifecycleOperationsLoader = async (device, signal, shutdownTarget) => { + const operations = await applicationLifecycleRuntimeFixture(device, signal, shutdownTarget); + return Object.freeze({ + ...operations, + prepareApplicationOpen: async ( + input: Parameters[0], + ) => { + input.onBootPerformance?.(command.bootPerformance!); + }, + }); + }; + const response = await handleSessionCommands({ + host: createTestHostEnvironment({ env }), + createCommandSurface: fakeCreateCommandSurface, + platformServices: daemonPlatformServicesFixture(), + sessionStore, + invoke: async () => ({ ok: true, data: {} }), + lifecycleOperationsLoader: loader, + req: { + token: 't', + command: command.name, + session: SESSION, + positionals: command.name === 'open' ? ['Demo'] : [], + flags: command.flags ?? {}, + }, + sessionName: SESSION, + logPath: path.join(stateDir, 'daemon.log'), + }); + return response; + } + + return { run, sessionStore, env }; +} + +function closeWarnings(response: { ok?: unknown; data?: unknown }): unknown { + if (!response.ok) throw new Error('expected a successful close'); + return (response.data as { warnings?: string[] }).warnings; +} + +beforeEach(() => { + vi.mocked(resolveTargetDevice).mockReset(); + mockShutdownTargetRuntime.mockClear(); +}); + +test('plain close keeps a simulator the platform says its own boot step never booted', async () => { + const runs = createRoutedSession(); + + // The snapshot said stopped, so selection inferred a boot; the platform's boot step then answered + // that the simulator was already up when it asked, which is the foreign boot. + const opened = await runs.run({ + name: 'open', + bootPerformance: { performed: false, reason: 'already-booted' }, + }); + expect(opened?.ok).toBe(true); + + const session = runs.sessionStore.get(SESSION); + expect(session?.bootedByOpen).toBeUndefined(); + expect(session?.bootOwnerUnverified).toBe(true); + + const closed = await runs.run({ name: 'close' }); + + expect(closed?.ok).toBe(true); + expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); + // The kept-running device is reported, and the reason is the published vocabulary member. + expect(closeWarnings(closed!)).toEqual([ + expect.stringContaining(CLOSE_BOOT_OWNER_UNVERIFIED_REASONS.bootOwnerUnverified), + ]); + // A plain close that stops nothing still succeeds and retires the session with its claim. + expect(runs.sessionStore.get(SESSION)).toBeUndefined(); + expect(inspectDeviceClaims({ serial: BOOTED_SIMULATOR.id }, runs.env)).toEqual([]); +}, 30_000); + +test('plain close stops the simulator whose boot the platform reports performing', async () => { + const runs = createRoutedSession(); + + const opened = await runs.run({ name: 'open', bootPerformance: { performed: true } }); + expect(opened?.ok).toBe(true); + expect(runs.sessionStore.get(SESSION)?.bootedByOpen).toBe(true); + expect(runs.sessionStore.get(SESSION)?.bootOwnerUnverified).toBeUndefined(); + + const closed = await runs.run({ name: 'close' }); + + expect(closed?.ok).toBe(true); + expect(mockShutdownTargetRuntime).toHaveBeenCalledTimes(1); + expect(closeWarnings(closed!)).toBeUndefined(); + if (closed?.ok) expect(closed.data).toMatchObject({ shutdown: { success: true } }); +}, 30_000); 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 93c635c80c..8bb5a8e946 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 @@ -2,6 +2,7 @@ import assert from 'node:assert/strict'; import { test } from 'vitest'; import { publishOpenSession } from '../session-open-state.ts'; import { makeSessionStore } from './session-open-runtime.fixtures.ts'; +import { NO_BOOT_PROOF } from '../../../../__tests__/support/boot-ownership-fixtures.ts'; import { authoringPublication, makeIosSession, @@ -28,6 +29,7 @@ function reopen(existingSession: ReturnType) { device: IOS_SIMULATOR, surface: 'app', appBundleId: 'com.example.other', + bootOwnership: NO_BOOT_PROOF, }), ); } @@ -69,7 +71,7 @@ function firstOpen(bootedByOpen: boolean | undefined) { sessionName: 's', device: IOS_SIMULATOR, surface: 'app', - bootedByOpen, + bootOwnership: { ownsBoot: bootedByOpen === true, bootOwnerUnverified: false }, }).session; } @@ -98,7 +100,7 @@ test.each([false, true])('replacement target owns only its own boot: %s', (repla existingRef: ref, device: { ...IOS_SIMULATOR, id: 'replacement-simulator' }, surface: 'app', - bootedByOpen: replacementBooted, + bootOwnership: { ownsBoot: replacementBooted, bootOwnerUnverified: false }, }), ); assert.equal(next.bootedByOpen, replacementBooted ? true : undefined); @@ -119,7 +121,7 @@ test.each(bootOwnershipFacts)( existingRef: ref, device: IOS_SIMULATOR, surface: 'app', - bootedByOpen: true, + bootOwnership: { ownsBoot: true, bootOwnerUnverified: false }, }), ); @@ -142,10 +144,67 @@ test.each(bootOwnershipFacts)( existingRef: ref, device: IOS_SIMULATOR, surface: 'app', - bootedByOpen: false, + bootOwnership: NO_BOOT_PROOF, }), ); assert.equal(next.bootedByOpen, bootedByOpen); }, ); + +test('#4791: an open the platform disproved records no boot and the reason close reports', () => { + const store = makeSessionStore(); + const next = publishOpenSession({ + req: { token: 't', command: 'open', positionals: [], session: 's' }, + sessionStore: store, + sessionName: 's', + device: IOS_SIMULATOR, + surface: 'app', + bootOwnership: { ownsBoot: false, bootOwnerUnverified: true }, + }).session; + + assert.equal(next.bootedByOpen, undefined); + assert.equal(next.bootOwnerUnverified, true); +}); + +test('#4791: a re-open of the same target clears the disproved boot with its own proof', () => { + const store = makeSessionStore(); + const existing = makeIosSession('s', { bootOwnerUnverified: 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, + surface: 'app', + bootOwnership: NO_BOOT_PROOF, + }), + ); + + assert.equal(next.bootOwnerUnverified, undefined); +}); + +test('#4791: a disproved re-open cannot take back a boot an earlier open of the same device proved', () => { + 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, + surface: 'app', + bootOwnership: { ownsBoot: false, bootOwnerUnverified: true }, + }), + ); + + // Close stops on the preserved proof, so it must not also report a stop it withheld. + assert.equal(next.bootedByOpen, true); + assert.equal(next.bootOwnerUnverified, undefined); +}); 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 4bc70b3b19..0a5b3a4b00 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-close-lifecycle-teardown.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-close-lifecycle-teardown.ts @@ -43,6 +43,11 @@ type CloseDeviceStopDecision = Readonly<{ */ implicitShutdownDeniedByPolicy: boolean; implicitShutdownClaimLost: boolean; + /** + * #4791: the session recorded the snapshot's boot inference and the platform then said its own boot + * step did not boot the device, so close owns no stop and reports the device it left running. + */ + implicitShutdownBootOwnerUnverified: boolean; }>; export type SessionCloseTeardownResult = Readonly<{ @@ -96,6 +101,10 @@ async function decideDeviceStopOnClose(params: { const { session } = params; const implicitShutdown = !params.explicitShutdown && session.bootedByOpen === true && params.localFamily; + // #4791: the open recorded a boot the platform later said it did not perform, so there is no stop + // for this close to owe. The device is somebody else's boot and stays as it is. + const implicitShutdownBootOwnerUnverified = + !params.explicitShutdown && session.bootOwnerUnverified === true && params.localFamily; const claimRenewal = implicitShutdown ? await renewDeviceClaim(session.deviceClaim, params.env) : undefined; @@ -108,6 +117,7 @@ async function decideDeviceStopOnClose(params: { (implicitShutdown && !implicitShutdownDeniedByPolicy && claimRenewal?.status === 'renewed'), implicitShutdownDeniedByPolicy, implicitShutdownClaimLost, + implicitShutdownBootOwnerUnverified, }; } 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 9b1b5f14ab..254b7ac1e2 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts @@ -50,6 +50,7 @@ import { closeCleanupError, runSessionCloseTeardown } from './session-close-life import type { PlatformResourceCleanup } from '../../../core/platform-resource-cleanup.ts'; import { errorResponse } from '@agent-device/kernel/contracts'; import { resolveCloseTargetRuntimeUse } from '@agent-device/contracts/application-lifecycle-runtime-plan'; +import { CLOSE_BOOT_OWNER_UNVERIFIED_REASONS } from '@agent-device/contracts/device-boot'; import { admitRuntimeUse } from '../../../core/runtime-admission.ts'; export type SessionCloseCommandInput = Readonly<{ @@ -371,6 +372,7 @@ export async function handleSessionCloseCommands( providerData: closed.providerData, implicitShutdownDeniedByPolicy: closed.implicitShutdownDeniedByPolicy, implicitShutdownClaimLost: closed.implicitShutdownClaimLost, + implicitShutdownBootOwnerUnverified: closed.implicitShutdownBootOwnerUnverified, implicitShutdownLaunchedProcessGone: closed.implicitShutdownLaunchedProcessGone, implicitShutdownLaunchedProcessUnverified: closed.implicitShutdownLaunchedProcessUnverified, shutdownStopUnconfirmed: closed.shutdownStopUnconfirmed, @@ -406,6 +408,8 @@ type SessionCloseFinalization = /** #4162: the policy denied the stop this close owed its own boot, so the device kept running. */ implicitShutdownDeniedByPolicy: boolean; implicitShutdownClaimLost: boolean; + /** #4791: the platform said its own boot step never booted this device, so close owed it no stop. */ + implicitShutdownBootOwnerUnverified: boolean; /** #4585: the device has been rebooted outside this session since its open, so close left it running. */ implicitShutdownLaunchedProcessGone: boolean; implicitShutdownLaunchedProcessUnverified: boolean; @@ -454,6 +458,7 @@ async function runCloseTeardownAndRelease(params: { shutdownResult, implicitShutdownDeniedByPolicy, implicitShutdownClaimLost, + implicitShutdownBootOwnerUnverified, implicitShutdownLaunchedProcessGone, implicitShutdownLaunchedProcessUnverified, shutdownStopUnconfirmed, @@ -521,6 +526,7 @@ async function runCloseTeardownAndRelease(params: { remoteScript: saveScriptOutcome.remote, implicitShutdownDeniedByPolicy, implicitShutdownClaimLost, + implicitShutdownBootOwnerUnverified, implicitShutdownLaunchedProcessGone, implicitShutdownLaunchedProcessUnverified, shutdownStopUnconfirmed, @@ -537,6 +543,7 @@ function buildCloseSuccessResponse(params: { implicitShutdownClaimLost: boolean; implicitShutdownLaunchedProcessGone: boolean; implicitShutdownLaunchedProcessUnverified: boolean; + implicitShutdownBootOwnerUnverified: boolean; shutdownStopUnconfirmed: boolean; }): DaemonResponse { const { @@ -549,6 +556,7 @@ function buildCloseSuccessResponse(params: { implicitShutdownClaimLost, implicitShutdownLaunchedProcessGone, implicitShutdownLaunchedProcessUnverified, + implicitShutdownBootOwnerUnverified, shutdownStopUnconfirmed, } = params; if (repair.aborted && requestedSaveScript) { @@ -605,6 +613,15 @@ function buildCloseSuccessResponse(params: { : "This session's open booted this device, but open recorded no emulator process identity, so close did not request a stop and left the device as it found it.", ); } + // #4791: the open inferred a boot from a snapshot that said the simulator was stopped, and the + // platform's own boot step then said it never booted it. Whatever is running is somebody else's + // boot, so close leaves it running and says which reason it refused the stop for. + if (implicitShutdownBootOwnerUnverified) { + appendResponseWarning( + data, + `This session's open found this device stopped, but reported ${CLOSE_BOOT_OWNER_UNVERIFIED_REASONS.bootOwnerUnverified}: its own boot step never booted the device, so close did not request a stop. The device is still running.`, + ); + } if (shutdownStopUnconfirmed) { appendResponseWarning( data, 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 6fd957b9d8..4331b4a6db 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 @@ -22,6 +22,11 @@ import type { OpenApplicationOutcome, OpenApplicationTiming, } from '@agent-device/contracts/application-lifecycle-runtime'; +import type { + DeviceBootPerformance, + CloseBootOwnership, +} from '@agent-device/contracts/device-boot'; +import { resolveSessionBootOwnership } from '@agent-device/contracts/device-boot'; import type { DeviceInfo } from '@agent-device/kernel/device'; import type { DaemonPlatformServices } from '../../../core/platform-services.ts'; import type { DaemonRequest } from '../../../core/daemon-request.ts'; @@ -247,6 +252,8 @@ export async function completeOpenCommand(params: { tookOverDeviceClaim?: TakenOverDeviceClaim; selection?: DeviceSelectionResult; androidLaunchIdentity?: AndroidEmulatorLaunchIdentity; + /** #4791: what the platform's own boot step reported about the preparation call this open made. */ + bootPerformance?: DeviceBootPerformance; }): Promise { const { req, @@ -277,6 +284,13 @@ export async function completeOpenCommand(params: { selection, lifecycle.owner.kind === 'local-family', ); + // #4791: the snapshot that says "stopped" is an inference, and the platform's own boot step is the + // proof. The pair below is what the session records: who owns the stop, and what close must say when + // the inference is refused. + const bootOwnership = resolveSessionBootOwnership({ + inferredFromSnapshot: preparedSelection?.bootOccurred === true, + bootPerformance: params.bootPerformance, + }); const provisionalSession = await prepareOpenDispatchSession({ req, @@ -287,7 +301,7 @@ export async function completeOpenCommand(params: { sessionAppBundleId, appName, existingRef, - bootedByOpen: preparedSelection?.bootOccurred === true, + bootOwnership, androidLaunchIdentity: params.androidLaunchIdentity, }); if (provisionalSession.type === 'response') return provisionalSession; @@ -404,7 +418,7 @@ export async function completeOpenCommand(params: { appBundleId: sessionAppBundleId, appName, deviceClaim, - bootedByOpen: preparedSelection?.bootOccurred === true, + bootOwnership, androidLaunchIdentity: params.androidLaunchIdentity, }); sessionStore.clearCloseEffectsUnconfirmed(nextRef); @@ -439,7 +453,7 @@ async function prepareOpenDispatchSession(params: { sessionAppBundleId: string | undefined; appName: string | undefined; existingRef: SessionRef | undefined; - bootedByOpen: boolean; + bootOwnership: CloseBootOwnership; androidLaunchIdentity?: AndroidEmulatorLaunchIdentity; }): Promise< { type: 'session'; ref?: SessionRef } | { type: 'response'; response: DaemonResponse } @@ -451,7 +465,7 @@ async function prepareOpenDispatchSession(params: { sessionStore.updateOpenDevice( existingRef, params.device, - params.bootedByOpen, + params.bootOwnership, params.androidLaunchIdentity, ); return { type: 'session', ref: existingRef }; @@ -465,7 +479,7 @@ async function prepareOpenDispatchSession(params: { surface: params.surface, appBundleId: params.sessionAppBundleId, appName: params.appName, - bootedByOpen: params.bootedByOpen, + bootOwnership: params.bootOwnership, androidLaunchIdentity: params.androidLaunchIdentity, }); const lifecycleResponse = await beforeDispatch(); @@ -627,6 +641,7 @@ export async function openNewSessionWithDeviceClaim(params: { tookOverDeviceClaim, selection, androidLaunchIdentity: params.androidLaunchIdentity, + bootPerformance: details.details.bootPerformance, }); if (!response.response.ok) await rollbackClaim(); return response; diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-prepare.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-prepare.ts index 742759e358..c9f1852e18 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-open-prepare.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-open-prepare.ts @@ -1,6 +1,7 @@ import type { DaemonResponse } from '@agent-device/kernel/contracts'; import { isDeepLinkTarget } from '@agent-device/contracts/command'; import type { RuntimeHintsApplicationInput } from '@agent-device/contracts/application-lifecycle-runtime'; +import type { DeviceBootPerformance } from '@agent-device/contracts/device-boot'; import { openApplicationRuntimeUse } from '@agent-device/contracts/application-lifecycle-runtime-plan'; import type { BoundDeviceRuntime } from '@agent-device/contracts/platform-runtime'; import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -23,6 +24,8 @@ type OpenCommandDetails = { appBundleId?: string; appName?: string; runtime: SessionRuntimeHints | undefined; + /** #4791: what the platform's own boot step reported about the call this open made. */ + bootPerformance: DeviceBootPerformance | undefined; }; export type PreparedOpenCommandDetailsResult = @@ -158,6 +161,7 @@ export async function prepareOpenCommandDetails(params: { clearRuntimeHints, foreground, } = params; + let reportedBootPerformance: DeviceBootPerformance | undefined; await runtime.operations.prepareApplicationOpen({ target: openTarget, currentAppBundleId: existingSession?.appBundleId, @@ -165,6 +169,11 @@ export async function prepareOpenCommandDetails(params: { surface, prewarmRunnerOnColdBoot: surface === 'app' && Boolean(openTarget) && !isDeepLinkTarget(openTarget ?? ''), + // #4791: this is the call that can boot the device for this open, so it is the call that has to + // say whether it did. Everything downstream takes boot ownership from this answer alone. + onBootPerformance: (performance) => { + reportedBootPerformance = performance; + }, execution: { startupDeadlineAtMs: params.startupDeadlineAtMs, requestId: req.meta?.requestId, @@ -213,6 +222,7 @@ export async function prepareOpenCommandDetails(params: { appBundleId, appName, runtime: runtimeHintPlan.runtime, + bootPerformance: reportedBootPerformance, }, }; } 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 4168c76bb2..6e9262404e 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,4 +1,5 @@ import type { AndroidEmulatorLaunchIdentity } from '@agent-device/contracts/device-readiness-runtime'; +import type { CloseBootOwnership } from '@agent-device/contracts/device-boot'; import type { DeviceInfo } from '@agent-device/kernel/device'; import type { SessionSurface } from '@agent-device/contracts/session'; import type { DaemonRequest } from '../../../core/daemon-request.ts'; @@ -32,8 +33,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; + /** #4162: who owns stopping this device, and what close must say when nobody proved a boot. */ + bootOwnership: CloseBootOwnership; androidLaunchIdentity?: AndroidEmulatorLaunchIdentity; }): SessionRef { const { @@ -46,16 +47,11 @@ export function publishOpenSession(params: { appBundleId, appName, deviceClaim, - bootedByOpen, + bootOwnership, } = params; requireOpenSessionAdmission(store, sessionName, existingRef); if (existingRef) { - store.updateOpenDevice( - existingRef, - device, - bootedByOpen === true, - params.androidLaunchIdentity, - ); + store.updateOpenDevice(existingRef, device, bootOwnership, params.androidLaunchIdentity); const session = store.update(existingRef, { surface, appBundleId, @@ -79,7 +75,7 @@ export function publishOpenSession(params: { deviceClaim, }; const ref = store.publish(sessionName, draft); - if (bootedByOpen === true) - store.updateOpenDevice(ref, device, true, params.androidLaunchIdentity); + if (bootOwnership.ownsBoot || bootOwnership.bootOwnerUnverified) + store.updateOpenDevice(ref, device, bootOwnership, params.androidLaunchIdentity); return store.refresh(ref); } diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-open.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-open.ts index 1f4cb4a368..a8251c319a 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-open.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-open.ts @@ -357,6 +357,7 @@ async function handleOpenCommand(params: SessionOpenCommandInput): Promise {}); } : undefined, + // #4791: this is the boot step `open` owns, so its answer is what the session records as boot + // ownership. Readiness always answers it, whether or not the caller asked. + onSimulatorBoot: input.onBootPerformance, }); adoptReadiedDevice(readied); }, diff --git a/packages/platform-apple/src/readiness/runtime.test.ts b/packages/platform-apple/src/readiness/runtime.test.ts index c43eb94e91..b7391355f8 100644 --- a/packages/platform-apple/src/readiness/runtime.test.ts +++ b/packages/platform-apple/src/readiness/runtime.test.ts @@ -1,4 +1,5 @@ import { expect, test, vi } from 'vitest'; +import type { DeviceBootPerformance } from '@agent-device/contracts/device-boot'; import type { PlatformRuntimeHost } from '@agent-device/contracts/platform-runtime-operations'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { platformRuntimeHostFixture } from '../runtime.fixtures.ts'; @@ -298,6 +299,78 @@ test('a cold boot reveals Simulator.app without taking focus from the frontmost ); }); +// --- #4791: the boot step answers for the boot it performed --- +// +// The report is what lets a later plain `close` stop the simulator. These pin each shape of the +// answer against the simctl traffic that produced it. + +test('a cold boot reports that this readiness call performed the boot', async () => { + const { host } = coldSimulatorHost({}); + const reports: DeviceBootPerformance[] = []; + + await ensureAppleReady(host, simulator(), new AbortController().signal, { + onSimulatorBoot: (report) => reports.push(report), + }); + + expect(reports).toEqual([{ performed: true }]); +}); + +test('a boot refused as already booted reports no boot and says why', async () => { + // The foreign-boot race: the listing said Shutdown, and by the time `simctl boot` ran somebody + // else's boot had won. `ensureBootedSimulator` absorbs the refusal, so this is the only answer + // that can reach the session. + const { host } = coldSimulatorHost({ + bootFailure: { + exitCode: 149, + stderr: 'Unable to boot device in current state: Booted\nCurrent device state: Booted', + }, + }); + const reports: DeviceBootPerformance[] = []; + + const readied = await ensureAppleReady(host, simulator(), new AbortController().signal, { + onSimulatorBoot: (report) => reports.push(report), + }); + + expect(reports).toEqual([{ performed: false, reason: 'already-booted' }]); + // The open still succeeds: the simulator is up, just not because of this call. + expect(readied.booted).toBe(true); +}); + +test('a readiness call that never reaches the boot step reports no boot attempt', async () => { + // Selection found the simulator already running, so nothing was booted and nothing is owed. + const run = vi.fn(async () => ({ + stdout: JSON.stringify({ devices: { ios: [{ udid: 'sim-1', state: 'Booted' }] } }), + stderr: '', + exitCode: 0, + })); + const host = platformRuntimeHostFixture(); + const reports: DeviceBootPerformance[] = []; + + await ensureAppleReady( + { ...host, appleTools: { ...host.appleTools, run } }, + simulator({ booted: true }), + new AbortController().signal, + { onSimulatorBoot: (report) => reports.push(report) }, + ); + + expect(reports).toEqual([{ performed: false, reason: 'already-booted' }]); +}); + +test('a physical device readiness reports no simulator boot attempt', async () => { + const host = platformRuntimeHostFixture(); + const ensureConnected = vi.fn(async () => {}); + const reports: DeviceBootPerformance[] = []; + + await ensureAppleReady( + { ...host, deviceReadiness: { ...host.deviceReadiness, applePhysical: { ensureConnected } } }, + simulator({ kind: 'device', booted: true }), + new AbortController().signal, + { onSimulatorBoot: (report) => reports.push(report) }, + ); + + expect(reports).toEqual([{ performed: false, reason: 'no-boot-attempt' }]); +}); + /** A Shutdown Simulator whose boot and bootstatus run the given hooks first. */ function coldSimulatorHost(hooks: { onBoot?: () => void; diff --git a/packages/platform-apple/src/readiness/runtime.ts b/packages/platform-apple/src/readiness/runtime.ts index fbcc5a4752..744105a20f 100644 --- a/packages/platform-apple/src/readiness/runtime.ts +++ b/packages/platform-apple/src/readiness/runtime.ts @@ -1,10 +1,11 @@ import { BOOT_TIMEOUT_REASON } from '@agent-device/contracts/device-readiness-runtime'; +import type { DeviceBootPerformance } from '@agent-device/contracts/device-boot'; import type { PlatformRuntimeHost } from '@agent-device/contracts/platform-runtime-operations'; import { isMacOs, type DeviceInfo } from '@agent-device/kernel/device'; import { AppError } from '@agent-device/kernel/errors'; import { requireExecSuccess } from '@agent-device/host-kit/command'; import { emitRequestProgress } from '@agent-device/host-kit/request'; -import { scopeSimctlArgsForDevice } from '../core/simctl.ts'; +import { simctlBootRefusedAlreadyBooted, scopeSimctlArgsForDevice } from '../core/simctl.ts'; import { getSimulatorState } from '../simulator-state.ts'; /** Readiness reads exactly these host ports; the lifecycle binding composes the same subset. */ @@ -28,6 +29,14 @@ export type AppleReadinessOptions = Readonly<{ * runner cache in parallel with the boot, which is the whole reason the hook exists. */ onColdBootStart?: () => void; + /** + * Reports what this call's own boot step did with its boot: `performed: true` when it started the + * boot, `already-booted` when `simctl` refused a Simulator that was up before the call, and + * `no-boot-attempt` when readiness settled the Simulator without reaching one. #4791: this is the + * positive proof `open` needs to own the boot, and it is the only report a boot attempt makes — + * an option the caller leaves unset costs it nothing. + */ + onSimulatorBoot?: (performance: DeviceBootPerformance) => void; }>; export async function ensureAppleReady( @@ -37,28 +46,44 @@ export async function ensureAppleReady( options: AppleReadinessOptions = {}, ): Promise { signal.throwIfAborted(); - if (isMacOs(device)) return { ...device, booted: true }; + // #4791: every exit of this function states what its boot step did with this call, so a caller + // that needs to know whether it caused the boot never has to read a device snapshot instead. + const reportBoot = (performance: DeviceBootPerformance) => options.onSimulatorBoot?.(performance); + if (isMacOs(device)) { + reportBoot({ performed: false, reason: 'no-boot-attempt' }); + return { ...device, booted: true }; + } if (device.kind === 'device') { await host.deviceReadiness.applePhysical.ensureConnected(device, signal); + reportBoot({ performed: false, reason: 'no-boot-attempt' }); + return { ...device, booted: true }; + } + if (device.kind !== 'simulator') { + reportBoot({ performed: false, reason: 'no-boot-attempt' }); return { ...device, booted: true }; } - if (device.kind !== 'simulator') return { ...device, booted: true }; const recentlyObservedBooted = await readRecentBootObservation(host, device); if (recentlyObservedBooted) { host.deviceReadiness.appleAutomation.keepHot(device); + reportBoot({ performed: false, reason: 'already-booted' }); return { ...device, booted: true }; } const state = await simulatorState(host, device, signal); + let bootPerformed: DeviceBootPerformance | undefined; if (state !== 'Booted') { options.onColdBootStart?.(); host.deviceReadiness.appleAutomation.keepHot(device); - await bootSimulator(host, device, signal, options.deadlineAtMs); + const startedBoot = await bootSimulator(host, device, signal, options); await showSimulator(host, signal); + bootPerformed = startedBoot + ? { performed: true } + : { performed: false, reason: 'already-booted' }; } host.deviceReadiness.appleAutomation.keepHot(device); // Publish the fresh observation so the boot checks later in this flow skip their own listing. host.deviceReadiness.appleAutomation.markBooted(device); + reportBoot(bootPerformed ?? { performed: false, reason: 'already-booted' }); return { ...device, booted: true }; } @@ -73,12 +98,14 @@ async function readRecentBootObservation( } } +/** True when the `simctl boot` this call issued started the boot, false when it was refused as already booted. */ async function bootSimulator( host: AppleReadinessHost, device: DeviceInfo, signal: AbortSignal, - deadlineAtMs = Date.now() + BOOT_TIMEOUT_MS, -): Promise { + options: AppleReadinessOptions, +): Promise { + const deadlineAtMs = options.deadlineAtMs ?? Date.now() + BOOT_TIMEOUT_MS; let started = false; try { started = await startSimulatorBoot(host, device, signal, deadlineAtMs); @@ -91,6 +118,7 @@ async function bootSimulator( if (Date.now() >= deadlineAtMs) throw bootDeadlineError(device, error); throw error; } + return started; } /** Issues `simctl boot`; true when this call started the boot, false when it was already booted. */ @@ -109,9 +137,7 @@ async function startSimulatorBoot( }, signal, ); - const output = `${boot.stdout}\n${boot.stderr}`.toLowerCase(); - const alreadyBooted = - output.includes('already booted') || output.includes('current state: booted'); + const alreadyBooted = simctlBootRefusedAlreadyBooted(`${boot.stdout}\n${boot.stderr}`); if (!alreadyBooted) requireExecSuccess(boot, 'simctl boot failed'); return !alreadyBooted; } diff --git a/scripts/layering/session-state.ts b/scripts/layering/session-state.ts index 9df6d2c347..5c95cbc250 100644 --- a/scripts/layering/session-state.ts +++ b/scripts/layering/session-state.ts @@ -112,6 +112,9 @@ export const STORE_OWNED_SESSION_STATE_FIELDS: ReadonlySet = new Set([ // Close only reads the fact; a replacement cannot inherit it. 'device', 'bootedByOpen', + // #4791: the same write records that the platform disproved the snapshot's boot inference, which is + // what makes close report the kept-running device instead of silently stopping somebody else's boot. + 'bootOwnerUnverified', // #4585: `SessionStore.updateOpenDevice` records the launch identity of the boot above in the // same write. Close compares it with the current emulator process before it stops the device. 'androidLaunchIdentity', diff --git a/test/repo-guards/runner-refusal-reason-docs.test.ts b/test/repo-guards/runner-refusal-reason-docs.test.ts index ed2a9d1318..39d7f04768 100644 --- a/test/repo-guards/runner-refusal-reason-docs.test.ts +++ b/test/repo-guards/runner-refusal-reason-docs.test.ts @@ -37,6 +37,11 @@ const REASON_TABLES = [ cliHelpWorkflows, ]), reasonTable('DeviceClaimConflictReason', 'packages/contracts/src/device-inventory.ts', 'union'), + reasonTable( + 'CLOSE_BOOT_OWNER_UNVERIFIED_REASONS', + 'packages/contracts/src/device-boot.ts', + 'object', + ), ]; test('every reason of every exported published-reason table is documented at its surfaces', () => { diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 4bcbbbe02d..ab6f3e0a5c 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -121,7 +121,7 @@ Device claims and the daemon: Open apps and links: -- `open [app|url] [url]` boots the selected device when needed and opens the target in a session. `open ` opens deep links on Android and iOS, and `open ` opens a deep link in that app on iOS. See [Desktop targets](#desktop-targets) for macOS activation behavior. +- `open [app|url] [url]` boots the selected device when needed and opens the target in a session. `open ` opens deep links on Android and iOS, and `open ` opens a deep link in that app on iOS. Only a boot this `open` performed gives a later plain `close` the right to stop the device. See [Desktop targets](#desktop-targets) for macOS activation behavior. - An `open` that launches a stopped Android emulator and then fails without publishing a session stops that emulator, so no unowned emulator is left running: a later `close` never learns the failed `open` booted it. The stop itself takes at most 3 seconds after the failure. The failed open's own error stays the reported error and carries `error.details.failedOpenEmulatorCleanup`: `stopped`, `kept_running` with `failedOpenEmulatorCleanupReason` (`daemon-policy-denied` when [daemon policy](/docs/remote-proxy#restrict-what-clients-can-do) denies `device-shutdown`, `device-in-use` when another session or claim took the booted device, or is in the middle of taking it, `no-process-identity` when the launch's start time could not be read), or `not_confirmed`. An emulator that was already running is never stopped. This rule covers failures after the boot completes: a boot that ran out its `--timeout`, or that failed before the emulator was ready, leaves the emulator as it is, as above; only a canceled boot stops the emulator it launched. - Remote daemons refuse `file:` URLs in `open` targets and launch URLs with reason `REMOTE_HOST_INPUT_DENIED`. Serve local web content over HTTP(S) instead. - On iOS devices, `http(s)://` URLs open in Safari when no app is active. Custom-scheme URLs need an active app in the session. @@ -132,7 +132,7 @@ Open apps and links: - iOS simulators: `open` prepares app accessibility before launching an app or URL. If an already-running app has an empty accessibility tree after an earlier XCTest session, run `open --relaunch`, then `snapshot -i`. Preparation failures are logged and do not block launch. Runner cleanup also restores app accessibility after confirmed termination; a runner started by a release before this change is not restored, so relaunch the app with `open --relaunch`. - Android React Native: `open --relaunch` needs an installed package name. Install or reinstall the APK first; `open --relaunch` is rejected. For Metro-backed JS changes, run `metro reload` before reaching for `open --relaunch`. - Android (adb): an intent target such as `open settings` records the package that opened as `appBundleId`. `open settings --relaunch` stops and restarts that app. If the intent matches more than one activity, `--relaunch` fails. -- `close` stops the local Apple simulator or Android emulator that session's `open` booted, and reports it in `data.shutdown` — the same field `close --shutdown` reports. A device that was already running when the session opened keeps running unless you pass `--shutdown`. For an Android emulator, that stop is owed to the emulator process the session's `open` launched, which `close` checks first; when that process is gone or the host cannot answer for it, plain `close` leaves the emulator running and reports why in `warnings`. `close --shutdown` skips that check and stops the emulator anyway, then confirms the process its `open` launched exited; when the session recorded no emulator process, such as a session on an already-running emulator, there is no process to confirm and the command returns once the device was asked to stop. A daemon whose policy denies `device-shutdown` stops nothing: `close --shutdown` fails with `UNAUTHORIZED` and `error.details.reason: DAEMON_POLICY_DENIED`, and a plain `close` succeeds and says in `warnings` that it left the device running. Plain `close` never stops a physical or provider-owned device. Explicit provider shutdown follows the provider release action; with [Limrun](/docs/limrun), it can delete an instance. +- `close` stops the local Apple simulator or Android emulator that session's `open` booted, and reports it in `data.shutdown` — the same field `close --shutdown` reports. A device that was already running when the session opened keeps running unless you pass `--shutdown`. For an Apple simulator, the proof that `open` booted it is that open's own boot step performed the boot. When something else booted the simulator first, such as a concurrent `xcrun simctl boot`, plain `close` leaves it running and reports `boot-owner-unverified` in `warnings`. For an Android emulator, that stop is owed to the emulator process the session's `open` launched, which `close` checks first; when that process is gone or the host cannot answer for it, plain `close` leaves the emulator running and reports why in `warnings`. `close --shutdown` skips that check and stops the emulator anyway, then confirms the process its `open` launched exited; when the session recorded no emulator process, such as a session on an already-running emulator, there is no process to confirm and the command returns once the device was asked to stop. A daemon whose policy denies `device-shutdown` stops nothing: `close --shutdown` fails with `UNAUTHORIZED` and `error.details.reason: DAEMON_POLICY_DENIED`, and a plain `close` succeeds and says in `warnings` that it left the device running. Plain `close` never stops a physical or provider-owned device. Explicit provider shutdown follows the provider release action; with [Limrun](/docs/limrun), it can delete an instance. - Android (ADB): `close` force-stops the app, then checks for 2 seconds that it has left the foreground, waits up to 10 seconds for the processes it killed to exit, and checks for 2 more that no new process started. If a check window ends first, `close` fails with `details.reason: android-app-close-timeout` and `details.phase` set to `foreground`, `exit`, or `process`; a process that survives the force-stop fails with `exit`, and apps Android restarts at once, such as the launcher, fail with `process`. `open --relaunch` runs the same checks but accepts a new process once the killed ones exit, because Android can restart an app at once for a background client, such as Settings on Android 17. When `pidof` cannot list the app's processes, `close` fails with `details.reason: android-process-probe-unavailable`; if that happens before the force-stop, the app keeps running. - To diagnose an Android foreground-close timeout (`details.phase: foreground`), inspect `details.foregroundObservations` and `details.initialProcessCount` in the JSON error. The observations retain at most the last five probes: `startMs` and `endMs` are milliseconds from the start of the foreground check, `remainingMs` is the budget left when the probe ends, and `result` is `target`, `other`, or `unknown`. The process count is read before force-stop. In the [session request log](/docs/sessions#find-a-sessions-logs-and-artifacts), the `android_close_foreground_fence` diagnostic records this history as `data.observations` with `data.initialProcessCount`. If a foreground probe throws, that diagnostic also retains the history with an `error` result for the failed probe; the command reports the probe failure. - When `close` cannot confirm its cleanup on a session that holds a device claim, it fails and keeps the session and its claim, so the device is not handed on unconfirmed. Run `close` again with the same options to retry the cleanup and release the device, leaving out `--save-script` once the first attempt has published the script. Only `close`, or a successful `open`, is supported on the kept session: other commands work, but the session stays marked, so an idle daemon can still shut it down. If nobody retries, the kept session does not keep the daemon alive: when the daemon has been idle for its idle timeout and shuts down, its shutdown retries the cleanup, and a claim it still cannot confirm goes stale instead of being released. Embedded runtimes and `AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS=0` never shut down for idleness, so there a retried `close` is the only release. diff --git a/website/docs/docs/sessions.md b/website/docs/docs/sessions.md index 9644700b7a..4b5faf84d8 100644 --- a/website/docs/docs/sessions.md +++ b/website/docs/docs/sessions.md @@ -126,6 +126,10 @@ agent-device open --platform ios --device iPhone_17_Pro agent-device close # the simulator this open booted ends shut down ``` +For an Apple simulator, the proof that `open` booted it is that `open`'s own boot step performed the +boot. If something else booted the simulator first, such as a concurrent `xcrun simctl boot`, plain +`close` leaves it running and reports `boot-owner-unverified` in `warnings`. + For an Android emulator, that stop is owed to the emulator process this session's `open` launched, so `close` checks that process before it asks for the stop. When it is gone, or when the host cannot answer for it, plain `close` leaves the emulator running and reports why in `warnings`. From bece9b32a4bc71f9fc24c62fa5bf15974dbd6a66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 20 Nov 2026 23:11:34 +0100 Subject: [PATCH 2/2] fix(close): let a proved boot own the stop without the snapshot's agreement The resolver required the pre-open snapshot to have inferred a boot before it would accept the boot step's own proof (#4791 review). The device can go down between the snapshot and readiness, which makes the reported boot real while the inference answers nothing, so the session would have owned no stop for a boot it performed. A boot the boot step reports performing is now proof on its own, and the contracts suite pins each answer pair at the owner of the decision. --- .../src/__tests__/device-boot.test.ts | 42 +++++++++++++++++++ packages/contracts/src/device-boot.ts | 5 ++- 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 packages/contracts/src/__tests__/device-boot.test.ts diff --git a/packages/contracts/src/__tests__/device-boot.test.ts b/packages/contracts/src/__tests__/device-boot.test.ts new file mode 100644 index 0000000000..c8452e4fdb --- /dev/null +++ b/packages/contracts/src/__tests__/device-boot.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, test } from 'vitest'; +import { resolveSessionBootOwnership } from '../device-boot.ts'; + +// #4791: boot ownership is decided from the platform's own boot report, not from what an inventory +// snapshot said before the boot could happen. These pin the decision at the owner of the type; the +// routed close behavior is pinned in the daemon's session-lifecycle lane. +describe('resolveSessionBootOwnership', () => { + test('a boot the boot step reports performing owns the stop on its own', () => { + expect( + resolveSessionBootOwnership({ + inferredFromSnapshot: false, + bootPerformance: { performed: true }, + }), + ).toEqual({ ownsBoot: true, bootOwnerUnverified: false }); + }); + + test('the snapshot inference still owns the boot for an owner that reports nothing', () => { + // Android boots through the daemon's own emulator launch outside its preparation, so it answers + // nothing and the inference stays in charge there. + expect( + resolveSessionBootOwnership({ inferredFromSnapshot: true, bootPerformance: undefined }), + ).toEqual({ ownsBoot: true, bootOwnerUnverified: false }); + }); + + test('a boot the boot step disproves refuses the snapshot inference and says so', () => { + expect( + resolveSessionBootOwnership({ + inferredFromSnapshot: true, + bootPerformance: { performed: false, reason: 'already-booted' }, + }), + ).toEqual({ ownsBoot: false, bootOwnerUnverified: true }); + }); + + test('nothing is owed when neither the snapshot nor the boot step claims a boot', () => { + expect( + resolveSessionBootOwnership({ + inferredFromSnapshot: false, + bootPerformance: { performed: false, reason: 'no-boot-attempt' }, + }), + ).toEqual({ ownsBoot: false, bootOwnerUnverified: false }); + }); +}); diff --git a/packages/contracts/src/device-boot.ts b/packages/contracts/src/device-boot.ts index c48848a5e9..db39515921 100644 --- a/packages/contracts/src/device-boot.ts +++ b/packages/contracts/src/device-boot.ts @@ -124,9 +124,12 @@ export function resolveSessionBootOwnership( bootPerformance: DeviceBootPerformance | undefined; }>, ): CloseBootOwnership { + // A boot the boot step reports performing is proof on its own: the device can even have gone down + // between the snapshot and this call, which makes the boot real while the inference says nothing. + const performed = input.bootPerformance?.performed === true; const disprovesSnapshot = input.bootPerformance?.performed === false; return { - ownsBoot: input.inferredFromSnapshot && !disprovesSnapshot, + ownsBoot: performed || (input.inferredFromSnapshot && !disprovesSnapshot), bootOwnerUnverified: input.inferredFromSnapshot && disprovesSnapshot, }; }