Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): recover orphaned simulator runtimes
JiangJiahaoe91871510522
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 67b202caaa..3fce30d4a5 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -310,6 +310,7 @@ import {cleanupIOSSimulatorRemovedSession,disposeIOSSimulatorHost,flushIOSSimulatorOwnershipRegistry,+ reconcilePersistedIOSSimulatorOwnership,} from './mcp-integrations/ios-simulator';import { abortIOSSimulatorOperationsForExit } from './mcp-integrations/ios-simulator-exit';import {@@ -6378,6 +6379,7 @@ app.on('ready', async () => {registerLocalDbIpc({cancelSessionOperations: cancelIOSSimulatorSessionOperations,cleanupRemovedSession: cleanupIOSSimulatorRemovedSession,+ reconcilePersistedSessionRuntimes: reconcilePersistedIOSSimulatorOwnership,withSessionLock: withSendToSessionLock,isOwnerCurrent: (userId) =>isLocalDbOwnerCurrent(authManager.getAuthState(), userId, isAppSessionBoundaryPending()),diff --git a/apps/desktop/src/main/cindy-media/__tests__/ledger.test.ts b/apps/desktop/src/main/cindy-media/__tests__/ledger.test.tsindex 769532b027..dedca96a42 100644--- a/apps/desktop/src/main/cindy-media/__tests__/ledger.test.ts+++ b/apps/desktop/src/main/cindy-media/__tests__/ledger.test.ts@@ -415,29 +415,33 @@ describe('removeSessionRefsIfDeleted(软删墓碑原子门禁)', () => {});describe('reconcileSessionMediaRefsForDeletedSessions(持久重试)', () => {- it('只重试 deleted 任务并且重复运行幂等', async () => {+ it('only retries deleted tasks and remains idempotent', async () => {await seedSession('deleted-1', 'deleted');await seedSession('archived-1', 'archived');await seedBlob(HASH_A);await ledger.addRef({ hash: HASH_A, refKind: 'session-attachment', refId: 'deleted-1' }, db);await ledger.addRef({ hash: HASH_A, refKind: 'session-attachment', refId: 'archived-1' }, db);+ const quiesceSession = vi.fn(async () => undefined);await expect(sessionCleanup.reconcileSessionMediaRefsForDeletedSessions({db,isOwnerCurrent: () => true,withSessionLock: async (_sessionId, task) => task(),- quiesceSession: async () => undefined,+ quiesceSession,}),).resolves.toMatchObject({ scanned: 1, removed: 1, failed: 0 });+ expect(quiesceSession).toHaveBeenCalledWith('deleted-1');+ quiesceSession.mockClear();await expect(sessionCleanup.reconcileSessionMediaRefsForDeletedSessions({db,isOwnerCurrent: () => true,withSessionLock: async (_sessionId, task) => task(),- quiesceSession: async () => undefined,+ quiesceSession,}),).resolves.toMatchObject({ scanned: 1, removed: 0, failed: 0 });+ expect(quiesceSession).toHaveBeenCalledTimes(1);expect(db.select().from(schema.mediaRefs).all()).toMatchObject([{ refId: 'archived-1' }]);});diff --git a/apps/desktop/src/main/cindy-media/sessionCleanup.ts b/apps/desktop/src/main/cindy-media/sessionCleanup.tsindex c0e243ee14..f2d12edd60 100644--- a/apps/desktop/src/main/cindy-media/sessionCleanup.ts+++ b/apps/desktop/src/main/cindy-media/sessionCleanup.ts@@ -22,9 +22,10 @@ export interface ReconcileDeletedSessionMediaResult {}/**- * Retry session-ref cleanup from durable soft-delete tombstones. A process- * restart guarantees old media producers are gone; the atomic ledger guard- * still preserves refs if a task was restored before this pass reaches it.+ * Retry runtime quiescence and session-ref cleanup from durable soft-delete+ * tombstones. Archived Simulator ownership is reconciled in one bounded Host+ * registry pass before this media cleanup runs. The atomic ledger guard still+ * preserves refs unless the task remains deleted when the DELETE executes.*/export async function reconcileSessionMediaRefsForDeletedSessions(options: ReconcileDeletedSessionMediaOptions,diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/ownerEnsureCoordinator.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/ownerEnsureCoordinator.test.tsindex 6c5930b7b4..7a49986301 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/ownerEnsureCoordinator.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/ownerEnsureCoordinator.test.ts@@ -116,7 +116,7 @@ describe('createOwnerEnsureCoordinator', () => {});describe('registerLocalDbIpc ready-hook composition', () => {- it('lets the lifecycle hook install DbClient before scheduling media reconcile', () => {+ it('installs DbClient before runtime recovery and deleted-media reconcile', () => {const source = fs.readFileSync(new URL('../registerAll.ts', import.meta.url), 'utf8');const start = source.indexOf('onReady: async (userId) => {');const end = source.indexOf('onReadyError:', start);@@ -125,6 +125,10 @@ describe('registerLocalDbIpc ready-hook composition', () => {expect(hook.indexOf('await opts.onReady?.(userId)')).toBeLessThan(hook.indexOf('tryGetDbClient()'),);+ expect(hook).toContain('await opts.reconcilePersistedSessionRuntimes?.()');+ expect(hook.indexOf('await opts.reconcilePersistedSessionRuntimes?.()')).toBeLessThan(+ hook.indexOf('reconcileSessionMediaRefsForDeletedSessions({'),+ );expect(hook).toContain('if (');expect(hook).toContain('!client');expect(hook).toContain('!withSessionLock');diff --git a/apps/desktop/src/main/localDb/ipc/registerAll.ts b/apps/desktop/src/main/localDb/ipc/registerAll.tsindex fd02bc90a0..45cefb2617 100644--- a/apps/desktop/src/main/localDb/ipc/registerAll.ts+++ b/apps/desktop/src/main/localDb/ipc/registerAll.ts@@ -79,6 +79,8 @@ export interface RegisterLocalDbIpcOpts {cancelSessionOperations?: (sessionId: string) => Promise<void>;/** Release Host-owned runtime and ownership after task removal is revalidated. */cleanupRemovedSession?: (sessionId: string) => Promise<void>;+ /** Reconcile persisted Host-owned task runtimes once the owner DB is readable. */+ reconcilePersistedSessionRuntimes?: () => Promise<void>;/** Serialize startup tombstone cleanup with task restore/start/send operations. */withSessionLock?: <T>(sessionId: string, task: () => Promise<T>) => Promise<T>;/**@@ -121,17 +123,35 @@ export function registerLocalDbIpc(opts: RegisterLocalDbIpcOpts = {}): void {const cancelSessionOperations = opts.cancelSessionOperations;const cleanupRemovedSession = opts.cleanupRemovedSession;const withSessionLock = opts.withSessionLock;- if (!cancelSessionOperations || !cleanupRemovedSession || !withSessionLock) return;const db = client.drizzle;- void reconcileSessionMediaRefsForDeletedSessions({- db,- isOwnerCurrent: isReadyOwnerCurrent,- withSessionLock,- quiesceSession: async (sessionId) => {- await cancelSessionOperations(sessionId);- await cleanupRemovedSession(sessionId);- },- }).catch((error) => {+ void (async () => {+ if (!isReadyOwnerCurrent()) return;+ try {+ await opts.reconcilePersistedSessionRuntimes?.();+ } catch (error) {+ log.warn('persisted task runtime reconcile failed', {+ userId,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ if (+ !isReadyOwnerCurrent() ||+ !cancelSessionOperations ||+ !cleanupRemovedSession ||+ !withSessionLock+ ) {+ return;+ }+ await reconcileSessionMediaRefsForDeletedSessions({+ db,+ isOwnerCurrent: isReadyOwnerCurrent,+ withSessionLock,+ quiesceSession: async (sessionId) => {+ await cancelSessionOperations(sessionId);+ await cleanupRemovedSession(sessionId);+ },+ });+ })().catch((error) => {log.warn('deleted task media reconcile failed', {userId,error: error instanceof Error ? error.message : String(error),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 c16b368ccb..bc6c59000e 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@@ -16,6 +16,7 @@ import {IOSSimulatorProjectBuildError,IOSSimulatorResourceScheduler,WdaError,+ WdaProcessManager,type IOSSimulatorEnvironmentReport,type IOSSimulatorH264Frame,type IOSSimulatorNativeSidecarDriver,@@ -34,6 +35,7 @@ import {disposeIOSSimulatorHost,flushIOSSimulatorOwnershipRegistry,getIOSSimulatorMcpDeps,+ reconcilePersistedIOSSimulatorOwnership,type IOSSimulatorAppLifecycleAdapter,type IOSSimulatorMediaCaptureAdapter,type IOSSimulatorProjectBuilderAdapter,@@ -124,6 +126,21 @@ describe('iOS Simulator host', () => {}});+ itMac('keeps startup ownership recovery lazy when the registry is empty', async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-host-lazy-reconcile-'));+ const getPath = vi.spyOn(app, 'getPath').mockReturnValue(root);+ const registryPath = path.join(root, 'ios-simulator', 'ownership-registry.json');+ const competingRegistry = new IOSSimulatorOwnershipRegistryFile(registryPath);+ try {+ await expect(reconcilePersistedIOSSimulatorOwnership()).resolves.toBeUndefined();+ expect(competingRegistry.acquireWriterSync()).toBe(true);+ } finally {+ competingRegistry.releaseWriterSync();+ getPath.mockRestore();+ await rm(root, { recursive: true, force: true });+ }+ });+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');@@ -468,6 +485,61 @@ describe('iOS Simulator host', () => {});});+ it('recovers persisted WDA ownership before marking a booted binding healthy', async () => {+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };+ const actor = new IOSSimulatorInstanceActor({+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),+ lifecycle,+ });+ const attached = actor.attach({+ sessionId: 'persisted-wda-session',+ worktreeRoot: '/tmp/persisted-wda-session',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const cleanupOrphaned = vi+ .fn(async () => undefined)+ .mockRejectedValueOnce(new WdaError('TERMINATION_FAILED', 'orphan still running'));+ const driverManager = {+ get: vi.fn(() => null),+ cleanupOrphaned,+ start: vi.fn(async () => {+ throw new Error('not expected');+ }),+ stop: vi.fn(async () => undefined),+ };+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => localSession('persisted-wda-session')),+ });++ await host.reconcileOwnership();+ expect(cleanupOrphaned).toHaveBeenCalledWith(attached.instanceId, attached.simulatorUdid);+ expect(actor.getOwned('persisted-wda-session', attached.instanceId)).toMatchObject({+ lifecycleState: 'ready',+ healthState: 'degraded',+ errorCode: 'WDA_UNAVAILABLE',+ });++ await host.reconcileOwnership();+ expect(cleanupOrphaned).toHaveBeenCalledTimes(2);+ expect(actor.getOwned('persisted-wda-session', attached.instanceId)).toMatchObject({+ lifecycleState: 'ready',+ healthState: 'healthy',+ errorCode: null,+ });+ expect(driverManager.stop).not.toHaveBeenCalled();+ });+it.each(['Booted', 'Booting'] as const)('restores scheduler occupancy for a persisted %s device',async (deviceState) => {@@ -801,6 +873,63 @@ describe('iOS Simulator host', () => {expect(actor.listAll()).toEqual([]);});+ it('rechecks archived status under the task route lock before destructive recovery', async () => {+ let releaseLock!: () => void;+ const lockGate = new Promise<void>((resolve) => {+ releaseLock = resolve;+ });+ let status: 'active' | 'archived' = 'archived';+ 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: 'archived-then-restored',+ worktreeRoot: '/tmp/archived-then-restored',+ sourceFingerprint: 'fingerprint-a',+ creationProvenance: 'cindy',+ bootProvenance: 'agent-booted',+ device: { ...READY_REPORT.devices[0]!, state: 'Booted' },+ });+ const withSessionLock = vi.fn(+ async <T>(_sessionId: string, task: () => Promise<T>): Promise<T> => {+ await lockGate;+ return task();+ },+ );+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ withSessionLock,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => ({+ ...localSession('archived-then-restored'),+ status,+ })),+ });++ const reconcile = host.reconcileOwnership();+ await vi.waitFor(() => expect(withSessionLock).toHaveBeenCalledOnce());+ status = 'active';+ releaseLock();+ await reconcile;++ expect(withSessionLock).toHaveBeenCalledWith('archived-then-restored', expect.any(Function));+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();+ expect(lifecycle.deleteExact).not.toHaveBeenCalled();+ expect(actor.getOwned('archived-then-restored', instance.instanceId)).toMatchObject({+ lifecycleState: 'ready',+ healthState: 'healthy',+ });+ });+it('stops the driver runtime before shutting down and deleting a stale device', async () => {const order: string[] = [];const lifecycle: IOSSimulatorSimctlLifecycle = {@@ -898,6 +1027,50 @@ describe('iOS Simulator host', () => {expect(lifecycle.deleteExact).not.toHaveBeenCalled();});+ it('aborts driver work before orphan recovery and still scans after stop fails', async () => {+ const order: string[] = [];+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(async () => READY_REPORT.devices[0]),+ 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: 'removed-during-driver-start',+ worktreeRoot: '/tmp/removed-during-driver-start',+ sourceFingerprint: 'fingerprint-a',+ device: READY_REPORT.devices[0]!,+ });+ const host = createIOSSimulatorHost({+ actor,+ lifecycle,+ driverManager: {+ get: vi.fn(() => null),+ start: vi.fn(),+ stop: vi.fn(async () => {+ order.push('stop');+ throw new Error('pending start cancellation failed');+ }),+ cleanupOrphaned: vi.fn(async () => {+ order.push('cleanup');+ }),+ },+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async () => null),+ });++ await expect(host.cleanupRemovedSession(instance.sessionId)).rejects.toMatchObject({+ code: 'DEVICE_BUSY',+ });+ expect(order).toEqual(['stop', 'cleanup']);+ expect(actor.listAll()).toHaveLength(1);+ });+it('stops the driver runtime when ownership reconcile observes a shut down device', async () => {const lifecycle: IOSSimulatorSimctlLifecycle = {findExact: vi.fn(),@@ -5781,6 +5954,9 @@ describe('iOS Simulator host', () => {.mockImplementation(() => {writerLeaseHeld = false;});+ const cleanupOrphaned = vi+ .spyOn(WdaProcessManager.prototype, 'cleanupOrphaned')+ .mockResolvedValue();try {await expect(cleanupIOSSimulatorRemovedSession('persisted-removed-session'),@@ -5805,6 +5981,7 @@ describe('iOS Simulator host', () => {releaseWriter.mockRestore();isWriter.mockRestore();acquireWriter.mockRestore();+ cleanupOrphaned.mockRestore();getPath.mockRestore();await rm(root, { recursive: true, force: true });}diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.tsindex edd3c21563..45f6c2c846 100644--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts@@ -82,6 +82,7 @@ import type {GhostIOSSimulatorStatusSnapshot,} from '../../shared/ghost.js';import { createLogger } from '../logger.js';+import { withSessionRouteLock } from '../localDb/sessionRouteLock.js';import { desktopSessionStorage } from '../maker-host/session-storage.js';import { isTrustedAppRendererWindow } from '../security/trustedAppRenderer.js';import {@@ -119,6 +120,7 @@ interface IOSSimulatorSessionSnapshot {interface IOSSimulatorDriverManager {get(instanceId: string): WdaRunningInstance | null;probe?(instanceId: string): Promise<WdaRunningInstance | null>;+ cleanupOrphaned?(instanceId: string, simulatorUdid: string): Promise<void>;start(options: WdaStartOptions): Promise<WdaRunningInstance>;stop(instanceId: string): Promise<void>;recoverNativeSidecar?(@@ -183,6 +185,8 @@ export interface IOSSimulatorHostOptions {/** Minimum interval between exact-UDID CoreSimulator liveness checks. */deviceLivenessIntervalMs?: number;getSession?: (sessionId: string) => Promise<IOSSimulatorSessionSnapshot | null>;+ /** Serialize persisted recovery with task archive/restore/send mutations. */+ withSessionLock?: <T>(sessionId: string, task: () => Promise<T>) => Promise<T>;resolveWorktreeRoot?: (workDir: string) => Promise<string>;requestViewerFocus?: (sessionId: string, instanceId: string) => void;/** Main → renderer route diagnostics seam; injected in tests, broadcast by default. */@@ -1567,6 +1571,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Istatus: await desktopSessionStorage.getStatus(sessionId),};});+ const withSessionLock = options.withSessionLock ?? withSessionRouteLock;const resolveWorktreeRoot = options.resolveWorktreeRoot ?? realpath;const requestViewerFocus =options.requestViewerFocus ??@@ -1712,6 +1717,21 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I}}+ async function cleanupOrphanedDriverRuntime(instance: IOSSimulatorInstance): Promise<boolean> {+ if (!driverManager?.cleanupOrphaned) return true;+ try {+ await driverManager.cleanupOrphaned(instance.instanceId, instance.simulatorUdid);+ return true;+ } catch (error) {+ logger.warn('iOS Simulator ownership cleanup could not recover orphaned driver runtime', {+ instanceId: instance.instanceId,+ simulatorUdid: instance.simulatorUdid,+ error: error instanceof Error ? error.message : String(error),+ });+ return false;+ }+ }+async function releaseInstanceRuntime(instance: IOSSimulatorInstance): Promise<boolean> {beginInstanceTeardown(instance.instanceId);try {@@ -1733,6 +1753,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Ierror: error instanceof Error ? error.message : String(error),});});+ if (!(await cleanupOrphanedDriverRuntime(instance))) cleanupSucceeded = false;}return cleanupSucceeded;} finally {@@ -2102,6 +2123,93 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I};}+ async function reconcilePersistedInstance(+ snapshot: IOSSimulatorInstance,+ devices: ReadonlyMap<string, IOSSimulatorEnvironmentReport['devices'][number]>,+ ): Promise<boolean> {+ const instance = actor+ .list(snapshot.sessionId)+ .find((candidate) => candidate.instanceId === snapshot.instanceId);+ if (!instance) return true;++ let complete = true;+ let driverRuntimeRecovered = await cleanupOrphanedDriverRuntime(instance);+ if (!driverRuntimeRecovered) complete = false;+ 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 occupancy before any fallible lookup/cleanup.+ resourceScheduler.restoreRunning(instance.instanceId);+ }+ let session: IOSSimulatorSessionSnapshot | null = null;+ try {+ session = await getSession(instance.sessionId);+ } catch (error) {+ logger.warn('iOS Simulator ownership reconcile could not read session', {+ instanceId: instance.instanceId,+ error: error instanceof Error ? error.message : String(error),+ });+ return false;+ }+ if (!session || session.status === 'deleted' || session.status === 'archived') {+ return (await releaseStaleBinding(instance, device)) && complete;+ }+ if (session.remoteHostId || !device) {+ const runtimeReleased = await releaseInstanceRuntime(instance);+ if (!runtimeReleased) complete = false;+ if (runtimeReleased && (!device || device.state.trim().toLowerCase() === 'shutdown')) {+ resourceScheduler.markStopped(instance.instanceId);+ }+ actor.reconcile(+ instance.instanceId,+ instance.sessionId,+ device ? (deviceState === 'booted' ? 'ready' : 'stopped') : 'error',+ 'degraded',+ session.remoteHostId ? 'UNSUPPORTED_SESSION_KIND' : 'ORPHANED_DEVICE',+ );+ return complete;+ }+ const reconciledDeviceState = deviceState ?? 'unknown';+ if (reconciledDeviceState === 'shutdown') {+ const runtimeReleased = await releaseInstanceRuntime(instance);+ if (runtimeReleased) {+ resourceScheduler.markStopped(instance.instanceId);+ } else {+ driverRuntimeRecovered = false;+ complete = false;+ }+ } 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.+ if (!(await releaseInstanceRuntime(instance))) {+ driverRuntimeRecovered = false;+ complete = false;+ }+ }+ actor.reconcile(+ instance.instanceId,+ instance.sessionId,+ reconciledDeviceState === 'booted'+ ? 'ready'+ : reconciledDeviceState === 'shutdown'+ ? 'stopped'+ : reconciledDeviceState.includes('boot')+ ? 'booting'+ : reconciledDeviceState.includes('shutting')+ ? 'stopping'+ : 'error',+ !driverRuntimeRecovered+ ? 'degraded'+ : reconciledDeviceState === 'booted' || reconciledDeviceState === 'shutdown'+ ? 'healthy'+ : 'recovering',+ driverRuntimeRecovered ? null : 'WDA_UNAVAILABLE',+ );+ return complete;+ }+async function reconcilePersistedOwnership(): Promise<void> {if (disposePromise) return;if (ownershipReconciled) return;@@ -2116,82 +2224,11 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Ienvironment.devices.map((device) => [device.udid.toUpperCase(), device]),);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);- } catch (error) {- complete = false;- logger.warn('iOS Simulator ownership reconcile could not read session', {- instanceId: instance.instanceId,- error: error instanceof Error ? error.message : String(error),- });- continue;- }- if (!session) {- if (!(await releaseStaleBinding(instance, device))) complete = false;- continue;- }- if (session.status === 'deleted') {- if (!(await releaseStaleBinding(instance, device))) complete = false;- continue;- }- if (session.status === 'archived') {- if (!(await releaseStaleBinding(instance, device))) complete = false;- continue;- }- if (session.remoteHostId || !device) {- const runtimeReleased = await releaseInstanceRuntime(instance);- if (!runtimeReleased) complete = false;- if (runtimeReleased && (!device || device.state.trim().toLowerCase() === 'shutdown')) {- resourceScheduler.markStopped(instance.instanceId);- }- actor.reconcile(- instance.instanceId,- instance.sessionId,- device ? (deviceState === 'booted' ? 'ready' : 'stopped') : 'error',- 'degraded',- session.remoteHostId ? 'UNSUPPORTED_SESSION_KIND' : 'ORPHANED_DEVICE',- );- continue;- }- const reconciledDeviceState = deviceState ?? 'unknown';- if (reconciledDeviceState === 'shutdown') {- const runtimeReleased = await releaseInstanceRuntime(instance);- if (runtimeReleased) {- resourceScheduler.markStopped(instance.instanceId);- } else complete = false;- } 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.- if (!(await releaseInstanceRuntime(instance))) complete = false;- }- actor.reconcile(- instance.instanceId,- instance.sessionId,- reconciledDeviceState === 'booted'- ? 'ready'- : reconciledDeviceState === 'shutdown'- ? 'stopped'- : reconciledDeviceState.includes('boot')- ? 'booting'- : reconciledDeviceState.includes('shutting')- ? 'stopping'- : 'error',- reconciledDeviceState === 'booted' || reconciledDeviceState === 'shutdown'- ? 'healthy'- : 'recovering',- null,+ for (const snapshot of actor.listAll()) {+ const instanceComplete = await withSessionLock(snapshot.sessionId, () =>+ reconcilePersistedInstance(snapshot, devices),);+ if (!instanceComplete) complete = false;}ownershipReconciled = complete;})().finally(() => {@@ -5553,6 +5590,7 @@ function installDefaultIOSSimulatorHost(const host = createIOSSimulatorHost({lifecycle,actor: persistedActor.actor,+ driverManager: createDefaultDriverManager(),});configureIOSSimulatorRendererAccessRevocationObserver((grants) => {for (const grant of grants) {@@ -5670,6 +5708,41 @@ export function reconcileIOSSimulatorOwnership(): Promise<void> {return initializeIOSSimulatorHost().reconcileOwnership();}+/**+ * Startup recovery stays lazy when this profile has never owned a simulator,+ * but persisted bindings must be reconciled even if the feature is not opened+ * again after a crash.+ */+export function reconcilePersistedIOSSimulatorOwnership(): Promise<void> {+ const currentHost = currentIOSSimulatorHost();+ if (currentHost) return currentHost.reconcileOwnership();+ if (process.platform !== 'darwin') return Promise.resolve();++ const registry = createDefaultOwnershipRegistry();+ let registryTransferred = false;+ try {+ if (!registry.acquireWriterSync()) {+ throw new IOSSimulatorInstanceError(+ 'DEVICE_BUSY',+ 'Another Cindy process is managing iOS Simulator ownership for this profile.',+ true,+ );+ }+ if (registry.loadSync().length === 0) {+ registry.releaseWriterSync();+ return Promise.resolve();+ }+ const lifecycle = createIOSSimulatorSimctlLifecycle();+ const persistedActor = createDefaultActor(lifecycle, registry);+ const host = installDefaultIOSSimulatorHost(lifecycle, persistedActor);+ registryTransferred = true;+ return host.reconcileOwnership();+ } catch (error) {+ if (!registryTransferred) registry.releaseWriterSync();+ return Promise.reject(error);+ }+}+export async function disposeIOSSimulatorHost(): Promise<void> {if (defaultIOSSimulatorRuntimeDisposePromise) return defaultIOSSimulatorRuntimeDisposePromise;defaultIOSSimulatorRuntimeClosing = true;diff --git a/docs/ios-simulator-integration-plan.md b/docs/ios-simulator-integration-plan.mdindex e0c3cb23ef..1d7707a167 100644--- a/docs/ios-simulator-integration-plan.md+++ b/docs/ios-simulator-integration-plan.md@@ -26,6 +26,7 @@- 新增 capability router/report、5-byte bounded sidecar protocol、按精确 UDID/generation 绑定的 `IOSSimulatorNativeSidecarAdapter` 和 native process manager;native executable 已开放只读单帧 correctness capture、H.264 产品连续流和连续 HID。Development 与 packaged 运行时都默认按能力尝试 Native;兼容矩阵 `unknown` 只进入 probation/handshake,不再阻止 Sidecar 启动,明确不兼容、artifact 不可信、资源拒绝或进程 parked 仍硬拒绝并回退 WDA/MJPEG。`CINDY_IOS_SIMULATOR_NATIVE_H264=0` / `CINDY_IOS_SIMULATOR_NATIVE_HID=0` 仍可作为开发诊断关闭开关。BGRA 产品流固定关闭。- native process manager 已实现 argv-only 绝对路径启动、POSIX process-group kill、最小环境变量白名单、协议/能力/UDID/generation handshake、availability probe、实例级 stop,以及同 identity 的 restart/re-arm;WDA manager 可在不重启 WDA session 或 simulator 的前提下重新握手、probe 并原子替换 capability router,失败仍只保留 MJPEG fallback。- Native Sidecar 与 WDA process manager 的 `stop()` 现在会确定性等待同 instance 的 in-flight start/recover:stop 先让已创建 channel 进入 stopped 并中止 pending request,晚到的 handshake/availability/restart 不会重新写回 running binding;重复 stop 共用同一收敛操作。WDA owner 同样等待正在 build/start 的 operation,完成后删除 session、结束 WDA 和 Sidecar,不把晚到子进程留给 Desktop quit。+- WDA controller 与 Simulator 内独立 Runner 共享由 profile、instance 和精确 UDID 推导的非敏感 owner fingerprint。Main 被 `SIGKILL` 后,新 Host 会先用无环境变量的进程清单筛出精确候选,再只读取候选 Runner 的 owner 标记并回收对应进程组;无法证明归属的同设备 WDA 不会被终止,也会阻止 Cindy 启动第二套 WDA。归档与删除任务都会在启动恢复中重试 runtime quiescence,但只有删除任务会移除媒体引用。- macOS-only sidecar executable 已实现精确 UDID 设备查找、0~16 有界 screen ID discovery、`IOSurfaceLock(.readOnly)`、BGRA pixel format/尺寸/stride/byte limit 校验和立即复制解锁;单帧通过现有 `StreamFrame`/`StreamEnd` 传输,不新增网络端口或持久媒体旁路。- arm64 与 x86_64 分别使用最小 ABI shim 调用 private Swift getter,显式满足其 method-self 寄存器约定,不依赖优化器偶然分配;`native:build` 生成架构专属 sidecar 并清理中间 object。- sidecar handshake 会报告 sanitized `framebufferSymbols`、`framebufferCapture` 和 width/height/bytesPerRow/byteCount/screenId/pixelFormat;framework 路径、IOSurface 句柄和原始 stderr 不进入 renderer/Agent diagnostics。diff --git a/packages/ios-simulator-runtime/src/wda/build-plan.test.ts b/packages/ios-simulator-runtime/src/wda/build-plan.test.tsindex 30451ebb88..e9072498a3 100644--- a/packages/ios-simulator-runtime/src/wda/build-plan.test.ts+++ b/packages/ios-simulator-runtime/src/wda/build-plan.test.ts@@ -5,6 +5,7 @@ import { describe, expect, it } from "vitest";import { createWdaBuildPlan, createWdaChildEnvironment } from "./build-plan.js";const UDID = "1A9D41E0-E031-4AD0-A8B5-847480802E8E";+const OWNER_FINGERPRINT = "b".repeat(64);const CHECKOUT_PATH = path.resolve("/tmp/wda");const DERIVED_DATA_PATH = path.resolve("/tmp/wda-derived");@@ -14,6 +15,7 @@ describe("createWdaBuildPlan", () => {checkoutPath: CHECKOUT_PATH,derivedDataPath: DERIVED_DATA_PATH,simulatorUdid: UDID.toLowerCase(),+ ownerFingerprint: OWNER_FINGERPRINT,architecture: "arm64",controlPort: 18_100,mjpegPort: 19_100,@@ -31,8 +33,17 @@ describe("createWdaBuildPlan", () => {);expect(plan.build.args[0]).toBe("-quiet");expect(plan.build.args).toContain("build-for-testing");+ expect(plan.build.args).toContain(+ `CINDY_WDA_OWNER_FINGERPRINT=${OWNER_FINGERPRINT}`,+ );expect(plan.build.env).not.toHaveProperty("XDT_CODEX_API_KEY");expect(plan.launch.args).toContain("test-without-building");+ expect(plan.launch.args).toContain(+ `CINDY_WDA_OWNER_FINGERPRINT=${OWNER_FINGERPRINT}`,+ );+ expect(plan.launch.args).toContain(+ `UPGRADE_TIMESTAMP=${OWNER_FINGERPRINT}`,+ );expect(plan.launch.args[0]).toBe("-quiet");expect(plan.launch.env).toMatchObject({USE_PORT: "18100",@@ -66,6 +77,7 @@ describe("createWdaBuildPlan", () => {checkoutPath: "relative",derivedDataPath: "/tmp/derived",simulatorUdid: UDID,+ ownerFingerprint: OWNER_FINGERPRINT,}),).toThrow("checkoutPath must be an absolute path");expect(() =>@@ -73,6 +85,7 @@ describe("createWdaBuildPlan", () => {checkoutPath: CHECKOUT_PATH,derivedDataPath: path.resolve("/tmp/derived"),simulatorUdid: "not-a-udid",+ ownerFingerprint: OWNER_FINGERPRINT,}),).toThrow("simulatorUdid must be an exact simulator UUID");expect(() =>@@ -80,9 +93,18 @@ describe("createWdaBuildPlan", () => {checkoutPath: CHECKOUT_PATH,derivedDataPath: path.resolve("/tmp/derived"),simulatorUdid: UDID,+ ownerFingerprint: OWNER_FINGERPRINT,controlPort: 8100,mjpegPort: 8100,}),).toThrow("controlPort and mjpegPort must differ");+ expect(() =>+ createWdaBuildPlan({+ checkoutPath: CHECKOUT_PATH,+ derivedDataPath: DERIVED_DATA_PATH,+ simulatorUdid: UDID,+ ownerFingerprint: "not-a-digest",+ }),+ ).toThrow("ownerFingerprint must be an exact SHA-256 hex digest");});});diff --git a/packages/ios-simulator-runtime/src/wda/build-plan.ts b/packages/ios-simulator-runtime/src/wda/build-plan.tsindex 8179a5ebf0..ce65bc205b 100644--- a/packages/ios-simulator-runtime/src/wda/build-plan.ts+++ b/packages/ios-simulator-runtime/src/wda/build-plan.ts@@ -34,6 +34,7 @@ export interface CreateWdaBuildPlanOptions {checkoutPath: string;derivedDataPath: string;simulatorUdid: string;+ ownerFingerprint: string;architecture?: "arm64" | "x86_64";controlPort?: number;mjpegPort?: number;@@ -60,6 +61,14 @@ function requireUdid(value: string): string {return normalized;}+function requireOwnerFingerprint(value: string): string {+ const normalized = value.trim().toLowerCase();+ if (!/^[0-9a-f]{64}$/.test(normalized)) {+ throw new Error("ownerFingerprint must be an exact SHA-256 hex digest");+ }+ return normalized;+}+/*** Xcode schemes may print their environment. Copy only host values required by* Apple tooling so API keys and unrelated app secrets cannot enter build logs.@@ -86,6 +95,7 @@ export function createWdaBuildPlan("derivedDataPath",);const simulatorUdid = requireUdid(options.simulatorUdid);+ const ownerFingerprint = requireOwnerFingerprint(options.ownerFingerprint);const architecture =options.architecture ?? (process.arch === "x64" ? "x86_64" : "arm64");const controlPort = requirePort(options.controlPort ?? 8100, "controlPort");@@ -108,6 +118,11 @@ export function createWdaBuildPlan(const buildSettings = ["CODE_SIGNING_ALLOWED=NO","COMPILER_INDEX_STORE_ENABLE=NO",+ `CINDY_WDA_OWNER_FINGERPRINT=${ownerFingerprint}`,+ // The bundled WDA scheme forwards this existing build setting into the+ // independent Simulator runner environment. It lets crash recovery prove+ // ownership without persisting or trusting a PID.+ `UPGRADE_TIMESTAMP=${ownerFingerprint}`,];return {diff --git a/packages/ios-simulator-runtime/src/wda/process-manager.test.ts b/packages/ios-simulator-runtime/src/wda/process-manager.test.tsindex 6210457276..7a101d16e8 100644--- a/packages/ios-simulator-runtime/src/wda/process-manager.test.ts+++ b/packages/ios-simulator-runtime/src/wda/process-manager.test.ts@@ -15,9 +15,19 @@ import type {} from "../driver.js";import type { IOSSimulatorNativeSidecarStartOptions } from "../native-sidecar/process-manager.js";import type { IOSSimulatorCommandRunner } from "../types.js";+import { WdaError } from "./errors.js";import {+ createWdaOwnerFingerprint,+ findCindyWdaDiagnosticCandidates,+ findCindyWdaOrphanProcessGroups,+ findCindyWdaRunnerCandidates,+ hasConflictingWdaController,+ matchesCindyWdaDiagnosticCommand,+ matchesCindyWdaRunnerEnvironment,+ matchesLegacyCindyWdaRunnerEnvironment,WdaProcessManager,type WdaManagedProcess,+ type WdaOrphanProcessCleaner,type WdaProcessManagerOptions,} from "./process-manager.js";@@ -28,6 +38,7 @@ interface HarnessOptions {startTimeoutMs?: number;leaderExitsOn?: readonly NodeJS.Signals[];groupExitsOn?: readonly NodeJS.Signals[];+ orphanProcessCleaner?: WdaOrphanProcessCleaner;}afterEach(async () => {@@ -126,6 +137,9 @@ async function createHarness(let now = 1_000;const ports = [18_100, 19_100, 18_101, 19_101];const launch = vi.fn(() => process);+ const orphanProcessCleaner = vi.fn<WdaOrphanProcessCleaner>(+ harnessOptions.orphanProcessCleaner ?? (async () => undefined),+ );const manager = new WdaProcessManager({archivePath,cacheRoot: path.join(root, "cache"),@@ -143,6 +157,7 @@ async function createHarness(},},nativeCapabilityProvider,+ orphanProcessCleaner,startTimeoutMs: harnessOptions.startTimeoutMs,});return {@@ -153,12 +168,346 @@ async function createHarness(process,killed,launch,+ orphanProcessCleaner,exitGroup,exitLeader: settleLeader,};}+describe("WDA orphan ownership matching", () => {+ const cacheRoot =+ "/Users/test/Library/Application Support/Cindy Test/ios-simulator/wda";+ const coreSimulatorRoot = "/Users/test/Library/Developer/CoreSimulator";+ const xcodebuild =+ "/Applications/Xcode Test.app/Contents/Developer/usr/bin/xcodebuild";+ const ownerFingerprint = createWdaOwnerFingerprint(+ cacheRoot,+ "instance-a",+ UDID,+ );+ const input = {+ cacheRoot,+ instanceId: "instance-a",+ simulatorUdid: UDID,+ ownerFingerprint,+ coreSimulatorRoot,+ xcodebuildExecutablePaths: [xcodebuild],+ };+ const project = `${cacheRoot}/source/${"a".repeat(40)}/WebDriverAgent.xcodeproj`;+ const derived = `${cacheRoot}/derived/${"b".repeat(64)}`;+ const command =+ `${xcodebuild} -quiet -project ${project}` ++ ` -scheme WebDriverAgentRunner` ++ ` -destination platform=iOS Simulator,id=${UDID},arch=arm64` ++ ` -derivedDataPath ${derived} test-without-building` ++ ` CODE_SIGNING_ALLOWED=NO COMPILER_INDEX_STORE_ENABLE=NO`;++ it("binds the owner fingerprint to profile, instance, and exact simulator", () => {+ expect(ownerFingerprint).toMatch(/^[0-9a-f]{64}$/);+ expect(+ createWdaOwnerFingerprint(cacheRoot, "instance-a", UDID.toLowerCase()),+ ).toBe(ownerFingerprint);+ expect(+ createWdaOwnerFingerprint(`${cacheRoot}-other`, "instance-a", UDID),+ ).not.toBe(ownerFingerprint);+ expect(createWdaOwnerFingerprint(cacheRoot, "instance-b", UDID)).not.toBe(+ ownerFingerprint,+ );+ });++ it("matches only an exact controller argv and keeps legacy ownership narrow", () => {+ const tagged =+ `${command} CINDY_WDA_OWNER_FINGERPRINT=${ownerFingerprint}` ++ ` UPGRADE_TIMESTAMP=${ownerFingerprint}`;+ expect(findCindyWdaOrphanProcessGroups(`420 420 ${tagged}`, input)).toEqual(+ [420],+ );+ expect(+ findCindyWdaOrphanProcessGroups(`421 421 ${command}`, input),+ ).toEqual([421]);++ const wrong = "c".repeat(64);+ const rejected = [+ `${tagged} EXTRA=1`,+ `${command} CINDY_WDA_OWNER_FINGERPRINT=${ownerFingerprint}suffix UPGRADE_TIMESTAMP=${ownerFingerprint}`,+ `${command} CINDY_WDA_OWNER_FINGERPRINT=${wrong} UPGRADE_TIMESTAMP=${wrong}`,+ command.replace("test-without-building", "not-test-without-building"),+ command.replace(`/source/${"a".repeat(40)}/`, "/source/../source/"),+ command.replace(xcodebuild, "/tmp/xcodebuild"),+ command.replace(UDID, "2A9D41E0-E031-4AD0-A8B5-847480802E8E"),+ ];+ for (const [index, candidate] of rejected.entries()) {+ expect(+ findCindyWdaOrphanProcessGroups(+ `${500 + index} ${500 + index} ${candidate}`,+ input,+ ),+ ).toEqual([]);+ }+ expect(findCindyWdaOrphanProcessGroups(`600 601 ${tagged}`, input)).toEqual(+ [],+ );+ });++ it("blocks an unowned same-device WDA controller without granting kill authority", () => {+ const external =+ `${xcodebuild} -quiet -project /tmp/ExternalAgent/WebDriverAgent.xcodeproj` ++ ` -destination platform=iOS Simulator,id=${UDID},arch=arm64` ++ ` -scheme WebDriverAgentRunner test-without-building`;+ expect(hasConflictingWdaController(`650 650 ${external}`, input)).toBe(+ true,+ );+ expect(+ findCindyWdaOrphanProcessGroups(`650 650 ${external}`, input),+ ).toEqual([]);+ expect(+ hasConflictingWdaController(+ `651 651 ${external.replace(UDID, "2A9D41E0-E031-4AD0-A8B5-847480802E8E")}`,+ input,+ ),+ ).toBe(false);+ expect(+ hasConflictingWdaController(+ `652 652 ${external.replace("WebDriverAgentRunner", "UserApp")}`,+ input,+ ),+ ).toBe(false);++ const otherXcode =+ "/Applications/Xcode Beta.app/Contents/Developer/usr/bin/xcodebuild";+ const otherXcodeCommand = external.replace(xcodebuild, otherXcode);+ expect(+ hasConflictingWdaController(`653 653 ${otherXcodeCommand}`, {+ ...input,+ inspectedXcodebuildExecutablePaths: [xcodebuild, otherXcode],+ }),+ ).toBe(true);+ expect(+ findCindyWdaOrphanProcessGroups(`653 653 ${otherXcodeCommand}`, {+ ...input,+ inspectedXcodebuildExecutablePaths: [xcodebuild, otherXcode],+ }),+ ).toEqual([]);+ });++ it("reads an owner marker only after selecting an exact same-device Runner", () => {+ const executable =+ `${coreSimulatorRoot}/Devices/${UDID}/data/Containers/Bundle/Application/` ++ `F152910A-1B1D-4F11-A669-68C785E9F638/` ++ `WebDriverAgentRunner-Runner.app/WebDriverAgentRunner-Runner`;+ const candidates = findCindyWdaRunnerCandidates(+ `700 700 ${executable}`,+ input,+ );+ expect(candidates).toEqual([+ { pid: 700, processGroupId: 700, executablePath: executable },+ ]);+ expect(+ matchesCindyWdaRunnerEnvironment(+ `700 700 ${executable} USE_PORT=18100 UPGRADE_TIMESTAMP=${ownerFingerprint}`,+ candidates[0]!,+ ownerFingerprint,+ ),+ ).toBe(true);+ expect(+ matchesCindyWdaRunnerEnvironment(+ `700 700 ${executable} UPGRADE_TIMESTAMP=${ownerFingerprint} UPGRADE_TIMESTAMP=${ownerFingerprint}`,+ candidates[0]!,+ ownerFingerprint,+ ),+ ).toBe(false);+ expect(+ matchesCindyWdaRunnerEnvironment(+ `700 700 ${executable} UPGRADE_TIMESTAMP=${"c".repeat(64)}`,+ candidates[0]!,+ ownerFingerprint,+ ),+ ).toBe(false);+ expect(+ findCindyWdaRunnerCandidates(+ `701 701 ${executable.replace(UDID, "2A9D41E0-E031-4AD0-A8B5-847480802E8E")}`,+ input,+ ),+ ).toEqual([]);++ const legacyEnvironment =+ `700 700 ${executable}` ++ ` SIMULATOR_UDID=${UDID}` ++ ` XCODE_SCHEME_NAME=WebDriverAgentRunner` ++ ` UPGRADE_TIMESTAMP=` ++ ` DYLD_LIBRARY_PATH=${cacheRoot}/derived/${"b".repeat(64)}` ++ `/Build/Products/Debug-iphonesimulator`;+ expect(+ matchesLegacyCindyWdaRunnerEnvironment(+ legacyEnvironment,+ candidates[0]!,+ input,+ ),+ ).toBe(true);+ expect(+ matchesLegacyCindyWdaRunnerEnvironment(+ legacyEnvironment.replace(+ "UPGRADE_TIMESTAMP= ",+ `UPGRADE_TIMESTAMP=${"c".repeat(64)} `,+ ),+ candidates[0]!,+ input,+ ),+ ).toBe(false);+ expect(+ matchesLegacyCindyWdaRunnerEnvironment(+ legacyEnvironment.replace(cacheRoot, `${cacheRoot}-other`),+ candidates[0]!,+ input,+ ),+ ).toBe(false);+ });++ it("reads only exact simctl candidates and revalidates diagnostic ownership", () => {+ const simctl = path.join(path.dirname(xcodebuild), "simctl");+ const diagnosticInput = {+ cacheRoot,+ simulatorUdid: UDID,+ xcodebuildExecutablePaths: [xcodebuild],+ };+ const candidates = findCindyWdaDiagnosticCandidates(+ [+ `810 810 ${simctl}`,+ "811 811 /usr/bin/xcrun",+ "812 812 /tmp/xcrun",+ ].join("\n"),+ diagnosticInput,+ );+ expect(candidates).toEqual([+ { pid: 810, processGroupId: 810, executablePath: simctl },+ { pid: 811, processGroupId: 811, executablePath: "/usr/bin/xcrun" },+ ]);++ const output = `${derived}/Logs/Test/Diagnostics`;+ const direct =+ `810 810 ${simctl} diagnose -b --timeout=60` ++ ` --output=${output} --udid=${UDID}`;+ expect(+ matchesCindyWdaDiagnosticCommand(direct, candidates[0]!, diagnosticInput),+ ).toBe(true);+ expect(+ matchesCindyWdaDiagnosticCommand(+ `811 811 /usr/bin/xcrun simctl diagnose --udid=${UDID} --output ${output}`,+ candidates[1]!,+ diagnosticInput,+ ),+ ).toBe(true);++ const rejected = [+ direct.replace("810 810", "900 900"),+ direct.replace(" diagnose ", " list "),+ direct.replace(UDID, "2A9D41E0-E031-4AD0-A8B5-847480802E8E"),+ direct.replace(output, `${cacheRoot}-other/derived/${"b".repeat(64)}`),+ `${direct} --udid=${UDID}`,+ direct.replace(output, `${derived}-reused`),+ ];+ for (const commandLine of rejected) {+ expect(+ matchesCindyWdaDiagnosticCommand(+ commandLine,+ candidates[0]!,+ diagnosticInput,+ ),+ ).toBe(false);+ }+ });+});+describe("WdaProcessManager", () => {+ it("runs orphan recovery before source preparation and launch", async () => {+ const harness = await createHarness();+ await harness.manager.start({+ instanceId: "instance-a",+ simulatorUdid: UDID,+ runtimeIdentifier: "runtime",+ xcodeBuild: "build",+ architecture: "arm64",+ });++ expect(harness.orphanProcessCleaner).toHaveBeenCalledTimes(2);+ expect(harness.orphanProcessCleaner).toHaveBeenCalledWith(+ expect.objectContaining({+ cacheRoot: path.join(harness.root, "cache"),+ instanceId: "instance-a",+ simulatorUdid: UDID,+ ownerFingerprint: createWdaOwnerFingerprint(+ path.join(harness.root, "cache"),+ "instance-a",+ UDID,+ ),+ signal: expect.any(AbortSignal),+ rejectForeign: true,+ }),+ );+ expect(+ harness.orphanProcessCleaner.mock.invocationCallOrder[0],+ ).toBeLessThan(harness.run.mock.invocationCallOrder[0]!);+ expect(harness.run.mock.invocationCallOrder[0]).toBeLessThan(+ harness.orphanProcessCleaner.mock.invocationCallOrder[1]!,+ );+ expect(+ harness.orphanProcessCleaner.mock.invocationCallOrder[1],+ ).toBeLessThan(harness.launch.mock.invocationCallOrder[0]!);+ });++ it("fails closed before build when orphan recovery is unavailable", async () => {+ const orphanProcessCleaner = vi.fn(async () => {+ throw new WdaError("TERMINATION_FAILED", "inventory unavailable");+ });+ const harness = await createHarness(undefined, { orphanProcessCleaner });++ await expect(+ harness.manager.start({+ instanceId: "instance-a",+ simulatorUdid: UDID,+ runtimeIdentifier: "runtime",+ xcodeBuild: "build",+ architecture: "arm64",+ }),+ ).rejects.toMatchObject({ code: "TERMINATION_FAILED" });+ expect(harness.run).not.toHaveBeenCalled();+ expect(harness.launch).not.toHaveBeenCalled();+ });++ it("cancels a pending orphan inventory without hanging stop", async () => {+ let calls = 0;+ const orphanProcessCleaner = vi.fn<WdaOrphanProcessCleaner>(+ async (input) => {+ calls += 1;+ if (calls > 1) return;+ await new Promise<void>((_resolve, reject) => {+ const onAbort = () =>+ reject(new WdaError("START_CANCELLED", "cancelled"));+ input.signal?.addEventListener("abort", onAbort, { once: true });+ if (input.signal?.aborted) onAbort();+ });+ },+ );+ const harness = await createHarness(undefined, { orphanProcessCleaner });+ const start = harness.manager.start({+ instanceId: "instance-a",+ simulatorUdid: UDID,+ runtimeIdentifier: "runtime",+ xcodeBuild: "build",+ architecture: "arm64",+ });+ await vi.waitFor(() =>+ expect(orphanProcessCleaner).toHaveBeenCalledTimes(1),+ );++ const stop = harness.manager.stop("instance-a");+ await expect(start).rejects.toMatchObject({ code: "START_CANCELLED" });+ await expect(stop).resolves.toBeUndefined();+ expect(orphanProcessCleaner).toHaveBeenCalledTimes(2);+ expect(harness.run).not.toHaveBeenCalled();+ expect(harness.launch).not.toHaveBeenCalled();+ });+it("builds once, starts on private ports, probes, and reuses a running instance", async () => {const harness = await createHarness();const input = {diff --git a/packages/ios-simulator-runtime/src/wda/process-manager.ts b/packages/ios-simulator-runtime/src/wda/process-manager.tsindex 80991c57bb..0e059560a0 100644--- a/packages/ios-simulator-runtime/src/wda/process-manager.ts+++ b/packages/ios-simulator-runtime/src/wda/process-manager.ts@@ -1,6 +1,8 @@import { spawn } from "node:child_process";+import { createHash } from "node:crypto";import { mkdir } from "node:fs/promises";import net from "node:net";+import os from "node:os";import path from "node:path";import { createNodeIOSSimulatorCommandRunner } from "../command-runner.js";@@ -31,6 +33,11 @@ const WDA_INTERRUPT_GRACE_MS = 5_000;const WDA_TERMINATE_GRACE_MS = 1_000;const WDA_KILL_GRACE_MS = 500;const WDA_EXIT_POLL_MS = 25;+const MAX_HOST_PROCESS_SNAPSHOT_BYTES = 4 * 1024 * 1024;+const MAX_CANDIDATE_PROCESS_BYTES = 64 * 1024;+const HOST_PROCESS_COMMAND_TIMEOUT_MS = 2_000;+const MAX_WDA_PROCESS_CANDIDATES = 128;+const WDA_DIAGNOSTIC_CLEANUP_BUDGET_MS = 1_000;export interface WdaManagedProcess {readonly pid: number;@@ -65,10 +72,29 @@ export interface WdaProcessManagerOptions {clock?: WdaProcessManagerClock;sourceManifest?: WdaSourceManifest;startTimeoutMs?: number;+ orphanProcessCleaner?: WdaOrphanProcessCleaner;/** Host-owned boundary; WDA never receives artifact paths or process launchers. */nativeCapabilityProvider?: IOSSimulatorCapabilityProvider;}+export interface WdaOrphanProcessCleanupInput {+ cacheRoot: string;+ instanceId: string;+ simulatorUdid: string;+ ownerFingerprint: string;+ signal?: AbortSignal;+ coreSimulatorRoot?: string;+ xcodebuildExecutablePaths?: readonly string[];+ /** Candidate argv paths inspected for conflict only; never grants kill authority. */+ inspectedXcodebuildExecutablePaths?: readonly string[];+ /** Start/reconcile rejects foreign same-device WDA; normal stop only removes Cindy-owned work. */+ rejectForeign?: boolean;+}++export type WdaOrphanProcessCleaner = (+ input: WdaOrphanProcessCleanupInput,+) => Promise<void>;+export interface WdaStartOptions {instanceId: string;simulatorUdid: string;@@ -143,52 +169,936 @@ function defaultClock(): WdaProcessManagerClock {};}-/**- * XCTest may detach its `simctl diagnose` helper when Simulator.app exits.- * Limit cleanup to helpers carrying both this manager's cache root and UDID so- * user-owned diagnostics for other simulators are never touched.- */-async function cleanupDetachedDiagnostics(+interface DarwinProcessSnapshotRow {+ pid: number;+ processGroupId: number;+ command: string;+}++export interface WdaRunnerProcessCandidate {+ pid: number;+ processGroupId: number;+ executablePath: string;+}++export interface WdaDiagnosticProcessCandidate {+ pid: number;+ processGroupId: number;+ executablePath: string;+}++export interface WdaDetachedDiagnosticCleanupInput {+ cacheRoot: string;+ simulatorUdid: string;+ signal?: AbortSignal;+ xcodebuildExecutablePaths?: readonly string[];+}++function normalizeSimulatorUdid(value: string): string | null {+ const normalized = value.trim().toUpperCase();+ return /^[0-9A-F]{8}(?:-[0-9A-F]{4}){3}-[0-9A-F]{12}$/.test(normalized)+ ? normalized+ : null;+}++/** Stable, non-secret owner marker embedded in the exact xcodebuild argv. */+export function createWdaOwnerFingerprint(cacheRoot: string,+ instanceId: string,simulatorUdid: string,-): Promise<void> {- if (process.platform !== "darwin") return;- await new Promise<void>((resolve) => {- const child = spawn("/bin/ps", ["-axo", "pid=,command="], {+): string {+ const normalizedUdid = normalizeSimulatorUdid(simulatorUdid);+ const normalizedInstanceId = instanceId.trim();+ if (!normalizedUdid || !normalizedInstanceId) {+ throw new WdaError(+ "INVALID_CONFIGURATION",+ "WDA orphan ownership requires an exact instance id and simulator UUID",+ );+ }+ return createHash("sha256")+ .update(path.resolve(cacheRoot))+ .update("\0")+ .update(normalizedInstanceId)+ .update("\0")+ .update(normalizedUdid)+ .digest("hex");+}++function parseDarwinProcessSnapshot(+ snapshot: string,+): DarwinProcessSnapshotRow[] {+ const rows: DarwinProcessSnapshotRow[] = [];+ for (const line of snapshot.split("\n")) {+ const match = line.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);+ if (!match) continue;+ const pid = Number(match[1]);+ const processGroupId = Number(match[2]);+ if (!Number.isInteger(pid) || !Number.isInteger(processGroupId)) continue;+ rows.push({ pid, processGroupId, command: match[3] });+ }+ return rows;+}++function escapeRegularExpression(value: string): string {+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}++function currentProcessGroup(+ rows: readonly DarwinProcessSnapshotRow[],+): number | null {+ return rows.find((row) => row.pid === process.pid)?.processGroupId ?? null;+}++function classifyCindyWdaControllers(+ snapshot: string,+ input: WdaOrphanProcessCleanupInput,+): { ownedGroups: number[]; conflictingGroups: number[] } {+ const normalizedUdid = normalizeSimulatorUdid(input.simulatorUdid);+ if (!normalizedUdid || !/^[0-9a-f]{64}$/.test(input.ownerFingerprint)) {+ return { ownedGroups: [], conflictingGroups: [] };+ }+ const executablePaths = [+ ...(input.xcodebuildExecutablePaths ?? ["/usr/bin/xcodebuild"]),+ ]+ .map((value) => path.resolve(value))+ .filter((value, index, values) => values.indexOf(value) === index);+ if (executablePaths.length === 0) {+ return { ownedGroups: [], conflictingGroups: [] };+ }+ const conflictExecutablePaths = [+ ...(input.inspectedXcodebuildExecutablePaths ?? executablePaths),+ ]+ .map((value) => path.resolve(value))+ .filter((value, index, values) => values.indexOf(value) === index);+ const root = path.resolve(input.cacheRoot);+ const executablePattern = executablePaths+ .map(escapeRegularExpression)+ .join("|");+ const projectPattern = `${escapeRegularExpression(path.join(root, "source"))}\\/[0-9a-f]{40}\\/WebDriverAgent\\.xcodeproj`;+ const derivedPattern = `${escapeRegularExpression(path.join(root, "derived"))}\\/[0-9a-f]{64}`;+ const basePattern =+ `(?:${executablePattern}) -quiet -project ${projectPattern}` ++ ` -scheme WebDriverAgentRunner` ++ ` -destination platform=iOS Simulator,id=${normalizedUdid},arch=(?:arm64|x86_64)` ++ ` -derivedDataPath ${derivedPattern}` ++ ` (?:build-for-testing|test-without-building)` ++ ` CODE_SIGNING_ALLOWED=NO COMPILER_INDEX_STORE_ENABLE=NO`;+ const legacyPattern = new RegExp(`^${basePattern}$`);+ const ownedPattern = new RegExp(+ `^${basePattern}` ++ ` CINDY_WDA_OWNER_FINGERPRINT=${input.ownerFingerprint}` ++ ` UPGRADE_TIMESTAMP=${input.ownerFingerprint}$`,+ );+ const schemePattern = /(?:^|\s)-scheme WebDriverAgentRunner(?=\s|$)/;+ const destinationPattern = new RegExp(+ `(?:^|\\s)-destination (?:platform=iOS Simulator,)?` ++ `[^\\s]*id=${normalizedUdid}(?=,|\\s|$)`,+ );+ const rows = parseDarwinProcessSnapshot(snapshot);+ const ownProcessGroup = currentProcessGroup(rows);+ const ownedGroups = new Set<number>();+ const conflictingGroups = new Set<number>();+ for (const row of rows) {+ const command = row.command.trim();+ const owned = ownedPattern.test(command) || legacyPattern.test(command);+ // A different profile/tool may use another project and DerivedData root.+ // It is never kill-authorized, but a same-device WDA controller must block+ // replacement startup until its Runner can be observed or it exits.+ const related =+ owned ||+ (conflictExecutablePaths.some((executable) =>+ command.startsWith(`${executable} `),+ ) &&+ schemePattern.test(command) &&+ destinationPattern.test(command));+ if (!related) continue;+ if (+ row.pid !== row.processGroupId ||+ row.processGroupId <= 1 ||+ row.processGroupId === ownProcessGroup+ ) {+ conflictingGroups.add(row.processGroupId);+ continue;+ }+ if (owned) {+ ownedGroups.add(row.processGroupId);+ } else {+ conflictingGroups.add(row.processGroupId);+ }+ }+ return {+ ownedGroups: [...ownedGroups],+ conflictingGroups: [...conflictingGroups],+ };+}++/**+ * Select only Cindy-owned WDA xcodebuild group leaders for one persisted+ * instance. A fingerprint mismatch is never treated as a legacy process.+ */+export function findCindyWdaOrphanProcessGroups(+ snapshot: string,+ input: WdaOrphanProcessCleanupInput,+): number[] {+ return classifyCindyWdaControllers(snapshot, input).ownedGroups;+}++/** Same-device WDA controllers whose exact Cindy ownership is not proven. */+export function hasConflictingWdaController(+ snapshot: string,+ input: WdaOrphanProcessCleanupInput,+): boolean {+ return (+ classifyCindyWdaControllers(snapshot, input).conflictingGroups.length > 0+ );+}++/** Select exact Simulator runner executables before reading candidate-only env. */+export function findCindyWdaRunnerCandidates(+ snapshot: string,+ input: WdaOrphanProcessCleanupInput,+): WdaRunnerProcessCandidate[] {+ const normalizedUdid = normalizeSimulatorUdid(input.simulatorUdid);+ if (!normalizedUdid) return [];+ const coreSimulatorRoot = path.resolve(+ input.coreSimulatorRoot ??+ path.join(os.homedir(), "Library", "Developer", "CoreSimulator"),+ );+ const runnerPattern = new RegExp(+ `^${escapeRegularExpression(+ path.join(+ coreSimulatorRoot,+ "Devices",+ normalizedUdid,+ "data",+ "Containers",+ "Bundle",+ "Application",+ ),+ )}\\/[0-9A-Fa-f]{8}(?:-[0-9A-Fa-f]{4}){3}-[0-9A-Fa-f]{12}` ++ `\\/WebDriverAgentRunner-Runner\\.app\\/WebDriverAgentRunner-Runner$`,+ );+ return parseDarwinProcessSnapshot(snapshot)+ .filter((row) => runnerPattern.test(row.command.trim()))+ .map((row) => ({+ pid: row.pid,+ processGroupId: row.processGroupId,+ executablePath: row.command.trim(),+ }));+}++function diagnosticExecutablePaths(+ xcodebuildExecutablePaths: readonly string[],+): Set<string> {+ const paths = new Set<string>(["/usr/bin/xcrun"]);+ for (const executable of xcodebuildExecutablePaths) {+ const resolved = path.resolve(executable);+ if (path.basename(resolved) !== "xcodebuild") continue;+ const simctl = path.join(path.dirname(resolved), "simctl");+ if (simctl !== "/usr/bin/simctl") paths.add(simctl);+ }+ return paths;+}++/** Select only exact xcrun/simctl executables before reading candidate argv. */+export function findCindyWdaDiagnosticCandidates(+ snapshot: string,+ input: WdaDetachedDiagnosticCleanupInput,+): WdaDiagnosticProcessCandidate[] {+ const executablePaths = diagnosticExecutablePaths(+ input.xcodebuildExecutablePaths ?? [],+ );+ return parseDarwinProcessSnapshot(snapshot)+ .filter((row) => executablePaths.has(path.resolve(row.command.trim())))+ .map((row) => ({+ pid: row.pid,+ processGroupId: row.processGroupId,+ executablePath: row.command.trim(),+ }));+}++/**+ * Prove that one exact candidate is a same-device diagnostic writing only+ * beneath this profile's WDA DerivedData root.+ */+export function matchesCindyWdaDiagnosticCommand(+ snapshot: string,+ candidate: WdaDiagnosticProcessCandidate,+ input: WdaDetachedDiagnosticCleanupInput,+): boolean {+ const normalizedUdid = normalizeSimulatorUdid(input.simulatorUdid);+ if (!normalizedUdid) return false;+ const rows = parseDarwinProcessSnapshot(snapshot);+ if (rows.length !== 1) return false;+ const row = rows[0];+ const commandPrefix = `${candidate.executablePath} `;+ if (+ row.pid !== candidate.pid ||+ row.processGroupId !== candidate.processGroupId ||+ !row.command.startsWith(commandPrefix)+ ) {+ return false;+ }++ const argv = row.command.slice(commandPrefix.length);+ const subcommand =+ candidate.executablePath === "/usr/bin/xcrun"+ ? "simctl diagnose"+ : "diagnose";+ if (argv !== subcommand && !argv.startsWith(`${subcommand} `)) return false;++ const udidPattern = new RegExp(+ `(?:^|\\s)--udid=${escapeRegularExpression(normalizedUdid)}(?=\\s|$)`,+ "gi",+ );+ if ([...argv.matchAll(udidPattern)].length !== 1) return false;++ const derivedRoot = path.join(path.resolve(input.cacheRoot), "derived");+ const outputPattern = new RegExp(+ `(?:^|\\s)--output(?:=|\\s+)${escapeRegularExpression(derivedRoot)}` ++ `\\/[0-9a-f]{64}(?=\\/|\\s|$)`,+ "g",+ );+ return [...argv.matchAll(outputPattern)].length === 1;+}++/** Verify the candidate PID still owns the exact Runner and owner env marker. */+export function matchesCindyWdaRunnerEnvironment(+ snapshot: string,+ candidate: WdaRunnerProcessCandidate,+ ownerFingerprint: string,+): boolean {+ const rows = parseDarwinProcessSnapshot(snapshot);+ if (rows.length !== 1) return false;+ const row = rows[0];+ if (+ row.pid !== candidate.pid ||+ row.processGroupId !== candidate.processGroupId ||+ !row.command.startsWith(`${candidate.executablePath} `)+ ) {+ return false;+ }+ const matches = environmentValues(row.command, "UPGRADE_TIMESTAMP");+ return matches.length === 1 && matches[0] === ownerFingerprint;+}++function environmentValues(command: string, key: string): string[] {+ const pattern = new RegExp(+ `(?:^|\\s)${escapeRegularExpression(key)}=([^\\s]*)(?=\\s|$)`,+ "g",+ );+ return [...command.matchAll(pattern)].map((match) => match[1] ?? "");+}++/** Narrow migration path for Cindy WDA runners launched before owner markers. */+export function matchesLegacyCindyWdaRunnerEnvironment(+ snapshot: string,+ candidate: WdaRunnerProcessCandidate,+ input: WdaOrphanProcessCleanupInput,+): boolean {+ const rows = parseDarwinProcessSnapshot(snapshot);+ if (rows.length !== 1) return false;+ const row = rows[0];+ const ownerMarkers = environmentValues(row.command, "UPGRADE_TIMESTAMP");+ const simulatorUdids = environmentValues(row.command, "SIMULATOR_UDID");+ const schemeNames = environmentValues(row.command, "XCODE_SCHEME_NAME");+ if (+ row.pid !== candidate.pid ||+ row.processGroupId !== candidate.processGroupId ||+ !row.command.startsWith(`${candidate.executablePath} `) ||+ ownerMarkers.length !== 1 ||+ ownerMarkers[0] !== "" ||+ simulatorUdids.length !== 1 ||+ simulatorUdids[0]?.toUpperCase() !==+ input.simulatorUdid.trim().toUpperCase() ||+ schemeNames.length !== 1 ||+ schemeNames[0] !== "WebDriverAgentRunner"+ ) {+ return false;+ }+ const derivedRoot = escapeRegularExpression(+ path.join(path.resolve(input.cacheRoot), "derived"),+ );+ const legacyDerivedPath = new RegExp(+ `(?:^|\\s)DYLD_LIBRARY_PATH=${derivedRoot}\\/[0-9a-f]{64}` ++ `\\/Build\\/Products\\/Debug-iphonesimulator[^\\s]*(?=\\s|$)`,+ "g",+ );+ return [...row.command.matchAll(legacyDerivedPath)].length === 1;+}++function startCancelledError(): WdaError {+ return new WdaError(+ "START_CANCELLED",+ "WebDriverAgent startup was cancelled",+ );+}++function throwIfCleanupAborted(signal?: AbortSignal): void {+ if (signal?.aborted) throw startCancelledError();+}++function readBoundedHostCommand(+ args: readonly string[],+ maxBytes: number,+ signal?: AbortSignal,+): Promise<{ output: string; exitCode: number | null }> {+ return new Promise((resolve, reject) => {+ throwIfCleanupAborted(signal);+ const child = spawn("/bin/ps", [...args], {+ env: { LANG: "C", PATH: "/usr/bin:/bin:/usr/sbin:/sbin" },shell: false,stdio: ["ignore", "pipe", "ignore"],});let output = "";+ let outputBytes = 0;+ let settled = false;+ const finish = (callback: () => void) => {+ if (settled) return;+ settled = true;+ clearTimeout(timeout);+ signal?.removeEventListener("abort", onAbort);+ callback();+ };+ const onAbort = () => {+ child.kill("SIGKILL");+ finish(() => reject(startCancelledError()));+ };+ const timeout = setTimeout(() => {+ child.kill("SIGKILL");+ finish(() =>+ reject(+ new WdaError(+ "TERMINATION_FAILED",+ "The host process inventory timed out during WDA recovery",+ ),+ ),+ );+ }, HOST_PROCESS_COMMAND_TIMEOUT_MS);+ signal?.addEventListener("abort", onAbort, { once: true });+ if (signal?.aborted) {+ onAbort();+ return;+ }child.stdout?.on("data", (chunk: Buffer) => {+ if (settled) return;+ outputBytes += chunk.byteLength;+ if (outputBytes > maxBytes) {+ child.kill("SIGKILL");+ finish(() =>+ reject(+ new WdaError(+ "TERMINATION_FAILED",+ "The host process inventory exceeded the WDA recovery limit",+ ),+ ),+ );+ return;+ }output += chunk.toString("utf8");});- const finish = () => {- const root = path.resolve(cacheRoot);- for (const line of output.split("\n")) {- const match = line.trim().match(/^(\d+)\s+(.*)$/);- if (!match) continue;- const pid = Number(match[1]);- const command = match[2];+ child.once("error", () =>+ finish(() =>+ reject(+ new WdaError(+ "TERMINATION_FAILED",+ "The host process inventory for WDA recovery is unavailable",+ ),+ ),+ ),+ );+ child.once("close", (code) =>+ finish(() => resolve({ output, exitCode: code })),+ );+ });+}++async function readDarwinProcessSnapshot(+ signal?: AbortSignal,+): Promise<string> {+ const result = await readBoundedHostCommand(+ ["-axo", "pid=,pgid=,comm="],+ MAX_HOST_PROCESS_SNAPSHOT_BYTES,+ signal,+ );+ if (result.exitCode !== 0) {+ throw new WdaError(+ "TERMINATION_FAILED",+ "The host process inventory for WDA recovery failed",+ );+ }+ return result.output;+}++async function readDarwinCandidateCommand(+ pid: number,+ includeEnvironment: boolean,+ signal?: AbortSignal,+): Promise<string | null> {+ const result = await readBoundedHostCommand(+ [+ ...(includeEnvironment ? ["eww"] : []),+ "-ww",+ "-p",+ String(pid),+ "-o",+ "pid=,pgid=,command=",+ ],+ MAX_CANDIDATE_PROCESS_BYTES,+ signal,+ );+ if (result.exitCode === 0) return result.output;+ if (result.exitCode === 1) return null;+ throw new WdaError(+ "TERMINATION_FAILED",+ "A candidate WebDriverAgent process could not be inspected",+ );+}++interface WdaProcessInventorySnapshot {+ processSnapshot: string;+ controllerSnapshot: string;+ inspectedXcodebuildExecutablePaths: string[];+}++function isAllowlistedXcodebuildCandidate(+ executablePath: string,+ selectedPaths: ReadonlySet<string>,+): boolean {+ const resolved = path.resolve(executablePath);+ if (selectedPaths.has(resolved) || resolved === "/usr/bin/xcodebuild") {+ return true;+ }+ return (+ /^\/Applications\/[^/]+\.app\/Contents\/Developer\/usr\/bin\/xcodebuild$/.test(+ resolved,+ ) || resolved === "/Library/Developer/CommandLineTools/usr/bin/xcodebuild"+ );+}++async function readWdaProcessInventory(+ input: WdaOrphanProcessCleanupInput,+): Promise<WdaProcessInventorySnapshot> {+ // The global pass reads executable paths only. Full argv/environment is+ // requested by PID only after an exact xcodebuild/Runner path match, so+ // unrelated process credentials never enter the Cindy process.+ const processSnapshot = await readDarwinProcessSnapshot(input.signal);+ const executablePaths = new Set(+ (input.xcodebuildExecutablePaths ?? []).map((value) => path.resolve(value)),+ );+ const rows = parseDarwinProcessSnapshot(processSnapshot);+ const controllerRows: string[] = [];+ const ownRow = rows.find((row) => row.pid === process.pid);+ if (ownRow) {+ controllerRows.push(+ `${ownRow.pid} ${ownRow.processGroupId} ${ownRow.command}`,+ );+ }+ const candidates = rows.filter((row) =>+ isAllowlistedXcodebuildCandidate(row.command.trim(), executablePaths),+ );+ if (candidates.length > MAX_WDA_PROCESS_CANDIDATES) {+ throw new WdaError(+ "TERMINATION_FAILED",+ "Too many xcodebuild processes were present for safe WDA recovery",+ );+ }+ const commands = await Promise.all(+ candidates.map((row) =>+ readDarwinCandidateCommand(row.pid, false, input.signal),+ ),+ );+ for (const command of commands) {+ if (command !== null) controllerRows.push(command.trim());+ }+ return {+ processSnapshot,+ controllerSnapshot: controllerRows.join("\n"),+ inspectedXcodebuildExecutablePaths: [+ ...new Set(candidates.map((row) => path.resolve(row.command.trim()))),+ ],+ };+}++async function readSelectedXcodebuildPaths(+ signal?: AbortSignal,+): Promise<string[]> {+ const configured = process.env.DEVELOPER_DIR?.trim();+ if (configured && path.isAbsolute(configured)) {+ return [+ "/usr/bin/xcodebuild",+ path.join(configured, "usr", "bin", "xcodebuild"),+ ];+ }+ const result = await new Promise<{ output: string; exitCode: number | null }>(+ (resolve, reject) => {+ throwIfCleanupAborted(signal);+ const child = spawn("/usr/bin/xcode-select", ["--print-path"], {+ env: { LANG: "C", PATH: "/usr/bin:/bin:/usr/sbin:/sbin" },+ shell: false,+ stdio: ["ignore", "pipe", "ignore"],+ });+ let output = "";+ let settled = false;+ const finish = (callback: () => void) => {+ if (settled) return;+ settled = true;+ clearTimeout(timeout);+ signal?.removeEventListener("abort", onAbort);+ callback();+ };+ const onAbort = () => {+ child.kill("SIGKILL");+ finish(() => reject(startCancelledError()));+ };+ const timeout = setTimeout(() => {+ child.kill("SIGKILL");+ finish(() =>+ reject(+ new WdaError(+ "TERMINATION_FAILED",+ "The selected Xcode path timed out during WDA recovery",+ ),+ ),+ );+ }, HOST_PROCESS_COMMAND_TIMEOUT_MS);+ signal?.addEventListener("abort", onAbort, { once: true });+ if (signal?.aborted) {+ onAbort();+ return;+ }+ child.stdout?.on("data", (chunk: Buffer) => {+ if (settled) return;+ if (+ Buffer.byteLength(output) + chunk.byteLength >+ MAX_CANDIDATE_PROCESS_BYTES+ ) {+ child.kill("SIGKILL");+ finish(() =>+ reject(+ new WdaError(+ "TERMINATION_FAILED",+ "The selected Xcode path exceeded the WDA recovery limit",+ ),+ ),+ );+ return;+ }+ output += chunk.toString("utf8");+ });+ child.once("error", () =>+ finish(() =>+ reject(+ new WdaError(+ "TERMINATION_FAILED",+ "The selected Xcode path is unavailable during WDA recovery",+ ),+ ),+ ),+ );+ child.once("close", (exitCode) =>+ finish(() => resolve({ output, exitCode })),+ );+ },+ );+ const developerDirectory = result.output.trim();+ if (result.exitCode !== 0 || !path.isAbsolute(developerDirectory)) {+ throw new WdaError(+ "TERMINATION_FAILED",+ "The selected Xcode path could not be verified during WDA recovery",+ );+ }+ return [+ "/usr/bin/xcodebuild",+ path.join(developerDirectory, "usr", "bin", "xcodebuild"),+ ];+}++function isDetachedProcessGroupAlive(processGroupId: number): boolean {+ try {+ process.kill(-processGroupId, 0);+ return true;+ } catch (error) {+ return (error as NodeJS.ErrnoException | null)?.code === "EPERM";+ }+}++async function waitForDetachedProcessGroupExit(+ processGroupId: number,+ signal?: AbortSignal,+): Promise<boolean> {+ const deadline = Date.now() + WDA_KILL_GRACE_MS;+ while (isDetachedProcessGroupAlive(processGroupId)) {+ throwIfCleanupAborted(signal);+ const remaining = deadline - Date.now();+ if (remaining <= 0) return false;+ await new Promise((resolve) =>+ setTimeout(resolve, Math.min(WDA_EXIT_POLL_MS, remaining)),+ );+ }+ return true;+}++async function classifyRunnerCandidates(+ snapshot: string,+ input: WdaOrphanProcessCleanupInput,+): Promise<{ ownedGroups: number[]; conflict: boolean }> {+ const candidates = findCindyWdaRunnerCandidates(snapshot, input);+ if (candidates.length > MAX_WDA_PROCESS_CANDIDATES) {+ throw new WdaError(+ "TERMINATION_FAILED",+ "Too many WebDriverAgent runners were present for safe recovery",+ );+ }+ const ownProcessGroup = currentProcessGroup(+ parseDarwinProcessSnapshot(snapshot),+ );+ const ownedGroups = new Set<number>();+ let conflict = false;+ const environments = await Promise.all(+ candidates.map((candidate) =>+ readDarwinCandidateCommand(candidate.pid, true, input.signal),+ ),+ );+ for (const [index, candidate] of candidates.entries()) {+ const environment = environments[index];+ if (environment == null) continue;+ const owned =+ matchesCindyWdaRunnerEnvironment(+ environment,+ candidate,+ input.ownerFingerprint,+ ) ||+ matchesLegacyCindyWdaRunnerEnvironment(environment, candidate, input);+ if (!owned) {+ conflict = true;+ continue;+ }+ if (+ candidate.pid !== candidate.processGroupId ||+ candidate.processGroupId <= 1 ||+ candidate.processGroupId === ownProcessGroup+ ) {+ conflict = true;+ continue;+ }+ ownedGroups.add(candidate.processGroupId);+ }+ return { ownedGroups: [...ownedGroups], conflict };+}++async function inspectWdaProcessOwnership(+ input: WdaOrphanProcessCleanupInput,+): Promise<{ ownedGroups: number[]; conflict: boolean }> {+ const snapshot = await readWdaProcessInventory(input);+ const controllers = classifyCindyWdaControllers(snapshot.controllerSnapshot, {+ ...input,+ inspectedXcodebuildExecutablePaths:+ snapshot.inspectedXcodebuildExecutablePaths,+ });+ const runners = await classifyRunnerCandidates(+ snapshot.processSnapshot,+ input,+ );+ return {+ ownedGroups: [+ ...new Set([...controllers.ownedGroups, ...runners.ownedGroups]),+ ],+ conflict: controllers.conflictingGroups.length > 0 || runners.conflict,+ };+}++async function revalidateWdaProcessGroupImmediately(+ processGroupId: number,+ input: WdaOrphanProcessCleanupInput,+): Promise<boolean> {+ const controller = await readDarwinCandidateCommand(+ processGroupId,+ false,+ input.signal,+ );+ if (+ controller !== null &&+ findCindyWdaOrphanProcessGroups(controller, input).includes(processGroupId)+ ) {+ return true;+ }++ const snapshot = await readDarwinProcessSnapshot(input.signal);+ const candidate = findCindyWdaRunnerCandidates(snapshot, input).find(+ (value) =>+ value.pid === processGroupId && value.processGroupId === processGroupId,+ );+ if (!candidate) return false;+ const environment = await readDarwinCandidateCommand(+ candidate.pid,+ true,+ input.signal,+ );+ return (+ environment !== null &&+ (matchesCindyWdaRunnerEnvironment(+ environment,+ candidate,+ input.ownerFingerprint,+ ) ||+ matchesLegacyCindyWdaRunnerEnvironment(environment, candidate, input))+ );+}++async function terminateRevalidatedWdaProcessGroups(+ initiallyOwnedGroups: readonly number[],+ input: WdaOrphanProcessCleanupInput,+): Promise<void> {+ if (initiallyOwnedGroups.length === 0) return;+ // Re-read each exact leader immediately before its own signal. One slow+ // unrelated candidate cannot create a PID/PGID reuse window for another.+ const groups = (+ await Promise.all(+ [...new Set(initiallyOwnedGroups)].map(async (processGroupId) => {if (- !Number.isInteger(pid) ||- pid === process.pid ||- !command.includes("simctl diagnose") ||- !command.includes(`--udid=${simulatorUdid}`) ||- !command.includes(`${root}/derived/`)+ !(await revalidateWdaProcessGroupImmediately(processGroupId, input))) {- continue;+ return null;}+ throwIfCleanupAborted(input.signal);try {- process.kill(pid, "SIGTERM");- } catch {- // It exited between ps and kill; cleanup is already complete.+ process.kill(-processGroupId, "SIGKILL");+ } catch (error) {+ if ((error as NodeJS.ErrnoException | null)?.code !== "ESRCH") {+ throw new WdaError(+ "TERMINATION_FAILED",+ "A recovered WebDriverAgent process group could not be terminated",+ );+ }}- }- resolve();- };- child.once("error", () => resolve());- child.once("close", finish);+ return processGroupId;+ }),+ )+ ).filter((value): value is number => value !== null);+ const exited = await Promise.all(+ groups.map((processGroupId) =>+ waitForDetachedProcessGroupExit(processGroupId, input.signal),+ ),+ );+ if (exited.some((value) => !value)) {+ throw new WdaError(+ "TERMINATION_FAILED",+ "A recovered WebDriverAgent process group is still running",+ );+ }+}++/** Recover detached WDA groups after an ungraceful Desktop termination. */+export const cleanupOrphanedWdaProcessGroups: WdaOrphanProcessCleaner = async (+ input,+) => {+ if (process.platform !== "darwin") return;+ throwIfCleanupAborted(input.signal);+ const xcodebuildExecutablePaths =+ input.xcodebuildExecutablePaths ??+ (await readSelectedXcodebuildPaths(input.signal));+ const normalizedInput = { ...input, xcodebuildExecutablePaths };+ const initial = await inspectWdaProcessOwnership(normalizedInput);+ await terminateRevalidatedWdaProcessGroups(+ initial.ownedGroups,+ normalizedInput,+ );++ const final = await inspectWdaProcessOwnership(normalizedInput);+ if (+ final.ownedGroups.length > 0 ||+ (input.rejectForeign !== false && final.conflict)+ ) {+ throw new WdaError(+ "TERMINATION_FAILED",+ "Another or unrecovered WebDriverAgent runtime still owns this simulator",+ );+ }+ await cleanupDetachedDiagnostics({+ cacheRoot: input.cacheRoot,+ simulatorUdid: input.simulatorUdid,+ signal: input.signal,+ xcodebuildExecutablePaths,});+};++/**+ * XCTest may detach its `simctl diagnose` helper when Simulator.app exits.+ * Limit cleanup to helpers carrying both this manager's cache root and UDID so+ * user-owned diagnostics for other simulators are never touched.+ */+async function cleanupDetachedDiagnostics(+ input: WdaDetachedDiagnosticCleanupInput,+): Promise<void> {+ if (process.platform !== "darwin") return;+ const budgetController = new AbortController();+ const onParentAbort = () => budgetController.abort();+ input.signal?.addEventListener("abort", onParentAbort, { once: true });+ if (input.signal?.aborted) onParentAbort();+ const budgetTimer = setTimeout(+ () => budgetController.abort(),+ WDA_DIAGNOSTIC_CLEANUP_BUDGET_MS,+ );+ budgetTimer.unref();+ const signal = budgetController.signal;+ try {+ throwIfCleanupAborted(signal);+ const xcodebuildExecutablePaths =+ input.xcodebuildExecutablePaths ??+ (await readSelectedXcodebuildPaths(signal));+ const normalizedInput = { ...input, xcodebuildExecutablePaths };+ const snapshot = await readDarwinProcessSnapshot(signal);+ const candidates = findCindyWdaDiagnosticCandidates(+ snapshot,+ normalizedInput,+ );+ if (candidates.length > MAX_WDA_PROCESS_CANDIDATES) return;++ const commands = await Promise.all(+ candidates.map((candidate) =>+ readDarwinCandidateCommand(candidate.pid, false, signal),+ ),+ );+ const owned = candidates.filter((candidate, index) => {+ const command = commands[index];+ return (+ command !== null &&+ matchesCindyWdaDiagnosticCommand(command, candidate, normalizedInput)+ );+ });++ await Promise.all(+ owned.map(async (candidate) => {+ throwIfCleanupAborted(signal);+ // Re-read immediately before signalling. A vanished or PID-reused+ // candidate receives no signal.+ const current = await readDarwinCandidateCommand(+ candidate.pid,+ false,+ signal,+ );+ if (+ current === null ||+ !matchesCindyWdaDiagnosticCommand(current, candidate, normalizedInput)+ ) {+ return;+ }+ try {+ process.kill(candidate.pid, "SIGTERM");+ } catch {+ // It exited between the exact revalidation and signal.+ }+ }),+ );+ } catch {+ // Diagnostics are best-effort after WDA ownership itself has converged,+ // but an explicit startup cancellation must still unwind immediately.+ if (input.signal?.aborted) throw startCancelledError();+ } finally {+ clearTimeout(budgetTimer);+ input.signal?.removeEventListener("abort", onParentAbort);+ }}/** Spawn long-running Xcode processes without a shell and with the plan's allowlisted env. */@@ -377,6 +1287,53 @@ export class WdaProcessManager {this.#options.nativeCapabilityProvider?.abortOperationsForExit?.();}+ async cleanupOrphaned(+ instanceId: string,+ simulatorUdid: string,+ ): Promise<void> {+ const stopping = this.#stopping.get(instanceId);+ if (stopping) await stopping;+ const starting = this.#starting.get(instanceId);+ if (starting) await starting.promise?.catch(() => undefined);+ const running = this.#running.get(instanceId);+ if (running) {+ if (+ running.simulatorUdid.toUpperCase() !==+ simulatorUdid.trim().toUpperCase()+ ) {+ throw new WdaError(+ "INVALID_CONFIGURATION",+ "The running WebDriverAgent instance is bound to another simulator",+ );+ }+ return;+ }+ await this.#cleanupOrphaned(instanceId, simulatorUdid);+ }++ #cleanupOrphaned(+ instanceId: string,+ simulatorUdid: string,+ signal?: AbortSignal,+ rejectForeign = true,+ ): Promise<void> {+ const ownerFingerprint = createWdaOwnerFingerprint(+ this.#options.cacheRoot,+ instanceId,+ simulatorUdid,+ );+ return (+ this.#options.orphanProcessCleaner ?? cleanupOrphanedWdaProcessGroups+ )({+ cacheRoot: this.#options.cacheRoot,+ instanceId,+ simulatorUdid,+ ownerFingerprint,+ signal,+ rejectForeign,+ });+ }+start(options: WdaStartOptions): Promise<WdaRunningInstance> {const stopping = this.#stopping.get(options.instanceId);if (stopping) return stopping.then(() => this.start(options));@@ -454,6 +1411,16 @@ export class WdaProcessManager {operation: PendingWdaOperation,): Promise<WdaRunningInstance> {const signal = operation.controller.signal;+ const ownerFingerprint = createWdaOwnerFingerprint(+ this.#options.cacheRoot,+ options.instanceId,+ options.simulatorUdid,+ );+ await this.#awaitStartOperation(+ this.#cleanupOrphaned(options.instanceId, options.simulatorUdid, signal),+ signal,+ );+ this.#throwIfStartCancelled(signal);const prepared = await this.#awaitStartOperation(prepareWdaSource({archivePath: this.#options.archivePath,@@ -490,6 +1457,7 @@ export class WdaProcessManager {checkoutPath: prepared.checkoutPath,derivedDataPath,simulatorUdid: options.simulatorUdid,+ ownerFingerprint,architecture: options.architecture,controlPort,mjpegPort,@@ -509,6 +1477,13 @@ export class WdaProcessManager {);}+ // The build may run for minutes. Recheck immediately before launching the+ // Runner so a foreign same-device WDA that appeared meanwhile blocks this+ // replacement instead of creating two competing sessions.+ await this.#awaitStartOperation(+ this.#cleanupOrphaned(options.instanceId, options.simulatorUdid, signal),+ signal,+ );this.#throwIfStartCancelled(signal);const process = this.#launcher.launch(plan.launch);operation.process = process;@@ -653,6 +1628,12 @@ export class WdaProcessManager {?.stop(options.instanceId).catch(() => undefined);await this.#terminatePendingProcess(options.instanceId, operation);+ await this.#cleanupOrphaned(+ options.instanceId,+ options.simulatorUdid,+ undefined,+ false,+ );if (error instanceof WdaError) throw error;throw new WdaError("LAUNCH_FAILED",@@ -785,10 +1766,10 @@ export class WdaProcessManager {) {return;}- retiring.finalizing ??= cleanupDetachedDiagnostics(- this.#options.cacheRoot,- retiring.simulatorUdid,- );+ retiring.finalizing ??= cleanupDetachedDiagnostics({+ cacheRoot: this.#options.cacheRoot,+ simulatorUdid: retiring.simulatorUdid,+ });await retiring.finalizing;if (this.#retiring.get(instanceId) === retiring &&@@ -832,7 +1813,10 @@ export class WdaProcessManager {if (retiring?.process === process) {await this.#finalizeRetiringProcess(instanceId, retiring);} else {- await cleanupDetachedDiagnostics(this.#options.cacheRoot, simulatorUdid);+ await cleanupDetachedDiagnostics({+ cacheRoot: this.#options.cacheRoot,+ simulatorUdid,+ });}this.#liveProcesses.delete(process);}@@ -871,6 +1855,7 @@ export class WdaProcessManager {async #stop(instanceId: string): Promise<void> {const pending = this.#starting.get(instanceId);+ let cleanupUdid = pending?.simulatorUdid;if (pending && !pending.committed) {pending.controller.abort();const nativeStop = this.#options.nativeCapabilityProvider@@ -883,6 +1868,7 @@ export class WdaProcessManager {}const retiring = this.#retiring.get(instanceId);if (retiring) {+ cleanupUdid = retiring.simulatorUdid;await this.#terminateProcessGroup(instanceId,retiring.simulatorUdid,@@ -890,7 +1876,13 @@ export class WdaProcessManager {);}const running = this.#running.get(instanceId);- if (!running) return;+ if (!running) {+ if (cleanupUdid) {+ await this.#cleanupOrphaned(instanceId, cleanupUdid, undefined, false);+ }+ return;+ }+ cleanupUdid = running.simulatorUdid;this.#running.delete(instanceId);running.unsubscribeOutput();await this.#options.nativeCapabilityProvider@@ -906,5 +1898,6 @@ export class WdaProcessManager {running.simulatorUdid,running.process,);+ await this.#cleanupOrphaned(instanceId, cleanupUdid, undefined, false);}}