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): close teardown and route races

JiangJiahao1ae5a983e547
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 a36a111b80..38b4f3cf18 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
@@ -1490,6 +1490,81 @@ describe('iOS Simulator host', () => {
expect(stopDriver).toHaveBeenCalledWith(removed.instanceId);
});
+ it('aborts CoreSimulator startup before waiting on task-removal barriers', async () => {
+ const shutdownDevice = { ...READY_REPORT.devices[0]!, state: 'Shutdown' };
+ let bootSignal: AbortSignal | undefined;
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(async () => shutdownDevice),
+ bootExact: vi.fn(
+ (_udid, signal) =>
+ new Promise<typeof shutdownDevice>((_resolve, reject) => {
+ bootSignal = signal;
+ signal?.addEventListener('abort', () => reject(signal.reason), { once: true });
+ }),
+ ),
+ shutdownExact: vi.fn(async () => undefined),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),
+ lifecycle,
+ });
+ const attached = actor.attach({
+ sessionId: 'removed-during-start',
+ worktreeRoot: '/tmp/removed-during-start',
+ sourceFingerprint: 'fingerprint-a',
+ device: shutdownDevice,
+ });
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ resourceScheduler: testResourceScheduler(),
+ driverManager: {
+ get: vi.fn(() => null),
+ start: vi.fn(),
+ stop: vi.fn(async () => undefined),
+ },
+ mediaCapture: {
+ discardSession: vi.fn(async () => undefined),
+ discardInstance: vi.fn(async () => undefined),
+ } as unknown as IOSSimulatorMediaCaptureAdapter,
+ runtime: {
+ inspect: vi.fn(async () => ({ ...READY_REPORT, devices: [shutdownDevice] })),
+ },
+ getSession: vi.fn(async (id) => localSession(id)),
+ });
+ await host.reconcileOwnership();
+ let releasePostCancellationProbe: (device: typeof shutdownDevice) => void = () => undefined;
+ const postCancellationProbe = new Promise<typeof shutdownDevice>((resolve) => {
+ releasePostCancellationProbe = resolve;
+ });
+ vi.mocked(lifecycle.findExact).mockImplementation(async () => postCancellationProbe);
+ const current = actor.getOwned(attached.sessionId, attached.instanceId);
+ const starting = host.callTool(
+ 'start_instance',
+ {
+ instanceId: current.instanceId,
+ generation: current.generation,
+ leaseId: current.lease.id,
+ },
+ { sessionId: current.sessionId, origin: 'user' },
+ );
+ await vi.waitFor(() => expect(bootSignal).toBeDefined());
+
+ const cleanup = host.cleanupRemovedSession(current.sessionId);
+ await vi.waitFor(() => expect(bootSignal?.aborted).toBe(true));
+
+ await expect(starting).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'MUTATION_CANCELLED',
+ });
+ releasePostCancellationProbe(shutdownDevice);
+ await expect(cleanup).resolves.toBeUndefined();
+ expect(actor.list(current.sessionId)).toEqual([]);
+ await host.dispose();
+ });
+
it('retains degraded ownership and scheduler capacity when removed-task cleanup fails', async () => {
const lifecycle: IOSSimulatorSimctlLifecycle = {
findExact: vi.fn(async () => READY_REPORT.devices[0]!),
@@ -1557,6 +1632,7 @@ describe('iOS Simulator host', () => {
};
const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });
const actor = new IOSSimulatorInstanceActor({ store, lifecycle });
+ const cancelLifecycleStarts = vi.spyOn(actor, 'cancelAllLifecycleStarts');
const instance = actor.attach({
sessionId: 'dispose-session',
worktreeRoot: '/tmp/dispose-session',
@@ -1584,6 +1660,7 @@ describe('iOS Simulator host', () => {
expect(discardInstance).toHaveBeenCalledWith(instance.instanceId);
expect(stopDriver).toHaveBeenCalledTimes(1);
expect(stopDriver).toHaveBeenCalledWith(instance.instanceId);
+ expect(cancelLifecycleStarts).toHaveBeenCalledTimes(1);
expect(actor.listAll()).toHaveLength(1);
});
@@ -1791,6 +1868,7 @@ describe('iOS Simulator host', () => {
store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),
lifecycle,
});
+ const abortLifecycleStarts = vi.spyOn(actor, 'abortOperationsForExit');
const instance = actor.attach({
sessionId: 'force-quit-build-session',
worktreeRoot: '/tmp/force-quit-build-session',
@@ -1855,6 +1933,7 @@ describe('iOS Simulator host', () => {
expect(() => host.abortOperationsForExit()).not.toThrow();
expect(buildSignal?.aborted).toBe(true);
+ expect(abortLifecycleStarts).toHaveBeenCalledOnce();
expect(abortRecording).toHaveBeenCalledOnce();
expect(abortDriver).toHaveBeenCalledOnce();
await expect(callPromise).resolves.toMatchObject({
@@ -3863,7 +3942,10 @@ describe('iOS Simulator host', () => {
{ sessionId: 'session-agent', origin: 'agent' },
),
).resolves.toMatchObject({ ok: true });
- expect(lifecycle.bootExact).toHaveBeenCalledWith(instance.simulatorUdid);
+ expect(lifecycle.bootExact).toHaveBeenCalledWith(
+ instance.simulatorUdid,
+ expect.any(AbortSignal),
+ );
});
it('renews the lease after a slow driver start and opens the embedded viewer', async () => {
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
index 4e2819a560..4f8f60bfbe 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
@@ -1074,6 +1074,9 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
return instanceLifecycleBarriers.get(instanceId) ?? { epoch: 0, pendingTeardowns: 0 };
}
function beginInstanceTeardown(instanceId: string): void {
+ // Abort CoreSimulator startup at teardown admission, before media or WDA
+ // cleanup can spend the remaining lifecycle budget.
+ void actor.cancelLifecycleStartsForInstance(instanceId);
const current = lifecycleBarrier(instanceId);
instanceLifecycleBarriers.set(instanceId, {
epoch: current.epoch + 1,
@@ -1835,7 +1838,11 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
}
async function performRemovedSessionCleanup(sessionId: string): Promise<void> {
- await cancelSessionBuildsAndRecordings(sessionId);
+ // Startup calls hold the same session-removal barrier awaited below. Abort
+ // them first so task archive/delete never waits out the 120-second boot
+ // budget before ownership cleanup can begin.
+ const lifecycleStarts = actor.cancelLifecycleStartsForSession(sessionId);
+ await Promise.all([lifecycleStarts, cancelSessionBuildsAndRecordings(sessionId)]);
await Promise.all(
[...(activeSessionRemovalBarrierOperations.get(sessionId) ?? [])].map(
(operation) => operation.settled,
@@ -4014,16 +4021,26 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
// readiness. Preserve the real resource occupancy even when
// actor.start() never returns its ready snapshot.
if (lifecycleStartAttempted && !runningCommitted) {
- try {
- const device = await lifecycle.findExact(starting.simulatorUdid);
- if (device && device.state.trim().toLowerCase() !== 'shutdown') {
+ if (
+ error instanceof IOSSimulatorInstanceError &&
+ error.code === 'MUTATION_CANCELLED'
+ ) {
+ // Teardown must not start another uncancellable simctl
+ // probe after it has already aborted bootstatus. Startup
+ // may have crossed `simctl boot`, so preserve occupancy.
+ commitRunning();
+ } else {
+ try {
+ const device = await lifecycle.findExact(starting.simulatorUdid);
+ if (device && device.state.trim().toLowerCase() !== 'shutdown') {
+ commitRunning();
+ }
+ } catch {
+ // An ambiguous probe cannot prove that CoreSimulator
+ // released the resource. Fail closed while preserving the
+ // original startup failure as the authoritative error.
commitRunning();
}
- } catch {
- // An ambiguous probe cannot prove that CoreSimulator
- // released the resource. Fail closed while preserving the
- // original startup failure as the authoritative error.
- commitRunning();
}
}
throw error;
@@ -5664,6 +5681,13 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
return cleanupRemovedSessionRuntime(sessionId);
},
abortOperationsForExit() {
+ try {
+ actor.abortOperationsForExit();
+ } catch (error) {
+ logger.warn('iOS Simulator exit cleanup could not abort simulator startup', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
for (const build of activeBuilds.values()) {
try {
build.controller.abort();
@@ -5691,6 +5715,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
dispose() {
if (disposePromise) return disposePromise;
disposePromise = (async () => {
+ const lifecycleStarts = actor.cancelAllLifecycleStarts();
const builds = [...activeBuilds.values()];
for (const build of builds) build.controller.abort();
// Close the recording start gate immediately, before waiting for a
@@ -5700,7 +5725,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
error: error instanceof Error ? error.message : String(error),
});
});
- await Promise.all(builds.map((build) => build.settled));
+ await Promise.all([lifecycleStarts, ...builds.map((build) => build.settled)]);
clearVisualBaselines();
await Promise.all(
[...buildDiagnostics.entries()].map(([diagnosticsId, diagnostic]) =>
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx
index d697a1be52..fc2ce7d7a9 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx
@@ -24,6 +24,7 @@ import type {
} from '@cindy/ios-simulator-runtime';
import type {
IOSSimulatorPublicInstance,
+ IOSSimulatorSessionStatus,
IOSSimulatorToolResponse,
} from '../../../../../shared/iosSimulatorIpc';
@@ -37,6 +38,7 @@ interface IOSSimulatorInstanceGridProps {
title: string;
countLabel: string;
onSelect: (instanceId: string) => void;
+ onRefresh: () => Promise<IOSSimulatorSessionStatus | null>;
}
const BACKGROUND_PROFILE: IOSSimulatorStreamProfile = {
@@ -67,12 +69,22 @@ function routeFor(instance: IOSSimulatorPublicInstance) {
};
}
+function routeKey(instance: IOSSimulatorPublicInstance): string {
+ return `${instance.generation}:${instance.lease.id}`;
+}
+
function streamFrom(result: IOSSimulatorToolResponse): IOSSimulatorFramePumpSnapshot | null {
if (!result.ok || !result.data || typeof result.data !== 'object') return null;
const stream = (result.data as { stream?: unknown }).stream;
return stream && typeof stream === 'object' ? (stream as IOSSimulatorFramePumpSnapshot) : null;
}
+function instanceFrom(result: IOSSimulatorToolResponse): IOSSimulatorPublicInstance | null {
+ if (!result.ok || !result.data || typeof result.data !== 'object') return null;
+ const instance = (result.data as { instance?: unknown }).instance;
+ return instance && typeof instance === 'object' ? (instance as IOSSimulatorPublicInstance) : null;
+}
+
/** Compact multi-instance view with per-tile basic input routed by exact instance. */
export function IOSSimulatorInstanceGrid({
sessionId,
@@ -84,10 +96,12 @@ export function IOSSimulatorInstanceGrid({
title,
countLabel,
onSelect,
+ onRefresh,
}: IOSSimulatorInstanceGridProps) {
const { t } = useTranslation();
const [tiles, setTiles] = useState<Record<string, TileState>>({});
const [tileBusy, setTileBusy] = useState<Record<string, boolean>>({});
+ const [invalidatedRouteKeys, setInvalidatedRouteKeys] = useState<Record<string, string>>({});
const [tileErrors, setTileErrors] = useState<Record<string, string>>({});
const [tileText, setTileText] = useState<Record<string, string>>({});
const [tileOrientation, setTileOrientation] = useState<Record<string, 'PORTRAIT' | 'LANDSCAPE'>>(
@@ -95,11 +109,18 @@ export function IOSSimulatorInstanceGrid({
);
const urlsRef = useRef<Record<string, string>>({});
const gesturesRef = useRef<Record<string, TileGesture | null>>({});
+ const invalidatedRouteKeysRef = useRef<Record<string, string>>({});
+ const routeRefreshStateRef = useRef({ pending: false, nextAttemptAt: 0 });
const readyInstances = useMemo(
() => instances.filter((instance) => instance.lifecycleState === 'ready'),
[instances],
);
const viewerVisible = active && shellVisible;
+ const routeIsInvalidated = useCallback(
+ (instance: IOSSimulatorPublicInstance) =>
+ invalidatedRouteKeysRef.current[instance.instanceId] === routeKey(instance),
+ [],
+ );
const callTile = useCallback(
async (
@@ -114,7 +135,13 @@ export function IOSSimulatorInstanceGrid({
| 'unlock_screen',
args: Record<string, unknown>,
): Promise<boolean> => {
- if (instance.lifecycleState !== 'ready' || tileBusy[instance.instanceId]) return false;
+ if (
+ instance.lifecycleState !== 'ready' ||
+ tileBusy[instance.instanceId] ||
+ routeIsInvalidated(instance)
+ ) {
+ return false;
+ }
setTileBusy((previous) => ({ ...previous, [instance.instanceId]: true }));
setTileErrors((previous) => {
const next = { ...previous };
@@ -151,7 +178,7 @@ export function IOSSimulatorInstanceGrid({
setTileBusy((previous) => ({ ...previous, [instance.instanceId]: false }));
}
},
- [sessionId, t, tileBusy],
+ [routeIsInvalidated, sessionId, t, tileBusy],
);
const tilePoint = useCallback((event: ReactPointerEvent<HTMLImageElement>) => {
@@ -164,7 +191,13 @@ export function IOSSimulatorInstanceGrid({
const onTilePointerDown = useCallback(
(instance: IOSSimulatorPublicInstance, event: ReactPointerEvent<HTMLImageElement>) => {
- if (event.button !== 0 || tileBusy[instance.instanceId]) return;
+ if (
+ event.button !== 0 ||
+ tileBusy[instance.instanceId] ||
+ routeIsInvalidated(instance)
+ ) {
+ return;
+ }
const point = tilePoint(event);
gesturesRef.current[instance.instanceId] = {
pointerId: event.pointerId,
@@ -176,7 +209,7 @@ export function IOSSimulatorInstanceGrid({
};
event.currentTarget.setPointerCapture(event.pointerId);
},
- [tileBusy, tilePoint],
+ [routeIsInvalidated, tileBusy, tilePoint],
);
const onTilePointerUp = useCallback(
@@ -187,6 +220,7 @@ export function IOSSimulatorInstanceGrid({
if (event.currentTarget.hasPointerCapture(event.pointerId)) {
event.currentTarget.releasePointerCapture(event.pointerId);
}
+ if (routeIsInvalidated(instance)) return;
const end = tilePoint(event);
const distance = Math.hypot(
event.clientX - gesture.startClientX,
@@ -205,7 +239,7 @@ export function IOSSimulatorInstanceGrid({
durationMs: Math.round(durationMs),
});
},
- [callTile, tilePoint],
+ [callTile, routeIsInvalidated, tilePoint],
);
const sendTileText = useCallback(
@@ -221,6 +255,9 @@ export function IOSSimulatorInstanceGrid({
useEffect(() => {
const currentIds = new Set(readyInstances.map((instance) => instance.instanceId));
+ const currentRoutes = new Map(
+ readyInstances.map((instance) => [instance.instanceId, routeKey(instance)]),
+ );
for (const [instanceId, url] of Object.entries(urlsRef.current)) {
if (!currentIds.has(instanceId)) {
URL.revokeObjectURL(url);
@@ -232,39 +269,91 @@ export function IOSSimulatorInstanceGrid({
Object.entries(previous).filter(([instanceId]) => currentIds.has(instanceId)),
),
);
+ const retainedInvalidatedRoutes = Object.fromEntries(
+ Object.entries(invalidatedRouteKeysRef.current).filter(
+ ([instanceId, invalidatedRoute]) => currentRoutes.get(instanceId) === invalidatedRoute,
+ ),
+ );
+ invalidatedRouteKeysRef.current = retainedInvalidatedRoutes;
+ setInvalidatedRouteKeys(retainedInvalidatedRoutes);
+ if (Object.keys(retainedInvalidatedRoutes).length === 0) {
+ routeRefreshStateRef.current.nextAttemptAt = 0;
+ }
}, [readyInstances]);
useEffect(() => {
let cancelled = false;
let polling = false;
- const setVisibility = async (visible: boolean) => {
- await Promise.all(
- readyInstances.map(async (instance) => {
- const route = {
- sessionId,
- ...routeFor(instance),
- visible,
- preferredEncoding: 'jpeg' as const,
- };
- await window.electronAPI.maker.iosSimulator
- .setViewerVisibility(route)
- .catch(() => undefined);
- if (visible && instance.instanceId !== selectedInstanceId) {
- await window.electronAPI.maker.iosSimulator
- .setStreamProfile({ sessionId, ...routeFor(instance), profile: BACKGROUND_PROFILE })
- .catch(() => undefined);
- }
- }),
- );
+ const requestRouteRefresh = () => {
+ const refreshState = routeRefreshStateRef.current;
+ if (
+ cancelled ||
+ refreshState.pending ||
+ Object.keys(invalidatedRouteKeysRef.current).length === 0 ||
+ Date.now() < refreshState.nextAttemptAt
+ ) {
+ return;
+ }
+ refreshState.pending = true;
+ refreshState.nextAttemptAt = Number.POSITIVE_INFINITY;
+ void Promise.resolve()
+ .then(onRefresh)
+ .catch(() => undefined)
+ .finally(() => {
+ // A returned status may lose a concurrent request-version race in
+ // the parent. Only changed props clear invalidation; until then keep
+ // retrying at a bounded cadence.
+ refreshState.nextAttemptAt =
+ Object.keys(invalidatedRouteKeysRef.current).length > 0 ? Date.now() + 500 : 0;
+ refreshState.pending = false;
+ });
+ };
+ const invalidateRoute = (instance: IOSSimulatorPublicInstance) => {
+ const instanceId = instance.instanceId;
+ if (cancelled || routeIsInvalidated(instance)) return;
+ const hadInvalidatedRoute = Object.keys(invalidatedRouteKeysRef.current).length > 0;
+ invalidatedRouteKeysRef.current = {
+ ...invalidatedRouteKeysRef.current,
+ [instanceId]: routeKey(instance),
+ };
+ if (!hadInvalidatedRoute) routeRefreshStateRef.current.nextAttemptAt = 0;
+ gesturesRef.current[instanceId] = null;
+ setInvalidatedRouteKeys((previous) => ({
+ ...previous,
+ [instanceId]: routeKey(instance),
+ }));
+ const previousUrl = urlsRef.current[instanceId];
+ if (previousUrl) {
+ URL.revokeObjectURL(previousUrl);
+ delete urlsRef.current[instanceId];
+ }
+ setTiles((previous) => ({
+ ...previous,
+ [instanceId]: { stream: null, frameUrl: null },
+ }));
+ requestRouteRefresh();
};
- const accept = (instanceId: string, result: IOSSimulatorToolResponse) => {
- if (cancelled) return;
+ const accept = (instance: IOSSimulatorPublicInstance, result: IOSSimulatorToolResponse) => {
+ if (cancelled || routeIsInvalidated(instance)) return;
+ if (!result.ok) {
+ if (result.errorCode === 'LEASE_EXPIRED' || result.errorCode === 'STALE_GENERATION') {
+ invalidateRoute(instance);
+ }
+ return;
+ }
+ // Host returns an instance only when reconcile or heartbeat advanced the
+ // authoritative route. Stop using the captured generation/lease before
+ // another poll or tile control can race the parent refresh.
+ if (instanceFrom(result)) {
+ invalidateRoute(instance);
+ return;
+ }
const stream = streamFrom(result);
const frame = stream?.latestFrame;
if (!frame) {
setTiles((previous) => ({
...previous,
- [instanceId]: { ...previous[instanceId], stream },
+ [instance.instanceId]: { ...previous[instance.instanceId], stream },
}));
return;
}
@@ -275,29 +364,59 @@ export function IOSSimulatorInstanceGrid({
);
const image = new Image();
image.onload = () => {
- if (cancelled) {
+ if (cancelled || routeIsInvalidated(instance)) {
URL.revokeObjectURL(url);
return;
}
- const previous = urlsRef.current[instanceId];
+ const previous = urlsRef.current[instance.instanceId];
if (previous) URL.revokeObjectURL(previous);
- urlsRef.current[instanceId] = url;
- setTiles((current) => ({ ...current, [instanceId]: { stream, frameUrl: url } }));
+ urlsRef.current[instance.instanceId] = url;
+ setTiles((current) => ({
+ ...current,
+ [instance.instanceId]: { stream, frameUrl: url },
+ }));
};
image.onerror = () => URL.revokeObjectURL(url);
image.src = url;
};
+ const setVisibility = async (visible: boolean) => {
+ await Promise.all(
+ readyInstances.map(async (instance) => {
+ const route = {
+ sessionId,
+ ...routeFor(instance),
+ visible,
+ preferredEncoding: 'jpeg' as const,
+ };
+ const result = await window.electronAPI.maker.iosSimulator
+ .setViewerVisibility(route)
+ .catch(() => null);
+ if (visible && result) accept(instance, result);
+ if (
+ visible &&
+ !routeIsInvalidated(instance) &&
+ instance.instanceId !== selectedInstanceId
+ ) {
+ await window.electronAPI.maker.iosSimulator
+ .setStreamProfile({ sessionId, ...routeFor(instance), profile: BACKGROUND_PROFILE })
+ .catch(() => undefined);
+ }
+ }),
+ );
+ };
const poll = async () => {
if (!viewerVisible || polling || cancelled) return;
polling = true;
try {
+ requestRouteRefresh();
await Promise.all(
readyInstances.map(async (instance) => {
+ if (routeIsInvalidated(instance)) return;
const result = await window.electronAPI.maker.iosSimulator.latestFrame({
sessionId,
...routeFor(instance),
});
- accept(instance.instanceId, result);
+ accept(instance, result);
}),
);
} finally {
@@ -314,7 +433,7 @@ export function IOSSimulatorInstanceGrid({
for (const url of Object.values(urlsRef.current)) URL.revokeObjectURL(url);
urlsRef.current = {};
};
- }, [readyInstances, selectedInstanceId, sessionId, viewerVisible]);
+ }, [onRefresh, readyInstances, routeIsInvalidated, selectedInstanceId, sessionId, viewerVisible]);
if (readyInstances.length < 2) return null;
@@ -337,7 +456,8 @@ export function IOSSimulatorInstanceGrid({
const agentBusy = Boolean(
mutation?.activeSource === 'agent' || (mutation?.queuedAgentMutations ?? 0) > 0,
);
- const busy = tileBusy[instance.instanceId] === true || agentBusy;
+ const routeInvalidated = invalidatedRouteKeys[instance.instanceId] === routeKey(instance);
+ const busy = tileBusy[instance.instanceId] === true || agentBusy || routeInvalidated;
const error = tileErrors[instance.instanceId];
return (
<article
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx
index cc385c2f19..ecea22a7f2 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx
@@ -1724,6 +1724,7 @@ export function IOSSimulatorTabBody({
count: instances.filter((instance) => instance.lifecycleState === 'ready').length,
})}
onSelect={(instanceId) => ctx.patchState({ instanceId })}
+ onRefresh={refresh}
/>
)}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx
index 554c7caec6..b5352bde85 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx
@@ -197,7 +197,7 @@ function installStatus(statusValue: IOSSimulatorSessionStatus) {
};
},
);
- const latestFrame = vi.fn(async (): Promise<IOSSimulatorToolResponse> => ({
+ const latestFrame = vi.fn(async (_request?: unknown): Promise<IOSSimulatorToolResponse> => ({
ok: true,
data: { stream: null },
}));
@@ -2308,4 +2308,152 @@ describe('IOSSimulatorTabBody', () => {
});
});
});
+
+ it('drops a stale grid route and retries when its refresh is superseded', async () => {
+ const instanceA: IOSSimulatorPublicInstance = {
+ ...readyInstance(1),
+ simulatorName: 'iPhone A',
+ lease: { ...readyInstance(1).lease, id: 'lease-a' },
+ };
+ const instanceB: IOSSimulatorPublicInstance = {
+ ...readyInstance(2),
+ instanceId: 'instance-b',
+ simulatorUdid: 'DEVICE-B',
+ simulatorName: 'iPhone B',
+ lease: { ...readyInstance(2).lease, id: 'lease-b' },
+ };
+ const stoppedB: IOSSimulatorPublicInstance = {
+ ...instanceB,
+ generation: 3,
+ lifecycleState: 'stopped',
+ lease: { ...instanceB.lease, id: 'lease-b-renewed' },
+ stoppedAt: '2026-07-24T00:00:00.000Z',
+ };
+ const readyBaseStatus = readyStatus(instanceA);
+ if (!readyBaseStatus.ok) throw new Error('Expected a ready status fixture.');
+ const initialStatus: IOSSimulatorSessionStatus = {
+ ...readyBaseStatus,
+ instances: [instanceA, instanceB],
+ };
+ const reconciledStatus: IOSSimulatorSessionStatus = {
+ ...initialStatus,
+ instances: [instanceA, stoppedB],
+ };
+ const api = installStatus(initialStatus);
+ let resolveSupersededRefresh: (status: IOSSimulatorSessionStatus) => void = () => undefined;
+ const supersededRefresh = new Promise<IOSSimulatorSessionStatus>((resolve) => {
+ resolveSupersededRefresh = resolve;
+ });
+ api.status
+ .mockResolvedValueOnce(initialStatus)
+ .mockImplementationOnce(async () => supersededRefresh)
+ .mockRejectedValueOnce(new Error('newer status request failed'))
+ .mockResolvedValue(reconciledStatus);
+ let instanceBPolls = 0;
+ api.latestFrame.mockImplementation(async (request?: unknown) => {
+ const route = request as { instanceId?: string } | undefined;
+ if (route?.instanceId !== 'instance-b') {
+ return { ok: true, data: { stream: null } };
+ }
+ instanceBPolls += 1;
+ if (instanceBPolls === 1) {
+ return {
+ ok: true,
+ data: {
+ stream: {
+ instanceId: 'instance-b',
+ generation: 2,
+ state: 'streaming',
+ reconnectAttempt: 0,
+ latestFrame: {
+ instanceId: 'instance-b',
+ generation: 2,
+ sequence: 1,
+ encoding: 'jpeg',
+ receivedAt: '2026-07-24T00:00:00.000Z',
+ bytes: new Uint8Array([1, 2, 3]),
+ },
+ },
+ },
+ };
+ }
+ return {
+ ok: true,
+ data: { instance: stoppedB, stream: null, viewport: null },
+ };
+ });
+
+ render(
+ <IOSSimulatorTabBody state={{ instanceId: 'instance-a' }} ctx={ctx} active shellVisible />,
+ );
+
+ const staleImage = (await screen.findByAltText('iPhone B')) as HTMLImageElement;
+ Object.defineProperties(staleImage, {
+ setPointerCapture: { configurable: true, value: vi.fn() },
+ hasPointerCapture: { configurable: true, value: vi.fn(() => true) },
+ releasePointerCapture: { configurable: true, value: vi.fn() },
+ getBoundingClientRect: {
+ configurable: true,
+ value: () => ({ left: 0, top: 0, width: 200, height: 400 }),
+ },
+ });
+ fireEvent.pointerDown(staleImage, {
+ pointerId: 31,
+ button: 0,
+ clientX: 20,
+ clientY: 40,
+ });
+ await waitFor(() => expect(api.status).toHaveBeenCalledTimes(2), { timeout: 2_000 });
+ await waitFor(() => expect(screen.queryByAltText('iPhone B')).toBeNull());
+ expect(
+ (
+ screen.getByRole('button', {
+ name: 'iPhone B rightSidebar.iosSimulator.pressHome',
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(true);
+ expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:ios-simulator-1');
+ fireEvent.pointerUp(staleImage, {
+ pointerId: 31,
+ clientX: 180,
+ clientY: 360,
+ });
+ expect(api.call).not.toHaveBeenCalled();
+
+ act(() => {
+ api.emitFocusRequest({
+ sessionId: 'session-a',
+ instanceId: 'instance-b',
+ userInitiated: false,
+ });
+ });
+ await waitFor(() => expect(api.status).toHaveBeenCalledTimes(3), { timeout: 2_000 });
+ await act(async () => {
+ resolveSupersededRefresh(reconciledStatus);
+ await Promise.resolve();
+ });
+
+ await waitFor(() => expect(api.status).toHaveBeenCalledTimes(4), { timeout: 2_000 });
+ await waitFor(() => expect(screen.queryByAltText('iPhone B')).toBeNull());
+ await waitFor(() =>
+ expect(
+ screen.queryByRole('button', {
+ name: 'iPhone B rightSidebar.iosSimulator.pressHome',
+ }),
+ ).toBeNull(),
+ );
+
+ const pollsAfterRefresh = api.latestFrame.mock.calls.filter(
+ ([request]) => (request as { instanceId?: string } | undefined)?.instanceId === 'instance-b',
+ ).length;
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 650));
+ });
+ expect(
+ api.latestFrame.mock.calls.filter(
+ ([request]) =>
+ (request as { instanceId?: string } | undefined)?.instanceId === 'instance-b',
+ ),
+ ).toHaveLength(pollsAfterRefresh);
+ });
});
diff --git a/packages/ios-simulator-runtime/src/instance-actor.test.ts b/packages/ios-simulator-runtime/src/instance-actor.test.ts
index f650d1623b..a7abaaea8c 100644
--- a/packages/ios-simulator-runtime/src/instance-actor.test.ts
+++ b/packages/ios-simulator-runtime/src/instance-actor.test.ts
@@ -86,7 +86,10 @@ describe("IOSSimulatorInstanceActor", () => {
bootProvenance: "agent-booted",
generation: 2,
});
- expect(harness.lifecycle.bootExact).toHaveBeenCalledWith(UDID);
+ expect(harness.lifecycle.bootExact).toHaveBeenCalledWith(
+ UDID,
+ expect.any(AbortSignal),
+ );
const stopped = await harness.actor.stop(harness.route(started));
expect(stopped).toMatchObject({ lifecycleState: "stopped", generation: 3 });
@@ -98,59 +101,72 @@ describe("IOSSimulatorInstanceActor", () => {
});
});
- it("keeps admitted teardown authority across generation advance and lease expiry", async () => {
+ it("cancels an in-flight start before an admitted stop waits on the serializer", async () => {
const harness = createHarness();
- let finishBoot: () => void = () => undefined;
+ let bootSignal: AbortSignal | undefined;
vi.mocked(harness.lifecycle.bootExact).mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- finishBoot = () => resolve({ ...DEVICE, state: "Booted" });
+ (_udid, signal) =>
+ new Promise((_resolve, reject) => {
+ bootSignal = signal;
+ signal?.addEventListener("abort", () => reject(signal.reason), {
+ once: true,
+ });
}),
);
const starting = harness.actor.start(harness.route());
await vi.waitFor(() =>
- expect(harness.lifecycle.bootExact).toHaveBeenCalledWith(UDID),
+ expect(harness.lifecycle.bootExact).toHaveBeenCalledWith(
+ UDID,
+ expect.any(AbortSignal),
+ ),
);
const route = harness.route();
const stopping = harness.actor.stop(route);
+ expect(bootSignal?.aborted).toBe(true);
harness.setNow(2_000_000);
route.sessionId = "forged-session";
route.instanceId = "forged-instance";
route.leaseId = "forged-lease";
- finishBoot();
- await expect(starting).resolves.toMatchObject({
- lifecycleState: "ready",
- generation: 2,
+ await expect(starting).rejects.toMatchObject({
+ code: "MUTATION_CANCELLED",
});
await expect(stopping).resolves.toMatchObject({
lifecycleState: "stopped",
- generation: 3,
+ generation: 2,
});
expect(harness.lifecycle.shutdownExact).toHaveBeenCalledWith(UDID);
});
- it("preserves detach grace when it takes over an in-flight start", async () => {
+ it("cancels an in-flight start while preserving Host-owned detach grace", async () => {
const harness = createHarness();
- let finishBoot: () => void = () => undefined;
+ let bootSignal: AbortSignal | undefined;
vi.mocked(harness.lifecycle.bootExact).mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- finishBoot = () => resolve({ ...DEVICE, state: "Booted" });
+ (_udid, signal) =>
+ new Promise((_resolve, reject) => {
+ bootSignal = signal;
+ signal?.addEventListener("abort", () => reject(signal.reason), {
+ once: true,
+ });
}),
);
const starting = harness.actor.start(harness.route());
await vi.waitFor(() =>
- expect(harness.lifecycle.bootExact).toHaveBeenCalledWith(UDID),
+ expect(harness.lifecycle.bootExact).toHaveBeenCalledWith(
+ UDID,
+ expect.any(AbortSignal),
+ ),
);
const detaching = harness.actor.detach(harness.route());
- finishBoot();
+ expect(bootSignal?.aborted).toBe(true);
- await expect(starting).resolves.toMatchObject({ generation: 2 });
+ await expect(starting).rejects.toMatchObject({
+ code: "MUTATION_CANCELLED",
+ });
await expect(detaching).resolves.toMatchObject({
- generation: 2,
+ generation: 1,
viewerState: "detached",
bootProvenance: "agent-booted",
});
@@ -158,6 +174,46 @@ describe("IOSSimulatorInstanceActor", () => {
expect(harness.lifecycle.shutdownExact).not.toHaveBeenCalled();
});
+ it("cancels startup by owning session and through the force-exit seam", async () => {
+ const harness = createHarness();
+ let bootSignal: AbortSignal | undefined;
+ vi.mocked(harness.lifecycle.bootExact).mockImplementation(
+ (_udid, signal) =>
+ new Promise((_resolve, reject) => {
+ bootSignal = signal;
+ signal?.addEventListener("abort", () => reject(signal.reason), {
+ once: true,
+ });
+ }),
+ );
+
+ const starting = harness.actor.start(harness.route());
+ await vi.waitFor(() => expect(bootSignal).toBeDefined());
+ await harness.actor.cancelLifecycleStartsForSession("another-session");
+ expect(bootSignal?.aborted).toBe(false);
+
+ const sessionCancellation =
+ harness.actor.cancelLifecycleStartsForSession("session-a");
+ expect(bootSignal?.aborted).toBe(true);
+ await sessionCancellation;
+ await expect(starting).rejects.toMatchObject({
+ code: "MUTATION_CANCELLED",
+ });
+
+ bootSignal = undefined;
+ const recovering = harness.actor.recover(harness.route());
+ await vi.waitFor(() =>
+ expect(harness.lifecycle.bootExact).toHaveBeenCalledTimes(2),
+ );
+ const recoverySignal = vi.mocked(harness.lifecycle.bootExact).mock
+ .calls[1]?.[1];
+ expect(() => harness.actor.abortOperationsForExit()).not.toThrow();
+ expect(recoverySignal?.aborted).toBe(true);
+ await expect(recovering).rejects.toMatchObject({
+ code: "MUTATION_CANCELLED",
+ });
+ });
+
it("does not let an admitted teardown cross a replacement lease", async () => {
const harness = createHarness({ booted: true });
const route = harness.route();
@@ -181,7 +237,10 @@ describe("IOSSimulatorInstanceActor", () => {
bootProvenance: "agent-booted",
generation: harness.instance.generation + 1,
});
- expect(harness.lifecycle.bootExact).toHaveBeenCalledWith(UDID);
+ expect(harness.lifecycle.bootExact).toHaveBeenCalledWith(
+ UDID,
+ expect.any(AbortSignal),
+ );
await expect(harness.actor.recover(harness.route())).rejects.toMatchObject({
code: "STALE_GENERATION",
});
diff --git a/packages/ios-simulator-runtime/src/instance-actor.ts b/packages/ios-simulator-runtime/src/instance-actor.ts
index b3161d2431..d61c6f9188 100644
--- a/packages/ios-simulator-runtime/src/instance-actor.ts
+++ b/packages/ios-simulator-runtime/src/instance-actor.ts
@@ -57,6 +57,12 @@ interface MutableMutationState {
takeoverEpoch: number;
}
+interface ActiveLifecycleStart {
+ sessionId: string;
+ controller: AbortController;
+ settled: Promise<void>;
+}
+
const DEFAULT_DETACH_GRACE_MS = 10 * 60_000;
function defaultScheduler(): IOSSimulatorScheduler {
@@ -80,6 +86,10 @@ export class IOSSimulatorInstanceActor {
readonly #cancelGrace = new Map<string, () => void>();
readonly #mutationStates = new Map<string, MutableMutationState>();
readonly #activeAgentMutations = new Map<string, AbortController>();
+ readonly #activeLifecycleStarts = new Map<
+ string,
+ Set<ActiveLifecycleStart>
+ >();
constructor(options: IOSSimulatorInstanceActorOptions) {
this.#store = options.store;
@@ -196,7 +206,9 @@ export class IOSSimulatorInstanceActor {
/** Remove a persisted binding after orphan policy has decided its fate. */
forget(instanceId: string, sessionId: string): IOSSimulatorInstance {
+ this.#store.requireOwned(instanceId, sessionId);
this.#cancelActiveAgentMutation(instanceId);
+ this.#abortLifecycleStartsForInstance(instanceId);
return this.#store.release(instanceId, sessionId);
}
@@ -208,8 +220,9 @@ export class IOSSimulatorInstanceActor {
healthState: IOSSimulatorInstance["healthState"],
errorCode: string | null,
): IOSSimulatorInstance {
- this.#cancelActiveAgentMutation(instanceId);
const current = this.#store.requireOwned(instanceId, sessionId);
+ this.#cancelActiveAgentMutation(instanceId);
+ this.#abortLifecycleStartsForInstance(instanceId);
const renewed = this.#store.renew(instanceId, sessionId);
return this.#store.update(instanceId, sessionId, {
generation: current.generation + 1,
@@ -266,6 +279,7 @@ export class IOSSimulatorInstanceActor {
// serialized and will revalidate their now-stale route afterwards.
this.#mutationState(input.instanceId).takeoverEpoch += 1;
this.#cancelActiveAgentMutation(input.instanceId);
+ this.#abortLifecycleStartsForInstance(input.instanceId);
this.#cancelGrace.get(input.instanceId)?.();
this.#cancelGrace.delete(input.instanceId);
@@ -473,6 +487,7 @@ export class IOSSimulatorInstanceActor {
const state = this.#mutationState(instanceId);
state.takeoverEpoch += 1;
this.#cancelActiveAgentMutation(instanceId);
+ this.#abortLifecycleStartsForInstance(instanceId);
this.#cancelGrace.get(instanceId)?.();
this.#cancelGrace.delete(instanceId);
return this.#serialize(instanceId, async () => {
@@ -485,6 +500,120 @@ export class IOSSimulatorInstanceActor {
this.#activeAgentMutations.get(instanceId)?.abort();
}
+ #lifecycleStartCancelledError(): IOSSimulatorInstanceError {
+ return new IOSSimulatorInstanceError(
+ "MUTATION_CANCELLED",
+ "Simulator startup was cancelled because its lifecycle changed.",
+ true,
+ );
+ }
+
+ #throwIfLifecycleStartCancelled(signal: AbortSignal): void {
+ if (!signal.aborted) return;
+ throw signal.reason instanceof Error
+ ? signal.reason
+ : this.#lifecycleStartCancelledError();
+ }
+
+ #abortLifecycleStarts(records: readonly ActiveLifecycleStart[]): void {
+ for (const record of records) {
+ if (!record.controller.signal.aborted) {
+ record.controller.abort(this.#lifecycleStartCancelledError());
+ }
+ }
+ }
+
+ #activeLifecycleStartsForInstance(
+ instanceId: string,
+ ): ActiveLifecycleStart[] {
+ return [...(this.#activeLifecycleStarts.get(instanceId) ?? [])];
+ }
+
+ #abortLifecycleStartsForInstance(instanceId: string): void {
+ this.#abortLifecycleStarts(
+ this.#activeLifecycleStartsForInstance(instanceId),
+ );
+ }
+
+ #runLifecycleStart(
+ route: IOSSimulatorMutationRoute,
+ task: (signal: AbortSignal) => Promise<IOSSimulatorInstance>,
+ ): Promise<IOSSimulatorInstance> {
+ try {
+ // Register before the serializer yields so teardown admission can abort
+ // both an active boot and a boot queued behind another mutation.
+ this.#store.assertMutationRoute(route);
+ } catch (error) {
+ return Promise.reject(error);
+ }
+ const record: ActiveLifecycleStart = {
+ sessionId: route.sessionId,
+ controller: new AbortController(),
+ settled: Promise.resolve(),
+ };
+ let records = this.#activeLifecycleStarts.get(route.instanceId);
+ if (!records) {
+ records = new Set();
+ this.#activeLifecycleStarts.set(route.instanceId, records);
+ }
+ records.add(record);
+ const operation = this.#serialize(route.instanceId, () =>
+ task(record.controller.signal),
+ );
+ record.settled = operation
+ .then(
+ () => undefined,
+ () => undefined,
+ )
+ .finally(() => {
+ records?.delete(record);
+ if (records?.size === 0) {
+ this.#activeLifecycleStarts.delete(route.instanceId);
+ }
+ });
+ return operation;
+ }
+
+ /** Abort one instance's queued/active CoreSimulator starts and await settlement. */
+ cancelLifecycleStartsForInstance(instanceId: string): Promise<void> {
+ const records = this.#activeLifecycleStartsForInstance(instanceId);
+ this.#abortLifecycleStarts(records);
+ return Promise.all(records.map((record) => record.settled)).then(
+ () => undefined,
+ );
+ }
+
+ /** Abort starts owned by a removed Cindy task before its Host barrier drains. */
+ cancelLifecycleStartsForSession(sessionId: string): Promise<void> {
+ const records = [...this.#activeLifecycleStarts.values()]
+ .flatMap((entries) => [...entries])
+ .filter((record) => record.sessionId === sessionId);
+ this.#abortLifecycleStarts(records);
+ return Promise.all(records.map((record) => record.settled)).then(
+ () => undefined,
+ );
+ }
+
+ /** Abort every CoreSimulator start while Desktop shutdown still has a budget. */
+ cancelAllLifecycleStarts(): Promise<void> {
+ const records = [...this.#activeLifecycleStarts.values()].flatMap(
+ (entries) => [...entries],
+ );
+ this.#abortLifecycleStarts(records);
+ return Promise.all(records.map((record) => record.settled)).then(
+ () => undefined,
+ );
+ }
+
+ /** Synchronous force-quit seam; async disposal separately awaits settlement. */
+ abortOperationsForExit(): void {
+ this.#abortLifecycleStarts(
+ [...this.#activeLifecycleStarts.values()].flatMap((entries) => [
+ ...entries,
+ ]),
+ );
+ }
+
#mutationState(instanceId: string): MutableMutationState {
let state = this.#mutationStates.get(instanceId);
if (!state) {
@@ -518,11 +647,28 @@ export class IOSSimulatorInstanceActor {
}
start(route: IOSSimulatorMutationRoute): Promise<IOSSimulatorInstance> {
- return this.#serialize(route.instanceId, async () => {
- const instance = this.#store.assertMutationRoute(route);
- if (instance.lifecycleState === "ready") {
- return this.#store.renew(instance.instanceId, instance.sessionId);
+ try {
+ if (this.#store.assertMutationRoute(route).lifecycleState === "ready") {
+ // A ready start only renews its lease; it owns no CoreSimulator process
+ // and must not be cancelled by the startup teardown seam.
+ return this.#serialize(route.instanceId, async () => {
+ const instance = this.#store.assertMutationRoute(route);
+ if (instance.lifecycleState !== "ready") {
+ throw new IOSSimulatorInstanceError(
+ "INVALID_INSTANCE_STATE",
+ "The simulator can no longer renew from its current state.",
+ true,
+ );
+ }
+ return this.#store.renew(instance.instanceId, instance.sessionId);
+ });
}
+ } catch (error) {
+ return Promise.reject(error);
+ }
+ return this.#runLifecycleStart(route, async (signal) => {
+ const instance = this.#store.assertMutationRoute(route);
+ this.#throwIfLifecycleStartCancelled(signal);
if (
instance.lifecycleState !== "stopped" &&
instance.lifecycleState !== "error"
@@ -537,9 +683,13 @@ export class IOSSimulatorInstanceActor {
lifecycleState: "booting",
healthState: "recovering",
errorCode: null,
+ // The Host owns the boot as soon as it issues the CoreSimulator
+ // mutation, even if readiness is later cancelled during bootstatus.
+ bootProvenance: "agent-booted",
});
try {
- await this.#lifecycle.bootExact(instance.simulatorUdid);
+ await this.#lifecycle.bootExact(instance.simulatorUdid, signal);
+ this.#throwIfLifecycleStartCancelled(signal);
const now = new Date(this.#clock.now()).toISOString();
return this.#store.update(instance.instanceId, instance.sessionId, {
lifecycleState: "ready",
@@ -566,8 +716,9 @@ export class IOSSimulatorInstanceActor {
/** Reboot a persisted ready binding after CoreSimulator was lost externally. */
recover(route: IOSSimulatorMutationRoute): Promise<IOSSimulatorInstance> {
- return this.#serialize(route.instanceId, async () => {
+ return this.#runLifecycleStart(route, async (signal) => {
const instance = this.#store.assertMutationRoute(route);
+ this.#throwIfLifecycleStartCancelled(signal);
if (
instance.lifecycleState !== "ready" &&
instance.lifecycleState !== "error" &&
@@ -583,9 +734,11 @@ export class IOSSimulatorInstanceActor {
lifecycleState: "booting",
healthState: "recovering",
errorCode: null,
+ bootProvenance: "agent-booted",
});
try {
- await this.#lifecycle.bootExact(instance.simulatorUdid);
+ await this.#lifecycle.bootExact(instance.simulatorUdid, signal);
+ this.#throwIfLifecycleStartCancelled(signal);
const now = new Date(this.#clock.now()).toISOString();
return this.#store.update(instance.instanceId, instance.sessionId, {
lifecycleState: "ready",
@@ -624,6 +777,7 @@ export class IOSSimulatorInstanceActor {
} catch (error) {
return Promise.reject(error);
}
+ this.#abortLifecycleStartsForInstance(admission.instanceId);
return this.#serialize(admission.instanceId, async () => {
const instance = this.#requireAdmittedLifecycleRoute(admission);
if (instance.lifecycleState === "stopped") return instance;
@@ -674,6 +828,7 @@ export class IOSSimulatorInstanceActor {
} catch (error) {
return Promise.reject(error);
}
+ this.#abortLifecycleStartsForInstance(admission.instanceId);
return this.#serialize(admission.instanceId, async () => {
const instance = this.#requireAdmittedLifecycleRoute(admission);
this.#cancelGrace.get(instance.instanceId)?.();
diff --git a/packages/ios-simulator-runtime/src/simctl-lifecycle.test.ts b/packages/ios-simulator-runtime/src/simctl-lifecycle.test.ts
index 3f3183228b..07006bc86a 100644
--- a/packages/ios-simulator-runtime/src/simctl-lifecycle.test.ts
+++ b/packages/ios-simulator-runtime/src/simctl-lifecycle.test.ts
@@ -126,6 +126,54 @@ describe("createIOSSimulatorSimctlLifecycle", () => {
]);
});
+ it("propagates startup cancellation into every simctl subprocess", async () => {
+ const controller = new AbortController();
+ let listCount = 0;
+ let bootStatusSignal: AbortSignal | undefined;
+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(
+ async (_command, args, options) => {
+ if (args[1] === "list") {
+ listCount += 1;
+ return {
+ stdout: listJson(listCount === 1 ? "Shutdown" : "Booted"),
+ stderr: "",
+ exitCode: 0,
+ };
+ }
+ if (args[1] === "boot") {
+ return { stdout: "", stderr: "", exitCode: 0 };
+ }
+ if (args[1] === "bootstatus") {
+ bootStatusSignal = options?.signal;
+ return await new Promise((resolve) => {
+ options?.signal?.addEventListener(
+ "abort",
+ () => resolve({ stdout: "", stderr: "", exitCode: null }),
+ { once: true },
+ );
+ });
+ }
+ throw new Error(`unexpected ${args.join(" ")}`);
+ },
+ );
+ const lifecycle = createIOSSimulatorSimctlLifecycle({
+ commandRunner: { run },
+ clock: {
+ now: () => 0,
+ sleep: async () => undefined,
+ },
+ });
+
+ const booting = lifecycle.bootExact(UDID, controller.signal);
+ await vi.waitFor(() => expect(bootStatusSignal).toBe(controller.signal));
+ controller.abort(new Error("cancelled for teardown"));
+
+ await expect(booting).rejects.toThrow("cancelled for teardown");
+ for (const [, , options] of run.mock.calls) {
+ expect(options?.signal).toBe(controller.signal);
+ }
+ });
+
it("uses exact argv for create, shutdown, and delete", async () => {
const run = vi.fn<IOSSimulatorCommandRunner["run"]>(
async (_command, args) => {
diff --git a/packages/ios-simulator-runtime/src/simctl-lifecycle.ts b/packages/ios-simulator-runtime/src/simctl-lifecycle.ts
index 09c299249b..4ce6532ce9 100644
--- a/packages/ios-simulator-runtime/src/simctl-lifecycle.ts
+++ b/packages/ios-simulator-runtime/src/simctl-lifecycle.ts
@@ -390,6 +390,17 @@ function defaultClock(): IOSSimulatorLifecycleClock {
};
}
+function throwIfAborted(signal?: AbortSignal): void {
+ if (!signal?.aborted) return;
+ throw signal.reason instanceof Error
+ ? signal.reason
+ : new IOSSimulatorInstanceError(
+ "MUTATION_CANCELLED",
+ "Simulator startup was cancelled because its lifecycle changed.",
+ true,
+ );
+}
+
/** Exact-UDID, argv-only CoreSimulator lifecycle adapter. */
export function createIOSSimulatorSimctlLifecycle(
options: IOSSimulatorSimctlLifecycleOptions = {},
@@ -405,8 +416,12 @@ export function createIOSSimulatorSimctlLifecycle(
);
}
- async function list(): Promise<IOSSimulatorDevice[]> {
- const result = await runner.run(XCRUN, ["simctl", "list", "-j"]);
+ async function list(signal?: AbortSignal): Promise<IOSSimulatorDevice[]> {
+ throwIfAborted(signal);
+ const result = signal
+ ? await runner.run(XCRUN, ["simctl", "list", "-j"], { signal })
+ : await runner.run(XCRUN, ["simctl", "list", "-j"]);
+ throwIfAborted(signal);
if (result.exitCode !== 0) {
throw new IOSSimulatorInstanceError(
"SIMULATOR_NOT_FOUND",
@@ -417,10 +432,13 @@ export function createIOSSimulatorSimctlLifecycle(
return parseSimctlListJson(result.stdout).devices;
}
- async function findExact(udid: string): Promise<IOSSimulatorDevice | null> {
+ async function findExact(
+ udid: string,
+ signal?: AbortSignal,
+ ): Promise<IOSSimulatorDevice | null> {
const normalized = requireUdid(udid);
return (
- (await list()).find(
+ (await list(signal)).find(
(device) => device.udid.toUpperCase() === normalized,
) ?? null
);
@@ -431,7 +449,8 @@ export function createIOSSimulatorSimctlLifecycle(
async bootExact(udid, signal): Promise<IOSSimulatorDevice> {
const normalized = requireUdid(udid);
- const before = await findExact(normalized);
+ throwIfAborted(signal);
+ const before = await findExact(normalized, signal);
if (!before) {
throw new IOSSimulatorInstanceError(
"SIMULATOR_NOT_FOUND",
@@ -441,7 +460,13 @@ export function createIOSSimulatorSimctlLifecycle(
if (before.state.toLowerCase() !== "booted") {
let bootedOrStarting = false;
for (let attempt = 0; attempt < 2; attempt += 1) {
- const boot = await runner.run(XCRUN, ["simctl", "boot", normalized]);
+ throwIfAborted(signal);
+ const boot = signal
+ ? await runner.run(XCRUN, ["simctl", "boot", normalized], {
+ signal,
+ })
+ : await runner.run(XCRUN, ["simctl", "boot", normalized]);
+ throwIfAborted(signal);
if (boot.exitCode === 0) {
bootedOrStarting = true;
break;
@@ -451,13 +476,16 @@ export function createIOSSimulatorSimctlLifecycle(
// transition is already in flight. Confirm the state before treating
// the failure as terminal, then allow one short retry for a genuine
// transient service race.
- const afterFailure = await findExact(normalized);
+ const afterFailure = await findExact(normalized, signal);
const state = afterFailure?.state.toLowerCase();
if (state === "booted" || state === "booting") {
bootedOrStarting = true;
break;
}
- if (attempt === 0) await clock.sleep(500, signal);
+ if (attempt === 0) {
+ await clock.sleep(500, signal);
+ throwIfAborted(signal);
+ }
}
if (!bootedOrStarting) {
throw new IOSSimulatorInstanceError(
@@ -470,8 +498,8 @@ export function createIOSSimulatorSimctlLifecycle(
const deadline = clock.now() + bootTimeoutMs;
while (clock.now() < deadline) {
- if (signal?.aborted) throw signal.reason;
- const device = await findExact(normalized);
+ throwIfAborted(signal);
+ const device = await findExact(normalized, signal);
if (!device) {
throw new IOSSimulatorInstanceError(
"SIMULATOR_NOT_FOUND",
@@ -487,14 +515,18 @@ export function createIOSSimulatorSimctlLifecycle(
const ready = await runner.run(
XCRUN,
["simctl", "bootstatus", normalized, "-b"],
- { timeoutMs: remaining },
+ signal
+ ? { timeoutMs: remaining, signal }
+ : { timeoutMs: remaining },
);
+ throwIfAborted(signal);
if (ready.exitCode === 0) return device;
}
await clock.sleep(
Math.min(pollIntervalMs, deadline - clock.now()),
signal,
);
+ throwIfAborted(signal);
}
throw new IOSSimulatorInstanceError(
"SIMULATOR_BOOT_TIMEOUT",