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 app lifecycle on teardown

JiangJiahaoe4d933ce653f
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 38b4f3cf18..528edbced8 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
@@ -1653,9 +1653,31 @@ describe('iOS Simulator host', () => {
getSession: vi.fn(async () => localSession('dispose-session')),
});
+ let mutationSignal: AbortSignal | undefined;
+ const activeMutation = actor
+ .runMutation(
+ {
+ sessionId: instance.sessionId,
+ instanceId: instance.instanceId,
+ generation: instance.generation,
+ leaseId: instance.lease.id,
+ },
+ async (_current, signal) => {
+ mutationSignal = signal;
+ await new Promise<void>((resolve) => {
+ signal.addEventListener('abort', () => resolve(), { once: true });
+ });
+ },
+ 'user',
+ )
+ .catch((error: unknown) => error);
+ await vi.waitFor(() => expect(mutationSignal).toBeDefined());
+
await host.dispose();
await host.dispose();
+ expect(mutationSignal?.aborted).toBe(true);
+ await expect(activeMutation).resolves.toMatchObject({ code: 'MUTATION_CANCELLED' });
expect(discardInstance).toHaveBeenCalledTimes(1);
expect(discardInstance).toHaveBeenCalledWith(instance.instanceId);
expect(stopDriver).toHaveBeenCalledTimes(1);
@@ -1930,9 +1952,30 @@ describe('iOS Simulator host', () => {
);
await vi.waitFor(() => expect(build).toHaveBeenCalledOnce());
+ let mutationSignal: AbortSignal | undefined;
+ const activeMutation = actor
+ .runMutation(
+ {
+ sessionId: current.sessionId,
+ instanceId: current.instanceId,
+ generation: current.generation,
+ leaseId: current.lease.id,
+ },
+ async (_instance, signal) => {
+ mutationSignal = signal;
+ await new Promise<void>((resolve) => {
+ signal.addEventListener('abort', () => resolve(), { once: true });
+ });
+ },
+ 'user',
+ )
+ .catch((error: unknown) => error);
+ await vi.waitFor(() => expect(mutationSignal).toBeDefined());
+
expect(() => host.abortOperationsForExit()).not.toThrow();
expect(buildSignal?.aborted).toBe(true);
+ expect(mutationSignal?.aborted).toBe(true);
expect(abortLifecycleStarts).toHaveBeenCalledOnce();
expect(abortRecording).toHaveBeenCalledOnce();
expect(abortDriver).toHaveBeenCalledOnce();
@@ -1940,6 +1983,7 @@ describe('iOS Simulator host', () => {
ok: false,
errorCode: 'MUTATION_CANCELLED',
});
+ await expect(activeMutation).resolves.toMatchObject({ code: 'MUTATION_CANCELLED' });
await host.dispose();
});
@@ -4865,6 +4909,61 @@ describe('iOS Simulator host', () => {
await host.dispose();
});
+ it('aborts and drains an active simulator mutation before task cancellation returns', async () => {
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(async () => undefined),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore(),
+ lifecycle,
+ });
+ const instance = actor.attach({
+ sessionId: 'session-a',
+ worktreeRoot: '/tmp/session-a',
+ sourceFingerprint: 'fingerprint-a',
+ device: READY_REPORT.devices[0]!,
+ bootProvenance: 'preexisting',
+ });
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ mediaCapture: {
+ discardSession: vi.fn(async () => undefined),
+ discardInstance: vi.fn(async () => undefined),
+ } as unknown as IOSSimulatorMediaCaptureAdapter,
+ });
+ let mutationSignal: AbortSignal | undefined;
+ const active = actor
+ .runMutation(
+ {
+ sessionId: instance.sessionId,
+ instanceId: instance.instanceId,
+ generation: instance.generation,
+ leaseId: instance.lease.id,
+ },
+ async (_current, signal) => {
+ mutationSignal = signal;
+ await new Promise<void>((resolve) => {
+ signal.addEventListener('abort', () => resolve(), { once: true });
+ });
+ },
+ 'user',
+ )
+ .catch((error: unknown) => error);
+ await vi.waitFor(() => expect(mutationSignal).toBeDefined());
+
+ await expect(host.cancelSessionOperations('session-a')).resolves.toBeUndefined();
+ expect(mutationSignal?.aborted).toBe(true);
+ await expect(active).resolves.toMatchObject({ code: 'MUTATION_CANCELLED' });
+ await host.dispose();
+ });
+
it('does not block task removal when recording cleanup fails', async () => {
const lifecycle: IOSSimulatorSimctlLifecycle = {
findExact: vi.fn(),
@@ -4951,6 +5050,7 @@ describe('iOS Simulator host', () => {
recordingId: 'late-recording',
startedAt: new Date().toISOString(),
}));
+ const openUrlExact = vi.fn(async () => undefined);
const host = createIOSSimulatorHost({
actor,
lifecycle,
@@ -4966,6 +5066,13 @@ describe('iOS Simulator host', () => {
startRecording,
discardInstance,
} as unknown as IOSSimulatorMediaCaptureAdapter,
+ appLifecycle: {
+ inspectArtifact: vi.fn(),
+ installExact: vi.fn(),
+ launchExact: vi.fn(),
+ terminateExact: vi.fn(),
+ openUrlExact,
+ },
});
await host.reconcileOwnership();
@@ -5005,6 +5112,14 @@ describe('iOS Simulator host', () => {
origin: 'user',
});
await discardStarted;
+ await expect(
+ host.callTool(
+ 'open_url',
+ { ...route, url: 'demo://teardown-race' },
+ { sessionId: 'session-a', origin: 'user' },
+ ),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'MUTATION_CANCELLED' });
+ expect(openUrlExact).not.toHaveBeenCalled();
releaseActive();
await expect(screenshot).resolves.toMatchObject({
@@ -5020,7 +5135,7 @@ describe('iOS Simulator host', () => {
releaseDiscard();
await expect(stopping).resolves.toMatchObject({ ok: true });
- await expect(active).resolves.toBeUndefined();
+ await expect(active).rejects.toMatchObject({ code: 'MUTATION_CANCELLED' });
await host.dispose();
});
@@ -6045,9 +6160,12 @@ describe('iOS Simulator host', () => {
const inspectArtifact = vi.fn<IOSSimulatorAppLifecycleAdapter['inspectArtifact']>(
async () => artifact,
);
+ const installExact = vi.fn<IOSSimulatorAppLifecycleAdapter['installExact']>(
+ async () => undefined,
+ );
const appLifecycle: IOSSimulatorAppLifecycleAdapter = {
inspectArtifact,
- installExact: vi.fn(async () => undefined),
+ installExact,
launchExact: vi.fn(async () => undefined),
terminateExact: vi.fn(async () => undefined),
openUrlExact: vi.fn(async () => undefined),
@@ -6175,6 +6293,7 @@ describe('iOS Simulator host', () => {
expect(validateLaunch).toHaveBeenCalledWith(
'/tmp/session-a',
READY_REPORT.devices[0]!.udid,
+ expect.any(AbortSignal),
);
await host.callTool(
'terminate_app',
@@ -6199,19 +6318,53 @@ describe('iOS Simulator host', () => {
containerPath: 'ios/Demo.xcodeproj',
}),
);
- expect(appLifecycle.installExact).toHaveBeenCalledWith(READY_REPORT.devices[0]!.udid, artifact);
- expect(appLifecycle.launchExact).toHaveBeenCalledWith(READY_REPORT.devices[0]!.udid, artifact, [
- '--uitesting',
- ]);
+ expect(appLifecycle.installExact).toHaveBeenCalledWith(
+ READY_REPORT.devices[0]!.udid,
+ artifact,
+ expect.any(AbortSignal),
+ );
+ expect(appLifecycle.launchExact).toHaveBeenCalledWith(
+ READY_REPORT.devices[0]!.udid,
+ artifact,
+ ['--uitesting'],
+ expect.any(AbortSignal),
+ );
expect(appLifecycle.terminateExact).toHaveBeenCalledWith(
READY_REPORT.devices[0]!.udid,
artifact.bundleId,
+ expect.any(AbortSignal),
);
expect(appLifecycle.openUrlExact).toHaveBeenCalledWith(
READY_REPORT.devices[0]!.udid,
'demo://home',
+ expect.any(AbortSignal),
);
expect(requestViewerFocus).toHaveBeenCalledWith('session-a', instance.instanceId);
+
+ let installSignal: AbortSignal | undefined;
+ installExact.mockImplementationOnce(
+ async (_simulatorUdid, _artifact, signal) =>
+ new Promise<void>((resolve) => {
+ installSignal = signal;
+ signal?.addEventListener('abort', () => resolve(), { once: true });
+ }),
+ );
+ const installing = host.callTool(
+ 'install_app',
+ { ...route, artifactId: artifact.artifactId },
+ { sessionId: 'session-a', origin: 'user' },
+ );
+ await vi.waitFor(() => expect(installSignal).toBeDefined());
+ const stopping = host.callTool('stop_instance', route, {
+ sessionId: 'session-a',
+ origin: 'user',
+ });
+ await vi.waitFor(() => expect(installSignal?.aborted).toBe(true));
+ await expect(installing).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'MUTATION_CANCELLED',
+ });
+ await expect(stopping).resolves.toMatchObject({ ok: true });
});
it('returns readable diagnostics when build_app fails', async () => {
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
index 4f8f60bfbe..9e95ac0315 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
@@ -941,7 +941,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
function assertSessionOperationAdmission(
sessionId: string,
expectedEpoch: number,
- operation: 'app build' | 'screenshot' | 'screen recording',
+ operation: 'app build' | 'screenshot' | 'screen recording' | 'simulator operation',
): void {
if ((sessionOperationAdmissionEpochs.get(sessionId) ?? 0) === expectedEpoch) return;
throw new IOSSimulatorInstanceError(
@@ -1075,7 +1075,9 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
}
function beginInstanceTeardown(instanceId: string): void {
// Abort CoreSimulator startup at teardown admission, before media or WDA
- // cleanup can spend the remaining lifecycle budget.
+ // cleanup can spend the remaining lifecycle budget. App lifecycle calls
+ // use the same mutation signal, so a slow simctl install is terminated too.
+ actor.abortMutationsForInstance(instanceId);
void actor.cancelLifecycleStartsForInstance(instanceId);
const current = lifecycleBarrier(instanceId);
instanceLifecycleBarriers.set(instanceId, {
@@ -1842,7 +1844,11 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
// 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([
+ lifecycleStarts,
+ actor.cancelMutationsForSession(sessionId),
+ cancelSessionBuildsAndRecordings(sessionId),
+ ]);
await Promise.all(
[...(activeSessionRemovalBarrierOperations.get(sessionId) ?? [])].map(
(operation) => operation.settled,
@@ -2913,11 +2919,36 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
task: (instance: IOSSimulatorInstance, signal: AbortSignal) => Promise<T>,
): Promise<T> {
assertHostActive();
+ const sessionAdmissionEpoch = sessionOperationAdmissionEpochs.get(route.sessionId) ?? 0;
+ const instanceAdmissionEpoch = captureInstanceOperationAdmission(
+ route.instanceId,
+ 'operation',
+ );
return actor.runMutation(
route,
async (instance, signal) => {
assertHostActive();
+ assertSessionOperationAdmission(
+ instance.sessionId,
+ sessionAdmissionEpoch,
+ 'simulator operation',
+ );
+ assertInstanceOperationAdmission(
+ instance.instanceId,
+ instanceAdmissionEpoch,
+ 'operation',
+ );
const result = await task(instance, signal);
+ assertSessionOperationAdmission(
+ instance.sessionId,
+ sessionAdmissionEpoch,
+ 'simulator operation',
+ );
+ assertInstanceOperationAdmission(
+ instance.instanceId,
+ instanceAdmissionEpoch,
+ 'operation',
+ );
assertHostActive();
return result;
},
@@ -5081,7 +5112,12 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
let artifact: IOSSimulatorAppArtifact;
try {
try {
- artifact = await appLifecycle.inspectArtifact(instance.worktreeRoot, built.appPath);
+ artifact = await appLifecycle.inspectArtifact(
+ instance.worktreeRoot,
+ built.appPath,
+ undefined,
+ activeBuild.controller.signal,
+ );
} catch (error) {
if (
!(error instanceof IOSSimulatorInstanceError) ||
@@ -5093,6 +5129,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
instance.worktreeRoot,
built.appPath,
derivedDataPath,
+ activeBuild.controller.signal,
);
}
} catch (error) {
@@ -5208,11 +5245,12 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
if (name === 'install_app') {
const route = readMutationRoute(sessionId, args);
const artifactId = readString(args, 'artifactId');
- await runHostMutation(route, context, async (instance) => {
+ await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
await appLifecycle.installExact(
instance.simulatorUdid,
requireArtifact(instance, artifactId),
+ signal,
);
});
return { ok: true, data: { artifactId, installed: true } };
@@ -5224,19 +5262,21 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
if (!Array.isArray(launchArgs) || launchArgs.some((value) => typeof value !== 'string')) {
throw new IOSSimulatorInstanceError('INVALID_ARGUMENT', 'args must be a string array');
}
- await runHostMutation(route, context, async (instance) => {
+ await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
const stored = appArtifacts.get(artifactId);
if (stored?.projectKind === 'cindy-mobile' && projectBuilder.validateLaunch) {
await projectBuilder.validateLaunch(
stored.artifact.worktreeRoot,
instance.simulatorUdid,
+ signal,
);
}
await appLifecycle.launchExact(
instance.simulatorUdid,
requireArtifact(instance, artifactId),
launchArgs,
+ signal,
);
screenMaps.invalidate(instance.instanceId);
});
@@ -5246,19 +5286,23 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
if (name === 'terminate_app') {
const route = readMutationRoute(sessionId, args);
const artifactId = readString(args, 'artifactId');
- await runHostMutation(route, context, async (instance) => {
+ await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
const artifact = requireArtifact(instance, artifactId);
- await appLifecycle.terminateExact(instance.simulatorUdid, artifact.bundleId);
+ await appLifecycle.terminateExact(instance.simulatorUdid, artifact.bundleId, signal);
screenMaps.invalidate(instance.instanceId);
});
return { ok: true, data: { artifactId, terminated: true } };
}
if (name === 'open_url') {
const route = readMutationRoute(sessionId, args);
- await runHostMutation(route, context, async (instance) => {
+ await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
- await appLifecycle.openUrlExact(instance.simulatorUdid, readString(args, 'url'));
+ await appLifecycle.openUrlExact(
+ instance.simulatorUdid,
+ readString(args, 'url'),
+ signal,
+ );
screenMaps.invalidate(instance.instanceId);
});
return { ok: true, data: { opened: true } };
@@ -5675,7 +5719,11 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
}
},
cancelSessionOperations(sessionId) {
- return cancelSessionBuildsAndRecordings(sessionId.trim());
+ const normalizedSessionId = sessionId.trim();
+ return Promise.all([
+ actor.cancelMutationsForSession(normalizedSessionId),
+ cancelSessionBuildsAndRecordings(normalizedSessionId),
+ ]).then(() => undefined);
},
cleanupRemovedSession(sessionId) {
return cleanupRemovedSessionRuntime(sessionId);
@@ -5684,7 +5732,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
try {
actor.abortOperationsForExit();
} catch (error) {
- logger.warn('iOS Simulator exit cleanup could not abort simulator startup', {
+ logger.warn('iOS Simulator exit cleanup could not abort simulator operations', {
error: error instanceof Error ? error.message : String(error),
});
}
@@ -5716,6 +5764,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
if (disposePromise) return disposePromise;
disposePromise = (async () => {
const lifecycleStarts = actor.cancelAllLifecycleStarts();
+ const mutations = actor.cancelAllMutations();
const builds = [...activeBuilds.values()];
for (const build of builds) build.controller.abort();
// Close the recording start gate immediately, before waiting for a
@@ -5725,7 +5774,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
error: error instanceof Error ? error.message : String(error),
});
});
- await Promise.all([lifecycleStarts, ...builds.map((build) => build.settled)]);
+ await Promise.all([lifecycleStarts, mutations, ...builds.map((build) => build.settled)]);
clearVisualBaselines();
await Promise.all(
[...buildDiagnostics.entries()].map(([diagnosticsId, diagnostic]) =>
diff --git a/packages/ios-simulator-runtime/src/app-lifecycle.test.ts b/packages/ios-simulator-runtime/src/app-lifecycle.test.ts
index 1efa652b02..750062778a 100644
--- a/packages/ios-simulator-runtime/src/app-lifecycle.test.ts
+++ b/packages/ios-simulator-runtime/src/app-lifecycle.test.ts
@@ -27,9 +27,12 @@ describe("IOSSimulatorAppLifecycle", () => {
exitCode: 0,
}));
const lifecycle = new IOSSimulatorAppLifecycle({ commandRunner: { run } });
- const artifact = await lifecycle.inspectArtifact(root, appPath);
- await lifecycle.installExact("EXACT-UDID", artifact);
- await lifecycle.launchExact("EXACT-UDID", artifact, ["--uitesting"]);
+ const signal = new AbortController().signal;
+ const artifact = await lifecycle.inspectArtifact(root, appPath, undefined, signal);
+ await lifecycle.installExact("EXACT-UDID", artifact, signal);
+ await lifecycle.launchExact("EXACT-UDID", artifact, ["--uitesting"], signal);
+ await lifecycle.terminateExact("EXACT-UDID", artifact.bundleId, signal);
+ await lifecycle.openUrlExact("EXACT-UDID", "demo://home", signal);
const resolvedAppPath = await realpath(appPath);
expect(artifact).toMatchObject({
@@ -39,12 +42,55 @@ describe("IOSSimulatorAppLifecycle", () => {
expect(run).toHaveBeenCalledWith(
"xcrun",
["simctl", "install", "EXACT-UDID", resolvedAppPath],
- expect.any(Object),
+ expect.objectContaining({ signal }),
);
expect(run).toHaveBeenCalledWith(
"xcrun",
["simctl", "launch", "EXACT-UDID", "com.example.app", "--uitesting"],
- expect.any(Object),
+ expect.objectContaining({ signal }),
+ );
+ expect(run).toHaveBeenCalledWith(
+ "xcrun",
+ ["simctl", "terminate", "EXACT-UDID", "com.example.app"],
+ expect.objectContaining({ signal }),
+ );
+ expect(run).toHaveBeenCalledWith(
+ "xcrun",
+ ["simctl", "openurl", "EXACT-UDID", "demo://home"],
+ expect.objectContaining({ signal }),
+ );
+ expect(run).toHaveBeenCalledWith(
+ "/usr/bin/plutil",
+ expect.any(Array),
+ expect.objectContaining({ signal }),
+ );
+ });
+
+ it("reports cancellation when a simctl app operation is aborted", async () => {
+ const controller = new AbortController();
+ const run = vi.fn(async () => {
+ controller.abort();
+ return { stdout: "", stderr: "", exitCode: null };
+ });
+ const lifecycle = new IOSSimulatorAppLifecycle({ commandRunner: { run } });
+
+ await expect(
+ lifecycle.installExact(
+ "EXACT-UDID",
+ {
+ artifactId: "artifact-a",
+ worktreeRoot: "/tmp/worktree",
+ appPath: "/tmp/worktree/Demo.app",
+ bundleId: "com.example.demo",
+ createdAt: "2026-08-08T00:00:00.000Z",
+ },
+ controller.signal,
+ ),
+ ).rejects.toMatchObject({ code: "MUTATION_CANCELLED" });
+ expect(run).toHaveBeenCalledWith(
+ "xcrun",
+ expect.arrayContaining(["install", "EXACT-UDID"]),
+ expect.objectContaining({ signal: controller.signal }),
);
});
diff --git a/packages/ios-simulator-runtime/src/app-lifecycle.ts b/packages/ios-simulator-runtime/src/app-lifecycle.ts
index c67e3bb7b2..9912485cf7 100644
--- a/packages/ios-simulator-runtime/src/app-lifecycle.ts
+++ b/packages/ios-simulator-runtime/src/app-lifecycle.ts
@@ -33,6 +33,15 @@ function requireBundleId(value: string): string {
return normalized;
}
+function throwIfAborted(signal?: AbortSignal): void {
+ if (!signal?.aborted) return;
+ throw new IOSSimulatorInstanceError(
+ "MUTATION_CANCELLED",
+ "The simulator app operation was cancelled because its lifecycle changed.",
+ true,
+ );
+}
+
/** Exact-UDID simctl app lifecycle with worktree-contained build artifacts. */
export class IOSSimulatorAppLifecycle {
readonly #runner: IOSSimulatorCommandRunner;
@@ -46,7 +55,9 @@ export class IOSSimulatorAppLifecycle {
worktreeRoot: string,
appPath: string,
trustedBuildRoot?: string,
+ signal?: AbortSignal,
): Promise<IOSSimulatorAppArtifact> {
+ throwIfAborted(signal);
const root = await realpath(worktreeRoot);
const resolvedApp = await realpath(appPath);
const resolvedBuildRoot = trustedBuildRoot
@@ -73,8 +84,9 @@ export class IOSSimulatorAppLifecycle {
const result = await this.#runner.run(
"/usr/bin/plutil",
["-extract", "CFBundleIdentifier", "raw", "-o", "-", plist],
- { timeoutMs: 15_000, maxBufferBytes: 64 * 1024 },
+ { timeoutMs: 15_000, maxBufferBytes: 64 * 1024, signal },
);
+ throwIfAborted(signal);
if (result.exitCode !== 0) {
throw new IOSSimulatorInstanceError(
"APP_ARTIFACT_INVALID",
@@ -93,14 +105,18 @@ export class IOSSimulatorAppLifecycle {
async installExact(
simulatorUdid: string,
artifact: IOSSimulatorAppArtifact,
+ signal?: AbortSignal,
): Promise<void> {
+ throwIfAborted(signal);
const result = await this.#runner.run(
"xcrun",
["simctl", "install", simulatorUdid, artifact.appPath],
{
timeoutMs: 120_000,
+ signal,
},
);
+ throwIfAborted(signal);
if (result.exitCode !== 0) {
throw new IOSSimulatorInstanceError(
"APP_INSTALL_FAILED",
@@ -114,7 +130,9 @@ export class IOSSimulatorAppLifecycle {
simulatorUdid: string,
artifact: Pick<IOSSimulatorAppArtifact, "bundleId">,
args: string[] = [],
+ signal?: AbortSignal,
): Promise<void> {
+ throwIfAborted(signal);
if (
args.length > 64 ||
args.some((arg) => typeof arg !== "string" || arg.length > 4_096)
@@ -133,8 +151,9 @@ export class IOSSimulatorAppLifecycle {
requireBundleId(artifact.bundleId),
...args,
],
- { timeoutMs: 30_000 },
+ { timeoutMs: 30_000, signal },
);
+ throwIfAborted(signal);
if (result.exitCode !== 0) {
throw new IOSSimulatorInstanceError(
"APP_LAUNCH_FAILED",
@@ -144,12 +163,18 @@ export class IOSSimulatorAppLifecycle {
}
}
- async terminateExact(simulatorUdid: string, bundleId: string): Promise<void> {
+ async terminateExact(
+ simulatorUdid: string,
+ bundleId: string,
+ signal?: AbortSignal,
+ ): Promise<void> {
+ throwIfAborted(signal);
const result = await this.#runner.run(
"xcrun",
["simctl", "terminate", simulatorUdid, requireBundleId(bundleId)],
- { timeoutMs: 30_000 },
+ { timeoutMs: 30_000, signal },
);
+ throwIfAborted(signal);
if (result.exitCode !== 0) {
throw new IOSSimulatorInstanceError(
"APP_TERMINATE_FAILED",
@@ -159,7 +184,12 @@ export class IOSSimulatorAppLifecycle {
}
}
- async openUrlExact(simulatorUdid: string, rawUrl: string): Promise<void> {
+ async openUrlExact(
+ simulatorUdid: string,
+ rawUrl: string,
+ signal?: AbortSignal,
+ ): Promise<void> {
+ throwIfAborted(signal);
if (rawUrl.length > 8_192 || /[\r\n\0]/.test(rawUrl)) {
throw new IOSSimulatorInstanceError(
"INVALID_ARGUMENT",
@@ -188,8 +218,9 @@ export class IOSSimulatorAppLifecycle {
const result = await this.#runner.run(
"xcrun",
["simctl", "openurl", simulatorUdid, url.toString()],
- { timeoutMs: 30_000 },
+ { timeoutMs: 30_000, signal },
);
+ throwIfAborted(signal);
if (result.exitCode !== 0) {
throw new IOSSimulatorInstanceError(
"OPEN_URL_FAILED",
diff --git a/packages/ios-simulator-runtime/src/instance-actor.test.ts b/packages/ios-simulator-runtime/src/instance-actor.test.ts
index a7abaaea8c..0719db86eb 100644
--- a/packages/ios-simulator-runtime/src/instance-actor.test.ts
+++ b/packages/ios-simulator-runtime/src/instance-actor.test.ts
@@ -339,6 +339,73 @@ describe("IOSSimulatorInstanceActor", () => {
});
});
+ it("cancels an active Agent mutation as soon as stop is admitted", async () => {
+ const harness = createHarness({ booted: true });
+ let activeSignal: AbortSignal | undefined;
+ const active = harness.actor.runMutation(
+ harness.route(),
+ async (_instance, signal) => {
+ activeSignal = signal;
+ await new Promise<void>((resolve) => {
+ signal.addEventListener("abort", () => resolve(), { once: true });
+ });
+ },
+ );
+ await vi.waitFor(() => expect(activeSignal).toBeDefined());
+
+ 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" });
+ });
+
+ it("cancels an active user mutation through the force-exit seam", async () => {
+ const harness = createHarness({ booted: true });
+ let activeSignal: AbortSignal | undefined;
+ const active = harness.actor.runMutation(
+ harness.route(),
+ async (_instance, signal) => {
+ activeSignal = signal;
+ await new Promise<void>((resolve) => {
+ signal.addEventListener("abort", () => resolve(), { once: true });
+ });
+ },
+ "user",
+ );
+ await vi.waitFor(() => expect(activeSignal).toBeDefined());
+
+ expect(() => harness.actor.abortOperationsForExit()).not.toThrow();
+ expect(activeSignal?.aborted).toBe(true);
+ await expect(active).rejects.toMatchObject({ code: "MUTATION_CANCELLED" });
+ });
+
+ it("aborts and drains active and queued mutations for one session", async () => {
+ const harness = createHarness({ booted: true });
+ let activeSignal: AbortSignal | undefined;
+ const active = harness.actor
+ .runMutation(
+ harness.route(),
+ async (_instance, signal) => {
+ activeSignal = signal;
+ await new Promise<void>((resolve) => {
+ signal.addEventListener("abort", () => resolve(), { once: true });
+ });
+ },
+ "user",
+ )
+ .catch((error: unknown) => error);
+ await vi.waitFor(() => expect(activeSignal).toBeDefined());
+ const queued = harness.actor
+ .runMutation(harness.route(), async () => "should-not-run", "user")
+ .catch((error: unknown) => error);
+
+ const cancelling = harness.actor.cancelMutationsForSession("session-a");
+ expect(activeSignal?.aborted).toBe(true);
+ await expect(cancelling).resolves.toBeUndefined();
+ await expect(active).resolves.toMatchObject({ code: "MUTATION_CANCELLED" });
+ await expect(queued).resolves.toMatchObject({ code: "MUTATION_CANCELLED" });
+ });
+
it("ignores a stale liveness result without cancelling the new generation", async () => {
const harness = createHarness({ booted: true });
const recovered = await harness.actor.recover(harness.route());
diff --git a/packages/ios-simulator-runtime/src/instance-actor.ts b/packages/ios-simulator-runtime/src/instance-actor.ts
index d61c6f9188..6b10a42886 100644
--- a/packages/ios-simulator-runtime/src/instance-actor.ts
+++ b/packages/ios-simulator-runtime/src/instance-actor.ts
@@ -85,7 +85,10 @@ export class IOSSimulatorInstanceActor {
readonly #tails = new Map<string, Promise<void>>();
readonly #cancelGrace = new Map<string, () => void>();
readonly #mutationStates = new Map<string, MutableMutationState>();
- readonly #activeAgentMutations = new Map<string, AbortController>();
+ readonly #activeMutations = new Map<
+ string,
+ { source: IOSSimulatorMutationSource; controller: AbortController }
+ >();
readonly #activeLifecycleStarts = new Map<
string,
Set<ActiveLifecycleStart>
@@ -275,8 +278,8 @@ export class IOSSimulatorInstanceActor {
}
// Invalidate mutations that entered the queue before this transition and
- // abort the currently active Agent operation. User operations remain
- // serialized and will revalidate their now-stale route afterwards.
+ // abort the currently active Agent operation. An already-active user
+ // operation remains serialized; queued work is cancelled before it runs.
this.#mutationState(input.instanceId).takeoverEpoch += 1;
this.#cancelActiveAgentMutation(input.instanceId);
this.#abortLifecycleStartsForInstance(input.instanceId);
@@ -382,6 +385,30 @@ export class IOSSimulatorInstanceActor {
return this.mutationState(route.instanceId);
}
+ /** Invalidate queued work and synchronously abort the active mutation. */
+ abortMutationsForInstance(instanceId: string): void {
+ this.#mutationState(instanceId).takeoverEpoch += 1;
+ this.#activeMutations.get(instanceId)?.controller.abort();
+ }
+
+ /** Abort and drain mutations owned by one Cindy task before its worktree is recycled. */
+ async cancelMutationsForSession(sessionId: string): Promise<void> {
+ await this.#abortAndDrainMutations(
+ this.#store.listForSession(sessionId).map((instance) => instance.instanceId),
+ );
+ }
+
+ /** Abort and drain every mutation before Host-owned runtime teardown. */
+ async cancelAllMutations(): Promise<void> {
+ await this.#abortAndDrainMutations([
+ ...new Set([
+ ...this.#mutationStates.keys(),
+ ...this.#activeMutations.keys(),
+ ...this.#tails.keys(),
+ ]),
+ ]);
+ }
+
/** Serialize one bounded driver mutation behind lifecycle operations. */
async runMutation<T>(
route: IOSSimulatorMutationRoute,
@@ -415,16 +442,19 @@ export class IOSSimulatorInstanceActor {
0,
state.queuedAgentMutations - 1,
);
- if (
- state.agentPaused ||
- state.takeoverEpoch !== expectedTakeoverEpoch
- ) {
+ if (state.agentPaused || state.takeoverEpoch !== expectedTakeoverEpoch) {
throw new IOSSimulatorInstanceError(
"MUTATION_CANCELLED",
"The queued simulator action was cancelled because simulator control changed.",
true,
);
}
+ } else if (state.takeoverEpoch !== expectedTakeoverEpoch) {
+ throw new IOSSimulatorInstanceError(
+ "MUTATION_CANCELLED",
+ "The queued simulator action was cancelled because its lifecycle changed.",
+ true,
+ );
} else if (state.activeSource === "agent") {
throw new IOSSimulatorInstanceError(
"DEVICE_BUSY",
@@ -434,9 +464,8 @@ export class IOSSimulatorInstanceActor {
}
state.activeSource = source;
const controller = new AbortController();
- if (source === "agent") {
- this.#activeAgentMutations.set(route.instanceId, controller);
- }
+ const activeMutation = { source, controller };
+ this.#activeMutations.set(route.instanceId, activeMutation);
try {
this.#store.assertMutationRoute(route);
const instance = this.#store.heartbeat(
@@ -451,7 +480,7 @@ export class IOSSimulatorInstanceActor {
);
}
const result = await task(instance, controller.signal);
- if (source === "agent" && controller.signal.aborted) {
+ if (controller.signal.aborted) {
throw new IOSSimulatorInstanceError(
"MUTATION_CANCELLED",
"The active simulator action was cancelled because simulator control changed.",
@@ -460,8 +489,8 @@ export class IOSSimulatorInstanceActor {
}
return result;
} finally {
- if (this.#activeAgentMutations.get(route.instanceId) === controller) {
- this.#activeAgentMutations.delete(route.instanceId);
+ if (this.#activeMutations.get(route.instanceId) === activeMutation) {
+ this.#activeMutations.delete(route.instanceId);
}
state.activeSource = null;
state.lastSource = source;
@@ -484,9 +513,7 @@ export class IOSSimulatorInstanceActor {
// serialized check below is still required because ownership can be
// rebound while cleanup waits behind an existing instance operation.
this.#store.requireOwned(instanceId, sessionId);
- const state = this.#mutationState(instanceId);
- state.takeoverEpoch += 1;
- this.#cancelActiveAgentMutation(instanceId);
+ this.abortMutationsForInstance(instanceId);
this.#abortLifecycleStartsForInstance(instanceId);
this.#cancelGrace.get(instanceId)?.();
this.#cancelGrace.delete(instanceId);
@@ -497,7 +524,19 @@ export class IOSSimulatorInstanceActor {
}
#cancelActiveAgentMutation(instanceId: string): void {
- this.#activeAgentMutations.get(instanceId)?.abort();
+ const active = this.#activeMutations.get(instanceId);
+ if (active?.source === "agent") active.controller.abort();
+ }
+
+ async #abortAndDrainMutations(instanceIds: string[]): Promise<void> {
+ const uniqueInstanceIds = [...new Set(instanceIds)];
+ for (const instanceId of uniqueInstanceIds) {
+ this.abortMutationsForInstance(instanceId);
+ }
+ const tails = uniqueInstanceIds
+ .map((instanceId) => this.#tails.get(instanceId))
+ .filter((tail): tail is Promise<void> => Boolean(tail));
+ await Promise.all(tails);
}
#lifecycleStartCancelledError(): IOSSimulatorInstanceError {
@@ -607,6 +646,9 @@ export class IOSSimulatorInstanceActor {
/** Synchronous force-quit seam; async disposal separately awaits settlement. */
abortOperationsForExit(): void {
+ for (const instanceId of this.#mutationStates.keys()) {
+ this.abortMutationsForInstance(instanceId);
+ }
this.#abortLifecycleStarts(
[...this.#activeLifecycleStarts.values()].flatMap((entries) => [
...entries,
@@ -777,6 +819,7 @@ export class IOSSimulatorInstanceActor {
} catch (error) {
return Promise.reject(error);
}
+ this.abortMutationsForInstance(admission.instanceId);
this.#abortLifecycleStartsForInstance(admission.instanceId);
return this.#serialize(admission.instanceId, async () => {
const instance = this.#requireAdmittedLifecycleRoute(admission);
@@ -828,6 +871,7 @@ export class IOSSimulatorInstanceActor {
} catch (error) {
return Promise.reject(error);
}
+ this.abortMutationsForInstance(admission.instanceId);
this.#abortLifecycleStartsForInstance(admission.instanceId);
return this.#serialize(admission.instanceId, async () => {
const instance = this.#requireAdmittedLifecycleRoute(admission);
diff --git a/packages/ios-simulator-runtime/src/project-adapter.test.ts b/packages/ios-simulator-runtime/src/project-adapter.test.ts
index 732e6a9a8f..cf5a8325f6 100644
--- a/packages/ios-simulator-runtime/src/project-adapter.test.ts
+++ b/packages/ios-simulator-runtime/src/project-adapter.test.ts
@@ -73,8 +73,9 @@ describe("IOSSimulatorProjectBuilder", () => {
return { stdout: "", stderr: "", exitCode: 0 };
});
const builder = new IOSSimulatorProjectBuilder({ commandRunner: { run } });
+ const signal = new AbortController().signal;
await expect(
- builder.validateLaunch(root, SIMULATOR_UDID.toLowerCase()),
+ builder.validateLaunch(root, SIMULATOR_UDID.toLowerCase(), signal),
).resolves.toMatchObject({
healthy: true,
expectedPort: 8081,
@@ -88,7 +89,7 @@ describe("IOSSimulatorProjectBuilder", () => {
"--udid",
SIMULATOR_UDID,
],
- expect.objectContaining({ cwd: await realpath(root) }),
+ expect.objectContaining({ cwd: await realpath(root), signal }),
);
});
diff --git a/packages/ios-simulator-runtime/src/project-adapter.ts b/packages/ios-simulator-runtime/src/project-adapter.ts
index 820896a7d9..fe133edf7e 100644
--- a/packages/ios-simulator-runtime/src/project-adapter.ts
+++ b/packages/ios-simulator-runtime/src/project-adapter.ts
@@ -148,6 +148,15 @@ async function throwIfBuildCancelled(
);
}
+function throwIfLaunchValidationCancelled(signal?: AbortSignal): void {
+ if (!signal?.aborted) return;
+ throw new IOSSimulatorInstanceError(
+ "MUTATION_CANCELLED",
+ "App launch validation was cancelled because its simulator session ended.",
+ true,
+ );
+}
+
/** Detects Cindy Mobile or one unambiguous generic Xcode container and builds without a shell. */
export class IOSSimulatorProjectBuilder {
readonly #runner: IOSSimulatorCommandRunner;
@@ -494,8 +503,11 @@ export class IOSSimulatorProjectBuilder {
async validateLaunch(
worktreeRoot: string,
simulatorUdid: string,
+ signal?: AbortSignal,
): Promise<IOSSimulatorMobileMetroStatus | null> {
+ throwIfLaunchValidationCancelled(signal);
const project = await this.inspect(worktreeRoot);
+ throwIfLaunchValidationCancelled(signal);
if (project.kind !== "cindy-mobile") return null;
const exactSimulatorUdid = simulatorUdid.trim().toUpperCase();
if (!/^[0-9A-F]{8}(?:-[0-9A-F]{4}){3}-[0-9A-F]{12}$/.test(exactSimulatorUdid)) {
@@ -517,8 +529,10 @@ export class IOSSimulatorProjectBuilder {
cwd: project.worktreeRoot,
timeoutMs: 60_000,
maxBufferBytes: 2 * 1024 * 1024,
+ signal,
},
);
+ throwIfLaunchValidationCancelled(signal);
const lines = `${result.stdout}\n${result.stderr}`
.split(/\r?\n/)
.map((line) => line.trim())