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): harden simulator operation lifecycle

JiangJiahaod72b2d308685
diff --git a/apps/desktop/src/main/__tests__/disableOrcaStrandedLead.test.ts b/apps/desktop/src/main/__tests__/disableOrcaStrandedLead.test.ts
index abee598b3b..9c4c89f8da 100644
--- a/apps/desktop/src/main/__tests__/disableOrcaStrandedLead.test.ts
+++ b/apps/desktop/src/main/__tests__/disableOrcaStrandedLead.test.ts
@@ -29,6 +29,12 @@ describe('disableOrcaInternal stranded-lead recovery', () => {
// If the prior disable was interrupted before archiveWorkersByTeam, the lead's worker
// sessions stay active+hidden+unreachable; the recovery must reconcile them too.
expect(registerSource).toContain('await reconcileInactiveTeamWorkersForLead(leadSessionId)');
+ expect(registerSource).toContain('await cancelIOSSimulatorSessionOperations(sid)');
+ });
+
+ it('cancels Host-owned worker operations before normal team archival', () => {
+ expect(registerSource).toContain('await cancelIOSSimulatorSessionOperations(w.sessionId)');
+ expect(registerSource).toContain('const archivedWorkerSessionIds = await archiveWorkersByTeam(team.id)');
});
it('reuses clearLeadOrcaRoleState on BOTH the normal-close and stranded-recovery paths', () => {
diff --git a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
index 9d2ce696cd..cd85b419ac 100644
--- a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
+++ b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
@@ -20,6 +20,7 @@ const h = vi.hoisted(() => ({
async (_sessionId: string, task: () => Promise<unknown>) => task(),
),
isSessionStillRemovable: vi.fn(),
+ cancelSessionOperations: vi.fn(),
recycleWorktreeForRemovedSession: vi.fn(),
userDataPath: '',
agentIslandService: {
@@ -61,6 +62,9 @@ vi.mock('../worktree/sessionRemovalRecycle.js', () => ({
isSessionStillRemovable: h.isSessionStillRemovable,
recycleWorktreeForRemovedSession: h.recycleWorktreeForRemovedSession,
}));
+vi.mock('../mcp-integrations/ios-simulator.js', () => ({
+ cancelIOSSimulatorSessionOperations: h.cancelSessionOperations,
+}));
import {
recycleSessionWorktreeForStatusChange,
@@ -72,6 +76,7 @@ beforeEach(() => {
h.userDataPath = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-set-sessions-status-'));
h.closeSession.mockResolvedValue(undefined);
h.isSessionStillRemovable.mockResolvedValue(true);
+ h.cancelSessionOperations.mockResolvedValue(undefined);
h.recycleWorktreeForRemovedSession.mockResolvedValue(undefined);
});
@@ -146,6 +151,7 @@ describe('setSessionsStatusInDb', () => {
});
expect(h.withSendToSessionLock).not.toHaveBeenCalled();
+ expect(h.cancelSessionOperations).not.toHaveBeenCalled();
expect(h.closeSession).not.toHaveBeenCalled();
expect(h.recycleWorktreeForRemovedSession).not.toHaveBeenCalled();
});
@@ -161,7 +167,8 @@ describe('setSessionsStatusInDb', () => {
});
expect(h.withSendToSessionLock).toHaveBeenCalledWith('s1', expect.any(Function));
- expect(h.isSessionStillRemovable).toHaveBeenCalledTimes(2);
+ expect(h.isSessionStillRemovable).toHaveBeenCalledTimes(3);
+ expect(h.cancelSessionOperations).toHaveBeenCalledWith('s1');
expect(h.recycleWorktreeForRemovedSession).toHaveBeenCalledWith('s1');
});
@@ -234,7 +241,8 @@ describe('recycleSessionWorktreeForStatusChange', () => {
await recycleSessionWorktreeForStatusChange('s1', 'deleted');
expect(h.withSendToSessionLock).toHaveBeenCalledWith('s1', expect.any(Function));
- expect(h.isSessionStillRemovable).toHaveBeenCalledTimes(2);
+ expect(h.isSessionStillRemovable).toHaveBeenCalledTimes(3);
+ expect(h.cancelSessionOperations).toHaveBeenCalledWith('s1');
expect(h.closeSession).toHaveBeenCalledWith('s1');
expect(h.recycleWorktreeForRemovedSession).toHaveBeenCalledWith('s1');
expect(h.webContentsSend).toHaveBeenCalledWith('worktree:changed', { sessionId: 's1' });
diff --git a/apps/desktop/src/main/__tests__/updateServiceIOSSimulatorExit.test.ts b/apps/desktop/src/main/__tests__/updateServiceIOSSimulatorExit.test.ts
new file mode 100644
index 0000000000..af74684e51
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/updateServiceIOSSimulatorExit.test.ts
@@ -0,0 +1,23 @@
+import { readFileSync } from 'node:fs';
+
+import { describe, expect, it } from 'vitest';
+
+const source = readFileSync(new URL('../updateService.ts', import.meta.url), 'utf8');
+
+describe('update force-quit iOS Simulator cleanup', () => {
+ it('aborts detached simulator operations before exiting the process', () => {
+ expect(source).toContain(
+ "import { abortIOSSimulatorOperationsForExit } from './mcp-integrations/ios-simulator-exit';",
+ );
+ const forceQuitStart = source.indexOf('function forceQuit(): void {');
+ const forceQuitEnd = source.indexOf('\nfunction executeUpdateMacOS', forceQuitStart);
+ const forceQuitSource = source.slice(forceQuitStart, forceQuitEnd);
+ const abortIndex = forceQuitSource.indexOf('abortIOSSimulatorOperationsForExit();');
+ const exitIndex = forceQuitSource.indexOf('process.exit(0);');
+
+ expect(forceQuitStart).toBeGreaterThanOrEqual(0);
+ expect(forceQuitEnd).toBeGreaterThan(forceQuitStart);
+ expect(abortIndex).toBeGreaterThanOrEqual(0);
+ expect(exitIndex).toBeGreaterThan(abortIndex);
+ });
+});
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionRemovalOperations.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionRemovalOperations.test.ts
new file mode 100644
index 0000000000..d0c031e01b
--- /dev/null
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionRemovalOperations.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { quiesceSessionBeforeWorktreeRecycle } from '../sessionRemovalOperations';
+
+describe('quiesceSessionBeforeWorktreeRecycle', () => {
+ it('cancels Host operations before closing the Agent session', async () => {
+ const order: string[] = [];
+ const isSessionStillRemovable = vi.fn(async () => {
+ order.push('check');
+ return true;
+ });
+ const cancelSessionOperations = vi.fn(async () => {
+ order.push('cancel');
+ });
+ const closeSession = vi.fn(async () => {
+ order.push('close');
+ });
+
+ await expect(
+ quiesceSessionBeforeWorktreeRecycle('session-a', {
+ isSessionStillRemovable,
+ cancelSessionOperations,
+ closeSession,
+ }),
+ ).resolves.toBe(true);
+ expect(order).toEqual(['check', 'cancel', 'check', 'close']);
+ });
+
+ it('does not close or recycle a task restored while cancellation settles', async () => {
+ const isSessionStillRemovable = vi
+ .fn<() => Promise<boolean>>()
+ .mockResolvedValueOnce(true)
+ .mockResolvedValueOnce(false);
+ const cancelSessionOperations = vi.fn(async () => undefined);
+ const closeSession = vi.fn(async () => undefined);
+
+ await expect(
+ quiesceSessionBeforeWorktreeRecycle('session-a', {
+ isSessionStillRemovable,
+ cancelSessionOperations,
+ closeSession,
+ }),
+ ).resolves.toBe(false);
+ expect(cancelSessionOperations).toHaveBeenCalledWith('session-a');
+ expect(closeSession).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/localDb/ipc/sessionRemovalOperations.ts b/apps/desktop/src/main/localDb/ipc/sessionRemovalOperations.ts
new file mode 100644
index 0000000000..4d0a299c74
--- /dev/null
+++ b/apps/desktop/src/main/localDb/ipc/sessionRemovalOperations.ts
@@ -0,0 +1,21 @@
+export interface SessionRemovalOperationDeps {
+ isSessionStillRemovable(sessionId: string): Promise<boolean>;
+ cancelSessionOperations(sessionId: string): Promise<void>;
+ closeSession(sessionId: string): Promise<void>;
+}
+
+/**
+ * Quiesce worktree writers while the session route lock is held. Eligibility
+ * is checked again after cancellation because a user may restore the task
+ * while an in-flight build is settling.
+ */
+export async function quiesceSessionBeforeWorktreeRecycle(
+ sessionId: string,
+ deps: SessionRemovalOperationDeps,
+): Promise<boolean> {
+ if (!(await deps.isSessionStillRemovable(sessionId))) return false;
+ await deps.cancelSessionOperations(sessionId);
+ if (!(await deps.isSessionStillRemovable(sessionId))) return false;
+ await deps.closeSession(sessionId);
+ return true;
+}
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index 083cdc87ae..9bb828b936 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -56,6 +56,7 @@ import {
} from './messages';
import { assertTrustedAppRendererEvent } from '../../security/trustedAppRenderer.js';
import { removeTurnChangeSetsForSession } from '../../turn-change-set/store.js';
+import { quiesceSessionBeforeWorktreeRecycle } from './sessionRemovalOperations.js';
const log = createLogger('sessions');
const REMOTE_EDITABLE_META = new Set(['status', 'title', 'pinnedAt']);
@@ -160,19 +161,26 @@ export async function recycleSessionWorktreeForStatusChange(
): Promise<void> {
if (status !== 'deleted' && status !== 'archived') return;
try {
- const [mh, recycle, routeLock] = await Promise.all([
+ const [mh, recycle, routeLock, iosSimulator] = await Promise.all([
import('../../maker-host/index.js'),
import('../../worktree/sessionRemovalRecycle.js'),
import('../../maker-ipc/register.js'),
+ import('../../mcp-integrations/ios-simulator.js'),
]);
if (!(await recycle.isSessionStillRemovable(sessionId))) return;
- await routeLock.withSendToSessionLock(sessionId, async () => {
- if (!(await recycle.isSessionStillRemovable(sessionId))) return;
- await mh
- .getMakerIfReady()
- ?.closeSession(sessionId)
- .catch(() => undefined);
- });
+ const shouldRecycle = await routeLock.withSendToSessionLock(sessionId, async () =>
+ quiesceSessionBeforeWorktreeRecycle(sessionId, {
+ isSessionStillRemovable: recycle.isSessionStillRemovable,
+ cancelSessionOperations: iosSimulator.cancelIOSSimulatorSessionOperations,
+ closeSession: async (id) => {
+ await mh
+ .getMakerIfReady()
+ ?.closeSession(id)
+ .catch(() => undefined);
+ },
+ }),
+ );
+ if (!shouldRecycle) return;
await recycle.recycleWorktreeForRemovedSession(sessionId);
} catch (err) {
log.warn('worktree recycle after session status change failed', {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts
index 2b2c63ad72..5e47400895 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts
@@ -167,7 +167,7 @@ describe('iOS Simulator IPC handlers', () => {
preferredEncoding: 'jpeg',
fallbackReason: 'native-decoder-fallback',
});
- await harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_LATEST_FRAME, route);
+ await harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_LATEST_FRAME, route);
expect(setViewerVisibility).toHaveBeenCalledWith(
'session-a',
@@ -196,11 +196,18 @@ describe('iOS Simulator IPC handlers', () => {
17,
undefined,
);
- expect(getLatestFrame).toHaveBeenCalledWith('session-a', {
- instanceId: 'instance-a',
- generation: 3,
- leaseId: 'lease-a',
- });
+ expect(getLatestFrame).toHaveBeenCalledWith(
+ 'session-a',
+ {
+ instanceId: 'instance-a',
+ generation: 3,
+ leaseId: 'lease-a',
+ },
+ 17,
+ );
+ await expect(
+ harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_LATEST_FRAME, route),
+ ).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
await expect(
harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_LATEST_FRAME, {
...route,
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
index dbcb10c8de..1c76a9832a 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
@@ -159,6 +159,9 @@ function createDeps(overrides: Partial<OrcaTeamServiceDeps> = {}) {
));
return true;
}),
+ cancelWorkerSessionOperations: vi.fn(async (sessionId) => {
+ calls.push(`cancelWorkerSessionOperations:${sessionId}`);
+ }),
closeWorkerSession: vi.fn(async (sessionId) => {
calls.push(`closeWorkerSession:${sessionId}`);
}),
@@ -1382,8 +1385,10 @@ describe('OrcaTeamService', () => {
});
expect(calls).toEqual([
+ 'cancelWorkerSessionOperations:worker-session-1',
'closeWorkerSession:worker-session-1',
'archiveWorkerSession:worker-session-1',
+ 'cancelWorkerSessionOperations:worker-session-1',
'updateWorkerStatus:done',
'broadcastOrcaWorkerChanged',
]);
@@ -1403,8 +1408,10 @@ describe('OrcaTeamService', () => {
expect(deps.updateWorkerStatus).toHaveBeenCalledWith('worker-1', 'done');
expect(calls).toEqual([
+ 'cancelWorkerSessionOperations:worker-session-1',
'closeWorkerSession:worker-session-1',
'archiveWorkerSession:worker-session-1',
+ 'cancelWorkerSessionOperations:worker-session-1',
'updateWorkerStatus:done',
'broadcastOrcaWorkerChanged',
]);
@@ -1498,8 +1505,10 @@ describe('OrcaTeamService', () => {
});
expect(calls).toEqual([
+ 'cancelWorkerSessionOperations:worker-session-1',
'closeWorkerSession:worker-session-1',
'archiveWorkerSession:worker-session-1',
+ 'cancelWorkerSessionOperations:worker-session-1',
'updateWorkerStatus:done',
'broadcastOrcaWorkerChanged',
]);
diff --git a/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts b/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts
index f2ccb6b3a6..cd5b1367ec 100644
--- a/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts
@@ -56,6 +56,7 @@ export interface IOSSimulatorHandlerDeps {
getLatestFrame(
sessionId: string,
route: { instanceId: string; generation: number; leaseId: string },
+ viewerWebContentsId: number,
): Promise<IOSSimulatorToolResponse>;
updateViewerTouch(
sessionId: string,
@@ -250,9 +251,13 @@ export function registerIOSSimulatorHandlers(
}
return resolved.setAgentMutationPaused(sessionId, readViewerRoute(record), record.paused);
});
- handle(MAKER_INVOKE.IOS_SIMULATOR_LATEST_FRAME, async (_event, payload) => {
+ handle(MAKER_INVOKE.IOS_SIMULATOR_LATEST_FRAME, async (event, payload) => {
const record = readRecord(payload);
- return resolved.getLatestFrame(readSessionId(record), readViewerRoute(record));
+ return resolved.getLatestFrame(
+ readSessionId(record),
+ readViewerRoute(record),
+ readSenderWebContentsId(event),
+ );
});
handle(MAKER_INVOKE.IOS_SIMULATOR_SET_STREAM_PROFILE, async (_event, payload) => {
const record = readRecord(payload);
diff --git a/apps/desktop/src/main/maker-ipc/orcaTeamService.ts b/apps/desktop/src/main/maker-ipc/orcaTeamService.ts
index 8719a465d4..d3db595d18 100644
--- a/apps/desktop/src/main/maker-ipc/orcaTeamService.ts
+++ b/apps/desktop/src/main/maker-ipc/orcaTeamService.ts
@@ -186,6 +186,8 @@ export interface OrcaTeamServiceDeps {
markWorkerIdle(workerId: string): Promise<void>;
markWorkerIdleIfStatus(workerId: string, expectedStatus: 'done'): Promise<boolean>;
restoreWorkerDoneIfIdle(workerId: string): Promise<boolean>;
+ /** Stop Host-owned work (for example iOS builds) before archiving this worker task. */
+ cancelWorkerSessionOperations(sessionId: string): Promise<void>;
closeWorkerSession(sessionId: string): Promise<void>;
/** 与 Session.send reservation 原子互斥;false 表示 direct send/turn 已先取得会话。 */
closeWorkerSessionIfIdle(sessionId: string): Promise<boolean>;
@@ -807,8 +809,13 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServic
clearRuntimeState(worker.sessionId);
deps.forgetWorkerSession?.(worker.sessionId);
+ await deps.cancelWorkerSessionOperations(worker.sessionId);
await closeWorkerSessionBestEffort(worker.sessionId, 'archiveWorker');
await deps.archiveWorkerSession(worker.sessionId);
+ // The archived status is the admission barrier for new Host work. Cancel
+ // once more after publishing it to catch a build that registered between
+ // the pre-close cancellation and the status transition.
+ await deps.cancelWorkerSessionOperations(worker.sessionId);
await deps.updateWorkerStatus(worker.id, 'done');
deps.broadcastOrcaWorkerChanged(link.leadSessionId);
return { ok: true, workerId: worker.id };
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index b3097daee4..f48dd1cc23 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -449,7 +449,10 @@ import {
} from './sessionReferenceResolver.js';
import { registerAndroidAutomationHandlers } from './androidHandlers.js';
import { registerIOSSimulatorHandlers } from './iosSimulatorHandlers.js';
-import { reconcileIOSSimulatorOwnership } from '../mcp-integrations/ios-simulator.js';
+import {
+ cancelIOSSimulatorSessionOperations,
+ reconcileIOSSimulatorOwnership,
+} from '../mcp-integrations/ios-simulator.js';
import { MAKER_INVOKE, MAKER_PUSH, MAKER_SEND } from './channels.js';
import type { CollabDispatchOutcome } from './collabSendOutcome.js';
import { runAcceptedCallback } from './acceptedCallbackRunner.js';
@@ -7936,6 +7939,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// active + hidden + unreachable —— 一并补齐归档,否则它们会成为永远触达不到的孤儿 worker。
const orphanedWorkerSessionIds = await reconcileInactiveTeamWorkersForLead(leadSessionId);
for (const sid of orphanedWorkerSessionIds) {
+ await cancelIOSSimulatorSessionOperations(sid);
cleanupPendingInteractionsForSession(sid, 'orca_disable');
forgetKnownOrcaWorkerSession(sid);
}
@@ -7956,6 +7960,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const activeWorkers = workers.filter((w) => w.teamId === team.id);
for (const w of activeWorkers) {
orcaTeamService.clearAutoBridgeState(w.sessionId);
+ await cancelIOSSimulatorSessionOperations(w.sessionId);
const sess = maker.getSession(w.sessionId);
if (sess) {
try {
@@ -7983,7 +7988,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
await markTeamEnded(team.id, 'completed');
await markWorkersStatusByTeam(team.id, 'done');
- await archiveWorkersByTeam(team.id);
+ const archivedWorkerSessionIds = await archiveWorkersByTeam(team.id);
+ await Promise.all(
+ archivedWorkerSessionIds.map((sessionId) =>
+ cancelIOSSimulatorSessionOperations(sessionId),
+ ),
+ );
await clearLeadOrcaRoleState(leadSessionId);
@@ -8148,6 +8158,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
},
markWorkerIdleIfStatus,
restoreWorkerDoneIfIdle,
+ cancelWorkerSessionOperations: cancelIOSSimulatorSessionOperations,
closeWorkerSession: async (sessionId) => {
const sess = maker.getSession(sessionId);
if (sess) {
@@ -8435,12 +8446,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
});
},
rollbackCreatedWorker: async ({ workerId, workerSessionId }) => {
+ await cancelIOSSimulatorSessionOperations(workerSessionId);
const workerSession = maker.getSession(workerSessionId);
if (workerSession) {
await maker.closeSession(workerSessionId).catch(() => undefined);
}
forgetKnownOrcaWorkerSession(workerSessionId);
await archiveSingleWorkerSession(workerSessionId).catch(() => undefined);
+ await cancelIOSSimulatorSessionOperations(workerSessionId);
await removeWorker(workerId);
},
broadcastSessionCreated,
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-exit.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-exit.test.ts
new file mode 100644
index 0000000000..1253f562cc
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-exit.test.ts
@@ -0,0 +1,37 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ abortIOSSimulatorOperationsForExit,
+ registerIOSSimulatorExitAbortHandler,
+} from '../ios-simulator-exit';
+
+let unregister: (() => void) | null = null;
+
+afterEach(() => {
+ unregister?.();
+ unregister = null;
+});
+
+describe('iOS Simulator updater exit abort seam', () => {
+ it('calls the registered lightweight abort handler', () => {
+ const abort = vi.fn();
+ unregister = registerIOSSimulatorExitAbortHandler(abort);
+
+ abortIOSSimulatorOperationsForExit();
+
+ expect(abort).toHaveBeenCalledOnce();
+ });
+
+ it('does not let stale unregister callbacks remove a replacement handler', () => {
+ const first = vi.fn();
+ const unregisterFirst = registerIOSSimulatorExitAbortHandler(first);
+ const second = vi.fn();
+ unregister = registerIOSSimulatorExitAbortHandler(second);
+
+ unregisterFirst();
+ abortIOSSimulatorOperationsForExit();
+
+ expect(first).not.toHaveBeenCalled();
+ expect(second).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-media.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-media.test.ts
index e9d1406555..4f6b8fb3fd 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-media.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-media.test.ts
@@ -1,4 +1,4 @@
-import { mkdir, stat, writeFile } from 'node:fs/promises';
+import { mkdir, stat, truncate, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
@@ -110,6 +110,48 @@ describe('IOSSimulatorMediaCapture', () => {
await expect(stat(path.dirname(launchArgs.at(-1)!))).rejects.toMatchObject({ code: 'ENOENT' });
});
+ it('rejects oversized recordings before buffering them in Electron Main', async () => {
+ const ingest = vi.fn();
+ let videoPath = '';
+ let resolveExit: () => void = () => undefined;
+ const capture = new IOSSimulatorMediaCapture({
+ ingest,
+ recordingLauncher: {
+ launch: vi.fn((args: readonly string[]) => {
+ videoPath = args.at(-1)!;
+ return {
+ exited: new Promise<void>((resolve) => {
+ resolveExit = resolve;
+ }),
+ kill: vi.fn(async () => {
+ await writeFile(videoPath, Buffer.alloc(0));
+ await truncate(videoPath, 128 * 1024 * 1024 + 1);
+ resolveExit();
+ }),
+ };
+ }),
+ },
+ });
+ const started = await capture.startRecording({
+ simulatorUdid: 'EXACT-UDID',
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 3,
+ source: 'agent',
+ });
+
+ await expect(
+ capture.stopRecording({
+ recordingId: started.recordingId,
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 3,
+ }),
+ ).rejects.toMatchObject({ code: 'RECORDING_FAILED' });
+ expect(ingest).not.toHaveBeenCalled();
+ await expect(stat(path.dirname(videoPath))).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
it('terminates and removes active recording state when an instance is discarded', async () => {
let resolveExit: () => void = () => undefined;
let videoPath = '';
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 97fb4f2057..7ffd5ef03f 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
@@ -979,14 +979,26 @@ describe('iOS Simulator host', () => {
);
const resultBundlePath = path.join(projectRoot, `CindyBuild-${crypto.randomUUID()}.xcresult`);
await mkdir(resultBundlePath, { recursive: true });
- let finishBuild!: (
- result: Awaited<ReturnType<IOSSimulatorProjectBuilderAdapter['build']>>,
- ) => void;
+ let buildSignal: AbortSignal | undefined;
const build = vi.fn(
- () =>
- new Promise<Awaited<ReturnType<IOSSimulatorProjectBuilderAdapter['build']>>>((resolve) => {
- finishBuild = resolve;
- }),
+ (input: Parameters<IOSSimulatorProjectBuilderAdapter['build']>[0]) =>
+ new Promise<Awaited<ReturnType<IOSSimulatorProjectBuilderAdapter['build']>>>(
+ (_, reject) => {
+ buildSignal = input.signal;
+ input.signal?.addEventListener('abort', () => {
+ reject(
+ new IOSSimulatorProjectBuildError(
+ 'APP_BUILD_FAILED',
+ 'cancelled',
+ '',
+ resultBundlePath,
+ false,
+ true,
+ ),
+ );
+ });
+ },
+ ),
);
const host = createIOSSimulatorHost({
actor,
@@ -1008,17 +1020,9 @@ describe('iOS Simulator host', () => {
);
await vi.waitFor(() => expect(build).toHaveBeenCalledTimes(1));
- await host.dispose();
- finishBuild({
- kind: 'xcode-project',
- worktreeRoot: instance.worktreeRoot,
- projectRoot: path.join(instance.worktreeRoot, 'ios'),
- containerPath: path.join(instance.worktreeRoot, 'ios', 'Demo.xcodeproj'),
- scheme: 'Demo',
- appPath: path.join(instance.worktreeRoot, 'build', 'Demo.app'),
- resultBundlePath,
- buildLogTail: 'BUILD SUCCEEDED',
- });
+ const disposePromise = host.dispose();
+ await vi.waitFor(() => expect(buildSignal?.aborted).toBe(true));
+ await disposePromise;
try {
await expect(callPromise).resolves.toMatchObject({
@@ -1032,6 +1036,75 @@ describe('iOS Simulator host', () => {
}
});
+ it('synchronously aborts active builds before updater force-quit', 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 instance = actor.attach({
+ sessionId: 'force-quit-build-session',
+ worktreeRoot: '/tmp/force-quit-build-session',
+ sourceFingerprint: 'fingerprint-a',
+ device: READY_REPORT.devices[0]!,
+ });
+ let buildSignal: AbortSignal | undefined;
+ const build = vi.fn(
+ (input: Parameters<IOSSimulatorProjectBuilderAdapter['build']>[0]) =>
+ new Promise<Awaited<ReturnType<IOSSimulatorProjectBuilderAdapter['build']>>>(
+ (_, reject) => {
+ buildSignal = input.signal;
+ input.signal?.addEventListener('abort', () => {
+ reject(
+ new IOSSimulatorProjectBuildError(
+ 'APP_BUILD_FAILED',
+ 'cancelled',
+ '',
+ null,
+ false,
+ true,
+ ),
+ );
+ });
+ },
+ ),
+ );
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ projectBuilder: { build },
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async () => localSession('force-quit-build-session')),
+ });
+ await host.reconcileOwnership();
+ const current = actor.getOwned('force-quit-build-session', instance.instanceId);
+ const callPromise = host.callTool(
+ 'build_app',
+ {
+ instanceId: current.instanceId,
+ generation: current.generation,
+ leaseId: current.lease.id,
+ },
+ { sessionId: 'force-quit-build-session', origin: 'user' },
+ );
+ await vi.waitFor(() => expect(build).toHaveBeenCalledOnce());
+
+ host.abortOperationsForExit();
+
+ expect(buildSignal?.aborted).toBe(true);
+ await expect(callPromise).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'MUTATION_CANCELLED',
+ });
+ await host.dispose();
+ });
+
it('rejects SSH sessions before touching local Apple tooling', async () => {
const inspect = vi.fn();
const host = createIOSSimulatorHost({
@@ -1065,6 +1138,49 @@ describe('iOS Simulator host', () => {
await expect(host.getStatus('session-a')).resolves.toMatchObject({ ok: true });
});
+ it('evaluates the MCP plugin gate against the current project workdir', async () => {
+ const host = createIOSSimulatorHost({
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ });
+ const isIOSSimulatorEnabled = vi.fn(
+ (context?: { workingDir?: string }) => context?.workingDir === '/projects/enabled-ios',
+ );
+ const deps = getIOSSimulatorMcpDeps({ host, isIOSSimulatorEnabled });
+
+ await expect(
+ deps.callTool(
+ 'check_environment',
+ {},
+ {
+ sessionId: 'session-a',
+ workingDir: '/projects/enabled-ios',
+ },
+ ),
+ ).resolves.toMatchObject({ ok: true });
+ await expect(
+ deps.callTool(
+ 'check_environment',
+ {},
+ {
+ sessionId: 'session-a',
+ workingDir: '/projects/disabled-ios',
+ },
+ ),
+ ).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'IOS_SIMULATOR_DISABLED',
+ });
+ expect(isIOSSimulatorEnabled).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({ workingDir: '/projects/enabled-ios' }),
+ );
+ expect(isIOSSimulatorEnabled).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({ workingDir: '/projects/disabled-ios' }),
+ );
+ });
+
it('does not expose WDA endpoints or raw driver errors to callers', async () => {
const host = createIOSSimulatorHost({
runtime: { inspect: vi.fn(async () => READY_REPORT) },
@@ -1341,11 +1457,11 @@ describe('iOS Simulator host', () => {
};
await expect(
- host.setViewerVisibility('session-a', initialRoute, true, 'h264'),
+ host.setViewerVisibility('session-a', initialRoute, true, 'h264', undefined, 17),
).resolves.toMatchObject({ ok: true });
h264FramePump.clear.mockClear();
now += 101;
- await expect(host.getLatestFrame('session-a', initialRoute)).resolves.toMatchObject({
+ await expect(host.getLatestFrame('session-a', initialRoute, 17)).resolves.toMatchObject({
ok: false,
errorCode: 'LEASE_EXPIRED',
});
@@ -1734,12 +1850,12 @@ describe('iOS Simulator host', () => {
leaseId: reconciled.lease.id,
};
- await expect(host.setViewerVisibility('session-a', route, true, 'h264')).resolves.toMatchObject(
- {
- ok: true,
- data: { stream: { state: 'connecting' } },
- },
- );
+ await expect(
+ host.setViewerVisibility('session-a', route, true, 'h264', undefined, 77),
+ ).resolves.toMatchObject({
+ ok: true,
+ data: { stream: { state: 'connecting' } },
+ });
expect(h264FramePump.setVisible).toHaveBeenCalledWith(
expect.objectContaining({
instanceId: started.instanceId,
@@ -1766,6 +1882,15 @@ describe('iOS Simulator host', () => {
},
});
+ h264FramePump.snapshot.mockClear();
+ framePump.snapshot.mockClear();
+ await expect(host.getLatestFrame('session-a', route, 88)).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'INSTANCE_NOT_OWNED',
+ });
+ expect(h264FramePump.snapshot).not.toHaveBeenCalled();
+ expect(framePump.snapshot).not.toHaveBeenCalled();
+
const fallbackHighProfile = {
framesPerSecond: 20,
jpegQuality: 70,
@@ -1911,7 +2036,7 @@ describe('iOS Simulator host', () => {
generation: afterOrientation.generation,
leaseId: afterOrientation.lease.id,
};
- await expect(host.getLatestFrame('session-a', latestRoute)).resolves.toMatchObject({
+ await expect(host.getLatestFrame('session-a', latestRoute, 77)).resolves.toMatchObject({
ok: true,
data: { stream: { state: 'connecting' } },
});
@@ -1932,7 +2057,7 @@ describe('iOS Simulator host', () => {
});
jpegSnapshot = { ...jpegSnapshot, state: 'reconnecting' };
- await expect(host.getLatestFrame('session-a', latestRoute)).resolves.toMatchObject({
+ await expect(host.getLatestFrame('session-a', latestRoute, 77)).resolves.toMatchObject({
ok: true,
data: { stream: { state: 'reconnecting' } },
});
@@ -1962,12 +2087,12 @@ describe('iOS Simulator host', () => {
}),
);
- await expect(host.setViewerVisibility('session-a', latestRoute, false)).resolves.toMatchObject({
- ok: true,
- });
+ await expect(
+ host.setViewerVisibility('session-a', latestRoute, false, 'jpeg', undefined, 77),
+ ).resolves.toMatchObject({ ok: true });
nativeAvailable = false;
await expect(
- host.setViewerVisibility('session-a', latestRoute, true, 'h264'),
+ host.setViewerVisibility('session-a', latestRoute, true, 'h264', undefined, 77),
).resolves.toMatchObject({ ok: true });
expect(driverManager.recoverNativeSidecar).toHaveBeenLastCalledWith(started.instanceId, {
rearm: true,
@@ -2134,6 +2259,109 @@ describe('iOS Simulator host', () => {
expect(driverManager.stop).toHaveBeenCalledTimes(2);
});
+ it('does not unblock builds when an external shutdown overlaps instance activation', async () => {
+ const shutdownDevice = { ...READY_REPORT.devices[0]!, state: 'Shutdown' as const };
+ const environment = { ...READY_REPORT, devices: [shutdownDevice] };
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(async () => shutdownDevice),
+ bootExact: vi.fn(async () => ({ ...READY_REPORT.devices[0]!, state: 'Booted' })),
+ 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: 'session-a',
+ worktreeRoot: '/tmp/session-a',
+ sourceFingerprint: 'fingerprint-a',
+ device: shutdownDevice,
+ });
+ const running = {
+ instanceId: attached.instanceId,
+ simulatorUdid: attached.simulatorUdid,
+ pid: 42,
+ driver: {},
+ driverSessionId: 'wda-session',
+ } as unknown as WdaRunningInstance;
+ const driverManager = {
+ get: vi.fn(() => null),
+ start: vi.fn(async () => running),
+ stop: vi.fn(async () => undefined),
+ };
+ const build = vi.fn<IOSSimulatorProjectBuilderAdapter['build']>();
+ const resourceScheduler = testResourceScheduler();
+ const runStart = resourceScheduler.runStart.bind(resourceScheduler);
+ let signalActivationReady!: () => void;
+ const activationReady = new Promise<void>((resolve) => {
+ signalActivationReady = resolve;
+ });
+ let releaseActivation!: () => void;
+ const activationGate = new Promise<void>((resolve) => {
+ releaseActivation = resolve;
+ });
+ vi.spyOn(resourceScheduler, 'runStart').mockImplementation(async (instanceId, task) => {
+ const result = await runStart(instanceId, task);
+ signalActivationReady();
+ await activationGate;
+ return result;
+ });
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ driverManager,
+ projectBuilder: { build },
+ runtime: { inspect: vi.fn(async () => environment) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ resourceScheduler,
+ deviceLivenessIntervalMs: 0,
+ });
+ await host.reconcileOwnership();
+ const current = actor.getOwned('session-a', attached.instanceId);
+ const route = {
+ instanceId: current.instanceId,
+ generation: current.generation,
+ leaseId: current.lease.id,
+ };
+
+ const startPromise = host.callTool('start_instance', route, {
+ sessionId: 'session-a',
+ origin: 'user',
+ });
+ await activationReady;
+ await expect(host.getStatus('session-a')).resolves.toMatchObject({
+ ok: true,
+ instances: [
+ {
+ instanceId: attached.instanceId,
+ lifecycleState: 'stopped',
+ },
+ ],
+ });
+ releaseActivation();
+
+ await expect(startPromise).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'MUTATION_CANCELLED',
+ });
+ const stopped = actor.getOwned('session-a', attached.instanceId);
+ await expect(
+ host.callTool(
+ 'build_app',
+ {
+ instanceId: stopped.instanceId,
+ generation: stopped.generation,
+ leaseId: stopped.lease.id,
+ },
+ { sessionId: 'session-a', origin: 'user' },
+ ),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'MUTATION_CANCELLED' });
+ expect(build).not.toHaveBeenCalled();
+ await host.dispose();
+ });
+
it('ignores an exact-device probe that finishes after the binding is detached', async () => {
let resolveProbe!: (device: (typeof READY_REPORT.devices)[number] | null) => void;
const lifecycle: IOSSimulatorSimctlLifecycle = {
@@ -2605,7 +2833,7 @@ describe('iOS Simulator host', () => {
expect(requestViewerFocus).not.toHaveBeenCalled();
});
- it('releases scheduler capacity when a ready preexisting device is detached', async () => {
+ it('cancels an active build before detaching and releasing scheduler capacity', async () => {
const lifecycle: IOSSimulatorSimctlLifecycle = {
findExact: vi.fn(),
bootExact: vi.fn(),
@@ -2617,8 +2845,38 @@ describe('iOS Simulator host', () => {
store: new IOSSimulatorOwnershipStore(),
lifecycle,
});
+ const actorStart = vi.spyOn(actor, 'start');
+ const actorAttach = vi.spyOn(actor, 'attachSerialized');
const resourceScheduler = testResourceScheduler();
let running: WdaRunningInstance | null = null;
+ let buildSignal: AbortSignal | undefined;
+ let finishDetachCleanup!: () => void;
+ const discardInstance = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ finishDetachCleanup = resolve;
+ }),
+ );
+ const build = vi.fn(
+ (input: Parameters<IOSSimulatorProjectBuilderAdapter['build']>[0]) =>
+ new Promise<Awaited<ReturnType<IOSSimulatorProjectBuilderAdapter['build']>>>(
+ (_, reject) => {
+ buildSignal = input.signal;
+ input.signal?.addEventListener('abort', () => {
+ reject(
+ new IOSSimulatorProjectBuildError(
+ 'APP_BUILD_FAILED',
+ 'cancelled',
+ '',
+ null,
+ false,
+ true,
+ ),
+ );
+ });
+ },
+ ),
+ );
const host = createIOSSimulatorHost({
actor,
lifecycle,
@@ -2626,6 +2884,7 @@ describe('iOS Simulator host', () => {
getSession: vi.fn(async (id) => localSession(id)),
resolveWorktreeRoot: vi.fn(async (workDir) => workDir),
resourceScheduler,
+ projectBuilder: { build },
driverManager: {
get: vi.fn(() => running),
start: vi.fn(async (options) => {
@@ -2643,7 +2902,7 @@ describe('iOS Simulator host', () => {
}),
},
mediaCapture: {
- discardInstance: vi.fn(async () => undefined),
+ discardInstance,
} as unknown as IOSSimulatorMediaCaptureAdapter,
});
@@ -2654,24 +2913,122 @@ describe('iOS Simulator host', () => {
{ sessionId: 'session-a', origin: 'user' },
),
).resolves.toMatchObject({ ok: true });
+ actorAttach.mockClear();
expect(resourceScheduler.runningCount()).toBe(1);
const attached = actor.list('session-a')[0]!;
+ const route = {
+ instanceId: attached.instanceId,
+ generation: attached.generation,
+ leaseId: attached.lease.id,
+ };
+ const buildPromise = host.callTool('build_app', route, {
+ sessionId: 'session-a',
+ origin: 'user',
+ });
+ await vi.waitFor(() => expect(build).toHaveBeenCalledOnce());
+ const detachPromise = host.callTool('detach_device', route, {
+ sessionId: 'session-a',
+ origin: 'user',
+ });
+ await vi.waitFor(() => expect(discardInstance).toHaveBeenCalledOnce());
+ expect(buildSignal?.aborted).toBe(true);
+ await expect(buildPromise).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'MUTATION_CANCELLED',
+ });
+ await expect(
+ host.callTool('build_app', route, { sessionId: 'session-a', origin: 'user' }),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'MUTATION_CANCELLED' });
+ await expect(
+ host.callTool('start_instance', route, { sessionId: 'session-a', origin: 'user' }),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'MUTATION_CANCELLED' });
await expect(
host.callTool(
- 'detach_device',
- {
- instanceId: attached.instanceId,
- generation: attached.generation,
- leaseId: attached.lease.id,
- },
+ 'attach_device',
+ { udid: READY_REPORT.devices[0]!.udid },
{ sessionId: 'session-a', origin: 'user' },
),
- ).resolves.toMatchObject({ ok: true });
+ ).resolves.toMatchObject({ ok: false, errorCode: 'MUTATION_CANCELLED' });
+ expect(build).toHaveBeenCalledOnce();
+ expect(actorStart).not.toHaveBeenCalled();
+ expect(actorAttach).not.toHaveBeenCalled();
+ finishDetachCleanup();
+ await expect(detachPromise).resolves.toMatchObject({ ok: true });
expect(resourceScheduler.runningCount()).toBe(0);
await host.dispose();
});
+ it('does not register a build after its task is archived at the reconcile boundary', async () => {
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(async () => undefined),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore(),
+ lifecycle,
+ });
+ actor.attach({
+ sessionId: 'session-a',
+ worktreeRoot: '/tmp/session-a',
+ sourceFingerprint: 'fingerprint-a',
+ device: READY_REPORT.devices[0]!,
+ bootProvenance: 'preexisting',
+ });
+ let armed = false;
+ let armedReadCount = 0;
+ let signalFinalRead!: () => void;
+ const finalReadStarted = new Promise<void>((resolve) => {
+ signalFinalRead = resolve;
+ });
+ let resolveFinalRead!: () => void;
+ const getSession = vi.fn(async (id: string) => {
+ const snapshot = { ...localSession(id), status: 'active' as const };
+ if (armed && ++armedReadCount === 2) {
+ signalFinalRead();
+ await new Promise<void>((resolve) => {
+ resolveFinalRead = resolve;
+ });
+ }
+ return snapshot;
+ });
+ const build = vi.fn<IOSSimulatorProjectBuilderAdapter['build']>();
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession,
+ projectBuilder: { build },
+ });
+
+ await host.reconcileOwnership();
+ const instance = actor.list('session-a')[0]!;
+ armed = true;
+
+ const buildPromise = host.callTool(
+ 'build_app',
+ {
+ instanceId: instance.instanceId,
+ generation: instance.generation,
+ leaseId: instance.lease.id,
+ },
+ { sessionId: 'session-a', origin: 'user' },
+ );
+ await finalReadStarted;
+ await host.cancelSessionOperations('session-a');
+ resolveFinalRead();
+
+ await expect(buildPromise).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'MUTATION_CANCELLED',
+ });
+ expect(build).not.toHaveBeenCalled();
+ await host.dispose();
+ });
+
it('shares exact attachment and lifecycle state while rejecting another session', async () => {
const lifecycle: IOSSimulatorSimctlLifecycle = {
findExact: vi.fn(),
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator-exit.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator-exit.ts
new file mode 100644
index 0000000000..c1c4f6ffac
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator-exit.ts
@@ -0,0 +1,17 @@
+type IOSSimulatorExitAbortHandler = () => void;
+
+let exitAbortHandler: IOSSimulatorExitAbortHandler | null = null;
+
+export function registerIOSSimulatorExitAbortHandler(
+ handler: IOSSimulatorExitAbortHandler,
+): () => void {
+ exitAbortHandler = handler;
+ return () => {
+ if (exitAbortHandler === handler) exitAbortHandler = null;
+ };
+}
+
+/** Lightweight updater seam: never imports the simulator or media runtime. */
+export function abortIOSSimulatorOperationsForExit(): void {
+ exitAbortHandler?.();
+}
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator-media.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator-media.ts
index ffad33a871..a76eebf038 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator-media.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator-media.ts
@@ -17,6 +17,10 @@ import {
import { ingestMedia, type IngestedMedia } from '../cindy-media/ingest.js';
const MAX_SCREENSHOT_BYTES = 32 * 1024 * 1024;
+// cindy-media currently ingests buffers. Keep the recording ceiling bounded to
+// an amount Electron Main can safely validate and ingest without multi-GiB
+// allocations; larger captures are rejected before readFile.
+const MAX_BUFFERED_RECORDING_BYTES = 128 * 1024 * 1024;
const RECORDING_STOP_TIMEOUT_MS = 5_000;
export interface IOSSimulatorMediaCaptureOptions {
@@ -238,7 +242,7 @@ export class IOSSimulatorMediaCapture {
try {
await terminateRecordingProcess(recording.process);
const info = await stat(recording.videoPath);
- if (!info.isFile() || info.size <= 0 || info.size > 2 * 1024 ** 3) {
+ if (!info.isFile() || info.size <= 0 || info.size > MAX_BUFFERED_RECORDING_BYTES) {
throw new IOSSimulatorInstanceError(
'RECORDING_FAILED',
'The simulator recording is invalid.',
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
index 4007e724da..4c89656ba4 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
@@ -89,6 +89,7 @@ import {
verifyIOSSimulatorSidecarDigest,
} from './ios-simulator-artifact.js';
import { resolveIOSSimulatorDesktopAdmissionPolicy } from './ios-simulator-admission.js';
+import { registerIOSSimulatorExitAbortHandler } from './ios-simulator-exit.js';
import { compareIOSSimulatorPngBuffers, IOSSimulatorMediaCapture } from './ios-simulator-media.js';
const logger = createLogger('mcp/cindy_ios_simulator');
@@ -182,6 +183,10 @@ export interface IOSSimulatorHostOptions {
export interface IOSSimulatorHost {
/** Stop host-owned WDA/recording resources without changing simulator ownership. */
dispose(): Promise<void>;
+ /** Synchronously signal child process trees before updater force-quit bypasses async cleanup. */
+ abortOperationsForExit(): void;
+ /** Cancel build processes before a task is archived, deleted, or its worktree is recycled. */
+ cancelSessionOperations(sessionId: string): Promise<void>;
reconcileOwnership(): Promise<void>;
describeTools(sessionId: string): Promise<IOSSimulatorToolAvailabilityReport>;
getStatus(sessionId: string): Promise<IOSSimulatorSessionStatus>;
@@ -214,6 +219,7 @@ export interface IOSSimulatorHost {
getLatestFrame(
sessionId: string,
route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,
+ viewerWebContentsId: number,
): Promise<IOSSimulatorHostResult>;
setViewerStreamProfile(
sessionId: string,
@@ -728,6 +734,19 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
const pendingBuildDiagnosticRemoval = new Map<string, BuildDiagnosticRecord>();
let buildResultBundlesReconciled = false;
let buildResultBundlesReconcilePromise: Promise<void> | null = null;
+ type ActiveBuild = {
+ sessionId: string;
+ controller: AbortController;
+ settled: Promise<void>;
+ resolveSettled: () => void;
+ };
+ const activeBuilds = new Map<string, ActiveBuild>();
+ const sessionBuildAdmissionEpochs = new Map<string, number>();
+ const blockedBuildInstances = new Set<string>();
+ const instanceLifecycleBarriers = new Map<
+ string,
+ { epoch: number; pendingTeardowns: number }
+ >();
const mediaCapture = options.mediaCapture ?? new IOSSimulatorMediaCapture();
const visualBaselines = new Map<
string,
@@ -803,6 +822,107 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
errorCode: 'IOS_SIMULATOR_HOST_ERROR',
message: 'The iOS Simulator host is shutting down.',
});
+ function beginBuild(instance: IOSSimulatorInstance, expectedSessionEpoch: number): ActiveBuild {
+ if (disposePromise) throw new IOSSimulatorHostDisposedError();
+ if ((sessionBuildAdmissionEpochs.get(instance.sessionId) ?? 0) !== expectedSessionEpoch) {
+ throw new IOSSimulatorInstanceError(
+ 'MUTATION_CANCELLED',
+ 'The app build was cancelled because its Cindy task lifecycle changed.',
+ true,
+ );
+ }
+ if (blockedBuildInstances.has(instance.instanceId)) {
+ throw new IOSSimulatorInstanceError(
+ 'MUTATION_CANCELLED',
+ 'The app build was cancelled because the simulator lifecycle is changing.',
+ true,
+ );
+ }
+ if (activeBuilds.has(instance.instanceId)) {
+ throw new IOSSimulatorInstanceError(
+ 'DEVICE_BUSY',
+ 'This simulator already has an app build in progress.',
+ true,
+ );
+ }
+ let resolveSettled: () => void = () => undefined;
+ const settled = new Promise<void>((resolve) => {
+ resolveSettled = resolve;
+ });
+ const build: ActiveBuild = {
+ sessionId: instance.sessionId,
+ controller: new AbortController(),
+ settled,
+ resolveSettled,
+ };
+ activeBuilds.set(instance.instanceId, build);
+ return build;
+ }
+ function finishBuild(instanceId: string, build: ActiveBuild): void {
+ if (activeBuilds.get(instanceId) === build) activeBuilds.delete(instanceId);
+ build.resolveSettled();
+ }
+ async function cancelBuild(instanceId: string): Promise<void> {
+ const build = activeBuilds.get(instanceId);
+ if (!build) return;
+ build.controller.abort();
+ await build.settled;
+ }
+ async function cancelSessionBuilds(sessionId: string): Promise<void> {
+ sessionBuildAdmissionEpochs.set(
+ sessionId,
+ (sessionBuildAdmissionEpochs.get(sessionId) ?? 0) + 1,
+ );
+ const builds = [...activeBuilds.entries()].filter(([, build]) => build.sessionId === sessionId);
+ for (const [, build] of builds) build.controller.abort();
+ await Promise.all(builds.map(([, build]) => build.settled));
+ }
+ function lifecycleBarrier(instanceId: string): { epoch: number; pendingTeardowns: number } {
+ return instanceLifecycleBarriers.get(instanceId) ?? { epoch: 0, pendingTeardowns: 0 };
+ }
+ function beginInstanceTeardown(instanceId: string): void {
+ const current = lifecycleBarrier(instanceId);
+ instanceLifecycleBarriers.set(instanceId, {
+ epoch: current.epoch + 1,
+ pendingTeardowns: current.pendingTeardowns + 1,
+ });
+ blockedBuildInstances.add(instanceId);
+ }
+ function finishInstanceTeardown(instanceId: string): void {
+ const current = lifecycleBarrier(instanceId);
+ instanceLifecycleBarriers.set(instanceId, {
+ epoch: current.epoch,
+ pendingTeardowns: Math.max(0, current.pendingTeardowns - 1),
+ });
+ }
+ function captureInstanceActivation(instanceId: string): number {
+ const current = lifecycleBarrier(instanceId);
+ if (current.pendingTeardowns > 0) {
+ throw new IOSSimulatorInstanceError(
+ 'MUTATION_CANCELLED',
+ 'The simulator cannot be activated while its lifecycle is changing.',
+ true,
+ );
+ }
+ return current.epoch;
+ }
+ function completeInstanceActivation(instance: IOSSimulatorInstance, expectedEpoch: number): void {
+ const current = lifecycleBarrier(instance.instanceId);
+ if (current.epoch !== expectedEpoch || current.pendingTeardowns > 0) {
+ throw new IOSSimulatorInstanceError(
+ 'MUTATION_CANCELLED',
+ 'The simulator activation was cancelled because its lifecycle changed.',
+ true,
+ );
+ }
+ actor.assertRoute({
+ sessionId: instance.sessionId,
+ instanceId: instance.instanceId,
+ generation: instance.generation,
+ leaseId: instance.lease.id,
+ });
+ blockedBuildInstances.delete(instance.instanceId);
+ }
function managedBuildResultsRoot(): string {
return path.join(app.getPath('userData'), 'ios-simulator', 'projects');
}
@@ -1321,33 +1441,39 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
}
async function releaseExternallyStoppedRuntime(instance: IOSSimulatorInstance): Promise<void> {
- cancelIdleRecycle(instance.instanceId);
- framePump.clear(instance.instanceId);
- h264FramePump.clear(instance.instanceId);
- viewerEncodings.delete(instance.instanceId);
- viewerPreferredEncodings.delete(instance.instanceId);
- viewerFallbackReasons.delete(instance.instanceId);
- viewerSessions.delete(instance.instanceId);
- streamProfiles.delete(instance.instanceId);
- nativeStreamProfiles.delete(instance.instanceId);
- clearViewportState(instance.instanceId);
- screenMaps.clear(instance.instanceId);
- clearVisualBaselines(instance.instanceId);
- await mediaCapture.discardInstance(instance.instanceId).catch((error) => {
- logger.warn('iOS Simulator external stop could not discard recording', {
- instanceId: instance.instanceId,
- error: error instanceof Error ? error.message : String(error),
- });
- });
- if (driverManager) {
- await driverManager.stop(instance.instanceId).catch((error) => {
- logger.warn('iOS Simulator external stop could not stop driver runtime', {
+ beginInstanceTeardown(instance.instanceId);
+ try {
+ await cancelBuild(instance.instanceId);
+ cancelIdleRecycle(instance.instanceId);
+ framePump.clear(instance.instanceId);
+ h264FramePump.clear(instance.instanceId);
+ viewerEncodings.delete(instance.instanceId);
+ viewerPreferredEncodings.delete(instance.instanceId);
+ viewerFallbackReasons.delete(instance.instanceId);
+ viewerSessions.delete(instance.instanceId);
+ streamProfiles.delete(instance.instanceId);
+ nativeStreamProfiles.delete(instance.instanceId);
+ clearViewportState(instance.instanceId);
+ screenMaps.clear(instance.instanceId);
+ clearVisualBaselines(instance.instanceId);
+ await mediaCapture.discardInstance(instance.instanceId).catch((error) => {
+ logger.warn('iOS Simulator external stop could not discard recording', {
instanceId: instance.instanceId,
error: error instanceof Error ? error.message : String(error),
});
});
+ if (driverManager) {
+ await driverManager.stop(instance.instanceId).catch((error) => {
+ logger.warn('iOS Simulator external stop could not stop driver runtime', {
+ instanceId: instance.instanceId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+ }
+ resourceScheduler.markStopped(instance.instanceId);
+ } finally {
+ finishInstanceTeardown(instance.instanceId);
}
- resourceScheduler.markStopped(instance.instanceId);
}
async function reconcileLiveDevice(
@@ -1600,31 +1726,37 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
}
};
const releaseInstanceRuntime = async (instance: IOSSimulatorInstance): Promise<boolean> => {
- cancelIdleRecycle(instance.instanceId);
- framePump.clear(instance.instanceId);
- h264FramePump.clear(instance.instanceId);
- viewerEncodings.delete(instance.instanceId);
- viewerPreferredEncodings.delete(instance.instanceId);
- viewerFallbackReasons.delete(instance.instanceId);
- viewerSessions.delete(instance.instanceId);
- clearViewportState(instance.instanceId);
- streamProfiles.delete(instance.instanceId);
- nativeStreamProfiles.delete(instance.instanceId);
- let cleanupSucceeded = await discardInstanceMedia(instance);
- let driverCleanupSucceeded = true;
- if (driverManager) {
- await driverManager.stop(instance.instanceId).catch((error) => {
- driverCleanupSucceeded = false;
- cleanupSucceeded = false;
- complete = false;
- logger.warn('iOS Simulator ownership reconcile could not stop driver runtime', {
- instanceId: instance.instanceId,
- error: error instanceof Error ? error.message : String(error),
+ beginInstanceTeardown(instance.instanceId);
+ try {
+ await cancelBuild(instance.instanceId);
+ cancelIdleRecycle(instance.instanceId);
+ framePump.clear(instance.instanceId);
+ h264FramePump.clear(instance.instanceId);
+ viewerEncodings.delete(instance.instanceId);
+ viewerPreferredEncodings.delete(instance.instanceId);
+ viewerFallbackReasons.delete(instance.instanceId);
+ viewerSessions.delete(instance.instanceId);
+ clearViewportState(instance.instanceId);
+ streamProfiles.delete(instance.instanceId);
+ nativeStreamProfiles.delete(instance.instanceId);
+ let cleanupSucceeded = await discardInstanceMedia(instance);
+ let driverCleanupSucceeded = true;
+ if (driverManager) {
+ await driverManager.stop(instance.instanceId).catch((error) => {
+ driverCleanupSucceeded = false;
+ cleanupSucceeded = false;
+ complete = false;
+ logger.warn('iOS Simulator ownership reconcile could not stop driver runtime', {
+ instanceId: instance.instanceId,
+ error: error instanceof Error ? error.message : String(error),
+ });
});
- });
+ }
+ if (driverCleanupSucceeded) resourceScheduler.markStopped(instance.instanceId);
+ return cleanupSucceeded;
+ } finally {
+ finishInstanceTeardown(instance.instanceId);
}
- if (driverCleanupSucceeded) resourceScheduler.markStopped(instance.instanceId);
- return cleanupSucceeded;
};
const releaseStaleBinding = async (
instance: IOSSimulatorInstance,
@@ -2775,12 +2907,25 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
return safeHostError(error, sessionId, 'set_viewer_visibility');
}
},
- async getLatestFrame(sessionId, route) {
+ async getLatestFrame(sessionId, route, viewerWebContentsId) {
try {
assertHostActive();
const resolved = await resolveSession(sessionId);
if (!resolved.ok) return resolved;
assertHostActive();
+ const viewer = viewerSessions.get(route.instanceId);
+ if (
+ !viewer ||
+ viewer.sessionId !== resolved.sessionId ||
+ viewer.webContentsId === null ||
+ viewer.webContentsId !== viewerWebContentsId
+ ) {
+ return {
+ ok: false,
+ errorCode: 'INSTANCE_NOT_OWNED',
+ message: 'This simulator viewer is not owned by the current Cindy window.',
+ };
+ }
let instance = actor.heartbeat({ ...route, sessionId: resolved.sessionId });
instance = await reconcileLiveDevice(instance);
assertHostActive();
@@ -3060,6 +3205,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
if (name === 'start_instance') {
const route = readMutationRoute(sessionId, args);
requireControlGrant(actor.getOwned(sessionId, route.instanceId), context);
+ const activationEpoch = captureInstanceActivation(route.instanceId);
const environment = await runtime.inspect();
if (!environment.ready) {
const safeEnvironment = publicEnvironment(environment);
@@ -3075,6 +3221,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
await ensureDriver(started, environment);
return actor.heartbeatOwned(sessionId, started.instanceId);
});
+ completeInstanceActivation(instance, activationEpoch);
screenMaps.clear(instance.instanceId);
framePump.clear(instance.instanceId);
h264FramePump.clear(instance.instanceId);
@@ -3094,49 +3241,61 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
const route = readMutationRoute(sessionId, args);
requireControlGrant(actor.getOwned(sessionId, route.instanceId), context);
actor.assertRoute(route);
- cancelIdleRecycle(route.instanceId);
- await mediaCapture.discardInstance(route.instanceId);
- clearVisualBaselines(route.instanceId);
- await getDriverManager().stop(route.instanceId);
- resourceScheduler.markStopped(route.instanceId);
- screenMaps.clear(route.instanceId);
- framePump.clear(route.instanceId);
- h264FramePump.clear(route.instanceId);
- viewerEncodings.delete(route.instanceId);
- viewerPreferredEncodings.delete(route.instanceId);
- viewerFallbackReasons.delete(route.instanceId);
- viewerSessions.delete(route.instanceId);
- clearViewportState(route.instanceId);
- const stopped = await actor.stop(route);
- publishRouteStatusForInstance(stopped, null);
- return {
- ok: true,
- data: instanceData(stopped),
- };
+ beginInstanceTeardown(route.instanceId);
+ try {
+ await cancelBuild(route.instanceId);
+ cancelIdleRecycle(route.instanceId);
+ await mediaCapture.discardInstance(route.instanceId);
+ clearVisualBaselines(route.instanceId);
+ await getDriverManager().stop(route.instanceId);
+ resourceScheduler.markStopped(route.instanceId);
+ screenMaps.clear(route.instanceId);
+ framePump.clear(route.instanceId);
+ h264FramePump.clear(route.instanceId);
+ viewerEncodings.delete(route.instanceId);
+ viewerPreferredEncodings.delete(route.instanceId);
+ viewerFallbackReasons.delete(route.instanceId);
+ viewerSessions.delete(route.instanceId);
+ clearViewportState(route.instanceId);
+ const stopped = await actor.stop(route);
+ publishRouteStatusForInstance(stopped, null);
+ return {
+ ok: true,
+ data: instanceData(stopped),
+ };
+ } finally {
+ finishInstanceTeardown(route.instanceId);
+ }
}
if (name === 'detach_device') {
const route = readMutationRoute(sessionId, args);
requireControlGrant(actor.getOwned(sessionId, route.instanceId), context);
actor.assertRoute(route);
- cancelIdleRecycle(route.instanceId);
- await mediaCapture.discardInstance(route.instanceId);
- clearVisualBaselines(route.instanceId);
- await getDriverManager().stop(route.instanceId);
- screenMaps.clear(route.instanceId);
- framePump.clear(route.instanceId);
- h264FramePump.clear(route.instanceId);
- viewerEncodings.delete(route.instanceId);
- viewerPreferredEncodings.delete(route.instanceId);
- viewerFallbackReasons.delete(route.instanceId);
- viewerSessions.delete(route.instanceId);
- clearViewportState(route.instanceId);
- agentControlLeases.delete(route.instanceId);
- return {
- ok: true,
- data: instanceData(
- await actor.detach(route, () => resourceScheduler.markStopped(route.instanceId)),
- ),
- };
+ beginInstanceTeardown(route.instanceId);
+ try {
+ await cancelBuild(route.instanceId);
+ cancelIdleRecycle(route.instanceId);
+ await mediaCapture.discardInstance(route.instanceId);
+ clearVisualBaselines(route.instanceId);
+ await getDriverManager().stop(route.instanceId);
+ screenMaps.clear(route.instanceId);
+ framePump.clear(route.instanceId);
+ h264FramePump.clear(route.instanceId);
+ viewerEncodings.delete(route.instanceId);
+ viewerPreferredEncodings.delete(route.instanceId);
+ viewerFallbackReasons.delete(route.instanceId);
+ viewerSessions.delete(route.instanceId);
+ clearViewportState(route.instanceId);
+ agentControlLeases.delete(route.instanceId);
+ return {
+ ok: true,
+ data: instanceData(
+ await actor.detach(route, () => resourceScheduler.markStopped(route.instanceId)),
+ ),
+ };
+ } finally {
+ finishInstanceTeardown(route.instanceId);
+ }
}
if (name === 'get_screen_map') {
const route = readMutationRoute(sessionId, args);
@@ -4002,91 +4161,133 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
return { ok: true, data: { interaction: name, screenMapInvalidated: true } };
}
if (name === 'build_app') {
- const route = readMutationRoute(sessionId, args);
+ // Revalidate immediately before registering the build. The shared
+ // ownership reconciliation above can yield long enough for the task
+ // to be archived and its worktree recycled. There must be no await
+ // between this check and beginBuild: if archival wins first this
+ // call fails closed; if beginBuild wins first archival observes and
+ // cancels the registered operation.
+ const buildAdmissionEpoch = sessionBuildAdmissionEpochs.get(sessionId) ?? 0;
+ const buildSession = await resolveSession(sessionId);
+ if (!buildSession.ok) return buildSession;
+ assertHostActive();
+ const route = readMutationRoute(buildSession.sessionId, args);
const instance = actor.assertRoute(route);
+ const activeBuild = beginBuild(instance, buildAdmissionEpoch);
const derivedDataPath = path.join(
app.getPath('userData'),
'ios-simulator',
'projects',
createHash('sha256').update(instance.instanceId).digest('hex').slice(0, 20),
);
- let built: IOSSimulatorProjectBuildResult;
try {
- built = await projectBuilder.build({
- worktreeRoot: instance.worktreeRoot,
- derivedDataPath,
- containerPath: readOptionalString(args, 'containerPath', 4_096),
- scheme: typeof args.scheme === 'string' ? args.scheme : undefined,
- });
- } catch (error) {
- if (!(error instanceof IOSSimulatorProjectBuildError)) throw error;
+ let built: IOSSimulatorProjectBuildResult;
+ try {
+ built = await projectBuilder.build({
+ worktreeRoot: instance.worktreeRoot,
+ derivedDataPath,
+ containerPath: readOptionalString(args, 'containerPath', 4_096),
+ scheme: typeof args.scheme === 'string' ? args.scheme : undefined,
+ signal: activeBuild.controller.signal,
+ });
+ } catch (error) {
+ if (disposePromise) {
+ await discardManagedBuildResultBundle(
+ error instanceof IOSSimulatorProjectBuildError ? error.resultBundlePath : null,
+ );
+ throw new IOSSimulatorHostDisposedError();
+ }
+ if (activeBuild.controller.signal.aborted) {
+ throw new IOSSimulatorInstanceError(
+ 'MUTATION_CANCELLED',
+ 'The app build was cancelled because its simulator session ended.',
+ true,
+ );
+ }
+ if (!(error instanceof IOSSimulatorProjectBuildError)) throw error;
+ const diagnostics = await storeBuildDiagnostics({
+ sessionId: instance.sessionId,
+ instanceId: instance.instanceId,
+ logTail: error.buildLogTail,
+ resultBundlePath: error.resultBundlePath,
+ outputTruncated: error.outputTruncated,
+ });
+ return buildFailureWithDiagnostics(error, sessionId, diagnostics);
+ }
if (disposePromise) {
- await discardManagedBuildResultBundle(error.resultBundlePath);
+ await discardManagedBuildResultBundle(built.resultBundlePath ?? null);
throw new IOSSimulatorHostDisposedError();
}
+ if (activeBuild.controller.signal.aborted) {
+ await discardManagedBuildResultBundle(built.resultBundlePath ?? null);
+ throw new IOSSimulatorInstanceError(
+ 'MUTATION_CANCELLED',
+ 'The app build was cancelled because its simulator session ended.',
+ true,
+ );
+ }
+ actor.assertRoute(route);
const diagnostics = await storeBuildDiagnostics({
sessionId: instance.sessionId,
instanceId: instance.instanceId,
- logTail: error.buildLogTail,
- resultBundlePath: error.resultBundlePath,
- outputTruncated: error.outputTruncated,
+ logTail: built.buildLogTail ?? '',
+ resultBundlePath: built.resultBundlePath ?? null,
+ outputTruncated: built.outputTruncated,
});
- return buildFailureWithDiagnostics(error, sessionId, diagnostics);
- }
- if (disposePromise) {
- await discardManagedBuildResultBundle(built.resultBundlePath ?? null);
- throw new IOSSimulatorHostDisposedError();
- }
- const diagnostics = await storeBuildDiagnostics({
- sessionId: instance.sessionId,
- instanceId: instance.instanceId,
- logTail: built.buildLogTail ?? '',
- resultBundlePath: built.resultBundlePath ?? null,
- outputTruncated: built.outputTruncated,
- });
- assertHostActive();
- let artifact: IOSSimulatorAppArtifact;
- try {
+ assertHostActive();
+ let artifact: IOSSimulatorAppArtifact;
try {
- artifact = await appLifecycle.inspectArtifact(instance.worktreeRoot, built.appPath);
+ try {
+ artifact = await appLifecycle.inspectArtifact(instance.worktreeRoot, built.appPath);
+ } catch (error) {
+ if (
+ !(error instanceof IOSSimulatorInstanceError) ||
+ error.code !== 'APP_ARTIFACT_INVALID'
+ ) {
+ throw error;
+ }
+ artifact = await appLifecycle.inspectArtifact(
+ instance.worktreeRoot,
+ built.appPath,
+ derivedDataPath,
+ );
+ }
} catch (error) {
- if (
- !(error instanceof IOSSimulatorInstanceError) ||
- error.code !== 'APP_ARTIFACT_INVALID'
- ) {
- throw error;
+ if (disposePromise || error instanceof IOSSimulatorHostDisposedError) {
+ throw new IOSSimulatorHostDisposedError();
}
- artifact = await appLifecycle.inspectArtifact(
- instance.worktreeRoot,
- built.appPath,
- derivedDataPath,
- );
+ return buildFailureWithDiagnostics(error, sessionId, diagnostics);
}
- } catch (error) {
- if (disposePromise || error instanceof IOSSimulatorHostDisposedError) {
- throw new IOSSimulatorHostDisposedError();
+ assertHostActive();
+ if (activeBuild.controller.signal.aborted) {
+ throw new IOSSimulatorInstanceError(
+ 'MUTATION_CANCELLED',
+ 'The app build was cancelled because its simulator session ended.',
+ true,
+ );
}
- return buildFailureWithDiagnostics(error, sessionId, diagnostics);
- }
- assertHostActive();
- appArtifacts.set(artifact.artifactId, {
- instanceId: instance.instanceId,
- projectKind: built.kind,
- artifact,
- });
- return {
- ok: true,
- data: {
- artifact: {
- artifactId: artifact.artifactId,
- bundleId: artifact.bundleId,
- projectKind: built.kind,
- scheme: built.scheme,
- createdAt: artifact.createdAt,
+ actor.assertRoute(route);
+ appArtifacts.set(artifact.artifactId, {
+ instanceId: instance.instanceId,
+ projectKind: built.kind,
+ artifact,
+ });
+ return {
+ ok: true,
+ data: {
+ artifact: {
+ artifactId: artifact.artifactId,
+ bundleId: artifact.bundleId,
+ projectKind: built.kind,
+ scheme: built.scheme,
+ createdAt: artifact.createdAt,
+ },
+ diagnostics,
},
- diagnostics,
- },
- };
+ };
+ } finally {
+ finishBuild(instance.instanceId, activeBuild);
+ }
}
if (name === 'read_build_diagnostics') {
const diagnosticsId = readString(args, 'diagnosticsId');
@@ -4514,35 +4715,53 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
'The selected iOS Simulator device does not exist or is unavailable.',
);
}
- const worktreeRoot = await resolveWorktreeRoot(resolved.session.workDir);
- const instance = await actor.attachSerialized({
- sessionId,
- worktreeRoot,
- sourceFingerprint: sourceFingerprint(worktreeRoot),
- device,
- creationProvenance: 'external',
- bootProvenance: device.state.toLowerCase() === 'booted' ? 'preexisting' : 'user-booted',
- });
- if (context?.origin === 'agent') {
- agentControlLeases.set(instance.instanceId, sessionId);
- }
- if (instance.lifecycleState === 'ready') {
- await resourceScheduler.runStart(instance.instanceId, async () => {
- await ensureDriver(instance, environment);
+ const existingInstance = actor
+ .listAll()
+ .find((candidate) => candidate.simulatorUdid.toUpperCase() === udid);
+ const existingActivationEpoch = existingInstance
+ ? captureInstanceActivation(existingInstance.instanceId)
+ : null;
+ const attach = async (): Promise<IOSSimulatorHostResult> => {
+ assertHostActive();
+ const worktreeRoot = await resolveWorktreeRoot(resolved.session.workDir);
+ const instance = await actor.attachSerialized({
+ sessionId,
+ worktreeRoot,
+ sourceFingerprint: sourceFingerprint(worktreeRoot),
+ device,
+ creationProvenance: 'external',
+ bootProvenance:
+ device.state.toLowerCase() === 'booted' ? 'preexisting' : 'user-booted',
});
- }
- screenMaps.clear(instance.instanceId);
- framePump.clear(instance.instanceId);
- h264FramePump.clear(instance.instanceId);
- viewerEncodings.delete(instance.instanceId);
- viewerPreferredEncodings.delete(instance.instanceId);
- viewerFallbackReasons.delete(instance.instanceId);
- viewerSessions.delete(instance.instanceId);
- clearViewportState(instance.instanceId);
- return {
- ok: true,
- data: instanceData(actor.getOwned(sessionId, instance.instanceId)),
+ const activationEpoch =
+ existingInstance?.instanceId === instance.instanceId &&
+ existingActivationEpoch !== null
+ ? existingActivationEpoch
+ : captureInstanceActivation(instance.instanceId);
+ if (instance.lifecycleState === 'ready') {
+ await resourceScheduler.runStart(instance.instanceId, async () => {
+ await ensureDriver(instance, environment);
+ });
+ }
+ const current = actor.getOwned(sessionId, instance.instanceId);
+ completeInstanceActivation(current, activationEpoch);
+ if (context?.origin === 'agent') {
+ agentControlLeases.set(instance.instanceId, sessionId);
+ }
+ screenMaps.clear(instance.instanceId);
+ framePump.clear(instance.instanceId);
+ h264FramePump.clear(instance.instanceId);
+ viewerEncodings.delete(instance.instanceId);
+ viewerPreferredEncodings.delete(instance.instanceId);
+ viewerFallbackReasons.delete(instance.instanceId);
+ viewerSessions.delete(instance.instanceId);
+ clearViewportState(instance.instanceId);
+ return {
+ ok: true,
+ data: instanceData(current),
+ };
};
+ return await attach();
}
return {
ok: false,
@@ -4554,9 +4773,18 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
return safeHostError(error, sessionId, name);
}
},
+ cancelSessionOperations(sessionId) {
+ return cancelSessionBuilds(sessionId.trim());
+ },
+ abortOperationsForExit() {
+ for (const build of activeBuilds.values()) build.controller.abort();
+ },
dispose() {
if (disposePromise) return disposePromise;
disposePromise = (async () => {
+ const builds = [...activeBuilds.values()];
+ for (const build of builds) build.controller.abort();
+ await Promise.all(builds.map((build) => build.settled));
clearVisualBaselines();
await Promise.all(
[...buildDiagnostics.entries()].map(([diagnosticsId, diagnostic]) =>
@@ -4608,6 +4836,9 @@ const defaultIOSSimulatorHost = createIOSSimulatorHost({
lifecycle: defaultIOSSimulatorLifecycle,
actor: createDefaultActor(defaultIOSSimulatorLifecycle),
});
+const releaseIOSSimulatorExitAbortHandler = registerIOSSimulatorExitAbortHandler(() => {
+ defaultIOSSimulatorHost.abortOperationsForExit();
+});
export function getIOSSimulatorSessionStatus(
sessionId: string,
@@ -4668,8 +4899,9 @@ export function setIOSSimulatorAgentMutationPaused(
export function getIOSSimulatorLatestFrame(
sessionId: string,
route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,
+ viewerWebContentsId: number,
): Promise<IOSSimulatorHostResult> {
- return defaultIOSSimulatorHost.getLatestFrame(sessionId, route);
+ return defaultIOSSimulatorHost.getLatestFrame(sessionId, route, viewerWebContentsId);
}
export async function flushIOSSimulatorOwnershipRegistry(): Promise<void> {
@@ -4685,10 +4917,15 @@ export async function disposeIOSSimulatorHost(): Promise<void> {
await defaultIOSSimulatorHost.dispose();
await defaultRegistryFlush?.();
} finally {
+ releaseIOSSimulatorExitAbortHandler();
defaultRegistryRelease?.();
}
}
+export function cancelIOSSimulatorSessionOperations(sessionId: string): Promise<void> {
+ return defaultIOSSimulatorHost.cancelSessionOperations(sessionId);
+}
+
export function setIOSSimulatorViewerStreamProfile(
sessionId: string,
route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,
@@ -4712,7 +4949,7 @@ export function updateIOSSimulatorViewerTouch(
}
export interface IOSSimulatorMcpDepsOptions {
- isIOSSimulatorEnabled?: () => boolean;
+ isIOSSimulatorEnabled?: (context?: IOSSimulatorMcpCallContext) => boolean;
host?: IOSSimulatorHost;
}
@@ -4734,7 +4971,7 @@ export function getIOSSimulatorMcpDeps(
},
};
}
- if (options.isIOSSimulatorEnabled && !options.isIOSSimulatorEnabled()) {
+ if (options.isIOSSimulatorEnabled && !options.isIOSSimulatorEnabled(context)) {
return {
ready: false,
instanceCount: 0,
@@ -4748,7 +4985,7 @@ export function getIOSSimulatorMcpDeps(
return host.describeTools(sessionId);
},
callTool: async (name, args, context) => {
- if (options.isIOSSimulatorEnabled && !options.isIOSSimulatorEnabled()) {
+ if (options.isIOSSimulatorEnabled && !options.isIOSSimulatorEnabled(context)) {
return {
ok: false,
errorCode: 'IOS_SIMULATOR_DISABLED',
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index 217671f678..147f10d75e 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -90,7 +90,8 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
// Project-scoped gating is applied by the provider wrapper below using
// the live MCP session context. This host-level check preserves the
// existing global fallback for non-session callers.
- isIOSSimulatorEnabled: () => pluginRegistry.isEnabled('ios-simulator'),
+ isIOSSimulatorEnabled: (context) =>
+ pluginRegistry.isEnabled('ios-simulator', context?.workingDir),
}),
browser: getBrowserMcpDeps(),
computer: getComputerMcpDeps({
diff --git a/apps/desktop/src/main/updateService.ts b/apps/desktop/src/main/updateService.ts
index 97c25ef06e..c368410441 100644
--- a/apps/desktop/src/main/updateService.ts
+++ b/apps/desktop/src/main/updateService.ts
@@ -49,6 +49,7 @@ import { throwIpcError } from './utils/ipcValidate';
import { noteExpectedExit } from './startup-diagnostics';
import { buildMacOSUpdateScript } from './updateScriptMacOS';
import { disposeAndroidAdb } from './mcp-integrations/android';
+import { abortIOSSimulatorOperationsForExit } from './mcp-integrations/ios-simulator-exit';
import { getGhostNodeRuntimeBroker } from './cindy-brain/index';
import { cleanOldUpdateFiles } from './updateArtifacts';
@@ -1015,6 +1016,9 @@ function forceQuit(): void {
// 绕过 onQuit 链意味着 disposeAndroidAdb 不会被自动调用——显式 fire-and-forget
// 收掉自带 adb server,避免它锁住安装目录阻碍 updater 替换文件。
disposeAndroidAdb();
+ // build_app uses detached process groups, so parent exit does not reliably
+ // reap xcodebuild. Abort synchronously before process.exit bypasses Host dispose.
+ abortIOSSimulatorOperationsForExit();
// Node 子进程同理——before-quit 的 destroyAll 不会触发,这里同步 kill。
try { getGhostNodeRuntimeBroker().destroyAll(); } catch { /* best-effort */ }
for (const win of BrowserWindow.getAllWindows()) {
diff --git a/packages/ios-simulator-runtime/src/command-runner.test.ts b/packages/ios-simulator-runtime/src/command-runner.test.ts
index 0a8daf937f..e2148a9c99 100644
--- a/packages/ios-simulator-runtime/src/command-runner.test.ts
+++ b/packages/ios-simulator-runtime/src/command-runner.test.ts
@@ -1,7 +1,21 @@
-import { describe, expect, it } from "vitest";
+import { mkdtemp, readFile, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+import { afterEach, describe, expect, it } from "vitest";
import { createNodeIOSSimulatorCommandRunner } from "./command-runner.js";
+const tempRoots: string[] = [];
+
+afterEach(async () => {
+ await Promise.all(
+ tempRoots
+ .splice(0)
+ .map((root) => rm(root, { recursive: true, force: true })),
+ );
+});
+
describe("createNodeIOSSimulatorCommandRunner", () => {
it("keeps draining a successful process after the output buffer fills", async () => {
const result = await createNodeIOSSimulatorCommandRunner().run(
@@ -25,4 +39,38 @@ describe("createNodeIOSSimulatorCommandRunner", () => {
Buffer.byteLength(result.stdout) + Buffer.byteLength(result.stderr),
).toBeLessThanOrEqual(128);
});
+
+ it.runIf(process.platform !== "win32")(
+ "kills the detached process group when a build is aborted",
+ async () => {
+ const root = await mkdtemp(
+ path.join(os.tmpdir(), "cindy-command-abort-"),
+ );
+ tempRoots.push(root);
+ const markerPath = path.join(root, "late-child.txt");
+ const controller = new AbortController();
+ const resultPromise = createNodeIOSSimulatorCommandRunner().run(
+ process.execPath,
+ [
+ "-e",
+ [
+ "const { spawn } = require('node:child_process');",
+ `spawn(process.execPath, ['-e', ${JSON.stringify(
+ `setTimeout(() => require('node:fs').writeFileSync(${JSON.stringify(markerPath)}, 'late'), 500)`,
+ )}], { stdio: 'ignore' });`,
+ "setInterval(() => undefined, 1000);",
+ ].join("\n"),
+ ],
+ { timeoutMs: 5_000, signal: controller.signal },
+ );
+
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ controller.abort();
+ await expect(resultPromise).resolves.toMatchObject({ exitCode: null });
+ await new Promise((resolve) => setTimeout(resolve, 650));
+ await expect(readFile(markerPath, "utf8")).rejects.toMatchObject({
+ code: "ENOENT",
+ });
+ },
+ );
});
diff --git a/packages/ios-simulator-runtime/src/command-runner.ts b/packages/ios-simulator-runtime/src/command-runner.ts
index fd4d5ff17d..4e7f98bfa1 100644
--- a/packages/ios-simulator-runtime/src/command-runner.ts
+++ b/packages/ios-simulator-runtime/src/command-runner.ts
@@ -12,6 +12,9 @@ const DEFAULT_MAX_BUFFER_BYTES = 16 * 1024 * 1024;
export function createNodeIOSSimulatorCommandRunner(): IOSSimulatorCommandRunner {
return {
run(command, args, options = {}): Promise<IOSSimulatorCommandResult> {
+ if (options.signal?.aborted) {
+ return Promise.resolve({ stdout: "", stderr: "", exitCode: null });
+ }
return new Promise((resolve) => {
const child = spawn(command, [...args], {
cwd: options.cwd,
@@ -30,6 +33,14 @@ export function createNodeIOSSimulatorCommandRunner(): IOSSimulatorCommandRunner
let outputTruncated = false;
let settled = false;
let timedOut = false;
+ let aborted = false;
+ const onAbort = () => {
+ if (settled || aborted) return;
+ aborted = true;
+ killProcessTree(child, "SIGKILL");
+ };
+ options.signal?.addEventListener("abort", onAbort, { once: true });
+ if (options.signal?.aborted) onAbort();
let timer: ReturnType<typeof setTimeout> | null = setTimeout(() => {
timedOut = true;
killProcessTree(child);
@@ -42,6 +53,7 @@ export function createNodeIOSSimulatorCommandRunner(): IOSSimulatorCommandRunner
if (settled) return;
settled = true;
if (timer) clearTimeout(timer);
+ options.signal?.removeEventListener("abort", onAbort);
const stdout = chunks
.filter((chunk) => chunk.stream === "stdout")
.map((chunk) => chunk.bytes);
@@ -80,21 +92,26 @@ export function createNodeIOSSimulatorCommandRunner(): IOSSimulatorCommandRunner
child.stdout?.on("data", (chunk: Buffer) => append("stdout", chunk));
child.stderr?.on("data", (chunk: Buffer) => append("stderr", chunk));
child.once("error", () => finish(null));
- child.once("close", (code) => finish(timedOut ? null : code));
+ child.once("close", (code) =>
+ finish(timedOut || aborted ? null : code),
+ );
});
},
};
}
-function killProcessTree(child: ReturnType<typeof spawn>): void {
+function killProcessTree(
+ child: ReturnType<typeof spawn>,
+ signal: NodeJS.Signals = "SIGTERM",
+): void {
if (!child.pid) return;
if (process.platform !== "win32") {
try {
- process.kill(-child.pid, "SIGTERM");
+ process.kill(-child.pid, signal);
return;
} catch {
// The process group may have already exited; fall back to the child.
}
}
- child.kill("SIGTERM");
+ child.kill(signal);
}
diff --git a/packages/ios-simulator-runtime/src/project-adapter.test.ts b/packages/ios-simulator-runtime/src/project-adapter.test.ts
index dcf9ad3981..8f20c117b6 100644
--- a/packages/ios-simulator-runtime/src/project-adapter.test.ts
+++ b/packages/ios-simulator-runtime/src/project-adapter.test.ts
@@ -15,6 +15,7 @@ import {
IOSSimulatorProjectBuildError,
IOSSimulatorProjectBuilder,
} from "./project-adapter.js";
+import type { IOSSimulatorCommandRunner } from "./types.js";
const roots: string[] = [];
afterEach(async () => {
@@ -388,4 +389,64 @@ describe("IOSSimulatorProjectBuilder", () => {
outputTruncated: true,
});
});
+
+ it("cancels an in-flight Xcode build before running later build steps", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-project-"));
+ roots.push(root);
+ await mkdir(path.join(root, "Example.xcworkspace"));
+ const controller = new AbortController();
+ let resultBundlePath = "";
+ const run = vi.fn(
+ async (
+ _command: string,
+ args: readonly string[],
+ options?: Parameters<IOSSimulatorCommandRunner["run"]>[2],
+ ) => {
+ if (args.includes("-list")) {
+ return {
+ stdout: JSON.stringify({ workspace: { schemes: ["Example"] } }),
+ stderr: "",
+ exitCode: 0,
+ };
+ }
+ const resultBundleIndex = args.indexOf("-resultBundlePath");
+ if (resultBundleIndex >= 0) {
+ resultBundlePath = args[resultBundleIndex + 1]!;
+ await mkdir(resultBundlePath, { recursive: true });
+ await new Promise<void>((resolve) => {
+ if (options?.signal?.aborted) resolve();
+ else
+ options?.signal?.addEventListener("abort", () => resolve(), {
+ once: true,
+ });
+ });
+ return { stdout: "", stderr: "", exitCode: null };
+ }
+ throw new Error("build continued after cancellation");
+ },
+ );
+ const buildPromise = new IOSSimulatorProjectBuilder({
+ commandRunner: { run },
+ }).build({
+ worktreeRoot: root,
+ derivedDataPath: path.join(root, "derived"),
+ signal: controller.signal,
+ });
+ await vi.waitFor(() => expect(resultBundlePath).not.toBe(""));
+
+ controller.abort();
+
+ await expect(buildPromise).rejects.toMatchObject({
+ code: "MUTATION_CANCELLED",
+ });
+ expect(run).toHaveBeenCalledTimes(2);
+ expect(
+ run.mock.calls.every(
+ ([, , options]) => options?.signal === controller.signal,
+ ),
+ ).toBe(true);
+ await expect(realpath(resultBundlePath)).rejects.toMatchObject({
+ code: "ENOENT",
+ });
+ });
});
diff --git a/packages/ios-simulator-runtime/src/project-adapter.ts b/packages/ios-simulator-runtime/src/project-adapter.ts
index 4bcdf33043..b3c8e7e47d 100644
--- a/packages/ios-simulator-runtime/src/project-adapter.ts
+++ b/packages/ios-simulator-runtime/src/project-adapter.ts
@@ -1,5 +1,5 @@
import { randomUUID } from "node:crypto";
-import { readdir, readFile, realpath, stat } from "node:fs/promises";
+import { readdir, readFile, realpath, rm, stat } from "node:fs/promises";
import path from "node:path";
import { createNodeIOSSimulatorCommandRunner } from "./command-runner.js";
@@ -129,6 +129,23 @@ function summarize(values: readonly string[], limit = 8): string {
return `${bounded.join(", ")}${remaining > 0 ? `, and ${remaining} more` : ""}`;
}
+async function throwIfBuildCancelled(
+ signal?: AbortSignal,
+ resultBundlePath?: string,
+): Promise<void> {
+ if (!signal?.aborted) return;
+ if (resultBundlePath) {
+ await rm(resultBundlePath, { recursive: true, force: true }).catch(
+ () => undefined,
+ );
+ }
+ throw new IOSSimulatorInstanceError(
+ "MUTATION_CANCELLED",
+ "The app build was cancelled because its simulator session ended.",
+ true,
+ );
+}
+
/** Detects Cindy Mobile or one unambiguous generic Xcode container and builds without a shell. */
export class IOSSimulatorProjectBuilder {
readonly #runner: IOSSimulatorCommandRunner;
@@ -251,8 +268,11 @@ export class IOSSimulatorProjectBuilder {
derivedDataPath: string;
containerPath?: string;
scheme?: string;
+ signal?: AbortSignal;
}): Promise<IOSSimulatorProjectBuildResult> {
+ await throwIfBuildCancelled(input.signal);
const project = await this.inspect(input.worktreeRoot, input.containerPath);
+ await throwIfBuildCancelled(input.signal);
if (project.kind === "cindy-mobile") {
const result = await this.#runner.run(
"pnpm",
@@ -261,8 +281,10 @@ export class IOSSimulatorProjectBuilder {
cwd: project.worktreeRoot,
timeoutMs: this.#buildTimeoutMs,
maxBufferBytes: 1024 * 1024,
+ signal: input.signal,
},
);
+ await throwIfBuildCancelled(input.signal);
if (result.exitCode !== 0) {
throw new IOSSimulatorProjectBuildError(
"APP_BUILD_FAILED",
@@ -284,6 +306,7 @@ export class IOSSimulatorProjectBuilder {
const apps = (await readdir(products)).filter((name) =>
name.endsWith(".app"),
);
+ await throwIfBuildCancelled(input.signal);
if (apps.length !== 1) {
throw new IOSSimulatorProjectBuildError(
"APP_ARTIFACT_INVALID",
@@ -293,10 +316,12 @@ export class IOSSimulatorProjectBuilder {
Boolean(result.outputTruncated),
);
}
+ const appPath = await realpath(path.join(products, apps[0]!));
+ await throwIfBuildCancelled(input.signal);
return {
...project,
scheme: apps[0]!.slice(0, -4),
- appPath: await realpath(path.join(products, apps[0]!)),
+ appPath,
resultBundlePath: null,
buildLogTail: commandLogTail([result]),
outputTruncated: Boolean(result.outputTruncated),
@@ -312,8 +337,10 @@ export class IOSSimulatorProjectBuilder {
cwd: project.projectRoot,
timeoutMs: 60_000,
maxBufferBytes: 1024 * 1024,
+ signal: input.signal,
},
);
+ await throwIfBuildCancelled(input.signal);
if (list.exitCode !== 0 || list.outputTruncated) {
throw new IOSSimulatorProjectBuildError(
"APP_BUILD_FAILED",
@@ -379,11 +406,14 @@ export class IOSSimulatorProjectBuilder {
cwd: project.projectRoot,
timeoutMs: this.#buildTimeoutMs,
maxBufferBytes: 1024 * 1024,
+ signal: input.signal,
},
);
+ await throwIfBuildCancelled(input.signal, resultBundlePath);
const availableResultBundlePath = (await exists(resultBundlePath))
? resultBundlePath
: null;
+ await throwIfBuildCancelled(input.signal, resultBundlePath);
if (build.exitCode !== 0) {
throw new IOSSimulatorProjectBuildError(
"APP_BUILD_FAILED",
@@ -401,8 +431,10 @@ export class IOSSimulatorProjectBuilder {
cwd: project.projectRoot,
timeoutMs: 60_000,
maxBufferBytes: 4 * 1024 * 1024,
+ signal: input.signal,
},
);
+ await throwIfBuildCancelled(input.signal, resultBundlePath);
if (settings.exitCode !== 0 || settings.outputTruncated) {
throw new IOSSimulatorProjectBuildError(
"APP_ARTIFACT_INVALID",
@@ -439,10 +471,13 @@ export class IOSSimulatorProjectBuilder {
Boolean(build.outputTruncated),
);
}
+ await throwIfBuildCancelled(input.signal, resultBundlePath);
+ const appPath = await realpath(uniqueApps[0]!);
+ await throwIfBuildCancelled(input.signal, resultBundlePath);
return {
...project,
scheme,
- appPath: await realpath(uniqueApps[0]!),
+ appPath,
resultBundlePath: availableResultBundlePath,
buildLogTail: commandLogTail([build]),
outputTruncated: Boolean(build.outputTruncated),
diff --git a/packages/ios-simulator-runtime/src/types.ts b/packages/ios-simulator-runtime/src/types.ts
index a3fbfe779a..30f56a0b4b 100644
--- a/packages/ios-simulator-runtime/src/types.ts
+++ b/packages/ios-simulator-runtime/src/types.ts
@@ -67,6 +67,7 @@ export interface IOSSimulatorCommandRunner {
maxBufferBytes?: number;
cwd?: string;
env?: NodeJS.ProcessEnv;
+ signal?: AbortSignal;
},
): Promise<IOSSimulatorCommandResult>;
}
diff --git a/packages/lizi-mcps/src/ios-simulator/iosSimulatorMcpServer.test.ts b/packages/lizi-mcps/src/ios-simulator/iosSimulatorMcpServer.test.ts
index ea9739733f..4c6150325c 100644
--- a/packages/lizi-mcps/src/ios-simulator/iosSimulatorMcpServer.test.ts
+++ b/packages/lizi-mcps/src/ios-simulator/iosSimulatorMcpServer.test.ts
@@ -5,8 +5,23 @@ import { describe, expect, it, vi } from "vitest";
import type { IOSSimulatorMcpDeps } from "../types.js";
import { createIOSSimulatorMcpServer } from "./server.js";
-async function connect(deps: IOSSimulatorMcpDeps, sessionId?: string) {
- const server = createIOSSimulatorMcpServer(deps, { sessionId });
+async function connect(
+ deps: IOSSimulatorMcpDeps,
+ sessionId?: string,
+ workingDir?: string,
+) {
+ const server = createIOSSimulatorMcpServer(deps, {
+ sessionId,
+ ...(workingDir
+ ? {
+ getSessionContext: () => ({
+ agentKind: "claude-code",
+ workingDir,
+ sessionId,
+ }),
+ }
+ : {}),
+ });
const client = new Client({ name: "test-client", version: "0.0.0" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
@@ -218,7 +233,11 @@ describe("createIOSSimulatorMcpServer", () => {
it("forwards the authoritative session context to the host", async () => {
const callTool = vi.fn(async () => ({ ok: true, data: { ready: true } }));
- const { client, server } = await connect({ callTool }, "session-a");
+ const { client, server } = await connect(
+ { callTool },
+ "session-a",
+ "/projects/enabled-ios",
+ );
const result = await client.callTool({
name: "call_tool",
arguments: { name: "check_environment", args: {} },
@@ -229,6 +248,7 @@ describe("createIOSSimulatorMcpServer", () => {
{},
{
sessionId: "session-a",
+ workingDir: "/projects/enabled-ios",
origin: "agent",
},
);
diff --git a/packages/lizi-mcps/src/ios-simulator/server.ts b/packages/lizi-mcps/src/ios-simulator/server.ts
index da7c7444e3..624bc64577 100644
--- a/packages/lizi-mcps/src/ios-simulator/server.ts
+++ b/packages/lizi-mcps/src/ios-simulator/server.ts
@@ -22,9 +22,17 @@ export interface IOSSimulatorMcpServerOptions {
function readContext(
options: IOSSimulatorMcpServerOptions,
): IOSSimulatorMcpCallContext | undefined {
- const sessionId =
- options.getSessionContext?.().sessionId ?? options.sessionId;
- return sessionId ? { sessionId, origin: "agent" } : undefined;
+ const sessionContext = options.getSessionContext?.();
+ const sessionId = sessionContext?.sessionId ?? options.sessionId;
+ return sessionId
+ ? {
+ sessionId,
+ ...(sessionContext?.workingDir
+ ? { workingDir: sessionContext.workingDir }
+ : {}),
+ origin: "agent",
+ }
+ : undefined;
}
export function createIOSSimulatorMcpServer(
@@ -51,12 +59,7 @@ export function createIOSSimulatorMcpServer(
"Discover Cindy's embedded iOS Simulator tools. This is the preferred entry point for opening, running, testing, or debugging an iOS app in Cindy. Do not use cindy_computer to launch macOS Simulator.app unless the user explicitly requests an external system window. Start with check_environment before selecting a device.",
{ category: z.enum(["ios_simulator"]).optional() },
async () => {
- const availability = options.getSessionContext
- ? await deps.describeTools?.({
- sessionId: options.getSessionContext().sessionId,
- origin: "agent",
- })
- : await deps.describeTools?.({ sessionId: options.sessionId, origin: "agent" });
+ const availability = await deps.describeTools?.(readContext(options));
return {
content: [
{
diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.ts
index 2b67463f67..460dd5880b 100644
--- a/packages/lizi-mcps/src/types.ts
+++ b/packages/lizi-mcps/src/types.ts
@@ -829,6 +829,8 @@ export type IOSSimulatorMcpToolName =
export interface IOSSimulatorMcpCallContext {
sessionId?: string;
+ /** Workdir bound by the Host for project-scoped capability policy. */
+ workingDir?: string;
/** Host-internal origin. MCP transport always uses agent; renderer IPC uses user. */
origin?: 'agent' | 'user';
}