Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): close simulator cleanup races

JiangJiahaobd8a207a035d
diff --git a/apps/desktop/src/main/__tests__/updateServiceIOSSimulatorExit.test.ts b/apps/desktop/src/main/__tests__/updateServiceIOSSimulatorExit.test.ts
index af74684e51..60ce30572f 100644
--- a/apps/desktop/src/main/__tests__/updateServiceIOSSimulatorExit.test.ts
+++ b/apps/desktop/src/main/__tests__/updateServiceIOSSimulatorExit.test.ts
@@ -3,6 +3,7 @@ import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
const source = readFileSync(new URL('../updateService.ts', import.meta.url), 'utf8');
+const bootstrapSource = readFileSync(new URL('../bootstrap-electron.ts', import.meta.url), 'utf8');
describe('update force-quit iOS Simulator cleanup', () => {
it('aborts detached simulator operations before exiting the process', () => {
@@ -20,4 +21,21 @@ describe('update force-quit iOS Simulator cleanup', () => {
expect(abortIndex).toBeGreaterThanOrEqual(0);
expect(exitIndex).toBeGreaterThan(abortIndex);
});
+
+ it('aborts detached simulator operations before the bounded async quit phase', () => {
+ expect(bootstrapSource).toContain(
+ "import { abortIOSSimulatorOperationsForExit } from './mcp-integrations/ios-simulator-exit';",
+ );
+ const abortIndex = bootstrapSource.indexOf(
+ "onQuit('ios-simulator-exit-abort', abortIOSSimulatorOperationsForExit, 'sync');",
+ );
+ const hostDisposeIndex = bootstrapSource.indexOf(
+ "onQuit('ios-simulator-host', disposeIOSSimulatorHost, 'async');",
+ );
+ const quitHandlerIndex = bootstrapSource.indexOf('installQuitHandler(6000);');
+
+ expect(abortIndex).toBeGreaterThanOrEqual(0);
+ expect(hostDisposeIndex).toBeGreaterThan(abortIndex);
+ expect(quitHandlerIndex).toBeGreaterThan(hostDisposeIndex);
+ });
});
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index a5996b60b4..67b202caaa 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -311,6 +311,7 @@ import {
disposeIOSSimulatorHost,
flushIOSSimulatorOwnershipRegistry,
} from './mcp-integrations/ios-simulator';
+import { abortIOSSimulatorOperationsForExit } from './mcp-integrations/ios-simulator-exit';
import {
clearIOSSimulatorRendererAccess,
configureIOSSimulatorRendererAccessConfirmation,
@@ -6900,6 +6901,10 @@ onQuit('codex-proxy', () => disposeCodexProxy(), 'async');
onQuit('remote-file-browser', () => disposeRemoteFileBrowser(), 'async');
// Remote SSH pool: 主动断开所有活动连接, 防止 ssh2 子句柄阻塞 Node 进程退出。
onQuit('remote-ssh-pool', () => disposeRemoteSshPool(), 'async');
+// WDA deleteSession may consume longer than the shared async quit budget. Kill
+// detached WDA/Sidecar process groups synchronously before that budget starts;
+// the lightweight seam is a no-op when Simulator was never initialized.
+onQuit('ios-simulator-exit-abort', abortIOSSimulatorOperationsForExit, 'sync');
// Hook 连接: 停掉全部 WS transport(含重连 timer), 防句柄阻塞退出。
onQuit('hook-control', () => disposeHookControl(), 'sync');
// session-git-pr-context: 取消 .git HEAD 的 parcel watcher 订阅, 防原生句柄阻塞退出。
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
index c8a080a901..c16b368ccb 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,4 @@
-import { mkdir, mkdtemp, rm, stat, utimes, writeFile } from 'node:fs/promises';
+import { mkdir, mkdtemp, readFile, rm, stat, utimes, writeFile } from 'node:fs/promises';
import { readFileSync } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
@@ -31,6 +31,7 @@ import {
cleanupIOSSimulatorRemovedSession,
createIOSSimulatorHost,
createRegistryBackedIOSSimulatorActor,
+ disposeIOSSimulatorHost,
flushIOSSimulatorOwnershipRegistry,
getIOSSimulatorMcpDeps,
type IOSSimulatorAppLifecycleAdapter,
@@ -73,6 +74,8 @@ const READY_REPORT: IOSSimulatorEnvironmentReport = {
setupSteps: [],
};
+const itMac = process.platform === 'darwin' ? it : it.skip;
+
describe('iOS Simulator host', () => {
function testResourceScheduler() {
return new IOSSimulatorResourceScheduler({ freeMemoryBytes: () => 100 * 1024 ** 3 });
@@ -82,7 +85,7 @@ describe('iOS Simulator host', () => {
return { id, workDir: `/tmp/${id}`, remoteHostId: null };
}
- it('keeps the default ownership registry lazy for disabled MCP discovery', async () => {
+ it('keeps the default ownership registry lazy for disabled MCP discovery and teardown', async () => {
const getPath = vi.spyOn(app, 'getPath');
try {
const deps = getIOSSimulatorMcpDeps({ isIOSSimulatorEnabled: () => false });
@@ -94,7 +97,6 @@ describe('iOS Simulator host', () => {
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 {
@@ -102,6 +104,26 @@ describe('iOS Simulator host', () => {
}
});
+ itMac('fences an ordinary removed task without retaining the default Host lease', async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-host-lazy-cleanup-'));
+ 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(cleanupIOSSimulatorRemovedSession('ordinary-session')).resolves.toBeUndefined();
+
+ expect(getPath).toHaveBeenCalledWith('userData');
+ await expect(stat(registryPath)).rejects.toMatchObject({
+ code: 'ENOENT',
+ });
+ 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');
@@ -5710,4 +5732,82 @@ describe('iOS Simulator host', () => {
),
).resolves.toMatchObject({ ok: false, errorCode: 'INVALID_ARGUMENT' });
});
+
+ itMac(
+ 'retries persisted removed-task cleanup after another registry writer releases its lease',
+ async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-host-persisted-cleanup-'));
+ const registryPath = path.join(root, 'ios-simulator', 'ownership-registry.json');
+ const setupRegistry = new IOSSimulatorOwnershipRegistryFile(registryPath, {
+ acquireWriterLease: () => {
+ let held = true;
+ return {
+ isHeld: () => held,
+ release: () => {
+ held = false;
+ },
+ };
+ },
+ });
+ expect(setupRegistry.acquireWriterSync()).toBe(true);
+ const persistedInstance = new IOSSimulatorOwnershipStore({
+ createId: () => 'persisted-removed-instance',
+ }).attach({
+ sessionId: 'persisted-removed-session',
+ worktreeRoot: '/tmp/persisted-removed-session',
+ sourceFingerprint: 'persisted-fingerprint',
+ device: READY_REPORT.devices[0]!,
+ });
+ setupRegistry.saveSync([persistedInstance]);
+ setupRegistry.releaseWriterSync();
+
+ const getPath = vi.spyOn(app, 'getPath').mockReturnValue(root);
+ let writerLeaseHeld = false;
+ let acquireAttempts = 0;
+ const acquireWriter = vi
+ .spyOn(IOSSimulatorOwnershipRegistryFile.prototype, 'acquireWriterSync')
+ .mockImplementation(() => {
+ if (writerLeaseHeld) return true;
+ acquireAttempts += 1;
+ if (acquireAttempts === 1) return false;
+ writerLeaseHeld = true;
+ return true;
+ });
+ const isWriter = vi
+ .spyOn(IOSSimulatorOwnershipRegistryFile.prototype, 'isWriter', 'get')
+ .mockImplementation(() => writerLeaseHeld);
+ const releaseWriter = vi
+ .spyOn(IOSSimulatorOwnershipRegistryFile.prototype, 'releaseWriterSync')
+ .mockImplementation(() => {
+ writerLeaseHeld = false;
+ });
+ try {
+ await expect(
+ cleanupIOSSimulatorRemovedSession('persisted-removed-session'),
+ ).rejects.toMatchObject({
+ code: 'DEVICE_BUSY',
+ retryable: true,
+ });
+ expect(acquireAttempts).toBe(1);
+
+ await expect(
+ cleanupIOSSimulatorRemovedSession('persisted-removed-session'),
+ ).resolves.toBeUndefined();
+
+ expect(acquireAttempts).toBe(2);
+ const persisted = JSON.parse(await readFile(registryPath, 'utf8')) as {
+ instances: unknown[];
+ };
+ expect(persisted.instances).toEqual([]);
+ } finally {
+ await disposeIOSSimulatorHost();
+ expect(writerLeaseHeld).toBe(false);
+ releaseWriter.mockRestore();
+ isWriter.mockRestore();
+ acquireWriter.mockRestore();
+ getPath.mockRestore();
+ await rm(root, { recursive: true, force: true });
+ }
+ },
+ );
});
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator-exit.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator-exit.ts
index 2d873b7197..9d758ee447 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator-exit.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator-exit.ts
@@ -11,11 +11,11 @@ export function registerIOSSimulatorExitAbortHandler(
};
}
-/** Lightweight updater seam: never imports the simulator or media runtime. */
+/** Lightweight bounded-exit seam: never imports the simulator or media runtime. */
export function abortIOSSimulatorOperationsForExit(): void {
try {
exitAbortHandler?.();
} catch {
- // A forced updater exit must not be blocked by best-effort child cleanup.
+ // A bounded or forced 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.ts
index 88a39f04a4..edd3c21563 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
@@ -347,15 +347,30 @@ export function createRegistryBackedIOSSimulatorActor(
}
}
-function createDefaultActor(lifecycle: IOSSimulatorSimctlLifecycle): {
+function createDefaultOwnershipRegistry(): IOSSimulatorOwnershipRegistryFile {
+ return new IOSSimulatorOwnershipRegistryFile(
+ path.join(app.getPath('userData'), 'ios-simulator', 'ownership-registry.json'),
+ );
+}
+
+function createDefaultActor(
+ lifecycle: IOSSimulatorSimctlLifecycle,
+ registry = createDefaultOwnershipRegistry(),
+): {
actor: IOSSimulatorInstanceActor;
flush: () => Promise<void>;
release: () => void;
} {
- const registry = new IOSSimulatorOwnershipRegistryFile(
- path.join(app.getPath('userData'), 'ios-simulator', 'ownership-registry.json'),
- );
- return createRegistryBackedIOSSimulatorActor(lifecycle, registry);
+ const persisted = createRegistryBackedIOSSimulatorActor(lifecycle, registry);
+ if (!registry.isWriter) {
+ persisted.release();
+ throw new IOSSimulatorInstanceError(
+ 'DEVICE_BUSY',
+ 'Another Cindy process is managing iOS Simulator ownership for this profile.',
+ true,
+ );
+ }
+ return persisted;
}
function createInMemoryActor(lifecycle: IOSSimulatorSimctlLifecycle): IOSSimulatorInstanceActor {
@@ -5520,20 +5535,19 @@ 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;
+function installDefaultIOSSimulatorHost(
+ lifecycle: IOSSimulatorSimctlLifecycle,
+ persistedActor: ReturnType<typeof createDefaultActor>,
+): IOSSimulatorHost {
+ if (defaultIOSSimulatorRuntime) {
+ persistedActor.release();
+ return defaultIOSSimulatorRuntime.host;
+ }
if (defaultIOSSimulatorRuntimeClosing) {
+ persistedActor.release();
throw new Error('The iOS Simulator host is shutting down.');
}
- const lifecycle = createIOSSimulatorSimctlLifecycle();
- const persistedActor = createDefaultActor(lifecycle);
let releaseExitAbortHandler: (() => void) | null = null;
try {
const host = createIOSSimulatorHost({
@@ -5563,6 +5577,23 @@ export function initializeIOSSimulatorHost(): IOSSimulatorHost {
}
}
+/**
+ * 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 lifecycle = createIOSSimulatorSimctlLifecycle();
+ const persistedActor = createDefaultActor(lifecycle);
+ return installDefaultIOSSimulatorHost(lifecycle, persistedActor);
+}
+
function currentIOSSimulatorHost(): IOSSimulatorHost | null {
return defaultIOSSimulatorRuntime?.host ?? null;
}
@@ -5665,7 +5696,42 @@ export function cancelIOSSimulatorSessionOperations(sessionId: string): Promise<
export function cleanupIOSSimulatorRemovedSession(sessionId: string): Promise<void> {
revokeIOSSimulatorRendererSession(sessionId);
- return currentIOSSimulatorHost()?.cleanupRemovedSession(sessionId) ?? Promise.resolve();
+ const currentHost = currentIOSSimulatorHost();
+ if (currentHost) return currentHost.cleanupRemovedSession(sessionId);
+ const normalizedSessionId = sessionId.trim();
+ if (!normalizedSessionId) return Promise.resolve();
+ // iOS ownership can only exist on macOS. Other platforms must keep generic
+ // task removal independent from the Darwin-only registry lease.
+ 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,
+ );
+ }
+ const persistedInstances = registry.loadSync();
+ if (!persistedInstances.some((instance) => instance.sessionId === normalizedSessionId)) {
+ registry.releaseWriterSync();
+ return Promise.resolve();
+ }
+
+ // Keep the same writer lease from the authoritative read through Host
+ // installation. Releasing and reacquiring here would reopen the race with
+ // another Cindy process attaching this task while it is being removed.
+ const lifecycle = createIOSSimulatorSimctlLifecycle();
+ const persistedActor = createDefaultActor(lifecycle, registry);
+ const host = installDefaultIOSSimulatorHost(lifecycle, persistedActor);
+ registryTransferred = true;
+ return host.cleanupRemovedSession(normalizedSessionId);
+ } catch (error) {
+ if (!registryTransferred) registry.releaseWriterSync();
+ return Promise.reject(error);
+ }
}
export function setIOSSimulatorViewerStreamProfile(