Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): harden iOS simulator runtime boundaries
JiangJiahaob2fb90fa63ea
diff --git a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.tsindex cd85b419ac..711f710291 100644--- a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts+++ b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts@@ -62,12 +62,9 @@ vi.mock('../worktree/sessionRemovalRecycle.js', () => ({isSessionStillRemovable: h.isSessionStillRemovable,recycleWorktreeForRemovedSession: h.recycleWorktreeForRemovedSession,}));-vi.mock('../mcp-integrations/ios-simulator.js', () => ({- cancelIOSSimulatorSessionOperations: h.cancelSessionOperations,-}));-import {recycleSessionWorktreeForStatusChange,+ setSessionRemovalCancelOperations,setSessionsStatusInDb,} from '../localDb/ipc/sessions.js';@@ -78,9 +75,11 @@ beforeEach(() => {h.isSessionStillRemovable.mockResolvedValue(true);h.cancelSessionOperations.mockResolvedValue(undefined);h.recycleWorktreeForRemovedSession.mockResolvedValue(undefined);+ setSessionRemovalCancelOperations(h.cancelSessionOperations);});afterEach(() => {+ setSessionRemovalCancelOperations(null);fs.rmSync(h.userDataPath, { recursive: true, force: true });});@@ -256,4 +255,20 @@ describe('recycleSessionWorktreeForStatusChange', () => {expect(h.recycleWorktreeForRemovedSession).not.toHaveBeenCalled();expect(h.webContentsSend).not.toHaveBeenCalledWith('worktree:changed', expect.anything());});++ it('fails closed before closing or recycling when Host cleanup is not configured', async () => {+ setSessionRemovalCancelOperations(null);++ await recycleSessionWorktreeForStatusChange('s1', 'deleted');++ expect(h.isSessionStillRemovable).not.toHaveBeenCalled();+ expect(h.closeSession).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')");+ });});diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 2a9eccccce..dd2d0067b0 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -15,6 +15,7 @@ import {session,shell,Tray,+ type WebContents,} from 'electron';import { resolveVibrancyConfig } from './vibrancyConfig';import { applyVibrancyToSecondaryWindows } from './secondary-windows';@@ -270,6 +271,7 @@ import { fetchReleaseNotes, fetchReleaseNotesIndex } from './releaseNotesServiceimport { resolveWorkspacePathCached, resolveWorkspacePathBatchCached } from './pathResolver';import { registerLocalDbIpc } from './localDb/ipc/registerAll';import { listPersistedChatAttachmentPaths } from './localDb/ipc/messages';+import { getSessionRowSnapshot } from './localDb/ipc/sessions';import {registerLegacyMigrationIpc,runLegacyUserDataMigrationForUser,@@ -305,9 +307,16 @@ import { outboundFetch } from './maker-host/outbound-fetch';import { registerDevEmbeddingIpc } from './ipc/dev/embedding';import { onQuit, installQuitHandler } from './lifecycle';import {+ cancelIOSSimulatorSessionOperations,disposeIOSSimulatorHost,flushIOSSimulatorOwnershipRegistry,} from './mcp-integrations/ios-simulator';+import {+ clearIOSSimulatorRendererAccess,+ configureIOSSimulatorRendererAccessConfirmation,+ configureIOSSimulatorRendererTargets,+ inheritIOSSimulatorRendererSessionAccess,+} from './mcp-integrations/ios-simulator-renderer-access';import {parseIOSSimulatorReleaseGateArgs,runIOSSimulatorReleaseGate,@@ -334,7 +343,12 @@ import {isFocusedAppContentWindow,markAppContentWindow,} from './windowFocusClassifier.js';-import { assertTrustedAppRendererEvent } from './security/trustedAppRenderer.js';+import {+ assertTrustedAppRendererEvent,+ isTrustedAppRendererWindow,+} from './security/trustedAppRenderer.js';+import { isMainShellWindowUrl } from './cindy-brain/scheduleSlot.js';+import { sanitizeGhostNoticeText } from './cindy-brain/notifySlot.js';import { isIpcError } from '../shared/ipc-errors';import { readFileBytesForPreview } from './fileReadBytes.js';import { initHeartbeatService } from './heartbeatService';@@ -1248,7 +1262,17 @@ installWebviewHardener();// 调用时机远晚于此处构造),状态机本体见 right-sidebar-window/controller.ts。const rsbWindowController = new RsbWindowController({settings: { read: readRsbWindowSettings, writePatch: writeRsbWindowSettingsPatch },- createWindow: (opts) => createRightSidebarWindow(opts),+ createWindow: (opts) => {+ const window = createRightSidebarWindow(opts);+ const mainTarget =+ mainWindowRef && !mainWindowRef.isDestroyed() && !mainWindowRef.webContents.isDestroyed()+ ? mainWindowRef.webContents+ : null;+ if (mainTarget) {+ inheritIOSSimulatorRendererSessionAccess(mainTarget, window.webContents);+ }+ return window;+ },getMainWindow: () => mainWindowRef,broadcastState: (state) => {for (const win of BrowserWindow.getAllWindows()) {@@ -1273,6 +1297,82 @@ const rsbWindowController = new RsbWindowController({canCloseWindow: () => !hasActiveRsbNativePopupSurfaces(),log: createLogger('right-sidebar-window-controller'),});++function isIOSSimulatorPluginActive(ghosts = getGhostManager().list()): boolean {+ return ghosts.some(+ (ghost) =>+ ghost.enabled === true &&+ ghost.manifest.slots.includes('ios-simulator') &&+ isGhostAvailableForActiveSession(ghost.manifest.id),+ );+}++function resolveIOSSimulatorRendererWindow(+ target: Parameters<typeof BrowserWindow.fromWebContents>[0],+): BrowserWindow | null {+ const owner = BrowserWindow.fromWebContents(target);+ if (!owner || !isTrustedAppRendererWindow(owner)) return null;+ const sidebarTarget = rsbWindowController.getSidebarWebContents();+ const isSidebar = sidebarTarget === target;+ if (!isSidebar && !isMainShellWindowUrl(owner.webContents.getURL())) return null;+ return owner;+}++configureIOSSimulatorRendererTargets((preferredTarget) => {+ if (!isIOSSimulatorPluginActive()) return null;+ const mainTarget =+ mainWindowRef && !mainWindowRef.isDestroyed() && !mainWindowRef.webContents.isDestroyed()+ ? mainWindowRef.webContents+ : null;+ const sidebarTarget = rsbWindowController.getSidebarWebContents();+ const belongsToMainFamily =+ !preferredTarget || preferredTarget === mainTarget || preferredTarget === sidebarTarget;+ if (!belongsToMainFamily) {+ if (!preferredTarget || !resolveIOSSimulatorRendererWindow(preferredTarget as WebContents)) {+ return null;+ }+ return {+ grantTargets: [preferredTarget],+ focusTarget: preferredTarget,+ };+ }+ const grantTargets = [mainTarget, sidebarTarget].filter(+ (target): target is NonNullable<typeof target> => Boolean(target),+ );+ const focusTarget = rsbWindowController.getHostWebContents() ?? preferredTarget ?? mainTarget;+ return focusTarget ? { grantTargets, focusTarget } : null;+});+configureIOSSimulatorRendererAccessConfirmation(async (target, sessionId) => {+ if (!isIOSSimulatorPluginActive()) return false;+ const owner = resolveIOSSimulatorRendererWindow(target as WebContents);+ if (!owner) return false;+ const row = await getSessionRowSnapshot(sessionId);+ if (!row || row.status !== 'active' || row.remoteHostId) return false;++ const taskLabel =+ sanitizeGhostNoticeText(row.title ?? '')+ .replace(/[\u202A-\u202E\u2066-\u2069]/g, '')+ .replace(/\s+/g, ' ')+ .slice(0, 120) || t('rightSidebar.iosSimulator.accessDialogUntitledTask');+ const result = await dialog.showMessageBox(owner, {+ type: 'question',+ title: t('rightSidebar.iosSimulator.accessDialogTitle'),+ message: t('rightSidebar.iosSimulator.accessDialogMessage').replaceAll('{{task}}', taskLabel),+ detail: t('rightSidebar.iosSimulator.accessDialogDetail'),+ buttons: [+ t('rightSidebar.iosSimulator.accessDialogAllow'),+ t('rightSidebar.iosSimulator.accessDialogCancel'),+ ],+ defaultId: 1,+ cancelId: 1,+ noLink: true,+ });+ if (result.response !== 0 || owner.isDestroyed() || target.isDestroyed()) return false;+ const current = await getSessionRowSnapshot(sessionId);+ return Boolean(+ current && current.status === 'active' && !current.remoteHostId && isIOSSimulatorPluginActive(),+ );+});registerRsbWindowIpc({controller: rsbWindowController,getMainWindow: () => mainWindowRef,@@ -1322,7 +1422,10 @@ const ghostPanelWindowsController = new GhostPanelWindowsController({log: createLogger('ghost-panel-window-controller'),});registerGhostPanelWindowIpc(ghostPanelWindowsController);-setGhostsChangedObserver((ghosts) => ghostPanelWindowsController.reconcile(ghosts));+setGhostsChangedObserver((ghosts) => {+ ghostPanelWindowsController.reconcile(ghosts);+ if (!isIOSSimulatorPluginActive(ghosts)) clearIOSSimulatorRendererAccess();+});const rsbBrowserRegistry = getRsbBrowserBridge();registerRsbNativePopupSurfaceIpc(rsbBrowserRegistry);@@ -4142,17 +4245,6 @@ 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);@@ -6289,6 +6381,7 @@ app.on('ready', async () => {// 保证 beforeEnsureReady 推送 confirm 态时 renderer 已能 invoke 确认通道。registerLegacyMigrationIpc();registerLocalDbIpc({+ cancelSessionOperations: cancelIOSSimulatorSessionOperations,isOwnerCurrent: (userId) =>isLocalDbOwnerCurrent(authManager.getAuthState(), userId, isAppSessionBoundaryPending()),discardStaleOwner: (userId) =>diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 307f26e75f..ad585b64e6 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -195,6 +195,11 @@ import { GhostPreviewSlot } from './previewSlot.js';import { GhostScheduleSlot, isMainShellWindowUrl } from './scheduleSlot.js';import { GhostWorkspaceSlot, type WorkspaceSessionService } from './workspaceSlot.js';import { GhostIOSSimulatorSlot, type IOSSimulatorSlotFocusContext } from './iosSimulatorSlot.js';+import {+ clearIOSSimulatorRendererAccess,+ focusIOSSimulatorRendererSession,+ revokeIOSSimulatorRendererAccessForSessionChange,+} from '../mcp-integrations/ios-simulator-renderer-access.js';import { getIOSSimulatorPluginStatus } from '../mcp-integrations/ios-simulator.js';import type { GhostTrustRegistry } from './ghostSignature.js';import { GhostNotifySlot, sanitizeGhostNoticeText } from './notifySlot.js';@@ -1842,6 +1847,10 @@ const ghostSessionFocusTrackedWebContents = new Set<number>();let ghostSessionFocusRevision = 0;function noteGhostWindowSessionFocused(sender: WebContents, sessionId: string | null): void {+ // Renderer route reports are not an authority to grant Simulator access. They+ // may only remove a stale Main-owned grant when this window family moves away+ // from the task for which it was explicitly authorized.+ revokeIOSSimulatorRendererAccessForSessionChange(sender, sessionId);const previous = ghostSessionFocusByWebContents.get(sender.id);if (previous?.sessionId === sessionId) return;ghostSessionFocusRevision += 1;@@ -1919,12 +1928,11 @@ export function getGhostIOSSimulatorSlot(): GhostIOSSimulatorSlot {if (!window) return false;try {if (window.isDestroyed() || window.webContents.isDestroyed()) return false;- window.webContents.send('maker:ios-simulator:focus-request', {- sessionId: context.sessionId,- ...(instanceId ? { instanceId } : {}),- userInitiated: false,- });- return true;+ return focusIOSSimulatorRendererSession(+ context.sessionId,+ instanceId,+ window.webContents,+ );} catch {return false;}@@ -4551,6 +4559,7 @@ export function registerGhostIpc(): void {connectionTokenProviderSingleton?.clearAll();// 当前任务绑定属于窗口内的 owner 上下文,切账号/会员身份后不得沿用旧快照。ghostSessionFocusByWebContents.clear();+ clearIOSSimulatorRendererAccess();if (!getAppCapabilities().canUseCindyAccountServices) suspendCindyAccountGhosts();// Even when provisioning itself is a no-op, the renderer and agent// roster must immediately reflect the new session capability set.diff --git a/apps/desktop/src/main/localDb/ipc/registerAll.ts b/apps/desktop/src/main/localDb/ipc/registerAll.tsindex 1fac29bece..4ace59e2a1 100644--- a/apps/desktop/src/main/localDb/ipc/registerAll.ts+++ b/apps/desktop/src/main/localDb/ipc/registerAll.ts@@ -11,7 +11,7 @@ import { ipcMain } from 'electron';import { closeDb, ensureReady, getCurrentUserId } from '../index';import { getCurrentDbClientUserId } from '../client/current';-import { registerSessionIpc } from './sessions';+import { registerSessionIpc, setSessionRemovalCancelOperations } from './sessions';import { registerMessageIpc } from './messages';import { registerOrcaWorkflowIpc } from './orcaTeams';import { registerSessionImportIpc } from './session-import';@@ -36,6 +36,8 @@ export interface RegisterLocalDbIpcOpts {discardStaleOwner?: (userId: string) => void | Promise<void>;/** ensureReady 打开/创建目标库前执行;失败时阻断,避免跳过认领后创建空库。 */beforeEnsureReady?: (userId: string) => void | Promise<void>;+ /** Stop Host-owned session operations before an archived/deleted worktree is recycled. */+ cancelSessionOperations?: (sessionId: string) => Promise<void>;/*** 可选回调:localDb.ensureReady 成功(含已就绪复用路径)后触发。* 用途:启动依赖 localDb 的 host 单例(如 scheduler-host)。失败时协调器会@@ -50,6 +52,7 @@ export interface RegisterLocalDbIpcOpts {}export function registerLocalDbIpc(opts: RegisterLocalDbIpcOpts = {}): void {+ setSessionRemovalCancelOperations(opts.cancelSessionOperations ?? null);const runEnsureReady = createOwnerEnsureCoordinator({isOwnerCurrent: opts.isOwnerCurrent ?? (() => true),beforeEnsureReady: opts.beforeEnsureReady,diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex 9bb828b936..0be0523a2e 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -63,6 +63,16 @@ const REMOTE_EDITABLE_META = new Set(['status', 'title', 'pinnedAt']);const initialSessionListLogged = new Set<string>();const SLOW_SESSION_LIST_MS = 250;type OwnerScope = ReturnType<typeof broadcastTap.captureDataOwnerBroadcastScope> | null;+type SessionRemovalCancelOperations = (sessionId: string) => Promise<void>;++let sessionRemovalCancelOperations: SessionRemovalCancelOperations | null = null;++/** Composition-root injection for Host-owned operations that must stop before worktree recycle. */+export function setSessionRemovalCancelOperations(+ cancelOperations: SessionRemovalCancelOperations | null,+): void {+ sessionRemovalCancelOperations = cancelOperations;+}function captureOwnerScope(): OwnerScope {try {@@ -149,8 +159,9 @@ function broadcastWorktreeChanged(sessionId: string): void {** fire-and-forget:回收失败不影响状态写库(启动期 reconcile 兜底 deleted 场景)。* 先关子进程再回收——Windows 下 CLI 子进程 cwd 在 worktree 内会锁目录。- * 动态 import 避免 localDb → maker-host / worktree 的静态模块环(worktreeStore- * 反向 import 本文件的 setWorktreePathInDb)。+ * 既有动态 import 避免 localDb → maker-host / worktree 的静态模块环(worktreeStore+ * 反向 import 本文件的 setWorktreePathInDb)。Simulator 清理由启动组合层静态注入,+ * 避免在回收临界路径上延迟加载带原生副作用的 Host 模块。** 回收链结束后(无论成功、跳过还是失败)都广播一次 worktree:changed —— 失败/跳过* 时条目仍在 store 里,重拉拿到的就是"徽标还在"这个真实状态,同样是对的。@@ -161,17 +172,20 @@ export async function recycleSessionWorktreeForStatusChange(): Promise<void> {if (status !== 'deleted' && status !== 'archived') return;try {- const [mh, recycle, routeLock, iosSimulator] = await Promise.all([+ const cancelOperations = sessionRemovalCancelOperations;+ if (!cancelOperations) {+ throw new Error('iOS Simulator session cleanup is not configured');+ }+ const [mh, recycle, routeLock] = await Promise.all([import('../../maker-host/index.js'),import('../../worktree/sessionRemovalRecycle.js'),import('../../maker-ipc/register.js'),- import('../../mcp-integrations/ios-simulator.js'),]);if (!(await recycle.isSessionStillRemovable(sessionId))) return;const shouldRecycle = await routeLock.withSendToSessionLock(sessionId, async () =>quiesceSessionBeforeWorktreeRecycle(sessionId, {isSessionStillRemovable: recycle.isSessionStillRemovable,- cancelSessionOperations: iosSimulator.cancelIOSSimulatorSessionOperations,+ cancelSessionOperations: cancelOperations,closeSession: async (id) => {await mh.getMakerIfReady()diff --git a/apps/desktop/src/main/maker-host/__tests__/shellCommandPolicy.test.ts b/apps/desktop/src/main/maker-host/__tests__/shellCommandPolicy.test.tsindex 49e70751ed..15f62f0f89 100644--- a/apps/desktop/src/main/maker-host/__tests__/shellCommandPolicy.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/shellCommandPolicy.test.ts@@ -47,6 +47,10 @@ describeMac('embedded iOS Simulator shell policy', () => {'env FOO=1 /usr/bin/xcrun simctl shutdown DEVICE','FOO=1 exec env BAR=2 xcrun simctl boot DEVICE',"bash -lc 'xcrun simctl shutdown DEVICE'",+ "/bin/csh -c 'xcrun simctl shutdown DEVICE'",+ "/bin/tcsh -c 'xcrun simctl shutdown DEVICE'",+ "/bin/ksh -c 'xcrun simctl shutdown DEVICE'",+ "fish -c 'xcrun simctl shutdown DEVICE'","eval 'xcrun simctl erase DEVICE'",'echo "$(xcrun simctl shutdown DEVICE)"','echo >(xcrun simctl shutdown DEVICE)',@@ -67,13 +71,57 @@ describeMac('embedded iOS Simulator shell policy', () => {'$(/usr/bin/xcrun --find simctl) shutdown DEVICE','/usr/bin/xc[r]un simctl shutdown DEVICE','TOOL=simctl; /usr/bin/xcrun "$TOOL" shutdown DEVICE',+ 'xargs /usr/bin/xcrun simctl shutdown DEVICE',+ "find . -maxdepth 0 -exec /usr/bin/xcrun simctl shutdown DEVICE ';'",+ `printf 'simctl shutdown DEVICE' | xargs /usr/bin/xcrun`,+ 'xcrun "$(printf simctl)" shutdown DEVICE',+ 'xcrun $(printf simctl) shutdown DEVICE',+ 'xcrun $(echo simctl) shutdown DEVICE',+ 'TOOL=$(printf simctl); xcrun "$TOOL" shutdown DEVICE',+ 'launchctl submit -l cindy-test -- /usr/bin/xcrun simctl shutdown DEVICE',+ `sandbox-exec -p '(version 1) (allow default)' /usr/bin/xcrun simctl shutdown DEVICE`,])('denies Simulator mutation hidden behind shell execution: %s', (command) => {expect(getDesktopShellCommandPolicy(command)).toMatchObject({ decision: 'deny' });});+ it.each([+ `python3 -c 'import subprocess; subprocess.run(["/usr/bin/xcrun", "simctl", "shutdown", "DEVICE"])'`,+ `node -e 'require("node:child_process").execFileSync("xcrun", ["simctl", "erase", "DEVICE"])'`,+ `ruby -e 'system("xcrun simctl boot DEVICE")'`,+ `perl -e 'system("simctl shutdown DEVICE")'`,+ `env FOO=1 python3.12 -c 'import os; os.system("xcrun simctl install DEVICE /tmp/App.app")'`,+ `/usr/bin/python3 -c 'import os; os.system("simctl shutdown DEVICE")'`,+ `awk 'BEGIN { system("xcrun simctl erase DEVICE") }'`,+ `osascript -e 'do shell script "/usr/bin/xcrun simctl shutdown DEVICE"'`,+ `osascript -e 'do shell script "open -a Simulator"'`,+ `printf '%s' 'import os; os.system("xcrun simctl shutdown DEVICE")' | python3`,+ `python3 <<'PY'+import os+os.system("xcrun simctl shutdown DEVICE")+PY`,+ `osascript -e 'set cmd to "/usr/bin/xcrun simctl shutdown DEVICE"' -e 'do shell script cmd'`,+ `osascript -l JavaScript -e 'ObjC.import("Foundation"); const task = $.NSTask.alloc.init; task.launchPath = "/usr/bin/xcrun"; task.arguments = ["simctl", "shutdown", "DEVICE"]; task.launch'`,+ `python3 -c 'import subprocess; subprocess.run(["/usr/bin/open","-a","Simulator"])'`,+ `node -e 'require("child_process").spawnSync("/usr/bin/open",["-na","Simulator"])'`,+ `ruby -e 'system("/usr/bin/open", "-a", "Simulator")'`,+ `/usr/bin/expect -c 'spawn /usr/bin/xcrun simctl shutdown DEVICE; expect eof'`,+ `printf '%s' 'exec /usr/bin/xcrun simctl shutdown DEVICE' | /usr/bin/tclsh`,+ `printf '%s' 'import os; os.system("xcrun simctl shutdown DEVICE")' |& python3`,+ `bash <<< 'xcrun simctl shutdown DEVICE'`,+ `zsh <<< 'open -a Simulator'`,+ `bash -c 'source /dev/stdin' <<< 'xcrun simctl shutdown DEVICE'`,+ `bash -c 'eval "$(cat)"' <<< 'xcrun simctl shutdown DEVICE'`,+ `printf 'xcrun simctl shutdown DEVICE' | bash -c 'eval "$(cat)"'`,+ ])('denies Simulator mutation hidden behind a programmable interpreter: %s', (command) => {+ expect(getDesktopShellCommandPolicy(command)).toMatchObject({ decision: 'deny' });+ });+it.each(['xcrun simctl list devices','xcrun simctl listapps DEVICE',+ 'xcrun simctl list "$DEVICE"',+ 'xcrun simctl getenv "$DEVICE" HOME',+ 'xcrun --sdk "$SDK" simctl list devices','exec xcrun simctl list devices','command -p xcrun simctl listapps DEVICE',"bash -lc 'xcrun simctl list devices'",@@ -83,6 +131,23 @@ describeMac('embedded iOS Simulator shell policy', () => {'open -a Xcode','echo "open -a Simulator"','osascript -e \'tell application "Simulator" to quit\'',+ `python3 -c 'print("ordinary project build")'`,+ `python3 -c 'print("Simulator")'`,+ `node -e 'console.log("ordinary project build")'`,+ 'swift test --filter IOSSimulatorTests',+ 'swift build --product IOSSimulatorRuntime',+ 'find . -maxdepth 1 -name simctl',+ 'git grep simctl',+ 'git log --grep=simctl',+ `sed -n '/simctl/p' README.md`,+ `jq '.simctl' config.json`,+ 'diff simctl-before.txt simctl-after.txt',+ 'cp simctl-notes.txt backup.txt',+ 'git grep simctl && python3 scripts/check.py',+ 'git grep simctl | python3 formatter.py',+ `git grep simctl | awk '{print $1}'`,+ `python3 -c 'print("ordinary")'; git grep simctl`,+ 'git grep simctl || python3',])('allows a non-bypass command: %s', (command) => {expect(getDesktopShellCommandPolicy(command)).toBeUndefined();});diff --git a/apps/desktop/src/main/maker-host/shell-command-policy.ts b/apps/desktop/src/main/maker-host/shell-command-policy.tsindex 2f2cfae479..3d6893afac 100644--- a/apps/desktop/src/main/maker-host/shell-command-policy.ts+++ b/apps/desktop/src/main/maker-host/shell-command-policy.ts@@ -4,8 +4,11 @@* Agent skills may contain legacy `simctl` / `open -a Simulator` recipes. Those* commands bypass Cindy's ownership, admission, viewer, and cleanup contracts,* so prompt guidance alone is not a sufficient boundary. This module detects- * executable shell segments and denies only the bypass paths; Cindy's own main- * process still uses simctl through the runtime adapter and is unaffected.+ * literal executable shell segments and denies only the bypass paths; Cindy's+ * own main process still uses simctl through the runtime adapter and is+ * unaffected. This is defense in depth for command text, not an OS process+ * sandbox: scripts whose contents are absent from the command cannot be proven+ * safe here and remain subject to the normal shell permission boundary.*/export interface ShellCommandPolicyDenial {@@ -137,8 +140,39 @@ interface UnwrappedCommand {}const MAX_WRAPPER_UNWRAP_DEPTH = 16;-const SHELL_EXECUTABLES = new Set(['bash', 'dash', 'sh', 'zsh']);+const SHELL_EXECUTABLES = new Set(['bash', 'csh', 'dash', 'fish', 'ksh', 'sh', 'tcsh', 'zsh']);+const NON_EXECUTING_REFERENCE_COMMANDS = new Set([+ 'cat',+ 'echo',+ 'egrep',+ 'fgrep',+ 'file',+ 'grep',+ 'head',+ 'less',+ 'ls',+ 'more',+ 'printf',+ 'rg',+ 'stat',+ 'tail',+ 'wc',+]);+const OPAQUE_EXECUTION_WRAPPERS = new Set([+ 'doas',+ 'gtimeout',+ 'launchctl',+ 'parallel',+ 'sandbox-exec',+ 'script',+ 'sudo',+ 'timeout',+ 'watch',+ 'xargs',+]);const SHELL_POSITIONAL_REFERENCE = /\$(?:[0-9]+|[@*#-]|\{(?:[0-9]+|[@*#-])\})/;+const PROGRAMMABLE_INTERPRETER =+ /^(?:python(?:\d+(?:\.\d+)*)?|pypy(?:\d+(?:\.\d+)*)?|node|nodejs|bun|deno|ruby(?:\d+(?:\.\d+)*)?|perl(?:\d+(?:\.\d+)*)?|php(?:\d+(?:\.\d+)*)?|lua(?:\d+(?:\.\d+)*)?|luajit|swift|expect(?:\d+(?:\.\d+)*)?|tclsh(?:\d+(?:\.\d+)*)?|wish(?:\d+(?:\.\d+)*)?|(?:g|m|n)?awk)$/;/** Peel only wrappers whose argv shape is fully understood; unknown options fail closed. */function unwrapCommand(input: string[]): UnwrappedCommand {@@ -480,6 +514,55 @@ function containsSimulatorExecutor(tokens: string[]): boolean {);}+function containsLiteralSimulatorExecutor(value: string): boolean {+ const argvLike = value.replace(/[^A-Za-z0-9_./-]+/g, ' ').trim();+ return (+ /\b(?:xcrun|simctl)\b/i.test(value) ||+ /\bSimulator\.app\b/i.test(value) ||+ /\bcom\.apple\.iphonesimulator\b/i.test(value) ||+ /(?:^|\s)(?:\S*\/)?open(?:\s+-[A-Za-z]+)*\s+Simulator(?:\.app)?(?:\s|$)/i.test(argvLike)+ );+}++/**+ * General-purpose interpreters can spawn simctl without making it the shell+ * executable. Treat a literal Simulator executor in their payload/argv as a+ * mutation-capable wrapper; command-text policy cannot safely inspect the+ * language semantics beneath this point.+ */+function containsInterpreterSimulatorPayload(tokens: string[]): boolean {+ const interpreter = executableName(tokens[0]);+ const payload = tokens.slice(1).join('\n');+ if (PROGRAMMABLE_INTERPRETER.test(interpreter)) {+ return containsLiteralSimulatorExecutor(payload);+ }+ if (interpreter === 'osascript') {+ // AppleScript can execute through `do shell script`, while JavaScript for+ // Automation can reach NSTask/NSProcessInfo directly. Once an osascript+ // payload contains a literal Simulator executor, command-text policy cannot+ // safely distinguish an inert reference from executable code.+ return containsLiteralSimulatorExecutor(payload);+ }+ return false;+}++/**+ * Fail closed when a command passes a literal Simulator executor to an opaque+ * execution wrapper (for example xargs or find -exec). Commands whose only+ * purpose is displaying/searching text remain outside this boundary.+ */+function containsOpaqueSimulatorExecution(tokens: string[]): boolean {+ const head = executableName(tokens[0]);+ if (!head || NON_EXECUTING_REFERENCE_COMMANDS.has(head) || head === 'osascript') return false;+ const findExec =+ head === 'find' && tokens.some((token) => /^-(?:exec|execdir|ok|okdir)$/.test(token));+ if (!findExec && !OPAQUE_EXECUTION_WRAPPERS.has(head)) return false;+ // Direct simctl commands have already been classified above, including the+ // explicitly read-only allowlist.+ if (simctlSubcommand(tokens) !== null) return false;+ return containsLiteralSimulatorExecutor(tokens.slice(1).join(' '));+}+/** Extract command/process substitutions because they execute even inside an otherwise safe command. */function shellSubcommands(command: string): string[] {const subcommands: string[] = [];@@ -546,6 +629,55 @@ function shellSubcommands(command: string): string[] {return subcommands;}+/** Split independent command clauses while retaining pipeline boundaries. */+function shellClauses(command: string): string[] {+ const clauses: string[] = [];+ let current = '';+ let quote: "'" | '"' | null = null;+ let escaped = false;+ for (let index = 0; index < command.length; index += 1) {+ const char = command[index]!;+ if (escaped) {+ current += char;+ escaped = false;+ continue;+ }+ if (char === '\\' && quote !== "'") {+ current += char;+ escaped = true;+ continue;+ }+ if (quote) {+ current += char;+ if (char === quote) quote = null;+ continue;+ }+ if (char === "'" || char === '"') {+ current += char;+ quote = char;+ continue;+ }+ if (char === '|' && command[index + 1] === '|') {+ if (current.trim()) clauses.push(current.trim());+ current = '';+ index += 1;+ continue;+ }+ if (char === '&' && current.trimEnd().endsWith('|')) {+ current += char;+ continue;+ }+ if (char === '\n' || char === ';' || char === '&') {+ if (current.trim()) clauses.push(current.trim());+ current = '';+ continue;+ }+ current += char;+ }+ if (current.trim()) clauses.push(current.trim());+ return clauses;+}+function isLiteralSimulatorBypass(command: string): boolean {for (const segment of shellSegments(command)) {const unwrapped = unwrapCommand(tokenizeShellSegment(segment));@@ -587,6 +719,11 @@ function containsTaintedVariableExecution(command: string): boolean {segment,tokens: tokenizeShellSegment(segment),}));+ for (const { segment } of tokenizedSegments) {+ for (const match of segment.matchAll(/\b([A-Za-z_][A-Za-z0-9_]*)=\$\(([^)]*)\)/g)) {+ if (containsLiteralSimulatorExecutor(match[2] ?? '')) tainted.add(match[1]!);+ }+ }for (const { tokens } of tokenizedSegments) {for (const token of tokens) {const assignment = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s.exec(token);@@ -619,18 +756,136 @@ function containsTaintedVariableExecution(command: string): boolean {return false;}-/** A literal command piped or passed to a shell becomes executable shell input. */-function containsShellConsumedLiteralBypass(command: string): boolean {- const segments = shellSegments(command).map(tokenizeShellSegment);- const invokesShell = segments.some((tokens) =>- SHELL_EXECUTABLES.has(executableName(unwrapCommand(tokens).tokens[0])),- );- if (!invokesShell) return false;- return segments.some((tokens) =>- tokens.some((token) => token.includes(' ') && isLiteralSimulatorBypass(token)),+function nestedShellConsumesStdinAsProgram(command: string): boolean {+ return (+ /(?:^|[;&|]\s*)(?:source|\.)\s+(?:\/dev\/stdin|\/dev\/fd\/0|-)(?:\s|$)/i.test(command) ||+ /\beval\b[\s\S]*\$\(\s*cat(?:\s+(?:-|\/dev\/stdin|\/dev\/fd\/0))?\s*\)/i.test(command));}+function consumesStdinAsProgram(tokens: string[]): boolean {+ const unwrapped = unwrapCommand(tokens);+ if (unwrapped.nestedShell !== null) {+ return !unwrapped.unresolvedWrapper && nestedShellConsumesStdinAsProgram(unwrapped.nestedShell);+ }+ if (unwrapped.unresolvedWrapper) return false;+ const executable = executableName(unwrapped.tokens[0]);+ const args = unwrapped.tokens.slice(1);+ if (SHELL_EXECUTABLES.has(executable)) {+ if (args.some((arg) => /^-[A-Za-z]*c[A-Za-z]*$/.test(arg))) return false;+ if (args.some((arg) => /^-[A-Za-z]*s[A-Za-z]*$/.test(arg))) return true;+ } else if (executable === 'osascript') {+ if (args.some((arg) => arg === '-e' || arg.startsWith('-e'))) return false;+ } else if (PROGRAMMABLE_INTERPRETER.test(executable)) {+ if (/^(?:(?:g|m|n)?awk)$/.test(executable)) return false;+ if (args.some((arg) => /^(?:-c|-e|-p|-m|--eval|--print|--input-type|--module)$/.test(arg))) {+ return false;+ }+ } else {+ return false;+ }+ const positional = args.find((arg) => !arg.startsWith('-'));+ return positional === undefined || positional === '-';+}++function containsInterpreterHeredocBypass(command: string): boolean {+ const lines = command.split(/\r?\n/);+ for (let index = 0; index < lines.length; index += 1) {+ const line = lines[index] ?? '';+ const marker = /<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1/.exec(line);+ if (!marker) continue;+ if (+ !shellSegments(line.slice(0, marker.index)).some((segment) =>+ consumesStdinAsProgram(tokenizeShellSegment(segment)),+ )+ ) {+ continue;+ }+ const delimiter = marker[2]!;+ const body: string[] = [];+ for (index += 1; index < lines.length; index += 1) {+ if ((lines[index] ?? '').replace(/^\t+/, '').trim() === delimiter) break;+ body.push(lines[index] ?? '');+ }+ if (containsLiteralSimulatorExecutor(body.join('\n'))) return true;+ }+ return false;+}++/** A here-string is executable stdin just like a heredoc or producer pipeline. */+function containsInterpreterHereStringBypass(command: string): boolean {+ for (const clause of shellClauses(command)) {+ let quote: "'" | '"' | null = null;+ let escaped = false;+ for (let index = 0; index < clause.length - 2; index += 1) {+ const char = clause[index]!;+ if (escaped) {+ escaped = false;+ continue;+ }+ if (char === '\\' && quote !== "'") {+ escaped = true;+ continue;+ }+ if (char === "'" || char === '"') {+ if (quote === char) quote = null;+ else if (quote === null) quote = char;+ continue;+ }+ if (quote || clause.slice(index, index + 3) !== '<<<') continue;+ const consumer = clause.slice(0, index).trim();+ const payload = clause.slice(index + 3);+ if (+ shellSegments(consumer).some((segment) =>+ consumesStdinAsProgram(tokenizeShellSegment(segment)),+ ) &&+ containsLiteralSimulatorExecutor(payload)+ ) {+ return true;+ }+ break;+ }+ }+ return false;+}++/** A literal command piped to a code-reading interpreter becomes executable input. */+function containsShellConsumedLiteralBypass(command: string): boolean {+ if (containsInterpreterHeredocBypass(command) || containsInterpreterHereStringBypass(command)) {+ return true;+ }+ for (const clause of shellClauses(command)) {+ if (!clause.includes('|')) continue;+ const segments = shellSegments(clause);+ if (+ segments.some((segment) => consumesStdinAsProgram(tokenizeShellSegment(segment))) &&+ containsLiteralSimulatorExecutor(clause)+ ) {+ return true;+ }+ }+ return false;+}++function hasUnresolvedXcrunTool(tokens: string[]): boolean {+ if (executableName(tokens[0]) !== 'xcrun') return false;+ let index = 1;+ while (index < tokens.length && tokens[index]!.startsWith('-')) {+ const option = tokens[index]!;+ index +=+ option === '--sdk' || option === '-sdk' || option === '--toolchain' || option === '-toolchain'+ ? 2+ : 1;+ }+ const firstToolToken = tokens[index] ?? '';+ if (!/[$`*?\[]/.test(firstToolToken)) return false;+ let end = index + 1;+ if (firstToolToken.includes('$(') && !firstToolToken.includes(')')) {+ while (end < tokens.length && !tokens[end - 1]!.includes(')')) end += 1;+ }+ return containsLiteralSimulatorExecutor(tokens.slice(index, end).join(' '));+}+/** Function bodies are executable later, so reject unsafe bodies at definition time. */function containsSimulatorFunctionBody(command: string, depth: number): boolean {const functionPattern =@@ -654,6 +909,11 @@ function containsSimulatorBypass(command: string, depth = 0): boolean {if (containsSimulatorBypass(nested, depth + 1)) return true;}for (const segment of shellSegments(command)) {+ // Function bodies were classified recursively above. The leading+ // `name(){` token is not an execution wrapper in its own right.+ if (/^(?:function\s+)?[A-Za-z_][A-Za-z0-9_]*(?:\s*\(\s*\))?\s*\{/.test(segment)) {+ continue;+ }const tokens = tokenizeShellSegment(segment);if (hasUnresolvedExecutableExpansion(segment, tokens)) return true;const unwrapped = unwrapCommand(tokens);@@ -665,7 +925,13 @@ function containsSimulatorBypass(command: string, depth = 0): boolean {continue;}if (unwrapped.unresolvedWrapper && containsSimulatorExecutor(unwrapped.tokens)) return true;- if (isExternalSimulatorLaunch(unwrapped.tokens) || isSimulatorMutation(unwrapped.tokens)) {+ if (+ hasUnresolvedXcrunTool(unwrapped.tokens) ||+ containsInterpreterSimulatorPayload(unwrapped.tokens) ||+ isExternalSimulatorLaunch(unwrapped.tokens) ||+ isSimulatorMutation(unwrapped.tokens) ||+ containsOpaqueSimulatorExecution(unwrapped.tokens)+ ) {return true;}}diff --git a/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.tsindex dfd4f598bd..557be99084 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts@@ -11,12 +11,13 @@ 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',+ hasSessionAccess: (_target, sessionId) => sessionId === 'session-a',...deps,});}it.each([+ MAKER_INVOKE.IOS_SIMULATOR_REQUEST_ACCESS,MAKER_INVOKE.IOS_SIMULATOR_STATUS,MAKER_INVOKE.IOS_SIMULATOR_CALL,MAKER_INVOKE.IOS_SIMULATOR_SET_AGENT_CONTROL,@@ -40,6 +41,53 @@ describe('iOS Simulator IPC handlers', () => {expect(getStatus).not.toHaveBeenCalled();});+ it('returns an existing Main-owned grant without opening confirmation', async () => {+ const harness = new IpcHarness();+ const requestSessionAccess = vi.fn(async () => false);+ registerTrusted(harness, { requestSessionAccess });++ await expect(+ harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_REQUEST_ACCESS, {+ sessionId: ' session-a ',+ }),+ ).resolves.toEqual({ granted: true });+ expect(requestSessionAccess).not.toHaveBeenCalled();+ });++ it('returns the explicit native confirmation result for a manual access request', async () => {+ const harness = new IpcHarness();+ const requestSessionAccess = vi.fn(async () => true);+ registerTrusted(harness, {+ hasSessionAccess: () => false,+ requestSessionAccess,+ });++ await expect(+ harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_REQUEST_ACCESS, {+ sessionId: ' session-a ',+ }),+ ).resolves.toEqual({ granted: true });+ expect(requestSessionAccess).toHaveBeenCalledWith(+ expect.objectContaining({ id: 17 }),+ 'session-a',+ );+ });++ it('keeps a cancelled manual access request ungranted', async () => {+ const harness = new IpcHarness();+ const requestSessionAccess = vi.fn(async () => false);+ registerTrusted(harness, {+ hasSessionAccess: () => false,+ requestSessionAccess,+ });++ await expect(+ harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_REQUEST_ACCESS, {+ sessionId: 'session-a',+ }),+ ).resolves.toEqual({ granted: false });+ });+it('passes a validated session id to the host', async () => {const harness = new IpcHarness();const getStatus = vi.fn(async (sessionId: string) => ({@@ -73,7 +121,7 @@ describe('iOS Simulator IPC handlers', () => {const callTool = vi.fn();registerIOSSimulatorHandlers(harness, {assertTrustedSender: () => undefined,- getRendererUrl: () => 'file:///app/index.html#/cc-agent/session-b',+ hasSessionAccess: () => false,getStatus,callTool,});diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.tsindex 08c0a1288d..13775e4a0f 100644--- a/apps/desktop/src/main/maker-ipc/channels.ts+++ b/apps/desktop/src/main/maker-ipc/channels.ts@@ -613,6 +613,7 @@ export const MAKER_INVOKE = {ANDROID_SET_ADB_PATH: 'maker:android:set-adb-path',ANDROID_PREPARE_ADB: 'maker:android:prepare-adb',// iOS Simulator pane and Agent discovery. Session id is required and checked in main.+ IOS_SIMULATOR_REQUEST_ACCESS: 'maker:ios-simulator:request-access',IOS_SIMULATOR_STATUS: 'maker:ios-simulator:status',IOS_SIMULATOR_CALL: 'maker:ios-simulator:call',IOS_SIMULATOR_SET_AGENT_CONTROL: 'maker:ios-simulator:set-agent-control',diff --git a/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts b/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.tsindex a3298cbfe2..a1bb005191 100644--- a/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts+++ b/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts@@ -5,7 +5,6 @@ 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,@@ -16,6 +15,11 @@ import {setIOSSimulatorViewerStreamProfile,updateIOSSimulatorViewerTouch,} from '../mcp-integrations/ios-simulator.js';+import {+ hasIOSSimulatorRendererSessionAccess,+ requestIOSSimulatorRendererSessionAccess,+ type IOSSimulatorRendererWebContents,+} from '../mcp-integrations/ios-simulator-renderer-access.js';import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';import { throwIpcError } from '../utils/ipcValidate.js';import { MAKER_INVOKE } from './channels.js';@@ -23,7 +27,11 @@ import type { IpcHandlerRegistry } from './ipcHandlerRegistry.js';export interface IOSSimulatorHandlerDeps {assertTrustedSender(event: unknown): void;- getRendererUrl(event: unknown): string;+ hasSessionAccess(target: IOSSimulatorRendererWebContents, sessionId: string): boolean;+ requestSessionAccess(+ target: IOSSimulatorRendererWebContents,+ sessionId: string,+ ): Promise<boolean>;getStatus(sessionId: string): Promise<IOSSimulatorSessionStatus>;callTool(name: IOSSimulatorRendererToolName,@@ -76,7 +84,8 @@ export interface IOSSimulatorHandlerDeps {const defaultDeps: IOSSimulatorHandlerDeps = {assertTrustedSender: (event) =>assertTrustedAppRendererEvent(event as Parameters<typeof assertTrustedAppRendererEvent>[0]),- getRendererUrl: readSenderWebContentsUrl,+ hasSessionAccess: hasIOSSimulatorRendererSessionAccess,+ requestSessionAccess: requestIOSSimulatorRendererSessionAccess,getStatus: getIOSSimulatorSessionStatus,callTool: callIOSSimulatorHostTool,setAgentControlGrant: setIOSSimulatorAgentControlGrant,@@ -125,24 +134,13 @@ function readViewerRoute(record: Record<string, unknown>) {return { instanceId: instanceId.trim(), generation: Number(generation), leaseId: leaseId.trim() };}-function readSenderWebContentsId(event: unknown): number {- const id = (event as { sender?: { id?: unknown } })?.sender?.id;+function readSenderWebContents(event: unknown): IOSSimulatorRendererWebContents {+ const sender = (event as { sender?: { id?: unknown } })?.sender;+ const id = sender?.id;if (!Number.isSafeInteger(id) || Number(id) <= 0) {throwIpcError('PERMISSION_DENIED', 'trusted renderer sender is required');}- 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');- }+ return sender as IOSSimulatorRendererWebContents;}export function registerIOSSimulatorHandlers(@@ -157,12 +155,22 @@ export function registerIOSSimulatorHandlers(});};const assertSenderSession = (event: unknown, sessionId: string): number => {- const webContentsId = readSenderWebContentsId(event);- if (!atContextVisibleSessionIdsFromRendererUrl(resolved.getRendererUrl(event)).has(sessionId)) {+ const sender = readSenderWebContents(event);+ if (!resolved.hasSessionAccess(sender, sessionId)) {throwIpcError('PERMISSION_DENIED', 'iOS Simulator access is limited to the current task');}- return webContentsId;+ return sender.id;};+ handle(MAKER_INVOKE.IOS_SIMULATOR_REQUEST_ACCESS, async (event, payload) => {+ const sessionId = readSessionId(payload);+ const sender = readSenderWebContents(event);+ if (resolved.hasSessionAccess(sender, sessionId)) return { granted: true };+ try {+ return { granted: await resolved.requestSessionAccess(sender, sessionId) };+ } catch (error) {+ throwIpcError('INTERNAL', error instanceof Error ? error.message : String(error));+ }+ });handle(MAKER_INVOKE.IOS_SIMULATOR_STATUS, async (event, payload) => {const sessionId = readSessionId(payload);assertSenderSession(event, sessionId);diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 19604ac495..7c0a8dd128 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -4770,8 +4770,6 @@ 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 可读后仍在后台运行的账号模型发现;新建 / 懒恢复路由前必须等待。 */@@ -12306,9 +12304,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// ── iOS Simulator pane / Agent discovery ────────────────────────────────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-media.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-media.test.tsindex 4f6b8fb3fd..2377f16c24 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-media.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-media.test.ts@@ -156,7 +156,7 @@ describe('IOSSimulatorMediaCapture', () => {let resolveExit: () => void = () => undefined;let videoPath = '';const kill = vi.fn((signal: NodeJS.Signals) => {- if (signal === 'SIGTERM') resolveExit();+ if (signal === 'SIGKILL') resolveExit();});const capture = new IOSSimulatorMediaCapture({recordingLauncher: {@@ -181,10 +181,9 @@ describe('IOSSimulatorMediaCapture', () => {vi.useFakeTimers();const discarded = capture.discardInstance('instance-a');- await vi.advanceTimersByTimeAsync(5_000);await discarded;- expect(kill.mock.calls.map(([signal]) => signal)).toEqual(['SIGINT', 'SIGTERM']);+ expect(kill.mock.calls.map(([signal]) => signal)).toEqual(['SIGKILL']);await expect(stat(path.dirname(videoPath))).rejects.toMatchObject({ code: 'ENOENT' });await expect(capture.stopRecording({@@ -195,4 +194,294 @@ describe('IOSSimulatorMediaCapture', () => {}),).rejects.toMatchObject({ code: 'RECORDING_NOT_FOUND' });});++ it('bounds cleanup when a discarded recording does not confirm SIGKILL', async () => {+ let videoPath = '';+ const kill = vi.fn();+ const capture = new IOSSimulatorMediaCapture({+ recordingLauncher: {+ launch: vi.fn((args: readonly string[]) => {+ videoPath = args.at(-1)!;+ return { exited: new Promise<void>(() => undefined), kill };+ }),+ },+ });+ await capture.startRecording({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ source: 'agent',+ });++ vi.useFakeTimers();+ const discarded = capture.discardInstance('instance-a');+ await vi.advanceTimersByTimeAsync(500);+ await discarded;++ expect(kill.mock.calls.map(([signal]) => signal)).toEqual(['SIGKILL']);+ await expect(stat(path.dirname(videoPath))).rejects.toMatchObject({ code: 'ENOENT' });+ expect(vi.getTimerCount()).toBe(0);+ });++ it('fails a finalized recording safely when no exit event arrives after SIGKILL', async () => {+ const ingest = vi.fn();+ let videoPath = '';+ const kill = vi.fn();+ const capture = new IOSSimulatorMediaCapture({+ ingest,+ recordingLauncher: {+ launch: vi.fn((args: readonly string[]) => {+ videoPath = args.at(-1)!;+ return {+ exited: new Promise<void>(() => undefined),+ kill,+ };+ }),+ },+ });+ const started = await capture.startRecording({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ source: 'agent',+ });++ vi.useFakeTimers();+ const stopped = capture.stopRecording({+ recordingId: started.recordingId,+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ });+ const rejection = expect(stopped).rejects.toMatchObject({ code: 'RECORDING_FAILED' });+ await vi.advanceTimersByTimeAsync(6_500);+ await rejection;++ expect(kill.mock.calls.map(([signal]) => signal)).toEqual(['SIGINT', 'SIGTERM', 'SIGKILL']);+ expect(ingest).not.toHaveBeenCalled();+ await expect(stat(path.dirname(videoPath))).rejects.toMatchObject({ code: 'ENOENT' });+ expect(vi.getTimerCount()).toBe(0);+ });++ it('does not treat a leader exit as success while its recording group is alive', async () => {+ let resolveLeaderExit: () => void = () => undefined;+ let groupAlive = true;+ let videoPath = '';+ const kill = vi.fn((signal: NodeJS.Signals) => {+ if (signal === 'SIGINT') resolveLeaderExit();+ if (signal === 'SIGKILL') groupAlive = false;+ });+ const ingest = vi.fn(async () => ({+ hash: 'c'.repeat(64),+ ext: '.mov',+ mimeType: 'video/quicktime',+ bytes: 9,+ url: `cindy-media://blobs/${'c'.repeat(64)}.mov`,+ deduplicated: false,+ refIds: ['ref-video'],+ }));+ const capture = new IOSSimulatorMediaCapture({+ ingest,+ recordingLauncher: {+ launch: vi.fn((args: readonly string[]) => {+ videoPath = args.at(-1)!;+ return {+ exited: new Promise<void>((resolve) => {+ resolveLeaderExit = resolve;+ }),+ isAlive: () => groupAlive,+ kill,+ };+ }),+ },+ });+ const started = await capture.startRecording({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ source: 'agent',+ });+ await writeFile(videoPath, Buffer.from('mov-bytes'));++ vi.useFakeTimers();+ const stopped = capture.stopRecording({+ recordingId: started.recordingId,+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ });+ await vi.advanceTimersByTimeAsync(6_025);+ await expect(stopped).rejects.toMatchObject({ code: 'RECORDING_FAILED' });++ expect(kill.mock.calls.map(([signal]) => signal)).toEqual(['SIGINT', 'SIGTERM', 'SIGKILL']);+ expect(ingest).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);+ });++ it('closes the start gate before an in-flight recording can launch during dispose', async () => {+ const launch = vi.fn();+ const capture = new IOSSimulatorMediaCapture({ recordingLauncher: { launch } });++ const starting = capture.startRecording({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ source: 'agent',+ });+ const disposing = capture.dispose();++ await expect(starting).rejects.toMatchObject({ code: 'RECORDING_FAILED' });+ await expect(disposing).resolves.toBeUndefined();+ expect(launch).not.toHaveBeenCalled();+ });++ it('synchronously kills active recorders on force-exit and rejects later starts', async () => {+ let resolveExit: () => void = () => undefined;+ let videoPath = '';+ const kill = vi.fn((signal: NodeJS.Signals) => {+ if (signal === 'SIGKILL') resolveExit();+ });+ const capture = new IOSSimulatorMediaCapture({+ recordingLauncher: {+ launch: vi.fn((args: readonly string[]) => {+ videoPath = args.at(-1)!;+ return {+ exited: new Promise<void>((resolve) => {+ resolveExit = resolve;+ }),+ kill,+ };+ }),+ },+ });+ await capture.startRecording({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ source: 'agent',+ });++ capture.abortOperationsForExit();++ expect(kill).toHaveBeenCalledWith('SIGKILL');+ await expect(stat(path.dirname(videoPath))).rejects.toMatchObject({ code: 'ENOENT' });+ await expect(+ capture.startRecording({+ simulatorUdid: 'EXACT-UDID-2',+ sessionId: 'session-a',+ instanceId: 'instance-b',+ generation: 1,+ source: 'agent',+ }),+ ).rejects.toMatchObject({ code: 'RECORDING_FAILED' });+ await capture.dispose();+ });++ it('keeps a finalizing recorder visible to the force-exit path', async () => {+ let resolveExit: () => void = () => undefined;+ let videoPath = '';+ const kill = vi.fn((signal: NodeJS.Signals) => {+ if (signal === 'SIGKILL') resolveExit();+ });+ const capture = new IOSSimulatorMediaCapture({+ recordingLauncher: {+ launch: vi.fn((args: readonly string[]) => {+ videoPath = args.at(-1)!;+ return {+ exited: new Promise<void>((resolve) => {+ resolveExit = resolve;+ }),+ kill,+ };+ }),+ },+ });+ const started = await capture.startRecording({+ simulatorUdid: 'EXACT-UDID',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ source: 'agent',+ });++ vi.useFakeTimers();+ const stopped = capture.stopRecording({+ recordingId: started.recordingId,+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 3,+ });+ await Promise.resolve();+ expect(kill).toHaveBeenCalledWith('SIGINT');++ capture.abortOperationsForExit();++ expect(kill).toHaveBeenCalledWith('SIGKILL');+ await expect(stopped).rejects.toMatchObject({ code: 'RECORDING_NOT_FOUND' });+ await expect(stat(path.dirname(videoPath))).rejects.toMatchObject({ code: 'ENOENT' });+ expect(vi.getTimerCount()).toBe(0);+ });++ it('regular dispose immediately kills both finalizing and active recorders', async () => {+ const exits = new Map<string, () => void>();+ const kills = new Map<string, ReturnType<typeof vi.fn>>();+ const paths = new Map<string, string>();+ const capture = new IOSSimulatorMediaCapture({+ recordingLauncher: {+ launch: vi.fn((args: readonly string[]) => {+ const instanceId = args[2] === 'UDID-A' ? 'instance-a' : 'instance-b';+ paths.set(instanceId, args.at(-1)!);+ const kill = vi.fn((signal: NodeJS.Signals) => {+ if (signal === 'SIGKILL') exits.get(instanceId)?.();+ });+ kills.set(instanceId, kill);+ return {+ exited: new Promise<void>((resolve) => exits.set(instanceId, resolve)),+ kill,+ };+ }),+ },+ });+ const first = await capture.startRecording({+ simulatorUdid: 'UDID-A',+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 1,+ source: 'agent',+ });+ await capture.startRecording({+ simulatorUdid: 'UDID-B',+ sessionId: 'session-a',+ instanceId: 'instance-b',+ generation: 1,+ source: 'agent',+ });++ vi.useFakeTimers();+ const stopping = capture.stopRecording({+ recordingId: first.recordingId,+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 1,+ });+ await Promise.resolve();+ const disposing = capture.dispose();++ expect(kills.get('instance-a')).toHaveBeenCalledWith('SIGKILL');+ expect(kills.get('instance-b')).toHaveBeenCalledWith('SIGKILL');+ await expect(stopping).rejects.toMatchObject({ code: 'RECORDING_NOT_FOUND' });+ await expect(disposing).resolves.toBeUndefined();+ await expect(stat(path.dirname(paths.get('instance-a')!))).rejects.toMatchObject({+ code: 'ENOENT',+ });+ await expect(stat(path.dirname(paths.get('instance-b')!))).rejects.toMatchObject({+ code: 'ENOENT',+ });+ expect(vi.getTimerCount()).toBe(0);+ });});diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-renderer-access.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-renderer-access.test.tsnew file mode 100644index 0000000000..c856d141e6--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-renderer-access.test.ts@@ -0,0 +1,349 @@+import { describe, expect, it, vi } from 'vitest';++import type { IOSSimulatorPublicRouteStatus } from '../../../shared/iosSimulatorIpc';+import {+ IOSSimulatorRendererAccessRegistry,+ type IOSSimulatorRendererWebContents,+} from '../ios-simulator-renderer-access';++function fakeWebContents(id: number) {+ let destroyed = false;+ let destroyedListener: (() => void) | null = null;+ const target: IOSSimulatorRendererWebContents = {+ id,+ isDestroyed: () => destroyed,+ send: vi.fn(),+ once: vi.fn((_event: 'destroyed', listener: () => void) => {+ destroyedListener = listener;+ }),+ };+ return {+ target,+ send: target.send as ReturnType<typeof vi.fn>,+ destroy: () => {+ destroyed = true;+ destroyedListener?.();+ },+ };+}++const routeStatus: IOSSimulatorPublicRouteStatus = {+ sessionId: 'session-a',+ instanceId: 'instance-a',+ generation: 1,+ updatedAt: '2026-08-08T00:00:00.000Z',+ stream: {+ adapter: 'native-sidecar',+ encoding: 'h264',+ state: 'active',+ reasonCode: 'native-active',+ },+ input: {+ adapter: 'native-sidecar',+ state: 'active',+ continuous: true,+ multiTouch: false,+ reasonCode: 'native-active',+ },+};++describe('IOSSimulatorRendererAccessRegistry', () => {+ it('grants an exact Main-owned window family and focuses only the selected host', () => {+ const registry = new IOSSimulatorRendererAccessRegistry();+ const main = fakeWebContents(11);+ const sidebar = fakeWebContents(12);+ registry.configureResolver(() => ({+ grantTargets: [main.target, sidebar.target],+ focusTarget: sidebar.target,+ }));++ expect(registry.grantAndFocus('session-a', 'instance-a')).toBe(true);+ expect(registry.hasAccess(main.target, 'session-a')).toBe(true);+ expect(registry.hasAccess(sidebar.target, 'session-a')).toBe(true);+ expect(registry.hasAccess(main.target, 'session-b')).toBe(false);+ expect(main.send).not.toHaveBeenCalled();+ expect(sidebar.send).toHaveBeenCalledWith('maker:ios-simulator:focus-request', {+ sessionId: 'session-a',+ instanceId: 'instance-a',+ userInitiated: false,+ });+ });++ it('replaces the previous session grant instead of trusting a forged route', () => {+ const registry = new IOSSimulatorRendererAccessRegistry();+ const main = fakeWebContents(21);+ registry.configureResolver(() => ({ grantTargets: [main.target], focusTarget: main.target }));++ registry.grantAndFocus('session-a');+ registry.grantAndFocus('session-b');++ expect(registry.hasAccess(main.target, 'session-a')).toBe(false);+ expect(registry.hasAccess(main.target, 'session-b')).toBe(true);+ });++ it('notifies only when an exact renderer actually loses its session grant', () => {+ const registry = new IOSSimulatorRendererAccessRegistry();+ const main = fakeWebContents(211);+ const sidebar = fakeWebContents(212);+ const revoked = vi.fn();+ registry.configureResolver(() => ({+ grantTargets: [main.target, sidebar.target],+ focusTarget: sidebar.target,+ }));+ registry.configureRevocationObserver(revoked);++ registry.grantAndFocus('session-a');+ revoked.mockClear();+ registry.grantAndFocus('session-a');+ expect(revoked).not.toHaveBeenCalled();++ registry.grantAndFocus('session-b');+ expect(revoked).toHaveBeenCalledTimes(1);+ expect(revoked.mock.calls[0]?.[0]).toEqual([+ expect.objectContaining({ sessionId: 'session-a', target: main.target }),+ expect.objectContaining({ sessionId: 'session-a', target: sidebar.target }),+ ]);++ revoked.mockClear();+ registry.clear();+ expect(revoked).toHaveBeenCalledTimes(1);+ expect(revoked.mock.calls[0]?.[0]).toEqual([+ expect.objectContaining({ sessionId: 'session-b', target: main.target }),+ expect.objectContaining({ sessionId: 'session-b', target: sidebar.target }),+ ]);+ });++ it('notifies synchronously when a granted renderer is destroyed', () => {+ const registry = new IOSSimulatorRendererAccessRegistry();+ const main = fakeWebContents(221);+ const revoked = vi.fn();+ registry.configureResolver(() => ({ grantTargets: [main.target], focusTarget: main.target }));+ registry.configureRevocationObserver(revoked);+ registry.grantAndFocus('session-a');+ revoked.mockClear();++ main.destroy();++ expect(revoked).toHaveBeenCalledWith([+ expect.objectContaining({ sessionId: 'session-a', target: main.target }),+ ]);+ });++ it('pushes route status only to exact renderers granted for that session', () => {+ const registry = new IOSSimulatorRendererAccessRegistry();+ const sessionA = fakeWebContents(31);+ const sessionB = fakeWebContents(32);+ registry.configureResolver((preferred) => ({+ grantTargets: preferred ? [preferred] : [],+ focusTarget: preferred ?? null,+ }));+ registry.grantAndFocus('session-a', undefined, sessionA.target);+ registry.grantAndFocus('session-b', undefined, sessionB.target);+ sessionA.send.mockClear();+ sessionB.send.mockClear();++ expect(registry.pushRouteStatus(routeStatus)).toBe(1);+ expect(sessionA.send).toHaveBeenCalledWith('maker:ios-simulator:route-status', routeStatus);+ expect(sessionB.send).not.toHaveBeenCalled();+ });++ it('revokes grants when a window is destroyed or a task is removed', () => {+ const registry = new IOSSimulatorRendererAccessRegistry();+ const first = fakeWebContents(41);+ const second = fakeWebContents(42);+ registry.configureResolver((preferred) => ({+ grantTargets: preferred ? [preferred] : [],+ focusTarget: preferred ?? null,+ }));+ registry.grantAndFocus('session-a', undefined, first.target);+ registry.grantAndFocus('session-a', undefined, second.target);++ first.destroy();+ expect(registry.hasAccess(first.target, 'session-a')).toBe(false);+ expect(registry.hasAccess(second.target, 'session-a')).toBe(true);++ registry.revokeSession('session-a');+ expect(registry.hasAccess(second.target, 'session-a')).toBe(false);+ });++ it('inherits the current Main grant when a detached sidebar is created later', () => {+ const registry = new IOSSimulatorRendererAccessRegistry();+ const main = fakeWebContents(51);+ const sidebar = fakeWebContents(52);+ registry.configureResolver(() => ({ grantTargets: [main.target], focusTarget: main.target }));+ registry.grantAndFocus('session-a');++ expect(registry.inheritAccess(main.target, sidebar.target)).toBe(true);+ expect(registry.hasAccess(sidebar.target, 'session-a')).toBe(true);+ expect(registry.hasAccess(sidebar.target, 'session-b')).toBe(false);+ });++ it('requires the exact WebContents object even when a numeric id is reused', () => {+ const registry = new IOSSimulatorRendererAccessRegistry();+ const original = fakeWebContents(61);+ const replacement = fakeWebContents(61);+ registry.configureResolver(() => ({+ grantTargets: [original.target],+ focusTarget: original.target,+ }));+ registry.grantAndFocus('session-a');++ expect(registry.hasAccess(original.target, 'session-a')).toBe(true);+ expect(registry.hasAccess(replacement.target, 'session-a')).toBe(false);+ });++ it('grants a confirmed manual request without sending a focus command', async () => {+ const registry = new IOSSimulatorRendererAccessRegistry();+ const main = fakeWebContents(71);+ const sidebar = fakeWebContents(72);+ const confirm = vi.fn(async () => true);+ registry.configureResolver(() => ({+ grantTargets: [main.target, sidebar.target],+ focusTarget: sidebar.target,+ }));+ registry.configureConfirmation(confirm);++ await expect(registry.requestAccess('session-a', main.target)).resolves.toBe(true);+ expect(confirm).toHaveBeenCalledWith(main.target, 'session-a');+ expect(registry.hasAccess(main.target, 'session-a')).toBe(true);+ expect(registry.hasAccess(sidebar.target, 'session-a')).toBe(true);+ expect(main.send).not.toHaveBeenCalled();+ expect(sidebar.send).not.toHaveBeenCalled();+ });++ it('does not grant when native confirmation is cancelled', async () => {+ const registry = new IOSSimulatorRendererAccessRegistry();+ const main = fakeWebContents(81);+ registry.configureResolver(() => ({ grantTargets: [main.target], focusTarget: main.target }));+ registry.configureConfirmation(async () => false);++ await expect(registry.requestAccess('session-a', main.target)).resolves.toBe(false);+ expect(registry.hasAccess(main.target, 'session-a')).toBe(false);+ });++ it('invalidates a pending confirmation when the window family switches tasks', async () => {+ const registry = new IOSSimulatorRendererAccessRegistry();+ const main = fakeWebContents(91);+ const sidebar = fakeWebContents(92);+ const deferred: { resolve?: (confirmed: boolean) => void } = {};+ registry.configureResolver(() => ({+ grantTargets: [main.target, sidebar.target],+ focusTarget: sidebar.target,+ }));+ registry.configureConfirmation(+ () =>+ new Promise<boolean>((resolve) => {+ deferred.resolve = resolve;+ }),+ );++ const pending = registry.requestAccess('session-a', sidebar.target);+ expect(registry.revokeForSessionChange(main.target, 'session-b')).toBe(0);+ deferred.resolve?.(true);++ await expect(pending).resolves.toBe(false);+ expect(registry.hasAccess(main.target, 'session-a')).toBe(false);+ expect(registry.hasAccess(sidebar.target, 'session-a')).toBe(false);+ });++ it('revokes an entire inherited family when either target switches tasks', () => {+ const registry = new IOSSimulatorRendererAccessRegistry();+ const main = fakeWebContents(101);+ const sidebar = fakeWebContents(102);+ registry.configureResolver(() => ({+ grantTargets: [main.target, sidebar.target],+ focusTarget: sidebar.target,+ }));+ registry.grantAndFocus('session-a');++ expect(registry.revokeForSessionChange(main.target, 'session-b')).toBe(2);+ expect(registry.hasAccess(main.target, 'session-a')).toBe(false);+ expect(registry.hasAccess(sidebar.target, 'session-a')).toBe(false);+ });++ it('does not grant after the requesting WebContents is destroyed', async () => {+ const registry = new IOSSimulatorRendererAccessRegistry();+ const main = fakeWebContents(111);+ const deferred: { resolve?: (confirmed: boolean) => void } = {};+ registry.configureResolver(() => ({ grantTargets: [main.target], focusTarget: main.target }));+ registry.configureConfirmation(+ () =>+ new Promise<boolean>((resolve) => {+ deferred.resolve = resolve;+ }),+ );++ const pending = registry.requestAccess('session-a', main.target);+ main.destroy();+ deferred.resolve?.(true);++ await expect(pending).resolves.toBe(false);+ });++ it('does not let an older manual confirmation overwrite a newer Host grant', async () => {+ const registry = new IOSSimulatorRendererAccessRegistry();+ const main = fakeWebContents(121);+ const deferred: { resolve?: (confirmed: boolean) => void } = {};+ registry.configureResolver(() => ({ grantTargets: [main.target], focusTarget: main.target }));+ registry.configureConfirmation(+ () =>+ new Promise<boolean>((resolve) => {+ deferred.resolve = resolve;+ }),+ );++ const pending = registry.requestAccess('session-a', main.target);+ expect(registry.grantAndFocus('session-b')).toBe(true);+ deferred.resolve?.(true);++ await expect(pending).resolves.toBe(false);+ expect(registry.hasAccess(main.target, 'session-a')).toBe(false);+ expect(registry.hasAccess(main.target, 'session-b')).toBe(true);+ });++ it('reports success when a concurrent Host flow grants the same session', async () => {+ const registry = new IOSSimulatorRendererAccessRegistry();+ const main = fakeWebContents(131);+ const deferred: { resolve?: (confirmed: boolean) => void } = {};+ registry.configureResolver(() => ({ grantTargets: [main.target], focusTarget: main.target }));+ registry.configureConfirmation(+ () =>+ new Promise<boolean>((resolve) => {+ deferred.resolve = resolve;+ }),+ );++ const pending = registry.requestAccess('session-a', main.target);+ expect(registry.grantAndFocus('session-a')).toBe(true);+ deferred.resolve?.(true);++ await expect(pending).resolves.toBe(true);+ expect(registry.hasAccess(main.target, 'session-a')).toBe(true);+ });++ it.each([+ ['plugin disable', (registry: IOSSimulatorRendererAccessRegistry) => registry.clear()],+ [+ 'session removal',+ (registry: IOSSimulatorRendererAccessRegistry) => registry.revokeSession('session-a'),+ ],+ ])('invalidates a pending confirmation after %s', async (_reason, revoke) => {+ const registry = new IOSSimulatorRendererAccessRegistry();+ const main = fakeWebContents(141);+ const deferred: { resolve?: (confirmed: boolean) => void } = {};+ registry.configureResolver(() => ({ grantTargets: [main.target], focusTarget: main.target }));+ registry.configureConfirmation(+ () =>+ new Promise<boolean>((resolve) => {+ deferred.resolve = resolve;+ }),+ );++ const pending = registry.requestAccess('session-a', main.target);+ revoke(registry);+ deferred.resolve?.(true);++ await expect(pending).resolves.toBe(false);+ expect(registry.hasAccess(main.target, 'session-a')).toBe(false);+ });+});diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.tsindex 1a23fbd1f3..99bdcb0381 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts@@ -1,4 +1,5 @@-import { mkdir, rm, stat, utimes } from 'node:fs/promises';+import { mkdir, mkdtemp, rm, stat, utimes, writeFile } from 'node:fs/promises';+import os from 'node:os';import path from 'node:path';import { app } from 'electron';@@ -10,6 +11,7 @@ import {IOSSimulatorInstanceActor,IOSSimulatorInstanceError,IOSSimulatorOwnershipStore,+ IOSSimulatorOwnershipRegistryFile,IOSSimulatorProjectBuildError,IOSSimulatorResourceScheduler,WdaError,@@ -25,6 +27,7 @@ import {import type { IOSSimulatorPublicRouteStatus } from '../../../shared/iosSimulatorIpc';import {createIOSSimulatorHost,+ createRegistryBackedIOSSimulatorActor,getIOSSimulatorMcpDeps,type IOSSimulatorAppLifecycleAdapter,type IOSSimulatorMediaCaptureAdapter,@@ -97,6 +100,71 @@ describe('iOS Simulator host', () => {expect(environment).not.toHaveProperty('data.devices.0.availabilityError');});+ it('keeps Desktop available while a malformed ownership registry fails Simulator closed', async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-host-registry-'));+ const registry = new IOSSimulatorOwnershipRegistryFile(path.join(root, 'registry.json'), {+ acquireWriterLease: () => {+ let held = true;+ return {+ isHeld: () => held,+ release: () => {+ held = false;+ },+ };+ },+ });+ await writeFile(registry.filePath, '{"version":1,"instances":[');+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(),+ deleteExact: vi.fn(),+ };++ try {+ const persisted = createRegistryBackedIOSSimulatorActor(lifecycle, registry);+ await expect(+ persisted.actor.create({+ sessionId: 'session-a',+ worktreeRoot: '/tmp/session-a',+ sourceFingerprint: 'fingerprint-a',+ name: 'Must not be created',+ templateDevice: {+ ...READY_REPORT.devices[0]!,+ deviceTypeIdentifier: 'com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro',+ },+ }),+ ).rejects.toMatchObject({ code: 'DEVICE_BUSY' });+ expect(lifecycle.createExact).not.toHaveBeenCalled();+ const host = createIOSSimulatorHost({+ actor: persisted.actor,+ lifecycle,+ runtime: { inspect: vi.fn(async () => READY_REPORT) },+ getSession: vi.fn(async (id) => localSession(id)),+ resolveWorktreeRoot: vi.fn(async () => '/tmp/session-a'),+ });++ await expect(+ host.callTool(+ 'attach_device',+ { udid: READY_REPORT.devices[0]!.udid },+ { sessionId: 'session-a', origin: 'user' },+ ),+ ).resolves.toMatchObject({+ ok: false,+ errorCode: 'DEVICE_BUSY',+ message: expect.stringContaining('ownership registry is invalid'),+ });+ expect(registry.isWriter).toBe(true);+ await persisted.flush();+ persisted.release();+ await host.dispose();+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });+it('projects task ownership, resource limits, and safe unavailable-device reasons', async () => {const unavailableDevice = {...READY_REPORT.devices[0]!,@@ -1087,10 +1155,14 @@ describe('iOS Simulator host', () => {},),);+ const disposeMedia = vi.fn(async () => undefined);const host = createIOSSimulatorHost({actor,lifecycle,projectBuilder: { build },+ mediaCapture: {+ dispose: disposeMedia,+ } as unknown as IOSSimulatorMediaCaptureAdapter,runtime: { inspect: vi.fn(async () => READY_REPORT) },getSession: vi.fn(async () => localSession('dispose-build-session')),});@@ -1108,6 +1180,7 @@ describe('iOS Simulator host', () => {await vi.waitFor(() => expect(build).toHaveBeenCalledTimes(1));const disposePromise = host.dispose();+ expect(disposeMedia).toHaveBeenCalledOnce();await vi.waitFor(() => expect(buildSignal?.aborted).toBe(true));await disposePromise;@@ -1162,10 +1235,15 @@ describe('iOS Simulator host', () => {},),);+ const abortRecording = vi.fn();const host = createIOSSimulatorHost({actor,lifecycle,projectBuilder: { build },+ mediaCapture: {+ abortOperationsForExit: abortRecording,+ discardInstance: vi.fn(async () => undefined),+ } as unknown as IOSSimulatorMediaCaptureAdapter,runtime: { inspect: vi.fn(async () => READY_REPORT) },getSession: vi.fn(async () => localSession('force-quit-build-session')),});@@ -1185,6 +1263,7 @@ describe('iOS Simulator host', () => {host.abortOperationsForExit();expect(buildSignal?.aborted).toBe(true);+ expect(abortRecording).toHaveBeenCalledOnce();await expect(callPromise).resolves.toMatchObject({ok: false,errorCode: 'MUTATION_CANCELLED',@@ -1632,6 +1711,9 @@ describe('iOS Simulator host', () => {} satisfies IOSSimulatorStreamStats;},);+ const beginTouch = vi.fn(async () => undefined);+ const moveTouch = vi.fn(async () => undefined);+ const endTouch = vi.fn(async () => undefined);const nativeDriver = {kind: 'native-sidecar',capabilities: {@@ -1646,6 +1728,9 @@ describe('iOS Simulator host', () => {},configureNativeStream: vi.fn(async (profile) => profile),streamNativeFrames,+ beginTouch,+ moveTouch,+ endTouch,} as unknown as IOSSimulatorNativeSidecarDriver;const getWindowSize = vi.fn(async () => ({ width: 393, height: 852 }));const wdaDriver = {@@ -1683,6 +1768,7 @@ describe('iOS Simulator host', () => {source: nativeDriver,})),capabilityReport,+ continuousInput: vi.fn(() => nativeDriver),},} as unknown as WdaRunningInstance;const pushH264Frame = vi.fn();@@ -1811,11 +1897,27 @@ describe('iOS Simulator host', () => {),).resolves.toMatchObject({ ok: true, data: { ignored: true } });+ await expect(+ host.updateViewerTouch('session-a', route, 88, {+ gestureId: 'gesture-old-viewer',+ phase: 'begin',+ xRatio: 0.4,+ yRatio: 0.4,+ }),+ ).resolves.toMatchObject({ ok: 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 vi.waitFor(() =>+ expect(endTouch).toHaveBeenCalledWith(+ 'gesture-old-viewer',+ expect.objectContaining({ x: expect.any(Number), y: expect.any(Number) }),+ true,+ ),+ );+ endTouch.mockClear();await emitFrame({ ...firstFrame, timestampMicros: 4 });expect(pushH264Frame).toHaveBeenCalledTimes(4);expect(pushH264Frame).toHaveBeenLastCalledWith(@@ -1823,6 +1925,31 @@ describe('iOS Simulator host', () => {expect.objectContaining({ instanceId: instance.instanceId }),);+ await expect(+ host.updateViewerTouch('session-a', route, 99, {+ gestureId: 'gesture-1',+ phase: 'begin',+ xRatio: 0.5,+ yRatio: 0.5,+ }),+ ).resolves.toMatchObject({ ok: true });+ expect(beginTouch).toHaveBeenCalledTimes(2);+ expect(host.revokeRendererViewer('session-b', 99)).toBe(0);+ expect(host.revokeRendererViewer('session-a', 98)).toBe(0);+ await emitFrame({ ...firstFrame, timestampMicros: 5 });+ expect(pushH264Frame).toHaveBeenCalledTimes(5);++ expect(host.revokeRendererViewer('session-a', 99)).toBe(1);+ await vi.waitFor(() =>+ expect(endTouch).toHaveBeenCalledWith(+ 'gesture-1',+ expect.objectContaining({ x: expect.any(Number), y: expect.any(Number) }),+ true,+ ),+ );+ await emitFrame({ ...firstFrame, timestampMicros: 6 });+ expect(pushH264Frame).toHaveBeenCalledTimes(5);+const current = actor.getOwned('session-a', instance.instanceId);await actor.stop({sessionId: current.sessionId,@@ -1830,8 +1957,8 @@ describe('iOS Simulator host', () => {generation: current.generation,leaseId: current.lease.id,});- await emitFrame({ ...firstFrame, timestampMicros: 5 });- expect(pushH264Frame).toHaveBeenCalledTimes(4);+ await emitFrame({ ...firstFrame, timestampMicros: 7 });+ expect(pushH264Frame).toHaveBeenCalledTimes(5);await host.dispose();});diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator-media.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator-media.tsindex a76eebf038..046f66060c 100644--- a/apps/desktop/src/main/mcp-integrations/ios-simulator-media.ts+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator-media.ts@@ -1,5 +1,6 @@import { randomUUID } from 'node:crypto';import { spawn } from 'node:child_process';+import { rmSync } from 'node:fs';import { mkdtemp, readFile, rm, stat } from 'node:fs/promises';import os from 'node:os';import path from 'node:path';@@ -22,6 +23,9 @@ const MAX_SCREENSHOT_BYTES = 32 * 1024 * 1024;// allocations; larger captures are rejected before readFile.const MAX_BUFFERED_RECORDING_BYTES = 128 * 1024 * 1024;const RECORDING_STOP_TIMEOUT_MS = 5_000;+const RECORDING_TERM_TIMEOUT_MS = 1_000;+const RECORDING_KILL_TIMEOUT_MS = 500;+const RECORDING_DISCARD_KILL_TIMEOUT_MS = 500;export interface IOSSimulatorMediaCaptureOptions {commandRunner?: IOSSimulatorCommandRunner;@@ -31,6 +35,8 @@ export interface IOSSimulatorMediaCaptureOptions {export interface IOSSimulatorRecordingProcess {exited: Promise<void>;+ /** True while the detached recorder process group still owns live members. */+ isAlive?(): boolean;kill(signal: NodeJS.Signals): void;}@@ -55,6 +61,19 @@ interface ActiveRecording {tempRoot: string;videoPath: string;process: IOSSimulatorRecordingProcess;+ phase: 'active' | 'finalizing';+ discardRequested: boolean;+ discardSignalSent: boolean;+}++function isProcessGroupAlive(pid: number, leaderClosed: boolean): boolean {+ if (process.platform === 'win32') return !leaderClosed;+ try {+ process.kill(-pid, 0);+ return true;+ } catch (error) {+ return (error as NodeJS.ErrnoException | null)?.code === 'EPERM';+ }}function createRecordingLauncher(): IOSSimulatorRecordingLauncher {@@ -66,21 +85,33 @@ function createRecordingLauncher(): IOSSimulatorRecordingLauncher {windowsHide: true,stdio: ['ignore', 'ignore', 'ignore'],});+ child.on('error', () => {+ // ChildProcess requires an error listener to avoid an uncaught Main+ // exception. The error is deliberately not treated as proof of exit.+ });if (!child.pid) {throw new IOSSimulatorInstanceError('RECORDING_FAILED','The recording process did not start.',);}+ const pid = child.pid;+ let leaderClosed = false;+ const exited = new Promise<void>((resolve) => {+ child.once('close', () => {+ leaderClosed = true;+ resolve();+ });+ // A post-spawn error is not proof that the detached process group is+ // gone. `close` plus the group liveness probe remains authoritative.+ });return {- exited: new Promise((resolve) => {- child.once('exit', () => resolve());- child.once('error', () => resolve());- }),+ exited,+ isAlive: () => isProcessGroupAlive(pid, leaderClosed),kill(signal) {- if (process.platform !== 'win32' && child.pid) {+ if (process.platform !== 'win32') {try {- process.kill(-child.pid, signal);+ process.kill(-pid, signal);return;} catch {// The process group may have already exited; fall back to child.@@ -97,17 +128,66 @@ async function waitForRecordingExit(process: IOSSimulatorRecordingProcess,timeoutMs: number,): Promise<boolean> {- return Promise.race([- process.exited.then(() => true),- new Promise<false>((resolve) => setTimeout(() => resolve(false), timeoutMs)),- ]);+ return new Promise<boolean>((resolve) => {+ let settled = false;+ let poll: ReturnType<typeof setInterval> | null = null;+ const finish = (exited: boolean): void => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ if (poll) clearInterval(poll);+ resolve(exited);+ };+ const timer = setTimeout(() => finish(false), timeoutMs);+ const confirmExit = (): void => {+ try {+ if (process.isAlive && !process.isAlive()) finish(true);+ } catch {+ // A failed liveness probe cannot prove the process group is gone.+ }+ };+ if (process.isAlive) {+ poll = setInterval(confirmExit, 25);+ confirmExit();+ }+ void process.exited.then(+ () => {+ if (!process.isAlive) finish(true);+ else confirmExit();+ },+ () => undefined,+ );+ });+}++function signalRecordingProcess(+ process: IOSSimulatorRecordingProcess,+ signal: NodeJS.Signals,+): void {+ try {+ process.kill(signal);+ } catch {+ // Exit observation remains authoritative; continue through the bounded waits.+ }}-async function terminateRecordingProcess(process: IOSSimulatorRecordingProcess): Promise<void> {- process.kill('SIGINT');- if (await waitForRecordingExit(process, RECORDING_STOP_TIMEOUT_MS)) return;- process.kill('SIGTERM');- await process.exited;+async function terminateRecordingProcess(+ process: IOSSimulatorRecordingProcess,+ mode: 'finalize' | 'discard',+): Promise<'finalized' | 'terminated' | 'stuck'> {+ if (mode === 'finalize') {+ signalRecordingProcess(process, 'SIGINT');+ if (await waitForRecordingExit(process, RECORDING_STOP_TIMEOUT_MS)) return 'finalized';+ signalRecordingProcess(process, 'SIGTERM');+ if (await waitForRecordingExit(process, RECORDING_TERM_TIMEOUT_MS)) return 'terminated';+ }+ signalRecordingProcess(process, 'SIGKILL');+ return (await waitForRecordingExit(+ process,+ mode === 'discard' ? RECORDING_DISCARD_KILL_TIMEOUT_MS : RECORDING_KILL_TIMEOUT_MS,+ ))+ ? 'terminated'+ : 'stuck';}/** Explicit simulator media capture. Transient stream frames never enter this path. */@@ -116,6 +196,8 @@ export class IOSSimulatorMediaCapture {readonly #ingest: typeof ingestMedia;readonly #recordingLauncher: IOSSimulatorRecordingLauncher;readonly #recordings = new Map<string, ActiveRecording>();+ #recordingOperationTail: Promise<void> = Promise.resolve();+ #closed = false;constructor(options: IOSSimulatorMediaCaptureOptions = {}) {this.#runner = options.commandRunner ?? createNodeIOSSimulatorCommandRunner();@@ -123,6 +205,48 @@ export class IOSSimulatorMediaCapture {this.#recordingLauncher = options.recordingLauncher ?? createRecordingLauncher();}+ #serializeRecordingOperation<T>(operation: () => Promise<T>): Promise<T> {+ const result = this.#recordingOperationTail.then(operation, operation);+ this.#recordingOperationTail = result.then(+ () => undefined,+ () => undefined,+ );+ return result;+ }++ #requestDiscard(instanceId?: string): void {+ for (const recording of this.#recordings.values()) {+ if (instanceId && recording.instanceId !== instanceId) continue;+ recording.discardRequested = true;+ if (!recording.discardSignalSent) {+ recording.discardSignalSent = true;+ // Discard never preserves the MOV. Kill immediately so one finalizing+ // recorder cannot hold Desktop teardown while another remains active.+ signalRecordingProcess(recording.process, 'SIGKILL');+ }+ }+ }++ async #discardMatching(instanceId?: string): Promise<void> {+ const recordings = Array.from(this.#recordings.values()).filter(+ (recording) => !instanceId || recording.instanceId === instanceId,+ );+ await Promise.all(+ recordings.map(async (recording) => {+ try {+ if (recording.discardSignalSent) {+ await waitForRecordingExit(recording.process, RECORDING_KILL_TIMEOUT_MS);+ } else {+ await terminateRecordingProcess(recording.process, 'discard');+ }+ } finally {+ this.#recordings.delete(recording.recordingId);+ await rm(recording.tempRoot, { recursive: true, force: true });+ }+ }),+ );+ }+async captureScreenshotBytes(input: Pick<IOSSimulatorScreenshotInput, 'simulatorUdid'>,): Promise<Buffer> {@@ -186,38 +310,57 @@ export class IOSSimulatorMediaCapture {generation: number;source: 'agent' | 'user';}): Promise<{ recordingId: string; startedAt: string }> {- if (- Array.from(this.#recordings.values()).some((item) => item.instanceId === input.instanceId)- ) {- throw new IOSSimulatorInstanceError(- 'RECORDING_ALREADY_ACTIVE',- 'This simulator already has an active recording.',- );- }- const tempRoot = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-recording-'));- const videoPath = path.join(tempRoot, 'recording.mov');- const recordingId = randomUUID();- try {- const process = this.#recordingLauncher.launch([- 'simctl',- 'io',- input.simulatorUdid,- 'recordVideo',- '--codec=h264',- videoPath,- ]);- this.#recordings.set(recordingId, {- ...input,- recordingId,- tempRoot,- videoPath,- process,- });- return { recordingId, startedAt: new Date().toISOString() };- } catch (error) {- await rm(tempRoot, { recursive: true, force: true });- throw error;- }+ return this.#serializeRecordingOperation(async () => {+ if (this.#closed) {+ throw new IOSSimulatorInstanceError(+ 'RECORDING_FAILED',+ 'The simulator media service is shutting down.',+ true,+ );+ }+ if (+ Array.from(this.#recordings.values()).some((item) => item.instanceId === input.instanceId)+ ) {+ throw new IOSSimulatorInstanceError(+ 'RECORDING_ALREADY_ACTIVE',+ 'This simulator already has an active recording.',+ );+ }+ const tempRoot = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-recording-'));+ const videoPath = path.join(tempRoot, 'recording.mov');+ const recordingId = randomUUID();+ try {+ if (this.#closed) {+ throw new IOSSimulatorInstanceError(+ 'RECORDING_FAILED',+ 'The simulator media service is shutting down.',+ true,+ );+ }+ const process = this.#recordingLauncher.launch([+ 'simctl',+ 'io',+ input.simulatorUdid,+ 'recordVideo',+ '--codec=h264',+ videoPath,+ ]);+ this.#recordings.set(recordingId, {+ ...input,+ recordingId,+ tempRoot,+ videoPath,+ process,+ phase: 'active',+ discardRequested: false,+ discardSignalSent: false,+ });+ return { recordingId, startedAt: new Date().toISOString() };+ } catch (error) {+ await rm(tempRoot, { recursive: true, force: true });+ throw error;+ }+ });}async stopRecording(input: {@@ -226,62 +369,94 @@ export class IOSSimulatorMediaCapture {instanceId: string;generation: number;}): Promise<IngestedMedia> {- const recording = this.#recordings.get(input.recordingId);- if (- !recording ||- recording.sessionId !== input.sessionId ||- recording.instanceId !== input.instanceId ||- recording.generation !== input.generation- ) {- throw new IOSSimulatorInstanceError(- 'RECORDING_NOT_FOUND',- 'The simulator recording does not exist for this current instance generation.',- );- }- this.#recordings.delete(input.recordingId);- try {- await terminateRecordingProcess(recording.process);- const info = await stat(recording.videoPath);- if (!info.isFile() || info.size <= 0 || info.size > MAX_BUFFERED_RECORDING_BYTES) {+ return this.#serializeRecordingOperation(async () => {+ const recording = this.#recordings.get(input.recordingId);+ if (+ !recording ||+ recording.sessionId !== input.sessionId ||+ recording.instanceId !== input.instanceId ||+ recording.generation !== input.generation+ ) {throw new IOSSimulatorInstanceError(- 'RECORDING_FAILED',- 'The simulator recording is invalid.',+ 'RECORDING_NOT_FOUND',+ 'The simulator recording does not exist for this current instance generation.',);}- const buffer = await readFile(recording.videoPath);- return await this.#ingest({- buffer,- mimeType: 'video/quicktime',- refs: [- {- refKind: 'session-attachment',- refId: `ios-simulator:${recording.instanceId}:${recording.recordingId}`,- originSessionId: recording.sessionId,- originKind: recording.source === 'agent' ? 'tool' : 'user',- originId: recording.instanceId,- label: 'iOS Simulator recording',- },- ],- });- } finally {- await rm(recording.tempRoot, { recursive: true, force: true });- }+ recording.phase = 'finalizing';+ try {+ const termination = await terminateRecordingProcess(recording.process, 'finalize');+ if (termination !== 'finalized') {+ throw new IOSSimulatorInstanceError(+ 'RECORDING_FAILED',+ termination === 'stuck'+ ? 'The simulator recording process could not be stopped safely.'+ : 'The simulator recording could not be finalized safely.',+ true,+ );+ }+ if (recording.discardRequested || this.#closed) {+ throw new IOSSimulatorInstanceError(+ 'RECORDING_NOT_FOUND',+ 'The simulator recording was discarded while its instance was closing.',+ true,+ );+ }+ const info = await stat(recording.videoPath);+ if (!info.isFile() || info.size <= 0 || info.size > MAX_BUFFERED_RECORDING_BYTES) {+ throw new IOSSimulatorInstanceError(+ 'RECORDING_FAILED',+ 'The simulator recording is invalid.',+ );+ }+ const buffer = await readFile(recording.videoPath);+ return await this.#ingest({+ buffer,+ mimeType: 'video/quicktime',+ refs: [+ {+ refKind: 'session-attachment',+ refId: `ios-simulator:${recording.instanceId}:${recording.recordingId}`,+ originSessionId: recording.sessionId,+ originKind: recording.source === 'agent' ? 'tool' : 'user',+ originId: recording.instanceId,+ label: 'iOS Simulator recording',+ },+ ],+ });+ } finally {+ this.#recordings.delete(recording.recordingId);+ await rm(recording.tempRoot, { recursive: true, force: true });+ }+ });}async discardInstance(instanceId: string): Promise<void> {- const recordings = Array.from(this.#recordings.values()).filter(- (recording) => recording.instanceId === instanceId,- );- await Promise.all(- recordings.map(async (recording) => {- this.#recordings.delete(recording.recordingId);- try {- await terminateRecordingProcess(recording.process);- } finally {- await rm(recording.tempRoot, { recursive: true, force: true });- }- }),- );+ this.#requestDiscard(instanceId);+ return this.#serializeRecordingOperation(() => this.#discardMatching(instanceId));+ }++ /** Graceful Host teardown closes the gate before waiting for in-flight starts. */+ async dispose(): Promise<void> {+ this.#closed = true;+ this.#requestDiscard();+ return this.#serializeRecordingOperation(() => this.#discardMatching());+ }++ /** Updater force-quit cannot await cleanup, so synchronously kill every group. */+ abortOperationsForExit(): void {+ this.#closed = true;+ for (const recording of this.#recordings.values()) {+ recording.discardRequested = true;+ if (!recording.discardSignalSent) {+ recording.discardSignalSent = true;+ signalRecordingProcess(recording.process, 'SIGKILL');+ }+ try {+ rmSync(recording.tempRoot, { recursive: true, force: true });+ } catch {+ // The next graceful cleanup attempt remains bounded and idempotent.+ }+ }}}diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator-renderer-access.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator-renderer-access.tsnew file mode 100644index 0000000000..7ed964dc95--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator-renderer-access.ts@@ -0,0 +1,454 @@+import type {+ IOSSimulatorFocusRequest,+ IOSSimulatorPublicRouteStatus,+} from '../../shared/iosSimulatorIpc.js';+import { IOS_SIMULATOR_ROUTE_STATUS_CHANNEL } from '../../shared/iosSimulatorIpc.js';++const IOS_SIMULATOR_FOCUS_REQUEST_CHANNEL = 'maker:ios-simulator:focus-request';++export interface IOSSimulatorRendererWebContents {+ readonly id: number;+ isDestroyed(): boolean;+ send(channel: string, payload: unknown): void;+ once(event: 'destroyed', listener: () => void): unknown;+}++export interface IOSSimulatorRendererTargetSet {+ /** Exact WebContents allowed to use the session-scoped Simulator IPC surface. */+ grantTargets: readonly IOSSimulatorRendererWebContents[];+ /** One target receives the panel-focus command; companions only receive route status. */+ focusTarget: IOSSimulatorRendererWebContents | null;+}++export type IOSSimulatorRendererTargetResolver = (+ preferredTarget?: IOSSimulatorRendererWebContents,+) => IOSSimulatorRendererTargetSet | null;++export type IOSSimulatorRendererAccessConfirmation = (+ target: IOSSimulatorRendererWebContents,+ sessionId: string,+) => Promise<boolean>;++export type IOSSimulatorRendererGrant = {+ sessionId: string;+ generation: number;+ target: IOSSimulatorRendererWebContents;+};++export type IOSSimulatorRendererAccessRevocationObserver = (+ grants: readonly IOSSimulatorRendererGrant[],+) => void;++/**+ * Main-owned capability registry for the privileged Simulator renderer surface.+ *+ * A renderer URL, route hash, or renderer-reported sidebar context is never an+ * authorization source. Grants are minted only by an authoritative Host flow+ * that already owns the sessionId, and one WebContents can hold only one live+ * session grant at a time.+ */+export class IOSSimulatorRendererAccessRegistry {+ private readonly grants = new Map<number, IOSSimulatorRendererGrant>();+ private readonly trackedTargets = new Map<number, IOSSimulatorRendererWebContents>();+ private readonly targetEpochs = new Map<number, number>();+ private readonly sessionEpochs = new Map<string, number>();+ private readonly pendingAccess = new Map<+ number,+ { sessionId: string; promise: Promise<boolean> }+ >();+ private readonly accessCooldownUntil = new Map<number, number>();+ private resolver: IOSSimulatorRendererTargetResolver | null = null;+ private confirmation: IOSSimulatorRendererAccessConfirmation | null = null;+ private revocationObserver: IOSSimulatorRendererAccessRevocationObserver | null = null;+ private nextGeneration = 0;+ private lifecycleEpoch = 0;++ private static readonly ACCESS_REQUEST_COOLDOWN_MS = 2_000;++ configureResolver(resolver: IOSSimulatorRendererTargetResolver | null): void {+ this.resolver = resolver;+ }++ configureConfirmation(confirmation: IOSSimulatorRendererAccessConfirmation | null): void {+ this.confirmation = confirmation;+ }++ configureRevocationObserver(observer: IOSSimulatorRendererAccessRevocationObserver | null): void {+ this.revocationObserver = observer;+ }++ hasAccess(target: IOSSimulatorRendererWebContents, sessionId: string): boolean {+ const grant = this.grants.get(target.id);+ if (+ !grant ||+ grant.target !== target ||+ grant.sessionId !== sessionId ||+ grant.target.isDestroyed()+ ) {+ if (grant?.target.isDestroyed()) this.revokeGrant(target.id, grant);+ return false;+ }+ return true;+ }++ grantAndFocus(+ sessionId: string,+ instanceId?: string,+ preferredTarget?: IOSSimulatorRendererWebContents,+ ): boolean {+ const normalizedSessionId = sessionId.trim();+ if (!normalizedSessionId) return false;+ const resolved = this.resolveTargets(preferredTarget);+ if (!resolved?.focusTarget) return false;+ const { focusTarget, targets } = resolved;+ if (targets.get(focusTarget.id) !== focusTarget) return false;++ const generation = this.grantTargets(normalizedSessionId, targets.values());++ const request: IOSSimulatorFocusRequest = {+ sessionId: normalizedSessionId,+ ...(instanceId?.trim() ? { instanceId: instanceId.trim() } : {}),+ userInitiated: false,+ };+ try {+ focusTarget.send(IOS_SIMULATOR_FOCUS_REQUEST_CHANNEL, request);+ return true;+ } catch {+ this.revokeGeneration(generation);+ return false;+ }+ }++ requestAccess(sessionId: string, target: IOSSimulatorRendererWebContents): Promise<boolean> {+ const normalizedSessionId = sessionId.trim();+ if (!normalizedSessionId || target.isDestroyed()) return Promise.resolve(false);+ if (this.hasAccess(target, normalizedSessionId)) return Promise.resolve(true);+ if (!this.confirmation || Date.now() < (this.accessCooldownUntil.get(target.id) ?? 0)) {+ return Promise.resolve(false);+ }+ const current = this.pendingAccess.get(target.id);+ if (current) {+ return current.sessionId === normalizedSessionId ? current.promise : Promise.resolve(false);+ }++ const promise = this.performAccessRequest(normalizedSessionId, target).finally(() => {+ const pending = this.pendingAccess.get(target.id);+ if (pending?.promise === promise) this.pendingAccess.delete(target.id);+ });+ this.pendingAccess.set(target.id, { sessionId: normalizedSessionId, promise });+ return promise;+ }++ pushRouteStatus(status: IOSSimulatorPublicRouteStatus): number {+ let delivered = 0;+ for (const [webContentsId, grant] of this.grants) {+ if (grant.sessionId !== status.sessionId) continue;+ if (grant.target.isDestroyed()) {+ this.revokeGrant(webContentsId, grant);+ continue;+ }+ try {+ grant.target.send(IOS_SIMULATOR_ROUTE_STATUS_CHANNEL, status);+ delivered += 1;+ } catch {+ this.revokeGrant(webContentsId, grant);+ }+ }+ return delivered;+ }++ /** Copy an existing Main-window grant when its detached sidebar WebContents is created. */+ inheritAccess(+ sourceTarget: IOSSimulatorRendererWebContents,+ target: IOSSimulatorRendererWebContents,+ ): boolean {+ const source = this.grants.get(sourceTarget.id);+ if (+ !source ||+ source.target !== sourceTarget ||+ source.target.isDestroyed() ||+ !Number.isSafeInteger(target.id) ||+ target.id <= 0 ||+ target.isDestroyed()+ ) {+ return false;+ }+ const existing = this.grants.get(target.id);+ if (existing?.target === target && existing.generation === source.generation) return true;+ const revoked = existing ? this.removeGeneration(existing.generation) : [];+ this.grants.set(target.id, {+ sessionId: source.sessionId,+ generation: source.generation,+ target,+ });+ this.trackDestroyed(target);+ this.notifyRevoked(+ revoked.filter((grant) => {+ const current = this.grants.get(grant.target.id);+ return current?.target !== grant.target || current.sessionId !== grant.sessionId;+ }),+ );+ return true;+ }++ revokeForSessionChange(+ preferredTarget: IOSSimulatorRendererWebContents,+ sessionId: string | null,+ ): number {+ const normalizedSessionId = sessionId?.trim() || null;+ const targets =+ this.resolveTargets(preferredTarget)?.targets ??+ new Map([[preferredTarget.id, preferredTarget]]);+ const generations = new Set<number>();+ for (const target of targets.values()) {+ const grant = this.grants.get(target.id);+ if (+ grant?.target === target &&+ (!normalizedSessionId || grant.sessionId !== normalizedSessionId)+ ) {+ generations.add(grant.generation);+ }+ const pending = this.pendingAccess.get(target.id);+ if (pending && (!normalizedSessionId || pending.sessionId !== normalizedSessionId)) {+ this.bumpTargetEpoch(target.id);+ }+ }+ let revoked = 0;+ for (const generation of generations) revoked += this.revokeGeneration(generation);+ return revoked;+ }++ revokeSession(sessionId: string): void {+ const normalizedSessionId = sessionId.trim();+ if (!normalizedSessionId) return;+ this.sessionEpochs.set(+ normalizedSessionId,+ (this.sessionEpochs.get(normalizedSessionId) ?? 0) + 1,+ );+ const generations = new Set<number>();+ for (const grant of this.grants.values()) {+ if (grant.sessionId === normalizedSessionId) generations.add(grant.generation);+ }+ for (const generation of generations) this.revokeGeneration(generation);+ }++ clear(): void {+ this.lifecycleEpoch += 1;+ const revoked = [...this.grants.values()];+ for (const grant of revoked) this.bumpTargetEpoch(grant.target.id);+ this.grants.clear();+ this.notifyRevoked(revoked);+ }++ private async performAccessRequest(+ sessionId: string,+ target: IOSSimulatorRendererWebContents,+ ): Promise<boolean> {+ const lifecycleEpoch = this.lifecycleEpoch;+ const targetEpoch = this.targetEpochs.get(target.id) ?? 0;+ const sessionEpoch = this.sessionEpochs.get(sessionId) ?? 0;+ const initialTargets = this.resolveTargets(target)?.targets;+ if (!initialTargets || initialTargets.get(target.id) !== target) return false;++ let confirmed = false;+ try {+ confirmed = (await this.confirmation?.(target, sessionId)) === true;+ } catch {+ confirmed = false;+ }+ if (!confirmed) {+ const alreadyGranted = this.hasAccess(target, sessionId);+ if (!alreadyGranted) {+ this.accessCooldownUntil.set(+ target.id,+ Date.now() + IOSSimulatorRendererAccessRegistry.ACCESS_REQUEST_COOLDOWN_MS,+ );+ }+ return alreadyGranted;+ }+ if (+ target.isDestroyed() ||+ this.lifecycleEpoch !== lifecycleEpoch ||+ (this.targetEpochs.get(target.id) ?? 0) !== targetEpoch ||+ (this.sessionEpochs.get(sessionId) ?? 0) !== sessionEpoch+ ) {+ return this.hasAccess(target, sessionId);+ }+ const currentTargets = this.resolveTargets(target)?.targets;+ if (!currentTargets || currentTargets.get(target.id) !== target) {+ return this.hasAccess(target, sessionId);+ }+ this.grantTargets(sessionId, currentTargets.values());+ return this.hasAccess(target, sessionId);+ }++ private resolveTargets(preferredTarget?: IOSSimulatorRendererWebContents): {+ targets: Map<number, IOSSimulatorRendererWebContents>;+ focusTarget: IOSSimulatorRendererWebContents | null;+ } | null {+ const resolved = this.resolver?.(preferredTarget);+ if (!resolved) return null;+ const targets = new Map<number, IOSSimulatorRendererWebContents>();+ for (const target of [+ ...resolved.grantTargets,+ ...(resolved.focusTarget ? [resolved.focusTarget] : []),+ ]) {+ if (!Number.isSafeInteger(target.id) || target.id <= 0 || target.isDestroyed()) continue;+ targets.set(target.id, target);+ }+ if (targets.size === 0) return null;+ return { targets, focusTarget: resolved.focusTarget };+ }++ private grantTargets(+ sessionId: string,+ candidates: Iterable<IOSSimulatorRendererWebContents>,+ ): number {+ const targets = [...candidates];+ // Every authoritative grant is also an authorization-generation change.+ // Invalidate any manual confirmation that started before this decision,+ // including the first grant for a previously ungranted WebContents.+ for (const target of targets) this.bumpTargetEpoch(target.id);+ const previousGenerations = new Set<number>();+ for (const target of targets) {+ const existing = this.grants.get(target.id);+ if (existing) previousGenerations.add(existing.generation);+ }+ const revoked: IOSSimulatorRendererGrant[] = [];+ for (const generation of previousGenerations) {+ revoked.push(...this.removeGeneration(generation));+ }++ const generation = ++this.nextGeneration;+ for (const target of targets) {+ this.grants.set(target.id, { sessionId, generation, target });+ this.trackDestroyed(target);+ }+ this.notifyRevoked(+ revoked.filter((grant) => {+ const current = this.grants.get(grant.target.id);+ return current?.target !== grant.target || current.sessionId !== grant.sessionId;+ }),+ );+ return generation;+ }++ private trackDestroyed(target: IOSSimulatorRendererWebContents): void {+ if (this.trackedTargets.get(target.id) === target) return;+ this.trackedTargets.set(target.id, target);+ target.once('destroyed', () => {+ if (this.trackedTargets.get(target.id) !== target) return;+ this.trackedTargets.delete(target.id);+ this.bumpTargetEpoch(target.id);+ const grant = this.grants.get(target.id);+ if (grant?.target === target) this.revokeGrant(target.id, grant);+ });+ }++ private revokeGeneration(generation: number): number {+ const revoked = this.removeGeneration(generation);+ this.notifyRevoked(revoked);+ return revoked.length;+ }++ private removeGeneration(generation: number): IOSSimulatorRendererGrant[] {+ const revoked: IOSSimulatorRendererGrant[] = [];+ for (const [webContentsId, grant] of this.grants) {+ if (grant.generation !== generation) continue;+ this.grants.delete(webContentsId);+ this.bumpTargetEpoch(webContentsId);+ revoked.push(grant);+ }+ return revoked;+ }++ private revokeGrant(webContentsId: number, expected: IOSSimulatorRendererGrant): void {+ if (this.grants.get(webContentsId) !== expected) return;+ this.grants.delete(webContentsId);+ this.bumpTargetEpoch(webContentsId);+ this.notifyRevoked([expected]);+ }++ private notifyRevoked(grants: readonly IOSSimulatorRendererGrant[]): void {+ if (grants.length === 0 || !this.revocationObserver) return;+ try {+ this.revocationObserver(grants);+ } catch {+ // Authorization removal is authoritative even if resource cleanup fails.+ }+ }++ private bumpTargetEpoch(webContentsId: number): void {+ this.targetEpochs.set(webContentsId, (this.targetEpochs.get(webContentsId) ?? 0) + 1);+ }+}++const rendererAccessRegistry = new IOSSimulatorRendererAccessRegistry();++export function configureIOSSimulatorRendererTargets(+ resolver: IOSSimulatorRendererTargetResolver | null,+): void {+ rendererAccessRegistry.configureResolver(resolver);+}++export function configureIOSSimulatorRendererAccessConfirmation(+ confirmation: IOSSimulatorRendererAccessConfirmation | null,+): void {+ rendererAccessRegistry.configureConfirmation(confirmation);+}++export function configureIOSSimulatorRendererAccessRevocationObserver(+ observer: IOSSimulatorRendererAccessRevocationObserver | null,+): void {+ rendererAccessRegistry.configureRevocationObserver(observer);+}++export function focusIOSSimulatorRendererSession(+ sessionId: string,+ instanceId?: string,+ preferredTarget?: IOSSimulatorRendererWebContents,+): boolean {+ return rendererAccessRegistry.grantAndFocus(sessionId, instanceId, preferredTarget);+}++export function hasIOSSimulatorRendererSessionAccess(+ target: IOSSimulatorRendererWebContents,+ sessionId: string,+): boolean {+ return rendererAccessRegistry.hasAccess(target, sessionId);+}++export function requestIOSSimulatorRendererSessionAccess(+ target: IOSSimulatorRendererWebContents,+ sessionId: string,+): Promise<boolean> {+ return rendererAccessRegistry.requestAccess(sessionId, target);+}++export function pushIOSSimulatorRouteStatusToGrantedRenderers(+ status: IOSSimulatorPublicRouteStatus,+): number {+ return rendererAccessRegistry.pushRouteStatus(status);+}++export function inheritIOSSimulatorRendererSessionAccess(+ sourceTarget: IOSSimulatorRendererWebContents,+ target: IOSSimulatorRendererWebContents,+): boolean {+ return rendererAccessRegistry.inheritAccess(sourceTarget, target);+}++export function revokeIOSSimulatorRendererAccessForSessionChange(+ target: IOSSimulatorRendererWebContents,+ sessionId: string | null,+): number {+ return rendererAccessRegistry.revokeForSessionChange(target, sessionId);+}++export function revokeIOSSimulatorRendererSession(sessionId: string): void {+ rendererAccessRegistry.revokeSession(sessionId);+}++export function clearIOSSimulatorRendererAccess(): void {+ rendererAccessRegistry.clear();+}diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.tsindex 65a1ac904f..14d9ebc20b 100644--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts@@ -41,6 +41,7 @@ import {type IOSSimulatorGrantDecision,type IOSSimulatorInstance,type IOSSimulatorLocationRouteOptions,+ type IOSSimulatorLiveTouchPoint,type IOSSimulatorContentSize,type IOSSimulatorScreenMap,type IOSSimulatorMutationRoute,@@ -76,7 +77,6 @@ import type {IOSSimulatorPublicRouteStatus,IOSSimulatorSessionStatus,} from '../../shared/iosSimulatorIpc.js';-import { IOS_SIMULATOR_ROUTE_STATUS_CHANNEL } from '../../shared/iosSimulatorIpc.js';import type {GhostIOSSimulatorStatusProbeResult,GhostIOSSimulatorStatusSnapshot,@@ -91,6 +91,13 @@ import {import { resolveIOSSimulatorDesktopAdmissionPolicy } from './ios-simulator-admission.js';import { registerIOSSimulatorExitAbortHandler } from './ios-simulator-exit.js';import { compareIOSSimulatorPngBuffers, IOSSimulatorMediaCapture } from './ios-simulator-media.js';+import {+ clearIOSSimulatorRendererAccess,+ configureIOSSimulatorRendererAccessRevocationObserver,+ focusIOSSimulatorRendererSession,+ pushIOSSimulatorRouteStatusToGrantedRenderers,+ revokeIOSSimulatorRendererSession,+} from './ios-simulator-renderer-access.js';const logger = createLogger('mcp/cindy_ios_simulator');const BUILD_DIAGNOSTICS_TTL_MS = 30 * 60_000;@@ -143,7 +150,8 @@ export type IOSSimulatorMediaCaptureAdapter = Pick<| 'startRecording'| 'stopRecording'| 'discardInstance'->;+> &+ Partial<Pick<IOSSimulatorMediaCapture, 'dispose' | 'abortOperationsForExit'>>;export type IOSSimulatorHostResult =| { ok: true; data: unknown }@@ -194,6 +202,8 @@ export interface IOSSimulatorHost {getStatus(sessionId: string): Promise<IOSSimulatorSessionStatus>;/** Read-only, redacted plugin projection; never reconciles or renews an ownership lease. */getPluginStatus(sessionId: string): Promise<GhostIOSSimulatorStatusProbeResult>;+ /** Synchronously retire media/input owned by one exact revoked renderer grant. */+ revokeRendererViewer(sessionId: string, viewerWebContentsId: number): number;callTool(name: IOSSimulatorMcpToolName,args: Record<string, unknown>,@@ -257,34 +267,83 @@ function sessionError(let defaultRegistryFlush: (() => Promise<void>) | null = null;let defaultRegistryRelease: (() => void) | null = null;-function createDefaultActor(lifecycle: IOSSimulatorSimctlLifecycle): IOSSimulatorInstanceActor {- const registry = new IOSSimulatorOwnershipRegistryFile(- path.join(app.getPath('userData'), 'ios-simulator', 'ownership-registry.json'),- );- const ownsWriterLease = registry.acquireWriterSync();+export function createRegistryBackedIOSSimulatorActor(+ lifecycle: IOSSimulatorSimctlLifecycle,+ registry: IOSSimulatorOwnershipRegistryFile,+): {+ actor: IOSSimulatorInstanceActor;+ flush: () => Promise<void>;+ release: () => void;+} {+ let ownsWriterLease = false;+ let startupError: unknown = null;+ try {+ ownsWriterLease = registry.acquireWriterSync();+ } catch (error) {+ startupError = new IOSSimulatorInstanceError(+ 'DEVICE_BUSY',+ 'Cindy cannot safely manage iOS Simulator devices because the ownership registry is unavailable.',+ false,+ );+ logger.error('iOS Simulator ownership registry writer could not start', {+ error: error instanceof Error ? error.message : String(error),+ });+ }try {+ let initialInstances: IOSSimulatorInstance[] = [];+ if (ownsWriterLease && !startupError) {+ try {+ initialInstances = registry.loadSync();+ } catch (error) {+ // A corrupt/partially-written registry must fail closed for Simulator+ // ownership without preventing the rest of Desktop Main from starting.+ // Keep the writer lease and refuse every ownership mutation so another+ // process cannot claim the same devices or overwrite recovery evidence.+ startupError = new IOSSimulatorInstanceError(+ 'DEVICE_BUSY',+ 'Cindy cannot safely manage iOS Simulator devices because the ownership registry is invalid.',+ false,+ );+ logger.error('iOS Simulator ownership registry is unavailable', {+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }+ const assertMutationAllowed = (): void => {+ if (startupError) throw startupError;+ registry.assertWriter();+ };const store = new IOSSimulatorOwnershipStore({maxInstancesPerSession: MAX_INSTANCES_PER_SESSION,- initialInstances: ownsWriterLease ? registry.loadSync() : [],- assertMutationAllowed: () => registry.assertWriter(),+ initialInstances,+ assertMutationAllowed,// Persist in the same mutation transaction. If the writer lease is lost or// the atomic write fails, OwnershipStore rolls its in-memory mutation back.onChange: (instances) => registry.saveSync(instances),});- defaultRegistryFlush = async () => {- if (registry.isWriter) registry.saveSync(store.listAll());+ return {+ actor: new IOSSimulatorInstanceActor({ store, lifecycle, assertMutationAllowed }),+ flush: async () => {+ if (registry.isWriter && !startupError) registry.saveSync(store.listAll());+ },+ release: () => registry.releaseWriterSync(),};- defaultRegistryRelease = () => registry.releaseWriterSync();- return new IOSSimulatorInstanceActor({- store,- lifecycle,- });} catch (error) {registry.releaseWriterSync();throw error;}}+function createDefaultActor(lifecycle: IOSSimulatorSimctlLifecycle): IOSSimulatorInstanceActor {+ const registry = new IOSSimulatorOwnershipRegistryFile(+ path.join(app.getPath('userData'), 'ios-simulator', 'ownership-registry.json'),+ );+ const persisted = createRegistryBackedIOSSimulatorActor(lifecycle, registry);+ defaultRegistryFlush = persisted.flush;+ defaultRegistryRelease = persisted.release;+ return persisted.actor;+}+function createInMemoryActor(lifecycle: IOSSimulatorSimctlLifecycle): IOSSimulatorInstanceActor {return new IOSSimulatorInstanceActor({store: new IOSSimulatorOwnershipStore({@@ -675,6 +734,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Istring,{ sessionId: string; webContentsId: number | null; viewerToken: string | null }>();+ const activeViewerTouches = new Map<string, Map<string, IOSSimulatorLiveTouchPoint>>();const pushH264Frame =options.pushH264Frame ??((viewerWebContentsId: number, frame: IOSSimulatorLatestH264Frame) => {@@ -812,16 +872,11 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Iconst pushRouteStatus =options.pushRouteStatus ??((status: IOSSimulatorPublicRouteStatus) => {- for (const window of BrowserWindow.getAllWindows()) {- if (window.isDestroyed()) continue;- try {- window.webContents.send(IOS_SIMULATOR_ROUTE_STATUS_CHANNEL, status);- } catch (error) {- logger.debug('iOS Simulator route status push skipped', {- instanceId: status.instanceId,- error: error instanceof Error ? error.message : String(error),- });- }+ if (pushIOSSimulatorRouteStatusToGrantedRenderers(status) === 0) {+ logger.debug('iOS Simulator route status has no granted renderer', {+ sessionId: status.sessionId,+ instanceId: status.instanceId,+ });}});const hostDisposedResult = (): IOSSimulatorHostResult => ({@@ -900,6 +955,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): IpendingTeardowns: current.pendingTeardowns + 1,});blockedBuildInstances.add(instanceId);+ releaseViewerTouches(instanceId);}function finishInstanceTeardown(instanceId: string): void {const current = lifecycleBarrier(instanceId);@@ -1377,14 +1433,11 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Iconst requestViewerFocus =options.requestViewerFocus ??((sessionId: string, instanceId: string) => {- for (const window of BrowserWindow.getAllWindows()) {- if (!window.isDestroyed()) {- window.webContents.send('maker:ios-simulator:focus-request', {- sessionId,- instanceId,- userInitiated: false,- });- }+ if (!focusIOSSimulatorRendererSession(sessionId, instanceId)) {+ logger.debug('iOS Simulator focus request has no Main-owned renderer target', {+ sessionId,+ instanceId,+ });}});@@ -2635,8 +2688,34 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): IidleRecycleTimers.set(instance.instanceId, timer);}+ function releaseViewerTouches(instanceId: string): void {+ const touches = activeViewerTouches.get(instanceId);+ activeViewerTouches.delete(instanceId);+ if (!touches || touches.size === 0) return;+ const nativeInput = getDriverManager().get(instanceId)?.driverRouter?.continuousInput();+ if (!nativeInput) return;+ for (const [gestureId, point] of touches) {+ try {+ void nativeInput.endTouch(gestureId, point, true).catch((error) => {+ logger.warn('iOS Simulator viewer touch release failed', {+ instanceId,+ error: error instanceof Error ? error.message : String(error),+ });+ });+ } catch (error) {+ logger.warn('iOS Simulator viewer touch release failed', {+ instanceId,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }+ }+function stopViewerMedia(instance: IOSSimulatorInstance): IOSSimulatorFramePumpSnapshot | null {const running = getDriverManager().get(instance.instanceId);+ // Enqueue Native HID cancellation before clearing the stream/viewer claim.+ // Renderer cleanup IPC may already be denied after its capability is revoked.+ releaseViewerTouches(instance.instanceId);viewerSessions.delete(instance.instanceId);h264FramePump.clear(instance.instanceId);viewerEncodings.delete(instance.instanceId);@@ -2751,6 +2830,14 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): IviewerToken ??(previous?.webContentsId === viewerWebContentsId ? previous.viewerToken : null),};+ if (+ previous &&+ (previous.sessionId !== claim.sessionId ||+ previous.webContentsId !== claim.webContentsId ||+ previous.viewerToken !== claim.viewerToken)+ ) {+ releaseViewerTouches(instanceId);+ }viewerSessions.set(instanceId, claim);return {assertCurrent: () => {@@ -2790,6 +2877,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): IpreviousViewer.webContentsId !== nextViewerWebContentsId ||previousViewer.viewerToken !== nextViewerToken) {+ if (previousViewer) releaseViewerTouches(instance.instanceId);viewerSessions.set(instance.instanceId, {sessionId: instance.sessionId,webContentsId: nextViewerWebContentsId,@@ -2873,6 +2961,29 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I},getStatus: inspectForSession,getPluginStatus: inspectForPlugin,+ revokeRendererViewer(sessionId, viewerWebContentsId) {+ let revoked = 0;+ for (const [instanceId, viewer] of [...viewerSessions]) {+ if (viewer.sessionId !== sessionId || viewer.webContentsId !== viewerWebContentsId) continue;+ revoked += 1;+ try {+ stopViewerMedia(actor.getOwned(sessionId, instanceId));+ } catch {+ // Ownership can disappear before the renderer grant. Clear every+ // process-local viewer resource without trying to recover a route.+ releaseViewerTouches(instanceId);+ viewerSessions.delete(instanceId);+ cancelIdleRecycle(instanceId);+ framePump.clear(instanceId);+ h264FramePump.clear(instanceId);+ viewerEncodings.delete(instanceId);+ viewerPreferredEncodings.delete(instanceId);+ viewerFallbackReasons.delete(instanceId);+ clearViewportState(instanceId);+ }+ }+ return revoked;+ },async setViewerVisibility(sessionId,route,@@ -3105,6 +3216,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I}}if (snapshot && snapshot.generation !== instance.generation) {+ releaseViewerTouches(instance.instanceId);framePump.clear(instance.instanceId);h264FramePump.clear(instance.instanceId);viewerEncodings.delete(instance.instanceId);@@ -3216,10 +3328,30 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Iconst point = normalizedPointFromViewport(driverPoint, driver);if (touch.phase === 'begin') {await nativeInput.beginTouch(touch.gestureId, point, signal);+ try {+ assertCurrentViewer(resolved.sessionId, instance.instanceId, viewerWebContentsId);+ } catch (error) {+ await nativeInput.endTouch(touch.gestureId, point, true).catch(() => undefined);+ throw error;+ }+ const touches = activeViewerTouches.get(instance.instanceId) ?? new Map();+ touches.set(touch.gestureId, point);+ activeViewerTouches.set(instance.instanceId, touches);} else if (touch.phase === 'move') {await nativeInput.moveTouch(touch.gestureId, point, signal);+ try {+ assertCurrentViewer(resolved.sessionId, instance.instanceId, viewerWebContentsId);+ } catch (error) {+ await nativeInput.endTouch(touch.gestureId, point, true).catch(() => undefined);+ activeViewerTouches.get(instance.instanceId)?.delete(touch.gestureId);+ throw error;+ }+ activeViewerTouches.get(instance.instanceId)?.set(touch.gestureId, point);} else {await nativeInput.endTouch(touch.gestureId, point, touch.phase === 'cancel', signal);+ const touches = activeViewerTouches.get(instance.instanceId);+ touches?.delete(touch.gestureId);+ if (touches?.size === 0) activeViewerTouches.delete(instance.instanceId);}screenMaps.invalidate(instance.instanceId);},@@ -3390,6 +3522,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I},);completeInstanceActivation(instance, activationEpoch);+ releaseViewerTouches(instance.instanceId);screenMaps.clear(instance.instanceId);framePump.clear(instance.instanceId);h264FramePump.clear(instance.instanceId);@@ -3398,8 +3531,8 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): IviewerFallbackReasons.delete(instance.instanceId);viewerSessions.delete(instance.instanceId);clearViewportState(instance.instanceId);- publishRouteStatusForInstance(instance, getDriverManager().get(instance.instanceId));requestViewerFocus(sessionId, instance.instanceId);+ publishRouteStatusForInstance(instance, getDriverManager().get(instance.instanceId));return {ok: true,data: instanceData(instance),@@ -4917,6 +5050,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Iif (context?.origin === 'agent') {agentControlLeases.set(instance.instanceId, sessionId);}+ releaseViewerTouches(instance.instanceId);screenMaps.clear(instance.instanceId);framePump.clear(instance.instanceId);h264FramePump.clear(instance.instanceId);@@ -4947,12 +5081,20 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I},abortOperationsForExit() {for (const build of activeBuilds.values()) build.controller.abort();+ mediaCapture.abortOperationsForExit?.();},dispose() {if (disposePromise) return disposePromise;disposePromise = (async () => {const builds = [...activeBuilds.values()];for (const build of builds) build.controller.abort();+ // Close the recording start gate immediately, before waiting for a+ // potentially slow xcodebuild process to acknowledge cancellation.+ const mediaDispose = mediaCapture.dispose?.().catch((error) => {+ logger.warn('iOS Simulator dispose could not close media capture', {+ error: error instanceof Error ? error.message : String(error),+ });+ });await Promise.all(builds.map((build) => build.settled));clearVisualBaselines();await Promise.all(@@ -4964,14 +5106,18 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): Ifor (const timer of idleRecycleTimers.values()) clearTimeout(timer);idleRecycleTimers.clear();const instances = actor.listAll();+ await mediaDispose;await Promise.all(instances.map(async (instance) => {- await mediaCapture.discardInstance(instance.instanceId).catch((error) => {- logger.warn('iOS Simulator dispose could not discard recording', {- instanceId: instance.instanceId,- error: error instanceof Error ? error.message : String(error),+ releaseViewerTouches(instance.instanceId);+ if (!mediaCapture.dispose) {+ await mediaCapture.discardInstance(instance.instanceId).catch((error) => {+ logger.warn('iOS Simulator dispose could not discard recording', {+ instanceId: instance.instanceId,+ error: error instanceof Error ? error.message : String(error),+ });});- });+ }if (driverManager) {await driverManager.stop(instance.instanceId).catch((error) => {logger.warn('iOS Simulator dispose could not stop WDA', {@@ -4992,6 +5138,8 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): InativeStreamProfiles.delete(instance.instanceId);}),);+ activeViewerTouches.clear();+ viewerSessions.clear();routeStatusCache.clear();pluginEnvironmentCache = null;})();@@ -5005,6 +5153,11 @@ const defaultIOSSimulatorHost = createIOSSimulatorHost({lifecycle: defaultIOSSimulatorLifecycle,actor: createDefaultActor(defaultIOSSimulatorLifecycle),});+configureIOSSimulatorRendererAccessRevocationObserver((grants) => {+ for (const grant of grants) {+ defaultIOSSimulatorHost.revokeRendererViewer(grant.sessionId, grant.target.id);+ }+});const releaseIOSSimulatorExitAbortHandler = registerIOSSimulatorExitAbortHandler(() => {defaultIOSSimulatorHost.abortOperationsForExit();});@@ -5083,15 +5236,18 @@ export function reconcileIOSSimulatorOwnership(): Promise<void> {export async function disposeIOSSimulatorHost(): Promise<void> {try {+ clearIOSSimulatorRendererAccess();await defaultIOSSimulatorHost.dispose();await defaultRegistryFlush?.();} finally {+ configureIOSSimulatorRendererAccessRevocationObserver(null);releaseIOSSimulatorExitAbortHandler();defaultRegistryRelease?.();}}export function cancelIOSSimulatorSessionOperations(sessionId: string): Promise<void> {+ revokeIOSSimulatorRendererSession(sessionId);return defaultIOSSimulatorHost.cancelSessionOperations(sessionId);}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex d2e2236e8c..9f3ccfbb32 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -133,6 +133,8 @@ import type {DesktopLoginActionResult,} from '../shared/authIpc';import type {+ IOSSimulatorAccessRequest,+ IOSSimulatorAccessRequestResult,IOSSimulatorSessionStatus,IOSSimulatorAgentControlRequest,IOSSimulatorFocusRequest,@@ -6252,6 +6254,10 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('maker:android:prepare-adb'),},iosSimulator: {+ requestAccess: (+ request: IOSSimulatorAccessRequest,+ ): Promise<IOSSimulatorAccessRequestResult> =>+ ipcRenderer.invoke('maker:ios-simulator:request-access', request),status: (request: IOSSimulatorStatusRequest): Promise<IOSSimulatorSessionStatus> =>ipcRenderer.invoke('maker:ios-simulator:status', request),call: (request: IOSSimulatorToolRequest): Promise<IOSSimulatorToolResponse> =>diff --git a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsxindex 3f0ca3ec4c..f55d1eec45 100644--- a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx@@ -23,6 +23,7 @@ import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from 'rimport { useTranslation } from 'react-i18next';import { createLogger } from '@/lib/logger';+import { isSecondaryWindow } from '@/lib/secondaryWindow';import { useAppShortcut } from '@/hooks/useAppShortcut';import { useMacFullscreen } from '@/hooks/useMacFullscreen';import { RightSidebarDetach } from '@/components/layout/RightSidebarDetach';@@ -163,7 +164,11 @@ export function RightSidebarShell({const { t } = useTranslation();const installedGhosts = useInstalledGhosts();const iosSimulatorPluginAvailable = useMemo(- () => isIOSSimulatorPluginAvailable(installedGhosts),+ // Session secondary windows do not own the Main/RSB capability family and+ // intentionally skip the Host focus bridge. Hide (but preserve) persisted+ // Simulator tabs there instead of exposing an authorization action that+ // can never succeed.+ () => !isSecondaryWindow() && isIOSSimulatorPluginAvailable(installedGhosts),[installedGhosts],);diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsxindex cab3e924fa..6c6442476b 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx@@ -28,6 +28,7 @@ import {import { useTranslation } from 'react-i18next';import { cn } from '@/lib/utils';+import { extractIpcError } from '@/utils/ipcError';import type {IOSSimulatorFramePumpSnapshot,IOSSimulatorMutationState,@@ -283,6 +284,8 @@ export function IOSSimulatorTabBody({{},);const [transportError, setTransportError] = useState(false);+ const [accessRequired, setAccessRequired] = useState(false);+ const [requestingAccess, setRequestingAccess] = useState(false);const [actionError, setActionError] = useState<string | null>(null);const [refreshing, setRefreshing] = useState(false);const [operation, setOperation] = useState<Operation>(null);@@ -388,16 +391,45 @@ export function IOSSimulatorTabBody({const next = await window.electronAPI.maker.iosSimulator.status({sessionId: ctx.sessionId,});- if (requestVersion === requestVersionRef.current) setStatus(next);+ if (requestVersion === requestVersionRef.current) {+ setAccessRequired(false);+ setStatus(next);+ }return next;- } catch {- if (requestVersion === requestVersionRef.current) setTransportError(true);+ } catch (error) {+ if (requestVersion === requestVersionRef.current) {+ if (extractIpcError(error)?.code === 'PERMISSION_DENIED') {+ setAccessRequired(true);+ setStatus(null);+ setRouteStatuses({});+ } else {+ setTransportError(true);+ }+ }return null;} finally {if (requestVersion === requestVersionRef.current) setRefreshing(false);}}, [ctx.sessionId]);+ const requestAccess = useCallback(async () => {+ setRequestingAccess(true);+ setTransportError(false);+ try {+ const result = await window.electronAPI.maker.iosSimulator.requestAccess({+ sessionId: ctx.sessionId,+ });+ if (result.granted) {+ setAccessRequired(false);+ await refresh();+ }+ } catch {+ setTransportError(true);+ } finally {+ setRequestingAccess(false);+ }+ }, [ctx.sessionId, refresh]);+useEffect(() => {void refresh();return () => {@@ -426,6 +458,18 @@ export function IOSSimulatorTabBody({});}, [ctx.sessionId]);+ useEffect(() => {+ const subscribe = window.electronAPI.maker.iosSimulator.onFocusRequest;+ if (typeof subscribe !== 'function') return undefined;+ return subscribe((request) => {+ if (request.sessionId !== ctx.sessionId) return;+ // Main sends this only after minting a Host-owned renderer grant. A+ // restored tab can therefore leave its access-required state without a+ // remount when an Agent/Host flow opens the same Simulator session.+ void refresh();+ });+ }, [ctx.sessionId, refresh]);+const environment = status?.ok ? status.environment : null;const instances = status?.ok ? status.instances : [];const resource = status?.ok ? (status.resource ?? null) : null;@@ -1506,7 +1550,7 @@ export function IOSSimulatorTabBody({return (<divclassName="h-full overflow-y-auto bg-[var(--surface)] text-[var(--text-primary)]"- aria-busy={busy || refreshing}+ aria-busy={busy || refreshing || requestingAccess}><div className="mx-auto flex w-full max-w-3xl flex-col gap-4 p-4"><header className="flex items-start justify-between gap-3">@@ -1527,10 +1571,41 @@ export function IOSSimulatorTabBody({/></header>- {!status && !transportError && (+ {!status && !transportError && !accessRequired && (<StatusCard icon={RefreshCw} title={t('rightSidebar.iosSimulator.checking')} />)}+ {accessRequired && (+ <div className="flex gap-2.5 rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-3">+ <ShieldCheck+ size={15}+ className="mt-0.5 shrink-0 text-[var(--text-secondary)]"+ aria-hidden="true"+ />+ <div className="min-w-0">+ <div className="text-[12px] font-medium">+ {t('rightSidebar.iosSimulator.accessRequiredTitle')}+ </div>+ <div className="mt-1 text-[11px] leading-relaxed text-[var(--text-secondary)]">+ {t('rightSidebar.iosSimulator.accessRequiredDescription')}+ </div>+ <div className="mt-3">+ <ActionButton+ onClick={() => void requestAccess()}+ disabled={requestingAccess}+ label={t(+ requestingAccess+ ? 'rightSidebar.iosSimulator.requestingAccess'+ : 'rightSidebar.iosSimulator.allowTaskAccess',+ )}+ icon={requestingAccess ? Loader2 : ShieldCheck}+ spinning={requestingAccess}+ />+ </div>+ </div>+ </div>+ )}+{transportError && (<StatusCardicon={AlertTriangle}@@ -2199,12 +2274,14 @@ function ActionButton({icon: Icon,disabled,describedBy,+ spinning,onClick,}: {label: string;icon: typeof AlertTriangle;disabled?: boolean;describedBy?: string;+ spinning?: boolean;onClick(): void;}) {return (@@ -2215,7 +2292,7 @@ function ActionButton({aria-describedby={describedBy}className="inline-flex h-8 shrink-0 select-none items-center gap-1.5 rounded-full border border-[var(--border-default)] bg-[var(--surface-elevated)] px-3 text-[11px] text-[var(--text-primary)] transition-colors hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:cursor-default disabled:opacity-50">- <Icon size={12} aria-hidden="true" />+ <Icon size={12} className={spinning ? 'animate-spin' : undefined} aria-hidden="true" />{label}</button>);diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsxindex ec0ca700a4..c3e431e724 100644--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/__tests__/IOSSimulatorTabBody.test.tsx@@ -4,6 +4,9 @@ import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-libraimport { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type {+ IOSSimulatorAccessRequest,+ IOSSimulatorAccessRequestResult,+ IOSSimulatorFocusRequest,IOSSimulatorH264FramePush,IOSSimulatorLiveTouchRequest,IOSSimulatorPublicInstance,@@ -144,6 +147,11 @@ function installFakeH264DecoderRuntime(): void {function installStatus(statusValue: IOSSimulatorSessionStatus) {let currentStatusValue = statusValue;const status = vi.fn(async () => currentStatusValue);+ const requestAccess = vi.fn(+ async (_request: IOSSimulatorAccessRequest): Promise<IOSSimulatorAccessRequestResult> => ({+ granted: true,+ }),+ );const call = vi.fn(async (): Promise<IOSSimulatorToolResponse> => ({ok: true as const,data: {},@@ -161,6 +169,7 @@ function installStatus(statusValue: IOSSimulatorSessionStatus) {const setStreamProfile = vi.fn(async () => ({ ok: true as const, data: {} }));let h264FrameListener: ((payload: IOSSimulatorH264FramePush) => void) | null = null;let routeStatusListener: ((payload: IOSSimulatorRouteStatusPush) => void) | null = null;+ let focusRequestListener: ((payload: IOSSimulatorFocusRequest) => void) | null = null;const onH264Frame = vi.fn((callback: (payload: IOSSimulatorH264FramePush) => void) => {h264FrameListener = callback;return () => {@@ -173,6 +182,12 @@ function installStatus(statusValue: IOSSimulatorSessionStatus) {if (routeStatusListener === callback) routeStatusListener = null;};});+ const onFocusRequest = vi.fn((callback: (payload: IOSSimulatorFocusRequest) => void) => {+ focusRequestListener = callback;+ return () => {+ if (focusRequestListener === callback) focusRequestListener = null;+ };+ });const liveTouch = vi.fn(async (request: IOSSimulatorLiveTouchRequest): Promise<IOSSimulatorToolResponse> => {void request;@@ -191,6 +206,7 @@ function installStatus(statusValue: IOSSimulatorSessionStatus) {electronAPI: {maker: {iosSimulator: {+ requestAccess: typeof requestAccess;status: typeof status;call: typeof call;setAgentControl: typeof setAgentControl;@@ -200,6 +216,7 @@ function installStatus(statusValue: IOSSimulatorSessionStatus) {liveTouch: typeof liveTouch;onH264Frame: typeof onH264Frame;onRouteStatus: typeof onRouteStatus;+ onFocusRequest: typeof onFocusRequest;};};};@@ -207,6 +224,7 @@ function installStatus(statusValue: IOSSimulatorSessionStatus) {).electronAPI = {maker: {iosSimulator: {+ requestAccess,status,call,setAgentControl,@@ -216,10 +234,12 @@ function installStatus(statusValue: IOSSimulatorSessionStatus) {liveTouch,onH264Frame,onRouteStatus,+ onFocusRequest,},},};return {+ requestAccess,status,call,setAgentControl,@@ -229,6 +249,7 @@ function installStatus(statusValue: IOSSimulatorSessionStatus) {liveTouch,onH264Frame,onRouteStatus,+ onFocusRequest,setStatusValue(value: IOSSimulatorSessionStatus) {currentStatusValue = value;},@@ -238,6 +259,9 @@ function installStatus(statusValue: IOSSimulatorSessionStatus) {emitRouteStatus(payload: IOSSimulatorRouteStatusPush) {routeStatusListener?.(payload);},+ emitFocusRequest(payload: IOSSimulatorFocusRequest) {+ focusRequestListener?.(payload);+ },};}@@ -279,6 +303,79 @@ afterEach(() => {});describe('IOSSimulatorTabBody', () => {+ it('requires a user gesture before requesting native access for a restored panel', async () => {+ const api = installStatus(readyStatus());+ api.status.mockRejectedValueOnce(+ new Error(+ 'Error invoking remote method: Error: [PERMISSION_DENIED] iOS Simulator access is limited to the current task',+ ),+ );++ render(<IOSSimulatorTabBody state={{ instanceId: null }} ctx={ctx} />);++ await waitFor(() => {+ expect(screen.getByText('rightSidebar.iosSimulator.accessRequiredTitle')).toBeTruthy();+ });+ expect(api.requestAccess).not.toHaveBeenCalled();++ fireEvent.click(+ screen.getByRole('button', { name: 'rightSidebar.iosSimulator.allowTaskAccess' }),+ );++ await waitFor(() => {+ expect(api.requestAccess).toHaveBeenCalledWith({ sessionId: 'session-a' });+ expect(api.status).toHaveBeenCalledTimes(2);+ });+ expect(screen.queryByText('rightSidebar.iosSimulator.accessRequiredTitle')).toBeNull();+ });++ it('keeps the access action visible when native confirmation is cancelled', async () => {+ const api = installStatus(readyStatus());+ api.status.mockRejectedValueOnce(+ new Error(+ 'Error invoking remote method: Error: [PERMISSION_DENIED] iOS Simulator access is limited to the current task',+ ),+ );+ api.requestAccess.mockResolvedValueOnce({ granted: false });++ render(<IOSSimulatorTabBody state={{ instanceId: null }} ctx={ctx} />);++ const button = await screen.findByRole('button', {+ name: 'rightSidebar.iosSimulator.allowTaskAccess',+ });+ fireEvent.click(button);++ await waitFor(() => expect(api.requestAccess).toHaveBeenCalledOnce());+ expect(+ screen.getByRole('button', { name: 'rightSidebar.iosSimulator.allowTaskAccess' }),+ ).toBeTruthy();+ expect(api.status).toHaveBeenCalledOnce();+ });++ it('refreshes a restored access-required tab after an authoritative Host focus grant', async () => {+ const api = installStatus(readyStatus());+ api.status.mockRejectedValueOnce(+ new Error(+ 'Error invoking remote method: Error: [PERMISSION_DENIED] iOS Simulator access is limited to the current task',+ ),+ );++ render(<IOSSimulatorTabBody state={{ instanceId: null }} ctx={ctx} />);++ await screen.findByText('rightSidebar.iosSimulator.accessRequiredTitle');+ act(() => {+ api.emitFocusRequest({+ sessionId: 'session-a',+ instanceId: 'instance-a',+ userInitiated: false,+ });+ });++ await waitFor(() => expect(api.status).toHaveBeenCalledTimes(2));+ expect(screen.queryByText('rightSidebar.iosSimulator.accessRequiredTitle')).toBeNull();+ expect(screen.getByText('iPhone 17 Pro')).toBeTruthy();+ });+it('renders exact device identity from the main-owned status report', async () => {const api = installStatus({ok: true,diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex ee09ad64b1..f8f9a44cb5 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -4446,6 +4446,16 @@"description": "Inspect the Xcode environment and simulators available to this local session.","refresh": "Refresh","checking": "Checking",+ "accessRequiredTitle": "Authorize This Session",+ "accessRequiredDescription": "This panel is not authorized to access the simulator for this session. Confirm access in the system dialog.",+ "allowTaskAccess": "Allow Session Access",+ "requestingAccess": "Requesting Access…",+ "accessDialogTitle": "Allow iOS Simulator Control?",+ "accessDialogMessage": "Allow this Cindy window to view and control the iOS Simulator for “{{task}}”?",+ "accessDialogDetail": "This permission applies only to this session and is revoked when you switch sessions.",+ "accessDialogAllow": "Allow Simulator Control",+ "accessDialogCancel": "Cancel",+ "accessDialogUntitledTask": "Untitled Session","readyTitle": "Simulator environment ready","unavailableTitle": "Simulator unavailable","connectionError": "Cindy could not inspect the local simulator environment. Try again.",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex a01b328ab6..622babb391 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -4444,6 +4444,16 @@"description": "このローカルセッションで使用できる Xcode 環境とシミュレータを確認します。","refresh": "更新","checking": "確認中",+ "accessRequiredTitle": "このセッションを承認",+ "accessRequiredDescription": "このパネルには、このセッションのシミュレータへアクセスする権限がありません。システムダイアログで確認してください。",+ "allowTaskAccess": "セッションのアクセスを許可",+ "requestingAccess": "アクセスをリクエスト中…",+ "accessDialogTitle": "iOS シミュレータの操作を許可しますか?",+ "accessDialogMessage": "Cindy のこのウインドウに「{{task}}」の iOS シミュレータの表示と操作を許可しますか?",+ "accessDialogDetail": "この権限はこのセッションにのみ適用され、別のセッションへ切り替えると取り消されます。",+ "accessDialogAllow": "シミュレータの操作を許可",+ "accessDialogCancel": "キャンセル",+ "accessDialogUntitledTask": "名称未設定のセッション","readyTitle": "シミュレータ環境の準備が完了しました","unavailableTitle": "シミュレータを使用できません","connectionError": "ローカルのシミュレータ環境を確認できませんでした。もう一度お試しください。",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 331e0d6562..9f22266ce9 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -4444,6 +4444,16 @@"description": "이 로컬 세션에서 사용할 수 있는 Xcode 환경과 시뮬레이터를 확인합니다.","refresh": "새로 고침","checking": "확인 중",+ "accessRequiredTitle": "이 세션 승인",+ "accessRequiredDescription": "이 패널에는 현재 세션의 시뮬레이터 접근 권한이 없습니다. 시스템 대화상자에서 확인하세요.",+ "allowTaskAccess": "세션 접근 허용",+ "requestingAccess": "접근 요청 중…",+ "accessDialogTitle": "iOS 시뮬레이터 제어를 허용할까요?",+ "accessDialogMessage": "이 Cindy 창에서 ‘{{task}}’의 iOS 시뮬레이터를 보고 제어하도록 허용할까요?",+ "accessDialogDetail": "이 권한은 현재 세션에만 적용되며 다른 세션으로 전환하면 해제됩니다.",+ "accessDialogAllow": "시뮬레이터 제어 허용",+ "accessDialogCancel": "취소",+ "accessDialogUntitledTask": "이름 없는 세션","readyTitle": "시뮬레이터 환경 준비 완료","unavailableTitle": "시뮬레이터를 사용할 수 없음","connectionError": "로컬 시뮬레이터 환경을 확인하지 못했습니다. 다시 시도해 주세요.",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex afca190d99..e6b223de44 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -4444,6 +4444,16 @@"description": "查看当前本地任务可用的 Xcode 环境和模拟器设备。","refresh": "刷新","checking": "正在检查",+ "accessRequiredTitle": "授权当前任务",+ "accessRequiredDescription": "此面板尚未获得当前任务的模拟器访问权限。请先在系统弹窗中确认。",+ "allowTaskAccess": "允许当前任务访问",+ "requestingAccess": "正在请求访问…",+ "accessDialogTitle": "允许控制 iOS 模拟器?",+ "accessDialogMessage": "允许当前 Cindy 窗口为任务“{{task}}”查看和控制 iOS 模拟器吗?",+ "accessDialogDetail": "此权限仅对该任务生效;切换任务后会自动撤销。",+ "accessDialogAllow": "允许模拟器控制",+ "accessDialogCancel": "取消",+ "accessDialogUntitledTask": "未命名任务","readyTitle": "模拟器环境已就绪","unavailableTitle": "模拟器不可用","connectionError": "Cindy 无法检查本机模拟器环境,请重试。",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 04626c0f02..e324b19615 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -27,6 +27,9 @@ type DesktopLoginAction = import('../shared/authIpc').DesktopLoginAction;type DesktopLoginActionResult = import('../shared/authIpc').DesktopLoginActionResult;type UtilityTextFailure = import('../shared/utilityTextResult').UtilityTextFailure;type IOSSimulatorSessionStatus = import('../shared/iosSimulatorIpc').IOSSimulatorSessionStatus;+type IOSSimulatorAccessRequest = import('../shared/iosSimulatorIpc').IOSSimulatorAccessRequest;+type IOSSimulatorAccessRequestResult =+ import('../shared/iosSimulatorIpc').IOSSimulatorAccessRequestResult;type IOSSimulatorStatusRequest = import('../shared/iosSimulatorIpc').IOSSimulatorStatusRequest;type IOSSimulatorToolRequest = import('../shared/iosSimulatorIpc').IOSSimulatorToolRequest;type IOSSimulatorToolResponse = import('../shared/iosSimulatorIpc').IOSSimulatorToolResponse;@@ -5778,6 +5781,9 @@ interface ElectronAPI {prepareAdb: () => Promise<AndroidAdbPreparationState>;};iosSimulator: {+ requestAccess: (+ request: IOSSimulatorAccessRequest,+ ) => Promise<IOSSimulatorAccessRequestResult>;status: (request: IOSSimulatorStatusRequest) => Promise<IOSSimulatorSessionStatus>;call: (request: IOSSimulatorToolRequest) => Promise<IOSSimulatorToolResponse>;setAgentControl: (diff --git a/apps/desktop/src/shared/iosSimulatorIpc.ts b/apps/desktop/src/shared/iosSimulatorIpc.tsindex 023eecc4e7..6b5fce74c4 100644--- a/apps/desktop/src/shared/iosSimulatorIpc.ts+++ b/apps/desktop/src/shared/iosSimulatorIpc.ts@@ -117,6 +117,14 @@ export interface IOSSimulatorStatusRequest {sessionId: string;}+export interface IOSSimulatorAccessRequest {+ sessionId: string;+}++export interface IOSSimulatorAccessRequestResult {+ granted: boolean;+}+/*** Renderer-owned simulator actions. Agent-only build, install, URL, push, media,* and diagnostic tools must stay behind the MCP approval/control boundary.diff --git a/packages/ios-simulator-runtime/src/command-runner.test.ts b/packages/ios-simulator-runtime/src/command-runner.test.tsindex e2148a9c99..427cc14dee 100644--- a/packages/ios-simulator-runtime/src/command-runner.test.ts+++ b/packages/ios-simulator-runtime/src/command-runner.test.ts@@ -40,6 +40,63 @@ describe("createNodeIOSSimulatorCommandRunner", () => {).toBeLessThanOrEqual(128);});+ it.runIf(process.platform !== "win32")(+ "escalates a timed-out process group and settles even when SIGTERM is ignored",+ async () => {+ const startedAt = Date.now();+ const result = await createNodeIOSSimulatorCommandRunner().run(+ process.execPath,+ [+ "-e",+ [+ "process.on('SIGTERM', () => undefined);",+ "setInterval(() => undefined, 1000);",+ ].join("\n"),+ ],+ { timeoutMs: 100 },+ );++ expect(result.exitCode).toBeNull();+ expect(Date.now() - startedAt).toBeLessThan(3_000);+ },+ );++ it.runIf(process.platform !== "win32")(+ "keeps the escalation alive when the leader exits before its descendant",+ async () => {+ const root = await mkdtemp(+ path.join(os.tmpdir(), "cindy-command-timeout-descendant-"),+ );+ tempRoots.push(root);+ const markerPath = path.join(root, "late-descendant.txt");+ const result = await createNodeIOSSimulatorCommandRunner().run(+ process.execPath,+ [+ "-e",+ [+ "const { spawn } = require('node:child_process');",+ `spawn(process.execPath, ['-e', ${JSON.stringify(+ [+ "process.on('SIGTERM', () => undefined);",+ `setTimeout(() => require('node:fs').writeFileSync(${JSON.stringify(markerPath)}, 'late'), 1500);`,+ "setInterval(() => undefined, 1000);",+ ].join("\n"),+ )}], { stdio: 'ignore' });`,+ "process.on('SIGTERM', () => process.exit(0));",+ "setInterval(() => undefined, 1000);",+ ].join("\n"),+ ],+ { timeoutMs: 100 },+ );++ expect(result.exitCode).toBeNull();+ await new Promise((resolve) => setTimeout(resolve, 600));+ await expect(readFile(markerPath, "utf8")).rejects.toMatchObject({+ code: "ENOENT",+ });+ },+ );+it.runIf(process.platform !== "win32")("kills the detached process group when a build is aborted",async () => {diff --git a/packages/ios-simulator-runtime/src/command-runner.ts b/packages/ios-simulator-runtime/src/command-runner.tsindex 4e7f98bfa1..be80df0e47 100644--- a/packages/ios-simulator-runtime/src/command-runner.ts+++ b/packages/ios-simulator-runtime/src/command-runner.ts@@ -7,6 +7,13 @@ import type {const DEFAULT_TIMEOUT_MS = 15_000;const DEFAULT_MAX_BUFFER_BYTES = 16 * 1024 * 1024;+const TERMINATION_GRACE_MS = 1_000;++function unrefTimer(timer: ReturnType<typeof setTimeout>): void {+ if (typeof timer === "object" && "unref" in timer) {+ (timer as NodeJS.Timeout).unref();+ }+}/** Node adapter for the runtime command seam. Commands are always argv-based. */export function createNodeIOSSimulatorCommandRunner(): IOSSimulatorCommandRunner {@@ -34,26 +41,21 @@ export function createNodeIOSSimulatorCommandRunner(): IOSSimulatorCommandRunnerlet settled = false;let timedOut = false;let aborted = false;- const onAbort = () => {- if (settled || aborted) return;- aborted = true;- killProcessTree(child, "SIGKILL");- };- options.signal?.addEventListener("abort", onAbort, { once: true });- if (options.signal?.aborted) onAbort();- let timer: ReturnType<typeof setTimeout> | null = setTimeout(() => {- timedOut = true;- killProcessTree(child);- }, timeoutMs);- if (timer && typeof timer === "object" && "unref" in timer) {- (timer as NodeJS.Timeout).unref();- }-+ let timer: ReturnType<typeof setTimeout> | null = null;+ let forceKillTimer: ReturnType<typeof setTimeout> | null = null;const finish = (exitCode: number | null) => {if (settled) return;settled = true;if (timer) clearTimeout(timer);+ if (forceKillTimer) clearTimeout(forceKillTimer);options.signal?.removeEventListener("abort", onAbort);+ if (timedOut || aborted) {+ child.stdout?.removeAllListeners("data");+ child.stderr?.removeAllListeners("data");+ child.stdout?.destroy();+ child.stderr?.destroy();+ child.unref();+ }const stdout = chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.bytes);@@ -67,6 +69,29 @@ export function createNodeIOSSimulatorCommandRunner(): IOSSimulatorCommandRunneroutputTruncated,});};+ const onAbort = () => {+ if (settled || aborted) return;+ aborted = true;+ killProcessTree(child, "SIGKILL");+ finish(null);+ };+ timer = setTimeout(() => {+ if (settled) return;+ timedOut = true;+ killProcessTree(child);+ forceKillTimer = setTimeout(() => {+ if (settled) return;+ killProcessTree(child, "SIGKILL");+ // Do not depend on a hostile or wedged child emitting `close`.+ finish(null);+ }, TERMINATION_GRACE_MS);+ // Keep the escalation watchdog referenced. The leader and its pipes+ // may close after SIGTERM while a detached descendant remains alive;+ // allowing this timer to unref could exit Main before SIGKILL.+ }, timeoutMs);+ unrefTimer(timer);+ options.signal?.addEventListener("abort", onAbort, { once: true });+ if (options.signal?.aborted) onAbort();const append = (stream: "stdout" | "stderr", chunk: Buffer) => {if (settled || chunk.byteLength === 0) return;if (maxBufferBytes <= 0) {@@ -91,15 +116,34 @@ export function createNodeIOSSimulatorCommandRunner(): IOSSimulatorCommandRunner};child.stdout?.on("data", (chunk: Buffer) => append("stdout", chunk));child.stderr?.on("data", (chunk: Buffer) => append("stderr", chunk));- child.once("error", () => finish(null));- child.once("close", (code) =>- finish(timedOut || aborted ? null : code),- );+ child.once("error", () => {+ // Once termination starts, a child error must not cancel the process-+ // group escalation watchdog. It remains authoritative until the+ // group is gone or the bounded SIGKILL fallback fires.+ if (timedOut || aborted) return;+ finish(null);+ });+ child.once("close", (code) => {+ // The leader may exit on SIGTERM while a same-group descendant stays+ // alive. Keep the escalation watchdog in that case.+ if (timedOut && isProcessGroupAlive(child)) return;+ finish(timedOut || aborted ? null : code);+ });});},};}+function isProcessGroupAlive(child: ReturnType<typeof spawn>): boolean {+ if (!child.pid || process.platform === "win32") return false;+ try {+ process.kill(-child.pid, 0);+ return true;+ } catch (error) {+ return (error as NodeJS.ErrnoException | null)?.code === "EPERM";+ }+}+function killProcessTree(child: ReturnType<typeof spawn>,signal: NodeJS.Signals = "SIGTERM",diff --git a/packages/ios-simulator-runtime/src/instance-actor.test.ts b/packages/ios-simulator-runtime/src/instance-actor.test.tsindex 38437a502d..b8c12484a2 100644--- a/packages/ios-simulator-runtime/src/instance-actor.test.ts+++ b/packages/ios-simulator-runtime/src/instance-actor.test.ts@@ -435,6 +435,45 @@ describe("IOSSimulatorInstanceActor", () => {});});+ it("deletes a newly created device when the ownership write fails after preflight", async () => {+ const createdUdid = "2A9D41E0-E031-4AD0-A8B5-847480802E8E";+ let mutationChecks = 0;+ const assertMutationAllowed = vi.fn(() => {+ mutationChecks += 1;+ if (mutationChecks > 1) throw new Error("writer lease lost");+ });+ const lifecycle: IOSSimulatorSimctlLifecycle = {+ findExact: vi.fn(),+ bootExact: vi.fn(),+ shutdownExact: vi.fn(),+ createExact: vi.fn(async () => ({+ udid: createdUdid,+ name: "Cindy iPhone",+ runtimeIdentifier: DEVICE.runtimeIdentifier,+ deviceTypeIdentifier: DEVICE.deviceTypeIdentifier!,+ })),+ deleteExact: vi.fn(async () => undefined),+ };+ const actor = new IOSSimulatorInstanceActor({+ lifecycle,+ assertMutationAllowed,+ store: new IOSSimulatorOwnershipStore({ assertMutationAllowed }),+ });++ await expect(+ actor.create({+ sessionId: "session-a",+ worktreeRoot: "/tmp/session-a",+ sourceFingerprint: "abc",+ name: "Cindy iPhone",+ templateDevice: DEVICE,+ }),+ ).rejects.toThrow("writer lease lost");+ expect(lifecycle.createExact).toHaveBeenCalledTimes(1);+ expect(lifecycle.deleteExact).toHaveBeenCalledWith(createdUdid);+ expect(actor.listAll()).toEqual([]);+ });+it("serializes bounded driver mutations and revalidates their route", async () => {const harness = createHarness({ booted: true });const order: string[] = [];diff --git a/packages/ios-simulator-runtime/src/instance-actor.ts b/packages/ios-simulator-runtime/src/instance-actor.tsindex 32de503abe..5e02a47f45 100644--- a/packages/ios-simulator-runtime/src/instance-actor.ts+++ b/packages/ios-simulator-runtime/src/instance-actor.ts@@ -17,6 +17,8 @@ export interface IOSSimulatorScheduler {export interface IOSSimulatorInstanceActorOptions {store: IOSSimulatorOwnershipStore;lifecycle: IOSSimulatorSimctlLifecycle;+ /** Fail-closed preflight before lifecycle side effects that precede store mutation. */+ assertMutationAllowed?: () => void;clock?: IOSSimulatorClock;scheduler?: IOSSimulatorScheduler;detachGraceMs?: number;@@ -73,6 +75,7 @@ export class IOSSimulatorInstanceActor {readonly #clock: IOSSimulatorClock;readonly #scheduler: IOSSimulatorScheduler;readonly #detachGraceMs: number;+ readonly #assertMutationAllowed: (() => void) | null;readonly #tails = new Map<string, Promise<void>>();readonly #cancelGrace = new Map<string, () => void>();readonly #mutationStates = new Map<string, MutableMutationState>();@@ -84,6 +87,7 @@ export class IOSSimulatorInstanceActor {this.#clock = options.clock ?? { now: () => Date.now() };this.#scheduler = options.scheduler ?? defaultScheduler();this.#detachGraceMs = options.detachGraceMs ?? DEFAULT_DETACH_GRACE_MS;+ this.#assertMutationAllowed = options.assertMutationAllowed ?? null;if (!Number.isSafeInteger(this.#detachGraceMs) ||this.#detachGraceMs <= 0@@ -153,6 +157,7 @@ export class IOSSimulatorInstanceActor {"The template simulator does not expose a device type identifier.",);}+ this.#assertMutationAllowed?.();const created = await this.#lifecycle.createExact({name: input.name,deviceTypeIdentifier,@@ -656,6 +661,7 @@ export class IOSSimulatorInstanceActor {) {return;}+ this.#assertMutationAllowed?.();await this.#lifecycle.shutdownExact(current.simulatorUdid);const afterShutdown = this.#store.get(detached.instanceId);if (@@ -692,6 +698,7 @@ export class IOSSimulatorInstanceActor {"Only simulators created by Cindy can be deleted.",);}+ this.#assertMutationAllowed?.();if (instance.lifecycleState === "ready") {await this.#lifecycle.shutdownExact(instance.simulatorUdid);}diff --git a/packages/ios-simulator-runtime/src/ownership-registry-file.test.ts b/packages/ios-simulator-runtime/src/ownership-registry-file.test.tsindex 688279f615..eaac082822 100644--- a/packages/ios-simulator-runtime/src/ownership-registry-file.test.ts+++ b/packages/ios-simulator-runtime/src/ownership-registry-file.test.ts@@ -1,5 +1,5 @@import { spawnSync } from "node:child_process";-import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";import os from "node:os";import path from "node:path";@@ -94,11 +94,40 @@ describe("IOSSimulatorOwnershipRegistryFile", () => {await writeFile(filePath,JSON.stringify({- version: 999,+ version: 1,instances: [{ simulatorUdid: DEVICE.udid }],}),);- expect(await registry.load()).toEqual([]);+ await expect(registry.load()).rejects.toMatchObject({+ code: "DEVICE_BUSY",+ });+ await writeFile(+ filePath,+ JSON.stringify({ version: 999, instances: [] }),+ );+ await expect(registry.load()).rejects.toMatchObject({+ code: "DEVICE_BUSY",+ });+ const validStore = new IOSSimulatorOwnershipStore({+ createId: () => "valid-instance",+ });+ const valid = validStore.attach({+ sessionId: "session-a",+ worktreeRoot: "/tmp/project-a",+ sourceFingerprint: "fingerprint-a",+ device: DEVICE,+ });+ await registry.save([valid]);+ const invalidDateSnapshot = JSON.parse(+ await readFile(registry.filePath, "utf8"),+ ) as {+ instances: Array<{ lease: { expiresAt: string } }>;+ };+ invalidDateSnapshot.instances[0]!.lease.expiresAt = "not-a-date";+ await writeFile(filePath, JSON.stringify(invalidDateSnapshot));+ await expect(registry.load()).rejects.toMatchObject({+ code: "DEVICE_BUSY",+ });const store = new IOSSimulatorOwnershipStore({createId: () => crypto.randomUUID(),});@@ -108,9 +137,83 @@ describe("IOSSimulatorOwnershipRegistryFile", () => {sourceFingerprint: "fingerprint-a",device: DEVICE,});- const duplicate = { ...first, instanceId: "different-instance" };+ const duplicate = {+ ...first,+ instanceId: "different-instance",+ simulatorUdid: first.simulatorUdid.toLowerCase(),+ };await registry.save([first, duplicate]);- expect(await registry.load()).toEqual([]);+ await expect(registry.load()).rejects.toMatchObject({+ code: "DEVICE_BUSY",+ });+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });++ it("canonicalizes persisted UDIDs before restoring ownership", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-registry-"));+ try {+ const registry = new IOSSimulatorOwnershipRegistryFile(+ path.join(root, "registry.json"),+ { acquireWriterLease: createWriterLeaseFactory() },+ );+ expect(registry.acquireWriterSync()).toBe(true);+ const source = new IOSSimulatorOwnershipStore({+ createId: (() => {+ let index = 0;+ return () => `restored-id-${++index}`;+ })(),+ }).attach({+ sessionId: "session-a",+ worktreeRoot: "/tmp/project-a",+ sourceFingerprint: "fingerprint-a",+ device: DEVICE,+ });+ await registry.save([+ { ...source, simulatorUdid: source.simulatorUdid.toLowerCase() },+ ]);++ const loaded = await registry.load();+ expect(loaded[0]?.simulatorUdid).toBe(DEVICE.udid);+ const restored = new IOSSimulatorOwnershipStore({+ initialInstances: loaded,+ });+ expect(() =>+ restored.attach({+ sessionId: "session-b",+ worktreeRoot: "/tmp/project-b",+ sourceFingerprint: "fingerprint-b",+ device: DEVICE,+ }),+ ).toThrowError(+ expect.objectContaining({ code: "SIMULATOR_ATTACHED_ELSEWHERE" }),+ );+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });++ it("treats only a missing registry as an empty first-run profile", async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-registry-"));+ try {+ const registry = new IOSSimulatorOwnershipRegistryFile(+ path.join(root, "missing-registry.json"),+ { acquireWriterLease: createWriterLeaseFactory() },+ );+ expect(registry.acquireWriterSync()).toBe(true);+ await expect(registry.load()).resolves.toEqual([]);++ await writeFile(registry.filePath, '{"version":1,"instances":[');+ await expect(registry.load()).rejects.toMatchObject({+ code: "DEVICE_BUSY",+ });++ await rm(registry.filePath, { force: true });+ await mkdir(registry.filePath);+ await expect(registry.load()).rejects.toMatchObject({+ code: "DEVICE_BUSY",+ });} finally {await rm(root, { recursive: true, force: true });}diff --git a/packages/ios-simulator-runtime/src/ownership-registry-file.ts b/packages/ios-simulator-runtime/src/ownership-registry-file.tsindex 0d40f2c7c3..c35e96401d 100644--- a/packages/ios-simulator-runtime/src/ownership-registry-file.ts+++ b/packages/ios-simulator-runtime/src/ownership-registry-file.ts@@ -42,34 +42,81 @@ function isRecord(value: unknown): value is Record<string, unknown> {return Boolean(value) && typeof value === "object" && !Array.isArray(value);}+const SIMULATOR_UDID_PATTERN =+ /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/;++function canonicalSimulatorUdid(value: unknown): string | null {+ if (typeof value !== "string") return null;+ const canonical = value.trim().toUpperCase();+ return SIMULATOR_UDID_PATTERN.test(canonical) ? canonical : null;+}++function isNonEmptyString(value: unknown): value is string {+ return typeof value === "string" && value.trim().length > 0;+}++function isIsoDateString(value: unknown): value is string {+ if (typeof value !== "string") return false;+ const timestamp = Date.parse(value);+ return (+ Number.isFinite(timestamp) && new Date(timestamp).toISOString() === value+ );+}++function isNullableIsoDateString(value: unknown): value is string | null {+ return value === null || isIsoDateString(value);+}+function isInstance(value: unknown): value is IOSSimulatorInstance {if (!isRecord(value)) return false;- const requiredStrings = [+ const requiredNonEmptyStrings = ["instanceId","sessionId",- "sessionKind","worktreeRoot","sourceFingerprint","simulatorUdid","simulatorName","runtimeIdentifier","deviceTypeIdentifier",- "creationProvenance",- "bootProvenance",- "lifecycleState",- "viewerState",- "healthState",- "createdAt",- "lastActiveAt",];- if (requiredStrings.some((key) => typeof value[key] !== "string"))+ if (requiredNonEmptyStrings.some((key) => !isNonEmptyString(value[key])))+ return false;+ if (canonicalSimulatorUdid(value.simulatorUdid) === null) return false;+ if (+ value.sessionKind !== "local" ||+ !["cindy", "external"].includes(String(value.creationProvenance)) ||+ !["agent-booted", "user-booted", "preexisting"].includes(+ String(value.bootProvenance),+ ) ||+ !["stopped", "booting", "ready", "stopping", "error"].includes(+ String(value.lifecycleState),+ ) ||+ !["detached", "attaching", "attached"].includes(+ String(value.viewerState),+ ) ||+ !["healthy", "degraded", "recovering", "error"].includes(+ String(value.healthState),+ )+ ) {return false;+ }const lease = value.lease;if (!isRecord(lease)) return false;+ if (!isNonEmptyString(lease.id) || !isIsoDateString(lease.issuedAt)) {+ return false;+ }if (- ["id", "issuedAt", "expiresAt"].some(- (key) => typeof lease[key] !== "string",- )+ !isIsoDateString(lease.expiresAt) ||+ Date.parse(lease.expiresAt) <= Date.parse(lease.issuedAt)+ ) {+ return false;+ }+ if (+ !isIsoDateString(value.createdAt) ||+ !isIsoDateString(value.lastActiveAt) ||+ !isNullableIsoDateString(value.stoppedAt) ||+ !isNullableIsoDateString(value.graceExpiresAt) ||+ (value.errorCode !== null && !isNonEmptyString(value.errorCode))) {return false;}@@ -80,19 +127,21 @@ function isInstance(value: unknown): value is IOSSimulatorInstance {);}-function parseSnapshot(value: unknown): IOSSimulatorInstance[] {+function parseSnapshot(value: unknown): IOSSimulatorInstance[] | null {if (!isRecord(value) ||value.version !== REGISTRY_VERSION ||+ !isIsoDateString(value.savedAt) ||!Array.isArray(value.instances)) {- return [];+ return null;}// A partially valid registry is unsafe: accepting only the valid subset could// leave an untracked device booted or permit duplicate ownership after restart.- if (!value.instances.every(isInstance)) return [];+ if (!value.instances.every(isInstance)) return null;const instances = value.instances.map((instance) => ({...instance,+ simulatorUdid: canonicalSimulatorUdid(instance.simulatorUdid)!,lease: { ...instance.lease },}));const instanceIds = new Set(instances.map((instance) => instance.instanceId));@@ -103,10 +152,18 @@ function parseSnapshot(value: unknown): IOSSimulatorInstance[] {instanceIds.size !== instances.length ||simulatorUdids.size !== instances.length)- return [];+ return null;return instances;}+function invalidRegistryError(): IOSSimulatorInstanceError {+ return new IOSSimulatorInstanceError(+ "DEVICE_BUSY",+ "Cindy cannot safely manage iOS Simulator devices because the ownership registry is invalid.",+ false,+ );+}+/*** Darwin can atomically acquire a BSD flock while opening via O_EXLOCK. The* resulting descriptor is held directly by Electron Main for its lifetime;@@ -211,13 +268,22 @@ export class IOSSimulatorOwnershipRegistryFile {/** Startup-only synchronous read; callers should use load() after initialization. */loadSync(): IOSSimulatorInstance[] {this.assertWriter();+ let serialized: string;try {- return parseSnapshot(- JSON.parse(readFileSync(this.#filePath, "utf8")) as unknown,- );+ serialized = readFileSync(this.#filePath, "utf8");+ } catch (error) {+ if ((error as NodeJS.ErrnoException | null)?.code === "ENOENT") return [];+ throw invalidRegistryError();+ }+ let value: unknown;+ try {+ value = JSON.parse(serialized) as unknown;} catch {- return [];+ throw invalidRegistryError();}+ const instances = parseSnapshot(value);+ if (!instances) throw invalidRegistryError();+ return instances;}async save(instances: IOSSimulatorInstance[]): Promise<void> {diff --git a/packages/ios-simulator-runtime/src/ownership-store.ts b/packages/ios-simulator-runtime/src/ownership-store.tsindex 1a0eab5156..73a03055a8 100644--- a/packages/ios-simulator-runtime/src/ownership-store.ts+++ b/packages/ios-simulator-runtime/src/ownership-store.ts@@ -81,7 +81,13 @@ export class IOSSimulatorOwnershipStore {}#restore(instance: IOSSimulatorInstance): void {- const copy = copyInstance(instance);+ const copy = {+ ...copyInstance(instance),+ simulatorUdid: requireNonEmpty(+ instance.simulatorUdid,+ "simulatorUdid",+ ).toUpperCase(),+ };if (this.#instances.has(copy.instanceId) ||this.#instanceByUdid.has(copy.simulatorUdid)