Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(ios-simulator): 把启动期的 Xcode 权限探测推迟到真正使用模拟器 (#2419)
JiangJiahao4acdcbb110ed
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.tsindex bfd804e638..c208421c80 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@@ -292,11 +292,15 @@ describe('iOS Simulator host', () => {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 evidencePath = path.join(root, 'ios-simulator', 'pending-create-evidence.json');+ await mkdir(path.dirname(evidencePath), { recursive: true });+ await writeFile(evidencePath, '{"version":1,"armedAt":"2026-08-11T00:00:00.000Z"}');const competingRegistry = new IOSSimulatorOwnershipRegistryFile(registryPath);- let finishRecovery: (value: readonly string[]) => void = () => undefined;+ let finishRecovery: (value: { recovered: readonly string[]; complete: boolean }) => void =+ () => undefined;const recoverPendingCreatesAtStartup = vi.fn((_owned: readonly { udid: string; name: string }[], _signal?: AbortSignal) =>- new Promise<readonly string[]>((resolve) => {+ new Promise<{ recovered: readonly string[]; complete: boolean }>((resolve) => {finishRecovery = resolve;}),);@@ -316,9 +320,12 @@ describe('iOS Simulator host', () => {expect(recoverPendingCreatesAtStartup).toHaveBeenCalledWith([], expect.any(AbortSignal));expect(competingRegistry.acquireWriterSync()).toBe(false);- finishRecovery([]);+ finishRecovery({ recovered: [], complete: true });await expect(recovering).resolves.toBeUndefined();expect(competingRegistry.acquireWriterSync()).toBe(true);+ // A completed sweep retires the breadcrumb, so the next startup has no+ // reason to touch CoreSimulator at all.+ await expect(stat(evidencePath)).rejects.toMatchObject({ code: 'ENOENT' });} finally {competingRegistry.releaseWriterSync();getPath.mockRestore();@@ -327,6 +334,97 @@ describe('iOS Simulator host', () => {},);+ itMac(+ 'performs no simulator probe at startup when the profile never created a device',+ async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-host-quiet-startup-'));+ const getPath = vi.spyOn(app, 'getPath').mockReturnValue(root);+ const registryPath = path.join(root, 'ios-simulator', 'ownership-registry.json');+ const competingRegistry = new IOSSimulatorOwnershipRegistryFile(registryPath);+ const createLifecycle = vi.fn();+ try {+ await expect(+ reconcilePersistedIOSSimulatorOwnership({ createLifecycle }),+ ).resolves.toBeUndefined();++ // No lifecycle means no xcrun/xcodebuild child process, so macOS never+ // raises an Xcode consent prompt detached from a user action.+ expect(createLifecycle).not.toHaveBeenCalled();+ expect(competingRegistry.acquireWriterSync()).toBe(true);+ } finally {+ competingRegistry.releaseWriterSync();+ getPath.mockRestore();+ await rm(root, { recursive: true, force: true });+ }+ },+ );++ itMac('retries an interrupted-create sweep that failed on the next startup', async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-host-failed-sweep-'));+ const getPath = vi.spyOn(app, 'getPath').mockReturnValue(root);+ const evidencePath = path.join(root, 'ios-simulator', 'pending-create-evidence.json');+ await mkdir(path.dirname(evidencePath), { recursive: true });+ await writeFile(evidencePath, '{"version":1,"armedAt":"2026-08-11T00:00:00.000Z"}');+ const competingRegistry = new IOSSimulatorOwnershipRegistryFile(+ path.join(root, 'ios-simulator', 'ownership-registry.json'),+ );+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ recoverPendingCreatesAtStartup: vi.fn(async () => {+ throw new Error('simctl list failed');+ }),+ deleteExact: vi.fn(),+ };+ try {+ await expect(+ reconcilePersistedIOSSimulatorOwnership({ createLifecycle: () => lifecycle }),+ ).resolves.toBeUndefined();++ // Keeping the breadcrumb is what makes the retry happen; dropping it here+ // would leak the hidden marker device.+ await expect(stat(evidencePath)).resolves.toMatchObject({});+ expect(competingRegistry.acquireWriterSync()).toBe(true);+ } finally {+ competingRegistry.releaseWriterSync();+ getPath.mockRestore();+ await rm(root, { recursive: true, force: true });+ }+ });++ itMac('keeps interrupted-create evidence when a startup sweep is incomplete', async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-host-incomplete-sweep-'));+ const getPath = vi.spyOn(app, 'getPath').mockReturnValue(root);+ const evidencePath = path.join(root, 'ios-simulator', 'pending-create-evidence.json');+ await mkdir(path.dirname(evidencePath), { recursive: true });+ await writeFile(evidencePath, '{"version":1,"armedAt":"2026-08-11T00:00:00.000Z"}');+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ recoverPendingCreatesAtStartup: vi.fn(async () => ({+ recovered: [],+ complete: false,+ })),+ deleteExact: vi.fn(),+ };+ try {+ await expect(+ reconcilePersistedIOSSimulatorOwnership({ createLifecycle: () => lifecycle }),+ ).resolves.toBeUndefined();++ // The runtime observed a marker but could not safely attribute it. Keeping+ // the breadcrumb is what makes the next startup retry instead of leaking it.+ await expect(stat(evidencePath)).resolves.toMatchObject({});+ } finally {+ getPath.mockRestore();+ await rm(root, { recursive: true, force: true });+ }+ });+itMac('does not inspect or delete pending markers when the ownership registry is invalid',async () => {@@ -352,10 +450,11 @@ describe('iOS Simulator host', () => {);it('gates an already-created Host on one startup pending-create recovery', async () => {- let finishRecovery: (value: readonly string[]) => void = () => undefined;+ let finishRecovery: (value: { recovered: readonly string[]; complete: boolean }) => void =+ () => undefined;const recoverPendingCreatesAtStartup = vi.fn((_owned: readonly { udid: string; name: string }[], _signal?: AbortSignal) =>- new Promise<readonly string[]>((resolve) => {+ new Promise<{ recovered: readonly string[]; complete: boolean }>((resolve) => {finishRecovery = resolve;}),);@@ -368,28 +467,42 @@ describe('iOS Simulator host', () => {deleteExact: vi.fn(),};const inspect = vi.fn(async () => READY_REPORT);+ const pendingCreateEvidence = {+ arm: vi.fn(() => 7),+ isArmed: vi.fn(() => true),+ generation: vi.fn(() => 7),+ clearIfUnchanged: vi.fn(),+ };const host = createIOSSimulatorHost({lifecycle,runtime: { inspect },getSession: vi.fn(async (id) => localSession(id)),+ pendingCreateEvidence,});const firstCall = host.callTool('list_devices', {}, { sessionId: 'session-a' });await vi.waitFor(() => expect(recoverPendingCreatesAtStartup).toHaveBeenCalledOnce());expect(recoverPendingCreatesAtStartup).toHaveBeenCalledWith([], expect.any(AbortSignal));expect(inspect).not.toHaveBeenCalled();+ expect(pendingCreateEvidence.clearIfUnchanged).not.toHaveBeenCalled();- finishRecovery([]);+ finishRecovery({ recovered: [], complete: true });await expect(firstCall).resolves.toMatchObject({ ok: true });await expect(host.callTool('list_devices', {}, { sessionId: 'session-a' }),).resolves.toMatchObject({ ok: true });expect(recoverPendingCreatesAtStartup).toHaveBeenCalledOnce();+ // The in-process sweep retires the same breadcrumb the create path arms, so+ // a profile that stops owning devices returns to quiet startups.+ expect(pendingCreateEvidence.clearIfUnchanged).toHaveBeenCalledWith(7);});it('retries startup pending-create recovery after the ownership gate becomes available', async () => {let recoveryAllowed = false;- const recoverPendingCreatesAtStartup = vi.fn(async () => [] as readonly string[]);+ const recoverPendingCreatesAtStartup = vi.fn(async () => ({+ recovered: [] as readonly string[],+ complete: true,+ }));const lifecycle: IOSSimulatorSimctlLifecycle = {findExact: vi.fn(),bootExact: vi.fn(),@@ -1221,6 +1334,138 @@ describe('iOS Simulator host', () => {expect(driverManager.stop).not.toHaveBeenCalled();});+ it('keeps a routable binding usable while another binding cannot be reconciled', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const routable = actor.attach({+ sessionId: 'routable-session',+ worktreeRoot: '/tmp/routable-session',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ actor.attach({+ sessionId: 'unreadable-session',+ worktreeRoot: '/tmp/unreadable-session',+ sourceFingerprint: 'fingerprint-b',+ device: { ...READY_REPORT.devices[0]!, udid: 'E4DED148-43B9-4193-9D80-399976A43E08' },+ });+ const inspect = vi.fn(async () => READY_REPORT);+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect },+ getSession: vi.fn(async (id: string) => {+ if (id === 'unreadable-session') throw new Error('session row is unreadable');+ return localSession(id);+ }),+ });++ try {+ await host.reconcileOwnership();+ const afterFirstSweep = actor.getOwned('routable-session', routable.instanceId);++ // A binding whose session row cannot be read keeps the pass incomplete, so+ // the sweep runs again on the next dispatch. It must not invalidate the+ // route of a binding it observed as unchanged, or no caller could ever use+ // a generation/lease pair it just read.+ await host.reconcileOwnership();+ expect(inspect).toHaveBeenCalledTimes(2);+ const afterSecondSweep = actor.getOwned('routable-session', routable.instanceId);+ expect(afterSecondSweep.generation).toBe(afterFirstSweep.generation);+ expect(afterSecondSweep.lease.id).toBe(afterFirstSweep.lease.id);+ expect(() =>+ actor.assertRoute({+ sessionId: afterFirstSweep.sessionId,+ instanceId: afterFirstSweep.instanceId,+ generation: afterFirstSweep.generation,+ leaseId: afterFirstSweep.lease.id,+ }),+ ).not.toThrow();+ } finally {+ await host.dispose();+ }+ });++ it('normalizes inherited viewer state per binding, not per sweep', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const reconciledFirst = actor.attach({+ sessionId: 'readable-session',+ worktreeRoot: '/tmp/readable-session',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const skippedFirst = actor.attach({+ sessionId: 'late-session',+ worktreeRoot: '/tmp/late-session',+ sourceFingerprint: 'fingerprint-b',+ device: { ...READY_REPORT.devices[0]!, udid: 'E4DED148-43B9-4193-9D80-399976A43E08' },+ });+ const normalizeRequests: { instanceId: string; normalizeViewerState: boolean }[] = [];+ const reconcile = actor.reconcile.bind(actor);+ vi.spyOn(actor, 'reconcile').mockImplementation((...args) => {+ normalizeRequests.push({+ instanceId: args[0],+ normalizeViewerState: args[5]?.normalizeViewerState === true,+ });+ return reconcile(...args);+ });+ let lateSessionReadable = false;+ const inspect = vi.fn(async () => READY_REPORT);+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ runtime: { inspect },+ getSession: vi.fn(async (id: string) => {+ if (id === 'late-session' && !lateSessionReadable) {+ throw new Error('session row is unreadable');+ }+ return localSession(id);+ }),+ });++ try {+ await host.reconcileOwnership();+ // The skipped binding never reached a reconcile, so nothing corrected the+ // viewer state it inherited from the previous process.+ expect(normalizeRequests).toEqual([+ { instanceId: reconciledFirst.instanceId, normalizeViewerState: true },+ ]);++ lateSessionReadable = true;+ normalizeRequests.length = 0;+ await host.reconcileOwnership();+ expect(inspect).toHaveBeenCalledTimes(2);+ // The retry must still normalize the binding it skipped, while leaving the+ // already-reconciled one alone so a viewer that attached meanwhile survives.+ expect(normalizeRequests).toEqual([+ { instanceId: reconciledFirst.instanceId, normalizeViewerState: false },+ { instanceId: skippedFirst.instanceId, normalizeViewerState: true },+ ]);+ } finally {+ vi.restoreAllMocks();+ await host.dispose();+ }+ });+it.each(['Booted', 'Booting'] as const)('restores scheduler occupancy for a persisted %s device',async (deviceState) => {diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.tsindex 4b0eec153c..7f361ab95e 100644--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts@@ -21,6 +21,7 @@ import {IOSSimulatorInstanceError,IOSSimulatorOwnershipStore,IOSSimulatorOwnershipRegistryFile,+ IOSSimulatorPendingCreateEvidenceFile,IOSSimulatorProjectBuildError,IOSSimulatorProjectBuilder,IOSSimulatorResourceScheduler,@@ -49,6 +50,8 @@ import {type IOSSimulatorMutationRoute,type IOSSimulatorNativeSidecarDriver,type IOSSimulatorLatestH264Frame,+ type IOSSimulatorPendingCreateEvidence,+ type IOSSimulatorPendingCreateEvidenceStore,type IOSSimulatorProjectBuildResult,type IOSSimulatorRuntime,type IOSSimulatorSimctlLifecycle,@@ -122,6 +125,16 @@ interface IOSSimulatorSessionSnapshot {status?: 'active' | 'archived' | 'deleted' | null;}+interface IOSSimulatorPersistedInstanceReconcileResult {+ /** False when this binding still needs another reconcile pass. */+ complete: boolean;+ /**+ * True once this pass either reconciled the binding or removed it, meaning a+ * later pass must no longer treat its persisted `viewerState` as inherited.+ */+ viewerStateHandled: boolean;+}+interface IOSSimulatorPluginStatusReadOptions {/** Test seam; production uses the active Main-owned task database. */getSession?: (sessionId: string) => Promise<IOSSimulatorSessionSnapshot | null>;@@ -200,6 +213,12 @@ export interface IOSSimulatorHostOptions {resourceScheduler?: IOSSimulatorResourceScheduler;/** Fail-closed gate supplied by the persisted registry owner. */canReconcilePendingCreates?: () => boolean;+ /**+ * Profile-scoped interrupted-create breadcrumb shared with the injected+ * lifecycle. A completed sweep retires it so later startups can skip the+ * CoreSimulator probe entirely.+ */+ pendingCreateEvidence?: IOSSimulatorPendingCreateEvidenceStore;/** Main-owned account generation used to scope persisted ownership reconciliation. */getOwnerScopeKey?: () => string;/** Fail closed while the active account runtime is being replaced. */@@ -444,14 +463,34 @@ export function createRegistryBackedIOSSimulatorDeviceGrantStore(});}+/**+ * Interrupted-create evidence lives beside the ownership registry, inside the+ * active Cindy profile. Its presence is the only reason a profile without+ * persisted ownership still needs a CoreSimulator sweep, so keeping it accurate+ * is what keeps Xcode consent prompts tied to real simulator use.+ */+function createDefaultPendingCreateEvidence(+ registry: IOSSimulatorOwnershipRegistryFile,+): IOSSimulatorPendingCreateEvidenceStore {+ const filePath = path.join(path.dirname(registry.filePath), 'pending-create-evidence.json');+ return new IOSSimulatorPendingCreateEvidenceFile(filePath, {+ onError: (error) =>+ logger.warn('iOS Simulator interrupted-create evidence could not be updated', {+ filePath: redact(filePath),+ error: error instanceof Error ? error.message : String(error),+ }),+ });+}+function createProfileScopedIOSSimulatorLifecycle(registry: IOSSimulatorOwnershipRegistryFile,+ pendingCreateEvidence: IOSSimulatorPendingCreateEvidence,): IOSSimulatorSimctlLifecycle {const createMarkerNamespace = createHash('sha256').update(path.resolve(registry.filePath)).digest('hex').slice(0, 16);- return createIOSSimulatorSimctlLifecycle({ createMarkerNamespace });+ return createIOSSimulatorSimctlLifecycle({ createMarkerNamespace, pendingCreateEvidence });}const STARTUP_PENDING_CREATE_RECOVERY_TIMEOUT_MS = 6_000;@@ -459,9 +498,15 @@ const STARTUP_PENDING_CREATE_RECOVERY_TIMEOUT_MS = 6_000;async function recoverProfilePendingCreatesAtStartup(lifecycle: IOSSimulatorSimctlLifecycle,persistedInstances: readonly IOSSimulatorInstance[],- signal?: AbortSignal,+ options: {+ signal?: AbortSignal;+ /** Retired only after a completed sweep proves no marker is left. */+ evidence?: IOSSimulatorPendingCreateEvidenceStore | null;+ } = {},): Promise<void> {if (!lifecycle.recoverPendingCreatesAtStartup) return;+ const { signal, evidence } = options;+ const evidenceGeneration = evidence?.generation() ?? 0;const controller = new AbortController();const abortFromParent = (): void => controller.abort(signal?.reason);if (signal?.aborted) abortFromParent();@@ -472,13 +517,17 @@ async function recoverProfilePendingCreatesAtStartup();timer.unref?.();try {- await lifecycle.recoverPendingCreatesAtStartup(+ const recovery = await lifecycle.recoverPendingCreatesAtStartup(persistedInstances.map((instance) => ({udid: instance.simulatorUdid,name: instance.simulatorName,})),controller.signal,);+ // A completed sweep proves this profile holds no leftover create marker.+ // Retire the breadcrumb so the next startup stays off xcrun — unless+ // another create armed it while this sweep was still running.+ if (recovery.complete) evidence?.clearIfUnchanged(evidenceGeneration);} 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@@ -1057,7 +1106,14 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Iconst getOwnerScopeKey = options.getOwnerScopeKey ?? activeOwnerScopeKey;const isOwnerBoundaryPending =options.isOwnerBoundaryPending ?? isAppSessionBoundaryPending;+ const pendingCreateEvidence = options.pendingCreateEvidence ?? null;let ownershipReconciledScopeKey: string | null = null;+ // Persisted `viewerState` can only be stale on the first sweep that actually+ // reaches a binding; after that a detached value would be this process's own+ // truth. Tracked per binding, because an incomplete sweep can skip one+ // binding entirely while normalizing the rest.+ let viewerStateNormalizedScopeKey: string | null = null;+ const viewerStateNormalizedInstanceIds = new Set<string>();let ownershipReconcilePromise: { scopeKey: string; promise: Promise<void> } | null = null;let pendingCreateReconcileController: AbortController | null = null;let pendingCreateReconcilePromise: Promise<unknown> | null = null;@@ -2322,11 +2378,13 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Iasync function reconcilePersistedInstance(snapshot: IOSSimulatorInstance,devices: ReadonlyMap<string, IOSSimulatorEnvironmentReport['devices'][number]>,- ): Promise<boolean> {+ normalizeViewerState: boolean,+ ): Promise<IOSSimulatorPersistedInstanceReconcileResult> {const instance = actor.list(snapshot.sessionId).find((candidate) => candidate.instanceId === snapshot.instanceId);- if (!instance) return true;+ // A binding that no longer exists has no inherited viewer state to correct.+ if (!instance) return { complete: true, viewerStateHandled: true };let complete = true;let driverRuntimeRecovered = await cleanupOrphanedDriverRuntime(instance);@@ -2350,7 +2408,9 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): IinstanceId: instance.instanceId,error: error instanceof Error ? error.message : String(error),});- return false;+ // This binding was skipped before any reconcile, so its inherited viewer+ // state is still unhandled and the retry must normalize it.+ return { complete: false, viewerStateHandled: false };}if (!session || session.status === 'deleted' || session.status === 'archived') {const released = await actor.runOwnershipCleanup(@@ -2358,7 +2418,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Iinstance.sessionId,(owned, signal) => releaseStaleBinding(owned, device, true, signal),);- return released && complete;+ return { complete: released && complete, viewerStateHandled: released };}if (session.remoteHostId || !device) {const runtimeReleased = await releaseInstanceRuntime(instance);@@ -2372,8 +2432,9 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Idevice ? (deviceState === 'booted' ? 'ready' : 'stopped') : 'error','degraded',session.remoteHostId ? 'UNSUPPORTED_SESSION_KIND' : 'ORPHANED_DEVICE',+ { normalizeViewerState },);- return complete;+ return { complete, viewerStateHandled: true };}const reconciledDeviceState = deviceState ?? 'unknown';if (reconciledDeviceState === 'shutdown') {@@ -2411,14 +2472,43 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I? 'healthy': 'recovering',driverRuntimeRecovered ? null : 'WDA_UNAVAILABLE',- { preserveDetachGrace: shouldResumeDetachGrace },+ { preserveDetachGrace: shouldResumeDetachGrace, normalizeViewerState },);if (shouldResumeDetachGrace && driverRuntimeRecovered && complete) {await actor.resumeDetachGrace(reconciled.instanceId, reconciled.sessionId, () =>resourceScheduler.markStopped(reconciled.instanceId),);}- return complete;+ return { complete, viewerStateHandled: true };+ }++ function isViewerStateNormalized(scopeKey: string, instanceId: string): boolean {+ return (+ viewerStateNormalizedScopeKey === scopeKey &&+ viewerStateNormalizedInstanceIds.has(instanceId)+ );+ }++ function markViewerStateNormalized(scopeKey: string, instanceId: string): void {+ // An old in-flight pass must not suppress the new owner's normalization.+ if (isOwnerBoundaryPending() || getOwnerScopeKey() !== scopeKey) return;+ if (viewerStateNormalizedScopeKey !== scopeKey) {+ viewerStateNormalizedInstanceIds.clear();+ viewerStateNormalizedScopeKey = scopeKey;+ }+ viewerStateNormalizedInstanceIds.add(instanceId);+ }++ /** Keep the per-binding latch bounded by the bindings that still exist. */+ function retainViewerStateNormalized(+ scopeKey: string,+ persisted: readonly IOSSimulatorInstance[],+ ): void {+ if (viewerStateNormalizedScopeKey !== scopeKey) return;+ const live = new Set(persisted.map((instance) => instance.instanceId));+ for (const instanceId of viewerStateNormalizedInstanceIds) {+ if (!live.has(instanceId)) viewerStateNormalizedInstanceIds.delete(instanceId);+ }}async function reconcilePersistedOwnership(): Promise<void> {@@ -2464,11 +2554,10 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I} else {startupPendingCreateRecoveryAttempted = true;const controller = new AbortController();- const recovery = recoverProfilePendingCreatesAtStartup(- lifecycle,- actor.listAll(),- controller.signal,- );+ const recovery = recoverProfilePendingCreatesAtStartup(lifecycle, actor.listAll(), {+ signal: controller.signal,+ evidence: pendingCreateEvidence,+ });pendingCreateReconcileController = controller;pendingCreateReconcilePromise = recovery;try {@@ -2523,11 +2612,22 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Iconst devices = new Map(environment.devices.map((device) => [device.udid.toUpperCase(), device]),);- for (const snapshot of actor.listAll()) {- const instanceComplete = await withSessionLock(snapshot.sessionId, () =>- reconcilePersistedInstance(snapshot, devices),+ const persisted = actor.listAll();+ retainViewerStateNormalized(scopeKey, persisted);+ for (const snapshot of persisted) {+ const normalizeViewerState = !isViewerStateNormalized(scopeKey, snapshot.instanceId);+ const instanceResult = await withSessionLock(snapshot.sessionId, () =>+ reconcilePersistedInstance(snapshot, devices, normalizeViewerState),);- if (!instanceComplete) complete = false;+ if (!instanceResult.complete) complete = false;+ // Latch per binding, not per pass: a binding skipped before its reconcile+ // (e.g. its session row was unreadable) still carries viewer state+ // inherited from a dead process, and the retry has to correct it. A+ // binding that was reconciled must not be normalized again, or the retry+ // would kick a viewer that attached in the meantime.+ if (instanceResult.viewerStateHandled) {+ markViewerStateNormalized(scopeKey, snapshot.instanceId);+ }}// Every DB/session read above belongs to the captured owner generation.// Never latch it across an account boundary or let an old in-flight pass@@ -6364,6 +6464,7 @@ function installDefaultIOSSimulatorHost(lifecycle: IOSSimulatorSimctlLifecycle,persistedActor: ReturnType<typeof createDefaultActor>,registry: IOSSimulatorOwnershipRegistryFile,+ pendingCreateEvidence: IOSSimulatorPendingCreateEvidenceStore,): IOSSimulatorHost {if (defaultIOSSimulatorRuntime) {persistedActor.release();@@ -6381,6 +6482,7 @@ function installDefaultIOSSimulatorHost(actor: persistedActor.actor,grantStore: createRegistryBackedIOSSimulatorDeviceGrantStore(registry),canReconcilePendingCreates: persistedActor.canReconcilePendingCreates,+ pendingCreateEvidence,driverManager: createDefaultDriverManager(),});configureIOSSimulatorRendererAccessRevocationObserver((grants) => {@@ -6419,9 +6521,15 @@ export function initializeIOSSimulatorHost(): IOSSimulatorHost {}const registry = createDefaultOwnershipRegistry();- const lifecycle = createProfileScopedIOSSimulatorLifecycle(registry);+ const pendingCreateEvidence = createDefaultPendingCreateEvidence(registry);+ const lifecycle = createProfileScopedIOSSimulatorLifecycle(registry, pendingCreateEvidence);const persistedActor = createDefaultActor(lifecycle, registry);- return installDefaultIOSSimulatorHost(lifecycle, persistedActor, registry);+ return installDefaultIOSSimulatorHost(+ lifecycle,+ persistedActor,+ registry,+ pendingCreateEvidence,+ );}function currentIOSSimulatorHost(): IOSSimulatorHost | null {@@ -6531,9 +6639,15 @@ export function reconcileIOSSimulatorOwnership(): Promise<void> {/*** Startup recovery performs one bounded, profile-scoped pending-create sweep- * even when ownership is empty, then releases the writer lease without+ * when this profile can still hold a create marker — persisted ownership, or an+ * armed interrupted-create breadcrumb — 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.+ *+ * A profile with neither is provably clean, so startup performs no `xcrun` /+ * CoreSimulator access at all. That keeps macOS Xcode consent prompts attached+ * to the moment the user actually opens the simulator, in the same spirit as+ * the safeStorage probe rule in `docs/dev-rules/credentials-and-local-storage.md`.*/export interface IOSSimulatorPersistedOwnershipRecoveryOptions {/** Test seam; production always derives a profile-scoped lifecycle. */@@ -6558,15 +6672,32 @@ export async function reconcilePersistedIOSSimulatorOwnership();}const persistedInstances = registry.loadSync();+ const pendingCreateEvidence = createDefaultPendingCreateEvidence(registry);+ if (persistedInstances.length === 0 && !pendingCreateEvidence.isArmed()) {+ // Nothing owned and no interrupted create: sweeping here would spawn+ // xcrun on a profile that never used the simulator, which is exactly the+ // startup-time Xcode permission prompt users report.+ logger.debug('Skipped iOS Simulator startup recovery for a profile with no simulator state');+ registry.releaseWriterSync();+ return;+ }const lifecycle =- options.createLifecycle?.(registry) ?? createProfileScopedIOSSimulatorLifecycle(registry);+ options.createLifecycle?.(registry) ??+ createProfileScopedIOSSimulatorLifecycle(registry, pendingCreateEvidence);if (persistedInstances.length === 0) {- await recoverProfilePendingCreatesAtStartup(lifecycle, persistedInstances);+ await recoverProfilePendingCreatesAtStartup(lifecycle, persistedInstances, {+ evidence: pendingCreateEvidence,+ });registry.releaseWriterSync();return;}const persistedActor = createDefaultActor(lifecycle, registry);- const host = installDefaultIOSSimulatorHost(lifecycle, persistedActor, registry);+ const host = installDefaultIOSSimulatorHost(+ lifecycle,+ persistedActor,+ registry,+ pendingCreateEvidence,+ );registryTransferred = true;await host.reconcileOwnership();} catch (error) {@@ -6628,9 +6759,15 @@ export function cleanupIOSSimulatorRemovedSession(sessionId: string): Promise<vo// Keep the same writer lease from the authoritative read through Host// installation. Releasing and reacquiring here would reopen the race with// another Cindy process attaching this task while it is being removed.- const lifecycle = createProfileScopedIOSSimulatorLifecycle(registry);+ const pendingCreateEvidence = createDefaultPendingCreateEvidence(registry);+ const lifecycle = createProfileScopedIOSSimulatorLifecycle(registry, pendingCreateEvidence);const persistedActor = createDefaultActor(lifecycle, registry);- const host = installDefaultIOSSimulatorHost(lifecycle, persistedActor, registry);+ const host = installDefaultIOSSimulatorHost(+ lifecycle,+ persistedActor,+ registry,+ pendingCreateEvidence,+ );registryTransferred = true;return host.cleanupRemovedSession(normalizedSessionId);} catch (error) {diff --git a/packages/ios-simulator-runtime/src/index.ts b/packages/ios-simulator-runtime/src/index.tsindex f585674628..fe7ddbf0ac 100644--- a/packages/ios-simulator-runtime/src/index.ts+++ b/packages/ios-simulator-runtime/src/index.ts@@ -24,6 +24,7 @@ export * from "./native-sidecar/sandbox.js";export * from "./native-sidecar/layout.js";export * from "./ownership-store.js";export * from "./ownership-registry-file.js";+export * from "./pending-create-evidence-file.js";export * from "./project-adapter.js";export * from "./runtime.js";export * from "./resource-scheduler.js";diff --git a/packages/ios-simulator-runtime/src/instance-actor.test.ts b/packages/ios-simulator-runtime/src/instance-actor.test.tsindex fe15668d4b..bf6ab6fa82 100644--- a/packages/ios-simulator-runtime/src/instance-actor.test.ts+++ b/packages/ios-simulator-runtime/src/instance-actor.test.ts@@ -94,6 +94,85 @@ function createHarness(}describe("IOSSimulatorInstanceActor", () => {+ it("keeps the current route when a reconcile observes no change", () => {+ const harness = createHarness();+ const before = harness.instance;++ const reconciled = harness.actor.reconcile(+ before.instanceId,+ before.sessionId,+ before.lifecycleState,+ before.healthState,+ before.errorCode,+ );++ expect(reconciled.generation).toBe(before.generation);+ expect(reconciled.lease.id).toBe(before.lease.id);+ // CoreSimulator says nothing about viewer attachment, so an unchanged+ // binding must not have a live viewer kicked out from under it.+ expect(reconciled.viewerState).toBe("attached");+ expect(() =>+ harness.actor.assertRoute(harness.route(before)),+ ).not.toThrow();+ });++ it("renews an expired lease on an unchanged reconcile without issuing a new generation", () => {+ const harness = createHarness();+ const before = harness.instance;+ // A persisted lease restored from a previous process, or idle past its TTL.+ harness.setNow(Date.parse(before.lease.expiresAt) + 1);++ const reconciled = harness.actor.reconcile(+ before.instanceId,+ before.sessionId,+ before.lifecycleState,+ before.healthState,+ before.errorCode,+ );++ // Without this, every later sweep stays unchanged too, so the binding could+ // never produce a usable route again.+ expect(reconciled.generation).toBe(before.generation);+ expect(reconciled.lease.id).not.toBe(before.lease.id);+ expect(reconciled.viewerState).toBe(before.viewerState);+ expect(() =>+ harness.actor.assertRoute(harness.route(reconciled)),+ ).not.toThrow();+ });++ it("issues a new route when the observed state changed", () => {+ const harness = createHarness();+ const before = harness.instance;++ const reconciled = harness.actor.reconcile(+ before.instanceId,+ before.sessionId,+ "ready",+ before.healthState,+ before.errorCode,+ );++ expect(reconciled.generation).toBe(before.generation + 1);+ expect(reconciled.lease.id).not.toBe(before.lease.id);+ expect(reconciled.viewerState).toBe("detached");+ });++ it("normalizes a viewer state inherited from a dead process", () => {+ const harness = createHarness();+ const before = harness.instance;++ const reconciled = harness.actor.reconcile(+ before.instanceId,+ before.sessionId,+ before.lifecycleState,+ before.healthState,+ before.errorCode,+ { normalizeViewerState: true },+ );++ expect(reconciled.viewerState).toBe("detached");+ });+it("increments generation across exact start and stop operations", async () => {const harness = createHarness();const started = await harness.actor.start(harness.route());diff --git a/packages/ios-simulator-runtime/src/instance-actor.ts b/packages/ios-simulator-runtime/src/instance-actor.tsindex a671bfdbaa..e0c2eabd54 100644--- a/packages/ios-simulator-runtime/src/instance-actor.ts+++ b/packages/ios-simulator-runtime/src/instance-actor.ts@@ -40,6 +40,13 @@ type IOSSimulatorCreateInput = Omit<IOSSimulatorAttachInput, "device"> & {export interface IOSSimulatorReconcileOptions {preserveDetachGrace?: boolean;+ /**+ * Correct a `viewerState` inherited from a process that is already gone. Only+ * the first sweep of an owner generation knows the persisted value cannot+ * describe a live viewer; later sweeps observe CoreSimulator alone and have no+ * evidence about viewer attachment, so they must leave it untouched.+ */+ normalizeViewerState?: boolean;}export type IOSSimulatorMutationSource = "agent" | "user";@@ -291,6 +298,34 @@ export class IOSSimulatorInstanceActor {options: IOSSimulatorReconcileOptions = {},): IOSSimulatorInstance {const current = this.#store.requireOwned(instanceId, sessionId);+ // The ownership sweep runs ahead of every tool dispatch, so a reconcile that+ // observed no change must not issue a new route: bumping the generation and+ // minting a new lease invalidates the (generation, leaseId) pair the caller+ // just read, which no caller can ever win against. Viewer attachment is+ // process-local and never observed by CoreSimulator, so an unchanged binding+ // keeps its viewer as well — see `normalizeViewerState` for the one sweep+ // that is allowed to correct a value inherited from a dead process. A+ // pending detach grace is excluded: re-arming that deadline in this process+ // is itself a transition, so it still issues a fresh route.+ const unchanged =+ options.preserveDetachGrace !== true &&+ current.graceExpiresAt === null &&+ current.lifecycleState === lifecycleState &&+ current.healthState === healthState &&+ current.errorCode === errorCode;+ const staleViewerState =+ options.normalizeViewerState === true && current.viewerState !== "detached";+ if (unchanged && !staleViewerState) {+ // Preserving the route must not mean preserving a lease that can no longer+ // authorize one. A persisted lease can already be expired here — restored+ // from a previous process, or idle past its TTL — and because every later+ // sweep is unchanged too, nothing would ever renew it: reads that hand back+ // a full route without heartbeating (`doctor`) would then fail+ // LEASE_EXPIRED forever. `heartbeat` is exactly the needed shape: it leaves+ // a healthy lease and its id untouched, extends one close to expiry under+ // the same id, and mints a new id only when the old one is already unusable.+ return this.#store.heartbeat(instanceId, sessionId);+ }this.#cancelActiveAgentMutation(instanceId);this.#abortLifecycleStartsForInstance(instanceId);const renewed = this.#store.renew(instanceId, sessionId, {diff --git a/packages/ios-simulator-runtime/src/pending-create-evidence-file.test.ts b/packages/ios-simulator-runtime/src/pending-create-evidence-file.test.tsnew file mode 100644index 0000000000..ad6f8509ae--- /dev/null+++ b/packages/ios-simulator-runtime/src/pending-create-evidence-file.test.ts@@ -0,0 +1,70 @@+import { mkdtemp, rm, stat } from "node:fs/promises";+import os from "node:os";+import path from "node:path";++import { describe, expect, it, vi } from "vitest";++import { IOSSimulatorPendingCreateEvidenceFile } from "./pending-create-evidence-file.js";++describe("IOSSimulatorPendingCreateEvidenceFile", () => {+ it("stays unarmed until a create arms it, then clears on a matching generation", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-evidence-"));+ try {+ const evidence = new IOSSimulatorPendingCreateEvidenceFile(+ path.join(root, "nested", "pending-create-evidence.json"),+ );+ expect(evidence.isArmed()).toBe(false);+ expect(evidence.generation()).toBe(0);++ // The armed generation goes back to the caller so it can retire exactly+ // its own evidence later.+ expect(evidence.arm()).toBe(1);+ expect(evidence.isArmed()).toBe(true);+ expect(evidence.generation()).toBe(1);+ if (process.platform !== "win32") {+ expect((await stat(evidence.filePath)).mode & 0o777).toBe(0o600);+ }++ evidence.clearIfUnchanged(evidence.generation());+ expect(evidence.isArmed()).toBe(false);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });++ it("keeps evidence armed by a create that started after the sweep captured its generation", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-evidence-"));+ try {+ const evidence = new IOSSimulatorPendingCreateEvidenceFile(+ path.join(root, "pending-create-evidence.json"),+ );+ evidence.arm();+ const sweepGeneration = evidence.generation();++ // A concurrent create arms again while the sweep is still running.+ evidence.arm();+ evidence.clearIfUnchanged(sweepGeneration);++ expect(evidence.isArmed()).toBe(true);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });++ it("reports a failed arm instead of failing the create", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-evidence-"));+ try {+ const onError = vi.fn();+ // A directory in place of the marker file makes every write fail.+ const evidence = new IOSSimulatorPendingCreateEvidenceFile(root, {+ onError,+ });++ expect(() => evidence.arm()).not.toThrow();+ expect(onError).toHaveBeenCalledOnce();+ expect(evidence.generation()).toBe(1);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });+});diff --git a/packages/ios-simulator-runtime/src/pending-create-evidence-file.ts b/packages/ios-simulator-runtime/src/pending-create-evidence-file.tsnew file mode 100644index 0000000000..4436faa3a8--- /dev/null+++ b/packages/ios-simulator-runtime/src/pending-create-evidence-file.ts@@ -0,0 +1,108 @@+import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";+import path from "node:path";++const EVIDENCE_VERSION = 1;++/**+ * Create-side view of the interrupted-create breadcrumb. `createExact` arms it+ * before `simctl create` can commit a device, so a crash between the create and+ * the ownership write still leaves proof that this profile may hold a hidden+ * create marker.+ */+export interface IOSSimulatorPendingCreateEvidence {+ /** Arms the breadcrumb and returns the generation that armed it. */+ arm(): number;+ /**+ * Retires the breadcrumb, but only when no later create armed it. Callers may+ * only invoke this from a path that proves their own marker no longer exists.+ */+ clearIfUnchanged(generation: number): void;+}++/**+ * Recovery-side view. A profile with no persisted ownership and no armed+ * evidence provably has nothing to sweep, so the Host can skip the+ * CoreSimulator probe entirely instead of running `simctl` on every startup.+ */+export interface IOSSimulatorPendingCreateEvidenceStore+ extends IOSSimulatorPendingCreateEvidence {+ isArmed(): boolean;+ /**+ * Monotonic arm counter. A sweep captures it before it starts and passes it+ * back to `clearIfUnchanged`, so a create issued while the sweep was running+ * never has its evidence retired by that sweep.+ */+ generation(): number;+}++export interface IOSSimulatorPendingCreateEvidenceFileOptions {+ /** Best-effort persistence seam: failures are reported, never thrown. */+ onError?: (error: unknown) => void;+}++/**+ * Presence-only marker file kept beside the profile ownership registry. Only+ * existence is authoritative; the JSON body is human-facing debug context and+ * is never parsed back.+ *+ * Concurrency: every mutation happens under the profile ownership writer lease+ * (creates require the persisted actor, sweeps run inside recovery), so no+ * cross-process locking of its own is required.+ */+export class IOSSimulatorPendingCreateEvidenceFile+ implements IOSSimulatorPendingCreateEvidenceStore+{+ readonly #filePath: string;+ readonly #onError: ((error: unknown) => void) | null;+ #generation = 0;++ constructor(+ filePath: string,+ options: IOSSimulatorPendingCreateEvidenceFileOptions = {},+ ) {+ this.#filePath = filePath;+ this.#onError = options.onError ?? null;+ }++ get filePath(): string {+ return this.#filePath;+ }++ arm(): number {+ this.#generation += 1;+ try {+ mkdirSync(path.dirname(this.#filePath), { recursive: true });+ writeFileSync(+ this.#filePath,+ JSON.stringify({+ version: EVIDENCE_VERSION,+ armedAt: new Date().toISOString(),+ }),+ { encoding: "utf8", mode: 0o600 },+ );+ } catch (error) {+ // A missing breadcrumb only defers marker cleanup to the next simulator+ // use. Failing the create the user actually asked for would be worse.+ this.#onError?.(error);+ }+ return this.#generation;+ }++ isArmed(): boolean {+ return existsSync(this.#filePath);+ }++ generation(): number {+ return this.#generation;+ }++ clearIfUnchanged(generation: number): void {+ if (generation !== this.#generation) return;+ try {+ rmSync(this.#filePath, { force: true });+ } catch (error) {+ // Keeping stale evidence only costs one extra sweep on the next startup.+ this.#onError?.(error);+ }+ }+}diff --git a/packages/ios-simulator-runtime/src/simctl-lifecycle.test.ts b/packages/ios-simulator-runtime/src/simctl-lifecycle.test.tsindex dc2622baca..9440150a56 100644--- a/packages/ios-simulator-runtime/src/simctl-lifecycle.test.ts+++ b/packages/ios-simulator-runtime/src/simctl-lifecycle.test.ts@@ -16,7 +16,8 @@ function devicesJson(udid: string;name: string;state?: string;- deviceTypeIdentifier?: string;+ /** `null` reproduces a listing that omits the device type. */+ deviceTypeIdentifier?: string | null;}>,): string {return JSON.stringify({@@ -33,7 +34,11 @@ function devicesJson(...device,state: device.state ?? "Shutdown",isAvailable: true,- deviceTypeIdentifier: device.deviceTypeIdentifier ?? DEVICE_TYPE,+ ...(device.deviceTypeIdentifier === null+ ? {}+ : {+ deviceTypeIdentifier: device.deviceTypeIdentifier ?? DEVICE_TYPE,+ }),})),},});@@ -43,6 +48,23 @@ function listJson(state: string): string {return devicesJson([{ udid: UDID, name: "iPhone 17 Pro", state }]);}+/** Records the arm/retire calls a lifecycle makes on the create breadcrumb. */+function createEvidenceSpy(events?: string[]) {+ const spy = {+ armed: 0,+ cleared: [] as number[],+ arm(): number {+ spy.armed += 1;+ events?.push("arm");+ return spy.armed;+ },+ clearIfUnchanged(generation: number): void {+ spy.cleared.push(generation);+ },+ };+ return spy;+}+describe("createIOSSimulatorSimctlLifecycle", () => {it("boots and polls an exact UDID until bootstatus succeeds", async () => {let now = 0;@@ -416,7 +438,7 @@ describe("createIOSSimulatorSimctlLifecycle", () => {await expect(lifecycle.recoverPendingCreatesAtStartup?.([]),- ).resolves.toEqual([UDID]);+ ).resolves.toEqual({ recovered: [UDID], complete: true });expect(run.mock.calls.filter(([, args]) => args[1] === "delete")).toEqual([expect.arrayContaining(["/usr/bin/xcrun", ["simctl", "delete", UDID]]),]);@@ -518,7 +540,7 @@ describe("createIOSSimulatorSimctlLifecycle", () => {lifecycle.recoverPendingCreatesAtStartup?.([{ udid: ownedUdid, name: "Cindy Restored iPhone" },]),- ).resolves.toEqual([UDID, ownedUdid]);+ ).resolves.toEqual({ recovered: [UDID, ownedUdid], complete: true });expect(run.mock.calls.filter(([, args]) => args[1] === "delete")).toEqual([expect.arrayContaining(["/usr/bin/xcrun", ["simctl", "delete", UDID]]),]);@@ -569,7 +591,43 @@ describe("createIOSSimulatorSimctlLifecycle", () => {await expect(lifecycle.recoverPendingCreatesAtStartup?.([]),- ).resolves.toEqual([]);+ ).resolves.toEqual({ recovered: [], complete: false });+ expect(+ run.mock.calls.filter(([, args]) => args[1] === "list"),+ ).toHaveLength(2);+ expect(run.mock.calls.filter(([, args]) => args[1] === "delete")).toEqual(+ [],+ );+ });++ it("reports incomplete startup recovery when marker metadata is missing", async () => {+ const markerName =+ "__CindyPending__profilealpha__11111111-2222-4333-8444-555555555555";+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(+ async (_command, args) => {+ if (args[1] === "list") {+ return {+ stdout: devicesJson([+ { udid: UDID, name: markerName, deviceTypeIdentifier: null },+ ]),+ 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({ recovered: [], complete: false });expect(run.mock.calls.filter(([, args]) => args[1] === "list"),).toHaveLength(2);@@ -578,6 +636,58 @@ describe("createIOSSimulatorSimctlLifecycle", () => {);});+ it("does not let a later settled create retire older incomplete startup evidence", async () => {+ const oldMarkerName =+ "__CindyPending__profilealpha__11111111-2222-4333-8444-555555555555";+ const newUdid = "2A9D41E0-E031-4AD0-A8B5-847480802E8E";+ let listCount = 0;+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(+ async (_command, args) => {+ if (args[1] === "list") {+ listCount += 1;+ return {+ stdout: devicesJson([+ {+ udid: UDID,+ name: oldMarkerName,+ deviceTypeIdentifier: null,+ },+ ]),+ stderr: "",+ exitCode: 0,+ };+ }+ if (args[1] === "create") {+ return { stdout: `${newUdid}\n`, stderr: "", exitCode: 0 };+ }+ if (args[1] === "rename") {+ return { stdout: "", stderr: "", exitCode: 0 };+ }+ throw new Error(`unexpected ${args.join(" ")}`);+ },+ );+ const evidence = createEvidenceSpy();+ const lifecycle = createIOSSimulatorSimctlLifecycle({+ commandRunner: { run },+ createMarkerNamespace: "profilealpha",+ pendingCreateEvidence: evidence,+ });++ await expect(+ lifecycle.recoverPendingCreatesAtStartup?.([]),+ ).resolves.toEqual({ recovered: [], complete: false });+ expect(listCount).toBe(2);++ const created = await lifecycle.createExact({+ name: "Cindy iPhone",+ deviceTypeIdentifier: DEVICE_TYPE,+ runtimeIdentifier: RUNTIME,+ });+ await lifecycle.renameExact?.(created.udid, "Cindy iPhone");++ expect(evidence.cleared).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");@@ -969,4 +1079,222 @@ describe("createIOSSimulatorSimctlLifecycle", () => {});expect(run).not.toHaveBeenCalled();});++ it("arms interrupted-create evidence before issuing simctl create", async () => {+ const events: string[] = [];+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(+ async (_command, args) => {+ events.push(`run:${args[1]}`);+ if (args[1] === "create") {+ return { stdout: "", stderr: "interrupted", exitCode: 1 };+ }+ return { stdout: devicesJson([]), stderr: "", exitCode: 0 };+ },+ );+ const evidence = createEvidenceSpy(events);+ const lifecycle = createIOSSimulatorSimctlLifecycle({+ commandRunner: { run },+ createMarkerNamespace: "testprofile",+ pendingCreateEvidence: evidence,+ });++ // A create that fails once CoreSimulator may already have committed the+ // device must still leave startup-recovery evidence behind.+ await expect(+ lifecycle.createExact({+ name: "Cindy iPhone",+ deviceTypeIdentifier: DEVICE_TYPE,+ runtimeIdentifier: RUNTIME,+ }),+ ).rejects.toMatchObject({ code: "SIMULATOR_CREATE_FAILED" });++ expect(events[0]).toBe("arm");+ expect(events).toContain("run:create");+ // The post-create list proved nothing was committed, so the profile must not+ // keep paying a startup sweep that has nothing to clean.+ expect(evidence.cleared).toEqual([1]);+ });++ it("keeps evidence when a failed create cannot be verified", async () => {+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(async (_command, args) => {+ if (args[1] === "create") {+ return { stdout: "", stderr: "interrupted", exitCode: 1 };+ }+ // The verification list itself fails: nothing is proven either way.+ return { stdout: "", stderr: "list failed", exitCode: 1 };+ });+ const evidence = createEvidenceSpy();+ const lifecycle = createIOSSimulatorSimctlLifecycle({+ commandRunner: { run },+ createMarkerNamespace: "testprofile",+ pendingCreateEvidence: evidence,+ });++ await expect(+ lifecycle.createExact({+ name: "Cindy iPhone",+ deviceTypeIdentifier: DEVICE_TYPE,+ runtimeIdentifier: RUNTIME,+ }),+ ).rejects.toMatchObject({ code: "SIMULATOR_CREATE_FAILED" });++ expect(evidence.armed).toBe(1);+ expect(evidence.cleared).toEqual([]);+ });++ it("keeps evidence when a marker device exists but cannot be attributed", async () => {+ let markerName = "";+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(async (_command, args) => {+ if (args[1] === "create") {+ markerName = args[2]!;+ return { stdout: "", stderr: "interrupted", exitCode: 1 };+ }+ if (args[1] === "list") {+ // The device really was committed under this exact random marker, but the+ // listing omits its device type, so it cannot be uniquely recovered.+ return {+ stdout: devicesJson([+ { udid: UDID, name: markerName, deviceTypeIdentifier: null },+ ]),+ stderr: "",+ exitCode: 0,+ };+ }+ return { stdout: "", stderr: "", exitCode: 0 };+ });+ const evidence = createEvidenceSpy();+ const lifecycle = createIOSSimulatorSimctlLifecycle({+ commandRunner: { run },+ createMarkerNamespace: "testprofile",+ pendingCreateEvidence: evidence,+ });++ await expect(+ lifecycle.createExact({+ name: "Cindy iPhone",+ deviceTypeIdentifier: DEVICE_TYPE,+ runtimeIdentifier: RUNTIME,+ }),+ ).rejects.toMatchObject({ code: "SIMULATOR_CREATE_FAILED" });++ // Retiring here would strand a hidden simulator: empty registry plus no+ // evidence means the next startup skips recovery entirely.+ expect(evidence.armed).toBe(1);+ expect(evidence.cleared).toEqual([]);+ // Attribution stayed strict, so nothing was deleted on a guess.+ expect(run).not.toHaveBeenCalledWith(+ "/usr/bin/xcrun",+ ["simctl", "delete", UDID],+ expect.anything(),+ );+ });++ it("retires evidence when a failed create is rolled back", async () => {+ let markerName = "";+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(async (_command, args) => {+ if (args[1] === "create") {+ markerName = args[2]!;+ return { stdout: "", stderr: "cancelled", exitCode: 1 };+ }+ if (args[1] === "list") {+ return {+ stdout: devicesJson([{ udid: UDID, name: markerName }]),+ stderr: "",+ exitCode: 0,+ };+ }+ return { stdout: "", stderr: "", exitCode: 0 };+ });+ const evidence = createEvidenceSpy();+ const lifecycle = createIOSSimulatorSimctlLifecycle({+ commandRunner: { run },+ createMarkerNamespace: "testprofile",+ pendingCreateEvidence: evidence,+ });++ await expect(+ lifecycle.createExact({+ name: "Cindy iPhone",+ deviceTypeIdentifier: DEVICE_TYPE,+ runtimeIdentifier: RUNTIME,+ }),+ ).rejects.toMatchObject({ code: "SIMULATOR_CREATE_FAILED" });++ expect(run).toHaveBeenCalledWith(+ "/usr/bin/xcrun",+ ["simctl", "delete", UDID],+ expect.objectContaining({ timeoutMs: expect.any(Number) }),+ );+ expect(evidence.cleared).toEqual([1]);+ });++ it("retires evidence once a created device is renamed away from its marker", async () => {+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(async (_command, args) => {+ if (args[1] === "create") {+ return { stdout: `${UDID}\n`, stderr: "", exitCode: 0 };+ }+ return { stdout: "", stderr: "", exitCode: 0 };+ });+ const evidence = createEvidenceSpy();+ const lifecycle = createIOSSimulatorSimctlLifecycle({+ commandRunner: { run },+ createMarkerNamespace: "testprofile",+ pendingCreateEvidence: evidence,+ });++ const created = await lifecycle.createExact({+ name: "Cindy iPhone",+ deviceTypeIdentifier: DEVICE_TYPE,+ runtimeIdentifier: RUNTIME,+ });+ // The caller persists ownership before finalizing the name, so evidence is+ // still required here.+ expect(evidence.cleared).toEqual([]);++ await lifecycle.renameExact?.(created.udid, "Cindy iPhone");+ expect(evidence.cleared).toEqual([1]);+ });++ it("keeps evidence while another create is still inside its ownership window", async () => {+ let creates = 0;+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(async (_command, args) => {+ if (args[1] === "create") {+ creates += 1;+ return creates === 1+ ? { stdout: `${UDID}\n`, stderr: "", exitCode: 0 }+ : { stdout: "", stderr: "blocked", exitCode: 1 };+ }+ if (args[1] === "list") {+ return { stdout: devicesJson([]), stderr: "", exitCode: 0 };+ }+ return { stdout: "", stderr: "", exitCode: 0 };+ });+ const evidence = createEvidenceSpy();+ const lifecycle = createIOSSimulatorSimctlLifecycle({+ commandRunner: { run },+ createMarkerNamespace: "testprofile",+ pendingCreateEvidence: evidence,+ });++ const first = await lifecycle.createExact({+ name: "Cindy iPhone",+ deviceTypeIdentifier: DEVICE_TYPE,+ runtimeIdentifier: RUNTIME,+ });++ // A second create fails cleanly while the first is still between create and+ // its ownership write. Retiring now would strand the first marker.+ await expect(+ lifecycle.createExact({+ name: "Cindy iPhone 2",+ deviceTypeIdentifier: DEVICE_TYPE,+ runtimeIdentifier: RUNTIME,+ }),+ ).rejects.toMatchObject({ code: "SIMULATOR_CREATE_FAILED" });+ expect(evidence.armed).toBe(2);+ expect(evidence.cleared).toEqual([]);++ await lifecycle.renameExact?.(first.udid, "Cindy iPhone");+ expect(evidence.cleared).toEqual([2]);+ });});diff --git a/packages/ios-simulator-runtime/src/simctl-lifecycle.ts b/packages/ios-simulator-runtime/src/simctl-lifecycle.tsindex 66e980bb58..615c215549 100644--- a/packages/ios-simulator-runtime/src/simctl-lifecycle.ts+++ b/packages/ios-simulator-runtime/src/simctl-lifecycle.ts@@ -6,6 +6,7 @@ import path from "node:path";import { createNodeIOSSimulatorCommandRunner } from "./command-runner.js";import { IOSSimulatorInstanceError } from "./instance-errors.js";import type { IOSSimulatorCreatedDevice } from "./instance-types.js";+import type { IOSSimulatorPendingCreateEvidence } from "./pending-create-evidence-file.js";import { parseSimctlListJson } from "./simctl-parser.js";import type {IOSSimulatorCommandResult,@@ -42,6 +43,19 @@ export interface IOSSimulatorSimctlLifecycleOptions {pollIntervalMs?: number;/** Stable, non-secret profile identity used to recover interrupted creates. */createMarkerNamespace?: string;+ /**+ * Host-owned breadcrumb armed before every `simctl create`. It is what lets+ * recovery stay off the CoreSimulator path until this profile has actually+ * created a device.+ */+ pendingCreateEvidence?: IOSSimulatorPendingCreateEvidence;+}++export interface IOSSimulatorPendingCreateRecoveryResult {+ /** Marker UUIDs that were renamed or deleted during the sweep. */+ recovered: readonly string[];+ /** False when a marker was observed but could not be safely attributed. */+ complete: boolean;}/**@@ -144,7 +158,7 @@ export interface IOSSimulatorSimctlLifecycle {recoverPendingCreatesAtStartup?(ownedDevices: readonly { udid: string; name: string }[],signal?: AbortSignal,- ): Promise<readonly string[]>;+ ): Promise<IOSSimulatorPendingCreateRecoveryResult>;deleteExact(udid: string, signal?: AbortSignal): Promise<void>;/** Set the simulated system appearance without bringing Simulator.app forward. */setAppearance?(@@ -502,6 +516,7 @@ export function createIOSSimulatorSimctlLifecycle(options.createMarkerNamespace ?? randomUUID().replaceAll("-", ""),);const createMarkerPrefix = `${CREATE_MARKER_PREFIX}${createMarkerNamespace}__`;+ const pendingCreateEvidence = options.pendingCreateEvidence ?? null;if (bootTimeoutMs <= 0 || pollIntervalMs <= 0) {throw new IOSSimulatorInstanceError("INVALID_ARGUMENT",@@ -526,6 +541,54 @@ export function createIOSSimulatorSimctlLifecycle();}+ /**+ * Markers minted by this process that may still exist in CoreSimulator. A+ * marker stays pending from the moment `simctl create` can commit a device+ * until that device is proven renamed away or deleted — a span that covers the+ * caller's ownership write, which is the window the breadcrumb exists for.+ *+ * The breadcrumb may only be retired while this map is empty: another create+ * still inside that window needs the same evidence to survive a crash.+ */+ const pendingCreateMarkers = new Map<string, string | null>();+ let lastArmedEvidenceGeneration = 0;+ // Evidence may predate this lifecycle. If startup recovery could not prove+ // that older marker is gone, a later create must not retire the shared file+ // merely because its own marker settled successfully.+ let startupRecoveryIncomplete = false;++ function armPendingCreateMarker(markerName: string): void {+ if (!pendingCreateEvidence) return;+ lastArmedEvidenceGeneration = pendingCreateEvidence.arm();+ pendingCreateMarkers.set(markerName, null);+ }++ function bindPendingCreateMarker(markerName: string, udid: string): void {+ if (!pendingCreateMarkers.has(markerName)) return;+ pendingCreateMarkers.set(markerName, udid.toUpperCase());+ }++ /** Only call from a path that proves this exact marker no longer exists. */+ function settlePendingCreateMarker(markerName: string): void {+ if (!pendingCreateEvidence) return;+ if (!pendingCreateMarkers.delete(markerName)) return;+ if (pendingCreateMarkers.size > 0 || startupRecoveryIncomplete) return;+ // The newest arm is the generation the file now carries, so retiring against+ // it is a no-op if anything armed the breadcrumb outside this lifecycle.+ pendingCreateEvidence.clearIfUnchanged(lastArmedEvidenceGeneration);+ }++ function settlePendingCreateMarkerForDevice(udid: string): void {+ if (pendingCreateMarkers.size === 0) return;+ const normalized = udid.toUpperCase();+ for (const [markerName, markerUdid] of pendingCreateMarkers) {+ if (markerUdid === normalized) {+ settlePendingCreateMarker(markerName);+ return;+ }+ }+ }+async function cleanupFailedCreate(udid: string,signal?: AbortSignal,@@ -546,25 +609,41 @@ export function createIOSSimulatorSimctlLifecycle(}}+ /**+ * `verified` separates "this profile provably created nothing" from "the check+ * itself could not run". Only the former may retire create evidence.+ */async function recoverCreatedMarker(markerName: string,deviceTypeIdentifier: string,runtimeIdentifier: string,signal: AbortSignal,- ): Promise<IOSSimulatorDevice | null> {+ ): Promise<{ device: IOSSimulatorDevice | null; verified: boolean }> {const result = await runner.run(XCRUN, ["simctl", "list", "-j"], {timeoutMs: CREATE_ABORT_CLEANUP_TIMEOUT_MS,signal,});- if (result.exitCode !== 0 || signal.aborted) return null;- const candidates = parseSimctlListJson(result.stdout).devices.filter(+ if (result.exitCode !== 0 || signal.aborted) {+ return { device: null, verified: false };+ }+ // The marker name is random and profile-scoped, so its presence alone proves+ // CoreSimulator committed something for this operation. Verification must key+ // on that name only: `deviceTypeIdentifier` is nullable in a listing, so a+ // metadata mismatch would otherwise be read as "nothing was created" and+ // retire the recovery evidence for a device that really exists.+ const named = parseSimctlListJson(result.stdout).devices.filter(+ (device) => device.name === markerName,+ );+ const candidates = named.filter((device) =>- device.name === markerName &&device.runtimeIdentifier === runtimeIdentifier &&device.deviceTypeIdentifier === deviceTypeIdentifier &&UUID_PATTERN.test(device.udid.toUpperCase()),);- return candidates.length === 1 ? candidates[0]! : null;+ // Deletion keeps the stricter identity rule; only a listing without this+ // exact name proves nothing needs recovering.+ if (candidates.length === 1) return { device: candidates[0]!, verified: true };+ return { device: null, verified: named.length === 0 };}async function list(signal?: AbortSignal): Promise<IOSSimulatorDevice[]> {@@ -613,6 +692,11 @@ export function createIOSSimulatorSimctlLifecycle(true,);}+ // The caller persists ownership before finalizing the name, so a marker that+ // is renamed away is both recorded and no longer sweepable.+ if (!isPendingCreateName(targetName)) {+ settlePendingCreateMarkerForDevice(normalized);+ }}return {@@ -745,6 +829,10 @@ export function createIOSSimulatorSimctlLifecycle();const markerName = `${createMarkerPrefix}${randomUUID()}`;throwIfAborted(signal);+ // Arm before CoreSimulator can commit the device: everything after this+ // point may leave a hidden marker behind if the process dies, and the+ // breadcrumb is the only thing that survives to prove it.+ armPendingCreateMarker(markerName);let result: IOSSimulatorCommandResult | null = null;let commandError: unknown = null;try {@@ -774,6 +862,7 @@ export function createIOSSimulatorSimctlLifecycle(deviceTypeIdentifier,}: null;+ if (createdDevice) bindPendingCreateMarker(markerName, createdDevice.udid);const createFailure =commandError ??(result?.exitCode !== 0@@ -802,13 +891,18 @@ export function createIOSSimulatorSimctlLifecycle(runtimeIdentifier,cleanupController.signal,);- if (recovered) {+ if (recovered.device) {createdDevice = {- udid: recovered.udid.toUpperCase(),+ udid: recovered.device.udid.toUpperCase(),name: markerName,runtimeIdentifier,deviceTypeIdentifier,};+ bindPendingCreateMarker(markerName, createdDevice.udid);+ } else if (recovered.verified) {+ // This create provably left nothing behind, so it must not keep the+ // profile paying a startup sweep it cannot clean anything with.+ settlePendingCreateMarker(markerName);}} catch {// The marker is profile-scoped and remains recoverable on startup.@@ -822,6 +916,8 @@ export function createIOSSimulatorSimctlLifecycle(createdDevice.udid,cleanupController?.signal,);+ // The compensating delete succeeded, so this marker is gone.+ settlePendingCreateMarker(markerName);} catch (error) {throw new IOSSimulatorCreateCleanupRequiredError(createdDevice,@@ -877,17 +973,24 @@ export function createIOSSimulatorSimctlLifecycle(async recoverPendingCreatesAtStartup(ownedDevices,signal,- ): Promise<readonly string[]> {+ ): Promise<IOSSimulatorPendingCreateRecoveryResult> {const owned = new Map(ownedDevices.map((device) => [requireUdid(device.udid),requireIdentifier(device.name, "name"),]),);- const pending = (await list(signal)).filter((device) =>- isPendingCreateName(device.name),- );+ let pending: IOSSimulatorDevice[];+ try {+ pending = (await list(signal)).filter((device) =>+ isPendingCreateName(device.name),+ );+ } catch (error) {+ startupRecoveryIncomplete = true;+ throw error;+ }const recovered: string[] = [];+ let complete = true;let firstFailure: unknown = null;for (const device of pending) {const udid = device.udid.toUpperCase();@@ -908,19 +1011,31 @@ export function createIOSSimulatorSimctlLifecycle(current.name !== device.name ||!isPendingCreateName(current.name) ||current.runtimeIdentifier !== device.runtimeIdentifier ||+ current.deviceTypeIdentifier === null ||current.deviceTypeIdentifier !== device.deviceTypeIdentifier) {+ // We deliberately avoid deleting a marker whose identity changed or+ // whose metadata is incomplete. That is not a completed sweep: the+ // breadcrumb must survive so a later startup can retry the cleanup.+ complete = false;continue;}await cleanupFailedCreate(udid, signal);recovered.push(udid);} catch (error) {- if (signal?.aborted) throwIfAborted(signal);+ if (signal?.aborted) {+ startupRecoveryIncomplete = true;+ throwIfAborted(signal);+ }firstFailure ??= error;}}- if (firstFailure !== null) throw firstFailure;- return recovered;+ if (firstFailure !== null) {+ startupRecoveryIncomplete = true;+ throw firstFailure;+ }+ startupRecoveryIncomplete = !complete;+ return { recovered, complete };},async deleteExact(udid, signal): Promise<void> {@@ -938,6 +1053,8 @@ export function createIOSSimulatorSimctlLifecycle("The iOS Simulator device could not be deleted.",);}+ // A rolled-back create leaves nothing for a sweep to find either.+ settlePendingCreateMarkerForDevice(normalized);},async setAppearance(udid, appearance, signal): Promise<void> {