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 ownership boundaries

JiangJiahao0504c7029c0d
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 44af8bc377..2a9eccccce 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -4142,6 +4142,17 @@ const registerIpcHandlers = () => {
refreshXdGatewayModels,
waitForAccountProviderModelsReady: waitForCurrentAccountProviderModelsReady,
onProviderModelAutoRefreshConfigured: markMakerProviderRefreshConfigured,
+ resolveIOSSimulatorRendererUrl: (event) => {
+ const sender = (event as { sender?: { getURL?: () => string } })?.sender;
+ if (!sender) return '';
+ if (sender === rsbWindowController.getSidebarWebContents()) {
+ const mainWindow = mainWindowRef;
+ return mainWindow && !mainWindow.isDestroyed() && !mainWindow.webContents.isDestroyed()
+ ? mainWindow.webContents.getURL()
+ : '';
+ }
+ return typeof sender.getURL === 'function' ? sender.getURL() : '';
+ },
});
registerMakerTitleIpc({ isSessionTurnPendingCompletion });
registerMakerHelpIpc(ipcMaker);
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 2aa8c2859e..dfd4f598bd 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts
@@ -11,6 +11,7 @@ describe('iOS Simulator IPC handlers', () => {
function registerTrusted(harness: IpcHarness, deps: Partial<IOSSimulatorHandlerDeps> = {}): void {
registerIOSSimulatorHandlers(harness, {
assertTrustedSender: () => undefined,
+ getRendererUrl: () => 'file:///app/index.html#/cc-agent/session-a',
...deps,
});
}
@@ -50,7 +51,7 @@ describe('iOS Simulator IPC handlers', () => {
registerTrusted(harness, { getStatus });
await expect(
- harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_STATUS, {
+ harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_STATUS, {
sessionId: ' session-a ',
}),
).resolves.toMatchObject({ sessionId: 'session-a' });
@@ -66,13 +67,40 @@ describe('iOS Simulator IPC handlers', () => {
});
});
+ it('rejects cross-task status and lifecycle calls from another renderer window', async () => {
+ const harness = new IpcHarness();
+ const getStatus = vi.fn();
+ const callTool = vi.fn();
+ registerIOSSimulatorHandlers(harness, {
+ assertTrustedSender: () => undefined,
+ getRendererUrl: () => 'file:///app/index.html#/cc-agent/session-b',
+ getStatus,
+ callTool,
+ });
+
+ await expect(
+ harness.invokeFrom(18, MAKER_INVOKE.IOS_SIMULATOR_STATUS, {
+ sessionId: 'session-a',
+ }),
+ ).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
+ await expect(
+ harness.invokeFrom(18, MAKER_INVOKE.IOS_SIMULATOR_CALL, {
+ sessionId: 'session-a',
+ name: 'stop_instance',
+ args: { instanceId: 'instance-a', generation: 1, leaseId: 'lease-a' },
+ }),
+ ).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
+ expect(getStatus).not.toHaveBeenCalled();
+ expect(callTool).not.toHaveBeenCalled();
+ });
+
it('validates and routes user lifecycle calls through the shared host', async () => {
const harness = new IpcHarness();
const callTool = vi.fn(async () => ({ ok: true as const, data: { instances: [] } }));
registerTrusted(harness, { callTool });
await expect(
- harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_CALL, {
+ harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_CALL, {
sessionId: 'session-a',
name: 'attach_device',
args: {},
@@ -81,7 +109,7 @@ describe('iOS Simulator IPC handlers', () => {
expect(callTool).toHaveBeenCalledWith('attach_device', {}, 'session-a');
for (const name of ['build_app', 'open_url', 'push_notification', 'delete_everything']) {
await expect(
- harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_CALL, {
+ harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_CALL, {
sessionId: 'session-a',
name,
args: {},
@@ -96,14 +124,14 @@ describe('iOS Simulator IPC handlers', () => {
const setAgentControlGrant = vi.fn(async () => ({ ok: true as const, data: {} }));
registerTrusted(harness, { setAgentControlGrant });
- await harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_SET_AGENT_CONTROL, {
+ await harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_SET_AGENT_CONTROL, {
sessionId: 'session-a',
instanceId: 'instance-a',
decision: 'allowed',
});
expect(setAgentControlGrant).toHaveBeenCalledWith('session-a', 'instance-a', 'allowed');
await expect(
- harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_SET_AGENT_CONTROL, {
+ harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_SET_AGENT_CONTROL, {
sessionId: 'session-a',
instanceId: 'instance-a',
decision: 'unknown',
@@ -122,7 +150,7 @@ describe('iOS Simulator IPC handlers', () => {
leaseId: 'lease-a',
};
- await harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_SET_MUTATION_CONTROL, {
+ await harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_SET_MUTATION_CONTROL, {
...route,
paused: true,
});
@@ -132,7 +160,7 @@ describe('iOS Simulator IPC handlers', () => {
true,
);
await expect(
- harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_SET_MUTATION_CONTROL, {
+ harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_SET_MUTATION_CONTROL, {
...route,
paused: 'yes',
}),
@@ -209,7 +237,7 @@ describe('iOS Simulator IPC handlers', () => {
harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_LATEST_FRAME, route),
).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
await expect(
- harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_LATEST_FRAME, {
+ harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_LATEST_FRAME, {
...route,
generation: 0,
}),
@@ -254,7 +282,7 @@ describe('iOS Simulator IPC handlers', () => {
generation: 3,
leaseId: 'lease-a',
};
- await harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_SET_STREAM_PROFILE, {
+ await harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_SET_STREAM_PROFILE, {
...route,
profile: { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 },
nativeProfile: { framesPerSecond: 60, scalingPercent: 70 },
@@ -266,13 +294,13 @@ describe('iOS Simulator IPC handlers', () => {
{ framesPerSecond: 60, scalingPercent: 70 },
);
await expect(
- harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_SET_STREAM_PROFILE, {
+ harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_SET_STREAM_PROFILE, {
...route,
profile: { framesPerSecond: '10', jpegQuality: 45, scalingPercent: 70 },
}),
).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
await expect(
- harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_SET_STREAM_PROFILE, {
+ harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_SET_STREAM_PROFILE, {
...route,
profile: { framesPerSecond: 20, jpegQuality: 70, scalingPercent: 100 },
nativeProfile: { framesPerSecond: '60', scalingPercent: 70 },
@@ -318,7 +346,7 @@ describe('iOS Simulator IPC handlers', () => {
}),
).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
await expect(
- harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_LIVE_TOUCH, {
+ harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_LIVE_TOUCH, {
...route,
gestureId: 'viewer-7',
phase: 'move',
diff --git a/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts b/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts
index 40b6100447..a3298cbfe2 100644
--- a/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts
@@ -5,6 +5,7 @@ import type {
IOSSimulatorToolResponse,
} from '../../shared/iosSimulatorIpc.js';
import { IOS_SIMULATOR_RENDERER_TOOL_NAMES } from '../../shared/iosSimulatorIpc.js';
+import { atContextVisibleSessionIdsFromRendererUrl } from '../../shared/atContextRouteScope.js';
import {
callIOSSimulatorHostTool,
getIOSSimulatorLatestFrame,
@@ -22,6 +23,7 @@ import type { IpcHandlerRegistry } from './ipcHandlerRegistry.js';
export interface IOSSimulatorHandlerDeps {
assertTrustedSender(event: unknown): void;
+ getRendererUrl(event: unknown): string;
getStatus(sessionId: string): Promise<IOSSimulatorSessionStatus>;
callTool(
name: IOSSimulatorRendererToolName,
@@ -74,6 +76,7 @@ export interface IOSSimulatorHandlerDeps {
const defaultDeps: IOSSimulatorHandlerDeps = {
assertTrustedSender: (event) =>
assertTrustedAppRendererEvent(event as Parameters<typeof assertTrustedAppRendererEvent>[0]),
+ getRendererUrl: readSenderWebContentsUrl,
getStatus: getIOSSimulatorSessionStatus,
callTool: callIOSSimulatorHostTool,
setAgentControlGrant: setIOSSimulatorAgentControlGrant,
@@ -130,6 +133,18 @@ function readSenderWebContentsId(event: unknown): number {
return Number(id);
}
+function readSenderWebContentsUrl(event: unknown): string {
+ const getURL = (event as { sender?: { getURL?: unknown } })?.sender?.getURL;
+ if (typeof getURL !== 'function') {
+ throwIpcError('PERMISSION_DENIED', 'trusted renderer sender URL is required');
+ }
+ try {
+ return String(getURL.call((event as { sender: unknown }).sender));
+ } catch {
+ throwIpcError('PERMISSION_DENIED', 'trusted renderer sender URL is required');
+ }
+}
+
export function registerIOSSimulatorHandlers(
registry: IpcHandlerRegistry,
deps: Partial<IOSSimulatorHandlerDeps> = {},
@@ -141,17 +156,26 @@ export function registerIOSSimulatorHandlers(
return handler(event, ...args);
});
};
- handle(MAKER_INVOKE.IOS_SIMULATOR_STATUS, async (_event, payload) => {
+ const assertSenderSession = (event: unknown, sessionId: string): number => {
+ const webContentsId = readSenderWebContentsId(event);
+ if (!atContextVisibleSessionIdsFromRendererUrl(resolved.getRendererUrl(event)).has(sessionId)) {
+ throwIpcError('PERMISSION_DENIED', 'iOS Simulator access is limited to the current task');
+ }
+ return webContentsId;
+ };
+ handle(MAKER_INVOKE.IOS_SIMULATOR_STATUS, async (event, payload) => {
const sessionId = readSessionId(payload);
+ assertSenderSession(event, sessionId);
try {
return await resolved.getStatus(sessionId);
} catch (error) {
throwIpcError('INTERNAL', error instanceof Error ? error.message : String(error));
}
});
- handle(MAKER_INVOKE.IOS_SIMULATOR_CALL, async (_event, payload) => {
+ handle(MAKER_INVOKE.IOS_SIMULATOR_CALL, async (event, payload) => {
const record = readRecord(payload);
const sessionId = readSessionId(record);
+ assertSenderSession(event, sessionId);
const name = record.name;
const args = record.args;
if (
@@ -169,9 +193,10 @@ export function registerIOSSimulatorHandlers(
sessionId,
);
});
- handle(MAKER_INVOKE.IOS_SIMULATOR_SET_AGENT_CONTROL, async (_event, payload) => {
+ handle(MAKER_INVOKE.IOS_SIMULATOR_SET_AGENT_CONTROL, async (event, payload) => {
const record = readRecord(payload);
const sessionId = readSessionId(record);
+ assertSenderSession(event, sessionId);
const instanceId = record.instanceId;
const decision = record.decision;
if (typeof instanceId !== 'string' || !instanceId.trim()) {
@@ -185,6 +210,7 @@ export function registerIOSSimulatorHandlers(
handle(MAKER_INVOKE.IOS_SIMULATOR_SET_VIEWER_VISIBILITY, async (event, payload) => {
const record = readRecord(payload);
const sessionId = readSessionId(record);
+ const viewerWebContentsId = assertSenderSession(event, sessionId);
if (typeof record.visible !== 'boolean') {
throwIpcError('INVALID_PARAMS', 'visible (boolean) required');
}
@@ -211,7 +237,6 @@ export function registerIOSSimulatorHandlers(
);
}
const route = readViewerRoute(record);
- const viewerWebContentsId = readSenderWebContentsId(event);
if (preferredEncoding === undefined && fallbackReason === undefined) {
return resolved.setViewerVisibility(
sessionId,
@@ -244,9 +269,10 @@ export function registerIOSSimulatorHandlers(
viewerToken?.trim(),
);
});
- handle(MAKER_INVOKE.IOS_SIMULATOR_SET_MUTATION_CONTROL, async (_event, payload) => {
+ handle(MAKER_INVOKE.IOS_SIMULATOR_SET_MUTATION_CONTROL, async (event, payload) => {
const record = readRecord(payload);
const sessionId = readSessionId(record);
+ assertSenderSession(event, sessionId);
if (typeof record.paused !== 'boolean') {
throwIpcError('INVALID_PARAMS', 'paused (boolean) required');
}
@@ -254,15 +280,17 @@ export function registerIOSSimulatorHandlers(
});
handle(MAKER_INVOKE.IOS_SIMULATOR_LATEST_FRAME, async (event, payload) => {
const record = readRecord(payload);
+ const sessionId = readSessionId(record);
return resolved.getLatestFrame(
- readSessionId(record),
+ sessionId,
readViewerRoute(record),
- readSenderWebContentsId(event),
+ assertSenderSession(event, sessionId),
);
});
- handle(MAKER_INVOKE.IOS_SIMULATOR_SET_STREAM_PROFILE, async (_event, payload) => {
+ handle(MAKER_INVOKE.IOS_SIMULATOR_SET_STREAM_PROFILE, async (event, payload) => {
const record = readRecord(payload);
const sessionId = readSessionId(record);
+ assertSenderSession(event, sessionId);
const profile = record.profile;
if (!profile || typeof profile !== 'object' || Array.isArray(profile)) {
throwIpcError('INVALID_PARAMS', 'profile must be an object');
@@ -311,6 +339,7 @@ export function registerIOSSimulatorHandlers(
handle(MAKER_INVOKE.IOS_SIMULATOR_LIVE_TOUCH, async (event, payload) => {
const record = readRecord(payload);
const sessionId = readSessionId(record);
+ const viewerWebContentsId = assertSenderSession(event, sessionId);
const gestureId = record.gestureId;
const phase = record.phase;
if (typeof gestureId !== 'string' || !gestureId.trim() || gestureId.trim().length > 128) {
@@ -331,16 +360,11 @@ export function registerIOSSimulatorHandlers(
) {
throwIpcError('INVALID_PARAMS', 'touch coordinates must be normalized');
}
- return resolved.updateViewerTouch(
- sessionId,
- readViewerRoute(record),
- readSenderWebContentsId(event),
- {
- gestureId: gestureId.trim(),
- phase,
- xRatio: record.xRatio,
- yRatio: record.yRatio,
- },
- );
+ return resolved.updateViewerTouch(sessionId, readViewerRoute(record), viewerWebContentsId, {
+ gestureId: gestureId.trim(),
+ phase,
+ xRatio: record.xRatio,
+ yRatio: record.yRatio,
+ });
});
}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index f48dd1cc23..19604ac495 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -4770,6 +4770,8 @@ export async function beginTurnChangeSetAtDispatch(
export interface RegisterMakerIpcOptions {
onAnySessionTurnKeepaliveChange?: (isRunning: boolean) => void;
+ /** Resolve detached sidebar calls against the Main-owned host window route. */
+ resolveIOSSimulatorRendererUrl?: (event: unknown) => string;
/** 由 bootstrap 注入,避免 maker-ipc → model-access → maker-host 的循环依赖。 */
refreshXdGatewayModels(): Promise<void>;
/** DB 可读后仍在后台运行的账号模型发现;新建 / 懒恢复路由前必须等待。 */
@@ -12302,7 +12304,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
registerAndroidAutomationHandlers(createElectronIpcHandlerRegistry());
// ── iOS Simulator pane / Agent discovery ────────────────────────────────
- registerIOSSimulatorHandlers(createElectronIpcHandlerRegistry());
+ registerIOSSimulatorHandlers(
+ createElectronIpcHandlerRegistry(),
+ options.resolveIOSSimulatorRendererUrl
+ ? { getRendererUrl: options.resolveIOSSimulatorRendererUrl }
+ : {},
+ );
void reconcileIOSSimulatorOwnership().catch((error) => {
log.warn('iOS Simulator ownership reconcile failed during IPC bootstrap', error);
});
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
index 9692bbfe80..73700158b4 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
@@ -771,43 +771,129 @@ describe('iOS Simulator host', () => {
expect(actor.listAll()).toEqual([]);
});
- it('keeps archived ownership when Cindy cleanup fails so a later restart can retry', async () => {
+ it.each(['Booted', 'Booting'] as const)(
+ 'keeps archived ownership and scheduler capacity when %s shutdown fails',
+ async (deviceState) => {
+ const sessionId = `archived-cleanup-failure-${deviceState.toLowerCase()}`;
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(async () => {
+ throw new Error('simctl shutdown failed');
+ }),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(async () => undefined),
+ };
+ const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });
+ const actor = new IOSSimulatorInstanceActor({ store, lifecycle });
+ const instance = actor.attach({
+ sessionId,
+ worktreeRoot: '/tmp/archived-cleanup-failure',
+ sourceFingerprint: 'fingerprint-a',
+ creationProvenance: 'cindy',
+ bootProvenance: 'agent-booted',
+ device: { ...READY_REPORT.devices[0]!, state: deviceState },
+ });
+ const resourceScheduler = testResourceScheduler();
+ await resourceScheduler.runStart(instance.instanceId, async () => undefined);
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ resourceScheduler,
+ runtime: {
+ inspect: vi.fn(async () => ({
+ ...READY_REPORT,
+ devices: [{ ...READY_REPORT.devices[0]!, state: deviceState }],
+ })),
+ },
+ getSession: vi.fn(async () => ({
+ ...localSession(sessionId),
+ status: 'archived' as const,
+ })),
+ });
+
+ await host.reconcileOwnership();
+
+ expect(actor.getOwned(sessionId, instance.instanceId)).toMatchObject({
+ healthState: 'degraded',
+ errorCode: 'ARCHIVED_CLEANUP_FAILED',
+ });
+ expect(resourceScheduler.runningCount()).toBe(1);
+ expect(lifecycle.deleteExact).not.toHaveBeenCalled();
+ },
+ );
+
+ it('releases scheduler capacity only after Simulator shutdown succeeds', async () => {
+ const shutdownExact = vi
+ .fn<() => Promise<void>>()
+ .mockRejectedValueOnce(
+ new IOSSimulatorInstanceError(
+ 'SIMULATOR_SHUTDOWN_FAILED',
+ 'simctl shutdown failed',
+ true,
+ ),
+ )
+ .mockResolvedValue(undefined);
const lifecycle: IOSSimulatorSimctlLifecycle = {
findExact: vi.fn(),
bootExact: vi.fn(),
- shutdownExact: vi.fn(async () => {
- throw new Error('simctl shutdown failed');
- }),
+ shutdownExact,
createExact: vi.fn(),
- deleteExact: vi.fn(async () => undefined),
+ deleteExact: vi.fn(),
};
- const store = new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() });
- const actor = new IOSSimulatorInstanceActor({ store, lifecycle });
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore({ createId: () => crypto.randomUUID() }),
+ lifecycle,
+ });
const instance = actor.attach({
- sessionId: 'archived-cleanup-failure',
- worktreeRoot: '/tmp/archived-cleanup-failure',
+ sessionId: 'shutdown-retry-session',
+ worktreeRoot: '/tmp/shutdown-retry-session',
sourceFingerprint: 'fingerprint-a',
- creationProvenance: 'cindy',
- bootProvenance: 'agent-booted',
device: { ...READY_REPORT.devices[0]!, state: 'Booted' },
});
+ const resourceScheduler = testResourceScheduler();
+ await resourceScheduler.runStart(instance.instanceId, async () => undefined);
const host = createIOSSimulatorHost({
actor,
lifecycle,
+ resourceScheduler,
+ driverManager: {
+ get: vi.fn(() => null),
+ start: vi.fn(),
+ stop: vi.fn(async () => undefined),
+ },
runtime: { inspect: vi.fn(async () => READY_REPORT) },
- getSession: vi.fn(async () => ({
- ...localSession('archived-cleanup-failure'),
- status: 'archived' as const,
- })),
+ getSession: vi.fn(async () => localSession('shutdown-retry-session')),
});
-
await host.reconcileOwnership();
+ const current = actor.getOwned('shutdown-retry-session', instance.instanceId);
+ const route = {
+ instanceId: current.instanceId,
+ generation: current.generation,
+ leaseId: current.lease.id,
+ };
- expect(actor.getOwned('archived-cleanup-failure', instance.instanceId)).toMatchObject({
- healthState: 'degraded',
- errorCode: 'ARCHIVED_CLEANUP_FAILED',
+ await expect(
+ host.callTool('stop_instance', route, {
+ sessionId: 'shutdown-retry-session',
+ origin: 'user',
+ }),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'SIMULATOR_SHUTDOWN_FAILED' });
+ expect(resourceScheduler.runningCount()).toBe(1);
+ expect(actor.getOwned('shutdown-retry-session', instance.instanceId)).toMatchObject({
+ lifecycleState: 'error',
+ errorCode: 'SIMULATOR_SHUTDOWN_FAILED',
});
- expect(lifecycle.deleteExact).not.toHaveBeenCalled();
+
+ await expect(
+ host.callTool('stop_instance', route, {
+ sessionId: 'shutdown-retry-session',
+ origin: 'user',
+ }),
+ ).resolves.toMatchObject({ ok: true });
+ expect(resourceScheduler.runningCount()).toBe(0);
+ expect(shutdownExact).toHaveBeenCalledTimes(2);
+ await host.dispose();
});
it('disposes WDA and recording resources on host shutdown without changing ownership', async () => {
@@ -1561,8 +1647,9 @@ describe('iOS Simulator host', () => {
configureNativeStream: vi.fn(async (profile) => profile),
streamNativeFrames,
} as unknown as IOSSimulatorNativeSidecarDriver;
+ const getWindowSize = vi.fn(async () => ({ width: 393, height: 852 }));
const wdaDriver = {
- getWindowSize: vi.fn(async () => ({ width: 393, height: 852 })),
+ getWindowSize,
getOrientation: vi.fn(async () => 'PORTRAIT' as const),
};
const capabilityReport = () => ({
@@ -1599,6 +1686,7 @@ describe('iOS Simulator host', () => {
},
} as unknown as WdaRunningInstance;
const pushH264Frame = vi.fn();
+ const liveViewerIds = new Set([77, 88]);
const host = createIOSSimulatorHost({
actor,
lifecycle,
@@ -1610,6 +1698,7 @@ describe('iOS Simulator host', () => {
stop: vi.fn(async () => undefined),
},
pushH264Frame,
+ isViewerWebContentsAlive: (webContentsId) => liveViewerIds.has(webContentsId),
});
const route = {
instanceId: instance.instanceId,
@@ -1647,14 +1736,21 @@ describe('iOS Simulator host', () => {
await expect(
host.setViewerVisibility('session-a', route, true, 'h264', undefined, 88, 'viewer-b'),
- ).resolves.toMatchObject({ ok: true });
+ ).resolves.toMatchObject({ ok: false, errorCode: 'INSTANCE_NOT_OWNED' });
await emitFrame({ ...firstFrame, timestampMicros: 2 });
expect(pushH264Frame).toHaveBeenCalledTimes(2);
expect(pushH264Frame).toHaveBeenLastCalledWith(
- 88,
+ 77,
expect.objectContaining({ instanceId: instance.instanceId }),
);
+ await expect(
+ host.setViewerVisibility('session-a', route, false, 'h264', undefined, 77, 'viewer-a'),
+ ).resolves.toMatchObject({ ok: true });
+ await expect(
+ host.setViewerVisibility('session-a', route, true, 'h264', undefined, 88, 'viewer-b'),
+ ).resolves.toMatchObject({ ok: true });
+
await expect(
host.setViewerVisibility('session-a', route, true, 'h264', undefined, 88, 'viewer-c'),
).resolves.toMatchObject({ ok: true });
@@ -1668,6 +1764,63 @@ describe('iOS Simulator host', () => {
expect.objectContaining({ instanceId: instance.instanceId }),
);
+ let releaseStaleViewport: ((value: { width: number; height: number }) => void) | null = null;
+ getWindowSize.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ releaseStaleViewport = resolve;
+ }),
+ );
+ const staleRemount = host.setViewerVisibility(
+ 'session-a',
+ route,
+ true,
+ 'h264',
+ undefined,
+ 88,
+ 'viewer-d-stale',
+ );
+ await vi.waitFor(() => expect(releaseStaleViewport).not.toBeNull());
+ await expect(
+ host.setViewerVisibility(
+ 'session-a',
+ route,
+ true,
+ 'h264',
+ undefined,
+ 88,
+ 'viewer-e-current',
+ ),
+ ).resolves.toMatchObject({ ok: true });
+ releaseStaleViewport?.({ width: 393, height: 852 });
+ await expect(staleRemount).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'INSTANCE_NOT_OWNED',
+ });
+ await expect(
+ host.setViewerVisibility(
+ 'session-a',
+ route,
+ false,
+ 'h264',
+ undefined,
+ 88,
+ 'viewer-d-stale',
+ ),
+ ).resolves.toMatchObject({ ok: true, data: { ignored: true } });
+
+ liveViewerIds.delete(88);
+ liveViewerIds.add(99);
+ await expect(
+ host.setViewerVisibility('session-a', route, true, 'h264', undefined, 99, 'viewer-f'),
+ ).resolves.toMatchObject({ ok: true });
+ await emitFrame({ ...firstFrame, timestampMicros: 4 });
+ expect(pushH264Frame).toHaveBeenCalledTimes(4);
+ expect(pushH264Frame).toHaveBeenLastCalledWith(
+ 99,
+ expect.objectContaining({ instanceId: instance.instanceId }),
+ );
+
const current = actor.getOwned('session-a', instance.instanceId);
await actor.stop({
sessionId: current.sessionId,
@@ -1675,8 +1828,8 @@ describe('iOS Simulator host', () => {
generation: current.generation,
leaseId: current.lease.id,
});
- await emitFrame({ ...firstFrame, timestampMicros: 4 });
- expect(pushH264Frame).toHaveBeenCalledTimes(3);
+ await emitFrame({ ...firstFrame, timestampMicros: 5 });
+ expect(pushH264Frame).toHaveBeenCalledTimes(4);
await host.dispose();
});
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
index 2b9dbd994a..65a1ac904f 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
@@ -178,6 +178,8 @@ export interface IOSSimulatorHostOptions {
pushRouteStatus?: (status: IOSSimulatorPublicRouteStatus) => void;
/** Main → exact owning viewer frame seam; injected in tests, fail-closed by default. */
pushH264Frame?: (viewerWebContentsId: number, frame: IOSSimulatorLatestH264Frame) => void;
+ /** Exact viewer liveness seam used to prevent cross-window ownership replacement. */
+ isViewerWebContentsAlive?: (viewerWebContentsId: number) => boolean;
}
export interface IOSSimulatorHost {
@@ -688,6 +690,16 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
},
});
});
+ const isViewerWebContentsAlive =
+ options.isViewerWebContentsAlive ??
+ ((viewerWebContentsId: number) =>
+ BrowserWindow.getAllWindows().some(
+ (candidate) =>
+ !candidate.isDestroyed() &&
+ !candidate.webContents.isDestroyed() &&
+ candidate.webContents.id === viewerWebContentsId &&
+ isTrustedAppRendererWindow(candidate),
+ ));
const h264FramePump =
options.h264FramePump ??
new IOSSimulatorH264FramePump({
@@ -1741,10 +1753,8 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
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', {
@@ -1753,7 +1763,6 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
});
});
}
- if (driverCleanupSucceeded) resourceScheduler.markStopped(instance.instanceId);
return cleanupSucceeded;
} finally {
finishInstanceTeardown(instance.instanceId);
@@ -1767,20 +1776,25 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
// 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);
- if (
- cleanupSucceeded &&
- device?.state.toLowerCase() === 'booted' &&
- (instance.bootProvenance === 'agent-booted' || instance.creationProvenance === 'cindy')
- ) {
- await lifecycle.shutdownExact(instance.simulatorUdid).catch((error) => {
+ 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) => {
@@ -1792,6 +1806,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
});
});
}
+ if (schedulerReleaseAllowed) resourceScheduler.markStopped(instance.instanceId);
if (cleanupSucceeded) {
actor.forget(instance.instanceId, instance.sessionId);
} else {
@@ -1800,7 +1815,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
actor.reconcile(
instance.instanceId,
instance.sessionId,
- device?.state.toLowerCase() === 'booted' ? 'ready' : 'stopped',
+ deviceStopped ? 'stopped' : 'error',
'degraded',
'ARCHIVED_CLEANUP_FAILED',
);
@@ -1837,6 +1852,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
// 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(
@@ -1851,7 +1867,13 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
continue;
}
if (session.remoteHostId || !device) {
- await releaseInstanceRuntime(instance);
+ const runtimeReleased = await releaseInstanceRuntime(instance);
+ if (
+ runtimeReleased &&
+ (!device || device.state.trim().toLowerCase() === 'shutdown')
+ ) {
+ resourceScheduler.markStopped(instance.instanceId);
+ }
actor.reconcile(
instance.instanceId,
instance.sessionId,
@@ -1861,14 +1883,30 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
);
continue;
}
- if (device.state.toLowerCase() !== 'booted') {
+ const deviceState = device.state.trim().toLowerCase();
+ if (deviceState === 'shutdown') {
+ if (await releaseInstanceRuntime(instance)) {
+ resourceScheduler.markStopped(instance.instanceId);
+ }
+ } 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);
}
actor.reconcile(
instance.instanceId,
instance.sessionId,
- device.state.toLowerCase() === 'booted' ? 'ready' : 'stopped',
- 'healthy',
+ deviceState === 'booted'
+ ? 'ready'
+ : deviceState === 'shutdown'
+ ? 'stopped'
+ : deviceState.includes('boot')
+ ? 'booting'
+ : deviceState.includes('shutting')
+ ? 'stopping'
+ : 'error',
+ deviceState === 'booted' || deviceState === 'shutdown' ? 'healthy' : 'recovering',
null,
);
}
@@ -2669,6 +2707,71 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
}
}
+ function assertViewerClaimAvailable(
+ sessionId: string,
+ instanceId: string,
+ viewerWebContentsId?: number,
+ ): void {
+ if (viewerWebContentsId === undefined) return;
+ const activeViewer = viewerSessions.get(instanceId);
+ if (
+ activeViewer?.webContentsId !== null &&
+ activeViewer?.webContentsId !== undefined &&
+ activeViewer.webContentsId !== viewerWebContentsId &&
+ isViewerWebContentsAlive(activeViewer.webContentsId)
+ ) {
+ throw new IOSSimulatorInstanceError(
+ 'INSTANCE_NOT_OWNED',
+ 'This simulator already has an active viewer in another Cindy window.',
+ true,
+ );
+ }
+ if (activeViewer && activeViewer.sessionId !== sessionId) {
+ throw new IOSSimulatorInstanceError(
+ 'INSTANCE_NOT_OWNED',
+ 'This simulator viewer belongs to another Cindy task.',
+ true,
+ );
+ }
+ }
+
+ function reserveViewerClaim(
+ sessionId: string,
+ instanceId: string,
+ viewerWebContentsId?: number,
+ viewerToken?: string,
+ ): { assertCurrent(): void; rollback(): void } | null {
+ if (viewerWebContentsId === undefined) return null;
+ assertViewerClaimAvailable(sessionId, instanceId, viewerWebContentsId);
+ const previous = viewerSessions.get(instanceId);
+ const claim = {
+ sessionId,
+ webContentsId: viewerWebContentsId,
+ viewerToken:
+ viewerToken ??
+ (previous?.webContentsId === viewerWebContentsId ? previous.viewerToken : null),
+ };
+ viewerSessions.set(instanceId, claim);
+ return {
+ assertCurrent: () => {
+ if (viewerSessions.get(instanceId) === claim) return;
+ throw new IOSSimulatorInstanceError(
+ 'INSTANCE_NOT_OWNED',
+ 'This simulator viewer was replaced by a newer viewer request.',
+ true,
+ );
+ },
+ rollback: () => {
+ if (viewerSessions.get(instanceId) !== claim) return;
+ if (previous?.webContentsId === viewerWebContentsId) {
+ viewerSessions.set(instanceId, previous);
+ } else {
+ viewerSessions.delete(instanceId);
+ }
+ },
+ };
+ }
+
function startViewerStream(
instance: IOSSimulatorInstance,
running: WdaRunningInstance,
@@ -2679,11 +2782,20 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
viewerToken?: string,
): IOSSimulatorFramePumpSnapshot {
const previousViewer = viewerSessions.get(instance.instanceId);
- viewerSessions.set(instance.instanceId, {
- sessionId: instance.sessionId,
- webContentsId: viewerWebContentsId ?? previousViewer?.webContentsId ?? null,
- viewerToken: viewerToken ?? previousViewer?.viewerToken ?? null,
- });
+ const nextViewerWebContentsId = viewerWebContentsId ?? previousViewer?.webContentsId ?? null;
+ const nextViewerToken = viewerToken ?? previousViewer?.viewerToken ?? null;
+ if (
+ !previousViewer ||
+ previousViewer.sessionId !== instance.sessionId ||
+ previousViewer.webContentsId !== nextViewerWebContentsId ||
+ previousViewer.viewerToken !== nextViewerToken
+ ) {
+ viewerSessions.set(instance.instanceId, {
+ sessionId: instance.sessionId,
+ webContentsId: nextViewerWebContentsId,
+ viewerToken: nextViewerToken,
+ });
+ }
viewerPreferredEncodings.set(instance.instanceId, fallbackReason ? 'h264' : preferredEncoding);
const nativeDriver = preferredEncoding === 'h264' ? nativeH264Driver(running) : null;
if (nativeDriver) {
@@ -2770,12 +2882,16 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
viewerWebContentsId,
viewerToken,
) {
+ let viewerClaimReservation: ReturnType<typeof reserveViewerClaim> = null;
try {
assertHostActive();
const resolved = await resolveSession(sessionId);
if (!resolved.ok) return resolved;
assertHostActive();
const mutationRoute = { ...route, sessionId: resolved.sessionId };
+ if (visible) {
+ assertViewerClaimAvailable(resolved.sessionId, route.instanceId, viewerWebContentsId);
+ }
let instance = visible
? actor.heartbeat(mutationRoute)
: assertViewerDeactivationRoute(mutationRoute);
@@ -2888,6 +3004,12 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
if (!current) return viewerRouteRefreshResult(currentOwnedInstance(instance));
instance = current;
}
+ viewerClaimReservation = reserveViewerClaim(
+ resolved.sessionId,
+ instance.instanceId,
+ viewerWebContentsId,
+ viewerToken,
+ );
let viewport: IOSSimulatorPublicViewport;
try {
viewport = await readViewport(running);
@@ -2904,6 +3026,10 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
// more after all slow startup work so the successful response always
// carries a live viewer route.
instance = actor.heartbeatOwned(resolved.sessionId, instance.instanceId);
+ viewerClaimReservation?.assertCurrent();
+ if (viewerWebContentsId !== undefined) {
+ assertCurrentViewer(resolved.sessionId, instance.instanceId, viewerWebContentsId);
+ }
const stream = startViewerStream(
instance,
running,
@@ -2913,6 +3039,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
viewerWebContentsId,
viewerToken,
);
+ viewerClaimReservation = null;
return {
ok: true,
data: {
@@ -2930,6 +3057,8 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
};
} catch (error) {
return safeHostError(error, sessionId, 'set_viewer_visibility');
+ } finally {
+ viewerClaimReservation?.rollback();
}
},
async getLatestFrame(sessionId, route, viewerWebContentsId) {
@@ -3287,7 +3416,6 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
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);
@@ -3297,6 +3425,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
viewerSessions.delete(route.instanceId);
clearViewportState(route.instanceId);
const stopped = await actor.stop(route);
+ resourceScheduler.markStopped(route.instanceId);
publishRouteStatusForInstance(stopped, null);
return {
ok: true,