diff --git a/packages/apple-runner/src/__tests__/runner-session-readiness.test.ts b/packages/apple-runner/src/__tests__/runner-session-readiness.test.ts index 45e66897e7..636f022ccd 100644 --- a/packages/apple-runner/src/__tests__/runner-session-readiness.test.ts +++ b/packages/apple-runner/src/__tests__/runner-session-readiness.test.ts @@ -184,6 +184,33 @@ beforeEach(async () => { ); mockWaitForRunner.mockResolvedValue(runnerResponse({ uptimeMs: 1 })); }); +// #4687: a session keeps `booted` from its open. When an external pool deletes that simulator, the +// runner start must name the missing device before xcodebuild waits out its destination timeout. +test('runner session start refuses a booted session simulator the listing no longer has', async () => { + const device = { ...IOS_SIMULATOR, id: 'runner-session-deleted-sim' }; + const listing = JSON.stringify({ + devices: { + 'com.apple.CoreSimulator.SimRuntime.iOS-27-2': [{ udid: 'other-sim', state: 'Booted' }], + }, + }); + mockRunXcrun.mockImplementation(async (args: string[]) => + args.includes('list') + ? { exitCode: 0, stdout: listing, stderr: '' } + : { exitCode: 0, stdout: '', stderr: '' }, + ); + + await assert.rejects(ensureRunnerSession(device, {}), (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.code, 'DEVICE_NOT_FOUND'); + assert.equal(error.details?.deviceId, device.id); + assert.equal(error.details?.dispatched, 'no'); + // The runner cache is shared by every agent on the host; a missing device is no reason to wipe it. + assert.doesNotMatch(String(error.details?.hint), /apple-runner\/derived|clean:xcuitest/); + return true; + }); + assert.equal(mockRunCmdBackground.mock.calls.length, 0); +}); + test('runner session executes read-only commands without uptime preflight', async () => { const session = makeRunnerSession({ state: 'starting' }); mockWaitForRunner.mockResolvedValueOnce(runnerResponse({ nodes: [], truncated: false })); diff --git a/packages/apple-runner/src/__tests__/runner-simulator-presence.test.ts b/packages/apple-runner/src/__tests__/runner-simulator-presence.test.ts new file mode 100644 index 0000000000..91fd6ac050 --- /dev/null +++ b/packages/apple-runner/src/__tests__/runner-simulator-presence.test.ts @@ -0,0 +1,45 @@ +import assert from 'node:assert/strict'; +import { beforeEach, test, vi } from 'vitest'; +import { appleRunnerTestHost } from '../test-host.ts'; +import { assertBootedSimulatorStillListed } from '../runner-simulator-presence.ts'; +import { IOS_SIMULATOR } from './device-fixtures.ts'; + +// The refusal itself is covered on the runner start route in runner-session.test.ts; these cases +// pin the listings that must NOT refuse a start. +const DEVICE = { ...IOS_SIMULATOR, id: '54A531E3-0610-48D3-9904-07E9F028397F' }; + +const runXcrun = vi.fn(); + +beforeEach(() => { + runXcrun.mockReset(); + appleRunnerTestHost.update({ runXcrun }); +}); + +test('a listing that cannot be read does not refuse the start', async () => { + runXcrun.mockResolvedValueOnce({ exitCode: 1, stdout: '', stderr: 'CoreSimulator unavailable' }); + await assertBootedSimulatorStillListed(DEVICE); + + runXcrun.mockResolvedValueOnce({ exitCode: 0, stdout: 'not json', stderr: '' }); + await assertBootedSimulatorStillListed(DEVICE); + + runXcrun.mockRejectedValueOnce(new Error('simctl timed out')); + await assertBootedSimulatorStillListed(DEVICE); +}); + +test('a simulator this process just observed booted is not listed again', async () => { + appleRunnerTestHost.update({ wasSimulatorRecentlyObservedBooted: async () => true }); + + await assertBootedSimulatorStillListed(DEVICE); + + assert.equal(runXcrun.mock.calls.length, 0); +}); + +test('a cancelled listing reports the cancellation, not a missing simulator', async () => { + const controller = new AbortController(); + runXcrun.mockImplementation(async () => { + controller.abort(new Error('request canceled')); + throw new Error('aborted'); + }); + + await assert.rejects(assertBootedSimulatorStillListed(DEVICE, controller.signal), /canceled/); +}); diff --git a/packages/apple-runner/src/__tests__/test-host-defaults.ts b/packages/apple-runner/src/__tests__/test-host-defaults.ts index 5249157f5f..ef49d09d95 100644 --- a/packages/apple-runner/src/__tests__/test-host-defaults.ts +++ b/packages/apple-runner/src/__tests__/test-host-defaults.ts @@ -33,6 +33,7 @@ function appleToolingTestAdapters(): Pick< | 'hasScopedAppleToolProvider' | 'buildSimctlArgsForDevice' | 'simulatorAddressFor' + | 'wasSimulatorRecentlyObservedBooted' | 'resolveIosPhysicalDeviceControl' > { const simulatorSetPathFor = (device: DeviceInfo): string | undefined => @@ -74,6 +75,7 @@ function appleToolingTestAdapters(): Pick< udid: device.id, simulatorSetPath: simulatorSetPathFor(device), }), + wasSimulatorRecentlyObservedBooted: async () => false, resolveIosPhysicalDeviceControl: (device): IosPhysicalDeviceRunnerControl => ({ backend: device.iosPhysicalDeviceBackend === 'xctest' ? 'xctest' : 'coredevice', resolveTunnel: async () => ({ tunnelIp: null }), diff --git a/packages/apple-runner/src/host.ts b/packages/apple-runner/src/host.ts index f4b90cef40..8ce159ac86 100644 --- a/packages/apple-runner/src/host.ts +++ b/packages/apple-runner/src/host.ts @@ -49,6 +49,8 @@ type AppleRunnerToolPort = { ) => Promise | null>; hasScopedAppleToolProvider: () => boolean; buildSimctlArgsForDevice: (device: DeviceInfo, args: readonly string[]) => ScopedSimctlCommand; + /** True while this process saw the simulator Booted moments ago, which proves it still exists. */ + wasSimulatorRecentlyObservedBooted: (device: DeviceInfo) => Promise; /** A simulator udid with the simulator set that holds it; two devices match only when both do. */ simulatorAddressFor: ( device: DeviceInfo, @@ -228,6 +230,7 @@ export const readApplePlistJson = delegate('readApplePlistJson'); export const hasScopedAppleToolProvider = delegate('hasScopedAppleToolProvider'); export const buildSimctlArgsForDevice = delegate('buildSimctlArgsForDevice'); export const simulatorAddressFor = delegate('simulatorAddressFor'); +export const wasSimulatorRecentlyObservedBooted = delegate('wasSimulatorRecentlyObservedBooted'); export const resolveIosPhysicalDeviceControl = delegate('resolveIosPhysicalDeviceControl'); export const leaseOwnerStateDir = delegate('leaseOwnerStateDir'); export const hasDeviceClaimAuthority = delegate('hasDeviceClaimAuthority'); diff --git a/packages/apple-runner/src/runner-session.ts b/packages/apple-runner/src/runner-session.ts index ad3378a2bb..854bbd882f 100644 --- a/packages/apple-runner/src/runner-session.ts +++ b/packages/apple-runner/src/runner-session.ts @@ -867,19 +867,20 @@ export async function stopAllIosRunnerSessions(): Promise { } } -function ensureBootedIfNeeded(device: DeviceInfo, signal?: AbortSignal): Promise { - if (device.kind !== 'simulator') { - return Promise.resolve(); - } +async function ensureBootedIfNeeded(device: DeviceInfo, signal?: AbortSignal): Promise { + if (device.kind !== 'simulator') return; if (device.booted) { emitDiagnostic({ level: 'debug', phase: 'ios_runner_startup_ensure_booted_skipped', data: { deviceId: device.id }, }); - return Promise.resolve(); + // Loaded at a start only, outside the Apple facades' eager import closure. + const { assertBootedSimulatorStillListed } = await import('./runner-simulator-presence.ts'); + await assertBootedSimulatorStillListed(device, signal); + return; } - return ensureBooted(device, signal); + await ensureBooted(device, signal); } async function ensureBooted(device: DeviceInfo, signal?: AbortSignal): Promise { diff --git a/packages/apple-runner/src/runner-simulator-presence.ts b/packages/apple-runner/src/runner-simulator-presence.ts new file mode 100644 index 0000000000..9eb374b7a1 --- /dev/null +++ b/packages/apple-runner/src/runner-simulator-presence.ts @@ -0,0 +1,67 @@ +import { AppError } from '@agent-device/kernel/errors'; +import type { DeviceInfo } from '@agent-device/kernel/device'; +import { + buildSimctlArgsForDevice, + emitDiagnostic, + isRecord, + runXcrun, + wasSimulatorRecentlyObservedBooted, +} from './host.ts'; + +/** Budget for the listing that confirms a session's booted simulator still exists. */ +const SIMULATOR_LISTING_TIMEOUT_MS = 5_000; + +/** + * A session's `booted` fact dates from its open, and an external pool can delete the simulator since. + * xcodebuild then waits out its whole destination timeout and exits with a failure that reads like a + * broken runner cache (#4687). One listing before the launch names the missing simulator instead. + * A Booted observation this process made moments ago already proves the simulator exists, so an + * `open` that just checked readiness pays nothing. + */ +export async function assertBootedSimulatorStillListed( + device: DeviceInfo, + signal?: AbortSignal, +): Promise { + if (await wasSimulatorRecentlyObservedBooted(device)) return; + let listed: boolean | undefined; + try { + const listing = await runXcrun(buildSimctlArgsForDevice(device, ['list', 'devices', '-j']), { + allowFailure: true, + timeoutMs: SIMULATOR_LISTING_TIMEOUT_MS, + signal, + }); + listed = listing.exitCode === 0 ? simctlListingHasDevice(listing.stdout, device.id) : undefined; + } catch (error) { + signal?.throwIfAborted(); + // CONSERVATIVE: a listing that failed proves nothing about the simulator, so the launch goes on. + emitDiagnostic({ + level: 'warn', + phase: 'ios_runner_startup_simulator_listing_failed', + data: { deviceId: device.id, error: String(error) }, + }); + return; + } + // CONSERVATIVE: only a readable listing that omits the simulator refuses the start. + if (listed !== false) return; + throw new AppError('DEVICE_NOT_FOUND', `iOS simulator ${device.id} no longer exists`, { + deviceId: device.id, + ...(device.simulatorSetPath ? { simulatorSetPath: device.simulatorSetPath } : {}), + dispatched: 'no', + hint: 'The simulator this session targets was deleted. Close this session, then open the app on an existing simulator (run devices to list them).', + }); +} + +/** Whether `simctl list devices -j` lists this udid; undefined when the output is not a listing. */ +function simctlListingHasDevice(stdout: string, udid: string): boolean | undefined { + let payload: unknown; + try { + payload = JSON.parse(stdout); + } catch { + return undefined; + } + if (!isRecord(payload) || !isRecord(payload.devices)) return undefined; + return Object.values(payload.devices).some( + (devices) => + Array.isArray(devices) && devices.some((entry) => isRecord(entry) && entry.udid === udid), + ); +} diff --git a/packages/platform-apple/src/core/runner-host.ts b/packages/platform-apple/src/core/runner-host.ts index 0c87712e3d..ed8a014535 100644 --- a/packages/platform-apple/src/core/runner-host.ts +++ b/packages/platform-apple/src/core/runner-host.ts @@ -119,6 +119,8 @@ export const appleRunnerHost: AppleRunnerHost = { hasScopedAppleToolProvider, buildSimctlArgsForDevice, simulatorAddressFor, + wasSimulatorRecentlyObservedBooted: async (device) => + (await import('./simulator.ts')).wasSimulatorRecentlyObservedBooted(device), resolveIosPhysicalDeviceControl, leaseOwnerStateDir: getRunnerLeaseOwnerStateDir, runnerRuntimeSlot: runtimeSlot,