Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
173 changes: 173 additions & 0 deletions src/daemon/handlers/__tests__/session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 <app> 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({
Expand Down
74 changes: 69 additions & 5 deletions src/daemon/handlers/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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<void> {
if (!isIosSimulator(device) || delayMs <= 0) return;
await new Promise<void>((resolve) => setTimeout(resolve, delayMs));
}

async function relaunchCloseApp(params: {
device: DeviceInfo;
closeTarget: string;
stopIosRunner: (deviceId: string) => Promise<void>;
dispatch: typeof dispatchCommand;
outFlag: string | undefined;
context: Parameters<typeof dispatchCommand>[4];
settleSimulator: (device: DeviceInfo, delayMs: number) => Promise<void>;
}): Promise<void> {
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,
Expand Down Expand Up @@ -560,6 +599,7 @@ export async function handleSessionCommands(params: {
device: DeviceInfo,
openTarget: string | undefined,
) => Promise<string | undefined>;
settleSimulator?: typeof settleIosSimulator;
}): Promise<DaemonResponse | null> {
const {
req,
Expand All @@ -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') {
Expand Down Expand Up @@ -993,15 +1035,24 @@ 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();
await dispatch(session.device, 'open', openPositionals, req.flags?.out, {
...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,
Expand Down Expand Up @@ -1060,15 +1111,24 @@ 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();
await dispatch(device, 'open', req.positionals ?? [], req.flags?.out, {
...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,
Expand Down Expand Up @@ -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);
Expand Down
1 change: 0 additions & 1 deletion src/platforms/ios/runner-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,6 @@ async function stopRunnerSessionInternal(deviceId: string, sessionOverride?: Run

async function ensureBooted(device: DeviceInfo): Promise<void> {
await runCmd('xcrun', buildSimctlArgsForDevice(device, ['bootstatus', device.id, '-b']), {
allowFailure: true,
timeoutMs: RUNNER_STARTUP_TIMEOUT_MS,
});
}
Expand Down
Loading