Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): close simulator review gaps
JiangJiahao6ab65a0b9c3c
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.tsindex 5e47400895..2aa8c2859e 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts@@ -290,7 +290,7 @@ describe('iOS Simulator IPC handlers', () => {generation: 3,leaseId: 'lease-a',};- await harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_LIVE_TOUCH, {+ await harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_LIVE_TOUCH, {...route,gestureId: 'viewer-7',phase: 'move',@@ -300,6 +300,7 @@ describe('iOS Simulator IPC handlers', () => {expect(updateViewerTouch).toHaveBeenCalledWith('session-a',{ instanceId: 'instance-a', generation: 3, leaseId: 'lease-a' },+ 17,{gestureId: 'viewer-7',phase: 'move',@@ -307,6 +308,15 @@ describe('iOS Simulator IPC handlers', () => {yRatio: 0.75,},);+ await expect(+ harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_LIVE_TOUCH, {+ ...route,+ gestureId: 'viewer-7',+ phase: 'move',+ xRatio: 0.25,+ yRatio: 0.75,+ }),+ ).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });await expect(harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_LIVE_TOUCH, {...route,diff --git a/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts b/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.tsindex cd5b1367ec..40b6100447 100644--- a/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts+++ b/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts@@ -61,6 +61,7 @@ export interface IOSSimulatorHandlerDeps {updateViewerTouch(sessionId: string,route: { instanceId: string; generation: number; leaseId: string },+ viewerWebContentsId: number,touch: {gestureId: string;phase: 'begin' | 'move' | 'end' | 'cancel';@@ -307,7 +308,7 @@ export function registerIOSSimulatorHandlers(nativeProfile,);});- handle(MAKER_INVOKE.IOS_SIMULATOR_LIVE_TOUCH, async (_event, payload) => {+ handle(MAKER_INVOKE.IOS_SIMULATOR_LIVE_TOUCH, async (event, payload) => {const record = readRecord(payload);const sessionId = readSessionId(record);const gestureId = record.gestureId;@@ -330,11 +331,16 @@ export function registerIOSSimulatorHandlers() {throwIpcError('INVALID_PARAMS', 'touch coordinates must be normalized');}- return resolved.updateViewerTouch(sessionId, readViewerRoute(record), {- gestureId: gestureId.trim(),- phase,- xRatio: record.xRatio,- yRatio: record.yRatio,- });+ return resolved.updateViewerTouch(+ sessionId,+ readViewerRoute(record),+ readSenderWebContentsId(event),+ {+ gestureId: gestureId.trim(),+ phase,+ xRatio: record.xRatio,+ yRatio: record.yRatio,+ },+ );});}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 7ffd5ef03f..9692bbfe80 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@@ -8,6 +8,7 @@ import {createIOSSimulatorNativeDevelopmentAdmissionPolicy,evaluateIOSSimulatorNativeCapabilityAdmission,IOSSimulatorInstanceActor,+ IOSSimulatorInstanceError,IOSSimulatorOwnershipStore,IOSSimulatorProjectBuildError,IOSSimulatorResourceScheduler,@@ -2788,16 +2789,25 @@ describe('iOS Simulator host', () => {lifecycle,});const requestViewerFocus = vi.fn();+ const resourceScheduler = testResourceScheduler();+ const driverManager = {+ get: vi.fn(() => null),+ start: vi.fn(async (options: { instanceId: string; simulatorUdid: string }) => {+ return {+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: 42,+ driver: {},+ driverSessionId: 'wda-session',+ } as unknown as WdaRunningInstance;+ }),+ stop: vi.fn(async () => undefined),+ };+ driverManager.start.mockRejectedValueOnce(new WdaError('UNREACHABLE', 'driver failed'));const host = createIOSSimulatorHost({actor,lifecycle,- driverManager: {- get: vi.fn(() => null),- start: vi.fn(async () => {- throw new WdaError('UNREACHABLE', 'driver failed');- }),- stop: vi.fn(async () => undefined),- },+ driverManager,requestViewerFocus,runtime: {inspect: vi.fn(async () => ({@@ -2807,7 +2817,7 @@ describe('iOS Simulator host', () => {},getSession: vi.fn(async (id) => localSession(id)),resolveWorktreeRoot: vi.fn(async (workDir) => workDir),- resourceScheduler: testResourceScheduler(),+ resourceScheduler,});await host.callTool(@@ -2831,8 +2841,101 @@ describe('iOS Simulator host', () => {errorCode: 'DRIVER_DISCONNECTED',});expect(requestViewerFocus).not.toHaveBeenCalled();+ expect(resourceScheduler.runningCount()).toBe(1);+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();+ const retryInstance = actor.list('failed-session')[0]!;+ expect(retryInstance).toMatchObject({+ lifecycleState: 'ready',+ healthState: 'degraded',+ errorCode: 'WDA_UNAVAILABLE',+ });+ await expect(+ host.callTool(+ 'start_instance',+ {+ instanceId: retryInstance.instanceId,+ generation: retryInstance.generation,+ leaseId: retryInstance.lease.id,+ },+ { sessionId: 'failed-session', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: true });+ expect(lifecycle.bootExact).toHaveBeenCalledOnce();+ expect(driverManager.start).toHaveBeenCalledTimes(2);+ expect(resourceScheduler.runningCount()).toBe(1);});+ it.each(['booting', 'probe-error'] as const)(+ 'keeps scheduler occupancy when readiness fails with a %s exact probe',+ async (probeMode) => {+ const shutdownDevice = { ...READY_REPORT.devices[0]!, state: 'Shutdown' as const };+ const bootingDevice = { ...READY_REPORT.devices[0]!, state: 'Booting' as const };+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(async () => {+ if (probeMode === 'probe-error') throw new Error('simctl probe failed');+ return bootingDevice;+ }),+ bootExact: vi.fn(async () => {+ throw new IOSSimulatorInstanceError(+ 'SIMULATOR_BOOT_TIMEOUT',+ 'Device boot started but readiness timed out.',+ true,+ );+ }),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore(),+ lifecycle,+ });+ const resourceScheduler = testResourceScheduler();+ const driverManager = {+ get: vi.fn(() => null),+ start: vi.fn(),+ stop: vi.fn(async () => undefined),+ };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ runtime: {+ inspect: vi.fn(async () => ({ ...READY_REPORT, devices: [shutdownDevice] })),+ },+ getSession: vi.fn(async (id) => localSession(id)),+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),+ resourceScheduler,+ deviceLivenessIntervalMs: 0,+ });++ await host.callTool(+ 'attach_device',+ { udid: shutdownDevice.udid },+ { sessionId: 'boot-timeout-session', origin: 'user' },+ );+ const attached = actor.list('boot-timeout-session')[0]!;+ await expect(+ host.callTool(+ 'start_instance',+ {+ instanceId: attached.instanceId,+ generation: attached.generation,+ leaseId: attached.lease.id,+ },+ { sessionId: 'boot-timeout-session', origin: 'user' },+ ),+ ).resolves.toMatchObject({ ok: false, errorCode: 'SIMULATOR_BOOT_TIMEOUT' });+ expect(resourceScheduler.runningCount()).toBe(1);+ expect(driverManager.start).not.toHaveBeenCalled();+ expect(actor.list('boot-timeout-session')[0]).toMatchObject({+ lifecycleState: 'error',+ errorCode: 'SIMULATOR_BOOT_TIMEOUT',+ });+ await host.dispose();+ },+ );+it('cancels an active build before detaching and releasing scheduler capacity', async () => {const lifecycle: IOSSimulatorSimctlLifecycle = {findExact: vi.fn(),@@ -3226,6 +3329,9 @@ describe('iOS Simulator host', () => {ok: true,data: { profile: { framesPerSecond: 10, jpegQuality: 45, scalingPercent: 70 } },});+ await expect(+ host.setViewerVisibility('session-a', route, true, 'jpeg', undefined, 17, 'viewer-token'),+ ).resolves.toMatchObject({ ok: true });await expect(host.callTool('stop_instance', route, { sessionId: 'session-a', origin: 'agent' }),).resolves.toMatchObject({ ok: false, errorCode: 'DEVICE_CONTROL_NOT_GRANTED' });@@ -3605,7 +3711,16 @@ describe('iOS Simulator host', () => {expect(swipeCall[3]).toBe(250);nativeInputEnabled = true;await expect(- host.updateViewerTouch('session-a', route, {+ host.updateViewerTouch('session-a', route, 18, {+ gestureId: 'viewer-1',+ phase: 'begin',+ xRatio: 0.1,+ yRatio: 0.2,+ }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'INSTANCE_NOT_OWNED' });+ expect(nativeInput.beginTouch).not.toHaveBeenCalled();+ await expect(+ host.updateViewerTouch('session-a', route, 17, {gestureId: 'viewer-1',phase: 'begin',xRatio: 0.1,@@ -3613,7 +3728,7 @@ describe('iOS Simulator host', () => {}),).resolves.toMatchObject({ ok: true });await expect(- host.updateViewerTouch('session-a', route, {+ host.updateViewerTouch('session-a', route, 17, {gestureId: 'viewer-1',phase: 'move',xRatio: 0.5,@@ -3621,7 +3736,7 @@ describe('iOS Simulator host', () => {}),).resolves.toMatchObject({ ok: true });await expect(- host.updateViewerTouch('session-a', route, {+ host.updateViewerTouch('session-a', route, 17, {gestureId: 'viewer-1',phase: 'end',xRatio: 0.9,diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.tsindex 4c89656ba4..2b9dbd994a 100644--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts@@ -230,6 +230,7 @@ export interface IOSSimulatorHost {updateViewerTouch(sessionId: string,route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,+ viewerWebContentsId: number,touch: {gestureId: string;phase: 'begin' | 'move' | 'end' | 'cancel';@@ -2648,6 +2649,26 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Ireturn nativeH264Driver(running);}+ function assertCurrentViewer(+ sessionId: string,+ instanceId: string,+ viewerWebContentsId: number,+ ): void {+ const viewer = viewerSessions.get(instanceId);+ if (+ !viewer ||+ viewer.sessionId !== sessionId ||+ viewer.webContentsId === null ||+ viewer.webContentsId !== viewerWebContentsId+ ) {+ throw new IOSSimulatorInstanceError(+ 'INSTANCE_NOT_OWNED',+ 'This simulator viewer is not owned by the current Cindy window.',+ true,+ );+ }+ }+function startViewerStream(instance: IOSSimulatorInstance,running: WdaRunningInstance,@@ -2838,8 +2859,12 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Ireturn viewerRouteRefreshResult(instance);}try {- running = await resourceScheduler.runStart(instance.instanceId, () =>- ensureDriver(instance, environment),+ running = await resourceScheduler.runStart(+ instance.instanceId,+ async (commitRunning) => {+ commitRunning();+ return ensureDriver(instance, environment);+ },);} catch (error) {if (isInstanceError(error, 'STALE_GENERATION')) {@@ -2913,19 +2938,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Iconst resolved = await resolveSession(sessionId);if (!resolved.ok) return resolved;assertHostActive();- const viewer = viewerSessions.get(route.instanceId);- if (- !viewer ||- viewer.sessionId !== resolved.sessionId ||- viewer.webContentsId === null ||- viewer.webContentsId !== viewerWebContentsId- ) {- return {- ok: false,- errorCode: 'INSTANCE_NOT_OWNED',- message: 'This simulator viewer is not owned by the current Cindy window.',- };- }+ assertCurrentViewer(resolved.sessionId, route.instanceId, viewerWebContentsId);let instance = actor.heartbeat({ ...route, sessionId: resolved.sessionId });instance = await reconcileLiveDevice(instance);assertHostActive();@@ -3040,17 +3053,19 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Ireturn safeHostError(error, sessionId, 'set_agent_mutation_paused');}},- async updateViewerTouch(sessionId, route, touch) {+ async updateViewerTouch(sessionId, route, viewerWebContentsId, touch) {try {assertHostActive();const resolved = await resolveSession(sessionId);if (!resolved.ok) return resolved;assertHostActive();+ assertCurrentViewer(resolved.sessionId, route.instanceId, viewerWebContentsId);const mutationRoute = { ...route, sessionId: resolved.sessionId };await runHostMutation(mutationRoute,{ sessionId: resolved.sessionId, origin: 'user' },async (instance, signal) => {+ assertCurrentViewer(resolved.sessionId, instance.instanceId, viewerWebContentsId);const running = requireDriver(instance.instanceId);const nativeInput = running.driverRouter?.continuousInput();if (!nativeInput) {@@ -3061,6 +3076,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I);}const { viewer, driver } = await currentViewports(running);+ assertCurrentViewer(resolved.sessionId, instance.instanceId, viewerWebContentsId);const driverPoint = pointFromViewer({ xRatio: touch.xRatio, yRatio: touch.yRatio },viewer,@@ -3215,12 +3231,35 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Imessage: safeEnvironment.error ?? 'iOS Simulator is not ready.',};}- const instance = await resourceScheduler.runStart(route.instanceId, async () => {- assertHostActive();- const started = await actor.start(route);- await ensureDriver(started, environment);- return actor.heartbeatOwned(sessionId, started.instanceId);- });+ const instance = await resourceScheduler.runStart(+ route.instanceId,+ async (commitRunning) => {+ assertHostActive();+ const starting = actor.getOwned(sessionId, route.instanceId);+ try {+ const started = await actor.start(route);+ commitRunning();+ await ensureDriver(started, environment);+ return actor.heartbeatOwned(sessionId, started.instanceId);+ } catch (error) {+ // simctl can boot the device and then fail while waiting for+ // readiness. Preserve the real resource occupancy even when+ // actor.start() never returns its ready snapshot.+ try {+ const device = await lifecycle.findExact(starting.simulatorUdid);+ if (device && device.state.trim().toLowerCase() !== 'shutdown') {+ commitRunning();+ }+ } catch {+ // An ambiguous probe cannot prove that CoreSimulator+ // released the resource. Fail closed while preserving the+ // original startup failure as the authoritative error.+ commitRunning();+ }+ throw error;+ }+ },+ );completeInstanceActivation(instance, activationEpoch);screenMaps.clear(instance.instanceId);framePump.clear(instance.instanceId);@@ -4739,7 +4778,8 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I? existingActivationEpoch: captureInstanceActivation(instance.instanceId);if (instance.lifecycleState === 'ready') {- await resourceScheduler.runStart(instance.instanceId, async () => {+ await resourceScheduler.runStart(instance.instanceId, async (commitRunning) => {+ commitRunning();await ensureDriver(instance, environment);});}@@ -4938,6 +4978,7 @@ export function setIOSSimulatorViewerStreamProfile(export function updateIOSSimulatorViewerTouch(sessionId: string,route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,+ viewerWebContentsId: number,touch: {gestureId: string;phase: 'begin' | 'move' | 'end' | 'cancel';@@ -4945,7 +4986,7 @@ export function updateIOSSimulatorViewerTouch(yRatio: number;},): Promise<IOSSimulatorHostResult> {- return defaultIOSSimulatorHost.updateViewerTouch(sessionId, route, touch);+ return defaultIOSSimulatorHost.updateViewerTouch(sessionId, route, viewerWebContentsId, touch);}export interface IOSSimulatorMcpDepsOptions {diff --git a/packages/ios-simulator-runtime/src/native-sidecar/channel.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/channel.test.tsindex 8ee1790919..bf6448e32f 100644--- a/packages/ios-simulator-runtime/src/native-sidecar/channel.test.ts+++ b/packages/ios-simulator-runtime/src/native-sidecar/channel.test.ts@@ -33,18 +33,31 @@ class FakeSidecarProcess});readonly pid = 123;emitExitOnKill = true;+ readonly killSignals: NodeJS.Signals[] = [];+ readonly exited: Promise<void>;+ #resolveExited!: () => void;++ constructor() {+ super();+ this.exited = new Promise<void>((resolve) => {+ this.#resolveExited = resolve;+ });+ }kill(signal: NodeJS.Signals = "SIGTERM"): boolean {+ this.killSignals.push(signal);if (this.emitExitOnKill) {this.stdout.end();this.stderr.end();- this.emit("exit", null, signal);+ this.exit(null, signal);}return true;}exit(code: number | null = 1, signal: NodeJS.Signals | null = null): void {this.emit("exit", code, signal);+ this.#resolveExited();+ this.emit("close", code, signal);}}@@ -178,6 +191,31 @@ describe("IOSSimulatorNativeSidecarChannel", () => {await channel.stop();});+ it("waits for exit and escalates a stuck sidecar process group", async () => {+ vi.useFakeTimers();+ try {+ const { channel, launcher, processes } = harness({ stopTimeoutMs: 5 });+ await channel.start();+ const process = processes[0]!;+ process.emitExitOnKill = false;++ const stop = channel.stop();+ expect(process.killSignals).toEqual(["SIGTERM"]);+ const restart = channel.start();+ expect(launcher.launch).toHaveBeenCalledTimes(1);++ await vi.advanceTimersByTimeAsync(5);+ expect(process.killSignals).toEqual(["SIGTERM", "SIGKILL"]);+ process.exit(null, "SIGKILL");+ await stop;+ await restart;+ expect(launcher.launch).toHaveBeenCalledTimes(2);+ await channel.stop();+ } finally {+ vi.useRealTimers();+ }+ });+it("terminates the process after consecutive request timeouts", async () => {const { channel } = harness({requestTimeoutMs: 5,@@ -203,6 +241,42 @@ describe("IOSSimulatorNativeSidecarChannel", () => {expect(channel.state).toBe("failed");});+ it("waits for a faulted process to close before stop or restart completes", async () => {+ vi.useFakeTimers();+ try {+ const { channel, launcher, processes } = harness({ stopTimeoutMs: 5 });+ await channel.start();+ const process = processes[0]!;+ process.emitExitOnKill = false;+ const pending = channel.request(command("availability"));++ process.stdout.write(new Uint8Array([0, 0, 0, 0, 255]));+ await expect(pending).rejects.toMatchObject({ code: "PROTOCOL_ERROR" });+ expect(channel.state).toBe("failed");+ expect(process.killSignals).toEqual(["SIGTERM"]);++ const stop = channel.stop();+ const restart = channel.start();+ expect(launcher.launch).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(5);+ expect(process.killSignals).toEqual(["SIGTERM", "SIGKILL"]);+ let settled = false;+ void Promise.all([stop, restart]).then(() => {+ settled = true;+ });+ await Promise.resolve();+ expect(settled).toBe(false);++ process.exit(null, "SIGKILL");+ await stop;+ await restart;+ expect(launcher.launch).toHaveBeenCalledTimes(2);+ await channel.stop();+ } finally {+ vi.useRealTimers();+ }+ });+it("stops a stream at maxFrames and rejects stale stream identities", async () => {const { channel, processes } = harness();await channel.start();@@ -303,7 +377,7 @@ describe("IOSSimulatorNativeSidecarChannel", () => {});});- it("does not let a retired process exit invalidate its replacement", async () => {+ it("waits for a retired process before launching an isolated replacement", async () => {const { channel, processes } = harness();await channel.start();const retired = processes[0]!;@@ -311,9 +385,11 @@ describe("IOSSimulatorNativeSidecarChannel", () => {const pending = channel.request(command("availability"));retired.stdout.write(new Uint8Array([0, 0, 0, 0, 255]));await expect(pending).rejects.toMatchObject({ code: "PROTOCOL_ERROR" });- await channel.restart();- expect(channel.state).toBe("running");+ const restart = channel.restart();+ await Promise.resolve();+ expect(processes).toHaveLength(1);retired.exit(1, "SIGKILL");+ await restart;expect(channel.state).toBe("running");const replacementRequest = channel.request(command("availability"));processes[1]!.stdout.write(diff --git a/packages/ios-simulator-runtime/src/native-sidecar/channel.ts b/packages/ios-simulator-runtime/src/native-sidecar/channel.tsindex e0dd66f5ee..91fc045746 100644--- a/packages/ios-simulator-runtime/src/native-sidecar/channel.ts+++ b/packages/ios-simulator-runtime/src/native-sidecar/channel.ts@@ -25,6 +25,7 @@ const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;const DEFAULT_MAX_CRASHES = 3;const DEFAULT_MAX_CONSECUTIVE_TIMEOUTS = 2;const DEFAULT_RESTART_BASE_DELAY_MS = 250;+const DEFAULT_STOP_TIMEOUT_MS = 2_000;const MAX_STDERR_TAIL_BYTES = 64 * 1024;const MAX_EARLY_STREAM_EVENTS_PER_STREAM = 4;const MAX_EARLY_STREAMS = 8;@@ -58,6 +59,8 @@ export interface IOSSimulatorNativeSidecarManagedProcess {readonly stdin: Writable;readonly stdout: Readable;readonly stderr: Readable;+ /** Resolves only after the process and its inherited stdio handles close. */+ readonly exited: Promise<void>;once(event: "error", listener: (error: Error) => void): this;once(event: "exit",@@ -105,12 +108,16 @@ class NodeIOSSimulatorNativeSidecarManagedProcess implements IOSSimulatorNativeSreadonly stdin: Writable;readonly stdout: Readable;readonly stderr: Readable;+ readonly exited: Promise<void>;constructor(readonly child: ChildProcessWithoutNullStreams) {this.pid = child.pid;this.stdin = child.stdin;this.stdout = child.stdout;this.stderr = child.stderr;+ this.exited = new Promise<void>((resolve) => {+ child.once("close", () => resolve());+ });}once(event: "error", listener: (error: Error) => void): this;@@ -157,6 +164,7 @@ export interface IOSSimulatorNativeSidecarChannelOptions {maxCrashes?: number;maxConsecutiveTimeouts?: number;restartBaseDelayMs?: number;+ stopTimeoutMs?: number;sleep?: (ms: number) => Promise<void>;now?: () => Date;}@@ -291,6 +299,7 @@ export class IOSSimulatorNativeSidecarChannel implements IOSSimulatorNativeSidec| "maxCrashes"| "maxConsecutiveTimeouts"| "restartBaseDelayMs"+ | "stopTimeoutMs">> &Pick<IOSSimulatorNativeSidecarChannelOptions, "sleep" | "now">;@@ -314,6 +323,8 @@ export class IOSSimulatorNativeSidecarChannel implements IOSSimulatorNativeSidecnull;#earlyStreamBytes = 0;#stopRequested = false;+ #stopPromise: Promise<void> | null = null;+ #stoppingProcess: IOSSimulatorNativeSidecarManagedProcess | null = null;constructor(options: IOSSimulatorNativeSidecarChannelOptions) {this.#launcher = options.launcher;@@ -324,6 +335,7 @@ export class IOSSimulatorNativeSidecarChannel implements IOSSimulatorNativeSidecoptions.maxConsecutiveTimeouts ?? DEFAULT_MAX_CONSECUTIVE_TIMEOUTS,restartBaseDelayMs:options.restartBaseDelayMs ?? DEFAULT_RESTART_BASE_DELAY_MS,+ stopTimeoutMs: options.stopTimeoutMs ?? DEFAULT_STOP_TIMEOUT_MS,sleep: options.sleep,now: options.now,};@@ -337,6 +349,7 @@ export class IOSSimulatorNativeSidecarChannel implements IOSSimulatorNativeSidecthis.#options.restartBaseDelayMs,"restartBaseDelayMs",);+ requirePositiveInteger(this.#options.stopTimeoutMs, "stopTimeoutMs");}get state(): IOSSimulatorNativeSidecarChannelState {@@ -356,6 +369,7 @@ export class IOSSimulatorNativeSidecarChannel implements IOSSimulatorNativeSidec}async start(): Promise<void> {+ if (this.#stopPromise) await this.#stopPromise;if (this.#state === "running" && this.#process) return;if (this.#state === "parked") {throw new IOSSimulatorNativeSidecarChannelError(@@ -502,7 +516,70 @@ export class IOSSimulatorNativeSidecarChannel implements IOSSimulatorNativeSidec"Native sidecar channel stopped.",),);- if (process) process.kill("SIGTERM");+ if (process) return this.#ensureProcessClosed(process, true);+ if (this.#stopPromise) return this.#stopPromise;+ }++ #ensureProcessClosed(+ process: IOSSimulatorNativeSidecarManagedProcess,+ terminate: boolean,+ ): Promise<void> {+ if (this.#stopPromise && this.#stoppingProcess === process) {+ return this.#stopPromise;+ }+ if (this.#stopPromise) {+ return this.#stopPromise.then(() =>+ this.#ensureProcessClosed(process, terminate),+ );+ }+ const operation = terminate+ ? this.#terminateStoppedProcess(process)+ : process.exited;+ const stopPromise = operation.finally(() => {+ if (this.#stopPromise === stopPromise) {+ this.#stopPromise = null;+ this.#stoppingProcess = null;+ }+ });+ this.#stoppingProcess = process;+ this.#stopPromise = stopPromise;+ return stopPromise;+ }++ async #terminateStoppedProcess(+ process: IOSSimulatorNativeSidecarManagedProcess,+ ): Promise<void> {+ const terminated = this.#waitForProcessExit(+ process,+ this.#options.stopTimeoutMs,+ );+ process.kill("SIGTERM");+ if (await terminated) return;+ const killed = this.#waitForProcessExit(+ process,+ this.#options.stopTimeoutMs,+ );+ process.kill("SIGKILL");+ if (!(await killed)) await process.exited;+ }++ #waitForProcessExit(+ process: IOSSimulatorNativeSidecarManagedProcess,+ timeoutMs: number,+ ): Promise<boolean> {+ return new Promise<boolean>((resolve) => {+ let settled = false;+ const timer = setTimeout(() => {+ settled = true;+ resolve(false);+ }, timeoutMs);+ void process.exited.then(() => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ resolve(true);+ });+ });}request(@@ -1028,7 +1105,7 @@ export class IOSSimulatorNativeSidecarChannel implements IOSSimulatorNativeSidecthis.#recordCrash();}this.#rejectAll(error);- if (kill) process.kill("SIGTERM");+ void this.#ensureProcessClosed(process, kill).catch(() => undefined);}#recordTermination(diff --git a/packages/ios-simulator-runtime/src/ownership-registry-file.test.ts b/packages/ios-simulator-runtime/src/ownership-registry-file.test.tsindex 5e92102d36..688279f615 100644--- a/packages/ios-simulator-runtime/src/ownership-registry-file.test.ts+++ b/packages/ios-simulator-runtime/src/ownership-registry-file.test.ts@@ -1,3 +1,4 @@+import { spawnSync } from "node:child_process";import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";import os from "node:os";import path from "node:path";@@ -174,7 +175,7 @@ describe("IOSSimulatorOwnershipRegistryFile", () => {const itMac = process.platform === "darwin" ? it : it.skip;itMac(- "holds the production advisory lock until the parent descriptor closes",+ "holds the production advisory lock on Main's descriptor until it closes",async () => {const root = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-registry-"));try {@@ -183,7 +184,30 @@ describe("IOSSimulatorOwnershipRegistryFile", () => {const second = new IOSSimulatorOwnershipRegistryFile(filePath);expect(first.acquireWriterSync()).toBe(true);expect(second.acquireWriterSync()).toBe(false);+ const contender = `+ const { closeSync, constants, openSync } = require("node:fs");+ try {+ const fd = openSync(+ process.argv[1],+ constants.O_CREAT | constants.O_RDWR | constants.O_NONBLOCK | 0x20,+ 0o600,+ );+ closeSync(fd);+ } catch (error) {+ process.exit(error?.code === "EAGAIN" || error?.code === "EWOULDBLOCK" ? 75 : 1);+ }+ `;+ expect(+ spawnSync(process.execPath, ["-e", contender, first.lockPath], {+ stdio: "ignore",+ }).status,+ ).toBe(75);first.releaseWriterSync();+ expect(+ spawnSync(process.execPath, ["-e", contender, first.lockPath], {+ stdio: "ignore",+ }).status,+ ).toBe(0);expect(second.acquireWriterSync()).toBe(true);second.releaseWriterSync();} finally {diff --git a/packages/ios-simulator-runtime/src/ownership-registry-file.ts b/packages/ios-simulator-runtime/src/ownership-registry-file.tsindex 553e561754..0d40f2c7c3 100644--- a/packages/ios-simulator-runtime/src/ownership-registry-file.ts+++ b/packages/ios-simulator-runtime/src/ownership-registry-file.ts@@ -1,7 +1,7 @@-import { spawnSync } from "node:child_process";import { randomUUID } from "node:crypto";import {closeSync,+ constants as fsConstants,mkdirSync,openSync,readFileSync,@@ -15,6 +15,8 @@ import { IOSSimulatorInstanceError } from "./instance-errors.js";import type { IOSSimulatorInstance } from "./instance-types.js";const REGISTRY_VERSION = 1;+// Darwin-only flag from <sys/fcntl.h>. Node does not expose O_EXLOCK.+const DARWIN_O_EXLOCK = 0x00000020;export interface IOSSimulatorRegistrySnapshot {version: 1;@@ -32,7 +34,7 @@ export type IOSSimulatorRegistryWriterLeaseFactory = () => IOSSimulatorRegistryWriterLease | null;export interface IOSSimulatorOwnershipRegistryFileOptions {- /** Cross-platform deterministic seam; production uses macOS lockf. */+ /** Cross-platform deterministic seam; production uses Darwin O_EXLOCK. */acquireWriterLease?: IOSSimulatorRegistryWriterLeaseFactory;}@@ -106,10 +108,9 @@ function parseSnapshot(value: unknown): IOSSimulatorInstance[] {}/**- * macOS `lockf` uses BSD flock semantics. Acquiring through an inherited file- * descriptor leaves the lock attached to the parent's open file description- * after the short-lived lockf process exits. Closing the descriptor (including- * process exit/crash) releases the lease without stale-file deletion races.+ * Darwin can atomically acquire a BSD flock while opening via O_EXLOCK. The+ * resulting descriptor is held directly by Electron Main for its lifetime;+ * close (including process exit/crash) releases it without stale-file races.*/function acquireDarwinWriterLease(lockPath: string,@@ -117,14 +118,14 @@ function acquireDarwinWriterLease(if (process.platform !== "darwin") return null;let fd: number | null = null;try {- fd = openSync(lockPath, "a+", 0o600);- const result = spawnSync("/usr/bin/lockf", ["-s", "-t", "0", "3"], {- stdio: ["ignore", "ignore", "ignore", fd],- });- if (result.status !== 0) {- closeSync(fd);- return null;- }+ fd = openSync(+ lockPath,+ fsConstants.O_CREAT |+ fsConstants.O_RDWR |+ fsConstants.O_NONBLOCK |+ DARWIN_O_EXLOCK,+ 0o600,+ );let held = true;return {isHeld: () => held,diff --git a/packages/ios-simulator-runtime/src/resource-scheduler.test.ts b/packages/ios-simulator-runtime/src/resource-scheduler.test.tsindex 5157a00935..ff917a577c 100644--- a/packages/ios-simulator-runtime/src/resource-scheduler.test.ts+++ b/packages/ios-simulator-runtime/src/resource-scheduler.test.ts@@ -115,6 +115,29 @@ describe("IOSSimulatorResourceScheduler", () => {);});+ it("keeps a booted instance admitted when later startup work fails", async () => {+ const scheduler = new IOSSimulatorResourceScheduler({+ softLimit: 1,+ hardLimit: 1,+ freeMemoryBytes: () => 100 * 1024 ** 3,+ });++ await expect(+ scheduler.runStart("a", async (commitRunning) => {+ commitRunning();+ throw new Error("driver failed");+ }),+ ).rejects.toThrow("driver failed");+ expect(scheduler.runningCount()).toBe(1);+ await expect(+ scheduler.runStart("b", async () => undefined),+ ).rejects.toMatchObject({ code: "RESOURCE_LIMIT_REACHED" });+ await expect(+ scheduler.runStart("a", async () => "recovered"),+ ).resolves.toBe("recovered");+ expect(scheduler.runningCount()).toBe(1);+ });+it("uses a hard architectural cap of four", async () => {const scheduler = new IOSSimulatorResourceScheduler({softLimit: 4,diff --git a/packages/ios-simulator-runtime/src/resource-scheduler.ts b/packages/ios-simulator-runtime/src/resource-scheduler.tsindex 4f9ad9b6ba..6a9fe92305 100644--- a/packages/ios-simulator-runtime/src/resource-scheduler.ts+++ b/packages/ios-simulator-runtime/src/resource-scheduler.ts@@ -142,7 +142,10 @@ export class IOSSimulatorResourceScheduler {this.#running.delete(instanceId);}- runStart<T>(instanceId: string, task: () => Promise<T>): Promise<T> {+ runStart<T>(+ instanceId: string,+ task: (commitRunning: () => void) => Promise<T>,+ ): Promise<T> {const previous = this.#startTail;let release: () => void = () => undefined;const gate = new Promise<void>((resolve) => {@@ -154,7 +157,8 @@ export class IOSSimulatorResourceScheduler {.then(async () => {try {if (!this.#running.has(instanceId)) await this.#assertAdmission();- const result = await task();+ const commitRunning = () => this.#running.add(instanceId);+ const result = await task(commitRunning);this.#running.add(instanceId);return result;} finally {