Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(desktop): harden iOS simulator ownership

JiangJiahao43b7a2b9a0af
diff --git a/apps/desktop/scripts/ios-simulator-release-gate.test.mjs b/apps/desktop/scripts/ios-simulator-release-gate.test.mjs
index 5e4beb7ff6..8d1a37270f 100644
--- a/apps/desktop/scripts/ios-simulator-release-gate.test.mjs
+++ b/apps/desktop/scripts/ios-simulator-release-gate.test.mjs
@@ -1,3 +1,5 @@
+import path from 'node:path';
+
import { describe, expect, it } from 'vitest';
import {
@@ -44,7 +46,7 @@ describe('iOS Simulator packaged release gate CLI', () => {
'--require-native',
]),
).toMatchObject({
- appPath: '/tmp/Cindy.app',
+ appPath: path.resolve('/tmp/Cindy.app'),
arch: 'arm64',
expectedTrust: 'verified',
requireNative: true,
diff --git a/apps/desktop/src/main/maker-host/__tests__/shellCommandPolicy.test.ts b/apps/desktop/src/main/maker-host/__tests__/shellCommandPolicy.test.ts
index 4267414040..49e70751ed 100644
--- a/apps/desktop/src/main/maker-host/__tests__/shellCommandPolicy.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/shellCommandPolicy.test.ts
@@ -7,6 +7,7 @@ describeMac('embedded iOS Simulator shell policy', () => {
it.each([
'open -a Simulator',
'open -n -a "Simulator.app"',
+ 'open -na Simulator',
'open -b com.apple.iphonesimulator',
'open /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app',
'/Applications/Xcode.app/Contents/Developer/Applications/Simulator.app/Contents/MacOS/Simulator',
@@ -38,9 +39,46 @@ describeMac('embedded iOS Simulator shell policy', () => {
expect(getDesktopShellCommandPolicy(command)).toMatchObject({ decision: 'deny' });
});
+ it.each([
+ 'exec /usr/bin/xcrun simctl shutdown DEVICE',
+ 'command -p xcrun simctl boot DEVICE',
+ 'builtin exec xcrun simctl install DEVICE /tmp/App.app',
+ 'nohup -- xcrun simctl launch DEVICE com.example.app',
+ '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'",
+ "eval 'xcrun simctl erase DEVICE'",
+ 'echo "$(xcrun simctl shutdown DEVICE)"',
+ 'echo >(xcrun simctl shutdown DEVICE)',
+ "env -S 'xcrun simctl shutdown DEVICE'",
+ 'CMD=xcrun\\ simctl\\ shutdown\\ DEVICE; eval "$CMD"',
+ 'CMD=xcrun\\ simctl\\ shutdown\\ DEVICE; sh -c "$CMD"',
+ 'CMD=xcrun\\ simctl\\ shutdown\\ DEVICE; $CMD',
+ 'printf "xcrun simctl shutdown DEVICE\\n" | sh',
+ 'time xcrun simctl shutdown DEVICE',
+ 'time -p xcrun simctl boot DEVICE',
+ 'f(){ xcrun simctl shutdown DEVICE;}; f',
+ '/usr/bin/xcrun \\\n simctl shutdown DEVICE',
+ '/usr/bin/nice /usr/bin/xcrun simctl erase DEVICE',
+ '/usr/bin/arch -arm64 /usr/bin/xcrun simctl boot DEVICE',
+ '/usr/bin/caffeinate -i /usr/bin/xcrun simctl shutdown DEVICE',
+ `/bin/sh -c '"$0" "$@"' /usr/bin/xcrun simctl shutdown DEVICE`,
+ `/bin/sh -c '/usr/bin/open -a "$1"' ignored Simulator`,
+ '$(/usr/bin/xcrun --find simctl) shutdown DEVICE',
+ '/usr/bin/xc[r]un simctl shutdown DEVICE',
+ 'TOOL=simctl; /usr/bin/xcrun "$TOOL" shutdown DEVICE',
+ ])('denies Simulator mutation hidden behind shell execution: %s', (command) => {
+ expect(getDesktopShellCommandPolicy(command)).toMatchObject({ decision: 'deny' });
+ });
+
it.each([
'xcrun simctl list devices',
'xcrun simctl listapps DEVICE',
+ 'exec xcrun simctl list devices',
+ 'command -p xcrun simctl listapps DEVICE',
+ "bash -lc 'xcrun simctl list devices'",
+ 'f(){ xcrun simctl list devices;}; f',
+ 'command -v xcrun',
'xcodebuild -scheme FiloApp -sdk iphonesimulator build',
'open -a Xcode',
'echo "open -a Simulator"',
diff --git a/apps/desktop/src/main/maker-host/shell-command-policy.ts b/apps/desktop/src/main/maker-host/shell-command-policy.ts
index 127daed42e..2f2cfae479 100644
--- a/apps/desktop/src/main/maker-host/shell-command-policy.ts
+++ b/apps/desktop/src/main/maker-host/shell-command-policy.ts
@@ -24,8 +24,7 @@ const SAFE_SIMCTL_COMMANDS = new Set([
const IOS_SIMULATOR_SHELL_DENIAL =
'Cindy blocked a shell command that would bypass the embedded iOS Simulator. ' +
- 'Use cindy_ios_simulator for device lifecycle, app install/launch, interaction, screenshots, and diagnostics. ' +
- 'If the user explicitly requests the external Simulator.app window, use cindy_computer.launch_app with use_external_simulator=true instead of shell open.';
+ 'Use cindy_ios_simulator for device lifecycle, app install/launch, interaction, screenshots, and diagnostics. External Simulator.app automation is unavailable until Cindy can issue an explicit host authorization.';
/** Split command lists without treating separators inside quotes as executable boundaries. */
function shellSegments(command: string): string[] {
@@ -66,48 +65,623 @@ function shellSegments(command: string): string[] {
return segments;
}
-function normalizedExecutableSegment(segment: string): string {
- return segment
- .replace(/^\s*(?:(?:if|then|do|else)\s+)+/i, '')
- .replace(/^\s*(?:(?:command|builtin|nohup)\s+)+/i, '')
- .trim();
+/** Lightweight argv tokenizer. Quotes group tokens but are not retained. */
+function tokenizeShellSegment(segment: string): string[] {
+ const tokens: string[] = [];
+ let token = '';
+ let started = false;
+ let quote: "'" | '"' | null = null;
+ const flush = (): void => {
+ if (!started) return;
+ tokens.push(token);
+ token = '';
+ started = false;
+ };
+ for (let index = 0; index < segment.length; index += 1) {
+ const char = segment[index]!;
+ if (char === '\\' && quote !== "'" && index + 1 < segment.length) {
+ token += segment[index + 1]!;
+ started = true;
+ index += 1;
+ continue;
+ }
+ if (quote) {
+ if (char === quote) quote = null;
+ else token += char;
+ started = true;
+ continue;
+ }
+ if (char === "'" || char === '"') {
+ quote = char;
+ started = true;
+ } else if (/\s/.test(char)) {
+ flush();
+ } else {
+ token += char;
+ started = true;
+ }
+ }
+ flush();
+ return tokens;
}
-function isExternalSimulatorLaunch(segment: string): boolean {
- const executable = normalizedExecutableSegment(segment);
- const unquoted = executable.replace(/["']/g, '');
+function executableName(token: string | undefined): string {
+ return (token ?? '')
+ .replace(/\\/g, '/')
+ .split('/')
+ .at(-1)!
+ .replace(/\.exe$/i, '')
+ .toLowerCase();
+}
- const openMatch = unquoted.match(/^(?:\/usr\/bin\/)?open\b([\s\S]*)$/i);
- if (openMatch) {
- const args = openMatch[1] ?? '';
- if (/(?:^|\s)-a\s+Simulator(?:\.app)?(?:\s|$)/i.test(args)) return true;
- if (/(?:^|\s)-b\s+com\.apple\.iphonesimulator(?:\s|$)/i.test(args)) return true;
- if (/(?:^|\s)\/[^\s]*Simulator\.app(?:\/Contents\/MacOS\/Simulator)?(?:\s|$)/i.test(args)) {
- return true;
+function stripShellControlTokens(tokens: string[]): string[] {
+ const out = [...tokens];
+ while (out.length > 0 && /^(?:\{|\(|!|then|do|else|elif|if|while|until)$/.test(out[0]!)) {
+ out.shift();
+ }
+ if (out[0]) out[0] = out[0].replace(/^[({]+/, '');
+ while (out[0] === '') out.shift();
+ const last = out.length - 1;
+ if (last >= 0) {
+ out[last] = out[last]!.replace(/[)}]+$/, '');
+ if (out[last] === '') out.pop();
+ }
+ return out;
+}
+
+interface UnwrappedCommand {
+ tokens: string[];
+ nestedShell: string | null;
+ inspectionOnly: boolean;
+ unresolvedWrapper: boolean;
+}
+
+const MAX_WRAPPER_UNWRAP_DEPTH = 16;
+const SHELL_EXECUTABLES = new Set(['bash', 'dash', 'sh', 'zsh']);
+const SHELL_POSITIONAL_REFERENCE = /\$(?:[0-9]+|[@*#-]|\{(?:[0-9]+|[@*#-])\})/;
+
+/** Peel only wrappers whose argv shape is fully understood; unknown options fail closed. */
+function unwrapCommand(input: string[]): UnwrappedCommand {
+ let tokens = stripShellControlTokens(input);
+ for (let depth = 0; depth < MAX_WRAPPER_UNWRAP_DEPTH; depth += 1) {
+ while (tokens[0] && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[0])) tokens.shift();
+ if (tokens.length === 0) {
+ return { tokens, nestedShell: null, inspectionOnly: false, unresolvedWrapper: false };
+ }
+ const head = executableName(tokens[0]);
+ if (head === 'env') {
+ let index = 1;
+ let unresolved = false;
+ while (index < tokens.length) {
+ const token = tokens[index]!;
+ if (token === '--') {
+ index += 1;
+ break;
+ }
+ if (
+ token === '-' ||
+ token === '-i' ||
+ token === '--ignore-environment' ||
+ token === '-0' ||
+ token === '--null'
+ ) {
+ index += 1;
+ continue;
+ }
+ if (token === '-u' || token === '--unset' || token === '-C' || token === '--chdir') {
+ if (index + 1 >= tokens.length) unresolved = true;
+ index += 2;
+ continue;
+ }
+ if (
+ /^--(?:unset|chdir)=/.test(token) ||
+ /^-(?:u|C).+/.test(token) ||
+ /^[A-Za-z_][A-Za-z0-9_]*=/.test(token)
+ ) {
+ index += 1;
+ continue;
+ }
+ if (token.startsWith('-')) unresolved = true;
+ break;
+ }
+ tokens = tokens.slice(index);
+ if (unresolved) {
+ return { tokens, nestedShell: null, inspectionOnly: false, unresolvedWrapper: true };
+ }
+ continue;
+ }
+ if (head === 'command') {
+ let index = 1;
+ let inspectionOnly = false;
+ while (index < tokens.length) {
+ const token = tokens[index]!;
+ if (token === '--') {
+ index += 1;
+ break;
+ }
+ if (/^-[pVv]+$/.test(token)) {
+ inspectionOnly ||= /[Vv]/.test(token);
+ index += 1;
+ continue;
+ }
+ if (token.startsWith('-')) {
+ return {
+ tokens: tokens.slice(index),
+ nestedShell: null,
+ inspectionOnly: false,
+ unresolvedWrapper: true,
+ };
+ }
+ break;
+ }
+ if (inspectionOnly) {
+ return { tokens: [], nestedShell: null, inspectionOnly: true, unresolvedWrapper: false };
+ }
+ tokens = tokens.slice(index);
+ continue;
+ }
+ if (head === 'exec') {
+ let index = 1;
+ while (index < tokens.length) {
+ const token = tokens[index]!;
+ if (token === '--') {
+ index += 1;
+ break;
+ }
+ if (token === '-a') {
+ if (index + 1 >= tokens.length) {
+ return {
+ tokens: [],
+ nestedShell: null,
+ inspectionOnly: false,
+ unresolvedWrapper: true,
+ };
+ }
+ index += 2;
+ continue;
+ }
+ if (/^-a.+/.test(token) || /^-[cl]+$/.test(token)) {
+ index += 1;
+ continue;
+ }
+ if (token.startsWith('-')) {
+ return {
+ tokens: tokens.slice(index),
+ nestedShell: null,
+ inspectionOnly: false,
+ unresolvedWrapper: true,
+ };
+ }
+ break;
+ }
+ tokens = tokens.slice(index);
+ continue;
}
+ if (head === 'builtin' || head === 'nohup' || head === 'time') {
+ let index = 1;
+ if (tokens[index] === '--') index += 1;
+ else if (head === 'time' && tokens[index] === '-p') index += 1;
+ else if (tokens[index]?.startsWith('-')) {
+ return {
+ tokens: tokens.slice(index),
+ nestedShell: null,
+ inspectionOnly: false,
+ unresolvedWrapper: true,
+ };
+ }
+ tokens = tokens.slice(index);
+ continue;
+ }
+ if (head === 'nice') {
+ let index = 1;
+ while (index < tokens.length) {
+ const token = tokens[index]!;
+ if (token === '--') {
+ index += 1;
+ break;
+ }
+ if (token === '-n' || token === '--adjustment') {
+ if (index + 1 >= tokens.length) {
+ return {
+ tokens: [],
+ nestedShell: null,
+ inspectionOnly: false,
+ unresolvedWrapper: true,
+ };
+ }
+ index += 2;
+ continue;
+ }
+ if (/^(?:--adjustment=.+|-\d+)$/.test(token)) {
+ index += 1;
+ continue;
+ }
+ if (token.startsWith('-')) {
+ return {
+ tokens: tokens.slice(index),
+ nestedShell: null,
+ inspectionOnly: false,
+ unresolvedWrapper: true,
+ };
+ }
+ break;
+ }
+ tokens = tokens.slice(index);
+ continue;
+ }
+ if (head === 'arch') {
+ let index = 1;
+ while (index < tokens.length) {
+ const token = tokens[index]!;
+ if (token === '--') {
+ index += 1;
+ break;
+ }
+ if (token === '-arch' || token === '--arch' || token === '-d' || token === '-e') {
+ if (index + 1 >= tokens.length) {
+ return {
+ tokens: [],
+ nestedShell: null,
+ inspectionOnly: false,
+ unresolvedWrapper: true,
+ };
+ }
+ index += 2;
+ continue;
+ }
+ if (/^-(?:arm64e?|x86_64|i386|32|64|c)$/.test(token)) {
+ index += 1;
+ continue;
+ }
+ if (token.startsWith('-')) {
+ return {
+ tokens: tokens.slice(index),
+ nestedShell: null,
+ inspectionOnly: false,
+ unresolvedWrapper: true,
+ };
+ }
+ break;
+ }
+ tokens = tokens.slice(index);
+ continue;
+ }
+ if (head === 'caffeinate') {
+ let index = 1;
+ while (index < tokens.length) {
+ const token = tokens[index]!;
+ if (token === '--') {
+ index += 1;
+ break;
+ }
+ if (token === '-t' || token === '-w') {
+ if (index + 1 >= tokens.length) {
+ return {
+ tokens: [],
+ nestedShell: null,
+ inspectionOnly: false,
+ unresolvedWrapper: true,
+ };
+ }
+ index += 2;
+ continue;
+ }
+ if (/^-[dimsur]+$/.test(token)) {
+ index += 1;
+ continue;
+ }
+ if (token.startsWith('-')) {
+ return {
+ tokens: tokens.slice(index),
+ nestedShell: null,
+ inspectionOnly: false,
+ unresolvedWrapper: true,
+ };
+ }
+ break;
+ }
+ tokens = tokens.slice(index);
+ continue;
+ }
+ if (head === 'eval') {
+ return {
+ tokens: [],
+ nestedShell: tokens.slice(1).join(' '),
+ inspectionOnly: false,
+ unresolvedWrapper: false,
+ };
+ }
+ if (SHELL_EXECUTABLES.has(head)) {
+ let index = 1;
+ while (index < tokens.length) {
+ const token = tokens[index]!;
+ if (token === '-o' || token === '-O') {
+ index += 2;
+ continue;
+ }
+ if (/^-[A-Za-z]*c[A-Za-z]*$/.test(token)) {
+ const nestedShell = tokens[index + 1] ?? '';
+ const positionalArgs = tokens.slice(index + 2);
+ return {
+ tokens: positionalArgs,
+ nestedShell,
+ inspectionOnly: false,
+ unresolvedWrapper:
+ index + 1 >= tokens.length ||
+ (SHELL_POSITIONAL_REFERENCE.test(nestedShell) &&
+ containsSimulatorExecutor(positionalArgs)),
+ };
+ }
+ if (token === '--') break;
+ if (!token.startsWith('-')) break;
+ index += 1;
+ }
+ }
+ return { tokens, nestedShell: null, inspectionOnly: false, unresolvedWrapper: false };
}
+ return { tokens, nestedShell: null, inspectionOnly: false, unresolvedWrapper: true };
+}
- return /^(?:\/Applications\/Xcode[^/]*\.app\/Contents\/Developer\/Applications\/)?Simulator\.app\/Contents\/MacOS\/Simulator(?:\s|$)/i.test(
- unquoted,
+function isExternalSimulatorLaunch(tokens: string[]): boolean {
+ const head = executableName(tokens[0]);
+ if (head === 'open') {
+ for (let index = 1; index < tokens.length; index += 1) {
+ const token = tokens[index]!;
+ const next = tokens[index + 1];
+ if (/^-[^-]*a[^-]*$/i.test(token) && /^Simulator(?:\.app)?$/i.test(next ?? '')) return true;
+ if (/^-aSimulator(?:\.app)?$/i.test(token)) return true;
+ if (/^-[^-]*b[^-]*$/i.test(token) && /^com\.apple\.iphonesimulator$/i.test(next ?? '')) {
+ return true;
+ }
+ if (/^-bcom\.apple\.iphonesimulator$/i.test(token)) return true;
+ if (/\/Simulator\.app(?:\/Contents\/MacOS\/Simulator)?$/i.test(token)) return true;
+ }
+ }
+ return (
+ head === 'simulator' && /Simulator\.app\/Contents\/MacOS\/Simulator$/i.test(tokens[0] ?? '')
);
}
-function isSimulatorMutation(segment: string): boolean {
- const executable = normalizedExecutableSegment(segment).replace(/["']/g, '');
- const match = executable.match(
- /^(?:(?:\/usr\/bin\/)?xcrun\s+)?(?:[^\s/]+\/)*simctl\s+(?:--set\s+\S+\s+)?([a-z_][a-z0-9_-]*)\b/i,
+function simctlSubcommand(tokens: string[]): string | null {
+ let index = 0;
+ if (executableName(tokens[index]) === 'xcrun') {
+ index += 1;
+ while (index < tokens.length && tokens[index]!.startsWith('-')) {
+ const option = tokens[index]!;
+ if (
+ option === '--sdk' ||
+ option === '-sdk' ||
+ option === '--toolchain' ||
+ option === '-toolchain'
+ ) {
+ index += 2;
+ } else {
+ index += 1;
+ }
+ }
+ }
+ if (executableName(tokens[index]) !== 'simctl') return null;
+ index += 1;
+ if (tokens[index] === '--set') index += 2;
+ return tokens[index]?.toLowerCase() ?? null;
+}
+
+function isSimulatorMutation(tokens: string[]): boolean {
+ const subcommand = simctlSubcommand(tokens);
+ return subcommand !== null && !SAFE_SIMCTL_COMMANDS.has(subcommand);
+}
+
+function containsSimulatorExecutor(tokens: string[]): boolean {
+ return tokens.some(
+ (token) =>
+ /(?:^|\/)simctl$/i.test(token) ||
+ /Simulator(?:\.app)?/i.test(token) ||
+ /\bxcrun\b[\s\S]*\bsimctl\b/i.test(token),
);
- if (!match) return false;
- return !SAFE_SIMCTL_COMMANDS.has(match[1].toLowerCase());
}
-/** Undefined means the normal shell permission flow remains unchanged. */
-export function getDesktopShellCommandPolicy(command: string): ShellCommandPolicyDenial | undefined {
- if (process.platform !== 'darwin') return undefined;
+/** Extract command/process substitutions because they execute even inside an otherwise safe command. */
+function shellSubcommands(command: string): string[] {
+ const subcommands: string[] = [];
+ let quote: "'" | '"' | null = null;
+ let escaped = false;
+ for (let index = 0; index < command.length; index += 1) {
+ const char = command[index]!;
+ if (escaped) {
+ escaped = false;
+ continue;
+ }
+ if (char === '\\' && quote !== "'") {
+ escaped = true;
+ continue;
+ }
+ if (char === "'") {
+ if (quote === "'") quote = null;
+ else if (quote === null) quote = "'";
+ continue;
+ }
+ if (char === '"') {
+ if (quote === '"') quote = null;
+ else if (quote === null) quote = '"';
+ continue;
+ }
+ if (quote === "'") continue;
+ if (char === '`') {
+ let end = index + 1;
+ for (; end < command.length; end += 1) {
+ if (command[end] === '\\') end += 1;
+ else if (command[end] === '`') break;
+ }
+ if (end < command.length) {
+ subcommands.push(command.slice(index + 1, end));
+ index = end;
+ }
+ continue;
+ }
+ if ((char === '$' || char === '<' || char === '>') && command[index + 1] === '(') {
+ let depth = 1;
+ let innerQuote: "'" | '"' | null = null;
+ let end = index + 2;
+ for (; end < command.length && depth > 0; end += 1) {
+ const inner = command[end]!;
+ if (inner === '\\' && innerQuote !== "'") {
+ end += 1;
+ continue;
+ }
+ if (inner === "'" || inner === '"') {
+ if (innerQuote === inner) innerQuote = null;
+ else if (innerQuote === null) innerQuote = inner;
+ continue;
+ }
+ if (innerQuote) continue;
+ if (inner === '(') depth += 1;
+ else if (inner === ')') depth -= 1;
+ }
+ if (depth === 0) {
+ subcommands.push(command.slice(index + 2, end - 1));
+ index = end - 1;
+ }
+ }
+ }
+ return subcommands;
+}
+
+function isLiteralSimulatorBypass(command: string): boolean {
+ for (const segment of shellSegments(command)) {
+ const unwrapped = unwrapCommand(tokenizeShellSegment(segment));
+ if (unwrapped.inspectionOnly || unwrapped.unresolvedWrapper) continue;
+ if (isExternalSimulatorLaunch(unwrapped.tokens) || isSimulatorMutation(unwrapped.tokens)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+function isSimulatorExecutorValue(value: string): boolean {
+ const normalized = value
+ .trim()
+ .replace(/^['"]|['"]$/g, '')
+ .replace(/\\/g, '/');
+ return /(?:^|\/)(?:xcrun|simctl)$/i.test(normalized) || /Simulator(?:\.app)?/i.test(normalized);
+}
+
+function hasUnresolvedExecutableExpansion(segment: string, tokens: string[]): boolean {
+ const executableTokens = stripShellControlTokens(tokens);
+ while (executableTokens[0] && /^[A-Za-z_][A-Za-z0-9_]*=/.test(executableTokens[0])) {
+ executableTokens.shift();
+ }
+ const executable = executableTokens[0] ?? '';
+ if (!/[$`*?\[]/.test(executable)) return false;
+ return /\b(?:xcrun|simctl|Simulator(?:\.app)?)\b/i.test(segment);
+}
+
+function referencesVariable(command: string, variable: string): boolean {
+ const escaped = variable.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ return new RegExp(`\\$(?:${escaped}\\b|\\{${escaped}\\})`).test(command);
+}
+
+/** Track simple shell assignments so a later eval/sh -c/$VAR cannot hide a bypass. */
+function containsTaintedVariableExecution(command: string): boolean {
+ const tainted = new Set<string>();
+ const tokenizedSegments = shellSegments(command).map((segment) => ({
+ segment,
+ tokens: tokenizeShellSegment(segment),
+ }));
+ for (const { tokens } of tokenizedSegments) {
+ for (const token of tokens) {
+ const assignment = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s.exec(token);
+ if (!assignment) break;
+ const value = assignment[2] ?? '';
+ if (isLiteralSimulatorBypass(value) || isSimulatorExecutorValue(value)) {
+ tainted.add(assignment[1]!);
+ }
+ }
+ }
+ if (tainted.size === 0) return false;
+
+ for (const { segment, tokens } of tokenizedSegments) {
+ const unwrapped = unwrapCommand(tokens);
+ for (const variable of tainted) {
+ if (unwrapped.nestedShell !== null && referencesVariable(unwrapped.nestedShell, variable)) {
+ return true;
+ }
+ if (referencesVariable(unwrapped.tokens[0] ?? '', variable)) return true;
+ if (
+ executableName(unwrapped.tokens[0]) === 'xcrun' &&
+ unwrapped.tokens.some((token) => referencesVariable(token, variable))
+ ) {
+ return true;
+ }
+ // Unknown wrappers are unsafe when they consume a tainted command value.
+ if (unwrapped.unresolvedWrapper && referencesVariable(segment, variable)) return true;
+ }
+ }
+ 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 bodies are executable later, so reject unsafe bodies at definition time. */
+function containsSimulatorFunctionBody(command: string, depth: number): boolean {
+ const functionPattern =
+ /(?:^|[;\n]\s*)(?:function\s+)?[A-Za-z_][A-Za-z0-9_]*(?:\s*\(\s*\))?\s*\{([\s\S]*?)\}/g;
+ for (const match of command.matchAll(functionPattern)) {
+ if (containsSimulatorBypass(match[1] ?? '', depth + 1)) return true;
+ }
+ return false;
+}
+
+function containsSimulatorBypass(command: string, depth = 0): boolean {
+ if (depth > 8) return /\b(?:simctl|Simulator(?:\.app)?)\b/i.test(command);
+ if (
+ containsTaintedVariableExecution(command) ||
+ containsShellConsumedLiteralBypass(command) ||
+ containsSimulatorFunctionBody(command, depth)
+ ) {
+ return true;
+ }
+ for (const nested of shellSubcommands(command)) {
+ if (containsSimulatorBypass(nested, depth + 1)) return true;
+ }
for (const segment of shellSegments(command)) {
- if (isExternalSimulatorLaunch(segment) || isSimulatorMutation(segment)) {
- return { decision: 'deny', reason: IOS_SIMULATOR_SHELL_DENIAL };
+ const tokens = tokenizeShellSegment(segment);
+ if (hasUnresolvedExecutableExpansion(segment, tokens)) return true;
+ const unwrapped = unwrapCommand(tokens);
+ if (unwrapped.inspectionOnly) continue;
+ if (unwrapped.nestedShell !== null) {
+ if (unwrapped.unresolvedWrapper)
+ return containsSimulatorExecutor(tokenizeShellSegment(segment));
+ if (containsSimulatorBypass(unwrapped.nestedShell, depth + 1)) return true;
+ continue;
}
+ if (unwrapped.unresolvedWrapper && containsSimulatorExecutor(unwrapped.tokens)) return true;
+ if (isExternalSimulatorLaunch(unwrapped.tokens) || isSimulatorMutation(unwrapped.tokens)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/** Undefined means the normal shell permission flow remains unchanged. */
+export function getDesktopShellCommandPolicy(
+ command: string,
+): ShellCommandPolicyDenial | undefined {
+ if (process.platform !== 'darwin') return undefined;
+ // POSIX shells remove an unquoted backslash-newline before tokenization.
+ // Mirror that expansion so the policy cannot be bypassed with continuations.
+ const expandedCommand = command.replace(/\\\r?\n/g, '');
+ if (containsSimulatorBypass(expandedCommand)) {
+ return { decision: 'deny', reason: IOS_SIMULATOR_SHELL_DENIAL };
}
return undefined;
}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts
index 5c3b8e29dc..2b2c63ad72 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/iosSimulatorHandlers.test.ts
@@ -1,10 +1,44 @@
import { describe, expect, it, vi } from 'vitest';
import { MAKER_INVOKE } from '../channels';
-import { registerIOSSimulatorHandlers } from '../iosSimulatorHandlers';
+import {
+ registerIOSSimulatorHandlers,
+ type IOSSimulatorHandlerDeps,
+} from '../iosSimulatorHandlers';
import { IpcHarness } from './helpers/ipcHarness';
describe('iOS Simulator IPC handlers', () => {
+ function registerTrusted(harness: IpcHarness, deps: Partial<IOSSimulatorHandlerDeps> = {}): void {
+ registerIOSSimulatorHandlers(harness, {
+ assertTrustedSender: () => undefined,
+ ...deps,
+ });
+ }
+
+ it.each([
+ MAKER_INVOKE.IOS_SIMULATOR_STATUS,
+ MAKER_INVOKE.IOS_SIMULATOR_CALL,
+ MAKER_INVOKE.IOS_SIMULATOR_SET_AGENT_CONTROL,
+ MAKER_INVOKE.IOS_SIMULATOR_SET_MUTATION_CONTROL,
+ MAKER_INVOKE.IOS_SIMULATOR_SET_VIEWER_VISIBILITY,
+ MAKER_INVOKE.IOS_SIMULATOR_LATEST_FRAME,
+ MAKER_INVOKE.IOS_SIMULATOR_SET_STREAM_PROFILE,
+ MAKER_INVOKE.IOS_SIMULATOR_LIVE_TOUCH,
+ ])('checks the trusted sender before parsing %s', async (channel) => {
+ const harness = new IpcHarness();
+ const getStatus = vi.fn();
+ const assertTrustedSender = vi.fn(() => {
+ throw Object.assign(new Error('untrusted sender'), { code: 'PERMISSION_DENIED' });
+ });
+ registerIOSSimulatorHandlers(harness, { assertTrustedSender, getStatus });
+
+ await expect(harness.invoke(channel, undefined)).rejects.toMatchObject({
+ code: 'PERMISSION_DENIED',
+ });
+ expect(assertTrustedSender).toHaveBeenCalledOnce();
+ expect(getStatus).not.toHaveBeenCalled();
+ });
+
it('passes a validated session id to the host', async () => {
const harness = new IpcHarness();
const getStatus = vi.fn(async (sessionId: string) => ({
@@ -13,7 +47,7 @@ describe('iOS Simulator IPC handlers', () => {
errorCode: 'UNSUPPORTED_SESSION_KIND' as const,
message: 'Remote session',
}));
- registerIOSSimulatorHandlers(harness, { getStatus });
+ registerTrusted(harness, { getStatus });
await expect(
harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_STATUS, {
@@ -25,7 +59,7 @@ describe('iOS Simulator IPC handlers', () => {
it('rejects missing session ids', async () => {
const harness = new IpcHarness();
- registerIOSSimulatorHandlers(harness, { getStatus: vi.fn() });
+ registerTrusted(harness, { getStatus: vi.fn() });
await expect(harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_STATUS, {})).rejects.toMatchObject({
code: 'INVALID_PARAMS',
@@ -35,29 +69,32 @@ describe('iOS Simulator IPC handlers', () => {
it('validates and routes user lifecycle calls through the shared host', async () => {
const harness = new IpcHarness();
const callTool = vi.fn(async () => ({ ok: true as const, data: { instances: [] } }));
- registerIOSSimulatorHandlers(harness, { callTool });
+ registerTrusted(harness, { callTool });
await expect(
harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_CALL, {
sessionId: 'session-a',
- name: 'list_instances',
+ name: 'attach_device',
args: {},
}),
).resolves.toMatchObject({ ok: true });
- expect(callTool).toHaveBeenCalledWith('list_instances', {}, 'session-a');
- await expect(
- harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_CALL, {
- sessionId: 'session-a',
- name: 'delete_everything',
- args: {},
- }),
- ).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
+ expect(callTool).toHaveBeenCalledWith('attach_device', {}, 'session-a');
+ for (const name of ['build_app', 'open_url', 'push_notification', 'delete_everything']) {
+ await expect(
+ harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_CALL, {
+ sessionId: 'session-a',
+ name,
+ args: {},
+ }),
+ ).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
+ }
+ expect(callTool).toHaveBeenCalledTimes(1);
});
it('allows only explicit agent-control grant decisions', async () => {
const harness = new IpcHarness();
const setAgentControlGrant = vi.fn(async () => ({ ok: true as const, data: {} }));
- registerIOSSimulatorHandlers(harness, { setAgentControlGrant });
+ registerTrusted(harness, { setAgentControlGrant });
await harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_SET_AGENT_CONTROL, {
sessionId: 'session-a',
@@ -77,7 +114,7 @@ describe('iOS Simulator IPC handlers', () => {
it('validates and routes explicit Agent mutation pause state', async () => {
const harness = new IpcHarness();
const setAgentMutationPaused = vi.fn(async () => ({ ok: true as const, data: {} }));
- registerIOSSimulatorHandlers(harness, { setAgentMutationPaused });
+ registerTrusted(harness, { setAgentMutationPaused });
const route = {
sessionId: 'session-a',
instanceId: 'instance-a',
@@ -106,7 +143,7 @@ describe('iOS Simulator IPC handlers', () => {
const harness = new IpcHarness();
const setViewerVisibility = vi.fn(async () => ({ ok: true as const, data: {} }));
const getLatestFrame = vi.fn(async () => ({ ok: true as const, data: { stream: null } }));
- registerIOSSimulatorHandlers(harness, { setViewerVisibility, getLatestFrame });
+ registerTrusted(harness, { setViewerVisibility, getLatestFrame });
const route = {
sessionId: 'session-a',
instanceId: 'instance-a',
@@ -114,16 +151,17 @@ describe('iOS Simulator IPC handlers', () => {
leaseId: 'lease-a',
};
- await harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_SET_VIEWER_VISIBILITY, {
+ await harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_SET_VIEWER_VISIBILITY, {
...route,
visible: true,
+ viewerToken: 'viewer-a',
});
- await harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_SET_VIEWER_VISIBILITY, {
+ await harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_SET_VIEWER_VISIBILITY, {
...route,
visible: true,
preferredEncoding: 'h264',
});
- await harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_SET_VIEWER_VISIBILITY, {
+ await harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_SET_VIEWER_VISIBILITY, {
...route,
visible: true,
preferredEncoding: 'jpeg',
@@ -135,12 +173,19 @@ describe('iOS Simulator IPC handlers', () => {
'session-a',
{ instanceId: 'instance-a', generation: 3, leaseId: 'lease-a' },
true,
+ undefined,
+ undefined,
+ 17,
+ 'viewer-a',
);
expect(setViewerVisibility).toHaveBeenCalledWith(
'session-a',
{ instanceId: 'instance-a', generation: 3, leaseId: 'lease-a' },
true,
'h264',
+ undefined,
+ 17,
+ undefined,
);
expect(setViewerVisibility).toHaveBeenCalledWith(
'session-a',
@@ -148,6 +193,8 @@ describe('iOS Simulator IPC handlers', () => {
true,
'jpeg',
'native-decoder-fallback',
+ 17,
+ undefined,
);
expect(getLatestFrame).toHaveBeenCalledWith('session-a', {
instanceId: 'instance-a',
@@ -161,32 +208,39 @@ describe('iOS Simulator IPC handlers', () => {
}),
).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
await expect(
- harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_SET_VIEWER_VISIBILITY, {
+ harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_SET_VIEWER_VISIBILITY, {
...route,
visible: 'yes',
}),
).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
await expect(
- harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_SET_VIEWER_VISIBILITY, {
+ harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_SET_VIEWER_VISIBILITY, {
...route,
visible: true,
preferredEncoding: 'hevc',
}),
).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
await expect(
- harness.invoke(MAKER_INVOKE.IOS_SIMULATOR_SET_VIEWER_VISIBILITY, {
+ harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_SET_VIEWER_VISIBILITY, {
...route,
visible: true,
preferredEncoding: 'jpeg',
fallbackReason: 'renderer-error',
}),
).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
+ await expect(
+ harness.invokeFrom(17, MAKER_INVOKE.IOS_SIMULATOR_SET_VIEWER_VISIBILITY, {
+ ...route,
+ visible: true,
+ viewerToken: '',
+ }),
+ ).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
});
it('validates and routes bounded stream profiles', async () => {
const harness = new IpcHarness();
const setViewerStreamProfile = vi.fn(async () => ({ ok: true as const, data: {} }));
- registerIOSSimulatorHandlers(harness, { setViewerStreamProfile });
+ registerTrusted(harness, { setViewerStreamProfile });
const route = {
sessionId: 'session-a',
instanceId: 'instance-a',
@@ -222,7 +276,7 @@ describe('iOS Simulator IPC handlers', () => {
it('validates and routes host-owned live touch samples', async () => {
const harness = new IpcHarness();
const updateViewerTouch = vi.fn(async () => ({ ok: true as const, data: {} }));
- registerIOSSimulatorHandlers(harness, { updateViewerTouch });
+ registerTrusted(harness, { updateViewerTouch });
const route = {
sessionId: 'session-a',
instanceId: 'instance-a',
diff --git a/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts b/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts
index 07f803dd19..f2ccb6b3a6 100644
--- a/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/iosSimulatorHandlers.ts
@@ -1,8 +1,10 @@
import type {
IOSSimulatorNativeH264StreamProfileRequest,
+ IOSSimulatorRendererToolName,
IOSSimulatorSessionStatus,
IOSSimulatorToolResponse,
} from '../../shared/iosSimulatorIpc.js';
+import { IOS_SIMULATOR_RENDERER_TOOL_NAMES } from '../../shared/iosSimulatorIpc.js';
import {
callIOSSimulatorHostTool,
getIOSSimulatorLatestFrame,
@@ -13,15 +15,16 @@ import {
setIOSSimulatorViewerStreamProfile,
updateIOSSimulatorViewerTouch,
} from '../mcp-integrations/ios-simulator.js';
-import type { IOSSimulatorMcpToolName } from '@cindy/mcps';
+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
import { throwIpcError } from '../utils/ipcValidate.js';
import { MAKER_INVOKE } from './channels.js';
import type { IpcHandlerRegistry } from './ipcHandlerRegistry.js';
export interface IOSSimulatorHandlerDeps {
+ assertTrustedSender(event: unknown): void;
getStatus(sessionId: string): Promise<IOSSimulatorSessionStatus>;
callTool(
- name: IOSSimulatorMcpToolName,
+ name: IOSSimulatorRendererToolName,
args: Record<string, unknown>,
sessionId: string,
): Promise<IOSSimulatorToolResponse>;
@@ -41,6 +44,8 @@ export interface IOSSimulatorHandlerDeps {
visible: boolean,
preferredEncoding?: 'jpeg' | 'h264',
fallbackReason?: 'native-decoder-fallback',
+ viewerWebContentsId?: number,
+ viewerToken?: string,
): Promise<IOSSimulatorToolResponse>;
setViewerStreamProfile(
sessionId: string,
@@ -65,6 +70,8 @@ export interface IOSSimulatorHandlerDeps {
}
const defaultDeps: IOSSimulatorHandlerDeps = {
+ assertTrustedSender: (event) =>
+ assertTrustedAppRendererEvent(event as Parameters<typeof assertTrustedAppRendererEvent>[0]),
getStatus: getIOSSimulatorSessionStatus,
callTool: callIOSSimulatorHostTool,
setAgentControlGrant: setIOSSimulatorAgentControlGrant,
@@ -75,51 +82,9 @@ const defaultDeps: IOSSimulatorHandlerDeps = {
updateViewerTouch: updateIOSSimulatorViewerTouch,
};
-const TOOL_NAMES = new Set<IOSSimulatorMcpToolName>([
- 'check_environment',
- 'list_devices',
- 'list_instances',
- 'create_instance',
- 'attach_device',
- 'detach_device',
- 'start_instance',
- 'stop_instance',
- 'get_screen_map',
- 'audit_accessibility',
- 'compare_screen_maps',
- 'tap',
- 'swipe',
- 'touch_path',
- 'touch2_path',
- 'type_text',
- 'press_home',
- 'set_orientation',
- 'set_appearance',
- 'set_increase_contrast',
- 'set_content_size',
- 'set_location',
- 'start_location_route',
- 'clear_location',
- 'set_privacy',
- 'push_notification',
- 'set_status_bar',
- 'clear_status_bar',
- 'lock_screen',
- 'unlock_screen',
- 'build_app',
- 'read_build_diagnostics',
- 'install_app',
- 'launch_app',
- 'terminate_app',
- 'open_url',
- 'take_screenshot',
- 'capture_visual_baseline',
- 'visual_diff',
- 'capture_state',
- 'get_diagnostics',
- 'start_recording',
- 'stop_recording',
-]);
+const RENDERER_TOOL_NAMES = new Set<IOSSimulatorRendererToolName>(
+ IOS_SIMULATOR_RENDERER_TOOL_NAMES,
+);
function readSessionId(payload: unknown): string {
if (!payload || typeof payload !== 'object') {
@@ -155,12 +120,26 @@ 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;
+ if (!Number.isSafeInteger(id) || Number(id) <= 0) {
+ throwIpcError('PERMISSION_DENIED', 'trusted renderer sender is required');
+ }
+ return Number(id);
+}
+
export function registerIOSSimulatorHandlers(
registry: IpcHandlerRegistry,
deps: Partial<IOSSimulatorHandlerDeps> = {},
): void {
const resolved = { ...defaultDeps, ...deps };
- registry.handle(MAKER_INVOKE.IOS_SIMULATOR_STATUS, async (_event, payload) => {
+ const handle: IpcHandlerRegistry['handle'] = (channel, handler) => {
+ registry.handle(channel, (event, ...args) => {
+ resolved.assertTrustedSender(event);
+ return handler(event, ...args);
+ });
+ };
+ handle(MAKER_INVOKE.IOS_SIMULATOR_STATUS, async (_event, payload) => {
const sessionId = readSessionId(payload);
try {
return await resolved.getStatus(sessionId);
@@ -168,24 +147,27 @@ export function registerIOSSimulatorHandlers(
throwIpcError('INTERNAL', error instanceof Error ? error.message : String(error));
}
});
- registry.handle(MAKER_INVOKE.IOS_SIMULATOR_CALL, async (_event, payload) => {
+ handle(MAKER_INVOKE.IOS_SIMULATOR_CALL, async (_event, payload) => {
const record = readRecord(payload);
const sessionId = readSessionId(record);
const name = record.name;
const args = record.args;
- if (typeof name !== 'string' || !TOOL_NAMES.has(name as IOSSimulatorMcpToolName)) {
+ if (
+ typeof name !== 'string' ||
+ !RENDERER_TOOL_NAMES.has(name as IOSSimulatorRendererToolName)
+ ) {
throwIpcError('INVALID_PARAMS', 'name must be a supported iOS Simulator tool');
}
if (!args || typeof args !== 'object' || Array.isArray(args)) {
throwIpcError('INVALID_PARAMS', 'args must be an object');
}
return resolved.callTool(
- name as IOSSimulatorMcpToolName,
+ name as IOSSimulatorRendererToolName,
args as Record<string, unknown>,
sessionId,
);
});
- registry.handle(MAKER_INVOKE.IOS_SIMULATOR_SET_AGENT_CONTROL, async (_event, payload) => {
+ handle(MAKER_INVOKE.IOS_SIMULATOR_SET_AGENT_CONTROL, async (_event, payload) => {
const record = readRecord(payload);
const sessionId = readSessionId(record);
const instanceId = record.instanceId;
@@ -198,7 +180,7 @@ export function registerIOSSimulatorHandlers(
}
return resolved.setAgentControlGrant(sessionId, instanceId.trim(), decision);
});
- registry.handle(MAKER_INVOKE.IOS_SIMULATOR_SET_VIEWER_VISIBILITY, async (_event, payload) => {
+ handle(MAKER_INVOKE.IOS_SIMULATOR_SET_VIEWER_VISIBILITY, async (event, payload) => {
const record = readRecord(payload);
const sessionId = readSessionId(record);
if (typeof record.visible !== 'boolean') {
@@ -216,12 +198,39 @@ export function registerIOSSimulatorHandlers(
if (fallbackReason !== undefined && fallbackReason !== 'native-decoder-fallback') {
throwIpcError('INVALID_PARAMS', 'fallbackReason is not supported');
}
+ const viewerToken = record.viewerToken;
+ if (
+ viewerToken !== undefined &&
+ (typeof viewerToken !== 'string' || !viewerToken.trim() || viewerToken.length > 128)
+ ) {
+ throwIpcError(
+ 'INVALID_PARAMS',
+ 'viewerToken must be a non-empty string of at most 128 chars',
+ );
+ }
const route = readViewerRoute(record);
+ const viewerWebContentsId = readSenderWebContentsId(event);
if (preferredEncoding === undefined && fallbackReason === undefined) {
- return resolved.setViewerVisibility(sessionId, route, record.visible);
+ return resolved.setViewerVisibility(
+ sessionId,
+ route,
+ record.visible,
+ undefined,
+ undefined,
+ viewerWebContentsId,
+ viewerToken?.trim(),
+ );
}
if (fallbackReason === undefined) {
- return resolved.setViewerVisibility(sessionId, route, record.visible, preferredEncoding);
+ return resolved.setViewerVisibility(
+ sessionId,
+ route,
+ record.visible,
+ preferredEncoding,
+ undefined,
+ viewerWebContentsId,
+ viewerToken?.trim(),
+ );
}
return resolved.setViewerVisibility(
sessionId,
@@ -229,9 +238,11 @@ export function registerIOSSimulatorHandlers(
record.visible,
preferredEncoding,
fallbackReason,
+ viewerWebContentsId,
+ viewerToken?.trim(),
);
});
- registry.handle(MAKER_INVOKE.IOS_SIMULATOR_SET_MUTATION_CONTROL, async (_event, payload) => {
+ handle(MAKER_INVOKE.IOS_SIMULATOR_SET_MUTATION_CONTROL, async (_event, payload) => {
const record = readRecord(payload);
const sessionId = readSessionId(record);
if (typeof record.paused !== 'boolean') {
@@ -239,11 +250,11 @@ export function registerIOSSimulatorHandlers(
}
return resolved.setAgentMutationPaused(sessionId, readViewerRoute(record), record.paused);
});
- registry.handle(MAKER_INVOKE.IOS_SIMULATOR_LATEST_FRAME, async (_event, payload) => {
+ handle(MAKER_INVOKE.IOS_SIMULATOR_LATEST_FRAME, async (_event, payload) => {
const record = readRecord(payload);
return resolved.getLatestFrame(readSessionId(record), readViewerRoute(record));
});
- registry.handle(MAKER_INVOKE.IOS_SIMULATOR_SET_STREAM_PROFILE, async (_event, payload) => {
+ handle(MAKER_INVOKE.IOS_SIMULATOR_SET_STREAM_PROFILE, async (_event, payload) => {
const record = readRecord(payload);
const sessionId = readSessionId(record);
const profile = record.profile;
@@ -291,7 +302,7 @@ export function registerIOSSimulatorHandlers(
nativeProfile,
);
});
- registry.handle(MAKER_INVOKE.IOS_SIMULATOR_LIVE_TOUCH, async (_event, payload) => {
+ handle(MAKER_INVOKE.IOS_SIMULATOR_LIVE_TOUCH, async (_event, payload) => {
const record = readRecord(payload);
const sessionId = readSessionId(record);
const gestureId = record.gestureId;
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
index fc1abfeed4..97fb4f2057 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
@@ -13,7 +13,10 @@ import {
IOSSimulatorResourceScheduler,
WdaError,
type IOSSimulatorEnvironmentReport,
+ type IOSSimulatorH264Frame,
+ type IOSSimulatorNativeSidecarDriver,
type IOSSimulatorSimctlLifecycle,
+ type IOSSimulatorStreamStats,
type IOSSimulatorStreamProfile,
type IOSSimulatorTouchPoint,
type WdaRunningInstance,
@@ -1384,6 +1387,182 @@ describe('iOS Simulator host', () => {
await host.dispose();
});
+ it('pushes H.264 frames only to the exact current viewer and rejects stale generations', async () => {
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(async () => READY_REPORT.devices[0]!),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(async () => undefined),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore(),
+ lifecycle,
+ });
+ const instance = actor.attach({
+ sessionId: 'session-a',
+ worktreeRoot: '/tmp/session-a',
+ sourceFingerprint: 'fingerprint-a',
+ device: READY_REPORT.devices[0]!,
+ bootProvenance: 'preexisting',
+ });
+ let frameSink: ((frame: IOSSimulatorH264Frame) => void | Promise<void>) | null = null;
+ const emitFrame = async (frame: IOSSimulatorH264Frame): Promise<void> => {
+ const sink = frameSink as ((nextFrame: IOSSimulatorH264Frame) => void | Promise<void>) | null;
+ if (!sink) throw new Error('native frame sink was not registered');
+ await sink(frame);
+ };
+ const streamNativeFrames = vi.fn<IOSSimulatorNativeSidecarDriver['streamNativeFrames']>(
+ async (options) => {
+ frameSink = options.onFrame;
+ await new Promise<void>((resolve) => {
+ if (options.signal?.aborted) resolve();
+ else options.signal?.addEventListener('abort', () => resolve(), { once: true });
+ });
+ return {
+ frameCount: 1,
+ byteCount: 4,
+ startedAt: '2026-08-07T00:00:00.000Z',
+ firstFrameAt: '2026-08-07T00:00:00.001Z',
+ endedAt: '2026-08-07T00:00:00.002Z',
+ endReason: 'aborted',
+ } satisfies IOSSimulatorStreamStats;
+ },
+ );
+ const nativeDriver = {
+ kind: 'native-sidecar',
+ capabilities: {
+ accessibility: false,
+ sessions: false,
+ jpegStream: false,
+ h264Stream: true,
+ bgraStream: true,
+ discreteInput: false,
+ continuousInput: true,
+ multiTouch: true,
+ },
+ configureNativeStream: vi.fn(async (profile) => profile),
+ streamNativeFrames,
+ } as unknown as IOSSimulatorNativeSidecarDriver;
+ const wdaDriver = {
+ getWindowSize: vi.fn(async () => ({ width: 393, height: 852 })),
+ getOrientation: vi.fn(async () => 'PORTRAIT' as const),
+ };
+ const capabilityReport = () => ({
+ nativeSidecar: { available: true },
+ routes: {
+ continuousInput: {
+ selected: 'native-sidecar',
+ fallback: false,
+ reason: null,
+ },
+ stream: {
+ h264: {
+ selected: 'native-sidecar',
+ fallback: false,
+ reason: null,
+ },
+ },
+ },
+ });
+ const running = {
+ instanceId: instance.instanceId,
+ simulatorUdid: instance.simulatorUdid,
+ pid: 42,
+ driver: wdaDriver,
+ driverSessionId: 'wda-session',
+ driverRouter: {
+ stream: vi.fn(() => ({
+ adapter: 'native-sidecar',
+ fallback: false,
+ reason: null,
+ source: nativeDriver,
+ })),
+ capabilityReport,
+ },
+ } as unknown as WdaRunningInstance;
+ const pushH264Frame = vi.fn();
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ driverManager: {
+ get: vi.fn(() => running),
+ start: vi.fn(async () => running),
+ stop: vi.fn(async () => undefined),
+ },
+ pushH264Frame,
+ });
+ const route = {
+ instanceId: instance.instanceId,
+ generation: instance.generation,
+ leaseId: instance.lease.id,
+ };
+
+ await expect(
+ host.setViewerVisibility('session-a', route, true, 'h264', undefined, 77, 'viewer-a'),
+ ).resolves.toMatchObject({ ok: true });
+ await vi.waitFor(() => expect(streamNativeFrames).toHaveBeenCalledOnce());
+ const firstFrame: IOSSimulatorH264Frame = {
+ encoding: 'h264',
+ format: 'annex-b',
+ bytes: Uint8Array.from([0, 0, 0, 1]),
+ receivedAt: '2026-08-07T00:00:00.001Z',
+ width: 393,
+ height: 852,
+ orientation: 'PORTRAIT',
+ scale: 1,
+ colorSpace: 'srgb',
+ timestampMicros: 1,
+ keyFrame: true,
+ };
+ await emitFrame(firstFrame);
+ expect(pushH264Frame).toHaveBeenCalledOnce();
+ expect(pushH264Frame).toHaveBeenCalledWith(
+ 77,
+ expect.objectContaining({
+ instanceId: instance.instanceId,
+ generation: instance.generation,
+ encoding: 'h264',
+ }),
+ );
+
+ await expect(
+ host.setViewerVisibility('session-a', route, true, 'h264', undefined, 88, 'viewer-b'),
+ ).resolves.toMatchObject({ ok: true });
+ await emitFrame({ ...firstFrame, timestampMicros: 2 });
+ expect(pushH264Frame).toHaveBeenCalledTimes(2);
+ expect(pushH264Frame).toHaveBeenLastCalledWith(
+ 88,
+ expect.objectContaining({ instanceId: instance.instanceId }),
+ );
+
+ await expect(
+ host.setViewerVisibility('session-a', route, true, 'h264', undefined, 88, 'viewer-c'),
+ ).resolves.toMatchObject({ ok: true });
+ await expect(
+ host.setViewerVisibility('session-a', route, false, 'h264', undefined, 88, 'viewer-b'),
+ ).resolves.toMatchObject({ ok: true, data: { ignored: true } });
+ await emitFrame({ ...firstFrame, timestampMicros: 3 });
+ expect(pushH264Frame).toHaveBeenCalledTimes(3);
+ expect(pushH264Frame).toHaveBeenLastCalledWith(
+ 88,
+ expect.objectContaining({ instanceId: instance.instanceId }),
+ );
+
+ const current = actor.getOwned('session-a', instance.instanceId);
+ await actor.stop({
+ sessionId: current.sessionId,
+ instanceId: current.instanceId,
+ generation: current.generation,
+ leaseId: current.lease.id,
+ });
+ await emitFrame({ ...firstFrame, timestampMicros: 4 });
+ expect(pushH264Frame).toHaveBeenCalledTimes(3);
+ await host.dispose();
+ });
+
it('selects H.264, falls back to JPEG, and re-arms native streaming on the next viewer request', async () => {
const lifecycle: IOSSimulatorSimctlLifecycle = {
findExact: vi.fn(),
@@ -2426,6 +2605,73 @@ describe('iOS Simulator host', () => {
expect(requestViewerFocus).not.toHaveBeenCalled();
});
+ it('releases scheduler capacity when a ready preexisting device is detached', async () => {
+ const lifecycle: IOSSimulatorSimctlLifecycle = {
+ findExact: vi.fn(),
+ bootExact: vi.fn(),
+ shutdownExact: vi.fn(async () => undefined),
+ createExact: vi.fn(),
+ deleteExact: vi.fn(),
+ };
+ const actor = new IOSSimulatorInstanceActor({
+ store: new IOSSimulatorOwnershipStore(),
+ lifecycle,
+ });
+ const resourceScheduler = testResourceScheduler();
+ let running: WdaRunningInstance | null = null;
+ const host = createIOSSimulatorHost({
+ actor,
+ lifecycle,
+ runtime: { inspect: vi.fn(async () => READY_REPORT) },
+ getSession: vi.fn(async (id) => localSession(id)),
+ resolveWorktreeRoot: vi.fn(async (workDir) => workDir),
+ resourceScheduler,
+ driverManager: {
+ get: vi.fn(() => running),
+ start: vi.fn(async (options) => {
+ running = {
+ instanceId: options.instanceId,
+ simulatorUdid: options.simulatorUdid,
+ pid: 42,
+ driver: {} as WdaRunningInstance['driver'],
+ driverSessionId: 'wda-session',
+ } as WdaRunningInstance;
+ return running;
+ }),
+ stop: vi.fn(async () => {
+ running = null;
+ }),
+ },
+ mediaCapture: {
+ discardInstance: vi.fn(async () => undefined),
+ } as unknown as IOSSimulatorMediaCaptureAdapter,
+ });
+
+ await expect(
+ host.callTool(
+ 'attach_device',
+ { udid: READY_REPORT.devices[0]!.udid },
+ { sessionId: 'session-a', origin: 'user' },
+ ),
+ ).resolves.toMatchObject({ ok: true });
+ expect(resourceScheduler.runningCount()).toBe(1);
+ const attached = actor.list('session-a')[0]!;
+
+ await expect(
+ host.callTool(
+ 'detach_device',
+ {
+ instanceId: attached.instanceId,
+ generation: attached.generation,
+ leaseId: attached.lease.id,
+ },
+ { sessionId: 'session-a', origin: 'user' },
+ ),
+ ).resolves.toMatchObject({ ok: true });
+ expect(resourceScheduler.runningCount()).toBe(0);
+ await host.dispose();
+ });
+
it('shares exact attachment and lifecycle state while rejecting another session', async () => {
const lifecycle: IOSSimulatorSimctlLifecycle = {
findExact: vi.fn(),
@@ -2573,12 +2819,13 @@ describe('iOS Simulator host', () => {
startRecording: vi.fn(),
stopRecording: vi.fn(),
} as unknown as IOSSimulatorMediaCaptureAdapter;
+ const resourceScheduler = testResourceScheduler();
const host = createIOSSimulatorHost({
actor,
lifecycle,
driverManager,
mediaCapture,
- resourceScheduler: testResourceScheduler(),
+ resourceScheduler,
runtime: { inspect: vi.fn(async () => READY_REPORT) },
getSession: vi.fn(async (id) => localSession(id)),
resolveWorktreeRoot: vi.fn(async (workDir) => workDir),
@@ -2593,6 +2840,7 @@ describe('iOS Simulator host', () => {
ok: true,
data: { instance: { sessionId: 'session-a', lifecycleState: 'ready' } },
});
+ expect(resourceScheduler.runningCount()).toBe(1);
expect(attached).not.toHaveProperty('data.instance.worktreeRoot');
await expect(
host.callTool(
@@ -3298,6 +3546,7 @@ describe('iOS Simulator host', () => {
),
).resolves.toMatchObject({ ok: true });
expect(discardInstance).toHaveBeenCalledTimes(2);
+ expect(resourceScheduler.runningCount()).toBe(0);
});
it('routes build, install, launch, terminate, and URL actions through injected adapters', async () => {
diff --git a/apps/desktop/src/main/mcp-integrations/computer.ts b/apps/desktop/src/main/mcp-integrations/computer.ts
index 2e2602e4a8..bcfcd7e40c 100644
--- a/apps/desktop/src/main/mcp-integrations/computer.ts
+++ b/apps/desktop/src/main/mcp-integrations/computer.ts
@@ -354,8 +354,6 @@ export interface ComputerDriverPermissionGrantResult {
export interface ComputerMcpDepsOptions {
isComputerUseEnabled?: (context?: ComputerMcpCallContext) => boolean;
- /** Host-issued grant; model-supplied MCP flags are never sufficient. */
- isExternalIosWorkflowAllowed?: (context?: ComputerMcpCallContext) => boolean;
/** Optional provider gate before the first status/tool request. */
prepareRuntimeBeforeUse?: () => Promise<void>;
}
@@ -3479,7 +3477,6 @@ export function getComputerMcpDeps(options: ComputerMcpDepsOptions = {}): Comput
executable: processInfo.executable,
};
},
- isExternalIosWorkflowAllowed: options.isExternalIosWorkflowAllowed,
callTool: async (name, args, context) => {
if (options.isComputerUseEnabled && !options.isComputerUseEnabled(context)) {
throw new ComputerDriverError('Computer Use is disabled in Settings.');
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
index e24f420973..4007e724da 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator.ts
@@ -83,6 +83,7 @@ import type {
} from '../../shared/ghost.js';
import { createLogger } from '../logger.js';
import { desktopSessionStorage } from '../maker-host/session-storage.js';
+import { isTrustedAppRendererWindow } from '../security/trustedAppRenderer.js';
import {
IOSSimulatorPackagedSidecarArtifactResolver,
verifyIOSSimulatorSidecarDigest,
@@ -174,6 +175,8 @@ export interface IOSSimulatorHostOptions {
requestViewerFocus?: (sessionId: string, instanceId: string) => void;
/** Main → renderer route diagnostics seam; injected in tests, broadcast by default. */
pushRouteStatus?: (status: IOSSimulatorPublicRouteStatus) => void;
+ /** Main → exact owning viewer frame seam; injected in tests, fail-closed by default. */
+ pushH264Frame?: (viewerWebContentsId: number, frame: IOSSimulatorLatestH264Frame) => void;
}
export interface IOSSimulatorHost {
@@ -205,6 +208,8 @@ export interface IOSSimulatorHost {
visible: boolean,
preferredEncoding?: 'jpeg' | 'h264',
fallbackReason?: 'native-decoder-fallback',
+ viewerWebContentsId?: number,
+ viewerToken?: string,
): Promise<IOSSimulatorHostResult>;
getLatestFrame(
sessionId: string,
@@ -241,29 +246,41 @@ 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'),
);
- let writeTail = Promise.resolve();
- const store = new IOSSimulatorOwnershipStore({
- maxInstancesPerSession: MAX_INSTANCES_PER_SESSION,
- initialInstances: registry.loadSync(),
- onChange: (instances) => {
- writeTail = writeTail
- .catch(() => undefined)
- .then(() => registry.save(instances))
- .catch((error) => {
- logger.warn('iOS Simulator ownership registry persistence failed', {
- error: error instanceof Error ? error.message : String(error),
- });
- });
- },
- });
- defaultRegistryFlush = () => writeTail;
+ const ownsWriterLease = registry.acquireWriterSync();
+ try {
+ const store = new IOSSimulatorOwnershipStore({
+ maxInstancesPerSession: MAX_INSTANCES_PER_SESSION,
+ initialInstances: ownsWriterLease ? registry.loadSync() : [],
+ assertMutationAllowed: () => registry.assertWriter(),
+ // 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());
+ };
+ defaultRegistryRelease = () => registry.releaseWriterSync();
+ return new IOSSimulatorInstanceActor({
+ store,
+ lifecycle,
+ });
+ } catch (error) {
+ registry.releaseWriterSync();
+ throw error;
+ }
+}
+
+function createInMemoryActor(lifecycle: IOSSimulatorSimctlLifecycle): IOSSimulatorInstanceActor {
return new IOSSimulatorInstanceActor({
- store,
+ store: new IOSSimulatorOwnershipStore({
+ maxInstancesPerSession: MAX_INSTANCES_PER_SESSION,
+ }),
lifecycle,
});
}
@@ -632,7 +649,9 @@ function safeHostError(
export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): IOSSimulatorHost {
const runtime = options.runtime ?? createIOSSimulatorRuntime();
const lifecycle = options.lifecycle ?? createIOSSimulatorSimctlLifecycle();
- const actor = options.actor ?? createDefaultActor(lifecycle);
+ // The exported factory is an isolated test/embedding seam. Only the module
+ // singleton below owns the profile-persisted registry and its writer lease.
+ const actor = options.actor ?? createInMemoryActor(lifecycle);
const grantStore = options.grantStore ?? new IOSSimulatorDeviceGrantStore();
/**
* A successful agent-created/agent-attached binding gets a host-issued,
@@ -643,38 +662,44 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
const agentControlLeases = new Map<string, string>();
const screenMaps = new IOSSimulatorScreenMapStore();
const framePump = options.framePump ?? new IOSSimulatorFramePump();
- const viewerSessions = new Map<string, string>();
+ const viewerSessions = new Map<
+ string,
+ { sessionId: string; webContentsId: number | null; viewerToken: string | null }
+ >();
+ const pushH264Frame =
+ options.pushH264Frame ??
+ ((viewerWebContentsId: number, frame: IOSSimulatorLatestH264Frame) => {
+ const target = BrowserWindow.getAllWindows().find(
+ (candidate) => candidate.webContents.id === viewerWebContentsId,
+ );
+ if (!target || !isTrustedAppRendererWindow(target)) return;
+ const bytes = frame.bytes.slice().buffer as ArrayBuffer;
+ target.webContents.send('maker:ios-simulator:h264-frame', {
+ frame: {
+ ...frame,
+ bytes,
+ },
+ });
+ });
const h264FramePump =
options.h264FramePump ??
new IOSSimulatorH264FramePump({
onFrame: (frame: IOSSimulatorLatestH264Frame) => {
- for (const window of BrowserWindow.getAllWindows()) {
- if (window.isDestroyed()) continue;
- try {
- const bytes = frame.bytes.slice().buffer as ArrayBuffer;
- window.webContents.send('maker:ios-simulator:h264-frame', {
- frame: {
- ...frame,
- bytes,
- },
- });
- } catch (error) {
- logger.debug('iOS Simulator H.264 frame push skipped', {
- error: error instanceof Error ? error.message : String(error),
- });
- }
- }
- const sessionId = viewerSessions.get(frame.instanceId);
- if (sessionId) {
- try {
- const instance = actor.getOwned(sessionId, frame.instanceId);
- if (instance.generation === frame.generation) {
- publishRouteStatusForInstance(instance);
- }
- } catch {
- // The instance may have been detached while the encoded frame was
- // already queued. The generation check above keeps this harmless.
+ const viewer = viewerSessions.get(frame.instanceId);
+ if (!viewer) return;
+ try {
+ const instance = actor.getOwned(viewer.sessionId, frame.instanceId);
+ if (instance.generation !== frame.generation) return;
+ if (viewer.webContentsId !== null) {
+ pushH264Frame(viewer.webContentsId, frame);
}
+ publishRouteStatusForInstance(instance);
+ } catch (error) {
+ // The instance or exact viewer may have disappeared while this frame
+ // was queued. Never fall back to broadcasting encoded screen data.
+ logger.debug('iOS Simulator H.264 frame push skipped', {
+ error: error instanceof Error ? error.message : String(error),
+ });
}
},
});
@@ -2497,8 +2522,15 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
preferredEncoding: 'jpeg' | 'h264',
orientation: 'PORTRAIT' | 'LANDSCAPE' = 'PORTRAIT',
fallbackReason: IOSSimulatorPublicRouteReasonCode = null,
+ viewerWebContentsId?: number,
+ viewerToken?: string,
): IOSSimulatorFramePumpSnapshot {
- viewerSessions.set(instance.instanceId, instance.sessionId);
+ const previousViewer = viewerSessions.get(instance.instanceId);
+ viewerSessions.set(instance.instanceId, {
+ sessionId: instance.sessionId,
+ webContentsId: viewerWebContentsId ?? previousViewer?.webContentsId ?? null,
+ viewerToken: viewerToken ?? previousViewer?.viewerToken ?? null,
+ });
viewerPreferredEncodings.set(instance.instanceId, fallbackReason ? 'h264' : preferredEncoding);
const nativeDriver = preferredEncoding === 'h264' ? nativeH264Driver(running) : null;
if (nativeDriver) {
@@ -2582,6 +2614,8 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
visible,
preferredEncoding = 'jpeg',
fallbackReason,
+ viewerWebContentsId,
+ viewerToken,
) {
try {
assertHostActive();
@@ -2593,6 +2627,23 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
? actor.heartbeat(mutationRoute)
: assertViewerDeactivationRoute(mutationRoute);
if (!visible) {
+ const activeViewer = viewerSessions.get(instance.instanceId);
+ if (
+ activeViewer &&
+ (activeViewer.sessionId !== resolved.sessionId ||
+ (activeViewer.webContentsId !== null &&
+ activeViewer.webContentsId !== viewerWebContentsId) ||
+ (activeViewer.viewerToken !== null && activeViewer.viewerToken !== viewerToken))
+ ) {
+ return {
+ ok: true,
+ data: {
+ stream: null,
+ ignored: true,
+ mutation: actor.mutationState(instance.instanceId),
+ },
+ };
+ }
const stream = stopViewerMedia(instance);
return {
ok: true,
@@ -2702,6 +2753,8 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
preferredEncoding,
viewport.orientation,
fallbackReason ?? null,
+ viewerWebContentsId,
+ viewerToken,
);
return {
ok: true,
@@ -3080,7 +3133,9 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
agentControlLeases.delete(route.instanceId);
return {
ok: true,
- data: instanceData(await actor.detach(route)),
+ data: instanceData(
+ await actor.detach(route, () => resourceScheduler.markStopped(route.instanceId)),
+ ),
};
}
if (name === 'get_screen_map') {
@@ -4460,7 +4515,7 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
);
}
const worktreeRoot = await resolveWorktreeRoot(resolved.session.workDir);
- const instance = actor.attach({
+ const instance = await actor.attachSerialized({
sessionId,
worktreeRoot,
sourceFingerprint: sourceFingerprint(worktreeRoot),
@@ -4548,7 +4603,11 @@ export function createIOSSimulatorHost(options: IOSSimulatorHostOptions = {}): I
};
}
-const defaultIOSSimulatorHost = createIOSSimulatorHost();
+const defaultIOSSimulatorLifecycle = createIOSSimulatorSimctlLifecycle();
+const defaultIOSSimulatorHost = createIOSSimulatorHost({
+ lifecycle: defaultIOSSimulatorLifecycle,
+ actor: createDefaultActor(defaultIOSSimulatorLifecycle),
+});
export function getIOSSimulatorSessionStatus(
sessionId: string,
@@ -4583,8 +4642,19 @@ export function setIOSSimulatorViewerVisibility(
route: Omit<IOSSimulatorMutationRoute, 'sessionId'>,
visible: boolean,
preferredEncoding?: 'jpeg' | 'h264',
+ fallbackReason?: 'native-decoder-fallback',
+ viewerWebContentsId?: number,
+ viewerToken?: string,
): Promise<IOSSimulatorHostResult> {
- return defaultIOSSimulatorHost.setViewerVisibility(sessionId, route, visible, preferredEncoding);
+ return defaultIOSSimulatorHost.setViewerVisibility(
+ sessionId,
+ route,
+ visible,
+ preferredEncoding,
+ fallbackReason,
+ viewerWebContentsId,
+ viewerToken,
+ );
}
export function setIOSSimulatorAgentMutationPaused(
@@ -4610,8 +4680,13 @@ export function reconcileIOSSimulatorOwnership(): Promise<void> {
return defaultIOSSimulatorHost.reconcileOwnership();
}
-export function disposeIOSSimulatorHost(): Promise<void> {
- return defaultIOSSimulatorHost.dispose();
+export async function disposeIOSSimulatorHost(): Promise<void> {
+ try {
+ await defaultIOSSimulatorHost.dispose();
+ await defaultRegistryFlush?.();
+ } finally {
+ defaultRegistryRelease?.();
+ }
}
export function setIOSSimulatorViewerStreamProfile(
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.tsx
index 7ed9c1bcf2..cab3e924fa 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
@@ -540,6 +540,7 @@ export function IOSSimulatorTabBody({
useEffect(() => {
if (!attachedInstance || attachedInstance.lifecycleState !== 'ready') return;
const route = { sessionId: ctx.sessionId, ...routeFor(attachedInstance) };
+ const viewerRoute = { ...route, viewerToken: window.crypto.randomUUID() };
let cancelled = false;
let polling = false;
let nextRecoveryAt = 0;
@@ -658,7 +659,7 @@ export function IOSSimulatorTabBody({
gate.attemptCount = attemptCount;
try {
return await window.electronAPI.maker.iosSimulator.setViewerVisibility({
- ...route,
+ ...viewerRoute,
visible: true,
preferredEncoding: 'h264',
});
@@ -676,7 +677,7 @@ export function IOSSimulatorTabBody({
};
const activateCompatibilityViewer = () =>
window.electronAPI.maker.iosSimulator.setViewerVisibility({
- ...route,
+ ...viewerRoute,
visible: true,
preferredEncoding: 'jpeg',
});
@@ -759,7 +760,7 @@ export function IOSSimulatorTabBody({
pollTimer = null;
void window.electronAPI.maker.iosSimulator
.setViewerVisibility({
- ...route,
+ ...viewerRoute,
visible: true,
preferredEncoding: 'jpeg',
fallbackReason: 'native-decoder-fallback',
@@ -783,7 +784,7 @@ export function IOSSimulatorTabBody({
) {
nextRecoveryAt = performance.now() + 3_000;
const recovered = await window.electronAPI.maker.iosSimulator.setViewerVisibility({
- ...route,
+ ...viewerRoute,
visible: true,
preferredEncoding,
...(nativeDecoderFallback
@@ -803,7 +804,7 @@ export function IOSSimulatorTabBody({
) {
nextRecoveryAt = performance.now() + 3_000;
const recovered = await window.electronAPI.maker.iosSimulator.setViewerVisibility({
- ...route,
+ ...viewerRoute,
visible: true,
preferredEncoding,
...(nativeDecoderFallback
@@ -850,7 +851,7 @@ export function IOSSimulatorTabBody({
? await attemptNativeRecovery().catch(() => null)
: await window.electronAPI.maker.iosSimulator
.setViewerVisibility({
- ...route,
+ ...viewerRoute,
visible: true,
preferredEncoding: 'h264',
})
@@ -859,7 +860,7 @@ export function IOSSimulatorTabBody({
result = nativeResult?.ok ? nativeResult : await activateCompatibilityViewer();
} else {
result = await window.electronAPI.maker.iosSimulator.setViewerVisibility({
- ...route,
+ ...viewerRoute,
visible: viewerVisible,
preferredEncoding,
});
@@ -880,7 +881,7 @@ export function IOSSimulatorTabBody({
document.removeEventListener('visibilitychange', recoverNativeOnForeground);
if (pollTimer !== null) window.clearTimeout(pollTimer);
void window.electronAPI.maker.iosSimulator
- .setViewerVisibility({ ...route, visible: false })
+ .setViewerVisibility({ ...viewerRoute, visible: false })
.catch(() => undefined);
};
}, [
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.tsx
index 8cc6ebb486..ec0ca700a4 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
@@ -741,14 +741,17 @@ describe('IOSSimulatorTabBody', () => {
);
await waitFor(() => {
- expect(api.setViewerVisibility).toHaveBeenCalledWith({
- sessionId: 'session-a',
- instanceId: 'instance-a',
- generation: 2,
- leaseId: 'lease-a',
- visible: false,
- preferredEncoding: 'jpeg',
- });
+ expect(api.setViewerVisibility).toHaveBeenCalledWith(
+ expect.objectContaining({
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 2,
+ leaseId: 'lease-a',
+ visible: false,
+ preferredEncoding: 'jpeg',
+ viewerToken: expect.any(String),
+ }),
+ );
expect(api.setStreamProfile).toHaveBeenCalledWith({
sessionId: 'session-a',
instanceId: 'instance-a',
diff --git a/apps/desktop/src/shared/iosSimulatorIpc.ts b/apps/desktop/src/shared/iosSimulatorIpc.ts
index 3587c5bd0b..023eecc4e7 100644
--- a/apps/desktop/src/shared/iosSimulatorIpc.ts
+++ b/apps/desktop/src/shared/iosSimulatorIpc.ts
@@ -117,9 +117,29 @@ export interface IOSSimulatorStatusRequest {
sessionId: string;
}
+/**
+ * Renderer-owned simulator actions. Agent-only build, install, URL, push, media,
+ * and diagnostic tools must stay behind the MCP approval/control boundary.
+ */
+export const IOS_SIMULATOR_RENDERER_TOOL_NAMES = [
+ 'attach_device',
+ 'detach_device',
+ 'start_instance',
+ 'stop_instance',
+ 'tap',
+ 'swipe',
+ 'type_text',
+ 'press_home',
+ 'set_orientation',
+ 'lock_screen',
+ 'unlock_screen',
+] as const satisfies readonly IOSSimulatorMcpToolName[];
+
+export type IOSSimulatorRendererToolName = (typeof IOS_SIMULATOR_RENDERER_TOOL_NAMES)[number];
+
export interface IOSSimulatorToolRequest {
sessionId: string;
- name: IOSSimulatorMcpToolName;
+ name: IOSSimulatorRendererToolName;
args: Record<string, unknown>;
}
@@ -147,6 +167,8 @@ export interface IOSSimulatorViewerRouteRequest {
export interface IOSSimulatorViewerVisibilityRequest extends IOSSimulatorViewerRouteRequest {
visible: boolean;
+ /** Identifies one renderer effect lifetime so a stale close cannot stop its replacement. */
+ viewerToken?: string;
preferredEncoding?: 'jpeg' | 'h264';
/** Renderer decoder failed after a native stream was selected. */
fallbackReason?: 'native-decoder-fallback';
diff --git a/docs/ios-simulator-integration-plan.md b/docs/ios-simulator-integration-plan.md
index 6fa39b6f92..e0c3cb23ef 100644
--- a/docs/ios-simulator-integration-plan.md
+++ b/docs/ios-simulator-integration-plan.md
@@ -18,7 +18,7 @@
- Desktop main 以真实 Session 记录为准,local macOS 会话可发现环境;缺失、已删除、SSH/remote Session 均 fail-closed。
- 新增默认启用、允许用户或项目显式关闭的 `cindy_ios_simulator` Agent provider,已经覆盖环境/设备/实例生命周期、screen map、基础输入、App build/install/launch/terminate/open URL、截图录屏和诊断工具。这样 iOS 请求可直接进入内嵌流程,而无需用户先为每个项目手动开启插件。
- 新增宿主级 shell hard gate:对 Agent 发出的 `open -a Simulator`、Simulator.app 直接可执行路径和会改变设备状态的 `xcrun simctl` 命令确定性拒绝,并将请求引导回 `cindy_ios_simulator`;只读 `simctl list/listapps`、Xcode build 和关闭外部 Simulator 不受影响。不同 Agent runtime 分别通过 PATH shim、command approval deny、item-start interrupt 或 pre-tool hook 覆盖 Full access 免审批命令与绝对路径兜底,避免旧 skill 或恢复会话绕过内嵌路由。
-- 新增 Computer MCP 外部 iOS 工作流硬闸:`launch_app(Xcode/Simulator)` 默认直接返回 `EMBEDDED_IOS_SIMULATOR_PREFERRED`;对 PID 定向的 click/hotkey/type 等修改操作先由 Desktop 使用 OS 进程快照解析真实 provenance,命中 Xcode 或 Simulator.app 时同样引导到 `cindy_ios_simulator`。只读窗口检查和其它应用操作保持可用;外部工作流的 MCP flag 只有在 Desktop 发放 host-issued 显式授权时才生效,模型自己填写 flag 不能绕过路由,flag 也不透传给 driver。
+- 新增 Computer MCP 外部 iOS 工作流硬闸:`launch_app(Xcode/Simulator)` 直接返回 `EMBEDDED_IOS_SIMULATOR_PREFERRED`;对 PID 定向的 click/hotkey/type 等修改操作先由 Desktop 使用 OS 进程快照解析真实 provenance,命中 Xcode 或 Simulator.app 时同样引导到 `cindy_ios_simulator`,无法验证 provenance 时 fail closed。只读窗口检查和其它已验证身份的应用操作保持可用;在 Cindy 建立 host-issued、按任务绑定的显式授权流之前,不向模型暴露外部 iOS 修改操作的 override 参数。
- 新增非 singleton 的 `ios-simulator` right-sidebar plugin;用户可手动打开、attach、启动/停止/解绑设备、管理 Agent 设备授权,并查看 main 内存中的实时 JPEG stream 与 FPS/连接状态。
- manual pane 与 Agent tool gate 分离:关闭实验性 Agent tool 不影响用户查看本机设备状态。
- 已覆盖 runtime parser、MCP envelope/session context、main host/IPC、远程会话拒绝、renderer 状态展示和 plugin provider 映射测试。
diff --git a/packages/ios-simulator-runtime/src/instance-actor.test.ts b/packages/ios-simulator-runtime/src/instance-actor.test.ts
index d7c4763105..38437a502d 100644
--- a/packages/ios-simulator-runtime/src/instance-actor.test.ts
+++ b/packages/ios-simulator-runtime/src/instance-actor.test.ts
@@ -267,24 +267,119 @@ describe("IOSSimulatorInstanceActor", () => {
it("keeps agent-booted devices for grace then shuts down and releases", async () => {
const harness = createHarness();
const started = await harness.actor.start(harness.route());
+ const onResourceReleased = vi.fn();
harness.setNow(2_000);
- const detached = await harness.actor.detach(harness.route(started));
+ const detached = await harness.actor.detach(
+ harness.route(started),
+ onResourceReleased,
+ );
expect(detached.viewerState).toBe("detached");
expect(detached.graceExpiresAt).toBe(new Date(602_000).toISOString());
expect(harness.scheduled).toHaveLength(1);
+ expect(onResourceReleased).not.toHaveBeenCalled();
await harness.scheduled[0]?.();
expect(harness.lifecycle.shutdownExact).toHaveBeenCalledWith(UDID);
expect(harness.store.get(detached.instanceId)).toBeNull();
+ expect(onResourceReleased).toHaveBeenCalledWith(
+ expect.objectContaining({ instanceId: detached.instanceId }),
+ );
});
it("releases preexisting devices immediately without shutdown", async () => {
const harness = createHarness({ booted: true });
- const detached = await harness.actor.detach(harness.route());
+ const onResourceReleased = vi.fn();
+ const detached = await harness.actor.detach(
+ harness.route(),
+ onResourceReleased,
+ );
expect(detached.bootProvenance).toBe("preexisting");
expect(harness.store.get(detached.instanceId)).toBeNull();
expect(harness.lifecycle.shutdownExact).not.toHaveBeenCalled();
+ expect(onResourceReleased).toHaveBeenCalledWith(detached);
+ });
+
+ it("keeps the resource counted when grace shutdown fails", async () => {
+ const harness = createHarness();
+ const started = await harness.actor.start(harness.route());
+ const onResourceReleased = vi.fn();
+ vi.mocked(harness.lifecycle.shutdownExact).mockRejectedValueOnce(
+ new Error("shutdown failed"),
+ );
+
+ const detached = await harness.actor.detach(
+ harness.route(started),
+ onResourceReleased,
+ );
+ await expect(harness.scheduled[0]?.()).rejects.toThrow("shutdown failed");
+
+ expect(harness.store.get(detached.instanceId)).not.toBeNull();
+ expect(onResourceReleased).not.toHaveBeenCalled();
+ });
+
+ it("cancels deferred resource release when a detached device is reattached", async () => {
+ const harness = createHarness();
+ const started = await harness.actor.start(harness.route());
+ const onResourceReleased = vi.fn();
+ await harness.actor.detach(harness.route(started), onResourceReleased);
+ expect(harness.scheduled).toHaveLength(1);
+
+ harness.actor.attach({
+ sessionId: "session-a",
+ worktreeRoot: "/tmp/session-a",
+ sourceFingerprint: "abc",
+ device: { ...DEVICE, state: "Booted" },
+ creationProvenance: "external",
+ bootProvenance: "agent-booted",
+ });
+
+ expect(harness.scheduled).toHaveLength(0);
+ expect(onResourceReleased).not.toHaveBeenCalled();
+ });
+
+ it("serializes reattachment behind an in-flight grace shutdown", async () => {
+ const harness = createHarness();
+ const started = await harness.actor.start(harness.route());
+ const onResourceReleased = vi.fn();
+ let finishShutdown: () => void = () => undefined;
+ vi.mocked(harness.lifecycle.shutdownExact).mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ finishShutdown = resolve;
+ }),
+ );
+ await harness.actor.detach(harness.route(started), onResourceReleased);
+
+ const cleanup = Promise.resolve(harness.scheduled[0]?.());
+ await vi.waitFor(() =>
+ expect(harness.lifecycle.shutdownExact).toHaveBeenCalledWith(UDID),
+ );
+ let reattached = false;
+ const reattach = harness.actor
+ .attachSerialized({
+ sessionId: "session-a",
+ worktreeRoot: "/tmp/session-a",
+ sourceFingerprint: "abc",
+ device: { ...DEVICE, state: "Booted" },
+ creationProvenance: "external",
+ bootProvenance: "agent-booted",
+ })
+ .then((instance) => {
+ reattached = true;
+ return instance;
+ });
+ await Promise.resolve();
+ expect(reattached).toBe(false);
+
+ finishShutdown();
+ await cleanup;
+ const next = await reattach;
+ expect(next.instanceId).not.toBe(started.instanceId);
+ expect(harness.store.listAll()).toEqual([next]);
+ expect(onResourceReleased).toHaveBeenCalledWith(
+ expect.objectContaining({ instanceId: started.instanceId }),
+ );
});
it("never deletes an external simulator", async () => {
diff --git a/packages/ios-simulator-runtime/src/instance-actor.ts b/packages/ios-simulator-runtime/src/instance-actor.ts
index d14667ada9..32de503abe 100644
--- a/packages/ios-simulator-runtime/src/instance-actor.ts
+++ b/packages/ios-simulator-runtime/src/instance-actor.ts
@@ -105,6 +105,40 @@ export class IOSSimulatorInstanceActor {
});
}
+ /** Serialize a user reattachment with any in-flight grace-period cleanup. */
+ attachSerialized(
+ input: IOSSimulatorAttachInput,
+ ): Promise<IOSSimulatorInstance> {
+ const normalizedUdid = input.device.udid.trim().toUpperCase();
+ const existing = this.#store
+ .listAll()
+ .find(
+ (instance) => instance.simulatorUdid.toUpperCase() === normalizedUdid,
+ );
+ return this.#serialize(
+ existing?.instanceId ?? `attach:${normalizedUdid}`,
+ async () => {
+ if (!existing) {
+ return this.attach(input);
+ }
+ const currentDevice = await this.#lifecycle.findExact(normalizedUdid);
+ if (currentDevice === null) {
+ throw new IOSSimulatorInstanceError(
+ "SIMULATOR_NOT_FOUND",
+ "The selected iOS Simulator device no longer exists.",
+ true,
+ );
+ }
+ return this.attach({
+ ...input,
+ // Some test adapters omit the optional lookup result. Production
+ // lifecycle adapters return either an exact device or null.
+ device: currentDevice ?? input.device,
+ });
+ },
+ );
+ }
+
create(
input: Omit<IOSSimulatorAttachInput, "device"> & {
name: string;
@@ -581,45 +615,70 @@ export class IOSSimulatorInstanceActor {
async detach(
route: IOSSimulatorMutationRoute,
+ onResourceReleased: (
+ instance: IOSSimulatorInstance,
+ ) => void | Promise<void> = () => undefined,
): Promise<IOSSimulatorInstance> {
- const instance = this.#store.assertMutationRoute(route);
- this.#cancelGrace.get(instance.instanceId)?.();
- this.#cancelGrace.delete(instance.instanceId);
- if (instance.bootProvenance !== "agent-booted") {
- return this.#store.release(instance.instanceId, instance.sessionId);
- }
-
- const graceExpiresAt = new Date(
- this.#clock.now() + this.#detachGraceMs,
- ).toISOString();
- const detached = this.#store.update(
- instance.instanceId,
- instance.sessionId,
- {
- viewerState: "detached",
- graceExpiresAt,
- },
- );
- const expectedGeneration = detached.generation;
- const cancel = this.#scheduler.schedule(this.#detachGraceMs, async () => {
- const current = this.#store.get(detached.instanceId);
- if (
- !current ||
- current.viewerState !== "detached" ||
- current.generation !== expectedGeneration ||
- current.graceExpiresAt !== graceExpiresAt
- ) {
- return;
- }
- try {
- await this.#lifecycle.shutdownExact(current.simulatorUdid);
- this.#store.release(current.instanceId, current.sessionId);
- } finally {
- this.#cancelGrace.delete(current.instanceId);
+ return this.#serialize(route.instanceId, async () => {
+ const instance = this.#store.assertMutationRoute(route);
+ this.#cancelGrace.get(instance.instanceId)?.();
+ this.#cancelGrace.delete(instance.instanceId);
+ if (instance.bootProvenance !== "agent-booted") {
+ const released = this.#store.release(
+ instance.instanceId,
+ instance.sessionId,
+ );
+ await onResourceReleased(released);
+ return released;
}
+
+ const graceExpiresAt = new Date(
+ this.#clock.now() + this.#detachGraceMs,
+ ).toISOString();
+ const detached = this.#store.update(
+ instance.instanceId,
+ instance.sessionId,
+ {
+ viewerState: "detached",
+ graceExpiresAt,
+ },
+ );
+ const expectedGeneration = detached.generation;
+ const cancel = this.#scheduler.schedule(this.#detachGraceMs, async () => {
+ try {
+ await this.#serialize(detached.instanceId, async () => {
+ const current = this.#store.get(detached.instanceId);
+ if (
+ !current ||
+ current.viewerState !== "detached" ||
+ current.generation !== expectedGeneration ||
+ current.graceExpiresAt !== graceExpiresAt
+ ) {
+ return;
+ }
+ await this.#lifecycle.shutdownExact(current.simulatorUdid);
+ const afterShutdown = this.#store.get(detached.instanceId);
+ if (
+ !afterShutdown ||
+ afterShutdown.viewerState !== "detached" ||
+ afterShutdown.generation !== expectedGeneration ||
+ afterShutdown.graceExpiresAt !== graceExpiresAt
+ ) {
+ return;
+ }
+ const released = this.#store.release(
+ afterShutdown.instanceId,
+ afterShutdown.sessionId,
+ );
+ await onResourceReleased(released);
+ });
+ } finally {
+ this.#cancelGrace.delete(detached.instanceId);
+ }
+ });
+ this.#cancelGrace.set(detached.instanceId, cancel);
+ return detached;
});
- this.#cancelGrace.set(detached.instanceId, cancel);
- return detached;
}
async delete(
diff --git a/packages/ios-simulator-runtime/src/native-sidecar/layout.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/layout.test.ts
index dac578eb90..248f171b05 100644
--- a/packages/ios-simulator-runtime/src/native-sidecar/layout.test.ts
+++ b/packages/ios-simulator-runtime/src/native-sidecar/layout.test.ts
@@ -1,3 +1,5 @@
+import path from "node:path";
+
import { describe, expect, it } from "vitest";
import {
@@ -13,7 +15,13 @@ describe("native sidecar artifact layout", () => {
"arm64",
),
).toBe(
- "/workspace/apps/desktop/resources/ios-simulator/native/arm64/ios-simulator-sidecar",
+ path.join(
+ "/workspace/apps/desktop/resources",
+ "ios-simulator",
+ "native",
+ "arm64",
+ "ios-simulator-sidecar",
+ ),
);
});
@@ -23,7 +31,13 @@ describe("native sidecar artifact layout", () => {
"/Applications/Cindy.app/Contents/Resources",
),
).toBe(
- "/Applications/Cindy.app/Contents/Helpers/Cindy iOS Simulator Helper.app/Contents/MacOS/ios-simulator-sidecar",
+ path.join(
+ "/Applications/Cindy.app/Contents/Helpers",
+ "Cindy iOS Simulator Helper.app",
+ "Contents",
+ "MacOS",
+ "ios-simulator-sidecar",
+ ),
);
});
});
diff --git a/packages/ios-simulator-runtime/src/native-sidecar/process-manager.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/process-manager.test.ts
index 214847ed21..ba92073159 100644
--- a/packages/ios-simulator-runtime/src/native-sidecar/process-manager.test.ts
+++ b/packages/ios-simulator-runtime/src/native-sidecar/process-manager.test.ts
@@ -886,7 +886,13 @@ describe("IOSSimulatorNativeSidecarProcessManager", () => {
"arm64",
),
).toBe(
- "/Applications/Cindy.app/Contents/Resources/ios-simulator/native/arm64/ios-simulator-sidecar",
+ path.join(
+ "/Applications/Cindy.app/Contents/Resources",
+ "ios-simulator",
+ "native",
+ "arm64",
+ "ios-simulator-sidecar",
+ ),
);
expect(() =>
resolveIOSSimulatorNativeSidecarBinary("relative", "arm64"),
@@ -896,7 +902,13 @@ describe("IOSSimulatorNativeSidecarProcessManager", () => {
"/Applications/Cindy.app/Contents/Resources",
),
).toBe(
- "/Applications/Cindy.app/Contents/Helpers/Cindy iOS Simulator Helper.app/Contents/MacOS/ios-simulator-sidecar",
+ path.join(
+ "/Applications/Cindy.app/Contents/Helpers",
+ "Cindy iOS Simulator Helper.app",
+ "Contents",
+ "MacOS",
+ "ios-simulator-sidecar",
+ ),
);
expect(() => resolveIOSSimulatorPackagedSidecarBinary("relative")).toThrow(
"must be absolute",
diff --git a/packages/ios-simulator-runtime/src/native-sidecar/provider.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/provider.test.ts
index dd11c60d6b..2ddeede2a2 100644
--- a/packages/ios-simulator-runtime/src/native-sidecar/provider.test.ts
+++ b/packages/ios-simulator-runtime/src/native-sidecar/provider.test.ts
@@ -1,3 +1,5 @@
+import path from "node:path";
+
import {
createIOSSimulatorNativeDevelopmentAdmissionPolicy,
evaluateIOSSimulatorNativeCapabilityAdmission,
@@ -46,7 +48,7 @@ const CAPABILITIES = Object.freeze({
function bundledArtifact(
patch: Partial<IOSSimulatorSidecarArtifactDescriptor> = {},
): IOSSimulatorSidecarArtifactDescriptor {
- return {
+ const descriptor: IOSSimulatorSidecarArtifactDescriptor = {
artifactId: "cindy.ios-simulator-sidecar",
source: "bundled",
version: "1.0.0",
@@ -56,6 +58,10 @@ function bundledArtifact(
sha256: null,
...patch,
};
+ return {
+ ...descriptor,
+ executablePath: path.normalize(descriptor.executablePath),
+ };
}
function developmentPolicy(
diff --git a/packages/ios-simulator-runtime/src/native-sidecar/sandbox.test.ts b/packages/ios-simulator-runtime/src/native-sidecar/sandbox.test.ts
index 979ea1a344..3abf8f9306 100644
--- a/packages/ios-simulator-runtime/src/native-sidecar/sandbox.test.ts
+++ b/packages/ios-simulator-runtime/src/native-sidecar/sandbox.test.ts
@@ -15,6 +15,8 @@ import {
const execFileAsync = promisify(execFile);
const UDID = "A1B2C3D4-1111-2222-3333-444455556666";
+const DARWIN_TEMPORARY_ROOT = "/private/tmp";
+const DARWIN_TEMPORARY_DIRECTORY = `${DARWIN_TEMPORARY_ROOT}/cindy-ios-sandbox-test`;
const temporaryDirectories: string[] = [];
async function temporaryDirectory(): Promise<string> {
@@ -35,11 +37,11 @@ afterEach(async () => {
describe("IOSSimulator native sidecar sandbox", () => {
it("builds a deny-by-default, stdio-only profile without network or broad user-data access", async () => {
- const temp = await temporaryDirectory();
+ const temp = DARWIN_TEMPORARY_DIRECTORY;
const policy = createIOSSimulatorNativeSidecarSandboxPolicy({
platform: "darwin",
homeDirectory: "/Users/example",
- temporaryRoot: os.tmpdir(),
+ temporaryRoot: DARWIN_TEMPORARY_ROOT,
developerDirectory: "/Applications/Xcode.app/Contents/Developer",
});
const profile = createIOSSimulatorNativeSidecarSandboxProfile({
@@ -59,7 +61,7 @@ describe("IOSSimulator native sidecar sandbox", () => {
);
expect(profile).toContain('(iokit-user-client-class "AGXDeviceUserClient"');
expect(profile).toContain(
- `(subpath ${JSON.stringify(path.join("/Users/example", "Library", "Developer", "CoreSimulator"))})`,
+ `(subpath ${JSON.stringify(path.posix.join("/Users/example", "Library", "Developer", "CoreSimulator"))})`,
);
expect(profile).not.toContain("(allow network");
expect(profile).not.toContain("com.apple.bsd.dirhelper");
@@ -74,7 +76,7 @@ describe("IOSSimulator native sidecar sandbox", () => {
});
it("rejects non-macOS hosts, ambiguous device identities, and temp-directory escapes", async () => {
- const temp = await temporaryDirectory();
+ const temp = DARWIN_TEMPORARY_DIRECTORY;
const policy = createIOSSimulatorNativeSidecarSandboxPolicy({
platform: "linux",
homeDirectory: "/home/example",
@@ -94,7 +96,12 @@ describe("IOSSimulator native sidecar sandbox", () => {
}),
);
- const macPolicy = { ...policy, platform: "darwin" as const };
+ const macPolicy = createIOSSimulatorNativeSidecarSandboxPolicy({
+ platform: "darwin",
+ homeDirectory: "/Users/example",
+ temporaryRoot: DARWIN_TEMPORARY_ROOT,
+ developerDirectory: "/Applications/Xcode.app/Contents/Developer",
+ });
expect(() =>
createIOSSimulatorNativeSidecarSandboxProfile({
policy: macPolicy,
@@ -118,12 +125,12 @@ describe("IOSSimulator native sidecar sandbox", () => {
});
it("passes only the private temp directory and selected developer directory to the sandboxed process", async () => {
- const temp = await temporaryDirectory();
+ const temp = DARWIN_TEMPORARY_DIRECTORY;
const plan = createIOSSimulatorNativeSidecarSandboxLaunchPlan({
policy: createIOSSimulatorNativeSidecarSandboxPolicy({
platform: "darwin",
homeDirectory: "/Users/example",
- temporaryRoot: os.tmpdir(),
+ temporaryRoot: DARWIN_TEMPORARY_ROOT,
developerDirectory: "/Applications/Xcode.app/Contents/Developer",
}),
binaryPath: "/opt/cindy/ios-simulator-sidecar",
@@ -148,8 +155,8 @@ describe("IOSSimulator native sidecar sandbox", () => {
LANG: "en_US.UTF-8",
HOME: "/Users/example",
DEVELOPER_DIR: "/Applications/Xcode.app/Contents/Developer",
- TMPDIR: `${temp}${path.sep}`,
- CINDY_IOS_SIDECAR_METAL_CACHE_DIR: path.join(temp, "metal-cache"),
+ TMPDIR: `${temp}${path.posix.sep}`,
+ CINDY_IOS_SIDECAR_METAL_CACHE_DIR: path.posix.join(temp, "metal-cache"),
});
expect(plan.diagnostics).toMatchObject({
required: true,
diff --git a/packages/ios-simulator-runtime/src/native-sidecar/sandbox.ts b/packages/ios-simulator-runtime/src/native-sidecar/sandbox.ts
index 7d7321670d..7154a08d17 100644
--- a/packages/ios-simulator-runtime/src/native-sidecar/sandbox.ts
+++ b/packages/ios-simulator-runtime/src/native-sidecar/sandbox.ts
@@ -72,9 +72,18 @@ export class IOSSimulatorNativeSidecarSandboxError extends Error {
const EXACT_SIMULATOR_UDID =
/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/;
-function requireAbsolutePath(value: string, name: string): string {
- const normalized = path.normalize(value);
- if (!path.isAbsolute(normalized)) {
+type PathDialect = Pick<
+ typeof path.posix,
+ "isAbsolute" | "join" | "normalize" | "relative" | "sep"
+>;
+
+function requireAbsolutePath(
+ value: string,
+ name: string,
+ dialect: PathDialect = path,
+): string {
+ const normalized = dialect.normalize(value);
+ if (!dialect.isAbsolute(normalized)) {
throw new IOSSimulatorNativeSidecarSandboxError(
"SANDBOX_PROFILE_INVALID",
`${name} must be absolute`,
@@ -87,14 +96,15 @@ function requireContainedPath(
value: string,
parent: string,
name: string,
+ dialect: PathDialect = path,
): string {
- const normalized = requireAbsolutePath(value, name);
- const relative = path.relative(parent, normalized);
+ const normalized = requireAbsolutePath(value, name, dialect);
+ const relative = dialect.relative(parent, normalized);
if (
relative === "" ||
- relative.startsWith(`..${path.sep}`) ||
+ relative.startsWith(`..${dialect.sep}`) ||
relative === ".." ||
- path.isAbsolute(relative)
+ dialect.isAbsolute(relative)
) {
throw new IOSSimulatorNativeSidecarSandboxError(
"SANDBOX_PROFILE_INVALID",
@@ -119,17 +129,21 @@ function pathRule(
export function createIOSSimulatorNativeSidecarSandboxPolicy(
input: IOSSimulatorNativeSidecarSandboxPolicyInput = {},
): IOSSimulatorNativeSidecarSandboxPolicy {
+ const platform = input.platform ?? process.platform;
+ const dialect: PathDialect = platform === "darwin" ? path.posix : path;
const homeDirectory = requireAbsolutePath(
input.homeDirectory ?? os.homedir(),
"homeDirectory",
+ dialect,
);
return Object.freeze({
required: input.required ?? true,
- platform: input.platform ?? process.platform,
+ platform,
sandboxExecutablePath: requireAbsolutePath(
input.sandboxExecutablePath ??
IOS_SIMULATOR_NATIVE_SIDECAR_SANDBOX_EXECUTABLE,
"sandboxExecutablePath",
+ dialect,
),
homeDirectory,
developerDirectory: requireAbsolutePath(
@@ -137,15 +151,18 @@ export function createIOSSimulatorNativeSidecarSandboxPolicy(
process.env.DEVELOPER_DIR ??
"/Applications/Xcode.app/Contents/Developer",
"developerDirectory",
+ dialect,
),
coreSimulatorRoot: requireAbsolutePath(
input.coreSimulatorRoot ??
- path.join(homeDirectory, "Library", "Developer", "CoreSimulator"),
+ dialect.join(homeDirectory, "Library", "Developer", "CoreSimulator"),
"coreSimulatorRoot",
+ dialect,
),
temporaryRoot: requireAbsolutePath(
input.temporaryRoot ?? os.tmpdir(),
"temporaryRoot",
+ dialect,
),
});
}
@@ -202,23 +219,32 @@ export function createIOSSimulatorNativeSidecarSandboxProfile(
"Native sidecar sandboxing is supported only on macOS",
);
}
- const binaryPath = requireAbsolutePath(input.binaryPath, "binaryPath");
+ const dialect = path.posix;
+ const binaryPath = requireAbsolutePath(
+ input.binaryPath,
+ "binaryPath",
+ dialect,
+ );
const developerDirectory = requireAbsolutePath(
policy.developerDirectory,
"developerDirectory",
+ dialect,
);
const coreSimulatorRoot = requireAbsolutePath(
policy.coreSimulatorRoot,
"coreSimulatorRoot",
+ dialect,
);
const temporaryRoot = requireAbsolutePath(
policy.temporaryRoot,
"temporaryRoot",
+ dialect,
);
const temporaryDirectory = requireContainedPath(
input.temporaryDirectory,
temporaryRoot,
"temporaryDirectory",
+ dialect,
);
const simulatorUdid = input.simulatorUdid.toUpperCase();
if (!EXACT_SIMULATOR_UDID.test(simulatorUdid)) {
@@ -360,8 +386,8 @@ export function createIOSSimulatorNativeSidecarSandboxLaunchPlan(
LANG: input.environment.LANG ?? "en_US.UTF-8",
HOME: input.policy.homeDirectory,
DEVELOPER_DIR: input.policy.developerDirectory,
- TMPDIR: `${input.temporaryDirectory}${path.sep}`,
- CINDY_IOS_SIDECAR_METAL_CACHE_DIR: path.join(
+ TMPDIR: `${input.temporaryDirectory}${path.posix.sep}`,
+ CINDY_IOS_SIDECAR_METAL_CACHE_DIR: path.posix.join(
input.temporaryDirectory,
"metal-cache",
),
diff --git a/packages/ios-simulator-runtime/src/ownership-registry-file.test.ts b/packages/ios-simulator-runtime/src/ownership-registry-file.test.ts
index d1ed0fd6ea..5e92102d36 100644
--- a/packages/ios-simulator-runtime/src/ownership-registry-file.test.ts
+++ b/packages/ios-simulator-runtime/src/ownership-registry-file.test.ts
@@ -1,10 +1,13 @@
-import { mkdtemp, readFile, rm } from "node:fs/promises";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
-import { IOSSimulatorOwnershipRegistryFile } from "./ownership-registry-file.js";
+import {
+ IOSSimulatorOwnershipRegistryFile,
+ type IOSSimulatorRegistryWriterLeaseFactory,
+} from "./ownership-registry-file.js";
import { IOSSimulatorOwnershipStore } from "./ownership-store.js";
import type { IOSSimulatorDevice } from "./types.js";
@@ -21,13 +24,33 @@ const DEVICE: IOSSimulatorDevice = {
lastBootedAt: null,
};
+function createWriterLeaseFactory(): IOSSimulatorRegistryWriterLeaseFactory {
+ const heldPaths = new Set<string>();
+ return (lockPath) => {
+ if (heldPaths.has(lockPath)) return null;
+ heldPaths.add(lockPath);
+ let held = true;
+ return {
+ isHeld: () => held,
+ release: () => {
+ if (!held) return;
+ held = false;
+ heldPaths.delete(lockPath);
+ },
+ };
+ };
+}
+
describe("IOSSimulatorOwnershipRegistryFile", () => {
it("round-trips a bounded ownership snapshot atomically", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-registry-"));
try {
+ const acquireWriterLease = createWriterLeaseFactory();
const registry = new IOSSimulatorOwnershipRegistryFile(
path.join(root, "registry.json"),
+ { acquireWriterLease },
);
+ expect(registry.acquireWriterSync()).toBe(true);
let snapshot: ReturnType<IOSSimulatorOwnershipStore["listAll"]> = [];
const store = new IOSSimulatorOwnershipStore({
createId: (() => {
@@ -62,11 +85,12 @@ describe("IOSSimulatorOwnershipRegistryFile", () => {
const root = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-registry-"));
try {
const filePath = path.join(root, "registry.json");
- const registry = new IOSSimulatorOwnershipRegistryFile(filePath);
+ const registry = new IOSSimulatorOwnershipRegistryFile(filePath, {
+ acquireWriterLease: createWriterLeaseFactory(),
+ });
+ expect(registry.acquireWriterSync()).toBe(true);
await registry.save([]);
- await (
- await import("node:fs/promises")
- ).writeFile(
+ await writeFile(
filePath,
JSON.stringify({
version: 999,
@@ -90,4 +114,81 @@ describe("IOSSimulatorOwnershipRegistryFile", () => {
await rm(root, { recursive: true, force: true });
}
});
+
+ it("admits only one profile writer and rejects loser reads and writes", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-registry-"));
+ try {
+ const filePath = path.join(root, "registry.json");
+ const acquireWriterLease = createWriterLeaseFactory();
+ const first = new IOSSimulatorOwnershipRegistryFile(filePath, {
+ acquireWriterLease,
+ });
+ const second = new IOSSimulatorOwnershipRegistryFile(filePath, {
+ acquireWriterLease,
+ });
+
+ expect(first.acquireWriterSync()).toBe(true);
+ expect(second.acquireWriterSync()).toBe(false);
+ expect(() => second.loadSync()).toThrowError(
+ expect.objectContaining({ code: "DEVICE_BUSY" }),
+ );
+ expect(() => second.saveSync([])).toThrowError(
+ expect.objectContaining({ code: "DEVICE_BUSY" }),
+ );
+
+ first.releaseWriterSync();
+ expect(second.acquireWriterSync()).toBe(true);
+ expect(second.isWriter).toBe(true);
+ second.releaseWriterSync();
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+
+ it("releases a writer lease without letting an old owner affect its replacement", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-registry-"));
+ try {
+ const filePath = path.join(root, "registry.json");
+ const acquireWriterLease = createWriterLeaseFactory();
+ const first = new IOSSimulatorOwnershipRegistryFile(filePath, {
+ acquireWriterLease,
+ });
+ expect(first.acquireWriterSync()).toBe(true);
+
+ const replacement = new IOSSimulatorOwnershipRegistryFile(filePath, {
+ acquireWriterLease,
+ });
+ expect(replacement.acquireWriterSync()).toBe(false);
+ first.releaseWriterSync();
+ expect(replacement.acquireWriterSync()).toBe(true);
+ expect(replacement.isWriter).toBe(true);
+
+ // A delayed release from the old owner must not remove the replacement.
+ first.releaseWriterSync();
+ expect(replacement.isWriter).toBe(true);
+ replacement.releaseWriterSync();
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+
+ const itMac = process.platform === "darwin" ? it : it.skip;
+ itMac(
+ "holds the production advisory lock until the parent descriptor closes",
+ async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-registry-"));
+ try {
+ const filePath = path.join(root, "registry.json");
+ const first = new IOSSimulatorOwnershipRegistryFile(filePath);
+ const second = new IOSSimulatorOwnershipRegistryFile(filePath);
+ expect(first.acquireWriterSync()).toBe(true);
+ expect(second.acquireWriterSync()).toBe(false);
+ first.releaseWriterSync();
+ expect(second.acquireWriterSync()).toBe(true);
+ second.releaseWriterSync();
+ } 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.ts
index c3c275d0e2..553e561754 100644
--- a/packages/ios-simulator-runtime/src/ownership-registry-file.ts
+++ b/packages/ios-simulator-runtime/src/ownership-registry-file.ts
@@ -1,7 +1,17 @@
-import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
-import { readFileSync } from "node:fs";
+import { spawnSync } from "node:child_process";
+import { randomUUID } from "node:crypto";
+import {
+ closeSync,
+ mkdirSync,
+ openSync,
+ readFileSync,
+ renameSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
import path from "node:path";
+import { IOSSimulatorInstanceError } from "./instance-errors.js";
import type { IOSSimulatorInstance } from "./instance-types.js";
const REGISTRY_VERSION = 1;
@@ -12,6 +22,20 @@ export interface IOSSimulatorRegistrySnapshot {
instances: IOSSimulatorInstance[];
}
+export interface IOSSimulatorRegistryWriterLease {
+ isHeld(): boolean;
+ release(): void;
+}
+
+export type IOSSimulatorRegistryWriterLeaseFactory = (
+ lockPath: string,
+) => IOSSimulatorRegistryWriterLease | null;
+
+export interface IOSSimulatorOwnershipRegistryFileOptions {
+ /** Cross-platform deterministic seam; production uses macOS lockf. */
+ acquireWriterLease?: IOSSimulatorRegistryWriterLeaseFactory;
+}
+
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
@@ -81,29 +105,111 @@ function parseSnapshot(value: unknown): IOSSimulatorInstance[] {
return instances;
}
+/**
+ * macOS `lockf` uses BSD flock semantics. Acquiring through an inherited file
+ * descriptor leaves the lock attached to the parent's open file description
+ * after the short-lived lockf process exits. Closing the descriptor (including
+ * process exit/crash) releases the lease without stale-file deletion races.
+ */
+function acquireDarwinWriterLease(
+ lockPath: string,
+): IOSSimulatorRegistryWriterLease | null {
+ if (process.platform !== "darwin") return null;
+ let fd: number | null = null;
+ try {
+ fd = openSync(lockPath, "a+", 0o600);
+ const result = spawnSync("/usr/bin/lockf", ["-s", "-t", "0", "3"], {
+ stdio: ["ignore", "ignore", "ignore", fd],
+ });
+ if (result.status !== 0) {
+ closeSync(fd);
+ return null;
+ }
+ let held = true;
+ return {
+ isHeld: () => held,
+ release: () => {
+ if (!held || fd === null) return;
+ held = false;
+ closeSync(fd);
+ fd = null;
+ },
+ };
+ } catch {
+ if (fd !== null) {
+ try {
+ closeSync(fd);
+ } catch {
+ // The acquisition failure remains authoritative.
+ }
+ }
+ return null;
+ }
+}
+
/** Atomic, schema-bounded registry used to survive a Cindy main-process restart. */
export class IOSSimulatorOwnershipRegistryFile {
readonly #filePath: string;
+ readonly #lockPath: string;
+ readonly #acquireWriterLease: IOSSimulatorRegistryWriterLeaseFactory;
+ #writerLease: IOSSimulatorRegistryWriterLease | null = null;
- constructor(filePath: string) {
+ constructor(
+ filePath: string,
+ options: IOSSimulatorOwnershipRegistryFileOptions = {},
+ ) {
this.#filePath = filePath;
+ this.#lockPath = `${filePath}.writer.lock`;
+ this.#acquireWriterLease =
+ options.acquireWriterLease ?? acquireDarwinWriterLease;
}
get filePath(): string {
return this.#filePath;
}
- async load(): Promise<IOSSimulatorInstance[]> {
- try {
- const raw = await readFile(this.#filePath, "utf8");
- return parseSnapshot(JSON.parse(raw) as unknown);
- } catch {
- return [];
+ get lockPath(): string {
+ return this.#lockPath;
+ }
+
+ get isWriter(): boolean {
+ return this.#writerLease?.isHeld() === true;
+ }
+
+ /** Claim the profile-scoped writer with a kernel-owned advisory lock. */
+ acquireWriterSync(): boolean {
+ if (this.isWriter) return true;
+ this.#writerLease?.release();
+ this.#writerLease = null;
+ mkdirSync(path.dirname(this.#filePath), { recursive: true });
+ this.#writerLease = this.#acquireWriterLease(this.#lockPath);
+ return this.isWriter;
+ }
+
+ assertWriter(): void {
+ if (!this.isWriter) {
+ this.#writerLease?.release();
+ this.#writerLease = null;
+ throw new IOSSimulatorInstanceError(
+ "DEVICE_BUSY",
+ "Another Cindy process is managing iOS Simulator ownership for this profile.",
+ true,
+ );
}
}
+ releaseWriterSync(): void {
+ this.#writerLease?.release();
+ this.#writerLease = null;
+ }
+
+ async load(): Promise<IOSSimulatorInstance[]> {
+ return this.loadSync();
+ }
+
/** Startup-only synchronous read; callers should use load() after initialization. */
loadSync(): IOSSimulatorInstance[] {
+ this.assertWriter();
try {
return parseSnapshot(
JSON.parse(readFileSync(this.#filePath, "utf8")) as unknown,
@@ -114,6 +220,11 @@ export class IOSSimulatorOwnershipRegistryFile {
}
async save(instances: IOSSimulatorInstance[]): Promise<void> {
+ this.saveSync(instances);
+ }
+
+ saveSync(instances: IOSSimulatorInstance[]): void {
+ this.assertWriter();
const snapshot: IOSSimulatorRegistrySnapshot = {
version: REGISTRY_VERSION,
savedAt: new Date().toISOString(),
@@ -122,12 +233,21 @@ export class IOSSimulatorOwnershipRegistryFile {
lease: { ...instance.lease },
})),
};
- await mkdir(path.dirname(this.#filePath), { recursive: true });
- const tempPath = `${this.#filePath}.${process.pid}.tmp`;
- await writeFile(tempPath, JSON.stringify(snapshot), {
- encoding: "utf8",
- mode: 0o600,
- });
- await rename(tempPath, this.#filePath);
+ mkdirSync(path.dirname(this.#filePath), { recursive: true });
+ const tempPath = `${this.#filePath}.${process.pid}.${randomUUID()}.tmp`;
+ try {
+ writeFileSync(tempPath, JSON.stringify(snapshot), {
+ encoding: "utf8",
+ mode: 0o600,
+ });
+ this.assertWriter();
+ renameSync(tempPath, this.#filePath);
+ } finally {
+ try {
+ rmSync(tempPath, { force: true });
+ } catch {
+ // A failed write already surfaces to the caller; cleanup is best effort.
+ }
+ }
}
}
diff --git a/packages/ios-simulator-runtime/src/ownership-store.test.ts b/packages/ios-simulator-runtime/src/ownership-store.test.ts
index 5465765efe..4ddc140e94 100644
--- a/packages/ios-simulator-runtime/src/ownership-store.test.ts
+++ b/packages/ios-simulator-runtime/src/ownership-store.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
+import { IOSSimulatorInstanceError } from "./instance-errors.js";
import { IOSSimulatorOwnershipStore } from "./ownership-store.js";
import type { IOSSimulatorDevice } from "./types.js";
@@ -92,6 +93,10 @@ describe("IOSSimulatorOwnershipStore", () => {
});
const instance = store.attach(input("session-a"));
+ now = 1_100;
+ const coalesced = store.heartbeat(instance.instanceId, "session-a");
+ expect(coalesced.lease).toEqual(instance.lease);
+
now = 1_500;
const active = store.heartbeat(instance.instanceId, "session-a");
expect(active.lease.id).toBe(instance.lease.id);
@@ -103,6 +108,28 @@ describe("IOSSimulatorOwnershipStore", () => {
expect(replaced.lease.expiresAt).toBe(new Date(4_000).toISOString());
});
+ it("fails a coalesced heartbeat after the persisted writer lease is lost", () => {
+ let writerAvailable = true;
+ const store = new IOSSimulatorOwnershipStore({
+ assertMutationAllowed: () => {
+ if (!writerAvailable) {
+ throw new IOSSimulatorInstanceError(
+ "DEVICE_BUSY",
+ "writer unavailable",
+ true,
+ );
+ }
+ },
+ });
+ const instance = store.attach(input("session-a"));
+ writerAvailable = false;
+
+ expect(() =>
+ store.heartbeat(instance.instanceId, instance.sessionId),
+ ).toThrowError(expect.objectContaining({ code: "DEVICE_BUSY" }));
+ expect(store.get(instance.instanceId)).toEqual(instance);
+ });
+
it("can raise the per-session cap without weakening global ownership", () => {
let id = 0;
const store = new IOSSimulatorOwnershipStore({
@@ -119,4 +146,58 @@ describe("IOSSimulatorOwnershipStore", () => {
}
expect(store.listForSession("session-a")).toHaveLength(4);
});
+
+ it("fails before mutation when the persisted writer lease is unavailable", () => {
+ const store = new IOSSimulatorOwnershipStore({
+ assertMutationAllowed: () => {
+ throw new IOSSimulatorInstanceError(
+ "DEVICE_BUSY",
+ "writer unavailable",
+ true,
+ );
+ },
+ });
+
+ expect(() => store.attach(input("session-a"))).toThrowError(
+ expect.objectContaining({ code: "DEVICE_BUSY" }),
+ );
+ expect(store.listAll()).toEqual([]);
+ });
+
+ it("rolls attach, update, and release back when persistence fails", () => {
+ let failPersistence = true;
+ const attachStore = new IOSSimulatorOwnershipStore({
+ createId: () => "attach-id",
+ onChange: () => {
+ if (failPersistence) throw new Error("disk unavailable");
+ },
+ });
+ expect(() => attachStore.attach(input("session-a"))).toThrow(
+ "disk unavailable",
+ );
+ expect(attachStore.listAll()).toEqual([]);
+
+ failPersistence = false;
+ let id = 0;
+ const store = new IOSSimulatorOwnershipStore({
+ createId: () => `id-${++id}`,
+ onChange: () => {
+ if (failPersistence) throw new Error("disk unavailable");
+ },
+ });
+ const instance = store.attach(input("session-a"));
+ failPersistence = true;
+
+ expect(() =>
+ store.update(instance.instanceId, instance.sessionId, {
+ healthState: "error",
+ }),
+ ).toThrow("disk unavailable");
+ expect(store.get(instance.instanceId)).toEqual(instance);
+
+ expect(() =>
+ store.release(instance.instanceId, instance.sessionId),
+ ).toThrow("disk unavailable");
+ expect(store.get(instance.instanceId)).toEqual(instance);
+ });
});
diff --git a/packages/ios-simulator-runtime/src/ownership-store.ts b/packages/ios-simulator-runtime/src/ownership-store.ts
index e55015faa0..1a0eab5156 100644
--- a/packages/ios-simulator-runtime/src/ownership-store.ts
+++ b/packages/ios-simulator-runtime/src/ownership-store.ts
@@ -21,6 +21,8 @@ export interface IOSSimulatorOwnershipStoreOptions {
initialInstances?: IOSSimulatorInstance[];
/** Called after each mutation so a host can persist a bounded snapshot. */
onChange?: (instances: IOSSimulatorInstance[]) => void;
+ /** Fail-closed gate used by persisted stores before changing ownership. */
+ assertMutationAllowed?: () => void;
}
const DEFAULT_LEASE_DURATION_MS = 60_000;
@@ -50,6 +52,7 @@ export class IOSSimulatorOwnershipStore {
readonly #leaseDurationMs: number;
readonly #maxInstancesPerSession: number;
readonly #onChange: ((instances: IOSSimulatorInstance[]) => void) | null;
+ readonly #assertMutationAllowed: (() => void) | null;
readonly #instances = new Map<string, IOSSimulatorInstance>();
readonly #instanceByUdid = new Map<string, string>();
@@ -60,6 +63,7 @@ export class IOSSimulatorOwnershipStore {
options.leaseDurationMs ?? DEFAULT_LEASE_DURATION_MS;
this.#maxInstancesPerSession = options.maxInstancesPerSession ?? 1;
this.#onChange = options.onChange ?? null;
+ this.#assertMutationAllowed = options.assertMutationAllowed ?? null;
if (
!Number.isSafeInteger(this.#leaseDurationMs) ||
this.#leaseDurationMs <= 0 ||
@@ -126,6 +130,7 @@ export class IOSSimulatorOwnershipStore {
"This Cindy session already has the maximum number of simulator instances.",
);
}
+ this.#assertMutationAllowed?.();
const now = this.#clock.now();
const state =
@@ -166,7 +171,13 @@ export class IOSSimulatorOwnershipStore {
};
this.#instances.set(instance.instanceId, instance);
this.#instanceByUdid.set(udid, instance.instanceId);
- this.#changed();
+ try {
+ this.#changed();
+ } catch (error) {
+ this.#instances.delete(instance.instanceId);
+ this.#instanceByUdid.delete(udid);
+ throw error;
+ }
return copyInstance(instance);
}
@@ -241,12 +252,17 @@ export class IOSSimulatorOwnershipStore {
});
}
- /** Extend an active lease without changing its id; expired leases are replaced. */
+ /** Extend an active lease as needed; hot input paths do not persist on every sample. */
heartbeat(instanceId: string, sessionId: string): IOSSimulatorInstance {
const instance = this.requireOwned(instanceId, sessionId);
+ this.#assertMutationAllowed?.();
const now = this.#clock.now();
+ const expiresAt = Date.parse(instance.lease.expiresAt);
+ if (expiresAt > now && expiresAt - now > this.#leaseDurationMs / 2) {
+ return instance;
+ }
const lease =
- Date.parse(instance.lease.expiresAt) <= now
+ expiresAt <= now
? this.#newLease(now)
: {
...instance.lease,
@@ -266,21 +282,34 @@ export class IOSSimulatorOwnershipStore {
>,
): IOSSimulatorInstance {
const current = this.requireOwned(instanceId, sessionId);
+ this.#assertMutationAllowed?.();
const next: IOSSimulatorInstance = {
...current,
...patch,
lease: patch.lease ? { ...patch.lease } : current.lease,
};
this.#instances.set(instanceId, next);
- this.#changed();
+ try {
+ this.#changed();
+ } catch (error) {
+ this.#instances.set(instanceId, current);
+ throw error;
+ }
return copyInstance(next);
}
release(instanceId: string, sessionId: string): IOSSimulatorInstance {
const current = this.requireOwned(instanceId, sessionId);
+ this.#assertMutationAllowed?.();
this.#instances.delete(instanceId);
this.#instanceByUdid.delete(current.simulatorUdid);
- this.#changed();
+ try {
+ this.#changed();
+ } catch (error) {
+ this.#instances.set(instanceId, current);
+ this.#instanceByUdid.set(current.simulatorUdid, instanceId);
+ throw error;
+ }
return current;
}
}
diff --git a/packages/ios-simulator-runtime/src/wda/build-plan.test.ts b/packages/ios-simulator-runtime/src/wda/build-plan.test.ts
index b59bd7049e..30451ebb88 100644
--- a/packages/ios-simulator-runtime/src/wda/build-plan.test.ts
+++ b/packages/ios-simulator-runtime/src/wda/build-plan.test.ts
@@ -5,12 +5,14 @@ import { describe, expect, it } from "vitest";
import { createWdaBuildPlan, createWdaChildEnvironment } from "./build-plan.js";
const UDID = "1A9D41E0-E031-4AD0-A8B5-847480802E8E";
+const CHECKOUT_PATH = path.resolve("/tmp/wda");
+const DERIVED_DATA_PATH = path.resolve("/tmp/wda-derived");
describe("createWdaBuildPlan", () => {
it("builds exact argv plans for a pinned simulator destination", () => {
const plan = createWdaBuildPlan({
- checkoutPath: "/tmp/wda",
- derivedDataPath: "/tmp/wda-derived",
+ checkoutPath: CHECKOUT_PATH,
+ derivedDataPath: DERIVED_DATA_PATH,
simulatorUdid: UDID.toLowerCase(),
architecture: "arm64",
controlPort: 18_100,
@@ -18,11 +20,11 @@ describe("createWdaBuildPlan", () => {
});
expect(plan.projectPath).toBe(
- path.join("/tmp/wda", "WebDriverAgent.xcodeproj"),
+ path.join(CHECKOUT_PATH, "WebDriverAgent.xcodeproj"),
);
expect(plan.build).toMatchObject({
command: "/usr/bin/xcodebuild",
- cwd: "/tmp/wda",
+ cwd: CHECKOUT_PATH,
});
expect(plan.build.args).toContain(
`platform=iOS Simulator,id=${UDID},arch=arm64`,
@@ -68,15 +70,15 @@ describe("createWdaBuildPlan", () => {
).toThrow("checkoutPath must be an absolute path");
expect(() =>
createWdaBuildPlan({
- checkoutPath: "/tmp/wda",
- derivedDataPath: "/tmp/derived",
+ checkoutPath: CHECKOUT_PATH,
+ derivedDataPath: path.resolve("/tmp/derived"),
simulatorUdid: "not-a-udid",
}),
).toThrow("simulatorUdid must be an exact simulator UUID");
expect(() =>
createWdaBuildPlan({
- checkoutPath: "/tmp/wda",
- derivedDataPath: "/tmp/derived",
+ checkoutPath: CHECKOUT_PATH,
+ derivedDataPath: path.resolve("/tmp/derived"),
simulatorUdid: UDID,
controlPort: 8100,
mjpegPort: 8100,
diff --git a/packages/ios-simulator-runtime/src/wda/checkout.test.ts b/packages/ios-simulator-runtime/src/wda/checkout.test.ts
index 8d1fab5d31..ad44f837f0 100644
--- a/packages/ios-simulator-runtime/src/wda/checkout.test.ts
+++ b/packages/ios-simulator-runtime/src/wda/checkout.test.ts
@@ -1,9 +1,13 @@
+import path from "node:path";
+
import { describe, expect, it, vi } from "vitest";
import type { IOSSimulatorCommandRunner } from "../types.js";
import { inspectWdaCheckout } from "./checkout.js";
import { WDA_SOURCE_PIN } from "./source-pin.js";
+const CHECKOUT_PATH = path.resolve("/tmp/wda");
+
function runnerWithRevision(revision: string): IOSSimulatorCommandRunner {
return {
run: vi.fn(async (command, args) => {
@@ -26,7 +30,7 @@ function runnerWithRevision(revision: string): IOSSimulatorCommandRunner {
describe("inspectWdaCheckout", () => {
it("accepts only the pinned revision and required scheme", async () => {
const runner = runnerWithRevision(WDA_SOURCE_PIN.revision);
- const result = await inspectWdaCheckout("/tmp/wda", runner);
+ const result = await inspectWdaCheckout(CHECKOUT_PATH, runner);
expect(result).toMatchObject({
ready: true,
@@ -35,21 +39,26 @@ describe("inspectWdaCheckout", () => {
});
expect(runner.run).toHaveBeenNthCalledWith(1, "/usr/bin/git", [
"-C",
- "/tmp/wda",
+ CHECKOUT_PATH,
"rev-parse",
"HEAD",
]);
expect(runner.run).toHaveBeenNthCalledWith(
2,
"/usr/bin/xcodebuild",
- ["-project", "/tmp/wda/WebDriverAgent.xcodeproj", "-list", "-json"],
+ [
+ "-project",
+ path.join(CHECKOUT_PATH, "WebDriverAgent.xcodeproj"),
+ "-list",
+ "-json",
+ ],
{ timeoutMs: 60_000, maxBufferBytes: 2 * 1024 * 1024 },
);
});
it("fails before Xcode inspection when the revision differs", async () => {
const runner = runnerWithRevision("deadbeef");
- const result = await inspectWdaCheckout("/tmp/wda", runner);
+ const result = await inspectWdaCheckout(CHECKOUT_PATH, runner);
expect(result).toMatchObject({ ready: false, issue: "REVISION_MISMATCH" });
expect(runner.run).toHaveBeenCalledTimes(1);
@@ -70,7 +79,7 @@ describe("inspectWdaCheckout", () => {
exitCode: 0,
}),
};
- const result = await inspectWdaCheckout("/tmp/wda", runner);
+ const result = await inspectWdaCheckout(CHECKOUT_PATH, runner);
expect(result).toMatchObject({ ready: false, issue: "SCHEME_NOT_FOUND" });
});
diff --git a/packages/lizi-mcps/src/computer/computerMcpServer.test.ts b/packages/lizi-mcps/src/computer/computerMcpServer.test.ts
index 1c104cca15..258cc0620a 100644
--- a/packages/lizi-mcps/src/computer/computerMcpServer.test.ts
+++ b/packages/lizi-mcps/src/computer/computerMcpServer.test.ts
@@ -20,8 +20,19 @@ function textPayload(result: unknown): unknown {
return JSON.parse(first.text);
}
-async function makeHarness(deps: ComputerMcpDeps, options?: Parameters<typeof createComputerMcpServer>[1]) {
- const server = createComputerMcpServer(deps, options);
+async function makeHarness(
+ deps: ComputerMcpDeps,
+ options?: Parameters<typeof createComputerMcpServer>[1],
+ testOptions: { injectDefaultProcessResolver?: boolean } = {},
+) {
+ const resolvedDeps =
+ testOptions.injectDefaultProcessResolver === false || deps.resolveProcessIdentity
+ ? deps
+ : {
+ ...deps,
+ resolveProcessIdentity: vi.fn(async (pid: number) => ({ pid, name: 'Code' })),
+ };
+ const server = createComputerMcpServer(resolvedDeps, options);
const [clientTx, serverTx] = InMemoryTransport.createLinkedPair();
const client = new Client({ name: 'computer-test-client', version: '0.0.0' });
await Promise.all([server.connect(serverTx), client.connect(clientTx)]);
@@ -73,8 +84,10 @@ describe('createComputerMcpServer', () => {
.toContain('Always include pid');
expect(payload.tools.find((tool) => tool.name === 'launch_app')?.description)
.toContain('{"process_name":"Simulator"}');
- expect(payload.tools.find((tool) => tool.name === 'launch_app')?.description)
- .toContain('use_external_simulator=true');
+ expect(payload.tools.find((tool) => tool.name === 'launch_app')?.inputSchema?.properties)
+ .not.toHaveProperty('use_external_simulator');
+ expect(payload.tools.find((tool) => tool.name === 'hotkey')?.inputSchema?.properties)
+ .not.toHaveProperty('use_external_ios_workflow');
expect(payload.workflow).toContain('always for coordinates');
expect(payload.workflow).toContain('{"capture_mode":"vision"}');
await h.cleanup();
@@ -512,6 +525,33 @@ describe('createComputerMcpServer', () => {
await h.cleanup();
});
+ it.each(['/Applications/Xcode-beta.app', '/Applications/Xcode_26.app'])(
+ 'routes renamed Xcode bundle %s to the embedded simulator workflow',
+ async (name) => {
+ const deps: ComputerMcpDeps = {
+ getStatus: vi.fn(),
+ callTool: vi.fn(),
+ };
+ const h = await makeHarness(deps);
+
+ const result = await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'launch_app',
+ args: { name },
+ },
+ });
+ expect(textPayload(result)).toMatchObject({
+ ok: false,
+ errorCode: 'EMBEDDED_IOS_SIMULATOR_PREFERRED',
+ data: { blocked_target: 'Xcode' },
+ });
+ expect(result.isError).toBe(true);
+ expect(deps.callTool).not.toHaveBeenCalled();
+ await h.cleanup();
+ },
+ );
+
it('blocks Xcode hotkeys using host-resolved PID provenance', async () => {
const deps: ComputerMcpDeps = {
getStatus: vi.fn(),
@@ -640,67 +680,44 @@ describe('createComputerMcpServer', () => {
await h.cleanup();
});
- it('allows an explicitly requested external Xcode workflow and strips the routing flag', async () => {
- const deps: ComputerMcpDeps = {
- getStatus: vi.fn(),
- isExternalIosWorkflowAllowed: vi.fn(() => true),
- resolveProcessIdentity: vi.fn(async (pid) => ({ pid, name: 'Xcode' })),
- callTool: vi.fn(async () => ({ ok: true })),
- };
- const h = await makeHarness(deps, { sessionId: 'agent-session-1' });
-
- const payload = textPayload(await h.client.callTool({
- name: 'call_tool',
- arguments: {
- name: 'hotkey',
- args: {
- pid: 686,
- window_id: 282,
- keys: ['cmd', 'r'],
- use_external_ios_workflow: true,
- },
- },
- })) as { ok: boolean };
-
- expect(payload.ok).toBe(true);
- expect(deps.resolveProcessIdentity).not.toHaveBeenCalled();
- expect(deps.callTool).toHaveBeenCalledWith('hotkey', {
- pid: 686,
- window_id: 282,
- keys: ['cmd', 'r'],
- session: 'agent-session-1',
- }, { sessionId: 'agent-session-1' });
- await h.cleanup();
- });
-
- it('allows an explicitly requested external Simulator.app and strips the routing flag', async () => {
+ it.each([
+ ['missing resolver', undefined],
+ ['resolver failure', vi.fn(async () => { throw new Error('process snapshot unavailable'); })],
+ ['missing process', vi.fn(async () => null)],
+ ['empty identity', vi.fn(async (pid: number) => ({ pid }))],
+ ['mismatched pid', vi.fn(async () => ({ pid: 999, name: 'Code' }))],
+ ])('fails closed for mutating actions with %s', async (_label, resolveProcessIdentity) => {
+ const callTool = vi.fn();
const deps: ComputerMcpDeps = {
getStatus: vi.fn(),
- isExternalIosWorkflowAllowed: vi.fn(() => true),
- callTool: vi.fn(async () => ({ ok: true })),
+ ...(resolveProcessIdentity ? { resolveProcessIdentity } : {}),
+ callTool,
};
- const h = await makeHarness(deps);
+ const h = await makeHarness(
+ deps,
+ undefined,
+ { injectDefaultProcessResolver: false },
+ );
const result = await h.client.callTool({
name: 'call_tool',
arguments: {
- name: 'launch_app',
- args: {
- bundle_id: 'com.apple.iphonesimulator',
- use_external_simulator: true,
- },
+ name: 'click',
+ args: { pid: 123, window_id: 7, x: 10, y: 20 },
},
});
- const payload = textPayload(result) as { ok: boolean };
+ const payload = textPayload(result) as { ok: boolean; errorCode: string };
- expect(payload.ok).toBe(true);
- expect(deps.callTool).toHaveBeenCalledWith('launch_app', {
- bundle_id: 'com.apple.iphonesimulator',
+ expect(payload).toMatchObject({
+ ok: false,
+ errorCode: 'TARGET_PROVENANCE_UNAVAILABLE',
});
+ expect(result.isError).toBe(true);
+ expect(callTool).not.toHaveBeenCalled();
await h.cleanup();
});
- it('does not treat a model-supplied external override as user authorization', async () => {
+ it('rejects model-supplied external iOS override fields before dispatch', async () => {
const deps: ComputerMcpDeps = {
getStatus: vi.fn(),
callTool: vi.fn(),
@@ -721,7 +738,7 @@ describe('createComputerMcpServer', () => {
expect(payload).toMatchObject({
ok: false,
- errorCode: 'EMBEDDED_IOS_SIMULATOR_PREFERRED',
+ errorCode: 'INVALID_ARGS',
});
expect(deps.callTool).not.toHaveBeenCalled();
await h.cleanup();
diff --git a/packages/lizi-mcps/src/computer/server.ts b/packages/lizi-mcps/src/computer/server.ts
index 03e5aeae51..6cff8f3d4b 100644
--- a/packages/lizi-mcps/src/computer/server.ts
+++ b/packages/lizi-mcps/src/computer/server.ts
@@ -266,7 +266,7 @@ export function createComputerMcpServer(
inputSchema: z.toJSONSchema(z.object(tool.inputShape).strict()),
})),
workflow:
- 'Start with status and check_permissions. For iOS work, use cindy_ios_simulator first; only use this server to inspect or launch macOS Simulator.app when the user explicitly requests an external window and launch_app receives use_external_simulator=true. Otherwise use get_accessibility_tree/list_windows, optionally narrow list_windows with query/workspace_root/process_name (for example, {"process_name":"Simulator"}), inspect a target with get_window_state, perform one action, and call get_window_state again to verify. Targeted actions such as click/type_text require pid; include window_id whenever the target window is known, and always for coordinates. Use get_window_state with {"capture_mode":"vision"} for screenshots and normally omit screenshot_out_file. Element indices are only valid for the latest snapshot of the same pid/window_id: pass the snapshot_id from get_window_state along with element_index, and re-observe when an action is rejected with STALE_SNAPSHOT. Use start_recording/stop_recording/replay_trajectory only when the user explicitly asks for recording or replay.',
+ 'Start with status and check_permissions. For iOS work, use cindy_ios_simulator first; this server may inspect the external Xcode/Simulator desktop UI read-only, but mutating external iOS workflows are not available until Cindy has a host-issued authorization flow. Otherwise use get_accessibility_tree/list_windows, optionally narrow list_windows with query/workspace_root/process_name (for example, {"process_name":"Simulator"}), inspect a target with get_window_state, perform one action, and call get_window_state again to verify. Targeted actions such as click/type_text require pid; include window_id whenever the target window is known, and always for coordinates. Use get_window_state with {"capture_mode":"vision"} for screenshots and normally omit screenshot_out_file. Element indices are only valid for the latest snapshot of the same pid/window_id: pass the snapshot_id from get_window_state along with element_index, and re-observe when an action is rejected with STALE_SNAPSHOT. Use start_recording/stop_recording/replay_trajectory only when the user explicitly asks for recording or replay.',
}),
);
@@ -314,13 +314,8 @@ export function createComputerMcpServer(
const externalIosGuard = await guardExternalIosDesktopWorkflow(
name as ComputerMcpToolName,
parsedData,
- callContext,
);
if (externalIosGuard) return externalIosGuard;
- // These MCP-only routing flags are consumed by the guard and must never be
- // forwarded to the underlying desktop driver.
- delete parsedData.use_external_simulator;
- delete parsedData.use_external_ios_workflow;
// 快照代际护栏:element_index 指向"某次 get_window_state 的第几项",观察和
// 动作之间 UI 树变化时会静默作用到错误元素。带 snapshot_id 的动作在此校验
@@ -375,25 +370,17 @@ export function createComputerMcpServer(
async function guardExternalIosDesktopWorkflow(
name: ComputerMcpToolName,
parsedData: Record<string, unknown>,
- callContext: ComputerMcpCallContext | undefined,
) {
- const hostAuthorized = deps.isExternalIosWorkflowAllowed?.(callContext) === true;
if (name === 'launch_app') {
const target = classifyExternalIosTarget({
name: parsedData.name,
bundleId: parsedData.bundle_id,
executable: parsedData.name,
});
- if (
- target === 'simulator' &&
- !(hostAuthorized && parsedData.use_external_simulator === true)
- ) {
+ if (target === 'simulator') {
return embeddedIosSimulatorPreferredResult('Simulator.app');
}
- if (
- target === 'xcode' &&
- !(hostAuthorized && parsedData.use_external_ios_workflow === true)
- ) {
+ if (target === 'xcode') {
return embeddedIosSimulatorPreferredResult('Xcode');
}
return null;
@@ -401,14 +388,11 @@ export function createComputerMcpServer(
if (
!TARGETED_MUTATING_TOOLS.has(name) ||
- typeof parsedData.pid !== 'number' ||
- !deps.resolveProcessIdentity
+ typeof parsedData.pid !== 'number'
) {
return null;
}
- if (hostAuthorized && parsedData.use_external_ios_workflow === true) {
- return null;
- }
+ if (!deps.resolveProcessIdentity) return targetProvenanceUnavailableResult();
let identity;
try {
@@ -419,9 +403,18 @@ export function createComputerMcpServer(
tool: name,
error: err instanceof Error ? err.message : String(err),
});
- return null;
+ return targetProvenanceUnavailableResult();
}
- const target = classifyExternalIosTarget(identity ?? {});
+ if (
+ !identity ||
+ identity.pid !== parsedData.pid ||
+ ![identity.name, identity.command, identity.executable, identity.bundleId].some(
+ (value) => typeof value === 'string' && value.trim().length > 0,
+ )
+ ) {
+ return targetProvenanceUnavailableResult();
+ }
+ const target = classifyExternalIosTarget(identity);
if (!target) return null;
return embeddedIosSimulatorPreferredResult(target === 'xcode' ? 'Xcode' : 'Simulator.app');
@@ -438,6 +431,7 @@ export function createComputerMcpServer(
const command = typeof input.command === 'string' ? input.command.trim().toLowerCase() : '';
const executable = typeof input.executable === 'string' ? input.executable.trim().toLowerCase() : '';
const provenance = [name, command, executable].filter(Boolean).join(' ');
+ const nameBasename = name.replace(/\\/g, '/').split('/').at(-1) ?? '';
if (
bundleId === 'com.apple.iphonesimulator' ||
@@ -447,6 +441,7 @@ export function createComputerMcpServer(
}
if (
bundleId === 'com.apple.dt.xcode' ||
+ /^xcode(?:[-_.][a-z0-9][a-z0-9._-]*)?(?:\.app)?$/i.test(nameBasename) ||
/(^|[\s/])xcode(?:\.app)?(?:[\s/]|$)/.test(provenance)
) {
return 'xcode';
@@ -461,7 +456,7 @@ export function createComputerMcpServer(
errorCode: 'EMBEDDED_IOS_SIMULATOR_PREFERRED',
data: {
message:
- `Use cindy_ios_simulator for Cindy's embedded viewer. External ${target} automation is disabled by default; use the explicit external-iOS override only when the user requested that desktop workflow.`,
+ `Use cindy_ios_simulator for Cindy's embedded viewer. External ${target} automation is unavailable until Cindy can issue an explicit host authorization.`,
next_tool: 'cindy_ios_simulator',
blocked_target: target,
},
@@ -470,6 +465,20 @@ export function createComputerMcpServer(
);
}
+ function targetProvenanceUnavailableResult() {
+ return textResult(
+ {
+ ok: false,
+ errorCode: 'TARGET_PROVENANCE_UNAVAILABLE',
+ data: {
+ message:
+ 'Cindy could not verify the target process identity, so this mutating desktop action was blocked. Refresh the target window and try again.',
+ },
+ },
+ true,
+ );
+ }
+
/**
* 把工具入参里的本地文件路径约束到 session workingDir。返回 null 放行(路径
* 已被替换为约束后的绝对路径),返回结果对象表示以 PATH_NOT_ALLOWED 拒绝。
diff --git a/packages/lizi-mcps/src/computer/snapshotGuard.test.ts b/packages/lizi-mcps/src/computer/snapshotGuard.test.ts
index e9daac651e..f8e04b4678 100644
--- a/packages/lizi-mcps/src/computer/snapshotGuard.test.ts
+++ b/packages/lizi-mcps/src/computer/snapshotGuard.test.ts
@@ -23,7 +23,14 @@ function makeLogger(): LiziMcpLogger & { warn: ReturnType<typeof vi.fn> } {
}
async function makeHarness(deps: ComputerMcpDeps, options?: Parameters<typeof createComputerMcpServer>[1]) {
- const server = createComputerMcpServer(deps, options);
+ const server = createComputerMcpServer(
+ {
+ ...deps,
+ resolveProcessIdentity:
+ deps.resolveProcessIdentity ?? (async (pid) => ({ pid, name: 'Code' })),
+ },
+ options,
+ );
const [clientTx, serverTx] = InMemoryTransport.createLinkedPair();
const client = new Client({ name: 'snapshot-test-client', version: '0.0.0' });
await Promise.all([server.connect(serverTx), client.connect(clientTx)]);
diff --git a/packages/lizi-mcps/src/computer/tools.ts b/packages/lizi-mcps/src/computer/tools.ts
index e6ecb5a6ff..a0a03883ce 100644
--- a/packages/lizi-mcps/src/computer/tools.ts
+++ b/packages/lizi-mcps/src/computer/tools.ts
@@ -20,18 +20,6 @@ const SNAPSHOT_ID_ARG = z
'snapshot_id returned by the get_window_state call this element_index comes from. Recommended whenever element_index is used: if the window has been observed again since, the action is rejected with STALE_SNAPSHOT so you can re-observe instead of acting on the wrong element.',
);
-/**
- * Explicit escape hatch for user-requested automation of Apple's standalone
- * Xcode/Simulator UI. It is consumed by the MCP routing guard and never sent
- * to cua-driver.
- */
-const EXTERNAL_IOS_WORKFLOW_ARG = z
- .boolean()
- .optional()
- .describe(
- 'Set true only when the user explicitly requests an external Xcode/Simulator desktop workflow instead of Cindy\'s embedded iOS simulator.',
- );
-
export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [
{
name: 'status',
@@ -58,7 +46,7 @@ export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [
{
name: 'launch_app',
description:
- 'Launch or locate a desktop application without stealing focus. Prefer this over shell open/Start-Process for GUI apps. For iOS work, use cindy_ios_simulator for Cindy\'s embedded viewer by default; do not launch macOS Simulator.app here unless the user explicitly requests an external system window and you set use_external_simulator=true. If an explicitly requested external Simulator is not discoverable here, use list_windows with {"process_name":"Simulator"}.',
+ 'Launch or locate a desktop application without stealing focus. Prefer this over shell open/Start-Process for GUI apps. For iOS work, use cindy_ios_simulator for Cindy\'s embedded viewer; launching Xcode or macOS Simulator.app is unavailable until Cindy can issue an explicit host authorization. Use list_windows with {"process_name":"Simulator"} for read-only external Simulator window discovery.',
inputShape: {
name: z.string().optional(),
bundle_id: z.string().optional(),
@@ -67,11 +55,6 @@ export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [
webkit_inspector_port: z.number().int().optional(),
creates_new_application_instance: z.boolean().optional(),
additional_arguments: z.array(z.string()).optional(),
- use_external_simulator: z
- .boolean()
- .optional()
- .describe('Required only for an explicit user request to open macOS Simulator.app instead of Cindy\'s embedded simulator.'),
- use_external_ios_workflow: EXTERNAL_IOS_WORKFLOW_ARG,
},
},
{
@@ -124,7 +107,6 @@ export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [
debug_image_out: z.string().optional(),
snapshot_id: SNAPSHOT_ID_ARG,
session: z.string().optional(),
- use_external_ios_workflow: EXTERNAL_IOS_WORKFLOW_ARG,
},
},
{
@@ -139,7 +121,6 @@ export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [
y: z.number().optional(),
snapshot_id: SNAPSHOT_ID_ARG,
session: z.string().optional(),
- use_external_ios_workflow: EXTERNAL_IOS_WORKFLOW_ARG,
},
},
{
@@ -155,7 +136,6 @@ export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [
modifier: z.array(z.string()).optional(),
snapshot_id: SNAPSHOT_ID_ARG,
session: z.string().optional(),
- use_external_ios_workflow: EXTERNAL_IOS_WORKFLOW_ARG,
},
},
{
@@ -174,7 +154,6 @@ export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [
modifier: z.array(z.string()).optional(),
from_zoom: z.boolean().optional(),
session: z.string().optional(),
- use_external_ios_workflow: EXTERNAL_IOS_WORKFLOW_ARG,
},
},
{
@@ -189,7 +168,6 @@ export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [
delay_ms: z.number().int().min(0).max(200).optional(),
snapshot_id: SNAPSHOT_ID_ARG,
session: z.string().optional(),
- use_external_ios_workflow: EXTERNAL_IOS_WORKFLOW_ARG,
},
},
{
@@ -203,7 +181,6 @@ export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [
value: z.string(),
snapshot_id: SNAPSHOT_ID_ARG,
session: z.string().optional(),
- use_external_ios_workflow: EXTERNAL_IOS_WORKFLOW_ARG,
},
},
{
@@ -217,7 +194,6 @@ export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [
window_id: z.number().int().nonnegative().optional(),
snapshot_id: SNAPSHOT_ID_ARG,
session: z.string().optional(),
- use_external_ios_workflow: EXTERNAL_IOS_WORKFLOW_ARG,
},
},
{
@@ -228,7 +204,6 @@ export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [
keys: z.array(z.string()).min(2),
window_id: z.number().int().nonnegative().optional(),
session: z.string().optional(),
- use_external_ios_workflow: EXTERNAL_IOS_WORKFLOW_ARG,
},
},
{
@@ -243,7 +218,6 @@ export const COMPUTER_TOOLS: readonly ComputerToolDef[] = [
by: z.enum(['line', 'page']).optional(),
snapshot_id: SNAPSHOT_ID_ARG,
session: z.string().optional(),
- use_external_ios_workflow: EXTERNAL_IOS_WORKFLOW_ARG,
},
},
{
diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.ts
index c90409193c..2b67463f67 100644
--- a/packages/lizi-mcps/src/types.ts
+++ b/packages/lizi-mcps/src/types.ts
@@ -608,8 +608,6 @@ export interface ComputerMcpDeps {
getStatus(): Promise<ComputerDriverStatus>;
/** Resolve process provenance without trusting model-supplied app labels. */
resolveProcessIdentity?(pid: number): Promise<ComputerProcessIdentity | null>;
- /** Host-issued authorization for an explicitly requested external iOS UI workflow. */
- isExternalIosWorkflowAllowed?(context?: ComputerMcpCallContext): boolean;
callTool(
name: ComputerMcpToolName,
args: Record<string, unknown>,