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): harden build and create recovery

JiangJiahaoacc4c2a69bec
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 7e088db2f0..4cf7ddb237 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
@@ -187,6 +187,7 @@ describe('iOS Simulator host', () => {
bootExact: vi.fn(),
shutdownExact: vi.fn(),
createExact: vi.fn(),
+ reconcilePendingCreates: vi.fn(),
deleteExact: vi.fn(),
};
@@ -208,6 +209,7 @@ describe('iOS Simulator host', () => {
const host = createIOSSimulatorHost({
actor: persisted.actor,
lifecycle,
+ canReconcilePendingCreates: persisted.canReconcilePendingCreates,
runtime: { inspect: vi.fn(async () => READY_REPORT) },
getSession: vi.fn(async (id) => localSession(id)),
resolveWorktreeRoot: vi.fn(async () => '/tmp/session-a'),
@@ -224,6 +226,7 @@ describe('iOS Simulator host', () => {
errorCode: 'DEVICE_BUSY',
message: expect.stringContaining('ownership registry is invalid'),
});
+ expect(lifecycle.reconcilePendingCreates).not.toHaveBeenCalled();
expect(registry.isWriter).toBe(true);
await persisted.flush();
persisted.release();
@@ -1791,6 +1794,58 @@ describe('iOS Simulator host', () => {
expect(lifecycle.deleteExact).not.toHaveBeenCalled();
});
+ it('aborts and drains pending-marker reconciliation before host disposal completes', async () => {
+ let reconcileSignal: AbortSignal | undefined;
+ let finishReconciliation: (value: readonly string[]) => void = () => undefined;
+ const reconcilePendingCreates = vi.fn(
+ (_owned: readonly { udid: string; name: string }[], signal?: AbortSignal) =>
+ new Promise<readonly string[]>((resolve) => {
+ reconcileSignal = signal;
+ finishReconciliation = resolve;
+ }),
+ );
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(),
+ createExact: vi.fn(),
+ reconcilePendingCreates,
+ deleteExact: vi.fn(),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore(),
+ lifecycle,
+ });
+ const instance = actor.attach({
+ sessionId: 'session-a',
+ worktreeRoot: '/tmp/session-a',
+ sourceFingerprint: 'abc',
+ device: READY_REPORT.devices[0]!,
+ });
+ const inspect = vi.fn(async () => READY_REPORT);
+ const host = createIOSSimulatorHost({ actor, lifecycle, runtime: { inspect } });
+
+ const reconciling = host.reconcileOwnership();
+ await vi.waitFor(() => expect(reconcileSignal).toBeDefined());
+ let disposed = false;
+ const disposing = host.dispose().then(() => {
+ disposed = true;
+ });
+
+ expect(reconcileSignal?.aborted).toBe(true);
+ await Promise.resolve();
+ expect(disposed).toBe(false);
+ expect(reconcilePendingCreates).toHaveBeenCalledWith(
+ [{ udid: instance.simulatorUdid, name: instance.simulatorName }],
+ reconcileSignal,
+ );
+
+ finishReconciliation([]);
+ await Promise.all([reconciling, disposing]);
+ expect(disposed).toBe(true);
+ expect(inspect).not.toHaveBeenCalled();
+ });
+
it('disposes WDA and recording resources on host shutdown without changing ownership', async () => {
const lifecycle: IOSSimulatorSimctlLifecycle = {
findExact: vi.fn(),
@@ -6475,7 +6530,8 @@ describe('iOS Simulator host', () => {
scheme: 'Demo',
appPath: `${worktreeRoot}/build/Demo.app`,
resultBundlePath: `${derivedDataPath}/CindyBuild.xcresult`,
- buildLogTail: 'compile /tmp/session-a/secret.swift\\nwarning: keep this warning',
+ buildLogTail:
+ 'compile /tmp/session-a/secret.swift\\nGH_TOKEN=ghp_1234567890abcdefghijkl\\nwarning: keep this warning',
}),
);
const validateLaunch = vi.fn(async () => ({
@@ -6490,7 +6546,14 @@ describe('iOS Simulator host', () => {
const projectBuilder: IOSSimulatorProjectBuilderAdapter = {
build: buildProject,
readXcresult: vi.fn(async () =>
- JSON.stringify({ issues: [{ message: 'failed at /Users/secret/project.swift' }] }),
+ JSON.stringify({
+ issues: [
+ {
+ message:
+ 'failed at /Users/secret/project.swift Authorization: Bearer simulator-diagnostic-secret-123456',
+ },
+ ],
+ }),
),
validateLaunch,
};
@@ -6557,6 +6620,7 @@ describe('iOS Simulator host', () => {
},
},
});
+ expect(JSON.stringify(built)).not.toContain('ghp_1234567890abcdefghijkl');
const diagnosticsId = (built as { ok: true; data: { diagnostics: { diagnosticsId: string } } })
.data.diagnostics.diagnosticsId;
await expect(
@@ -6585,6 +6649,7 @@ describe('iOS Simulator host', () => {
);
expect(xcresult).toMatchObject({ ok: true, data: { available: true, eof: true } });
expect(JSON.stringify(xcresult)).not.toContain('/Users/secret');
+ expect(JSON.stringify(xcresult)).not.toContain('simulator-diagnostic-secret-123456');
await expect(
host.callTool(
'read_build_diagnostics',
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
index b0edad561e..fc8702f3ae 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
@@ -82,6 +82,7 @@ import type {
GhostIOSSimulatorStatusSnapshot,
} from '../../shared/ghost.js';
import { createLogger } from '../logger.js';
+import { redact } from '../log-upload/redact.js';
import { withSessionRouteLock } from '../localDb/sessionRouteLock.js';
import { desktopSessionStorage } from '../maker-host/session-storage.js';
import { isTrustedAppRendererWindow } from '../security/trustedAppRenderer.js';
@@ -180,6 +181,8 @@ export interface IOSSimulatorHostOptions {
mediaCapture?: IOSSimulatorMediaCaptureAdapter;
diagnosticsStore?: IOSSimulatorDiagnosticsStore;
resourceScheduler?: IOSSimulatorResourceScheduler;
+ /** Fail-closed gate supplied by the persisted registry owner. */
+ canReconcilePendingCreates?: () => boolean;
/** Recycle an idle WDA process while retaining the booted simulator binding. */
idleRecycleMs?: number;
/** Minimum interval between exact-UDID CoreSimulator liveness checks. */
@@ -299,6 +302,7 @@ export function createRegistryBackedIOSSimulatorActor(
actor: IOSSimulatorInstanceActor;
flush: () => Promise<void>;
release: () => void;
+ canReconcilePendingCreates: () => boolean;
} {
let ownsWriterLease = false;
let startupError: unknown = null;
@@ -357,6 +361,7 @@ export function createRegistryBackedIOSSimulatorActor(
if (registry.isWriter && !startupError) registry.saveSync(store.listAll());
},
release: () => registry.releaseWriterSync(),
+ canReconcilePendingCreates: () => !startupError && registry.isWriter,
};
} catch (error) {
registry.releaseWriterSync();
@@ -370,6 +375,16 @@ function createDefaultOwnershipRegistry(): IOSSimulatorOwnershipRegistryFile {
);
}
+function createProfileScopedIOSSimulatorLifecycle(
+ registry: IOSSimulatorOwnershipRegistryFile,
+): IOSSimulatorSimctlLifecycle {
+ const createMarkerNamespace = createHash('sha256')
+ .update(path.resolve(registry.filePath))
+ .digest('hex')
+ .slice(0, 16);
+ return createIOSSimulatorSimctlLifecycle({ createMarkerNamespace });
+}
+
function createDefaultActor(
lifecycle: IOSSimulatorSimctlLifecycle,
registry = createDefaultOwnershipRegistry(),
@@ -377,6 +392,7 @@ function createDefaultActor(
actor: IOSSimulatorInstanceActor;
flush: () => Promise<void>;
release: () => void;
+ canReconcilePendingCreates: () => boolean;
} {
const persisted = createRegistryBackedIOSSimulatorActor(lifecycle, registry);
if (!registry.isWriter) {
@@ -703,7 +719,7 @@ function publicNativeSidecarDiagnostics(
}
function publicBuildText(value: string): string {
- return value
+ return redact(value)
.replace(/https?:\/\/[^\s)]+/gi, '<redacted-url>')
.replace(/(?:\/Users\/|\/private\/var\/|\/tmp\/)[^\s"']+/g, '<redacted-path>')
.slice(-2 * 1024 * 1024);
@@ -930,7 +946,20 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
>();
let ownershipReconciled = false;
let ownershipReconcilePromise: Promise<void> | null = null;
+ let pendingCreateReconcileController: AbortController | null = null;
+ let pendingCreateReconcilePromise: Promise<readonly string[]> | null = null;
let disposePromise: Promise<void> | null = null;
+ const canReconcilePendingCreates = options.canReconcilePendingCreates ?? (() => true);
+
+ function abortPendingCreateReconciliation(): Promise<void> {
+ pendingCreateReconcileController?.abort();
+ return (
+ pendingCreateReconcilePromise?.then(
+ () => undefined,
+ () => undefined,
+ ) ?? Promise.resolve()
+ );
+ }
const pushRouteStatus =
options.pushRouteStatus ??
((status: IOSSimulatorPublicRouteStatus) => {
@@ -2271,6 +2300,40 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
if (ownershipReconciled) return;
if (ownershipReconcilePromise) return ownershipReconcilePromise;
ownershipReconcilePromise = (async () => {
+ let complete = true;
+ const persistedInstances = actor.listAll();
+ if (lifecycle.reconcilePendingCreates && persistedInstances.length > 0) {
+ if (!canReconcilePendingCreates()) {
+ complete = false;
+ } else {
+ const controller = new AbortController();
+ const reconciliation = lifecycle.reconcilePendingCreates(
+ persistedInstances.map((instance) => ({
+ udid: instance.simulatorUdid,
+ name: instance.simulatorName,
+ })),
+ controller.signal,
+ );
+ pendingCreateReconcileController = controller;
+ pendingCreateReconcilePromise = reconciliation;
+ try {
+ await reconciliation;
+ } catch (error) {
+ complete = false;
+ if (!disposePromise) {
+ logger.warn('Interrupted simulator create reconciliation will retry', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ } finally {
+ if (pendingCreateReconcileController === controller) {
+ pendingCreateReconcileController = null;
+ pendingCreateReconcilePromise = null;
+ }
+ }
+ }
+ }
+ if (disposePromise) return;
await reconcileOrphanedBuildResultBundles();
if (disposePromise) return;
const environment = await runtime.inspect();
@@ -2279,7 +2342,6 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
const devices = new Map(
environment.devices.map((device) => [device.udid.toUpperCase(), device]),
);
- let complete = true;
for (const snapshot of actor.listAll()) {
const instanceComplete = await withSessionLock(snapshot.sessionId, () =>
reconcilePersistedInstance(snapshot, devices),
@@ -5770,6 +5832,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
return cleanupRemovedSessionRuntime(sessionId);
},
abortOperationsForExit() {
+ void abortPendingCreateReconciliation();
try {
actor.abortOperationsForExit();
} catch (error) {
@@ -5804,6 +5867,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
dispose() {
if (disposePromise) return disposePromise;
disposePromise = (async () => {
+ const pendingCreateReconciliation = abortPendingCreateReconciliation();
actor.abortOperationsForExit();
const lifecycleStarts = actor.cancelAllLifecycleStarts();
const mutations = actor.cancelAllMutations();
@@ -5816,7 +5880,12 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
error: error instanceof Error ? error.message : String(error),
});
});
- await Promise.all([lifecycleStarts, mutations, ...builds.map((build) => build.settled)]);
+ await Promise.all([
+ pendingCreateReconciliation,
+ lifecycleStarts,
+ mutations,
+ ...builds.map((build) => build.settled),
+ ]);
clearVisualBaselines();
await Promise.all(
[...buildDiagnostics.entries()].map(([diagnosticsId, diagnostic]) =>
@@ -5899,6 +5968,7 @@ function installDefaultIOSSimulatorHost(
const host = createIOSSimulatorHost({
lifecycle,
actor: persistedActor.actor,
+ canReconcilePendingCreates: persistedActor.canReconcilePendingCreates,
driverManager: createDefaultDriverManager(),
});
configureIOSSimulatorRendererAccessRevocationObserver((grants) => {
@@ -5936,8 +6006,9 @@ export function initializeIOSSimulatorHost(): IOSSimulatorHost {
throw new Error('The iOS Simulator host is shutting down.');
}
- const lifecycle = createIOSSimulatorSimctlLifecycle();
- const persistedActor = createDefaultActor(lifecycle);
+ const registry = createDefaultOwnershipRegistry();
+ const lifecycle = createProfileScopedIOSSimulatorLifecycle(registry);
+ const persistedActor = createDefaultActor(lifecycle, registry);
return installDefaultIOSSimulatorHost(lifecycle, persistedActor);
}
@@ -6037,11 +6108,12 @@ export function reconcilePersistedIOSSimulatorOwnership(): Promise<void> {
true,
);
}
- if (registry.loadSync().length === 0) {
+ const persistedInstances = registry.loadSync();
+ if (persistedInstances.length === 0) {
registry.releaseWriterSync();
return Promise.resolve();
}
- const lifecycle = createIOSSimulatorSimctlLifecycle();
+ const lifecycle = createProfileScopedIOSSimulatorLifecycle(registry);
const persistedActor = createDefaultActor(lifecycle, registry);
const host = installDefaultIOSSimulatorHost(lifecycle, persistedActor);
registryTransferred = true;
@@ -6105,7 +6177,7 @@ 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 = createIOSSimulatorSimctlLifecycle();
+ const lifecycle = createProfileScopedIOSSimulatorLifecycle(registry);
const persistedActor = createDefaultActor(lifecycle, registry);
const host = installDefaultIOSSimulatorHost(lifecycle, persistedActor);
registryTransferred = true;
diff --git a/packages/ios-simulator-runtime/src/instance-actor.test.ts b/packages/ios-simulator-runtime/src/instance-actor.test.ts
index 4fa04104e0..fe15668d4b 100644
--- a/packages/ios-simulator-runtime/src/instance-actor.test.ts
+++ b/packages/ios-simulator-runtime/src/instance-actor.test.ts
@@ -891,11 +891,55 @@ describe("IOSSimulatorInstanceActor", () => {
);
expect(created).toMatchObject({
simulatorUdid: createdUdid,
+ simulatorName: "Cindy iPhone",
creationProvenance: "cindy",
lifecycleState: "stopped",
});
});
+ it("persists exact ownership before renaming an interrupted-create marker", async () => {
+ const harness = createHarness();
+ const createdUdid = "2A9D41E0-E031-4AD0-A8B5-847480802E8E";
+ const markerName =
+ "__CindyPending__testprofile__11111111-2222-4333-8444-555555555555";
+ vi.mocked(harness.lifecycle.createExact).mockResolvedValue({
+ udid: createdUdid,
+ name: markerName,
+ runtimeIdentifier: DEVICE.runtimeIdentifier,
+ deviceTypeIdentifier: DEVICE.deviceTypeIdentifier!,
+ });
+ harness.lifecycle.renameExact = vi.fn(async (udid, name) => {
+ expect(harness.store.listAll()).toEqual([
+ expect.objectContaining({
+ simulatorUdid: createdUdid,
+ simulatorName: "Cindy iPhone",
+ sessionId: "session-a",
+ }),
+ ]);
+ expect(udid).toBe(createdUdid);
+ expect(name).toBe("Cindy iPhone");
+ });
+ await harness.actor.detach(harness.route());
+
+ const created = await harness.actor.create({
+ sessionId: "session-a",
+ worktreeRoot: "/tmp/session-a",
+ sourceFingerprint: "abc",
+ name: "Cindy iPhone",
+ templateDevice: DEVICE,
+ });
+
+ expect(harness.lifecycle.renameExact).toHaveBeenCalledWith(
+ createdUdid,
+ "Cindy iPhone",
+ expect.any(AbortSignal),
+ );
+ expect(created).toMatchObject({
+ simulatorUdid: createdUdid,
+ simulatorName: "Cindy iPhone",
+ });
+ });
+
it("cancels and rolls back an in-flight create by owning session", async () => {
const harness = createHarness();
const createdUdid = "2A9D41E0-E031-4AD0-A8B5-847480802E8E";
diff --git a/packages/ios-simulator-runtime/src/instance-actor.ts b/packages/ios-simulator-runtime/src/instance-actor.ts
index 4982e360cb..a671bfdbaa 100644
--- a/packages/ios-simulator-runtime/src/instance-actor.ts
+++ b/packages/ios-simulator-runtime/src/instance-actor.ts
@@ -746,7 +746,7 @@ export class IOSSimulatorInstanceActor {
device: {
...input.templateDevice,
udid: created.udid,
- name: created.name,
+ name: input.name,
state: "Shutdown",
lastBootedAt: null,
},
@@ -797,6 +797,17 @@ export class IOSSimulatorInstanceActor {
),
);
this.#throwCreateFailure(cleanupRequired, signal);
+ if (created.name !== input.name) {
+ if (!this.#lifecycle.renameExact) {
+ throw new IOSSimulatorInstanceError(
+ "SIMULATOR_CREATE_FAILED",
+ "The simulator lifecycle cannot finalize the created device name.",
+ true,
+ );
+ }
+ await this.#lifecycle.renameExact(created.udid, input.name, signal);
+ this.#throwCreateFailure(cleanupRequired, signal);
+ }
return rollbackBinding;
} catch (error) {
const current = this.#bindingForUdid(created.udid);
diff --git a/packages/ios-simulator-runtime/src/project-adapter.test.ts b/packages/ios-simulator-runtime/src/project-adapter.test.ts
index cf5a8325f6..1b7d60dc65 100644
--- a/packages/ios-simulator-runtime/src/project-adapter.test.ts
+++ b/packages/ios-simulator-runtime/src/project-adapter.test.ts
@@ -72,7 +72,15 @@ describe("IOSSimulatorProjectBuilder", () => {
}
return { stdout: "", stderr: "", exitCode: 0 };
});
- const builder = new IOSSimulatorProjectBuilder({ commandRunner: { run } });
+ const builder = new IOSSimulatorProjectBuilder({
+ commandRunner: { run },
+ environment: {
+ PATH: "/safe/bin",
+ DEVELOPER_DIR: "/Applications/Xcode.app/Contents/Developer",
+ GH_TOKEN: "ghp_should_not_reach_builds",
+ XDT_CODEX_API_KEY: "should-not-reach-builds",
+ },
+ });
const signal = new AbortController().signal;
await expect(
builder.validateLaunch(root, SIMULATOR_UDID.toLowerCase(), signal),
@@ -82,14 +90,15 @@ describe("IOSSimulatorProjectBuilder", () => {
});
expect(run).toHaveBeenCalledWith(
"pnpm",
- [
- "mobile:sim:whoami",
- "--",
- "--json",
- "--udid",
- SIMULATOR_UDID,
- ],
- expect.objectContaining({ cwd: await realpath(root), signal }),
+ ["mobile:sim:whoami", "--", "--json", "--udid", SIMULATOR_UDID],
+ expect.objectContaining({
+ cwd: await realpath(root),
+ signal,
+ env: {
+ DEVELOPER_DIR: "/Applications/Xcode.app/Contents/Developer",
+ PATH: "/safe/bin",
+ },
+ }),
);
});
@@ -309,32 +318,40 @@ describe("IOSSimulatorProjectBuilder", () => {
const appPath = path.join(root, "derived", "Build", "Example.app");
await mkdir(workspace);
await mkdir(appPath, { recursive: true });
- const run = vi.fn(async (_command: string, args: readonly string[]) => {
- if (args.includes("-list")) {
- return {
- stdout: JSON.stringify({ workspace: { schemes: ["Example"] } }),
- stderr: "",
- exitCode: 0,
- };
- }
- if (args.includes("-showBuildSettings")) {
- return {
- stdout: JSON.stringify([
- {
- buildSettings: {
- TARGET_BUILD_DIR: path.dirname(appPath),
- WRAPPER_NAME: "Example.app",
+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(
+ async (_command, args) => {
+ if (args.includes("-list")) {
+ return {
+ stdout: JSON.stringify({ workspace: { schemes: ["Example"] } }),
+ stderr: "",
+ exitCode: 0,
+ };
+ }
+ if (args.includes("-showBuildSettings")) {
+ return {
+ stdout: JSON.stringify([
+ {
+ buildSettings: {
+ TARGET_BUILD_DIR: path.dirname(appPath),
+ WRAPPER_NAME: "Example.app",
+ },
},
- },
- ]),
- stderr: "",
- exitCode: 0,
- };
- }
- return { stdout: "", stderr: "", exitCode: 0 };
- });
+ ]),
+ stderr: "",
+ exitCode: 0,
+ };
+ }
+ return { stdout: "", stderr: "", exitCode: 0 };
+ },
+ );
const result = await new IOSSimulatorProjectBuilder({
commandRunner: { run },
+ environment: {
+ PATH: "/safe/bin",
+ HOME: "/safe/home",
+ GH_TOKEN: "ghp_should_not_reach_xcode",
+ NODE_OPTIONS: "--require=/tmp/untrusted.js",
+ },
}).build({
worktreeRoot: root,
derivedDataPath: path.join(root, "derived"),
@@ -357,6 +374,14 @@ describe("IOSSimulatorProjectBuilder", () => {
args.includes("-showBuildSettings"),
);
expect(settingsCall?.[1]).not.toContain("-resultBundlePath");
+ for (const [, , options] of run.mock.calls) {
+ expect(options?.env).toEqual({
+ HOME: "/safe/home",
+ PATH: "/safe/bin",
+ });
+ expect(options?.env).not.toHaveProperty("GH_TOKEN");
+ expect(options?.env).not.toHaveProperty("NODE_OPTIONS");
+ }
});
it("uses a fresh xcresult bundle for each build", async () => {
diff --git a/packages/ios-simulator-runtime/src/project-adapter.ts b/packages/ios-simulator-runtime/src/project-adapter.ts
index fe133edf7e..041e212255 100644
--- a/packages/ios-simulator-runtime/src/project-adapter.ts
+++ b/packages/ios-simulator-runtime/src/project-adapter.ts
@@ -4,6 +4,7 @@ import path from "node:path";
import { createNodeIOSSimulatorCommandRunner } from "./command-runner.js";
import { IOSSimulatorInstanceError } from "./instance-errors.js";
+import { createWdaChildEnvironment } from "./wda/build-plan.js";
import type {
IOSSimulatorCommandResult,
IOSSimulatorCommandRunner,
@@ -45,6 +46,8 @@ export class IOSSimulatorProjectBuildError extends IOSSimulatorInstanceError {
export interface IOSSimulatorProjectBuilderOptions {
commandRunner?: IOSSimulatorCommandRunner;
buildTimeoutMs?: number;
+ /** Test/integration seam; only the shared child-process allowlist is retained. */
+ environment?: NodeJS.ProcessEnv;
}
export interface IOSSimulatorMobileMetroStatus {
@@ -161,11 +164,15 @@ function throwIfLaunchValidationCancelled(signal?: AbortSignal): void {
export class IOSSimulatorProjectBuilder {
readonly #runner: IOSSimulatorCommandRunner;
readonly #buildTimeoutMs: number;
+ readonly #childEnvironment: NodeJS.ProcessEnv;
constructor(options: IOSSimulatorProjectBuilderOptions = {}) {
this.#runner =
options.commandRunner ?? createNodeIOSSimulatorCommandRunner();
this.#buildTimeoutMs = options.buildTimeoutMs ?? 30 * 60_000;
+ this.#childEnvironment = createWdaChildEnvironment(
+ options.environment ?? process.env,
+ );
}
async inspect(
@@ -293,6 +300,7 @@ export class IOSSimulatorProjectBuilder {
timeoutMs: this.#buildTimeoutMs,
maxBufferBytes: 1024 * 1024,
signal: input.signal,
+ env: this.#childEnvironment,
},
);
await throwIfBuildCancelled(input.signal);
@@ -349,6 +357,7 @@ export class IOSSimulatorProjectBuilder {
timeoutMs: 60_000,
maxBufferBytes: 1024 * 1024,
signal: input.signal,
+ env: this.#childEnvironment,
},
);
await throwIfBuildCancelled(input.signal);
@@ -418,6 +427,7 @@ export class IOSSimulatorProjectBuilder {
timeoutMs: this.#buildTimeoutMs,
maxBufferBytes: 1024 * 1024,
signal: input.signal,
+ env: this.#childEnvironment,
},
);
await throwIfBuildCancelled(input.signal, resultBundlePath);
@@ -443,6 +453,7 @@ export class IOSSimulatorProjectBuilder {
timeoutMs: 60_000,
maxBufferBytes: 4 * 1024 * 1024,
signal: input.signal,
+ env: this.#childEnvironment,
},
);
await throwIfBuildCancelled(input.signal, resultBundlePath);
@@ -510,7 +521,9 @@ export class IOSSimulatorProjectBuilder {
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)) {
+ if (
+ !/^[0-9A-F]{8}(?:-[0-9A-F]{4}){3}-[0-9A-F]{12}$/.test(exactSimulatorUdid)
+ ) {
throw new IOSSimulatorInstanceError(
"INVALID_ARGUMENT",
"simulatorUdid must be an exact simulator UUID",
@@ -518,18 +531,13 @@ export class IOSSimulatorProjectBuilder {
}
const result = await this.#runner.run(
"pnpm",
- [
- "mobile:sim:whoami",
- "--",
- "--json",
- "--udid",
- exactSimulatorUdid,
- ],
+ ["mobile:sim:whoami", "--", "--json", "--udid", exactSimulatorUdid],
{
cwd: project.worktreeRoot,
timeoutMs: 60_000,
maxBufferBytes: 2 * 1024 * 1024,
signal,
+ env: this.#childEnvironment,
},
);
throwIfLaunchValidationCancelled(signal);
@@ -578,7 +586,11 @@ export class IOSSimulatorProjectBuilder {
const result = await this.#runner.run(
"xcrun",
["xcresulttool", "get", "--path", resultBundlePath, "--format", "json"],
- { timeoutMs: 60_000, maxBufferBytes },
+ {
+ timeoutMs: 60_000,
+ maxBufferBytes,
+ env: this.#childEnvironment,
+ },
);
if (result.exitCode !== 0) {
throw new IOSSimulatorInstanceError(
diff --git a/packages/ios-simulator-runtime/src/runtime.test.ts b/packages/ios-simulator-runtime/src/runtime.test.ts
index e925a2a06c..af9087e1ff 100644
--- a/packages/ios-simulator-runtime/src/runtime.test.ts
+++ b/packages/ios-simulator-runtime/src/runtime.test.ts
@@ -48,7 +48,7 @@ const SIMCTL_LIST = JSON.stringify({
},
});
-function runnerForSimctl(): IOSSimulatorCommandRunner {
+function runnerForSimctl(simctlList = SIMCTL_LIST): IOSSimulatorCommandRunner {
return {
run: vi.fn(async (command, args) => {
const key = `${command} ${args.join(" ")}`;
@@ -67,7 +67,7 @@ function runnerForSimctl(): IOSSimulatorCommandRunner {
};
}
if (key === "/usr/bin/xcrun simctl list -j") {
- return { stdout: SIMCTL_LIST, stderr: "", exitCode: 0 };
+ return { stdout: simctlList, stderr: "", exitCode: 0 };
}
throw new Error(`unexpected command: ${key}`);
}),
@@ -168,6 +168,29 @@ describe("createIOSSimulatorRuntime", () => {
expect(report.devices).toHaveLength(2);
});
+ it("never exposes interrupted-create markers as attachable devices", async () => {
+ const simctl = JSON.parse(SIMCTL_LIST) as {
+ devices: Record<string, Array<Record<string, unknown>>>;
+ };
+ simctl.devices["com.apple.CoreSimulator.SimRuntime.iOS-26-4"]!.push({
+ udid: "MARKER-UDID",
+ name: "__CindyPending__profilealpha__11111111-2222-4333-8444-555555555555",
+ state: "Booted",
+ isAvailable: true,
+ deviceTypeIdentifier: "com.apple.CoreSimulator.SimDeviceType.iPhone-17",
+ });
+
+ const report = await createIOSSimulatorRuntime({
+ platform: "darwin",
+ commandRunner: runnerForSimctl(JSON.stringify(simctl)),
+ }).inspect();
+
+ expect(report.ready).toBe(true);
+ expect(report.devices.map((device) => device.udid)).not.toContain(
+ "MARKER-UDID",
+ );
+ });
+
it("uses one exact DEVELOPER_DIR without mutating xcode-select", async () => {
const commandRunner = runnerForSimctl();
const developerDir = "/Applications/Xcode-26.4.app/Contents/Developer";
diff --git a/packages/ios-simulator-runtime/src/runtime.ts b/packages/ios-simulator-runtime/src/runtime.ts
index 049269a87b..2ba01abcaf 100644
--- a/packages/ios-simulator-runtime/src/runtime.ts
+++ b/packages/ios-simulator-runtime/src/runtime.ts
@@ -1,5 +1,6 @@
import { createNodeIOSSimulatorCommandRunner } from "./command-runner.js";
import { IOSSimulatorRuntimeError } from "./errors.js";
+import { isIOSSimulatorPendingCreateName } from "./simctl-lifecycle.js";
import { parseSimctlListJson } from "./simctl-parser.js";
import path from "node:path";
import type {
@@ -146,7 +147,10 @@ export function createIOSSimulatorRuntime(
const availableRuntimes = parsed.runtimes.filter(
(runtime) => runtime.isAvailable,
);
- const availableDevices = parsed.devices.filter(
+ const visibleDevices = parsed.devices.filter(
+ (device) => !isIOSSimulatorPendingCreateName(device.name),
+ );
+ const availableDevices = visibleDevices.filter(
(device) => device.isAvailable,
);
if (availableRuntimes.length === 0) {
@@ -162,7 +166,7 @@ export function createIOSSimulatorRuntime(
xcodeSelectPath,
xcodeVersion,
runtimes: parsed.runtimes,
- devices: parsed.devices,
+ devices: visibleDevices,
},
);
}
@@ -178,7 +182,7 @@ export function createIOSSimulatorRuntime(
xcodeSelectPath,
xcodeVersion,
runtimes: parsed.runtimes,
- devices: parsed.devices,
+ devices: visibleDevices,
},
);
}
@@ -189,7 +193,7 @@ export function createIOSSimulatorRuntime(
xcodeSelectPath,
xcodeVersion,
runtimes: parsed.runtimes,
- devices: parsed.devices,
+ devices: visibleDevices,
issue: null,
error: null,
setupSteps: [],
diff --git a/packages/ios-simulator-runtime/src/simctl-lifecycle.test.ts b/packages/ios-simulator-runtime/src/simctl-lifecycle.test.ts
index c7fbbe7cdb..78b3a17274 100644
--- a/packages/ios-simulator-runtime/src/simctl-lifecycle.test.ts
+++ b/packages/ios-simulator-runtime/src/simctl-lifecycle.test.ts
@@ -8,8 +8,17 @@ import {
import type { IOSSimulatorCommandRunner } from "./types.js";
const UDID = "1A9D41E0-E031-4AD0-A8B5-847480802E8E";
-
-function listJson(state: string): string {
+const DEVICE_TYPE = "com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro";
+const RUNTIME = "com.apple.CoreSimulator.SimRuntime.iOS-26-4";
+
+function devicesJson(
+ devices: Array<{
+ udid: string;
+ name: string;
+ state?: string;
+ deviceTypeIdentifier?: string;
+ }>,
+): string {
return JSON.stringify({
runtimes: [
{
@@ -20,20 +29,20 @@ function listJson(state: string): string {
},
],
devices: {
- "com.apple.CoreSimulator.SimRuntime.iOS-26-4": [
- {
- udid: UDID,
- name: "iPhone 17 Pro",
- state,
- isAvailable: true,
- deviceTypeIdentifier:
- "com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro",
- },
- ],
+ [RUNTIME]: devices.map((device) => ({
+ ...device,
+ state: device.state ?? "Shutdown",
+ isAvailable: true,
+ deviceTypeIdentifier: device.deviceTypeIdentifier ?? DEVICE_TYPE,
+ })),
},
});
}
+function listJson(state: string): string {
+ return devicesJson([{ udid: UDID, name: "iPhone 17 Pro", state }]);
+}
+
describe("createIOSSimulatorSimctlLifecycle", () => {
it("boots and polls an exact UDID until bootstatus succeeds", async () => {
let now = 0;
@@ -245,6 +254,7 @@ describe("createIOSSimulatorSimctlLifecycle", () => {
);
const lifecycle = createIOSSimulatorSimctlLifecycle({
commandRunner: { run },
+ createMarkerNamespace: "testprofile",
});
await lifecycle.createExact({
@@ -253,6 +263,7 @@ describe("createIOSSimulatorSimctlLifecycle", () => {
"com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro",
runtimeIdentifier: "com.apple.CoreSimulator.SimRuntime.iOS-26-4",
});
+ await lifecycle.renameExact?.(UDID, "Cindy iPhone");
await lifecycle.shutdownExact(UDID);
await lifecycle.deleteExact(UDID);
@@ -261,12 +272,18 @@ describe("createIOSSimulatorSimctlLifecycle", () => {
[
"simctl",
"create",
- "Cindy iPhone",
+ expect.stringMatching(/^__CindyPending__testprofile__[0-9a-f-]{36}$/),
"com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro",
"com.apple.CoreSimulator.SimRuntime.iOS-26-4",
],
{ timeoutMs: 60_000 },
);
+ expect(run).toHaveBeenCalledWith("/usr/bin/xcrun", [
+ "simctl",
+ "rename",
+ UDID,
+ "Cindy iPhone",
+ ]);
expect(run).toHaveBeenCalledWith("/usr/bin/xcrun", [
"simctl",
"shutdown",
@@ -279,6 +296,124 @@ describe("createIOSSimulatorSimctlLifecycle", () => {
]);
});
+ it("recovers and deletes a cancelled create whose UUID never reached stdout", async () => {
+ const controller = new AbortController();
+ const reason = new Error("create cancelled before stdout");
+ const preexistingUdid = "2A9D41E0-E031-4AD0-A8B5-847480802E8E";
+ let markerName = "";
+ let createSignal: AbortSignal | undefined;
+ 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") {
+ return {
+ stdout: devicesJson([
+ {
+ udid: preexistingUdid,
+ name: "Cindy iPhone",
+ },
+ { udid: UDID, name: markerName },
+ ]),
+ 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: "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(markerName).toMatch(/^__CindyPending__testprofile__[0-9a-f-]{36}$/);
+ const deleteCalls = run.mock.calls.filter(
+ ([, args]) => args[1] === "delete",
+ );
+ expect(deleteCalls).toHaveLength(1);
+ expect(deleteCalls[0]?.[1]).toEqual(["simctl", "delete", UDID]);
+ expect(JSON.stringify(deleteCalls)).not.toContain(preexistingUdid);
+ });
+
+ 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";
+ const ordinaryUdid = "4A9D41E0-E031-4AD0-A8B5-847480802E8E";
+ const run = vi.fn<IOSSimulatorCommandRunner["run"]>(
+ async (_command, args) => {
+ if (args[1] === "list") {
+ return {
+ stdout: devicesJson([
+ {
+ udid: UDID,
+ name: "__CindyPending__profilealpha__11111111-2222-4333-8444-555555555555",
+ },
+ {
+ udid: ownedUdid,
+ name: "__CindyPending__profilealpha__22222222-3333-4444-8555-666666666666",
+ },
+ {
+ udid: otherProfileUdid,
+ name: "__CindyPending__profilebeta__33333333-4444-4555-8666-777777777777",
+ },
+ { udid: ordinaryUdid, name: "Cindy iPhone" },
+ ]),
+ 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.reconcilePendingCreates?.([
+ { udid: ownedUdid, name: "Cindy Restored iPhone" },
+ ]),
+ ).resolves.toEqual([ownedUdid]);
+ const deleteCalls = run.mock.calls.filter(
+ ([, args]) => args[1] === "delete",
+ );
+ expect(deleteCalls).toHaveLength(0);
+ expect(run).toHaveBeenCalledWith("/usr/bin/xcrun", [
+ "simctl",
+ "rename",
+ ownedUdid,
+ "Cindy Restored iPhone",
+ ]);
+ });
+
it("cancels create and deletes only an exact late-created UDID", async () => {
const controller = new AbortController();
const reason = new Error("create cancelled for exit");
@@ -299,6 +434,7 @@ describe("createIOSSimulatorSimctlLifecycle", () => {
);
const lifecycle = createIOSSimulatorSimctlLifecycle({
commandRunner: { run },
+ createMarkerNamespace: "testprofile",
});
const creating = lifecycle.createExact(
@@ -320,7 +456,7 @@ describe("createIOSSimulatorSimctlLifecycle", () => {
[
"simctl",
"create",
- "Cindy iPhone",
+ expect.stringMatching(/^__CindyPending__testprofile__[0-9a-f-]{36}$/),
"com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro",
"com.apple.CoreSimulator.SimRuntime.iOS-26-4",
],
@@ -354,6 +490,7 @@ describe("createIOSSimulatorSimctlLifecycle", () => {
);
const lifecycle = createIOSSimulatorSimctlLifecycle({
commandRunner: { run },
+ createMarkerNamespace: "testprofile",
});
const creating = lifecycle.createExact(
@@ -374,7 +511,9 @@ describe("createIOSSimulatorSimctlLifecycle", () => {
originalReason: reason,
createdDevice: {
udid: UDID,
- name: "Cindy iPhone",
+ name: expect.stringMatching(
+ /^__CindyPending__testprofile__[0-9a-f-]{36}$/,
+ ),
deviceTypeIdentifier:
"com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro",
runtimeIdentifier: "com.apple.CoreSimulator.SimRuntime.iOS-26-4",
diff --git a/packages/ios-simulator-runtime/src/simctl-lifecycle.ts b/packages/ios-simulator-runtime/src/simctl-lifecycle.ts
index d6e25d8357..76166e4fa0 100644
--- a/packages/ios-simulator-runtime/src/simctl-lifecycle.ts
+++ b/packages/ios-simulator-runtime/src/simctl-lifecycle.ts
@@ -1,3 +1,4 @@
+import { randomUUID } from "node:crypto";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
@@ -6,11 +7,28 @@ import { createNodeIOSSimulatorCommandRunner } from "./command-runner.js";
import { IOSSimulatorInstanceError } from "./instance-errors.js";
import type { IOSSimulatorCreatedDevice } from "./instance-types.js";
import { parseSimctlListJson } from "./simctl-parser.js";
-import type { IOSSimulatorCommandRunner, IOSSimulatorDevice } from "./types.js";
+import type {
+ IOSSimulatorCommandResult,
+ IOSSimulatorCommandRunner,
+ IOSSimulatorDevice,
+} from "./types.js";
const XCRUN = "/usr/bin/xcrun";
const UUID_PATTERN = /^[0-9A-F]{8}(?:-[0-9A-F]{4}){3}-[0-9A-F]{12}$/;
const CREATE_ABORT_CLEANUP_TIMEOUT_MS = 4_000;
+const CREATE_ABORT_RECONCILE_TIMEOUT_MS = 3_000;
+const CREATE_MARKER_PREFIX = "__CindyPending__";
+const CREATE_MARKER_UUID_PATTERN =
+ /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
+const ANY_CREATE_MARKER_PATTERN = new RegExp(
+ `^${CREATE_MARKER_PREFIX}[A-Za-z0-9_-]{8,64}__${CREATE_MARKER_UUID_PATTERN.source.slice(1, -1)}$`,
+ "i",
+);
+
+/** Internal create markers are recovery evidence, never user-attachable devices. */
+export function isIOSSimulatorPendingCreateName(name: string): boolean {
+ return ANY_CREATE_MARKER_PATTERN.test(name);
+}
export interface IOSSimulatorLifecycleClock {
now(): number;
@@ -22,6 +40,8 @@ export interface IOSSimulatorSimctlLifecycleOptions {
clock?: IOSSimulatorLifecycleClock;
bootTimeoutMs?: number;
pollIntervalMs?: number;
+ /** Stable, non-secret profile identity used to recover interrupted creates. */
+ createMarkerNamespace?: string;
}
/**
@@ -109,6 +129,13 @@ export interface IOSSimulatorSimctlLifecycle {
},
signal?: AbortSignal,
): Promise<IOSSimulatorCreatedDevice>;
+ /** Rename only an exact UUID after ownership has been persisted. */
+ renameExact?(udid: string, name: string, signal?: AbortSignal): Promise<void>;
+ /** Rename only exact markers already proven owned by this profile. */
+ reconcilePendingCreates?(
+ 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?(
@@ -188,6 +215,17 @@ function requireIdentifier(value: string, label: string): string {
return normalized;
}
+function requireCreateMarkerNamespace(value: string): string {
+ const normalized = value.trim();
+ if (!/^[A-Za-z0-9_-]{8,64}$/.test(normalized)) {
+ throw new IOSSimulatorInstanceError(
+ "INVALID_ARGUMENT",
+ "createMarkerNamespace is invalid",
+ );
+ }
+ return normalized;
+}
+
function requireBundleId(value: string): string {
const normalized = value.trim();
if (!/^[A-Za-z0-9][A-Za-z0-9.-]{1,254}$/.test(normalized)) {
@@ -451,6 +489,10 @@ export function createIOSSimulatorSimctlLifecycle(
const clock = options.clock ?? defaultClock();
const bootTimeoutMs = options.bootTimeoutMs ?? 120_000;
const pollIntervalMs = options.pollIntervalMs ?? 1_000;
+ const createMarkerNamespace = requireCreateMarkerNamespace(
+ options.createMarkerNamespace ?? randomUUID().replaceAll("-", ""),
+ );
+ const createMarkerPrefix = `${CREATE_MARKER_PREFIX}${createMarkerNamespace}__`;
if (bootTimeoutMs <= 0 || pollIntervalMs <= 0) {
throw new IOSSimulatorInstanceError(
"INVALID_ARGUMENT",
@@ -467,10 +509,25 @@ export function createIOSSimulatorSimctlLifecycle(
return result;
}
- async function cleanupFailedCreate(udid: string): Promise<void> {
- const result = await runner.run(XCRUN, ["simctl", "delete", udid], {
- timeoutMs: CREATE_ABORT_CLEANUP_TIMEOUT_MS,
- });
+ function isPendingCreateName(name: string): boolean {
+ return (
+ isIOSSimulatorPendingCreateName(name) &&
+ name.startsWith(createMarkerPrefix) &&
+ CREATE_MARKER_UUID_PATTERN.test(name.slice(createMarkerPrefix.length))
+ );
+ }
+
+ async function cleanupFailedCreate(
+ udid: string,
+ signal?: AbortSignal,
+ ): Promise<void> {
+ const result = await runner.run(
+ XCRUN,
+ ["simctl", "delete", udid],
+ signal
+ ? { timeoutMs: CREATE_ABORT_CLEANUP_TIMEOUT_MS, signal }
+ : { timeoutMs: CREATE_ABORT_CLEANUP_TIMEOUT_MS },
+ );
if (result.exitCode !== 0) {
throw new IOSSimulatorInstanceError(
"SIMULATOR_DELETE_FAILED",
@@ -480,6 +537,27 @@ export function createIOSSimulatorSimctlLifecycle(
}
}
+ async function recoverCreatedMarker(
+ markerName: string,
+ deviceTypeIdentifier: string,
+ runtimeIdentifier: string,
+ signal: AbortSignal,
+ ): Promise<IOSSimulatorDevice | null> {
+ 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(
+ (device) =>
+ device.name === markerName &&
+ device.runtimeIdentifier === runtimeIdentifier &&
+ device.deviceTypeIdentifier === deviceTypeIdentifier &&
+ UUID_PATTERN.test(device.udid.toUpperCase()),
+ );
+ return candidates.length === 1 ? candidates[0]! : null;
+ }
+
async function list(signal?: AbortSignal): Promise<IOSSimulatorDevice[]> {
throwIfAborted(signal);
const result = signal
@@ -508,6 +586,26 @@ export function createIOSSimulatorSimctlLifecycle(
);
}
+ async function renameExact(
+ udid: string,
+ name: string,
+ signal?: AbortSignal,
+ ): Promise<void> {
+ const normalized = requireUdid(udid);
+ const targetName = requireIdentifier(name, "name");
+ const result = await runSimctl(
+ ["simctl", "rename", normalized, targetName],
+ signal,
+ );
+ if (result.exitCode !== 0) {
+ throw new IOSSimulatorInstanceError(
+ "SIMULATOR_CREATE_FAILED",
+ "The newly created iOS Simulator could not be named.",
+ true,
+ );
+ }
+ }
+
return {
findExact,
@@ -627,7 +725,7 @@ export function createIOSSimulatorSimctlLifecycle(
},
async createExact(input, signal): Promise<IOSSimulatorCreatedDevice> {
- const name = requireIdentifier(input.name, "name");
+ requireIdentifier(input.name, "name");
const deviceTypeIdentifier = requireIdentifier(
input.deviceTypeIdentifier,
"deviceTypeIdentifier",
@@ -636,46 +734,135 @@ export function createIOSSimulatorSimctlLifecycle(
input.runtimeIdentifier,
"runtimeIdentifier",
);
+ const markerName = `${createMarkerPrefix}${randomUUID()}`;
throwIfAborted(signal);
- const result = await runner.run(
- XCRUN,
- ["simctl", "create", name, deviceTypeIdentifier, runtimeIdentifier],
- signal ? { timeoutMs: 60_000, signal } : { timeoutMs: 60_000 },
- );
- const udid = result.stdout.trim().toUpperCase();
- const hasExactCreatedDevice = UUID_PATTERN.test(udid);
+ let result: IOSSimulatorCommandResult | null = null;
+ let commandError: unknown = null;
+ try {
+ result = await runner.run(
+ XCRUN,
+ [
+ "simctl",
+ "create",
+ markerName,
+ deviceTypeIdentifier,
+ runtimeIdentifier,
+ ],
+ signal ? { timeoutMs: 60_000, signal } : { timeoutMs: 60_000 },
+ );
+ } catch (error) {
+ commandError = error;
+ }
+
+ const stdoutUdid = result?.stdout.trim().toUpperCase() ?? "";
+ let createdDevice: IOSSimulatorCreatedDevice | null = UUID_PATTERN.test(
+ stdoutUdid,
+ )
+ ? {
+ udid: stdoutUdid,
+ name: markerName,
+ runtimeIdentifier,
+ deviceTypeIdentifier,
+ }
+ : null;
const createFailure =
- result.exitCode !== 0 || !hasExactCreatedDevice
+ commandError ??
+ (result?.exitCode !== 0
? new IOSSimulatorInstanceError(
"SIMULATOR_CREATE_FAILED",
"The iOS Simulator device could not be created.",
)
- : null;
- if (hasExactCreatedDevice && (signal?.aborted || createFailure)) {
- const createdDevice = {
- udid,
- name,
- runtimeIdentifier,
- deviceTypeIdentifier,
- };
+ : null);
+
+ // CoreSimulator may commit the device before a cancelled xcrun flushes
+ // its UUID. The random profile marker remains in CoreSimulator itself,
+ // so one bounded post-create list can recover only this operation.
+ let cleanupController: AbortController | null = null;
+ let cleanupTimer: ReturnType<typeof setTimeout> | null = null;
+ if (!createdDevice) {
+ cleanupController = new AbortController();
+ cleanupTimer = setTimeout(
+ () => cleanupController?.abort(),
+ CREATE_ABORT_RECONCILE_TIMEOUT_MS,
+ );
+ cleanupTimer.unref?.();
+ try {
+ const recovered = await recoverCreatedMarker(
+ markerName,
+ deviceTypeIdentifier,
+ runtimeIdentifier,
+ cleanupController.signal,
+ );
+ if (recovered) {
+ createdDevice = {
+ udid: recovered.udid.toUpperCase(),
+ name: markerName,
+ runtimeIdentifier,
+ deviceTypeIdentifier,
+ };
+ }
+ } catch {
+ // The marker is profile-scoped and remains recoverable on startup.
+ }
+ }
+
+ if (createdDevice && (signal?.aborted || createFailure)) {
const originalReason = signal?.aborted ? signal.reason : createFailure;
try {
- await cleanupFailedCreate(udid);
+ await cleanupFailedCreate(
+ createdDevice.udid,
+ cleanupController?.signal,
+ );
} catch (error) {
throw new IOSSimulatorCreateCleanupRequiredError(
createdDevice,
originalReason,
- {
- cause: error,
- },
+ { cause: error },
);
+ } finally {
+ if (cleanupTimer) clearTimeout(cleanupTimer);
}
+ } else if (cleanupTimer) {
+ clearTimeout(cleanupTimer);
}
if (signal?.aborted) {
throwIfAborted(signal);
}
+ if (commandError) throw commandError;
if (createFailure) throw createFailure;
- return { udid, name, runtimeIdentifier, deviceTypeIdentifier };
+ if (!createdDevice) {
+ throw new IOSSimulatorInstanceError(
+ "SIMULATOR_CREATE_FAILED",
+ "The iOS Simulator device could not be created.",
+ );
+ }
+ return createdDevice;
+ },
+
+ renameExact,
+
+ async reconcilePendingCreates(
+ 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) &&
+ owned.has(device.udid.toUpperCase()),
+ );
+ const reconciled: string[] = [];
+ for (const device of pending) {
+ const udid = device.udid.toUpperCase();
+ await renameExact(udid, owned.get(udid)!, signal);
+ reconciled.push(udid);
+ }
+ return reconciled;
},
async deleteExact(udid, signal): Promise<void> {