Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(ios-simulator): cancel create and control commands

JiangJiahaoc3867ef832fc
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
index 1345a5b7f5..7e088db2f0 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
@@ -1021,10 +1021,7 @@ describe('iOS Simulator host', () => {
device: { ...READY_REPORT.devices[0]!, state: 'Booted' },
});
const observeSessionLock = vi.fn();
- const withSessionLock = async <T>(
- sessionId: string,
- task: () => Promise<T>,
- ): Promise<T> => {
+ const withSessionLock = async <T>(sessionId: string, task: () => Promise<T>): Promise<T> => {
observeSessionLock(sessionId, task);
await lockGate;
return task();
@@ -1046,10 +1043,7 @@ describe('iOS Simulator host', () => {
releaseLock();
await reconcile;
- expect(observeSessionLock).toHaveBeenCalledWith(
- 'archived-then-restored',
- expect.any(Function),
- );
+ expect(observeSessionLock).toHaveBeenCalledWith('archived-then-restored', expect.any(Function));
expect(lifecycle.shutdownExact).not.toHaveBeenCalled();
expect(lifecycle.deleteExact).not.toHaveBeenCalled();
expect(actor.getOwned('archived-then-restored', instance.instanceId)).toMatchObject({
@@ -2239,7 +2233,15 @@ describe('iOS Simulator host', () => {
});
it('does not expose WDA endpoints or raw driver errors to callers', async () => {
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(async () => READY_REPORT.devices[0]!),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ };
const host = createIOSSimulatorHost({
+ lifecycle,
runtime: { inspect: vi.fn(async () => READY_REPORT) },
driverManager: {
get: vi.fn(() => null),
@@ -2459,29 +2461,13 @@ describe('iOS Simulator host', () => {
);
await vi.waitFor(() => expect(probe).toHaveBeenCalledTimes(2));
await expect(
- host.setViewerVisibility(
- 'session-a',
- route,
- true,
- 'jpeg',
- undefined,
- 17,
- 'viewer-current',
- ),
+ host.setViewerVisibility('session-a', route, true, 'jpeg', undefined, 17, 'viewer-current'),
).resolves.toMatchObject({ ok: true });
const hiddenCallsBeforeStaleClose = framePump.setVisible.mock.calls.filter(
([request]) => request.visible === false,
).length;
await expect(
- host.setViewerVisibility(
- 'session-a',
- route,
- false,
- 'jpeg',
- undefined,
- 17,
- 'viewer-stale',
- ),
+ host.setViewerVisibility('session-a', route, false, 'jpeg', undefined, 17, 'viewer-stale'),
).resolves.toMatchObject({ ok: true, data: { ignored: true } });
expect(
framePump.setVisible.mock.calls.filter(([request]) => request.visible === false),
@@ -2493,15 +2479,7 @@ describe('iOS Simulator host', () => {
});
await expect(
- host.setViewerVisibility(
- 'session-a',
- route,
- false,
- 'jpeg',
- undefined,
- 17,
- 'viewer-current',
- ),
+ host.setViewerVisibility('session-a', route, false, 'jpeg', undefined, 17, 'viewer-current'),
).resolves.toMatchObject({ ok: true });
let resolveRevokedProbe: (value: WdaRunningInstance | null) => void = () => undefined;
probe.mockImplementationOnce(
@@ -4089,11 +4067,159 @@ describe('iOS Simulator host', () => {
},
},
});
- expect(lifecycle.createExact).toHaveBeenCalledWith({
+ expect(lifecycle.createExact).toHaveBeenCalledWith(
+ {
+ name: 'Cindy iPhone',
+ runtimeIdentifier: templateDevice.runtimeIdentifier,
+ deviceTypeIdentifier: templateDevice.deviceTypeIdentifier,
+ },
+ expect.any(AbortSignal),
+ );
+ });
+
+ it('aborts and drains create_instance before Host disposal completes', async () => {
+ const createdUdid = '2A9D41E0-E031-4AD0-A8B5-847480802E8E';
+ let createSignal: AbortSignal | undefined;
+ let resolveCreate: (created: {
+ udid: string;
+ name: string;
+ runtimeIdentifier: string;
+ deviceTypeIdentifier: string;
+ }) => void = () => undefined;
+ let resolveDelete: () => void = () => undefined;
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(),
+ createExact: vi.fn(
+ (_input, signal) =>
+ new Promise<Awaited<ReturnType<IOSSimulatorSimctlLifecycle['createExact']>>>(
+ (resolve) => {
+ createSignal = signal;
+ resolveCreate = resolve;
+ },
+ ),
+ ),
+ deleteExact: vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveDelete = resolve;
+ }),
+ ),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore(),
+ lifecycle,
+ });
+ const templateDevice = {
+ ...READY_REPORT.devices[0]!,
+ deviceTypeIdentifier: 'com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro',
+ };
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ runtime: {
+ inspect: vi.fn(async () => ({ ...READY_REPORT, devices: [templateDevice] })),
+ },
+ getSession: vi.fn(async (id) => localSession(id)),
+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),
+ });
+
+ const call = host.callTool(
+ 'create_instance',
+ { templateUdid: templateDevice.udid, name: 'Cindy iPhone' },
+ { sessionId: 'session-a', origin: 'user' },
+ );
+ await vi.waitFor(() => expect(createSignal).toBeDefined());
+
+ const disposing = host.dispose();
+ expect(createSignal?.aborted).toBe(true);
+ resolveCreate({
+ udid: createdUdid,
name: 'Cindy iPhone',
runtimeIdentifier: templateDevice.runtimeIdentifier,
deviceTypeIdentifier: templateDevice.deviceTypeIdentifier,
});
+ await vi.waitFor(() => expect(lifecycle.deleteExact).toHaveBeenCalledOnce());
+ let disposed = false;
+ void disposing.then(() => {
+ disposed = true;
+ });
+ await Promise.resolve();
+ expect(disposed).toBe(false);
+ resolveDelete();
+
+ await expect(call).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'MUTATION_CANCELLED',
+ });
+ await expect(disposing).resolves.toBeUndefined();
+ expect(lifecycle.deleteExact).toHaveBeenCalledWith(createdUdid, expect.any(AbortSignal));
+ expect(actor.listAll()).toEqual([]);
+ });
+
+ it('forwards task cancellation to an active simulator control command', async () => {
+ let controlSignal: AbortSignal | undefined;
+ const bootedDevice = READY_REPORT.devices[0]!;
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(async () => bootedDevice),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ setAppearance: vi.fn(
+ (_udid, _appearance, signal) =>
+ new Promise<void>((_resolve, reject) => {
+ controlSignal = signal;
+ signal?.addEventListener('abort', () => reject(signal.reason), { once: true });
+ }),
+ ),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore(),
+ lifecycle,
+ });
+ const instance = actor.attach({
+ sessionId: 'session-a',
+ worktreeRoot: '/tmp/session-a',
+ sourceFingerprint: 'abc',
+ device: bootedDevice,
+ });
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ });
+ await host.reconcileOwnership();
+ const current = actor.getOwned('session-a', instance.instanceId);
+ const route = {
+ instanceId: current.instanceId,
+ generation: current.generation,
+ leaseId: current.lease.id,
+ };
+
+ const changing = host.callTool(
+ 'set_appearance',
+ { ...route, appearance: 'dark' },
+ { sessionId: 'session-a', origin: 'user' },
+ );
+ await vi.waitFor(() => expect(controlSignal).toBeDefined());
+
+ const cancelling = host.cancelSessionOperations('session-a');
+ expect(controlSignal?.aborted).toBe(true);
+
+ await expect(changing).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'MUTATION_CANCELLED',
+ });
+ await expect(cancelling).resolves.toBeUndefined();
+ expect(lifecycle.setAppearance).toHaveBeenCalledWith(
+ instance.simulatorUdid,
+ 'dark',
+ controlSignal,
+ );
+ await host.dispose();
});
it('automatically authorizes the same agent session after attach for start', async () => {
@@ -4350,8 +4476,11 @@ describe('iOS Simulator host', () => {
async (probeMode) => {
const shutdownDevice = { ...READY_REPORT.devices[0]!, state: 'Shutdown' as const };
const bootingDevice = { ...READY_REPORT.devices[0]!, state: 'Booting' as const };
+ let findExactCalls = 0;
const lifecycle: IOSSimulatorSimctlLifecycle = {
findExact: vi.fn(async () => {
+ findExactCalls += 1;
+ if (findExactCalls === 1) return shutdownDevice;
if (probeMode === 'probe-error') throw new Error('simctl probe failed');
return bootingDevice;
}),
@@ -4844,7 +4973,7 @@ describe('iOS Simulator host', () => {
});
await expect(cleanup).resolves.toBeUndefined();
expect(actor.list('session-a')).toEqual([]);
- expect(lifecycle.findExact).toHaveBeenCalledWith(createdDevice.udid, expect.any(AbortSignal));
+ expect(lifecycle.findExact).not.toHaveBeenCalled();
expect(lifecycle.shutdownExact).not.toHaveBeenCalled();
expect(lifecycle.deleteExact).toHaveBeenCalledWith(createdDevice.udid, expect.any(AbortSignal));
});
@@ -5773,39 +5902,69 @@ describe('iOS Simulator host', () => {
await expect(
host.callTool('clear_status_bar', route, { sessionId: 'session-a', origin: 'agent' }),
).resolves.toMatchObject({ ok: true, data: { interaction: 'clear_status_bar' } });
- expect(lifecycle.setAppearance).toHaveBeenCalledWith(instance.simulatorUdid, 'dark');
- expect(lifecycle.setIncreaseContrast).toHaveBeenCalledWith(instance.simulatorUdid, true);
+ expect(lifecycle.setAppearance).toHaveBeenCalledWith(
+ instance.simulatorUdid,
+ 'dark',
+ expect.any(AbortSignal),
+ );
+ expect(lifecycle.setIncreaseContrast).toHaveBeenCalledWith(
+ instance.simulatorUdid,
+ true,
+ expect.any(AbortSignal),
+ );
expect(lifecycle.setContentSize).toHaveBeenCalledWith(
instance.simulatorUdid,
'accessibility-extra-large',
+ expect.any(AbortSignal),
+ );
+ expect(lifecycle.setLocation).toHaveBeenCalledWith(
+ instance.simulatorUdid,
+ 31.23,
+ 121.47,
+ expect.any(AbortSignal),
+ );
+ expect(lifecycle.startLocationRoute).toHaveBeenCalledWith(
+ instance.simulatorUdid,
+ {
+ waypoints: [
+ { latitude: 31.23, longitude: 121.47 },
+ { latitude: 31.24, longitude: 121.48 },
+ ],
+ speedMetersPerSecond: 8,
+ intervalSeconds: 1,
+ distanceMeters: undefined,
+ },
+ expect.any(AbortSignal),
+ );
+ expect(lifecycle.clearLocation).toHaveBeenCalledWith(
+ instance.simulatorUdid,
+ expect.any(AbortSignal),
);
- expect(lifecycle.setLocation).toHaveBeenCalledWith(instance.simulatorUdid, 31.23, 121.47);
- expect(lifecycle.startLocationRoute).toHaveBeenCalledWith(instance.simulatorUdid, {
- waypoints: [
- { latitude: 31.23, longitude: 121.47 },
- { latitude: 31.24, longitude: 121.48 },
- ],
- speedMetersPerSecond: 8,
- intervalSeconds: 1,
- distanceMeters: undefined,
- });
- expect(lifecycle.clearLocation).toHaveBeenCalledWith(instance.simulatorUdid);
expect(lifecycle.setPrivacy).toHaveBeenCalledWith(
instance.simulatorUdid,
'grant',
'photos',
'com.example.app',
+ expect.any(AbortSignal),
);
expect(lifecycle.pushNotification).toHaveBeenCalledWith(
instance.simulatorUdid,
'com.example.app',
{ aps: { alert: 'Hi' } },
+ expect.any(AbortSignal),
+ );
+ expect(lifecycle.setStatusBar).toHaveBeenCalledWith(
+ instance.simulatorUdid,
+ {
+ time: '9:41',
+ wifiBars: 3,
+ },
+ expect.any(AbortSignal),
+ );
+ expect(lifecycle.clearStatusBar).toHaveBeenCalledWith(
+ instance.simulatorUdid,
+ expect.any(AbortSignal),
);
- expect(lifecycle.setStatusBar).toHaveBeenCalledWith(instance.simulatorUdid, {
- time: '9:41',
- wifiBars: 3,
- });
- expect(lifecycle.clearStatusBar).toHaveBeenCalledWith(instance.simulatorUdid);
const refreshedScreenResult = await host.callTool('get_screen_map', route, {
sessionId: 'session-a',
origin: 'agent',
@@ -6174,7 +6333,11 @@ describe('iOS Simulator host', () => {
{ sessionId: 'session-a', origin: 'user' },
),
).resolves.toMatchObject({ ok: true, data: { orientation: 'LANDSCAPE' } });
- expect(driver.setOrientation).toHaveBeenCalledWith('LANDSCAPE', 'wda-session');
+ expect(driver.setOrientation).toHaveBeenCalledWith(
+ 'LANDSCAPE',
+ 'wda-session',
+ expect.any(AbortSignal),
+ );
driver.setOrientation.mockRejectedValueOnce(
new WdaError(
'ORIENTATION_UNSUPPORTED',
@@ -6199,8 +6362,8 @@ describe('iOS Simulator host', () => {
await expect(
host.callTool('unlock_screen', route, { sessionId: 'session-a', origin: 'user' }),
).resolves.toMatchObject({ ok: true });
- expect(driver.lock).toHaveBeenCalledWith('wda-session');
- expect(driver.unlock).toHaveBeenCalledWith('wda-session');
+ expect(driver.lock).toHaveBeenCalledWith('wda-session', expect.any(AbortSignal));
+ expect(driver.unlock).toHaveBeenCalledWith('wda-session', expect.any(AbortSignal));
expect(driver.getAccessibilityTree).toHaveBeenCalledTimes(
accessibilityCallsAfterNativeInteractions,
);
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
index b35536489f..b0edad561e 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
@@ -2201,8 +2201,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
const released = await actor.runOwnershipCleanup(
instance.instanceId,
instance.sessionId,
- (owned, signal) =>
- releaseStaleBinding(owned, device, true, signal),
+ (owned, signal) => releaseStaleBinding(owned, device, true, signal),
);
return released && complete;
}
@@ -2388,18 +2387,22 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
async function readDriverViewport(
running: WdaRunningInstance,
+ signal?: AbortSignal,
): Promise<IOSSimulatorPublicViewport> {
const [size, orientation] = await Promise.all([
- running.driver.getWindowSize(running.driverSessionId),
- running.driver.getOrientation(running.driverSessionId),
+ running.driver.getWindowSize(running.driverSessionId, signal),
+ running.driver.getOrientation(running.driverSessionId, signal),
]);
const viewport = { ...size, orientation };
driverViewports.set(running.instanceId, viewport);
return viewport;
}
- async function readViewport(running: WdaRunningInstance): Promise<IOSSimulatorPublicViewport> {
- const driverViewport = await readDriverViewport(running);
+ async function readViewport(
+ running: WdaRunningInstance,
+ signal?: AbortSignal,
+ ): Promise<IOSSimulatorPublicViewport> {
+ const driverViewport = await readDriverViewport(running, signal);
const viewport = displayedViewport(
driverViewport,
viewerOrientationOverrides.get(running.instanceId) ?? driverViewport.orientation,
@@ -2408,7 +2411,10 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
return viewport;
}
- async function currentViewports(running: WdaRunningInstance): Promise<{
+ async function currentViewports(
+ running: WdaRunningInstance,
+ signal?: AbortSignal,
+ ): Promise<{
viewer: IOSSimulatorPublicViewport;
driver: IOSSimulatorPublicViewport;
}> {
@@ -2417,7 +2423,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
if (cachedViewer && cachedDriver) {
return { viewer: cachedViewer, driver: cachedDriver };
}
- const viewer = await readViewport(running);
+ const viewer = await readViewport(running, signal);
return {
viewer,
driver: driverViewports.get(running.instanceId) ?? viewer,
@@ -2951,10 +2957,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
): Promise<T> {
assertHostActive();
const sessionAdmissionEpoch = sessionOperationAdmissionEpochs.get(route.sessionId) ?? 0;
- const instanceAdmissionEpoch = captureInstanceOperationAdmission(
- route.instanceId,
- 'operation',
- );
+ const instanceAdmissionEpoch = captureInstanceOperationAdmission(route.instanceId, 'operation');
return actor.runMutation(
route,
async (instance, signal) => {
@@ -2964,22 +2967,26 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
sessionAdmissionEpoch,
'simulator operation',
);
- assertInstanceOperationAdmission(
- instance.instanceId,
- instanceAdmissionEpoch,
- 'operation',
- );
- const result = await task(instance, signal);
+ assertInstanceOperationAdmission(instance.instanceId, instanceAdmissionEpoch, 'operation');
+ let result: T;
+ try {
+ result = await task(instance, signal);
+ } catch (error) {
+ if (signal.aborted) {
+ throw new IOSSimulatorInstanceError(
+ 'MUTATION_CANCELLED',
+ 'The simulator operation was cancelled because its lifecycle changed.',
+ true,
+ );
+ }
+ throw error;
+ }
assertSessionOperationAdmission(
instance.sessionId,
sessionAdmissionEpoch,
'simulator operation',
);
- assertInstanceOperationAdmission(
- instance.instanceId,
- instanceAdmissionEpoch,
- 'operation',
- );
+ assertInstanceOperationAdmission(instance.instanceId, instanceAdmissionEpoch, 'operation');
assertHostActive();
return result;
},
@@ -3197,11 +3204,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
const normalizedSessionId = sessionId.trim();
// Register ordering before the first await, but never allocate state for a
// renderer-supplied instance id that is not owned by this exact task.
- if (
- !actor
- .list(normalizedSessionId)
- .some((instance) => instance.instanceId === instanceId)
- ) {
+ if (!actor.list(normalizedSessionId).some((instance) => instance.instanceId === instanceId)) {
return { intent: null, ignored: false };
}
const normalizedViewerToken = viewerToken ?? null;
@@ -4698,7 +4701,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
'orientation must be PORTRAIT or LANDSCAPE',
);
}
- const rotation = await runHostMutation(route, context, async (instance) => {
+ const rotation = await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
const running = requireDriver(instance.instanceId);
if (context?.origin !== 'user') {
@@ -4707,9 +4710,9 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
let mode: 'device' | 'viewer' = 'device';
let viewport: IOSSimulatorPublicViewport;
try {
- await running.driver.setOrientation(orientation, running.driverSessionId);
+ await running.driver.setOrientation(orientation, running.driverSessionId, signal);
clearViewerOrientationOverride(instance.instanceId);
- viewport = await readViewport(running);
+ viewport = await readViewport(running, signal);
} catch (error) {
const nativeDriver =
viewerEncodings.get(instance.instanceId) === 'h264'
@@ -4723,7 +4726,8 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
throw error;
}
const driverViewport =
- driverViewports.get(instance.instanceId) ?? (await readDriverViewport(running));
+ driverViewports.get(instance.instanceId) ??
+ (await readDriverViewport(running, signal));
const fallbackProfile = streamProfiles.get(instance.instanceId) ?? {
framesPerSecond: 5,
jpegQuality: 25,
@@ -4797,7 +4801,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
'appearance must be light or dark',
);
}
- await runHostMutation(route, context, async (instance) => {
+ await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
if (!lifecycle.setAppearance) {
throw new IOSSimulatorInstanceError(
@@ -4805,7 +4809,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
'Simulator appearance control is unavailable on this host.',
);
}
- await lifecycle.setAppearance(instance.simulatorUdid, appearance);
+ await lifecycle.setAppearance(instance.simulatorUdid, appearance, signal);
screenMaps.invalidate(instance.instanceId);
});
return { ok: true, data: { interaction: 'set_appearance', appearance } };
@@ -4816,7 +4820,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
if (typeof enabled !== 'boolean') {
throw new IOSSimulatorInstanceError('INVALID_ARGUMENT', 'enabled must be a boolean');
}
- await runHostMutation(route, context, async (instance) => {
+ await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
if (!lifecycle.setIncreaseContrast) {
throw new IOSSimulatorInstanceError(
@@ -4824,7 +4828,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
'Simulator Increase Contrast control is unavailable on this host.',
);
}
- await lifecycle.setIncreaseContrast(instance.simulatorUdid, enabled);
+ await lifecycle.setIncreaseContrast(instance.simulatorUdid, enabled, signal);
screenMaps.invalidate(instance.instanceId);
});
return { ok: true, data: { interaction: 'set_increase_contrast', enabled } };
@@ -4849,7 +4853,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
if (!validContentSizes.has(contentSize)) {
throw new IOSSimulatorInstanceError('INVALID_ARGUMENT', 'contentSize is invalid');
}
- await runHostMutation(route, context, async (instance) => {
+ await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
if (!lifecycle.setContentSize) {
throw new IOSSimulatorInstanceError(
@@ -4857,7 +4861,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
'Simulator Dynamic Type control is unavailable on this host.',
);
}
- await lifecycle.setContentSize(instance.simulatorUdid, contentSize);
+ await lifecycle.setContentSize(instance.simulatorUdid, contentSize, signal);
screenMaps.invalidate(instance.instanceId);
});
return { ok: true, data: { interaction: 'set_content_size', contentSize } };
@@ -4866,7 +4870,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
const route = readMutationRoute(sessionId, args);
const latitude = readBoundedFinite(args, 'latitude', -90, 90);
const longitude = readBoundedFinite(args, 'longitude', -180, 180);
- await runHostMutation(route, context, async (instance) => {
+ await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
if (!lifecycle.setLocation) {
throw new IOSSimulatorInstanceError(
@@ -4874,7 +4878,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
'Simulator location control is unavailable on this host.',
);
}
- await lifecycle.setLocation(instance.simulatorUdid, latitude, longitude);
+ await lifecycle.setLocation(instance.simulatorUdid, latitude, longitude, signal);
screenMaps.invalidate(instance.instanceId);
});
return { ok: true, data: { interaction: 'set_location', latitude, longitude } };
@@ -4919,7 +4923,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
'intervalSeconds and distanceMeters cannot be used together',
);
}
- await runHostMutation(route, context, async (instance) => {
+ await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
if (!lifecycle.startLocationRoute) {
throw new IOSSimulatorInstanceError(
@@ -4927,12 +4931,16 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
'Simulator location route control is unavailable on this host.',
);
}
- await lifecycle.startLocationRoute(instance.simulatorUdid, {
- waypoints,
- speedMetersPerSecond,
- intervalSeconds,
- distanceMeters,
- } satisfies IOSSimulatorLocationRouteOptions);
+ await lifecycle.startLocationRoute(
+ instance.simulatorUdid,
+ {
+ waypoints,
+ speedMetersPerSecond,
+ intervalSeconds,
+ distanceMeters,
+ } satisfies IOSSimulatorLocationRouteOptions,
+ signal,
+ );
screenMaps.invalidate(instance.instanceId);
});
return {
@@ -4942,7 +4950,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
}
if (name === 'clear_location') {
const route = readMutationRoute(sessionId, args);
- await runHostMutation(route, context, async (instance) => {
+ await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
if (!lifecycle.clearLocation) {
throw new IOSSimulatorInstanceError(
@@ -4950,7 +4958,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
'Simulator location control is unavailable on this host.',
);
}
- await lifecycle.clearLocation(instance.simulatorUdid);
+ await lifecycle.clearLocation(instance.simulatorUdid, signal);
screenMaps.invalidate(instance.instanceId);
});
return { ok: true, data: { interaction: 'clear_location' } };
@@ -4966,7 +4974,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
if (!/^[a-z][a-z0-9-]{0,63}$/.test(service)) {
throw new IOSSimulatorInstanceError('INVALID_ARGUMENT', 'privacy service is invalid');
}
- await runHostMutation(route, context, async (instance) => {
+ await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
if (!lifecycle.setPrivacy) {
throw new IOSSimulatorInstanceError(
@@ -4979,6 +4987,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
action as 'grant' | 'revoke' | 'reset',
service,
bundleId,
+ signal,
);
screenMaps.invalidate(instance.instanceId);
});
@@ -4991,7 +5000,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
const route = readMutationRoute(sessionId, args);
const bundleId = readString(args, 'bundleId');
const payload = readObject(args, 'payload');
- await runHostMutation(route, context, async (instance) => {
+ await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
if (!lifecycle.pushNotification) {
throw new IOSSimulatorInstanceError(
@@ -4999,7 +5008,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
'Simulator push notification control is unavailable on this host.',
);
}
- await lifecycle.pushNotification(instance.simulatorUdid, bundleId, payload);
+ await lifecycle.pushNotification(instance.simulatorUdid, bundleId, payload, signal);
screenMaps.invalidate(instance.instanceId);
});
return {
@@ -5020,7 +5029,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
...(typeof args.batteryState === 'string' ? { batteryState: args.batteryState } : {}),
...(typeof args.batteryLevel === 'number' ? { batteryLevel: args.batteryLevel } : {}),
} as IOSSimulatorStatusBarOverrides;
- await runHostMutation(route, context, async (instance) => {
+ await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
if (!lifecycle.setStatusBar) {
throw new IOSSimulatorInstanceError(
@@ -5028,14 +5037,14 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
'Simulator status-bar control is unavailable on this host.',
);
}
- await lifecycle.setStatusBar(instance.simulatorUdid, overrides);
+ await lifecycle.setStatusBar(instance.simulatorUdid, overrides, signal);
screenMaps.invalidate(instance.instanceId);
});
return { ok: true, data: { interaction: 'set_status_bar', overrides } };
}
if (name === 'clear_status_bar') {
const route = readMutationRoute(sessionId, args);
- await runHostMutation(route, context, async (instance) => {
+ await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
if (!lifecycle.clearStatusBar) {
throw new IOSSimulatorInstanceError(
@@ -5043,23 +5052,23 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
'Simulator status-bar control is unavailable on this host.',
);
}
- await lifecycle.clearStatusBar(instance.simulatorUdid);
+ await lifecycle.clearStatusBar(instance.simulatorUdid, signal);
screenMaps.invalidate(instance.instanceId);
});
return { ok: true, data: { interaction: 'clear_status_bar' } };
}
if (name === 'lock_screen' || name === 'unlock_screen') {
const route = readMutationRoute(sessionId, args);
- await runHostMutation(route, context, async (instance) => {
+ await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
const running = requireDriver(instance.instanceId);
if (context?.origin !== 'user') {
requireAgentInteractionSnapshot(instance, args);
}
if (name === 'lock_screen') {
- await running.driver.lock(running.driverSessionId);
+ await running.driver.lock(running.driverSessionId, signal);
} else {
- await running.driver.unlock(running.driverSessionId);
+ await running.driver.unlock(running.driverSessionId, signal);
}
screenMaps.invalidate(instance.instanceId);
});
@@ -5752,6 +5761,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
cancelSessionOperations(sessionId) {
const normalizedSessionId = sessionId.trim();
return Promise.all([
+ actor.cancelLifecycleStartsForSession(normalizedSessionId),
actor.cancelMutationsForSession(normalizedSessionId),
cancelSessionBuildsAndRecordings(normalizedSessionId),
]).then(() => undefined);
diff --git a/packages/ios-simulator-runtime/src/instance-actor.test.ts b/packages/ios-simulator-runtime/src/instance-actor.test.ts
index 1fb480879e..4fa04104e0 100644
--- a/packages/ios-simulator-runtime/src/instance-actor.test.ts
+++ b/packages/ios-simulator-runtime/src/instance-actor.test.ts
@@ -2,7 +2,10 @@ import { describe, expect, it, vi } from "vitest";
import { IOSSimulatorInstanceActor } from "./instance-actor.js";
import { IOSSimulatorOwnershipStore } from "./ownership-store.js";
-import type { IOSSimulatorSimctlLifecycle } from "./simctl-lifecycle.js";
+import {
+ IOSSimulatorCreateCleanupRequiredError,
+ type IOSSimulatorSimctlLifecycle,
+} from "./simctl-lifecycle.js";
import type { IOSSimulatorDevice } from "./types.js";
const UDID = "1A9D41E0-E031-4AD0-A8B5-847480802E8E";
@@ -399,7 +402,9 @@ describe("IOSSimulatorInstanceActor", () => {
const stopping = harness.actor.stop(harness.route());
expect(activeSignal?.aborted).toBe(true);
await expect(active).rejects.toMatchObject({ code: "MUTATION_CANCELLED" });
- await expect(stopping).resolves.toMatchObject({ lifecycleState: "stopped" });
+ await expect(stopping).resolves.toMatchObject({
+ lifecycleState: "stopped",
+ });
});
it("cancels an active user mutation through the force-exit seam", async () => {
@@ -876,11 +881,14 @@ describe("IOSSimulatorInstanceActor", () => {
templateDevice: DEVICE,
});
- expect(harness.lifecycle.createExact).toHaveBeenCalledWith({
- name: "Cindy iPhone",
- runtimeIdentifier: DEVICE.runtimeIdentifier,
- deviceTypeIdentifier: DEVICE.deviceTypeIdentifier,
- });
+ expect(harness.lifecycle.createExact).toHaveBeenCalledWith(
+ {
+ name: "Cindy iPhone",
+ runtimeIdentifier: DEVICE.runtimeIdentifier,
+ deviceTypeIdentifier: DEVICE.deviceTypeIdentifier,
+ },
+ expect.any(AbortSignal),
+ );
expect(created).toMatchObject({
simulatorUdid: createdUdid,
creationProvenance: "cindy",
@@ -888,6 +896,382 @@ describe("IOSSimulatorInstanceActor", () => {
});
});
+ it("cancels and rolls back an in-flight create by owning session", async () => {
+ const harness = createHarness();
+ const createdUdid = "2A9D41E0-E031-4AD0-A8B5-847480802E8E";
+ let createSignal: AbortSignal | undefined;
+ let resolveCreate: (created: {
+ udid: string;
+ name: string;
+ runtimeIdentifier: string;
+ deviceTypeIdentifier: string;
+ }) => void = () => undefined;
+ vi.mocked(harness.lifecycle.createExact).mockImplementationOnce(
+ (_input, signal) =>
+ new Promise((resolve) => {
+ createSignal = signal;
+ resolveCreate = resolve;
+ }),
+ );
+
+ const creating = harness.actor.create({
+ sessionId: "session-a",
+ worktreeRoot: "/tmp/session-a",
+ sourceFingerprint: "abc",
+ name: "Cindy iPhone",
+ templateDevice: DEVICE,
+ });
+ await vi.waitFor(() => expect(createSignal).toBeDefined());
+
+ await harness.actor.cancelLifecycleStartsForSession("another-session");
+ expect(createSignal?.aborted).toBe(false);
+ const cancelling =
+ harness.actor.cancelLifecycleStartsForSession("session-a");
+ expect(createSignal?.aborted).toBe(true);
+ let drained = false;
+ void cancelling.then(() => {
+ drained = true;
+ });
+ await Promise.resolve();
+ expect(drained).toBe(false);
+
+ resolveCreate({
+ udid: createdUdid,
+ name: "Cindy iPhone",
+ runtimeIdentifier: DEVICE.runtimeIdentifier,
+ deviceTypeIdentifier: DEVICE.deviceTypeIdentifier!,
+ });
+
+ await expect(creating).rejects.toMatchObject({
+ code: "MUTATION_CANCELLED",
+ });
+ await expect(cancelling).resolves.toBeUndefined();
+ expect(harness.lifecycle.deleteExact).toHaveBeenCalledWith(
+ createdUdid,
+ expect.any(AbortSignal),
+ );
+ expect(
+ harness.actor
+ .listAll()
+ .some((instance) => instance.simulatorUdid === createdUdid),
+ ).toBe(false);
+ });
+
+ it("does not delete a newly created device that another session attached first", async () => {
+ const createdUdid = "2A9D41E0-E031-4AD0-A8B5-847480802E8E";
+ const createdDevice = {
+ ...DEVICE,
+ udid: createdUdid,
+ name: "Cindy iPhone",
+ };
+ let resolveCreate: (created: {
+ udid: string;
+ name: string;
+ runtimeIdentifier: string;
+ deviceTypeIdentifier: string;
+ }) => void = () => undefined;
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(async () => createdDevice),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(),
+ createExact: vi.fn(
+ () =>
+ new Promise<
+ Awaited<ReturnType<IOSSimulatorSimctlLifecycle["createExact"]>>
+ >((resolve) => {
+ resolveCreate = resolve;
+ }),
+ ),
+ deleteExact: vi.fn(async () => undefined),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ lifecycle,
+ store: new IOSSimulatorOwnershipStore({ maxInstancesPerSession: 2 }),
+ });
+
+ const creating = actor.create({
+ sessionId: "session-a",
+ worktreeRoot: "/tmp/session-a",
+ sourceFingerprint: "abc",
+ name: createdDevice.name,
+ templateDevice: DEVICE,
+ });
+ await vi.waitFor(() =>
+ expect(lifecycle.createExact).toHaveBeenCalledOnce(),
+ );
+ const attachedElsewhere = await actor.attachSerialized({
+ sessionId: "session-b",
+ worktreeRoot: "/tmp/session-b",
+ sourceFingerprint: "def",
+ device: createdDevice,
+ });
+ resolveCreate({
+ udid: createdUdid,
+ name: createdDevice.name,
+ runtimeIdentifier: DEVICE.runtimeIdentifier,
+ deviceTypeIdentifier: DEVICE.deviceTypeIdentifier!,
+ });
+
+ await expect(creating).rejects.toMatchObject({
+ code: "SIMULATOR_ATTACHED_ELSEWHERE",
+ });
+ expect(lifecycle.deleteExact).not.toHaveBeenCalled();
+ expect(
+ actor.getOwned("session-b", attachedElsewhere.instanceId),
+ ).toMatchObject({
+ simulatorUdid: createdUdid,
+ });
+ });
+
+ it("rejects a stale attach queued behind created-device rollback", async () => {
+ const createdUdid = "2A9D41E0-E031-4AD0-A8B5-847480802E8E";
+ const createdDevice = {
+ ...DEVICE,
+ udid: createdUdid,
+ name: "Cindy iPhone",
+ };
+ let createSignal: AbortSignal | undefined;
+ let resolveCreate: (created: {
+ udid: string;
+ name: string;
+ runtimeIdentifier: string;
+ deviceTypeIdentifier: string;
+ }) => void = () => undefined;
+ let resolveDelete: () => void = () => undefined;
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(async () => null),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(),
+ createExact: vi.fn(
+ (_input, signal) =>
+ new Promise<
+ Awaited<ReturnType<IOSSimulatorSimctlLifecycle["createExact"]>>
+ >((resolve) => {
+ createSignal = signal;
+ resolveCreate = resolve;
+ }),
+ ),
+ deleteExact: vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveDelete = resolve;
+ }),
+ ),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ lifecycle,
+ store: new IOSSimulatorOwnershipStore({ maxInstancesPerSession: 2 }),
+ });
+
+ const creating = actor.create({
+ sessionId: "session-a",
+ worktreeRoot: "/tmp/session-a",
+ sourceFingerprint: "abc",
+ name: createdDevice.name,
+ templateDevice: DEVICE,
+ });
+ await vi.waitFor(() => expect(createSignal).toBeDefined());
+ const cancelling = actor.cancelLifecycleStartsForSession("session-a");
+ resolveCreate({
+ udid: createdUdid,
+ name: createdDevice.name,
+ runtimeIdentifier: DEVICE.runtimeIdentifier,
+ deviceTypeIdentifier: DEVICE.deviceTypeIdentifier!,
+ });
+ await vi.waitFor(() =>
+ expect(lifecycle.deleteExact).toHaveBeenCalledOnce(),
+ );
+
+ const staleAttach = actor.attachSerialized({
+ sessionId: "session-b",
+ worktreeRoot: "/tmp/session-b",
+ sourceFingerprint: "def",
+ device: createdDevice,
+ });
+ resolveDelete();
+
+ await expect(creating).rejects.toMatchObject({
+ code: "MUTATION_CANCELLED",
+ });
+ await expect(cancelling).resolves.toBeUndefined();
+ await expect(staleAttach).rejects.toMatchObject({
+ code: "SIMULATOR_NOT_FOUND",
+ });
+ expect(actor.listAll()).toEqual([]);
+ });
+
+ it("aborts an exact attach probe so exit can drain queued create rollback", async () => {
+ const createdUdid = "2A9D41E0-E031-4AD0-A8B5-847480802E8E";
+ const createdDevice = {
+ ...DEVICE,
+ udid: createdUdid,
+ name: "Cindy iPhone",
+ };
+ let findSignal: AbortSignal | undefined;
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(
+ (_udid, signal) =>
+ new Promise<
+ Awaited<ReturnType<IOSSimulatorSimctlLifecycle["findExact"]>>
+ >((_resolve, reject) => {
+ findSignal = signal;
+ signal?.addEventListener("abort", () => reject(signal.reason), {
+ once: true,
+ });
+ }),
+ ),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(),
+ createExact: vi.fn(async () => ({
+ udid: createdUdid,
+ name: createdDevice.name,
+ runtimeIdentifier: DEVICE.runtimeIdentifier,
+ deviceTypeIdentifier: DEVICE.deviceTypeIdentifier!,
+ })),
+ deleteExact: vi.fn(async () => undefined),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ lifecycle,
+ store: new IOSSimulatorOwnershipStore({ maxInstancesPerSession: 2 }),
+ });
+
+ const attaching = actor.attachSerialized({
+ sessionId: "session-b",
+ worktreeRoot: "/tmp/session-b",
+ sourceFingerprint: "def",
+ device: createdDevice,
+ });
+ await vi.waitFor(() => expect(findSignal).toBeDefined());
+ const creating = actor.create({
+ sessionId: "session-a",
+ worktreeRoot: "/tmp/session-a",
+ sourceFingerprint: "abc",
+ name: createdDevice.name,
+ templateDevice: DEVICE,
+ });
+ await vi.waitFor(() =>
+ expect(lifecycle.createExact).toHaveBeenCalledOnce(),
+ );
+
+ actor.abortOperationsForExit();
+ const draining = actor.cancelAllLifecycleStarts();
+
+ expect(findSignal?.aborted).toBe(true);
+ await expect(attaching).rejects.toMatchObject({
+ code: "MUTATION_CANCELLED",
+ });
+ await expect(creating).rejects.toMatchObject({
+ code: "MUTATION_CANCELLED",
+ });
+ await expect(draining).resolves.toBeUndefined();
+ expect(lifecycle.deleteExact).toHaveBeenCalledWith(
+ createdUdid,
+ expect.any(AbortSignal),
+ );
+ expect(actor.listAll()).toEqual([]);
+ });
+
+ it("persists the exact created device when cancellation rollback fails", async () => {
+ const harness = createHarness();
+ const createdUdid = "2A9D41E0-E031-4AD0-A8B5-847480802E8E";
+ let createSignal: AbortSignal | undefined;
+ let resolveCreate: (created: {
+ udid: string;
+ name: string;
+ runtimeIdentifier: string;
+ deviceTypeIdentifier: string;
+ }) => void = () => undefined;
+ vi.mocked(harness.lifecycle.createExact).mockImplementationOnce(
+ (_input, signal) =>
+ new Promise((resolve) => {
+ createSignal = signal;
+ resolveCreate = resolve;
+ }),
+ );
+ vi.mocked(harness.lifecycle.deleteExact).mockRejectedValueOnce(
+ new Error("delete failed"),
+ );
+
+ const creating = harness.actor.create({
+ sessionId: "session-a",
+ worktreeRoot: "/tmp/session-a",
+ sourceFingerprint: "abc",
+ name: "Cindy iPhone",
+ templateDevice: DEVICE,
+ });
+ await vi.waitFor(() => expect(createSignal).toBeDefined());
+ const cancelling =
+ harness.actor.cancelLifecycleStartsForSession("session-a");
+ resolveCreate({
+ udid: createdUdid,
+ name: "Cindy iPhone",
+ runtimeIdentifier: DEVICE.runtimeIdentifier,
+ deviceTypeIdentifier: DEVICE.deviceTypeIdentifier!,
+ });
+
+ await expect(creating).rejects.toMatchObject({
+ code: "MUTATION_CANCELLED",
+ });
+ await expect(cancelling).resolves.toBeUndefined();
+ expect(
+ harness.actor
+ .listAll()
+ .find((instance) => instance.simulatorUdid === createdUdid),
+ ).toEqual(
+ expect.objectContaining({
+ sessionId: expect.stringMatching(/^__cindy_create_cleanup__:/),
+ creationProvenance: "cindy",
+ healthState: "degraded",
+ errorCode: "SIMULATOR_DELETE_FAILED",
+ }),
+ );
+ });
+
+ it("persists a timed-out created device without repeating spent cleanup", async () => {
+ const createdUdid = "2A9D41E0-E031-4AD0-A8B5-847480802E8E";
+ const createFailure = new Error("create timed out");
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(),
+ createExact: vi.fn(async () => {
+ throw new IOSSimulatorCreateCleanupRequiredError(
+ {
+ udid: createdUdid,
+ name: "Cindy iPhone",
+ runtimeIdentifier: DEVICE.runtimeIdentifier,
+ deviceTypeIdentifier: DEVICE.deviceTypeIdentifier!,
+ },
+ createFailure,
+ );
+ }),
+ deleteExact: vi.fn(async () => undefined),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ lifecycle,
+ store: new IOSSimulatorOwnershipStore(),
+ });
+
+ await expect(
+ actor.create({
+ sessionId: "session-a",
+ worktreeRoot: "/tmp/session-a",
+ sourceFingerprint: "abc",
+ name: "Cindy iPhone",
+ templateDevice: DEVICE,
+ }),
+ ).rejects.toBe(createFailure);
+ expect(lifecycle.deleteExact).not.toHaveBeenCalled();
+ expect(actor.listAll()).toEqual([
+ expect.objectContaining({
+ sessionId: expect.stringMatching(/^__cindy_create_cleanup__:/),
+ simulatorUdid: createdUdid,
+ healthState: "degraded",
+ errorCode: "SIMULATOR_DELETE_FAILED",
+ }),
+ ]);
+ });
+
it("deletes a newly created device when the ownership write fails after preflight", async () => {
const createdUdid = "2A9D41E0-E031-4AD0-A8B5-847480802E8E";
let mutationChecks = 0;
@@ -923,7 +1307,10 @@ describe("IOSSimulatorInstanceActor", () => {
}),
).rejects.toThrow("writer lease lost");
expect(lifecycle.createExact).toHaveBeenCalledTimes(1);
- expect(lifecycle.deleteExact).toHaveBeenCalledWith(createdUdid);
+ expect(lifecycle.deleteExact).toHaveBeenCalledWith(
+ createdUdid,
+ expect.any(AbortSignal),
+ );
expect(actor.listAll()).toEqual([]);
});
diff --git a/packages/ios-simulator-runtime/src/instance-actor.ts b/packages/ios-simulator-runtime/src/instance-actor.ts
index eef901b288..4982e360cb 100644
--- a/packages/ios-simulator-runtime/src/instance-actor.ts
+++ b/packages/ios-simulator-runtime/src/instance-actor.ts
@@ -1,6 +1,7 @@
import { IOSSimulatorInstanceError } from "./instance-errors.js";
import type {
IOSSimulatorAttachInput,
+ IOSSimulatorCreatedDevice,
IOSSimulatorInstance,
IOSSimulatorMutationRoute,
} from "./instance-types.js";
@@ -8,7 +9,10 @@ import {
IOSSimulatorOwnershipStore,
type IOSSimulatorClock,
} from "./ownership-store.js";
-import type { IOSSimulatorSimctlLifecycle } from "./simctl-lifecycle.js";
+import {
+ IOSSimulatorCreateCleanupRequiredError,
+ type IOSSimulatorSimctlLifecycle,
+} from "./simctl-lifecycle.js";
export interface IOSSimulatorScheduler {
schedule(delayMs: number, task: () => void | Promise<void>): () => void;
@@ -29,6 +33,11 @@ export interface IOSSimulatorInstanceActorOptions {
) => void;
}
+type IOSSimulatorCreateInput = Omit<IOSSimulatorAttachInput, "device"> & {
+ name: string;
+ templateDevice: IOSSimulatorAttachInput["device"];
+};
+
export interface IOSSimulatorReconcileOptions {
preserveDetachGrace?: boolean;
}
@@ -74,6 +83,7 @@ interface ActiveLifecycleStart {
const DEFAULT_DETACH_GRACE_MS = 10 * 60_000;
const DEFAULT_DETACH_CLEANUP_RETRY_MS = 5_000;
+const CREATE_ROLLBACK_TIMEOUT_MS = 4_000;
interface DetachGraceCleanupContext {
instanceId: string;
@@ -165,75 +175,92 @@ export class IOSSimulatorInstanceActor {
input: IOSSimulatorAttachInput,
): Promise<IOSSimulatorInstance> {
const normalizedUdid = input.device.udid.trim().toUpperCase();
- const existing = this.#store
- .listAll()
- .find(
- (instance) => instance.simulatorUdid.toUpperCase() === normalizedUdid,
- );
return this.#serialize(
- existing?.instanceId ?? `attach:${normalizedUdid}`,
+ this.#deviceOperationKey(normalizedUdid),
async () => {
+ const existing = this.#bindingForUdid(normalizedUdid);
if (!existing) {
- return this.attach(input);
- }
- const currentDevice = await this.#lifecycle.findExact(normalizedUdid);
- if (currentDevice === null) {
- throw new IOSSimulatorInstanceError(
- "SIMULATOR_NOT_FOUND",
- "The selected iOS Simulator device no longer exists.",
- true,
+ const currentDevice = await this.#lifecycle.findExact(
+ normalizedUdid,
+ this.#lifecycleExitController.signal,
);
+ if (currentDevice === null) {
+ throw new IOSSimulatorInstanceError(
+ "SIMULATOR_NOT_FOUND",
+ "The selected iOS Simulator device no longer exists.",
+ true,
+ );
+ }
+ return this.attach({
+ ...input,
+ device: currentDevice ?? input.device,
+ });
}
- return this.attach({
- ...input,
- // Some test adapters omit the optional lookup result. Production
- // lifecycle adapters return either an exact device or null.
- device: currentDevice ?? input.device,
+ return this.#serialize(existing.instanceId, async () => {
+ const currentDevice = await this.#lifecycle.findExact(
+ normalizedUdid,
+ this.#lifecycleExitController.signal,
+ );
+ if (currentDevice === null) {
+ throw new IOSSimulatorInstanceError(
+ "SIMULATOR_NOT_FOUND",
+ "The selected iOS Simulator device no longer exists.",
+ true,
+ );
+ }
+ return this.attach({
+ ...input,
+ // Some test adapters omit the optional lookup result. Production
+ // lifecycle adapters return either an exact device or null.
+ device: currentDevice ?? input.device,
+ });
});
},
);
}
- create(
- input: Omit<IOSSimulatorAttachInput, "device"> & {
- name: string;
- templateDevice: IOSSimulatorAttachInput["device"];
- },
- ): Promise<IOSSimulatorInstance> {
- return this.#serialize(`create:${input.sessionId}`, async () => {
- const deviceTypeIdentifier = input.templateDevice.deviceTypeIdentifier;
- if (!deviceTypeIdentifier) {
- throw new IOSSimulatorInstanceError(
- "INVALID_ARGUMENT",
- "The template simulator does not expose a device type identifier.",
+ create(input: IOSSimulatorCreateInput): Promise<IOSSimulatorInstance> {
+ return this.#runTrackedLifecycleStart(
+ `create:${input.sessionId}`,
+ input.sessionId,
+ async (signal) => {
+ this.#throwIfLifecycleStartCancelled(signal);
+ const deviceTypeIdentifier = input.templateDevice.deviceTypeIdentifier;
+ if (!deviceTypeIdentifier) {
+ throw new IOSSimulatorInstanceError(
+ "INVALID_ARGUMENT",
+ "The template simulator does not expose a device type identifier.",
+ );
+ }
+ this.#assertMutationAllowed?.();
+ let created: Awaited<
+ ReturnType<IOSSimulatorSimctlLifecycle["createExact"]>
+ >;
+ let cleanupRequired: IOSSimulatorCreateCleanupRequiredError | null =
+ null;
+ try {
+ created = await this.#lifecycle.createExact(
+ {
+ name: input.name,
+ deviceTypeIdentifier,
+ runtimeIdentifier: input.templateDevice.runtimeIdentifier,
+ },
+ signal,
+ );
+ } catch (error) {
+ if (!(error instanceof IOSSimulatorCreateCleanupRequiredError))
+ throw error;
+ created = error.createdDevice;
+ cleanupRequired = error;
+ }
+ return this.#finalizeCreatedDevice(
+ input,
+ created,
+ signal,
+ cleanupRequired,
);
- }
- this.#assertMutationAllowed?.();
- const created = await this.#lifecycle.createExact({
- name: input.name,
- deviceTypeIdentifier,
- runtimeIdentifier: input.templateDevice.runtimeIdentifier,
- });
- try {
- return this.attach({
- sessionId: input.sessionId,
- worktreeRoot: input.worktreeRoot,
- sourceFingerprint: input.sourceFingerprint,
- creationProvenance: "cindy",
- bootProvenance: "user-booted",
- device: {
- ...input.templateDevice,
- udid: created.udid,
- name: created.name,
- state: "Shutdown",
- lastBootedAt: null,
- },
- });
- } catch (error) {
- await this.#lifecycle.deleteExact(created.udid).catch(() => undefined);
- throw error;
- }
- });
+ },
+ );
}
list(sessionId: string): IOSSimulatorInstance[] {
@@ -650,18 +677,30 @@ export class IOSSimulatorInstanceActor {
} catch (error) {
return Promise.reject(error);
}
+ return this.#runTrackedLifecycleStart(
+ route.instanceId,
+ route.sessionId,
+ task,
+ );
+ }
+
+ #runTrackedLifecycleStart(
+ operationKey: string,
+ sessionId: string,
+ task: (signal: AbortSignal) => Promise<IOSSimulatorInstance>,
+ ): Promise<IOSSimulatorInstance> {
const record: ActiveLifecycleStart = {
- sessionId: route.sessionId,
+ sessionId,
controller: new AbortController(),
settled: Promise.resolve(),
};
- let records = this.#activeLifecycleStarts.get(route.instanceId);
+ let records = this.#activeLifecycleStarts.get(operationKey);
if (!records) {
records = new Set();
- this.#activeLifecycleStarts.set(route.instanceId, records);
+ this.#activeLifecycleStarts.set(operationKey, records);
}
records.add(record);
- const operation = this.#serialize(route.instanceId, () =>
+ const operation = this.#serialize(operationKey, () =>
task(record.controller.signal),
);
record.settled = operation
@@ -672,12 +711,176 @@ export class IOSSimulatorInstanceActor {
.finally(() => {
records?.delete(record);
if (records?.size === 0) {
- this.#activeLifecycleStarts.delete(route.instanceId);
+ this.#activeLifecycleStarts.delete(operationKey);
}
});
return operation;
}
+ #deviceOperationKey(udid: string): string {
+ return `attach:${udid.trim().toUpperCase()}`;
+ }
+
+ #bindingForUdid(udid: string): IOSSimulatorInstance | null {
+ const normalized = udid.trim().toUpperCase();
+ return (
+ this.#store
+ .listAll()
+ .find(
+ (instance) => instance.simulatorUdid.toUpperCase() === normalized,
+ ) ?? null
+ );
+ }
+
+ #createdAttachInput(
+ input: IOSSimulatorCreateInput,
+ created: IOSSimulatorCreatedDevice,
+ sessionId: string,
+ ): IOSSimulatorAttachInput {
+ return {
+ sessionId,
+ worktreeRoot: input.worktreeRoot,
+ sourceFingerprint: input.sourceFingerprint,
+ creationProvenance: "cindy",
+ bootProvenance: "user-booted",
+ device: {
+ ...input.templateDevice,
+ udid: created.udid,
+ name: created.name,
+ state: "Shutdown",
+ lastBootedAt: null,
+ },
+ };
+ }
+
+ #createCleanupSessionId(udid: string): string {
+ return `__cindy_create_cleanup__:${udid.trim().toUpperCase()}`;
+ }
+
+ #throwCreateFailure(
+ cleanupRequired: IOSSimulatorCreateCleanupRequiredError | null,
+ signal: AbortSignal,
+ ): void {
+ this.#throwIfLifecycleStartCancelled(signal);
+ if (!cleanupRequired) return;
+ if (cleanupRequired.originalReason instanceof Error) {
+ throw cleanupRequired.originalReason;
+ }
+ throw cleanupRequired;
+ }
+
+ async #finalizeCreatedDevice(
+ input: IOSSimulatorCreateInput,
+ created: IOSSimulatorCreatedDevice,
+ signal: AbortSignal,
+ cleanupRequired: IOSSimulatorCreateCleanupRequiredError | null,
+ ): Promise<IOSSimulatorInstance> {
+ return this.#serialize(this.#deviceOperationKey(created.udid), async () => {
+ const existing = this.#bindingForUdid(created.udid);
+ if (existing) {
+ this.#throwCreateFailure(cleanupRequired, signal);
+ throw new IOSSimulatorInstanceError(
+ "SIMULATOR_ATTACHED_ELSEWHERE",
+ "The newly created simulator was attached to another Cindy session.",
+ );
+ }
+
+ let rollbackBinding: IOSSimulatorInstance | null = null;
+ try {
+ rollbackBinding = this.attach(
+ this.#createdAttachInput(
+ input,
+ created,
+ signal.aborted || cleanupRequired
+ ? this.#createCleanupSessionId(created.udid)
+ : input.sessionId,
+ ),
+ );
+ this.#throwCreateFailure(cleanupRequired, signal);
+ return rollbackBinding;
+ } catch (error) {
+ const current = this.#bindingForUdid(created.udid);
+ if (
+ current &&
+ (!rollbackBinding ||
+ current.instanceId !== rollbackBinding.instanceId)
+ ) {
+ this.#throwCreateFailure(cleanupRequired, signal);
+ throw error;
+ }
+ rollbackBinding = current;
+ if (!rollbackBinding) {
+ try {
+ rollbackBinding = this.attach(
+ this.#createdAttachInput(
+ input,
+ created,
+ this.#createCleanupSessionId(created.udid),
+ ),
+ );
+ } catch {
+ // A registry write failure must not prevent an exact best-effort
+ // rollback. If another binding raced this fallback, protect it.
+ if (this.#bindingForUdid(created.udid)) {
+ this.#throwCreateFailure(cleanupRequired, signal);
+ throw error;
+ }
+ }
+ }
+
+ // `createExact` already spent its bounded cleanup budget before
+ // raising CleanupRequired. Persist the exact binding instead of
+ // retrying here and extending Desktop shutdown past its deadline.
+ const deleted = cleanupRequired
+ ? false
+ : await this.#rollbackCreatedDevice(created.udid);
+ if (deleted && rollbackBinding) {
+ try {
+ this.#store.release(
+ rollbackBinding.instanceId,
+ rollbackBinding.sessionId,
+ );
+ } catch {
+ // The device is gone, but retaining the exact binding is safer
+ // than replacing the authoritative create/cancellation error.
+ }
+ } else if (rollbackBinding) {
+ try {
+ this.#store.update(
+ rollbackBinding.instanceId,
+ rollbackBinding.sessionId,
+ {
+ healthState: "degraded",
+ errorCode: "SIMULATOR_DELETE_FAILED",
+ },
+ );
+ } catch {
+ // The initial attach already persisted the exact identity. Keep it
+ // intact if the diagnostic update itself cannot be written.
+ }
+ }
+ this.#throwCreateFailure(cleanupRequired, signal);
+ throw error;
+ }
+ });
+ }
+
+ async #rollbackCreatedDevice(udid: string): Promise<boolean> {
+ const controller = new AbortController();
+ const timer = setTimeout(() => {
+ controller.abort(this.#lifecycleStartCancelledError());
+ }, CREATE_ROLLBACK_TIMEOUT_MS);
+ timer.unref?.();
+ try {
+ await this.#lifecycle.deleteExact(udid, controller.signal);
+ return true;
+ } catch {
+ return false;
+ } finally {
+ clearTimeout(timer);
+ }
+ }
+
/** Abort one instance's queued/active CoreSimulator starts and await settlement. */
cancelLifecycleStartsForInstance(instanceId: string): Promise<void> {
const records = this.#activeLifecycleStartsForInstance(instanceId);
diff --git a/packages/ios-simulator-runtime/src/simctl-lifecycle.test.ts b/packages/ios-simulator-runtime/src/simctl-lifecycle.test.ts
index 64428114e7..c7fbbe7cdb 100644
--- a/packages/ios-simulator-runtime/src/simctl-lifecycle.test.ts
+++ b/packages/ios-simulator-runtime/src/simctl-lifecycle.test.ts
@@ -1,7 +1,10 @@
import { access } from "node:fs/promises";
import { describe, expect, it, vi } from "vitest";
-import { createIOSSimulatorSimctlLifecycle } from "./simctl-lifecycle.js";
+import {
+ createIOSSimulatorSimctlLifecycle,
+ IOSSimulatorCreateCleanupRequiredError,
+} from "./simctl-lifecycle.js";
import type { IOSSimulatorCommandRunner } from "./types.js";
const UDID = "1A9D41E0-E031-4AD0-A8B5-847480802E8E";
@@ -276,6 +279,149 @@ describe("createIOSSimulatorSimctlLifecycle", () => {
]);
});
+ it("cancels create and deletes only an exact late-created UDID", async () => {
+ const controller = new AbortController();
+ const reason = new Error("create cancelled for exit");
+ let createSignal: AbortSignal | undefined;
+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(
+ async (_command, args, options) => {
+ if (args[1] === "create") {
+ createSignal = options?.signal;
+ await new Promise<void>((resolve) => {
+ options?.signal?.addEventListener("abort", () => resolve(), {
+ once: true,
+ });
+ });
+ return { stdout: `${UDID}\n`, stderr: "", exitCode: null };
+ }
+ return { stdout: "", stderr: "", exitCode: 0 };
+ },
+ );
+ const lifecycle = createIOSSimulatorSimctlLifecycle({
+ commandRunner: { run },
+ });
+
+ const creating = lifecycle.createExact(
+ {
+ name: "Cindy iPhone",
+ deviceTypeIdentifier:
+ "com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro",
+ runtimeIdentifier: "com.apple.CoreSimulator.SimRuntime.iOS-26-4",
+ },
+ controller.signal,
+ );
+ await vi.waitFor(() => expect(createSignal).toBe(controller.signal));
+ controller.abort(reason);
+
+ await expect(creating).rejects.toBe(reason);
+ expect(run).toHaveBeenNthCalledWith(
+ 1,
+ "/usr/bin/xcrun",
+ [
+ "simctl",
+ "create",
+ "Cindy iPhone",
+ "com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro",
+ "com.apple.CoreSimulator.SimRuntime.iOS-26-4",
+ ],
+ { timeoutMs: 60_000, signal: controller.signal },
+ );
+ expect(run).toHaveBeenNthCalledWith(
+ 2,
+ "/usr/bin/xcrun",
+ ["simctl", "delete", UDID],
+ { timeoutMs: 4_000 },
+ );
+ });
+
+ it("returns the exact created identity when cancellation cleanup fails", async () => {
+ const controller = new AbortController();
+ const reason = new Error("create cancelled for exit");
+ let createSignal: AbortSignal | undefined;
+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(
+ async (_command, args, options) => {
+ if (args[1] === "create") {
+ createSignal = options?.signal;
+ await new Promise<void>((resolve) => {
+ options?.signal?.addEventListener("abort", () => resolve(), {
+ once: true,
+ });
+ });
+ return { stdout: `${UDID}\n`, stderr: "", exitCode: null };
+ }
+ return { stdout: "", stderr: "delete failed", exitCode: 1 };
+ },
+ );
+ const lifecycle = createIOSSimulatorSimctlLifecycle({
+ commandRunner: { run },
+ });
+
+ const creating = lifecycle.createExact(
+ {
+ name: "Cindy iPhone",
+ deviceTypeIdentifier:
+ "com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro",
+ runtimeIdentifier: "com.apple.CoreSimulator.SimRuntime.iOS-26-4",
+ },
+ controller.signal,
+ );
+ await vi.waitFor(() => expect(createSignal).toBe(controller.signal));
+ controller.abort(reason);
+
+ await expect(creating).rejects.toMatchObject({
+ name: "IOSSimulatorCreateCleanupRequiredError",
+ code: "SIMULATOR_DELETE_FAILED",
+ originalReason: reason,
+ createdDevice: {
+ udid: UDID,
+ name: "Cindy iPhone",
+ deviceTypeIdentifier:
+ "com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro",
+ runtimeIdentifier: "com.apple.CoreSimulator.SimRuntime.iOS-26-4",
+ },
+ } satisfies Partial<IOSSimulatorCreateCleanupRequiredError>);
+ expect(run).toHaveBeenNthCalledWith(
+ 2,
+ "/usr/bin/xcrun",
+ ["simctl", "delete", UDID],
+ { timeoutMs: 4_000 },
+ );
+ });
+
+ it("preserves an exact UUID when create times out and cleanup fails", async () => {
+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(
+ async (_command, args) =>
+ args[1] === "create"
+ ? { stdout: `${UDID}\n`, stderr: "", exitCode: null }
+ : { stdout: "", stderr: "delete failed", exitCode: 1 },
+ );
+ const lifecycle = createIOSSimulatorSimctlLifecycle({
+ commandRunner: { run },
+ });
+
+ await expect(
+ lifecycle.createExact({
+ name: "Cindy iPhone",
+ deviceTypeIdentifier:
+ "com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro",
+ runtimeIdentifier: "com.apple.CoreSimulator.SimRuntime.iOS-26-4",
+ }),
+ ).rejects.toMatchObject({
+ name: "IOSSimulatorCreateCleanupRequiredError",
+ code: "SIMULATOR_DELETE_FAILED",
+ originalReason: expect.objectContaining({
+ code: "SIMULATOR_CREATE_FAILED",
+ }),
+ createdDevice: expect.objectContaining({ udid: UDID }),
+ });
+ expect(run).toHaveBeenNthCalledWith(
+ 2,
+ "/usr/bin/xcrun",
+ ["simctl", "delete", UDID],
+ { timeoutMs: 4_000 },
+ );
+ });
+
it("rejects non-UUID mutation selectors before invoking simctl", async () => {
const run = vi.fn();
const lifecycle = createIOSSimulatorSimctlLifecycle({
@@ -297,101 +443,127 @@ describe("createIOSSimulatorSimctlLifecycle", () => {
const lifecycle = createIOSSimulatorSimctlLifecycle({
commandRunner: { run },
});
+ const signal = new AbortController().signal;
- await lifecycle.setAppearance?.(UDID, "dark");
- await lifecycle.setLocation?.(UDID, 31.2304, 121.4737);
- await lifecycle.startLocationRoute?.(UDID, {
- waypoints: [
- { latitude: 31.2304, longitude: 121.4737 },
- { latitude: 31.233, longitude: 121.48 },
- ],
- speedMetersPerSecond: 12,
- intervalSeconds: 2,
- });
- await lifecycle.clearLocation?.(UDID);
- await lifecycle.setPrivacy?.(UDID, "grant", "photos", "com.example.app");
- await lifecycle.setPrivacy?.(UDID, "reset", "all");
- await lifecycle.pushNotification?.(UDID, "com.example.app", {
- aps: { alert: "Hello" },
- });
- await lifecycle.setStatusBar?.(UDID, {
- time: "9:41",
- wifiBars: 3,
- batteryLevel: 100,
- });
- await lifecycle.clearStatusBar?.(UDID);
-
- expect(run).toHaveBeenNthCalledWith(1, "/usr/bin/xcrun", [
- "simctl",
- "ui",
- UDID,
- "appearance",
- "dark",
- ]);
- expect(run).toHaveBeenNthCalledWith(2, "/usr/bin/xcrun", [
- "simctl",
- "location",
- UDID,
- "set",
- "31.2304,121.4737",
- ]);
- expect(run).toHaveBeenNthCalledWith(3, "/usr/bin/xcrun", [
- "simctl",
- "location",
+ await lifecycle.setAppearance?.(UDID, "dark", signal);
+ await lifecycle.setLocation?.(UDID, 31.2304, 121.4737, signal);
+ await lifecycle.startLocationRoute?.(
UDID,
- "start",
- "--speed=12",
- "--interval=2",
- "31.2304,121.4737",
- "31.233,121.48",
- ]);
- expect(run).toHaveBeenNthCalledWith(4, "/usr/bin/xcrun", [
- "simctl",
- "location",
- UDID,
- "clear",
- ]);
- expect(run).toHaveBeenNthCalledWith(5, "/usr/bin/xcrun", [
- "simctl",
- "privacy",
+ {
+ waypoints: [
+ { latitude: 31.2304, longitude: 121.4737 },
+ { latitude: 31.233, longitude: 121.48 },
+ ],
+ speedMetersPerSecond: 12,
+ intervalSeconds: 2,
+ },
+ signal,
+ );
+ await lifecycle.clearLocation?.(UDID, signal);
+ await lifecycle.setPrivacy?.(
UDID,
"grant",
"photos",
"com.example.app",
- ]);
- expect(run).toHaveBeenNthCalledWith(6, "/usr/bin/xcrun", [
- "simctl",
- "privacy",
+ signal,
+ );
+ await lifecycle.setPrivacy?.(UDID, "reset", "all", undefined, signal);
+ await lifecycle.pushNotification?.(
UDID,
- "reset",
- "all",
- ]);
+ "com.example.app",
+ {
+ aps: { alert: "Hello" },
+ },
+ signal,
+ );
+ await lifecycle.setStatusBar?.(
+ UDID,
+ {
+ time: "9:41",
+ wifiBars: 3,
+ batteryLevel: 100,
+ },
+ signal,
+ );
+ await lifecycle.clearStatusBar?.(UDID, signal);
+
+ expect(run).toHaveBeenNthCalledWith(
+ 1,
+ "/usr/bin/xcrun",
+ ["simctl", "ui", UDID, "appearance", "dark"],
+ { signal },
+ );
+ expect(run).toHaveBeenNthCalledWith(
+ 2,
+ "/usr/bin/xcrun",
+ ["simctl", "location", UDID, "set", "31.2304,121.4737"],
+ { signal },
+ );
+ expect(run).toHaveBeenNthCalledWith(
+ 3,
+ "/usr/bin/xcrun",
+ [
+ "simctl",
+ "location",
+ UDID,
+ "start",
+ "--speed=12",
+ "--interval=2",
+ "31.2304,121.4737",
+ "31.233,121.48",
+ ],
+ { signal },
+ );
+ expect(run).toHaveBeenNthCalledWith(
+ 4,
+ "/usr/bin/xcrun",
+ ["simctl", "location", UDID, "clear"],
+ { signal },
+ );
+ expect(run).toHaveBeenNthCalledWith(
+ 5,
+ "/usr/bin/xcrun",
+ ["simctl", "privacy", UDID, "grant", "photos", "com.example.app"],
+ { signal },
+ );
+ expect(run).toHaveBeenNthCalledWith(
+ 6,
+ "/usr/bin/xcrun",
+ ["simctl", "privacy", UDID, "reset", "all"],
+ { signal },
+ );
const pushCall = run.mock.calls[6];
expect(pushCall?.[0]).toBe("/usr/bin/xcrun");
expect(pushCall?.[1]).toEqual(
expect.arrayContaining(["simctl", "push", UDID, "com.example.app"]),
);
+ expect(pushCall?.[2]).toEqual({ signal });
const payloadPath = pushCall?.[1]?.at(-1);
expect(typeof payloadPath).toBe("string");
await expect(access(String(payloadPath))).rejects.toThrow();
- expect(run).toHaveBeenNthCalledWith(8, "/usr/bin/xcrun", [
- "simctl",
- "status_bar",
- UDID,
- "override",
- "--time",
- "9:41",
- "--wifiBars",
- "3",
- "--batteryLevel",
- "100",
- ]);
- expect(run).toHaveBeenNthCalledWith(9, "/usr/bin/xcrun", [
- "simctl",
- "status_bar",
- UDID,
- "clear",
- ]);
+ expect(run).toHaveBeenNthCalledWith(
+ 8,
+ "/usr/bin/xcrun",
+ [
+ "simctl",
+ "status_bar",
+ UDID,
+ "override",
+ "--time",
+ "9:41",
+ "--wifiBars",
+ "3",
+ "--batteryLevel",
+ "100",
+ ],
+ { signal },
+ );
+ expect(run).toHaveBeenNthCalledWith(
+ 9,
+ "/usr/bin/xcrun",
+ ["simctl", "status_bar", UDID, "clear"],
+ { signal },
+ );
});
it("uses bounded argv for accessibility contrast and Dynamic Type controls", async () => {
@@ -403,24 +575,49 @@ describe("createIOSSimulatorSimctlLifecycle", () => {
const lifecycle = createIOSSimulatorSimctlLifecycle({
commandRunner: { run },
});
+ const signal = new AbortController().signal;
- await lifecycle.setIncreaseContrast?.(UDID, true);
- await lifecycle.setContentSize?.(UDID, "accessibility-extra-large");
+ await lifecycle.setIncreaseContrast?.(UDID, true, signal);
+ await lifecycle.setContentSize?.(UDID, "accessibility-extra-large", signal);
- expect(run).toHaveBeenNthCalledWith(1, "/usr/bin/xcrun", [
- "simctl",
- "ui",
- UDID,
- "increase_contrast",
- "enabled",
- ]);
- expect(run).toHaveBeenNthCalledWith(2, "/usr/bin/xcrun", [
- "simctl",
- "ui",
- UDID,
- "content_size",
- "accessibility-extra-large",
- ]);
+ expect(run).toHaveBeenNthCalledWith(
+ 1,
+ "/usr/bin/xcrun",
+ ["simctl", "ui", UDID, "increase_contrast", "enabled"],
+ { signal },
+ );
+ expect(run).toHaveBeenNthCalledWith(
+ 2,
+ "/usr/bin/xcrun",
+ ["simctl", "ui", UDID, "content_size", "accessibility-extra-large"],
+ { signal },
+ );
+ });
+
+ it("preserves the abort reason for an active simulator control", async () => {
+ const controller = new AbortController();
+ const reason = new Error("control cancelled for exit");
+ let commandSignal: AbortSignal | undefined;
+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(
+ async (_command, _args, options) => {
+ commandSignal = options?.signal;
+ await new Promise<void>((resolve) => {
+ options?.signal?.addEventListener("abort", () => resolve(), {
+ once: true,
+ });
+ });
+ return { stdout: "", stderr: "", exitCode: null };
+ },
+ );
+ const lifecycle = createIOSSimulatorSimctlLifecycle({
+ commandRunner: { run },
+ });
+
+ const changing = lifecycle.setAppearance?.(UDID, "dark", controller.signal);
+ await vi.waitFor(() => expect(commandSignal).toBe(controller.signal));
+ controller.abort(reason);
+
+ await expect(changing).rejects.toBe(reason);
});
it("rejects invalid location and privacy arguments before invoking simctl", async () => {
diff --git a/packages/ios-simulator-runtime/src/simctl-lifecycle.ts b/packages/ios-simulator-runtime/src/simctl-lifecycle.ts
index af574c1e33..d6e25d8357 100644
--- a/packages/ios-simulator-runtime/src/simctl-lifecycle.ts
+++ b/packages/ios-simulator-runtime/src/simctl-lifecycle.ts
@@ -10,6 +10,7 @@ import type { IOSSimulatorCommandRunner, IOSSimulatorDevice } from "./types.js";
const XCRUN = "/usr/bin/xcrun";
const UUID_PATTERN = /^[0-9A-F]{8}(?:-[0-9A-F]{4}){3}-[0-9A-F]{12}$/;
+const CREATE_ABORT_CLEANUP_TIMEOUT_MS = 4_000;
export interface IOSSimulatorLifecycleClock {
now(): number;
@@ -23,6 +24,27 @@ export interface IOSSimulatorSimctlLifecycleOptions {
pollIntervalMs?: number;
}
+/**
+ * Carries the exact device identity when a failed or aborted `simctl create`
+ * produced a device but its immediate compensating delete also failed. The
+ * ownership actor can persist that identity for recovery instead of losing it.
+ */
+export class IOSSimulatorCreateCleanupRequiredError extends IOSSimulatorInstanceError {
+ constructor(
+ readonly createdDevice: IOSSimulatorCreatedDevice,
+ readonly originalReason: unknown,
+ options: { cause?: unknown } = {},
+ ) {
+ super(
+ "SIMULATOR_DELETE_FAILED",
+ "The simulator was created, but cancellation cleanup could not remove it.",
+ true,
+ );
+ this.name = "IOSSimulatorCreateCleanupRequiredError";
+ if (options.cause !== undefined) this.cause = options.cause;
+ }
+}
+
export interface IOSSimulatorStatusBarOverrides {
time?: string;
dataNetwork?:
@@ -79,52 +101,69 @@ export interface IOSSimulatorSimctlLifecycle {
): Promise<IOSSimulatorDevice | null>;
bootExact(udid: string, signal?: AbortSignal): Promise<IOSSimulatorDevice>;
shutdownExact(udid: string, signal?: AbortSignal): Promise<void>;
- createExact(input: {
- name: string;
- deviceTypeIdentifier: string;
- runtimeIdentifier: string;
- }): Promise<IOSSimulatorCreatedDevice>;
+ createExact(
+ input: {
+ name: string;
+ deviceTypeIdentifier: string;
+ runtimeIdentifier: string;
+ },
+ signal?: AbortSignal,
+ ): Promise<IOSSimulatorCreatedDevice>;
deleteExact(udid: string, signal?: AbortSignal): Promise<void>;
/** Set the simulated system appearance without bringing Simulator.app forward. */
- setAppearance?(udid: string, appearance: "light" | "dark"): Promise<void>;
+ setAppearance?(
+ udid: string,
+ appearance: "light" | "dark",
+ signal?: AbortSignal,
+ ): Promise<void>;
/** Enable or disable the simulated Increase Contrast accessibility setting. */
- setIncreaseContrast?(udid: string, enabled: boolean): Promise<void>;
+ setIncreaseContrast?(
+ udid: string,
+ enabled: boolean,
+ signal?: AbortSignal,
+ ): Promise<void>;
/** Set the simulated Dynamic Type content-size category. */
setContentSize?(
udid: string,
contentSize: IOSSimulatorContentSize,
+ signal?: AbortSignal,
): Promise<void>;
/** Set or clear the simulated device location. */
setLocation?(
udid: string,
latitude: number,
longitude: number,
+ signal?: AbortSignal,
): Promise<void>;
/** Start a bounded simulated route through explicit latitude/longitude waypoints. */
startLocationRoute?(
udid: string,
options: IOSSimulatorLocationRouteOptions,
+ signal?: AbortSignal,
): Promise<void>;
- clearLocation?(udid: string): Promise<void>;
+ clearLocation?(udid: string, signal?: AbortSignal): Promise<void>;
/** Grant, revoke, or reset an app privacy permission. */
setPrivacy?(
udid: string,
action: "grant" | "revoke" | "reset",
service: string,
bundleId?: string,
+ signal?: AbortSignal,
): Promise<void>;
/** Send one bounded APNs simulator payload through simctl. */
pushNotification?(
udid: string,
bundleId: string,
payload: Record<string, unknown>,
+ signal?: AbortSignal,
): Promise<void>;
/** Set or clear deterministic status-bar overrides. */
setStatusBar?(
udid: string,
overrides: IOSSimulatorStatusBarOverrides,
+ signal?: AbortSignal,
): Promise<void>;
- clearStatusBar?(udid: string): Promise<void>;
+ clearStatusBar?(udid: string, signal?: AbortSignal): Promise<void>;
}
function requireUdid(value: string): string {
@@ -419,6 +458,28 @@ export function createIOSSimulatorSimctlLifecycle(
);
}
+ async function runSimctl(args: readonly string[], signal?: AbortSignal) {
+ throwIfAborted(signal);
+ const result = signal
+ ? await runner.run(XCRUN, args, { signal })
+ : await runner.run(XCRUN, args);
+ throwIfAborted(signal);
+ return result;
+ }
+
+ async function cleanupFailedCreate(udid: string): Promise<void> {
+ const result = await runner.run(XCRUN, ["simctl", "delete", udid], {
+ timeoutMs: CREATE_ABORT_CLEANUP_TIMEOUT_MS,
+ });
+ if (result.exitCode !== 0) {
+ throw new IOSSimulatorInstanceError(
+ "SIMULATOR_DELETE_FAILED",
+ "The simulator created during cancellation could not be removed.",
+ true,
+ );
+ }
+ }
+
async function list(signal?: AbortSignal): Promise<IOSSimulatorDevice[]> {
throwIfAborted(signal);
const result = signal
@@ -565,7 +626,7 @@ export function createIOSSimulatorSimctlLifecycle(
}
},
- async createExact(input): Promise<IOSSimulatorCreatedDevice> {
+ async createExact(input, signal): Promise<IOSSimulatorCreatedDevice> {
const name = requireIdentifier(input.name, "name");
const deviceTypeIdentifier = requireIdentifier(
input.deviceTypeIdentifier,
@@ -575,18 +636,45 @@ export function createIOSSimulatorSimctlLifecycle(
input.runtimeIdentifier,
"runtimeIdentifier",
);
+ throwIfAborted(signal);
const result = await runner.run(
XCRUN,
["simctl", "create", name, deviceTypeIdentifier, runtimeIdentifier],
- { timeoutMs: 60_000 },
+ signal ? { timeoutMs: 60_000, signal } : { timeoutMs: 60_000 },
);
const udid = result.stdout.trim().toUpperCase();
- if (result.exitCode !== 0 || !UUID_PATTERN.test(udid)) {
- throw new IOSSimulatorInstanceError(
- "SIMULATOR_CREATE_FAILED",
- "The iOS Simulator device could not be created.",
- );
+ const hasExactCreatedDevice = UUID_PATTERN.test(udid);
+ const createFailure =
+ result.exitCode !== 0 || !hasExactCreatedDevice
+ ? new IOSSimulatorInstanceError(
+ "SIMULATOR_CREATE_FAILED",
+ "The iOS Simulator device could not be created.",
+ )
+ : null;
+ if (hasExactCreatedDevice && (signal?.aborted || createFailure)) {
+ const createdDevice = {
+ udid,
+ name,
+ runtimeIdentifier,
+ deviceTypeIdentifier,
+ };
+ const originalReason = signal?.aborted ? signal.reason : createFailure;
+ try {
+ await cleanupFailedCreate(udid);
+ } catch (error) {
+ throw new IOSSimulatorCreateCleanupRequiredError(
+ createdDevice,
+ originalReason,
+ {
+ cause: error,
+ },
+ );
+ }
+ }
+ if (signal?.aborted) {
+ throwIfAborted(signal);
}
+ if (createFailure) throw createFailure;
return { udid, name, runtimeIdentifier, deviceTypeIdentifier };
},
@@ -607,7 +695,7 @@ export function createIOSSimulatorSimctlLifecycle(
}
},
- async setAppearance(udid, appearance): Promise<void> {
+ async setAppearance(udid, appearance, signal): Promise<void> {
const normalized = requireUdid(udid);
if (appearance !== "light" && appearance !== "dark") {
throw new IOSSimulatorInstanceError(
@@ -615,13 +703,10 @@ export function createIOSSimulatorSimctlLifecycle(
"appearance must be light or dark",
);
}
- const result = await runner.run(XCRUN, [
- "simctl",
- "ui",
- normalized,
- "appearance",
- appearance,
- ]);
+ const result = await runSimctl(
+ ["simctl", "ui", normalized, "appearance", appearance],
+ signal,
+ );
if (result.exitCode !== 0) {
throw new IOSSimulatorInstanceError(
"SIMULATOR_CONTROL_FAILED",
@@ -631,7 +716,7 @@ export function createIOSSimulatorSimctlLifecycle(
}
},
- async setIncreaseContrast(udid, enabled): Promise<void> {
+ async setIncreaseContrast(udid, enabled, signal): Promise<void> {
const normalized = requireUdid(udid);
if (typeof enabled !== "boolean") {
throw new IOSSimulatorInstanceError(
@@ -639,13 +724,16 @@ export function createIOSSimulatorSimctlLifecycle(
"increase contrast enabled must be a boolean",
);
}
- const result = await runner.run(XCRUN, [
- "simctl",
- "ui",
- normalized,
- "increase_contrast",
- enabled ? "enabled" : "disabled",
- ]);
+ const result = await runSimctl(
+ [
+ "simctl",
+ "ui",
+ normalized,
+ "increase_contrast",
+ enabled ? "enabled" : "disabled",
+ ],
+ signal,
+ );
if (result.exitCode !== 0) {
throw new IOSSimulatorInstanceError(
"SIMULATOR_CONTROL_FAILED",
@@ -655,7 +743,7 @@ export function createIOSSimulatorSimctlLifecycle(
}
},
- async setContentSize(udid, contentSize): Promise<void> {
+ async setContentSize(udid, contentSize, signal): Promise<void> {
const normalized = requireUdid(udid);
if (!CONTENT_SIZES.has(contentSize)) {
throw new IOSSimulatorInstanceError(
@@ -663,13 +751,10 @@ export function createIOSSimulatorSimctlLifecycle(
"content size is invalid",
);
}
- const result = await runner.run(XCRUN, [
- "simctl",
- "ui",
- normalized,
- "content_size",
- contentSize,
- ]);
+ const result = await runSimctl(
+ ["simctl", "ui", normalized, "content_size", contentSize],
+ signal,
+ );
if (result.exitCode !== 0) {
throw new IOSSimulatorInstanceError(
"SIMULATOR_CONTROL_FAILED",
@@ -679,7 +764,7 @@ export function createIOSSimulatorSimctlLifecycle(
}
},
- async setLocation(udid, latitude, longitude): Promise<void> {
+ async setLocation(udid, latitude, longitude, signal): Promise<void> {
const normalized = requireUdid(udid);
if (!Number.isFinite(latitude) || latitude < -90 || latitude > 90) {
throw new IOSSimulatorInstanceError(
@@ -694,13 +779,10 @@ export function createIOSSimulatorSimctlLifecycle(
);
}
const coordinate = `${latitude},${longitude}`;
- const result = await runner.run(XCRUN, [
- "simctl",
- "location",
- normalized,
- "set",
- coordinate,
- ]);
+ const result = await runSimctl(
+ ["simctl", "location", normalized, "set", coordinate],
+ signal,
+ );
if (result.exitCode !== 0) {
throw new IOSSimulatorInstanceError(
"SIMULATOR_CONTROL_FAILED",
@@ -710,7 +792,7 @@ export function createIOSSimulatorSimctlLifecycle(
}
},
- async startLocationRoute(udid, options): Promise<void> {
+ async startLocationRoute(udid, options, signal): Promise<void> {
const normalized = requireUdid(udid);
const route = requireLocationRoute(options);
const args = ["simctl", "location", normalized, "start"];
@@ -727,7 +809,7 @@ export function createIOSSimulatorSimctlLifecycle(
(waypoint) => `${waypoint.latitude},${waypoint.longitude}`,
),
);
- const result = await runner.run(XCRUN, args);
+ const result = await runSimctl(args, signal);
if (result.exitCode !== 0) {
throw new IOSSimulatorInstanceError(
"SIMULATOR_CONTROL_FAILED",
@@ -737,14 +819,12 @@ export function createIOSSimulatorSimctlLifecycle(
}
},
- async clearLocation(udid): Promise<void> {
+ async clearLocation(udid, signal): Promise<void> {
const normalized = requireUdid(udid);
- const result = await runner.run(XCRUN, [
- "simctl",
- "location",
- normalized,
- "clear",
- ]);
+ const result = await runSimctl(
+ ["simctl", "location", normalized, "clear"],
+ signal,
+ );
if (result.exitCode !== 0) {
throw new IOSSimulatorInstanceError(
"SIMULATOR_CONTROL_FAILED",
@@ -754,7 +834,7 @@ export function createIOSSimulatorSimctlLifecycle(
}
},
- async setPrivacy(udid, action, service, bundleId): Promise<void> {
+ async setPrivacy(udid, action, service, bundleId, signal): Promise<void> {
const normalized = requireUdid(udid);
if (!["grant", "revoke", "reset"].includes(action)) {
throw new IOSSimulatorInstanceError(
@@ -782,7 +862,7 @@ export function createIOSSimulatorSimctlLifecycle(
}
const args = ["simctl", "privacy", normalized, action, service];
if (bundleId) args.push(bundleId);
- const result = await runner.run(XCRUN, args);
+ const result = await runSimctl(args, signal);
if (result.exitCode !== 0) {
throw new IOSSimulatorInstanceError(
"SIMULATOR_CONTROL_FAILED",
@@ -792,7 +872,7 @@ export function createIOSSimulatorSimctlLifecycle(
}
},
- async pushNotification(udid, bundleId, payload): Promise<void> {
+ async pushNotification(udid, bundleId, payload, signal): Promise<void> {
const normalized = requireUdid(udid);
const normalizedBundleId = requireBundleId(bundleId);
if (
@@ -821,20 +901,22 @@ export function createIOSSimulatorSimctlLifecycle(
"push payload must be at most 4096 bytes",
);
}
+ throwIfAborted(signal);
const tempRoot = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-push-"));
const payloadPath = path.join(tempRoot, "payload.json");
try {
- await writeFile(payloadPath, serialized, {
- encoding: "utf8",
- mode: 0o600,
- });
- const result = await runner.run(XCRUN, [
- "simctl",
- "push",
- normalized,
- normalizedBundleId,
+ await writeFile(
payloadPath,
- ]);
+ serialized,
+ signal
+ ? { encoding: "utf8", mode: 0o600, signal }
+ : { encoding: "utf8", mode: 0o600 },
+ );
+ throwIfAborted(signal);
+ const result = await runSimctl(
+ ["simctl", "push", normalized, normalizedBundleId, payloadPath],
+ signal,
+ );
if (result.exitCode !== 0) {
throw new IOSSimulatorInstanceError(
"SIMULATOR_CONTROL_FAILED",
@@ -847,16 +929,13 @@ export function createIOSSimulatorSimctlLifecycle(
}
},
- async setStatusBar(udid, overrides): Promise<void> {
+ async setStatusBar(udid, overrides, signal): Promise<void> {
const normalized = requireUdid(udid);
const entries = requireStatusBarOverrides(overrides);
- const result = await runner.run(XCRUN, [
- "simctl",
- "status_bar",
- normalized,
- "override",
- ...entries.flat(),
- ]);
+ const result = await runSimctl(
+ ["simctl", "status_bar", normalized, "override", ...entries.flat()],
+ signal,
+ );
if (result.exitCode !== 0) {
throw new IOSSimulatorInstanceError(
"SIMULATOR_CONTROL_FAILED",
@@ -866,14 +945,12 @@ export function createIOSSimulatorSimctlLifecycle(
}
},
- async clearStatusBar(udid): Promise<void> {
+ async clearStatusBar(udid, signal): Promise<void> {
const normalized = requireUdid(udid);
- const result = await runner.run(XCRUN, [
- "simctl",
- "status_bar",
- normalized,
- "clear",
- ]);
+ const result = await runSimctl(
+ ["simctl", "status_bar", normalized, "clear"],
+ signal,
+ );
if (result.exitCode !== 0) {
throw new IOSSimulatorInstanceError(
"SIMULATOR_CONTROL_FAILED",