diff --git a/packages/contracts/src/device-boot.ts b/packages/contracts/src/device-boot.ts index db39515921..fce1061260 100644 --- a/packages/contracts/src/device-boot.ts +++ b/packages/contracts/src/device-boot.ts @@ -99,41 +99,6 @@ 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 { - // 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: performed || (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 index 79fee1ad26..e92b448361 100644 --- a/packages/daemon/src/__tests__/support/boot-ownership-fixtures.ts +++ b/packages/daemon/src/__tests__/support/boot-ownership-fixtures.ts @@ -1,11 +1,8 @@ -import type { CloseBootOwnership } from '@agent-device/contracts/device-boot'; +import type { CloseBootOwnership } from '../../core/session-state.ts'; /** - * The boot-ownership pair an `open` records when it proved nothing about the device's boot: it owns no + * The boot ownership 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. + * inventing one of their own, so a new answer of the pair cannot be quietly defaulted away. */ -export const NO_BOOT_PROOF: CloseBootOwnership = { - ownsBoot: false, - bootOwnerUnverified: false, -}; +export const NO_BOOT_PROOF: CloseBootOwnership = 'none'; diff --git a/packages/daemon/src/core/session-state.ts b/packages/daemon/src/core/session-state.ts index c53dc8138e..53841dfe09 100644 --- a/packages/daemon/src/core/session-state.ts +++ b/packages/daemon/src/core/session-state.ts @@ -137,6 +137,16 @@ export type SessionRef = Readonly<{ lifetime: object; }>; +/** + * Whether a session's `open` owns stopping the device it holds, and whether it must say why not. + * The four answers are exclusive by type: an open either proved its boot, inferred one the platform + * did not disprove, disproved the inference it started from, or has no claim at all. #4791: only + * `proved` and `inferred` owe a stop, and `disproved` is the one close reports. The daemon's own + * vocabulary: `resolveSessionBootOwnership` decides a member, `SessionStore.updateOpenDevice` + * records it, and a plain `close` reads what was recorded. + */ +export type CloseBootOwnership = 'proved' | 'inferred' | 'disproved' | 'none'; + export type SessionState = { name: string; sessionScope?: SessionScope; @@ -176,10 +186,11 @@ export type SessionState = { 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. + * `close` stops it and leaves the device as the session found it. Recorded when device selection + * reports the boot (`selection.bootOccurred`) or the platform's own boot step reports performing + * it (#4791), neither of which 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; /** diff --git a/packages/daemon/src/core/session-store.ts b/packages/daemon/src/core/session-store.ts index 27796cad07..ac97c45b13 100644 --- a/packages/daemon/src/core/session-store.ts +++ b/packages/daemon/src/core/session-store.ts @@ -1,5 +1,4 @@ import type { AndroidEmulatorLaunchIdentity } from '@agent-device/contracts/device-readiness-runtime'; -import type { CloseBootOwnership } from '@agent-device/contracts/device-boot'; import { resolveSessionDir, resolveSessionAppLogPath, @@ -17,7 +16,12 @@ import { 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 type { + CloseBootOwnership, + SessionRef, + SessionRuntimeHints, + SessionState, +} from './session-state.ts'; import { recordActionEntry, type RecordActionEntry } from './session-action-recorder.ts'; import { isSafeSessionSegment, safeSessionName } from '@agent-device/host-kit/session-paths'; import { @@ -425,7 +429,12 @@ export class SessionStore { session.lastActivityAtMs = atMs; } - /** Keep boot ownership and its launch identity together for the same device identity. */ + /** + * Keep boot ownership and its launch identity together for the same device identity. A `none` + * write — a re-open that proved nothing — keeps the recorded disproval: it establishes no ownership + * of its own, and a session that disproved a boot is still the same promise to report keeping that + * device running, whether this re-open then succeeds or fails partway. + */ updateOpenDevice( ref: SessionRef, device: DeviceInfo, @@ -434,19 +443,26 @@ export class SessionStore { ): void { const current = this.requireCurrent(ref); const retainsBoot = sameDeviceIdentity(deviceIdentity(current.device), deviceIdentity(device)); - const ownsBoot = bootOwnership.ownsBoot || (retainsBoot && current.bootedByOpen === true); + const provesBoot = bootOwnership === 'proved' || bootOwnership === 'inferred'; + const ownsBoot = provesBoot || (retainsBoot && current.bootedByOpen === true); this.update(ref, { device, - androidLaunchIdentity: bootOwnership.ownsBoot + androidLaunchIdentity: provesBoot ? 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, + // #4791: the reason rides the ownership it refused. A write that owns a stop — including a + // re-open that disproves its OWN boot while an earlier open of this same device proved one and + // #4162 keeps it — reports nothing, because close stops on the preserved proof. + bootOwnerUnverified: ownsBoot + ? undefined + : bootOwnership === 'disproved' + ? true + : retainsBoot + ? current.bootOwnerUnverified + : undefined, }); } 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 index 93ef193a09..7d194faa84 100644 --- 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 @@ -75,14 +75,22 @@ function createRoutedSession() { 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; - }) { + /** Every open of this suite must state what its boot step reports; a close reports nothing. */ + type RunCommand = + | { + name: 'open'; + /** What the platform's own boot step reports about the open's preparation call. */ + bootPerformance: DeviceBootPerformance; + /** Fails the open after its ownership write and before dispatch, keeping the session. */ + failBeforeDispatch?: boolean; + flags?: Record; + } + | { name: 'close'; flags?: Record }; + + async function run(command: RunCommand) { if (command.name === 'open') { // Selection sees a shut-down simulator, which is the inference #4791 refuses to act on alone. + // A re-open of this session resolves the session's own device and infers no boot at all. vi.mocked(resolveTargetDevice).mockResolvedValue(STOPPED_SIMULATOR); } const loader: LifecycleOperationsLoader = async (device, signal, shutdownTarget) => { @@ -92,7 +100,8 @@ function createRoutedSession() { prepareApplicationOpen: async ( input: Parameters[0], ) => { - input.onBootPerformance?.(command.bootPerformance!); + // An open states its boot report in its own command shape; a close prepares nothing. + if (command.name === 'open') input.onBootPerformance?.(command.bootPerformance); }, }); }; @@ -109,6 +118,18 @@ function createRoutedSession() { session: SESSION, positionals: command.name === 'open' ? ['Demo'] : [], flags: command.flags ?? {}, + ...(command.name === 'open' && command.failBeforeDispatch + ? { + internal: { + openLifecycle: { + beforeDispatch: async () => ({ + ok: false as const, + error: { code: 'COMMAND_FAILED' as const, message: 'Dispatch refused' }, + }), + }, + }, + } + : {}), }, sessionName: SESSION, logPath: path.join(stateDir, 'daemon.log'), @@ -172,3 +193,52 @@ test('plain close stops the simulator whose boot the platform reports performing expect(closeWarnings(closed!)).toBeUndefined(); if (closed?.ok) expect(closed.data).toMatchObject({ shutdown: { success: true } }); }, 30_000); + +test('close --shutdown commands the stop a disproved open withheld', async () => { + // The state the warning actually creates: the user is told the device is still running and + // answers with an explicit shutdown. That commands the stop without the ownership question. + const runs = createRoutedSession(); + + const opened = await runs.run({ + name: 'open', + bootPerformance: { performed: false, reason: 'already-booted' }, + }); + expect(opened?.ok).toBe(true); + + const closed = await runs.run({ name: 'close', flags: { shutdown: true } }); + + 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); + +test('a failed re-open cannot silence the disproved boot the session already reported', async () => { + // The re-open writes ownership before dispatch and its own readiness finds the foreign boot up, + // so it proves nothing. When its dispatch then fails, the surviving session keeps the record: + // the same simulator is still running on somebody else's boot, and close must still say so. + const runs = createRoutedSession(); + + const opened = await runs.run({ + name: 'open', + bootPerformance: { performed: false, reason: 'already-booted' }, + }); + expect(opened?.ok).toBe(true); + + const reopened = await runs.run({ + name: 'open', + bootPerformance: { performed: false, reason: 'already-booted' }, + flags: {}, + failBeforeDispatch: true, + }); + expect(reopened?.ok).toBe(false); + expect(runs.sessionStore.get(SESSION)?.bootOwnerUnverified).toBe(true); + + const closed = await runs.run({ name: 'close' }); + + expect(closed?.ok).toBe(true); + expect(mockShutdownTargetRuntime).not.toHaveBeenCalled(); + expect(closeWarnings(closed!)).toEqual([ + expect.stringContaining(CLOSE_BOOT_OWNER_UNVERIFIED_REASONS.bootOwnerUnverified), + ]); +}, 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 8bb5a8e946..b4c4f97492 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 @@ -3,6 +3,7 @@ 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 type { CloseBootOwnership } from '../../../../core/session-state.ts'; import { authoringPublication, makeIosSession, @@ -63,7 +64,8 @@ test('a re-open of a session that never armed records nothing', () => { // // Ownership survives reopens of the same target. A replacement owns only its own boot. -function firstOpen(bootedByOpen: boolean | undefined) { +/** One open of a fresh session under the given ownership answer. */ +function firstOpen(bootOwnership: CloseBootOwnership) { const store = makeSessionStore(); return publishOpenSession({ req: { token: 't', command: 'open', positionals: [], session: 's' }, @@ -71,18 +73,22 @@ function firstOpen(bootedByOpen: boolean | undefined) { sessionName: 's', device: IOS_SIMULATOR, surface: 'app', - bootOwnership: { ownsBoot: bootedByOpen === true, bootOwnerUnverified: false }, + bootOwnership, }).session; } test('#4162: an open whose selection reported the boot records it on the new session', () => { - assert.equal(firstOpen(true).bootedByOpen, true); + assert.equal(firstOpen('inferred').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); +test('an open whose boot step proved the boot records it on the new session', () => { + assert.equal(firstOpen('proved').bootedByOpen, true); +}); + +test.each(['none', 'disproved'] as const)( + '#4162: an open whose selection reported no boot records nothing: %s', + (bootOwnership) => { + assert.equal(firstOpen(bootOwnership).bootedByOpen, undefined); }, ); @@ -100,7 +106,7 @@ test.each([false, true])('replacement target owns only its own boot: %s', (repla existingRef: ref, device: { ...IOS_SIMULATOR, id: 'replacement-simulator' }, surface: 'app', - bootOwnership: { ownsBoot: replacementBooted, bootOwnerUnverified: false }, + bootOwnership: replacementBooted ? 'inferred' : 'none', }), ); assert.equal(next.bootedByOpen, replacementBooted ? true : undefined); @@ -121,7 +127,7 @@ test.each(bootOwnershipFacts)( existingRef: ref, device: IOS_SIMULATOR, surface: 'app', - bootOwnership: { ownsBoot: true, bootOwnerUnverified: false }, + bootOwnership: 'inferred', }), ); @@ -160,14 +166,14 @@ test('#4791: an open the platform disproved records no boot and the reason close sessionName: 's', device: IOS_SIMULATOR, surface: 'app', - bootOwnership: { ownsBoot: false, bootOwnerUnverified: true }, + bootOwnership: 'disproved', }).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', () => { +test('#4791: a re-open that proves its own boot clears the earlier disproved one', () => { const store = makeSessionStore(); const existing = makeIosSession('s', { bootOwnerUnverified: true }); const ref = store.publish(existing.name, existing); @@ -180,13 +186,37 @@ test('#4791: a re-open of the same target clears the disproved boot with its own existingRef: ref, device: IOS_SIMULATOR, surface: 'app', - bootOwnership: NO_BOOT_PROOF, + bootOwnership: 'proved', }), ); + // The device went down and this open really brought it up: close owes the stop, not the warning. + assert.equal(next.bootedByOpen, true); assert.equal(next.bootOwnerUnverified, undefined); }); +test('#4791: a re-open that proves nothing keeps the disproved boot on record', () => { + // The same foreign boot is still running — readiness finds it up and answers nothing new — so a + // later plain close must keep warning about it, whether this re-open then succeeds or fails. + 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, true); +}); + 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 }); @@ -200,7 +230,7 @@ test('#4791: a disproved re-open cannot take back a boot an earlier open of the existingRef: ref, device: IOS_SIMULATOR, surface: 'app', - bootOwnership: { ownsBoot: false, bootOwnerUnverified: true }, + bootOwnership: 'disproved', }), ); diff --git a/packages/contracts/src/__tests__/device-boot.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-boot-ownership.test.ts similarity index 73% rename from packages/contracts/src/__tests__/device-boot.test.ts rename to packages/daemon/src/sessions/session-lifecycle/internal/session-boot-ownership.test.ts index c8452e4fdb..6eea5c24e9 100644 --- a/packages/contracts/src/__tests__/device-boot.test.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-boot-ownership.test.ts @@ -1,9 +1,9 @@ import { describe, expect, test } from 'vitest'; -import { resolveSessionBootOwnership } from '../device-boot.ts'; +import { resolveSessionBootOwnership } from './session-boot-ownership.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. +// routed close behavior is pinned in the session-lifecycle __tests__ lane. describe('resolveSessionBootOwnership', () => { test('a boot the boot step reports performing owns the stop on its own', () => { expect( @@ -11,7 +11,7 @@ describe('resolveSessionBootOwnership', () => { inferredFromSnapshot: false, bootPerformance: { performed: true }, }), - ).toEqual({ ownsBoot: true, bootOwnerUnverified: false }); + ).toBe('proved'); }); test('the snapshot inference still owns the boot for an owner that reports nothing', () => { @@ -19,7 +19,7 @@ describe('resolveSessionBootOwnership', () => { // nothing and the inference stays in charge there. expect( resolveSessionBootOwnership({ inferredFromSnapshot: true, bootPerformance: undefined }), - ).toEqual({ ownsBoot: true, bootOwnerUnverified: false }); + ).toBe('inferred'); }); test('a boot the boot step disproves refuses the snapshot inference and says so', () => { @@ -28,7 +28,7 @@ describe('resolveSessionBootOwnership', () => { inferredFromSnapshot: true, bootPerformance: { performed: false, reason: 'already-booted' }, }), - ).toEqual({ ownsBoot: false, bootOwnerUnverified: true }); + ).toBe('disproved'); }); test('nothing is owed when neither the snapshot nor the boot step claims a boot', () => { @@ -37,6 +37,15 @@ describe('resolveSessionBootOwnership', () => { inferredFromSnapshot: false, bootPerformance: { performed: false, reason: 'no-boot-attempt' }, }), - ).toEqual({ ownsBoot: false, bootOwnerUnverified: false }); + ).toBe('none'); + }); + + test('a disproved boot nobody inferred is no claim either', () => { + expect( + resolveSessionBootOwnership({ + inferredFromSnapshot: false, + bootPerformance: { performed: false, reason: 'already-booted' }, + }), + ).toBe('none'); }); }); diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-boot-ownership.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-boot-ownership.ts new file mode 100644 index 0000000000..e3a1e44634 --- /dev/null +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-boot-ownership.ts @@ -0,0 +1,29 @@ +import type { DeviceBootPerformance } from '@agent-device/contracts/device-boot'; +import type { CloseBootOwnership } from '../../../core/session-state.ts'; + +/** + * Decides what a session's `open` owns stopping, from the two answers it has. + * + * #4791: a boot the platform's own boot step reports performing is positive proof, so it owns the + * boot whatever the snapshot said — the device can even have gone down between the two, which makes + * the reported boot real while the inference answers nothing. A device-selection snapshot only says + * the device was STOPPED when the open looked at it, which proves nothing about the boot that + * followed: 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 (`disproved`). An owner + * that boots through a step of its own outside the preparation that reports — the daemon's Android + * emulator launch — answers nothing, which leaves the snapshot inference in charge for that family. + */ +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 { + if (input.bootPerformance?.performed === true) return 'proved'; + if (input.bootPerformance?.performed === false) + return input.inferredFromSnapshot ? 'disproved' : 'none'; + return input.inferredFromSnapshot ? 'inferred' : 'none'; +} 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 4331b4a6db..9e546f6a69 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,16 +22,13 @@ 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 { DeviceBootPerformance } from '@agent-device/contracts/device-boot'; +import { resolveSessionBootOwnership } from './session-boot-ownership.ts'; import type { DeviceInfo } from '@agent-device/kernel/device'; import type { DaemonPlatformServices } from '../../../core/platform-services.ts'; import type { DaemonRequest } from '../../../core/daemon-request.ts'; import { requestCwd } from '../../../core/context.ts'; -import type { SessionRef, SessionState } from '../../../core/session-state.ts'; +import type { CloseBootOwnership, SessionRef, SessionState } from '../../../core/session-state.ts'; import { abortAuthoringOnSecondOpen, armAuthoringOnOpen, @@ -285,8 +282,8 @@ export async function completeOpenCommand(params: { 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. + // proof. The answer 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, 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 6e9262404e..15d9ebe1af 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,9 +1,8 @@ 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'; -import type { SessionRef, SessionState } from '../../../core/session-state.ts'; +import type { CloseBootOwnership, 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'; @@ -75,7 +74,8 @@ export function publishOpenSession(params: { deviceClaim, }; const ref = store.publish(sessionName, draft); - if (bootOwnership.ownsBoot || bootOwnership.bootOwnerUnverified) - store.updateOpenDevice(ref, device, bootOwnership, params.androidLaunchIdentity); + // The store decides what each ownership answer records; a fresh draft carries the device already, + // and 'none' writes nothing but its absence. No second copy of that rule belongs here. + store.updateOpenDevice(ref, device, bootOwnership, params.androidLaunchIdentity); return store.refresh(ref); } diff --git a/packages/platform-apple/src/core/__tests__/simulator.test.ts b/packages/platform-apple/src/core/__tests__/simulator.test.ts index 2017a6fa27..d2a8118697 100644 --- a/packages/platform-apple/src/core/__tests__/simulator.test.ts +++ b/packages/platform-apple/src/core/__tests__/simulator.test.ts @@ -190,6 +190,30 @@ test('ensureBootedSimulator retries a transient simctl boot failure and boots on ); }); +test('ensureBootedSimulator absorbs a boot CoreSimulator refuses as already booted', async () => { + // #4791: this is the same one read `ensureAppleReady` uses (simctlBootRefusedAlreadyBooted), so + // the exact refusal CoreSimulator answers a foreign-boot race with must stay absorbed here too — + // a caller like screenshot or app-launch must not fail on a Simulator that is up. + mockRunCmdResponses({ + 'xcrun simctl list devices -j': simulatorStateSequence('Shutdown', 'Booted'), + 'xcrun simctl boot sim-1': () => ({ + exitCode: 149, + stdout: '', + stderr: 'Unable to boot device in current state: Booted', + }), + 'xcrun simctl bootstatus sim-1 -b': OK_RESULT, + 'open -g -a Simulator': OK_RESULT, + }); + + await settleBoot(ensureBootedSimulator(IOS_TEST_SIMULATOR)); + + assert.equal( + mockRunCmd.mock.calls.filter(([, args]) => args.includes('boot') && args.includes('sim-1')) + .length, + 1, + ); +}); + test('ensureBootedSimulator gives up without retrying a boot that reports a timeout', async () => { mockRunCmdResponses({ 'xcrun simctl list devices -j': simulatorListDevicesResult('Shutdown'), diff --git a/packages/platform-apple/src/core/simctl.ts b/packages/platform-apple/src/core/simctl.ts index 55b75f7209..e697f54667 100644 --- a/packages/platform-apple/src/core/simctl.ts +++ b/packages/platform-apple/src/core/simctl.ts @@ -55,15 +55,12 @@ export function scopeSimctlArgsForDevice( /** * Whether a `simctl boot` was refused because the Simulator was already up. CoreSimulator answers * this with text and a non-zero exit rather than a distinguishable code, so this is the one read of - * it in the package: a boot refused this way was NOT performed by the call that asked for it. + * it in the package: a boot refused this way was NOT performed by the call that asked for it. The + * wording is CoreSimulator's own — `Unable to boot device in current state: Booted`. */ export function simctlBootRefusedAlreadyBooted(output: string): boolean { const lowered = output.toLowerCase(); - return ( - lowered.includes('already booted') || - lowered.includes('current state: booted') || - lowered.includes('current device state: booted') - ); + return lowered.includes('already booted') || lowered.includes('current state: booted'); } export function buildSimctlArgsForAddress( diff --git a/packages/platform-apple/src/lifecycle-readied-device.test.ts b/packages/platform-apple/src/lifecycle-readied-device.test.ts index 35808e6216..480f88a0b6 100644 --- a/packages/platform-apple/src/lifecycle-readied-device.test.ts +++ b/packages/platform-apple/src/lifecycle-readied-device.test.ts @@ -1,4 +1,5 @@ import { expect, test } from 'vitest'; +import type { DeviceBootPerformance } from '@agent-device/contracts/device-boot'; import { bindAppleApplicationLifecycle } from './lifecycle.ts'; import { coldSimulatorLifecycleHost, openInput, simulator } from './lifecycle.fixtures.ts'; @@ -74,6 +75,63 @@ test('a failed preparation leaves the original device bound', async () => { expect(prewarmRunnerSession).toHaveBeenCalledWith(shutdownSimulator, {}, signal, false); }); +// --- #4791: the open's preparation carries its own boot report out --- +// +// The routed daemon lane answers the port itself, so only this lane can prove the Apple lifecycle +// actually forwards readiness's answer. Deleting that forwarding must fail here. + +test('preparing an open on a Shutdown Simulator reports that its boot step performed the boot', async () => { + const { host } = coldSimulatorLifecycleHost(); + const lifecycle = bindAppleApplicationLifecycle({ + host, + device: shutdownSimulator, + signal: new AbortController().signal, + }); + const reports: DeviceBootPerformance[] = []; + + await lifecycle.prepareApplicationOpen({ + ...prepareOpenInput, + onBootPerformance: (report) => reports.push(report), + }); + + expect(reports).toEqual([{ performed: true }]); +}); + +test('preparing an open whose boot CoreSimulator refuses reports no boot performed', async () => { + const { host } = coldSimulatorLifecycleHost({ + bootFailure: { exitCode: 149, stderr: 'Unable to boot device in current state: Booted' }, + }); + const lifecycle = bindAppleApplicationLifecycle({ + host, + device: shutdownSimulator, + signal: new AbortController().signal, + }); + const reports: DeviceBootPerformance[] = []; + + await lifecycle.prepareApplicationOpen({ + ...prepareOpenInput, + onBootPerformance: (report) => reports.push(report), + }); + + // The open still succeeds — the simulator is up, just not because of this call — so the session + // learns the one thing close needs: this open owns no stop. + expect(reports).toEqual([{ performed: false, reason: 'already-booted' }]); +}); + +test('an open that asks for no boot report still prepares', async () => { + const { host, calls } = coldSimulatorLifecycleHost(); + const lifecycle = bindAppleApplicationLifecycle({ + host, + device: shutdownSimulator, + signal: new AbortController().signal, + }); + + await lifecycle.prepareApplicationOpen(prepareOpenInput); + + // Readiness answers whether or not the caller asked, and asking nothing costs the open nothing. + expect(calls.filter((call) => call.args.includes('bootstatus'))).toHaveLength(1); +}); + test('a cancelled runner preparation prepares nothing and leaves the original device bound', async () => { const controller = new AbortController(); const { host, prepareRunner, prewarmRunnerSession } = coldSimulatorLifecycleHost({ diff --git a/packages/platform-apple/src/lifecycle.fixtures.ts b/packages/platform-apple/src/lifecycle.fixtures.ts index 9f76db715c..d595021ae5 100644 --- a/packages/platform-apple/src/lifecycle.fixtures.ts +++ b/packages/platform-apple/src/lifecycle.fixtures.ts @@ -198,7 +198,13 @@ export function launchUrlSimulator( /** A Shutdown Simulator host whose boot and bootstatus calls run the given hooks before succeeding. */ export function coldSimulatorLifecycleHost( - hooks: { onBoot?: () => void; onBootstatus?: () => void; bootstatusExitCode?: number } = {}, + hooks: { + onBoot?: () => void; + onBootstatus?: () => void; + bootstatusExitCode?: number; + /** When set, `simctl boot` answers this instead of succeeding. */ + bootFailure?: { stdout?: string; stderr: string; exitCode: number }; + } = {}, ) { const calls: Array<{ args: string[]; timeoutMs?: number }> = []; let state = 'Shutdown'; @@ -213,6 +219,11 @@ export function coldSimulatorLifecycleHost( } if (request.args.includes('boot')) { hooks.onBoot?.(); + if (hooks.bootFailure) { + // CoreSimulator's own refusal for a Simulator somebody else booted first (#4791). + state = 'Booted'; + return { stdout: '', ...hooks.bootFailure }; + } state = 'Booted'; } if (request.args.includes('bootstatus')) { diff --git a/packages/platform-apple/src/readiness/runtime.test.ts b/packages/platform-apple/src/readiness/runtime.test.ts index b7391355f8..4b82856e23 100644 --- a/packages/platform-apple/src/readiness/runtime.test.ts +++ b/packages/platform-apple/src/readiness/runtime.test.ts @@ -322,7 +322,7 @@ test('a boot refused as already booted reports no boot and says why', async () = const { host } = coldSimulatorHost({ bootFailure: { exitCode: 149, - stderr: 'Unable to boot device in current state: Booted\nCurrent device state: Booted', + stderr: 'Unable to boot device in current state: Booted', }, }); const reports: DeviceBootPerformance[] = []; diff --git a/packages/platform-apple/src/readiness/runtime.ts b/packages/platform-apple/src/readiness/runtime.ts index 744105a20f..c52250c351 100644 --- a/packages/platform-apple/src/readiness/runtime.ts +++ b/packages/platform-apple/src/readiness/runtime.ts @@ -31,9 +31,10 @@ export type AppleReadinessOptions = Readonly<{ 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 — + * boot, `already-booted` when the Simulator was up before the call — a fresh Booted listing, a + * recent boot observation, or `simctl` refusing the boot — and `no-boot-attempt` for a target this + * call readies without a simulator boot: macOS, a physical device, or another kind. #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; diff --git a/skills/ios-simulator/SKILL.md b/skills/ios-simulator/SKILL.md index 99c8931c79..1857eb18a9 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, 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`. +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`. When the session's first open selected a stopped simulator and something else booted it before that open's own boot step, plain close leaves it running and warns with `boot-owner-unverified` until a later open of the session records that it booted the simulator. 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 083b141fd7..7b8675d894 100644 --- a/src/commands/schema/cli-help-workflows.ts +++ b/src/commands/schema/cli-help-workflows.ts @@ -29,7 +29,7 @@ Loop: 4. Treat a settled:true diff as the next observation. Do not add wait stable or another snapshot when the diff already shows the next target or expected result. 5. If --settle prints not settled, follow its hint before the next ref-based action. 6. Verify named expectations with wait text/selector/absent, get, is, find text "..." exists, or the settled diff. Bare find clicks. A bare screenshot/snapshot is not verification for a named expectation. - 7. Close the session when the script ends. Plain close stops a local simulator or emulator this session's open booted unless daemon policy denies device-shutdown; inspect warnings for a local device kept running. When the emulator process its own open launched is gone or cannot be verified, plain close leaves the emulator running and reports why. A device that was already running keeps running. + 7. Close the session when the script ends. Plain close stops a local simulator or emulator this session's open booted unless daemon policy denies device-shutdown; inspect warnings for a local device kept running. When the emulator process its own open launched is gone or cannot be verified, or the session's first open selected a stopped Apple simulator that something else booted before that open's own boot step (boot-owner-unverified), plain close leaves the device running and reports why. A device that was already running when the session first opened it, and that the session has not since booted, keeps running on plain close without a boot-ownership warning; a reopen of the same device keeps an earlier boot-ownership warning until a later open of the session records that it booted the simulator, and a reopen that selects a different device clears it. Command shapes: agent-device open com.example.app --relaunch @@ -344,7 +344,7 @@ Loop: 3. Use snapshot -i and press/fill/click/longpress --settle for UI-driving steps. 4. Use the settled diff as evidence when it shows the changed behavior; otherwise verify with wait/get/is, find text "..." exists, screenshot, logs, network, perf, or trace based on the claim. 5. Record timings, token/output size, screenshots/videos, logs, or perf artifacts only when they answer the validation question. - 6. Close sessions and release leases before finishing. Plain close stops a local simulator or emulator this session's open booted unless daemon policy denies device-shutdown; inspect warnings for a local device kept running. When the emulator process its own open launched is gone or cannot be verified, plain close leaves the emulator running and reports why. A device that was already running keeps running. + 6. Close sessions and release leases before finishing. Plain close stops a local simulator or emulator this session's open booted unless daemon policy denies device-shutdown; inspect warnings for a local device kept running. When the emulator process its own open launched is gone or cannot be verified, or the session's first open selected a stopped Apple simulator that something else booted before that open's own boot step (boot-owner-unverified), plain close leaves the device running and reports why. A device that was already running when the session first opened it, and that the session has not since booted, keeps running on plain close without a boot-ownership warning; a reopen of the same device keeps an earlier boot-ownership warning until a later open of the session records that it booted the simulator, and a reopen that selects a different device clears it. Evidence: CLI/runtime freshness: pnpm build, pnpm clean:daemon, then agent-device --version or the command under test. diff --git a/test/repo-guards/runner-refusal-reason-docs.test.ts b/test/repo-guards/runner-refusal-reason-docs.test.ts index 91f2f7b52d..bb65bcb5f0 100644 --- a/test/repo-guards/runner-refusal-reason-docs.test.ts +++ b/test/repo-guards/runner-refusal-reason-docs.test.ts @@ -42,6 +42,7 @@ const REASON_TABLES = [ 'CLOSE_BOOT_OWNER_UNVERIFIED_REASONS', 'packages/contracts/src/device-boot.ts', 'object', + [commandsDoc, cliHelpWorkflows], ), ];