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): clean up simulator sessions on task removal

JiangJiahao150dd3539e9c
diff --git a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
index 6a309d09ec..c2d5a9db5c 100644
--- a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
+++ b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts
@@ -25,6 +25,7 @@ const h = vi.hoisted(() => ({
) as SessionRouteLockMock,
isSessionStillRemovable: vi.fn(),
cancelSessionOperations: vi.fn(),
+ cleanupRemovedSession: vi.fn(),
removeSessionRefs: vi.fn(),
recycleWorktreeForRemovedSession: vi.fn(),
isOwnerScopeCurrent: vi.fn(),
@@ -77,6 +78,7 @@ vi.mock('../worktree/sessionRemovalRecycle.js', () => ({
import {
recycleSessionWorktreeForStatusChange,
setSessionRemovalCancelOperations,
+ setSessionRemovalCleanup,
setSessionsStatusInDb,
} from '../localDb/ipc/sessions.js';
import { setSessionRouteLockImplementation } from '../localDb/sessionRouteLock.js';
@@ -87,15 +89,18 @@ beforeEach(() => {
h.closeSession.mockResolvedValue(undefined);
h.isSessionStillRemovable.mockResolvedValue(true);
h.cancelSessionOperations.mockResolvedValue(undefined);
+ h.cleanupRemovedSession.mockResolvedValue(undefined);
h.removeSessionRefs.mockResolvedValue(0);
h.recycleWorktreeForRemovedSession.mockResolvedValue(undefined);
h.isOwnerScopeCurrent.mockReturnValue(true);
setSessionRemovalCancelOperations(h.cancelSessionOperations);
+ setSessionRemovalCleanup(h.cleanupRemovedSession);
setSessionRouteLockImplementation(h.withSendToSessionLock);
});
afterEach(() => {
setSessionRemovalCancelOperations(null);
+ setSessionRemovalCleanup(null);
setSessionRouteLockImplementation(null);
fs.rmSync(h.userDataPath, { recursive: true, force: true });
});
@@ -231,7 +236,7 @@ describe('setSessionsStatusInDb', () => {
});
expect(h.withSendToSessionLock).toHaveBeenCalledWith('s1', expect.any(Function));
- expect(h.isSessionStillRemovable).toHaveBeenCalledTimes(4);
+ expect(h.isSessionStillRemovable).toHaveBeenCalledTimes(5);
expect(h.cancelSessionOperations).toHaveBeenCalledWith('s1');
expect(h.recycleWorktreeForRemovedSession).toHaveBeenCalledWith(
's1',
@@ -333,6 +338,9 @@ describe('recycleSessionWorktreeForStatusChange', () => {
h.cancelSessionOperations.mockImplementationOnce(async () => {
order.push('cancel');
});
+ h.cleanupRemovedSession.mockImplementationOnce(async () => {
+ order.push('cleanup');
+ });
h.removeSessionRefs.mockImplementationOnce(async () => {
order.push('remove-media-refs');
return 1;
@@ -344,8 +352,9 @@ describe('recycleSessionWorktreeForStatusChange', () => {
await recycleSessionWorktreeForStatusChange('s1', 'deleted');
expect(h.withSendToSessionLock).toHaveBeenCalledWith('s1', expect.any(Function));
- expect(h.isSessionStillRemovable).toHaveBeenCalledTimes(4);
+ expect(h.isSessionStillRemovable).toHaveBeenCalledTimes(5);
expect(h.cancelSessionOperations).toHaveBeenCalledWith('s1');
+ expect(h.cleanupRemovedSession).toHaveBeenCalledWith('s1');
expect(h.closeSession).toHaveBeenCalledWith('s1');
expect(h.removeSessionRefs).toHaveBeenCalledWith('s1', h.drizzle);
expect(h.recycleWorktreeForRemovedSession).toHaveBeenCalledWith(
@@ -353,7 +362,7 @@ describe('recycleSessionWorktreeForStatusChange', () => {
expect.objectContaining({ db: h.drizzle, isOwnerCurrent: expect.any(Function) }),
);
expect(h.webContentsSend).toHaveBeenCalledWith('worktree:changed', { sessionId: 's1' });
- expect(order).toEqual(['cancel', 'remove-media-refs', 'recycle-worktree']);
+ expect(order).toEqual(['cancel', 'cleanup', 'remove-media-refs', 'recycle-worktree']);
});
it('keeps media and worktree deletion inside the task route lock', async () => {
@@ -403,6 +412,19 @@ describe('recycleSessionWorktreeForStatusChange', () => {
expect(h.webContentsSend).toHaveBeenCalledWith('worktree:changed', { sessionId: 's1' });
});
+ it('does not remove media or recycle the worktree when Simulator cleanup fails', async () => {
+ h.cleanupRemovedSession.mockRejectedValueOnce(new Error('simulator is still shutting down'));
+
+ await recycleSessionWorktreeForStatusChange('s1', 'deleted');
+
+ expect(h.cancelSessionOperations).toHaveBeenCalledWith('s1');
+ expect(h.cleanupRemovedSession).toHaveBeenCalledWith('s1');
+ expect(h.closeSession).not.toHaveBeenCalled();
+ expect(h.removeSessionRefs).not.toHaveBeenCalled();
+ expect(h.recycleWorktreeForRemovedSession).not.toHaveBeenCalled();
+ expect(h.webContentsSend).toHaveBeenCalledWith('worktree:changed', { sessionId: 's1' });
+ });
+
it('does not dynamically import the Simulator Host from the recycle path', () => {
const source = fs.readFileSync(new URL('../localDb/ipc/sessions.ts', import.meta.url), 'utf8');
expect(source).not.toContain("import('../../mcp-integrations/ios-simulator.js')");
@@ -418,6 +440,7 @@ describe('recycleSessionWorktreeForStatusChange', () => {
expect(h.isSessionStillRemovable).not.toHaveBeenCalled();
expect(h.cancelSessionOperations).not.toHaveBeenCalled();
+ expect(h.cleanupRemovedSession).not.toHaveBeenCalled();
expect(h.removeSessionRefs).not.toHaveBeenCalled();
expect(h.recycleWorktreeForRemovedSession).not.toHaveBeenCalled();
});
@@ -433,6 +456,7 @@ describe('recycleSessionWorktreeForStatusChange', () => {
});
expect(h.cancelSessionOperations).toHaveBeenCalledWith('shared-session-id');
+ expect(h.cleanupRemovedSession).toHaveBeenCalledWith('shared-session-id');
expect(h.closeSession).toHaveBeenCalledWith('shared-session-id');
expect(h.removeSessionRefs).not.toHaveBeenCalled();
expect(h.recycleWorktreeForRemovedSession).not.toHaveBeenCalled();
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 9076b4d154..a5996b60b4 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -307,6 +307,7 @@ import { registerDevEmbeddingIpc } from './ipc/dev/embedding';
import { onQuit, installQuitHandler } from './lifecycle';
import {
cancelIOSSimulatorSessionOperations,
+ cleanupIOSSimulatorRemovedSession,
disposeIOSSimulatorHost,
flushIOSSimulatorOwnershipRegistry,
} from './mcp-integrations/ios-simulator';
@@ -6375,6 +6376,7 @@ app.on('ready', async () => {
registerLegacyMigrationIpc();
registerLocalDbIpc({
cancelSessionOperations: cancelIOSSimulatorSessionOperations,
+ cleanupRemovedSession: cleanupIOSSimulatorRemovedSession,
withSessionLock: withSendToSessionLock,
isOwnerCurrent: (userId) =>
isLocalDbOwnerCurrent(authManager.getAuthState(), userId, isAppSessionBoundaryPending()),
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionRemovalOperations.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionRemovalOperations.test.ts
index edb4a6b974..9845c1f09a 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionRemovalOperations.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionRemovalOperations.test.ts
@@ -12,6 +12,9 @@ describe('quiesceSessionBeforeWorktreeRecycle', () => {
const cancelSessionOperations = vi.fn(async () => {
order.push('cancel');
});
+ const cleanupRemovedSession = vi.fn(async () => {
+ order.push('cleanup');
+ });
const closeSession = vi.fn(async () => {
order.push('close');
});
@@ -21,10 +24,11 @@ describe('quiesceSessionBeforeWorktreeRecycle', () => {
isOwnerCurrent: () => true,
isSessionStillRemovable,
cancelSessionOperations,
+ cleanupRemovedSession,
closeSession,
}),
).resolves.toBe(true);
- expect(order).toEqual(['check', 'cancel', 'check', 'close', 'check']);
+ expect(order).toEqual(['check', 'cancel', 'check', 'cleanup', 'check', 'close', 'check']);
});
it('does not close or recycle a task restored while cancellation settles', async () => {
@@ -33,6 +37,7 @@ describe('quiesceSessionBeforeWorktreeRecycle', () => {
.mockResolvedValueOnce(true)
.mockResolvedValueOnce(false);
const cancelSessionOperations = vi.fn(async () => undefined);
+ const cleanupRemovedSession = vi.fn(async () => undefined);
const closeSession = vi.fn(async () => undefined);
await expect(
@@ -40,10 +45,12 @@ describe('quiesceSessionBeforeWorktreeRecycle', () => {
isOwnerCurrent: () => true,
isSessionStillRemovable,
cancelSessionOperations,
+ cleanupRemovedSession,
closeSession,
}),
).resolves.toBe(false);
expect(cancelSessionOperations).toHaveBeenCalledWith('session-a');
+ expect(cleanupRemovedSession).not.toHaveBeenCalled();
expect(closeSession).not.toHaveBeenCalled();
});
@@ -52,8 +59,10 @@ describe('quiesceSessionBeforeWorktreeRecycle', () => {
.fn<() => Promise<boolean>>()
.mockResolvedValueOnce(true)
.mockResolvedValueOnce(true)
+ .mockResolvedValueOnce(true)
.mockResolvedValueOnce(false);
const cancelSessionOperations = vi.fn(async () => undefined);
+ const cleanupRemovedSession = vi.fn(async () => undefined);
const closeSession = vi.fn(async () => undefined);
await expect(
@@ -61,12 +70,35 @@ describe('quiesceSessionBeforeWorktreeRecycle', () => {
isOwnerCurrent: () => true,
isSessionStillRemovable,
cancelSessionOperations,
+ cleanupRemovedSession,
closeSession,
}),
).resolves.toBe(false);
expect(closeSession).toHaveBeenCalledWith('session-a');
});
+ it('does not close the Agent session when Host runtime cleanup fails', async () => {
+ const cancelSessionOperations = vi.fn(async () => undefined);
+ const cleanupError = new Error('simulator process group is still alive');
+ const cleanupRemovedSession = vi.fn(async () => {
+ throw cleanupError;
+ });
+ const closeSession = vi.fn(async () => undefined);
+
+ await expect(
+ quiesceSessionBeforeWorktreeRecycle('session-a', {
+ isOwnerCurrent: () => true,
+ isSessionStillRemovable: vi.fn(async () => true),
+ cancelSessionOperations,
+ cleanupRemovedSession,
+ closeSession,
+ }),
+ ).rejects.toBe(cleanupError);
+ expect(cancelSessionOperations).toHaveBeenCalledWith('session-a');
+ expect(cleanupRemovedSession).toHaveBeenCalledWith('session-a');
+ expect(closeSession).not.toHaveBeenCalled();
+ });
+
it('stops before each side effect when the captured owner changes', async () => {
let current = true;
const isSessionStillRemovable = vi.fn(async () => {
@@ -74,6 +106,7 @@ describe('quiesceSessionBeforeWorktreeRecycle', () => {
return true;
});
const cancelSessionOperations = vi.fn(async () => undefined);
+ const cleanupRemovedSession = vi.fn(async () => undefined);
const closeSession = vi.fn(async () => undefined);
await expect(
@@ -81,10 +114,12 @@ describe('quiesceSessionBeforeWorktreeRecycle', () => {
isOwnerCurrent: () => current,
isSessionStillRemovable,
cancelSessionOperations,
+ cleanupRemovedSession,
closeSession,
}),
).resolves.toBe(false);
expect(cancelSessionOperations).not.toHaveBeenCalled();
+ expect(cleanupRemovedSession).not.toHaveBeenCalled();
expect(closeSession).not.toHaveBeenCalled();
});
});
diff --git a/apps/desktop/src/main/localDb/ipc/registerAll.ts b/apps/desktop/src/main/localDb/ipc/registerAll.ts
index 732477f8a9..fd02bc90a0 100644
--- a/apps/desktop/src/main/localDb/ipc/registerAll.ts
+++ b/apps/desktop/src/main/localDb/ipc/registerAll.ts
@@ -11,7 +11,11 @@ import { ipcMain } from 'electron';
import { closeDb, ensureReady, getCurrentUserId } from '../index';
import { getCurrentDbClientUserId, tryGetDbClient } from '../client/current';
-import { registerSessionIpc, setSessionRemovalCancelOperations } from './sessions';
+import {
+ registerSessionIpc,
+ setSessionRemovalCancelOperations,
+ setSessionRemovalCleanup,
+} from './sessions';
import { registerMessageIpc } from './messages';
import { registerOrcaWorkflowIpc } from './orcaTeams';
import { registerSessionImportIpc } from './session-import';
@@ -73,6 +77,8 @@ export interface RegisterLocalDbIpcOpts {
beforeEnsureReady?: (userId: string) => void | Promise<void>;
/** Stop Host-owned session operations before an archived/deleted worktree is recycled. */
cancelSessionOperations?: (sessionId: string) => Promise<void>;
+ /** Release Host-owned runtime and ownership after task removal is revalidated. */
+ cleanupRemovedSession?: (sessionId: string) => Promise<void>;
/** Serialize startup tombstone cleanup with task restore/start/send operations. */
withSessionLock?: <T>(sessionId: string, task: () => Promise<T>) => Promise<T>;
/**
@@ -90,6 +96,7 @@ export interface RegisterLocalDbIpcOpts {
export function registerLocalDbIpc(opts: RegisterLocalDbIpcOpts = {}): void {
setSessionRemovalCancelOperations(opts.cancelSessionOperations ?? null);
+ setSessionRemovalCleanup(opts.cleanupRemovedSession ?? null);
setSessionRouteLockImplementation(opts.withSessionLock ?? null);
const runEnsureReady = createOwnerEnsureCoordinator({
isOwnerCurrent: opts.isOwnerCurrent ?? (() => true),
@@ -112,14 +119,18 @@ export function registerLocalDbIpc(opts: RegisterLocalDbIpcOpts = {}): void {
startMediaRefCompensationReconcile(userId, client, isReadyOwnerCurrent);
const cancelSessionOperations = opts.cancelSessionOperations;
+ const cleanupRemovedSession = opts.cleanupRemovedSession;
const withSessionLock = opts.withSessionLock;
- if (!cancelSessionOperations || !withSessionLock) return;
+ if (!cancelSessionOperations || !cleanupRemovedSession || !withSessionLock) return;
const db = client.drizzle;
void reconcileSessionMediaRefsForDeletedSessions({
db,
isOwnerCurrent: isReadyOwnerCurrent,
withSessionLock,
- quiesceSession: cancelSessionOperations,
+ quiesceSession: async (sessionId) => {
+ await cancelSessionOperations(sessionId);
+ await cleanupRemovedSession(sessionId);
+ },
}).catch((error) => {
log.warn('deleted task media reconcile failed', {
userId,
diff --git a/apps/desktop/src/main/localDb/ipc/sessionRemovalOperations.ts b/apps/desktop/src/main/localDb/ipc/sessionRemovalOperations.ts
index 070a2b9594..30475945ed 100644
--- a/apps/desktop/src/main/localDb/ipc/sessionRemovalOperations.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessionRemovalOperations.ts
@@ -2,6 +2,7 @@ export interface SessionRemovalOperationDeps {
isOwnerCurrent(): boolean;
isSessionStillRemovable(sessionId: string): Promise<boolean>;
cancelSessionOperations(sessionId: string): Promise<void>;
+ cleanupRemovedSession(sessionId: string): Promise<void>;
closeSession(sessionId: string): Promise<void>;
}
@@ -21,6 +22,10 @@ export async function quiesceSessionBeforeWorktreeRecycle(
if (!deps.isOwnerCurrent()) return false;
if (!(await deps.isSessionStillRemovable(sessionId))) return false;
if (!deps.isOwnerCurrent()) return false;
+ await deps.cleanupRemovedSession(sessionId);
+ if (!deps.isOwnerCurrent()) return false;
+ if (!(await deps.isSessionStillRemovable(sessionId))) return false;
+ if (!deps.isOwnerCurrent()) return false;
await deps.closeSession(sessionId);
if (!deps.isOwnerCurrent()) return false;
return deps.isSessionStillRemovable(sessionId);
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index f855b53cef..4f2aa4aca4 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -62,12 +62,14 @@ const initialSessionListLogged = new Set<string>();
const SLOW_SESSION_LIST_MS = 250;
type OwnerScope = ReturnType<typeof broadcastTap.captureDataOwnerBroadcastScope> | null;
type SessionRemovalCancelOperations = (sessionId: string) => Promise<void>;
+type SessionRemovalCleanup = (sessionId: string) => Promise<void>;
export interface SessionRecycleScope {
ownerScope: OwnerScope;
mediaDb: DbClient['drizzle'];
}
let sessionRemovalCancelOperations: SessionRemovalCancelOperations | null = null;
+let sessionRemovalCleanup: SessionRemovalCleanup | null = null;
/** Composition-root injection for Host-owned operations that must stop before worktree recycle. */
export function setSessionRemovalCancelOperations(
@@ -76,6 +78,13 @@ export function setSessionRemovalCancelOperations(
sessionRemovalCancelOperations = cancelOperations;
}
+/** Composition-root injection for destructive cleanup after removal is revalidated. */
+export function setSessionRemovalCleanup(
+ cleanupRemovedSession: SessionRemovalCleanup | null,
+): void {
+ sessionRemovalCleanup = cleanupRemovedSession;
+}
+
function captureOwnerScope(): OwnerScope {
try {
const capture = broadcastTap.captureDataOwnerBroadcastScope;
@@ -225,7 +234,8 @@ export async function recycleSessionWorktreeForStatusChange(
const mediaDb = capturedScope?.mediaDb ?? getDbClient().drizzle;
if (!isOwnerScopeCurrent(ownerScope)) return;
const cancelOperations = sessionRemovalCancelOperations;
- if (!cancelOperations) {
+ const cleanupRemovedSession = sessionRemovalCleanup;
+ if (!cancelOperations || !cleanupRemovedSession) {
throw new Error('iOS Simulator session cleanup is not configured');
}
const [mh, recycle] = await Promise.all([
@@ -241,6 +251,7 @@ export async function recycleSessionWorktreeForStatusChange(
isOwnerCurrent: ownerIsCurrent,
isSessionStillRemovable: isStillRemovable,
cancelSessionOperations: cancelOperations,
+ cleanupRemovedSession,
closeSession: async (id) => {
await mh
.getMakerIfReady()
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 2b269c1425..17fbfd594f 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
@@ -960,6 +960,274 @@ describe('iOS Simulator host', () => {
await host.dispose();
});
+ it.each([
+ {
+ label: 'external preexisting',
+ creationProvenance: 'external' as const,
+ bootProvenance: 'preexisting' as const,
+ expectShutdown: false,
+ expectDelete: false,
+ },
+ {
+ label: 'external Agent-booted',
+ creationProvenance: 'external' as const,
+ bootProvenance: 'agent-booted' as const,
+ expectShutdown: true,
+ expectDelete: false,
+ },
+ {
+ label: 'Cindy-created',
+ creationProvenance: 'cindy' as const,
+ bootProvenance: 'user-booted' as const,
+ expectShutdown: true,
+ expectDelete: true,
+ },
+ ])(
+ 'cleans a removed $label binding after startup ownership reconcile has latched',
+ async ({ creationProvenance, bootProvenance, expectShutdown, expectDelete }) => {
+ const device = { ...READY_REPORT.devices[0]!, state: 'Booted' as const };
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(async () => device),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(async () => undefined),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(async () => undefined),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),
+ lifecycle,
+ });
+ const instance = actor.attach({
+ sessionId: 'removed-session',
+ worktreeRoot: '/tmp/removed-session',
+ sourceFingerprint: 'fingerprint-a',
+ creationProvenance,
+ bootProvenance,
+ device,
+ });
+ const resourceScheduler = testResourceScheduler();
+ await resourceScheduler.runStart(instance.instanceId, async (commitRunning) => {
+ commitRunning();
+ });
+ const stopDriver = vi.fn(async () => undefined);
+ const discardSession = vi.fn(async () => undefined);
+ const discardInstance = vi.fn(async () => undefined);
+ const framePump = { clear: vi.fn(), snapshot: vi.fn(() => null) };
+ const h264FramePump = { clear: vi.fn() };
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ resourceScheduler,
+ driverManager: {
+ get: vi.fn(() => null),
+ start: vi.fn(),
+ stop: stopDriver,
+ },
+ framePump: framePump as never,
+ h264FramePump: h264FramePump as never,
+ mediaCapture: {
+ discardSession,
+ discardInstance,
+ } as unknown as IOSSimulatorMediaCaptureAdapter,
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ });
+
+ await host.reconcileOwnership();
+ await expect(host.cleanupRemovedSession('removed-session')).resolves.toBeUndefined();
+ await expect(host.cleanupRemovedSession('removed-session')).resolves.toBeUndefined();
+
+ expect(actor.list('removed-session')).toEqual([]);
+ expect(resourceScheduler.runningCount()).toBe(0);
+ expect(stopDriver).toHaveBeenCalledOnce();
+ expect(stopDriver).toHaveBeenCalledWith(instance.instanceId);
+ expect(discardInstance).toHaveBeenCalledOnce();
+ expect(framePump.clear).toHaveBeenCalledWith(instance.instanceId);
+ expect(h264FramePump.clear).toHaveBeenCalledWith(instance.instanceId);
+ expect(lifecycle.findExact).toHaveBeenCalledTimes(expectShutdown ? 1 : 0);
+ expect(lifecycle.shutdownExact).toHaveBeenCalledTimes(expectShutdown ? 1 : 0);
+ expect(lifecycle.deleteExact).toHaveBeenCalledTimes(expectDelete ? 1 : 0);
+ },
+ );
+
+ it('treats an already missing Cindy-created device as successfully removed', async () => {
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(async () => null),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(async () => undefined),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(async () => undefined),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),
+ lifecycle,
+ });
+ const instance = actor.attach({
+ sessionId: 'removed-session',
+ worktreeRoot: '/tmp/removed-session',
+ sourceFingerprint: 'fingerprint-a',
+ creationProvenance: 'cindy',
+ bootProvenance: 'agent-booted',
+ device: READY_REPORT.devices[0]!,
+ });
+ const resourceScheduler = testResourceScheduler();
+ await resourceScheduler.runStart(instance.instanceId, async (commitRunning) => {
+ commitRunning();
+ });
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ resourceScheduler,
+ driverManager: {
+ get: vi.fn(() => null),
+ start: vi.fn(),
+ stop: vi.fn(async () => undefined),
+ },
+ mediaCapture: {
+ discardSession: vi.fn(async () => undefined),
+ discardInstance: vi.fn(async () => undefined),
+ } as unknown as IOSSimulatorMediaCaptureAdapter,
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ });
+
+ await host.reconcileOwnership();
+ await expect(host.cleanupRemovedSession('removed-session')).resolves.toBeUndefined();
+ await expect(host.cleanupRemovedSession('removed-session')).resolves.toBeUndefined();
+
+ expect(actor.list('removed-session')).toEqual([]);
+ expect(resourceScheduler.runningCount()).toBe(0);
+ expect(lifecycle.findExact).toHaveBeenCalledOnce();
+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();
+ expect(lifecycle.deleteExact).not.toHaveBeenCalled();
+ });
+
+ it('cleans only the removed task ownership and scheduler capacity', async () => {
+ const otherDevice = {
+ ...READY_REPORT.devices[0]!,
+ udid: '2A9D41E0-E031-4AD0-A8B5-847480802E8E',
+ name: 'iPhone 17 Pro B',
+ };
+ const environment = { ...READY_REPORT, devices: [READY_REPORT.devices[0]!, otherDevice] };
+ 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 removed = actor.attach({
+ sessionId: 'session-a',
+ worktreeRoot: '/tmp/session-a',
+ sourceFingerprint: 'fingerprint-a',
+ creationProvenance: 'external',
+ bootProvenance: 'preexisting',
+ device: READY_REPORT.devices[0]!,
+ });
+ const retained = actor.attach({
+ sessionId: 'session-b',
+ worktreeRoot: '/tmp/session-b',
+ sourceFingerprint: 'fingerprint-b',
+ creationProvenance: 'external',
+ bootProvenance: 'preexisting',
+ device: otherDevice,
+ });
+ const resourceScheduler = testResourceScheduler();
+ for (const instance of [removed, retained]) {
+ await resourceScheduler.runStart(instance.instanceId, async (commitRunning) => {
+ commitRunning();
+ });
+ }
+ const stopDriver = vi.fn(async () => undefined);
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ resourceScheduler,
+ driverManager: {
+ get: vi.fn(() => null),
+ start: vi.fn(),
+ stop: stopDriver,
+ },
+ mediaCapture: {
+ discardSession: vi.fn(async () => undefined),
+ discardInstance: vi.fn(async () => undefined),
+ } as unknown as IOSSimulatorMediaCaptureAdapter,
+ runtime: { inspect: vi.fn(async () => environment) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ });
+
+ await host.reconcileOwnership();
+ await host.cleanupRemovedSession('session-a');
+
+ expect(actor.list('session-a')).toEqual([]);
+ expect(actor.list('session-b')).toHaveLength(1);
+ expect(actor.list('session-b')[0]?.instanceId).toBe(retained.instanceId);
+ expect(resourceScheduler.runningCount()).toBe(1);
+ expect(stopDriver).toHaveBeenCalledOnce();
+ expect(stopDriver).toHaveBeenCalledWith(removed.instanceId);
+ });
+
+ it('retains degraded ownership and scheduler capacity when removed-task cleanup fails', async () => {
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(async () => READY_REPORT.devices[0]!),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(async () => undefined),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),
+ lifecycle,
+ });
+ const instance = actor.attach({
+ sessionId: 'removed-session',
+ worktreeRoot: '/tmp/removed-session',
+ sourceFingerprint: 'fingerprint-a',
+ creationProvenance: 'external',
+ bootProvenance: 'agent-booted',
+ device: READY_REPORT.devices[0]!,
+ });
+ const resourceScheduler = testResourceScheduler();
+ await resourceScheduler.runStart(instance.instanceId, async (commitRunning) => {
+ commitRunning();
+ });
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ resourceScheduler,
+ driverManager: {
+ get: vi.fn(() => null),
+ start: vi.fn(),
+ stop: vi.fn(async () => {
+ throw new Error('driver process group did not stop');
+ }),
+ },
+ mediaCapture: {
+ discardSession: vi.fn(async () => undefined),
+ discardInstance: vi.fn(async () => undefined),
+ } as unknown as IOSSimulatorMediaCaptureAdapter,
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ });
+
+ await host.reconcileOwnership();
+ await expect(host.cleanupRemovedSession('removed-session')).rejects.toMatchObject({
+ code: 'DEVICE_BUSY',
+ });
+
+ expect(actor.getOwned('removed-session', instance.instanceId)).toMatchObject({
+ healthState: 'degraded',
+ errorCode: 'ARCHIVED_CLEANUP_FAILED',
+ });
+ expect(resourceScheduler.runningCount()).toBe(1);
+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();
+ expect(lifecycle.deleteExact).not.toHaveBeenCalled();
+ });
+
it('disposes WDA and recording resources on host shutdown without changing ownership', async () => {
const lifecycle: IOSSimulatorSimctlLifecycle = {
findExact: vi.fn(),
@@ -3324,6 +3592,310 @@ describe('iOS Simulator host', () => {
await host.dispose();
});
+ it('waits for a racing start and shuts down the device before cleanup returns', async () => {
+ const shutdownDevice = { ...READY_REPORT.devices[0]!, state: 'Shutdown' as const };
+ const bootedDevice = { ...READY_REPORT.devices[0]!, state: 'Booted' as const };
+ let resolveBoot: (device: typeof bootedDevice) => void = () => undefined;
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(async () => bootedDevice),
+ bootExact: vi.fn(
+ () =>
+ new Promise<typeof bootedDevice>((resolve) => {
+ resolveBoot = resolve;
+ }),
+ ),
+ shutdownExact: vi.fn(async () => undefined),
+ 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 driverManager = {
+ get: vi.fn(() => null),
+ start: vi.fn(),
+ stop: vi.fn(async () => undefined),
+ };
+ const resourceScheduler = testResourceScheduler();
+ const environment = { ...READY_REPORT, devices: [shutdownDevice] };
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ driverManager,
+ resourceScheduler,
+ mediaCapture: {
+ discardSession: vi.fn(async () => undefined),
+ discardInstance: vi.fn(async () => undefined),
+ } as unknown as IOSSimulatorMediaCaptureAdapter,
+ runtime: { inspect: vi.fn(async () => environment) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ });
+ await host.reconcileOwnership();
+ driverManager.stop.mockClear();
+ const current = actor.getOwned('session-a', attached.instanceId);
+ const route = {
+ instanceId: current.instanceId,
+ generation: current.generation,
+ leaseId: current.lease.id,
+ };
+
+ const start = host.callTool('start_instance', route, {
+ sessionId: 'session-a',
+ origin: 'user',
+ });
+ await vi.waitFor(() => expect(lifecycle.bootExact).toHaveBeenCalledOnce());
+ const cleanup = host.cleanupRemovedSession('session-a');
+ resolveBoot(bootedDevice);
+
+ await expect(start).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'MUTATION_CANCELLED',
+ });
+ await expect(cleanup).resolves.toBeUndefined();
+ expect(driverManager.start).not.toHaveBeenCalled();
+ expect(driverManager.stop).toHaveBeenCalledWith(attached.instanceId);
+ expect(lifecycle.shutdownExact).toHaveBeenCalledWith(attached.simulatorUdid);
+ expect(actor.list('session-a')).toEqual([]);
+ expect(resourceScheduler.runningCount()).toBe(0);
+ });
+
+ it('waits for a racing viewer open before clearing its runtime projection', async () => {
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),
+ lifecycle,
+ });
+ const attached = actor.attach({
+ sessionId: 'session-a',
+ worktreeRoot: '/tmp/session-a',
+ sourceFingerprint: 'fingerprint-a',
+ device: READY_REPORT.devices[0]!,
+ });
+ let resolveWindowSize: (size: { width: number; height: number }) => void = () => undefined;
+ const running = {
+ instanceId: attached.instanceId,
+ simulatorUdid: attached.simulatorUdid,
+ pid: 42,
+ driver: {
+ getWindowSize: vi.fn(
+ () =>
+ new Promise<{ width: number; height: number }>((resolve) => {
+ resolveWindowSize = resolve;
+ }),
+ ),
+ getOrientation: vi.fn(async () => 'PORTRAIT' as const),
+ },
+ driverSessionId: 'wda-session',
+ } as unknown as WdaRunningInstance;
+ const driverManager = {
+ get: vi.fn(() => running),
+ start: vi.fn(),
+ stop: vi.fn(async () => undefined),
+ };
+ const framePump = {
+ setVisible: vi.fn(),
+ snapshot: vi.fn(() => null),
+ clear: vi.fn(),
+ };
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ driverManager,
+ framePump: framePump as never,
+ mediaCapture: {
+ discardSession: vi.fn(async () => undefined),
+ discardInstance: vi.fn(async () => undefined),
+ } as unknown as IOSSimulatorMediaCaptureAdapter,
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ resourceScheduler: testResourceScheduler(),
+ });
+ await host.reconcileOwnership();
+ const current = actor.getOwned('session-a', attached.instanceId);
+ const route = {
+ instanceId: current.instanceId,
+ generation: current.generation,
+ leaseId: current.lease.id,
+ };
+
+ const viewer = host.setViewerVisibility('session-a', route, true, 'jpeg');
+ await vi.waitFor(() => expect(running.driver.getWindowSize).toHaveBeenCalledOnce());
+ const cleanup = host.cleanupRemovedSession('session-a');
+ await Promise.resolve();
+ expect(driverManager.stop).not.toHaveBeenCalled();
+ resolveWindowSize({ width: 393, height: 852 });
+
+ await expect(viewer).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'MUTATION_CANCELLED',
+ });
+ await expect(cleanup).resolves.toBeUndefined();
+ expect(framePump.setVisible).not.toHaveBeenCalled();
+ expect(framePump.clear).toHaveBeenCalledWith(attached.instanceId);
+ expect(driverManager.stop).toHaveBeenCalledWith(attached.instanceId);
+ expect(actor.list('session-a')).toEqual([]);
+ });
+
+ it('waits for a racing attach and removes its partially started runtime', 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,
+ });
+ let resolveDriverStart: (running: WdaRunningInstance) => void = () => undefined;
+ let liveRunning: WdaRunningInstance | null = null;
+ const driverManager = {
+ get: vi.fn(() => liveRunning),
+ start: vi.fn(
+ () =>
+ new Promise<WdaRunningInstance>((resolve) => {
+ resolveDriverStart = (running) => {
+ liveRunning = running;
+ resolve(running);
+ };
+ }),
+ ),
+ stop: vi.fn(async () => {
+ liveRunning = null;
+ }),
+ };
+ const resourceScheduler = testResourceScheduler();
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ driverManager,
+ resourceScheduler,
+ mediaCapture: {
+ discardSession: vi.fn(async () => undefined),
+ discardInstance: vi.fn(async () => undefined),
+ } as unknown as IOSSimulatorMediaCaptureAdapter,
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),
+ });
+ await host.reconcileOwnership();
+
+ const attach = host.callTool(
+ 'attach_device',
+ { udid: READY_REPORT.devices[0]!.udid },
+ { sessionId: 'session-a', origin: 'user' },
+ );
+ await vi.waitFor(() => expect(driverManager.start).toHaveBeenCalledOnce());
+ const attached = actor.list('session-a')[0]!;
+ const cleanup = host.cleanupRemovedSession('session-a');
+ resolveDriverStart({
+ instanceId: attached.instanceId,
+ simulatorUdid: attached.simulatorUdid,
+ pid: 42,
+ driver: {},
+ driverSessionId: 'wda-session',
+ } as unknown as WdaRunningInstance);
+
+ await expect(attach).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'MUTATION_CANCELLED',
+ });
+ await expect(cleanup).resolves.toBeUndefined();
+ expect(actor.list('session-a')).toEqual([]);
+ expect(resourceScheduler.runningCount()).toBe(0);
+ expect(driverManager.stop).toHaveBeenCalledWith(attached.instanceId);
+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();
+ expect(lifecycle.deleteExact).not.toHaveBeenCalled();
+ });
+
+ it('waits for a racing create and deletes the late Cindy-owned device', async () => {
+ const template = {
+ ...READY_REPORT.devices[0]!,
+ deviceTypeIdentifier: 'com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro',
+ };
+ const createdDevice = {
+ ...template,
+ udid: '2A9D41E0-E031-4AD0-A8B5-847480802E8E',
+ name: 'Late Cindy iPhone',
+ state: 'Shutdown' as const,
+ };
+ let resolveCreate: (device: {
+ udid: string;
+ name: string;
+ runtimeIdentifier: string;
+ deviceTypeIdentifier: string;
+ }) => void = () => undefined;
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(async () => createdDevice),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(),
+ createExact: vi.fn(
+ (_input: Parameters<IOSSimulatorSimctlLifecycle['createExact']>[0]) =>
+ new Promise<Awaited<ReturnType<IOSSimulatorSimctlLifecycle['createExact']>>>(
+ (resolve) => {
+ resolveCreate = resolve;
+ },
+ ),
+ ),
+ deleteExact: vi.fn(async () => undefined),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),
+ lifecycle,
+ });
+ const environment = { ...READY_REPORT, devices: [template] };
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ mediaCapture: {
+ discardSession: vi.fn(async () => undefined),
+ discardInstance: vi.fn(async () => undefined),
+ } as unknown as IOSSimulatorMediaCaptureAdapter,
+ runtime: { inspect: vi.fn(async () => environment) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),
+ });
+ await host.reconcileOwnership();
+
+ const create = host.callTool(
+ 'create_instance',
+ { templateUdid: template.udid, name: createdDevice.name },
+ { sessionId: 'session-a', origin: 'user' },
+ );
+ await vi.waitFor(() => expect(lifecycle.createExact).toHaveBeenCalledOnce());
+ const cleanup = host.cleanupRemovedSession('session-a');
+ resolveCreate({
+ udid: createdDevice.udid,
+ name: createdDevice.name,
+ runtimeIdentifier: createdDevice.runtimeIdentifier,
+ deviceTypeIdentifier: createdDevice.deviceTypeIdentifier!,
+ });
+
+ await expect(create).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'MUTATION_CANCELLED',
+ });
+ await expect(cleanup).resolves.toBeUndefined();
+ expect(actor.list('session-a')).toEqual([]);
+ expect(lifecycle.findExact).toHaveBeenCalledWith(createdDevice.udid);
+ expect(lifecycle.shutdownExact).not.toHaveBeenCalled();
+ expect(lifecycle.deleteExact).toHaveBeenCalledWith(createdDevice.udid);
+ });
+
it('does not register a build after its task is archived at the reconcile boundary', async () => {
const lifecycle: IOSSimulatorSimctlLifecycle = {
findExact: vi.fn(),
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
index 34c2592876..98245688a1 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
@@ -198,6 +198,8 @@ export interface IOSSimulatorHost {
abortOperationsForExit(): void;
/** Cancel build processes before a task is archived, deleted, or its worktree is recycled. */
cancelSessionOperations(sessionId: string): Promise<void>;
+ /** Tear down all simulator runtime and ownership after a task is durably removed. */
+ cleanupRemovedSession(sessionId: string): Promise<void>;
reconcileOwnership(): Promise<void>;
describeTools(sessionId: string): Promise<IOSSimulatorToolAvailabilityReport>;
getStatus(sessionId: string): Promise<IOSSimulatorSessionStatus>;
@@ -254,9 +256,20 @@ export interface IOSSimulatorHost {
}
type SessionResolution =
- | { ok: true; sessionId: string; session: IOSSimulatorSessionSnapshot }
+ | {
+ ok: true;
+ sessionId: string;
+ session: IOSSimulatorSessionSnapshot;
+ removalBarrierOperation?: IOSSimulatorSessionRemovalBarrierOperation;
+ }
| Extract<IOSSimulatorSessionStatus, { ok: false }>;
+interface IOSSimulatorSessionRemovalBarrierOperation {
+ admissionEpoch: number;
+ settled: Promise<void>;
+ finish(): void;
+}
+
function sessionError(
sessionId: string | null,
errorCode: IOSSimulatorMcpErrorCode,
@@ -816,6 +829,12 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
};
const activeBuilds = new Map<string, ActiveBuild>();
const sessionOperationAdmissionEpochs = new Map<string, number>();
+ const sessionRemovalAdmissionEpochs = new Map<string, number>();
+ const activeSessionRemovalBarrierOperations = new Map<
+ string,
+ Set<IOSSimulatorSessionRemovalBarrierOperation>
+ >();
+ const sessionRemovalCleanupPromises = new Map<string, Promise<void>>();
const blockedBuildInstances = new Set<string>();
const instanceLifecycleBarriers = new Map<string, { epoch: number; pendingTeardowns: number }>();
const mediaCapture = options.mediaCapture ?? new IOSSimulatorMediaCapture();
@@ -900,6 +919,62 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
true,
);
}
+ function beginSessionRemovalBarrierOperation(
+ sessionId: string,
+ expectedRemovalEpoch: number,
+ ): IOSSimulatorSessionRemovalBarrierOperation {
+ if (
+ (sessionRemovalAdmissionEpochs.get(sessionId) ?? 0) !== expectedRemovalEpoch ||
+ sessionRemovalCleanupPromises.has(sessionId)
+ ) {
+ throw new IOSSimulatorInstanceError(
+ 'MUTATION_CANCELLED',
+ 'The simulator binding was cancelled because its Cindy task lifecycle changed.',
+ true,
+ );
+ }
+ let resolveSettled: () => void = () => undefined;
+ const settled = new Promise<void>((resolve) => {
+ resolveSettled = resolve;
+ });
+ let finished = false;
+ const operation: IOSSimulatorSessionRemovalBarrierOperation = {
+ admissionEpoch: expectedRemovalEpoch,
+ settled,
+ finish() {
+ if (finished) return;
+ finished = true;
+ const operations = activeSessionRemovalBarrierOperations.get(sessionId);
+ operations?.delete(operation);
+ if (operations?.size === 0) activeSessionRemovalBarrierOperations.delete(sessionId);
+ resolveSettled();
+ },
+ };
+ let operations = activeSessionRemovalBarrierOperations.get(sessionId);
+ if (!operations) {
+ operations = new Set();
+ activeSessionRemovalBarrierOperations.set(sessionId, operations);
+ }
+ operations.add(operation);
+ return operation;
+ }
+ function assertSessionRemovalAdmission(
+ sessionId: string,
+ operation: IOSSimulatorSessionRemovalBarrierOperation | null,
+ ): void {
+ if (
+ operation &&
+ (sessionRemovalAdmissionEpochs.get(sessionId) ?? 0) === operation.admissionEpoch &&
+ !sessionRemovalCleanupPromises.has(sessionId)
+ ) {
+ return;
+ }
+ throw new IOSSimulatorInstanceError(
+ 'MUTATION_CANCELLED',
+ 'The simulator binding was cancelled because its Cindy task lifecycle changed.',
+ true,
+ );
+ }
function beginBuild(instance: IOSSimulatorInstance, expectedSessionEpoch: number): ActiveBuild {
if (disposePromise) throw new IOSSimulatorHostDisposedError();
assertSessionOperationAdmission(instance.sessionId, expectedSessionEpoch, 'app build');
@@ -1485,11 +1560,15 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
}
});
- async function resolveSession(sessionId: string): Promise<SessionResolution> {
+ async function resolveSession(
+ sessionId: string,
+ options: { registerRemovalBarrier?: boolean } = {},
+ ): Promise<SessionResolution> {
const normalizedSessionId = sessionId.trim();
if (!normalizedSessionId) {
return sessionError(null, 'SESSION_CONTEXT_REQUIRED', 'A Cindy session is required.');
}
+ const removalAdmissionEpoch = sessionRemovalAdmissionEpochs.get(normalizedSessionId) ?? 0;
const session = await getSession(normalizedSessionId);
if (!session) {
return sessionError(
@@ -1512,7 +1591,10 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
'SSH and remote sessions cannot access simulators on this Mac.',
);
}
- return { ok: true, sessionId: normalizedSessionId, session };
+ const removalBarrierOperation = options.registerRemovalBarrier
+ ? beginSessionRemovalBarrierOperation(normalizedSessionId, removalAdmissionEpoch)
+ : undefined;
+ return { ok: true, sessionId: normalizedSessionId, session, removalBarrierOperation };
}
function currentOwnedInstance(instance: IOSSimulatorInstance): IOSSimulatorInstance {
@@ -1586,6 +1668,200 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
}
}
+ function clearInstanceRuntimeProjection(instanceId: string): void {
+ cancelIdleRecycle(instanceId);
+ releaseViewerTouches(instanceId);
+ screenMaps.clear(instanceId);
+ framePump.clear(instanceId);
+ h264FramePump.clear(instanceId);
+ viewerEncodings.delete(instanceId);
+ viewerPreferredEncodings.delete(instanceId);
+ viewerFallbackReasons.delete(instanceId);
+ viewerSessions.delete(instanceId);
+ streamProfiles.delete(instanceId);
+ nativeStreamProfiles.delete(instanceId);
+ clearViewportState(instanceId);
+ clearVisualBaselines(instanceId);
+ deviceLivenessChecks.delete(instanceId);
+ routeStatusCache.delete(instanceId);
+ }
+
+ function clearRemovedInstanceProjection(instanceId: string): void {
+ agentControlLeases.delete(instanceId);
+ for (const [artifactId, stored] of appArtifacts) {
+ if (stored.instanceId === instanceId) appArtifacts.delete(artifactId);
+ }
+ }
+
+ async function releaseInstanceRuntime(instance: IOSSimulatorInstance): Promise<boolean> {
+ beginInstanceTeardown(instance.instanceId);
+ try {
+ await cancelBuild(instance.instanceId);
+ clearInstanceRuntimeProjection(instance.instanceId);
+ let cleanupSucceeded = true;
+ await mediaCapture.discardInstance(instance.instanceId).catch((error) => {
+ cleanupSucceeded = false;
+ logger.warn('iOS Simulator ownership cleanup could not discard recording', {
+ instanceId: instance.instanceId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+ if (driverManager) {
+ await driverManager.stop(instance.instanceId).catch((error) => {
+ cleanupSucceeded = false;
+ logger.warn('iOS Simulator ownership cleanup could not stop driver runtime', {
+ instanceId: instance.instanceId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+ }
+ return cleanupSucceeded;
+ } finally {
+ finishInstanceTeardown(instance.instanceId);
+ }
+ }
+
+ async function releaseStaleBinding(
+ instance: IOSSimulatorInstance,
+ device: IOSSimulatorEnvironmentReport['devices'][number] | null | undefined,
+ deviceStateKnown = true,
+ ): Promise<boolean> {
+ const hostOwnsBoot =
+ instance.bootProvenance === 'agent-booted' || instance.creationProvenance === 'cindy';
+ const deviceState = device?.state.trim().toLowerCase() ?? null;
+ let deviceStopped = deviceStateKnown && (!device || deviceState === 'shutdown');
+ let cleanupSucceeded = await releaseInstanceRuntime(instance);
+ clearRemovedInstanceProjection(instance.instanceId);
+ let schedulerReleaseAllowed = cleanupSucceeded && (!hostOwnsBoot || deviceStopped);
+ if (cleanupSucceeded && hostOwnsBoot && !deviceStopped) {
+ if (!deviceStateKnown) {
+ cleanupSucceeded = false;
+ logger.warn('iOS Simulator stale binding cleanup could not verify exact device state', {
+ instanceId: instance.instanceId,
+ });
+ } else {
+ try {
+ await lifecycle.shutdownExact(instance.simulatorUdid);
+ deviceStopped = true;
+ schedulerReleaseAllowed = true;
+ } catch (error) {
+ cleanupSucceeded = false;
+ logger.warn('iOS Simulator stale binding cleanup could not shut down device', {
+ instanceId: instance.instanceId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ }
+ // A known-missing Cindy-created device is already deleted. Reissuing
+ // `simctl delete` would turn successful external cleanup into a permanent
+ // retry loop, so only delete when the exact device still exists.
+ if (instance.creationProvenance === 'cindy' && cleanupSucceeded && device) {
+ await lifecycle.deleteExact(instance.simulatorUdid).catch((error) => {
+ cleanupSucceeded = false;
+ logger.warn('iOS Simulator stale binding cleanup could not delete device', {
+ instanceId: instance.instanceId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+ }
+ if (schedulerReleaseAllowed) resourceScheduler.markStopped(instance.instanceId);
+ if (cleanupSucceeded) {
+ actor.forget(instance.instanceId, instance.sessionId);
+ } else {
+ ownershipReconciled = false;
+ actor.reconcile(
+ instance.instanceId,
+ instance.sessionId,
+ deviceStopped ? 'stopped' : 'error',
+ 'degraded',
+ 'ARCHIVED_CLEANUP_FAILED',
+ );
+ }
+ return cleanupSucceeded;
+ }
+
+ async function performRemovedSessionCleanup(sessionId: string): Promise<void> {
+ await cancelSessionBuildsAndRecordings(sessionId);
+ await Promise.all(
+ [...(activeSessionRemovalBarrierOperations.get(sessionId) ?? [])].map(
+ (operation) => operation.settled,
+ ),
+ );
+ const failures = new Set<string>();
+ for (const snapshot of actor.list(sessionId)) {
+ try {
+ const released = await actor.runOwnershipCleanup(
+ snapshot.instanceId,
+ sessionId,
+ async (instance) => {
+ const hostOwnsBoot =
+ instance.bootProvenance === 'agent-booted' || instance.creationProvenance === 'cindy';
+ let device: IOSSimulatorEnvironmentReport['devices'][number] | null | undefined;
+ let deviceStateKnown = !hostOwnsBoot;
+ if (hostOwnsBoot) {
+ try {
+ device = await lifecycle.findExact(instance.simulatorUdid);
+ deviceStateKnown = device !== undefined;
+ } catch (error) {
+ logger.warn('iOS Simulator removed task cleanup could not inspect exact device', {
+ sessionId,
+ instanceId: instance.instanceId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ return releaseStaleBinding(instance, device, deviceStateKnown);
+ },
+ );
+ if (!released) failures.add(snapshot.instanceId);
+ else {
+ blockedBuildInstances.delete(snapshot.instanceId);
+ instanceLifecycleBarriers.delete(snapshot.instanceId);
+ }
+ } catch (error) {
+ if (
+ isInstanceError(error, 'INSTANCE_NOT_OWNED') &&
+ !actor.list(sessionId).some((instance) => instance.instanceId === snapshot.instanceId)
+ ) {
+ continue;
+ }
+ failures.add(snapshot.instanceId);
+ logger.warn('iOS Simulator removed task cleanup failed', {
+ sessionId,
+ instanceId: snapshot.instanceId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ if (failures.size > 0) {
+ throw new IOSSimulatorInstanceError(
+ 'DEVICE_BUSY',
+ `Simulator cleanup is still pending for ${failures.size} instance(s).`,
+ true,
+ );
+ }
+ }
+
+ function cleanupRemovedSessionRuntime(sessionId: string): Promise<void> {
+ const normalizedSessionId = sessionId.trim();
+ const existing = sessionRemovalCleanupPromises.get(normalizedSessionId);
+ if (existing) return existing;
+ sessionRemovalAdmissionEpochs.set(
+ normalizedSessionId,
+ (sessionRemovalAdmissionEpochs.get(normalizedSessionId) ?? 0) + 1,
+ );
+ let trackedCleanup: Promise<void>;
+ const cleanup = Promise.resolve().then(() => performRemovedSessionCleanup(normalizedSessionId));
+ trackedCleanup = cleanup.finally(() => {
+ if (sessionRemovalCleanupPromises.get(normalizedSessionId) === trackedCleanup) {
+ sessionRemovalCleanupPromises.delete(normalizedSessionId);
+ }
+ });
+ sessionRemovalCleanupPromises.set(normalizedSessionId, trackedCleanup);
+ return trackedCleanup;
+ }
+
async function reconcileLiveDevice(
instance: IOSSimulatorInstance,
): Promise<IOSSimulatorInstance> {
@@ -1821,103 +2097,6 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
environment.devices.map((device) => [device.udid.toUpperCase(), device]),
);
let complete = true;
- const discardInstanceMedia = async (instance: IOSSimulatorInstance): Promise<boolean> => {
- try {
- await mediaCapture.discardInstance(instance.instanceId);
- clearVisualBaselines(instance.instanceId);
- return true;
- } catch (error) {
- complete = false;
- logger.warn('iOS Simulator ownership reconcile could not discard recording', {
- instanceId: instance.instanceId,
- error: error instanceof Error ? error.message : String(error),
- });
- return false;
- }
- };
- const releaseInstanceRuntime = async (instance: IOSSimulatorInstance): Promise<boolean> => {
- 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);
- if (driverManager) {
- await driverManager.stop(instance.instanceId).catch((error) => {
- 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),
- });
- });
- }
- return cleanupSucceeded;
- } finally {
- finishInstanceTeardown(instance.instanceId);
- }
- };
- const releaseStaleBinding = async (
- instance: IOSSimulatorInstance,
- device: IOSSimulatorEnvironmentReport['devices'][number] | undefined,
- ): Promise<void> => {
- // Archived sessions cannot be routed by callers. Apply the same
- // provenance rule as detach/quit: only shut down a device Cindy or an
- // Agent booted; never mutate a user-owned external device. Cindy-created
- // devices are safe to delete after they are stopped.
- const deviceState = device?.state.trim().toLowerCase() ?? null;
- let deviceStopped = !device || deviceState === 'shutdown';
- let cleanupSucceeded = await releaseInstanceRuntime(instance);
- const hostOwnsBoot =
- instance.bootProvenance === 'agent-booted' || instance.creationProvenance === 'cindy';
- let schedulerReleaseAllowed = cleanupSucceeded && (!hostOwnsBoot || deviceStopped);
- if (cleanupSucceeded && hostOwnsBoot && !deviceStopped) {
- try {
- await lifecycle.shutdownExact(instance.simulatorUdid);
- deviceStopped = true;
- schedulerReleaseAllowed = true;
- } catch (error) {
- cleanupSucceeded = false;
- complete = false;
- logger.warn('iOS Simulator stale binding cleanup could not shut down device', {
- instanceId: instance.instanceId,
- error: error instanceof Error ? error.message : String(error),
- });
- }
- }
- if (instance.creationProvenance === 'cindy' && cleanupSucceeded) {
- await lifecycle.deleteExact(instance.simulatorUdid).catch((error) => {
- cleanupSucceeded = false;
- complete = false;
- logger.warn('iOS Simulator stale binding cleanup could not delete device', {
- instanceId: instance.instanceId,
- error: error instanceof Error ? error.message : String(error),
- });
- });
- }
- if (schedulerReleaseAllowed) resourceScheduler.markStopped(instance.instanceId);
- if (cleanupSucceeded) {
- actor.forget(instance.instanceId, instance.sessionId);
- } else {
- // Preserve the record when an external mutation failed so a future
- // Cindy start can retry cleanup instead of losing ownership.
- actor.reconcile(
- instance.instanceId,
- instance.sessionId,
- deviceStopped ? 'stopped' : 'error',
- 'degraded',
- 'ARCHIVED_CLEANUP_FAILED',
- );
- }
- };
for (const instance of actor.listAll()) {
let session: IOSSimulatorSessionSnapshot | null = null;
try {
@@ -1932,39 +2111,20 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
}
const device = devices.get(instance.simulatorUdid.toUpperCase());
if (!session) {
- await releaseStaleBinding(instance, device);
+ if (!(await releaseStaleBinding(instance, device))) complete = false;
continue;
}
if (session.status === 'deleted') {
- await releaseStaleBinding(instance, device);
+ if (!(await releaseStaleBinding(instance, device))) complete = false;
continue;
}
if (session.status === 'archived') {
- if (
- instance.creationProvenance === 'cindy' ||
- instance.bootProvenance === 'agent-booted'
- ) {
- await releaseStaleBinding(instance, device);
- } else {
- // External/preexisting devices remain untouched, but the archived
- // Session must no longer retain an unroutable ownership record.
- if (await releaseInstanceRuntime(instance)) {
- resourceScheduler.markStopped(instance.instanceId);
- actor.forget(instance.instanceId, instance.sessionId);
- } else {
- actor.reconcile(
- instance.instanceId,
- instance.sessionId,
- device?.state.toLowerCase() === 'booted' ? 'ready' : 'stopped',
- 'degraded',
- 'ARCHIVED_CLEANUP_FAILED',
- );
- }
- }
+ if (!(await releaseStaleBinding(instance, device))) complete = false;
continue;
}
if (session.remoteHostId || !device) {
const runtimeReleased = await releaseInstanceRuntime(instance);
+ if (!runtimeReleased) complete = false;
if (runtimeReleased && (!device || device.state.trim().toLowerCase() === 'shutdown')) {
resourceScheduler.markStopped(instance.instanceId);
}
@@ -1979,14 +2139,15 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
}
const deviceState = device.state.trim().toLowerCase();
if (deviceState === 'shutdown') {
- if (await releaseInstanceRuntime(instance)) {
+ const runtimeReleased = await releaseInstanceRuntime(instance);
+ if (runtimeReleased) {
resourceScheduler.markStopped(instance.instanceId);
- }
+ } else complete = false;
} else if (deviceState !== 'booted') {
// Booting / Shutting Down / unknown concrete states may still own a
// CoreSimulator process. Tear down Cindy media but keep scheduler
// occupancy until a later probe proves the device is Shutdown.
- await releaseInstanceRuntime(instance);
+ if (!(await releaseInstanceRuntime(instance))) complete = false;
}
actor.reconcile(
instance.instanceId,
@@ -3057,10 +3218,15 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
viewerToken,
) {
let viewerClaimReservation: ReturnType<typeof reserveViewerClaim> = null;
+ let removalBarrierOperation: IOSSimulatorSessionRemovalBarrierOperation | null = null;
try {
assertHostActive();
- const resolved = await resolveSession(sessionId);
+ const resolved = await resolveSession(sessionId, {
+ registerRemovalBarrier: visible,
+ });
if (!resolved.ok) return resolved;
+ removalBarrierOperation = resolved.removalBarrierOperation ?? null;
+ if (visible) assertSessionRemovalAdmission(resolved.sessionId, removalBarrierOperation);
assertHostActive();
const mutationRoute = { ...route, sessionId: resolved.sessionId };
if (visible) {
@@ -3107,6 +3273,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
// re-arm a parked Sidecar.
const rearmNativeSidecar = !viewerSessions.has(instance.instanceId);
instance = await reconcileLiveDevice(instance);
+ if (visible) assertSessionRemovalAdmission(resolved.sessionId, removalBarrierOperation);
assertHostActive();
if (instance.lifecycleState !== 'ready') {
return viewerRouteRefreshResult(instance);
@@ -3120,6 +3287,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
if (!running) {
actor.markHealth(resolved.sessionId, instance.instanceId, 'recovering', null);
const environment = await runtime.inspect();
+ assertSessionRemovalAdmission(resolved.sessionId, removalBarrierOperation);
assertHostActive();
current = currentReadyGeneration(instance);
if (!current) return viewerRouteRefreshResult(currentOwnedInstance(instance));
@@ -3153,7 +3321,9 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
instance.instanceId,
async (commitRunning) => {
commitRunning();
- return ensureDriver(instance, environment);
+ const started = await ensureDriver(instance, environment);
+ assertSessionRemovalAdmission(resolved.sessionId, removalBarrierOperation);
+ return started;
},
);
} catch (error) {
@@ -3173,6 +3343,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
(await driverManager.recoverNativeSidecar(instance.instanceId, {
rearm: rearmNativeSidecar,
})) ?? running;
+ assertSessionRemovalAdmission(resolved.sessionId, removalBarrierOperation);
assertHostActive();
current = currentReadyGeneration(instance);
if (!current) return viewerRouteRefreshResult(currentOwnedInstance(instance));
@@ -3187,6 +3358,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
let viewport: IOSSimulatorPublicViewport;
try {
viewport = await readViewport(running);
+ assertSessionRemovalAdmission(resolved.sessionId, removalBarrierOperation);
} catch (error) {
current = currentReadyGeneration(instance);
if (!current) return viewerRouteRefreshResult(currentOwnedInstance(instance));
@@ -3233,17 +3405,22 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
return safeHostError(error, sessionId, 'set_viewer_visibility');
} finally {
viewerClaimReservation?.rollback();
+ removalBarrierOperation?.finish();
}
},
async getLatestFrame(sessionId, route, viewerWebContentsId) {
+ let removalBarrierOperation: IOSSimulatorSessionRemovalBarrierOperation | null = null;
try {
assertHostActive();
- const resolved = await resolveSession(sessionId);
+ const resolved = await resolveSession(sessionId, { registerRemovalBarrier: true });
if (!resolved.ok) return resolved;
+ removalBarrierOperation = resolved.removalBarrierOperation ?? null;
+ assertSessionRemovalAdmission(resolved.sessionId, removalBarrierOperation);
assertHostActive();
assertCurrentViewer(resolved.sessionId, route.instanceId, viewerWebContentsId);
let instance = actor.heartbeat({ ...route, sessionId: resolved.sessionId });
instance = await reconcileLiveDevice(instance);
+ assertSessionRemovalAdmission(resolved.sessionId, removalBarrierOperation);
assertHostActive();
if (instance.lifecycleState !== 'ready') {
return {
@@ -3263,6 +3440,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
: framePump.snapshot(instance.instanceId);
if (selectedEncoding === 'h264' && snapshot?.state === 'disconnected') {
const running = await getHealthyDriver(instance.instanceId);
+ assertSessionRemovalAdmission(resolved.sessionId, removalBarrierOperation);
h264FramePump.clear(instance.instanceId);
if (running) {
snapshot = startViewerStream(
@@ -3311,6 +3489,8 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
const expired = currentExpiredViewerRoute({ ...route, sessionId: sessionId.trim() }, error);
if (expired) stopViewerMedia(expired);
return safeHostError(error, sessionId, 'get_latest_frame');
+ } finally {
+ removalBarrierOperation?.finish();
}
},
async setAgentControlGrant(sessionId, instanceId, decision) {
@@ -3425,10 +3605,13 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
}
},
async setViewerStreamProfile(sessionId, route, profile, nativeProfile) {
+ let removalBarrierOperation: IOSSimulatorSessionRemovalBarrierOperation | null = null;
try {
assertHostActive();
- const resolved = await resolveSession(sessionId);
+ const resolved = await resolveSession(sessionId, { registerRemovalBarrier: true });
if (!resolved.ok) return resolved;
+ removalBarrierOperation = resolved.removalBarrierOperation ?? null;
+ assertSessionRemovalAdmission(resolved.sessionId, removalBarrierOperation);
assertHostActive();
if (
!Number.isSafeInteger(profile.framesPerSecond) ||
@@ -3473,11 +3656,13 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
if (!running) {
// The viewer may request its fallback profile while WDA is being rebuilt.
// Native-only intent is rejected above because no active route can prove it.
+ assertSessionRemovalAdmission(resolved.sessionId, removalBarrierOperation);
streamProfiles.set(instance.instanceId, profile);
nativeStreamProfiles.delete(instance.instanceId);
return { ok: true, data: { profile } };
}
const applied = await running.driver.configureStream(running.driverSessionId, profile);
+ assertSessionRemovalAdmission(resolved.sessionId, removalBarrierOperation);
assertHostActive();
streamProfiles.set(instance.instanceId, applied);
if (nativeProfile) nativeStreamProfiles.set(instance.instanceId, nativeProfile);
@@ -3512,6 +3697,8 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
};
} catch (error) {
return safeHostError(error, sessionId, 'set_viewer_stream_profile');
+ } finally {
+ removalBarrierOperation?.finish();
}
},
async callTool(name, args, context): Promise<IOSSimulatorHostResult> {
@@ -3524,9 +3711,14 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
};
}
if (disposePromise) return hostDisposedResult();
+ let removalBarrierOperation: IOSSimulatorSessionRemovalBarrierOperation | null = null;
try {
- const resolved = await resolveSession(sessionId);
+ const resolved = await resolveSession(sessionId, {
+ registerRemovalBarrier:
+ name === 'start_instance' || name === 'create_instance' || name === 'attach_device',
+ });
if (!resolved.ok) return resolved;
+ removalBarrierOperation = resolved.removalBarrierOperation ?? null;
assertHostActive();
await reconcilePersistedOwnership();
assertHostActive();
@@ -3543,10 +3735,12 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
};
}
if (name === 'start_instance') {
+ assertSessionRemovalAdmission(sessionId, removalBarrierOperation);
const route = readMutationRoute(sessionId, args);
requireControlGrant(actor.getOwned(sessionId, route.instanceId), context);
const activationEpoch = captureInstanceActivation(route.instanceId);
const environment = await runtime.inspect();
+ assertSessionRemovalAdmission(sessionId, removalBarrierOperation);
if (!environment.ready) {
const safeEnvironment = publicEnvironment(environment);
return {
@@ -3559,11 +3753,14 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
route.instanceId,
async (commitRunning) => {
assertHostActive();
+ assertSessionRemovalAdmission(sessionId, removalBarrierOperation);
const starting = actor.getOwned(sessionId, route.instanceId);
try {
const started = await actor.start(route);
+ assertSessionRemovalAdmission(sessionId, removalBarrierOperation);
commitRunning();
await ensureDriver(started, environment);
+ assertSessionRemovalAdmission(sessionId, removalBarrierOperation);
return actor.heartbeatOwned(sessionId, started.instanceId);
} catch (error) {
// simctl can boot the device and then fail while waiting for
@@ -3584,6 +3781,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
}
},
);
+ assertSessionRemovalAdmission(sessionId, removalBarrierOperation);
completeInstanceActivation(instance, activationEpoch);
releaseViewerTouches(instance.instanceId);
screenMaps.clear(instance.instanceId);
@@ -5107,7 +5305,9 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
'The selected template simulator does not exist or is unavailable.',
);
}
+ assertSessionRemovalAdmission(sessionId, removalBarrierOperation);
const worktreeRoot = await resolveWorktreeRoot(resolved.session.workDir);
+ assertSessionRemovalAdmission(sessionId, removalBarrierOperation);
const instance = await actor.create({
sessionId,
worktreeRoot,
@@ -5115,6 +5315,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
name: readString(args, 'name'),
templateDevice,
});
+ assertSessionRemovalAdmission(sessionId, removalBarrierOperation);
if (context?.origin === 'agent') {
agentControlLeases.set(instance.instanceId, sessionId);
}
@@ -5139,7 +5340,9 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
: null;
const attach = async (): Promise<IOSSimulatorHostResult> => {
assertHostActive();
+ assertSessionRemovalAdmission(sessionId, removalBarrierOperation);
const worktreeRoot = await resolveWorktreeRoot(resolved.session.workDir);
+ assertSessionRemovalAdmission(sessionId, removalBarrierOperation);
const instance = await actor.attachSerialized({
sessionId,
worktreeRoot,
@@ -5149,6 +5352,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
bootProvenance:
device.state.toLowerCase() === 'booted' ? 'preexisting' : 'user-booted',
});
+ assertSessionRemovalAdmission(sessionId, removalBarrierOperation);
const activationEpoch =
existingInstance?.instanceId === instance.instanceId &&
existingActivationEpoch !== null
@@ -5156,10 +5360,13 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
: captureInstanceActivation(instance.instanceId);
if (instance.lifecycleState === 'ready') {
await resourceScheduler.runStart(instance.instanceId, async (commitRunning) => {
+ assertSessionRemovalAdmission(sessionId, removalBarrierOperation);
commitRunning();
await ensureDriver(instance, environment);
+ assertSessionRemovalAdmission(sessionId, removalBarrierOperation);
});
}
+ assertSessionRemovalAdmission(sessionId, removalBarrierOperation);
const current = actor.getOwned(sessionId, instance.instanceId);
completeInstanceActivation(current, activationEpoch);
if (context?.origin === 'agent') {
@@ -5189,11 +5396,16 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
} catch (error) {
if (error instanceof IOSSimulatorHostDisposedError) return hostDisposedResult();
return safeHostError(error, sessionId, name);
+ } finally {
+ removalBarrierOperation?.finish();
}
},
cancelSessionOperations(sessionId) {
return cancelSessionBuildsAndRecordings(sessionId.trim());
},
+ cleanupRemovedSession(sessionId) {
+ return cleanupRemovedSessionRuntime(sessionId);
+ },
abortOperationsForExit() {
for (const build of activeBuilds.values()) build.controller.abort();
mediaCapture.abortOperationsForExit?.();
@@ -5366,6 +5578,11 @@ export function cancelIOSSimulatorSessionOperations(sessionId: string): Promise<
return defaultIOSSimulatorHost.cancelSessionOperations(sessionId);
}
+export function cleanupIOSSimulatorRemovedSession(sessionId: string): Promise<void> {
+ revokeIOSSimulatorRendererSession(sessionId);
+ return defaultIOSSimulatorHost.cleanupRemovedSession(sessionId);
+}
+
export function setIOSSimulatorViewerStreamProfile(
sessionId: string,
route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,
diff --git a/packages/ios-simulator-runtime/src/instance-actor.test.ts b/packages/ios-simulator-runtime/src/instance-actor.test.ts
index b8c12484a2..a18709f22c 100644
--- a/packages/ios-simulator-runtime/src/instance-actor.test.ts
+++ b/packages/ios-simulator-runtime/src/instance-actor.test.ts
@@ -555,4 +555,79 @@ describe("IOSSimulatorInstanceActor", () => {
harness.actor.runMutation(harness.route(), async () => "agent-ok"),
).resolves.toBe("agent-ok");
});
+
+ it("serializes ownership cleanup after cancelling active and queued Agent mutations", async () => {
+ const harness = createHarness({ booted: true });
+ let releaseActive: () => void = () => undefined;
+ let activeSignal: AbortSignal | undefined;
+ const order: string[] = [];
+ const active = harness.actor.runMutation(
+ harness.route(),
+ async (_instance, signal) => {
+ activeSignal = signal;
+ order.push("active");
+ await new Promise<void>((resolve) => {
+ releaseActive = resolve;
+ });
+ },
+ );
+ const queued = harness.actor
+ .runMutation(harness.route(), async () => order.push("queued"))
+ .catch((error: unknown) => error);
+
+ await vi.waitFor(() => expect(activeSignal).toBeDefined());
+ const cleanup = harness.actor.runOwnershipCleanup(
+ harness.instance.instanceId,
+ harness.instance.sessionId,
+ async (instance) => {
+ order.push("cleanup");
+ return instance;
+ },
+ );
+
+ expect(activeSignal?.aborted).toBe(true);
+ releaseActive();
+ await expect(active).rejects.toMatchObject({ code: "MUTATION_CANCELLED" });
+ await expect(queued).resolves.toMatchObject({ code: "MUTATION_CANCELLED" });
+ await expect(cleanup).resolves.toMatchObject({
+ instanceId: harness.instance.instanceId,
+ sessionId: harness.instance.sessionId,
+ });
+ expect(order).toEqual(["active", "cleanup"]);
+ });
+
+ it("does not disturb the current owner when stale cleanup names another session", async () => {
+ const harness = createHarness({ booted: true });
+ let releaseActive: () => void = () => undefined;
+ let activeSignal: AbortSignal | undefined;
+ const active = harness.actor.runMutation(
+ harness.route(),
+ async (_instance, signal) => {
+ activeSignal = signal;
+ await new Promise<void>((resolve) => {
+ releaseActive = resolve;
+ });
+ return "completed";
+ },
+ );
+ await vi.waitFor(() => expect(activeSignal).toBeDefined());
+
+ expect(() =>
+ harness.actor.runOwnershipCleanup(
+ harness.instance.instanceId,
+ "stale-session",
+ async () => undefined,
+ ),
+ ).toThrowError(expect.objectContaining({ code: "INSTANCE_NOT_OWNED" }));
+
+ expect(activeSignal?.aborted).toBe(false);
+ expect(
+ harness.actor.mutationState(harness.instance.instanceId),
+ ).toMatchObject({
+ activeSource: "agent",
+ queuedAgentMutations: 0,
+ });
+ releaseActive();
+ await expect(active).resolves.toBe("completed");
+ });
});
diff --git a/packages/ios-simulator-runtime/src/instance-actor.ts b/packages/ios-simulator-runtime/src/instance-actor.ts
index 5e02a47f45..93f10257ff 100644
--- a/packages/ios-simulator-runtime/src/instance-actor.ts
+++ b/packages/ios-simulator-runtime/src/instance-actor.ts
@@ -455,6 +455,32 @@ export class IOSSimulatorInstanceActor {
});
}
+ /**
+ * Serialize Host-owned cleanup behind any active instance mutation while
+ * invalidating queued Agent work. The callback receives ownership only after
+ * the exact session still owns the instance, so task removal cannot tear down
+ * a device that was concurrently rebound elsewhere.
+ */
+ runOwnershipCleanup<T>(
+ instanceId: string,
+ sessionId: string,
+ task: (instance: IOSSimulatorInstance) => Promise<T>,
+ ): Promise<T> {
+ // Validate the old owner before changing mutation/grace state. The
+ // serialized check below is still required because ownership can be
+ // rebound while cleanup waits behind an existing instance operation.
+ this.#store.requireOwned(instanceId, sessionId);
+ const state = this.#mutationState(instanceId);
+ state.takeoverEpoch += 1;
+ this.#cancelActiveAgentMutation(instanceId);
+ this.#cancelGrace.get(instanceId)?.();
+ this.#cancelGrace.delete(instanceId);
+ return this.#serialize(instanceId, async () => {
+ const instance = this.#store.requireOwned(instanceId, sessionId);
+ return task(instance);
+ });
+ }
+
#cancelActiveAgentMutation(instanceId: string): void {
this.#activeAgentMutations.get(instanceId)?.abort();
}