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): recover markers and cancel screenshots

JiangJiahao1765e437153f
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-media.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-media.test.ts
index 05ea7e0434..32d1edb1a0 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-media.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-media.test.ts
@@ -3,6 +3,8 @@ import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { IOSSimulatorCommandRunner } from '@cindy/ios-simulator-runtime';
+
import { IOSSimulatorMediaCapture } from '../ios-simulator-media';
afterEach(() => {
@@ -54,6 +56,82 @@ describe('IOSSimulatorMediaCapture', () => {
);
});
+ it('forwards screenshot cancellation to xcrun and removes the temporary directory', async () => {
+ let screenshotPath = '';
+ let runnerSignal: AbortSignal | undefined;
+ const run = vi.fn<IOSSimulatorCommandRunner['run']>(async (_command, args, options) => {
+ screenshotPath = args.at(-1)!;
+ runnerSignal = options?.signal;
+ return new Promise((resolve) => {
+ options?.signal?.addEventListener(
+ 'abort',
+ () => resolve({ stdout: '', stderr: '', exitCode: null }),
+ { once: true },
+ );
+ });
+ });
+ const capture = new IOSSimulatorMediaCapture({ commandRunner: { run } });
+ const controller = new AbortController();
+
+ const screenshot = capture.captureScreenshotBytes({
+ simulatorUdid: 'EXACT-UDID',
+ signal: controller.signal,
+ });
+ await vi.waitFor(() => expect(runnerSignal).toBe(controller.signal));
+ const tempRoot = path.dirname(screenshotPath);
+ controller.abort(new Error('task closed'));
+
+ await expect(screenshot).rejects.toMatchObject({ code: 'SCREENSHOT_CAPTURE_FAILED' });
+ await expect(stat(tempRoot)).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
+ it('invalidates screenshot ingest when its host mutation is cancelled after capture', async () => {
+ let markIngestStarted: () => void = () => undefined;
+ let releaseIngest: () => void = () => undefined;
+ const ingestStarted = new Promise<void>((resolve) => {
+ markIngestStarted = resolve;
+ });
+ const ingestGate = new Promise<void>((resolve) => {
+ releaseIngest = resolve;
+ });
+ const ingest = vi.fn(async (params) => {
+ markIngestStarted();
+ await ingestGate;
+ params.assertStillValid?.();
+ return {
+ hash: 'b'.repeat(64),
+ ext: '.png',
+ mimeType: 'image/png',
+ bytes: params.buffer.length,
+ url: `cindy-media://blobs/${'b'.repeat(64)}.png`,
+ deduplicated: false,
+ refIds: ['late-ref'],
+ };
+ });
+ const run = vi.fn(async (_command: string, args: readonly string[]) => {
+ const output = args.at(-1)!;
+ await mkdir(path.dirname(output), { recursive: true });
+ await writeFile(output, Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 1]));
+ return { stdout: '', stderr: '', exitCode: 0 };
+ });
+ const capture = new IOSSimulatorMediaCapture({ commandRunner: { run }, ingest });
+ const controller = new AbortController();
+
+ const screenshot = capture.takeScreenshot({
+ simulatorUdid: 'EXACT-UDID',
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ source: 'agent',
+ signal: controller.signal,
+ });
+ await ingestStarted;
+ controller.abort(new Error('task closed'));
+
+ await expect(screenshot).rejects.toMatchObject({ code: 'MUTATION_CANCELLED' });
+ releaseIngest();
+ await expect(capture.dispose()).resolves.toBeUndefined();
+ });
+
it('does not ingest a screenshot after its data owner changes during capture', async () => {
let ownerScopeKey = 'owner-a';
const ingest = vi.fn();
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 4cf7ddb237..5b137de520 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
@@ -126,20 +126,70 @@ describe('iOS Simulator host', () => {
}
});
- itMac('keeps startup ownership recovery lazy when the registry is empty', async () => {
- const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-host-lazy-reconcile-'));
- const getPath = vi.spyOn(app, 'getPath').mockReturnValue(root);
- const registryPath = path.join(root, 'ios-simulator', 'ownership-registry.json');
- const competingRegistry = new IOSSimulatorOwnershipRegistryFile(registryPath);
- try {
- await expect(reconcilePersistedIOSSimulatorOwnership()).resolves.toBeUndefined();
- expect(competingRegistry.acquireWriterSync()).toBe(true);
- } finally {
- competingRegistry.releaseWriterSync();
- getPath.mockRestore();
- await rm(root, { recursive: true, force: true });
- }
- });
+ itMac(
+ 'recovers pending creates with an empty registry before releasing its writer lease',
+ async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-host-lazy-reconcile-'));
+ const getPath = vi.spyOn(app, 'getPath').mockReturnValue(root);
+ const registryPath = path.join(root, 'ios-simulator', 'ownership-registry.json');
+ const competingRegistry = new IOSSimulatorOwnershipRegistryFile(registryPath);
+ let finishRecovery: (value: readonly string[]) => void = () => undefined;
+ const recoverPendingCreatesAtStartup = vi.fn(
+ (_owned: readonly { udid: string; name: string }[], _signal?: AbortSignal) =>
+ new Promise<readonly string[]>((resolve) => {
+ finishRecovery = resolve;
+ }),
+ );
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(),
+ createExact: vi.fn(),
+ recoverPendingCreatesAtStartup,
+ deleteExact: vi.fn(),
+ };
+ try {
+ const recovering = reconcilePersistedIOSSimulatorOwnership({
+ createLifecycle: () => lifecycle,
+ });
+ await vi.waitFor(() => expect(recoverPendingCreatesAtStartup).toHaveBeenCalledOnce());
+ expect(recoverPendingCreatesAtStartup).toHaveBeenCalledWith([], expect.any(AbortSignal));
+ expect(competingRegistry.acquireWriterSync()).toBe(false);
+
+ finishRecovery([]);
+ await expect(recovering).resolves.toBeUndefined();
+ expect(competingRegistry.acquireWriterSync()).toBe(true);
+ } finally {
+ competingRegistry.releaseWriterSync();
+ getPath.mockRestore();
+ await rm(root, { recursive: true, force: true });
+ }
+ },
+ );
+
+ itMac(
+ 'does not inspect or delete pending markers when the ownership registry is invalid',
+ async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-host-invalid-reconcile-'));
+ const getPath = vi.spyOn(app, 'getPath').mockReturnValue(root);
+ const registryPath = path.join(root, 'ios-simulator', 'ownership-registry.json');
+ await mkdir(path.dirname(registryPath), { recursive: true });
+ await writeFile(registryPath, '{"version":1,"instances":[');
+ const createLifecycle = vi.fn();
+ const competingRegistry = new IOSSimulatorOwnershipRegistryFile(registryPath);
+ try {
+ await expect(
+ reconcilePersistedIOSSimulatorOwnership({ createLifecycle }),
+ ).rejects.toMatchObject({ code: 'DEVICE_BUSY' });
+ expect(createLifecycle).not.toHaveBeenCalled();
+ expect(competingRegistry.acquireWriterSync()).toBe(true);
+ } finally {
+ competingRegistry.releaseWriterSync();
+ getPath.mockRestore();
+ await rm(root, { recursive: true, force: true });
+ }
+ },
+ );
it('does not reconcile Simulator ownership during generic IPC bootstrap', () => {
const source = readFileSync(new URL('../../maker-ipc/register.ts', import.meta.url), 'utf8');
@@ -5716,7 +5766,15 @@ describe('iOS Simulator host', () => {
'base64',
),
),
- takeScreenshot: vi.fn(),
+ takeScreenshot: vi.fn(async () => ({
+ hash: 'a'.repeat(64),
+ ext: '.png',
+ mimeType: 'image/png',
+ bytes: 8,
+ url: `cindy-media://blobs/${'a'.repeat(64)}.png`,
+ deduplicated: false,
+ refIds: ['ref-screenshot'],
+ })),
startRecording: vi.fn(),
stopRecording: vi.fn(),
} as unknown as IOSSimulatorMediaCaptureAdapter;
@@ -5850,6 +5908,19 @@ describe('iOS Simulator host', () => {
ok: true,
data: { diff: { unchangedCount: 1, added: [], removed: [], changed: [] } },
});
+ await expect(
+ host.callTool('take_screenshot', route, { sessionId: 'session-a', origin: 'agent' }),
+ ).resolves.toMatchObject({
+ ok: true,
+ data: { mediaUrl: expect.stringMatching(/^cindy-media:\/\/blobs\//) },
+ });
+ expect(mediaCapture.takeScreenshot).toHaveBeenCalledWith({
+ simulatorUdid: instance.simulatorUdid,
+ sessionId: 'session-a',
+ instanceId: instance.instanceId,
+ source: 'agent',
+ signal: expect.any(AbortSignal),
+ });
const visualBaseline = await host.callTool('capture_visual_baseline', route, {
sessionId: 'session-a',
origin: 'agent',
@@ -5870,6 +5941,14 @@ describe('iOS Simulator host', () => {
ok: true,
data: { diff: { comparedPixels: 1, differentPixels: 0, differenceRatio: 0 } },
});
+ expect(mediaCapture.captureScreenshotBytes).toHaveBeenNthCalledWith(1, {
+ simulatorUdid: instance.simulatorUdid,
+ signal: expect.any(AbortSignal),
+ });
+ expect(mediaCapture.captureScreenshotBytes).toHaveBeenNthCalledWith(2, {
+ simulatorUdid: instance.simulatorUdid,
+ signal: expect.any(AbortSignal),
+ });
await expect(
host.callTool(
'audit_accessibility',
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator-media.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator-media.ts
index 7d513b1810..c38c064ad8 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator-media.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator-media.ts
@@ -62,6 +62,7 @@ export interface IOSSimulatorScreenshotInput {
sessionId: string;
instanceId: string;
source: 'agent' | 'user';
+ signal?: AbortSignal;
}
interface ActiveRecording {
@@ -654,7 +655,7 @@ export class IOSSimulatorMediaCapture {
}
async captureScreenshotBytes(
- input: Pick<IOSSimulatorScreenshotInput, 'simulatorUdid'>,
+ input: Pick<IOSSimulatorScreenshotInput, 'simulatorUdid' | 'signal'>,
): Promise<Buffer> {
const tempRoot = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-screenshot-'));
const screenshotPath = path.join(tempRoot, 'screenshot.png');
@@ -662,7 +663,7 @@ export class IOSSimulatorMediaCapture {
const result = await this.#runner.run(
'xcrun',
['simctl', 'io', input.simulatorUdid, 'screenshot', '--type=png', screenshotPath],
- { timeoutMs: 30_000, maxBufferBytes: 256 * 1024 },
+ { timeoutMs: 30_000, maxBufferBytes: 256 * 1024, signal: input.signal },
);
if (result.exitCode !== 0) {
throw new IOSSimulatorInstanceError(
@@ -708,6 +709,13 @@ export class IOSSimulatorMediaCapture {
const requests = this.#screenshotRequestsBySession.get(input.sessionId) ?? new Set();
requests.add(request);
this.#screenshotRequestsBySession.set(input.sessionId, requests);
+ const cancelForAbortedMutation = (): void => {
+ if (request.cancelled) return;
+ request.cancelled = true;
+ request.resolveCancelled();
+ };
+ if (input.signal?.aborted) cancelForAbortedMutation();
+ else input.signal?.addEventListener('abort', cancelForAbortedMutation, { once: true });
const operation = (async (): Promise<IngestedMedia> => {
this.#assertScreenshotCurrent(request);
const buffer = await this.captureScreenshotBytes(input);
@@ -741,6 +749,7 @@ export class IOSSimulatorMediaCapture {
try {
return await this.#awaitScreenshotRequest(request, operation);
} finally {
+ input.signal?.removeEventListener('abort', cancelForAbortedMutation);
requests.delete(request);
if (requests.size === 0) this.#screenshotRequestsBySession.delete(input.sessionId);
}
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
index fc8702f3ae..bfcc07aad8 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
@@ -385,6 +385,39 @@ function createProfileScopedIOSSimulatorLifecycle(
return createIOSSimulatorSimctlLifecycle({ createMarkerNamespace });
}
+const STARTUP_PENDING_CREATE_RECOVERY_TIMEOUT_MS = 6_000;
+
+async function recoverProfilePendingCreatesAtStartup(
+ lifecycle: IOSSimulatorSimctlLifecycle,
+ persistedInstances: readonly IOSSimulatorInstance[],
+): Promise<void> {
+ if (!lifecycle.recoverPendingCreatesAtStartup) return;
+ const controller = new AbortController();
+ const timer = setTimeout(
+ () => controller.abort(new Error('Simulator pending-create startup recovery timed out')),
+ STARTUP_PENDING_CREATE_RECOVERY_TIMEOUT_MS,
+ );
+ timer.unref?.();
+ try {
+ await lifecycle.recoverPendingCreatesAtStartup(
+ persistedInstances.map((instance) => ({
+ udid: instance.simulatorUdid,
+ name: instance.simulatorName,
+ })),
+ controller.signal,
+ );
+ } catch (error) {
+ // A marker remains hidden and profile-scoped, so an optional Simulator
+ // cleanup failure must not block Cindy startup. Keeping it intact lets the
+ // next startup retry under the same exclusive registry lease.
+ logger.warn('Interrupted simulator create startup recovery will retry', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
function createDefaultActor(
lifecycle: IOSSimulatorSimctlLifecycle,
registry = createDefaultOwnershipRegistry(),
@@ -5419,7 +5452,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
route.instanceId,
'screenshot',
);
- const captured = await runHostMutation(route, context, async (instance) => {
+ const captured = await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
assertSessionOperationAdmission(
instance.sessionId,
@@ -5436,6 +5469,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
sessionId: instance.sessionId,
instanceId: instance.instanceId,
source: context?.origin === 'user' ? 'user' : 'agent',
+ signal,
});
});
return {
@@ -5451,7 +5485,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
}
if (name === 'capture_visual_baseline') {
const route = readMutationRoute(sessionId, args);
- const baseline = await runHostMutation(route, context, async (instance) => {
+ const baseline = await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
if (typeof mediaCapture.captureScreenshotBytes !== 'function') {
throw new IOSSimulatorInstanceError(
@@ -5461,6 +5495,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
}
const bytes = await mediaCapture.captureScreenshotBytes({
simulatorUdid: instance.simulatorUdid,
+ signal,
});
const baselineId = randomUUID();
while (visualBaselines.size >= 4) {
@@ -5508,7 +5543,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
'threshold must be between 0 and 255',
);
}
- const diff = await runHostMutation(route, context, async (instance) => {
+ const diff = await runHostMutation(route, context, async (instance, signal) => {
requireControlGrant(instance, context);
if (typeof mediaCapture.captureScreenshotBytes !== 'function') {
throw new IOSSimulatorInstanceError(
@@ -5518,6 +5553,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
}
const current = await mediaCapture.captureScreenshotBytes({
simulatorUdid: instance.simulatorUdid,
+ signal,
});
return compareIOSSimulatorPngBuffers(baseline.bytes, current, threshold);
});
@@ -6089,14 +6125,22 @@ export function reconcileIOSSimulatorOwnership(): Promise<void> {
}
/**
- * Startup recovery stays lazy when this profile has never owned a simulator,
- * but persisted bindings must be reconciled even if the feature is not opened
- * again after a crash.
+ * Startup recovery performs one bounded, profile-scoped pending-create sweep
+ * even when ownership is empty, then releases the writer lease without
+ * installing the Host. Persisted bindings still install the Host so they are
+ * reconciled even if the feature is not opened again after a crash.
*/
-export function reconcilePersistedIOSSimulatorOwnership(): Promise<void> {
+export interface IOSSimulatorPersistedOwnershipRecoveryOptions {
+ /** Test seam; production always derives a profile-scoped lifecycle. */
+ createLifecycle?: (registry: IOSSimulatorOwnershipRegistryFile) => IOSSimulatorSimctlLifecycle;
+}
+
+export async function reconcilePersistedIOSSimulatorOwnership(
+ options: IOSSimulatorPersistedOwnershipRecoveryOptions = {},
+): Promise<void> {
const currentHost = currentIOSSimulatorHost();
if (currentHost) return currentHost.reconcileOwnership();
- if (process.platform !== 'darwin') return Promise.resolve();
+ if (process.platform !== 'darwin') return;
const registry = createDefaultOwnershipRegistry();
let registryTransferred = false;
@@ -6109,18 +6153,20 @@ export function reconcilePersistedIOSSimulatorOwnership(): Promise<void> {
);
}
const persistedInstances = registry.loadSync();
+ const lifecycle =
+ options.createLifecycle?.(registry) ?? createProfileScopedIOSSimulatorLifecycle(registry);
+ await recoverProfilePendingCreatesAtStartup(lifecycle, persistedInstances);
if (persistedInstances.length === 0) {
registry.releaseWriterSync();
- return Promise.resolve();
+ return;
}
- const lifecycle = createProfileScopedIOSSimulatorLifecycle(registry);
const persistedActor = createDefaultActor(lifecycle, registry);
const host = installDefaultIOSSimulatorHost(lifecycle, persistedActor);
registryTransferred = true;
- return host.reconcileOwnership();
+ await host.reconcileOwnership();
} catch (error) {
if (!registryTransferred) registry.releaseWriterSync();
- return Promise.reject(error);
+ throw error;
}
}
diff --git a/packages/ios-simulator-runtime/src/simctl-lifecycle.test.ts b/packages/ios-simulator-runtime/src/simctl-lifecycle.test.ts
index 78b3a17274..dc2622baca 100644
--- a/packages/ios-simulator-runtime/src/simctl-lifecycle.test.ts
+++ b/packages/ios-simulator-runtime/src/simctl-lifecycle.test.ts
@@ -359,6 +359,69 @@ describe("createIOSSimulatorSimctlLifecycle", () => {
expect(JSON.stringify(deleteCalls)).not.toContain(preexistingUdid);
});
+ it("deletes a delayed unclaimed marker during the next profile startup recovery", async () => {
+ const controller = new AbortController();
+ const reason = new Error("create cancelled before delayed marker appeared");
+ let markerName = "";
+ let createSignal: AbortSignal | undefined;
+ let listCount = 0;
+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(
+ async (_command, args, options) => {
+ if (args[1] === "create") {
+ markerName = args[2]!;
+ createSignal = options?.signal;
+ await new Promise<void>((resolve) => {
+ options?.signal?.addEventListener("abort", () => resolve(), {
+ once: true,
+ });
+ });
+ return { stdout: "", stderr: "", exitCode: null };
+ }
+ if (args[1] === "list") {
+ listCount += 1;
+ return {
+ stdout:
+ listCount === 1
+ ? devicesJson([])
+ : devicesJson([{ udid: UDID, name: markerName }]),
+ stderr: "",
+ exitCode: 0,
+ };
+ }
+ if (args[1] === "delete") {
+ return { stdout: "", stderr: "", exitCode: 0 };
+ }
+ throw new Error(`unexpected ${args.join(" ")}`);
+ },
+ );
+ const lifecycle = createIOSSimulatorSimctlLifecycle({
+ commandRunner: { run },
+ createMarkerNamespace: "testprofile",
+ });
+
+ const creating = lifecycle.createExact(
+ {
+ name: "Cindy iPhone",
+ deviceTypeIdentifier: DEVICE_TYPE,
+ runtimeIdentifier: RUNTIME,
+ },
+ controller.signal,
+ );
+ await vi.waitFor(() => expect(createSignal).toBe(controller.signal));
+ controller.abort(reason);
+ await expect(creating).rejects.toBe(reason);
+ expect(
+ run.mock.calls.filter(([, args]) => args[1] === "delete"),
+ ).toHaveLength(0);
+
+ await expect(
+ lifecycle.recoverPendingCreatesAtStartup?.([]),
+ ).resolves.toEqual([UDID]);
+ expect(run.mock.calls.filter(([, args]) => args[1] === "delete")).toEqual([
+ expect.arrayContaining(["/usr/bin/xcrun", ["simctl", "delete", UDID]]),
+ ]);
+ });
+
it("renames only this profile's markers with persisted exact ownership", async () => {
const ownedUdid = "2A9D41E0-E031-4AD0-A8B5-847480802E8E";
const otherProfileUdid = "3A9D41E0-E031-4AD0-A8B5-847480802E8E";
@@ -414,6 +477,107 @@ describe("createIOSSimulatorSimctlLifecycle", () => {
]);
});
+ it("startup recovery deletes only unclaimed markers from this exact profile", async () => {
+ const ownedUdid = "2A9D41E0-E031-4AD0-A8B5-847480802E8E";
+ const otherProfileUdid = "3A9D41E0-E031-4AD0-A8B5-847480802E8E";
+ const ordinaryUdid = "4A9D41E0-E031-4AD0-A8B5-847480802E8E";
+ const unclaimedName =
+ "__CindyPending__profilealpha__11111111-2222-4333-8444-555555555555";
+ const ownedName =
+ "__CindyPending__profilealpha__22222222-3333-4444-8555-666666666666";
+ const devices = [
+ { udid: UDID, name: unclaimedName },
+ { udid: ownedUdid, name: ownedName },
+ {
+ udid: otherProfileUdid,
+ name: "__CindyPending__profilebeta__33333333-4444-4555-8666-777777777777",
+ },
+ { udid: ordinaryUdid, name: "Cindy iPhone" },
+ ];
+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(
+ async (_command, args) => {
+ if (args[1] === "list") {
+ return {
+ stdout: devicesJson(devices),
+ stderr: "",
+ exitCode: 0,
+ };
+ }
+ if (args[1] === "delete" || args[1] === "rename") {
+ return { stdout: "", stderr: "", exitCode: 0 };
+ }
+ throw new Error(`unexpected ${args.join(" ")}`);
+ },
+ );
+ const lifecycle = createIOSSimulatorSimctlLifecycle({
+ commandRunner: { run },
+ createMarkerNamespace: "profilealpha",
+ });
+
+ await expect(
+ lifecycle.recoverPendingCreatesAtStartup?.([
+ { udid: ownedUdid, name: "Cindy Restored iPhone" },
+ ]),
+ ).resolves.toEqual([UDID, ownedUdid]);
+ expect(run.mock.calls.filter(([, args]) => args[1] === "delete")).toEqual([
+ expect.arrayContaining(["/usr/bin/xcrun", ["simctl", "delete", UDID]]),
+ ]);
+ expect(run.mock.calls.filter(([, args]) => args[1] === "rename")).toEqual([
+ expect.arrayContaining([
+ "/usr/bin/xcrun",
+ ["simctl", "rename", ownedUdid, "Cindy Restored iPhone"],
+ ]),
+ ]);
+ expect(JSON.stringify(run.mock.calls)).not.toContain(
+ `["simctl","delete","${otherProfileUdid}"]`,
+ );
+ expect(JSON.stringify(run.mock.calls)).not.toContain(
+ `["simctl","delete","${ordinaryUdid}"]`,
+ );
+ });
+
+ it("does not delete a pending device that changes during startup revalidation", async () => {
+ const markerName =
+ "__CindyPending__profilealpha__11111111-2222-4333-8444-555555555555";
+ let listCount = 0;
+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(
+ async (_command, args) => {
+ if (args[1] === "list") {
+ listCount += 1;
+ return {
+ stdout: devicesJson([
+ {
+ udid: UDID,
+ name:
+ listCount === 1 ? markerName : "Externally Renamed iPhone",
+ },
+ ]),
+ stderr: "",
+ exitCode: 0,
+ };
+ }
+ if (args[1] === "delete") {
+ return { stdout: "", stderr: "", exitCode: 0 };
+ }
+ throw new Error(`unexpected ${args.join(" ")}`);
+ },
+ );
+ const lifecycle = createIOSSimulatorSimctlLifecycle({
+ commandRunner: { run },
+ createMarkerNamespace: "profilealpha",
+ });
+
+ await expect(
+ lifecycle.recoverPendingCreatesAtStartup?.([]),
+ ).resolves.toEqual([]);
+ expect(
+ run.mock.calls.filter(([, args]) => args[1] === "list"),
+ ).toHaveLength(2);
+ expect(run.mock.calls.filter(([, args]) => args[1] === "delete")).toEqual(
+ [],
+ );
+ });
+
it("cancels create and deletes only an exact late-created UDID", async () => {
const controller = new AbortController();
const reason = new Error("create cancelled for exit");
diff --git a/packages/ios-simulator-runtime/src/simctl-lifecycle.ts b/packages/ios-simulator-runtime/src/simctl-lifecycle.ts
index 76166e4fa0..66e980bb58 100644
--- a/packages/ios-simulator-runtime/src/simctl-lifecycle.ts
+++ b/packages/ios-simulator-runtime/src/simctl-lifecycle.ts
@@ -136,6 +136,15 @@ export interface IOSSimulatorSimctlLifecycle {
ownedDevices: readonly { udid: string; name: string }[],
signal?: AbortSignal,
): Promise<readonly string[]>;
+ /**
+ * Startup-only recovery while the caller holds this profile's exclusive
+ * ownership-registry lease. Unclaimed markers from this exact profile are
+ * deleted by exact UUID; other profiles and ordinary devices are untouched.
+ */
+ recoverPendingCreatesAtStartup?(
+ ownedDevices: readonly { udid: string; name: string }[],
+ signal?: AbortSignal,
+ ): Promise<readonly string[]>;
deleteExact(udid: string, signal?: AbortSignal): Promise<void>;
/** Set the simulated system appearance without bringing Simulator.app forward. */
setAppearance?(
@@ -865,6 +874,55 @@ export function createIOSSimulatorSimctlLifecycle(
return reconciled;
},
+ async recoverPendingCreatesAtStartup(
+ ownedDevices,
+ signal,
+ ): Promise<readonly string[]> {
+ const owned = new Map(
+ ownedDevices.map((device) => [
+ requireUdid(device.udid),
+ requireIdentifier(device.name, "name"),
+ ]),
+ );
+ const pending = (await list(signal)).filter((device) =>
+ isPendingCreateName(device.name),
+ );
+ const recovered: string[] = [];
+ let firstFailure: unknown = null;
+ for (const device of pending) {
+ const udid = device.udid.toUpperCase();
+ try {
+ const ownedName = owned.get(udid);
+ if (ownedName) {
+ await renameExact(udid, ownedName, signal);
+ recovered.push(udid);
+ continue;
+ }
+
+ // CoreSimulator is global to the macOS user. Re-read the exact UUID
+ // before deleting so an external rename or replacement cannot turn
+ // a profile-scoped cleanup into deletion of an ordinary device.
+ const current = await findExact(udid, signal);
+ if (
+ !current ||
+ current.name !== device.name ||
+ !isPendingCreateName(current.name) ||
+ current.runtimeIdentifier !== device.runtimeIdentifier ||
+ current.deviceTypeIdentifier !== device.deviceTypeIdentifier
+ ) {
+ continue;
+ }
+ await cleanupFailedCreate(udid, signal);
+ recovered.push(udid);
+ } catch (error) {
+ if (signal?.aborted) throwIfAborted(signal);
+ firstFailure ??= error;
+ }
+ }
+ if (firstFailure !== null) throw firstFailure;
+ return recovered;
+ },
+
async deleteExact(udid, signal): Promise<void> {
const normalized = requireUdid(udid);
throwIfAborted(signal);