Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): harden simulator runtime shutdown
JiangJiahaob28b7e442d56
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 8e9179d136..19be11aa0d 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -452,7 +452,6 @@ import { registerAndroidAutomationHandlers } from './androidHandlers.js';import { registerIOSSimulatorHandlers } from './iosSimulatorHandlers.js';import {cancelIOSSimulatorSessionOperations,- reconcileIOSSimulatorOwnership,} from '../mcp-integrations/ios-simulator.js';import { MAKER_INVOKE, MAKER_PUSH, MAKER_SEND } from './channels.js';import type { CollabDispatchOutcome } from './collabSendOutcome.js';@@ -12291,9 +12290,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)registerIOSSimulatorHandlers(createElectronIpcHandlerRegistry(),);- void reconcileIOSSimulatorOwnership().catch((error) => {- log.warn('iOS Simulator ownership reconcile failed during IPC bootstrap', error);- });// ── Browser automation (Settings →「电脑使用」) ───────────────────────────// Probe local browser detection. Drives the detection status + downloaddiff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-exit.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-exit.test.tsindex 1253f562cc..4ed8a3d24a 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-exit.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-exit.test.ts@@ -34,4 +34,12 @@ describe('iOS Simulator updater exit abort seam', () => {expect(first).not.toHaveBeenCalled();expect(second).toHaveBeenCalledOnce();});++ it('does not let a cleanup failure block the updater exit seam', () => {+ unregister = registerIOSSimulatorExitAbortHandler(() => {+ throw new Error('already exited');+ });++ expect(() => abortIOSSimulatorOperationsForExit()).not.toThrow();+ });});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 17fbfd594f..c8a080a901 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@@ -1,4 +1,5 @@import { mkdir, mkdtemp, rm, stat, utimes, writeFile } from 'node:fs/promises';+import { readFileSync } from 'node:fs';import os from 'node:os';import path from 'node:path';@@ -26,8 +27,11 @@ import {} from '@cindy/ios-simulator-runtime';import type { IOSSimulatorPublicRouteStatus } from '../../../shared/iosSimulatorIpc';import {+ cancelIOSSimulatorSessionOperations,+ cleanupIOSSimulatorRemovedSession,createIOSSimulatorHost,createRegistryBackedIOSSimulatorActor,+ flushIOSSimulatorOwnershipRegistry,getIOSSimulatorMcpDeps,type IOSSimulatorAppLifecycleAdapter,type IOSSimulatorMediaCaptureAdapter,@@ -78,6 +82,31 @@ describe('iOS Simulator host', () => {return { id, workDir: `/tmp/${id}`, remoteHostId: null };}+ it('keeps the default ownership registry lazy for disabled MCP discovery', async () => {+ const getPath = vi.spyOn(app, 'getPath');+ try {+ const deps = getIOSSimulatorMcpDeps({ isIOSSimulatorEnabled: () => false });++ await expect(deps.describeTools?.({ sessionId: 'disabled-session' })).resolves.toMatchObject({+ ready: false,+ });+ await expect(+ deps.callTool('check_environment', {}, { sessionId: 'disabled-session' }),+ ).resolves.toMatchObject({ errorCode: 'IOS_SIMULATOR_DISABLED' });+ await cancelIOSSimulatorSessionOperations('ordinary-session');+ await cleanupIOSSimulatorRemovedSession('ordinary-session');+ await flushIOSSimulatorOwnershipRegistry();+ expect(getPath).not.toHaveBeenCalled();+ } finally {+ getPath.mockRestore();+ }+ });++ it('does not reconcile Simulator ownership during generic IPC bootstrap', () => {+ const source = readFileSync(new URL('../../maker-ipc/register.ts', import.meta.url), 'utf8');+ expect(source).not.toContain('reconcileIOSSimulatorOwnership');+ });+it('returns device discovery for a local session', async () => {const host = createIOSSimulatorHost({runtime: { inspect: vi.fn(async () => READY_REPORT) },@@ -200,7 +229,6 @@ describe('iOS Simulator host', () => {bootProvenance: 'preexisting',});const resourceScheduler = testResourceScheduler();- await resourceScheduler.runStart('running-instance', async () => undefined);const host = createIOSSimulatorHost({actor,lifecycle,@@ -418,6 +446,97 @@ describe('iOS Simulator host', () => {});});+ it.each(['Booted', 'Booting'] as const)(+ 'restores scheduler occupancy for a persisted %s device',+ async (deviceState) => {+ 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 instance = actor.attach({+ sessionId: 'persisted-capacity-session',+ worktreeRoot: '/tmp/persisted-capacity-session',+ sourceFingerprint: 'fingerprint-a',+ device: { ...READY_REPORT.devices[0]!, state: deviceState },+ });+ const resourceScheduler = new IOSSimulatorResourceScheduler({+ softLimit: 1,+ hardLimit: 1,+ freeMemoryBytes: () => 100 * 1024 ** 3,+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ resourceScheduler,+ runtime: {+ inspect: vi.fn(async () => ({+ ...READY_REPORT,+ devices: [{ ...READY_REPORT.devices[0]!, state: deviceState }],+ })),+ },+ getSession: vi.fn(async () => localSession('persisted-capacity-session')),+ });++ await host.reconcileOwnership();++ expect(resourceScheduler.runningCount()).toBe(1);+ await expect(+ resourceScheduler.runStart('new-instance', async () => undefined),+ ).rejects.toMatchObject({ code: 'RESOURCE_LIMIT_REACHED' });+ expect(actor.getOwned('persisted-capacity-session', instance.instanceId)).toMatchObject({+ lifecycleState: deviceState === 'Booted' ? 'ready' : 'booting',+ });+ },+ );++ it('keeps restored capacity reserved when persisted task lookup fails', 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,+ });+ actor.attach({+ sessionId: 'unreadable-persisted-session',+ worktreeRoot: '/tmp/unreadable-persisted-session',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const resourceScheduler = new IOSSimulatorResourceScheduler({+ softLimit: 1,+ hardLimit: 1,+ freeMemoryBytes: () => 100 * 1024 ** 3,+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ resourceScheduler,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => {+ throw new Error('database unavailable');+ }),+ });++ await host.reconcileOwnership();++ expect(resourceScheduler.runningCount()).toBe(1);+ await expect(+ resourceScheduler.runStart('new-instance', async () => undefined),+ ).rejects.toMatchObject({ code: 'RESOURCE_LIMIT_REACHED' });+ });+it('cleans up missing-session ownership using the injected lifecycle only', async () => {const lifecycle: IOSSimulatorSimctlLifecycle = {findExact: vi.fn(),@@ -863,7 +982,6 @@ describe('iOS Simulator host', () => {device: { ...READY_REPORT.devices[0]!, state: deviceState },});const resourceScheduler = testResourceScheduler();- await resourceScheduler.runStart(instance.instanceId, async () => undefined);const host = createIOSSimulatorHost({actor,lifecycle,@@ -1499,10 +1617,19 @@ describe('iOS Simulator host', () => {},),);- const abortRecording = vi.fn();+ const abortRecording = vi.fn(() => {+ throw new Error('recording already exited');+ });+ const abortDriver = vi.fn();const host = createIOSSimulatorHost({actor,lifecycle,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(),+ stop: vi.fn(async () => undefined),+ abortOperationsForExit: abortDriver,+ },projectBuilder: { build },mediaCapture: {abortOperationsForExit: abortRecording,@@ -1524,10 +1651,11 @@ describe('iOS Simulator host', () => {);await vi.waitFor(() => expect(build).toHaveBeenCalledOnce());- host.abortOperationsForExit();+ expect(() => host.abortOperationsForExit()).not.toThrow();expect(buildSignal?.aborted).toBe(true);expect(abortRecording).toHaveBeenCalledOnce();+ expect(abortDriver).toHaveBeenCalledOnce();await expect(callPromise).resolves.toMatchObject({ok: false,errorCode: 'MUTATION_CANCELLED',diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator-exit.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator-exit.tsindex c1c4f6ffac..2d873b7197 100644--- a/apps/desktop/src/main/mcp-integrations/ios-simulator-exit.ts+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator-exit.ts@@ -13,5 +13,9 @@ export function registerIOSSimulatorExitAbortHandler(/** Lightweight updater seam: never imports the simulator or media runtime. */export function abortIOSSimulatorOperationsForExit(): void {- exitAbortHandler?.();+ try {+ exitAbortHandler?.();+ } catch {+ // A forced updater exit must not be blocked by best-effort child cleanup.+ }}diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.tsindex 98245688a1..88a39f04a4 100644--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts@@ -131,6 +131,8 @@ interface IOSSimulatorDriverManager {capabilityReport?: IOSSimulatorDriverCapabilityReport | null;nativeSidecar?: IOSSimulatorNativeSidecarDiagnostics | null;};+ /** Synchronous child teardown used immediately before updater force-quit. */+ abortOperationsForExit?(): void;}export type IOSSimulatorAppLifecycleAdapter = Pick<@@ -278,9 +280,6 @@ function sessionError(return { ok: false, sessionId, errorCode, message };}-let defaultRegistryFlush: (() => Promise<void>) | null = null;-let defaultRegistryRelease: (() => void) | null = null;-export function createRegistryBackedIOSSimulatorActor(lifecycle: IOSSimulatorSimctlLifecycle,registry: IOSSimulatorOwnershipRegistryFile,@@ -348,14 +347,15 @@ export function createRegistryBackedIOSSimulatorActor(}}-function createDefaultActor(lifecycle: IOSSimulatorSimctlLifecycle): IOSSimulatorInstanceActor {+function createDefaultActor(lifecycle: IOSSimulatorSimctlLifecycle): {+ actor: IOSSimulatorInstanceActor;+ flush: () => Promise<void>;+ release: () => void;+} {const registry = new IOSSimulatorOwnershipRegistryFile(path.join(app.getPath('userData'), 'ios-simulator', 'ownership-registry.json'),);- const persisted = createRegistryBackedIOSSimulatorActor(lifecycle, registry);- defaultRegistryFlush = persisted.flush;- defaultRegistryRelease = persisted.release;- return persisted.actor;+ return createRegistryBackedIOSSimulatorActor(lifecycle, registry);}function createInMemoryActor(lifecycle: IOSSimulatorSimctlLifecycle): IOSSimulatorInstanceActor {@@ -692,13 +692,15 @@ function safeHostError(error instanceof IOSSimulatorInstanceError? error.code: error instanceof WdaError- ? error.code === 'BUILD_FAILED'- ? 'XCODE_BUILD_FAILED'- : error.code === 'UNREACHABLE'- ? 'DRIVER_DISCONNECTED'- : error.code === 'ORIENTATION_UNSUPPORTED'- ? 'ORIENTATION_UNSUPPORTED'- : 'WDA_UNAVAILABLE'+ ? error.code === 'START_CANCELLED'+ ? 'MUTATION_CANCELLED'+ : error.code === 'BUILD_FAILED'+ ? 'XCODE_BUILD_FAILED'+ : error.code === 'UNREACHABLE'+ ? 'DRIVER_DISCONNECTED'+ : error.code === 'ORIENTATION_UNSUPPORTED'+ ? 'ORIENTATION_UNSUPPORTED'+ : 'WDA_UNAVAILABLE': 'IOS_SIMULATOR_HOST_ERROR';logger.warn('iOS Simulator host call failed', {sessionId,@@ -710,13 +712,15 @@ function safeHostError(error instanceof IOSSimulatorHostDisposedError? error.message: error instanceof WdaError- ? error.code === 'BUILD_FAILED'- ? 'WebDriverAgent could not be built for this simulator.'- : error.code === 'UNREACHABLE'- ? 'The simulator automation driver is disconnected.'- : error.code === 'ORIENTATION_UNSUPPORTED'- ? 'The foreground app does not support the requested orientation.'- : 'The simulator automation driver is unavailable.'+ ? error.code === 'START_CANCELLED'+ ? 'The simulator automation driver startup was cancelled.'+ : error.code === 'BUILD_FAILED'+ ? 'WebDriverAgent could not be built for this simulator.'+ : error.code === 'UNREACHABLE'+ ? 'The simulator automation driver is disconnected.'+ : error.code === 'ORIENTATION_UNSUPPORTED'+ ? 'The foreground app does not support the requested orientation.'+ : 'The simulator automation driver is unavailable.': error instanceof IOSSimulatorInstanceError? error.message: 'The iOS Simulator operation failed.';@@ -2098,6 +2102,14 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I);let complete = true;for (const instance of actor.listAll()) {+ const device = devices.get(instance.simulatorUdid.toUpperCase());+ const deviceState = device?.state.trim().toLowerCase() ?? null;+ if (device && deviceState !== 'shutdown') {+ // This scheduler is process-local while ownership is persisted.+ // Restore observed CoreSimulator occupancy before any fallible task+ // lookup/cleanup so failed recovery remains capacity-safe.+ resourceScheduler.restoreRunning(instance.instanceId);+ }let session: IOSSimulatorSessionSnapshot | null = null;try {session = await getSession(instance.sessionId);@@ -2109,7 +2121,6 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I});continue;}- const device = devices.get(instance.simulatorUdid.toUpperCase());if (!session) {if (!(await releaseStaleBinding(instance, device))) complete = false;continue;@@ -2131,19 +2142,19 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Iactor.reconcile(instance.instanceId,instance.sessionId,- device ? (device.state.toLowerCase() === 'booted' ? 'ready' : 'stopped') : 'error',+ device ? (deviceState === 'booted' ? 'ready' : 'stopped') : 'error','degraded',session.remoteHostId ? 'UNSUPPORTED_SESSION_KIND' : 'ORPHANED_DEVICE',);continue;}- const deviceState = device.state.trim().toLowerCase();- if (deviceState === 'shutdown') {+ const reconciledDeviceState = deviceState ?? 'unknown';+ if (reconciledDeviceState === 'shutdown') {const runtimeReleased = await releaseInstanceRuntime(instance);if (runtimeReleased) {resourceScheduler.markStopped(instance.instanceId);} else complete = false;- } else if (deviceState !== 'booted') {+ } else if (reconciledDeviceState !== 'booted') {// Booting / Shutting Down / unknown concrete states may still own a// CoreSimulator process. Tear down Cindy media but keep scheduler// occupancy until a later probe proves the device is Shutdown.@@ -2152,16 +2163,18 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Iactor.reconcile(instance.instanceId,instance.sessionId,- deviceState === 'booted'+ reconciledDeviceState === 'booted'? 'ready'- : deviceState === 'shutdown'+ : reconciledDeviceState === 'shutdown'? 'stopped'- : deviceState.includes('boot')+ : reconciledDeviceState.includes('boot')? 'booting'- : deviceState.includes('shutting')+ : reconciledDeviceState.includes('shutting')? 'stopping': 'error',- deviceState === 'booted' || deviceState === 'shutdown' ? 'healthy' : 'recovering',+ reconciledDeviceState === 'booted' || reconciledDeviceState === 'shutdown'+ ? 'healthy'+ : 'recovering',null,);}@@ -5407,8 +5420,29 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Ireturn cleanupRemovedSessionRuntime(sessionId);},abortOperationsForExit() {- for (const build of activeBuilds.values()) build.controller.abort();- mediaCapture.abortOperationsForExit?.();+ for (const build of activeBuilds.values()) {+ try {+ build.controller.abort();+ } catch (error) {+ logger.warn('iOS Simulator exit cleanup could not abort an app build', {+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }+ try {+ mediaCapture.abortOperationsForExit?.();+ } catch (error) {+ logger.warn('iOS Simulator exit cleanup could not abort media capture', {+ error: error instanceof Error ? error.message : String(error),+ });+ }+ try {+ driverManager?.abortOperationsForExit?.();+ } catch (error) {+ logger.warn('iOS Simulator exit cleanup could not abort driver processes', {+ error: error instanceof Error ? error.message : String(error),+ });+ }},dispose() {if (disposePromise) return disposePromise;@@ -5475,30 +5509,74 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I};}-const defaultIOSSimulatorLifecycle = createIOSSimulatorSimctlLifecycle();-const defaultIOSSimulatorHost = createIOSSimulatorHost({- lifecycle: defaultIOSSimulatorLifecycle,- actor: createDefaultActor(defaultIOSSimulatorLifecycle),-});-configureIOSSimulatorRendererAccessRevocationObserver((grants) => {- for (const grant of grants) {- defaultIOSSimulatorHost.revokeRendererViewer(grant.sessionId, grant.target.id);+interface DefaultIOSSimulatorRuntime {+ host: IOSSimulatorHost;+ flushRegistry(): Promise<void>;+ releaseRegistry(): void;+ releaseExitAbortHandler(): void;+}++let defaultIOSSimulatorRuntime: DefaultIOSSimulatorRuntime | null = null;+let defaultIOSSimulatorRuntimeClosing = false;+let defaultIOSSimulatorRuntimeDisposePromise: Promise<void> | null = null;++/**+ * The ownership registry holds a process-wide writer lease, so the default+ * Simulator Host must stay lazy. Passive/dev Desktop instances that never use+ * Simulator must not prevent the instance that actually needs it from taking+ * ownership.+ */+export function initializeIOSSimulatorHost(): IOSSimulatorHost {+ if (defaultIOSSimulatorRuntime) return defaultIOSSimulatorRuntime.host;+ if (defaultIOSSimulatorRuntimeClosing) {+ throw new Error('The iOS Simulator host is shutting down.');}-});-const releaseIOSSimulatorExitAbortHandler = registerIOSSimulatorExitAbortHandler(() => {- defaultIOSSimulatorHost.abortOperationsForExit();-});++ const lifecycle = createIOSSimulatorSimctlLifecycle();+ const persistedActor = createDefaultActor(lifecycle);+ let releaseExitAbortHandler: (() => void) | null = null;+ try {+ const host = createIOSSimulatorHost({+ lifecycle,+ actor: persistedActor.actor,+ });+ configureIOSSimulatorRendererAccessRevocationObserver((grants) => {+ for (const grant of grants) {+ host.revokeRendererViewer(grant.sessionId, grant.target.id);+ }+ });+ releaseExitAbortHandler = registerIOSSimulatorExitAbortHandler(() => {+ host.abortOperationsForExit();+ });+ defaultIOSSimulatorRuntime = {+ host,+ flushRegistry: persistedActor.flush,+ releaseRegistry: persistedActor.release,+ releaseExitAbortHandler,+ };+ return host;+ } catch (error) {+ configureIOSSimulatorRendererAccessRevocationObserver(null);+ releaseExitAbortHandler?.();+ persistedActor.release();+ throw error;+ }+}++function currentIOSSimulatorHost(): IOSSimulatorHost | null {+ return defaultIOSSimulatorRuntime?.host ?? null;+}export function getIOSSimulatorSessionStatus(sessionId: string,): Promise<IOSSimulatorSessionStatus> {- return defaultIOSSimulatorHost.getStatus(sessionId);+ return initializeIOSSimulatorHost().getStatus(sessionId);}export function getIOSSimulatorPluginStatus(sessionId: string,): Promise<GhostIOSSimulatorStatusProbeResult> {- return defaultIOSSimulatorHost.getPluginStatus(sessionId);+ return initializeIOSSimulatorHost().getPluginStatus(sessionId);}export function callIOSSimulatorHostTool(@@ -5506,7 +5584,7 @@ export function callIOSSimulatorHostTool(args: Record<string, unknown>,sessionId: string,): Promise<IOSSimulatorHostResult> {- return defaultIOSSimulatorHost.callTool(name, args, { sessionId, origin: 'user' });+ return initializeIOSSimulatorHost().callTool(name, args, { sessionId, origin: 'user' });}export function setIOSSimulatorAgentControlGrant(@@ -5514,7 +5592,7 @@ export function setIOSSimulatorAgentControlGrant(instanceId: string,decision: 'allowed' | 'denied',): Promise<IOSSimulatorHostResult> {- return defaultIOSSimulatorHost.setAgentControlGrant(sessionId, instanceId, decision);+ return initializeIOSSimulatorHost().setAgentControlGrant(sessionId, instanceId, decision);}export function setIOSSimulatorViewerVisibility(@@ -5526,7 +5604,7 @@ export function setIOSSimulatorViewerVisibility(viewerWebContentsId?: number,viewerToken?: string,): Promise<IOSSimulatorHostResult> {- return defaultIOSSimulatorHost.setViewerVisibility(+ return initializeIOSSimulatorHost().setViewerVisibility(sessionId,route,visible,@@ -5542,7 +5620,7 @@ export function setIOSSimulatorAgentMutationPaused(route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,paused: boolean,): Promise<IOSSimulatorHostResult> {- return defaultIOSSimulatorHost.setAgentMutationPaused(sessionId, route, paused);+ return initializeIOSSimulatorHost().setAgentMutationPaused(sessionId, route, paused);}export function getIOSSimulatorLatestFrame(@@ -5550,37 +5628,44 @@ export function getIOSSimulatorLatestFrame(route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,viewerWebContentsId: number,): Promise<IOSSimulatorHostResult> {- return defaultIOSSimulatorHost.getLatestFrame(sessionId, route, viewerWebContentsId);+ return initializeIOSSimulatorHost().getLatestFrame(sessionId, route, viewerWebContentsId);}export async function flushIOSSimulatorOwnershipRegistry(): Promise<void> {- await defaultRegistryFlush?.();+ await defaultIOSSimulatorRuntime?.flushRegistry();}export function reconcileIOSSimulatorOwnership(): Promise<void> {- return defaultIOSSimulatorHost.reconcileOwnership();+ return initializeIOSSimulatorHost().reconcileOwnership();}export async function disposeIOSSimulatorHost(): Promise<void> {- try {- clearIOSSimulatorRendererAccess();- await defaultIOSSimulatorHost.dispose();- await defaultRegistryFlush?.();- } finally {- configureIOSSimulatorRendererAccessRevocationObserver(null);- releaseIOSSimulatorExitAbortHandler();- defaultRegistryRelease?.();- }+ if (defaultIOSSimulatorRuntimeDisposePromise) return defaultIOSSimulatorRuntimeDisposePromise;+ defaultIOSSimulatorRuntimeClosing = true;+ const runtime = defaultIOSSimulatorRuntime;+ defaultIOSSimulatorRuntimeDisposePromise = (async () => {+ try {+ clearIOSSimulatorRendererAccess();+ if (!runtime) return;+ await runtime.host.dispose();+ await runtime.flushRegistry();+ } finally {+ configureIOSSimulatorRendererAccessRevocationObserver(null);+ runtime?.releaseExitAbortHandler();+ runtime?.releaseRegistry();+ }+ })();+ return defaultIOSSimulatorRuntimeDisposePromise;}export function cancelIOSSimulatorSessionOperations(sessionId: string): Promise<void> {revokeIOSSimulatorRendererSession(sessionId);- return defaultIOSSimulatorHost.cancelSessionOperations(sessionId);+ return currentIOSSimulatorHost()?.cancelSessionOperations(sessionId) ?? Promise.resolve();}export function cleanupIOSSimulatorRemovedSession(sessionId: string): Promise<void> {revokeIOSSimulatorRendererSession(sessionId);- return defaultIOSSimulatorHost.cleanupRemovedSession(sessionId);+ return currentIOSSimulatorHost()?.cleanupRemovedSession(sessionId) ?? Promise.resolve();}export function setIOSSimulatorViewerStreamProfile(@@ -5589,7 +5674,12 @@ export function setIOSSimulatorViewerStreamProfile(profile: IOSSimulatorStreamProfile,nativeProfile?: IOSSimulatorNativeH264StreamProfileRequest,): Promise<IOSSimulatorHostResult> {- return defaultIOSSimulatorHost.setViewerStreamProfile(sessionId, route, profile, nativeProfile);+ return initializeIOSSimulatorHost().setViewerStreamProfile(+ sessionId,+ route,+ profile,+ nativeProfile,+ );}export function updateIOSSimulatorViewerTouch(@@ -5603,7 +5693,12 @@ export function updateIOSSimulatorViewerTouch(yRatio: number;},): Promise<IOSSimulatorHostResult> {- return defaultIOSSimulatorHost.updateViewerTouch(sessionId, route, viewerWebContentsId, touch);+ return initializeIOSSimulatorHost().updateViewerTouch(+ sessionId,+ route,+ viewerWebContentsId,+ touch,+ );}export interface IOSSimulatorMcpDepsOptions {@@ -5614,7 +5709,7 @@ export interface IOSSimulatorMcpDepsOptions {export function getIOSSimulatorMcpDeps(options: IOSSimulatorMcpDepsOptions = {},): IOSSimulatorMcpDeps {- const host = options.host ?? defaultIOSSimulatorHost;+ const getHost = (): IOSSimulatorHost => options.host ?? initializeIOSSimulatorHost();return {describeTools: async (context) => {const sessionId = context?.sessionId?.trim();@@ -5640,7 +5735,7 @@ export function getIOSSimulatorMcpDeps(},};}- return host.describeTools(sessionId);+ return getHost().describeTools(sessionId);},callTool: async (name, args, context) => {if (options.isIOSSimulatorEnabled && !options.isIOSSimulatorEnabled(context)) {@@ -5650,7 +5745,7 @@ export function getIOSSimulatorMcpDeps(message: 'iOS Simulator tools are disabled for this project.',};}- return host.callTool(name, args, context);+ return getHost().callTool(name, args, context);},logger,};diff --git a/packages/ios-simulator-runtime/src/command-runner.ts b/packages/ios-simulator-runtime/src/command-runner.tsindex be80df0e47..0b0618bd22 100644--- a/packages/ios-simulator-runtime/src/command-runner.ts+++ b/packages/ios-simulator-runtime/src/command-runner.ts@@ -72,8 +72,19 @@ export function createNodeIOSSimulatorCommandRunner(): IOSSimulatorCommandRunnerconst onAbort = () => {if (settled || aborted) return;aborted = true;+ if (timer) {+ clearTimeout(timer);+ timer = null;+ }+ if (forceKillTimer) clearTimeout(forceKillTimer);killProcessTree(child, "SIGKILL");- finish(null);+ forceKillTimer = setTimeout(() => {+ if (settled) return;+ killProcessTree(child, "SIGKILL");+ // The updater may force-quit after this bounded grace period. Do+ // not wait forever for hostile inherited stdio handles to close.+ finish(null);+ }, TERMINATION_GRACE_MS);};timer = setTimeout(() => {if (settled) return;@@ -126,7 +137,7 @@ export function createNodeIOSSimulatorCommandRunner(): IOSSimulatorCommandRunnerchild.once("close", (code) => {// The leader may exit on SIGTERM while a same-group descendant stays// alive. Keep the escalation watchdog in that case.- if (timedOut && isProcessGroupAlive(child)) return;+ if ((timedOut || aborted) && isProcessGroupAlive(child)) return;finish(timedOut || aborted ? null : code);});});diff --git a/packages/ios-simulator-runtime/src/native-sidecar/channel.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/channel.test.tsindex bf6448e32f..40bbae2924 100644--- a/packages/ios-simulator-runtime/src/native-sidecar/channel.test.ts+++ b/packages/ios-simulator-runtime/src/native-sidecar/channel.test.ts@@ -216,6 +216,31 @@ describe("IOSSimulatorNativeSidecarChannel", () => {}});+ it("synchronously kills both active and already-stopping processes for Host exit", async () => {+ const activeHarness = harness();+ await activeHarness.channel.start();+ activeHarness.channel.abortOperationsForExit();+ expect(activeHarness.processes[0]!.killSignals).toEqual(["SIGKILL"]);+ expect(activeHarness.channel.state).toBe("stopped");++ vi.useFakeTimers();+ try {+ const stoppingHarness = harness({ stopTimeoutMs: 5 });+ await stoppingHarness.channel.start();+ const process = stoppingHarness.processes[0]!;+ process.emitExitOnKill = false;+ const stop = stoppingHarness.channel.stop();+ expect(process.killSignals).toEqual(["SIGTERM"]);++ stoppingHarness.channel.abortOperationsForExit();+ expect(process.killSignals).toEqual(["SIGTERM", "SIGKILL"]);+ process.exit(null, "SIGKILL");+ await stop;+ } finally {+ vi.useRealTimers();+ }+ });+it("terminates the process after consecutive request timeouts", async () => {const { channel } = harness({requestTimeoutMs: 5,diff --git a/packages/ios-simulator-runtime/src/native-sidecar/channel.ts b/packages/ios-simulator-runtime/src/native-sidecar/channel.tsindex 91fc045746..4cd2ee56fe 100644--- a/packages/ios-simulator-runtime/src/native-sidecar/channel.ts+++ b/packages/ios-simulator-runtime/src/native-sidecar/channel.ts@@ -520,6 +520,30 @@ export class IOSSimulatorNativeSidecarChannel implements IOSSimulatorNativeSidecif (this.#stopPromise) return this.#stopPromise;}+ /** Synchronously kill both active and already-stopping process groups. */+ abortOperationsForExit(): void {+ this.#stopRequested = true;+ this.#state = "stopped";+ this.#rejectAll(+ new IOSSimulatorNativeSidecarChannelError(+ "ABORTED",+ "Native sidecar channel aborted for Host exit.",+ ),+ );+ const processes = new Set([+ ...(this.#process ? [this.#process] : []),+ ...(this.#stoppingProcess ? [this.#stoppingProcess] : []),+ ]);+ this.#process = null;+ for (const process of processes) {+ try {+ process.kill("SIGKILL");+ } catch {+ // The process may have exited between collection and termination.+ }+ }+ }+#ensureProcessClosed(process: IOSSimulatorNativeSidecarManagedProcess,terminate: boolean,diff --git a/packages/ios-simulator-runtime/src/native-sidecar/process-manager.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/process-manager.test.tsindex ba92073159..d3dd476030 100644--- a/packages/ios-simulator-runtime/src/native-sidecar/process-manager.test.ts+++ b/packages/ios-simulator-runtime/src/native-sidecar/process-manager.test.ts@@ -53,6 +53,9 @@ class FakeChannel implements IOSSimulatorNativeSidecarManagedChannel {this.crashCount = 0;this.state = "idle";});+ readonly abortOperationsForExit = vi.fn(() => {+ this.state = "stopped";+ });constructor(readonly handshake: Record<string, unknown> = {@@ -131,6 +134,19 @@ function input() {}describe("IOSSimulatorNativeSidecarProcessManager", () => {+ it("forwards updater force-exit aborts to every live channel", async () => {+ const channel = new FakeChannel();+ const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath: "/private/fake/ios-simulator-sidecar",+ createChannel: () => channel,+ });+ await manager.start(input());++ manager.abortOperationsForExit();++ expect(channel.abortOperationsForExit).toHaveBeenCalledOnce();+ });+it("adds native product flags only for explicitly enabled host capabilities", () => {const start = input();expect(createIOSSimulatorNativeSidecarArguments(start)).toEqual([@@ -508,6 +524,24 @@ describe("IOSSimulatorNativeSidecarProcessManager", () => {});});+ it("removes a failed recovery channel from force-exit tracking", async () => {+ const channel = new FakeChannel();+ const manager = new IOSSimulatorNativeSidecarProcessManager({+ binaryPath: "/private/fake/ios-simulator-sidecar",+ createChannel: () => channel,+ });+ await manager.start(input());+ channel.state = "failed";+ channel.restart.mockRejectedValueOnce(new Error("restart failed"));++ await expect(manager.recover(input())).rejects.toMatchObject({+ code: "UNAVAILABLE",+ });+ manager.abortOperationsForExit();++ expect(channel.abortOperationsForExit).not.toHaveBeenCalled();+ });+it("only re-arms a parked binding for explicit recovery", async () => {const channel = new FakeChannel();const manager = new IOSSimulatorNativeSidecarProcessManager({diff --git a/packages/ios-simulator-runtime/src/native-sidecar/process-manager.ts b/packages/ios-simulator-runtime/src/native-sidecar/process-manager.tsindex 6c8650bde3..c37abf2c52 100644--- a/packages/ios-simulator-runtime/src/native-sidecar/process-manager.ts+++ b/packages/ios-simulator-runtime/src/native-sidecar/process-manager.ts@@ -49,6 +49,7 @@ export interface IOSSimulatorNativeSidecarManagedChannel extends IOSSimulatorNatrestart(): Promise<void>;rearm(): void;stop(): Promise<void>;+ abortOperationsForExit?(): void;}export interface IOSSimulatorNativeSidecarStartOptions {@@ -560,6 +561,7 @@ export class IOSSimulatorNativeSidecarProcessManager {readonly #running = new Map<string, InternalRunningInstance>();readonly #starting = new Map<string, PendingSidecarOperation>();readonly #stopping = new Map<string, Promise<void>>();+ readonly #liveChannels = new Set<IOSSimulatorNativeSidecarManagedChannel>();readonly #lastProbe = new Map<string,IOSSimulatorNativeSidecarProbe | null@@ -650,6 +652,20 @@ export class IOSSimulatorNativeSidecarProcessManager {};}+ /** Best-effort synchronous child teardown for updater force-quit. */+ abortOperationsForExit(): void {+ for (const pending of this.#starting.values()) {+ pending.stopRequested = true;+ }+ for (const channel of this.#liveChannels) {+ try {+ channel.abortOperationsForExit?.();+ } catch {+ // Continue terminating the remaining exact channels.+ }+ }+ }+start(input: IOSSimulatorNativeSidecarStartOptions,): Promise<IOSSimulatorNativeSidecarRunningInstance> {@@ -735,6 +751,7 @@ export class IOSSimulatorNativeSidecarProcessManager {this.#createChannelOptions(input, preflight, sandbox),);operation.channel = channel;+ this.#liveChannels.add(channel);try {await channel.start();if (operation.stopRequested) {@@ -819,7 +836,11 @@ export class IOSSimulatorNativeSidecarProcessManager {}}await channel.stop().catch(() => undefined);- await this.#disposeSandbox(sandbox);+ try {+ await this.#disposeSandbox(sandbox);+ } finally {+ this.#liveChannels.delete(channel);+ }throw failure;}}@@ -976,7 +997,11 @@ export class IOSSimulatorNativeSidecarProcessManager {if (operation.stopRequested || running.channel.state !== "parked") {this.#running.delete(input.instanceId);await running.channel.stop().catch(() => undefined);- await this.#disposeSandbox(running.sandbox);+ try {+ await this.#disposeSandbox(running.sandbox);+ } finally {+ this.#liveChannels.delete(running.channel);+ }}throw failure;}@@ -1104,6 +1129,7 @@ export class IOSSimulatorNativeSidecarProcessManager {this.#running.delete(instanceId);await running.adapter.detach().catch(() => undefined);await running.channel.stop().catch(() => undefined);+ this.#liveChannels.delete(running.channel);}await pending?.promise?.catch(() => undefined);running = this.#running.get(instanceId);@@ -1111,7 +1137,9 @@ export class IOSSimulatorNativeSidecarProcessManager {this.#running.delete(instanceId);await running.adapter.detach().catch(() => undefined);await running.channel.stop().catch(() => undefined);+ this.#liveChannels.delete(running.channel);}+ if (pending?.channel) this.#liveChannels.delete(pending.channel);const policy = running?.policy ?? stoppedRunning?.policy ?? pending?.policy;const sandbox =running?.sandbox ?? stoppedRunning?.sandbox ?? pending?.sandbox;diff --git a/packages/ios-simulator-runtime/src/native-sidecar/provider.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/provider.test.tsindex 2ddeede2a2..43379ef0ea 100644--- a/packages/ios-simulator-runtime/src/native-sidecar/provider.test.ts+++ b/packages/ios-simulator-runtime/src/native-sidecar/provider.test.ts@@ -131,6 +131,7 @@ class FakeRuntime implements IOSSimulatorSidecarRuntime {readonly stop = vi.fn(async (instanceId: string) => {this.running.delete(instanceId);});+ readonly abortOperationsForExit = vi.fn();constructor(readonly artifact: Readonly<IOSSimulatorSidecarArtifactDescriptor>,@@ -198,6 +199,17 @@ function createSupervisor(input: {}describe("HostIOSSimulatorSidecarSupervisor", () => {+ it("forwards updater force-exit aborts to the bound Host runtime", async () => {+ const { supervisor, runtimes } = createSupervisor({+ resolve: () => bundledArtifact(),+ });+ await supervisor.start(START);++ supervisor.abortOperationsForExit();++ expect(runtimes[0]!.abortOperationsForExit).toHaveBeenCalledOnce();+ });+it("keeps artifact resolution and process creation behind the Host provider", async () => {const artifact = bundledArtifact();const { supervisor, createRuntime, runtimes } = createSupervisor({diff --git a/packages/ios-simulator-runtime/src/native-sidecar/provider.ts b/packages/ios-simulator-runtime/src/native-sidecar/provider.tsindex 4c96236093..3f520fa534 100644--- a/packages/ios-simulator-runtime/src/native-sidecar/provider.ts+++ b/packages/ios-simulator-runtime/src/native-sidecar/provider.ts@@ -65,6 +65,8 @@ export interface IOSSimulatorCapabilityProvider {options?: IOSSimulatorNativeSidecarRecoverOptions,): Promise<IOSSimulatorNativeSidecarRunningInstance>;stop(instanceId: string): Promise<void>;+ /** Best-effort synchronous child teardown before a forced Host exit. */+ abortOperationsForExit?(): void;}/** Lifecycle owner used for provider disable, upgrade, uninstall, and Host quit. */@@ -261,6 +263,22 @@ export class HostIOSSimulatorSidecarSupervisor implements IOSSimulatorSidecarSupthis.#runtimeArtifacts.clear();}+ abortOperationsForExit(): void {+ for (const pending of this.#starting.values()) {+ pending.stopRequested = true;+ }+ for (const runtime of new Set([+ ...this.#runtimes.values(),+ ...[...this.#bindings.values()].map((binding) => binding.runtime),+ ])) {+ try {+ runtime.abortOperationsForExit?.();+ } catch {+ // The updater must still be able to exit if one runtime is already gone.+ }+ }+ }+async invalidateArtifact(artifactId: string): Promise<void> {if (!SAFE_ARTIFACT_ID.test(artifactId)) {throw new IOSSimulatorCapabilityProviderError(diff --git a/packages/ios-simulator-runtime/src/resource-scheduler.test.ts b/packages/ios-simulator-runtime/src/resource-scheduler.test.tsindex ff917a577c..4a1bd50d17 100644--- a/packages/ios-simulator-runtime/src/resource-scheduler.test.ts+++ b/packages/ios-simulator-runtime/src/resource-scheduler.test.ts@@ -138,6 +138,25 @@ describe("IOSSimulatorResourceScheduler", () => {expect(scheduler.runningCount()).toBe(1);});+ it("restores persisted occupancy without bypassing limits for another instance", async () => {+ const scheduler = new IOSSimulatorResourceScheduler({+ softLimit: 1,+ hardLimit: 1,+ freeMemoryBytes: () => 100 * 1024 ** 3,+ });++ scheduler.restoreRunning("persisted");+ scheduler.restoreRunning("persisted");++ expect(scheduler.runningCount()).toBe(1);+ await expect(+ scheduler.runStart("new", async () => undefined),+ ).rejects.toMatchObject({ code: "RESOURCE_LIMIT_REACHED" });+ await expect(+ scheduler.runStart("persisted", async () => "recovered"),+ ).resolves.toBe("recovered");+ });+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 6a9fe92305..1a18435b0c 100644--- a/packages/ios-simulator-runtime/src/resource-scheduler.ts+++ b/packages/ios-simulator-runtime/src/resource-scheduler.ts@@ -142,6 +142,11 @@ export class IOSSimulatorResourceScheduler {this.#running.delete(instanceId);}+ /** Restore observed CoreSimulator occupancy without re-running start admission. */+ restoreRunning(instanceId: string): void {+ this.#running.add(instanceId);+ }+runStart<T>(instanceId: string,task: (commitRunning: () => void) => Promise<T>,diff --git a/packages/ios-simulator-runtime/src/wda/errors.ts b/packages/ios-simulator-runtime/src/wda/errors.tsindex 73528d4085..0225901a44 100644--- a/packages/ios-simulator-runtime/src/wda/errors.ts+++ b/packages/ios-simulator-runtime/src/wda/errors.ts@@ -12,6 +12,7 @@ export const WDA_ERROR_CODES = ["BUILD_FAILED","LAUNCH_FAILED","START_TIMEOUT",+ "START_CANCELLED","TERMINATION_FAILED",] as const;diff --git a/packages/ios-simulator-runtime/src/wda/process-manager.test.ts b/packages/ios-simulator-runtime/src/wda/process-manager.test.tsindex cef2aa264b..6210457276 100644--- a/packages/ios-simulator-runtime/src/wda/process-manager.test.ts+++ b/packages/ios-simulator-runtime/src/wda/process-manager.test.ts@@ -1,5 +1,5 @@import { createHash } from "node:crypto";-import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";import os from "node:os";import path from "node:path";@@ -146,6 +146,7 @@ async function createHarness(startTimeoutMs: harnessOptions.startTimeoutMs,});return {+ root,manager,run,driver,@@ -237,15 +238,19 @@ describe("WdaProcessManager", () => {expect(harness.killed).toEqual(["SIGINT"]);});- it("waits for an in-flight start and deterministically stops the late process", async () => {+ it("cancels an in-flight WDA build without launching a late process", async () => {const harness = await createHarness();const runBuild = harness.run.getMockImplementation()!;- let releaseBuild!: () => void;- const buildGate = new Promise<void>((resolve) => {- releaseBuild = resolve;- });harness.run.mockImplementation(async (...args) => {- if (args[1].includes("build-for-testing")) await buildGate;+ if (args[1].includes("build-for-testing")) {+ return new Promise((resolve) => {+ const signal = args[2]?.signal;+ const finish = () =>+ resolve({ stdout: "", stderr: "", exitCode: null });+ signal?.addEventListener("abort", finish, { once: true });+ if (signal?.aborted) finish();+ });+ }return runBuild(...args);});@@ -263,20 +268,127 @@ describe("WdaProcessManager", () => {),).toBe(true),);- let stopSettled = false;- const stop = harness.manager.stop("instance-a").then(() => {- stopSettled = true;- });- await Promise.resolve();- expect(stopSettled).toBe(false);+ const stop = harness.manager.stop("instance-a");- releaseBuild();- await start;- await stop;+ await expect(start).rejects.toMatchObject({ code: "START_CANCELLED" });+ await expect(stop).resolves.toBeUndefined();expect(harness.manager.get("instance-a")).toBeNull();- expect(harness.driver.deleteSession).toHaveBeenCalledWith("wda-session");+ expect(harness.launch).not.toHaveBeenCalled();+ expect(harness.driver.createSession).not.toHaveBeenCalled();+ const buildCall = harness.run.mock.calls.find(([, args]) =>+ args.includes("build-for-testing"),+ );+ expect(buildCall?.[2]?.signal?.aborted).toBe(true);+ });++ it("stops promptly while shared WDA source extraction finishes independently", async () => {+ const harness = await createHarness();+ const runCommand = harness.run.getMockImplementation()!;+ let releaseExtraction!: () => void;+ const extractionGate = new Promise<void>((resolve) => {+ releaseExtraction = resolve;+ });+ harness.run.mockImplementation(async (...args) => {+ if (!args[1].includes("-xzf")) return runCommand(...args);+ await extractionGate;+ return runCommand(...args);+ });++ const start = harness.manager.start({+ instanceId: "instance-a",+ simulatorUdid: UDID,+ runtimeIdentifier: "runtime",+ xcodeBuild: "build",+ architecture: "arm64",+ });+ await vi.waitFor(() =>+ expect(+ harness.run.mock.calls.some(([, args]) => args.includes("-xzf")),+ ).toBe(true),+ );++ await expect(harness.manager.stop("instance-a")).resolves.toBeUndefined();+ await expect(start).rejects.toMatchObject({ code: "START_CANCELLED" });+ expect(harness.launch).not.toHaveBeenCalled();++ releaseExtraction();+ await vi.waitFor(async () => {+ const marker = await readFile(+ path.join(+ harness.root,+ "cache",+ "source",+ "a".repeat(40),+ ".cindy-wda-source.json",+ ),+ "utf8",+ );+ expect(marker).toContain('"revision"');+ });+ });++ it("cancels readiness probing and terminates the already-launched process", async () => {+ const harness = await createHarness();+ harness.driver.probe.mockImplementation(() => new Promise(() => undefined));+ const start = harness.manager.start({+ instanceId: "instance-a",+ simulatorUdid: UDID,+ runtimeIdentifier: "runtime",+ xcodeBuild: "build",+ architecture: "arm64",+ });+ await vi.waitFor(() => expect(harness.driver.probe).toHaveBeenCalled());++ const stop = harness.manager.stop("instance-a");++ await expect(start).rejects.toMatchObject({ code: "START_CANCELLED" });+ await expect(stop).resolves.toBeUndefined();expect(harness.killed).toEqual(["SIGINT"]);+ expect(harness.manager.get("instance-a")).toBeNull();+ });++ it("synchronously kills live WDA processes during updater force-exit", async () => {+ const harness = await createHarness();+ await harness.manager.start({+ instanceId: "instance-a",+ simulatorUdid: UDID,+ runtimeIdentifier: "runtime",+ xcodeBuild: "build",+ architecture: "arm64",+ });++ harness.manager.abortOperationsForExit();++ expect(harness.killed).toEqual(["SIGKILL"]);+ });++ it("keeps stop-gap WDA processes visible to force-exit cleanup", async () => {+ const harness = await createHarness();+ await harness.manager.start({+ instanceId: "instance-a",+ simulatorUdid: UDID,+ runtimeIdentifier: "runtime",+ xcodeBuild: "build",+ architecture: "arm64",+ });+ let releaseDelete!: () => void;+ harness.driver.deleteSession.mockImplementation(+ () =>+ new Promise<undefined>((resolve) => {+ releaseDelete = () => resolve(undefined);+ }),+ );+ const stop = harness.manager.stop("instance-a");+ await vi.waitFor(() =>+ expect(harness.driver.deleteSession).toHaveBeenCalledWith("wda-session"),+ );++ harness.manager.abortOperationsForExit();+ expect(harness.killed).toEqual(["SIGKILL"]);++ releaseDelete();+ await stop;});it("awaits full process-group termination before returning a readiness timeout", async () => {@@ -363,6 +475,31 @@ describe("WdaProcessManager", () => {expect(harness.process.isAlive()).toBe(false);});+ it("uses normal running teardown when process exit races the start commit", async () => {+ const harness = await createHarness(undefined, {+ groupExitsOn: [],+ });+ harness.driver.configureStream.mockImplementation(+ async (_sessionId, profile) => {+ harness.exitLeader("SIGTERM");+ return profile;+ },+ );++ await harness.manager.start({+ instanceId: "instance-a",+ simulatorUdid: UDID,+ runtimeIdentifier: "runtime",+ xcodeBuild: "build",+ architecture: "arm64",+ });++ await vi.waitFor(() =>+ expect(harness.killed).toEqual(["SIGINT", "SIGTERM", "SIGKILL"]),+ );+ expect(harness.manager.get("instance-a")).toBeNull();+ });+it("quarantines an unkillable process group and blocks replacement starts", async () => {const harness = await createHarness(undefined, {leaderExitsOn: ["SIGINT"],@@ -447,6 +584,9 @@ describe("WdaProcessManager", () => {expect(running.pid).toBe(43);expect(harness.launch).toHaveBeenCalledTimes(2);+ harness.manager.abortOperationsForExit();+ expect(harness.killed).toEqual(["SIGINT", "SIGTERM", "SIGKILL"]);+ expect(replacement.kill).toHaveBeenCalledWith("SIGKILL");});it("attaches the optional native adapter by exact generation and stops it with WDA", async () => {diff --git a/packages/ios-simulator-runtime/src/wda/process-manager.ts b/packages/ios-simulator-runtime/src/wda/process-manager.tsindex 4c9f840dfa..80991c57bb 100644--- a/packages/ios-simulator-runtime/src/wda/process-manager.ts+++ b/packages/ios-simulator-runtime/src/wda/process-manager.ts@@ -20,6 +20,7 @@ import { createWdaBuildPlan, type WdaCommandPlan } from "./build-plan.js";import { WdaClient } from "./client.js";import { WdaError } from "./errors.js";import {+ abortWdaSourcePreparationForExit,createWdaBuildCacheKey,prepareWdaSource,type WdaSourceManifest,@@ -106,6 +107,11 @@ interface InternalRunningInstance extends WdaRunningInstance {}interface PendingWdaOperation {+ controller: AbortController;+ simulatorUdid: string;+ committed: boolean;+ process?: WdaManagedProcess;+ termination?: Promise<void>;promise?: Promise<WdaRunningInstance>;}@@ -287,6 +293,7 @@ export class WdaProcessManager {readonly #starting = new Map<string, PendingWdaOperation>();readonly #stopping = new Map<string, Promise<void>>();readonly #retiring = new Map<string, RetiringWdaProcess>();+ readonly #liveProcesses = new Set<WdaManagedProcess>();constructor(options: WdaProcessManagerOptions) {this.#options = options;@@ -354,6 +361,22 @@ export class WdaProcessManager {};}+ /** Best-effort synchronous child teardown for updater force-quit. */+ abortOperationsForExit(): void {+ abortWdaSourcePreparationForExit();+ for (const pending of this.#starting.values()) {+ pending.controller.abort();+ }+ for (const process of this.#liveProcesses) {+ try {+ process.kill("SIGKILL");+ } catch {+ // The process group may already have exited.+ }+ }+ this.#options.nativeCapabilityProvider?.abortOperationsForExit?.();+ }+start(options: WdaStartOptions): Promise<WdaRunningInstance> {const stopping = this.#stopping.get(options.instanceId);if (stopping) return stopping.then(() => this.start(options));@@ -363,8 +386,12 @@ export class WdaProcessManager {if (running) return Promise.resolve(running);const pending = this.#starting.get(options.instanceId);if (pending) return pending.promise!;- const starting: PendingWdaOperation = {};- const operation = this.#start(options).finally(() => {+ const starting: PendingWdaOperation = {+ controller: new AbortController(),+ simulatorUdid: options.simulatorUdid,+ committed: false,+ };+ const operation = this.#start(options, starting).finally(() => {if (this.#starting.get(options.instanceId) === starting) {this.#starting.delete(options.instanceId);}@@ -422,13 +449,21 @@ export class WdaProcessManager {return this.get(instanceId);}- async #start(options: WdaStartOptions): Promise<WdaRunningInstance> {- const prepared = await prepareWdaSource({- archivePath: this.#options.archivePath,- cacheRoot: path.join(this.#options.cacheRoot, "source"),- manifest: this.#options.sourceManifest,- commandRunner: this.#runner,- });+ async #start(+ options: WdaStartOptions,+ operation: PendingWdaOperation,+ ): Promise<WdaRunningInstance> {+ const signal = operation.controller.signal;+ const prepared = await this.#awaitStartOperation(+ prepareWdaSource({+ archivePath: this.#options.archivePath,+ cacheRoot: path.join(this.#options.cacheRoot, "source"),+ manifest: this.#options.sourceManifest,+ commandRunner: this.#runner,+ }),+ signal,+ );+ this.#throwIfStartCancelled(signal);const buildCacheKey = createWdaBuildCacheKey({sourceRevision: prepared.revision,xcodeBuild: options.xcodeBuild,@@ -441,10 +476,16 @@ export class WdaProcessManager {buildCacheKey,);await mkdir(derivedDataPath, { recursive: true });+ this.#throwIfStartCancelled(signal);const allocate = this.#options.allocatePort ?? allocateLoopbackPort;const controlPort = await allocate();+ this.#throwIfStartCancelled(signal);let mjpegPort = await allocate();- while (mjpegPort === controlPort) mjpegPort = await allocate();+ this.#throwIfStartCancelled(signal);+ while (mjpegPort === controlPort) {+ mjpegPort = await allocate();+ this.#throwIfStartCancelled(signal);+ }const plan = createWdaBuildPlan({checkoutPath: prepared.checkoutPath,derivedDataPath,@@ -458,7 +499,9 @@ export class WdaProcessManager {env: plan.build.env,timeoutMs: 10 * 60_000,maxBufferBytes: MAX_LOG_BYTES,+ signal,});+ this.#throwIfStartCancelled(signal);if (build.exitCode !== 0) {throw new WdaError("BUILD_FAILED",@@ -466,7 +509,10 @@ export class WdaProcessManager {);}+ this.#throwIfStartCancelled(signal);const process = this.#launcher.launch(plan.launch);+ operation.process = process;+ this.#liveProcesses.add(process);const log = new BoundedLog();log.append(build.stdout);log.append(build.stderr);@@ -477,129 +523,146 @@ export class WdaProcessManager {controlUrl: `http://127.0.0.1:${controlPort}`,mjpegUrl: `http://127.0.0.1:${mjpegPort}`,});- const deadline =- this.#clock.now() + (this.#options.startTimeoutMs ?? 90_000);- let health: IOSSimulatorDriverHealth | null = null;- let processExited = false;- void process.exited.then(() => {- processExited = true;- });- while (this.#clock.now() < deadline) {- if (processExited) break;- try {- const probed = await driver.probe();- if (probed.ready) {- health = probed;- break;+ try {+ this.#throwIfStartCancelled(signal);+ const deadline =+ this.#clock.now() + (this.#options.startTimeoutMs ?? 90_000);+ let health: IOSSimulatorDriverHealth | null = null;+ let processExited = false;+ void process.exited.then(() => {+ processExited = true;+ });+ while (this.#clock.now() < deadline) {+ this.#throwIfStartCancelled(signal);+ if (processExited) break;+ try {+ const probed = await this.#awaitStartOperation(+ driver.probe(),+ signal,+ );+ if (probed.ready) {+ health = probed;+ break;+ }+ } catch (error) {+ this.#throwIfStartCancelled(signal);+ // WDA commonly refuses connections while XCTest is still launching.}- } catch {- // WDA commonly refuses connections while XCTest is still launching.+ await this.#sleepWhileStarting(500, signal);}- await this.#clock.sleep(500);- }- if (!health) {- unsubscribeOutput();- const failure = new WdaError(- "START_TIMEOUT",- "WebDriverAgent did not become ready in time",+ this.#throwIfStartCancelled(signal);+ if (!health) {+ throw new WdaError(+ "START_TIMEOUT",+ "WebDriverAgent did not become ready in time",+ );+ }++ const session = await this.#awaitStartOperation(+ driver.createSession(),+ signal,);- await this.#terminateProcessGroup(- options.instanceId,- options.simulatorUdid,- process,+ const driverSessionId = session.id;+ await this.#awaitStartOperation(+ driver.configureStream(driverSessionId, {+ framesPerSecond: 5,+ jpegQuality: 25,+ scalingPercent: 50,+ }),+ signal,);- throw failure;- }- let driverSessionId: string;- try {- const session = await driver.createSession();- driverSessionId = session.id;- await driver.configureStream(driverSessionId, {- framesPerSecond: 5,- jpegQuality: 25,- scalingPercent: 50,+ this.#throwIfStartCancelled(signal);++ let nativeSidecar: IOSSimulatorNativeSidecarDriver | undefined;+ let nativeUnavailableReason: string | null = null;+ const nativeManager = this.#options.nativeCapabilityProvider;+ if (nativeManager) {+ if (options.generation === undefined) {+ nativeUnavailableReason =+ "Native sidecar requires the simulator generation from the ownership actor.";+ } else {+ try {+ nativeSidecar = (+ await this.#awaitStartOperation(+ nativeManager.start({+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ generation: options.generation,+ runtime: {+ runtimeIdentifier: options.runtimeIdentifier,+ runtimeBuildVersion: options.runtimeBuildVersion ?? null,+ xcodeBuild: options.xcodeBuild,+ architecture: options.architecture,+ },+ }),+ signal,+ )+ ).adapter;+ } catch (error) {+ this.#throwIfStartCancelled(signal);+ nativeUnavailableReason =+ error instanceof Error+ ? error.message+ : "Native sidecar capability probe failed.";+ }+ }+ }+ this.#throwIfStartCancelled(signal);+ const driverRouter = this.#createDriverRouter({+ instanceId: options.instanceId,+ driver,+ nativeSidecar,+ nativeUnavailableReason,});+ const running: InternalRunningInstance = {+ instanceId: options.instanceId,+ simulatorUdid: options.simulatorUdid,+ pid: process.pid,+ controlPort,+ mjpegPort,+ sourceRevision: prepared.revision,+ buildCacheKey,+ driver,+ driverRouter,+ driverSessionId,+ health,+ startedAt: new Date(this.#clock.now()).toISOString(),+ process,+ unsubscribeOutput,+ log,+ nativeSidecar,+ nativeGeneration: options.generation,+ nativeRuntime: {+ runtimeIdentifier: options.runtimeIdentifier,+ runtimeBuildVersion: options.runtimeBuildVersion ?? null,+ xcodeBuild: options.xcodeBuild,+ architecture: options.architecture,+ },+ };+ operation.committed = true;+ this.#running.set(options.instanceId, running);+ void process.exited.then(() => {+ if (this.#running.get(options.instanceId)?.pid === process.pid) {+ void this.stop(options.instanceId).catch(() => undefined);+ }+ });+ return this.get(options.instanceId)!;} catch (error) {unsubscribeOutput();- const failure = new WdaError(+ await this.#options.nativeCapabilityProvider+ ?.stop(options.instanceId)+ .catch(() => undefined);+ await this.#terminatePendingProcess(options.instanceId, operation);+ if (error instanceof WdaError) throw error;+ throw new WdaError("LAUNCH_FAILED",`WebDriverAgent session setup failed: ${error instanceof Error ? error.message : String(error)}`,);- await this.#terminateProcessGroup(- options.instanceId,- options.simulatorUdid,- process,- );- throw failure;- }- let nativeSidecar: IOSSimulatorNativeSidecarDriver | undefined;- let nativeUnavailableReason: string | null = null;- const nativeManager = this.#options.nativeCapabilityProvider;- if (nativeManager) {- if (options.generation === undefined) {- nativeUnavailableReason =- "Native sidecar requires the simulator generation from the ownership actor.";- } else {- try {- nativeSidecar = (- await nativeManager.start({- instanceId: options.instanceId,- simulatorUdid: options.simulatorUdid,- generation: options.generation,- runtime: {- runtimeIdentifier: options.runtimeIdentifier,- runtimeBuildVersion: options.runtimeBuildVersion ?? null,- xcodeBuild: options.xcodeBuild,- architecture: options.architecture,- },- })- ).adapter;- } catch (error) {- nativeUnavailableReason =- error instanceof Error- ? error.message- : "Native sidecar capability probe failed.";- }+ } finally {+ if (!operation.committed && !this.#isProcessGroupAlive(process)) {+ this.#liveProcesses.delete(process);}}- const driverRouter = this.#createDriverRouter({- instanceId: options.instanceId,- driver,- nativeSidecar,- nativeUnavailableReason,- });- const running: InternalRunningInstance = {- instanceId: options.instanceId,- simulatorUdid: options.simulatorUdid,- pid: process.pid,- controlPort,- mjpegPort,- sourceRevision: prepared.revision,- buildCacheKey,- driver,- driverRouter,- driverSessionId,- health,- startedAt: new Date(this.#clock.now()).toISOString(),- process,- unsubscribeOutput,- log,- nativeSidecar,- nativeGeneration: options.generation,- nativeRuntime: {- runtimeIdentifier: options.runtimeIdentifier,- runtimeBuildVersion: options.runtimeBuildVersion ?? null,- xcodeBuild: options.xcodeBuild,- architecture: options.architecture,- },- };- this.#running.set(options.instanceId, running);- void process.exited.then(() => {- if (this.#running.get(options.instanceId)?.pid === process.pid) {- void this.stop(options.instanceId).catch(() => undefined);- }- });- return this.get(options.instanceId)!;}#createDriverRouter(input: {@@ -624,6 +687,60 @@ export class WdaProcessManager {});}+ #startCancelledError(): WdaError {+ return new WdaError(+ "START_CANCELLED",+ "WebDriverAgent startup was cancelled",+ );+ }++ #throwIfStartCancelled(signal: AbortSignal): void {+ if (signal.aborted) throw this.#startCancelledError();+ }++ #awaitStartOperation<T>(+ operation: Promise<T>,+ signal: AbortSignal,+ ): Promise<T> {+ if (signal.aborted) return Promise.reject(this.#startCancelledError());+ return new Promise<T>((resolve, reject) => {+ let settled = false;+ const finish = (callback: () => void) => {+ if (settled) return;+ settled = true;+ signal.removeEventListener("abort", onAbort);+ callback();+ };+ const onAbort = () => finish(() => reject(this.#startCancelledError()));+ signal.addEventListener("abort", onAbort, { once: true });+ if (signal.aborted) {+ onAbort();+ return;+ }+ operation.then(+ (value) => finish(() => resolve(value)),+ (error) => finish(() => reject(error)),+ );+ });+ }++ #sleepWhileStarting(ms: number, signal: AbortSignal): Promise<void> {+ return this.#awaitStartOperation(this.#clock.sleep(ms), signal);+ }++ #terminatePendingProcess(+ instanceId: string,+ operation: PendingWdaOperation,+ ): Promise<void> {+ if (!operation.process) return Promise.resolve();+ operation.termination ??= this.#terminateProcessGroup(+ instanceId,+ operation.simulatorUdid,+ operation.process,+ );+ return operation.termination;+ }+#isProcessGroupAlive(process: WdaManagedProcess): boolean {try {return process.isAlive();@@ -678,6 +795,7 @@ export class WdaProcessManager {!this.#isProcessGroupAlive(retiring.process)) {this.#retiring.delete(instanceId);+ this.#liveProcesses.delete(retiring.process);}}@@ -716,6 +834,7 @@ export class WdaProcessManager {} else {await cleanupDetachedDiagnostics(this.#options.cacheRoot, simulatorUdid);}+ this.#liveProcesses.delete(process);}async #resumeAfterRetiringProcess(@@ -752,11 +871,15 @@ export class WdaProcessManager {async #stop(instanceId: string): Promise<void> {const pending = this.#starting.get(instanceId);- if (pending) {- await this.#options.nativeCapabilityProvider+ if (pending && !pending.committed) {+ pending.controller.abort();+ const nativeStop = this.#options.nativeCapabilityProvider?.stop(instanceId).catch(() => undefined);+ const termination = this.#terminatePendingProcess(instanceId, pending);await pending.promise?.catch(() => undefined);+ await nativeStop;+ await termination;}const retiring = this.#retiring.get(instanceId);if (retiring) {diff --git a/packages/ios-simulator-runtime/src/wda/source-provider.test.ts b/packages/ios-simulator-runtime/src/wda/source-provider.test.tsindex 94b6b26279..92db4187fd 100644--- a/packages/ios-simulator-runtime/src/wda/source-provider.test.ts+++ b/packages/ios-simulator-runtime/src/wda/source-provider.test.ts@@ -6,7 +6,11 @@ import path from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";import type { IOSSimulatorCommandRunner } from "../types.js";-import { createWdaBuildCacheKey, prepareWdaSource } from "./source-provider.js";+import {+ abortWdaSourcePreparationForExit,+ createWdaBuildCacheKey,+ prepareWdaSource,+} from "./source-provider.js";const roots: string[] = [];@@ -73,7 +77,11 @@ describe("prepareWdaSource", () => {expect.stringContaining(".extract-"),"--strip-components=1",],- { timeoutMs: 60_000, maxBufferBytes: 2 * 1024 * 1024 },+ {+ timeoutMs: 60_000,+ maxBufferBytes: 2 * 1024 * 1024,+ signal: expect.any(AbortSignal),+ },);const marker = JSON.parse(await readFile(@@ -93,6 +101,42 @@ describe("prepareWdaSource", () => {expect(test.run).toHaveBeenCalledTimes(1);});+ it("shares and synchronously aborts in-flight extraction for updater exit", async () => {+ const test = await harness();+ let extractionSignal: AbortSignal | undefined;+ test.run.mockImplementation(async (_command, args, options) => {+ extractionSignal = options?.signal;+ return new Promise((resolve) => {+ const finish = () =>+ resolve({ stdout: "", stderr: "", exitCode: null });+ extractionSignal?.addEventListener("abort", finish, { once: true });+ if (extractionSignal?.aborted) finish();+ });+ });++ const first = prepareWdaSource({+ archivePath: test.archivePath,+ cacheRoot: test.cacheRoot,+ manifest: test.manifest,+ commandRunner: test.runner,+ });+ const second = prepareWdaSource({+ archivePath: test.archivePath,+ cacheRoot: test.cacheRoot,+ manifest: test.manifest,+ commandRunner: test.runner,+ });+ expect(second).toBe(first);+ await vi.waitFor(() => expect(test.run).toHaveBeenCalledTimes(1));++ abortWdaSourcePreparationForExit();++ expect(extractionSignal?.aborted).toBe(true);+ await expect(first).rejects.toMatchObject({+ code: "INVALID_CONFIGURATION",+ });+ });+it("rejects checksum drift before invoking tar", async () => {const test = await harness();await expect(diff --git a/packages/ios-simulator-runtime/src/wda/source-provider.ts b/packages/ios-simulator-runtime/src/wda/source-provider.tsindex 83c2ff4f1c..778ce77084 100644--- a/packages/ios-simulator-runtime/src/wda/source-provider.ts+++ b/packages/ios-simulator-runtime/src/wda/source-provider.ts@@ -46,7 +46,17 @@ export interface WdaBuildCacheIdentity {architecture: "arm64" | "x86_64";}-const inFlight = new Map<string, Promise<PreparedWdaSource>>();+interface InFlightWdaSourcePreparation {+ promise: Promise<PreparedWdaSource>;+ controller: AbortController;+}++const inFlight = new Map<string, InFlightWdaSourcePreparation>();++/** Synchronously signal shared extraction subprocesses before updater force-exit. */+export function abortWdaSourcePreparationForExit(): void {+ for (const operation of inFlight.values()) operation.controller.abort();+}function requireAbsolute(value: string, label: string): string {if (!path.isAbsolute(value)) {@@ -144,7 +154,8 @@ export function prepareWdaSource(const manifest = requireManifest(options.manifest ?? WDA_SOURCE_PIN);const key = `${archivePath}\0${cacheRoot}\0${manifest.revision}`;const existing = inFlight.get(key);- if (existing) return existing;+ if (existing) return existing.promise;+ const controller = new AbortController();const operation = (async () => {const runner =@@ -167,7 +178,11 @@ export function prepareWdaSource(const extracted = await runner.run(TAR,["-xzf", archivePath, "-C", temporaryPath, "--strip-components=1"],- { timeoutMs: 60_000, maxBufferBytes: 2 * 1024 * 1024 },+ {+ timeoutMs: 60_000,+ maxBufferBytes: 2 * 1024 * 1024,+ signal: controller.signal,+ },);if (extracted.exitCode !== 0) {throw new WdaError(@@ -204,6 +219,6 @@ export function prepareWdaSource(fromCache: false,};})().finally(() => inFlight.delete(key));- inFlight.set(key, operation);+ inFlight.set(key, { promise: operation, controller });return operation;}