diff --git a/src/daemon/handlers/__tests__/session.test.ts b/src/daemon/handlers/__tests__/session.test.ts index 3618371103..0bf3e6ef5a 100644 --- a/src/daemon/handlers/__tests__/session.test.ts +++ b/src/daemon/handlers/__tests__/session.test.ts @@ -1550,6 +1550,135 @@ test('open --relaunch closes and reopens active session app', async () => { assert.deepEqual(calls[1], { command: 'open', positionals: ['com.example.app'] }); }); +test('open --relaunch on iOS stops runner before close/open', async () => { + const sessionStore = makeSessionStore(); + const sessionName = 'ios-session'; + sessionStore.set( + sessionName, + { + ...makeSession(sessionName, { + platform: 'ios', + id: 'ios-device-1', + name: 'My iPhone', + kind: 'device', + booted: true, + }), + appName: 'com.example.app', + }, + ); + + const calls: string[] = []; + const response = await handleSessionCommands({ + req: { + token: 't', + session: sessionName, + command: 'open', + positionals: [], + flags: { relaunch: true }, + }, + sessionName, + logPath: path.join(os.tmpdir(), 'daemon.log'), + sessionStore, + invoke: noopInvoke, + stopIosRunner: async () => { + calls.push('stop-runner'); + }, + dispatch: async (_device, command, positionals) => { + calls.push(`${command}:${positionals.join(' ')}`); + return {}; + }, + ensureReady: async () => {}, + }); + + assert.ok(response); + assert.equal(response?.ok, true); + assert.deepEqual(calls, ['stop-runner', 'close:com.example.app', 'open:com.example.app']); +}); + +test('open --relaunch on iOS without existing session closes then opens target app', async () => { + const sessionStore = makeSessionStore(); + const sessionName = 'ios-new-session'; + + const calls: string[] = []; + const response = await handleSessionCommands({ + req: { + token: 't', + session: sessionName, + command: 'open', + positionals: ['com.example.app'], + flags: { relaunch: true, platform: 'ios' }, + }, + sessionName, + logPath: path.join(os.tmpdir(), 'daemon.log'), + sessionStore, + invoke: noopInvoke, + resolveTargetDevice: async () => ({ + platform: 'ios', + id: 'ios-device-1', + name: 'My iPhone', + kind: 'device', + booted: true, + }), + stopIosRunner: async () => { + calls.push('stop-runner'); + }, + dispatch: async (_device, command, positionals) => { + calls.push(`${command}:${positionals.join(' ')}`); + return {}; + }, + ensureReady: async () => {}, + }); + + assert.ok(response); + assert.equal(response?.ok, true); + assert.deepEqual(calls, ['stop-runner', 'close:com.example.app', 'open:com.example.app']); +}); + +test('open --relaunch on iOS simulator reaches settle path for close and open', async () => { + const sessionStore = makeSessionStore(); + const sessionName = 'ios-sim-session'; + sessionStore.set( + sessionName, + { + ...makeSession(sessionName, { + platform: 'ios', + id: 'sim-1', + name: 'iPhone 16', + kind: 'simulator', + booted: true, + }), + appName: 'com.example.app', + }, + ); + + const settleCalls: Array<{ deviceId: string; delayMs: number }> = []; + const response = await handleSessionCommands({ + req: { + token: 't', + session: sessionName, + command: 'open', + positionals: [], + flags: { relaunch: true }, + }, + sessionName, + logPath: path.join(os.tmpdir(), 'daemon.log'), + sessionStore, + invoke: noopInvoke, + dispatch: async () => ({}), + stopIosRunner: async () => {}, + ensureReady: async () => {}, + settleSimulator: async (device, delayMs) => { + settleCalls.push({ deviceId: device.id, delayMs }); + }, + }); + + assert.ok(response); + assert.equal(response?.ok, true); + assert.equal(settleCalls.length, 2); + assert.deepEqual(settleCalls[0], { deviceId: 'sim-1', delayMs: 300 }); + assert.deepEqual(settleCalls[1], { deviceId: 'sim-1', delayMs: 300 }); +}); + test('close on iOS session with recording stops runner session before delete', async () => { const sessionStore = makeSessionStore(); const sessionName = 'ios-device-session'; @@ -1595,6 +1724,50 @@ test('close on iOS session with recording stops runner session before delete', a assert.equal(sessionStore.get(sessionName), undefined); }); +test('close on iOS stops runner before app close dispatch and performs final idempotent stop', async () => { + const sessionStore = makeSessionStore(); + const sessionName = 'ios-close-session'; + sessionStore.set( + sessionName, + { + ...makeSession(sessionName, { + platform: 'ios', + id: 'ios-device-1', + name: 'My iPhone', + kind: 'device', + booted: true, + }), + appName: 'com.example.app', + }, + ); + + const calls: string[] = []; + const response = await handleSessionCommands({ + req: { + token: 't', + session: sessionName, + command: 'close', + positionals: ['com.example.app'], + flags: {}, + }, + sessionName, + logPath: path.join(os.tmpdir(), 'daemon.log'), + sessionStore, + invoke: noopInvoke, + stopIosRunner: async () => { + calls.push('stop-runner'); + }, + dispatch: async (_device, command, positionals) => { + calls.push(`${command}:${positionals.join(' ')}`); + return {}; + }, + }); + + assert.ok(response); + assert.equal(response?.ok, true); + assert.deepEqual(calls, ['stop-runner', 'close:com.example.app', 'stop-runner']); +}); + test('open --relaunch rejects URL targets', async () => { const sessionStore = makeSessionStore(); const response = await handleSessionCommands({ diff --git a/src/daemon/handlers/session.ts b/src/daemon/handlers/session.ts index 00b1c1332a..7fdc4f5ba5 100644 --- a/src/daemon/handlers/session.ts +++ b/src/daemon/handlers/session.ts @@ -11,6 +11,7 @@ import { isDeepLinkTarget, resolveIosDeviceDeepLinkBundleId } from '../../core/o import { AppError, asAppError, normalizeError } from '../../utils/errors.ts'; import { normalizePlatformSelector, type DeviceInfo } from '../../utils/device.ts'; import { resolveAndroidSerialAllowlist, resolveIosSimulatorDeviceSetPath } from '../../utils/device-isolation.ts'; +import { resolveTimeoutMs } from '../../utils/timeouts.ts'; import type { DaemonRequest, DaemonResponse, SessionAction, SessionState } from '../types.ts'; import { SessionStore } from '../session-store.ts'; import { contextFromFlags } from '../context.ts'; @@ -66,6 +67,18 @@ const STARTUP_SAMPLE_METHOD = 'open-command-roundtrip'; const STARTUP_SAMPLE_DESCRIPTION = 'Elapsed wall-clock time around dispatching the open command for the active session app target.'; const PERF_STARTUP_SAMPLE_LIMIT = 20; +// Default simulator cool-down after terminate/close to reduce SpringBoard/XCTest attach races. +const IOS_SIMULATOR_POST_CLOSE_SETTLE_MS = resolveTimeoutMs( + process.env.AGENT_DEVICE_IOS_SIMULATOR_POST_CLOSE_SETTLE_MS, + 300, + 0, +); +// Default simulator cool-down after launch/open before follow-up interactions/attach. +const IOS_SIMULATOR_POST_OPEN_SETTLE_MS = resolveTimeoutMs( + process.env.AGENT_DEVICE_IOS_SIMULATOR_POST_OPEN_SETTLE_MS, + 300, + 0, +); type StartupPerfSample = { durationMs: number; @@ -198,6 +211,32 @@ function hasExplicitSessionFlag(flags: DaemonRequest['flags'] | undefined): bool return typeof flags?.session === 'string' && flags.session.trim().length > 0; } +function isIosSimulator(device: DeviceInfo): boolean { + return device.platform === 'ios' && device.kind === 'simulator'; +} + +async function settleIosSimulator(device: DeviceInfo, delayMs: number): Promise { + if (!isIosSimulator(device) || delayMs <= 0) return; + await new Promise((resolve) => setTimeout(resolve, delayMs)); +} + +async function relaunchCloseApp(params: { + device: DeviceInfo; + closeTarget: string; + stopIosRunner: (deviceId: string) => Promise; + dispatch: typeof dispatchCommand; + outFlag: string | undefined; + context: Parameters[4]; + settleSimulator: (device: DeviceInfo, delayMs: number) => Promise; +}): Promise { + const { device, closeTarget, stopIosRunner, dispatch, outFlag, context, settleSimulator } = params; + if (device.platform === 'ios') { + await stopIosRunner(device.id); + } + await dispatch(device, 'close', [closeTarget], outFlag, context); + await settleSimulator(device, IOS_SIMULATOR_POST_CLOSE_SETTLE_MS); +} + function selectorTargetsSessionDevice( flags: DaemonRequest['flags'] | undefined, session: SessionState | undefined, @@ -560,6 +599,7 @@ export async function handleSessionCommands(params: { device: DeviceInfo, openTarget: string | undefined, ) => Promise; + settleSimulator?: typeof settleIosSimulator; }): Promise { const { req, @@ -578,11 +618,13 @@ export async function handleSessionCommands(params: { }, ensureAndroidEmulatorBoot: ensureAndroidEmulatorBootOverride = defaultEnsureAndroidEmulatorBoot, resolveAndroidPackageForOpen: resolveAndroidPackageForOpenOverride = resolveAndroidPackageForOpen, + settleSimulator: settleSimulatorOverride, } = params; const dispatch = dispatchOverride ?? dispatchCommand; const ensureReady = ensureReadyOverride ?? ensureDeviceReady; const resolveDevice = resolveTargetDeviceOverride ?? resolveTargetDevice; const stopIosRunner = stopIosRunnerOverride ?? stopIosRunnerSession; + const settleSimulator = settleSimulatorOverride ?? settleIosSimulator; const command = req.command; if (command === 'session_list') { @@ -993,8 +1035,16 @@ export async function handleSessionCommands(params: { const openPositionals = requestedOpenTarget ? (req.positionals ?? []) : [openTarget]; if (shouldRelaunch) { const closeTarget = appBundleId ?? openTarget; - await dispatch(session.device, 'close', [closeTarget], req.flags?.out, { - ...contextFromFlags(logPath, req.flags, appBundleId ?? session.appBundleId, session.trace?.outPath), + await relaunchCloseApp({ + device: session.device, + closeTarget, + stopIosRunner, + dispatch, + outFlag: req.flags?.out, + context: { + ...contextFromFlags(logPath, req.flags, appBundleId ?? session.appBundleId, session.trace?.outPath), + }, + settleSimulator, }); } const openStartedAtMs = Date.now(); @@ -1002,6 +1052,7 @@ export async function handleSessionCommands(params: { ...contextFromFlags(logPath, req.flags, appBundleId), }); const startupSample = buildStartupPerfSample(openStartedAtMs, openTarget, appBundleId); + await settleSimulator(session.device, IOS_SIMULATOR_POST_OPEN_SETTLE_MS); const nextSession: SessionState = { ...session, appBundleId, @@ -1060,8 +1111,16 @@ export async function handleSessionCommands(params: { await resolveSessionAppBundleIdForTarget(device, openTarget, undefined, resolveAndroidPackageForOpenOverride); if (shouldRelaunch && openTarget) { const closeTarget = appBundleId ?? openTarget; - await dispatch(device, 'close', [closeTarget], req.flags?.out, { - ...contextFromFlags(logPath, req.flags, appBundleId), + await relaunchCloseApp({ + device, + closeTarget, + stopIosRunner, + dispatch, + outFlag: req.flags?.out, + context: { + ...contextFromFlags(logPath, req.flags, appBundleId), + }, + settleSimulator, }); } const openStartedAtMs = Date.now(); @@ -1069,6 +1128,7 @@ export async function handleSessionCommands(params: { ...contextFromFlags(logPath, req.flags, appBundleId), }); const startupSample = openTarget ? buildStartupPerfSample(openStartedAtMs, openTarget, appBundleId) : undefined; + await settleSimulator(device, IOS_SIMULATOR_POST_OPEN_SETTLE_MS); const session: SessionState = { name: sessionName, device, @@ -1389,9 +1449,13 @@ export async function handleSessionCommands(params: { await appLogOps.stop(session.appLog); } if (req.positionals && req.positionals.length > 0) { - await dispatch(session.device, 'close', req.positionals ?? [], req.flags?.out, { + if (session.device.platform === 'ios') { + await stopIosRunner(session.device.id); + } + await dispatch(session.device, 'close', req.positionals, req.flags?.out, { ...contextFromFlags(logPath, req.flags, session.appBundleId, session.trace?.outPath), }); + await settleSimulator(session.device, IOS_SIMULATOR_POST_CLOSE_SETTLE_MS); } if (session.device.platform === 'ios') { await stopIosRunner(session.device.id); diff --git a/src/platforms/ios/runner-client.ts b/src/platforms/ios/runner-client.ts index 201decbfaf..f3a31f352f 100644 --- a/src/platforms/ios/runner-client.ts +++ b/src/platforms/ios/runner-client.ts @@ -339,7 +339,6 @@ async function stopRunnerSessionInternal(deviceId: string, sessionOverride?: Run async function ensureBooted(device: DeviceInfo): Promise { await runCmd('xcrun', buildSimctlArgsForDevice(device, ['bootstatus', device.id, '-b']), { - allowFailure: true, timeoutMs: RUNNER_STARTUP_TIMEOUT_MS, }); }